diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index c77fe1c5076..ef4cdd98efb 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -1,6 +1,6 @@
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
- rev: v0.2.1
+ rev: v0.3.4
hooks:
- id: ruff
args:
diff --git a/homeassistant/backports/functools.py b/homeassistant/backports/functools.py
index 6271bb87d14..8aab50eeb66 100644
--- a/homeassistant/backports/functools.py
+++ b/homeassistant/backports/functools.py
@@ -41,12 +41,10 @@ class cached_property(Generic[_T]):
)
@overload
- def __get__(self, instance: None, owner: type[Any] | None = None) -> Self:
- ...
+ def __get__(self, instance: None, owner: type[Any] | None = None) -> Self: ...
@overload
- def __get__(self, instance: Any, owner: type[Any] | None = None) -> _T:
- ...
+ def __get__(self, instance: Any, owner: type[Any] | None = None) -> _T: ...
def __get__(
self, instance: Any | None, owner: type[Any] | None = None
diff --git a/homeassistant/components/airvisual/__init__.py b/homeassistant/components/airvisual/__init__.py
index ec3e0ad7028..c0a6b8d38ef 100644
--- a/homeassistant/components/airvisual/__init__.py
+++ b/homeassistant/components/airvisual/__init__.py
@@ -162,13 +162,13 @@ def _standardize_geography_config_entry(
# about, infer it from the data we have:
entry_updates["data"] = {**entry.data}
if CONF_CITY in entry.data:
- entry_updates["data"][
- CONF_INTEGRATION_TYPE
- ] = INTEGRATION_TYPE_GEOGRAPHY_NAME
+ entry_updates["data"][CONF_INTEGRATION_TYPE] = (
+ INTEGRATION_TYPE_GEOGRAPHY_NAME
+ )
else:
- entry_updates["data"][
- CONF_INTEGRATION_TYPE
- ] = INTEGRATION_TYPE_GEOGRAPHY_COORDS
+ entry_updates["data"][CONF_INTEGRATION_TYPE] = (
+ INTEGRATION_TYPE_GEOGRAPHY_COORDS
+ )
if not entry_updates:
return
diff --git a/homeassistant/components/amcrest/__init__.py b/homeassistant/components/amcrest/__init__.py
index 6a5481f0d1a..cb6abff3f89 100644
--- a/homeassistant/components/amcrest/__init__.py
+++ b/homeassistant/components/amcrest/__init__.py
@@ -211,9 +211,10 @@ class AmcrestChecker(ApiWrapper):
self, *args: Any, **kwargs: Any
) -> AsyncIterator[httpx.Response]:
"""amcrest.ApiWrapper.command wrapper to catch errors."""
- async with self._async_command_wrapper(), super().async_stream_command(
- *args, **kwargs
- ) as ret:
+ async with (
+ self._async_command_wrapper(),
+ super().async_stream_command(*args, **kwargs) as ret,
+ ):
yield ret
@asynccontextmanager
diff --git a/homeassistant/components/amcrest/sensor.py b/homeassistant/components/amcrest/sensor.py
index 6e096d8c764..b54d71c5814 100644
--- a/homeassistant/components/amcrest/sensor.py
+++ b/homeassistant/components/amcrest/sensor.py
@@ -108,21 +108,21 @@ class AmcrestSensor(SensorEntity):
elif sensor_type == SENSOR_SDCARD:
storage = await self._api.async_storage_all
try:
- self._attr_extra_state_attributes[
- "Total"
- ] = f"{storage['total'][0]:.2f} {storage['total'][1]}"
+ self._attr_extra_state_attributes["Total"] = (
+ f"{storage['total'][0]:.2f} {storage['total'][1]}"
+ )
except ValueError:
- self._attr_extra_state_attributes[
- "Total"
- ] = f"{storage['total'][0]} {storage['total'][1]}"
+ self._attr_extra_state_attributes["Total"] = (
+ f"{storage['total'][0]} {storage['total'][1]}"
+ )
try:
- self._attr_extra_state_attributes[
- "Used"
- ] = f"{storage['used'][0]:.2f} {storage['used'][1]}"
+ self._attr_extra_state_attributes["Used"] = (
+ f"{storage['used'][0]:.2f} {storage['used'][1]}"
+ )
except ValueError:
- self._attr_extra_state_attributes[
- "Used"
- ] = f"{storage['used'][0]} {storage['used'][1]}"
+ self._attr_extra_state_attributes["Used"] = (
+ f"{storage['used'][0]} {storage['used'][1]}"
+ )
try:
self._attr_native_value = f"{storage['used_percent']:.2f}"
except ValueError:
diff --git a/homeassistant/components/apcupsd/diagnostics.py b/homeassistant/components/apcupsd/diagnostics.py
index 60433dfbdf4..d375a8bc248 100644
--- a/homeassistant/components/apcupsd/diagnostics.py
+++ b/homeassistant/components/apcupsd/diagnostics.py
@@ -1,4 +1,5 @@
"""Diagnostics support for APCUPSD."""
+
from __future__ import annotations
from typing import Any
diff --git a/homeassistant/components/aranet/__init__.py b/homeassistant/components/aranet/__init__.py
index 7d9254e4223..3a2bc266653 100644
--- a/homeassistant/components/aranet/__init__.py
+++ b/homeassistant/components/aranet/__init__.py
@@ -33,14 +33,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
address = entry.unique_id
assert address is not None
- coordinator = hass.data.setdefault(DOMAIN, {})[
- entry.entry_id
- ] = PassiveBluetoothProcessorCoordinator(
- hass,
- _LOGGER,
- address=address,
- mode=BluetoothScanningMode.PASSIVE,
- update_method=_service_info_to_adv,
+ coordinator = hass.data.setdefault(DOMAIN, {})[entry.entry_id] = (
+ PassiveBluetoothProcessorCoordinator(
+ hass,
+ _LOGGER,
+ address=address,
+ mode=BluetoothScanningMode.PASSIVE,
+ update_method=_service_info_to_adv,
+ )
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(
diff --git a/homeassistant/components/assist_pipeline/pipeline.py b/homeassistant/components/assist_pipeline/pipeline.py
index e55f73ce8a5..01a12b3635b 100644
--- a/homeassistant/components/assist_pipeline/pipeline.py
+++ b/homeassistant/components/assist_pipeline/pipeline.py
@@ -754,9 +754,9 @@ class PipelineRun:
raise DuplicateWakeUpDetectedError(result.wake_word_phrase)
# Record last wake up time to block duplicate detections
- self.hass.data[DATA_LAST_WAKE_UP][
- result.wake_word_phrase
- ] = time.monotonic()
+ self.hass.data[DATA_LAST_WAKE_UP][result.wake_word_phrase] = (
+ time.monotonic()
+ )
if result.queued_audio:
# Add audio that was pending at detection.
@@ -1375,9 +1375,9 @@ class PipelineInput:
raise DuplicateWakeUpDetectedError(self.wake_word_phrase)
# Record last wake up time to block duplicate detections
- self.run.hass.data[DATA_LAST_WAKE_UP][
- self.wake_word_phrase
- ] = time.monotonic()
+ self.run.hass.data[DATA_LAST_WAKE_UP][self.wake_word_phrase] = (
+ time.monotonic()
+ )
stt_input_stream = stt_processed_stream
diff --git a/homeassistant/components/asuswrt/device_tracker.py b/homeassistant/components/asuswrt/device_tracker.py
index 65d33500970..059a0eeb3fb 100644
--- a/homeassistant/components/asuswrt/device_tracker.py
+++ b/homeassistant/components/asuswrt/device_tracker.py
@@ -101,9 +101,9 @@ class AsusWrtDevice(ScannerEntity):
self._device = self._router.devices[self._device.mac]
self._attr_extra_state_attributes = {}
if self._device.last_activity:
- self._attr_extra_state_attributes[
- ATTR_LAST_TIME_REACHABLE
- ] = self._device.last_activity.isoformat(timespec="seconds")
+ self._attr_extra_state_attributes[ATTR_LAST_TIME_REACHABLE] = (
+ self._device.last_activity.isoformat(timespec="seconds")
+ )
self.async_write_ha_state()
async def async_added_to_hass(self) -> None:
diff --git a/homeassistant/components/august/lock.py b/homeassistant/components/august/lock.py
index f4b6db55779..e711edd6893 100644
--- a/homeassistant/components/august/lock.py
+++ b/homeassistant/components/august/lock.py
@@ -141,9 +141,9 @@ class AugustLock(AugustEntityMixin, RestoreEntity, LockEntity):
ATTR_BATTERY_LEVEL: self._detail.battery_level
}
if self._detail.keypad is not None:
- self._attr_extra_state_attributes[
- "keypad_battery_level"
- ] = self._detail.keypad.battery_level
+ self._attr_extra_state_attributes["keypad_battery_level"] = (
+ self._detail.keypad.battery_level
+ )
async def async_added_to_hass(self) -> None:
"""Restore ATTR_CHANGED_BY on startup since it is likely no longer in the activity log."""
diff --git a/homeassistant/components/auth/indieauth.py b/homeassistant/components/auth/indieauth.py
index 0bbfcc01fc7..232f067b673 100644
--- a/homeassistant/components/auth/indieauth.py
+++ b/homeassistant/components/auth/indieauth.py
@@ -92,9 +92,10 @@ async def fetch_redirect_uris(hass: HomeAssistant, url: str) -> list[str]:
parser = LinkTagParser("redirect_uri")
chunks = 0
try:
- async with aiohttp.ClientSession() as session, session.get(
- url, timeout=5
- ) as resp:
+ async with (
+ aiohttp.ClientSession() as session,
+ session.get(url, timeout=5) as resp,
+ ):
async for data in resp.content.iter_chunked(1024):
parser.feed(data.decode())
chunks += 1
diff --git a/homeassistant/components/awair/config_flow.py b/homeassistant/components/awair/config_flow.py
index cce447d33f8..d3c4703e89c 100644
--- a/homeassistant/components/awair/config_flow.py
+++ b/homeassistant/components/awair/config_flow.py
@@ -122,9 +122,9 @@ class AwairFlowHandler(ConfigFlow, domain=DOMAIN):
for flow in self._async_in_progress():
if flow["context"]["source"] == SOURCE_ZEROCONF:
info = flow["context"]["title_placeholders"]
- entries[
- flow["context"]["host"]
- ] = f"{info['model']} ({info['device_id']})"
+ entries[flow["context"]["host"]] = (
+ f"{info['model']} ({info['device_id']})"
+ )
return entries
async def async_step_local(
diff --git a/homeassistant/components/axis/hub/entity_loader.py b/homeassistant/components/axis/hub/entity_loader.py
index def22d62bd8..36523e24d83 100644
--- a/homeassistant/components/axis/hub/entity_loader.py
+++ b/homeassistant/components/axis/hub/entity_loader.py
@@ -2,6 +2,7 @@
Central point to load entities for the different platforms.
"""
+
from __future__ import annotations
from functools import partial
diff --git a/homeassistant/components/bluemaestro/__init__.py b/homeassistant/components/bluemaestro/__init__.py
index 2b9a2ab15ec..c25ceb44759 100644
--- a/homeassistant/components/bluemaestro/__init__.py
+++ b/homeassistant/components/bluemaestro/__init__.py
@@ -26,14 +26,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
address = entry.unique_id
assert address is not None
data = BlueMaestroBluetoothDeviceData()
- coordinator = hass.data.setdefault(DOMAIN, {})[
- entry.entry_id
- ] = PassiveBluetoothProcessorCoordinator(
- hass,
- _LOGGER,
- address=address,
- mode=BluetoothScanningMode.PASSIVE,
- update_method=data.update,
+ coordinator = hass.data.setdefault(DOMAIN, {})[entry.entry_id] = (
+ PassiveBluetoothProcessorCoordinator(
+ hass,
+ _LOGGER,
+ address=address,
+ mode=BluetoothScanningMode.PASSIVE,
+ update_method=data.update,
+ )
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(
diff --git a/homeassistant/components/bluetooth/passive_update_processor.py b/homeassistant/components/bluetooth/passive_update_processor.py
index 4e2de196da4..b7a7a165f71 100644
--- a/homeassistant/components/bluetooth/passive_update_processor.py
+++ b/homeassistant/components/bluetooth/passive_update_processor.py
@@ -129,9 +129,9 @@ class PassiveBluetoothDataUpdate(Generic[_T]):
"""Generic bluetooth data."""
devices: dict[str | None, DeviceInfo] = dataclasses.field(default_factory=dict)
- entity_descriptions: dict[
- PassiveBluetoothEntityKey, EntityDescription
- ] = dataclasses.field(default_factory=dict)
+ entity_descriptions: dict[PassiveBluetoothEntityKey, EntityDescription] = (
+ dataclasses.field(default_factory=dict)
+ )
entity_names: dict[PassiveBluetoothEntityKey, str | None] = dataclasses.field(
default_factory=dict
)
diff --git a/homeassistant/components/bluetooth/util.py b/homeassistant/components/bluetooth/util.py
index 166930d64f3..0faac9a8613 100644
--- a/homeassistant/components/bluetooth/util.py
+++ b/homeassistant/components/bluetooth/util.py
@@ -29,14 +29,14 @@ def async_load_history_from_system(
not (existing_all := connectable_loaded_history.get(address))
or history.advertisement_data.rssi > existing_all.rssi
):
- connectable_loaded_history[address] = all_loaded_history[
- address
- ] = BluetoothServiceInfoBleak.from_device_and_advertisement_data(
- history.device,
- history.advertisement_data,
- history.source,
- now_monotonic,
- True,
+ connectable_loaded_history[address] = all_loaded_history[address] = (
+ BluetoothServiceInfoBleak.from_device_and_advertisement_data(
+ history.device,
+ history.advertisement_data,
+ history.source,
+ now_monotonic,
+ True,
+ )
)
# Restore remote adapters
diff --git a/homeassistant/components/bmw_connected_drive/lock.py b/homeassistant/components/bmw_connected_drive/lock.py
index 3de41bfb911..9529c135280 100644
--- a/homeassistant/components/bmw_connected_drive/lock.py
+++ b/homeassistant/components/bmw_connected_drive/lock.py
@@ -102,8 +102,8 @@ class BMWLock(BMWBaseEntity, LockEntity):
LockState.LOCKED,
LockState.SECURED,
}
- self._attr_extra_state_attributes[
- "door_lock_state"
- ] = self.vehicle.doors_and_windows.door_lock_state.value
+ self._attr_extra_state_attributes["door_lock_state"] = (
+ self.vehicle.doors_and_windows.door_lock_state.value
+ )
super()._handle_coordinator_update()
diff --git a/homeassistant/components/bosch_shc/__init__.py b/homeassistant/components/bosch_shc/__init__.py
index 1ccb31d1dc9..9a00029412d 100644
--- a/homeassistant/components/bosch_shc/__init__.py
+++ b/homeassistant/components/bosch_shc/__init__.py
@@ -76,9 +76,9 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
await hass.async_add_executor_job(session.stop_polling)
await hass.async_add_executor_job(session.start_polling)
- hass.data[DOMAIN][entry.entry_id][
- DATA_POLLING_HANDLER
- ] = hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_polling)
+ hass.data[DOMAIN][entry.entry_id][DATA_POLLING_HANDLER] = (
+ hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_polling)
+ )
return True
diff --git a/homeassistant/components/brottsplatskartan/sensor.py b/homeassistant/components/brottsplatskartan/sensor.py
index 750b99abb67..6725a32bb40 100644
--- a/homeassistant/components/brottsplatskartan/sensor.py
+++ b/homeassistant/components/brottsplatskartan/sensor.py
@@ -63,9 +63,9 @@ class BrottsplatskartanSensor(SensorEntity):
"""Update device state."""
incident_counts: defaultdict[str, int] = defaultdict(int)
- get_incidents: dict[str, list] | Literal[
- False
- ] = self._brottsplatskartan.get_incidents()
+ get_incidents: dict[str, list] | Literal[False] = (
+ self._brottsplatskartan.get_incidents()
+ )
if get_incidents is False:
LOGGER.debug("Problems fetching incidents")
diff --git a/homeassistant/components/bthome/__init__.py b/homeassistant/components/bthome/__init__.py
index d677bd28260..8509b5d1d46 100644
--- a/homeassistant/components/bthome/__init__.py
+++ b/homeassistant/components/bthome/__init__.py
@@ -129,20 +129,22 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
data = BTHomeBluetoothDeviceData(**kwargs)
device_registry = async_get(hass)
- coordinator = hass.data.setdefault(DOMAIN, {})[
- entry.entry_id
- ] = BTHomePassiveBluetoothProcessorCoordinator(
- hass,
- _LOGGER,
- address=address,
- mode=BluetoothScanningMode.PASSIVE,
- update_method=lambda service_info: process_service_info(
- hass, entry, data, service_info, device_registry
- ),
- device_data=data,
- discovered_event_classes=set(entry.data.get(CONF_DISCOVERED_EVENT_CLASSES, [])),
- connectable=False,
- entry=entry,
+ coordinator = hass.data.setdefault(DOMAIN, {})[entry.entry_id] = (
+ BTHomePassiveBluetoothProcessorCoordinator(
+ hass,
+ _LOGGER,
+ address=address,
+ mode=BluetoothScanningMode.PASSIVE,
+ update_method=lambda service_info: process_service_info(
+ hass, entry, data, service_info, device_registry
+ ),
+ device_data=data,
+ discovered_event_classes=set(
+ entry.data.get(CONF_DISCOVERED_EVENT_CLASSES, [])
+ ),
+ connectable=False,
+ entry=entry,
+ )
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
diff --git a/homeassistant/components/canary/coordinator.py b/homeassistant/components/canary/coordinator.py
index 534ca4df9fb..d58d1da0f79 100644
--- a/homeassistant/components/canary/coordinator.py
+++ b/homeassistant/components/canary/coordinator.py
@@ -46,9 +46,9 @@ class CanaryDataUpdateCoordinator(DataUpdateCoordinator[CanaryData]):
for device in location.devices:
if device.is_online:
- readings_by_device_id[
- device.device_id
- ] = self.canary.get_latest_readings(device.device_id)
+ readings_by_device_id[device.device_id] = (
+ self.canary.get_latest_readings(device.device_id)
+ )
return {
"locations": locations_by_id,
diff --git a/homeassistant/components/climate/device_trigger.py b/homeassistant/components/climate/device_trigger.py
index 30c282344a4..9702c97d0da 100644
--- a/homeassistant/components/climate/device_trigger.py
+++ b/homeassistant/components/climate/device_trigger.py
@@ -140,13 +140,13 @@ async def async_attach_trigger(
}
if trigger_type == "current_temperature_changed":
- numeric_state_config[
- numeric_state_trigger.CONF_VALUE_TEMPLATE
- ] = "{{ state.attributes.current_temperature }}"
+ numeric_state_config[numeric_state_trigger.CONF_VALUE_TEMPLATE] = (
+ "{{ state.attributes.current_temperature }}"
+ )
else: # trigger_type == "current_humidity_changed"
- numeric_state_config[
- numeric_state_trigger.CONF_VALUE_TEMPLATE
- ] = "{{ state.attributes.current_humidity }}"
+ numeric_state_config[numeric_state_trigger.CONF_VALUE_TEMPLATE] = (
+ "{{ state.attributes.current_humidity }}"
+ )
if CONF_ABOVE in config:
numeric_state_config[CONF_ABOVE] = config[CONF_ABOVE]
diff --git a/homeassistant/components/co2signal/sensor.py b/homeassistant/components/co2signal/sensor.py
index 685c03136da..5b11fd85827 100644
--- a/homeassistant/components/co2signal/sensor.py
+++ b/homeassistant/components/co2signal/sensor.py
@@ -29,9 +29,9 @@ class CO2SensorEntityDescription(SensorEntityDescription):
# For backwards compat, allow description to override unique ID key to use
unique_id: str | None = None
- unit_of_measurement_fn: Callable[
- [CarbonIntensityResponse], str | None
- ] | None = None
+ unit_of_measurement_fn: Callable[[CarbonIntensityResponse], str | None] | None = (
+ None
+ )
value_fn: Callable[[CarbonIntensityResponse], float | None]
diff --git a/homeassistant/components/daikin/climate.py b/homeassistant/components/daikin/climate.py
index f48bedad4ec..34ae8701d5d 100644
--- a/homeassistant/components/daikin/climate.py
+++ b/homeassistant/components/daikin/climate.py
@@ -178,9 +178,9 @@ class DaikinClimate(ClimateEntity):
# temperature
elif attr == ATTR_TEMPERATURE:
try:
- values[
- HA_ATTR_TO_DAIKIN[ATTR_TARGET_TEMPERATURE]
- ] = format_target_temperature(value)
+ values[HA_ATTR_TO_DAIKIN[ATTR_TARGET_TEMPERATURE]] = (
+ format_target_temperature(value)
+ )
except ValueError:
_LOGGER.error("Invalid temperature %s", value)
diff --git a/homeassistant/components/debugpy/__init__.py b/homeassistant/components/debugpy/__init__.py
index 4dfad108136..5caf517a483 100644
--- a/homeassistant/components/debugpy/__init__.py
+++ b/homeassistant/components/debugpy/__init__.py
@@ -6,7 +6,7 @@ from asyncio import Event, get_running_loop
import logging
from threading import Thread
-import debugpy
+import debugpy # noqa: T100
import voluptuous as vol
from homeassistant.const import CONF_HOST, CONF_PORT
@@ -60,7 +60,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
ready = Event()
def waitfor():
- debugpy.wait_for_client()
+ debugpy.wait_for_client() # noqa: T100
hass.loop.call_soon_threadsafe(ready.set)
Thread(target=waitfor).start()
diff --git a/homeassistant/components/deconz/deconz_event.py b/homeassistant/components/deconz/deconz_event.py
index 601190eaab7..56cbf47b4e3 100644
--- a/homeassistant/components/deconz/deconz_event.py
+++ b/homeassistant/components/deconz/deconz_event.py
@@ -61,7 +61,12 @@ async def async_setup_events(hub: DeconzHub) -> None:
@callback
def async_add_sensor(_: EventType, sensor_id: str) -> None:
"""Create DeconzEvent."""
- new_event: DeconzAlarmEvent | DeconzEvent | DeconzPresenceEvent | DeconzRelativeRotaryEvent
+ new_event: (
+ DeconzAlarmEvent
+ | DeconzEvent
+ | DeconzPresenceEvent
+ | DeconzRelativeRotaryEvent
+ )
sensor = hub.api.sensors[sensor_id]
if isinstance(sensor, Switch):
diff --git a/homeassistant/components/device_automation/__init__.py b/homeassistant/components/device_automation/__init__.py
index 4eaff935dce..6d95d18214e 100644
--- a/homeassistant/components/device_automation/__init__.py
+++ b/homeassistant/components/device_automation/__init__.py
@@ -134,8 +134,7 @@ async def async_get_device_automation_platform(
hass: HomeAssistant,
domain: str,
automation_type: Literal[DeviceAutomationType.TRIGGER],
-) -> DeviceAutomationTriggerProtocol:
- ...
+) -> DeviceAutomationTriggerProtocol: ...
@overload
@@ -143,8 +142,7 @@ async def async_get_device_automation_platform(
hass: HomeAssistant,
domain: str,
automation_type: Literal[DeviceAutomationType.CONDITION],
-) -> DeviceAutomationConditionProtocol:
- ...
+) -> DeviceAutomationConditionProtocol: ...
@overload
@@ -152,15 +150,13 @@ async def async_get_device_automation_platform(
hass: HomeAssistant,
domain: str,
automation_type: Literal[DeviceAutomationType.ACTION],
-) -> DeviceAutomationActionProtocol:
- ...
+) -> DeviceAutomationActionProtocol: ...
@overload
async def async_get_device_automation_platform(
hass: HomeAssistant, domain: str, automation_type: DeviceAutomationType
-) -> DeviceAutomationPlatformType:
- ...
+) -> DeviceAutomationPlatformType: ...
async def async_get_device_automation_platform(
diff --git a/homeassistant/components/devolo_home_network/device_tracker.py b/homeassistant/components/devolo_home_network/device_tracker.py
index 92ab56ab922..f97a4c36400 100644
--- a/homeassistant/components/devolo_home_network/device_tracker.py
+++ b/homeassistant/components/devolo_home_network/device_tracker.py
@@ -28,9 +28,9 @@ async def async_setup_entry(
) -> None:
"""Get all devices and sensors and setup them via config entry."""
device: Device = hass.data[DOMAIN][entry.entry_id]["device"]
- coordinators: dict[
- str, DataUpdateCoordinator[list[ConnectedStationInfo]]
- ] = hass.data[DOMAIN][entry.entry_id]["coordinators"]
+ coordinators: dict[str, DataUpdateCoordinator[list[ConnectedStationInfo]]] = (
+ hass.data[DOMAIN][entry.entry_id]["coordinators"]
+ )
registry = er.async_get(hass)
tracked = set()
diff --git a/homeassistant/components/diagnostics/__init__.py b/homeassistant/components/diagnostics/__init__.py
index 9dec7cc15be..5ada7713c33 100644
--- a/homeassistant/components/diagnostics/__init__.py
+++ b/homeassistant/components/diagnostics/__init__.py
@@ -41,13 +41,17 @@ CONFIG_SCHEMA = cv.empty_config_schema(DOMAIN)
class DiagnosticsPlatformData:
"""Diagnostic platform data."""
- config_entry_diagnostics: Callable[
- [HomeAssistant, ConfigEntry], Coroutine[Any, Any, Mapping[str, Any]]
- ] | None
- device_diagnostics: Callable[
- [HomeAssistant, ConfigEntry, DeviceEntry],
- Coroutine[Any, Any, Mapping[str, Any]],
- ] | None
+ config_entry_diagnostics: (
+ Callable[[HomeAssistant, ConfigEntry], Coroutine[Any, Any, Mapping[str, Any]]]
+ | None
+ )
+ device_diagnostics: (
+ Callable[
+ [HomeAssistant, ConfigEntry, DeviceEntry],
+ Coroutine[Any, Any, Mapping[str, Any]],
+ ]
+ | None
+ )
@dataclass(slots=True)
diff --git a/homeassistant/components/diagnostics/util.py b/homeassistant/components/diagnostics/util.py
index 5b30692aa9b..9b33b33f1ed 100644
--- a/homeassistant/components/diagnostics/util.py
+++ b/homeassistant/components/diagnostics/util.py
@@ -18,8 +18,7 @@ def async_redact_data(data: Mapping, to_redact: Iterable[Any]) -> dict: # type:
@overload
-def async_redact_data(data: _T, to_redact: Iterable[Any]) -> _T:
- ...
+def async_redact_data(data: _T, to_redact: Iterable[Any]) -> _T: ...
@callback
diff --git a/homeassistant/components/ecovacs/event.py b/homeassistant/components/ecovacs/event.py
index dbef806fa76..daac4a626ae 100644
--- a/homeassistant/components/ecovacs/event.py
+++ b/homeassistant/components/ecovacs/event.py
@@ -1,6 +1,5 @@
"""Event module."""
-
from deebot_client.capabilities import Capabilities, CapabilityEvent
from deebot_client.device import Device
from deebot_client.events import CleanJobStatus, ReportStatsEvent
diff --git a/homeassistant/components/entur_public_transport/sensor.py b/homeassistant/components/entur_public_transport/sensor.py
index fed556359bd..70b86d0271f 100644
--- a/homeassistant/components/entur_public_transport/sensor.py
+++ b/homeassistant/components/entur_public_transport/sensor.py
@@ -238,9 +238,9 @@ class EnturPublicTransportSensor(SensorEntity):
self._attributes[ATTR_NEXT_UP_AT] = calls[1].expected_departure_time.strftime(
"%H:%M"
)
- self._attributes[
- ATTR_NEXT_UP_IN
- ] = f"{due_in_minutes(calls[1].expected_departure_time)} min"
+ self._attributes[ATTR_NEXT_UP_IN] = (
+ f"{due_in_minutes(calls[1].expected_departure_time)} min"
+ )
self._attributes[ATTR_NEXT_UP_REALTIME] = calls[1].is_realtime
self._attributes[ATTR_NEXT_UP_DELAY] = calls[1].delay_in_min
diff --git a/homeassistant/components/esphome/alarm_control_panel.py b/homeassistant/components/esphome/alarm_control_panel.py
index 0c483119b22..54bce4e6015 100644
--- a/homeassistant/components/esphome/alarm_control_panel.py
+++ b/homeassistant/components/esphome/alarm_control_panel.py
@@ -40,21 +40,21 @@ from .entity import (
)
from .enum_mapper import EsphomeEnumMapper
-_ESPHOME_ACP_STATE_TO_HASS_STATE: EsphomeEnumMapper[
- AlarmControlPanelState, str
-] = EsphomeEnumMapper(
- {
- AlarmControlPanelState.DISARMED: STATE_ALARM_DISARMED,
- AlarmControlPanelState.ARMED_HOME: STATE_ALARM_ARMED_HOME,
- AlarmControlPanelState.ARMED_AWAY: STATE_ALARM_ARMED_AWAY,
- AlarmControlPanelState.ARMED_NIGHT: STATE_ALARM_ARMED_NIGHT,
- AlarmControlPanelState.ARMED_VACATION: STATE_ALARM_ARMED_VACATION,
- AlarmControlPanelState.ARMED_CUSTOM_BYPASS: STATE_ALARM_ARMED_CUSTOM_BYPASS,
- AlarmControlPanelState.PENDING: STATE_ALARM_PENDING,
- AlarmControlPanelState.ARMING: STATE_ALARM_ARMING,
- AlarmControlPanelState.DISARMING: STATE_ALARM_DISARMING,
- AlarmControlPanelState.TRIGGERED: STATE_ALARM_TRIGGERED,
- }
+_ESPHOME_ACP_STATE_TO_HASS_STATE: EsphomeEnumMapper[AlarmControlPanelState, str] = (
+ EsphomeEnumMapper(
+ {
+ AlarmControlPanelState.DISARMED: STATE_ALARM_DISARMED,
+ AlarmControlPanelState.ARMED_HOME: STATE_ALARM_ARMED_HOME,
+ AlarmControlPanelState.ARMED_AWAY: STATE_ALARM_ARMED_AWAY,
+ AlarmControlPanelState.ARMED_NIGHT: STATE_ALARM_ARMED_NIGHT,
+ AlarmControlPanelState.ARMED_VACATION: STATE_ALARM_ARMED_VACATION,
+ AlarmControlPanelState.ARMED_CUSTOM_BYPASS: STATE_ALARM_ARMED_CUSTOM_BYPASS,
+ AlarmControlPanelState.PENDING: STATE_ALARM_PENDING,
+ AlarmControlPanelState.ARMING: STATE_ALARM_ARMING,
+ AlarmControlPanelState.DISARMING: STATE_ALARM_DISARMING,
+ AlarmControlPanelState.TRIGGERED: STATE_ALARM_TRIGGERED,
+ }
+ )
)
diff --git a/homeassistant/components/esphome/entity.py b/homeassistant/components/esphome/entity.py
index c069f93276b..4f32f62ee62 100644
--- a/homeassistant/components/esphome/entity.py
+++ b/homeassistant/components/esphome/entity.py
@@ -166,14 +166,14 @@ def convert_api_error_ha_error(
ICON_SCHEMA = vol.Schema(cv.icon)
-ENTITY_CATEGORIES: EsphomeEnumMapper[
- EsphomeEntityCategory, EntityCategory | None
-] = EsphomeEnumMapper(
- {
- EsphomeEntityCategory.NONE: None,
- EsphomeEntityCategory.CONFIG: EntityCategory.CONFIG,
- EsphomeEntityCategory.DIAGNOSTIC: EntityCategory.DIAGNOSTIC,
- }
+ENTITY_CATEGORIES: EsphomeEnumMapper[EsphomeEntityCategory, EntityCategory | None] = (
+ EsphomeEnumMapper(
+ {
+ EsphomeEntityCategory.NONE: None,
+ EsphomeEntityCategory.CONFIG: EntityCategory.CONFIG,
+ EsphomeEntityCategory.DIAGNOSTIC: EntityCategory.DIAGNOSTIC,
+ }
+ )
)
diff --git a/homeassistant/components/esphome/enum_mapper.py b/homeassistant/components/esphome/enum_mapper.py
index fd09f9a05b6..0e59cde8a7e 100644
--- a/homeassistant/components/esphome/enum_mapper.py
+++ b/homeassistant/components/esphome/enum_mapper.py
@@ -21,12 +21,10 @@ class EsphomeEnumMapper(Generic[_EnumT, _ValT]):
self._inverse: dict[_ValT, _EnumT] = {v: k for k, v in mapping.items()}
@overload
- def from_esphome(self, value: _EnumT) -> _ValT:
- ...
+ def from_esphome(self, value: _EnumT) -> _ValT: ...
@overload
- def from_esphome(self, value: _EnumT | None) -> _ValT | None:
- ...
+ def from_esphome(self, value: _EnumT | None) -> _ValT | None: ...
def from_esphome(self, value: _EnumT | None) -> _ValT | None:
"""Convert from an esphome int representation to a hass string."""
diff --git a/homeassistant/components/esphome/sensor.py b/homeassistant/components/esphome/sensor.py
index e89901604b2..4c99463505f 100644
--- a/homeassistant/components/esphome/sensor.py
+++ b/homeassistant/components/esphome/sensor.py
@@ -52,15 +52,15 @@ async def async_setup_entry(
)
-_STATE_CLASSES: EsphomeEnumMapper[
- EsphomeSensorStateClass, SensorStateClass | None
-] = EsphomeEnumMapper(
- {
- EsphomeSensorStateClass.NONE: None,
- EsphomeSensorStateClass.MEASUREMENT: SensorStateClass.MEASUREMENT,
- EsphomeSensorStateClass.TOTAL_INCREASING: SensorStateClass.TOTAL_INCREASING,
- EsphomeSensorStateClass.TOTAL: SensorStateClass.TOTAL,
- }
+_STATE_CLASSES: EsphomeEnumMapper[EsphomeSensorStateClass, SensorStateClass | None] = (
+ EsphomeEnumMapper(
+ {
+ EsphomeSensorStateClass.NONE: None,
+ EsphomeSensorStateClass.MEASUREMENT: SensorStateClass.MEASUREMENT,
+ EsphomeSensorStateClass.TOTAL_INCREASING: SensorStateClass.TOTAL_INCREASING,
+ EsphomeSensorStateClass.TOTAL: SensorStateClass.TOTAL,
+ }
+ )
)
diff --git a/homeassistant/components/file_upload/__init__.py b/homeassistant/components/file_upload/__init__.py
index bb8c34fb28a..60caf0ef7f3 100644
--- a/homeassistant/components/file_upload/__init__.py
+++ b/homeassistant/components/file_upload/__init__.py
@@ -154,9 +154,9 @@ class FileUploadView(HomeAssistantView):
file_upload_data: FileUploadData = hass.data[DOMAIN]
file_dir = file_upload_data.file_dir(file_id)
- queue: SimpleQueue[
- tuple[bytes, asyncio.Future[None] | None] | None
- ] = SimpleQueue()
+ queue: SimpleQueue[tuple[bytes, asyncio.Future[None] | None] | None] = (
+ SimpleQueue()
+ )
def _sync_queue_consumer() -> None:
file_dir.mkdir()
diff --git a/homeassistant/components/forked_daapd/config_flow.py b/homeassistant/components/forked_daapd/config_flow.py
index 6f7f9f2689a..2440fc82943 100644
--- a/homeassistant/components/forked_daapd/config_flow.py
+++ b/homeassistant/components/forked_daapd/config_flow.py
@@ -96,9 +96,9 @@ def fill_in_schema_dict(some_input):
schema_dict = {}
for field, _type in DATA_SCHEMA_DICT.items():
if some_input.get(str(field)):
- schema_dict[
- vol.Optional(str(field), default=some_input[str(field)])
- ] = _type
+ schema_dict[vol.Optional(str(field), default=some_input[str(field)])] = (
+ _type
+ )
else:
schema_dict[field] = _type
return schema_dict
diff --git a/homeassistant/components/forked_daapd/media_player.py b/homeassistant/components/forked_daapd/media_player.py
index 2b6101c9c33..44596a448fc 100644
--- a/homeassistant/components/forked_daapd/media_player.py
+++ b/homeassistant/components/forked_daapd/media_player.py
@@ -127,9 +127,9 @@ async def async_setup_entry(
forked_daapd_updater = ForkedDaapdUpdater(
hass, forked_daapd_api, config_entry.entry_id
)
- hass.data[DOMAIN][config_entry.entry_id][
- HASS_DATA_UPDATER_KEY
- ] = forked_daapd_updater
+ hass.data[DOMAIN][config_entry.entry_id][HASS_DATA_UPDATER_KEY] = (
+ forked_daapd_updater
+ )
await forked_daapd_updater.async_init()
@@ -956,9 +956,9 @@ class ForkedDaapdUpdater:
if not {"outputs", "volume"}.isdisjoint(update_types): # update outputs
if outputs := await self._api.get_request("outputs"):
outputs = outputs["outputs"]
- update_events[
- "outputs"
- ] = asyncio.Event() # only for master, zones should ignore
+ update_events["outputs"] = (
+ asyncio.Event()
+ ) # only for master, zones should ignore
async_dispatcher_send(
self.hass,
SIGNAL_UPDATE_OUTPUTS.format(self._entry_id),
diff --git a/homeassistant/components/fronius/coordinator.py b/homeassistant/components/fronius/coordinator.py
index b36f1a653d9..d0a20b25bee 100644
--- a/homeassistant/components/fronius/coordinator.py
+++ b/homeassistant/components/fronius/coordinator.py
@@ -78,9 +78,9 @@ class FroniusCoordinatorBase(
for solar_net_id in data:
if solar_net_id not in self.unregistered_descriptors:
# id seen for the first time
- self.unregistered_descriptors[
- solar_net_id
- ] = self.valid_descriptions.copy()
+ self.unregistered_descriptors[solar_net_id] = (
+ self.valid_descriptions.copy()
+ )
return data
@callback
@@ -115,9 +115,9 @@ class FroniusCoordinatorBase(
solar_net_id=solar_net_id,
)
)
- self.unregistered_descriptors[
- solar_net_id
- ] = remaining_unregistered_descriptors
+ self.unregistered_descriptors[solar_net_id] = (
+ remaining_unregistered_descriptors
+ )
async_add_entities(new_entities)
_add_entities_for_unregistered_descriptors()
diff --git a/homeassistant/components/geo_rss_events/sensor.py b/homeassistant/components/geo_rss_events/sensor.py
index d64c08a6917..8c704bcf16a 100644
--- a/homeassistant/components/geo_rss_events/sensor.py
+++ b/homeassistant/components/geo_rss_events/sensor.py
@@ -162,9 +162,9 @@ class GeoRssServiceSensor(SensorEntity):
# And now compute the attributes from the filtered events.
matrix = {}
for entry in feed_entries:
- matrix[
- entry.title
- ] = f"{entry.distance_to_home:.0f}{UnitOfLength.KILOMETERS}"
+ matrix[entry.title] = (
+ f"{entry.distance_to_home:.0f}{UnitOfLength.KILOMETERS}"
+ )
self._state_attributes = matrix
elif status == UPDATE_OK_NO_DATA:
_LOGGER.debug("Update successful, but no data received from %s", self._feed)
diff --git a/homeassistant/components/geofency/device_tracker.py b/homeassistant/components/geofency/device_tracker.py
index eff937a2170..178c72d2071 100644
--- a/homeassistant/components/geofency/device_tracker.py
+++ b/homeassistant/components/geofency/device_tracker.py
@@ -30,9 +30,9 @@ async def async_setup_entry(
async_add_entities([GeofencyEntity(device, gps, location_name, attributes)])
- hass.data[GF_DOMAIN]["unsub_device_tracker"][
- config_entry.entry_id
- ] = async_dispatcher_connect(hass, TRACKER_UPDATE, _receive_data)
+ hass.data[GF_DOMAIN]["unsub_device_tracker"][config_entry.entry_id] = (
+ async_dispatcher_connect(hass, TRACKER_UPDATE, _receive_data)
+ )
# Restore previously loaded devices
dev_reg = dr.async_get(hass)
diff --git a/homeassistant/components/govee_ble/__init__.py b/homeassistant/components/govee_ble/__init__.py
index d5c601b55d9..8d074b6f997 100644
--- a/homeassistant/components/govee_ble/__init__.py
+++ b/homeassistant/components/govee_ble/__init__.py
@@ -26,14 +26,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
address = entry.unique_id
assert address is not None
data = GoveeBluetoothDeviceData()
- coordinator = hass.data.setdefault(DOMAIN, {})[
- entry.entry_id
- ] = PassiveBluetoothProcessorCoordinator(
- hass,
- _LOGGER,
- address=address,
- mode=BluetoothScanningMode.ACTIVE,
- update_method=data.update,
+ coordinator = hass.data.setdefault(DOMAIN, {})[entry.entry_id] = (
+ PassiveBluetoothProcessorCoordinator(
+ hass,
+ _LOGGER,
+ address=address,
+ mode=BluetoothScanningMode.ACTIVE,
+ update_method=data.update,
+ )
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(
diff --git a/homeassistant/components/gpslogger/device_tracker.py b/homeassistant/components/gpslogger/device_tracker.py
index 025183718fc..4a28606662f 100644
--- a/homeassistant/components/gpslogger/device_tracker.py
+++ b/homeassistant/components/gpslogger/device_tracker.py
@@ -40,9 +40,9 @@ async def async_setup_entry(
async_add_entities([GPSLoggerEntity(device, gps, battery, accuracy, attrs)])
- hass.data[GPL_DOMAIN]["unsub_device_tracker"][
- entry.entry_id
- ] = async_dispatcher_connect(hass, TRACKER_UPDATE, _receive_data)
+ hass.data[GPL_DOMAIN]["unsub_device_tracker"][entry.entry_id] = (
+ async_dispatcher_connect(hass, TRACKER_UPDATE, _receive_data)
+ )
# Restore previously loaded devices
dev_reg = dr.async_get(hass)
diff --git a/homeassistant/components/gtfs/sensor.py b/homeassistant/components/gtfs/sensor.py
index 8a20755e936..a0a0f0ebc0e 100644
--- a/homeassistant/components/gtfs/sensor.py
+++ b/homeassistant/components/gtfs/sensor.py
@@ -737,10 +737,10 @@ class GTFSDepartureSensor(SensorEntity):
self._attributes[ATTR_LOCATION_DESTINATION] = LOCATION_TYPE_OPTIONS.get(
self._destination.location_type, LOCATION_TYPE_DEFAULT
)
- self._attributes[
- ATTR_WHEELCHAIR_DESTINATION
- ] = WHEELCHAIR_BOARDING_OPTIONS.get(
- self._destination.wheelchair_boarding, WHEELCHAIR_BOARDING_DEFAULT
+ self._attributes[ATTR_WHEELCHAIR_DESTINATION] = (
+ WHEELCHAIR_BOARDING_OPTIONS.get(
+ self._destination.wheelchair_boarding, WHEELCHAIR_BOARDING_DEFAULT
+ )
)
# Manage Route metadata
diff --git a/homeassistant/components/guardian/__init__.py b/homeassistant/components/guardian/__init__.py
index 4c6a979cd1d..812c54d76a6 100644
--- a/homeassistant/components/guardian/__init__.py
+++ b/homeassistant/components/guardian/__init__.py
@@ -139,16 +139,16 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
(API_VALVE_STATUS, client.valve.status),
(API_WIFI_STATUS, client.wifi.status),
):
- coordinator = valve_controller_coordinators[
- api
- ] = GuardianDataUpdateCoordinator(
- hass,
- entry=entry,
- client=client,
- api_name=api,
- api_coro=api_coro,
- api_lock=api_lock,
- valve_controller_uid=entry.data[CONF_UID],
+ coordinator = valve_controller_coordinators[api] = (
+ GuardianDataUpdateCoordinator(
+ hass,
+ entry=entry,
+ client=client,
+ api_name=api,
+ api_coro=api_coro,
+ api_lock=api_lock,
+ valve_controller_uid=entry.data[CONF_UID],
+ )
)
init_valve_controller_tasks.append(async_init_coordinator(coordinator))
diff --git a/homeassistant/components/hassio/http.py b/homeassistant/components/hassio/http.py
index 0b92ada6c70..ffb67730fa5 100644
--- a/homeassistant/components/hassio/http.py
+++ b/homeassistant/components/hassio/http.py
@@ -148,9 +148,9 @@ class HassIOView(HomeAssistantView):
return web.Response(status=HTTPStatus.UNAUTHORIZED)
if authorized:
- headers[
- AUTHORIZATION
- ] = f"Bearer {os.environ.get('SUPERVISOR_TOKEN', '')}"
+ headers[AUTHORIZATION] = (
+ f"Bearer {os.environ.get('SUPERVISOR_TOKEN', '')}"
+ )
if request.method == "POST":
headers[CONTENT_TYPE] = request.content_type
diff --git a/homeassistant/components/heos/media_player.py b/homeassistant/components/heos/media_player.py
index 5fd64ec7d38..564b764bc2e 100644
--- a/homeassistant/components/heos/media_player.py
+++ b/homeassistant/components/heos/media_player.py
@@ -161,9 +161,9 @@ class HeosMediaPlayer(MediaPlayerEntity):
async_dispatcher_connect(self.hass, SIGNAL_HEOS_UPDATED, self._heos_updated)
)
# Register this player's entity_id so it can be resolved by the group manager
- self.hass.data[HEOS_DOMAIN][DATA_ENTITY_ID_MAP][
- self._player.player_id
- ] = self.entity_id
+ self.hass.data[HEOS_DOMAIN][DATA_ENTITY_ID_MAP][self._player.player_id] = (
+ self.entity_id
+ )
async_dispatcher_send(self.hass, SIGNAL_HEOS_PLAYER_ADDED)
@log_command_error("clear playlist")
diff --git a/homeassistant/components/http/decorators.py b/homeassistant/components/http/decorators.py
index bffb42d5817..d2e6121b08e 100644
--- a/homeassistant/components/http/decorators.py
+++ b/homeassistant/components/http/decorators.py
@@ -29,15 +29,13 @@ def require_admin(
) -> Callable[
[_FuncType[_HomeAssistantViewT, _P, _ResponseT]],
_FuncType[_HomeAssistantViewT, _P, _ResponseT],
-]:
- ...
+]: ...
@overload
def require_admin(
_func: _FuncType[_HomeAssistantViewT, _P, _ResponseT],
-) -> _FuncType[_HomeAssistantViewT, _P, _ResponseT]:
- ...
+) -> _FuncType[_HomeAssistantViewT, _P, _ResponseT]: ...
def require_admin(
diff --git a/homeassistant/components/humidifier/device_trigger.py b/homeassistant/components/humidifier/device_trigger.py
index 757b0d9a078..80e0ef8df58 100644
--- a/homeassistant/components/humidifier/device_trigger.py
+++ b/homeassistant/components/humidifier/device_trigger.py
@@ -126,13 +126,13 @@ async def async_attach_trigger(
),
}
if trigger_type == "target_humidity_changed":
- numeric_state_config[
- numeric_state_trigger.CONF_VALUE_TEMPLATE
- ] = "{{ state.attributes.humidity }}"
+ numeric_state_config[numeric_state_trigger.CONF_VALUE_TEMPLATE] = (
+ "{{ state.attributes.humidity }}"
+ )
else: # trigger_type == "current_humidity_changed"
- numeric_state_config[
- numeric_state_trigger.CONF_VALUE_TEMPLATE
- ] = "{{ state.attributes.current_humidity }}"
+ numeric_state_config[numeric_state_trigger.CONF_VALUE_TEMPLATE] = (
+ "{{ state.attributes.current_humidity }}"
+ )
if CONF_ABOVE in config:
numeric_state_config[CONF_ABOVE] = config[CONF_ABOVE]
diff --git a/homeassistant/components/hunterdouglas_powerview/__init__.py b/homeassistant/components/hunterdouglas_powerview/__init__.py
index d1ac0950c58..106a61e75cc 100644
--- a/homeassistant/components/hunterdouglas_powerview/__init__.py
+++ b/homeassistant/components/hunterdouglas_powerview/__init__.py
@@ -1,4 +1,5 @@
"""The Hunter Douglas PowerView integration."""
+
import logging
from aiopvapi.helpers.aiorequest import AioRequest
diff --git a/homeassistant/components/icloud/account.py b/homeassistant/components/icloud/account.py
index 7e7f4632b59..015726fbf73 100644
--- a/homeassistant/components/icloud/account.py
+++ b/homeassistant/components/icloud/account.py
@@ -150,9 +150,9 @@ class IcloudAccount:
self._family_members_fullname = {}
if user_info.get("membersInfo") is not None:
for prs_id, member in user_info["membersInfo"].items():
- self._family_members_fullname[
- prs_id
- ] = f"{member['firstName']} {member['lastName']}"
+ self._family_members_fullname[prs_id] = (
+ f"{member['firstName']} {member['lastName']}"
+ )
self._devices = {}
self.update_devices()
diff --git a/homeassistant/components/imap/__init__.py b/homeassistant/components/imap/__init__.py
index 091110c5e51..7504446f3fb 100644
--- a/homeassistant/components/imap/__init__.py
+++ b/homeassistant/components/imap/__init__.py
@@ -63,8 +63,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
- coordinator: ImapPushDataUpdateCoordinator | ImapPollingDataUpdateCoordinator = hass.data[
- DOMAIN
- ].pop(entry.entry_id)
+ coordinator: (
+ ImapPushDataUpdateCoordinator | ImapPollingDataUpdateCoordinator
+ ) = hass.data[DOMAIN].pop(entry.entry_id)
await coordinator.shutdown()
return unload_ok
diff --git a/homeassistant/components/influxdb/__init__.py b/homeassistant/components/influxdb/__init__.py
index 5c40dac1c9d..b1c0cc53d61 100644
--- a/homeassistant/components/influxdb/__init__.py
+++ b/homeassistant/components/influxdb/__init__.py
@@ -513,9 +513,9 @@ class InfluxThread(threading.Thread):
def __init__(self, hass, influx, event_to_json, max_tries):
"""Initialize the listener."""
threading.Thread.__init__(self, name=DOMAIN)
- self.queue: queue.SimpleQueue[
- threading.Event | tuple[float, Event] | None
- ] = queue.SimpleQueue()
+ self.queue: queue.SimpleQueue[threading.Event | tuple[float, Event] | None] = (
+ queue.SimpleQueue()
+ )
self.influx = influx
self.event_to_json = event_to_json
self.max_tries = max_tries
diff --git a/homeassistant/components/inkbird/__init__.py b/homeassistant/components/inkbird/__init__.py
index f78a6c4e1b8..c715c64599a 100644
--- a/homeassistant/components/inkbird/__init__.py
+++ b/homeassistant/components/inkbird/__init__.py
@@ -26,14 +26,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
address = entry.unique_id
assert address is not None
data = INKBIRDBluetoothDeviceData()
- coordinator = hass.data.setdefault(DOMAIN, {})[
- entry.entry_id
- ] = PassiveBluetoothProcessorCoordinator(
- hass,
- _LOGGER,
- address=address,
- mode=BluetoothScanningMode.ACTIVE,
- update_method=data.update,
+ coordinator = hass.data.setdefault(DOMAIN, {})[entry.entry_id] = (
+ PassiveBluetoothProcessorCoordinator(
+ hass,
+ _LOGGER,
+ address=address,
+ mode=BluetoothScanningMode.ACTIVE,
+ update_method=data.update,
+ )
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(
diff --git a/homeassistant/components/iqvia/sensor.py b/homeassistant/components/iqvia/sensor.py
index da8556d9218..ba3c288b702 100644
--- a/homeassistant/components/iqvia/sensor.py
+++ b/homeassistant/components/iqvia/sensor.py
@@ -212,12 +212,12 @@ class ForecastSensor(IQVIAEntity, SensorEntity):
if not outlook_coordinator.last_update_success:
return
- self._attr_extra_state_attributes[
- ATTR_OUTLOOK
- ] = outlook_coordinator.data.get("Outlook")
- self._attr_extra_state_attributes[
- ATTR_SEASON
- ] = outlook_coordinator.data.get("Season")
+ self._attr_extra_state_attributes[ATTR_OUTLOOK] = (
+ outlook_coordinator.data.get("Outlook")
+ )
+ self._attr_extra_state_attributes[ATTR_SEASON] = (
+ outlook_coordinator.data.get("Season")
+ )
class IndexSensor(IQVIAEntity, SensorEntity):
@@ -283,8 +283,8 @@ class IndexSensor(IQVIAEntity, SensorEntity):
)
elif self.entity_description.key == TYPE_DISEASE_TODAY:
for attrs in period["Triggers"]:
- self._attr_extra_state_attributes[
- f"{attrs['Name'].lower()}_index"
- ] = attrs["Index"]
+ self._attr_extra_state_attributes[f"{attrs['Name'].lower()}_index"] = (
+ attrs["Index"]
+ )
self._attr_native_value = period["Index"]
diff --git a/homeassistant/components/isy994/helpers.py b/homeassistant/components/isy994/helpers.py
index 1e496446a30..8b6a4249931 100644
--- a/homeassistant/components/isy994/helpers.py
+++ b/homeassistant/components/isy994/helpers.py
@@ -317,9 +317,9 @@ def _generate_device_info(node: Node) -> DeviceInfo:
and node.zwave_props
and node.zwave_props.mfr_id != "0"
):
- device_info[
- ATTR_MANUFACTURER
- ] = f"Z-Wave MfrID:{int(node.zwave_props.mfr_id):#0{6}x}"
+ device_info[ATTR_MANUFACTURER] = (
+ f"Z-Wave MfrID:{int(node.zwave_props.mfr_id):#0{6}x}"
+ )
model += (
f"Type:{int(node.zwave_props.prod_type_id):#0{6}x} "
f"Product:{int(node.zwave_props.product_id):#0{6}x}"
diff --git a/homeassistant/components/kegtron/__init__.py b/homeassistant/components/kegtron/__init__.py
index 55b93a0da3d..d7485be0840 100644
--- a/homeassistant/components/kegtron/__init__.py
+++ b/homeassistant/components/kegtron/__init__.py
@@ -26,14 +26,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
address = entry.unique_id
assert address is not None
data = KegtronBluetoothDeviceData()
- coordinator = hass.data.setdefault(DOMAIN, {})[
- entry.entry_id
- ] = PassiveBluetoothProcessorCoordinator(
- hass,
- _LOGGER,
- address=address,
- mode=BluetoothScanningMode.PASSIVE,
- update_method=data.update,
+ coordinator = hass.data.setdefault(DOMAIN, {})[entry.entry_id] = (
+ PassiveBluetoothProcessorCoordinator(
+ hass,
+ _LOGGER,
+ address=address,
+ mode=BluetoothScanningMode.PASSIVE,
+ update_method=data.update,
+ )
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(
diff --git a/homeassistant/components/leaone/__init__.py b/homeassistant/components/leaone/__init__.py
index 74dfa872ce2..74119cfaa4c 100644
--- a/homeassistant/components/leaone/__init__.py
+++ b/homeassistant/components/leaone/__init__.py
@@ -26,14 +26,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
address = entry.unique_id
assert address is not None
data = LeaoneBluetoothDeviceData()
- coordinator = hass.data.setdefault(DOMAIN, {})[
- entry.entry_id
- ] = PassiveBluetoothProcessorCoordinator(
- hass,
- _LOGGER,
- address=address,
- mode=BluetoothScanningMode.PASSIVE,
- update_method=data.update,
+ coordinator = hass.data.setdefault(DOMAIN, {})[entry.entry_id] = (
+ PassiveBluetoothProcessorCoordinator(
+ hass,
+ _LOGGER,
+ address=address,
+ mode=BluetoothScanningMode.PASSIVE,
+ update_method=data.update,
+ )
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(
diff --git a/homeassistant/components/lidarr/sensor.py b/homeassistant/components/lidarr/sensor.py
index 9a3dee1a802..c876aec4623 100644
--- a/homeassistant/components/lidarr/sensor.py
+++ b/homeassistant/components/lidarr/sensor.py
@@ -63,10 +63,13 @@ class LidarrSensorEntityDescription(
"""Class to describe a Lidarr sensor."""
attributes_fn: Callable[[T], dict[str, str] | None] = lambda _: None
- description_fn: Callable[
- [LidarrSensorEntityDescription[T], LidarrRootFolder],
- tuple[LidarrSensorEntityDescription[T], str] | None,
- ] | None = None
+ description_fn: (
+ Callable[
+ [LidarrSensorEntityDescription[T], LidarrRootFolder],
+ tuple[LidarrSensorEntityDescription[T], str] | None,
+ ]
+ | None
+ ) = None
SENSOR_TYPES: dict[str, LidarrSensorEntityDescription[Any]] = {
diff --git a/homeassistant/components/light/__init__.py b/homeassistant/components/light/__init__.py
index 0045e2324ff..53c7328ece4 100644
--- a/homeassistant/components/light/__init__.py
+++ b/homeassistant/components/light/__init__.py
@@ -1218,9 +1218,9 @@ class LightEntity(ToggleEntity, cached_properties=CACHED_PROPERTIES_WITH_ATTR_):
color_temp_kelvin = self.color_temp_kelvin
data[ATTR_COLOR_TEMP_KELVIN] = color_temp_kelvin
if color_temp_kelvin:
- data[
- ATTR_COLOR_TEMP
- ] = color_util.color_temperature_kelvin_to_mired(color_temp_kelvin)
+ data[ATTR_COLOR_TEMP] = (
+ color_util.color_temperature_kelvin_to_mired(color_temp_kelvin)
+ )
else:
data[ATTR_COLOR_TEMP] = None
else:
@@ -1233,9 +1233,9 @@ class LightEntity(ToggleEntity, cached_properties=CACHED_PROPERTIES_WITH_ATTR_):
color_temp_kelvin = self.color_temp_kelvin
data[ATTR_COLOR_TEMP_KELVIN] = color_temp_kelvin
if color_temp_kelvin:
- data[
- ATTR_COLOR_TEMP
- ] = color_util.color_temperature_kelvin_to_mired(color_temp_kelvin)
+ data[ATTR_COLOR_TEMP] = (
+ color_util.color_temperature_kelvin_to_mired(color_temp_kelvin)
+ )
else:
data[ATTR_COLOR_TEMP] = None
else:
diff --git a/homeassistant/components/locative/device_tracker.py b/homeassistant/components/locative/device_tracker.py
index e8135bbd03c..0b5cb32c22b 100644
--- a/homeassistant/components/locative/device_tracker.py
+++ b/homeassistant/components/locative/device_tracker.py
@@ -24,9 +24,9 @@ async def async_setup_entry(
async_add_entities([LocativeEntity(device, location, location_name)])
- hass.data[LT_DOMAIN]["unsub_device_tracker"][
- entry.entry_id
- ] = async_dispatcher_connect(hass, TRACKER_UPDATE, _receive_data)
+ hass.data[LT_DOMAIN]["unsub_device_tracker"][entry.entry_id] = (
+ async_dispatcher_connect(hass, TRACKER_UPDATE, _receive_data)
+ )
class LocativeEntity(TrackerEntity):
diff --git a/homeassistant/components/london_air/sensor.py b/homeassistant/components/london_air/sensor.py
index 12d52b9a20a..0895e507a85 100644
--- a/homeassistant/components/london_air/sensor.py
+++ b/homeassistant/components/london_air/sensor.py
@@ -166,9 +166,9 @@ def parse_species(species_data):
species_dict["code"] = species["@SpeciesCode"]
species_dict["quality"] = species["@AirQualityBand"]
species_dict["index"] = species["@AirQualityIndex"]
- species_dict[
- "summary"
- ] = f"{species_dict['code']} is {species_dict['quality']}"
+ species_dict["summary"] = (
+ f"{species_dict['code']} is {species_dict['quality']}"
+ )
parsed_species_data.append(species_dict)
quality_list.append(species_dict["quality"])
return parsed_species_data, quality_list
diff --git a/homeassistant/components/moat/__init__.py b/homeassistant/components/moat/__init__.py
index 4c48c03b897..8ee2e294552 100644
--- a/homeassistant/components/moat/__init__.py
+++ b/homeassistant/components/moat/__init__.py
@@ -26,14 +26,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
address = entry.unique_id
assert address is not None
data = MoatBluetoothDeviceData()
- coordinator = hass.data.setdefault(DOMAIN, {})[
- entry.entry_id
- ] = PassiveBluetoothProcessorCoordinator(
- hass,
- _LOGGER,
- address=address,
- mode=BluetoothScanningMode.PASSIVE,
- update_method=data.update,
+ coordinator = hass.data.setdefault(DOMAIN, {})[entry.entry_id] = (
+ PassiveBluetoothProcessorCoordinator(
+ hass,
+ _LOGGER,
+ address=address,
+ mode=BluetoothScanningMode.PASSIVE,
+ update_method=data.update,
+ )
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(
diff --git a/homeassistant/components/mobile_app/webhook.py b/homeassistant/components/mobile_app/webhook.py
index 3e16c21261b..e7cccd0f151 100644
--- a/homeassistant/components/mobile_app/webhook.py
+++ b/homeassistant/components/mobile_app/webhook.py
@@ -602,9 +602,9 @@ async def webhook_register_sensor(
async_dispatcher_send(hass, f"{SIGNAL_SENSOR_UPDATE}-{unique_store_key}", data)
else:
data[CONF_UNIQUE_ID] = unique_store_key
- data[
- CONF_NAME
- ] = f"{config_entry.data[ATTR_DEVICE_NAME]} {data[ATTR_SENSOR_NAME]}"
+ data[CONF_NAME] = (
+ f"{config_entry.data[ATTR_DEVICE_NAME]} {data[ATTR_SENSOR_NAME]}"
+ )
register_signal = f"{DOMAIN}_{data[ATTR_SENSOR_TYPE]}_register"
async_dispatcher_send(hass, register_signal, data)
diff --git a/homeassistant/components/modbus/modbus.py b/homeassistant/components/modbus/modbus.py
index d955c6656f8..0d1848e0d8e 100644
--- a/homeassistant/components/modbus/modbus.py
+++ b/homeassistant/components/modbus/modbus.py
@@ -258,7 +258,9 @@ class ModbusHub:
"""Initialize the Modbus hub."""
# generic configuration
- self._client: AsyncModbusSerialClient | AsyncModbusTcpClient | AsyncModbusUdpClient | None = None
+ self._client: (
+ AsyncModbusSerialClient | AsyncModbusTcpClient | AsyncModbusUdpClient | None
+ ) = None
self._async_cancel_listener: Callable[[], None] | None = None
self._in_error = False
self._lock = asyncio.Lock()
diff --git a/homeassistant/components/mopeka/__init__.py b/homeassistant/components/mopeka/__init__.py
index 09dec3bf3d2..da3ee156683 100644
--- a/homeassistant/components/mopeka/__init__.py
+++ b/homeassistant/components/mopeka/__init__.py
@@ -26,14 +26,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
address = entry.unique_id
assert address is not None
data = MopekaIOTBluetoothDeviceData()
- coordinator = hass.data.setdefault(DOMAIN, {})[
- entry.entry_id
- ] = PassiveBluetoothProcessorCoordinator(
- hass,
- _LOGGER,
- address=address,
- mode=BluetoothScanningMode.PASSIVE,
- update_method=data.update,
+ coordinator = hass.data.setdefault(DOMAIN, {})[entry.entry_id] = (
+ PassiveBluetoothProcessorCoordinator(
+ hass,
+ _LOGGER,
+ address=address,
+ mode=BluetoothScanningMode.PASSIVE,
+ update_method=data.update,
+ )
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(
diff --git a/homeassistant/components/mqtt/config_flow.py b/homeassistant/components/mqtt/config_flow.py
index b6fcae4d5ec..5bf0c9c1879 100644
--- a/homeassistant/components/mqtt/config_flow.py
+++ b/homeassistant/components/mqtt/config_flow.py
@@ -398,9 +398,9 @@ class MQTTOptionsFlowHandler(OptionsFlow):
# build form
fields: OrderedDict[vol.Marker, Any] = OrderedDict()
fields[vol.Optional(CONF_DISCOVERY, default=discovery)] = BOOLEAN_SELECTOR
- fields[
- vol.Optional(CONF_DISCOVERY_PREFIX, default=discovery_prefix)
- ] = PUBLISH_TOPIC_SELECTOR
+ fields[vol.Optional(CONF_DISCOVERY_PREFIX, default=discovery_prefix)] = (
+ PUBLISH_TOPIC_SELECTOR
+ )
# Birth message is disabled if CONF_BIRTH_MESSAGE = {}
fields[
@@ -421,9 +421,9 @@ class MQTTOptionsFlowHandler(OptionsFlow):
)
] = TEXT_SELECTOR
fields[vol.Optional("birth_qos", default=birth[ATTR_QOS])] = QOS_SELECTOR
- fields[
- vol.Optional("birth_retain", default=birth[ATTR_RETAIN])
- ] = BOOLEAN_SELECTOR
+ fields[vol.Optional("birth_retain", default=birth[ATTR_RETAIN])] = (
+ BOOLEAN_SELECTOR
+ )
# Will message is disabled if CONF_WILL_MESSAGE = {}
fields[
@@ -444,9 +444,9 @@ class MQTTOptionsFlowHandler(OptionsFlow):
)
] = TEXT_SELECTOR
fields[vol.Optional("will_qos", default=will[ATTR_QOS])] = QOS_SELECTOR
- fields[
- vol.Optional("will_retain", default=will[ATTR_RETAIN])
- ] = BOOLEAN_SELECTOR
+ fields[vol.Optional("will_retain", default=will[ATTR_RETAIN])] = (
+ BOOLEAN_SELECTOR
+ )
return self.async_show_form(
step_id="options",
diff --git a/homeassistant/components/mqtt/mixins.py b/homeassistant/components/mqtt/mixins.py
index 84afe26bc97..42ad807d2f1 100644
--- a/homeassistant/components/mqtt/mixins.py
+++ b/homeassistant/components/mqtt/mixins.py
@@ -1055,16 +1055,16 @@ class MqttDiscoveryUpdate(Entity):
if self._discovery_data is not None:
discovery_hash: tuple[str, str] = self._discovery_data[ATTR_DISCOVERY_HASH]
if self.registry_entry is not None:
- self._registry_hooks[
- discovery_hash
- ] = async_track_entity_registry_updated_event(
- self.hass,
- self.entity_id,
- partial(
- async_clear_discovery_topic_if_entity_removed,
+ self._registry_hooks[discovery_hash] = (
+ async_track_entity_registry_updated_event(
self.hass,
- self._discovery_data,
- ),
+ self.entity_id,
+ partial(
+ async_clear_discovery_topic_if_entity_removed,
+ self.hass,
+ self._discovery_data,
+ ),
+ )
)
stop_discovery_updates(self.hass, self._discovery_data)
send_discovery_done(self.hass, self._discovery_data)
diff --git a/homeassistant/components/mutesync/__init__.py b/homeassistant/components/mutesync/__init__.py
index 40aba72b0f6..75eefaf6784 100644
--- a/homeassistant/components/mutesync/__init__.py
+++ b/homeassistant/components/mutesync/__init__.py
@@ -41,14 +41,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
return state
- coordinator = hass.data.setdefault(DOMAIN, {})[
- entry.entry_id
- ] = update_coordinator.DataUpdateCoordinator(
- hass,
- logging.getLogger(__name__),
- name=DOMAIN,
- update_interval=UPDATE_INTERVAL_NOT_IN_MEETING,
- update_method=update_data,
+ coordinator = hass.data.setdefault(DOMAIN, {})[entry.entry_id] = (
+ update_coordinator.DataUpdateCoordinator(
+ hass,
+ logging.getLogger(__name__),
+ name=DOMAIN,
+ update_interval=UPDATE_INTERVAL_NOT_IN_MEETING,
+ update_method=update_data,
+ )
)
await coordinator.async_config_entry_first_refresh()
diff --git a/homeassistant/components/mysensors/config_flow.py b/homeassistant/components/mysensors/config_flow.py
index 7920e8025cf..b4347a39e12 100644
--- a/homeassistant/components/mysensors/config_flow.py
+++ b/homeassistant/components/mysensors/config_flow.py
@@ -302,9 +302,9 @@ class MySensorsConfigFlowHandler(ConfigFlow, domain=DOMAIN):
except vol.Invalid:
errors[CONF_PERSISTENCE_FILE] = "invalid_persistence_file"
else:
- real_persistence_path = user_input[
- CONF_PERSISTENCE_FILE
- ] = self._normalize_persistence_file(user_input[CONF_PERSISTENCE_FILE])
+ real_persistence_path = user_input[CONF_PERSISTENCE_FILE] = (
+ self._normalize_persistence_file(user_input[CONF_PERSISTENCE_FILE])
+ )
for other_entry in self._async_current_entries():
if CONF_PERSISTENCE_FILE not in other_entry.data:
continue
diff --git a/homeassistant/components/mysensors/gateway.py b/homeassistant/components/mysensors/gateway.py
index 177dbbe4dc9..b932a33d0fa 100644
--- a/homeassistant/components/mysensors/gateway.py
+++ b/homeassistant/components/mysensors/gateway.py
@@ -279,10 +279,8 @@ async def _gw_start(
gateway.on_conn_made = gateway_connected
# Don't use hass.async_create_task to avoid holding up setup indefinitely.
- hass.data[DOMAIN][
- MYSENSORS_GATEWAY_START_TASK.format(entry.entry_id)
- ] = asyncio.create_task(
- gateway.start()
+ hass.data[DOMAIN][MYSENSORS_GATEWAY_START_TASK.format(entry.entry_id)] = (
+ asyncio.create_task(gateway.start())
) # store the connect task so it can be cancelled in gw_stop
async def stop_this_gw(_: Event) -> None:
diff --git a/homeassistant/components/netatmo/climate.py b/homeassistant/components/netatmo/climate.py
index df9c7f6fee2..15bf3291618 100644
--- a/homeassistant/components/netatmo/climate.py
+++ b/homeassistant/components/netatmo/climate.py
@@ -267,9 +267,9 @@ class NetatmoThermostat(NetatmoBaseEntity, ClimateEntity):
"name",
None,
)
- self._attr_extra_state_attributes[
- ATTR_SELECTED_SCHEDULE
- ] = self._selected_schedule
+ self._attr_extra_state_attributes[ATTR_SELECTED_SCHEDULE] = (
+ self._selected_schedule
+ )
self.async_write_ha_state()
self.data_handler.async_force_update(self._signal_name)
return
@@ -430,14 +430,14 @@ class NetatmoThermostat(NetatmoBaseEntity, ClimateEntity):
self._selected_schedule = getattr(
self._room.home.get_selected_schedule(), "name", None
)
- self._attr_extra_state_attributes[
- ATTR_SELECTED_SCHEDULE
- ] = self._selected_schedule
+ self._attr_extra_state_attributes[ATTR_SELECTED_SCHEDULE] = (
+ self._selected_schedule
+ )
if self._model == NA_VALVE:
- self._attr_extra_state_attributes[
- ATTR_HEATING_POWER_REQUEST
- ] = self._room.heating_power_request
+ self._attr_extra_state_attributes[ATTR_HEATING_POWER_REQUEST] = (
+ self._room.heating_power_request
+ )
else:
for module in self._room.modules.values():
if hasattr(module, "boiler_status"):
diff --git a/homeassistant/components/netatmo/config_flow.py b/homeassistant/components/netatmo/config_flow.py
index 54ec019f815..b5eae967d56 100644
--- a/homeassistant/components/netatmo/config_flow.py
+++ b/homeassistant/components/netatmo/config_flow.py
@@ -149,13 +149,13 @@ class NetatmoOptionsFlowHandler(OptionsFlow):
async def async_step_public_weather(self, user_input: dict) -> ConfigFlowResult:
"""Manage configuration of Netatmo public weather sensors."""
if user_input is not None and CONF_NEW_AREA not in user_input:
- self.options[CONF_WEATHER_AREAS][
- user_input[CONF_AREA_NAME]
- ] = fix_coordinates(user_input)
+ self.options[CONF_WEATHER_AREAS][user_input[CONF_AREA_NAME]] = (
+ fix_coordinates(user_input)
+ )
- self.options[CONF_WEATHER_AREAS][user_input[CONF_AREA_NAME]][
- CONF_UUID
- ] = str(uuid.uuid4())
+ self.options[CONF_WEATHER_AREAS][user_input[CONF_AREA_NAME]][CONF_UUID] = (
+ str(uuid.uuid4())
+ )
return await self.async_step_public_weather_areas()
diff --git a/homeassistant/components/nissan_leaf/__init__.py b/homeassistant/components/nissan_leaf/__init__.py
index 85ff6876a05..9eaca66119f 100644
--- a/homeassistant/components/nissan_leaf/__init__.py
+++ b/homeassistant/components/nissan_leaf/__init__.py
@@ -321,9 +321,9 @@ class LeafDataStore:
self.data[DATA_RANGE_AC] = None
if hasattr(server_response, "cruising_range_ac_off_km"):
- self.data[
- DATA_RANGE_AC_OFF
- ] = server_response.cruising_range_ac_off_km
+ self.data[DATA_RANGE_AC_OFF] = (
+ server_response.cruising_range_ac_off_km
+ )
else:
self.data[DATA_RANGE_AC_OFF] = None
diff --git a/homeassistant/components/nzbget/config_flow.py b/homeassistant/components/nzbget/config_flow.py
index ff89d8090d6..2c549e4ed24 100644
--- a/homeassistant/components/nzbget/config_flow.py
+++ b/homeassistant/components/nzbget/config_flow.py
@@ -82,9 +82,9 @@ class NZBGetConfigFlow(ConfigFlow, domain=DOMAIN):
}
if self.show_advanced_options:
- data_schema[
- vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL)
- ] = bool
+ data_schema[vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL)] = (
+ bool
+ )
return self.async_show_form(
step_id="user",
diff --git a/homeassistant/components/onvif/camera.py b/homeassistant/components/onvif/camera.py
index 3fa41d629b2..4b6dfa1a625 100644
--- a/homeassistant/components/onvif/camera.py
+++ b/homeassistant/components/onvif/camera.py
@@ -105,9 +105,9 @@ class ONVIFCameraEntity(ONVIFBaseEntity, Camera):
self.stream_options[CONF_RTSP_TRANSPORT] = device.config_entry.options.get(
CONF_RTSP_TRANSPORT, next(iter(RTSP_TRANSPORTS))
)
- self.stream_options[
- CONF_USE_WALLCLOCK_AS_TIMESTAMPS
- ] = device.config_entry.options.get(CONF_USE_WALLCLOCK_AS_TIMESTAMPS, False)
+ self.stream_options[CONF_USE_WALLCLOCK_AS_TIMESTAMPS] = (
+ device.config_entry.options.get(CONF_USE_WALLCLOCK_AS_TIMESTAMPS, False)
+ )
self._basic_auth = (
device.config_entry.data.get(CONF_SNAPSHOT_AUTH)
== HTTP_BASIC_AUTHENTICATION
diff --git a/homeassistant/components/onvif/parsers.py b/homeassistant/components/onvif/parsers.py
index 721ec08cb48..690a3739b4f 100644
--- a/homeassistant/components/onvif/parsers.py
+++ b/homeassistant/components/onvif/parsers.py
@@ -12,9 +12,9 @@ from homeassistant.util.decorator import Registry
from .models import Event
-PARSERS: Registry[
- str, Callable[[str, Any], Coroutine[Any, Any, Event | None]]
-] = Registry()
+PARSERS: Registry[str, Callable[[str, Any], Coroutine[Any, Any, Event | None]]] = (
+ Registry()
+)
VIDEO_SOURCE_MAPPING = {
"vsconf": "VideoSourceToken",
diff --git a/homeassistant/components/oralb/__init__.py b/homeassistant/components/oralb/__init__.py
index 29aa63410e5..71bcb2f2deb 100644
--- a/homeassistant/components/oralb/__init__.py
+++ b/homeassistant/components/oralb/__init__.py
@@ -65,20 +65,20 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
)
return await data.async_poll(connectable_device)
- coordinator = hass.data.setdefault(DOMAIN, {})[
- entry.entry_id
- ] = ActiveBluetoothProcessorCoordinator(
- hass,
- _LOGGER,
- address=address,
- mode=BluetoothScanningMode.PASSIVE,
- update_method=data.update,
- needs_poll_method=_needs_poll,
- poll_method=_async_poll,
- # We will take advertisements from non-connectable devices
- # since we will trade the BLEDevice for a connectable one
- # if we need to poll it
- connectable=False,
+ coordinator = hass.data.setdefault(DOMAIN, {})[entry.entry_id] = (
+ ActiveBluetoothProcessorCoordinator(
+ hass,
+ _LOGGER,
+ address=address,
+ mode=BluetoothScanningMode.PASSIVE,
+ update_method=data.update,
+ needs_poll_method=_needs_poll,
+ poll_method=_async_poll,
+ # We will take advertisements from non-connectable devices
+ # since we will trade the BLEDevice for a connectable one
+ # if we need to poll it
+ connectable=False,
+ )
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(
diff --git a/homeassistant/components/overkiz/number.py b/homeassistant/components/overkiz/number.py
index 76a3e5d932b..f81ed82f7b1 100644
--- a/homeassistant/components/overkiz/number.py
+++ b/homeassistant/components/overkiz/number.py
@@ -37,9 +37,9 @@ class OverkizNumberDescription(NumberEntityDescription):
min_value_state_name: str | None = None
max_value_state_name: str | None = None
inverted: bool = False
- set_native_value: Callable[
- [float, Callable[..., Awaitable[None]]], Awaitable[None]
- ] | None = None
+ set_native_value: (
+ Callable[[float, Callable[..., Awaitable[None]]], Awaitable[None]] | None
+ ) = None
async def _async_set_native_value_boost_mode_duration(
diff --git a/homeassistant/components/plex/sensor.py b/homeassistant/components/plex/sensor.py
index 30ff8e72f60..eb27f465a7e 100644
--- a/homeassistant/components/plex/sensor.py
+++ b/homeassistant/components/plex/sensor.py
@@ -186,10 +186,10 @@ class PlexLibrarySectionSensor(SensorEntity):
libtype=primary_libtype, includeCollections=False
)
for libtype in LIBRARY_ATTRIBUTE_TYPES.get(self.library_type, []):
- self._attr_extra_state_attributes[
- f"{libtype}s"
- ] = self.library_section.totalViewSize(
- libtype=libtype, includeCollections=False
+ self._attr_extra_state_attributes[f"{libtype}s"] = (
+ self.library_section.totalViewSize(
+ libtype=libtype, includeCollections=False
+ )
)
recent_libtype = LIBRARY_RECENT_LIBTYPE.get(
diff --git a/homeassistant/components/plex/server.py b/homeassistant/components/plex/server.py
index bd2aa7063dd..9e2bf63ce55 100644
--- a/homeassistant/components/plex/server.py
+++ b/homeassistant/components/plex/server.py
@@ -482,9 +482,9 @@ class PlexServer:
continue
process_device("session", player)
- available_clients[player.machineIdentifier][
- "session"
- ] = self.active_sessions[unique_id]
+ available_clients[player.machineIdentifier]["session"] = (
+ self.active_sessions[unique_id]
+ )
for device in devices:
process_device("PMS", device)
diff --git a/homeassistant/components/progettihwsw/config_flow.py b/homeassistant/components/progettihwsw/config_flow.py
index 91fe41cda52..5a5d0de1a80 100644
--- a/homeassistant/components/progettihwsw/config_flow.py
+++ b/homeassistant/components/progettihwsw/config_flow.py
@@ -51,13 +51,13 @@ class ProgettiHWSWConfigFlow(ConfigFlow, domain=DOMAIN):
relay_modes_schema = {}
for i in range(1, int(self.s1_in["relay_count"]) + 1):
- relay_modes_schema[
- vol.Required(f"relay_{str(i)}", default="bistable")
- ] = vol.In(
- {
- "bistable": "Bistable (ON/OFF Mode)",
- "monostable": "Monostable (Timer Mode)",
- }
+ relay_modes_schema[vol.Required(f"relay_{str(i)}", default="bistable")] = (
+ vol.In(
+ {
+ "bistable": "Bistable (ON/OFF Mode)",
+ "monostable": "Monostable (Timer Mode)",
+ }
+ )
)
return self.async_show_form(
diff --git a/homeassistant/components/proximity/coordinator.py b/homeassistant/components/proximity/coordinator.py
index 829e9aaf4a1..ea33c1f8121 100644
--- a/homeassistant/components/proximity/coordinator.py
+++ b/homeassistant/components/proximity/coordinator.py
@@ -294,15 +294,15 @@ class ProximityDataUpdateCoordinator(DataUpdateCoordinator[ProximityData]):
old_lat = None
old_lon = None
- entities_data[state_change_data.entity_id][
- ATTR_DIR_OF_TRAVEL
- ] = self._calc_direction_of_travel(
- zone_state,
- new_state,
- old_lat,
- old_lon,
- new_state.attributes.get(ATTR_LATITUDE),
- new_state.attributes.get(ATTR_LONGITUDE),
+ entities_data[state_change_data.entity_id][ATTR_DIR_OF_TRAVEL] = (
+ self._calc_direction_of_travel(
+ zone_state,
+ new_state,
+ old_lat,
+ old_lon,
+ new_state.attributes.get(ATTR_LATITUDE),
+ new_state.attributes.get(ATTR_LONGITUDE),
+ )
)
# takeover data for legacy proximity entity
@@ -337,9 +337,9 @@ class ProximityDataUpdateCoordinator(DataUpdateCoordinator[ProximityData]):
if cast(int, nearest_distance_to) == int(distance_to):
_LOGGER.debug("set equally close entity_data: %s", entity_data)
- proximity_data[
- ATTR_NEAREST
- ] = f"{proximity_data[ATTR_NEAREST]}, {str(entity_data[ATTR_NAME])}"
+ proximity_data[ATTR_NEAREST] = (
+ f"{proximity_data[ATTR_NEAREST]}, {str(entity_data[ATTR_NAME])}"
+ )
return ProximityData(proximity_data, entities_data)
diff --git a/homeassistant/components/qingping/__init__.py b/homeassistant/components/qingping/__init__.py
index 48cae5c48e6..ac91f314a28 100644
--- a/homeassistant/components/qingping/__init__.py
+++ b/homeassistant/components/qingping/__init__.py
@@ -26,14 +26,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
address = entry.unique_id
assert address is not None
data = QingpingBluetoothDeviceData()
- coordinator = hass.data.setdefault(DOMAIN, {})[
- entry.entry_id
- ] = PassiveBluetoothProcessorCoordinator(
- hass,
- _LOGGER,
- address=address,
- mode=BluetoothScanningMode.PASSIVE,
- update_method=data.update,
+ coordinator = hass.data.setdefault(DOMAIN, {})[entry.entry_id] = (
+ PassiveBluetoothProcessorCoordinator(
+ hass,
+ _LOGGER,
+ address=address,
+ mode=BluetoothScanningMode.PASSIVE,
+ update_method=data.update,
+ )
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(
diff --git a/homeassistant/components/radarr/sensor.py b/homeassistant/components/radarr/sensor.py
index 0435474e423..e6700fb3637 100644
--- a/homeassistant/components/radarr/sensor.py
+++ b/homeassistant/components/radarr/sensor.py
@@ -61,10 +61,13 @@ class RadarrSensorEntityDescription(
):
"""Class to describe a Radarr sensor."""
- description_fn: Callable[
- [RadarrSensorEntityDescription[T], RootFolder],
- tuple[RadarrSensorEntityDescription[T], str] | None,
- ] | None = None
+ description_fn: (
+ Callable[
+ [RadarrSensorEntityDescription[T], RootFolder],
+ tuple[RadarrSensorEntityDescription[T], str] | None,
+ ]
+ | None
+ ) = None
SENSOR_TYPES: dict[str, RadarrSensorEntityDescription[Any]] = {
diff --git a/homeassistant/components/rapt_ble/__init__.py b/homeassistant/components/rapt_ble/__init__.py
index f5587ba5770..4fd4c32a4cc 100644
--- a/homeassistant/components/rapt_ble/__init__.py
+++ b/homeassistant/components/rapt_ble/__init__.py
@@ -26,14 +26,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
address = entry.unique_id
assert address is not None
data = RAPTPillBluetoothDeviceData()
- coordinator = hass.data.setdefault(DOMAIN, {})[
- entry.entry_id
- ] = PassiveBluetoothProcessorCoordinator(
- hass,
- _LOGGER,
- address=address,
- mode=BluetoothScanningMode.ACTIVE,
- update_method=data.update,
+ coordinator = hass.data.setdefault(DOMAIN, {})[entry.entry_id] = (
+ PassiveBluetoothProcessorCoordinator(
+ hass,
+ _LOGGER,
+ address=address,
+ mode=BluetoothScanningMode.ACTIVE,
+ update_method=data.update,
+ )
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(
diff --git a/homeassistant/components/recollect_waste/sensor.py b/homeassistant/components/recollect_waste/sensor.py
index 1ae3c296885..36658fb5008 100644
--- a/homeassistant/components/recollect_waste/sensor.py
+++ b/homeassistant/components/recollect_waste/sensor.py
@@ -89,9 +89,9 @@ class ReCollectWasteSensor(ReCollectWasteEntity, SensorEntity):
self._attr_native_value = None
else:
self._attr_extra_state_attributes[ATTR_AREA_NAME] = event.area_name
- self._attr_extra_state_attributes[
- ATTR_PICKUP_TYPES
- ] = async_get_pickup_type_names(self._entry, event.pickup_types)
+ self._attr_extra_state_attributes[ATTR_PICKUP_TYPES] = (
+ async_get_pickup_type_names(self._entry, event.pickup_types)
+ )
self._attr_native_value = event.date
super()._handle_coordinator_update()
diff --git a/homeassistant/components/recorder/migration.py b/homeassistant/components/recorder/migration.py
index 6021c7b5f5b..60373a053c9 100644
--- a/homeassistant/components/recorder/migration.py
+++ b/homeassistant/components/recorder/migration.py
@@ -878,9 +878,10 @@ 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), 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.
@@ -1132,9 +1133,10 @@ def _correct_table_character_set_and_collation(
"computers. Please be patient!",
table,
)
- with contextlib.suppress(SQLAlchemyError), 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
@@ -1579,9 +1581,9 @@ def migrate_event_type_ids(instance: Recorder) -> bool:
assert (
db_event_type.event_type is not None
), "event_type should never be None"
- event_type_to_id[
- db_event_type.event_type
- ] = db_event_type.event_type_id
+ event_type_to_id[db_event_type.event_type] = (
+ db_event_type.event_type_id
+ )
event_type_manager.clear_non_existent(db_event_type.event_type)
session.execute(
@@ -1652,9 +1654,9 @@ def migrate_entity_ids(instance: Recorder) -> bool:
assert (
db_states_metadata.entity_id is not None
), "entity_id should never be None"
- entity_id_to_metadata_id[
- db_states_metadata.entity_id
- ] = db_states_metadata.metadata_id
+ entity_id_to_metadata_id[db_states_metadata.entity_id] = (
+ db_states_metadata.metadata_id
+ )
session.execute(
update(States),
diff --git a/homeassistant/components/recorder/models/time.py b/homeassistant/components/recorder/models/time.py
index af0df4e806d..6295060c8d3 100644
--- a/homeassistant/components/recorder/models/time.py
+++ b/homeassistant/components/recorder/models/time.py
@@ -16,13 +16,11 @@ EMPTY_JSON_OBJECT = "{}"
@overload
-def process_timestamp(ts: None) -> None:
- ...
+def process_timestamp(ts: None) -> None: ...
@overload
-def process_timestamp(ts: datetime) -> datetime:
- ...
+def process_timestamp(ts: datetime) -> datetime: ...
def process_timestamp(ts: datetime | None) -> datetime | None:
@@ -36,13 +34,11 @@ def process_timestamp(ts: datetime | None) -> datetime | None:
@overload
-def process_timestamp_to_utc_isoformat(ts: None) -> None:
- ...
+def process_timestamp_to_utc_isoformat(ts: None) -> None: ...
@overload
-def process_timestamp_to_utc_isoformat(ts: datetime) -> str:
- ...
+def process_timestamp_to_utc_isoformat(ts: datetime) -> str: ...
def process_timestamp_to_utc_isoformat(ts: datetime | None) -> str | None:
diff --git a/homeassistant/components/rejseplanen/sensor.py b/homeassistant/components/rejseplanen/sensor.py
index 6486ba329f4..d95b9e1b271 100644
--- a/homeassistant/components/rejseplanen/sensor.py
+++ b/homeassistant/components/rejseplanen/sensor.py
@@ -239,9 +239,9 @@ class PublicTransportData:
}
if real_time_date is not None and real_time_time is not None:
- departure_data[
- ATTR_REAL_TIME_AT
- ] = f"{real_time_date} {real_time_time}"
+ departure_data[ATTR_REAL_TIME_AT] = (
+ f"{real_time_date} {real_time_time}"
+ )
if item.get("rtTrack") is not None:
departure_data[ATTR_TRACK] = item.get("rtTrack")
diff --git a/homeassistant/components/reolink/config_flow.py b/homeassistant/components/reolink/config_flow.py
index 3257d183de8..b62a7b7f709 100644
--- a/homeassistant/components/reolink/config_flow.py
+++ b/homeassistant/components/reolink/config_flow.py
@@ -193,9 +193,9 @@ class ReolinkFlowHandler(ConfigFlow, domain=DOMAIN):
errors[CONF_HOST] = "api_error"
except ReolinkWebhookException as err:
placeholders["error"] = str(err)
- placeholders[
- "more_info"
- ] = "https://www.home-assistant.io/more-info/no-url-available/#configuring-the-instance-url"
+ placeholders["more_info"] = (
+ "https://www.home-assistant.io/more-info/no-url-available/#configuring-the-instance-url"
+ )
errors["base"] = "webhook_exception"
except (ReolinkError, ReolinkException) as err:
placeholders["error"] = str(err)
diff --git a/homeassistant/components/romy/entity.py b/homeassistant/components/romy/entity.py
index 3fa6eefbe02..ee4e209f158 100644
--- a/homeassistant/components/romy/entity.py
+++ b/homeassistant/components/romy/entity.py
@@ -1,6 +1,5 @@
"""Base entity for ROMY."""
-
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity
diff --git a/homeassistant/components/ruuvitag_ble/__init__.py b/homeassistant/components/ruuvitag_ble/__init__.py
index 031bed232bd..86a0b2cd40a 100644
--- a/homeassistant/components/ruuvitag_ble/__init__.py
+++ b/homeassistant/components/ruuvitag_ble/__init__.py
@@ -26,14 +26,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
address = entry.unique_id
assert address is not None
data = RuuvitagBluetoothDeviceData()
- coordinator = hass.data.setdefault(DOMAIN, {})[
- entry.entry_id
- ] = PassiveBluetoothProcessorCoordinator(
- hass,
- _LOGGER,
- address=address,
- mode=BluetoothScanningMode.ACTIVE,
- update_method=data.update,
+ coordinator = hass.data.setdefault(DOMAIN, {})[entry.entry_id] = (
+ PassiveBluetoothProcessorCoordinator(
+ hass,
+ _LOGGER,
+ address=address,
+ mode=BluetoothScanningMode.ACTIVE,
+ update_method=data.update,
+ )
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(
diff --git a/homeassistant/components/sabnzbd/config_flow.py b/homeassistant/components/sabnzbd/config_flow.py
index 12138a8a085..944c3f2936c 100644
--- a/homeassistant/components/sabnzbd/config_flow.py
+++ b/homeassistant/components/sabnzbd/config_flow.py
@@ -68,7 +68,7 @@ class SABnzbdConfigFlow(ConfigFlow, domain=DOMAIN):
async def async_step_import(self, import_data):
"""Import sabnzbd config from configuration.yaml."""
protocol = "https://" if import_data[CONF_SSL] else "http://"
- import_data[
- CONF_URL
- ] = f"{protocol}{import_data[CONF_HOST]}:{import_data[CONF_PORT]}"
+ import_data[CONF_URL] = (
+ f"{protocol}{import_data[CONF_HOST]}:{import_data[CONF_PORT]}"
+ )
return await self.async_step_user(import_data)
diff --git a/homeassistant/components/samsungtv/config_flow.py b/homeassistant/components/samsungtv/config_flow.py
index fbaab44ddec..4845fb4fb74 100644
--- a/homeassistant/components/samsungtv/config_flow.py
+++ b/homeassistant/components/samsungtv/config_flow.py
@@ -184,13 +184,13 @@ class SamsungTVConfigFlow(ConfigFlow, domain=DOMAIN):
if self._model:
updates[CONF_MODEL] = self._model
if self._ssdp_rendering_control_location:
- updates[
- CONF_SSDP_RENDERING_CONTROL_LOCATION
- ] = self._ssdp_rendering_control_location
+ updates[CONF_SSDP_RENDERING_CONTROL_LOCATION] = (
+ self._ssdp_rendering_control_location
+ )
if self._ssdp_main_tv_agent_location:
- updates[
- CONF_SSDP_MAIN_TV_AGENT_LOCATION
- ] = self._ssdp_main_tv_agent_location
+ updates[CONF_SSDP_MAIN_TV_AGENT_LOCATION] = (
+ self._ssdp_main_tv_agent_location
+ )
self._abort_if_unique_id_configured(updates=updates, reload_on_update=False)
async def _async_create_bridge(self) -> None:
@@ -388,13 +388,13 @@ class SamsungTVConfigFlow(ConfigFlow, domain=DOMAIN):
or update_model
):
if update_ssdp_rendering_control_location:
- data[
- CONF_SSDP_RENDERING_CONTROL_LOCATION
- ] = self._ssdp_rendering_control_location
+ data[CONF_SSDP_RENDERING_CONTROL_LOCATION] = (
+ self._ssdp_rendering_control_location
+ )
if update_ssdp_main_tv_agent_location:
- data[
- CONF_SSDP_MAIN_TV_AGENT_LOCATION
- ] = self._ssdp_main_tv_agent_location
+ data[CONF_SSDP_MAIN_TV_AGENT_LOCATION] = (
+ self._ssdp_main_tv_agent_location
+ )
if update_mac:
data[CONF_MAC] = self._mac
if update_model:
diff --git a/homeassistant/components/sensirion_ble/__init__.py b/homeassistant/components/sensirion_ble/__init__.py
index 762086d102d..5ea5593004e 100644
--- a/homeassistant/components/sensirion_ble/__init__.py
+++ b/homeassistant/components/sensirion_ble/__init__.py
@@ -26,14 +26,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
address = entry.unique_id
assert address is not None
data = SensirionBluetoothDeviceData()
- coordinator = hass.data.setdefault(DOMAIN, {})[
- entry.entry_id
- ] = PassiveBluetoothProcessorCoordinator(
- hass,
- _LOGGER,
- address=address,
- mode=BluetoothScanningMode.ACTIVE,
- update_method=data.update,
+ coordinator = hass.data.setdefault(DOMAIN, {})[entry.entry_id] = (
+ PassiveBluetoothProcessorCoordinator(
+ hass,
+ _LOGGER,
+ address=address,
+ mode=BluetoothScanningMode.ACTIVE,
+ update_method=data.update,
+ )
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(
diff --git a/homeassistant/components/sensor/__init__.py b/homeassistant/components/sensor/__init__.py
index 0b2eb911cf2..ce32be40b30 100644
--- a/homeassistant/components/sensor/__init__.py
+++ b/homeassistant/components/sensor/__init__.py
@@ -872,9 +872,9 @@ class SensorExtraStoredData(ExtraStoredData):
def as_dict(self) -> dict[str, Any]:
"""Return a dict representation of the sensor data."""
- native_value: StateType | date | datetime | Decimal | dict[
- str, str
- ] = self.native_value
+ native_value: StateType | date | datetime | Decimal | dict[str, str] = (
+ self.native_value
+ )
if isinstance(native_value, (date, datetime)):
native_value = {
"__type": str(type(native_value)),
diff --git a/homeassistant/components/sensorpro/__init__.py b/homeassistant/components/sensorpro/__init__.py
index a4b5ae351a1..be15b65e0f9 100644
--- a/homeassistant/components/sensorpro/__init__.py
+++ b/homeassistant/components/sensorpro/__init__.py
@@ -26,14 +26,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
address = entry.unique_id
assert address is not None
data = SensorProBluetoothDeviceData()
- coordinator = hass.data.setdefault(DOMAIN, {})[
- entry.entry_id
- ] = PassiveBluetoothProcessorCoordinator(
- hass,
- _LOGGER,
- address=address,
- mode=BluetoothScanningMode.PASSIVE,
- update_method=data.update,
+ coordinator = hass.data.setdefault(DOMAIN, {})[entry.entry_id] = (
+ PassiveBluetoothProcessorCoordinator(
+ hass,
+ _LOGGER,
+ address=address,
+ mode=BluetoothScanningMode.PASSIVE,
+ update_method=data.update,
+ )
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(
diff --git a/homeassistant/components/sensorpush/__init__.py b/homeassistant/components/sensorpush/__init__.py
index 177b51d135b..1a479caacf2 100644
--- a/homeassistant/components/sensorpush/__init__.py
+++ b/homeassistant/components/sensorpush/__init__.py
@@ -26,14 +26,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
address = entry.unique_id
assert address is not None
data = SensorPushBluetoothDeviceData()
- coordinator = hass.data.setdefault(DOMAIN, {})[
- entry.entry_id
- ] = PassiveBluetoothProcessorCoordinator(
- hass,
- _LOGGER,
- address=address,
- mode=BluetoothScanningMode.PASSIVE,
- update_method=data.update,
+ coordinator = hass.data.setdefault(DOMAIN, {})[entry.entry_id] = (
+ PassiveBluetoothProcessorCoordinator(
+ hass,
+ _LOGGER,
+ address=address,
+ mode=BluetoothScanningMode.PASSIVE,
+ update_method=data.update,
+ )
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(
diff --git a/homeassistant/components/shelly/entity.py b/homeassistant/components/shelly/entity.py
index edcee5c2dda..accca5f1a64 100644
--- a/homeassistant/components/shelly/entity.py
+++ b/homeassistant/components/shelly/entity.py
@@ -629,9 +629,9 @@ class ShellySleepingRpcAttributeEntity(ShellyRpcAttributeEntity):
self._attr_device_info = DeviceInfo(
connections={(CONNECTION_NETWORK_MAC, coordinator.mac)}
)
- self._attr_unique_id = (
- self._attr_unique_id
- ) = f"{coordinator.mac}-{key}-{attribute}"
+ self._attr_unique_id = self._attr_unique_id = (
+ f"{coordinator.mac}-{key}-{attribute}"
+ )
self._last_value = None
if coordinator.device.initialized:
diff --git a/homeassistant/components/slimproto/media_player.py b/homeassistant/components/slimproto/media_player.py
index f3cbcef2a61..42c50d21e75 100644
--- a/homeassistant/components/slimproto/media_player.py
+++ b/homeassistant/components/slimproto/media_player.py
@@ -107,9 +107,9 @@ class SlimProtoPlayer(MediaPlayerEntity):
)
# PiCore + SqueezeESP32 player has web interface
if "-pCP" in self.player.firmware or self.player.device_model == "SqueezeESP32":
- self._attr_device_info[
- "configuration_url"
- ] = f"http://{self.player.device_address}"
+ self._attr_device_info["configuration_url"] = (
+ f"http://{self.player.device_address}"
+ )
self.update_attributes()
async def async_added_to_hass(self) -> None:
diff --git a/homeassistant/components/smtp/notify.py b/homeassistant/components/smtp/notify.py
index 68be378f367..bac18576f06 100644
--- a/homeassistant/components/smtp/notify.py
+++ b/homeassistant/components/smtp/notify.py
@@ -287,9 +287,9 @@ def _attach_file(hass, atch_name, content_id=""):
atch_name,
)
attachment = MIMEApplication(file_bytes, Name=os.path.basename(atch_name))
- attachment[
- "Content-Disposition"
- ] = f'attachment; filename="{os.path.basename(atch_name)}"'
+ attachment["Content-Disposition"] = (
+ f'attachment; filename="{os.path.basename(atch_name)}"'
+ )
else:
if content_id:
attachment.add_header("Content-ID", f"<{content_id}>")
diff --git a/homeassistant/components/sonarr/config_flow.py b/homeassistant/components/sonarr/config_flow.py
index 7d1db21cd53..9e84d040ad1 100644
--- a/homeassistant/components/sonarr/config_flow.py
+++ b/homeassistant/components/sonarr/config_flow.py
@@ -150,9 +150,9 @@ class SonarrConfigFlow(ConfigFlow, domain=DOMAIN):
}
if self.show_advanced_options:
- data_schema[
- vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL)
- ] = bool
+ data_schema[vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL)] = (
+ bool
+ )
return data_schema
diff --git a/homeassistant/components/sonarr/sensor.py b/homeassistant/components/sonarr/sensor.py
index 6e08d6b4886..bdb647de39c 100644
--- a/homeassistant/components/sonarr/sensor.py
+++ b/homeassistant/components/sonarr/sensor.py
@@ -54,9 +54,9 @@ def get_disk_space_attr(disks: list[Diskspace]) -> dict[str, str]:
free = disk.freeSpace / 1024**3
total = disk.totalSpace / 1024**3
usage = free / total * 100
- attrs[
- disk.path
- ] = f"{free:.2f}/{total:.2f}{UnitOfInformation.GIGABYTES} ({usage:.2f}%)"
+ attrs[disk.path] = (
+ f"{free:.2f}/{total:.2f}{UnitOfInformation.GIGABYTES} ({usage:.2f}%)"
+ )
return attrs
diff --git a/homeassistant/components/sonos/helpers.py b/homeassistant/components/sonos/helpers.py
index b855c014e1d..2070d37b1a4 100644
--- a/homeassistant/components/sonos/helpers.py
+++ b/homeassistant/components/sonos/helpers.py
@@ -39,15 +39,13 @@ _ReturnFuncType = Callable[Concatenate[_T, _P], _R | None]
@overload
def soco_error(
errorcodes: None = ...,
-) -> Callable[[_FuncType[_T, _P, _R]], _FuncType[_T, _P, _R]]:
- ...
+) -> Callable[[_FuncType[_T, _P, _R]], _FuncType[_T, _P, _R]]: ...
@overload
def soco_error(
errorcodes: list[str],
-) -> Callable[[_FuncType[_T, _P, _R]], _ReturnFuncType[_T, _P, _R]]:
- ...
+) -> Callable[[_FuncType[_T, _P, _R]], _ReturnFuncType[_T, _P, _R]]: ...
def soco_error(
diff --git a/homeassistant/components/spotify/__init__.py b/homeassistant/components/spotify/__init__.py
index eb3c57eba21..8d5183a459d 100644
--- a/homeassistant/components/spotify/__init__.py
+++ b/homeassistant/components/spotify/__init__.py
@@ -89,14 +89,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
return devices.get("devices", [])
- device_coordinator: DataUpdateCoordinator[
- list[dict[str, Any]]
- ] = DataUpdateCoordinator(
- hass,
- LOGGER,
- name=f"{entry.title} Devices",
- update_interval=timedelta(minutes=5),
- update_method=_update_devices,
+ device_coordinator: DataUpdateCoordinator[list[dict[str, Any]]] = (
+ DataUpdateCoordinator(
+ hass,
+ LOGGER,
+ name=f"{entry.title} Devices",
+ update_interval=timedelta(minutes=5),
+ update_method=_update_devices,
+ )
)
await device_coordinator.async_config_entry_first_refresh()
diff --git a/homeassistant/components/squeezebox/media_player.py b/homeassistant/components/squeezebox/media_player.py
index f0b474064c2..007d880a263 100644
--- a/homeassistant/components/squeezebox/media_player.py
+++ b/homeassistant/components/squeezebox/media_player.py
@@ -168,9 +168,9 @@ async def async_setup_entry(
for player in players:
hass.async_create_task(_discovered_player(player))
- hass.data[DOMAIN][config_entry.entry_id][
- PLAYER_DISCOVERY_UNSUB
- ] = async_call_later(hass, DISCOVERY_INTERVAL, _discovery)
+ hass.data[DOMAIN][config_entry.entry_id][PLAYER_DISCOVERY_UNSUB] = (
+ async_call_later(hass, DISCOVERY_INTERVAL, _discovery)
+ )
_LOGGER.debug("Adding player discovery job for LMS server: %s", host)
config_entry.async_create_background_task(
diff --git a/homeassistant/components/ssdp/__init__.py b/homeassistant/components/ssdp/__init__.py
index 75ffac772f6..b34105106e0 100644
--- a/homeassistant/components/ssdp/__init__.py
+++ b/homeassistant/components/ssdp/__init__.py
@@ -256,9 +256,9 @@ class IntegrationMatchers:
def __init__(self) -> None:
"""Init optimized integration matching."""
- self._match_by_key: dict[
- str, dict[str, list[tuple[str, dict[str, str]]]]
- ] | None = None
+ self._match_by_key: (
+ dict[str, dict[str, list[tuple[str, dict[str, str]]]]] | None
+ ) = None
@core_callback
def async_setup(
diff --git a/homeassistant/components/statistics/sensor.py b/homeassistant/components/statistics/sensor.py
index a39137e9d81..d995f529b7d 100644
--- a/homeassistant/components/statistics/sensor.py
+++ b/homeassistant/components/statistics/sensor.py
@@ -320,9 +320,9 @@ class StatisticsSensor(SensorEntity):
self.ages: deque[datetime] = deque(maxlen=self._samples_max_buffer_size)
self.attributes: dict[str, StateType] = {}
- self._state_characteristic_fn: Callable[
- [], StateType | datetime
- ] = self._callable_characteristic_fn(self._state_characteristic)
+ self._state_characteristic_fn: Callable[[], StateType | datetime] = (
+ self._callable_characteristic_fn(self._state_characteristic)
+ )
self._update_listener: CALLBACK_TYPE | None = None
diff --git a/homeassistant/components/stream/recorder.py b/homeassistant/components/stream/recorder.py
index 3af581d0e1b..6dfc09891b7 100644
--- a/homeassistant/components/stream/recorder.py
+++ b/homeassistant/components/stream/recorder.py
@@ -155,9 +155,10 @@ class RecorderOutput(StreamOutput):
def write_transform_matrix_and_rename(video_path: str) -> None:
"""Update the transform matrix and write to the desired filename."""
- with open(video_path + ".tmp", mode="rb") as in_file, open(
- video_path, mode="wb"
- ) as out_file:
+ with (
+ open(video_path + ".tmp", mode="rb") as in_file,
+ open(video_path, mode="wb") as out_file,
+ ):
init = transform_init(
read_init(in_file), self.dynamic_stream_settings.orientation
)
diff --git a/homeassistant/components/stream/worker.py b/homeassistant/components/stream/worker.py
index e86179a91eb..87d9118f3a5 100644
--- a/homeassistant/components/stream/worker.py
+++ b/homeassistant/components/stream/worker.py
@@ -68,9 +68,9 @@ class StreamState:
"""Initialize StreamState."""
self._stream_id: int = 0
self.hass = hass
- self._outputs_callback: Callable[
- [], Mapping[str, StreamOutput]
- ] = outputs_callback
+ self._outputs_callback: Callable[[], Mapping[str, StreamOutput]] = (
+ outputs_callback
+ )
# sequence gets incremented before the first segment so the first segment
# has a sequence number of 0.
self._sequence = -1
diff --git a/homeassistant/components/suez_water/sensor.py b/homeassistant/components/suez_water/sensor.py
index 5f89c28808d..7060339250c 100644
--- a/homeassistant/components/suez_water/sensor.py
+++ b/homeassistant/components/suez_water/sensor.py
@@ -124,28 +124,28 @@ class SuezSensor(SensorEntity):
self._attr_extra_state_attributes["this_month_consumption"] = {}
for item in self.client.attributes["thisMonthConsumption"]:
- self._attr_extra_state_attributes["this_month_consumption"][
- item
- ] = self.client.attributes["thisMonthConsumption"][item]
+ self._attr_extra_state_attributes["this_month_consumption"][item] = (
+ self.client.attributes["thisMonthConsumption"][item]
+ )
self._attr_extra_state_attributes["previous_month_consumption"] = {}
for item in self.client.attributes["previousMonthConsumption"]:
self._attr_extra_state_attributes["previous_month_consumption"][
item
] = self.client.attributes["previousMonthConsumption"][item]
- self._attr_extra_state_attributes[
- "highest_monthly_consumption"
- ] = self.client.attributes["highestMonthlyConsumption"]
- self._attr_extra_state_attributes[
- "last_year_overall"
- ] = self.client.attributes["lastYearOverAll"]
- self._attr_extra_state_attributes[
- "this_year_overall"
- ] = self.client.attributes["thisYearOverAll"]
+ self._attr_extra_state_attributes["highest_monthly_consumption"] = (
+ self.client.attributes["highestMonthlyConsumption"]
+ )
+ self._attr_extra_state_attributes["last_year_overall"] = (
+ self.client.attributes["lastYearOverAll"]
+ )
+ self._attr_extra_state_attributes["this_year_overall"] = (
+ self.client.attributes["thisYearOverAll"]
+ )
self._attr_extra_state_attributes["history"] = {}
for item in self.client.attributes["history"]:
- self._attr_extra_state_attributes["history"][
- item
- ] = self.client.attributes["history"][item]
+ self._attr_extra_state_attributes["history"][item] = (
+ self.client.attributes["history"][item]
+ )
except PySuezError:
self._attr_available = False
diff --git a/homeassistant/components/switcher_kis/__init__.py b/homeassistant/components/switcher_kis/__init__.py
index 14aeea09626..b3315bac2ca 100644
--- a/homeassistant/components/switcher_kis/__init__.py
+++ b/homeassistant/components/switcher_kis/__init__.py
@@ -98,9 +98,9 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
device.device_type.hex_rep,
)
- coordinator = hass.data[DOMAIN][DATA_DEVICE][
- device.device_id
- ] = SwitcherDataUpdateCoordinator(hass, entry, device)
+ coordinator = hass.data[DOMAIN][DATA_DEVICE][device.device_id] = (
+ SwitcherDataUpdateCoordinator(hass, entry, device)
+ )
coordinator.async_setup()
# Must be ready before dispatcher is called
diff --git a/homeassistant/components/system_bridge/media_player.py b/homeassistant/components/system_bridge/media_player.py
index d467110e06d..aeff3b22fb2 100644
--- a/homeassistant/components/system_bridge/media_player.py
+++ b/homeassistant/components/system_bridge/media_player.py
@@ -53,13 +53,13 @@ MEDIA_SET_REPEAT_MAP: Final[dict[RepeatMode, int]] = {
RepeatMode.ALL: 2,
}
-MEDIA_PLAYER_DESCRIPTION: Final[
- MediaPlayerEntityDescription
-] = MediaPlayerEntityDescription(
- key="media",
- translation_key="media",
- icon="mdi:volume-high",
- device_class=MediaPlayerDeviceClass.RECEIVER,
+MEDIA_PLAYER_DESCRIPTION: Final[MediaPlayerEntityDescription] = (
+ MediaPlayerEntityDescription(
+ key="media",
+ translation_key="media",
+ icon="mdi:volume-high",
+ device_class=MediaPlayerDeviceClass.RECEIVER,
+ )
)
diff --git a/homeassistant/components/systemmonitor/coordinator.py b/homeassistant/components/systemmonitor/coordinator.py
index 6ce2836fcde..d12eddbb14a 100644
--- a/homeassistant/components/systemmonitor/coordinator.py
+++ b/homeassistant/components/systemmonitor/coordinator.py
@@ -87,9 +87,9 @@ class SystemMonitorCoordinator(TimestampDataUpdateCoordinator[SensorData]):
self.boot_time: datetime | None = None
self._initial_update: bool = True
- self.update_subscribers: dict[
- tuple[str, str], set[str]
- ] = self.set_subscribers_tuples(arguments)
+ self.update_subscribers: dict[tuple[str, str], set[str]] = (
+ self.set_subscribers_tuples(arguments)
+ )
def set_subscribers_tuples(
self, arguments: list[str]
diff --git a/homeassistant/components/tado/climate.py b/homeassistant/components/tado/climate.py
index 2bd1bc31bb0..621f5a1ad61 100644
--- a/homeassistant/components/tado/climate.py
+++ b/homeassistant/components/tado/climate.py
@@ -485,12 +485,12 @@ class TadoClimate(TadoZoneEntity, ClimateEntity):
def extra_state_attributes(self) -> Mapping[str, Any] | None:
"""Return temperature offset."""
state_attr: dict[str, Any] = self._tado_zone_temp_offset
- state_attr[
- HA_TERMINATION_TYPE
- ] = self._tado_zone_data.default_overlay_termination_type
- state_attr[
- HA_TERMINATION_DURATION
- ] = self._tado_zone_data.default_overlay_termination_duration
+ state_attr[HA_TERMINATION_TYPE] = (
+ self._tado_zone_data.default_overlay_termination_type
+ )
+ state_attr[HA_TERMINATION_DURATION] = (
+ self._tado_zone_data.default_overlay_termination_duration
+ )
return state_attr
def set_swing_mode(self, swing_mode: str) -> None:
diff --git a/homeassistant/components/tasmota/binary_sensor.py b/homeassistant/components/tasmota/binary_sensor.py
index 450cd833fcf..071cce81880 100644
--- a/homeassistant/components/tasmota/binary_sensor.py
+++ b/homeassistant/components/tasmota/binary_sensor.py
@@ -43,12 +43,12 @@ async def async_setup_entry(
]
)
- hass.data[
- DATA_REMOVE_DISCOVER_COMPONENT.format(binary_sensor.DOMAIN)
- ] = async_dispatcher_connect(
- hass,
- TASMOTA_DISCOVERY_ENTITY_NEW.format(binary_sensor.DOMAIN),
- async_discover,
+ hass.data[DATA_REMOVE_DISCOVER_COMPONENT.format(binary_sensor.DOMAIN)] = (
+ async_dispatcher_connect(
+ hass,
+ TASMOTA_DISCOVERY_ENTITY_NEW.format(binary_sensor.DOMAIN),
+ async_discover,
+ )
)
diff --git a/homeassistant/components/tasmota/cover.py b/homeassistant/components/tasmota/cover.py
index 48ac868d64b..4ab9464e9f9 100644
--- a/homeassistant/components/tasmota/cover.py
+++ b/homeassistant/components/tasmota/cover.py
@@ -41,12 +41,12 @@ async def async_setup_entry(
[TasmotaCover(tasmota_entity=tasmota_entity, discovery_hash=discovery_hash)]
)
- hass.data[
- DATA_REMOVE_DISCOVER_COMPONENT.format(COVER_DOMAIN)
- ] = async_dispatcher_connect(
- hass,
- TASMOTA_DISCOVERY_ENTITY_NEW.format(COVER_DOMAIN),
- async_discover,
+ hass.data[DATA_REMOVE_DISCOVER_COMPONENT.format(COVER_DOMAIN)] = (
+ async_dispatcher_connect(
+ hass,
+ TASMOTA_DISCOVERY_ENTITY_NEW.format(COVER_DOMAIN),
+ async_discover,
+ )
)
diff --git a/homeassistant/components/tasmota/device_automation.py b/homeassistant/components/tasmota/device_automation.py
index 2fdcad45c81..ef05585dd87 100644
--- a/homeassistant/components/tasmota/device_automation.py
+++ b/homeassistant/components/tasmota/device_automation.py
@@ -43,12 +43,12 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> N
hass, tasmota_automation, config_entry, discovery_hash
)
- hass.data[
- DATA_REMOVE_DISCOVER_COMPONENT.format("device_automation")
- ] = async_dispatcher_connect(
- hass,
- TASMOTA_DISCOVERY_ENTITY_NEW.format("device_automation"),
- async_discover,
+ hass.data[DATA_REMOVE_DISCOVER_COMPONENT.format("device_automation")] = (
+ async_dispatcher_connect(
+ hass,
+ TASMOTA_DISCOVERY_ENTITY_NEW.format("device_automation"),
+ async_discover,
+ )
)
hass.data[DATA_UNSUB].append(
hass.bus.async_listen(
diff --git a/homeassistant/components/tasmota/fan.py b/homeassistant/components/tasmota/fan.py
index 22502c474b1..cdb0fb8d2f6 100644
--- a/homeassistant/components/tasmota/fan.py
+++ b/homeassistant/components/tasmota/fan.py
@@ -49,12 +49,12 @@ async def async_setup_entry(
[TasmotaFan(tasmota_entity=tasmota_entity, discovery_hash=discovery_hash)]
)
- hass.data[
- DATA_REMOVE_DISCOVER_COMPONENT.format(FAN_DOMAIN)
- ] = async_dispatcher_connect(
- hass,
- TASMOTA_DISCOVERY_ENTITY_NEW.format(FAN_DOMAIN),
- async_discover,
+ hass.data[DATA_REMOVE_DISCOVER_COMPONENT.format(FAN_DOMAIN)] = (
+ async_dispatcher_connect(
+ hass,
+ TASMOTA_DISCOVERY_ENTITY_NEW.format(FAN_DOMAIN),
+ async_discover,
+ )
)
diff --git a/homeassistant/components/tasmota/light.py b/homeassistant/components/tasmota/light.py
index 76859311c6d..5effc9c4997 100644
--- a/homeassistant/components/tasmota/light.py
+++ b/homeassistant/components/tasmota/light.py
@@ -57,12 +57,12 @@ async def async_setup_entry(
[TasmotaLight(tasmota_entity=tasmota_entity, discovery_hash=discovery_hash)]
)
- hass.data[
- DATA_REMOVE_DISCOVER_COMPONENT.format(light.DOMAIN)
- ] = async_dispatcher_connect(
- hass,
- TASMOTA_DISCOVERY_ENTITY_NEW.format(light.DOMAIN),
- async_discover,
+ hass.data[DATA_REMOVE_DISCOVER_COMPONENT.format(light.DOMAIN)] = (
+ async_dispatcher_connect(
+ hass,
+ TASMOTA_DISCOVERY_ENTITY_NEW.format(light.DOMAIN),
+ async_discover,
+ )
)
diff --git a/homeassistant/components/tasmota/sensor.py b/homeassistant/components/tasmota/sensor.py
index d919cb73cf5..546e3eb4539 100644
--- a/homeassistant/components/tasmota/sensor.py
+++ b/homeassistant/components/tasmota/sensor.py
@@ -252,12 +252,12 @@ async def async_setup_entry(
]
)
- hass.data[
- DATA_REMOVE_DISCOVER_COMPONENT.format(sensor.DOMAIN)
- ] = async_dispatcher_connect(
- hass,
- TASMOTA_DISCOVERY_ENTITY_NEW.format(sensor.DOMAIN),
- async_discover,
+ hass.data[DATA_REMOVE_DISCOVER_COMPONENT.format(sensor.DOMAIN)] = (
+ async_dispatcher_connect(
+ hass,
+ TASMOTA_DISCOVERY_ENTITY_NEW.format(sensor.DOMAIN),
+ async_discover,
+ )
)
diff --git a/homeassistant/components/tasmota/switch.py b/homeassistant/components/tasmota/switch.py
index 0a80992b1d8..44c45621e09 100644
--- a/homeassistant/components/tasmota/switch.py
+++ b/homeassistant/components/tasmota/switch.py
@@ -38,12 +38,12 @@ async def async_setup_entry(
]
)
- hass.data[
- DATA_REMOVE_DISCOVER_COMPONENT.format(switch.DOMAIN)
- ] = async_dispatcher_connect(
- hass,
- TASMOTA_DISCOVERY_ENTITY_NEW.format(switch.DOMAIN),
- async_discover,
+ hass.data[DATA_REMOVE_DISCOVER_COMPONENT.format(switch.DOMAIN)] = (
+ async_dispatcher_connect(
+ hass,
+ TASMOTA_DISCOVERY_ENTITY_NEW.format(switch.DOMAIN),
+ async_discover,
+ )
)
diff --git a/homeassistant/components/template/template_entity.py b/homeassistant/components/template/template_entity.py
index a851e547844..735fa7ddd23 100644
--- a/homeassistant/components/template/template_entity.py
+++ b/homeassistant/components/template/template_entity.py
@@ -271,15 +271,18 @@ class TemplateEntity(Entity):
self._attr_extra_state_attributes = {}
self._self_ref_update_count = 0
self._attr_unique_id = unique_id
- self._preview_callback: Callable[
- [
- str | None,
- dict[str, Any] | None,
- dict[str, bool | set[str]] | None,
- str | None,
- ],
- None,
- ] | None = None
+ self._preview_callback: (
+ Callable[
+ [
+ str | None,
+ dict[str, Any] | None,
+ dict[str, bool | set[str]] | None,
+ str | None,
+ ],
+ None,
+ ]
+ | None
+ ) = None
if config is None:
self._attribute_templates = attribute_templates
self._availability_template = availability_template
diff --git a/homeassistant/components/template/weather.py b/homeassistant/components/template/weather.py
index b572f0ecbb8..6f6861830c7 100644
--- a/homeassistant/components/template/weather.py
+++ b/homeassistant/components/template/weather.py
@@ -574,12 +574,12 @@ class TriggerWeatherEntity(TriggerEntity, WeatherEntity, RestoreEntity):
and state.state not in (STATE_UNKNOWN, STATE_UNAVAILABLE)
and (weather_data := await self.async_get_last_weather_data())
):
- self._rendered[
- CONF_APPARENT_TEMPERATURE_TEMPLATE
- ] = weather_data.last_apparent_temperature
- self._rendered[
- CONF_CLOUD_COVERAGE_TEMPLATE
- ] = weather_data.last_cloud_coverage
+ self._rendered[CONF_APPARENT_TEMPERATURE_TEMPLATE] = (
+ weather_data.last_apparent_temperature
+ )
+ self._rendered[CONF_CLOUD_COVERAGE_TEMPLATE] = (
+ weather_data.last_cloud_coverage
+ )
self._rendered[CONF_CONDITION_TEMPLATE] = state.state
self._rendered[CONF_DEW_POINT_TEMPLATE] = weather_data.last_dew_point
self._rendered[CONF_HUMIDITY_TEMPLATE] = weather_data.last_humidity
@@ -588,9 +588,9 @@ class TriggerWeatherEntity(TriggerEntity, WeatherEntity, RestoreEntity):
self._rendered[CONF_TEMPERATURE_TEMPLATE] = weather_data.last_temperature
self._rendered[CONF_VISIBILITY_TEMPLATE] = weather_data.last_visibility
self._rendered[CONF_WIND_BEARING_TEMPLATE] = weather_data.last_wind_bearing
- self._rendered[
- CONF_WIND_GUST_SPEED_TEMPLATE
- ] = weather_data.last_wind_gust_speed
+ self._rendered[CONF_WIND_GUST_SPEED_TEMPLATE] = (
+ weather_data.last_wind_gust_speed
+ )
self._rendered[CONF_WIND_SPEED_TEMPLATE] = weather_data.last_wind_speed
@property
diff --git a/homeassistant/components/thermobeacon/__init__.py b/homeassistant/components/thermobeacon/__init__.py
index 853d2b3dc65..073ff6bbdc3 100644
--- a/homeassistant/components/thermobeacon/__init__.py
+++ b/homeassistant/components/thermobeacon/__init__.py
@@ -26,14 +26,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
address = entry.unique_id
assert address is not None
data = ThermoBeaconBluetoothDeviceData()
- coordinator = hass.data.setdefault(DOMAIN, {})[
- entry.entry_id
- ] = PassiveBluetoothProcessorCoordinator(
- hass,
- _LOGGER,
- address=address,
- mode=BluetoothScanningMode.PASSIVE,
- update_method=data.update,
+ coordinator = hass.data.setdefault(DOMAIN, {})[entry.entry_id] = (
+ PassiveBluetoothProcessorCoordinator(
+ hass,
+ _LOGGER,
+ address=address,
+ mode=BluetoothScanningMode.PASSIVE,
+ update_method=data.update,
+ )
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(
diff --git a/homeassistant/components/thermopro/__init__.py b/homeassistant/components/thermopro/__init__.py
index 51bc4123870..2cd207818c5 100644
--- a/homeassistant/components/thermopro/__init__.py
+++ b/homeassistant/components/thermopro/__init__.py
@@ -26,14 +26,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
address = entry.unique_id
assert address is not None
data = ThermoProBluetoothDeviceData()
- coordinator = hass.data.setdefault(DOMAIN, {})[
- entry.entry_id
- ] = PassiveBluetoothProcessorCoordinator(
- hass,
- _LOGGER,
- address=address,
- mode=BluetoothScanningMode.ACTIVE,
- update_method=data.update,
+ coordinator = hass.data.setdefault(DOMAIN, {})[entry.entry_id] = (
+ PassiveBluetoothProcessorCoordinator(
+ hass,
+ _LOGGER,
+ address=address,
+ mode=BluetoothScanningMode.ACTIVE,
+ update_method=data.update,
+ )
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(
diff --git a/homeassistant/components/thermoworks_smoke/sensor.py b/homeassistant/components/thermoworks_smoke/sensor.py
index b2d6613f2e5..57621ba1055 100644
--- a/homeassistant/components/thermoworks_smoke/sensor.py
+++ b/homeassistant/components/thermoworks_smoke/sensor.py
@@ -159,9 +159,9 @@ class ThermoworksSmokeSensor(SensorEntity):
if key and key not in EXCLUDE_KEYS:
self._attr_extra_state_attributes[key] = val
# store actual unit because attributes are not converted
- self._attr_extra_state_attributes[
- "unit_of_min_max"
- ] = self._attr_native_unit_of_measurement
+ self._attr_extra_state_attributes["unit_of_min_max"] = (
+ self._attr_native_unit_of_measurement
+ )
except (RequestException, ValueError, KeyError):
_LOGGER.warning("Could not update status for %s", self.name)
diff --git a/homeassistant/components/tilt_ble/__init__.py b/homeassistant/components/tilt_ble/__init__.py
index 7770eb3cd20..9ac2cb91aff 100644
--- a/homeassistant/components/tilt_ble/__init__.py
+++ b/homeassistant/components/tilt_ble/__init__.py
@@ -26,14 +26,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
address = entry.unique_id
assert address is not None
data = TiltBluetoothDeviceData()
- coordinator = hass.data.setdefault(DOMAIN, {})[
- entry.entry_id
- ] = PassiveBluetoothProcessorCoordinator(
- hass,
- _LOGGER,
- address=address,
- mode=BluetoothScanningMode.ACTIVE,
- update_method=data.update,
+ coordinator = hass.data.setdefault(DOMAIN, {})[entry.entry_id] = (
+ PassiveBluetoothProcessorCoordinator(
+ hass,
+ _LOGGER,
+ address=address,
+ mode=BluetoothScanningMode.ACTIVE,
+ update_method=data.update,
+ )
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(
diff --git a/homeassistant/components/tolo/const.py b/homeassistant/components/tolo/const.py
index e4f30eda6d3..40940c4283c 100644
--- a/homeassistant/components/tolo/const.py
+++ b/homeassistant/components/tolo/const.py
@@ -1,4 +1,5 @@
"""Constants for the tolo integration."""
+
from enum import Enum
from tololib import AromaTherapySlot as ToloAromaTherapySlot, LampMode as ToloLampMode
diff --git a/homeassistant/components/traccar/device_tracker.py b/homeassistant/components/traccar/device_tracker.py
index 93ee63df397..d82b922f586 100644
--- a/homeassistant/components/traccar/device_tracker.py
+++ b/homeassistant/components/traccar/device_tracker.py
@@ -144,9 +144,9 @@ async def async_setup_entry(
[TraccarEntity(device, latitude, longitude, battery, accuracy, attrs)]
)
- hass.data[DOMAIN]["unsub_device_tracker"][
- entry.entry_id
- ] = async_dispatcher_connect(hass, TRACKER_UPDATE, _receive_data)
+ hass.data[DOMAIN]["unsub_device_tracker"][entry.entry_id] = (
+ async_dispatcher_connect(hass, TRACKER_UPDATE, _receive_data)
+ )
# Restore previously loaded devices
dev_reg = dr.async_get(hass)
diff --git a/homeassistant/components/tuya/base.py b/homeassistant/components/tuya/base.py
index 409e0b2e763..8ff7041fd5e 100644
--- a/homeassistant/components/tuya/base.py
+++ b/homeassistant/components/tuya/base.py
@@ -166,8 +166,7 @@ class TuyaEntity(Entity):
*,
prefer_function: bool = False,
dptype: Literal[DPType.ENUM],
- ) -> EnumTypeData | None:
- ...
+ ) -> EnumTypeData | None: ...
@overload
def find_dpcode(
@@ -176,8 +175,7 @@ class TuyaEntity(Entity):
*,
prefer_function: bool = False,
dptype: Literal[DPType.INTEGER],
- ) -> IntegerTypeData | None:
- ...
+ ) -> IntegerTypeData | None: ...
@overload
def find_dpcode(
@@ -185,8 +183,7 @@ class TuyaEntity(Entity):
dpcodes: str | DPCode | tuple[DPCode, ...] | None,
*,
prefer_function: bool = False,
- ) -> DPCode | None:
- ...
+ ) -> DPCode | None: ...
def find_dpcode(
self,
diff --git a/homeassistant/components/twentemilieu/__init__.py b/homeassistant/components/twentemilieu/__init__.py
index 293bab54e16..d9881b0b2c8 100644
--- a/homeassistant/components/twentemilieu/__init__.py
+++ b/homeassistant/components/twentemilieu/__init__.py
@@ -34,14 +34,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
session=session,
)
- coordinator: DataUpdateCoordinator[
- dict[WasteType, list[date]]
- ] = DataUpdateCoordinator(
- hass,
- LOGGER,
- name=DOMAIN,
- update_interval=SCAN_INTERVAL,
- update_method=twentemilieu.update,
+ coordinator: DataUpdateCoordinator[dict[WasteType, list[date]]] = (
+ DataUpdateCoordinator(
+ hass,
+ LOGGER,
+ name=DOMAIN,
+ update_interval=SCAN_INTERVAL,
+ update_method=twentemilieu.update,
+ )
)
await coordinator.async_config_entry_first_refresh()
diff --git a/homeassistant/components/unifi/config_flow.py b/homeassistant/components/unifi/config_flow.py
index 435d36d8feb..79b5e035f41 100644
--- a/homeassistant/components/unifi/config_flow.py
+++ b/homeassistant/components/unifi/config_flow.py
@@ -237,9 +237,9 @@ class UnifiFlowHandler(ConfigFlow, domain=UNIFI_DOMAIN):
if (port := MODEL_PORTS.get(model_description)) is not None:
self.config[CONF_PORT] = port
- self.context[
- "configuration_url"
- ] = f"https://{self.config[CONF_HOST]}:{port}"
+ self.context["configuration_url"] = (
+ f"https://{self.config[CONF_HOST]}:{port}"
+ )
return await self.async_step_user()
@@ -279,9 +279,9 @@ class UnifiOptionsFlowHandler(OptionsFlow):
clients_to_block = {}
for client in self.hub.api.clients.values():
- clients_to_block[
- client.mac
- ] = f"{client.name or client.hostname} ({client.mac})"
+ clients_to_block[client.mac] = (
+ f"{client.name or client.hostname} ({client.mac})"
+ )
return self.async_show_form(
step_id="simple_options",
@@ -410,9 +410,9 @@ class UnifiOptionsFlowHandler(OptionsFlow):
clients_to_block = {}
for client in self.hub.api.clients.values():
- clients_to_block[
- client.mac
- ] = f"{client.name or client.hostname} ({client.mac})"
+ clients_to_block[client.mac] = (
+ f"{client.name or client.hostname} ({client.mac})"
+ )
selected_clients_to_block = [
client
diff --git a/homeassistant/components/unifiprotect/entity.py b/homeassistant/components/unifiprotect/entity.py
index 8366f2b7f04..932cc75b9d0 100644
--- a/homeassistant/components/unifiprotect/entity.py
+++ b/homeassistant/components/unifiprotect/entity.py
@@ -195,9 +195,9 @@ class ProtectDeviceEntity(Entity):
super().__init__()
self.data: ProtectData = data
self.device = device
- self._async_get_ufp_enabled: Callable[
- [ProtectAdoptableDeviceModel], bool
- ] | None = None
+ self._async_get_ufp_enabled: (
+ Callable[[ProtectAdoptableDeviceModel], bool] | None
+ ) = None
if description is None:
self._attr_unique_id = f"{self.device.mac}"
diff --git a/homeassistant/components/upnp/device.py b/homeassistant/components/upnp/device.py
index 04d8b3414bd..4dff753ac6a 100644
--- a/homeassistant/components/upnp/device.py
+++ b/homeassistant/components/upnp/device.py
@@ -86,9 +86,9 @@ class Device:
"""Initialize UPnP/IGD device."""
self.hass = hass
self._igd_device = igd_device
- self.coordinator: DataUpdateCoordinator[
- dict[str, str | datetime | int | float | None]
- ] | None = None
+ self.coordinator: (
+ DataUpdateCoordinator[dict[str, str | datetime | int | float | None]] | None
+ ) = None
self.original_udn: str | None = None
async def async_get_mac_address(self) -> str | None:
diff --git a/homeassistant/components/utility_meter/__init__.py b/homeassistant/components/utility_meter/__init__.py
index aeed9885872..71df488de7e 100644
--- a/homeassistant/components/utility_meter/__init__.py
+++ b/homeassistant/components/utility_meter/__init__.py
@@ -164,9 +164,9 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
)
)
- hass.data[DATA_UTILITY][meter][
- CONF_TARIFF_ENTITY
- ] = f"{SELECT_DOMAIN}.{meter}"
+ hass.data[DATA_UTILITY][meter][CONF_TARIFF_ENTITY] = (
+ f"{SELECT_DOMAIN}.{meter}"
+ )
# add one meter for each tariff
tariff_confs = {}
@@ -213,9 +213,9 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
entity_entry = entity_registry.async_get_or_create(
Platform.SELECT, DOMAIN, entry.entry_id, suggested_object_id=entry.title
)
- hass.data[DATA_UTILITY][entry.entry_id][
- CONF_TARIFF_ENTITY
- ] = entity_entry.entity_id
+ hass.data[DATA_UTILITY][entry.entry_id][CONF_TARIFF_ENTITY] = (
+ entity_entry.entity_id
+ )
await hass.config_entries.async_forward_entry_setups(
entry, (Platform.SELECT, Platform.SENSOR)
)
diff --git a/homeassistant/components/verisure/switch.py b/homeassistant/components/verisure/switch.py
index b7dd06ac3a5..e0238097e01 100644
--- a/homeassistant/components/verisure/switch.py
+++ b/homeassistant/components/verisure/switch.py
@@ -90,9 +90,9 @@ class VerisureSmartplug(CoordinatorEntity[VerisureDataUpdateCoordinator], Switch
async def async_set_plug_state(self, state: bool) -> None:
"""Set smartplug state."""
- command: dict[
- str, str | dict[str, str]
- ] = self.coordinator.verisure.set_smartplug(self.serial_number, state)
+ command: dict[str, str | dict[str, str]] = (
+ self.coordinator.verisure.set_smartplug(self.serial_number, state)
+ )
await self.hass.async_add_executor_job(
self.coordinator.verisure.request,
command,
diff --git a/homeassistant/components/vicare/climate.py b/homeassistant/components/vicare/climate.py
index 4b231443350..490048190fa 100644
--- a/homeassistant/components/vicare/climate.py
+++ b/homeassistant/components/vicare/climate.py
@@ -199,14 +199,14 @@ class ViCareClimate(ViCareEntity, ClimateEntity):
}
with suppress(PyViCareNotSupportedFeatureError):
- self._attributes[
- "heating_curve_slope"
- ] = self._circuit.getHeatingCurveSlope()
+ self._attributes["heating_curve_slope"] = (
+ self._circuit.getHeatingCurveSlope()
+ )
with suppress(PyViCareNotSupportedFeatureError):
- self._attributes[
- "heating_curve_shift"
- ] = self._circuit.getHeatingCurveShift()
+ self._attributes["heating_curve_shift"] = (
+ self._circuit.getHeatingCurveShift()
+ )
with suppress(PyViCareNotSupportedFeatureError):
self._attributes["vicare_modes"] = self._circuit.getModes()
diff --git a/homeassistant/components/vulcan/config_flow.py b/homeassistant/components/vulcan/config_flow.py
index 15749a7bf3d..ae44c507c6a 100644
--- a/homeassistant/components/vulcan/config_flow.py
+++ b/homeassistant/components/vulcan/config_flow.py
@@ -111,9 +111,9 @@ class VulcanFlowHandler(ConfigFlow, domain=DOMAIN):
students = {}
if self.students is not None:
for student in self.students:
- students[
- str(student.pupil.id)
- ] = f"{student.pupil.first_name} {student.pupil.last_name}"
+ students[str(student.pupil.id)] = (
+ f"{student.pupil.first_name} {student.pupil.last_name}"
+ )
if user_input is not None:
student_id = user_input["student"]
await self.async_set_unique_id(str(student_id))
diff --git a/homeassistant/components/vulcan/fetch_data.py b/homeassistant/components/vulcan/fetch_data.py
index c706bfa805f..cd82346d5b7 100644
--- a/homeassistant/components/vulcan/fetch_data.py
+++ b/homeassistant/components/vulcan/fetch_data.py
@@ -87,9 +87,9 @@ async def get_student_info(client, student_id):
if student.pupil.second_name:
student_info["second_name"] = student.pupil.second_name
student_info["last_name"] = student.pupil.last_name
- student_info[
- "full_name"
- ] = f"{student.pupil.first_name} {student.pupil.last_name}"
+ student_info["full_name"] = (
+ f"{student.pupil.first_name} {student.pupil.last_name}"
+ )
student_info["id"] = student.pupil.id
student_info["class"] = student.class_
student_info["school"] = student.school.name
diff --git a/homeassistant/components/wallbox/coordinator.py b/homeassistant/components/wallbox/coordinator.py
index a33d90db700..4725e92ca84 100644
--- a/homeassistant/components/wallbox/coordinator.py
+++ b/homeassistant/components/wallbox/coordinator.py
@@ -133,9 +133,9 @@ class WallboxCoordinator(DataUpdateCoordinator[dict[str, Any]]):
data[CHARGER_ENERGY_PRICE_KEY] = data[CHARGER_DATA_KEY][
CHARGER_ENERGY_PRICE_KEY
]
- data[
- CHARGER_CURRENCY_KEY
- ] = f"{data[CHARGER_DATA_KEY][CHARGER_CURRENCY_KEY][CODE_KEY]}/kWh"
+ data[CHARGER_CURRENCY_KEY] = (
+ f"{data[CHARGER_DATA_KEY][CHARGER_CURRENCY_KEY][CODE_KEY]}/kWh"
+ )
data[CHARGER_STATUS_DESCRIPTION_KEY] = CHARGER_STATUS.get(
data[CHARGER_STATUS_ID_KEY], ChargerStatus.UNKNOWN
diff --git a/homeassistant/components/websocket_api/auth.py b/homeassistant/components/websocket_api/auth.py
index 5093ef187c5..a15f76632c1 100644
--- a/homeassistant/components/websocket_api/auth.py
+++ b/homeassistant/components/websocket_api/auth.py
@@ -90,10 +90,10 @@ class AuthPhase:
refresh_token.user,
refresh_token,
)
- conn.subscriptions[
- "auth"
- ] = self._hass.auth.async_register_revoke_token_callback(
- refresh_token.id, self._cancel_ws
+ conn.subscriptions["auth"] = (
+ self._hass.auth.async_register_revoke_token_callback(
+ refresh_token.id, self._cancel_ws
+ )
)
await self._send_bytes_text(AUTH_OK_MESSAGE)
self._logger.debug("Auth OK")
diff --git a/homeassistant/components/xiaomi_ble/__init__.py b/homeassistant/components/xiaomi_ble/__init__.py
index 1402a15a56d..19c1f3feea1 100644
--- a/homeassistant/components/xiaomi_ble/__init__.py
+++ b/homeassistant/components/xiaomi_ble/__init__.py
@@ -168,25 +168,27 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
return await data.async_poll(connectable_device)
device_registry = async_get(hass)
- coordinator = hass.data.setdefault(DOMAIN, {})[
- entry.entry_id
- ] = XiaomiActiveBluetoothProcessorCoordinator(
- hass,
- _LOGGER,
- address=address,
- mode=BluetoothScanningMode.PASSIVE,
- update_method=lambda service_info: process_service_info(
- hass, entry, data, service_info, device_registry
- ),
- needs_poll_method=_needs_poll,
- device_data=data,
- discovered_event_classes=set(entry.data.get(CONF_DISCOVERED_EVENT_CLASSES, [])),
- poll_method=_async_poll,
- # We will take advertisements from non-connectable devices
- # since we will trade the BLEDevice for a connectable one
- # if we need to poll it
- connectable=False,
- entry=entry,
+ coordinator = hass.data.setdefault(DOMAIN, {})[entry.entry_id] = (
+ XiaomiActiveBluetoothProcessorCoordinator(
+ hass,
+ _LOGGER,
+ address=address,
+ mode=BluetoothScanningMode.PASSIVE,
+ update_method=lambda service_info: process_service_info(
+ hass, entry, data, service_info, device_registry
+ ),
+ needs_poll_method=_needs_poll,
+ device_data=data,
+ discovered_event_classes=set(
+ entry.data.get(CONF_DISCOVERED_EVENT_CLASSES, [])
+ ),
+ poll_method=_async_poll,
+ # We will take advertisements from non-connectable devices
+ # since we will trade the BLEDevice for a connectable one
+ # if we need to poll it
+ connectable=False,
+ entry=entry,
+ )
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(
diff --git a/homeassistant/components/zha/core/cluster_handlers/__init__.py b/homeassistant/components/zha/core/cluster_handlers/__init__.py
index ff880ed3b69..ae7b0945230 100644
--- a/homeassistant/components/zha/core/cluster_handlers/__init__.py
+++ b/homeassistant/components/zha/core/cluster_handlers/__init__.py
@@ -335,9 +335,9 @@ class ClusterHandler(LogMixin):
return
for record in res:
- event_data[self.cluster.find_attribute(record.attrid).name][
- "status"
- ] = record.status.name
+ event_data[self.cluster.find_attribute(record.attrid).name]["status"] = (
+ record.status.name
+ )
failed = [
self.cluster.find_attribute(record.attrid).name
for record in res
diff --git a/homeassistant/components/zha/core/discovery.py b/homeassistant/components/zha/core/discovery.py
index 98d37f1a7db..75e5b51e599 100644
--- a/homeassistant/components/zha/core/discovery.py
+++ b/homeassistant/components/zha/core/discovery.py
@@ -293,9 +293,9 @@ class ProbeEndpoint:
not in cluster_handler.ZCL_INIT_ATTRS
):
init_attrs = cluster_handler.ZCL_INIT_ATTRS.copy()
- init_attrs[
- quirk_metadata.entity_metadata.attribute_name
- ] = quirk_metadata.attribute_initialized_from_cache
+ init_attrs[quirk_metadata.entity_metadata.attribute_name] = (
+ quirk_metadata.attribute_initialized_from_cache
+ )
cluster_handler.__dict__[zha_const.ZCL_INIT_ATTRS] = init_attrs
endpoint.async_new_entity(
diff --git a/homeassistant/components/zha/core/gateway.py b/homeassistant/components/zha/core/gateway.py
index 6706aef91f3..83aa12fbfa1 100644
--- a/homeassistant/components/zha/core/gateway.py
+++ b/homeassistant/components/zha/core/gateway.py
@@ -133,9 +133,9 @@ class ZHAGateway:
self._groups: dict[int, ZHAGroup] = {}
self.application_controller: ControllerApplication = None
self.coordinator_zha_device: ZHADevice = None # type: ignore[assignment]
- self._device_registry: collections.defaultdict[
- EUI64, list[EntityReference]
- ] = collections.defaultdict(list)
+ self._device_registry: collections.defaultdict[EUI64, list[EntityReference]] = (
+ collections.defaultdict(list)
+ )
self._log_levels: dict[str, dict[str, int]] = {
DEBUG_LEVEL_ORIGINAL: async_capture_log_levels(),
DEBUG_LEVEL_CURRENT: async_capture_log_levels(),
diff --git a/homeassistant/components/zha/core/registries.py b/homeassistant/components/zha/core/registries.py
index 10e63dd3590..b9110a8dcde 100644
--- a/homeassistant/components/zha/core/registries.py
+++ b/homeassistant/components/zha/core/registries.py
@@ -108,12 +108,12 @@ DEVICE_CLASS = {
DEVICE_CLASS = collections.defaultdict(dict, DEVICE_CLASS)
CLUSTER_HANDLER_ONLY_CLUSTERS = SetRegistry()
-CLIENT_CLUSTER_HANDLER_REGISTRY: DictRegistry[
- type[ClientClusterHandler]
-] = DictRegistry()
-ZIGBEE_CLUSTER_HANDLER_REGISTRY: NestedDictRegistry[
- type[ClusterHandler]
-] = NestedDictRegistry()
+CLIENT_CLUSTER_HANDLER_REGISTRY: DictRegistry[type[ClientClusterHandler]] = (
+ DictRegistry()
+)
+ZIGBEE_CLUSTER_HANDLER_REGISTRY: NestedDictRegistry[type[ClusterHandler]] = (
+ NestedDictRegistry()
+)
WEIGHT_ATTR = attrgetter("weight")
@@ -278,9 +278,9 @@ class ZHAEntityRegistry:
def __init__(self) -> None:
"""Initialize Registry instance."""
- self._strict_registry: dict[
- Platform, dict[MatchRule, type[ZhaEntity]]
- ] = collections.defaultdict(dict)
+ self._strict_registry: dict[Platform, dict[MatchRule, type[ZhaEntity]]] = (
+ collections.defaultdict(dict)
+ )
self._multi_entity_registry: dict[
Platform, dict[int | str | None, dict[MatchRule, list[type[ZhaEntity]]]]
] = collections.defaultdict(
@@ -292,9 +292,9 @@ class ZHAEntityRegistry:
lambda: collections.defaultdict(lambda: collections.defaultdict(list))
)
self._group_registry: dict[str, type[ZhaGroupEntity]] = {}
- self.single_device_matches: dict[
- Platform, dict[EUI64, list[str]]
- ] = collections.defaultdict(lambda: collections.defaultdict(list))
+ self.single_device_matches: dict[Platform, dict[EUI64, list[str]]] = (
+ collections.defaultdict(lambda: collections.defaultdict(list))
+ )
def get_entity(
self,
@@ -324,9 +324,9 @@ class ZHAEntityRegistry:
dict[Platform, list[EntityClassAndClusterHandlers]], list[ClusterHandler]
]:
"""Match ZHA cluster handlers to potentially multiple ZHA Entity classes."""
- result: dict[
- Platform, list[EntityClassAndClusterHandlers]
- ] = collections.defaultdict(list)
+ result: dict[Platform, list[EntityClassAndClusterHandlers]] = (
+ collections.defaultdict(list)
+ )
all_claimed: set[ClusterHandler] = set()
for component, stop_match_groups in self._multi_entity_registry.items():
for stop_match_grp, matches in stop_match_groups.items():
@@ -357,9 +357,9 @@ class ZHAEntityRegistry:
dict[Platform, list[EntityClassAndClusterHandlers]], list[ClusterHandler]
]:
"""Match ZHA cluster handlers to potentially multiple ZHA Entity classes."""
- result: dict[
- Platform, list[EntityClassAndClusterHandlers]
- ] = collections.defaultdict(list)
+ result: dict[Platform, list[EntityClassAndClusterHandlers]] = (
+ collections.defaultdict(list)
+ )
all_claimed: set[ClusterHandler] = set()
for (
component,
diff --git a/homeassistant/components/zwave_js/__init__.py b/homeassistant/components/zwave_js/__init__.py
index 0fdf7a77895..52c7804bb8f 100644
--- a/homeassistant/components/zwave_js/__init__.py
+++ b/homeassistant/components/zwave_js/__init__.py
@@ -186,9 +186,9 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
# Create a task to allow the config entry to be unloaded before the driver is ready.
# Unloading the config entry is needed if the client listen task errors.
start_client_task = hass.async_create_task(start_client(hass, entry, client))
- hass.data[DOMAIN].setdefault(entry.entry_id, {})[
- DATA_START_CLIENT_TASK
- ] = start_client_task
+ hass.data[DOMAIN].setdefault(entry.entry_id, {})[DATA_START_CLIENT_TASK] = (
+ start_client_task
+ )
return True
diff --git a/homeassistant/components/zwave_js/binary_sensor.py b/homeassistant/components/zwave_js/binary_sensor.py
index 8137623379a..79181e818a2 100644
--- a/homeassistant/components/zwave_js/binary_sensor.py
+++ b/homeassistant/components/zwave_js/binary_sensor.py
@@ -270,7 +270,9 @@ async def async_setup_entry(
if state_key == "0":
continue
- notification_description: NotificationZWaveJSEntityDescription | None = None
+ notification_description: (
+ NotificationZWaveJSEntityDescription | None
+ ) = None
for description in NOTIFICATION_SENSOR_MAPPINGS:
if (
diff --git a/homeassistant/components/zwave_js/triggers/event.py b/homeassistant/components/zwave_js/triggers/event.py
index 28717370d20..6cf4a31c0eb 100644
--- a/homeassistant/components/zwave_js/triggers/event.py
+++ b/homeassistant/components/zwave_js/triggers/event.py
@@ -197,9 +197,9 @@ async def async_attach_trigger(
else:
payload["description"] = primary_desc
- payload[
- "description"
- ] = f"{payload['description']} with event data: {event_data}"
+ payload["description"] = (
+ f"{payload['description']} with event data: {event_data}"
+ )
hass.async_run_hass_job(job, {"trigger": payload})
diff --git a/homeassistant/config.py b/homeassistant/config.py
index d2390c6c4ff..c570e36c6c1 100644
--- a/homeassistant/config.py
+++ b/homeassistant/config.py
@@ -1112,9 +1112,9 @@ async def merge_packages_config(
continue
try:
- config_platform: ModuleType | None = (
- await integration.async_get_platform("config")
- )
+ config_platform: (
+ ModuleType | None
+ ) = await integration.async_get_platform("config")
# Test if config platform has a config validator
if not hasattr(config_platform, "async_validate_config"):
config_platform = None
diff --git a/homeassistant/config_entries.py b/homeassistant/config_entries.py
index 9ea049c4616..15de62179cb 100644
--- a/homeassistant/config_entries.py
+++ b/homeassistant/config_entries.py
@@ -372,9 +372,9 @@ class ConfigEntry:
self._async_cancel_retry_setup: Callable[[], Any] | None = None
# Hold list for actions to call on unload.
- self._on_unload: list[
- Callable[[], Coroutine[Any, Any, None] | None]
- ] | None = None
+ self._on_unload: list[Callable[[], Coroutine[Any, Any, None] | None]] | None = (
+ None
+ )
# Reload lock to prevent conflicting reloads
self.reload_lock = asyncio.Lock()
@@ -1138,9 +1138,9 @@ class ConfigEntriesFlowManager(data_entry_flow.FlowManager[ConfigFlowResult]):
loop = self.hass.loop
if context["source"] == SOURCE_IMPORT:
- self._pending_import_flows.setdefault(handler, {})[
- flow_id
- ] = loop.create_future()
+ self._pending_import_flows.setdefault(handler, {})[flow_id] = (
+ loop.create_future()
+ )
cancel_init_future = loop.create_future()
self._initialize_futures.setdefault(handler, []).append(cancel_init_future)
diff --git a/homeassistant/core.py b/homeassistant/core.py
index 561cb45d39f..7d229e3727f 100644
--- a/homeassistant/core.py
+++ b/homeassistant/core.py
@@ -563,8 +563,7 @@ class HomeAssistant:
target: Callable[[*_Ts], Coroutine[Any, Any, _R]],
*args: *_Ts,
eager_start: bool = False,
- ) -> asyncio.Future[_R] | None:
- ...
+ ) -> asyncio.Future[_R] | None: ...
@overload
@callback
@@ -573,8 +572,7 @@ class HomeAssistant:
target: Callable[[*_Ts], Coroutine[Any, Any, _R] | _R],
*args: *_Ts,
eager_start: bool = False,
- ) -> asyncio.Future[_R] | None:
- ...
+ ) -> asyncio.Future[_R] | None: ...
@overload
@callback
@@ -583,8 +581,7 @@ class HomeAssistant:
target: Coroutine[Any, Any, _R],
*args: Any,
eager_start: bool = False,
- ) -> asyncio.Future[_R] | None:
- ...
+ ) -> asyncio.Future[_R] | None: ...
@callback
def async_add_job(
@@ -637,8 +634,7 @@ class HomeAssistant:
*args: Any,
eager_start: bool = False,
background: bool = False,
- ) -> asyncio.Future[_R] | None:
- ...
+ ) -> asyncio.Future[_R] | None: ...
@overload
@callback
@@ -648,8 +644,7 @@ class HomeAssistant:
*args: Any,
eager_start: bool = False,
background: bool = False,
- ) -> asyncio.Future[_R] | None:
- ...
+ ) -> asyncio.Future[_R] | None: ...
@callback
def async_add_hass_job(
@@ -801,8 +796,7 @@ class HomeAssistant:
hassjob: HassJob[..., Coroutine[Any, Any, _R]],
*args: Any,
background: bool = False,
- ) -> asyncio.Future[_R] | None:
- ...
+ ) -> asyncio.Future[_R] | None: ...
@overload
@callback
@@ -811,8 +805,7 @@ class HomeAssistant:
hassjob: HassJob[..., Coroutine[Any, Any, _R] | _R],
*args: Any,
background: bool = False,
- ) -> asyncio.Future[_R] | None:
- ...
+ ) -> asyncio.Future[_R] | None: ...
@callback
def async_run_hass_job(
@@ -848,22 +841,19 @@ class HomeAssistant:
@callback
def async_run_job(
self, target: Callable[[*_Ts], Coroutine[Any, Any, _R]], *args: *_Ts
- ) -> asyncio.Future[_R] | None:
- ...
+ ) -> asyncio.Future[_R] | None: ...
@overload
@callback
def async_run_job(
self, target: Callable[[*_Ts], Coroutine[Any, Any, _R] | _R], *args: *_Ts
- ) -> asyncio.Future[_R] | None:
- ...
+ ) -> asyncio.Future[_R] | None: ...
@overload
@callback
def async_run_job(
self, target: Coroutine[Any, Any, _R], *args: Any
- ) -> asyncio.Future[_R] | None:
- ...
+ ) -> asyncio.Future[_R] | None: ...
@callback
def async_run_job(
@@ -956,15 +946,13 @@ class HomeAssistant:
@callback
def async_add_shutdown_job(
self, hassjob: HassJob[..., Coroutine[Any, Any, Any]], *args: Any
- ) -> CALLBACK_TYPE:
- ...
+ ) -> CALLBACK_TYPE: ...
@overload
@callback
def async_add_shutdown_job(
self, hassjob: HassJob[..., Coroutine[Any, Any, Any] | Any], *args: Any
- ) -> CALLBACK_TYPE:
- ...
+ ) -> CALLBACK_TYPE: ...
@callback
def async_add_shutdown_job(
@@ -1788,9 +1776,9 @@ class State:
COMPRESSED_STATE_LAST_CHANGED: self.last_changed_timestamp,
}
if self.last_changed != self.last_updated:
- compressed_state[
- COMPRESSED_STATE_LAST_UPDATED
- ] = self.last_updated_timestamp
+ compressed_state[COMPRESSED_STATE_LAST_UPDATED] = (
+ self.last_updated_timestamp
+ )
return compressed_state
@cached_property
diff --git a/homeassistant/exceptions.py b/homeassistant/exceptions.py
index f681764b4af..bdf4d8c060b 100644
--- a/homeassistant/exceptions.py
+++ b/homeassistant/exceptions.py
@@ -72,9 +72,9 @@ class HomeAssistantError(Exception):
assert self.translation_domain is not None
if "async_get_exception_message" not in _function_cache:
- _function_cache[
- "async_get_exception_message"
- ] = import_async_get_exception_message()
+ _function_cache["async_get_exception_message"] = (
+ import_async_get_exception_message()
+ )
self._message = _function_cache["async_get_exception_message"](
self.translation_domain, self.translation_key, self.translation_placeholders
diff --git a/homeassistant/helpers/config_entry_oauth2_flow.py b/homeassistant/helpers/config_entry_oauth2_flow.py
index 83e76ca4ebe..caf47432623 100644
--- a/homeassistant/helpers/config_entry_oauth2_flow.py
+++ b/homeassistant/helpers/config_entry_oauth2_flow.py
@@ -439,9 +439,9 @@ def async_add_implementation_provider(
If no implementation found, return None.
"""
- hass.data.setdefault(DATA_PROVIDERS, {})[
- provider_domain
- ] = async_provide_implementation
+ hass.data.setdefault(DATA_PROVIDERS, {})[provider_domain] = (
+ async_provide_implementation
+ )
class OAuth2AuthorizeCallbackView(http.HomeAssistantView):
diff --git a/homeassistant/helpers/config_validation.py b/homeassistant/helpers/config_validation.py
index 3f5af582424..6dd5d7f2bdb 100644
--- a/homeassistant/helpers/config_validation.py
+++ b/homeassistant/helpers/config_validation.py
@@ -284,18 +284,15 @@ def isdir(value: Any) -> str:
@overload
-def ensure_list(value: None) -> list[Any]:
- ...
+def ensure_list(value: None) -> list[Any]: ...
@overload
-def ensure_list(value: list[_T]) -> list[_T]:
- ...
+def ensure_list(value: list[_T]) -> list[_T]: ...
@overload
-def ensure_list(value: list[_T] | _T) -> list[_T]:
- ...
+def ensure_list(value: list[_T] | _T) -> list[_T]: ...
def ensure_list(value: _T | None) -> list[_T] | list[Any]:
diff --git a/homeassistant/helpers/dispatcher.py b/homeassistant/helpers/dispatcher.py
index cb812ef071b..22d9c3bbab8 100644
--- a/homeassistant/helpers/dispatcher.py
+++ b/homeassistant/helpers/dispatcher.py
@@ -53,16 +53,14 @@ _DispatcherDataType = dict[
@bind_hass
def dispatcher_connect(
hass: HomeAssistant, signal: SignalType[*_Ts], target: Callable[[*_Ts], None]
-) -> Callable[[], None]:
- ...
+) -> Callable[[], None]: ...
@overload
@bind_hass
def dispatcher_connect(
hass: HomeAssistant, signal: str, target: Callable[..., None]
-) -> Callable[[], None]:
- ...
+) -> Callable[[], None]: ...
@bind_hass # type: ignore[misc] # workaround; exclude typing of 2 overload in func def
@@ -108,8 +106,7 @@ def _async_remove_dispatcher(
@bind_hass
def async_dispatcher_connect(
hass: HomeAssistant, signal: SignalType[*_Ts], target: Callable[[*_Ts], Any]
-) -> Callable[[], None]:
- ...
+) -> Callable[[], None]: ...
@overload
@@ -117,8 +114,7 @@ def async_dispatcher_connect(
@bind_hass
def async_dispatcher_connect(
hass: HomeAssistant, signal: str, target: Callable[..., Any]
-) -> Callable[[], None]:
- ...
+) -> Callable[[], None]: ...
@callback
@@ -150,14 +146,14 @@ def async_dispatcher_connect(
@overload
@bind_hass
-def dispatcher_send(hass: HomeAssistant, signal: SignalType[*_Ts], *args: *_Ts) -> None:
- ...
+def dispatcher_send(
+ hass: HomeAssistant, signal: SignalType[*_Ts], *args: *_Ts
+) -> None: ...
@overload
@bind_hass
-def dispatcher_send(hass: HomeAssistant, signal: str, *args: Any) -> None:
- ...
+def dispatcher_send(hass: HomeAssistant, signal: str, *args: Any) -> None: ...
@bind_hass # type: ignore[misc] # workaround; exclude typing of 2 overload in func def
@@ -195,15 +191,13 @@ def _generate_job(
@bind_hass
def async_dispatcher_send(
hass: HomeAssistant, signal: SignalType[*_Ts], *args: *_Ts
-) -> None:
- ...
+) -> None: ...
@overload
@callback
@bind_hass
-def async_dispatcher_send(hass: HomeAssistant, signal: str, *args: Any) -> None:
- ...
+def async_dispatcher_send(hass: HomeAssistant, signal: str, *args: Any) -> None: ...
@callback
diff --git a/homeassistant/helpers/entity_platform.py b/homeassistant/helpers/entity_platform.py
index b0e094f97b4..1cff472af72 100644
--- a/homeassistant/helpers/entity_platform.py
+++ b/homeassistant/helpers/entity_platform.py
@@ -163,9 +163,9 @@ class EntityPlatform:
# with the child dict indexed by entity_id
#
# This is usually media_player.yamaha, light.hue, switch.tplink, etc.
- domain_platform_entities: dict[
- tuple[str, str], dict[str, Entity]
- ] = hass.data.setdefault(DATA_DOMAIN_PLATFORM_ENTITIES, {})
+ domain_platform_entities: dict[tuple[str, str], dict[str, Entity]] = (
+ hass.data.setdefault(DATA_DOMAIN_PLATFORM_ENTITIES, {})
+ )
key = (domain, platform_name)
self.domain_platform_entities = domain_platform_entities.setdefault(key, {})
diff --git a/homeassistant/helpers/floor_registry.py b/homeassistant/helpers/floor_registry.py
index eba3a05cea8..904acc1d805 100644
--- a/homeassistant/helpers/floor_registry.py
+++ b/homeassistant/helpers/floor_registry.py
@@ -54,13 +54,13 @@ class FloorRegistry(BaseRegistry):
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize the floor registry."""
self.hass = hass
- self._store: Store[
- dict[str, list[dict[str, str | int | list[str] | None]]]
- ] = Store(
- hass,
- STORAGE_VERSION_MAJOR,
- STORAGE_KEY,
- atomic_writes=True,
+ self._store: Store[dict[str, list[dict[str, str | int | list[str] | None]]]] = (
+ Store(
+ hass,
+ STORAGE_VERSION_MAJOR,
+ STORAGE_KEY,
+ atomic_writes=True,
+ )
)
@callback
diff --git a/homeassistant/helpers/integration_platform.py b/homeassistant/helpers/integration_platform.py
index e142f9c2e5a..6d474557748 100644
--- a/homeassistant/helpers/integration_platform.py
+++ b/homeassistant/helpers/integration_platform.py
@@ -52,9 +52,9 @@ def _async_integration_platform_component_loaded(
if component_name in integration_platform.seen_components:
continue
integration_platform.seen_components.add(component_name)
- integration_platforms_by_name[
- integration_platform.platform_name
- ] = integration_platform
+ integration_platforms_by_name[integration_platform.platform_name] = (
+ integration_platform
+ )
if not integration_platforms_by_name:
return
diff --git a/homeassistant/helpers/redact.py b/homeassistant/helpers/redact.py
index 1ee9eeaae42..ad06f58a50a 100644
--- a/homeassistant/helpers/redact.py
+++ b/homeassistant/helpers/redact.py
@@ -34,15 +34,13 @@ def partial_redact(
@overload
def async_redact_data( # type: ignore[overload-overlap]
data: Mapping, to_redact: Iterable[Any] | Mapping[Any, Callable[[_ValueT], _ValueT]]
-) -> dict:
- ...
+) -> dict: ...
@overload
def async_redact_data(
data: _T, to_redact: Iterable[Any] | Mapping[Any, Callable[[_ValueT], _ValueT]]
-) -> _T:
- ...
+) -> _T: ...
@callback
diff --git a/homeassistant/helpers/reload.py b/homeassistant/helpers/reload.py
index d6338af95c7..ffd6bdeb50d 100644
--- a/homeassistant/helpers/reload.py
+++ b/homeassistant/helpers/reload.py
@@ -139,8 +139,7 @@ async def _async_reconfig_platform(
@overload
async def async_integration_yaml_config(
hass: HomeAssistant, integration_name: str
-) -> ConfigType | None:
- ...
+) -> ConfigType | None: ...
@overload
@@ -149,8 +148,7 @@ async def async_integration_yaml_config(
integration_name: str,
*,
raise_on_failure: Literal[True],
-) -> ConfigType:
- ...
+) -> ConfigType: ...
@overload
@@ -159,8 +157,7 @@ async def async_integration_yaml_config(
integration_name: str,
*,
raise_on_failure: Literal[False] | bool,
-) -> ConfigType | None:
- ...
+) -> ConfigType | None: ...
async def async_integration_yaml_config(
diff --git a/homeassistant/helpers/schema_config_entry_flow.py b/homeassistant/helpers/schema_config_entry_flow.py
index b5b53c91def..0486c7b6f8c 100644
--- a/homeassistant/helpers/schema_config_entry_flow.py
+++ b/homeassistant/helpers/schema_config_entry_flow.py
@@ -38,9 +38,11 @@ class SchemaFlowStep:
class SchemaFlowFormStep(SchemaFlowStep):
"""Define a config or options flow form step."""
- schema: vol.Schema | Callable[
- [SchemaCommonFlowHandler], Coroutine[Any, Any, vol.Schema | None]
- ] | None = None
+ schema: (
+ vol.Schema
+ | Callable[[SchemaCommonFlowHandler], Coroutine[Any, Any, vol.Schema | None]]
+ | None
+ ) = None
"""Optional voluptuous schema, or function which returns a schema or None, for
requesting and validating user input.
@@ -50,9 +52,13 @@ class SchemaFlowFormStep(SchemaFlowStep):
user input is requested.
"""
- validate_user_input: Callable[
- [SchemaCommonFlowHandler, dict[str, Any]], Coroutine[Any, Any, dict[str, Any]]
- ] | None = None
+ validate_user_input: (
+ Callable[
+ [SchemaCommonFlowHandler, dict[str, Any]],
+ Coroutine[Any, Any, dict[str, Any]],
+ ]
+ | None
+ ) = None
"""Optional function to validate user input.
- The `validate_user_input` function is called if the schema validates successfully.
@@ -61,9 +67,9 @@ class SchemaFlowFormStep(SchemaFlowStep):
- The `validate_user_input` should raise `SchemaFlowError` if user input is invalid.
"""
- next_step: Callable[
- [dict[str, Any]], Coroutine[Any, Any, str | None]
- ] | str | None = None
+ next_step: (
+ Callable[[dict[str, Any]], Coroutine[Any, Any, str | None]] | str | None
+ ) = None
"""Optional property to identify next step.
- If `next_step` is a function, it is called if the schema validates successfully or
@@ -73,9 +79,11 @@ class SchemaFlowFormStep(SchemaFlowStep):
- If `next_step` is None, the flow is ended with `FlowResultType.CREATE_ENTRY`.
"""
- suggested_values: Callable[
- [SchemaCommonFlowHandler], Coroutine[Any, Any, dict[str, Any]]
- ] | None | UndefinedType = UNDEFINED
+ suggested_values: (
+ Callable[[SchemaCommonFlowHandler], Coroutine[Any, Any, dict[str, Any]]]
+ | None
+ | UndefinedType
+ ) = UNDEFINED
"""Optional property to populate suggested values.
- If `suggested_values` is UNDEFINED, each key in the schema will get a suggested
diff --git a/homeassistant/helpers/service.py b/homeassistant/helpers/service.py
index 34cee93d971..da27df9d139 100644
--- a/homeassistant/helpers/service.py
+++ b/homeassistant/helpers/service.py
@@ -656,9 +656,9 @@ async def async_get_all_descriptions(
hass: HomeAssistant,
) -> dict[str, dict[str, Any]]:
"""Return descriptions (i.e. user documentation) for all service calls."""
- descriptions_cache: dict[
- tuple[str, str], dict[str, Any] | None
- ] = hass.data.setdefault(SERVICE_DESCRIPTION_CACHE, {})
+ descriptions_cache: dict[tuple[str, str], dict[str, Any] | None] = (
+ hass.data.setdefault(SERVICE_DESCRIPTION_CACHE, {})
+ )
# We don't mutate services here so we avoid calling
# async_services which makes a copy of every services
@@ -808,9 +808,9 @@ def async_set_service_schema(
domain = domain.lower()
service = service.lower()
- descriptions_cache: dict[
- tuple[str, str], dict[str, Any] | None
- ] = hass.data.setdefault(SERVICE_DESCRIPTION_CACHE, {})
+ descriptions_cache: dict[tuple[str, str], dict[str, Any] | None] = (
+ hass.data.setdefault(SERVICE_DESCRIPTION_CACHE, {})
+ )
description = {
"name": schema.get("name", ""),
diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py
index 58a7e27714c..fc38b821eee 100644
--- a/homeassistant/helpers/template.py
+++ b/homeassistant/helpers/template.py
@@ -1208,13 +1208,11 @@ def _resolve_state(
@overload
-def forgiving_boolean(value: Any) -> bool | object:
- ...
+def forgiving_boolean(value: Any) -> bool | object: ...
@overload
-def forgiving_boolean(value: Any, default: _T) -> bool | _T:
- ...
+def forgiving_boolean(value: Any, default: _T) -> bool | _T: ...
def forgiving_boolean(
@@ -2846,8 +2844,7 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment):
filename: str | None = None,
raw: Literal[False] = False,
defer_init: bool = False,
- ) -> CodeType:
- ...
+ ) -> CodeType: ...
@overload
def compile(
@@ -2857,8 +2854,7 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment):
filename: str | None = None,
raw: Literal[True] = ...,
defer_init: bool = False,
- ) -> str:
- ...
+ ) -> str: ...
def compile(
self,
diff --git a/homeassistant/loader.py b/homeassistant/loader.py
index ae823d9a204..f462ea16886 100644
--- a/homeassistant/loader.py
+++ b/homeassistant/loader.py
@@ -296,9 +296,9 @@ async def async_get_custom_components(
hass: HomeAssistant,
) -> dict[str, Integration]:
"""Return cached list of custom integrations."""
- comps_or_future: dict[str, Integration] | asyncio.Future[
- dict[str, Integration]
- ] | None = hass.data.get(DATA_CUSTOM_COMPONENTS)
+ comps_or_future: (
+ dict[str, Integration] | asyncio.Future[dict[str, Integration]] | None
+ ) = hass.data.get(DATA_CUSTOM_COMPONENTS)
if comps_or_future is None:
future = hass.data[DATA_CUSTOM_COMPONENTS] = hass.loop.create_future()
diff --git a/homeassistant/setup.py b/homeassistant/setup.py
index f9c86b23d96..178ee6425e3 100644
--- a/homeassistant/setup.py
+++ b/homeassistant/setup.py
@@ -33,9 +33,9 @@ from .helpers.issue_registry import IssueSeverity, async_create_issue
from .helpers.typing import ConfigType
from .util.async_ import create_eager_task
-current_setup_group: contextvars.ContextVar[
- tuple[str, str | None] | None
-] = contextvars.ContextVar("current_setup_group", default=None)
+current_setup_group: contextvars.ContextVar[tuple[str, str | None] | None] = (
+ contextvars.ContextVar("current_setup_group", default=None)
+)
_LOGGER = logging.getLogger(__name__)
diff --git a/homeassistant/util/dt.py b/homeassistant/util/dt.py
index 5fa27c826b8..39976cce5f7 100644
--- a/homeassistant/util/dt.py
+++ b/homeassistant/util/dt.py
@@ -179,20 +179,17 @@ def start_of_local_day(dt_or_d: dt.date | dt.datetime | None = None) -> dt.datet
# All rights reserved.
# https://github.com/django/django/blob/main/LICENSE
@overload
-def parse_datetime(dt_str: str) -> dt.datetime | None:
- ...
+def parse_datetime(dt_str: str) -> dt.datetime | None: ...
@overload
-def parse_datetime(dt_str: str, *, raise_on_error: Literal[True]) -> dt.datetime:
- ...
+def parse_datetime(dt_str: str, *, raise_on_error: Literal[True]) -> dt.datetime: ...
@overload
def parse_datetime(
dt_str: str, *, raise_on_error: Literal[False] | bool
-) -> dt.datetime | None:
- ...
+) -> dt.datetime | None: ...
def parse_datetime(dt_str: str, *, raise_on_error: bool = False) -> dt.datetime | None:
diff --git a/homeassistant/util/logging.py b/homeassistant/util/logging.py
index ac85691b7c2..489b6493ef1 100644
--- a/homeassistant/util/logging.py
+++ b/homeassistant/util/logging.py
@@ -139,15 +139,13 @@ def _callback_wrapper(
@overload
def catch_log_exception(
func: Callable[[*_Ts], Coroutine[Any, Any, Any]], format_err: Callable[[*_Ts], Any]
-) -> Callable[[*_Ts], Coroutine[Any, Any, None]]:
- ...
+) -> Callable[[*_Ts], Coroutine[Any, Any, None]]: ...
@overload
def catch_log_exception(
func: Callable[[*_Ts], Any], format_err: Callable[[*_Ts], Any]
-) -> Callable[[*_Ts], None] | Callable[[*_Ts], Coroutine[Any, Any, None]]:
- ...
+) -> Callable[[*_Ts], None] | Callable[[*_Ts], Coroutine[Any, Any, None]]: ...
def catch_log_exception(
diff --git a/homeassistant/util/variance.py b/homeassistant/util/variance.py
index 974a0f88e90..b109e5c476c 100644
--- a/homeassistant/util/variance.py
+++ b/homeassistant/util/variance.py
@@ -14,22 +14,19 @@ _P = ParamSpec("_P")
@overload
def ignore_variance(
func: Callable[_P, int], ignored_variance: int
-) -> Callable[_P, int]:
- ...
+) -> Callable[_P, int]: ...
@overload
def ignore_variance(
func: Callable[_P, float], ignored_variance: float
-) -> Callable[_P, float]:
- ...
+) -> Callable[_P, float]: ...
@overload
def ignore_variance(
func: Callable[_P, datetime], ignored_variance: timedelta
-) -> Callable[_P, datetime]:
- ...
+) -> Callable[_P, datetime]: ...
def ignore_variance(func: Callable[_P, _R], ignored_variance: Any) -> Callable[_P, _R]:
diff --git a/homeassistant/util/yaml/loader.py b/homeassistant/util/yaml/loader.py
index 0713fd83ee8..28027c97211 100644
--- a/homeassistant/util/yaml/loader.py
+++ b/homeassistant/util/yaml/loader.py
@@ -293,8 +293,7 @@ def _add_reference(
obj: list | NodeListClass,
loader: LoaderType,
node: yaml.nodes.Node,
-) -> NodeListClass:
- ...
+) -> NodeListClass: ...
@overload
@@ -302,13 +301,13 @@ def _add_reference(
obj: str | NodeStrClass,
loader: LoaderType,
node: yaml.nodes.Node,
-) -> NodeStrClass:
- ...
+) -> NodeStrClass: ...
@overload
-def _add_reference(obj: _DictT, loader: LoaderType, node: yaml.nodes.Node) -> _DictT:
- ...
+def _add_reference(
+ obj: _DictT, loader: LoaderType, node: yaml.nodes.Node
+) -> _DictT: ...
def _add_reference( # type: ignore[no-untyped-def]
diff --git a/requirements_test_pre_commit.txt b/requirements_test_pre_commit.txt
index a68b91e563f..cb64db20dcd 100644
--- a/requirements_test_pre_commit.txt
+++ b/requirements_test_pre_commit.txt
@@ -1,5 +1,5 @@
# Automatically generated from .pre-commit-config.yaml by gen_requirements_all.py, do not edit
codespell==2.2.6
-ruff==0.2.1
+ruff==0.3.4
yamllint==1.35.1
diff --git a/script/translations/migrate.py b/script/translations/migrate.py
index a6cffe28f7f..0f51e49c5a9 100644
--- a/script/translations/migrate.py
+++ b/script/translations/migrate.py
@@ -269,9 +269,9 @@ def find_frontend_states():
for device_class, dev_class_states in domain_to_write.items():
to_device_class = "_" if device_class == "default" else device_class
for key in dev_class_states:
- to_migrate[
- f"{from_key_base}::{device_class}::{key}"
- ] = f"{to_key_base}::{to_device_class}::{key}"
+ to_migrate[f"{from_key_base}::{device_class}::{key}"] = (
+ f"{to_key_base}::{to_device_class}::{key}"
+ )
# Rewrite "default" device class to _
if "default" in domain_to_write:
diff --git a/tests/auth/mfa_modules/test_notify.py b/tests/auth/mfa_modules/test_notify.py
index 662da38b35b..23b8811dbf9 100644
--- a/tests/auth/mfa_modules/test_notify.py
+++ b/tests/auth/mfa_modules/test_notify.py
@@ -183,8 +183,9 @@ async def test_login_flow_validates_mfa(hass: HomeAssistant) -> None:
assert len(notify_calls) == 1
# retry twice
- with patch("pyotp.HOTP.verify", return_value=False), patch(
- "pyotp.HOTP.at", return_value=MOCK_CODE_2
+ with (
+ patch("pyotp.HOTP.verify", return_value=False),
+ patch("pyotp.HOTP.at", return_value=MOCK_CODE_2),
):
result = await hass.auth.login_flow.async_configure(
result["flow_id"], {"code": "invalid-code"}
diff --git a/tests/auth/test_auth_store.py b/tests/auth/test_auth_store.py
index 91048cd8568..3d62190eab6 100644
--- a/tests/auth/test_auth_store.py
+++ b/tests/auth/test_auth_store.py
@@ -201,13 +201,13 @@ async def test_system_groups_store_id_and_name(
async def test_loading_only_once(hass: HomeAssistant) -> None:
"""Test only one storage load is allowed."""
store = auth_store.AuthStore(hass)
- with patch(
- "homeassistant.helpers.entity_registry.async_get"
- ) as mock_ent_registry, patch(
- "homeassistant.helpers.device_registry.async_get"
- ) as mock_dev_registry, patch(
- "homeassistant.helpers.storage.Store.async_load", return_value=None
- ) as mock_load:
+ with (
+ patch("homeassistant.helpers.entity_registry.async_get") as mock_ent_registry,
+ patch("homeassistant.helpers.device_registry.async_get") as mock_dev_registry,
+ patch(
+ "homeassistant.helpers.storage.Store.async_load", return_value=None
+ ) as mock_load,
+ ):
await store.async_load()
with pytest.raises(RuntimeError, match="Auth storage is already loaded"):
await store.async_load()
diff --git a/tests/auth/test_init.py b/tests/auth/test_init.py
index 91db3fd51d4..4cf6b2cc5f7 100644
--- a/tests/auth/test_init.py
+++ b/tests/auth/test_init.py
@@ -556,10 +556,13 @@ async def test_refresh_token_provider_validation(mock_hass) -> None:
assert manager.async_create_access_token(refresh_token, ip) is not None
- with patch(
- "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token",
- side_effect=InvalidAuthError("Invalid access"),
- ) as call, pytest.raises(InvalidAuthError):
+ with (
+ patch(
+ "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token",
+ side_effect=InvalidAuthError("Invalid access"),
+ ) as call,
+ pytest.raises(InvalidAuthError),
+ ):
manager.async_create_access_token(refresh_token, ip)
call.assert_called_with(refresh_token, ip)
@@ -1103,9 +1106,10 @@ async def test_async_remove_user_fail_if_remove_credential_fails(
"""Test removing a user."""
await hass.auth.async_link_user(hass_admin_user, hass_admin_credential)
- with patch.object(
- hass.auth, "async_remove_credentials", side_effect=ValueError
- ), pytest.raises(ValueError):
+ with (
+ patch.object(hass.auth, "async_remove_credentials", side_effect=ValueError),
+ pytest.raises(ValueError),
+ ):
await hass.auth.async_remove_user(hass_admin_user)
diff --git a/tests/common.py b/tests/common.py
index 72b38a64650..b04632caea2 100644
--- a/tests/common.py
+++ b/tests/common.py
@@ -313,28 +313,35 @@ async def async_test_home_assistant(
hass
)
if load_registries:
- with patch.object(
- StoreWithoutWriteLoad, "async_load", return_value=None
- ), patch(
- "homeassistant.helpers.area_registry.AreaRegistryStore",
- StoreWithoutWriteLoad,
- ), patch(
- "homeassistant.helpers.device_registry.DeviceRegistryStore",
- StoreWithoutWriteLoad,
- ), patch(
- "homeassistant.helpers.entity_registry.EntityRegistryStore",
- StoreWithoutWriteLoad,
- ), patch(
- "homeassistant.helpers.storage.Store", # Floor & label registry are different
- StoreWithoutWriteLoad,
- ), patch(
- "homeassistant.helpers.issue_registry.IssueRegistryStore",
- StoreWithoutWriteLoad,
- ), patch(
- "homeassistant.helpers.restore_state.RestoreStateData.async_setup_dump",
- return_value=None,
- ), patch(
- "homeassistant.helpers.restore_state.start.async_at_start",
+ with (
+ patch.object(StoreWithoutWriteLoad, "async_load", return_value=None),
+ patch(
+ "homeassistant.helpers.area_registry.AreaRegistryStore",
+ StoreWithoutWriteLoad,
+ ),
+ patch(
+ "homeassistant.helpers.device_registry.DeviceRegistryStore",
+ StoreWithoutWriteLoad,
+ ),
+ patch(
+ "homeassistant.helpers.entity_registry.EntityRegistryStore",
+ StoreWithoutWriteLoad,
+ ),
+ patch(
+ "homeassistant.helpers.storage.Store", # Floor & label registry are different
+ StoreWithoutWriteLoad,
+ ),
+ patch(
+ "homeassistant.helpers.issue_registry.IssueRegistryStore",
+ StoreWithoutWriteLoad,
+ ),
+ patch(
+ "homeassistant.helpers.restore_state.RestoreStateData.async_setup_dump",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.helpers.restore_state.start.async_at_start",
+ ),
):
await ar.async_load(hass)
await cr.async_load(hass)
@@ -517,12 +524,15 @@ def _async_fire_time_changed(
future_seconds = task.when() - (hass.loop.time() + _MONOTONIC_RESOLUTION)
if fire_all or mock_seconds_into_future >= future_seconds:
- with patch(
- "homeassistant.helpers.event.time_tracker_utcnow",
- return_value=utc_datetime,
- ), patch(
- "homeassistant.helpers.event.time_tracker_timestamp",
- return_value=timestamp,
+ with (
+ patch(
+ "homeassistant.helpers.event.time_tracker_utcnow",
+ return_value=utc_datetime,
+ ),
+ patch(
+ "homeassistant.helpers.event.time_tracker_timestamp",
+ return_value=timestamp,
+ ),
):
task._run()
task.cancel()
@@ -1377,18 +1387,22 @@ def mock_storage(
"""Remove data."""
data.pop(store.key, None)
- with patch(
- "homeassistant.helpers.storage.Store._async_load",
- side_effect=mock_async_load,
- autospec=True,
- ), patch(
- "homeassistant.helpers.storage.Store._async_write_data",
- side_effect=mock_write_data,
- autospec=True,
- ), patch(
- "homeassistant.helpers.storage.Store.async_remove",
- side_effect=mock_remove,
- autospec=True,
+ with (
+ patch(
+ "homeassistant.helpers.storage.Store._async_load",
+ side_effect=mock_async_load,
+ autospec=True,
+ ),
+ patch(
+ "homeassistant.helpers.storage.Store._async_write_data",
+ side_effect=mock_write_data,
+ autospec=True,
+ ),
+ patch(
+ "homeassistant.helpers.storage.Store.async_remove",
+ side_effect=mock_remove,
+ autospec=True,
+ ),
):
yield data
diff --git a/tests/components/abode/common.py b/tests/components/abode/common.py
index 20739cf58a1..22ee95cfa57 100644
--- a/tests/components/abode/common.py
+++ b/tests/components/abode/common.py
@@ -23,8 +23,9 @@ async def setup_platform(hass: HomeAssistant, platform: str) -> MockConfigEntry:
)
mock_entry.add_to_hass(hass)
- with patch("homeassistant.components.abode.PLATFORMS", [platform]), patch(
- "jaraco.abode.event_controller.sio"
+ with (
+ patch("homeassistant.components.abode.PLATFORMS", [platform]),
+ patch("jaraco.abode.event_controller.sio"),
):
assert await async_setup_component(hass, ABODE_DOMAIN, {})
await hass.async_block_till_done()
diff --git a/tests/components/abode/test_init.py b/tests/components/abode/test_init.py
index e23fa5aa1b9..e6e5da35a5e 100644
--- a/tests/components/abode/test_init.py
+++ b/tests/components/abode/test_init.py
@@ -57,9 +57,10 @@ async def test_unload_entry(hass: HomeAssistant) -> None:
"""Test unloading the Abode entry."""
mock_entry = await setup_platform(hass, ALARM_DOMAIN)
- with patch("jaraco.abode.client.Client.logout") as mock_logout, patch(
- "jaraco.abode.event_controller.EventController.stop"
- ) as mock_events_stop:
+ with (
+ patch("jaraco.abode.client.Client.logout") as mock_logout,
+ patch("jaraco.abode.event_controller.EventController.stop") as mock_events_stop,
+ ):
assert await hass.config_entries.async_unload(mock_entry.entry_id)
mock_logout.assert_called_once()
mock_events_stop.assert_called_once()
@@ -71,19 +72,22 @@ async def test_unload_entry(hass: HomeAssistant) -> None:
async def test_invalid_credentials(hass: HomeAssistant) -> None:
"""Test Abode credentials changing."""
- with patch(
- "homeassistant.components.abode.Abode",
- side_effect=AbodeAuthenticationException(
- (HTTPStatus.BAD_REQUEST, "auth error")
+ with (
+ patch(
+ "homeassistant.components.abode.Abode",
+ side_effect=AbodeAuthenticationException(
+ (HTTPStatus.BAD_REQUEST, "auth error")
+ ),
),
- ), patch(
- "homeassistant.components.abode.config_flow.AbodeFlowHandler.async_step_reauth",
- return_value={
- "type": data_entry_flow.FlowResultType.FORM,
- "flow_id": "mock_flow",
- "step_id": "reauth_confirm",
- },
- ) as mock_async_step_reauth:
+ patch(
+ "homeassistant.components.abode.config_flow.AbodeFlowHandler.async_step_reauth",
+ return_value={
+ "type": data_entry_flow.FlowResultType.FORM,
+ "flow_id": "mock_flow",
+ "step_id": "reauth_confirm",
+ },
+ ) as mock_async_step_reauth,
+ ):
await setup_platform(hass, ALARM_DOMAIN)
mock_async_step_reauth.assert_called_once()
diff --git a/tests/components/accuweather/__init__.py b/tests/components/accuweather/__init__.py
index 51ced2202bd..afaa5bbef25 100644
--- a/tests/components/accuweather/__init__.py
+++ b/tests/components/accuweather/__init__.py
@@ -38,16 +38,20 @@ async def init_integration(
if unsupported_icon:
current["WeatherIcon"] = 999
- with patch(
- "homeassistant.components.accuweather.AccuWeather.async_get_current_conditions",
- return_value=current,
- ), patch(
- "homeassistant.components.accuweather.AccuWeather.async_get_daily_forecast",
- return_value=forecast,
- ), patch(
- "homeassistant.components.accuweather.AccuWeather.requests_remaining",
- new_callable=PropertyMock,
- return_value=10,
+ with (
+ patch(
+ "homeassistant.components.accuweather.AccuWeather.async_get_current_conditions",
+ return_value=current,
+ ),
+ patch(
+ "homeassistant.components.accuweather.AccuWeather.async_get_daily_forecast",
+ return_value=forecast,
+ ),
+ patch(
+ "homeassistant.components.accuweather.AccuWeather.requests_remaining",
+ new_callable=PropertyMock,
+ return_value=10,
+ ),
):
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
diff --git a/tests/components/accuweather/test_config_flow.py b/tests/components/accuweather/test_config_flow.py
index bb338618ccc..c9d95c34b7c 100644
--- a/tests/components/accuweather/test_config_flow.py
+++ b/tests/components/accuweather/test_config_flow.py
@@ -119,11 +119,14 @@ async def test_integration_already_exists(hass: HomeAssistant) -> None:
async def test_create_entry(hass: HomeAssistant) -> None:
"""Test that the user step works."""
- with patch(
- "homeassistant.components.accuweather.AccuWeather._async_get_data",
- return_value=load_json_object_fixture("accuweather/location_data.json"),
- ), patch(
- "homeassistant.components.accuweather.async_setup_entry", return_value=True
+ with (
+ patch(
+ "homeassistant.components.accuweather.AccuWeather._async_get_data",
+ return_value=load_json_object_fixture("accuweather/location_data.json"),
+ ),
+ patch(
+ "homeassistant.components.accuweather.async_setup_entry", return_value=True
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -148,20 +151,25 @@ async def test_options_flow(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.accuweather.AccuWeather._async_get_data",
- return_value=load_json_object_fixture("accuweather/location_data.json"),
- ), patch(
- "homeassistant.components.accuweather.AccuWeather.async_get_current_conditions",
- return_value=load_json_object_fixture(
- "accuweather/current_conditions_data.json"
+ with (
+ patch(
+ "homeassistant.components.accuweather.AccuWeather._async_get_data",
+ return_value=load_json_object_fixture("accuweather/location_data.json"),
+ ),
+ patch(
+ "homeassistant.components.accuweather.AccuWeather.async_get_current_conditions",
+ return_value=load_json_object_fixture(
+ "accuweather/current_conditions_data.json"
+ ),
+ ),
+ patch(
+ "homeassistant.components.accuweather.AccuWeather.async_get_daily_forecast"
+ ),
+ patch(
+ "homeassistant.components.accuweather.AccuWeather.requests_remaining",
+ new_callable=PropertyMock,
+ return_value=10,
),
- ), patch(
- "homeassistant.components.accuweather.AccuWeather.async_get_daily_forecast"
- ), patch(
- "homeassistant.components.accuweather.AccuWeather.requests_remaining",
- new_callable=PropertyMock,
- return_value=10,
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/accuweather/test_init.py b/tests/components/accuweather/test_init.py
index 5f2f9f07a2f..bb5b67e7918 100644
--- a/tests/components/accuweather/test_init.py
+++ b/tests/components/accuweather/test_init.py
@@ -101,13 +101,16 @@ async def test_update_interval_forecast(hass: HomeAssistant) -> None:
forecast = load_json_array_fixture("accuweather/forecast_data.json")
future = utcnow() + timedelta(minutes=80)
- with patch(
- "homeassistant.components.accuweather.AccuWeather.async_get_current_conditions",
- return_value=current,
- ) as mock_current, patch(
- "homeassistant.components.accuweather.AccuWeather.async_get_daily_forecast",
- return_value=forecast,
- ) as mock_forecast:
+ with (
+ patch(
+ "homeassistant.components.accuweather.AccuWeather.async_get_current_conditions",
+ return_value=current,
+ ) as mock_current,
+ patch(
+ "homeassistant.components.accuweather.AccuWeather.async_get_daily_forecast",
+ return_value=forecast,
+ ) as mock_forecast,
+ ):
assert mock_current.call_count == 0
assert mock_forecast.call_count == 0
diff --git a/tests/components/accuweather/test_sensor.py b/tests/components/accuweather/test_sensor.py
index 6c93c21ccc0..8e6e01a4578 100644
--- a/tests/components/accuweather/test_sensor.py
+++ b/tests/components/accuweather/test_sensor.py
@@ -577,15 +577,18 @@ async def test_availability(hass: HomeAssistant) -> None:
assert state.state == STATE_UNAVAILABLE
future = utcnow() + timedelta(minutes=120)
- with patch(
- "homeassistant.components.accuweather.AccuWeather.async_get_current_conditions",
- return_value=load_json_object_fixture(
- "accuweather/current_conditions_data.json"
+ with (
+ patch(
+ "homeassistant.components.accuweather.AccuWeather.async_get_current_conditions",
+ return_value=load_json_object_fixture(
+ "accuweather/current_conditions_data.json"
+ ),
+ ),
+ patch(
+ "homeassistant.components.accuweather.AccuWeather.requests_remaining",
+ new_callable=PropertyMock,
+ return_value=10,
),
- ), patch(
- "homeassistant.components.accuweather.AccuWeather.requests_remaining",
- new_callable=PropertyMock,
- return_value=10,
):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
@@ -605,16 +608,20 @@ async def test_manual_update_entity(hass: HomeAssistant) -> None:
current = load_json_object_fixture("accuweather/current_conditions_data.json")
forecast = load_json_array_fixture("accuweather/forecast_data.json")
- with patch(
- "homeassistant.components.accuweather.AccuWeather.async_get_current_conditions",
- return_value=current,
- ) as mock_current, patch(
- "homeassistant.components.accuweather.AccuWeather.async_get_daily_forecast",
- return_value=forecast,
- ) as mock_forecast, patch(
- "homeassistant.components.accuweather.AccuWeather.requests_remaining",
- new_callable=PropertyMock,
- return_value=10,
+ with (
+ patch(
+ "homeassistant.components.accuweather.AccuWeather.async_get_current_conditions",
+ return_value=current,
+ ) as mock_current,
+ patch(
+ "homeassistant.components.accuweather.AccuWeather.async_get_daily_forecast",
+ return_value=forecast,
+ ) as mock_forecast,
+ patch(
+ "homeassistant.components.accuweather.AccuWeather.requests_remaining",
+ new_callable=PropertyMock,
+ return_value=10,
+ ),
):
await hass.services.async_call(
"homeassistant",
@@ -665,13 +672,16 @@ async def test_state_update(hass: HomeAssistant) -> None:
)
current_condition["Ceiling"]["Metric"]["Value"] = 3300
- with patch(
- "homeassistant.components.accuweather.AccuWeather.async_get_current_conditions",
- return_value=current_condition,
- ), patch(
- "homeassistant.components.accuweather.AccuWeather.requests_remaining",
- new_callable=PropertyMock,
- return_value=10,
+ with (
+ patch(
+ "homeassistant.components.accuweather.AccuWeather.async_get_current_conditions",
+ return_value=current_condition,
+ ),
+ patch(
+ "homeassistant.components.accuweather.AccuWeather.requests_remaining",
+ new_callable=PropertyMock,
+ return_value=10,
+ ),
):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
diff --git a/tests/components/accuweather/test_weather.py b/tests/components/accuweather/test_weather.py
index 2b2c304f948..291c1c1dcdf 100644
--- a/tests/components/accuweather/test_weather.py
+++ b/tests/components/accuweather/test_weather.py
@@ -152,15 +152,18 @@ async def test_availability(hass: HomeAssistant) -> None:
assert state.state == STATE_UNAVAILABLE
future = utcnow() + timedelta(minutes=120)
- with patch(
- "homeassistant.components.accuweather.AccuWeather.async_get_current_conditions",
- return_value=load_json_object_fixture(
- "accuweather/current_conditions_data.json"
+ with (
+ patch(
+ "homeassistant.components.accuweather.AccuWeather.async_get_current_conditions",
+ return_value=load_json_object_fixture(
+ "accuweather/current_conditions_data.json"
+ ),
+ ),
+ patch(
+ "homeassistant.components.accuweather.AccuWeather.requests_remaining",
+ new_callable=PropertyMock,
+ return_value=10,
),
- ), patch(
- "homeassistant.components.accuweather.AccuWeather.requests_remaining",
- new_callable=PropertyMock,
- return_value=10,
):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
@@ -180,16 +183,20 @@ async def test_manual_update_entity(hass: HomeAssistant) -> None:
current = load_json_object_fixture("accuweather/current_conditions_data.json")
forecast = load_json_array_fixture("accuweather/forecast_data.json")
- with patch(
- "homeassistant.components.accuweather.AccuWeather.async_get_current_conditions",
- return_value=current,
- ) as mock_current, patch(
- "homeassistant.components.accuweather.AccuWeather.async_get_daily_forecast",
- return_value=forecast,
- ) as mock_forecast, patch(
- "homeassistant.components.accuweather.AccuWeather.requests_remaining",
- new_callable=PropertyMock,
- return_value=10,
+ with (
+ patch(
+ "homeassistant.components.accuweather.AccuWeather.async_get_current_conditions",
+ return_value=current,
+ ) as mock_current,
+ patch(
+ "homeassistant.components.accuweather.AccuWeather.async_get_daily_forecast",
+ return_value=forecast,
+ ) as mock_forecast,
+ patch(
+ "homeassistant.components.accuweather.AccuWeather.requests_remaining",
+ new_callable=PropertyMock,
+ return_value=10,
+ ),
):
await hass.services.async_call(
"homeassistant",
@@ -271,16 +278,20 @@ async def test_forecast_subscription(
current = load_json_object_fixture("accuweather/current_conditions_data.json")
forecast = load_json_array_fixture("accuweather/forecast_data.json")
- with patch(
- "homeassistant.components.accuweather.AccuWeather.async_get_current_conditions",
- return_value=current,
- ), patch(
- "homeassistant.components.accuweather.AccuWeather.async_get_daily_forecast",
- return_value=forecast,
- ), patch(
- "homeassistant.components.accuweather.AccuWeather.requests_remaining",
- new_callable=PropertyMock,
- return_value=10,
+ with (
+ patch(
+ "homeassistant.components.accuweather.AccuWeather.async_get_current_conditions",
+ return_value=current,
+ ),
+ patch(
+ "homeassistant.components.accuweather.AccuWeather.async_get_daily_forecast",
+ return_value=forecast,
+ ),
+ patch(
+ "homeassistant.components.accuweather.AccuWeather.requests_remaining",
+ new_callable=PropertyMock,
+ return_value=10,
+ ),
):
freezer.tick(timedelta(minutes=80) + timedelta(seconds=1))
await hass.async_block_till_done()
diff --git a/tests/components/adax/test_config_flow.py b/tests/components/adax/test_config_flow.py
index 1189258d81d..b2342b7c2a7 100644
--- a/tests/components/adax/test_config_flow.py
+++ b/tests/components/adax/test_config_flow.py
@@ -42,13 +42,16 @@ async def test_form(hass: HomeAssistant) -> None:
)
assert result2["type"] == FlowResultType.FORM
- with patch(
- "adax.get_adax_token",
- return_value="test_token",
- ), patch(
- "homeassistant.components.adax.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "adax.get_adax_token",
+ return_value="test_token",
+ ),
+ patch(
+ "homeassistant.components.adax.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
TEST_DATA,
@@ -149,12 +152,16 @@ async def test_local_create_entry(hass: HomeAssistant) -> None:
WIFI_PSWD: "pswd",
}
- with patch(
- "homeassistant.components.adax.async_setup_entry",
- return_value=True,
- ), patch(
- "homeassistant.components.adax.config_flow.adax_local.AdaxConfig", autospec=True
- ) as mock_client_class:
+ with (
+ patch(
+ "homeassistant.components.adax.async_setup_entry",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.adax.config_flow.adax_local.AdaxConfig",
+ autospec=True,
+ ) as mock_client_class,
+ ):
client = mock_client_class.return_value
client.configure_device.return_value = True
client.device_ip = "192.168.1.4"
diff --git a/tests/components/advantage_air/test_config_flow.py b/tests/components/advantage_air/test_config_flow.py
index f5f972a9884..134cfee9f68 100644
--- a/tests/components/advantage_air/test_config_flow.py
+++ b/tests/components/advantage_air/test_config_flow.py
@@ -21,13 +21,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result1["step_id"] == "user"
assert result1["errors"] == {}
- with patch(
- "homeassistant.components.advantage_air.config_flow.advantage_air.async_get",
- new=AsyncMock(return_value=TEST_SYSTEM_DATA),
- ) as mock_get, patch(
- "homeassistant.components.advantage_air.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.advantage_air.config_flow.advantage_air.async_get",
+ new=AsyncMock(return_value=TEST_SYSTEM_DATA),
+ ) as mock_get,
+ patch(
+ "homeassistant.components.advantage_air.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result1["flow_id"],
USER_INPUT,
diff --git a/tests/components/airnow/conftest.py b/tests/components/airnow/conftest.py
index a374168df6a..1010a45b8fb 100644
--- a/tests/components/airnow/conftest.py
+++ b/tests/components/airnow/conftest.py
@@ -59,7 +59,8 @@ def mock_api_get_fixture(data):
@pytest.fixture(name="setup_airnow")
async def setup_airnow_fixture(hass, config, mock_api_get):
"""Define a fixture to set up AirNow."""
- with patch("pyairnow.WebServiceAPI._get", mock_api_get), patch(
- "homeassistant.components.airnow.PLATFORMS", []
+ with (
+ patch("pyairnow.WebServiceAPI._get", mock_api_get),
+ patch("homeassistant.components.airnow.PLATFORMS", []),
):
yield
diff --git a/tests/components/airq/test_config_flow.py b/tests/components/airq/test_config_flow.py
index 8069ce4450d..9c5492eaa20 100644
--- a/tests/components/airq/test_config_flow.py
+++ b/tests/components/airq/test_config_flow.py
@@ -37,8 +37,9 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with patch("aioairq.AirQ.validate"), patch(
- "aioairq.AirQ.fetch_device_info", return_value=TEST_DEVICE_INFO
+ with (
+ patch("aioairq.AirQ.validate"),
+ patch("aioairq.AirQ.fetch_device_info", return_value=TEST_DEVICE_INFO),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -93,8 +94,9 @@ async def test_duplicate_error(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch("aioairq.AirQ.validate"), patch(
- "aioairq.AirQ.fetch_device_info", return_value=TEST_DEVICE_INFO
+ with (
+ patch("aioairq.AirQ.validate"),
+ patch("aioairq.AirQ.fetch_device_info", return_value=TEST_DEVICE_INFO),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], TEST_USER_DATA
diff --git a/tests/components/airthings/test_config_flow.py b/tests/components/airthings/test_config_flow.py
index f685f4c021c..2ea157f09b1 100644
--- a/tests/components/airthings/test_config_flow.py
+++ b/tests/components/airthings/test_config_flow.py
@@ -27,13 +27,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with patch(
- "airthings.get_token",
- return_value="test_token",
- ), patch(
- "homeassistant.components.airthings.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "airthings.get_token",
+ return_value="test_token",
+ ),
+ patch(
+ "homeassistant.components.airthings.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
TEST_DATA,
diff --git a/tests/components/airthings_ble/test_config_flow.py b/tests/components/airthings_ble/test_config_flow.py
index 792ac2ad7ab..edeb08abb74 100644
--- a/tests/components/airthings_ble/test_config_flow.py
+++ b/tests/components/airthings_ble/test_config_flow.py
@@ -26,13 +26,16 @@ from tests.common import MockConfigEntry
async def test_bluetooth_discovery(hass: HomeAssistant) -> None:
"""Test discovery via bluetooth with a valid device."""
- with patch_async_ble_device_from_address(WAVE_SERVICE_INFO), patch_airthings_ble(
- AirthingsDevice(
- manufacturer="Airthings AS",
- model=AirthingsDeviceType.WAVE_PLUS,
- name="Airthings Wave Plus",
- identifier="123456",
- )
+ with (
+ patch_async_ble_device_from_address(WAVE_SERVICE_INFO),
+ patch_airthings_ble(
+ AirthingsDevice(
+ manufacturer="Airthings AS",
+ model=AirthingsDeviceType.WAVE_PLUS,
+ name="Airthings Wave Plus",
+ identifier="123456",
+ )
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -74,9 +77,10 @@ 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
- ), 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},
@@ -105,16 +109,20 @@ async def test_bluetooth_discovery_already_setup(hass: HomeAssistant) -> None:
async def test_user_setup(hass: HomeAssistant) -> None:
"""Test the user initiated form."""
- 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(
- AirthingsDevice(
- manufacturer="Airthings AS",
- model=AirthingsDeviceType.WAVE_PLUS,
- name="Airthings Wave Plus",
- identifier="123456",
- )
+ 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(
+ AirthingsDevice(
+ manufacturer="Airthings AS",
+ model=AirthingsDeviceType.WAVE_PLUS,
+ name="Airthings Wave Plus",
+ identifier="123456",
+ )
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
@@ -176,11 +184,13 @@ async def test_user_setup_existing_and_unknown_device(hass: HomeAssistant) -> No
async def test_user_setup_unknown_error(hass: HomeAssistant) -> None:
"""Test the user initiated form with an unknown error."""
- 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(
+ "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()),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
@@ -192,11 +202,13 @@ async def test_user_setup_unknown_error(hass: HomeAssistant) -> None:
async def test_user_setup_unable_to_connect(hass: HomeAssistant) -> None:
"""Test the user initiated form with a device that's failing connection."""
- 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(
+ "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")),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
diff --git a/tests/components/airtouch4/test_config_flow.py b/tests/components/airtouch4/test_config_flow.py
index a75312bc55b..e5e3672f69d 100644
--- a/tests/components/airtouch4/test_config_flow.py
+++ b/tests/components/airtouch4/test_config_flow.py
@@ -24,13 +24,16 @@ async def test_form(hass: HomeAssistant) -> None:
mock_airtouch.GetAcs = Mock(return_value=[mock_ac])
mock_airtouch.GetGroups = Mock(return_value=[mock_groups])
- with patch(
- "homeassistant.components.airtouch4.config_flow.AirTouch",
- return_value=mock_airtouch,
- ), patch(
- "homeassistant.components.airtouch4.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.airtouch4.config_flow.AirTouch",
+ return_value=mock_airtouch,
+ ),
+ patch(
+ "homeassistant.components.airtouch4.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": "0.0.0.1"}
)
diff --git a/tests/components/airvisual/conftest.py b/tests/components/airvisual/conftest.py
index dde75738e80..1538af28a08 100644
--- a/tests/components/airvisual/conftest.py
+++ b/tests/components/airvisual/conftest.py
@@ -113,18 +113,23 @@ def integration_type_fixture():
@pytest.fixture(name="mock_pyairvisual")
async def mock_pyairvisual_fixture(cloud_api, node_samba):
"""Define a fixture to patch pyairvisual."""
- with patch(
- "homeassistant.components.airvisual.CloudAPI",
- return_value=cloud_api,
- ), patch(
- "homeassistant.components.airvisual.config_flow.CloudAPI",
- return_value=cloud_api,
- ), patch(
- "homeassistant.components.airvisual_pro.NodeSamba",
- return_value=node_samba,
- ), patch(
- "homeassistant.components.airvisual_pro.config_flow.NodeSamba",
- return_value=node_samba,
+ with (
+ patch(
+ "homeassistant.components.airvisual.CloudAPI",
+ return_value=cloud_api,
+ ),
+ patch(
+ "homeassistant.components.airvisual.config_flow.CloudAPI",
+ return_value=cloud_api,
+ ),
+ patch(
+ "homeassistant.components.airvisual_pro.NodeSamba",
+ return_value=node_samba,
+ ),
+ patch(
+ "homeassistant.components.airvisual_pro.config_flow.NodeSamba",
+ return_value=node_samba,
+ ),
):
yield
diff --git a/tests/components/airvisual_pro/conftest.py b/tests/components/airvisual_pro/conftest.py
index 34426e8e9c8..719b25b3cdf 100644
--- a/tests/components/airvisual_pro/conftest.py
+++ b/tests/components/airvisual_pro/conftest.py
@@ -75,11 +75,14 @@ def pro_fixture(connect, data, disconnect):
@pytest.fixture(name="setup_airvisual_pro")
async def setup_airvisual_pro_fixture(hass, config, pro):
"""Define a fixture to set up AirVisual Pro."""
- with patch(
- "homeassistant.components.airvisual_pro.config_flow.NodeSamba", return_value=pro
- ), patch(
- "homeassistant.components.airvisual_pro.NodeSamba", return_value=pro
- ), patch("homeassistant.components.airvisual.PLATFORMS", []):
+ with (
+ patch(
+ "homeassistant.components.airvisual_pro.config_flow.NodeSamba",
+ return_value=pro,
+ ),
+ patch("homeassistant.components.airvisual_pro.NodeSamba", return_value=pro),
+ patch("homeassistant.components.airvisual.PLATFORMS", []),
+ ):
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
yield
diff --git a/tests/components/airzone/test_climate.py b/tests/components/airzone/test_climate.py
index 07d7f3127fa..fa972bd3899 100644
--- a/tests/components/airzone/test_climate.py
+++ b/tests/components/airzone/test_climate.py
@@ -229,18 +229,23 @@ async def test_airzone_create_climates(hass: HomeAssistant) -> None:
HVAC_MOCK_CHANGED[API_SYSTEMS][0][API_DATA][0][API_MAX_TEMP] = 25
HVAC_MOCK_CHANGED[API_SYSTEMS][0][API_DATA][0][API_MIN_TEMP] = 10
- with patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_dhw",
- return_value=HVAC_DHW_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_hvac",
- return_value=HVAC_MOCK_CHANGED,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_hvac_systems",
- return_value=HVAC_SYSTEMS_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_webserver",
- return_value=HVAC_WEBSERVER_MOCK,
+ with (
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_dhw",
+ return_value=HVAC_DHW_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_hvac",
+ return_value=HVAC_MOCK_CHANGED,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_hvac_systems",
+ return_value=HVAC_SYSTEMS_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_webserver",
+ return_value=HVAC_WEBSERVER_MOCK,
+ ),
):
async_fire_time_changed(hass, utcnow() + SCAN_INTERVAL)
await hass.async_block_till_done()
@@ -443,18 +448,23 @@ async def test_airzone_climate_set_hvac_mode(hass: HomeAssistant) -> None:
HVAC_MOCK_NO_SET_POINT = copy.deepcopy(HVAC_MOCK)
del HVAC_MOCK_NO_SET_POINT[API_SYSTEMS][0][API_DATA][0][API_SET_POINT]
- with patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_dhw",
- return_value=HVAC_DHW_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_hvac",
- return_value=HVAC_MOCK_NO_SET_POINT,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_hvac_systems",
- return_value=HVAC_SYSTEMS_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_webserver",
- return_value=HVAC_WEBSERVER_MOCK,
+ with (
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_dhw",
+ return_value=HVAC_DHW_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_hvac",
+ return_value=HVAC_MOCK_NO_SET_POINT,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_hvac_systems",
+ return_value=HVAC_SYSTEMS_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_webserver",
+ return_value=HVAC_WEBSERVER_MOCK,
+ ),
):
async_fire_time_changed(hass, utcnow() + SCAN_INTERVAL)
await hass.async_block_till_done()
@@ -478,10 +488,13 @@ async def test_airzone_climate_set_hvac_slave_error(hass: HomeAssistant) -> None
await async_init_integration(hass)
- with patch(
- "homeassistant.components.airzone.AirzoneLocalApi.put_hvac",
- return_value=HVAC_MOCK,
- ), pytest.raises(HomeAssistantError):
+ with (
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.put_hvac",
+ return_value=HVAC_MOCK,
+ ),
+ pytest.raises(HomeAssistantError),
+ ):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_HVAC_MODE,
@@ -570,10 +583,13 @@ async def test_airzone_climate_set_temp_error(hass: HomeAssistant) -> None:
await async_init_integration(hass)
- with patch(
- "homeassistant.components.airzone.AirzoneLocalApi.put_hvac",
- side_effect=AirzoneError,
- ), pytest.raises(HomeAssistantError):
+ with (
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.put_hvac",
+ side_effect=AirzoneError,
+ ),
+ pytest.raises(HomeAssistantError),
+ ):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
diff --git a/tests/components/airzone/test_config_flow.py b/tests/components/airzone/test_config_flow.py
index cd1190c2af5..c47e2b1a3dd 100644
--- a/tests/components/airzone/test_config_flow.py
+++ b/tests/components/airzone/test_config_flow.py
@@ -46,24 +46,31 @@ TEST_PORT = 3000
async def test_form(hass: HomeAssistant) -> None:
"""Test that the form is served with valid input."""
- with patch(
- "homeassistant.components.airzone.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_dhw",
- return_value=HVAC_DHW_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_hvac",
- return_value=HVAC_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_hvac_systems",
- side_effect=SystemOutOfRange,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_version",
- return_value=HVAC_VERSION_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_webserver",
- return_value=HVAC_WEBSERVER_MOCK,
+ with (
+ patch(
+ "homeassistant.components.airzone.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_dhw",
+ return_value=HVAC_DHW_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_hvac",
+ return_value=HVAC_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_hvac_systems",
+ side_effect=SystemOutOfRange,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_version",
+ return_value=HVAC_VERSION_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_webserver",
+ return_value=HVAC_WEBSERVER_MOCK,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
@@ -95,24 +102,31 @@ async def test_form(hass: HomeAssistant) -> None:
async def test_form_invalid_system_id(hass: HomeAssistant) -> None:
"""Test Invalid System ID 0."""
- with patch(
- "homeassistant.components.airzone.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_dhw",
- side_effect=HotWaterNotAvailable,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_hvac",
- side_effect=InvalidSystem,
- ) as mock_hvac, patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_hvac_systems",
- side_effect=SystemOutOfRange,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_version",
- return_value=HVAC_VERSION_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_webserver",
- side_effect=InvalidMethod,
+ with (
+ patch(
+ "homeassistant.components.airzone.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_dhw",
+ side_effect=HotWaterNotAvailable,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_hvac",
+ side_effect=InvalidSystem,
+ ) as mock_hvac,
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_hvac_systems",
+ side_effect=SystemOutOfRange,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_version",
+ return_value=HVAC_VERSION_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_webserver",
+ side_effect=InvalidMethod,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=CONFIG
@@ -197,24 +211,31 @@ async def test_dhcp_flow(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "discovered_connection"
- with patch(
- "homeassistant.components.airzone.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_dhw",
- return_value=HVAC_DHW_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_hvac",
- return_value=HVAC_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_hvac_systems",
- side_effect=SystemOutOfRange,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_version",
- return_value=HVAC_VERSION_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_webserver",
- return_value=HVAC_WEBSERVER_MOCK,
+ with (
+ patch(
+ "homeassistant.components.airzone.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_dhw",
+ return_value=HVAC_DHW_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_hvac",
+ return_value=HVAC_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_hvac_systems",
+ side_effect=SystemOutOfRange,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_version",
+ return_value=HVAC_VERSION_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_webserver",
+ return_value=HVAC_WEBSERVER_MOCK,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -278,24 +299,31 @@ async def test_dhcp_connection_error(hass: HomeAssistant) -> None:
assert result["errors"] == {"base": "cannot_connect"}
- with patch(
- "homeassistant.components.airzone.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_dhw",
- return_value=HVAC_DHW_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_hvac",
- return_value=HVAC_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_hvac_systems",
- side_effect=SystemOutOfRange,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_version",
- return_value=HVAC_VERSION_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_webserver",
- return_value=HVAC_WEBSERVER_MOCK,
+ with (
+ patch(
+ "homeassistant.components.airzone.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_dhw",
+ return_value=HVAC_DHW_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_hvac",
+ return_value=HVAC_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_hvac_systems",
+ side_effect=SystemOutOfRange,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_version",
+ return_value=HVAC_VERSION_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_webserver",
+ return_value=HVAC_WEBSERVER_MOCK,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -334,24 +362,31 @@ async def test_dhcp_invalid_system_id(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "discovered_connection"
- with patch(
- "homeassistant.components.airzone.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_dhw",
- side_effect=HotWaterNotAvailable,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_hvac",
- side_effect=InvalidSystem,
- ) as mock_hvac, patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_hvac_systems",
- side_effect=SystemOutOfRange,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_version",
- return_value=HVAC_VERSION_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_webserver",
- side_effect=InvalidMethod,
+ with (
+ patch(
+ "homeassistant.components.airzone.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_dhw",
+ side_effect=HotWaterNotAvailable,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_hvac",
+ side_effect=InvalidSystem,
+ ) as mock_hvac,
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_hvac_systems",
+ side_effect=SystemOutOfRange,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_version",
+ return_value=HVAC_VERSION_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_webserver",
+ side_effect=InvalidMethod,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/airzone/test_coordinator.py b/tests/components/airzone/test_coordinator.py
index 62f6a15fe35..06c77bebb81 100644
--- a/tests/components/airzone/test_coordinator.py
+++ b/tests/components/airzone/test_coordinator.py
@@ -30,21 +30,27 @@ async def test_coordinator_client_connector_error(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_dhw",
- side_effect=HotWaterNotAvailable,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_hvac",
- return_value=HVAC_MOCK,
- ) as mock_hvac, patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_hvac_systems",
- side_effect=SystemOutOfRange,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_version",
- return_value=HVAC_VERSION_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_webserver",
- side_effect=InvalidMethod,
+ with (
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_dhw",
+ side_effect=HotWaterNotAvailable,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_hvac",
+ return_value=HVAC_MOCK,
+ ) as mock_hvac,
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_hvac_systems",
+ side_effect=SystemOutOfRange,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_version",
+ return_value=HVAC_VERSION_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_webserver",
+ side_effect=InvalidMethod,
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/airzone/test_init.py b/tests/components/airzone/test_init.py
index 8936fa3e282..293fc75acb5 100644
--- a/tests/components/airzone/test_init.py
+++ b/tests/components/airzone/test_init.py
@@ -22,21 +22,27 @@ async def test_unique_id_migrate(
config_entry = MockConfigEntry(domain=DOMAIN, data=CONFIG)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_dhw",
- side_effect=HotWaterNotAvailable,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_hvac",
- return_value=HVAC_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_hvac_systems",
- side_effect=SystemOutOfRange,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_version",
- return_value=HVAC_VERSION_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_webserver",
- side_effect=InvalidMethod,
+ with (
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_dhw",
+ side_effect=HotWaterNotAvailable,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_hvac",
+ return_value=HVAC_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_hvac_systems",
+ side_effect=SystemOutOfRange,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_version",
+ return_value=HVAC_VERSION_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_webserver",
+ side_effect=InvalidMethod,
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -47,21 +53,27 @@ async def test_unique_id_migrate(
== f"{config_entry.entry_id}_1:1_temp"
)
- with patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_dhw",
- side_effect=HotWaterNotAvailable,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_hvac",
- return_value=HVAC_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_hvac_systems",
- side_effect=SystemOutOfRange,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_version",
- return_value=HVAC_VERSION_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_webserver",
- return_value=HVAC_WEBSERVER_MOCK,
+ with (
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_dhw",
+ side_effect=HotWaterNotAvailable,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_hvac",
+ return_value=HVAC_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_hvac_systems",
+ side_effect=SystemOutOfRange,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_version",
+ return_value=HVAC_VERSION_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_webserver",
+ return_value=HVAC_WEBSERVER_MOCK,
+ ),
):
await hass.config_entries.async_reload(config_entry.entry_id)
await hass.async_block_till_done()
@@ -83,12 +95,15 @@ async def test_unload_entry(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.airzone.AirzoneLocalApi.validate",
- return_value=None,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.update",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.validate",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.update",
+ return_value=None,
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/airzone/test_sensor.py b/tests/components/airzone/test_sensor.py
index 1511cd4362c..3d4c54522fc 100644
--- a/tests/components/airzone/test_sensor.py
+++ b/tests/components/airzone/test_sensor.py
@@ -91,21 +91,27 @@ async def test_airzone_sensors_availability(
HVAC_MOCK_UNAVAILABLE_ZONE = copy.deepcopy(HVAC_MOCK)
del HVAC_MOCK_UNAVAILABLE_ZONE[API_SYSTEMS][0][API_DATA][1]
- with patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_dhw",
- return_value=HVAC_DHW_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_hvac",
- return_value=HVAC_MOCK_UNAVAILABLE_ZONE,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_hvac_systems",
- return_value=HVAC_SYSTEMS_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_version",
- return_value=HVAC_VERSION_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_webserver",
- return_value=HVAC_WEBSERVER_MOCK,
+ with (
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_dhw",
+ return_value=HVAC_DHW_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_hvac",
+ return_value=HVAC_MOCK_UNAVAILABLE_ZONE,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_hvac_systems",
+ return_value=HVAC_SYSTEMS_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_version",
+ return_value=HVAC_VERSION_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_webserver",
+ return_value=HVAC_WEBSERVER_MOCK,
+ ),
):
async_fire_time_changed(hass, utcnow() + SCAN_INTERVAL)
await hass.async_block_till_done()
diff --git a/tests/components/airzone/test_water_heater.py b/tests/components/airzone/test_water_heater.py
index ca7344204cf..fa4507223e2 100644
--- a/tests/components/airzone/test_water_heater.py
+++ b/tests/components/airzone/test_water_heater.py
@@ -211,10 +211,13 @@ async def test_airzone_water_heater_set_temp_error(hass: HomeAssistant) -> None:
await async_init_integration(hass)
- with patch(
- "homeassistant.components.airzone.AirzoneLocalApi.put_hvac",
- side_effect=AirzoneError,
- ), pytest.raises(HomeAssistantError):
+ with (
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.put_hvac",
+ side_effect=AirzoneError,
+ ),
+ pytest.raises(HomeAssistantError),
+ ):
await hass.services.async_call(
WATER_HEATER_DOMAIN,
SERVICE_SET_TEMPERATURE,
diff --git a/tests/components/airzone/util.py b/tests/components/airzone/util.py
index f83eceaae9c..c5c2d5972d4 100644
--- a/tests/components/airzone/util.py
+++ b/tests/components/airzone/util.py
@@ -322,21 +322,27 @@ async def async_init_integration(
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_dhw",
- return_value=HVAC_DHW_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_hvac",
- return_value=HVAC_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_hvac_systems",
- return_value=HVAC_SYSTEMS_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_version",
- return_value=HVAC_VERSION_MOCK,
- ), patch(
- "homeassistant.components.airzone.AirzoneLocalApi.get_webserver",
- return_value=HVAC_WEBSERVER_MOCK,
+ with (
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_dhw",
+ return_value=HVAC_DHW_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_hvac",
+ return_value=HVAC_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_hvac_systems",
+ return_value=HVAC_SYSTEMS_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_version",
+ return_value=HVAC_VERSION_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone.AirzoneLocalApi.get_webserver",
+ return_value=HVAC_WEBSERVER_MOCK,
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/airzone_cloud/conftest.py b/tests/components/airzone_cloud/conftest.py
index a63ab18d7bc..b289efd3fb9 100644
--- a/tests/components/airzone_cloud/conftest.py
+++ b/tests/components/airzone_cloud/conftest.py
@@ -8,11 +8,14 @@ import pytest
@pytest.fixture(autouse=True)
def airzone_cloud_no_websockets():
"""Fixture to completely disable Airzone Cloud WebSockets."""
- with patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi._update_websockets",
- return_value=False,
- ), patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.connect_installation_websockets",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi._update_websockets",
+ return_value=False,
+ ),
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.connect_installation_websockets",
+ return_value=None,
+ ),
):
yield
diff --git a/tests/components/airzone_cloud/test_climate.py b/tests/components/airzone_cloud/test_climate.py
index 46fc16b07df..9bfaf5683a1 100644
--- a/tests/components/airzone_cloud/test_climate.py
+++ b/tests/components/airzone_cloud/test_climate.py
@@ -492,10 +492,13 @@ async def test_airzone_climate_set_hvac_slave_error(hass: HomeAssistant) -> None
await async_init_integration(hass)
- with patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_patch_device",
- return_value=None,
- ), pytest.raises(HomeAssistantError):
+ with (
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_patch_device",
+ return_value=None,
+ ),
+ pytest.raises(HomeAssistantError),
+ ):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_HVAC_MODE,
@@ -580,10 +583,13 @@ async def test_airzone_climate_set_temp_error(hass: HomeAssistant) -> None:
await async_init_integration(hass)
# Aidoos
- with patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_patch_device",
- side_effect=AirzoneCloudError,
- ), pytest.raises(HomeAssistantError):
+ with (
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_patch_device",
+ side_effect=AirzoneCloudError,
+ ),
+ pytest.raises(HomeAssistantError),
+ ):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
@@ -598,10 +604,13 @@ async def test_airzone_climate_set_temp_error(hass: HomeAssistant) -> None:
assert state.attributes[ATTR_TEMPERATURE] == 22.0
# Groups
- with patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_put_group",
- side_effect=AirzoneCloudError,
- ), pytest.raises(HomeAssistantError):
+ with (
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_put_group",
+ side_effect=AirzoneCloudError,
+ ),
+ pytest.raises(HomeAssistantError),
+ ):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
@@ -616,10 +625,13 @@ async def test_airzone_climate_set_temp_error(hass: HomeAssistant) -> None:
assert state.attributes[ATTR_TEMPERATURE] == 24.0
# Installations
- with patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_put_installation",
- side_effect=AirzoneCloudError,
- ), pytest.raises(HomeAssistantError):
+ with (
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_put_installation",
+ side_effect=AirzoneCloudError,
+ ),
+ pytest.raises(HomeAssistantError),
+ ):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
@@ -634,10 +646,13 @@ async def test_airzone_climate_set_temp_error(hass: HomeAssistant) -> None:
assert state.attributes[ATTR_TEMPERATURE] == 23.0
# Zones
- with patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_patch_device",
- side_effect=AirzoneCloudError,
- ), pytest.raises(HomeAssistantError):
+ with (
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_patch_device",
+ side_effect=AirzoneCloudError,
+ ),
+ pytest.raises(HomeAssistantError),
+ ):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
diff --git a/tests/components/airzone_cloud/test_config_flow.py b/tests/components/airzone_cloud/test_config_flow.py
index ec031d4bf25..e1d31e28d4b 100644
--- a/tests/components/airzone_cloud/test_config_flow.py
+++ b/tests/components/airzone_cloud/test_config_flow.py
@@ -23,24 +23,31 @@ from .util import (
async def test_form(hass: HomeAssistant) -> None:
"""Test that the form is served with valid input."""
- with patch(
- "homeassistant.components.airzone_cloud.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_device_status",
- side_effect=mock_get_device_status,
- ), patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_installation",
- return_value=GET_INSTALLATION_MOCK,
- ), patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_installations",
- return_value=GET_INSTALLATIONS_MOCK,
- ), patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_webserver",
- side_effect=mock_get_webserver,
- ), patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.login",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.components.airzone_cloud.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_device_status",
+ side_effect=mock_get_device_status,
+ ),
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_installation",
+ return_value=GET_INSTALLATION_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_installations",
+ return_value=GET_INSTALLATIONS_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_webserver",
+ side_effect=mock_get_webserver,
+ ),
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.login",
+ return_value=None,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
@@ -87,21 +94,27 @@ async def test_form(hass: HomeAssistant) -> None:
async def test_installations_list_error(hass: HomeAssistant) -> None:
"""Test connection error."""
- with patch(
- "homeassistant.components.airzone_cloud.async_setup_entry",
- return_value=True,
- ), patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_device_status",
- side_effect=mock_get_device_status,
- ), patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_installations",
- side_effect=AirzoneCloudError,
- ), patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_webserver",
- side_effect=mock_get_webserver,
- ), patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.login",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.components.airzone_cloud.async_setup_entry",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_device_status",
+ side_effect=mock_get_device_status,
+ ),
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_installations",
+ side_effect=AirzoneCloudError,
+ ),
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_webserver",
+ side_effect=mock_get_webserver,
+ ),
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.login",
+ return_value=None,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
diff --git a/tests/components/airzone_cloud/test_coordinator.py b/tests/components/airzone_cloud/test_coordinator.py
index 4b42ab7c329..b4b7afd6086 100644
--- a/tests/components/airzone_cloud/test_coordinator.py
+++ b/tests/components/airzone_cloud/test_coordinator.py
@@ -31,21 +31,27 @@ async def test_coordinator_client_connector_error(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_device_status",
- side_effect=mock_get_device_status,
- ) as mock_device_status, patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_installation",
- return_value=GET_INSTALLATION_MOCK,
- ) as mock_installation, patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_installations",
- return_value=GET_INSTALLATIONS_MOCK,
- ) as mock_installations, patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_webserver",
- side_effect=mock_get_webserver,
- ) as mock_webserver, patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.login",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_device_status",
+ side_effect=mock_get_device_status,
+ ) as mock_device_status,
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_installation",
+ return_value=GET_INSTALLATION_MOCK,
+ ) as mock_installation,
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_installations",
+ return_value=GET_INSTALLATIONS_MOCK,
+ ) as mock_installations,
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_webserver",
+ side_effect=mock_get_webserver,
+ ) as mock_webserver,
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.login",
+ return_value=None,
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/airzone_cloud/test_init.py b/tests/components/airzone_cloud/test_init.py
index f8a7a710e08..b5b4bcebaa8 100644
--- a/tests/components/airzone_cloud/test_init.py
+++ b/tests/components/airzone_cloud/test_init.py
@@ -21,21 +21,27 @@ async def test_unload_entry(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.login",
- return_value=None,
- ), patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.logout",
- return_value=None,
- ), patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.list_installations",
- return_value=[],
- ), patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.update_installation",
- return_value=None,
- ), patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.update",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.login",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.logout",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.list_installations",
+ return_value=[],
+ ),
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.update_installation",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.update",
+ return_value=None,
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/airzone_cloud/util.py b/tests/components/airzone_cloud/util.py
index 98ff7c65478..ea0dbf9f736 100644
--- a/tests/components/airzone_cloud/util.py
+++ b/tests/components/airzone_cloud/util.py
@@ -432,21 +432,27 @@ async def async_init_integration(
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_device_status",
- side_effect=mock_get_device_status,
- ), patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_installation",
- return_value=GET_INSTALLATION_MOCK,
- ), patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_installations",
- return_value=GET_INSTALLATIONS_MOCK,
- ), patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_webserver",
- side_effect=mock_get_webserver,
- ), patch(
- "homeassistant.components.airzone_cloud.AirzoneCloudApi.login",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_device_status",
+ side_effect=mock_get_device_status,
+ ),
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_installation",
+ return_value=GET_INSTALLATION_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_installations",
+ return_value=GET_INSTALLATIONS_MOCK,
+ ),
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.api_get_webserver",
+ side_effect=mock_get_webserver,
+ ),
+ patch(
+ "homeassistant.components.airzone_cloud.AirzoneCloudApi.login",
+ return_value=None,
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/aladdin_connect/test_config_flow.py b/tests/components/aladdin_connect/test_config_flow.py
index 2bdc05f57a3..90cf269b3f8 100644
--- a/tests/components/aladdin_connect/test_config_flow.py
+++ b/tests/components/aladdin_connect/test_config_flow.py
@@ -23,12 +23,16 @@ async def test_form(hass: HomeAssistant, mock_aladdinconnect_api: MagicMock) ->
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with patch(
- "homeassistant.components.aladdin_connect.config_flow.AladdinConnectClient",
- return_value=mock_aladdinconnect_api,
- ), patch(
- "homeassistant.components.aladdin_connect.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.aladdin_connect.config_flow.AladdinConnectClient",
+ return_value=mock_aladdinconnect_api,
+ ),
+ patch(
+ "homeassistant.components.aladdin_connect.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -158,12 +162,15 @@ async def test_reauth_flow(
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.aladdin_connect.async_setup_entry",
- return_value=True,
- ), patch(
- "homeassistant.components.aladdin_connect.config_flow.AladdinConnectClient",
- return_value=mock_aladdinconnect_api,
+ with (
+ patch(
+ "homeassistant.components.aladdin_connect.async_setup_entry",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.aladdin_connect.config_flow.AladdinConnectClient",
+ return_value=mock_aladdinconnect_api,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -206,15 +213,19 @@ async def test_reauth_flow_auth_error(
assert result["errors"] == {}
mock_aladdinconnect_api.login.return_value = False
mock_aladdinconnect_api.login.side_effect = InvalidPasswordError
- with patch(
- "homeassistant.components.aladdin_connect.config_flow.AladdinConnectClient",
- return_value=mock_aladdinconnect_api,
- ), patch(
- "homeassistant.components.aladdin_connect.cover.async_setup_entry",
- return_value=True,
- ), patch(
- "homeassistant.components.aladdin_connect.cover.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.aladdin_connect.config_flow.AladdinConnectClient",
+ return_value=mock_aladdinconnect_api,
+ ),
+ patch(
+ "homeassistant.components.aladdin_connect.cover.async_setup_entry",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.aladdin_connect.cover.async_setup_entry",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/aladdin_connect/test_init.py b/tests/components/aladdin_connect/test_init.py
index 8f0b40328e4..c995fb5074d 100644
--- a/tests/components/aladdin_connect/test_init.py
+++ b/tests/components/aladdin_connect/test_init.py
@@ -26,12 +26,15 @@ async def test_setup_get_doors_errors(hass: HomeAssistant) -> None:
unique_id="test-id",
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.aladdin_connect.cover.AladdinConnectClient.login",
- return_value=True,
- ), patch(
- "homeassistant.components.aladdin_connect.cover.AladdinConnectClient.get_doors",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.components.aladdin_connect.cover.AladdinConnectClient.login",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.aladdin_connect.cover.AladdinConnectClient.get_doors",
+ return_value=None,
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id) is True
await hass.async_block_till_done()
diff --git a/tests/components/alarmdecoder/test_config_flow.py b/tests/components/alarmdecoder/test_config_flow.py
index ce7fc1ef333..614d055405e 100644
--- a/tests/components/alarmdecoder/test_config_flow.py
+++ b/tests/components/alarmdecoder/test_config_flow.py
@@ -74,12 +74,14 @@ async def test_setups(hass: HomeAssistant, protocol, connection, title) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "protocol"
- with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch(
- "homeassistant.components.alarmdecoder.config_flow.AdExt.close"
- ), patch(
- "homeassistant.components.alarmdecoder.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"),
+ patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"),
+ patch(
+ "homeassistant.components.alarmdecoder.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], connection
)
@@ -117,20 +119,26 @@ async def test_setup_connection_error(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "protocol"
- with patch(
- "homeassistant.components.alarmdecoder.config_flow.AdExt.open",
- side_effect=NoDeviceError,
- ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"):
+ with (
+ patch(
+ "homeassistant.components.alarmdecoder.config_flow.AdExt.open",
+ side_effect=NoDeviceError,
+ ),
+ patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"),
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], connection_settings
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] == {"base": "cannot_connect"}
- with patch(
- "homeassistant.components.alarmdecoder.config_flow.AdExt.open",
- side_effect=Exception,
- ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"):
+ with (
+ patch(
+ "homeassistant.components.alarmdecoder.config_flow.AdExt.open",
+ side_effect=Exception,
+ ),
+ patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"),
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], connection_settings
)
diff --git a/tests/components/ambient_station/conftest.py b/tests/components/ambient_station/conftest.py
index 25b11740db6..adbd6777727 100644
--- a/tests/components/ambient_station/conftest.py
+++ b/tests/components/ambient_station/conftest.py
@@ -53,10 +53,13 @@ def data_station_fixture():
@pytest.fixture(name="mock_aioambient")
async def mock_aioambient_fixture(api):
"""Define a fixture to patch aioambient."""
- with patch(
- "homeassistant.components.ambient_station.config_flow.API",
- return_value=api,
- ), patch("aioambient.websocket.Websocket.connect"):
+ with (
+ patch(
+ "homeassistant.components.ambient_station.config_flow.API",
+ return_value=api,
+ ),
+ patch("aioambient.websocket.Websocket.connect"),
+ ):
yield
diff --git a/tests/components/analytics/test_analytics.py b/tests/components/analytics/test_analytics.py
index 7c380d7bbd3..da8d45d41ad 100644
--- a/tests/components/analytics/test_analytics.py
+++ b/tests/components/analytics/test_analytics.py
@@ -91,12 +91,15 @@ async def test_load_with_supervisor_diagnostics(hass: HomeAssistant) -> None:
"""Test loading with a supervisor that has diagnostics enabled."""
analytics = Analytics(hass)
assert not analytics.preferences[ATTR_DIAGNOSTICS]
- with patch(
- "homeassistant.components.hassio.get_supervisor_info",
- side_effect=Mock(return_value={"diagnostics": True}),
- ), patch(
- "homeassistant.components.hassio.is_hassio",
- side_effect=Mock(return_value=True),
+ with (
+ patch(
+ "homeassistant.components.hassio.get_supervisor_info",
+ side_effect=Mock(return_value={"diagnostics": True}),
+ ),
+ patch(
+ "homeassistant.components.hassio.is_hassio",
+ side_effect=Mock(return_value=True),
+ ),
):
await analytics.load()
assert analytics.preferences[ATTR_DIAGNOSTICS]
@@ -109,12 +112,15 @@ async def test_load_with_supervisor_without_diagnostics(hass: HomeAssistant) ->
assert analytics.preferences[ATTR_DIAGNOSTICS]
- with patch(
- "homeassistant.components.hassio.get_supervisor_info",
- side_effect=Mock(return_value={"diagnostics": False}),
- ), patch(
- "homeassistant.components.hassio.is_hassio",
- side_effect=Mock(return_value=True),
+ with (
+ patch(
+ "homeassistant.components.hassio.get_supervisor_info",
+ side_effect=Mock(return_value={"diagnostics": False}),
+ ),
+ patch(
+ "homeassistant.components.hassio.is_hassio",
+ side_effect=Mock(return_value=True),
+ ),
):
await analytics.load()
@@ -190,23 +196,29 @@ async def test_send_base_with_supervisor(
await analytics.save_preferences({ATTR_BASE: True})
assert analytics.preferences[ATTR_BASE]
- with patch(
- "homeassistant.components.hassio.get_supervisor_info",
- side_effect=Mock(
- return_value={"supported": True, "healthy": True, "arch": "amd64"}
+ with (
+ patch(
+ "homeassistant.components.hassio.get_supervisor_info",
+ side_effect=Mock(
+ return_value={"supported": True, "healthy": True, "arch": "amd64"}
+ ),
+ ),
+ patch(
+ "homeassistant.components.hassio.get_os_info",
+ side_effect=Mock(return_value={"board": "blue", "version": "123"}),
+ ),
+ patch(
+ "homeassistant.components.hassio.get_info",
+ side_effect=Mock(return_value={}),
+ ),
+ patch(
+ "homeassistant.components.hassio.get_host_info",
+ side_effect=Mock(return_value={}),
+ ),
+ patch(
+ "homeassistant.components.hassio.is_hassio",
+ side_effect=Mock(return_value=True),
),
- ), patch(
- "homeassistant.components.hassio.get_os_info",
- side_effect=Mock(return_value={"board": "blue", "version": "123"}),
- ), patch(
- "homeassistant.components.hassio.get_info",
- side_effect=Mock(return_value={}),
- ), patch(
- "homeassistant.components.hassio.get_host_info",
- side_effect=Mock(return_value={}),
- ), patch(
- "homeassistant.components.hassio.is_hassio",
- side_effect=Mock(return_value=True),
):
await analytics.load()
@@ -270,38 +282,45 @@ async def test_send_usage_with_supervisor(
assert analytics.preferences[ATTR_USAGE]
hass.config.components = ["default_config"]
- with patch(
- "homeassistant.components.hassio.get_supervisor_info",
- side_effect=Mock(
- return_value={
- "healthy": True,
- "supported": True,
- "arch": "amd64",
- "addons": [{"slug": "test_addon"}],
- }
+ with (
+ patch(
+ "homeassistant.components.hassio.get_supervisor_info",
+ side_effect=Mock(
+ return_value={
+ "healthy": True,
+ "supported": True,
+ "arch": "amd64",
+ "addons": [{"slug": "test_addon"}],
+ }
+ ),
),
- ), patch(
- "homeassistant.components.hassio.get_os_info",
- side_effect=Mock(return_value={}),
- ), patch(
- "homeassistant.components.hassio.get_info",
- side_effect=Mock(return_value={}),
- ), patch(
- "homeassistant.components.hassio.get_host_info",
- side_effect=Mock(return_value={}),
- ), patch(
- "homeassistant.components.hassio.async_get_addon_info",
- side_effect=AsyncMock(
- return_value={
- "slug": "test_addon",
- "protected": True,
- "version": "1",
- "auto_update": False,
- }
+ patch(
+ "homeassistant.components.hassio.get_os_info",
+ side_effect=Mock(return_value={}),
+ ),
+ patch(
+ "homeassistant.components.hassio.get_info",
+ side_effect=Mock(return_value={}),
+ ),
+ patch(
+ "homeassistant.components.hassio.get_host_info",
+ side_effect=Mock(return_value={}),
+ ),
+ patch(
+ "homeassistant.components.hassio.async_get_addon_info",
+ side_effect=AsyncMock(
+ return_value={
+ "slug": "test_addon",
+ "protected": True,
+ "version": "1",
+ "auto_update": False,
+ }
+ ),
+ ),
+ patch(
+ "homeassistant.components.hassio.is_hassio",
+ side_effect=Mock(return_value=True),
),
- ), patch(
- "homeassistant.components.hassio.is_hassio",
- side_effect=Mock(return_value=True),
):
await analytics.send_analytics()
@@ -461,9 +480,12 @@ async def test_send_statistics_async_get_integration_unknown_exception(
assert analytics.preferences[ATTR_STATISTICS]
hass.config.components = ["default_config"]
- with pytest.raises(ValueError), patch(
- "homeassistant.components.analytics.analytics.async_get_integrations",
- return_value={"any": ValueError()},
+ with (
+ pytest.raises(ValueError),
+ patch(
+ "homeassistant.components.analytics.analytics.async_get_integrations",
+ return_value={"any": ValueError()},
+ ),
):
await analytics.send_analytics()
@@ -482,38 +504,45 @@ async def test_send_statistics_with_supervisor(
assert analytics.preferences[ATTR_BASE]
assert analytics.preferences[ATTR_STATISTICS]
- with patch(
- "homeassistant.components.hassio.get_supervisor_info",
- side_effect=Mock(
- return_value={
- "healthy": True,
- "supported": True,
- "arch": "amd64",
- "addons": [{"slug": "test_addon"}],
- }
+ with (
+ patch(
+ "homeassistant.components.hassio.get_supervisor_info",
+ side_effect=Mock(
+ return_value={
+ "healthy": True,
+ "supported": True,
+ "arch": "amd64",
+ "addons": [{"slug": "test_addon"}],
+ }
+ ),
),
- ), patch(
- "homeassistant.components.hassio.get_os_info",
- side_effect=Mock(return_value={}),
- ), patch(
- "homeassistant.components.hassio.get_info",
- side_effect=Mock(return_value={}),
- ), patch(
- "homeassistant.components.hassio.get_host_info",
- side_effect=Mock(return_value={}),
- ), patch(
- "homeassistant.components.hassio.async_get_addon_info",
- side_effect=AsyncMock(
- return_value={
- "slug": "test_addon",
- "protected": True,
- "version": "1",
- "auto_update": False,
- }
+ patch(
+ "homeassistant.components.hassio.get_os_info",
+ side_effect=Mock(return_value={}),
+ ),
+ patch(
+ "homeassistant.components.hassio.get_info",
+ side_effect=Mock(return_value={}),
+ ),
+ patch(
+ "homeassistant.components.hassio.get_host_info",
+ side_effect=Mock(return_value={}),
+ ),
+ patch(
+ "homeassistant.components.hassio.async_get_addon_info",
+ side_effect=AsyncMock(
+ return_value={
+ "slug": "test_addon",
+ "protected": True,
+ "version": "1",
+ "auto_update": False,
+ }
+ ),
+ ),
+ patch(
+ "homeassistant.components.hassio.is_hassio",
+ side_effect=Mock(return_value=True),
),
- ), patch(
- "homeassistant.components.hassio.is_hassio",
- side_effect=Mock(return_value=True),
):
await analytics.send_analytics()
@@ -641,12 +670,16 @@ async def test_send_with_no_energy(
await analytics.save_preferences({ATTR_BASE: True, ATTR_USAGE: True})
- with patch(
- "homeassistant.components.analytics.analytics.energy_is_configured", AsyncMock()
- ) as energy_is_configured, patch(
- "homeassistant.components.analytics.analytics.get_recorder_instance",
- Mock(),
- ) as get_recorder_instance:
+ with (
+ patch(
+ "homeassistant.components.analytics.analytics.energy_is_configured",
+ AsyncMock(),
+ ) as energy_is_configured,
+ patch(
+ "homeassistant.components.analytics.analytics.get_recorder_instance",
+ Mock(),
+ ) as get_recorder_instance,
+ ):
energy_is_configured.return_value = False
get_recorder_instance.return_value = Mock(database_engine=Mock())
await analytics.send_analytics()
@@ -849,21 +882,24 @@ async def test_not_check_config_entries_if_yaml(
)
mock_config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.analytics.analytics.async_get_integrations",
- return_value={
- "default_config": mock_integration(
- hass,
- MockModule(
- "default_config",
- async_setup=AsyncMock(return_value=True),
- partial_manifest={"config_flow": True},
+ with (
+ patch(
+ "homeassistant.components.analytics.analytics.async_get_integrations",
+ return_value={
+ "default_config": mock_integration(
+ hass,
+ MockModule(
+ "default_config",
+ async_setup=AsyncMock(return_value=True),
+ partial_manifest={"config_flow": True},
+ ),
),
- ),
- },
- ), patch(
- "homeassistant.config.load_yaml_config_file",
- return_value={"default_config": {}},
+ },
+ ),
+ patch(
+ "homeassistant.config.load_yaml_config_file",
+ return_value={"default_config": {}},
+ ),
):
await analytics.send_analytics()
diff --git a/tests/components/analytics_insights/conftest.py b/tests/components/analytics_insights/conftest.py
index f5f811c6d26..03bd24faeea 100644
--- a/tests/components/analytics_insights/conftest.py
+++ b/tests/components/analytics_insights/conftest.py
@@ -29,12 +29,15 @@ def mock_setup_entry() -> Generator[AsyncMock, None, None]:
@pytest.fixture
def mock_analytics_client() -> Generator[AsyncMock, None, None]:
"""Mock a Homeassistant Analytics client."""
- with patch(
- "homeassistant.components.analytics_insights.HomeassistantAnalyticsClient",
- autospec=True,
- ) as mock_client, patch(
- "homeassistant.components.analytics_insights.config_flow.HomeassistantAnalyticsClient",
- new=mock_client,
+ with (
+ patch(
+ "homeassistant.components.analytics_insights.HomeassistantAnalyticsClient",
+ autospec=True,
+ ) as mock_client,
+ patch(
+ "homeassistant.components.analytics_insights.config_flow.HomeassistantAnalyticsClient",
+ new=mock_client,
+ ),
):
client = mock_client.return_value
client.get_current_analytics.return_value = CurrentAnalytics.from_json(
diff --git a/tests/components/androidtv/test_config_flow.py b/tests/components/androidtv/test_config_flow.py
index 7946ba4db99..afebe9903ce 100644
--- a/tests/components/androidtv/test_config_flow.py
+++ b/tests/components/androidtv/test_config_flow.py
@@ -108,10 +108,13 @@ async def test_user(
assert flow_result["step_id"] == "user"
# test with all provided
- with patch(
- CONNECT_METHOD,
- return_value=(MockConfigDevice(eth_mac, wifi_mac), None),
- ), PATCH_SETUP_ENTRY as mock_setup_entry:
+ with (
+ patch(
+ CONNECT_METHOD,
+ return_value=(MockConfigDevice(eth_mac, wifi_mac), None),
+ ),
+ PATCH_SETUP_ENTRY as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
flow_result["flow_id"], user_input=config
)
@@ -129,10 +132,15 @@ async def test_user_adbkey(hass: HomeAssistant) -> None:
config_data = CONFIG_PYTHON_ADB.copy()
config_data[CONF_ADBKEY] = ADBKEY
- with patch(
- CONNECT_METHOD,
- return_value=(MockConfigDevice(), None),
- ), PATCH_ISFILE, PATCH_ACCESS, PATCH_SETUP_ENTRY as mock_setup_entry:
+ with (
+ patch(
+ CONNECT_METHOD,
+ return_value=(MockConfigDevice(), None),
+ ),
+ PATCH_ISFILE,
+ PATCH_ACCESS,
+ PATCH_SETUP_ENTRY as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER, "show_advanced_options": True},
@@ -161,10 +169,13 @@ async def test_error_both_key_server(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] == {"base": "key_and_server"}
- with patch(
- CONNECT_METHOD,
- return_value=(MockConfigDevice(), None),
- ), PATCH_SETUP_ENTRY:
+ with (
+ patch(
+ CONNECT_METHOD,
+ return_value=(MockConfigDevice(), None),
+ ),
+ PATCH_SETUP_ENTRY,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=CONFIG_ADB_SERVER
)
@@ -188,10 +199,13 @@ async def test_error_invalid_key(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] == {"base": "adbkey_not_file"}
- with patch(
- CONNECT_METHOD,
- return_value=(MockConfigDevice(), None),
- ), PATCH_SETUP_ENTRY:
+ with (
+ patch(
+ CONNECT_METHOD,
+ return_value=(MockConfigDevice(), None),
+ ),
+ PATCH_SETUP_ENTRY,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=CONFIG_ADB_SERVER
)
@@ -299,10 +313,13 @@ async def test_on_connect_failed(hass: HomeAssistant) -> None:
assert result2["type"] == data_entry_flow.FlowResultType.FORM
assert result2["errors"] == {"base": "unknown"}
- with patch(
- CONNECT_METHOD,
- return_value=(MockConfigDevice(), None),
- ), PATCH_SETUP_ENTRY:
+ with (
+ patch(
+ CONNECT_METHOD,
+ return_value=(MockConfigDevice(), None),
+ ),
+ PATCH_SETUP_ENTRY,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"], user_input=CONFIG_ADB_SERVER
)
diff --git a/tests/components/androidtv/test_media_player.py b/tests/components/androidtv/test_media_player.py
index f09e21dd056..63923a57996 100644
--- a/tests/components/androidtv/test_media_player.py
+++ b/tests/components/androidtv/test_media_player.py
@@ -235,9 +235,10 @@ async def test_reconnect(
patch_key, entity_id, config_entry = _setup(config)
config_entry.add_to_hass(hass)
- with patchers.patch_connect(True)[patch_key], patchers.patch_shell(
- SHELL_RESPONSE_OFF
- )[patch_key]:
+ with (
+ patchers.patch_connect(True)[patch_key],
+ patchers.patch_shell(SHELL_RESPONSE_OFF)[patch_key],
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -249,9 +250,10 @@ async def test_reconnect(
caplog.clear()
caplog.set_level(logging.WARNING)
- with patchers.patch_connect(False)[patch_key], patchers.patch_shell(error=True)[
- patch_key
- ]:
+ with (
+ patchers.patch_connect(False)[patch_key],
+ patchers.patch_shell(error=True)[patch_key],
+ ):
for _ in range(5):
await async_update_entity(hass, entity_id)
state = hass.states.get(entity_id)
@@ -263,9 +265,11 @@ async def test_reconnect(
assert caplog.record_tuples[1][1] == logging.WARNING
caplog.set_level(logging.DEBUG)
- with patchers.patch_connect(True)[patch_key], patchers.patch_shell(
- SHELL_RESPONSE_STANDBY
- )[patch_key], patchers.PATCH_SCREENCAP:
+ with (
+ patchers.patch_connect(True)[patch_key],
+ patchers.patch_shell(SHELL_RESPONSE_STANDBY)[patch_key],
+ patchers.PATCH_SCREENCAP,
+ ):
await async_update_entity(hass, entity_id)
state = hass.states.get(entity_id)
@@ -293,9 +297,10 @@ async def test_adb_shell_returns_none(
patch_key, entity_id, config_entry = _setup(config)
config_entry.add_to_hass(hass)
- with patchers.patch_connect(True)[patch_key], patchers.patch_shell(
- SHELL_RESPONSE_OFF
- )[patch_key]:
+ with (
+ patchers.patch_connect(True)[patch_key],
+ patchers.patch_shell(SHELL_RESPONSE_OFF)[patch_key],
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -304,9 +309,10 @@ async def test_adb_shell_returns_none(
assert state is not None
assert state.state != STATE_UNAVAILABLE
- with patchers.patch_shell(None)[patch_key], patchers.patch_shell(error=True)[
- patch_key
- ]:
+ with (
+ patchers.patch_shell(None)[patch_key],
+ patchers.patch_shell(error=True)[patch_key],
+ ):
await async_update_entity(hass, entity_id)
state = hass.states.get(entity_id)
assert state is not None
@@ -318,9 +324,11 @@ async def test_setup_with_adbkey(hass: HomeAssistant) -> None:
patch_key, entity_id, config_entry = _setup(CONFIG_ANDROID_PYTHON_ADB_KEY)
config_entry.add_to_hass(hass)
- with patchers.patch_connect(True)[patch_key], patchers.patch_shell(
- SHELL_RESPONSE_OFF
- )[patch_key], patchers.PATCH_ISFILE:
+ with (
+ patchers.patch_connect(True)[patch_key],
+ patchers.patch_shell(SHELL_RESPONSE_OFF)[patch_key],
+ patchers.PATCH_ISFILE,
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -348,9 +356,10 @@ async def test_sources(hass: HomeAssistant, config: dict[str, Any]) -> None:
config_entry.add_to_hass(hass)
hass.config_entries.async_update_entry(config_entry, options={CONF_APPS: conf_apps})
- with patchers.patch_connect(True)[patch_key], patchers.patch_shell(
- SHELL_RESPONSE_OFF
- )[patch_key]:
+ with (
+ patchers.patch_connect(True)[patch_key],
+ patchers.patch_shell(SHELL_RESPONSE_OFF)[patch_key],
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -418,9 +427,10 @@ async def test_exclude_sources(
config_entry, options={CONF_EXCLUDE_UNNAMED_APPS: True, CONF_APPS: conf_apps}
)
- with patchers.patch_connect(True)[patch_key], patchers.patch_shell(
- SHELL_RESPONSE_OFF
- )[patch_key]:
+ with (
+ patchers.patch_connect(True)[patch_key],
+ patchers.patch_shell(SHELL_RESPONSE_OFF)[patch_key],
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -462,9 +472,10 @@ async def _test_select_source(
config_entry.add_to_hass(hass)
hass.config_entries.async_update_entry(config_entry, options={CONF_APPS: conf_apps})
- with patchers.patch_connect(True)[patch_key], patchers.patch_shell(
- SHELL_RESPONSE_OFF
- )[patch_key]:
+ with (
+ patchers.patch_connect(True)[patch_key],
+ patchers.patch_shell(SHELL_RESPONSE_OFF)[patch_key],
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -569,9 +580,12 @@ async def test_setup_fail(
patch_key, entity_id, config_entry = _setup(config)
config_entry.add_to_hass(hass)
- with patchers.patch_connect(connect)[patch_key], patchers.patch_shell(
- SHELL_RESPONSE_OFF, error=True, exc=AdbShellTimeoutException
- )[patch_key]:
+ with (
+ patchers.patch_connect(connect)[patch_key],
+ patchers.patch_shell(
+ SHELL_RESPONSE_OFF, error=True, exc=AdbShellTimeoutException
+ )[patch_key],
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id) is False
await hass.async_block_till_done()
@@ -588,9 +602,10 @@ async def test_adb_command(hass: HomeAssistant) -> None:
command = "test command"
response = "test response"
- with patchers.patch_connect(True)[patch_key], patchers.patch_shell(
- SHELL_RESPONSE_OFF
- )[patch_key]:
+ with (
+ patchers.patch_connect(True)[patch_key],
+ patchers.patch_shell(SHELL_RESPONSE_OFF)[patch_key],
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -617,9 +632,10 @@ async def test_adb_command_unicode_decode_error(hass: HomeAssistant) -> None:
command = "test command"
response = b"test response"
- with patchers.patch_connect(True)[patch_key], patchers.patch_shell(
- SHELL_RESPONSE_OFF
- )[patch_key]:
+ with (
+ patchers.patch_connect(True)[patch_key],
+ patchers.patch_shell(SHELL_RESPONSE_OFF)[patch_key],
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -646,9 +662,10 @@ async def test_adb_command_key(hass: HomeAssistant) -> None:
command = "HOME"
response = None
- with patchers.patch_connect(True)[patch_key], patchers.patch_shell(
- SHELL_RESPONSE_OFF
- )[patch_key]:
+ with (
+ patchers.patch_connect(True)[patch_key],
+ patchers.patch_shell(SHELL_RESPONSE_OFF)[patch_key],
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -675,9 +692,10 @@ async def test_adb_command_get_properties(hass: HomeAssistant) -> None:
command = "GET_PROPERTIES"
response = {"test key": "test value"}
- with patchers.patch_connect(True)[patch_key], patchers.patch_shell(
- SHELL_RESPONSE_OFF
- )[patch_key]:
+ with (
+ patchers.patch_connect(True)[patch_key],
+ patchers.patch_shell(SHELL_RESPONSE_OFF)[patch_key],
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -704,9 +722,10 @@ async def test_learn_sendevent(hass: HomeAssistant) -> None:
config_entry.add_to_hass(hass)
response = "sendevent 1 2 3 4"
- with patchers.patch_connect(True)[patch_key], patchers.patch_shell(
- SHELL_RESPONSE_OFF
- )[patch_key]:
+ with (
+ patchers.patch_connect(True)[patch_key],
+ patchers.patch_shell(SHELL_RESPONSE_OFF)[patch_key],
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -732,9 +751,10 @@ async def test_update_lock_not_acquired(hass: HomeAssistant) -> None:
patch_key, entity_id, config_entry = _setup(CONFIG_ANDROID_DEFAULT)
config_entry.add_to_hass(hass)
- with patchers.patch_connect(True)[patch_key], patchers.patch_shell(
- SHELL_RESPONSE_OFF
- )[patch_key]:
+ with (
+ patchers.patch_connect(True)[patch_key],
+ patchers.patch_shell(SHELL_RESPONSE_OFF)[patch_key],
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -744,18 +764,22 @@ async def test_update_lock_not_acquired(hass: HomeAssistant) -> None:
assert state is not None
assert state.state == STATE_OFF
- with patch(
- "androidtv.androidtv.androidtv_async.AndroidTVAsync.update",
- side_effect=LockNotAcquiredException,
- ), patchers.patch_shell(SHELL_RESPONSE_STANDBY)[patch_key]:
+ with (
+ patch(
+ "androidtv.androidtv.androidtv_async.AndroidTVAsync.update",
+ side_effect=LockNotAcquiredException,
+ ),
+ patchers.patch_shell(SHELL_RESPONSE_STANDBY)[patch_key],
+ ):
await async_update_entity(hass, 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
- ], patchers.PATCH_SCREENCAP:
+ with (
+ patchers.patch_shell(SHELL_RESPONSE_STANDBY)[patch_key],
+ patchers.PATCH_SCREENCAP,
+ ):
await async_update_entity(hass, entity_id)
state = hass.states.get(entity_id)
assert state is not None
@@ -769,9 +793,10 @@ async def test_download(hass: HomeAssistant) -> None:
device_path = "device/path"
local_path = "local/path"
- with patchers.patch_connect(True)[patch_key], patchers.patch_shell(
- SHELL_RESPONSE_OFF
- )[patch_key]:
+ with (
+ patchers.patch_connect(True)[patch_key],
+ patchers.patch_shell(SHELL_RESPONSE_OFF)[patch_key],
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -790,10 +815,9 @@ async def test_download(hass: HomeAssistant) -> None:
patch_pull.assert_not_called()
# Successful download
- with patch(
- "androidtv.basetv.basetv_async.BaseTVAsync.adb_pull"
- ) as patch_pull, patch.object(
- hass.config, "is_allowed_path", return_value=True
+ with (
+ patch("androidtv.basetv.basetv_async.BaseTVAsync.adb_pull") as patch_pull,
+ patch.object(hass.config, "is_allowed_path", return_value=True),
):
await hass.services.async_call(
DOMAIN,
@@ -815,9 +839,10 @@ async def test_upload(hass: HomeAssistant) -> None:
device_path = "device/path"
local_path = "local/path"
- with patchers.patch_connect(True)[patch_key], patchers.patch_shell(
- SHELL_RESPONSE_OFF
- )[patch_key]:
+ with (
+ patchers.patch_connect(True)[patch_key],
+ patchers.patch_shell(SHELL_RESPONSE_OFF)[patch_key],
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -836,10 +861,9 @@ async def test_upload(hass: HomeAssistant) -> None:
patch_push.assert_not_called()
# Successful upload
- with patch(
- "androidtv.basetv.basetv_async.BaseTVAsync.adb_push"
- ) as patch_push, patch.object(
- hass.config, "is_allowed_path", return_value=True
+ with (
+ patch("androidtv.basetv.basetv_async.BaseTVAsync.adb_push") as patch_push,
+ patch.object(hass.config, "is_allowed_path", return_value=True),
):
await hass.services.async_call(
DOMAIN,
@@ -859,9 +883,10 @@ async def test_androidtv_volume_set(hass: HomeAssistant) -> None:
patch_key, entity_id, config_entry = _setup(CONFIG_ANDROID_DEFAULT)
config_entry.add_to_hass(hass)
- with patchers.patch_connect(True)[patch_key], patchers.patch_shell(
- SHELL_RESPONSE_OFF
- )[patch_key]:
+ with (
+ patchers.patch_connect(True)[patch_key],
+ patchers.patch_shell(SHELL_RESPONSE_OFF)[patch_key],
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -888,15 +913,17 @@ async def test_get_image_http(
patch_key, entity_id, config_entry = _setup(CONFIG_ANDROID_DEFAULT)
config_entry.add_to_hass(hass)
- with patchers.patch_connect(True)[patch_key], patchers.patch_shell(
- SHELL_RESPONSE_OFF
- )[patch_key]:
+ with (
+ patchers.patch_connect(True)[patch_key],
+ patchers.patch_shell(SHELL_RESPONSE_OFF)[patch_key],
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
- with patchers.patch_shell("11")[
- patch_key
- ], patchers.PATCH_SCREENCAP as patch_screen_cap:
+ with (
+ patchers.patch_shell("11")[patch_key],
+ patchers.PATCH_SCREENCAP as patch_screen_cap,
+ ):
await async_update_entity(hass, entity_id)
patch_screen_cap.assert_called()
@@ -913,20 +940,20 @@ async def test_get_image_http(
assert content == b"image"
next_update = utcnow() + timedelta(seconds=30)
- with patchers.patch_shell("11")[
- patch_key
- ], patchers.PATCH_SCREENCAP as patch_screen_cap, patch(
- "homeassistant.util.utcnow", return_value=next_update
+ with (
+ patchers.patch_shell("11")[patch_key],
+ patchers.PATCH_SCREENCAP as patch_screen_cap,
+ patch("homeassistant.util.utcnow", return_value=next_update),
):
async_fire_time_changed(hass, next_update, True)
await hass.async_block_till_done()
patch_screen_cap.assert_not_called()
next_update = utcnow() + timedelta(seconds=60)
- with patchers.patch_shell("11")[
- patch_key
- ], patchers.PATCH_SCREENCAP as patch_screen_cap, patch(
- "homeassistant.util.utcnow", return_value=next_update
+ with (
+ patchers.patch_shell("11")[patch_key],
+ patchers.PATCH_SCREENCAP as patch_screen_cap,
+ patch("homeassistant.util.utcnow", return_value=next_update),
):
async_fire_time_changed(hass, next_update, True)
await hass.async_block_till_done()
@@ -939,15 +966,19 @@ async def test_get_image_http_fail(hass: HomeAssistant) -> None:
patch_key, entity_id, config_entry = _setup(CONFIG_ANDROID_DEFAULT)
config_entry.add_to_hass(hass)
- with patchers.patch_connect(True)[patch_key], patchers.patch_shell(
- SHELL_RESPONSE_OFF
- )[patch_key]:
+ with (
+ patchers.patch_connect(True)[patch_key],
+ patchers.patch_shell(SHELL_RESPONSE_OFF)[patch_key],
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
- with patchers.patch_shell("11")[patch_key], patch(
- "androidtv.basetv.basetv_async.BaseTVAsync.adb_screencap",
- side_effect=ConnectionResetError,
+ with (
+ patchers.patch_shell("11")[patch_key],
+ patch(
+ "androidtv.basetv.basetv_async.BaseTVAsync.adb_screencap",
+ side_effect=ConnectionResetError,
+ ),
):
await async_update_entity(hass, entity_id)
@@ -968,9 +999,10 @@ async def test_get_image_disabled(hass: HomeAssistant) -> None:
config_entry, options={CONF_SCREENCAP: False}
)
- with patchers.patch_connect(True)[patch_key], patchers.patch_shell(
- SHELL_RESPONSE_OFF
- )[patch_key]:
+ with (
+ patchers.patch_connect(True)[patch_key],
+ patchers.patch_shell(SHELL_RESPONSE_OFF)[patch_key],
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -1025,9 +1057,10 @@ async def test_services_androidtv(hass: HomeAssistant) -> None:
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
- with patchers.patch_shell(SHELL_RESPONSE_STANDBY)[
- patch_key
- ], patchers.PATCH_SCREENCAP:
+ with (
+ patchers.patch_shell(SHELL_RESPONSE_STANDBY)[patch_key],
+ patchers.PATCH_SCREENCAP,
+ ):
await _test_service(
hass, entity_id, SERVICE_MEDIA_NEXT_TRACK, "media_next_track"
)
@@ -1075,9 +1108,10 @@ async def test_services_firetv(hass: HomeAssistant) -> None:
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
- with patchers.patch_shell(SHELL_RESPONSE_STANDBY)[
- patch_key
- ], patchers.PATCH_SCREENCAP:
+ with (
+ patchers.patch_shell(SHELL_RESPONSE_STANDBY)[patch_key],
+ patchers.PATCH_SCREENCAP,
+ ):
await _test_service(hass, entity_id, SERVICE_MEDIA_STOP, "back")
await _test_service(hass, entity_id, SERVICE_TURN_OFF, "adb_shell")
await _test_service(hass, entity_id, SERVICE_TURN_ON, "adb_shell")
@@ -1093,9 +1127,10 @@ async def test_volume_mute(hass: HomeAssistant) -> None:
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
- with patchers.patch_shell(SHELL_RESPONSE_STANDBY)[
- patch_key
- ], patchers.PATCH_SCREENCAP:
+ with (
+ patchers.patch_shell(SHELL_RESPONSE_STANDBY)[patch_key],
+ patchers.PATCH_SCREENCAP,
+ ):
service_data = {ATTR_ENTITY_ID: entity_id, ATTR_MEDIA_VOLUME_MUTED: True}
with patch(
"androidtv.androidtv.androidtv_async.AndroidTVAsync.mute_volume",
@@ -1133,9 +1168,10 @@ async def test_connection_closed_on_ha_stop(hass: HomeAssistant) -> None:
patch_key, _, config_entry = _setup(CONFIG_ANDROID_DEFAULT)
config_entry.add_to_hass(hass)
- with patchers.patch_connect(True)[patch_key], patchers.patch_shell(
- SHELL_RESPONSE_OFF
- )[patch_key]:
+ with (
+ patchers.patch_connect(True)[patch_key],
+ patchers.patch_shell(SHELL_RESPONSE_OFF)[patch_key],
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -1153,9 +1189,10 @@ async def test_exception(hass: HomeAssistant) -> None:
patch_key, entity_id, config_entry = _setup(CONFIG_ANDROID_DEFAULT)
config_entry.add_to_hass(hass)
- with patchers.patch_connect(True)[patch_key], patchers.patch_shell(
- SHELL_RESPONSE_OFF
- )[patch_key]:
+ with (
+ patchers.patch_connect(True)[patch_key],
+ patchers.patch_shell(SHELL_RESPONSE_OFF)[patch_key],
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -1183,9 +1220,10 @@ async def test_options_reload(hass: HomeAssistant) -> None:
patch_key, entity_id, config_entry = _setup(CONFIG_ANDROID_DEFAULT)
config_entry.add_to_hass(hass)
- with patchers.patch_connect(True)[patch_key], patchers.patch_shell(
- SHELL_RESPONSE_OFF
- )[patch_key]:
+ with (
+ patchers.patch_connect(True)[patch_key],
+ patchers.patch_shell(SHELL_RESPONSE_OFF)[patch_key],
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/anova/__init__.py b/tests/components/anova/__init__.py
index fb4c578ba1b..03cfb7589d0 100644
--- a/tests/components/anova/__init__.py
+++ b/tests/components/anova/__init__.py
@@ -47,13 +47,15 @@ async def async_init_integration(
error: str | None = None,
) -> ConfigEntry:
"""Set up the Anova integration in Home Assistant."""
- with patch(
- "homeassistant.components.anova.coordinator.AnovaPrecisionCooker.update"
- ) as update_patch, patch(
- "homeassistant.components.anova.AnovaApi.authenticate"
- ), patch(
- "homeassistant.components.anova.AnovaApi.get_devices",
- ) as device_patch:
+ with (
+ patch(
+ "homeassistant.components.anova.coordinator.AnovaPrecisionCooker.update"
+ ) as update_patch,
+ patch("homeassistant.components.anova.AnovaApi.authenticate"),
+ patch(
+ "homeassistant.components.anova.AnovaApi.get_devices",
+ ) as device_patch,
+ ):
update_patch.return_value = ONLINE_UPDATE
device_patch.return_value = [
AnovaPrecisionCooker(None, DEVICE_UNIQUE_ID, "type_sample", None)
diff --git a/tests/components/anova/test_config_flow.py b/tests/components/anova/test_config_flow.py
index d1255876137..6ea988dc53a 100644
--- a/tests/components/anova/test_config_flow.py
+++ b/tests/components/anova/test_config_flow.py
@@ -16,15 +16,16 @@ async def test_flow_user(
hass: HomeAssistant,
) -> None:
"""Test user initialized flow."""
- with patch(
- "homeassistant.components.anova.config_flow.AnovaApi.authenticate",
- ) as auth_patch, patch(
- "homeassistant.components.anova.AnovaApi.get_devices"
- ) as device_patch, patch(
- "homeassistant.components.anova.AnovaApi.authenticate"
- ), patch(
- "homeassistant.components.anova.config_flow.AnovaApi.get_devices"
- ) as config_flow_device_patch:
+ with (
+ patch(
+ "homeassistant.components.anova.config_flow.AnovaApi.authenticate",
+ ) as auth_patch,
+ patch("homeassistant.components.anova.AnovaApi.get_devices") as device_patch,
+ patch("homeassistant.components.anova.AnovaApi.authenticate"),
+ patch(
+ "homeassistant.components.anova.config_flow.AnovaApi.get_devices"
+ ) as config_flow_device_patch,
+ ):
auth_patch.return_value = True
device_patch.return_value = [
AnovaPrecisionCooker(None, DEVICE_UNIQUE_ID, "type_sample", None)
@@ -50,13 +51,15 @@ async def test_flow_user(
async def test_flow_user_already_configured(hass: HomeAssistant) -> None:
"""Test user initialized flow with duplicate device."""
- with patch(
- "homeassistant.components.anova.config_flow.AnovaApi.authenticate",
- ) as auth_patch, patch(
- "homeassistant.components.anova.AnovaApi.get_devices"
- ) as device_patch, patch(
- "homeassistant.components.anova.config_flow.AnovaApi.get_devices"
- ) as config_flow_device_patch:
+ with (
+ patch(
+ "homeassistant.components.anova.config_flow.AnovaApi.authenticate",
+ ) as auth_patch,
+ patch("homeassistant.components.anova.AnovaApi.get_devices") as device_patch,
+ patch(
+ "homeassistant.components.anova.config_flow.AnovaApi.get_devices"
+ ) as config_flow_device_patch,
+ ):
auth_patch.return_value = True
device_patch.return_value = [
AnovaPrecisionCooker(None, DEVICE_UNIQUE_ID, "type_sample", None)
@@ -115,11 +118,12 @@ async def test_flow_unknown_error(hass: HomeAssistant) -> None:
async def test_flow_no_devices(hass: HomeAssistant) -> None:
"""Test unknown error throwing error."""
- with patch(
- "homeassistant.components.anova.config_flow.AnovaApi.authenticate"
- ), patch(
- "homeassistant.components.anova.config_flow.AnovaApi.get_devices",
- side_effect=NoDevicesFound(),
+ with (
+ patch("homeassistant.components.anova.config_flow.AnovaApi.authenticate"),
+ patch(
+ "homeassistant.components.anova.config_flow.AnovaApi.get_devices",
+ side_effect=NoDevicesFound(),
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
diff --git a/tests/components/aosmith/test_config_flow.py b/tests/components/aosmith/test_config_flow.py
index b981047c926..32f259f552c 100644
--- a/tests/components/aosmith/test_config_flow.py
+++ b/tests/components/aosmith/test_config_flow.py
@@ -124,13 +124,17 @@ async def test_reauth_flow(
assert len(flows) == 1
assert flows[0]["step_id"] == "reauth_confirm"
- with patch(
- "homeassistant.components.aosmith.config_flow.AOSmithAPIClient.get_devices",
- return_value=[],
- ), patch(
- "homeassistant.components.aosmith.config_flow.AOSmithAPIClient.get_energy_use_data",
- return_value=[],
- ), patch("homeassistant.components.aosmith.async_setup_entry", return_value=True):
+ with (
+ patch(
+ "homeassistant.components.aosmith.config_flow.AOSmithAPIClient.get_devices",
+ return_value=[],
+ ),
+ patch(
+ "homeassistant.components.aosmith.config_flow.AOSmithAPIClient.get_energy_use_data",
+ return_value=[],
+ ),
+ patch("homeassistant.components.aosmith.async_setup_entry", return_value=True),
+ ):
result2 = await hass.config_entries.flow.async_configure(
flows[0]["flow_id"],
{CONF_PASSWORD: FIXTURE_USER_INPUT[CONF_PASSWORD]},
@@ -178,10 +182,13 @@ async def test_reauth_flow_retry(
assert result2["errors"] == {"base": "invalid_auth"}
# Second attempt at reauth - authentication succeeds
- with patch(
- "homeassistant.components.aosmith.config_flow.AOSmithAPIClient.get_devices",
- return_value=[],
- ), patch("homeassistant.components.aosmith.async_setup_entry", return_value=True):
+ with (
+ patch(
+ "homeassistant.components.aosmith.config_flow.AOSmithAPIClient.get_devices",
+ return_value=[],
+ ),
+ patch("homeassistant.components.aosmith.async_setup_entry", return_value=True),
+ ):
result3 = await hass.config_entries.flow.async_configure(
flows[0]["flow_id"],
{CONF_PASSWORD: FIXTURE_USER_INPUT[CONF_PASSWORD]},
diff --git a/tests/components/aosmith/test_init.py b/tests/components/aosmith/test_init.py
index 7e081686790..940b0cbc6b5 100644
--- a/tests/components/aosmith/test_init.py
+++ b/tests/components/aosmith/test_init.py
@@ -59,12 +59,15 @@ async def test_config_entry_not_ready_get_energy_use_data_error(
)
]
- with patch(
- "homeassistant.components.aosmith.config_flow.AOSmithAPIClient.get_devices",
- return_value=get_devices_fixture,
- ), patch(
- "homeassistant.components.aosmith.config_flow.AOSmithAPIClient.get_energy_use_data",
- side_effect=AOSmithUnknownException("Unknown error"),
+ with (
+ patch(
+ "homeassistant.components.aosmith.config_flow.AOSmithAPIClient.get_devices",
+ return_value=get_devices_fixture,
+ ),
+ patch(
+ "homeassistant.components.aosmith.config_flow.AOSmithAPIClient.get_energy_use_data",
+ side_effect=AOSmithUnknownException("Unknown error"),
+ ),
):
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/apache_kafka/test_init.py b/tests/components/apache_kafka/test_init.py
index 2a7a92b773b..93d9619f0c3 100644
--- a/tests/components/apache_kafka/test_init.py
+++ b/tests/components/apache_kafka/test_init.py
@@ -43,9 +43,11 @@ class MockKafkaClient:
@pytest.fixture(name="mock_client")
def mock_client_fixture():
"""Mock the apache kafka client."""
- with patch(f"{PRODUCER_PATH}.start") as start, patch(
- f"{PRODUCER_PATH}.send_and_wait"
- ) as send_and_wait, patch(f"{PRODUCER_PATH}.__init__", return_value=None) as init:
+ with (
+ patch(f"{PRODUCER_PATH}.start") as start,
+ patch(f"{PRODUCER_PATH}.send_and_wait") as send_and_wait,
+ patch(f"{PRODUCER_PATH}.__init__", return_value=None) as init,
+ ):
yield MockKafkaClient(init, start, send_and_wait)
diff --git a/tests/components/apcupsd/test_diagnostics.py b/tests/components/apcupsd/test_diagnostics.py
index 56249a7823b..5dfce28a989 100644
--- a/tests/components/apcupsd/test_diagnostics.py
+++ b/tests/components/apcupsd/test_diagnostics.py
@@ -1,4 +1,5 @@
"""Test APCUPSd diagnostics reporting abilities."""
+
from syrupy.assertion import SnapshotAssertion
from homeassistant.core import HomeAssistant
diff --git a/tests/components/apprise/test_notify.py b/tests/components/apprise/test_notify.py
index c2b11ccb043..7d37d7a5d99 100644
--- a/tests/components/apprise/test_notify.py
+++ b/tests/components/apprise/test_notify.py
@@ -34,12 +34,15 @@ async def test_apprise_config_load_fail02(hass: HomeAssistant) -> None:
BASE_COMPONENT: {"name": "test", "platform": "apprise", "config": "/path/"}
}
- with patch(
- "homeassistant.components.apprise.notify.apprise.Apprise.add",
- return_value=False,
- ), patch(
- "homeassistant.components.apprise.notify.apprise.AppriseConfig.add",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.apprise.notify.apprise.Apprise.add",
+ return_value=False,
+ ),
+ patch(
+ "homeassistant.components.apprise.notify.apprise.AppriseConfig.add",
+ return_value=True,
+ ),
):
assert await async_setup_component(hass, BASE_COMPONENT, config)
await hass.async_block_till_done()
diff --git a/tests/components/arcam_fmj/conftest.py b/tests/components/arcam_fmj/conftest.py
index 7c42fb9e0ff..f5a9ab6315a 100644
--- a/tests/components/arcam_fmj/conftest.py
+++ b/tests/components/arcam_fmj/conftest.py
@@ -98,9 +98,14 @@ async def player_setup_fixture(hass, state_1, state_2, client):
await async_setup_component(hass, "homeassistant", {})
- with patch("homeassistant.components.arcam_fmj.Client", return_value=client), patch(
- "homeassistant.components.arcam_fmj.media_player.State", side_effect=state_mock
- ), patch("homeassistant.components.arcam_fmj._run_client", return_value=None):
+ with (
+ patch("homeassistant.components.arcam_fmj.Client", return_value=client),
+ patch(
+ "homeassistant.components.arcam_fmj.media_player.State",
+ side_effect=state_mock,
+ ),
+ patch("homeassistant.components.arcam_fmj._run_client", return_value=None),
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
yield MOCK_ENTITY_ID
diff --git a/tests/components/aseko_pool_live/test_config_flow.py b/tests/components/aseko_pool_live/test_config_flow.py
index 4ebcf0e0c7d..2566dfd61e6 100644
--- a/tests/components/aseko_pool_live/test_config_flow.py
+++ b/tests/components/aseko_pool_live/test_config_flow.py
@@ -29,13 +29,16 @@ async def test_async_step_user_success(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "homeassistant.components.aseko_pool_live.config_flow.WebAccount.login",
- return_value=AccountInfo("aseko@example.com", "a_user_id", "any_language"),
- ), patch(
- "homeassistant.components.aseko_pool_live.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.aseko_pool_live.config_flow.WebAccount.login",
+ return_value=AccountInfo("aseko@example.com", "a_user_id", "any_language"),
+ ),
+ patch(
+ "homeassistant.components.aseko_pool_live.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
diff --git a/tests/components/assist_pipeline/test_pipeline.py b/tests/components/assist_pipeline/test_pipeline.py
index 40b701588a0..3bfe6605839 100644
--- a/tests/components/assist_pipeline/test_pipeline.py
+++ b/tests/components/assist_pipeline/test_pipeline.py
@@ -401,9 +401,10 @@ async def test_default_pipeline(
hass.config.country = ha_country
hass.config.language = ha_language
- with patch.object(
- mock_stt_provider, "_supported_languages", MANY_LANGUAGES
- ), patch.object(mock_tts_provider, "_supported_languages", MANY_LANGUAGES):
+ with (
+ patch.object(mock_stt_provider, "_supported_languages", MANY_LANGUAGES),
+ patch.object(mock_tts_provider, "_supported_languages", MANY_LANGUAGES),
+ ):
assert await async_setup_component(hass, "assist_pipeline", {})
pipeline_data: PipelineData = hass.data[DOMAIN]
diff --git a/tests/components/assist_pipeline/test_websocket.py b/tests/components/assist_pipeline/test_websocket.py
index 612bf760bd0..0883046f3a1 100644
--- a/tests/components/assist_pipeline/test_websocket.py
+++ b/tests/components/assist_pipeline/test_websocket.py
@@ -381,12 +381,15 @@ async def test_audio_pipeline_no_wake_word_entity(
"""Test timeout from a pipeline run with audio input/output + wake word."""
client = await hass_ws_client(hass)
- with patch(
- "homeassistant.components.wake_word.async_default_entity",
- return_value="wake_word.bad-entity-id",
- ), patch(
- "homeassistant.components.wake_word.async_get_wake_word_detection_entity",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.components.wake_word.async_default_entity",
+ return_value="wake_word.bad-entity-id",
+ ),
+ patch(
+ "homeassistant.components.wake_word.async_get_wake_word_detection_entity",
+ return_value=None,
+ ),
):
await client.send_json_auto_id(
{
@@ -1700,15 +1703,19 @@ async def test_list_pipeline_languages_with_aliases(
"""Test listing pipeline languages using aliases."""
client = await hass_ws_client(hass)
- with patch(
- "homeassistant.components.conversation.async_get_conversation_languages",
- return_value={"he", "nb"},
- ), patch(
- "homeassistant.components.stt.async_get_speech_to_text_languages",
- return_value={"he", "no"},
- ), patch(
- "homeassistant.components.tts.async_get_text_to_speech_languages",
- return_value={"iw", "nb"},
+ with (
+ patch(
+ "homeassistant.components.conversation.async_get_conversation_languages",
+ return_value={"he", "nb"},
+ ),
+ patch(
+ "homeassistant.components.stt.async_get_speech_to_text_languages",
+ return_value={"he", "no"},
+ ),
+ patch(
+ "homeassistant.components.tts.async_get_text_to_speech_languages",
+ return_value={"iw", "nb"},
+ ),
):
await client.send_json_auto_id({"type": "assist_pipeline/language/list"})
diff --git a/tests/components/august/mocks.py b/tests/components/august/mocks.py
index b819565d4bf..75145df2509 100644
--- a/tests/components/august/mocks.py
+++ b/tests/components/august/mocks.py
@@ -76,8 +76,9 @@ async def _mock_setup_august(
options={},
)
entry.add_to_hass(hass)
- with patch("homeassistant.components.august.async_create_pubnub"), patch(
- "homeassistant.components.august.AugustPubNub", return_value=pubnub_mock
+ with (
+ patch("homeassistant.components.august.async_create_pubnub"),
+ patch("homeassistant.components.august.AugustPubNub", return_value=pubnub_mock),
):
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/august/test_config_flow.py b/tests/components/august/test_config_flow.py
index 3eb87c2b096..e1e6f622c2e 100644
--- a/tests/components/august/test_config_flow.py
+++ b/tests/components/august/test_config_flow.py
@@ -34,13 +34,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.august.config_flow.AugustGateway.async_authenticate",
- return_value=True,
- ), patch(
- "homeassistant.components.august.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.august.config_flow.AugustGateway.async_authenticate",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.august.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -142,13 +145,16 @@ async def test_form_needs_validate(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "homeassistant.components.august.config_flow.AugustGateway.async_authenticate",
- side_effect=RequireValidation,
- ), patch(
- "homeassistant.components.august.gateway.AuthenticatorAsync.async_send_verification_code",
- return_value=True,
- ) as mock_send_verification_code:
+ with (
+ patch(
+ "homeassistant.components.august.config_flow.AugustGateway.async_authenticate",
+ side_effect=RequireValidation,
+ ),
+ patch(
+ "homeassistant.components.august.gateway.AuthenticatorAsync.async_send_verification_code",
+ return_value=True,
+ ) as mock_send_verification_code,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -164,16 +170,20 @@ async def test_form_needs_validate(hass: HomeAssistant) -> None:
assert result2["step_id"] == "validation"
# Try with the WRONG verification code give us the form back again
- with patch(
- "homeassistant.components.august.config_flow.AugustGateway.async_authenticate",
- side_effect=RequireValidation,
- ), patch(
- "homeassistant.components.august.gateway.AuthenticatorAsync.async_validate_verification_code",
- return_value=ValidationResult.INVALID_VERIFICATION_CODE,
- ) as mock_validate_verification_code, patch(
- "homeassistant.components.august.gateway.AuthenticatorAsync.async_send_verification_code",
- return_value=True,
- ) as mock_send_verification_code:
+ with (
+ patch(
+ "homeassistant.components.august.config_flow.AugustGateway.async_authenticate",
+ side_effect=RequireValidation,
+ ),
+ patch(
+ "homeassistant.components.august.gateway.AuthenticatorAsync.async_validate_verification_code",
+ return_value=ValidationResult.INVALID_VERIFICATION_CODE,
+ ) as mock_validate_verification_code,
+ patch(
+ "homeassistant.components.august.gateway.AuthenticatorAsync.async_send_verification_code",
+ return_value=True,
+ ) as mock_send_verification_code,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{VERIFICATION_CODE_KEY: "incorrect"},
@@ -188,18 +198,23 @@ async def test_form_needs_validate(hass: HomeAssistant) -> None:
assert result3["step_id"] == "validation"
# Try with the CORRECT verification code and we setup
- with patch(
- "homeassistant.components.august.config_flow.AugustGateway.async_authenticate",
- return_value=True,
- ), patch(
- "homeassistant.components.august.gateway.AuthenticatorAsync.async_validate_verification_code",
- return_value=ValidationResult.VALIDATED,
- ) as mock_validate_verification_code, patch(
- "homeassistant.components.august.gateway.AuthenticatorAsync.async_send_verification_code",
- return_value=True,
- ) as mock_send_verification_code, patch(
- "homeassistant.components.august.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.august.config_flow.AugustGateway.async_authenticate",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.august.gateway.AuthenticatorAsync.async_validate_verification_code",
+ return_value=ValidationResult.VALIDATED,
+ ) as mock_validate_verification_code,
+ patch(
+ "homeassistant.components.august.gateway.AuthenticatorAsync.async_send_verification_code",
+ return_value=True,
+ ) as mock_send_verification_code,
+ patch(
+ "homeassistant.components.august.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
result4 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{VERIFICATION_CODE_KEY: "correct"},
@@ -243,13 +258,16 @@ async def test_form_reauth(hass: HomeAssistant) -> None:
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.august.config_flow.AugustGateway.async_authenticate",
- return_value=True,
- ), patch(
- "homeassistant.components.august.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.august.config_flow.AugustGateway.async_authenticate",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.august.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -286,13 +304,16 @@ async def test_form_reauth_with_2fa(hass: HomeAssistant) -> None:
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.august.config_flow.AugustGateway.async_authenticate",
- side_effect=RequireValidation,
- ), patch(
- "homeassistant.components.august.gateway.AuthenticatorAsync.async_send_verification_code",
- return_value=True,
- ) as mock_send_verification_code:
+ with (
+ patch(
+ "homeassistant.components.august.config_flow.AugustGateway.async_authenticate",
+ side_effect=RequireValidation,
+ ),
+ patch(
+ "homeassistant.components.august.gateway.AuthenticatorAsync.async_send_verification_code",
+ return_value=True,
+ ) as mock_send_verification_code,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -307,18 +328,23 @@ async def test_form_reauth_with_2fa(hass: HomeAssistant) -> None:
assert result2["step_id"] == "validation"
# Try with the CORRECT verification code and we setup
- with patch(
- "homeassistant.components.august.config_flow.AugustGateway.async_authenticate",
- return_value=True,
- ), patch(
- "homeassistant.components.august.gateway.AuthenticatorAsync.async_validate_verification_code",
- return_value=ValidationResult.VALIDATED,
- ) as mock_validate_verification_code, patch(
- "homeassistant.components.august.gateway.AuthenticatorAsync.async_send_verification_code",
- return_value=True,
- ) as mock_send_verification_code, patch(
- "homeassistant.components.august.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.august.config_flow.AugustGateway.async_authenticate",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.august.gateway.AuthenticatorAsync.async_validate_verification_code",
+ return_value=ValidationResult.VALIDATED,
+ ) as mock_validate_verification_code,
+ patch(
+ "homeassistant.components.august.gateway.AuthenticatorAsync.async_send_verification_code",
+ return_value=True,
+ ) as mock_send_verification_code,
+ patch(
+ "homeassistant.components.august.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{VERIFICATION_CODE_KEY: "correct"},
@@ -354,13 +380,16 @@ async def test_switching_brands(hass: HomeAssistant) -> None:
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.august.config_flow.AugustGateway.async_authenticate",
- return_value=True,
- ), patch(
- "homeassistant.components.august.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.august.config_flow.AugustGateway.async_authenticate",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.august.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
diff --git a/tests/components/aurora/test_config_flow.py b/tests/components/aurora/test_config_flow.py
index 087c4f55ee0..d8f42e48842 100644
--- a/tests/components/aurora/test_config_flow.py
+++ b/tests/components/aurora/test_config_flow.py
@@ -25,13 +25,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.aurora.config_flow.AuroraForecast.get_forecast_data",
- return_value=True,
- ), patch(
- "homeassistant.components.aurora.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.aurora.config_flow.AuroraForecast.get_forecast_data",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.aurora.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
DATA,
diff --git a/tests/components/aurora_abb_powerone/test_config_flow.py b/tests/components/aurora_abb_powerone/test_config_flow.py
index 6b7a227ed04..fbeaff2f4f8 100644
--- a/tests/components/aurora_abb_powerone/test_config_flow.py
+++ b/tests/components/aurora_abb_powerone/test_config_flow.py
@@ -33,25 +33,32 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "aurorapy.client.AuroraSerialClient.connect",
- return_value=None,
- ), patch(
- "aurorapy.client.AuroraSerialClient.serial_number",
- return_value="9876543",
- ), patch(
- "aurorapy.client.AuroraSerialClient.version",
- return_value="9.8.7.6",
- ), patch(
- "aurorapy.client.AuroraSerialClient.pn",
- return_value="A.B.C",
- ), patch(
- "aurorapy.client.AuroraSerialClient.firmware",
- return_value="1.234",
- ) as mock_setup, patch(
- "homeassistant.components.aurora_abb_powerone.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "aurorapy.client.AuroraSerialClient.connect",
+ return_value=None,
+ ),
+ patch(
+ "aurorapy.client.AuroraSerialClient.serial_number",
+ return_value="9876543",
+ ),
+ patch(
+ "aurorapy.client.AuroraSerialClient.version",
+ return_value="9.8.7.6",
+ ),
+ patch(
+ "aurorapy.client.AuroraSerialClient.pn",
+ return_value="A.B.C",
+ ),
+ patch(
+ "aurorapy.client.AuroraSerialClient.firmware",
+ return_value="1.234",
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.aurora_abb_powerone.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_PORT: "/dev/ttyUSB7", CONF_ADDRESS: 7},
@@ -135,16 +142,20 @@ async def test_form_invalid_com_ports(hass: HomeAssistant) -> None:
)
assert result2["errors"] == {"base": "cannot_connect"}
- with patch(
- "aurorapy.client.AuroraSerialClient.connect",
- side_effect=AuroraError("...Some other message!!!123..."),
- return_value=None,
- ), patch(
- "serial.Serial.isOpen",
- return_value=True,
- ), patch(
- "aurorapy.client.AuroraSerialClient.close",
- ) as mock_clientclose:
+ with (
+ patch(
+ "aurorapy.client.AuroraSerialClient.connect",
+ side_effect=AuroraError("...Some other message!!!123..."),
+ return_value=None,
+ ),
+ patch(
+ "serial.Serial.isOpen",
+ return_value=True,
+ ),
+ patch(
+ "aurorapy.client.AuroraSerialClient.close",
+ ) as mock_clientclose,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_PORT: "/dev/ttyUSB7", CONF_ADDRESS: 7},
diff --git a/tests/components/aurora_abb_powerone/test_init.py b/tests/components/aurora_abb_powerone/test_init.py
index 811a0c84f3d..18b9854773e 100644
--- a/tests/components/aurora_abb_powerone/test_init.py
+++ b/tests/components/aurora_abb_powerone/test_init.py
@@ -17,18 +17,24 @@ from tests.common import MockConfigEntry
async def test_unload_entry(hass: HomeAssistant) -> None:
"""Test unloading the aurora_abb_powerone entry."""
- with patch("aurorapy.client.AuroraSerialClient.connect", return_value=None), patch(
- "aurorapy.client.AuroraSerialClient.serial_number",
- return_value="9876543",
- ), patch(
- "aurorapy.client.AuroraSerialClient.version",
- return_value="9.8.7.6",
- ), patch(
- "aurorapy.client.AuroraSerialClient.pn",
- return_value="A.B.C",
- ), patch(
- "aurorapy.client.AuroraSerialClient.firmware",
- return_value="1.234",
+ with (
+ patch("aurorapy.client.AuroraSerialClient.connect", return_value=None),
+ patch(
+ "aurorapy.client.AuroraSerialClient.serial_number",
+ return_value="9876543",
+ ),
+ patch(
+ "aurorapy.client.AuroraSerialClient.version",
+ return_value="9.8.7.6",
+ ),
+ patch(
+ "aurorapy.client.AuroraSerialClient.pn",
+ return_value="A.B.C",
+ ),
+ patch(
+ "aurorapy.client.AuroraSerialClient.firmware",
+ return_value="1.234",
+ ),
):
mock_entry = MockConfigEntry(
domain=DOMAIN,
diff --git a/tests/components/aurora_abb_powerone/test_sensor.py b/tests/components/aurora_abb_powerone/test_sensor.py
index 9a8b21cdbd3..178cf165f67 100644
--- a/tests/components/aurora_abb_powerone/test_sensor.py
+++ b/tests/components/aurora_abb_powerone/test_sensor.py
@@ -68,26 +68,33 @@ async def test_sensors(hass: HomeAssistant, entity_registry: EntityRegistry) ->
"""Test data coming back from inverter."""
mock_entry = _mock_config_entry()
- with patch("aurorapy.client.AuroraSerialClient.connect", return_value=None), patch(
- "aurorapy.client.AuroraSerialClient.measure",
- side_effect=_simulated_returns,
- ), patch(
- "aurorapy.client.AuroraSerialClient.alarms", return_value=["No alarm"]
- ), patch(
- "aurorapy.client.AuroraSerialClient.serial_number",
- return_value="9876543",
- ), patch(
- "aurorapy.client.AuroraSerialClient.version",
- return_value="9.8.7.6",
- ), patch(
- "aurorapy.client.AuroraSerialClient.pn",
- return_value="A.B.C",
- ), patch(
- "aurorapy.client.AuroraSerialClient.firmware",
- return_value="1.234",
- ), patch(
- "aurorapy.client.AuroraSerialClient.cumulated_energy",
- side_effect=_simulated_returns,
+ with (
+ patch("aurorapy.client.AuroraSerialClient.connect", return_value=None),
+ patch(
+ "aurorapy.client.AuroraSerialClient.measure",
+ side_effect=_simulated_returns,
+ ),
+ patch("aurorapy.client.AuroraSerialClient.alarms", return_value=["No alarm"]),
+ patch(
+ "aurorapy.client.AuroraSerialClient.serial_number",
+ return_value="9876543",
+ ),
+ patch(
+ "aurorapy.client.AuroraSerialClient.version",
+ return_value="9.8.7.6",
+ ),
+ patch(
+ "aurorapy.client.AuroraSerialClient.pn",
+ return_value="A.B.C",
+ ),
+ patch(
+ "aurorapy.client.AuroraSerialClient.firmware",
+ return_value="1.234",
+ ),
+ patch(
+ "aurorapy.client.AuroraSerialClient.cumulated_energy",
+ side_effect=_simulated_returns,
+ ),
):
mock_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_entry.entry_id)
@@ -144,25 +151,32 @@ async def test_sensor_dark(hass: HomeAssistant, freezer: FrozenDateTimeFactory)
mock_entry = _mock_config_entry()
# sun is up
- with patch("aurorapy.client.AuroraSerialClient.connect", return_value=None), patch(
- "aurorapy.client.AuroraSerialClient.measure", side_effect=_simulated_returns
- ), patch(
- "aurorapy.client.AuroraSerialClient.alarms", return_value=["No alarm"]
- ), patch(
- "aurorapy.client.AuroraSerialClient.cumulated_energy",
- side_effect=_simulated_returns,
- ), patch(
- "aurorapy.client.AuroraSerialClient.serial_number",
- return_value="9876543",
- ), patch(
- "aurorapy.client.AuroraSerialClient.version",
- return_value="9.8.7.6",
- ), patch(
- "aurorapy.client.AuroraSerialClient.pn",
- return_value="A.B.C",
- ), patch(
- "aurorapy.client.AuroraSerialClient.firmware",
- return_value="1.234",
+ with (
+ patch("aurorapy.client.AuroraSerialClient.connect", return_value=None),
+ patch(
+ "aurorapy.client.AuroraSerialClient.measure", side_effect=_simulated_returns
+ ),
+ patch("aurorapy.client.AuroraSerialClient.alarms", return_value=["No alarm"]),
+ patch(
+ "aurorapy.client.AuroraSerialClient.cumulated_energy",
+ side_effect=_simulated_returns,
+ ),
+ patch(
+ "aurorapy.client.AuroraSerialClient.serial_number",
+ return_value="9876543",
+ ),
+ patch(
+ "aurorapy.client.AuroraSerialClient.version",
+ return_value="9.8.7.6",
+ ),
+ patch(
+ "aurorapy.client.AuroraSerialClient.pn",
+ return_value="A.B.C",
+ ),
+ patch(
+ "aurorapy.client.AuroraSerialClient.firmware",
+ return_value="1.234",
+ ),
):
mock_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_entry.entry_id)
@@ -173,25 +187,35 @@ async def test_sensor_dark(hass: HomeAssistant, freezer: FrozenDateTimeFactory)
assert power.state == "45.7"
# sunset
- with patch("aurorapy.client.AuroraSerialClient.connect", return_value=None), patch(
- "aurorapy.client.AuroraSerialClient.measure",
- side_effect=AuroraTimeoutError("No response after 10 seconds"),
- ), patch(
- "aurorapy.client.AuroraSerialClient.cumulated_energy",
- side_effect=AuroraTimeoutError("No response after 3 tries"),
- ), patch("aurorapy.client.AuroraSerialClient.alarms", return_value=["No alarm"]):
+ with (
+ patch("aurorapy.client.AuroraSerialClient.connect", return_value=None),
+ patch(
+ "aurorapy.client.AuroraSerialClient.measure",
+ side_effect=AuroraTimeoutError("No response after 10 seconds"),
+ ),
+ patch(
+ "aurorapy.client.AuroraSerialClient.cumulated_energy",
+ side_effect=AuroraTimeoutError("No response after 3 tries"),
+ ),
+ patch("aurorapy.client.AuroraSerialClient.alarms", return_value=["No alarm"]),
+ ):
freezer.tick(SCAN_INTERVAL * 2)
async_fire_time_changed(hass)
await hass.async_block_till_done()
power = hass.states.get("sensor.mydevicename_total_energy")
assert power.state == "unknown"
# sun rose again
- with patch("aurorapy.client.AuroraSerialClient.connect", return_value=None), patch(
- "aurorapy.client.AuroraSerialClient.measure", side_effect=_simulated_returns
- ), patch(
- "aurorapy.client.AuroraSerialClient.cumulated_energy",
- side_effect=_simulated_returns,
- ), patch("aurorapy.client.AuroraSerialClient.alarms", return_value=["No alarm"]):
+ with (
+ patch("aurorapy.client.AuroraSerialClient.connect", return_value=None),
+ patch(
+ "aurorapy.client.AuroraSerialClient.measure", side_effect=_simulated_returns
+ ),
+ patch(
+ "aurorapy.client.AuroraSerialClient.cumulated_energy",
+ side_effect=_simulated_returns,
+ ),
+ patch("aurorapy.client.AuroraSerialClient.alarms", return_value=["No alarm"]),
+ ):
freezer.tick(SCAN_INTERVAL * 4)
async_fire_time_changed(hass)
await hass.async_block_till_done()
@@ -199,13 +223,18 @@ async def test_sensor_dark(hass: HomeAssistant, freezer: FrozenDateTimeFactory)
assert power is not None
assert power.state == "45.7"
# sunset
- with patch("aurorapy.client.AuroraSerialClient.connect", return_value=None), patch(
- "aurorapy.client.AuroraSerialClient.measure",
- side_effect=AuroraTimeoutError("No response after 10 seconds"),
- ), patch(
- "aurorapy.client.AuroraSerialClient.cumulated_energy",
- side_effect=AuroraError("No response after 10 seconds"),
- ), patch("aurorapy.client.AuroraSerialClient.alarms", return_value=["No alarm"]):
+ with (
+ patch("aurorapy.client.AuroraSerialClient.connect", return_value=None),
+ patch(
+ "aurorapy.client.AuroraSerialClient.measure",
+ side_effect=AuroraTimeoutError("No response after 10 seconds"),
+ ),
+ patch(
+ "aurorapy.client.AuroraSerialClient.cumulated_energy",
+ side_effect=AuroraError("No response after 10 seconds"),
+ ),
+ patch("aurorapy.client.AuroraSerialClient.alarms", return_value=["No alarm"]),
+ ):
freezer.tick(SCAN_INTERVAL * 6)
async_fire_time_changed(hass)
await hass.async_block_till_done()
@@ -222,24 +251,30 @@ async def test_sensor_unknown_error(
mock_entry = _mock_config_entry()
# sun is up
- with patch("aurorapy.client.AuroraSerialClient.connect", return_value=None), patch(
- "aurorapy.client.AuroraSerialClient.measure", side_effect=_simulated_returns
- ), patch(
- "aurorapy.client.AuroraSerialClient.alarms", return_value=["No alarm"]
- ), patch(
- "aurorapy.client.AuroraSerialClient.cumulated_energy",
- side_effect=_simulated_returns,
+ with (
+ patch("aurorapy.client.AuroraSerialClient.connect", return_value=None),
+ patch(
+ "aurorapy.client.AuroraSerialClient.measure", side_effect=_simulated_returns
+ ),
+ patch("aurorapy.client.AuroraSerialClient.alarms", return_value=["No alarm"]),
+ patch(
+ "aurorapy.client.AuroraSerialClient.cumulated_energy",
+ side_effect=_simulated_returns,
+ ),
):
mock_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_entry.entry_id)
await hass.async_block_till_done()
- with patch("aurorapy.client.AuroraSerialClient.connect", return_value=None), patch(
- "aurorapy.client.AuroraSerialClient.measure",
- side_effect=AuroraError("another error"),
- ), patch(
- "aurorapy.client.AuroraSerialClient.alarms", return_value=["No alarm"]
- ), patch("serial.Serial.isOpen", return_value=True):
+ with (
+ patch("aurorapy.client.AuroraSerialClient.connect", return_value=None),
+ patch(
+ "aurorapy.client.AuroraSerialClient.measure",
+ side_effect=AuroraError("another error"),
+ ),
+ patch("aurorapy.client.AuroraSerialClient.alarms", return_value=["No alarm"]),
+ patch("serial.Serial.isOpen", return_value=True),
+ ):
freezer.tick(SCAN_INTERVAL * 2)
async_fire_time_changed(hass)
await hass.async_block_till_done()
diff --git a/tests/components/aussie_broadband/common.py b/tests/components/aussie_broadband/common.py
index 1ad56ab47f6..1c992d116d1 100644
--- a/tests/components/aussie_broadband/common.py
+++ b/tests/components/aussie_broadband/common.py
@@ -50,20 +50,24 @@ async def setup_platform(
)
mock_entry.add_to_hass(hass)
- with patch("homeassistant.components.aussie_broadband.PLATFORMS", platforms), patch(
- "aussiebb.asyncio.AussieBB.__init__", return_value=None
- ), patch(
- "aussiebb.asyncio.AussieBB.login",
- return_value=True,
- side_effect=side_effect,
- ), patch(
- "aussiebb.asyncio.AussieBB.get_services",
- return_value=FAKE_SERVICES,
- side_effect=side_effect,
- ), patch(
- "aussiebb.asyncio.AussieBB.get_usage",
- return_value=usage,
- side_effect=usage_effect,
+ with (
+ patch("homeassistant.components.aussie_broadband.PLATFORMS", platforms),
+ patch("aussiebb.asyncio.AussieBB.__init__", return_value=None),
+ patch(
+ "aussiebb.asyncio.AussieBB.login",
+ return_value=True,
+ side_effect=side_effect,
+ ),
+ patch(
+ "aussiebb.asyncio.AussieBB.get_services",
+ return_value=FAKE_SERVICES,
+ side_effect=side_effect,
+ ),
+ patch(
+ "aussiebb.asyncio.AussieBB.get_usage",
+ return_value=usage,
+ side_effect=usage_effect,
+ ),
):
await hass.config_entries.async_setup(mock_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/aussie_broadband/test_config_flow.py b/tests/components/aussie_broadband/test_config_flow.py
index 37839e92cdd..f08b56502b8 100644
--- a/tests/components/aussie_broadband/test_config_flow.py
+++ b/tests/components/aussie_broadband/test_config_flow.py
@@ -25,14 +25,15 @@ async def test_form(hass: HomeAssistant) -> None:
assert result1["type"] == FlowResultType.FORM
assert result1["errors"] is None
- with patch("aussiebb.asyncio.AussieBB.__init__", return_value=None), patch(
- "aussiebb.asyncio.AussieBB.login", return_value=True
- ), patch(
- "aussiebb.asyncio.AussieBB.get_services", return_value=FAKE_SERVICES
- ), patch(
- "homeassistant.components.aussie_broadband.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("aussiebb.asyncio.AussieBB.__init__", return_value=None),
+ patch("aussiebb.asyncio.AussieBB.login", return_value=True),
+ patch("aussiebb.asyncio.AussieBB.get_services", return_value=FAKE_SERVICES),
+ patch(
+ "homeassistant.components.aussie_broadband.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result1["flow_id"],
FAKE_DATA,
@@ -52,14 +53,17 @@ async def test_already_configured(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch("aussiebb.asyncio.AussieBB.__init__", return_value=None), patch(
- "aussiebb.asyncio.AussieBB.login", return_value=True
- ), patch(
- "aussiebb.asyncio.AussieBB.get_services", return_value=[FAKE_SERVICES[0]]
- ), patch(
- "homeassistant.components.aussie_broadband.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("aussiebb.asyncio.AussieBB.__init__", return_value=None),
+ patch("aussiebb.asyncio.AussieBB.login", return_value=True),
+ patch(
+ "aussiebb.asyncio.AussieBB.get_services", return_value=[FAKE_SERVICES[0]]
+ ),
+ patch(
+ "homeassistant.components.aussie_broadband.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
await hass.config_entries.flow.async_configure(
result1["flow_id"],
FAKE_DATA,
@@ -70,14 +74,17 @@ async def test_already_configured(hass: HomeAssistant) -> None:
result3 = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch("aussiebb.asyncio.AussieBB.__init__", return_value=None), patch(
- "aussiebb.asyncio.AussieBB.login", return_value=True
- ), patch(
- "aussiebb.asyncio.AussieBB.get_services", return_value=[FAKE_SERVICES[0]]
- ), patch(
- "homeassistant.components.aussie_broadband.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("aussiebb.asyncio.AussieBB.__init__", return_value=None),
+ patch("aussiebb.asyncio.AussieBB.login", return_value=True),
+ patch(
+ "aussiebb.asyncio.AussieBB.get_services", return_value=[FAKE_SERVICES[0]]
+ ),
+ patch(
+ "homeassistant.components.aussie_broadband.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result4 = await hass.config_entries.flow.async_configure(
result3["flow_id"],
FAKE_DATA,
@@ -96,12 +103,15 @@ async def test_no_services(hass: HomeAssistant) -> None:
assert result1["type"] == FlowResultType.FORM
assert result1["errors"] is None
- with patch("aussiebb.asyncio.AussieBB.__init__", return_value=None), patch(
- "aussiebb.asyncio.AussieBB.login", return_value=True
- ), patch("aussiebb.asyncio.AussieBB.get_services", return_value=[]), patch(
- "homeassistant.components.aussie_broadband.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("aussiebb.asyncio.AussieBB.__init__", return_value=None),
+ patch("aussiebb.asyncio.AussieBB.login", return_value=True),
+ patch("aussiebb.asyncio.AussieBB.get_services", return_value=[]),
+ patch(
+ "homeassistant.components.aussie_broadband.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result1["flow_id"],
FAKE_DATA,
@@ -119,8 +129,9 @@ async def test_form_invalid_auth(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch("aussiebb.asyncio.AussieBB.__init__", return_value=None), patch(
- "aussiebb.asyncio.AussieBB.login", side_effect=AuthenticationException()
+ with (
+ patch("aussiebb.asyncio.AussieBB.__init__", return_value=None),
+ patch("aussiebb.asyncio.AussieBB.login", side_effect=AuthenticationException()),
):
result2 = await hass.config_entries.flow.async_configure(
result1["flow_id"],
@@ -137,8 +148,9 @@ async def test_form_network_issue(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch("aussiebb.asyncio.AussieBB.__init__", return_value=None), patch(
- "aussiebb.asyncio.AussieBB.login", side_effect=ClientConnectionError()
+ with (
+ patch("aussiebb.asyncio.AussieBB.__init__", return_value=None),
+ patch("aussiebb.asyncio.AussieBB.login", side_effect=ClientConnectionError()),
):
result2 = await hass.config_entries.flow.async_configure(
result1["flow_id"],
@@ -157,13 +169,16 @@ async def test_reauth(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_REAUTH}, data=FAKE_DATA
)
- with patch("aussiebb.asyncio.AussieBB.__init__", return_value=None), patch(
- "aussiebb.asyncio.AussieBB.login", return_value=True
- ), patch(
- "aussiebb.asyncio.AussieBB.get_services", return_value=[FAKE_SERVICES[0]]
- ), patch(
- "homeassistant.components.aussie_broadband.async_setup_entry",
- return_value=True,
+ with (
+ patch("aussiebb.asyncio.AussieBB.__init__", return_value=None),
+ patch("aussiebb.asyncio.AussieBB.login", return_value=True),
+ patch(
+ "aussiebb.asyncio.AussieBB.get_services", return_value=[FAKE_SERVICES[0]]
+ ),
+ patch(
+ "homeassistant.components.aussie_broadband.async_setup_entry",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result1["flow_id"],
@@ -185,9 +200,13 @@ async def test_reauth(hass: HomeAssistant) -> None:
)
assert result5["step_id"] == "reauth_confirm"
- with patch("aussiebb.asyncio.AussieBB.__init__", return_value=None), patch(
- "aussiebb.asyncio.AussieBB.login", side_effect=AuthenticationException()
- ), patch("aussiebb.asyncio.AussieBB.get_services", return_value=[FAKE_SERVICES[0]]):
+ with (
+ patch("aussiebb.asyncio.AussieBB.__init__", return_value=None),
+ patch("aussiebb.asyncio.AussieBB.login", side_effect=AuthenticationException()),
+ patch(
+ "aussiebb.asyncio.AussieBB.get_services", return_value=[FAKE_SERVICES[0]]
+ ),
+ ):
result6 = await hass.config_entries.flow.async_configure(
result5["flow_id"],
{
@@ -199,9 +218,13 @@ async def test_reauth(hass: HomeAssistant) -> None:
assert result6["step_id"] == "reauth_confirm"
# Test successful reauth
- with patch("aussiebb.asyncio.AussieBB.__init__", return_value=None), patch(
- "aussiebb.asyncio.AussieBB.login", return_value=True
- ), patch("aussiebb.asyncio.AussieBB.get_services", return_value=[FAKE_SERVICES[0]]):
+ with (
+ patch("aussiebb.asyncio.AussieBB.__init__", return_value=None),
+ patch("aussiebb.asyncio.AussieBB.login", return_value=True),
+ patch(
+ "aussiebb.asyncio.AussieBB.get_services", return_value=[FAKE_SERVICES[0]]
+ ),
+ ):
result7 = await hass.config_entries.flow.async_configure(
result6["flow_id"],
{
diff --git a/tests/components/auth/test_login_flow.py b/tests/components/auth/test_login_flow.py
index 59c066a4f85..af9a2cf62f1 100644
--- a/tests/components/auth/test_login_flow.py
+++ b/tests/components/auth/test_login_flow.py
@@ -219,11 +219,15 @@ async def test_invalid_redirect_uri(
assert resp.status == HTTPStatus.OK
step = await resp.json()
- with patch(
- "homeassistant.components.auth.indieauth.fetch_redirect_uris", return_value=[]
- ), patch(
- "homeassistant.components.http.ban.process_wrong_login"
- ) as mock_process_wrong_login:
+ with (
+ patch(
+ "homeassistant.components.auth.indieauth.fetch_redirect_uris",
+ return_value=[],
+ ),
+ patch(
+ "homeassistant.components.http.ban.process_wrong_login"
+ ) as mock_process_wrong_login,
+ ):
resp = await client.post(
f"/auth/login_flow/{step['flow_id']}",
json={
diff --git a/tests/components/automation/test_init.py b/tests/components/automation/test_init.py
index 234fc912118..00a7e6980d7 100644
--- a/tests/components/automation/test_init.py
+++ b/tests/components/automation/test_init.py
@@ -1102,14 +1102,17 @@ async def test_reload_automation_when_blueprint_changes(
blueprint_config["action"] = [blueprint_config["action"]]
blueprint_config["action"].append(blueprint_config["action"][-1])
- with patch(
- "homeassistant.config.load_yaml_config_file",
- autospec=True,
- return_value=config,
- ), patch(
- "homeassistant.components.blueprint.models.yaml.load_yaml_dict",
- autospec=True,
- return_value=blueprint_config,
+ with (
+ patch(
+ "homeassistant.config.load_yaml_config_file",
+ autospec=True,
+ return_value=config,
+ ),
+ patch(
+ "homeassistant.components.blueprint.models.yaml.load_yaml_dict",
+ autospec=True,
+ return_value=blueprint_config,
+ ),
):
await hass.services.async_call(
automation.DOMAIN, SERVICE_RELOAD, blocking=True
diff --git a/tests/components/awair/test_config_flow.py b/tests/components/awair/test_config_flow.py
index d03dde0d867..c8b9ea262a8 100644
--- a/tests/components/awair/test_config_flow.py
+++ b/tests/components/awair/test_config_flow.py
@@ -155,10 +155,13 @@ async def test_reauth(hass: HomeAssistant, user, cloud_devices) -> None:
assert result["step_id"] == "reauth_confirm"
assert result["errors"] == {CONF_ACCESS_TOKEN: "invalid_access_token"}
- with patch(
- "python_awair.AwairClient.query",
- side_effect=[user, cloud_devices],
- ), patch("homeassistant.components.awair.async_setup_entry", return_value=True):
+ with (
+ patch(
+ "python_awair.AwairClient.query",
+ side_effect=[user, cloud_devices],
+ ),
+ patch("homeassistant.components.awair.async_setup_entry", return_value=True),
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=CLOUD_CONFIG,
@@ -199,12 +202,15 @@ async def test_reauth_error(hass: HomeAssistant) -> None:
async def test_create_cloud_entry(hass: HomeAssistant, user, cloud_devices) -> None:
"""Test overall flow when using cloud api."""
- with patch(
- "python_awair.AwairClient.query",
- side_effect=[user, cloud_devices],
- ), patch(
- "homeassistant.components.awair.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "python_awair.AwairClient.query",
+ side_effect=[user, cloud_devices],
+ ),
+ patch(
+ "homeassistant.components.awair.async_setup_entry",
+ return_value=True,
+ ),
):
menu_step = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=CLOUD_CONFIG
@@ -229,9 +235,12 @@ async def test_create_cloud_entry(hass: HomeAssistant, user, cloud_devices) -> N
async def test_create_local_entry(hass: HomeAssistant, local_devices) -> None:
"""Test overall flow when using local API."""
- with patch("python_awair.AwairClient.query", side_effect=[local_devices]), patch(
- "homeassistant.components.awair.async_setup_entry",
- return_value=True,
+ with (
+ patch("python_awair.AwairClient.query", side_effect=[local_devices]),
+ patch(
+ "homeassistant.components.awair.async_setup_entry",
+ return_value=True,
+ ),
):
menu_step = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=LOCAL_CONFIG
@@ -287,9 +296,12 @@ async def test_create_local_entry_from_discovery(
{},
)
- with patch("python_awair.AwairClient.query", side_effect=[local_devices]), patch(
- "homeassistant.components.awair.async_setup_entry",
- return_value=True,
+ with (
+ patch("python_awair.AwairClient.query", side_effect=[local_devices]),
+ patch(
+ "homeassistant.components.awair.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_configure(
form_step["flow_id"],
@@ -337,9 +349,12 @@ async def test_create_local_entry_awair_error(hass: HomeAssistant) -> None:
async def test_create_zeroconf_entry(hass: HomeAssistant, local_devices) -> None:
"""Test overall flow when using discovery."""
- with patch("python_awair.AwairClient.query", side_effect=[local_devices]), patch(
- "homeassistant.components.awair.async_setup_entry",
- return_value=True,
+ with (
+ patch("python_awair.AwairClient.query", side_effect=[local_devices]),
+ patch(
+ "homeassistant.components.awair.async_setup_entry",
+ return_value=True,
+ ),
):
confirm_step = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_ZEROCONF}, data=ZEROCONF_DISCOVERY
@@ -382,14 +397,16 @@ async def test_zeroconf_discovery_update_configuration(
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.awair.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "python_awair.AwairClient.query", side_effect=[local_devices]
- ), patch(
- "homeassistant.components.awair.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.awair.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch("python_awair.AwairClient.query", side_effect=[local_devices]),
+ patch(
+ "homeassistant.components.awair.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -408,14 +425,16 @@ async def test_zeroconf_during_onboarding(
hass: HomeAssistant, local_devices: Any
) -> None:
"""Test the zeroconf creates an entry during onboarding."""
- with patch(
- "homeassistant.components.awair.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "python_awair.AwairClient.query", side_effect=[local_devices]
- ), patch(
- "homeassistant.components.onboarding.async_is_onboarded",
- return_value=False,
+ with (
+ patch(
+ "homeassistant.components.awair.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch("python_awair.AwairClient.query", side_effect=[local_devices]),
+ patch(
+ "homeassistant.components.onboarding.async_is_onboarded",
+ return_value=False,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_ZEROCONF}, data=ZEROCONF_DISCOVERY
diff --git a/tests/components/aws/test_init.py b/tests/components/aws/test_init.py
index 9cf8966483b..9589ad6c037 100644
--- a/tests/components/aws/test_init.py
+++ b/tests/components/aws/test_init.py
@@ -161,10 +161,13 @@ async def test_access_key_credential(hass: HomeAssistant) -> None:
async def test_notify_credential(hass: HomeAssistant) -> None:
"""Test notify service can use access key directly."""
mock_session = MockAioSession()
- with async_patch(
- "homeassistant.components.aws.AioSession", return_value=mock_session
- ), async_patch(
- "homeassistant.components.aws.notify.AioSession", return_value=mock_session
+ with (
+ async_patch(
+ "homeassistant.components.aws.AioSession", return_value=mock_session
+ ),
+ async_patch(
+ "homeassistant.components.aws.notify.AioSession", return_value=mock_session
+ ),
):
await async_setup_component(
hass,
@@ -195,10 +198,13 @@ async def test_notify_credential(hass: HomeAssistant) -> None:
async def test_notify_credential_profile(hass: HomeAssistant) -> None:
"""Test notify service can use profile directly."""
mock_session = MockAioSession()
- with async_patch(
- "homeassistant.components.aws.AioSession", return_value=mock_session
- ), async_patch(
- "homeassistant.components.aws.notify.AioSession", return_value=mock_session
+ with (
+ async_patch(
+ "homeassistant.components.aws.AioSession", return_value=mock_session
+ ),
+ async_patch(
+ "homeassistant.components.aws.notify.AioSession", return_value=mock_session
+ ),
):
await async_setup_component(
hass,
diff --git a/tests/components/axis/test_hub.py b/tests/components/axis/test_hub.py
index d166aaed733..3291f88d90a 100644
--- a/tests/components/axis/test_hub.py
+++ b/tests/components/axis/test_hub.py
@@ -187,9 +187,12 @@ async def test_device_trigger_reauth_flow(
hass: HomeAssistant, config_entry, setup_default_vapix_requests
) -> None:
"""Failed authentication trigger a reauthentication flow."""
- with patch.object(
- axis, "get_axis_api", side_effect=axis.errors.AuthenticationRequired
- ), patch.object(hass.config_entries.flow, "async_init") as mock_flow_init:
+ with (
+ patch.object(
+ axis, "get_axis_api", side_effect=axis.errors.AuthenticationRequired
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_flow_init,
+ ):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
mock_flow_init.assert_called_once()
@@ -223,9 +226,12 @@ async def test_shutdown(config_entry_data) -> None:
async def test_get_device_fails(hass: HomeAssistant, config_entry_data) -> None:
"""Device unauthorized yields authentication required error."""
- with patch(
- "axis.interfaces.vapix.Vapix.initialize", side_effect=axislib.Unauthorized
- ), pytest.raises(axis.errors.AuthenticationRequired):
+ with (
+ patch(
+ "axis.interfaces.vapix.Vapix.initialize", side_effect=axislib.Unauthorized
+ ),
+ pytest.raises(axis.errors.AuthenticationRequired),
+ ):
await axis.hub.get_axis_api(hass, config_entry_data)
@@ -233,15 +239,17 @@ async def test_get_device_device_unavailable(
hass: HomeAssistant, config_entry_data
) -> None:
"""Device unavailable yields cannot connect error."""
- with patch(
- "axis.interfaces.vapix.Vapix.request", side_effect=axislib.RequestError
- ), pytest.raises(axis.errors.CannotConnect):
+ with (
+ patch("axis.interfaces.vapix.Vapix.request", side_effect=axislib.RequestError),
+ pytest.raises(axis.errors.CannotConnect),
+ ):
await axis.hub.get_axis_api(hass, config_entry_data)
async def test_get_device_unknown_error(hass: HomeAssistant, config_entry_data) -> None:
"""Device yield unknown error."""
- with patch(
- "axis.interfaces.vapix.Vapix.request", side_effect=axislib.AxisException
- ), pytest.raises(axis.errors.AuthenticationRequired):
+ with (
+ patch("axis.interfaces.vapix.Vapix.request", side_effect=axislib.AxisException),
+ pytest.raises(axis.errors.AuthenticationRequired),
+ ):
await axis.hub.get_axis_api(hass, config_entry_data)
diff --git a/tests/components/axis/test_light.py b/tests/components/axis/test_light.py
index 95956450c9e..5cde6b74fc4 100644
--- a/tests/components/axis/test_light.py
+++ b/tests/components/axis/test_light.py
@@ -149,11 +149,12 @@ async def test_lights(
assert light_0.name == f"{NAME} IR Light 0"
# Turn on, set brightness, light already on
- with patch(
- "axis.interfaces.vapix.LightHandler.activate_light"
- ) as mock_activate, patch(
- "axis.interfaces.vapix.LightHandler.set_manual_intensity"
- ) as mock_set_intensity:
+ with (
+ patch("axis.interfaces.vapix.LightHandler.activate_light") as mock_activate,
+ patch(
+ "axis.interfaces.vapix.LightHandler.set_manual_intensity"
+ ) as mock_set_intensity,
+ ):
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
@@ -189,11 +190,12 @@ async def test_lights(
assert light_0.state == STATE_OFF
# Turn on, set brightness
- with patch(
- "axis.interfaces.vapix.LightHandler.activate_light"
- ) as mock_activate, patch(
- "axis.interfaces.vapix.LightHandler.set_manual_intensity"
- ) as mock_set_intensity:
+ with (
+ patch("axis.interfaces.vapix.LightHandler.activate_light") as mock_activate,
+ patch(
+ "axis.interfaces.vapix.LightHandler.set_manual_intensity"
+ ) as mock_set_intensity,
+ ):
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
diff --git a/tests/components/azure_devops/test_config_flow.py b/tests/components/azure_devops/test_config_flow.py
index 08856fccb17..84c2b5d3cca 100644
--- a/tests/components/azure_devops/test_config_flow.py
+++ b/tests/components/azure_devops/test_config_flow.py
@@ -134,14 +134,18 @@ async def test_reauth_connection_error(hass: HomeAssistant) -> None:
async def test_project_error(hass: HomeAssistant) -> None:
"""Test we show user form on Azure DevOps connection error."""
- with patch(
- "homeassistant.components.azure_devops.config_flow.DevOpsClient.authorized",
- return_value=True,
- ), patch(
- "homeassistant.components.azure_devops.config_flow.DevOpsClient.authorize",
- ), patch(
- "homeassistant.components.azure_devops.config_flow.DevOpsClient.get_project",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.components.azure_devops.config_flow.DevOpsClient.authorized",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.azure_devops.config_flow.DevOpsClient.authorize",
+ ),
+ patch(
+ "homeassistant.components.azure_devops.config_flow.DevOpsClient.get_project",
+ return_value=None,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@@ -163,14 +167,18 @@ async def test_project_error(hass: HomeAssistant) -> None:
async def test_reauth_project_error(hass: HomeAssistant) -> None:
"""Test we show user form on Azure DevOps project error."""
- with patch(
- "homeassistant.components.azure_devops.config_flow.DevOpsClient.authorize",
- ), patch(
- "homeassistant.components.azure_devops.config_flow.DevOpsClient.authorized",
- return_value=True,
- ), patch(
- "homeassistant.components.azure_devops.config_flow.DevOpsClient.get_project",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.components.azure_devops.config_flow.DevOpsClient.authorize",
+ ),
+ patch(
+ "homeassistant.components.azure_devops.config_flow.DevOpsClient.authorized",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.azure_devops.config_flow.DevOpsClient.get_project",
+ return_value=None,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -213,15 +221,19 @@ async def test_reauth_flow(hass: HomeAssistant) -> None:
assert result["step_id"] == "reauth"
assert result["errors"] == {"base": "invalid_auth"}
- with patch(
- "homeassistant.components.azure_devops.config_flow.DevOpsClient.authorize",
- ), patch(
- "homeassistant.components.azure_devops.config_flow.DevOpsClient.authorized",
- return_value=True,
- ), patch(
- "homeassistant.components.azure_devops.config_flow.DevOpsClient.get_project",
- return_value=DevOpsProject(
- "abcd-abcd-abcd-abcd", FIXTURE_USER_INPUT[CONF_PROJECT]
+ with (
+ patch(
+ "homeassistant.components.azure_devops.config_flow.DevOpsClient.authorize",
+ ),
+ patch(
+ "homeassistant.components.azure_devops.config_flow.DevOpsClient.authorized",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.azure_devops.config_flow.DevOpsClient.get_project",
+ return_value=DevOpsProject(
+ "abcd-abcd-abcd-abcd", FIXTURE_USER_INPUT[CONF_PROJECT]
+ ),
),
):
result2 = await hass.config_entries.flow.async_configure(
@@ -236,18 +248,23 @@ async def test_reauth_flow(hass: HomeAssistant) -> None:
async def test_full_flow_implementation(hass: HomeAssistant) -> None:
"""Test registering an integration and finishing flow works."""
- with patch(
- "homeassistant.components.azure_devops.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.azure_devops.config_flow.DevOpsClient.authorized",
- return_value=True,
- ), patch(
- "homeassistant.components.azure_devops.config_flow.DevOpsClient.authorize",
- ), patch(
- "homeassistant.components.azure_devops.config_flow.DevOpsClient.get_project",
- return_value=DevOpsProject(
- "abcd-abcd-abcd-abcd", FIXTURE_USER_INPUT[CONF_PROJECT]
+ with (
+ patch(
+ "homeassistant.components.azure_devops.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.azure_devops.config_flow.DevOpsClient.authorized",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.azure_devops.config_flow.DevOpsClient.authorize",
+ ),
+ patch(
+ "homeassistant.components.azure_devops.config_flow.DevOpsClient.get_project",
+ return_value=DevOpsProject(
+ "abcd-abcd-abcd-abcd", FIXTURE_USER_INPUT[CONF_PROJECT]
+ ),
),
):
result = await hass.config_entries.flow.async_init(
diff --git a/tests/components/backup/test_http.py b/tests/components/backup/test_http.py
index 02e446f5b88..baf1798534a 100644
--- a/tests/components/backup/test_http.py
+++ b/tests/components/backup/test_http.py
@@ -21,12 +21,16 @@ async def test_downloading_backup(
client = await hass_client()
- with patch(
- "homeassistant.components.backup.http.BackupManager.get_backup",
- return_value=TEST_BACKUP,
- ), patch("pathlib.Path.exists", return_value=True), patch(
- "homeassistant.components.backup.http.FileResponse",
- return_value=web.Response(text=""),
+ with (
+ patch(
+ "homeassistant.components.backup.http.BackupManager.get_backup",
+ return_value=TEST_BACKUP,
+ ),
+ patch("pathlib.Path.exists", return_value=True),
+ patch(
+ "homeassistant.components.backup.http.FileResponse",
+ return_value=web.Response(text=""),
+ ),
):
resp = await client.get("/api/backup/download/abc123")
assert resp.status == 200
diff --git a/tests/components/backup/test_manager.py b/tests/components/backup/test_manager.py
index 516f8fc1bc4..41749298819 100644
--- a/tests/components/backup/test_manager.py
+++ b/tests/components/backup/test_manager.py
@@ -30,28 +30,37 @@ async def _mock_backup_generation(manager: BackupManager):
Path(".storage"),
]
- with patch(
- "homeassistant.components.backup.manager.SecureTarFile"
- ) as mocked_tarfile, patch("pathlib.Path.iterdir", _mock_iterdir), patch(
- "pathlib.Path.stat", MagicMock(st_size=123)
- ), patch("pathlib.Path.is_file", lambda x: x.name != ".storage"), patch(
- "pathlib.Path.is_dir",
- lambda x: x.name == ".storage",
- ), patch(
- "pathlib.Path.exists",
- lambda x: x != manager.backup_dir,
- ), patch(
- "pathlib.Path.is_symlink",
- lambda _: False,
- ), patch(
- "pathlib.Path.mkdir",
- MagicMock(),
- ), patch(
- "homeassistant.components.backup.manager.json_bytes",
- return_value=b"{}", # Empty JSON
- ) as mocked_json_bytes, patch(
- "homeassistant.components.backup.manager.HAVERSION",
- "2025.1.0",
+ with (
+ patch(
+ "homeassistant.components.backup.manager.SecureTarFile"
+ ) as mocked_tarfile,
+ patch("pathlib.Path.iterdir", _mock_iterdir),
+ patch("pathlib.Path.stat", MagicMock(st_size=123)),
+ patch("pathlib.Path.is_file", lambda x: x.name != ".storage"),
+ patch(
+ "pathlib.Path.is_dir",
+ lambda x: x.name == ".storage",
+ ),
+ patch(
+ "pathlib.Path.exists",
+ lambda x: x != manager.backup_dir,
+ ),
+ patch(
+ "pathlib.Path.is_symlink",
+ lambda _: False,
+ ),
+ patch(
+ "pathlib.Path.mkdir",
+ MagicMock(),
+ ),
+ patch(
+ "homeassistant.components.backup.manager.json_bytes",
+ return_value=b"{}", # Empty JSON
+ ) as mocked_json_bytes,
+ patch(
+ "homeassistant.components.backup.manager.HAVERSION",
+ "2025.1.0",
+ ),
):
await manager.generate_backup()
@@ -82,18 +91,21 @@ async def test_constructor(hass: HomeAssistant) -> None:
async def test_load_backups(hass: HomeAssistant) -> None:
"""Test loading backups."""
manager = BackupManager(hass)
- with patch("pathlib.Path.glob", return_value=[TEST_BACKUP.path]), patch(
- "tarfile.open", return_value=MagicMock()
- ), patch(
- "homeassistant.components.backup.manager.json_loads_object",
- return_value={
- "slug": TEST_BACKUP.slug,
- "name": TEST_BACKUP.name,
- "date": TEST_BACKUP.date,
- },
- ), patch(
- "pathlib.Path.stat",
- return_value=MagicMock(st_size=TEST_BACKUP.size),
+ with (
+ patch("pathlib.Path.glob", return_value=[TEST_BACKUP.path]),
+ patch("tarfile.open", return_value=MagicMock()),
+ patch(
+ "homeassistant.components.backup.manager.json_loads_object",
+ return_value={
+ "slug": TEST_BACKUP.slug,
+ "name": TEST_BACKUP.name,
+ "date": TEST_BACKUP.date,
+ },
+ ),
+ patch(
+ "pathlib.Path.stat",
+ return_value=MagicMock(st_size=TEST_BACKUP.size),
+ ),
):
await manager.load_backups()
backups = await manager.get_backups()
@@ -106,8 +118,9 @@ async def test_load_backups_with_exception(
) -> None:
"""Test loading backups with exception."""
manager = BackupManager(hass)
- with patch("pathlib.Path.glob", return_value=[TEST_BACKUP.path]), patch(
- "tarfile.open", side_effect=OSError("Test exception")
+ with (
+ patch("pathlib.Path.glob", return_value=[TEST_BACKUP.path]),
+ patch("tarfile.open", side_effect=OSError("Test exception")),
):
await manager.load_backups()
backups = await manager.get_backups()
diff --git a/tests/components/baf/test_config_flow.py b/tests/components/baf/test_config_flow.py
index 0369e1e1955..c7c56179839 100644
--- a/tests/components/baf/test_config_flow.py
+++ b/tests/components/baf/test_config_flow.py
@@ -33,10 +33,13 @@ async def test_form_user(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with _patch_device_config_flow(), patch(
- "homeassistant.components.baf.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_device_config_flow(),
+ patch(
+ "homeassistant.components.baf.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_IP_ADDRESS: "127.0.0.1"},
@@ -182,10 +185,13 @@ async def test_user_flow_is_not_blocked_by_discovery(hass: HomeAssistant) -> Non
assert result["type"] == "form"
assert result["errors"] == {}
- with _patch_device_config_flow(), patch(
- "homeassistant.components.baf.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_device_config_flow(),
+ patch(
+ "homeassistant.components.baf.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_IP_ADDRESS: "127.0.0.1"},
diff --git a/tests/components/balboa/test_config_flow.py b/tests/components/balboa/test_config_flow.py
index d2a8def9e63..66bc47d23f0 100644
--- a/tests/components/balboa/test_config_flow.py
+++ b/tests/components/balboa/test_config_flow.py
@@ -26,13 +26,16 @@ async def test_form(hass: HomeAssistant, client: MagicMock) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.balboa.config_flow.SpaClient.__aenter__",
- return_value=client,
- ), patch(
- "homeassistant.components.balboa.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.balboa.config_flow.SpaClient.__aenter__",
+ return_value=client,
+ ),
+ patch(
+ "homeassistant.components.balboa.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
TEST_DATA,
@@ -113,12 +116,15 @@ async def test_already_configured(hass: HomeAssistant, client: MagicMock) -> Non
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.balboa.config_flow.SpaClient.__aenter__",
- return_value=client,
- ), patch(
- "homeassistant.components.balboa.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.balboa.config_flow.SpaClient.__aenter__",
+ return_value=client,
+ ),
+ patch(
+ "homeassistant.components.balboa.async_setup_entry",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/bang_olufsen/conftest.py b/tests/components/bang_olufsen/conftest.py
index b7b6b84b7fd..d076316e36c 100644
--- a/tests/components/bang_olufsen/conftest.py
+++ b/tests/components/bang_olufsen/conftest.py
@@ -34,11 +34,14 @@ def mock_config_entry():
def mock_mozart_client() -> Generator[AsyncMock, None, None]:
"""Mock MozartClient."""
- with patch(
- "homeassistant.components.bang_olufsen.MozartClient", autospec=True
- ) as mock_client, patch(
- "homeassistant.components.bang_olufsen.config_flow.MozartClient",
- new=mock_client,
+ with (
+ patch(
+ "homeassistant.components.bang_olufsen.MozartClient", autospec=True
+ ) as mock_client,
+ patch(
+ "homeassistant.components.bang_olufsen.config_flow.MozartClient",
+ new=mock_client,
+ ),
):
client = mock_client.return_value
client.get_beolink_self = AsyncMock()
diff --git a/tests/components/blink/test_config_flow.py b/tests/components/blink/test_config_flow.py
index 304f1bd97a9..b5fbf19ef9b 100644
--- a/tests/components/blink/test_config_flow.py
+++ b/tests/components/blink/test_config_flow.py
@@ -19,13 +19,17 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch("homeassistant.components.blink.config_flow.Auth.startup"), patch(
- "homeassistant.components.blink.config_flow.Auth.check_key_required",
- return_value=False,
- ), patch(
- "homeassistant.components.blink.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("homeassistant.components.blink.config_flow.Auth.startup"),
+ patch(
+ "homeassistant.components.blink.config_flow.Auth.check_key_required",
+ return_value=False,
+ ),
+ patch(
+ "homeassistant.components.blink.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"username": "blink@example.com", "password": "example"},
@@ -55,9 +59,12 @@ async def test_form_2fa(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch("homeassistant.components.blink.config_flow.Auth.startup"), patch(
- "homeassistant.components.blink.config_flow.Auth.check_key_required",
- return_value=True,
+ with (
+ patch("homeassistant.components.blink.config_flow.Auth.startup"),
+ patch(
+ "homeassistant.components.blink.config_flow.Auth.check_key_required",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -67,18 +74,24 @@ async def test_form_2fa(hass: HomeAssistant) -> None:
assert result2["type"] == "form"
assert result2["step_id"] == "2fa"
- with patch("homeassistant.components.blink.config_flow.Auth.startup"), patch(
- "homeassistant.components.blink.config_flow.Auth.check_key_required",
- return_value=False,
- ), patch(
- "homeassistant.components.blink.config_flow.Auth.send_auth_key",
- return_value=True,
- ), patch(
- "homeassistant.components.blink.config_flow.Blink.setup_urls",
- return_value=True,
- ), patch(
- "homeassistant.components.blink.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch("homeassistant.components.blink.config_flow.Auth.startup"),
+ patch(
+ "homeassistant.components.blink.config_flow.Auth.check_key_required",
+ return_value=False,
+ ),
+ patch(
+ "homeassistant.components.blink.config_flow.Auth.send_auth_key",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.blink.config_flow.Blink.setup_urls",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.blink.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"], {"pin": "1234"}
)
@@ -97,9 +110,12 @@ async def test_form_2fa_connect_error(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch("homeassistant.components.blink.config_flow.Auth.startup"), patch(
- "homeassistant.components.blink.config_flow.Auth.check_key_required",
- return_value=True,
+ with (
+ patch("homeassistant.components.blink.config_flow.Auth.startup"),
+ patch(
+ "homeassistant.components.blink.config_flow.Auth.check_key_required",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -109,18 +125,24 @@ async def test_form_2fa_connect_error(hass: HomeAssistant) -> None:
assert result2["type"] == "form"
assert result2["step_id"] == "2fa"
- with patch("homeassistant.components.blink.config_flow.Auth.startup"), patch(
- "homeassistant.components.blink.config_flow.Auth.check_key_required",
- return_value=False,
- ), patch(
- "homeassistant.components.blink.config_flow.Auth.send_auth_key",
- return_value=True,
- ), patch(
- "homeassistant.components.blink.config_flow.Blink.setup_urls",
- side_effect=BlinkSetupError,
- ), patch(
- "homeassistant.components.blink.async_setup_entry",
- return_value=True,
+ with (
+ patch("homeassistant.components.blink.config_flow.Auth.startup"),
+ patch(
+ "homeassistant.components.blink.config_flow.Auth.check_key_required",
+ return_value=False,
+ ),
+ patch(
+ "homeassistant.components.blink.config_flow.Auth.send_auth_key",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.blink.config_flow.Blink.setup_urls",
+ side_effect=BlinkSetupError,
+ ),
+ patch(
+ "homeassistant.components.blink.async_setup_entry",
+ return_value=True,
+ ),
):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"], {"pin": "1234"}
@@ -137,9 +159,12 @@ async def test_form_2fa_invalid_key(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch("homeassistant.components.blink.config_flow.Auth.startup"), patch(
- "homeassistant.components.blink.config_flow.Auth.check_key_required",
- return_value=True,
+ with (
+ patch("homeassistant.components.blink.config_flow.Auth.startup"),
+ patch(
+ "homeassistant.components.blink.config_flow.Auth.check_key_required",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -149,20 +174,26 @@ async def test_form_2fa_invalid_key(hass: HomeAssistant) -> None:
assert result2["type"] == "form"
assert result2["step_id"] == "2fa"
- with patch(
- "homeassistant.components.blink.config_flow.Auth.startup",
- ), patch(
- "homeassistant.components.blink.config_flow.Auth.check_key_required",
- return_value=False,
- ), patch(
- "homeassistant.components.blink.config_flow.Auth.send_auth_key",
- return_value=False,
- ), patch(
- "homeassistant.components.blink.config_flow.Blink.setup_urls",
- return_value=True,
- ), patch(
- "homeassistant.components.blink.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.blink.config_flow.Auth.startup",
+ ),
+ patch(
+ "homeassistant.components.blink.config_flow.Auth.check_key_required",
+ return_value=False,
+ ),
+ patch(
+ "homeassistant.components.blink.config_flow.Auth.send_auth_key",
+ return_value=False,
+ ),
+ patch(
+ "homeassistant.components.blink.config_flow.Blink.setup_urls",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.blink.async_setup_entry",
+ return_value=True,
+ ),
):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"], {"pin": "1234"}
@@ -179,9 +210,12 @@ async def test_form_2fa_unknown_error(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch("homeassistant.components.blink.config_flow.Auth.startup"), patch(
- "homeassistant.components.blink.config_flow.Auth.check_key_required",
- return_value=True,
+ with (
+ patch("homeassistant.components.blink.config_flow.Auth.startup"),
+ patch(
+ "homeassistant.components.blink.config_flow.Auth.check_key_required",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -191,18 +225,24 @@ async def test_form_2fa_unknown_error(hass: HomeAssistant) -> None:
assert result2["type"] == "form"
assert result2["step_id"] == "2fa"
- with patch("homeassistant.components.blink.config_flow.Auth.startup"), patch(
- "homeassistant.components.blink.config_flow.Auth.check_key_required",
- return_value=False,
- ), patch(
- "homeassistant.components.blink.config_flow.Auth.send_auth_key",
- return_value=True,
- ), patch(
- "homeassistant.components.blink.config_flow.Blink.setup_urls",
- side_effect=KeyError,
- ), patch(
- "homeassistant.components.blink.async_setup_entry",
- return_value=True,
+ with (
+ patch("homeassistant.components.blink.config_flow.Auth.startup"),
+ patch(
+ "homeassistant.components.blink.config_flow.Auth.check_key_required",
+ return_value=False,
+ ),
+ patch(
+ "homeassistant.components.blink.config_flow.Auth.send_auth_key",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.blink.config_flow.Blink.setup_urls",
+ side_effect=KeyError,
+ ),
+ patch(
+ "homeassistant.components.blink.async_setup_entry",
+ return_value=True,
+ ),
):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"], {"pin": "1234"}
diff --git a/tests/components/blueprint/test_models.py b/tests/components/blueprint/test_models.py
index 2bc6d60ccda..96e72e2b4cc 100644
--- a/tests/components/blueprint/test_models.py
+++ b/tests/components/blueprint/test_models.py
@@ -207,14 +207,18 @@ async def test_domain_blueprints_get_blueprint_errors(
"""Test domain blueprints."""
assert hass.data["blueprint"]["automation"] is domain_bps
- with pytest.raises(errors.FailedToLoad), patch(
- "homeassistant.util.yaml.load_yaml", side_effect=FileNotFoundError
+ with (
+ pytest.raises(errors.FailedToLoad),
+ patch("homeassistant.util.yaml.load_yaml", side_effect=FileNotFoundError),
):
await domain_bps.async_get_blueprint("non-existing-path")
- with patch(
- "homeassistant.util.yaml.load_yaml", return_value={"blueprint": "invalid"}
- ), pytest.raises(errors.FailedToLoad):
+ with (
+ patch(
+ "homeassistant.util.yaml.load_yaml", return_value={"blueprint": "invalid"}
+ ),
+ pytest.raises(errors.FailedToLoad),
+ ):
await domain_bps.async_get_blueprint("non-existing-path")
@@ -240,8 +244,9 @@ async def test_domain_blueprints_inputs_from_config(domain_bps, blueprint_1) ->
with pytest.raises(errors.InvalidBlueprintInputs):
await domain_bps.async_inputs_from_config({"not-referencing": "use_blueprint"})
- with pytest.raises(errors.MissingInput), patch.object(
- domain_bps, "async_get_blueprint", return_value=blueprint_1
+ with (
+ pytest.raises(errors.MissingInput),
+ patch.object(domain_bps, "async_get_blueprint", return_value=blueprint_1),
):
await domain_bps.async_inputs_from_config(
{"use_blueprint": {"path": "bla.yaml", "input": {}}}
diff --git a/tests/components/bluetooth/__init__.py b/tests/components/bluetooth/__init__.py
index b6d7220da16..675f3de67ee 100644
--- a/tests/components/bluetooth/__init__.py
+++ b/tests/components/bluetooth/__init__.py
@@ -58,13 +58,14 @@ BLE_DEVICE_DEFAULTS = {
@contextmanager
def patch_bluetooth_time(mock_time: float) -> None:
"""Patch the bluetooth time."""
- with patch(
- "homeassistant.components.bluetooth.MONOTONIC_TIME", return_value=mock_time
- ), patch(
- "habluetooth.base_scanner.monotonic_time_coarse", return_value=mock_time
- ), patch(
- "habluetooth.manager.monotonic_time_coarse", return_value=mock_time
- ), patch("habluetooth.scanner.monotonic_time_coarse", return_value=mock_time):
+ with (
+ patch(
+ "homeassistant.components.bluetooth.MONOTONIC_TIME", return_value=mock_time
+ ),
+ patch("habluetooth.base_scanner.monotonic_time_coarse", return_value=mock_time),
+ patch("habluetooth.manager.monotonic_time_coarse", return_value=mock_time),
+ patch("habluetooth.scanner.monotonic_time_coarse", return_value=mock_time),
+ ):
yield
diff --git a/tests/components/bluetooth/conftest.py b/tests/components/bluetooth/conftest.py
index 3c23c7428fb..c1e040ccd49 100644
--- a/tests/components/bluetooth/conftest.py
+++ b/tests/components/bluetooth/conftest.py
@@ -32,18 +32,21 @@ def disable_bluetooth_auto_recovery():
@pytest.fixture(name="operating_system_85")
def mock_operating_system_85():
"""Mock running Home Assistant Operating system 8.5."""
- with patch("homeassistant.components.hassio.is_hassio", return_value=True), patch(
- "homeassistant.components.hassio.get_os_info",
- return_value={
- "version": "8.5",
- "version_latest": "10.0.dev20220912",
- "update_available": False,
- "board": "odroid-n2",
- "boot": "B",
- "data_disk": "/dev/mmcblk1p4",
- },
- ), patch("homeassistant.components.hassio.get_info", return_value={}), patch(
- "homeassistant.components.hassio.get_host_info", return_value={}
+ with (
+ patch("homeassistant.components.hassio.is_hassio", return_value=True),
+ patch(
+ "homeassistant.components.hassio.get_os_info",
+ return_value={
+ "version": "8.5",
+ "version_latest": "10.0.dev20220912",
+ "update_available": False,
+ "board": "odroid-n2",
+ "boot": "B",
+ "data_disk": "/dev/mmcblk1p4",
+ },
+ ),
+ patch("homeassistant.components.hassio.get_info", return_value={}),
+ patch("homeassistant.components.hassio.get_host_info", return_value={}),
):
yield
@@ -51,18 +54,21 @@ def mock_operating_system_85():
@pytest.fixture(name="operating_system_90")
def mock_operating_system_90():
"""Mock running Home Assistant Operating system 9.0."""
- with patch("homeassistant.components.hassio.is_hassio", return_value=True), patch(
- "homeassistant.components.hassio.get_os_info",
- return_value={
- "version": "9.0.dev20220912",
- "version_latest": "10.0.dev20220912",
- "update_available": False,
- "board": "odroid-n2",
- "boot": "B",
- "data_disk": "/dev/mmcblk1p4",
- },
- ), patch("homeassistant.components.hassio.get_info", return_value={}), patch(
- "homeassistant.components.hassio.get_host_info", return_value={}
+ with (
+ patch("homeassistant.components.hassio.is_hassio", return_value=True),
+ patch(
+ "homeassistant.components.hassio.get_os_info",
+ return_value={
+ "version": "9.0.dev20220912",
+ "version_latest": "10.0.dev20220912",
+ "update_available": False,
+ "board": "odroid-n2",
+ "boot": "B",
+ "data_disk": "/dev/mmcblk1p4",
+ },
+ ),
+ patch("homeassistant.components.hassio.get_info", return_value={}),
+ patch("homeassistant.components.hassio.get_host_info", return_value={}),
):
yield
@@ -70,46 +76,62 @@ def mock_operating_system_90():
@pytest.fixture(name="macos_adapter")
def macos_adapter():
"""Fixture that mocks the macos adapter."""
- with patch("bleak.get_platform_scanner_backend_type"), patch(
- "homeassistant.components.bluetooth.platform.system",
- return_value="Darwin",
- ), patch(
- "habluetooth.scanner.platform.system",
- return_value="Darwin",
- ), patch(
- "bluetooth_adapters.systems.platform.system",
- return_value="Darwin",
- ), patch("habluetooth.scanner.SYSTEM", "Darwin"):
+ with (
+ patch("bleak.get_platform_scanner_backend_type"),
+ patch(
+ "homeassistant.components.bluetooth.platform.system",
+ return_value="Darwin",
+ ),
+ patch(
+ "habluetooth.scanner.platform.system",
+ return_value="Darwin",
+ ),
+ patch(
+ "bluetooth_adapters.systems.platform.system",
+ return_value="Darwin",
+ ),
+ patch("habluetooth.scanner.SYSTEM", "Darwin"),
+ ):
yield
@pytest.fixture(name="windows_adapter")
def windows_adapter():
"""Fixture that mocks the windows adapter."""
- with patch(
- "bluetooth_adapters.systems.platform.system",
- return_value="Windows",
- ), patch("habluetooth.scanner.SYSTEM", "Windows"):
+ with (
+ patch(
+ "bluetooth_adapters.systems.platform.system",
+ return_value="Windows",
+ ),
+ patch("habluetooth.scanner.SYSTEM", "Windows"),
+ ):
yield
@pytest.fixture(name="no_adapters")
def no_adapter_fixture():
"""Fixture that mocks no adapters on Linux."""
- with patch(
- "homeassistant.components.bluetooth.platform.system",
- return_value="Linux",
- ), patch(
- "habluetooth.scanner.platform.system",
- return_value="Linux",
- ), patch(
- "bluetooth_adapters.systems.platform.system",
- return_value="Linux",
- ), patch("habluetooth.scanner.SYSTEM", "Linux"), patch(
- "bluetooth_adapters.systems.linux.LinuxAdapters.refresh",
- ), patch(
- "bluetooth_adapters.systems.linux.LinuxAdapters.adapters",
- {},
+ with (
+ patch(
+ "homeassistant.components.bluetooth.platform.system",
+ return_value="Linux",
+ ),
+ patch(
+ "habluetooth.scanner.platform.system",
+ return_value="Linux",
+ ),
+ patch(
+ "bluetooth_adapters.systems.platform.system",
+ return_value="Linux",
+ ),
+ patch("habluetooth.scanner.SYSTEM", "Linux"),
+ patch(
+ "bluetooth_adapters.systems.linux.LinuxAdapters.refresh",
+ ),
+ patch(
+ "bluetooth_adapters.systems.linux.LinuxAdapters.adapters",
+ {},
+ ),
):
yield
@@ -117,31 +139,38 @@ def no_adapter_fixture():
@pytest.fixture(name="one_adapter")
def one_adapter_fixture():
"""Fixture that mocks one adapter on Linux."""
- with patch(
- "homeassistant.components.bluetooth.platform.system",
- return_value="Linux",
- ), patch(
- "habluetooth.scanner.platform.system",
- return_value="Linux",
- ), patch(
- "bluetooth_adapters.systems.platform.system",
- return_value="Linux",
- ), patch("habluetooth.scanner.SYSTEM", "Linux"), patch(
- "bluetooth_adapters.systems.linux.LinuxAdapters.refresh",
- ), patch(
- "bluetooth_adapters.systems.linux.LinuxAdapters.adapters",
- {
- "hci0": {
- "address": "00:00:00:00:00:01",
- "hw_version": "usb:v1D6Bp0246d053F",
- "passive_scan": True,
- "sw_version": "homeassistant",
- "manufacturer": "ACME",
- "product": "Bluetooth Adapter 5.0",
- "product_id": "aa01",
- "vendor_id": "cc01",
+ with (
+ patch(
+ "homeassistant.components.bluetooth.platform.system",
+ return_value="Linux",
+ ),
+ patch(
+ "habluetooth.scanner.platform.system",
+ return_value="Linux",
+ ),
+ patch(
+ "bluetooth_adapters.systems.platform.system",
+ return_value="Linux",
+ ),
+ patch("habluetooth.scanner.SYSTEM", "Linux"),
+ patch(
+ "bluetooth_adapters.systems.linux.LinuxAdapters.refresh",
+ ),
+ patch(
+ "bluetooth_adapters.systems.linux.LinuxAdapters.adapters",
+ {
+ "hci0": {
+ "address": "00:00:00:00:00:01",
+ "hw_version": "usb:v1D6Bp0246d053F",
+ "passive_scan": True,
+ "sw_version": "homeassistant",
+ "manufacturer": "ACME",
+ "product": "Bluetooth Adapter 5.0",
+ "product_id": "aa01",
+ "vendor_id": "cc01",
+ },
},
- },
+ ),
):
yield
@@ -149,39 +178,43 @@ def one_adapter_fixture():
@pytest.fixture(name="two_adapters")
def two_adapters_fixture():
"""Fixture that mocks two adapters on Linux."""
- with patch(
- "homeassistant.components.bluetooth.platform.system", return_value="Linux"
- ), patch(
- "habluetooth.scanner.platform.system",
- return_value="Linux",
- ), patch("bluetooth_adapters.systems.platform.system", return_value="Linux"), patch(
- "bluetooth_adapters.systems.linux.LinuxAdapters.refresh"
- ), patch(
- "bluetooth_adapters.systems.linux.LinuxAdapters.adapters",
- {
- "hci0": {
- "address": "00:00:00:00:00:01",
- "hw_version": "usb:v1D6Bp0246d053F",
- "passive_scan": False,
- "sw_version": "homeassistant",
- "manufacturer": "ACME",
- "product": "Bluetooth Adapter 5.0",
- "product_id": "aa01",
- "vendor_id": "cc01",
- "connection_slots": 1,
+ with (
+ patch(
+ "homeassistant.components.bluetooth.platform.system", return_value="Linux"
+ ),
+ patch(
+ "habluetooth.scanner.platform.system",
+ return_value="Linux",
+ ),
+ patch("bluetooth_adapters.systems.platform.system", return_value="Linux"),
+ patch("bluetooth_adapters.systems.linux.LinuxAdapters.refresh"),
+ patch(
+ "bluetooth_adapters.systems.linux.LinuxAdapters.adapters",
+ {
+ "hci0": {
+ "address": "00:00:00:00:00:01",
+ "hw_version": "usb:v1D6Bp0246d053F",
+ "passive_scan": False,
+ "sw_version": "homeassistant",
+ "manufacturer": "ACME",
+ "product": "Bluetooth Adapter 5.0",
+ "product_id": "aa01",
+ "vendor_id": "cc01",
+ "connection_slots": 1,
+ },
+ "hci1": {
+ "address": "00:00:00:00:00:02",
+ "hw_version": "usb:v1D6Bp0246d053F",
+ "passive_scan": True,
+ "sw_version": "homeassistant",
+ "manufacturer": "ACME",
+ "product": "Bluetooth Adapter 5.0",
+ "product_id": "aa01",
+ "vendor_id": "cc01",
+ "connection_slots": 2,
+ },
},
- "hci1": {
- "address": "00:00:00:00:00:02",
- "hw_version": "usb:v1D6Bp0246d053F",
- "passive_scan": True,
- "sw_version": "homeassistant",
- "manufacturer": "ACME",
- "product": "Bluetooth Adapter 5.0",
- "product_id": "aa01",
- "vendor_id": "cc01",
- "connection_slots": 2,
- },
- },
+ ),
):
yield
@@ -189,27 +222,31 @@ def two_adapters_fixture():
@pytest.fixture(name="one_adapter_old_bluez")
def one_adapter_old_bluez():
"""Fixture that mocks two adapters on Linux."""
- with patch(
- "homeassistant.components.bluetooth.platform.system", return_value="Linux"
- ), patch(
- "habluetooth.scanner.platform.system",
- return_value="Linux",
- ), patch("bluetooth_adapters.systems.platform.system", return_value="Linux"), patch(
- "bluetooth_adapters.systems.linux.LinuxAdapters.refresh"
- ), patch(
- "bluetooth_adapters.systems.linux.LinuxAdapters.adapters",
- {
- "hci0": {
- "address": "00:00:00:00:00:01",
- "hw_version": "usb:v1D6Bp0246d053F",
- "passive_scan": False,
- "sw_version": "homeassistant",
- "manufacturer": "ACME",
- "product": "Bluetooth Adapter 5.0",
- "product_id": "aa01",
- "vendor_id": "cc01",
+ with (
+ patch(
+ "homeassistant.components.bluetooth.platform.system", return_value="Linux"
+ ),
+ patch(
+ "habluetooth.scanner.platform.system",
+ return_value="Linux",
+ ),
+ patch("bluetooth_adapters.systems.platform.system", return_value="Linux"),
+ patch("bluetooth_adapters.systems.linux.LinuxAdapters.refresh"),
+ patch(
+ "bluetooth_adapters.systems.linux.LinuxAdapters.adapters",
+ {
+ "hci0": {
+ "address": "00:00:00:00:00:01",
+ "hw_version": "usb:v1D6Bp0246d053F",
+ "passive_scan": False,
+ "sw_version": "homeassistant",
+ "manufacturer": "ACME",
+ "product": "Bluetooth Adapter 5.0",
+ "product_id": "aa01",
+ "vendor_id": "cc01",
+ },
},
- },
+ ),
):
yield
diff --git a/tests/components/bluetooth/test_base_scanner.py b/tests/components/bluetooth/test_base_scanner.py
index cd3cea5c33a..0839c9c56a4 100644
--- a/tests/components/bluetooth/test_base_scanner.py
+++ b/tests/components/bluetooth/test_base_scanner.py
@@ -348,11 +348,14 @@ async def test_restore_history_remote_adapter(
if address != "E3:A5:63:3E:5E:23":
timestamps[address] = now
- with patch(
- "bluetooth_adapters.systems.linux.LinuxAdapters.history",
- {},
- ), patch(
- "bluetooth_adapters.systems.linux.LinuxAdapters.refresh",
+ with (
+ patch(
+ "bluetooth_adapters.systems.linux.LinuxAdapters.history",
+ {},
+ ),
+ patch(
+ "bluetooth_adapters.systems.linux.LinuxAdapters.refresh",
+ ),
):
assert await async_setup_component(hass, bluetooth.DOMAIN, {})
await hass.async_block_till_done()
diff --git a/tests/components/bluetooth/test_config_flow.py b/tests/components/bluetooth/test_config_flow.py
index bc8e93d6b38..9ca674e2d32 100644
--- a/tests/components/bluetooth/test_config_flow.py
+++ b/tests/components/bluetooth/test_config_flow.py
@@ -55,11 +55,12 @@ async def test_async_step_user_macos(hass: HomeAssistant, macos_adapter: None) -
)
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "single_adapter"
- with patch(
- "homeassistant.components.bluetooth.async_setup", return_value=True
- ), patch(
- "homeassistant.components.bluetooth.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch("homeassistant.components.bluetooth.async_setup", return_value=True),
+ patch(
+ "homeassistant.components.bluetooth.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
@@ -80,11 +81,12 @@ async def test_async_step_user_linux_one_adapter(
)
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "single_adapter"
- with patch(
- "homeassistant.components.bluetooth.async_setup", return_value=True
- ), patch(
- "homeassistant.components.bluetooth.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch("homeassistant.components.bluetooth.async_setup", return_value=True),
+ patch(
+ "homeassistant.components.bluetooth.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
@@ -105,11 +107,12 @@ async def test_async_step_user_linux_two_adapters(
)
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "multiple_adapters"
- with patch(
- "homeassistant.components.bluetooth.async_setup", return_value=True
- ), patch(
- "homeassistant.components.bluetooth.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch("homeassistant.components.bluetooth.async_setup", return_value=True),
+ patch(
+ "homeassistant.components.bluetooth.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_ADAPTER: "hci1"}
)
@@ -151,11 +154,12 @@ async def test_async_step_integration_discovery(hass: HomeAssistant) -> None:
)
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "single_adapter"
- with patch(
- "homeassistant.components.bluetooth.async_setup", return_value=True
- ), patch(
- "homeassistant.components.bluetooth.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch("homeassistant.components.bluetooth.async_setup", return_value=True),
+ patch(
+ "homeassistant.components.bluetooth.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
@@ -176,14 +180,16 @@ async def test_async_step_integration_discovery_during_onboarding_one_adapter(
manufacturer="ACME",
)
- with patch(
- "homeassistant.components.bluetooth.async_setup", return_value=True
- ), patch(
- "homeassistant.components.bluetooth.async_setup_entry", return_value=True
- ) as mock_setup_entry, patch(
- "homeassistant.components.onboarding.async_is_onboarded",
- return_value=False,
- ) as mock_onboarding:
+ with (
+ patch("homeassistant.components.bluetooth.async_setup", return_value=True),
+ patch(
+ "homeassistant.components.bluetooth.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.onboarding.async_is_onboarded",
+ return_value=False,
+ ) as mock_onboarding,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY},
@@ -213,14 +219,16 @@ async def test_async_step_integration_discovery_during_onboarding_two_adapters(
manufacturer="ACME",
)
- with patch(
- "homeassistant.components.bluetooth.async_setup", return_value=True
- ), patch(
- "homeassistant.components.bluetooth.async_setup_entry", return_value=True
- ) as mock_setup_entry, patch(
- "homeassistant.components.onboarding.async_is_onboarded",
- return_value=False,
- ) as mock_onboarding:
+ with (
+ patch("homeassistant.components.bluetooth.async_setup", return_value=True),
+ patch(
+ "homeassistant.components.bluetooth.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.onboarding.async_is_onboarded",
+ return_value=False,
+ ) as mock_onboarding,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY},
@@ -254,14 +262,16 @@ async def test_async_step_integration_discovery_during_onboarding(
manufacturer="ACME",
)
- with patch(
- "homeassistant.components.bluetooth.async_setup", return_value=True
- ), patch(
- "homeassistant.components.bluetooth.async_setup_entry", return_value=True
- ) as mock_setup_entry, patch(
- "homeassistant.components.onboarding.async_is_onboarded",
- return_value=False,
- ) as mock_onboarding:
+ with (
+ patch("homeassistant.components.bluetooth.async_setup", return_value=True),
+ patch(
+ "homeassistant.components.bluetooth.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.onboarding.async_is_onboarded",
+ return_value=False,
+ ) as mock_onboarding,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY},
diff --git a/tests/components/bluetooth/test_diagnostics.py b/tests/components/bluetooth/test_diagnostics.py
index 0cd96854320..3d29080d56c 100644
--- a/tests/components/bluetooth/test_diagnostics.py
+++ b/tests/components/bluetooth/test_diagnostics.py
@@ -57,27 +57,30 @@ async def test_diagnostics(
# error if the test is not running on linux since we won't have the correct
# deps installed when testing on MacOS.
- with patch(
- "homeassistant.components.bluetooth.diagnostics.platform.system",
- return_value="Linux",
- ), patch(
- "homeassistant.components.bluetooth.diagnostics.get_dbus_managed_objects",
- return_value={
- "org.bluez": {
- "/org/bluez/hci0": {
- "org.bluez.Adapter1": {
- "Name": "BlueZ 5.63",
- "Alias": "BlueZ 5.63",
- "Modalias": "usb:v1D6Bp0246d0540",
- "Discovering": False,
- },
- "org.bluez.AdvertisementMonitorManager1": {
- "SupportedMonitorTypes": ["or_patterns"],
- "SupportedFeatures": [],
- },
+ with (
+ patch(
+ "homeassistant.components.bluetooth.diagnostics.platform.system",
+ return_value="Linux",
+ ),
+ patch(
+ "homeassistant.components.bluetooth.diagnostics.get_dbus_managed_objects",
+ return_value={
+ "org.bluez": {
+ "/org/bluez/hci0": {
+ "org.bluez.Adapter1": {
+ "Name": "BlueZ 5.63",
+ "Alias": "BlueZ 5.63",
+ "Modalias": "usb:v1D6Bp0246d0540",
+ "Discovering": False,
+ },
+ "org.bluez.AdvertisementMonitorManager1": {
+ "SupportedMonitorTypes": ["or_patterns"],
+ "SupportedFeatures": [],
+ },
+ }
}
- }
- },
+ },
+ ),
):
entry2 = MockConfigEntry(
domain=bluetooth.DOMAIN, data={}, unique_id="00:00:00:00:00:02"
@@ -236,12 +239,15 @@ async def test_diagnostics_macos(
local_name="wohand", service_uuids=[], manufacturer_data={1: b"\x01"}
)
- with patch(
- "homeassistant.components.bluetooth.diagnostics.platform.system",
- return_value="Darwin",
- ), patch(
- "homeassistant.components.bluetooth.diagnostics.get_dbus_managed_objects",
- return_value={},
+ with (
+ patch(
+ "homeassistant.components.bluetooth.diagnostics.platform.system",
+ return_value="Darwin",
+ ),
+ patch(
+ "homeassistant.components.bluetooth.diagnostics.get_dbus_managed_objects",
+ return_value={},
+ ),
):
entry1 = MockConfigEntry(
domain=bluetooth.DOMAIN,
@@ -414,12 +420,15 @@ async def test_diagnostics_remote_adapter(
MONOTONIC_TIME(),
)
- with patch(
- "homeassistant.components.bluetooth.diagnostics.platform.system",
- return_value="Linux",
- ), patch(
- "homeassistant.components.bluetooth.diagnostics.get_dbus_managed_objects",
- return_value={},
+ with (
+ patch(
+ "homeassistant.components.bluetooth.diagnostics.platform.system",
+ return_value="Linux",
+ ),
+ patch(
+ "homeassistant.components.bluetooth.diagnostics.get_dbus_managed_objects",
+ return_value={},
+ ),
):
entry1 = hass.config_entries.async_entries(bluetooth.DOMAIN)[0]
connector = (
diff --git a/tests/components/bluetooth/test_init.py b/tests/components/bluetooth/test_init.py
index 2130e883af4..e9198362d8f 100644
--- a/tests/components/bluetooth/test_init.py
+++ b/tests/components/bluetooth/test_init.py
@@ -66,9 +66,13 @@ async def test_setup_and_stop(
mock_bt = [
{"domain": "switchbot", "service_uuid": "cba20d00-224d-11e6-9fb8-0002a5d5c51b"}
]
- with patch(
- "homeassistant.components.bluetooth.async_get_bluetooth", return_value=mock_bt
- ), patch.object(hass.config_entries.flow, "async_init"):
+ with (
+ patch(
+ "homeassistant.components.bluetooth.async_get_bluetooth",
+ return_value=mock_bt,
+ ),
+ patch.object(hass.config_entries.flow, "async_init"),
+ ):
assert await async_setup_component(
hass, bluetooth.DOMAIN, {bluetooth.DOMAIN: {}}
)
@@ -186,12 +190,17 @@ async def test_setup_and_stop_no_bluetooth(
mock_bt = [
{"domain": "switchbot", "service_uuid": "cba20d00-224d-11e6-9fb8-0002a5d5c51b"}
]
- with patch(
- "habluetooth.scanner.OriginalBleakScanner",
- side_effect=BleakError,
- ) as mock_ha_bleak_scanner, patch(
- "homeassistant.components.bluetooth.async_get_bluetooth", return_value=mock_bt
- ), patch("homeassistant.components.bluetooth.discovery_flow.async_create_flow"):
+ with (
+ patch(
+ "habluetooth.scanner.OriginalBleakScanner",
+ side_effect=BleakError,
+ ) as mock_ha_bleak_scanner,
+ patch(
+ "homeassistant.components.bluetooth.async_get_bluetooth",
+ return_value=mock_bt,
+ ),
+ patch("homeassistant.components.bluetooth.discovery_flow.async_create_flow"),
+ ):
await async_setup_with_one_adapter(hass)
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
@@ -207,11 +216,15 @@ async def test_setup_and_stop_broken_bluetooth(
) -> None:
"""Test we fail gracefully when bluetooth/dbus is broken."""
mock_bt = []
- with patch(
- "habluetooth.scanner.OriginalBleakScanner.start",
- side_effect=BleakError,
- ), patch(
- "homeassistant.components.bluetooth.async_get_bluetooth", return_value=mock_bt
+ with (
+ patch(
+ "habluetooth.scanner.OriginalBleakScanner.start",
+ side_effect=BleakError,
+ ),
+ patch(
+ "homeassistant.components.bluetooth.async_get_bluetooth",
+ return_value=mock_bt,
+ ),
):
await async_setup_with_default_adapter(hass)
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -232,11 +245,16 @@ async def test_setup_and_stop_broken_bluetooth_hanging(
async def _mock_hang():
await asyncio.sleep(1)
- with patch.object(scanner, "START_TIMEOUT", 0), patch(
- "habluetooth.scanner.OriginalBleakScanner.start",
- side_effect=_mock_hang,
- ), patch(
- "homeassistant.components.bluetooth.async_get_bluetooth", return_value=mock_bt
+ with (
+ patch.object(scanner, "START_TIMEOUT", 0),
+ patch(
+ "habluetooth.scanner.OriginalBleakScanner.start",
+ side_effect=_mock_hang,
+ ),
+ patch(
+ "homeassistant.components.bluetooth.async_get_bluetooth",
+ return_value=mock_bt,
+ ),
):
await async_setup_with_default_adapter(hass)
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -252,11 +270,15 @@ async def test_setup_and_retry_adapter_not_yet_available(
) -> None:
"""Test we retry if the adapter is not yet available."""
mock_bt = []
- with patch(
- "habluetooth.scanner.OriginalBleakScanner.start",
- side_effect=BleakError,
- ), patch(
- "homeassistant.components.bluetooth.async_get_bluetooth", return_value=mock_bt
+ with (
+ patch(
+ "habluetooth.scanner.OriginalBleakScanner.start",
+ side_effect=BleakError,
+ ),
+ patch(
+ "homeassistant.components.bluetooth.async_get_bluetooth",
+ return_value=mock_bt,
+ ),
):
await async_setup_with_default_adapter(hass)
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -287,11 +309,15 @@ async def test_no_race_during_manual_reload_in_retry_state(
) -> None:
"""Test we can successfully reload when the entry is in a retry state."""
mock_bt = []
- with patch(
- "habluetooth.scanner.OriginalBleakScanner.start",
- side_effect=BleakError,
- ), patch(
- "homeassistant.components.bluetooth.async_get_bluetooth", return_value=mock_bt
+ with (
+ patch(
+ "habluetooth.scanner.OriginalBleakScanner.start",
+ side_effect=BleakError,
+ ),
+ patch(
+ "homeassistant.components.bluetooth.async_get_bluetooth",
+ return_value=mock_bt,
+ ),
):
await async_setup_with_default_adapter(hass)
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -323,11 +349,15 @@ async def test_calling_async_discovered_devices_no_bluetooth(
) -> None:
"""Test we fail gracefully when asking for discovered devices and there is no blueooth."""
mock_bt = []
- with patch(
- "habluetooth.scanner.OriginalBleakScanner",
- side_effect=FileNotFoundError,
- ), patch(
- "homeassistant.components.bluetooth.async_get_bluetooth", return_value=mock_bt
+ with (
+ patch(
+ "habluetooth.scanner.OriginalBleakScanner",
+ side_effect=FileNotFoundError,
+ ),
+ patch(
+ "homeassistant.components.bluetooth.async_get_bluetooth",
+ return_value=mock_bt,
+ ),
):
await async_setup_with_default_adapter(hass)
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -347,9 +377,13 @@ async def test_discovery_match_by_service_uuid(
mock_bt = [
{"domain": "switchbot", "service_uuid": "cba20d00-224d-11e6-9fb8-0002a5d5c51b"}
]
- with patch(
- "homeassistant.components.bluetooth.async_get_bluetooth", return_value=mock_bt
- ), patch.object(hass.config_entries.flow, "async_init") as mock_config_flow:
+ with (
+ patch(
+ "homeassistant.components.bluetooth.async_get_bluetooth",
+ return_value=mock_bt,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ ):
await async_setup_with_default_adapter(hass)
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
@@ -444,9 +478,13 @@ async def test_discovery_match_by_service_uuid_connectable(
"service_uuid": "cba20d00-224d-11e6-9fb8-0002a5d5c51b",
}
]
- with patch(
- "homeassistant.components.bluetooth.async_get_bluetooth", return_value=mock_bt
- ), patch.object(hass.config_entries.flow, "async_init") as mock_config_flow:
+ with (
+ patch(
+ "homeassistant.components.bluetooth.async_get_bluetooth",
+ return_value=mock_bt,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ ):
await async_setup_with_default_adapter(hass)
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
@@ -491,9 +529,13 @@ async def test_discovery_match_by_service_uuid_not_connectable(
"service_uuid": "cba20d00-224d-11e6-9fb8-0002a5d5c51b",
}
]
- with patch(
- "homeassistant.components.bluetooth.async_get_bluetooth", return_value=mock_bt
- ), patch.object(hass.config_entries.flow, "async_init") as mock_config_flow:
+ with (
+ patch(
+ "homeassistant.components.bluetooth.async_get_bluetooth",
+ return_value=mock_bt,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ ):
await async_setup_with_default_adapter(hass)
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
@@ -536,9 +578,13 @@ async def test_discovery_match_by_name_connectable_false(
"local_name": "Qingping*",
}
]
- with patch(
- "homeassistant.components.bluetooth.async_get_bluetooth", return_value=mock_bt
- ), patch.object(hass.config_entries.flow, "async_init") as mock_config_flow:
+ with (
+ patch(
+ "homeassistant.components.bluetooth.async_get_bluetooth",
+ return_value=mock_bt,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ ):
await async_setup_with_default_adapter(hass)
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
@@ -1063,9 +1109,13 @@ async def test_rediscovery(
mock_bt = [
{"domain": "switchbot", "service_uuid": "cba20d00-224d-11e6-9fb8-0002a5d5c51b"}
]
- with patch(
- "homeassistant.components.bluetooth.async_get_bluetooth", return_value=mock_bt
- ), patch.object(hass.config_entries.flow, "async_init") as mock_config_flow:
+ with (
+ patch(
+ "homeassistant.components.bluetooth.async_get_bluetooth",
+ return_value=mock_bt,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ ):
await async_setup_with_default_adapter(hass)
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
@@ -1104,11 +1154,20 @@ async def test_async_discovered_device_api(
) -> None:
"""Test the async_discovered_device API."""
mock_bt = []
- with patch(
- "homeassistant.components.bluetooth.async_get_bluetooth", return_value=mock_bt
- ), patch(
- "bleak.BleakScanner.discovered_devices_and_advertisement_data", # Must patch before we setup
- {"44:44:33:11:23:45": (MagicMock(address="44:44:33:11:23:45"), MagicMock())},
+ with (
+ patch(
+ "homeassistant.components.bluetooth.async_get_bluetooth",
+ return_value=mock_bt,
+ ),
+ patch(
+ "bleak.BleakScanner.discovered_devices_and_advertisement_data", # Must patch before we setup
+ {
+ "44:44:33:11:23:45": (
+ MagicMock(address="44:44:33:11:23:45"),
+ MagicMock(),
+ )
+ },
+ ),
):
assert not bluetooth.async_discovered_service_info(hass)
assert not bluetooth.async_address_present(hass, "44:44:22:22:11:22")
@@ -1207,9 +1266,13 @@ async def test_register_callbacks(
"""Fake subscriber for the BleakScanner."""
callbacks.append((service_info, change))
- with patch(
- "homeassistant.components.bluetooth.async_get_bluetooth", return_value=mock_bt
- ), patch.object(hass.config_entries.flow, "async_init"):
+ with (
+ patch(
+ "homeassistant.components.bluetooth.async_get_bluetooth",
+ return_value=mock_bt,
+ ),
+ patch.object(hass.config_entries.flow, "async_init"),
+ ):
await async_setup_with_default_adapter(hass)
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -1288,9 +1351,13 @@ async def test_register_callbacks_raises_exception(
callbacks.append((service_info, change))
raise ValueError
- with patch(
- "homeassistant.components.bluetooth.async_get_bluetooth", return_value=mock_bt
- ), patch.object(hass.config_entries.flow, "async_init"):
+ with (
+ patch(
+ "homeassistant.components.bluetooth.async_get_bluetooth",
+ return_value=mock_bt,
+ ),
+ patch.object(hass.config_entries.flow, "async_init"),
+ ):
await async_setup_with_default_adapter(hass)
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -2493,9 +2560,12 @@ async def test_wrapped_instance_with_broken_callbacks(
hass: HomeAssistant, mock_bleak_scanner_start: MagicMock, enable_bluetooth: None
) -> None:
"""Test broken callbacks do not cause the scanner to fail."""
- with patch(
- "homeassistant.components.bluetooth.async_get_bluetooth", return_value=[]
- ), patch.object(hass.config_entries.flow, "async_init"):
+ with (
+ patch(
+ "homeassistant.components.bluetooth.async_get_bluetooth", return_value=[]
+ ),
+ patch.object(hass.config_entries.flow, "async_init"),
+ ):
await async_setup_with_default_adapter(hass)
with patch.object(hass.config_entries.flow, "async_init"):
@@ -2675,11 +2745,20 @@ async def test_async_ble_device_from_address(
) -> None:
"""Test the async_ble_device_from_address api."""
mock_bt = []
- with patch(
- "homeassistant.components.bluetooth.async_get_bluetooth", return_value=mock_bt
- ), patch(
- "bleak.BleakScanner.discovered_devices_and_advertisement_data", # Must patch before we setup
- {"44:44:33:11:23:45": (MagicMock(address="44:44:33:11:23:45"), MagicMock())},
+ with (
+ patch(
+ "homeassistant.components.bluetooth.async_get_bluetooth",
+ return_value=mock_bt,
+ ),
+ patch(
+ "bleak.BleakScanner.discovered_devices_and_advertisement_data", # Must patch before we setup
+ {
+ "44:44:33:11:23:45": (
+ MagicMock(address="44:44:33:11:23:45"),
+ MagicMock(),
+ )
+ },
+ ),
):
assert not bluetooth.async_discovered_service_info(hass)
assert not bluetooth.async_address_present(hass, "44:44:22:22:11:22")
@@ -2814,11 +2893,13 @@ async def test_auto_detect_bluetooth_adapters_linux_none_found(
hass: HomeAssistant,
) -> None:
"""Test we auto detect bluetooth adapters on linux with no adapters found."""
- with patch(
- "bluetooth_adapters.systems.platform.system", return_value="Linux"
- ), patch("bluetooth_adapters.systems.linux.LinuxAdapters.refresh"), patch(
- "bluetooth_adapters.systems.linux.LinuxAdapters.adapters",
- {},
+ with (
+ patch("bluetooth_adapters.systems.platform.system", return_value="Linux"),
+ patch("bluetooth_adapters.systems.linux.LinuxAdapters.refresh"),
+ patch(
+ "bluetooth_adapters.systems.linux.LinuxAdapters.adapters",
+ {},
+ ),
):
assert await async_setup_component(hass, bluetooth.DOMAIN, {})
await hass.async_block_till_done()
@@ -2923,24 +3004,26 @@ async def test_discover_new_usb_adapters(
saved_callback()
assert not hass.config_entries.flow.async_progress(DOMAIN)
- with patch(
- "bluetooth_adapters.systems.platform.system", return_value="Linux"
- ), patch("bluetooth_adapters.systems.linux.LinuxAdapters.refresh"), patch(
- "bluetooth_adapters.systems.linux.LinuxAdapters.adapters",
- {
- "hci0": {
- "address": "00:00:00:00:00:01",
- "hw_version": "usb:v1D6Bp0246d053F",
- "passive_scan": False,
- "sw_version": "homeassistant",
+ with (
+ patch("bluetooth_adapters.systems.platform.system", return_value="Linux"),
+ patch("bluetooth_adapters.systems.linux.LinuxAdapters.refresh"),
+ patch(
+ "bluetooth_adapters.systems.linux.LinuxAdapters.adapters",
+ {
+ "hci0": {
+ "address": "00:00:00:00:00:01",
+ "hw_version": "usb:v1D6Bp0246d053F",
+ "passive_scan": False,
+ "sw_version": "homeassistant",
+ },
+ "hci1": {
+ "address": "00:00:00:00:00:02",
+ "hw_version": "usb:v1D6Bp0246d053F",
+ "passive_scan": False,
+ "sw_version": "homeassistant",
+ },
},
- "hci1": {
- "address": "00:00:00:00:00:02",
- "hw_version": "usb:v1D6Bp0246d053F",
- "passive_scan": False,
- "sw_version": "homeassistant",
- },
- },
+ ),
):
for wait_sec in range(10, 20):
async_fire_time_changed(
@@ -2979,11 +3062,13 @@ async def test_discover_new_usb_adapters_with_firmware_fallback_delay(
saved_callback()
assert not hass.config_entries.flow.async_progress(DOMAIN)
- with patch(
- "bluetooth_adapters.systems.platform.system", return_value="Linux"
- ), patch("bluetooth_adapters.systems.linux.LinuxAdapters.refresh"), patch(
- "bluetooth_adapters.systems.linux.LinuxAdapters.adapters",
- {},
+ with (
+ patch("bluetooth_adapters.systems.platform.system", return_value="Linux"),
+ patch("bluetooth_adapters.systems.linux.LinuxAdapters.refresh"),
+ patch(
+ "bluetooth_adapters.systems.linux.LinuxAdapters.adapters",
+ {},
+ ),
):
async_fire_time_changed(
hass, dt_util.utcnow() + timedelta(BLUETOOTH_DISCOVERY_COOLDOWN_SECONDS * 2)
@@ -2992,24 +3077,26 @@ async def test_discover_new_usb_adapters_with_firmware_fallback_delay(
assert len(hass.config_entries.flow.async_progress(DOMAIN)) == 0
- with patch(
- "bluetooth_adapters.systems.platform.system", return_value="Linux"
- ), patch("bluetooth_adapters.systems.linux.LinuxAdapters.refresh"), patch(
- "bluetooth_adapters.systems.linux.LinuxAdapters.adapters",
- {
- "hci0": {
- "address": "00:00:00:00:00:01",
- "hw_version": "usb:v1D6Bp0246d053F",
- "passive_scan": False,
- "sw_version": "homeassistant",
+ with (
+ patch("bluetooth_adapters.systems.platform.system", return_value="Linux"),
+ patch("bluetooth_adapters.systems.linux.LinuxAdapters.refresh"),
+ patch(
+ "bluetooth_adapters.systems.linux.LinuxAdapters.adapters",
+ {
+ "hci0": {
+ "address": "00:00:00:00:00:01",
+ "hw_version": "usb:v1D6Bp0246d053F",
+ "passive_scan": False,
+ "sw_version": "homeassistant",
+ },
+ "hci1": {
+ "address": "00:00:00:00:00:02",
+ "hw_version": "usb:v1D6Bp0246d053F",
+ "passive_scan": False,
+ "sw_version": "homeassistant",
+ },
},
- "hci1": {
- "address": "00:00:00:00:00:02",
- "hw_version": "usb:v1D6Bp0246d053F",
- "passive_scan": False,
- "sw_version": "homeassistant",
- },
- },
+ ),
):
async_fire_time_changed(
hass,
diff --git a/tests/components/bluetooth/test_manager.py b/tests/components/bluetooth/test_manager.py
index b99d47cdba1..cb2be8a0e8d 100644
--- a/tests/components/bluetooth/test_manager.py
+++ b/tests/components/bluetooth/test_manager.py
@@ -1028,14 +1028,16 @@ async def test_goes_unavailable_dismisses_discovery_and_makes_discoverable(
not in non_connectable_scanner.discovered_devices_and_advertisement_data
)
monotonic_now = time.monotonic()
- with patch.object(
- hass.config_entries.flow,
- "async_progress_by_init_data_type",
- return_value=[{"flow_id": "mock_flow_id"}],
- ) as mock_async_progress_by_init_data_type, patch.object(
- hass.config_entries.flow, "async_abort"
- ) as mock_async_abort, patch_bluetooth_time(
- monotonic_now + FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS,
+ with (
+ patch.object(
+ hass.config_entries.flow,
+ "async_progress_by_init_data_type",
+ return_value=[{"flow_id": "mock_flow_id"}],
+ ) as mock_async_progress_by_init_data_type,
+ patch.object(hass.config_entries.flow, "async_abort") as mock_async_abort,
+ patch_bluetooth_time(
+ monotonic_now + FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS,
+ ),
):
async_fire_time_changed(
hass, dt_util.utcnow() + timedelta(seconds=UNAVAILABLE_TRACK_SECONDS)
diff --git a/tests/components/bluetooth/test_models.py b/tests/components/bluetooth/test_models.py
index 837a95ea2d1..087d443c5a0 100644
--- a/tests/components/bluetooth/test_models.py
+++ b/tests/components/bluetooth/test_models.py
@@ -116,10 +116,15 @@ async def test_wrapped_bleak_client_local_adapter_only(
)
client = HaBleakClientWrapper(switchbot_device)
- with patch(
- "bleak.backends.bluezdbus.client.BleakClientBlueZDBus.connect",
- return_value=True,
- ), patch("bleak.backends.bluezdbus.client.BleakClientBlueZDBus.is_connected", True):
+ with (
+ patch(
+ "bleak.backends.bluezdbus.client.BleakClientBlueZDBus.connect",
+ return_value=True,
+ ),
+ patch(
+ "bleak.backends.bluezdbus.client.BleakClientBlueZDBus.is_connected", True
+ ),
+ ):
assert await client.connect() is True
assert client.is_connected is True
client.set_disconnected_callback(lambda client: None)
@@ -201,10 +206,15 @@ async def test_wrapped_bleak_client_set_disconnected_callback_after_connected(
"esp32_has_connection_slot",
)
client = HaBleakClientWrapper(switchbot_proxy_device_has_connection_slot)
- with patch(
- "bleak.backends.bluezdbus.client.BleakClientBlueZDBus.connect",
- return_value=True,
- ), patch("bleak.backends.bluezdbus.client.BleakClientBlueZDBus.is_connected", True):
+ with (
+ patch(
+ "bleak.backends.bluezdbus.client.BleakClientBlueZDBus.connect",
+ return_value=True,
+ ),
+ patch(
+ "bleak.backends.bluezdbus.client.BleakClientBlueZDBus.is_connected", True
+ ),
+ ):
assert await client.connect() is True
assert client.is_connected is True
client.set_disconnected_callback(lambda client: None)
@@ -240,9 +250,10 @@ async def test_ble_device_with_proxy_client_out_of_connections_no_scanners(
]
client = HaBleakClientWrapper(switchbot_proxy_device_no_connection_slot)
- with patch(
- "bleak.backends.bluezdbus.client.BleakClientBlueZDBus.connect"
- ), pytest.raises(BleakError):
+ with (
+ patch("bleak.backends.bluezdbus.client.BleakClientBlueZDBus.connect"),
+ pytest.raises(BleakError),
+ ):
await client.connect()
assert client.is_connected is False
client.set_disconnected_callback(lambda client: None)
@@ -304,9 +315,10 @@ async def test_ble_device_with_proxy_client_out_of_connections(
]
client = HaBleakClientWrapper(switchbot_proxy_device_no_connection_slot)
- with patch(
- "bleak.backends.bluezdbus.client.BleakClientBlueZDBus.connect"
- ), pytest.raises(BleakError):
+ with (
+ patch("bleak.backends.bluezdbus.client.BleakClientBlueZDBus.connect"),
+ pytest.raises(BleakError),
+ ):
await client.connect()
assert client.is_connected is False
client.set_disconnected_callback(lambda client: None)
diff --git a/tests/components/bluetooth/test_passive_update_coordinator.py b/tests/components/bluetooth/test_passive_update_coordinator.py
index ba8e150d028..54d4f8d5662 100644
--- a/tests/components/bluetooth/test_passive_update_coordinator.py
+++ b/tests/components/bluetooth/test_passive_update_coordinator.py
@@ -164,8 +164,9 @@ async def test_unavailable_callbacks_mark_the_coordinator_unavailable(
monotonic_now = start_monotonic + FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 1
- with patch_bluetooth_time(monotonic_now), patch_all_discovered_devices(
- [MagicMock(address="44:44:33:11:23:45")]
+ with (
+ patch_bluetooth_time(monotonic_now),
+ patch_all_discovered_devices([MagicMock(address="44:44:33:11:23:45")]),
):
async_fire_time_changed(
hass,
@@ -180,9 +181,12 @@ async def test_unavailable_callbacks_mark_the_coordinator_unavailable(
monotonic_now = start_monotonic + FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 2
- with patch_bluetooth_time(
- monotonic_now,
- ), patch_all_discovered_devices([MagicMock(address="44:44:33:11:23:45")]):
+ with (
+ patch_bluetooth_time(
+ monotonic_now,
+ ),
+ patch_all_discovered_devices([MagicMock(address="44:44:33:11:23:45")]),
+ ):
async_fire_time_changed(
hass,
dt_util.utcnow()
diff --git a/tests/components/bluetooth/test_passive_update_processor.py b/tests/components/bluetooth/test_passive_update_processor.py
index d7248e8f405..3578e2e6f6f 100644
--- a/tests/components/bluetooth/test_passive_update_processor.py
+++ b/tests/components/bluetooth/test_passive_update_processor.py
@@ -473,9 +473,12 @@ async def test_unavailable_after_no_data(
assert processor.available is True
monotonic_now = start_monotonic + FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 1
- with patch_bluetooth_time(
- monotonic_now,
- ), patch_all_discovered_devices([MagicMock(address="44:44:33:11:23:45")]):
+ with (
+ patch_bluetooth_time(
+ monotonic_now,
+ ),
+ patch_all_discovered_devices([MagicMock(address="44:44:33:11:23:45")]),
+ ):
async_fire_time_changed(
hass, dt_util.utcnow() + timedelta(seconds=UNAVAILABLE_TRACK_SECONDS)
)
@@ -491,9 +494,12 @@ async def test_unavailable_after_no_data(
monotonic_now = start_monotonic + FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 2
- with patch_bluetooth_time(
- monotonic_now,
- ), patch_all_discovered_devices([MagicMock(address="44:44:33:11:23:45")]):
+ with (
+ patch_bluetooth_time(
+ monotonic_now,
+ ),
+ patch_all_discovered_devices([MagicMock(address="44:44:33:11:23:45")]),
+ ):
async_fire_time_changed(
hass, dt_util.utcnow() + timedelta(seconds=UNAVAILABLE_TRACK_SECONDS)
)
diff --git a/tests/components/bluetooth/test_scanner.py b/tests/components/bluetooth/test_scanner.py
index aefc36fe6eb..504122fb671 100644
--- a/tests/components/bluetooth/test_scanner.py
+++ b/tests/components/bluetooth/test_scanner.py
@@ -66,9 +66,12 @@ async def test_dbus_socket_missing_in_container(
) -> None:
"""Test we handle dbus being missing in the container."""
- with patch("habluetooth.scanner.is_docker_env", return_value=True), patch(
- "habluetooth.scanner.OriginalBleakScanner.start",
- side_effect=FileNotFoundError,
+ with (
+ patch("habluetooth.scanner.is_docker_env", return_value=True),
+ patch(
+ "habluetooth.scanner.OriginalBleakScanner.start",
+ side_effect=FileNotFoundError,
+ ),
):
await async_setup_with_one_adapter(hass)
@@ -86,9 +89,12 @@ async def test_dbus_socket_missing(
) -> None:
"""Test we handle dbus being missing."""
- with patch("habluetooth.scanner.is_docker_env", return_value=False), patch(
- "habluetooth.scanner.OriginalBleakScanner.start",
- side_effect=FileNotFoundError,
+ with (
+ patch("habluetooth.scanner.is_docker_env", return_value=False),
+ patch(
+ "habluetooth.scanner.OriginalBleakScanner.start",
+ side_effect=FileNotFoundError,
+ ),
):
await async_setup_with_one_adapter(hass)
@@ -106,9 +112,12 @@ async def test_dbus_broken_pipe_in_container(
) -> None:
"""Test we handle dbus broken pipe in the container."""
- with patch("habluetooth.scanner.is_docker_env", return_value=True), patch(
- "habluetooth.scanner.OriginalBleakScanner.start",
- side_effect=BrokenPipeError,
+ with (
+ patch("habluetooth.scanner.is_docker_env", return_value=True),
+ patch(
+ "habluetooth.scanner.OriginalBleakScanner.start",
+ side_effect=BrokenPipeError,
+ ),
):
await async_setup_with_one_adapter(hass)
@@ -127,9 +136,12 @@ async def test_dbus_broken_pipe(
) -> None:
"""Test we handle dbus broken pipe."""
- with patch("habluetooth.scanner.is_docker_env", return_value=False), patch(
- "habluetooth.scanner.OriginalBleakScanner.start",
- side_effect=BrokenPipeError,
+ with (
+ patch("habluetooth.scanner.is_docker_env", return_value=False),
+ patch(
+ "habluetooth.scanner.OriginalBleakScanner.start",
+ side_effect=BrokenPipeError,
+ ),
):
await async_setup_with_one_adapter(hass)
@@ -168,12 +180,15 @@ async def test_adapter_needs_reset_at_start(
) -> None:
"""Test we cycle the adapter when it needs a restart."""
- with patch(
- "habluetooth.scanner.OriginalBleakScanner.start",
- side_effect=[BleakError(error), None],
- ), patch(
- "habluetooth.util.recover_adapter", return_value=True
- ) as mock_recover_adapter:
+ with (
+ patch(
+ "habluetooth.scanner.OriginalBleakScanner.start",
+ side_effect=[BleakError(error), None],
+ ),
+ patch(
+ "habluetooth.util.recover_adapter", return_value=True
+ ) as mock_recover_adapter,
+ ):
await async_setup_with_one_adapter(hass)
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -299,11 +314,14 @@ async def test_adapter_recovery(hass: HomeAssistant, one_adapter: None) -> None:
scanner = MockBleakScanner()
start_time_monotonic = time.monotonic()
- with patch_bluetooth_time(
- start_time_monotonic,
- ), patch(
- "habluetooth.scanner.OriginalBleakScanner",
- return_value=scanner,
+ with (
+ patch_bluetooth_time(
+ start_time_monotonic,
+ ),
+ patch(
+ "habluetooth.scanner.OriginalBleakScanner",
+ return_value=scanner,
+ ),
):
await async_setup_with_one_adapter(hass)
@@ -331,13 +349,16 @@ async def test_adapter_recovery(hass: HomeAssistant, one_adapter: None) -> None:
assert called_start == 1
# We hit the timer with no detections, so we reset the adapter and restart the scanner
- with patch_bluetooth_time(
- start_time_monotonic
- + SCANNER_WATCHDOG_TIMEOUT
- + SCANNER_WATCHDOG_INTERVAL.total_seconds(),
- ), patch(
- "habluetooth.util.recover_adapter", return_value=True
- ) as mock_recover_adapter:
+ with (
+ patch_bluetooth_time(
+ start_time_monotonic
+ + SCANNER_WATCHDOG_TIMEOUT
+ + SCANNER_WATCHDOG_INTERVAL.total_seconds(),
+ ),
+ patch(
+ "habluetooth.util.recover_adapter", return_value=True
+ ) as mock_recover_adapter,
+ ):
async_fire_time_changed(hass, dt_util.utcnow() + SCANNER_WATCHDOG_INTERVAL)
await hass.async_block_till_done()
@@ -384,11 +405,14 @@ async def test_adapter_scanner_fails_to_start_first_time(
scanner = MockBleakScanner()
start_time_monotonic = time.monotonic()
- with patch_bluetooth_time(
- start_time_monotonic,
- ), patch(
- "habluetooth.scanner.OriginalBleakScanner",
- return_value=scanner,
+ with (
+ patch_bluetooth_time(
+ start_time_monotonic,
+ ),
+ patch(
+ "habluetooth.scanner.OriginalBleakScanner",
+ return_value=scanner,
+ ),
):
await async_setup_with_one_adapter(hass)
@@ -416,13 +440,16 @@ async def test_adapter_scanner_fails_to_start_first_time(
assert called_start == 1
# We hit the timer with no detections, so we reset the adapter and restart the scanner
- with patch_bluetooth_time(
- start_time_monotonic
- + SCANNER_WATCHDOG_TIMEOUT
- + SCANNER_WATCHDOG_INTERVAL.total_seconds(),
- ), patch(
- "habluetooth.util.recover_adapter", return_value=True
- ) as mock_recover_adapter:
+ with (
+ patch_bluetooth_time(
+ start_time_monotonic
+ + SCANNER_WATCHDOG_TIMEOUT
+ + SCANNER_WATCHDOG_INTERVAL.total_seconds(),
+ ),
+ patch(
+ "habluetooth.util.recover_adapter", return_value=True
+ ) as mock_recover_adapter,
+ ):
async_fire_time_changed(hass, dt_util.utcnow() + SCANNER_WATCHDOG_INTERVAL)
await hass.async_block_till_done()
@@ -431,13 +458,16 @@ async def test_adapter_scanner_fails_to_start_first_time(
# We hit the timer again the previous start call failed, make sure
# we try again
- with patch_bluetooth_time(
- start_time_monotonic
- + SCANNER_WATCHDOG_TIMEOUT
- + SCANNER_WATCHDOG_INTERVAL.total_seconds(),
- ), patch(
- "habluetooth.util.recover_adapter", return_value=True
- ) as mock_recover_adapter:
+ with (
+ patch_bluetooth_time(
+ start_time_monotonic
+ + SCANNER_WATCHDOG_TIMEOUT
+ + SCANNER_WATCHDOG_INTERVAL.total_seconds(),
+ ),
+ patch(
+ "habluetooth.util.recover_adapter", return_value=True
+ ) as mock_recover_adapter,
+ ):
async_fire_time_changed(hass, dt_util.utcnow() + SCANNER_WATCHDOG_INTERVAL)
await hass.async_block_till_done()
@@ -490,17 +520,22 @@ async def test_adapter_fails_to_start_and_takes_a_bit_to_init(
scanner = MockBleakScanner()
start_time_monotonic = time.monotonic()
- with patch(
- "habluetooth.scanner.ADAPTER_INIT_TIME",
- 0,
- ), patch_bluetooth_time(
- start_time_monotonic,
- ), patch(
- "habluetooth.scanner.OriginalBleakScanner",
- return_value=scanner,
- ), patch(
- "habluetooth.util.recover_adapter", return_value=True
- ) as mock_recover_adapter:
+ with (
+ patch(
+ "habluetooth.scanner.ADAPTER_INIT_TIME",
+ 0,
+ ),
+ patch_bluetooth_time(
+ start_time_monotonic,
+ ),
+ patch(
+ "habluetooth.scanner.OriginalBleakScanner",
+ return_value=scanner,
+ ),
+ patch(
+ "habluetooth.util.recover_adapter", return_value=True
+ ) as mock_recover_adapter,
+ ):
await async_setup_with_one_adapter(hass)
assert called_start == 3
@@ -540,15 +575,20 @@ async def test_restart_takes_longer_than_watchdog_time(
scanner = MockBleakScanner()
start_time_monotonic = time.monotonic()
- with patch(
- "habluetooth.scanner.ADAPTER_INIT_TIME",
- 0,
- ), patch_bluetooth_time(
- start_time_monotonic,
- ), patch(
- "habluetooth.scanner.OriginalBleakScanner",
- return_value=scanner,
- ), patch("habluetooth.util.recover_adapter", return_value=True):
+ with (
+ patch(
+ "habluetooth.scanner.ADAPTER_INIT_TIME",
+ 0,
+ ),
+ patch_bluetooth_time(
+ start_time_monotonic,
+ ),
+ patch(
+ "habluetooth.scanner.OriginalBleakScanner",
+ return_value=scanner,
+ ),
+ patch("habluetooth.util.recover_adapter", return_value=True),
+ ):
await async_setup_with_one_adapter(hass)
assert called_start == 1
diff --git a/tests/components/bluetooth/test_wrappers.py b/tests/components/bluetooth/test_wrappers.py
index 1fc42ebf187..0630d671038 100644
--- a/tests/components/bluetooth/test_wrappers.py
+++ b/tests/components/bluetooth/test_wrappers.py
@@ -207,11 +207,12 @@ async def test_test_switch_adapters_when_out_of_slots(
hass
)
# hci0 has 2 slots, hci1 has 1 slot
- with patch.object(
- manager.slot_manager, "release_slot"
- ) as release_slot_mock, patch.object(
- manager.slot_manager, "allocate_slot", return_value=True
- ) as allocate_slot_mock:
+ with (
+ patch.object(manager.slot_manager, "release_slot") as release_slot_mock,
+ patch.object(
+ manager.slot_manager, "allocate_slot", return_value=True
+ ) as allocate_slot_mock,
+ ):
ble_device = hci0_device_advs["00:00:00:00:00:01"][0]
client = bleak.BleakClient(ble_device)
assert await client.connect() is True
@@ -219,11 +220,12 @@ async def test_test_switch_adapters_when_out_of_slots(
assert release_slot_mock.call_count == 0
# All adapters are out of slots
- with patch.object(
- manager.slot_manager, "release_slot"
- ) as release_slot_mock, patch.object(
- manager.slot_manager, "allocate_slot", return_value=False
- ) as allocate_slot_mock:
+ with (
+ patch.object(manager.slot_manager, "release_slot") as release_slot_mock,
+ patch.object(
+ manager.slot_manager, "allocate_slot", return_value=False
+ ) as allocate_slot_mock,
+ ):
ble_device = hci0_device_advs["00:00:00:00:00:02"][0]
client = bleak.BleakClient(ble_device)
with pytest.raises(bleak.exc.BleakError):
@@ -237,11 +239,12 @@ async def test_test_switch_adapters_when_out_of_slots(
return True
return False
- with patch.object(
- manager.slot_manager, "release_slot"
- ) as release_slot_mock, patch.object(
- manager.slot_manager, "allocate_slot", _allocate_slot_mock
- ) as allocate_slot_mock:
+ with (
+ patch.object(manager.slot_manager, "release_slot") as release_slot_mock,
+ patch.object(
+ manager.slot_manager, "allocate_slot", _allocate_slot_mock
+ ) as allocate_slot_mock,
+ ):
ble_device = hci0_device_advs["00:00:00:00:00:03"][0]
client = bleak.BleakClient(ble_device)
assert await client.connect() is True
@@ -264,11 +267,12 @@ async def test_release_slot_on_connect_failure(
hass
)
# hci0 has 2 slots, hci1 has 1 slot
- with patch.object(
- manager.slot_manager, "release_slot"
- ) as release_slot_mock, patch.object(
- manager.slot_manager, "allocate_slot", return_value=True
- ) as allocate_slot_mock:
+ with (
+ patch.object(manager.slot_manager, "release_slot") as release_slot_mock,
+ patch.object(
+ manager.slot_manager, "allocate_slot", return_value=True
+ ) as allocate_slot_mock,
+ ):
ble_device = hci0_device_advs["00:00:00:00:00:01"][0]
client = bleak.BleakClient(ble_device)
assert await client.connect() is False
@@ -292,11 +296,12 @@ async def test_release_slot_on_connect_exception(
hass
)
# hci0 has 2 slots, hci1 has 1 slot
- with patch.object(
- manager.slot_manager, "release_slot"
- ) as release_slot_mock, patch.object(
- manager.slot_manager, "allocate_slot", return_value=True
- ) as allocate_slot_mock:
+ with (
+ patch.object(manager.slot_manager, "release_slot") as release_slot_mock,
+ patch.object(
+ manager.slot_manager, "allocate_slot", return_value=True
+ ) as allocate_slot_mock,
+ ):
ble_device = hci0_device_advs["00:00:00:00:00:01"][0]
client = bleak.BleakClient(ble_device)
with pytest.raises(Exception):
diff --git a/tests/components/bmw_connected_drive/test_config_flow.py b/tests/components/bmw_connected_drive/test_config_flow.py
index 07c84e09707..ab7366e9da4 100644
--- a/tests/components/bmw_connected_drive/test_config_flow.py
+++ b/tests/components/bmw_connected_drive/test_config_flow.py
@@ -101,14 +101,17 @@ async def test_api_error(hass: HomeAssistant) -> None:
async def test_full_user_flow_implementation(hass: HomeAssistant) -> None:
"""Test registering an integration and finishing flow works."""
- with patch(
- "bimmer_connected.api.authentication.MyBMWAuthentication.login",
- side_effect=login_sideeffect,
- autospec=True,
- ), patch(
- "homeassistant.components.bmw_connected_drive.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "bimmer_connected.api.authentication.MyBMWAuthentication.login",
+ side_effect=login_sideeffect,
+ autospec=True,
+ ),
+ patch(
+ "homeassistant.components.bmw_connected_drive.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
@@ -123,13 +126,16 @@ async def test_full_user_flow_implementation(hass: HomeAssistant) -> None:
async def test_options_flow_implementation(hass: HomeAssistant) -> None:
"""Test config flow options."""
- with patch(
- "bimmer_connected.account.MyBMWAccount.get_vehicles",
- return_value=[],
- ), patch(
- "homeassistant.components.bmw_connected_drive.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "bimmer_connected.account.MyBMWAccount.get_vehicles",
+ return_value=[],
+ ),
+ patch(
+ "homeassistant.components.bmw_connected_drive.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
config_entry = MockConfigEntry(**FIXTURE_CONFIG_ENTRY)
config_entry.add_to_hass(hass)
@@ -156,14 +162,17 @@ async def test_options_flow_implementation(hass: HomeAssistant) -> None:
async def test_reauth(hass: HomeAssistant) -> None:
"""Test the reauth form."""
- with patch(
- "bimmer_connected.api.authentication.MyBMWAuthentication.login",
- side_effect=login_sideeffect,
- autospec=True,
- ), patch(
- "homeassistant.components.bmw_connected_drive.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "bimmer_connected.api.authentication.MyBMWAuthentication.login",
+ side_effect=login_sideeffect,
+ autospec=True,
+ ),
+ patch(
+ "homeassistant.components.bmw_connected_drive.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
wrong_password = "wrong"
config_entry_with_wrong_password = deepcopy(FIXTURE_CONFIG_ENTRY)
diff --git a/tests/components/bond/common.py b/tests/components/bond/common.py
index 6f1cd30a484..619aa03572a 100644
--- a/tests/components/bond/common.py
+++ b/tests/components/bond/common.py
@@ -63,14 +63,16 @@ async def setup_bond_entity(
"""Set up Bond entity."""
config_entry.add_to_hass(hass)
- with patch_start_bpup(), patch_bond_bridge(enabled=patch_bridge), patch_bond_token(
- enabled=patch_token
- ), patch_bond_version(enabled=patch_version), patch_bond_device_ids(
- enabled=patch_device_ids
- ), patch_setup_entry("cover", enabled=patch_platforms), patch_setup_entry(
- "fan", enabled=patch_platforms
- ), patch_setup_entry("light", enabled=patch_platforms), patch_setup_entry(
- "switch", enabled=patch_platforms
+ with (
+ patch_start_bpup(),
+ patch_bond_bridge(enabled=patch_bridge),
+ patch_bond_token(enabled=patch_token),
+ patch_bond_version(enabled=patch_version),
+ patch_bond_device_ids(enabled=patch_device_ids),
+ patch_setup_entry("cover", enabled=patch_platforms),
+ patch_setup_entry("fan", enabled=patch_platforms),
+ patch_setup_entry("light", enabled=patch_platforms),
+ patch_setup_entry("switch", enabled=patch_platforms),
):
return await hass.config_entries.async_setup(config_entry.entry_id)
@@ -94,16 +96,16 @@ async def setup_platform(
)
mock_entry.add_to_hass(hass)
- 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
+ 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()
diff --git a/tests/components/bond/test_config_flow.py b/tests/components/bond/test_config_flow.py
index 9e5457197b2..bfe61c536d9 100644
--- a/tests/components/bond/test_config_flow.py
+++ b/tests/components/bond/test_config_flow.py
@@ -38,11 +38,15 @@ async def test_user_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch_bond_version(
- return_value={"bondid": "ZXXX12345"}
- ), patch_bond_device_ids(
- return_value=["f6776c11", "f6776c12"]
- ), patch_bond_bridge(), patch_bond_device_properties(), patch_bond_device(), patch_bond_device_state(), _patch_async_setup_entry() as mock_setup_entry:
+ with (
+ patch_bond_version(return_value={"bondid": "ZXXX12345"}),
+ patch_bond_device_ids(return_value=["f6776c11", "f6776c12"]),
+ patch_bond_bridge(),
+ patch_bond_device_properties(),
+ patch_bond_device(),
+ patch_bond_device_state(),
+ _patch_async_setup_entry() as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_HOST: "some host", CONF_ACCESS_TOKEN: "test-token"},
@@ -67,17 +71,19 @@ async def test_user_form_with_non_bridge(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch_bond_version(
- return_value={"bondid": "KXXX12345"}
- ), patch_bond_device_ids(
- return_value=["f6776c11"]
- ), patch_bond_device_properties(), patch_bond_device(
- return_value={
- "name": "New Fan",
- }
- ), patch_bond_bridge(
- return_value={}
- ), patch_bond_device_state(), _patch_async_setup_entry() as mock_setup_entry:
+ with (
+ patch_bond_version(return_value={"bondid": "KXXX12345"}),
+ patch_bond_device_ids(return_value=["f6776c11"]),
+ patch_bond_device_properties(),
+ patch_bond_device(
+ return_value={
+ "name": "New Fan",
+ }
+ ),
+ patch_bond_bridge(return_value={}),
+ patch_bond_device_state(),
+ _patch_async_setup_entry() as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_HOST: "some host", CONF_ACCESS_TOKEN: "test-token"},
@@ -99,10 +105,12 @@ async def test_user_form_invalid_auth(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch_bond_version(
- return_value={"bond_id": "ZXXX12345"}
- ), patch_bond_bridge(), patch_bond_device_ids(
- side_effect=ClientResponseError(Mock(), Mock(), status=401),
+ with (
+ patch_bond_version(return_value={"bond_id": "ZXXX12345"}),
+ patch_bond_bridge(),
+ patch_bond_device_ids(
+ side_effect=ClientResponseError(Mock(), Mock(), status=401),
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -119,9 +127,11 @@ async def test_user_form_cannot_connect(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch_bond_version(
- side_effect=ClientConnectionError()
- ), patch_bond_bridge(), patch_bond_device_ids():
+ with (
+ patch_bond_version(side_effect=ClientConnectionError()),
+ patch_bond_bridge(),
+ patch_bond_device_ids(),
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_HOST: "some host", CONF_ACCESS_TOKEN: "test-token"},
@@ -137,9 +147,11 @@ async def test_user_form_old_firmware(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch_bond_version(
- return_value={"no_bond_id": "present"}
- ), patch_bond_bridge(), patch_bond_device_ids():
+ with (
+ patch_bond_version(return_value={"no_bond_id": "present"}),
+ patch_bond_bridge(),
+ patch_bond_device_ids(),
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_HOST: "some host", CONF_ACCESS_TOKEN: "test-token"},
@@ -181,9 +193,12 @@ async def test_user_form_one_entry_per_device_allowed(hass: HomeAssistant) -> No
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch_bond_version(
- return_value={"bondid": "already-registered-bond-id"}
- ), patch_bond_bridge(), patch_bond_device_ids(), _patch_async_setup_entry() as mock_setup_entry:
+ with (
+ patch_bond_version(return_value={"bondid": "already-registered-bond-id"}),
+ patch_bond_bridge(),
+ patch_bond_device_ids(),
+ _patch_async_setup_entry() as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_HOST: "some host", CONF_ACCESS_TOKEN: "test-token"},
@@ -216,9 +231,12 @@ async def test_zeroconf_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch_bond_version(
- return_value={"bondid": "ZXXX12345"}
- ), patch_bond_bridge(), patch_bond_device_ids(), _patch_async_setup_entry() as mock_setup_entry:
+ with (
+ patch_bond_version(return_value={"bondid": "ZXXX12345"}),
+ patch_bond_bridge(),
+ patch_bond_device_ids(),
+ _patch_async_setup_entry() as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_ACCESS_TOKEN: "test-token"},
@@ -255,7 +273,12 @@ async def test_zeroconf_form_token_unavailable(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch_bond_version(), patch_bond_bridge(), patch_bond_device_ids(), _patch_async_setup_entry() as mock_setup_entry:
+ with (
+ patch_bond_version(),
+ patch_bond_bridge(),
+ patch_bond_device_ids(),
+ _patch_async_setup_entry() as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_ACCESS_TOKEN: "test-token"},
@@ -292,7 +315,12 @@ async def test_zeroconf_form_token_times_out(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch_bond_version(), patch_bond_bridge(), patch_bond_device_ids(), _patch_async_setup_entry() as mock_setup_entry:
+ with (
+ patch_bond_version(),
+ patch_bond_bridge(),
+ patch_bond_device_ids(),
+ _patch_async_setup_entry() as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_ACCESS_TOKEN: "test-token"},
@@ -311,11 +339,12 @@ async def test_zeroconf_form_token_times_out(hass: HomeAssistant) -> None:
async def test_zeroconf_form_with_token_available(hass: HomeAssistant) -> None:
"""Test we get the discovery form when we can get the token."""
- with patch_bond_version(return_value={"bondid": "ZXXX12345"}), patch_bond_token(
- return_value={"token": "discovered-token"}
- ), patch_bond_bridge(
- return_value={"name": "discovered-name"}
- ), patch_bond_device_ids():
+ with (
+ patch_bond_version(return_value={"bondid": "ZXXX12345"}),
+ patch_bond_token(return_value={"token": "discovered-token"}),
+ patch_bond_bridge(return_value={"name": "discovered-name"}),
+ patch_bond_device_ids(),
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_ZEROCONF},
@@ -354,9 +383,12 @@ async def test_zeroconf_form_with_token_available_name_unavailable(
) -> None:
"""Test we get the discovery form when we can get the token but the name is unavailable."""
- with patch_bond_version(
- side_effect=ClientResponseError(Mock(), (), status=HTTPStatus.BAD_REQUEST)
- ), patch_bond_token(return_value={"token": "discovered-token"}):
+ with (
+ patch_bond_version(
+ side_effect=ClientResponseError(Mock(), (), status=HTTPStatus.BAD_REQUEST)
+ ),
+ patch_bond_token(return_value={"token": "discovered-token"}),
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_ZEROCONF},
@@ -482,8 +514,9 @@ async def test_zeroconf_already_configured_refresh_token(hass: HomeAssistant) ->
await hass.config_entries.async_setup(entry.entry_id)
assert entry.state is ConfigEntryState.SETUP_ERROR
- with _patch_async_setup_entry() as mock_setup_entry, patch_bond_token(
- return_value={"token": "discovered-token"}
+ with (
+ _patch_async_setup_entry() as mock_setup_entry,
+ patch_bond_token(return_value={"token": "discovered-token"}),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -520,8 +553,9 @@ async def test_zeroconf_already_configured_no_reload_same_host(
)
entry.add_to_hass(hass)
- with _patch_async_setup_entry() as mock_setup_entry, patch_bond_token(
- return_value={"token": "correct-token"}
+ with (
+ _patch_async_setup_entry() as mock_setup_entry,
+ patch_bond_token(return_value={"token": "correct-token"}),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -576,9 +610,10 @@ async def _help_test_form_unexpected_error(
DOMAIN, context={"source": source}, data=initial_input
)
- with patch_bond_version(
- return_value={"bond_id": "ZXXX12345"}
- ), patch_bond_device_ids(side_effect=error):
+ with (
+ patch_bond_version(return_value={"bond_id": "ZXXX12345"}),
+ patch_bond_device_ids(side_effect=error),
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input
)
diff --git a/tests/components/bond/test_cover.py b/tests/components/bond/test_cover.py
index 4af096f1431..e438a830eb5 100644
--- a/tests/components/bond/test_cover.py
+++ b/tests/components/bond/test_cover.py
@@ -265,8 +265,9 @@ async def test_set_position_cover(hass: HomeAssistant) -> None:
bond_device_id="test-device-id",
)
- with patch_bond_action() as mock_hold, patch_bond_device_state(
- return_value={"position": 0, "open": 1}
+ with (
+ patch_bond_action() as mock_hold,
+ patch_bond_device_state(return_value={"position": 0, "open": 1}),
):
await hass.services.async_call(
COVER_DOMAIN,
@@ -282,8 +283,9 @@ async def test_set_position_cover(hass: HomeAssistant) -> None:
assert entity_state.state == STATE_OPEN
assert entity_state.attributes[ATTR_CURRENT_POSITION] == 100
- with patch_bond_action() as mock_hold, patch_bond_device_state(
- return_value={"position": 100, "open": 0}
+ with (
+ patch_bond_action() as mock_hold,
+ patch_bond_device_state(return_value={"position": 100, "open": 0}),
):
await hass.services.async_call(
COVER_DOMAIN,
@@ -299,8 +301,9 @@ async def test_set_position_cover(hass: HomeAssistant) -> None:
assert entity_state.state == STATE_CLOSED
assert entity_state.attributes[ATTR_CURRENT_POSITION] == 0
- with patch_bond_action() as mock_hold, patch_bond_device_state(
- return_value={"position": 40, "open": 1}
+ with (
+ patch_bond_action() as mock_hold,
+ patch_bond_device_state(return_value={"position": 40, "open": 1}),
):
await hass.services.async_call(
COVER_DOMAIN,
diff --git a/tests/components/bond/test_fan.py b/tests/components/bond/test_fan.py
index 766e1e8ad07..6a0160fbec9 100644
--- a/tests/components/bond/test_fan.py
+++ b/tests/components/bond/test_fan.py
@@ -253,13 +253,17 @@ async def test_turn_on_fan_preset_mode_not_supported(hass: HomeAssistant) -> Non
props={"max_speed": 6},
)
- with patch_bond_action(), patch_bond_device_state(), pytest.raises(
- NotValidPresetModeError
+ with (
+ patch_bond_action(),
+ patch_bond_device_state(),
+ pytest.raises(NotValidPresetModeError),
):
await turn_fan_on(hass, "fan.name_1", preset_mode=PRESET_MODE_BREEZE)
- with patch_bond_action(), patch_bond_device_state(), pytest.raises(
- NotValidPresetModeError
+ with (
+ patch_bond_action(),
+ patch_bond_device_state(),
+ pytest.raises(NotValidPresetModeError),
):
await hass.services.async_call(
FAN_DOMAIN,
@@ -381,9 +385,11 @@ async def test_set_speed_belief_speed_api_error(hass: HomeAssistant) -> None:
hass, FAN_DOMAIN, ceiling_fan("name-1"), bond_device_id="test-device-id"
)
- with pytest.raises(
- HomeAssistantError
- ), patch_bond_action_returns_clientresponseerror(), patch_bond_device_state():
+ with (
+ pytest.raises(HomeAssistantError),
+ patch_bond_action_returns_clientresponseerror(),
+ patch_bond_device_state(),
+ ):
await hass.services.async_call(
BOND_DOMAIN,
SERVICE_SET_FAN_SPEED_TRACKED_STATE,
diff --git a/tests/components/bond/test_init.py b/tests/components/bond/test_init.py
index db10a842b27..167cd9aa401 100644
--- a/tests/components/bond/test_init.py
+++ b/tests/components/bond/test_init.py
@@ -89,20 +89,21 @@ async def test_async_setup_entry_sets_up_hub_and_supported_domains(
data={CONF_HOST: "some host", CONF_ACCESS_TOKEN: "test-token"},
)
- with patch_bond_bridge(), patch_bond_version(
- return_value={
- "bondid": "ZXXX12345",
- "target": "test-model",
- "fw_ver": "test-version",
- "mcu_ver": "test-hw-version",
- }
- ), patch_setup_entry("cover") as mock_cover_async_setup_entry, patch_setup_entry(
- "fan"
- ) as mock_fan_async_setup_entry, patch_setup_entry(
- "light"
- ) as mock_light_async_setup_entry, patch_setup_entry(
- "switch"
- ) as mock_switch_async_setup_entry:
+ with (
+ patch_bond_bridge(),
+ patch_bond_version(
+ return_value={
+ "bondid": "ZXXX12345",
+ "target": "test-model",
+ "fw_ver": "test-version",
+ "mcu_ver": "test-hw-version",
+ }
+ ),
+ patch_setup_entry("cover") as mock_cover_async_setup_entry,
+ patch_setup_entry("fan") as mock_fan_async_setup_entry,
+ patch_setup_entry("light") as mock_light_async_setup_entry,
+ patch_setup_entry("switch") as mock_switch_async_setup_entry,
+ ):
result = await setup_bond_entity(hass, config_entry, patch_device_ids=True)
assert result is True
await hass.async_block_till_done()
@@ -171,21 +172,25 @@ async def test_old_identifiers_are_removed(
name="old",
)
- with patch_bond_bridge(), patch_bond_version(
- return_value={
- "bondid": "ZXXX12345",
- "target": "test-model",
- "fw_ver": "test-version",
- }
- ), patch_start_bpup(), patch_bond_device_ids(
- return_value=["bond-device-id", "device_id"]
- ), patch_bond_device(
- return_value={
- "name": "test1",
- "type": DeviceType.GENERIC_DEVICE,
- }
- ), patch_bond_device_properties(return_value={}), patch_bond_device_state(
- return_value={}
+ with (
+ patch_bond_bridge(),
+ patch_bond_version(
+ return_value={
+ "bondid": "ZXXX12345",
+ "target": "test-model",
+ "fw_ver": "test-version",
+ }
+ ),
+ patch_start_bpup(),
+ patch_bond_device_ids(return_value=["bond-device-id", "device_id"]),
+ patch_bond_device(
+ return_value={
+ "name": "test1",
+ "type": DeviceType.GENERIC_DEVICE,
+ }
+ ),
+ patch_bond_device_properties(return_value={}),
+ patch_bond_device_state(return_value={}),
):
assert await hass.config_entries.async_setup(config_entry.entry_id) is True
await hass.async_block_till_done()
@@ -210,24 +215,26 @@ async def test_smart_by_bond_device_suggested_area(
config_entry.add_to_hass(hass)
- with patch_bond_bridge(
- side_effect=ClientResponseError(Mock(), Mock(), status=404)
- ), patch_bond_version(
- return_value={
- "bondid": "KXXX12345",
- "target": "test-model",
- "fw_ver": "test-version",
- }
- ), patch_start_bpup(), patch_bond_device_ids(
- return_value=["bond-device-id", "device_id"]
- ), patch_bond_device(
- return_value={
- "name": "test1",
- "type": DeviceType.GENERIC_DEVICE,
- "location": "Den",
- }
- ), patch_bond_device_properties(return_value={}), patch_bond_device_state(
- return_value={}
+ with (
+ patch_bond_bridge(side_effect=ClientResponseError(Mock(), Mock(), status=404)),
+ patch_bond_version(
+ return_value={
+ "bondid": "KXXX12345",
+ "target": "test-model",
+ "fw_ver": "test-version",
+ }
+ ),
+ patch_start_bpup(),
+ patch_bond_device_ids(return_value=["bond-device-id", "device_id"]),
+ patch_bond_device(
+ return_value={
+ "name": "test1",
+ "type": DeviceType.GENERIC_DEVICE,
+ "location": "Den",
+ }
+ ),
+ patch_bond_device_properties(return_value={}),
+ patch_bond_device_state(return_value={}),
):
assert await hass.config_entries.async_setup(config_entry.entry_id) is True
await hass.async_block_till_done()
@@ -252,27 +259,31 @@ async def test_bridge_device_suggested_area(
config_entry.add_to_hass(hass)
- with patch_bond_bridge(
- return_value={
- "name": "Office Bridge",
- "location": "Office",
- }
- ), patch_bond_version(
- return_value={
- "bondid": "ZXXX12345",
- "target": "test-model",
- "fw_ver": "test-version",
- }
- ), patch_start_bpup(), patch_bond_device_ids(
- return_value=["bond-device-id", "device_id"]
- ), patch_bond_device(
- return_value={
- "name": "test1",
- "type": DeviceType.GENERIC_DEVICE,
- "location": "Bathroom",
- }
- ), patch_bond_device_properties(return_value={}), patch_bond_device_state(
- return_value={}
+ with (
+ patch_bond_bridge(
+ return_value={
+ "name": "Office Bridge",
+ "location": "Office",
+ }
+ ),
+ patch_bond_version(
+ return_value={
+ "bondid": "ZXXX12345",
+ "target": "test-model",
+ "fw_ver": "test-version",
+ }
+ ),
+ patch_start_bpup(),
+ patch_bond_device_ids(return_value=["bond-device-id", "device_id"]),
+ patch_bond_device(
+ return_value={
+ "name": "test1",
+ "type": DeviceType.GENERIC_DEVICE,
+ "location": "Bathroom",
+ }
+ ),
+ patch_bond_device_properties(return_value={}),
+ patch_bond_device_state(return_value={}),
):
assert await hass.config_entries.async_setup(config_entry.entry_id) is True
await hass.async_block_till_done()
diff --git a/tests/components/bond/test_light.py b/tests/components/bond/test_light.py
index eed8166b1a6..37cd82fc321 100644
--- a/tests/components/bond/test_light.py
+++ b/tests/components/bond/test_light.py
@@ -330,9 +330,11 @@ async def test_light_set_brightness_belief_api_error(hass: HomeAssistant) -> Non
bond_device_id="test-device-id",
)
- with pytest.raises(
- HomeAssistantError
- ), patch_bond_action_returns_clientresponseerror(), patch_bond_device_state():
+ with (
+ pytest.raises(HomeAssistantError),
+ patch_bond_action_returns_clientresponseerror(),
+ patch_bond_device_state(),
+ ):
await hass.services.async_call(
DOMAIN,
SERVICE_SET_LIGHT_BRIGHTNESS_TRACKED_STATE,
@@ -374,9 +376,11 @@ async def test_fp_light_set_brightness_belief_api_error(hass: HomeAssistant) ->
bond_device_id="test-device-id",
)
- with pytest.raises(
- HomeAssistantError
- ), patch_bond_action_returns_clientresponseerror(), patch_bond_device_state():
+ with (
+ pytest.raises(HomeAssistantError),
+ patch_bond_action_returns_clientresponseerror(),
+ patch_bond_device_state(),
+ ):
await hass.services.async_call(
DOMAIN,
SERVICE_SET_LIGHT_BRIGHTNESS_TRACKED_STATE,
@@ -485,9 +489,11 @@ async def test_light_set_power_belief_api_error(hass: HomeAssistant) -> None:
bond_device_id="test-device-id",
)
- with pytest.raises(
- HomeAssistantError
- ), patch_bond_action_returns_clientresponseerror(), patch_bond_device_state():
+ with (
+ pytest.raises(HomeAssistantError),
+ patch_bond_action_returns_clientresponseerror(),
+ patch_bond_device_state(),
+ ):
await hass.services.async_call(
DOMAIN,
SERVICE_SET_LIGHT_POWER_TRACKED_STATE,
@@ -529,9 +535,11 @@ async def test_fp_light_set_power_belief_api_error(hass: HomeAssistant) -> None:
bond_device_id="test-device-id",
)
- with pytest.raises(
- HomeAssistantError
- ), patch_bond_action_returns_clientresponseerror(), patch_bond_device_state():
+ with (
+ pytest.raises(HomeAssistantError),
+ patch_bond_action_returns_clientresponseerror(),
+ patch_bond_device_state(),
+ ):
await hass.services.async_call(
DOMAIN,
SERVICE_SET_LIGHT_POWER_TRACKED_STATE,
diff --git a/tests/components/bond/test_switch.py b/tests/components/bond/test_switch.py
index 6bef33939ab..3d3ad663656 100644
--- a/tests/components/bond/test_switch.py
+++ b/tests/components/bond/test_switch.py
@@ -112,9 +112,11 @@ async def test_switch_set_power_belief_api_error(hass: HomeAssistant) -> None:
hass, SWITCH_DOMAIN, generic_device("name-1"), bond_device_id="test-device-id"
)
- with pytest.raises(
- HomeAssistantError
- ), patch_bond_action_returns_clientresponseerror(), patch_bond_device_state():
+ with (
+ pytest.raises(HomeAssistantError),
+ patch_bond_action_returns_clientresponseerror(),
+ patch_bond_device_state(),
+ ):
await hass.services.async_call(
BOND_DOMAIN,
SERVICE_SET_POWER_TRACKED_STATE,
diff --git a/tests/components/bosch_shc/test_config_flow.py b/tests/components/bosch_shc/test_config_flow.py
index 99def2b0f29..2fe2b98308d 100644
--- a/tests/components/bosch_shc/test_config_flow.py
+++ b/tests/components/bosch_shc/test_config_flow.py
@@ -44,17 +44,21 @@ async def test_form_user(hass: HomeAssistant, mock_zeroconf: None) -> None:
assert result["step_id"] == "user"
assert result["errors"] == {}
- with patch(
- "boschshcpy.session.SHCSession.mdns_info",
- return_value=SHCInformation,
- ), patch(
- "boschshcpy.information.SHCInformation.name",
- new_callable=PropertyMock,
- return_value="shc012345",
- ), patch(
- "boschshcpy.information.SHCInformation.unique_id",
- new_callable=PropertyMock,
- return_value="test-mac",
+ with (
+ patch(
+ "boschshcpy.session.SHCSession.mdns_info",
+ return_value=SHCInformation,
+ ),
+ patch(
+ "boschshcpy.information.SHCInformation.name",
+ new_callable=PropertyMock,
+ return_value="shc012345",
+ ),
+ patch(
+ "boschshcpy.information.SHCInformation.unique_id",
+ new_callable=PropertyMock,
+ return_value="test-mac",
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -65,19 +69,23 @@ async def test_form_user(hass: HomeAssistant, mock_zeroconf: None) -> None:
assert result2["step_id"] == "credentials"
assert result2["errors"] == {}
- with patch(
- "boschshcpy.register_client.SHCRegisterClient.register",
- return_value={
- "token": "abc:123",
- "cert": b"content_cert",
- "key": b"content_key",
- },
- ), patch("os.mkdir"), patch(
- "homeassistant.components.bosch_shc.config_flow.open"
- ), patch("boschshcpy.session.SHCSession.authenticate") as mock_authenticate, patch(
- "homeassistant.components.bosch_shc.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "boschshcpy.register_client.SHCRegisterClient.register",
+ return_value={
+ "token": "abc:123",
+ "cert": b"content_cert",
+ "key": b"content_key",
+ },
+ ),
+ patch("os.mkdir"),
+ patch("homeassistant.components.bosch_shc.config_flow.open"),
+ patch("boschshcpy.session.SHCSession.authenticate") as mock_authenticate,
+ patch(
+ "homeassistant.components.bosch_shc.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{"password": "test"},
@@ -150,17 +158,21 @@ async def test_form_pairing_error(hass: HomeAssistant, mock_zeroconf: None) -> N
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "boschshcpy.session.SHCSession.mdns_info",
- return_value=SHCInformation,
- ), patch(
- "boschshcpy.information.SHCInformation.name",
- new_callable=PropertyMock,
- return_value="shc012345",
- ), patch(
- "boschshcpy.information.SHCInformation.unique_id",
- new_callable=PropertyMock,
- return_value="test-mac",
+ with (
+ patch(
+ "boschshcpy.session.SHCSession.mdns_info",
+ return_value=SHCInformation,
+ ),
+ patch(
+ "boschshcpy.information.SHCInformation.name",
+ new_callable=PropertyMock,
+ return_value="shc012345",
+ ),
+ patch(
+ "boschshcpy.information.SHCInformation.unique_id",
+ new_callable=PropertyMock,
+ return_value="test-mac",
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -192,17 +204,21 @@ async def test_form_user_invalid_auth(hass: HomeAssistant, mock_zeroconf: None)
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "boschshcpy.session.SHCSession.mdns_info",
- return_value=SHCInformation,
- ), patch(
- "boschshcpy.information.SHCInformation.name",
- new_callable=PropertyMock,
- return_value="shc012345",
- ), patch(
- "boschshcpy.information.SHCInformation.unique_id",
- new_callable=PropertyMock,
- return_value="test-mac",
+ with (
+ patch(
+ "boschshcpy.session.SHCSession.mdns_info",
+ return_value=SHCInformation,
+ ),
+ patch(
+ "boschshcpy.information.SHCInformation.name",
+ new_callable=PropertyMock,
+ return_value="shc012345",
+ ),
+ patch(
+ "boschshcpy.information.SHCInformation.unique_id",
+ new_callable=PropertyMock,
+ return_value="test-mac",
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -213,18 +229,21 @@ async def test_form_user_invalid_auth(hass: HomeAssistant, mock_zeroconf: None)
assert result2["step_id"] == "credentials"
assert result2["errors"] == {}
- with patch(
- "boschshcpy.register_client.SHCRegisterClient.register",
- return_value={
- "token": "abc:123",
- "cert": b"content_cert",
- "key": b"content_key",
- },
- ), patch("os.mkdir"), patch(
- "homeassistant.components.bosch_shc.config_flow.open"
- ), patch(
- "boschshcpy.session.SHCSession.authenticate",
- side_effect=SHCAuthenticationError,
+ with (
+ patch(
+ "boschshcpy.register_client.SHCRegisterClient.register",
+ return_value={
+ "token": "abc:123",
+ "cert": b"content_cert",
+ "key": b"content_key",
+ },
+ ),
+ patch("os.mkdir"),
+ patch("homeassistant.components.bosch_shc.config_flow.open"),
+ patch(
+ "boschshcpy.session.SHCSession.authenticate",
+ side_effect=SHCAuthenticationError,
+ ),
):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
@@ -245,17 +264,21 @@ async def test_form_validate_connection_error(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "boschshcpy.session.SHCSession.mdns_info",
- return_value=SHCInformation,
- ), patch(
- "boschshcpy.information.SHCInformation.name",
- new_callable=PropertyMock,
- return_value="shc012345",
- ), patch(
- "boschshcpy.information.SHCInformation.unique_id",
- new_callable=PropertyMock,
- return_value="test-mac",
+ with (
+ patch(
+ "boschshcpy.session.SHCSession.mdns_info",
+ return_value=SHCInformation,
+ ),
+ patch(
+ "boschshcpy.information.SHCInformation.name",
+ new_callable=PropertyMock,
+ return_value="shc012345",
+ ),
+ patch(
+ "boschshcpy.information.SHCInformation.unique_id",
+ new_callable=PropertyMock,
+ return_value="test-mac",
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -266,18 +289,21 @@ async def test_form_validate_connection_error(
assert result2["step_id"] == "credentials"
assert result2["errors"] == {}
- with patch(
- "boschshcpy.register_client.SHCRegisterClient.register",
- return_value={
- "token": "abc:123",
- "cert": b"content_cert",
- "key": b"content_key",
- },
- ), patch("os.mkdir"), patch(
- "homeassistant.components.bosch_shc.config_flow.open"
- ), patch(
- "boschshcpy.session.SHCSession.authenticate",
- side_effect=SHCConnectionError,
+ with (
+ patch(
+ "boschshcpy.register_client.SHCRegisterClient.register",
+ return_value={
+ "token": "abc:123",
+ "cert": b"content_cert",
+ "key": b"content_key",
+ },
+ ),
+ patch("os.mkdir"),
+ patch("homeassistant.components.bosch_shc.config_flow.open"),
+ patch(
+ "boschshcpy.session.SHCSession.authenticate",
+ side_effect=SHCConnectionError,
+ ),
):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
@@ -298,17 +324,21 @@ async def test_form_validate_session_error(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "boschshcpy.session.SHCSession.mdns_info",
- return_value=SHCInformation,
- ), patch(
- "boschshcpy.information.SHCInformation.name",
- new_callable=PropertyMock,
- return_value="shc012345",
- ), patch(
- "boschshcpy.information.SHCInformation.unique_id",
- new_callable=PropertyMock,
- return_value="test-mac",
+ with (
+ patch(
+ "boschshcpy.session.SHCSession.mdns_info",
+ return_value=SHCInformation,
+ ),
+ patch(
+ "boschshcpy.information.SHCInformation.name",
+ new_callable=PropertyMock,
+ return_value="shc012345",
+ ),
+ patch(
+ "boschshcpy.information.SHCInformation.unique_id",
+ new_callable=PropertyMock,
+ return_value="test-mac",
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -319,18 +349,21 @@ async def test_form_validate_session_error(
assert result2["step_id"] == "credentials"
assert result2["errors"] == {}
- with patch(
- "boschshcpy.register_client.SHCRegisterClient.register",
- return_value={
- "token": "abc:123",
- "cert": b"content_cert",
- "key": b"content_key",
- },
- ), patch("os.mkdir"), patch(
- "homeassistant.components.bosch_shc.config_flow.open"
- ), patch(
- "boschshcpy.session.SHCSession.authenticate",
- side_effect=SHCSessionError(""),
+ with (
+ patch(
+ "boschshcpy.register_client.SHCRegisterClient.register",
+ return_value={
+ "token": "abc:123",
+ "cert": b"content_cert",
+ "key": b"content_key",
+ },
+ ),
+ patch("os.mkdir"),
+ patch("homeassistant.components.bosch_shc.config_flow.open"),
+ patch(
+ "boschshcpy.session.SHCSession.authenticate",
+ side_effect=SHCSessionError(""),
+ ),
):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
@@ -351,17 +384,21 @@ async def test_form_validate_exception(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "boschshcpy.session.SHCSession.mdns_info",
- return_value=SHCInformation,
- ), patch(
- "boschshcpy.information.SHCInformation.name",
- new_callable=PropertyMock,
- return_value="shc012345",
- ), patch(
- "boschshcpy.information.SHCInformation.unique_id",
- new_callable=PropertyMock,
- return_value="test-mac",
+ with (
+ patch(
+ "boschshcpy.session.SHCSession.mdns_info",
+ return_value=SHCInformation,
+ ),
+ patch(
+ "boschshcpy.information.SHCInformation.name",
+ new_callable=PropertyMock,
+ return_value="shc012345",
+ ),
+ patch(
+ "boschshcpy.information.SHCInformation.unique_id",
+ new_callable=PropertyMock,
+ return_value="test-mac",
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -372,18 +409,21 @@ async def test_form_validate_exception(
assert result2["step_id"] == "credentials"
assert result2["errors"] == {}
- with patch(
- "boschshcpy.register_client.SHCRegisterClient.register",
- return_value={
- "token": "abc:123",
- "cert": b"content_cert",
- "key": b"content_key",
- },
- ), patch("os.mkdir"), patch(
- "homeassistant.components.bosch_shc.config_flow.open"
- ), patch(
- "boschshcpy.session.SHCSession.authenticate",
- side_effect=Exception,
+ with (
+ patch(
+ "boschshcpy.register_client.SHCRegisterClient.register",
+ return_value={
+ "token": "abc:123",
+ "cert": b"content_cert",
+ "key": b"content_key",
+ },
+ ),
+ patch("os.mkdir"),
+ patch("homeassistant.components.bosch_shc.config_flow.open"),
+ patch(
+ "boschshcpy.session.SHCSession.authenticate",
+ side_effect=Exception,
+ ),
):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
@@ -410,17 +450,21 @@ async def test_form_already_configured(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "boschshcpy.session.SHCSession.mdns_info",
- return_value=SHCInformation,
- ), patch(
- "boschshcpy.information.SHCInformation.name",
- new_callable=PropertyMock,
- return_value="shc012345",
- ), patch(
- "boschshcpy.information.SHCInformation.unique_id",
- new_callable=PropertyMock,
- return_value="test-mac",
+ with (
+ patch(
+ "boschshcpy.session.SHCSession.mdns_info",
+ return_value=SHCInformation,
+ ),
+ patch(
+ "boschshcpy.information.SHCInformation.name",
+ new_callable=PropertyMock,
+ return_value="shc012345",
+ ),
+ patch(
+ "boschshcpy.information.SHCInformation.unique_id",
+ new_callable=PropertyMock,
+ return_value="test-mac",
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -437,17 +481,21 @@ async def test_form_already_configured(
async def test_zeroconf(hass: HomeAssistant, mock_zeroconf: None) -> None:
"""Test we get the form."""
- with patch(
- "boschshcpy.session.SHCSession.mdns_info",
- return_value=SHCInformation,
- ), patch(
- "boschshcpy.information.SHCInformation.name",
- new_callable=PropertyMock,
- return_value="shc012345",
- ), patch(
- "boschshcpy.information.SHCInformation.unique_id",
- new_callable=PropertyMock,
- return_value="test-mac",
+ with (
+ patch(
+ "boschshcpy.session.SHCSession.mdns_info",
+ return_value=SHCInformation,
+ ),
+ patch(
+ "boschshcpy.information.SHCInformation.name",
+ new_callable=PropertyMock,
+ return_value="shc012345",
+ ),
+ patch(
+ "boschshcpy.information.SHCInformation.unique_id",
+ new_callable=PropertyMock,
+ return_value="test-mac",
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -471,21 +519,25 @@ async def test_zeroconf(hass: HomeAssistant, mock_zeroconf: None) -> None:
assert result2["type"] == "form"
assert result2["step_id"] == "credentials"
- with patch(
- "boschshcpy.register_client.SHCRegisterClient.register",
- return_value={
- "token": "abc:123",
- "cert": b"content_cert",
- "key": b"content_key",
- },
- ), patch("os.mkdir"), patch(
- "homeassistant.components.bosch_shc.config_flow.open"
- ), patch(
- "boschshcpy.session.SHCSession.authenticate",
- ), patch(
- "homeassistant.components.bosch_shc.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "boschshcpy.register_client.SHCRegisterClient.register",
+ return_value={
+ "token": "abc:123",
+ "cert": b"content_cert",
+ "key": b"content_key",
+ },
+ ),
+ patch("os.mkdir"),
+ patch("homeassistant.components.bosch_shc.config_flow.open"),
+ patch(
+ "boschshcpy.session.SHCSession.authenticate",
+ ),
+ patch(
+ "homeassistant.components.bosch_shc.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{"password": "test"},
@@ -514,17 +566,21 @@ async def test_zeroconf_already_configured(
)
entry.add_to_hass(hass)
- with patch(
- "boschshcpy.session.SHCSession.mdns_info",
- return_value=SHCInformation,
- ), patch(
- "boschshcpy.information.SHCInformation.name",
- new_callable=PropertyMock,
- return_value="shc012345",
- ), patch(
- "boschshcpy.information.SHCInformation.unique_id",
- new_callable=PropertyMock,
- return_value="test-mac",
+ with (
+ patch(
+ "boschshcpy.session.SHCSession.mdns_info",
+ return_value=SHCInformation,
+ ),
+ patch(
+ "boschshcpy.information.SHCInformation.name",
+ new_callable=PropertyMock,
+ return_value="shc012345",
+ ),
+ patch(
+ "boschshcpy.information.SHCInformation.unique_id",
+ new_callable=PropertyMock,
+ return_value="test-mac",
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -597,17 +653,21 @@ async def test_reauth(hass: HomeAssistant, mock_zeroconf: None) -> None:
assert result["type"] == "form"
assert result["step_id"] == "reauth_confirm"
- with patch(
- "boschshcpy.session.SHCSession.mdns_info",
- return_value=SHCInformation,
- ), patch(
- "boschshcpy.information.SHCInformation.name",
- new_callable=PropertyMock,
- return_value="shc012345",
- ), patch(
- "boschshcpy.information.SHCInformation.unique_id",
- new_callable=PropertyMock,
- return_value="test-mac",
+ with (
+ patch(
+ "boschshcpy.session.SHCSession.mdns_info",
+ return_value=SHCInformation,
+ ),
+ patch(
+ "boschshcpy.information.SHCInformation.name",
+ new_callable=PropertyMock,
+ return_value="shc012345",
+ ),
+ patch(
+ "boschshcpy.information.SHCInformation.unique_id",
+ new_callable=PropertyMock,
+ return_value="test-mac",
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -618,19 +678,23 @@ async def test_reauth(hass: HomeAssistant, mock_zeroconf: None) -> None:
assert result2["step_id"] == "credentials"
assert result2["errors"] == {}
- with patch(
- "boschshcpy.register_client.SHCRegisterClient.register",
- return_value={
- "token": "abc:123",
- "cert": b"content_cert",
- "key": b"content_key",
- },
- ), patch("os.mkdir"), patch(
- "homeassistant.components.bosch_shc.config_flow.open"
- ), patch("boschshcpy.session.SHCSession.authenticate"), patch(
- "homeassistant.components.bosch_shc.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "boschshcpy.register_client.SHCRegisterClient.register",
+ return_value={
+ "token": "abc:123",
+ "cert": b"content_cert",
+ "key": b"content_key",
+ },
+ ),
+ patch("os.mkdir"),
+ patch("homeassistant.components.bosch_shc.config_flow.open"),
+ patch("boschshcpy.session.SHCSession.authenticate"),
+ patch(
+ "homeassistant.components.bosch_shc.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{"password": "test"},
@@ -652,9 +716,12 @@ async def test_tls_assets_writer(hass: HomeAssistant) -> None:
"cert": b"content_cert",
"key": b"content_key",
}
- with patch("os.mkdir"), patch(
- "homeassistant.components.bosch_shc.config_flow.open", mock_open()
- ) as mocked_file:
+ with (
+ patch("os.mkdir"),
+ patch(
+ "homeassistant.components.bosch_shc.config_flow.open", mock_open()
+ ) as mocked_file,
+ ):
write_tls_asset(hass, CONF_SHC_CERT, assets["cert"])
mocked_file.assert_called_with(
hass.config.path(DOMAIN, CONF_SHC_CERT), "w", encoding="utf8"
diff --git a/tests/components/braviatv/test_config_flow.py b/tests/components/braviatv/test_config_flow.py
index 36673cfe011..673344017f7 100644
--- a/tests/components/braviatv/test_config_flow.py
+++ b/tests/components/braviatv/test_config_flow.py
@@ -108,11 +108,14 @@ async def test_ssdp_discovery(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "confirm"
- with patch("pybravia.BraviaClient.connect"), patch(
- "pybravia.BraviaClient.pair"
- ), patch("pybravia.BraviaClient.set_wol_mode"), patch(
- "pybravia.BraviaClient.get_system_info",
- return_value=BRAVIA_SYSTEM_INFO,
+ with (
+ patch("pybravia.BraviaClient.connect"),
+ patch("pybravia.BraviaClient.pair"),
+ patch("pybravia.BraviaClient.set_wol_mode"),
+ patch(
+ "pybravia.BraviaClient.get_system_info",
+ return_value=BRAVIA_SYSTEM_INFO,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
@@ -201,10 +204,13 @@ async def test_user_invalid_host(hass: HomeAssistant) -> None:
)
async def test_pin_form_error(hass: HomeAssistant, side_effect, error_message) -> None:
"""Test that PIN form errors are correct."""
- with patch(
- "pybravia.BraviaClient.connect",
- side_effect=side_effect,
- ), patch("pybravia.BraviaClient.pair"):
+ with (
+ patch(
+ "pybravia.BraviaClient.connect",
+ side_effect=side_effect,
+ ),
+ patch("pybravia.BraviaClient.pair"),
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data={CONF_HOST: "bravia-host"}
)
@@ -273,11 +279,14 @@ async def test_duplicate_error(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with patch("pybravia.BraviaClient.connect"), patch(
- "pybravia.BraviaClient.pair"
- ), patch("pybravia.BraviaClient.set_wol_mode"), patch(
- "pybravia.BraviaClient.get_system_info",
- return_value=BRAVIA_SYSTEM_INFO,
+ with (
+ patch("pybravia.BraviaClient.connect"),
+ patch("pybravia.BraviaClient.pair"),
+ patch("pybravia.BraviaClient.set_wol_mode"),
+ patch(
+ "pybravia.BraviaClient.get_system_info",
+ return_value=BRAVIA_SYSTEM_INFO,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data={CONF_HOST: "bravia-host"}
@@ -297,11 +306,14 @@ async def test_create_entry(hass: HomeAssistant) -> None:
"""Test that entry is added correctly with PIN auth."""
uuid = await instance_id.async_get(hass)
- with patch("pybravia.BraviaClient.connect"), patch(
- "pybravia.BraviaClient.pair"
- ), patch("pybravia.BraviaClient.set_wol_mode"), patch(
- "pybravia.BraviaClient.get_system_info",
- return_value=BRAVIA_SYSTEM_INFO,
+ with (
+ patch("pybravia.BraviaClient.connect"),
+ patch("pybravia.BraviaClient.pair"),
+ patch("pybravia.BraviaClient.set_wol_mode"),
+ patch(
+ "pybravia.BraviaClient.get_system_info",
+ return_value=BRAVIA_SYSTEM_INFO,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data={CONF_HOST: "bravia-host"}
@@ -336,11 +348,13 @@ async def test_create_entry(hass: HomeAssistant) -> None:
async def test_create_entry_psk(hass: HomeAssistant) -> None:
"""Test that entry is added correctly with PSK auth."""
- with patch("pybravia.BraviaClient.connect"), patch(
- "pybravia.BraviaClient.set_wol_mode"
- ), patch(
- "pybravia.BraviaClient.get_system_info",
- return_value=BRAVIA_SYSTEM_INFO,
+ with (
+ patch("pybravia.BraviaClient.connect"),
+ patch("pybravia.BraviaClient.set_wol_mode"),
+ patch(
+ "pybravia.BraviaClient.get_system_info",
+ return_value=BRAVIA_SYSTEM_INFO,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data={CONF_HOST: "bravia-host"}
@@ -392,15 +406,20 @@ async def test_reauth_successful(hass: HomeAssistant, use_psk, new_pin) -> None:
)
config_entry.add_to_hass(hass)
- with patch("pybravia.BraviaClient.connect"), patch(
- "pybravia.BraviaClient.get_power_status",
- return_value="active",
- ), patch(
- "pybravia.BraviaClient.get_external_status",
- return_value=BRAVIA_SOURCES,
- ), patch(
- "pybravia.BraviaClient.send_rest_req",
- return_value={},
+ with (
+ patch("pybravia.BraviaClient.connect"),
+ patch(
+ "pybravia.BraviaClient.get_power_status",
+ return_value="active",
+ ),
+ patch(
+ "pybravia.BraviaClient.get_external_status",
+ return_value=BRAVIA_SOURCES,
+ ),
+ patch(
+ "pybravia.BraviaClient.send_rest_req",
+ return_value={},
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
diff --git a/tests/components/braviatv/test_diagnostics.py b/tests/components/braviatv/test_diagnostics.py
index f5c174ee672..13f6c92fb76 100644
--- a/tests/components/braviatv/test_diagnostics.py
+++ b/tests/components/braviatv/test_diagnostics.py
@@ -56,16 +56,17 @@ async def test_entry_diagnostics(
)
config_entry.add_to_hass(hass)
- with patch("pybravia.BraviaClient.connect"), patch(
- "pybravia.BraviaClient.pair"
- ), patch("pybravia.BraviaClient.set_wol_mode"), patch(
- "pybravia.BraviaClient.get_system_info", return_value=BRAVIA_SYSTEM_INFO
- ), patch("pybravia.BraviaClient.get_power_status", return_value="active"), patch(
- "pybravia.BraviaClient.get_external_status", return_value=INPUTS
- ), patch("pybravia.BraviaClient.get_volume_info", return_value={}), patch(
- "pybravia.BraviaClient.get_playing_info", return_value={}
- ), patch("pybravia.BraviaClient.get_app_list", return_value=[]), patch(
- "pybravia.BraviaClient.get_content_list_all", return_value=[]
+ with (
+ patch("pybravia.BraviaClient.connect"),
+ patch("pybravia.BraviaClient.pair"),
+ patch("pybravia.BraviaClient.set_wol_mode"),
+ patch("pybravia.BraviaClient.get_system_info", return_value=BRAVIA_SYSTEM_INFO),
+ patch("pybravia.BraviaClient.get_power_status", return_value="active"),
+ patch("pybravia.BraviaClient.get_external_status", return_value=INPUTS),
+ patch("pybravia.BraviaClient.get_volume_info", return_value={}),
+ patch("pybravia.BraviaClient.get_playing_info", return_value={}),
+ patch("pybravia.BraviaClient.get_app_list", return_value=[]),
+ patch("pybravia.BraviaClient.get_content_list_all", return_value=[]),
):
assert await async_setup_component(hass, DOMAIN, {})
result = await get_diagnostics_for_config_entry(hass, hass_client, config_entry)
diff --git a/tests/components/bring/conftest.py b/tests/components/bring/conftest.py
index c296642f020..e399e18dfbe 100644
--- a/tests/components/bring/conftest.py
+++ b/tests/components/bring/conftest.py
@@ -28,12 +28,15 @@ def mock_setup_entry() -> Generator[AsyncMock, None, None]:
@pytest.fixture
def mock_bring_client() -> Generator[AsyncMock, None, None]:
"""Mock a Bring client."""
- with patch(
- "homeassistant.components.bring.Bring",
- autospec=True,
- ) as mock_client, patch(
- "homeassistant.components.bring.config_flow.Bring",
- new=mock_client,
+ with (
+ patch(
+ "homeassistant.components.bring.Bring",
+ autospec=True,
+ ) as mock_client,
+ patch(
+ "homeassistant.components.bring.config_flow.Bring",
+ new=mock_client,
+ ),
):
client = mock_client.return_value
client.uuid = UUID
diff --git a/tests/components/broadlink/test_config_flow.py b/tests/components/broadlink/test_config_flow.py
index 6eb87966082..143742d3a9a 100644
--- a/tests/components/broadlink/test_config_flow.py
+++ b/tests/components/broadlink/test_config_flow.py
@@ -21,9 +21,12 @@ DEVICE_FACTORY = "homeassistant.components.broadlink.config_flow.blk.gendevice"
@pytest.fixture(autouse=True)
def broadlink_setup_fixture():
"""Mock broadlink entry setup."""
- with patch(
- "homeassistant.components.broadlink.async_setup", return_value=True
- ), patch("homeassistant.components.broadlink.async_setup_entry", return_value=True):
+ with (
+ patch("homeassistant.components.broadlink.async_setup", return_value=True),
+ patch(
+ "homeassistant.components.broadlink.async_setup_entry", return_value=True
+ ),
+ ):
yield
diff --git a/tests/components/broadlink/test_device.py b/tests/components/broadlink/test_device.py
index 365d61a9e69..c9f22dbcbf8 100644
--- a/tests/components/broadlink/test_device.py
+++ b/tests/components/broadlink/test_device.py
@@ -20,11 +20,10 @@ async def test_device_setup(hass: HomeAssistant) -> None:
"""Test a successful setup."""
device = get_device("Office")
- with patch.object(
- hass.config_entries, "async_forward_entry_setups"
- ) as mock_forward, patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_init:
+ with (
+ patch.object(hass.config_entries, "async_forward_entry_setups") as mock_forward,
+ patch.object(hass.config_entries.flow, "async_init") as mock_init,
+ ):
mock_setup = await device.setup_entry(hass)
assert mock_setup.entry.state is ConfigEntryState.LOADED
@@ -45,11 +44,10 @@ async def test_device_setup_authentication_error(hass: HomeAssistant) -> None:
mock_api = device.get_mock_api()
mock_api.auth.side_effect = blke.AuthenticationError()
- with patch.object(
- hass.config_entries, "async_forward_entry_setups"
- ) as mock_forward, patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_init:
+ with (
+ patch.object(hass.config_entries, "async_forward_entry_setups") as mock_forward,
+ patch.object(hass.config_entries.flow, "async_init") as mock_init,
+ ):
mock_setup = await device.setup_entry(hass, mock_api=mock_api)
assert mock_setup.entry.state is ConfigEntryState.SETUP_ERROR
@@ -69,11 +67,10 @@ async def test_device_setup_network_timeout(hass: HomeAssistant) -> None:
mock_api = device.get_mock_api()
mock_api.auth.side_effect = blke.NetworkTimeoutError()
- with patch.object(
- hass.config_entries, "async_forward_entry_setups"
- ) as mock_forward, patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_init:
+ with (
+ patch.object(hass.config_entries, "async_forward_entry_setups") as mock_forward,
+ patch.object(hass.config_entries.flow, "async_init") as mock_init,
+ ):
mock_setup = await device.setup_entry(hass, mock_api=mock_api)
assert mock_setup.entry.state is ConfigEntryState.SETUP_RETRY
@@ -88,11 +85,10 @@ async def test_device_setup_os_error(hass: HomeAssistant) -> None:
mock_api = device.get_mock_api()
mock_api.auth.side_effect = OSError()
- with patch.object(
- hass.config_entries, "async_forward_entry_setups"
- ) as mock_forward, patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_init:
+ with (
+ patch.object(hass.config_entries, "async_forward_entry_setups") as mock_forward,
+ patch.object(hass.config_entries.flow, "async_init") as mock_init,
+ ):
mock_setup = await device.setup_entry(hass, mock_api=mock_api)
assert mock_setup.entry.state is ConfigEntryState.SETUP_RETRY
@@ -107,11 +103,10 @@ async def test_device_setup_broadlink_exception(hass: HomeAssistant) -> None:
mock_api = device.get_mock_api()
mock_api.auth.side_effect = blke.BroadlinkException()
- with patch.object(
- hass.config_entries, "async_forward_entry_setups"
- ) as mock_forward, patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_init:
+ with (
+ patch.object(hass.config_entries, "async_forward_entry_setups") as mock_forward,
+ patch.object(hass.config_entries.flow, "async_init") as mock_init,
+ ):
mock_setup = await device.setup_entry(hass, mock_api=mock_api)
assert mock_setup.entry.state is ConfigEntryState.SETUP_ERROR
@@ -126,11 +121,10 @@ async def test_device_setup_update_network_timeout(hass: HomeAssistant) -> None:
mock_api = device.get_mock_api()
mock_api.check_sensors.side_effect = blke.NetworkTimeoutError()
- with patch.object(
- hass.config_entries, "async_forward_entry_setups"
- ) as mock_forward, patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_init:
+ with (
+ patch.object(hass.config_entries, "async_forward_entry_setups") as mock_forward,
+ patch.object(hass.config_entries.flow, "async_init") as mock_init,
+ ):
mock_setup = await device.setup_entry(hass, mock_api=mock_api)
assert mock_setup.entry.state is ConfigEntryState.SETUP_RETRY
@@ -149,11 +143,10 @@ async def test_device_setup_update_authorization_error(hass: HomeAssistant) -> N
{"temperature": 30},
)
- with patch.object(
- hass.config_entries, "async_forward_entry_setups"
- ) as mock_forward, patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_init:
+ with (
+ patch.object(hass.config_entries, "async_forward_entry_setups") as mock_forward,
+ patch.object(hass.config_entries.flow, "async_init") as mock_init,
+ ):
mock_setup = await device.setup_entry(hass, mock_api=mock_api)
assert mock_setup.entry.state is ConfigEntryState.LOADED
@@ -174,11 +167,10 @@ async def test_device_setup_update_authentication_error(hass: HomeAssistant) ->
mock_api.check_sensors.side_effect = blke.AuthorizationError()
mock_api.auth.side_effect = (None, blke.AuthenticationError())
- with patch.object(
- hass.config_entries, "async_forward_entry_setups"
- ) as mock_forward, patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_init:
+ with (
+ patch.object(hass.config_entries, "async_forward_entry_setups") as mock_forward,
+ patch.object(hass.config_entries.flow, "async_init") as mock_init,
+ ):
mock_setup = await device.setup_entry(hass, mock_api=mock_api)
assert mock_setup.entry.state is ConfigEntryState.SETUP_RETRY
@@ -199,11 +191,10 @@ async def test_device_setup_update_broadlink_exception(hass: HomeAssistant) -> N
mock_api = device.get_mock_api()
mock_api.check_sensors.side_effect = blke.BroadlinkException()
- with patch.object(
- hass.config_entries, "async_forward_entry_setups"
- ) as mock_forward, patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_init:
+ with (
+ patch.object(hass.config_entries, "async_forward_entry_setups") as mock_forward,
+ patch.object(hass.config_entries.flow, "async_init") as mock_init,
+ ):
mock_setup = await device.setup_entry(hass, mock_api=mock_api)
assert mock_setup.entry.state is ConfigEntryState.SETUP_RETRY
@@ -306,8 +297,9 @@ async def test_device_unload_authentication_error(hass: HomeAssistant) -> None:
mock_api = device.get_mock_api()
mock_api.auth.side_effect = blke.AuthenticationError()
- with patch.object(hass.config_entries, "async_forward_entry_setups"), patch.object(
- hass.config_entries.flow, "async_init"
+ with (
+ patch.object(hass.config_entries, "async_forward_entry_setups"),
+ patch.object(hass.config_entries.flow, "async_init"),
):
mock_setup = await device.setup_entry(hass, mock_api=mock_api)
diff --git a/tests/components/brother/__init__.py b/tests/components/brother/__init__.py
index 591a227c3b5..b5a3f8ed5ef 100644
--- a/tests/components/brother/__init__.py
+++ b/tests/components/brother/__init__.py
@@ -24,9 +24,12 @@ async def init_integration(
entry.add_to_hass(hass)
if not skip_setup:
- with patch("brother.Brother.initialize"), patch(
- "brother.Brother._get_data",
- return_value=json.loads(load_fixture("printer_data.json", "brother")),
+ with (
+ patch("brother.Brother.initialize"),
+ patch(
+ "brother.Brother._get_data",
+ return_value=json.loads(load_fixture("printer_data.json", "brother")),
+ ),
):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/brother/test_config_flow.py b/tests/components/brother/test_config_flow.py
index dc8e5c4d079..2eff4ed2770 100644
--- a/tests/components/brother/test_config_flow.py
+++ b/tests/components/brother/test_config_flow.py
@@ -33,9 +33,12 @@ async def test_show_form(hass: HomeAssistant) -> None:
async def test_create_entry_with_hostname(hass: HomeAssistant) -> None:
"""Test that the user step works with printer hostname."""
- with patch("brother.Brother.initialize"), patch(
- "brother.Brother._get_data",
- return_value=json.loads(load_fixture("printer_data.json", "brother")),
+ with (
+ patch("brother.Brother.initialize"),
+ patch(
+ "brother.Brother._get_data",
+ return_value=json.loads(load_fixture("printer_data.json", "brother")),
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -51,9 +54,12 @@ async def test_create_entry_with_hostname(hass: HomeAssistant) -> None:
async def test_create_entry_with_ipv4_address(hass: HomeAssistant) -> None:
"""Test that the user step works with printer IPv4 address."""
- with patch("brother.Brother.initialize"), patch(
- "brother.Brother._get_data",
- return_value=json.loads(load_fixture("printer_data.json", "brother")),
+ with (
+ patch("brother.Brother.initialize"),
+ patch(
+ "brother.Brother._get_data",
+ return_value=json.loads(load_fixture("printer_data.json", "brother")),
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=CONFIG
@@ -67,9 +73,12 @@ async def test_create_entry_with_ipv4_address(hass: HomeAssistant) -> None:
async def test_create_entry_with_ipv6_address(hass: HomeAssistant) -> None:
"""Test that the user step works with printer IPv6 address."""
- with patch("brother.Brother.initialize"), patch(
- "brother.Brother._get_data",
- return_value=json.loads(load_fixture("printer_data.json", "brother")),
+ with (
+ patch("brother.Brother.initialize"),
+ patch(
+ "brother.Brother._get_data",
+ return_value=json.loads(load_fixture("printer_data.json", "brother")),
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -97,8 +106,9 @@ async def test_invalid_hostname(hass: HomeAssistant) -> None:
@pytest.mark.parametrize("exc", [ConnectionError, TimeoutError])
async def test_connection_error(hass: HomeAssistant, exc: Exception) -> None:
"""Test connection to host error."""
- with patch("brother.Brother.initialize"), patch(
- "brother.Brother._get_data", side_effect=exc
+ with (
+ patch("brother.Brother.initialize"),
+ patch("brother.Brother._get_data", side_effect=exc),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=CONFIG
@@ -109,8 +119,9 @@ async def test_connection_error(hass: HomeAssistant, exc: Exception) -> None:
async def test_snmp_error(hass: HomeAssistant) -> None:
"""Test SNMP error."""
- with patch("brother.Brother.initialize"), patch(
- "brother.Brother._get_data", side_effect=SnmpError("error")
+ with (
+ patch("brother.Brother.initialize"),
+ patch("brother.Brother._get_data", side_effect=SnmpError("error")),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=CONFIG
@@ -121,8 +132,9 @@ async def test_snmp_error(hass: HomeAssistant) -> None:
async def test_unsupported_model_error(hass: HomeAssistant) -> None:
"""Test unsupported printer model error."""
- with patch("brother.Brother.initialize"), patch(
- "brother.Brother._get_data", side_effect=UnsupportedModelError("error")
+ with (
+ patch("brother.Brother.initialize"),
+ patch("brother.Brother._get_data", side_effect=UnsupportedModelError("error")),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=CONFIG
@@ -134,9 +146,12 @@ async def test_unsupported_model_error(hass: HomeAssistant) -> None:
async def test_device_exists_abort(hass: HomeAssistant) -> None:
"""Test we abort config flow if Brother printer already configured."""
- with patch("brother.Brother.initialize"), patch(
- "brother.Brother._get_data",
- return_value=json.loads(load_fixture("printer_data.json", "brother")),
+ with (
+ patch("brother.Brother.initialize"),
+ patch(
+ "brother.Brother._get_data",
+ return_value=json.loads(load_fixture("printer_data.json", "brother")),
+ ),
):
MockConfigEntry(domain=DOMAIN, unique_id="0123456789", data=CONFIG).add_to_hass(
hass
@@ -152,8 +167,9 @@ async def test_device_exists_abort(hass: HomeAssistant) -> None:
@pytest.mark.parametrize("exc", [ConnectionError, TimeoutError, SnmpError("error")])
async def test_zeroconf_exception(hass: HomeAssistant, exc: Exception) -> None:
"""Test we abort zeroconf flow on exception."""
- with patch("brother.Brother.initialize"), patch(
- "brother.Brother._get_data", side_effect=exc
+ with (
+ patch("brother.Brother.initialize"),
+ patch("brother.Brother._get_data", side_effect=exc),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -175,9 +191,10 @@ async def test_zeroconf_exception(hass: HomeAssistant, exc: Exception) -> None:
async def test_zeroconf_unsupported_model(hass: HomeAssistant) -> None:
"""Test unsupported printer model error."""
- with patch("brother.Brother.initialize"), patch(
- "brother.Brother._get_data"
- ) as mock_get_data:
+ with (
+ patch("brother.Brother.initialize"),
+ patch("brother.Brother._get_data") as mock_get_data,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
@@ -199,9 +216,12 @@ async def test_zeroconf_unsupported_model(hass: HomeAssistant) -> None:
async def test_zeroconf_device_exists_abort(hass: HomeAssistant) -> None:
"""Test we abort zeroconf flow if Brother printer already configured."""
- with patch("brother.Brother.initialize"), patch(
- "brother.Brother._get_data",
- return_value=json.loads(load_fixture("printer_data.json", "brother")),
+ with (
+ patch("brother.Brother.initialize"),
+ patch(
+ "brother.Brother._get_data",
+ return_value=json.loads(load_fixture("printer_data.json", "brother")),
+ ),
):
entry = MockConfigEntry(
domain=DOMAIN,
@@ -235,9 +255,10 @@ async def test_zeroconf_no_probe_existing_device(hass: HomeAssistant) -> None:
"""Test we do not probe the device is the host is already configured."""
entry = MockConfigEntry(domain=DOMAIN, unique_id="0123456789", data=CONFIG)
entry.add_to_hass(hass)
- with patch("brother.Brother.initialize"), patch(
- "brother.Brother._get_data"
- ) as mock_get_data:
+ with (
+ patch("brother.Brother.initialize"),
+ patch("brother.Brother._get_data") as mock_get_data,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
@@ -260,9 +281,12 @@ async def test_zeroconf_no_probe_existing_device(hass: HomeAssistant) -> None:
async def test_zeroconf_confirm_create_entry(hass: HomeAssistant) -> None:
"""Test zeroconf confirmation and create config entry."""
- with patch("brother.Brother.initialize"), patch(
- "brother.Brother._get_data",
- return_value=json.loads(load_fixture("printer_data.json", "brother")),
+ with (
+ patch("brother.Brother.initialize"),
+ patch(
+ "brother.Brother._get_data",
+ return_value=json.loads(load_fixture("printer_data.json", "brother")),
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
diff --git a/tests/components/brother/test_diagnostics.py b/tests/components/brother/test_diagnostics.py
index c935ae5e50a..2ea9faa151e 100644
--- a/tests/components/brother/test_diagnostics.py
+++ b/tests/components/brother/test_diagnostics.py
@@ -25,11 +25,13 @@ async def test_entry_diagnostics(
entry = await init_integration(hass, skip_setup=True)
test_time = datetime(2019, 11, 11, 9, 10, 32, tzinfo=UTC)
- with patch("brother.Brother.initialize"), patch(
- "brother.datetime", now=Mock(return_value=test_time)
- ), patch(
- "brother.Brother._get_data",
- return_value=json.loads(load_fixture("printer_data.json", "brother")),
+ with (
+ patch("brother.Brother.initialize"),
+ patch("brother.datetime", now=Mock(return_value=test_time)),
+ patch(
+ "brother.Brother._get_data",
+ return_value=json.loads(load_fixture("printer_data.json", "brother")),
+ ),
):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/brother/test_init.py b/tests/components/brother/test_init.py
index 331f022e2a9..582e64c71ae 100644
--- a/tests/components/brother/test_init.py
+++ b/tests/components/brother/test_init.py
@@ -34,8 +34,9 @@ async def test_config_not_ready(hass: HomeAssistant) -> None:
data={CONF_HOST: "localhost", CONF_TYPE: "laser"},
)
- with patch("brother.Brother.initialize"), patch(
- "brother.Brother._get_data", side_effect=ConnectionError()
+ with (
+ patch("brother.Brother.initialize"),
+ patch("brother.Brother._get_data", side_effect=ConnectionError()),
):
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
diff --git a/tests/components/brother/test_sensor.py b/tests/components/brother/test_sensor.py
index 25015b28269..ff29f8cb368 100644
--- a/tests/components/brother/test_sensor.py
+++ b/tests/components/brother/test_sensor.py
@@ -46,11 +46,13 @@ async def test_sensors(hass: HomeAssistant, entity_registry: er.EntityRegistry)
disabled_by=None,
)
test_time = datetime(2019, 11, 11, 9, 10, 32, tzinfo=UTC)
- with patch("brother.Brother.initialize"), patch(
- "brother.datetime", now=Mock(return_value=test_time)
- ), patch(
- "brother.Brother._get_data",
- return_value=json.loads(load_fixture("printer_data.json", "brother")),
+ with (
+ patch("brother.Brother.initialize"),
+ patch("brother.datetime", now=Mock(return_value=test_time)),
+ patch(
+ "brother.Brother._get_data",
+ return_value=json.loads(load_fixture("printer_data.json", "brother")),
+ ),
):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
@@ -394,8 +396,9 @@ async def test_availability(hass: HomeAssistant) -> None:
assert state.state == "waiting"
future = utcnow() + timedelta(minutes=5)
- with patch("brother.Brother.initialize"), patch(
- "brother.Brother._get_data", side_effect=ConnectionError()
+ with (
+ patch("brother.Brother.initialize"),
+ patch("brother.Brother._get_data", side_effect=ConnectionError()),
):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
@@ -405,9 +408,12 @@ async def test_availability(hass: HomeAssistant) -> None:
assert state.state == STATE_UNAVAILABLE
future = utcnow() + timedelta(minutes=10)
- with patch("brother.Brother.initialize"), patch(
- "brother.Brother._get_data",
- return_value=json.loads(load_fixture("printer_data.json", "brother")),
+ with (
+ patch("brother.Brother.initialize"),
+ patch(
+ "brother.Brother._get_data",
+ return_value=json.loads(load_fixture("printer_data.json", "brother")),
+ ),
):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
diff --git a/tests/components/bsblan/conftest.py b/tests/components/bsblan/conftest.py
index 98e2410383b..a9120832ac4 100644
--- a/tests/components/bsblan/conftest.py
+++ b/tests/components/bsblan/conftest.py
@@ -43,10 +43,9 @@ def mock_setup_entry() -> Generator[AsyncMock, None, None]:
def mock_bsblan(request: pytest.FixtureRequest) -> Generator[None, MagicMock, None]:
"""Return a mocked BSBLAN client."""
- with patch(
- "homeassistant.components.bsblan.BSBLAN", autospec=True
- ) as bsblan_mock, patch(
- "homeassistant.components.bsblan.config_flow.BSBLAN", new=bsblan_mock
+ with (
+ patch("homeassistant.components.bsblan.BSBLAN", autospec=True) as bsblan_mock,
+ patch("homeassistant.components.bsblan.config_flow.BSBLAN", new=bsblan_mock),
):
bsblan = bsblan_mock.return_value
bsblan.info.return_value = Info.parse_raw(load_fixture("info.json", DOMAIN))
diff --git a/tests/components/bthome/test_config_flow.py b/tests/components/bthome/test_config_flow.py
index b6a3498d570..1a785858752 100644
--- a/tests/components/bthome/test_config_flow.py
+++ b/tests/components/bthome/test_config_flow.py
@@ -41,12 +41,15 @@ async def test_async_step_bluetooth_valid_device(hass: HomeAssistant) -> None:
async def test_async_step_bluetooth_during_onboarding(hass: HomeAssistant) -> None:
"""Test discovery via bluetooth during onboarding."""
- with patch(
- "homeassistant.components.bthome.async_setup_entry", return_value=True
- ) as mock_setup_entry, patch(
- "homeassistant.components.onboarding.async_is_onboarded",
- return_value=False,
- ) as mock_onboarding:
+ with (
+ patch(
+ "homeassistant.components.bthome.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.onboarding.async_is_onboarded",
+ return_value=False,
+ ) as mock_onboarding,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_BLUETOOTH},
diff --git a/tests/components/camera/conftest.py b/tests/components/camera/conftest.py
index c1d630de126..ee8c5df7d65 100644
--- a/tests/components/camera/conftest.py
+++ b/tests/components/camera/conftest.py
@@ -63,12 +63,15 @@ async def mock_camera_web_rtc_fixture(hass):
)
await hass.async_block_till_done()
- with patch(
- "homeassistant.components.camera.Camera.frontend_stream_type",
- new_callable=PropertyMock(return_value=StreamType.WEB_RTC),
- ), patch(
- "homeassistant.components.camera.Camera.async_handle_web_rtc_offer",
- return_value=WEBRTC_ANSWER,
+ with (
+ patch(
+ "homeassistant.components.camera.Camera.frontend_stream_type",
+ new_callable=PropertyMock(return_value=StreamType.WEB_RTC),
+ ),
+ patch(
+ "homeassistant.components.camera.Camera.async_handle_web_rtc_offer",
+ return_value=WEBRTC_ANSWER,
+ ),
):
yield
@@ -85,14 +88,16 @@ async def mock_camera_with_device_fixture():
def __get__(self, obj, obj_type=None):
return obj.name
- with patch(
- "homeassistant.components.camera.Camera.has_entity_name",
- new_callable=PropertyMock(return_value=True),
- ), patch(
- "homeassistant.components.camera.Camera.unique_id", new=UniqueIdMock()
- ), patch(
- "homeassistant.components.camera.Camera.device_info",
- new_callable=PropertyMock(return_value=dev_info),
+ with (
+ patch(
+ "homeassistant.components.camera.Camera.has_entity_name",
+ new_callable=PropertyMock(return_value=True),
+ ),
+ patch("homeassistant.components.camera.Camera.unique_id", new=UniqueIdMock()),
+ patch(
+ "homeassistant.components.camera.Camera.device_info",
+ new_callable=PropertyMock(return_value=dev_info),
+ ),
):
yield
diff --git a/tests/components/camera/test_init.py b/tests/components/camera/test_init.py
index 82a2652b8bc..ccec2b6f50c 100644
--- a/tests/components/camera/test_init.py
+++ b/tests/components/camera/test_init.py
@@ -112,14 +112,17 @@ async def test_get_image_from_camera_with_width_height(
turbo_jpeg = mock_turbo_jpeg(
first_width=16, first_height=12, second_width=300, second_height=200
)
- with patch(
- "homeassistant.components.camera.img_util.TurboJPEGSingleton.instance",
- return_value=turbo_jpeg,
- ), patch(
- "homeassistant.components.demo.camera.Path.read_bytes",
- autospec=True,
- return_value=b"Test",
- ) as mock_camera:
+ with (
+ patch(
+ "homeassistant.components.camera.img_util.TurboJPEGSingleton.instance",
+ return_value=turbo_jpeg,
+ ),
+ patch(
+ "homeassistant.components.demo.camera.Path.read_bytes",
+ autospec=True,
+ return_value=b"Test",
+ ) as mock_camera,
+ ):
image = await camera.async_get_image(
hass, "camera.demo_camera", width=640, height=480
)
@@ -136,14 +139,17 @@ async def test_get_image_from_camera_with_width_height_scaled(
turbo_jpeg = mock_turbo_jpeg(
first_width=16, first_height=12, second_width=300, second_height=200
)
- with patch(
- "homeassistant.components.camera.img_util.TurboJPEGSingleton.instance",
- return_value=turbo_jpeg,
- ), patch(
- "homeassistant.components.demo.camera.Path.read_bytes",
- autospec=True,
- return_value=b"Valid jpeg",
- ) as mock_camera:
+ with (
+ patch(
+ "homeassistant.components.camera.img_util.TurboJPEGSingleton.instance",
+ return_value=turbo_jpeg,
+ ),
+ patch(
+ "homeassistant.components.demo.camera.Path.read_bytes",
+ autospec=True,
+ return_value=b"Valid jpeg",
+ ) as mock_camera,
+ ):
image = await camera.async_get_image(
hass, "camera.demo_camera", width=4, height=3
)
@@ -161,14 +167,17 @@ async def test_get_image_from_camera_not_jpeg(
turbo_jpeg = mock_turbo_jpeg(
first_width=16, first_height=12, second_width=300, second_height=200
)
- with patch(
- "homeassistant.components.camera.img_util.TurboJPEGSingleton.instance",
- return_value=turbo_jpeg,
- ), patch(
- "homeassistant.components.demo.camera.Path.read_bytes",
- autospec=True,
- return_value=b"png",
- ) as mock_camera:
+ with (
+ patch(
+ "homeassistant.components.camera.img_util.TurboJPEGSingleton.instance",
+ return_value=turbo_jpeg,
+ ),
+ patch(
+ "homeassistant.components.demo.camera.Path.read_bytes",
+ autospec=True,
+ return_value=b"png",
+ ) as mock_camera,
+ ):
image = await camera.async_get_image(
hass, "camera.demo_camera_png", width=4, height=3
)
@@ -193,28 +202,37 @@ async def test_get_image_without_exists_camera(
hass: HomeAssistant, image_mock_url
) -> None:
"""Try to get image without exists camera."""
- with patch(
- "homeassistant.helpers.entity_component.EntityComponent.get_entity",
- return_value=None,
- ), pytest.raises(HomeAssistantError):
+ with (
+ patch(
+ "homeassistant.helpers.entity_component.EntityComponent.get_entity",
+ return_value=None,
+ ),
+ pytest.raises(HomeAssistantError),
+ ):
await camera.async_get_image(hass, "camera.demo_camera")
async def test_get_image_with_timeout(hass: HomeAssistant, image_mock_url) -> None:
"""Try to get image with timeout."""
- with patch(
- "homeassistant.components.demo.camera.DemoCamera.async_camera_image",
- side_effect=TimeoutError,
- ), pytest.raises(HomeAssistantError):
+ with (
+ patch(
+ "homeassistant.components.demo.camera.DemoCamera.async_camera_image",
+ side_effect=TimeoutError,
+ ),
+ pytest.raises(HomeAssistantError),
+ ):
await camera.async_get_image(hass, "camera.demo_camera")
async def test_get_image_fails(hass: HomeAssistant, image_mock_url) -> None:
"""Try to get image with timeout."""
- with patch(
- "homeassistant.components.demo.camera.DemoCamera.async_camera_image",
- return_value=None,
- ), pytest.raises(HomeAssistantError):
+ with (
+ patch(
+ "homeassistant.components.demo.camera.DemoCamera.async_camera_image",
+ return_value=None,
+ ),
+ pytest.raises(HomeAssistantError),
+ ):
await camera.async_get_image(hass, "camera.demo_camera")
@@ -222,9 +240,13 @@ async def test_snapshot_service(hass: HomeAssistant, mock_camera) -> None:
"""Test snapshot service."""
mopen = mock_open()
- with patch("homeassistant.components.camera.open", mopen, create=True), patch(
- "homeassistant.components.camera.os.makedirs",
- ), patch.object(hass.config, "is_allowed_path", return_value=True):
+ with (
+ patch("homeassistant.components.camera.open", mopen, create=True),
+ patch(
+ "homeassistant.components.camera.os.makedirs",
+ ),
+ patch.object(hass.config, "is_allowed_path", return_value=True),
+ ):
await hass.services.async_call(
camera.DOMAIN,
camera.SERVICE_SNAPSHOT,
@@ -247,9 +269,13 @@ async def test_snapshot_service_not_allowed_path(
"""Test snapshot service with a not allowed path."""
mopen = mock_open()
- with patch("homeassistant.components.camera.open", mopen, create=True), patch(
- "homeassistant.components.camera.os.makedirs",
- ), pytest.raises(HomeAssistantError, match="/test/snapshot.jpg"):
+ with (
+ patch("homeassistant.components.camera.open", mopen, create=True),
+ patch(
+ "homeassistant.components.camera.os.makedirs",
+ ),
+ pytest.raises(HomeAssistantError, match="/test/snapshot.jpg"),
+ ):
await hass.services.async_call(
camera.DOMAIN,
camera.SERVICE_SNAPSHOT,
@@ -286,12 +312,15 @@ async def test_websocket_camera_stream(
"""Test camera/stream websocket command."""
await async_setup_component(hass, "camera", {})
- with patch(
- "homeassistant.components.camera.Stream.endpoint_url",
- return_value="http://home.assistant/playlist.m3u8",
- ) as mock_stream_view_url, patch(
- "homeassistant.components.demo.camera.DemoCamera.stream_source",
- return_value="http://example.com",
+ with (
+ patch(
+ "homeassistant.components.camera.Stream.endpoint_url",
+ return_value="http://home.assistant/playlist.m3u8",
+ ) as mock_stream_view_url,
+ patch(
+ "homeassistant.components.demo.camera.DemoCamera.stream_source",
+ return_value="http://example.com",
+ ),
):
# Request playlist through WebSocket
client = await hass_ws_client(hass)
@@ -444,11 +473,14 @@ async def test_handle_play_stream_service(
{"external_url": "https://example.com"},
)
await async_setup_component(hass, "media_player", {})
- with patch(
- "homeassistant.components.camera.Stream.endpoint_url",
- ) as mock_request_stream, patch(
- "homeassistant.components.demo.camera.DemoCamera.stream_source",
- return_value="http://example.com",
+ with (
+ patch(
+ "homeassistant.components.camera.Stream.endpoint_url",
+ ) as mock_request_stream,
+ patch(
+ "homeassistant.components.demo.camera.DemoCamera.stream_source",
+ return_value="http://example.com",
+ ),
):
# Call service
await hass.services.async_call(
@@ -468,15 +500,19 @@ async def test_handle_play_stream_service(
async def test_no_preload_stream(hass: HomeAssistant, mock_stream) -> None:
"""Test camera preload preference."""
demo_settings = camera.DynamicStreamSettings()
- with patch(
- "homeassistant.components.camera.Stream.endpoint_url",
- ) as mock_request_stream, patch(
- "homeassistant.components.camera.prefs.CameraPreferences.get_dynamic_stream_settings",
- return_value=demo_settings,
- ), patch(
- "homeassistant.components.demo.camera.DemoCamera.stream_source",
- new_callable=PropertyMock,
- ) as mock_stream_source:
+ with (
+ patch(
+ "homeassistant.components.camera.Stream.endpoint_url",
+ ) as mock_request_stream,
+ patch(
+ "homeassistant.components.camera.prefs.CameraPreferences.get_dynamic_stream_settings",
+ return_value=demo_settings,
+ ),
+ patch(
+ "homeassistant.components.demo.camera.DemoCamera.stream_source",
+ new_callable=PropertyMock,
+ ) as mock_stream_source,
+ ):
mock_stream_source.return_value = io.BytesIO()
await async_setup_component(hass, "camera", {DOMAIN: {"platform": "demo"}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -487,14 +523,16 @@ async def test_no_preload_stream(hass: HomeAssistant, mock_stream) -> None:
async def test_preload_stream(hass: HomeAssistant, mock_stream) -> None:
"""Test camera preload preference."""
demo_settings = camera.DynamicStreamSettings(preload_stream=True)
- with patch(
- "homeassistant.components.camera.create_stream"
- ) as mock_create_stream, patch(
- "homeassistant.components.camera.prefs.CameraPreferences.get_dynamic_stream_settings",
- return_value=demo_settings,
- ), patch(
- "homeassistant.components.demo.camera.DemoCamera.stream_source",
- return_value="http://example.com",
+ with (
+ patch("homeassistant.components.camera.create_stream") as mock_create_stream,
+ patch(
+ "homeassistant.components.camera.prefs.CameraPreferences.get_dynamic_stream_settings",
+ return_value=demo_settings,
+ ),
+ patch(
+ "homeassistant.components.demo.camera.DemoCamera.stream_source",
+ return_value="http://example.com",
+ ),
):
mock_create_stream.return_value.start = AsyncMock()
assert await async_setup_component(
@@ -508,9 +546,10 @@ async def test_preload_stream(hass: HomeAssistant, mock_stream) -> None:
async def test_record_service_invalid_path(hass: HomeAssistant, mock_camera) -> None:
"""Test record service with invalid path."""
- with patch.object(
- hass.config, "is_allowed_path", return_value=False
- ), pytest.raises(HomeAssistantError):
+ with (
+ patch.object(hass.config, "is_allowed_path", return_value=False),
+ pytest.raises(HomeAssistantError),
+ ):
# Call service
await hass.services.async_call(
camera.DOMAIN,
@@ -525,13 +564,16 @@ async def test_record_service_invalid_path(hass: HomeAssistant, mock_camera) ->
async def test_record_service(hass: HomeAssistant, mock_camera, mock_stream) -> None:
"""Test record service."""
- with patch(
- "homeassistant.components.demo.camera.DemoCamera.stream_source",
- return_value="http://example.com",
- ), patch(
- "homeassistant.components.stream.Stream.async_record",
- autospec=True,
- ) as mock_record:
+ with (
+ patch(
+ "homeassistant.components.demo.camera.DemoCamera.stream_source",
+ return_value="http://example.com",
+ ),
+ patch(
+ "homeassistant.components.stream.Stream.async_record",
+ autospec=True,
+ ) as mock_record,
+ ):
# Call service
await hass.services.async_call(
camera.DOMAIN,
@@ -727,15 +769,19 @@ async def test_stream_unavailable(
"""Camera state."""
await async_setup_component(hass, "camera", {})
- with patch(
- "homeassistant.components.camera.Stream.endpoint_url",
- return_value="http://home.assistant/playlist.m3u8",
- ), patch(
- "homeassistant.components.demo.camera.DemoCamera.stream_source",
- return_value="http://example.com",
- ), patch(
- "homeassistant.components.camera.Stream.set_update_callback",
- ) as mock_update_callback:
+ with (
+ patch(
+ "homeassistant.components.camera.Stream.endpoint_url",
+ return_value="http://home.assistant/playlist.m3u8",
+ ),
+ patch(
+ "homeassistant.components.demo.camera.DemoCamera.stream_source",
+ return_value="http://example.com",
+ ),
+ patch(
+ "homeassistant.components.camera.Stream.set_update_callback",
+ ) as mock_update_callback,
+ ):
# Request playlist through WebSocket. We just want to create the stream
# but don't care about the result.
client = await hass_ws_client(hass)
@@ -920,12 +966,15 @@ async def test_use_stream_for_stills(
client = await hass_client()
- with patch(
- "homeassistant.components.demo.camera.DemoCamera.stream_source",
- return_value=None,
- ) as mock_stream_source, patch(
- "homeassistant.components.demo.camera.DemoCamera.use_stream_for_stills",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.demo.camera.DemoCamera.stream_source",
+ return_value=None,
+ ) as mock_stream_source,
+ patch(
+ "homeassistant.components.demo.camera.DemoCamera.use_stream_for_stills",
+ return_value=True,
+ ),
):
# First test when the integration does not support stream should fail
resp = await client.get("/api/camera_proxy/camera.demo_camera_without_stream")
@@ -938,14 +987,16 @@ async def test_use_stream_for_stills(
mock_stream_source.assert_called_once()
assert resp.status == HTTPStatus.INTERNAL_SERVER_ERROR
- with patch(
- "homeassistant.components.demo.camera.DemoCamera.stream_source",
- return_value="rtsp://some_source",
- ) as mock_stream_source, patch(
- "homeassistant.components.camera.create_stream"
- ) as mock_create_stream, patch(
- "homeassistant.components.demo.camera.DemoCamera.use_stream_for_stills",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.demo.camera.DemoCamera.stream_source",
+ return_value="rtsp://some_source",
+ ) as mock_stream_source,
+ patch("homeassistant.components.camera.create_stream") as mock_create_stream,
+ patch(
+ "homeassistant.components.demo.camera.DemoCamera.use_stream_for_stills",
+ return_value=True,
+ ),
):
# Now test when creating the stream succeeds
mock_stream = Mock()
diff --git a/tests/components/camera/test_media_source.py b/tests/components/camera/test_media_source.py
index bab6d3a236b..3dd0399a710 100644
--- a/tests/components/camera/test_media_source.py
+++ b/tests/components/camera/test_media_source.py
@@ -124,9 +124,12 @@ async def test_resolving_errors(hass: HomeAssistant, mock_camera_hls) -> None:
)
assert str(exc_info.value) == "Could not resolve media item: camera.non_existing"
- with pytest.raises(media_source.Unresolvable) as exc_info, patch(
- "homeassistant.components.camera.Camera.frontend_stream_type",
- new_callable=PropertyMock(return_value=StreamType.WEB_RTC),
+ with (
+ pytest.raises(media_source.Unresolvable) as exc_info,
+ patch(
+ "homeassistant.components.camera.Camera.frontend_stream_type",
+ new_callable=PropertyMock(return_value=StreamType.WEB_RTC),
+ ),
):
await media_source.async_resolve_media(
hass, "media-source://camera/camera.demo_camera", None
diff --git a/tests/components/canary/conftest.py b/tests/components/canary/conftest.py
index 25c9b3c3a4f..336e6577ecc 100644
--- a/tests/components/canary/conftest.py
+++ b/tests/components/canary/conftest.py
@@ -15,9 +15,10 @@ def mock_ffmpeg(hass):
@pytest.fixture
def canary(hass):
"""Mock the CanaryApi for easier testing."""
- with patch.object(Api, "login", return_value=True), patch(
- "homeassistant.components.canary.Api"
- ) as mock_canary:
+ with (
+ patch.object(Api, "login", return_value=True),
+ patch("homeassistant.components.canary.Api") as mock_canary,
+ ):
instance = mock_canary.return_value = Api(
"test-username",
"test-password",
@@ -39,9 +40,10 @@ def canary(hass):
@pytest.fixture
def canary_config_flow(hass):
"""Mock the CanaryApi for easier config flow testing."""
- with patch.object(Api, "login", return_value=True), patch(
- "homeassistant.components.canary.config_flow.Api"
- ) as mock_canary:
+ with (
+ patch.object(Api, "login", return_value=True),
+ patch("homeassistant.components.canary.config_flow.Api") as mock_canary,
+ ):
instance = mock_canary.return_value = Api(
"test-username",
"test-password",
diff --git a/tests/components/canary/test_config_flow.py b/tests/components/canary/test_config_flow.py
index 1f28daaeaa3..3c32c683a39 100644
--- a/tests/components/canary/test_config_flow.py
+++ b/tests/components/canary/test_config_flow.py
@@ -27,7 +27,10 @@ async def test_user_form(hass: HomeAssistant, canary_config_flow) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with _patch_async_setup() as mock_setup, _patch_async_setup_entry() as mock_setup_entry:
+ with (
+ _patch_async_setup() as mock_setup,
+ _patch_async_setup_entry() as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
USER_INPUT,
diff --git a/tests/components/cast/conftest.py b/tests/components/cast/conftest.py
index 817c4428098..d9ebb24696e 100644
--- a/tests/components/cast/conftest.py
+++ b/tests/components/cast/conftest.py
@@ -68,27 +68,35 @@ def cast_mock(
"""Mock pychromecast."""
ignore_cec_orig = list(pychromecast.IGNORE_CEC)
- with patch(
- "homeassistant.components.cast.discovery.pychromecast.discovery.CastBrowser",
- castbrowser_mock,
- ), patch(
- "homeassistant.components.cast.helpers.dial.get_cast_type",
- get_cast_type_mock,
- ), patch(
- "homeassistant.components.cast.helpers.dial.get_multizone_status",
- get_multizone_status_mock,
- ), patch(
- "homeassistant.components.cast.media_player.MultizoneManager",
- return_value=mz_mock,
- ), patch(
- "homeassistant.components.cast.media_player.zeroconf.async_get_instance",
- AsyncMock(),
- ), patch(
- "homeassistant.components.cast.media_player.quick_play",
- quick_play_mock,
- ), patch(
- "homeassistant.components.cast.media_player.pychromecast.get_chromecast_from_cast_info",
- get_chromecast_mock,
+ with (
+ patch(
+ "homeassistant.components.cast.discovery.pychromecast.discovery.CastBrowser",
+ castbrowser_mock,
+ ),
+ patch(
+ "homeassistant.components.cast.helpers.dial.get_cast_type",
+ get_cast_type_mock,
+ ),
+ patch(
+ "homeassistant.components.cast.helpers.dial.get_multizone_status",
+ get_multizone_status_mock,
+ ),
+ patch(
+ "homeassistant.components.cast.media_player.MultizoneManager",
+ return_value=mz_mock,
+ ),
+ patch(
+ "homeassistant.components.cast.media_player.zeroconf.async_get_instance",
+ AsyncMock(),
+ ),
+ patch(
+ "homeassistant.components.cast.media_player.quick_play",
+ quick_play_mock,
+ ),
+ patch(
+ "homeassistant.components.cast.media_player.pychromecast.get_chromecast_from_cast_info",
+ get_chromecast_mock,
+ ),
):
yield
diff --git a/tests/components/cast/test_config_flow.py b/tests/components/cast/test_config_flow.py
index 7c7bb64d552..62c21fc95ee 100644
--- a/tests/components/cast/test_config_flow.py
+++ b/tests/components/cast/test_config_flow.py
@@ -14,13 +14,15 @@ from tests.common import MockConfigEntry
async def test_creating_entry_sets_up_media_player(hass: HomeAssistant) -> None:
"""Test setting up Cast loads the media player."""
- with patch(
- "homeassistant.components.cast.media_player.async_setup_entry",
- return_value=True,
- ) as mock_setup, patch(
- "pychromecast.discovery.discover_chromecasts", return_value=(True, None)
- ), patch(
- "pychromecast.discovery.stop_discovery",
+ with (
+ patch(
+ "homeassistant.components.cast.media_player.async_setup_entry",
+ return_value=True,
+ ) as mock_setup,
+ patch("pychromecast.discovery.discover_chromecasts", return_value=(True, None)),
+ patch(
+ "pychromecast.discovery.stop_discovery",
+ ),
):
result = await hass.config_entries.flow.async_init(
cast.DOMAIN, context={"source": config_entries.SOURCE_USER}
diff --git a/tests/components/cast/test_home_assistant_cast.py b/tests/components/cast/test_home_assistant_cast.py
index aa84afb734c..74ab776ec3b 100644
--- a/tests/components/cast/test_home_assistant_cast.py
+++ b/tests/components/cast/test_home_assistant_cast.py
@@ -121,9 +121,10 @@ async def test_remove_entry(hass: HomeAssistant, mock_zeroconf: None) -> None:
entry.add_to_hass(hass)
- with patch(
- "pychromecast.discovery.discover_chromecasts", return_value=(True, None)
- ), patch("pychromecast.discovery.stop_discovery"):
+ with (
+ patch("pychromecast.discovery.discover_chromecasts", return_value=(True, None)),
+ patch("pychromecast.discovery.stop_discovery"),
+ ):
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert "cast" in hass.config.components
diff --git a/tests/components/cast/test_media_player.py b/tests/components/cast/test_media_player.py
index 7756a2aacbd..9ef31457d5c 100644
--- a/tests/components/cast/test_media_player.py
+++ b/tests/components/cast/test_media_player.py
@@ -191,15 +191,19 @@ async def async_setup_media_player_cast(hass: HomeAssistant, info: ChromecastInf
chromecast = get_fake_chromecast(info)
zconf = get_fake_zconf(host=info.cast_info.host, port=info.cast_info.port)
- with patch(
- "homeassistant.components.cast.discovery.pychromecast.get_chromecast_from_cast_info",
- return_value=chromecast,
- ) as get_chromecast, patch(
- "homeassistant.components.cast.discovery.pychromecast.discovery.CastBrowser",
- return_value=browser,
- ) as cast_browser, patch(
- "homeassistant.components.cast.discovery.ChromeCastZeroconf.get_zeroconf",
- return_value=zconf,
+ with (
+ patch(
+ "homeassistant.components.cast.discovery.pychromecast.get_chromecast_from_cast_info",
+ return_value=chromecast,
+ ) as get_chromecast,
+ patch(
+ "homeassistant.components.cast.discovery.pychromecast.discovery.CastBrowser",
+ return_value=browser,
+ ) as cast_browser,
+ patch(
+ "homeassistant.components.cast.discovery.ChromeCastZeroconf.get_zeroconf",
+ return_value=zconf,
+ ),
):
data = {"ignore_cec": [], "known_hosts": [], "uuid": [str(info.uuid)]}
entry = MockConfigEntry(data=data, domain="cast")
@@ -580,13 +584,16 @@ async def test_discover_dynamic_group(
tasks.append(real_create_task(coroutine))
# Discover cast service
- with patch(
- "homeassistant.components.cast.discovery.ChromeCastZeroconf.get_zeroconf",
- return_value=zconf_1,
- ), patch.object(
- hass,
- "async_create_background_task",
- wraps=create_task,
+ with (
+ patch(
+ "homeassistant.components.cast.discovery.ChromeCastZeroconf.get_zeroconf",
+ return_value=zconf_1,
+ ),
+ patch.object(
+ hass,
+ "async_create_background_task",
+ wraps=create_task,
+ ),
):
discover_cast(
pychromecast.discovery.MDNSServiceInfo("service"),
@@ -606,13 +613,16 @@ async def test_discover_dynamic_group(
)
# Discover other dynamic group cast service
- with patch(
- "homeassistant.components.cast.discovery.ChromeCastZeroconf.get_zeroconf",
- return_value=zconf_2,
- ), patch.object(
- hass,
- "async_create_background_task",
- wraps=create_task,
+ with (
+ patch(
+ "homeassistant.components.cast.discovery.ChromeCastZeroconf.get_zeroconf",
+ return_value=zconf_2,
+ ),
+ patch.object(
+ hass,
+ "async_create_background_task",
+ wraps=create_task,
+ ),
):
discover_cast(
pychromecast.discovery.MDNSServiceInfo("service"),
@@ -632,13 +642,16 @@ async def test_discover_dynamic_group(
)
# Get update for cast service
- with patch(
- "homeassistant.components.cast.discovery.ChromeCastZeroconf.get_zeroconf",
- return_value=zconf_1,
- ), patch.object(
- hass,
- "async_create_background_task",
- wraps=create_task,
+ with (
+ patch(
+ "homeassistant.components.cast.discovery.ChromeCastZeroconf.get_zeroconf",
+ return_value=zconf_1,
+ ),
+ patch.object(
+ hass,
+ "async_create_background_task",
+ wraps=create_task,
+ ),
):
discover_cast(
pychromecast.discovery.MDNSServiceInfo("service"),
diff --git a/tests/components/cert_expiry/test_config_flow.py b/tests/components/cert_expiry/test_config_flow.py
index 64afed59d5a..aa5f32c0ca2 100644
--- a/tests/components/cert_expiry/test_config_flow.py
+++ b/tests/components/cert_expiry/test_config_flow.py
@@ -65,11 +65,14 @@ async def test_user_with_bad_cert(hass: HomeAssistant) -> None:
async def test_import_host_only(hass: HomeAssistant) -> None:
"""Test import with host only."""
- with patch(
- "homeassistant.components.cert_expiry.config_flow.get_cert_expiry_timestamp"
- ), patch(
- "homeassistant.components.cert_expiry.coordinator.get_cert_expiry_timestamp",
- return_value=future_timestamp(1),
+ with (
+ patch(
+ "homeassistant.components.cert_expiry.config_flow.get_cert_expiry_timestamp"
+ ),
+ patch(
+ "homeassistant.components.cert_expiry.coordinator.get_cert_expiry_timestamp",
+ return_value=future_timestamp(1),
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -87,11 +90,14 @@ async def test_import_host_only(hass: HomeAssistant) -> None:
async def test_import_host_and_port(hass: HomeAssistant) -> None:
"""Test import with host and port."""
- with patch(
- "homeassistant.components.cert_expiry.config_flow.get_cert_expiry_timestamp"
- ), patch(
- "homeassistant.components.cert_expiry.coordinator.get_cert_expiry_timestamp",
- return_value=future_timestamp(1),
+ with (
+ patch(
+ "homeassistant.components.cert_expiry.config_flow.get_cert_expiry_timestamp"
+ ),
+ patch(
+ "homeassistant.components.cert_expiry.coordinator.get_cert_expiry_timestamp",
+ return_value=future_timestamp(1),
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -109,11 +115,14 @@ async def test_import_host_and_port(hass: HomeAssistant) -> None:
async def test_import_non_default_port(hass: HomeAssistant) -> None:
"""Test import with host and non-default port."""
- with patch(
- "homeassistant.components.cert_expiry.config_flow.get_cert_expiry_timestamp"
- ), patch(
- "homeassistant.components.cert_expiry.coordinator.get_cert_expiry_timestamp",
- return_value=future_timestamp(1),
+ with (
+ patch(
+ "homeassistant.components.cert_expiry.config_flow.get_cert_expiry_timestamp"
+ ),
+ patch(
+ "homeassistant.components.cert_expiry.coordinator.get_cert_expiry_timestamp",
+ return_value=future_timestamp(1),
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -131,11 +140,14 @@ async def test_import_non_default_port(hass: HomeAssistant) -> None:
async def test_import_with_name(hass: HomeAssistant) -> None:
"""Test import with name (deprecated)."""
- with patch(
- "homeassistant.components.cert_expiry.config_flow.get_cert_expiry_timestamp"
- ), patch(
- "homeassistant.components.cert_expiry.coordinator.get_cert_expiry_timestamp",
- return_value=future_timestamp(1),
+ with (
+ patch(
+ "homeassistant.components.cert_expiry.config_flow.get_cert_expiry_timestamp"
+ ),
+ patch(
+ "homeassistant.components.cert_expiry.coordinator.get_cert_expiry_timestamp",
+ return_value=future_timestamp(1),
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
diff --git a/tests/components/cert_expiry/test_init.py b/tests/components/cert_expiry/test_init.py
index 360cd118a13..312b87affd3 100644
--- a/tests/components/cert_expiry/test_init.py
+++ b/tests/components/cert_expiry/test_init.py
@@ -42,11 +42,14 @@ async def test_setup_with_config(hass: HomeAssistant) -> None:
next_update = dt_util.utcnow() + timedelta(seconds=20)
async_fire_time_changed(hass, next_update)
- with patch(
- "homeassistant.components.cert_expiry.config_flow.get_cert_expiry_timestamp"
- ), patch(
- "homeassistant.components.cert_expiry.coordinator.get_cert_expiry_timestamp",
- return_value=future_timestamp(1),
+ with (
+ patch(
+ "homeassistant.components.cert_expiry.config_flow.get_cert_expiry_timestamp"
+ ),
+ patch(
+ "homeassistant.components.cert_expiry.coordinator.get_cert_expiry_timestamp",
+ return_value=future_timestamp(1),
+ ),
):
await hass.async_block_till_done()
diff --git a/tests/components/cert_expiry/test_sensors.py b/tests/components/cert_expiry/test_sensors.py
index 01eb1ba6ea6..d68e973e1fa 100644
--- a/tests/components/cert_expiry/test_sensors.py
+++ b/tests/components/cert_expiry/test_sensors.py
@@ -85,9 +85,12 @@ async def test_update_sensor(hass: HomeAssistant) -> None:
starting_time = static_datetime()
timestamp = future_timestamp(100)
- with freeze_time(starting_time), patch(
- "homeassistant.components.cert_expiry.coordinator.get_cert_expiry_timestamp",
- return_value=timestamp,
+ with (
+ freeze_time(starting_time),
+ patch(
+ "homeassistant.components.cert_expiry.coordinator.get_cert_expiry_timestamp",
+ return_value=timestamp,
+ ),
):
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
@@ -101,9 +104,12 @@ async def test_update_sensor(hass: HomeAssistant) -> None:
assert state.attributes.get("is_valid")
next_update = starting_time + timedelta(hours=24)
- with freeze_time(next_update), patch(
- "homeassistant.components.cert_expiry.coordinator.get_cert_expiry_timestamp",
- return_value=timestamp,
+ with (
+ freeze_time(next_update),
+ patch(
+ "homeassistant.components.cert_expiry.coordinator.get_cert_expiry_timestamp",
+ return_value=timestamp,
+ ),
):
async_fire_time_changed(hass, utcnow() + timedelta(hours=24))
await hass.async_block_till_done()
@@ -129,9 +135,12 @@ async def test_update_sensor_network_errors(hass: HomeAssistant) -> None:
starting_time = static_datetime()
timestamp = future_timestamp(100)
- with freeze_time(starting_time), patch(
- "homeassistant.components.cert_expiry.coordinator.get_cert_expiry_timestamp",
- return_value=timestamp,
+ with (
+ freeze_time(starting_time),
+ patch(
+ "homeassistant.components.cert_expiry.coordinator.get_cert_expiry_timestamp",
+ return_value=timestamp,
+ ),
):
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
@@ -146,9 +155,12 @@ async def test_update_sensor_network_errors(hass: HomeAssistant) -> None:
next_update = starting_time + timedelta(hours=24)
- with freeze_time(next_update), patch(
- "homeassistant.components.cert_expiry.helper.async_get_cert",
- side_effect=socket.gaierror,
+ with (
+ freeze_time(next_update),
+ patch(
+ "homeassistant.components.cert_expiry.helper.async_get_cert",
+ side_effect=socket.gaierror,
+ ),
):
async_fire_time_changed(hass, utcnow() + timedelta(hours=24))
await hass.async_block_till_done()
@@ -158,9 +170,12 @@ async def test_update_sensor_network_errors(hass: HomeAssistant) -> None:
state = hass.states.get("sensor.example_com_cert_expiry")
assert state.state == STATE_UNAVAILABLE
- with freeze_time(next_update), patch(
- "homeassistant.components.cert_expiry.coordinator.get_cert_expiry_timestamp",
- return_value=timestamp,
+ with (
+ freeze_time(next_update),
+ patch(
+ "homeassistant.components.cert_expiry.coordinator.get_cert_expiry_timestamp",
+ return_value=timestamp,
+ ),
):
async_fire_time_changed(hass, utcnow() + timedelta(hours=48))
await hass.async_block_till_done()
@@ -174,9 +189,12 @@ async def test_update_sensor_network_errors(hass: HomeAssistant) -> None:
next_update = starting_time + timedelta(hours=72)
- with freeze_time(next_update), patch(
- "homeassistant.components.cert_expiry.helper.async_get_cert",
- side_effect=ssl.SSLError("something bad"),
+ with (
+ freeze_time(next_update),
+ patch(
+ "homeassistant.components.cert_expiry.helper.async_get_cert",
+ side_effect=ssl.SSLError("something bad"),
+ ),
):
async_fire_time_changed(hass, utcnow() + timedelta(hours=72))
await hass.async_block_till_done()
@@ -189,9 +207,12 @@ async def test_update_sensor_network_errors(hass: HomeAssistant) -> None:
next_update = starting_time + timedelta(hours=96)
- with freeze_time(next_update), patch(
- "homeassistant.components.cert_expiry.helper.async_get_cert",
- side_effect=Exception(),
+ with (
+ freeze_time(next_update),
+ patch(
+ "homeassistant.components.cert_expiry.helper.async_get_cert",
+ side_effect=Exception(),
+ ),
):
async_fire_time_changed(hass, utcnow() + timedelta(hours=96))
await hass.async_block_till_done()
diff --git a/tests/components/cloud/conftest.py b/tests/components/cloud/conftest.py
index 4350c58e625..0147556a888 100644
--- a/tests/components/cloud/conftest.py
+++ b/tests/components/cloud/conftest.py
@@ -236,8 +236,9 @@ def mock_cloud_login(hass, mock_cloud_setup):
@pytest.fixture(name="mock_auth")
def mock_auth_fixture():
"""Mock check token."""
- with patch("hass_nabucasa.auth.CognitoAuth.async_check_token"), patch(
- "hass_nabucasa.auth.CognitoAuth.async_renew_access_token"
+ with (
+ patch("hass_nabucasa.auth.CognitoAuth.async_check_token"),
+ patch("hass_nabucasa.auth.CognitoAuth.async_renew_access_token"),
):
yield
diff --git a/tests/components/cloud/test_account_link.py b/tests/components/cloud/test_account_link.py
index 0708c952ca5..99a21734588 100644
--- a/tests/components/cloud/test_account_link.py
+++ b/tests/components/cloud/test_account_link.py
@@ -54,30 +54,34 @@ async def test_setup_provide_implementation(hass: HomeAssistant) -> None:
legacy_entry.add_to_hass(hass)
account_link.async_setup(hass)
- with patch(
- "homeassistant.components.cloud.account_link._get_services",
- return_value=[
- {"service": "test", "min_version": "0.1.0"},
- {"service": "too_new", "min_version": "1000000.0.0"},
- {"service": "dev", "min_version": "2022.9.0"},
- {
- "service": "deprecated",
- "min_version": "0.1.0",
- "accepts_new_authorizations": False,
- },
- {
- "service": "legacy",
- "min_version": "0.1.0",
- "accepts_new_authorizations": False,
- },
- {
- "service": "no_cloud",
- "min_version": "0.1.0",
- "accepts_new_authorizations": False,
- },
- ],
- ), patch(
- "homeassistant.components.cloud.account_link.HA_VERSION", "2022.9.0.dev20220817"
+ with (
+ patch(
+ "homeassistant.components.cloud.account_link._get_services",
+ return_value=[
+ {"service": "test", "min_version": "0.1.0"},
+ {"service": "too_new", "min_version": "1000000.0.0"},
+ {"service": "dev", "min_version": "2022.9.0"},
+ {
+ "service": "deprecated",
+ "min_version": "0.1.0",
+ "accepts_new_authorizations": False,
+ },
+ {
+ "service": "legacy",
+ "min_version": "0.1.0",
+ "accepts_new_authorizations": False,
+ },
+ {
+ "service": "no_cloud",
+ "min_version": "0.1.0",
+ "accepts_new_authorizations": False,
+ },
+ ],
+ ),
+ patch(
+ "homeassistant.components.cloud.account_link.HA_VERSION",
+ "2022.9.0.dev20220817",
+ ),
):
assert (
await config_entry_oauth2_flow.async_get_implementations(
@@ -132,10 +136,13 @@ async def test_get_services_cached(hass: HomeAssistant) -> None:
services = 1
- with patch.object(account_link, "CACHE_TIMEOUT", 0), patch(
- "hass_nabucasa.account_link.async_fetch_available_services",
- side_effect=lambda _: services,
- ) as mock_fetch:
+ with (
+ patch.object(account_link, "CACHE_TIMEOUT", 0),
+ patch(
+ "hass_nabucasa.account_link.async_fetch_available_services",
+ side_effect=lambda _: services,
+ ) as mock_fetch,
+ ):
assert await account_link._get_services(hass) == 1
services = 2
@@ -159,9 +166,12 @@ async def test_get_services_error(hass: HomeAssistant) -> None:
"""Test that we cache services."""
hass.data["cloud"] = None
- with patch.object(account_link, "CACHE_TIMEOUT", 0), patch(
- "hass_nabucasa.account_link.async_fetch_available_services",
- side_effect=TimeoutError,
+ with (
+ patch.object(account_link, "CACHE_TIMEOUT", 0),
+ patch(
+ "hass_nabucasa.account_link.async_fetch_available_services",
+ side_effect=TimeoutError,
+ ),
):
assert await account_link._get_services(hass) == []
assert account_link.DATA_SERVICES not in hass.data
diff --git a/tests/components/cloud/test_alexa_config.py b/tests/components/cloud/test_alexa_config.py
index 21fe75b9494..a6b05198ca4 100644
--- a/tests/components/cloud/test_alexa_config.py
+++ b/tests/components/cloud/test_alexa_config.py
@@ -331,9 +331,12 @@ def patch_sync_helper():
to_remove.extend([ent_id for ent_id in to_rem if ent_id not in to_remove])
return True
- with patch("homeassistant.components.cloud.alexa_config.SYNC_DELAY", 0), patch(
- "homeassistant.components.cloud.alexa_config.CloudAlexaConfig._sync_helper",
- side_effect=sync_helper,
+ with (
+ patch("homeassistant.components.cloud.alexa_config.SYNC_DELAY", 0),
+ patch(
+ "homeassistant.components.cloud.alexa_config.CloudAlexaConfig._sync_helper",
+ side_effect=sync_helper,
+ ),
):
yield to_update, to_remove
@@ -485,10 +488,13 @@ async def test_alexa_update_report_state(
await conf.async_initialize()
await conf.set_authorized(True)
- with patch(
- "homeassistant.components.cloud.alexa_config.CloudAlexaConfig.async_sync_entities",
- ) as mock_sync, patch(
- "homeassistant.components.cloud.alexa_config.CloudAlexaConfig.async_enable_proactive_mode",
+ with (
+ patch(
+ "homeassistant.components.cloud.alexa_config.CloudAlexaConfig.async_sync_entities",
+ ) as mock_sync,
+ patch(
+ "homeassistant.components.cloud.alexa_config.CloudAlexaConfig.async_enable_proactive_mode",
+ ),
):
await cloud_prefs.async_update(alexa_report_state=True)
await hass.async_block_till_done()
diff --git a/tests/components/cloud/test_client.py b/tests/components/cloud/test_client.py
index 6f1552527c4..5e15aa32b6f 100644
--- a/tests/components/cloud/test_client.py
+++ b/tests/components/cloud/test_client.py
@@ -368,9 +368,10 @@ async def test_system_msg(hass: HomeAssistant) -> None:
async def test_cloud_connection_info(hass: HomeAssistant) -> None:
"""Test connection info msg."""
- with patch("hass_nabucasa.Cloud.initialize"), patch(
- "uuid.UUID.hex", new_callable=PropertyMock
- ) as hexmock:
+ with (
+ patch("hass_nabucasa.Cloud.initialize"),
+ patch("uuid.UUID.hex", new_callable=PropertyMock) as hexmock,
+ ):
hexmock.return_value = "12345678901234567890"
setup = await async_setup_component(hass, "cloud", {"cloud": {}})
assert setup
diff --git a/tests/components/cloud/test_config_flow.py b/tests/components/cloud/test_config_flow.py
index 4c9823ee8eb..6b506d6b883 100644
--- a/tests/components/cloud/test_config_flow.py
+++ b/tests/components/cloud/test_config_flow.py
@@ -11,12 +11,15 @@ from tests.common import MockConfigEntry
async def test_config_flow(hass: HomeAssistant) -> None:
"""Test create cloud entry."""
- with patch(
- "homeassistant.components.cloud.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.cloud.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.cloud.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.cloud.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "system"}
)
diff --git a/tests/components/cloud/test_google_config.py b/tests/components/cloud/test_google_config.py
index bde2d85de46..5ce390fd9a3 100644
--- a/tests/components/cloud/test_google_config.py
+++ b/tests/components/cloud/test_google_config.py
@@ -69,9 +69,12 @@ async def test_google_update_report_state(
mock_conf._cloud.subscription_expired = False
- with patch.object(mock_conf, "async_sync_entities") as mock_sync, patch(
- "homeassistant.components.google_assistant.report_state.async_enable_report_state"
- ) as mock_report_state:
+ with (
+ patch.object(mock_conf, "async_sync_entities") as mock_sync,
+ patch(
+ "homeassistant.components.google_assistant.report_state.async_enable_report_state"
+ ) as mock_report_state,
+ ):
await cloud_prefs.async_update(google_report_state=True)
await hass.async_block_till_done()
@@ -90,9 +93,12 @@ async def test_google_update_report_state_subscription_expired(
assert mock_conf._cloud.subscription_expired
- with patch.object(mock_conf, "async_sync_entities") as mock_sync, patch(
- "homeassistant.components.google_assistant.report_state.async_enable_report_state"
- ) as mock_report_state:
+ with (
+ patch.object(mock_conf, "async_sync_entities") as mock_sync,
+ patch(
+ "homeassistant.components.google_assistant.report_state.async_enable_report_state"
+ ) as mock_report_state,
+ ):
await cloud_prefs.async_update(google_report_state=True)
await hass.async_block_till_done()
@@ -154,8 +160,9 @@ async def test_google_update_expose_trigger_sync(
await hass.async_block_till_done()
await config.async_connect_agent_user("mock-user-id")
- with patch.object(config, "async_sync_entities") as mock_sync, patch.object(
- ga_helpers, "SYNC_DELAY", 0
+ with (
+ patch.object(config, "async_sync_entities") as mock_sync,
+ patch.object(ga_helpers, "SYNC_DELAY", 0),
):
expose_entity(hass, light_entry.entity_id, True)
await hass.async_block_till_done()
@@ -164,8 +171,9 @@ async def test_google_update_expose_trigger_sync(
assert len(mock_sync.mock_calls) == 1
- with patch.object(config, "async_sync_entities") as mock_sync, patch.object(
- ga_helpers, "SYNC_DELAY", 0
+ with (
+ patch.object(config, "async_sync_entities") as mock_sync,
+ patch.object(ga_helpers, "SYNC_DELAY", 0),
):
expose_entity(hass, light_entry.entity_id, False)
expose_entity(hass, binary_sensor_entry.entity_id, True)
@@ -194,10 +202,10 @@ async def test_google_entity_registry_sync(
await config.async_initialize()
await config.async_connect_agent_user("mock-user-id")
- with patch.object(
- config, "async_schedule_google_sync_all"
- ) as mock_sync, patch.object(config, "async_sync_entities_all"), patch.object(
- ga_helpers, "SYNC_DELAY", 0
+ with (
+ patch.object(config, "async_schedule_google_sync_all") as mock_sync,
+ patch.object(config, "async_sync_entities_all"),
+ patch.object(ga_helpers, "SYNC_DELAY", 0),
):
# Created entity
entry = entity_registry.async_get_or_create(
diff --git a/tests/components/cloud/test_http_api.py b/tests/components/cloud/test_http_api.py
index 40092997c79..0dad7cfa882 100644
--- a/tests/components/cloud/test_http_api.py
+++ b/tests/components/cloud/test_http_api.py
@@ -749,14 +749,17 @@ async def test_websocket_status(
cloud.iot.state = STATE_CONNECTED
client = await hass_ws_client(hass)
- with patch.dict(
- "homeassistant.components.google_assistant.const.DOMAIN_TO_GOOGLE_TYPES",
- {"light": None},
- clear=True,
- ), patch.dict(
- "homeassistant.components.alexa.entities.ENTITY_ADAPTERS",
- {"switch": None},
- clear=True,
+ with (
+ patch.dict(
+ "homeassistant.components.google_assistant.const.DOMAIN_TO_GOOGLE_TYPES",
+ {"light": None},
+ clear=True,
+ ),
+ patch.dict(
+ "homeassistant.components.alexa.entities.ENTITY_ADAPTERS",
+ {"switch": None},
+ clear=True,
+ ),
):
await client.send_json({"id": 5, "type": "cloud/status"})
response = await client.receive_json()
@@ -954,16 +957,20 @@ async def test_websocket_update_preferences_alexa_report_state(
"""Test updating alexa_report_state sets alexa authorized."""
client = await hass_ws_client(hass)
- with patch(
- "homeassistant.components.cloud.alexa_config.CloudAlexaConfig.async_sync_entities"
- ), patch(
- (
- "homeassistant.components.cloud.alexa_config.CloudAlexaConfig"
- ".async_get_access_token"
+ with (
+ patch(
+ "homeassistant.components.cloud.alexa_config.CloudAlexaConfig.async_sync_entities"
),
- ), patch(
- "homeassistant.components.cloud.alexa_config.CloudAlexaConfig.set_authorized"
- ) as set_authorized_mock:
+ patch(
+ (
+ "homeassistant.components.cloud.alexa_config.CloudAlexaConfig"
+ ".async_get_access_token"
+ ),
+ ),
+ patch(
+ "homeassistant.components.cloud.alexa_config.CloudAlexaConfig.set_authorized"
+ ) as set_authorized_mock,
+ ):
set_authorized_mock.assert_not_called()
await client.send_json(
@@ -985,15 +992,18 @@ async def test_websocket_update_preferences_require_relink(
"""Test updating preference requires relink."""
client = await hass_ws_client(hass)
- with patch(
- (
- "homeassistant.components.cloud.alexa_config.CloudAlexaConfig"
- ".async_get_access_token"
+ with (
+ patch(
+ (
+ "homeassistant.components.cloud.alexa_config.CloudAlexaConfig"
+ ".async_get_access_token"
+ ),
+ side_effect=alexa_errors.RequireRelink,
),
- side_effect=alexa_errors.RequireRelink,
- ), patch(
- "homeassistant.components.cloud.alexa_config.CloudAlexaConfig.set_authorized"
- ) as set_authorized_mock:
+ patch(
+ "homeassistant.components.cloud.alexa_config.CloudAlexaConfig.set_authorized"
+ ) as set_authorized_mock,
+ ):
set_authorized_mock.assert_not_called()
await client.send_json(
@@ -1015,15 +1025,18 @@ async def test_websocket_update_preferences_no_token(
"""Test updating preference no token available."""
client = await hass_ws_client(hass)
- with patch(
- (
- "homeassistant.components.cloud.alexa_config.CloudAlexaConfig"
- ".async_get_access_token"
+ with (
+ patch(
+ (
+ "homeassistant.components.cloud.alexa_config.CloudAlexaConfig"
+ ".async_get_access_token"
+ ),
+ side_effect=alexa_errors.NoTokenAvailable,
),
- side_effect=alexa_errors.NoTokenAvailable,
- ), patch(
- "homeassistant.components.cloud.alexa_config.CloudAlexaConfig.set_authorized"
- ) as set_authorized_mock:
+ patch(
+ "homeassistant.components.cloud.alexa_config.CloudAlexaConfig.set_authorized"
+ ) as set_authorized_mock,
+ ):
set_authorized_mock.assert_not_called()
await client.send_json(
@@ -1357,13 +1370,16 @@ async def test_list_alexa_entities(
"interfaces": ["Alexa.PowerController", "Alexa.EndpointHealth", "Alexa"],
}
- with patch(
- (
- "homeassistant.components.cloud.alexa_config.CloudAlexaConfig"
- ".async_get_access_token"
+ with (
+ patch(
+ (
+ "homeassistant.components.cloud.alexa_config.CloudAlexaConfig"
+ ".async_get_access_token"
+ ),
+ ),
+ patch(
+ "homeassistant.components.cloud.alexa_config.alexa_state_report.async_send_add_or_update_message"
),
- ), patch(
- "homeassistant.components.cloud.alexa_config.alexa_state_report.async_send_add_or_update_message"
):
# Add the entity to the entity registry
entity_registry.async_get_or_create(
diff --git a/tests/components/cloud/test_init.py b/tests/components/cloud/test_init.py
index 9fb8b383501..9cc1324ebc1 100644
--- a/tests/components/cloud/test_init.py
+++ b/tests/components/cloud/test_init.py
@@ -87,8 +87,9 @@ async def test_remote_services(
# Test admin access required
non_admin_context = Context(user_id=hass_read_only_user.id)
- with patch("hass_nabucasa.remote.RemoteUI.connect") as mock_connect, pytest.raises(
- Unauthorized
+ with (
+ patch("hass_nabucasa.remote.RemoteUI.connect") as mock_connect,
+ pytest.raises(Unauthorized),
):
await hass.services.async_call(
DOMAIN, "remote_connect", blocking=True, context=non_admin_context
@@ -96,9 +97,10 @@ async def test_remote_services(
assert mock_connect.called is False
- with patch(
- "hass_nabucasa.remote.RemoteUI.disconnect"
- ) as mock_disconnect, pytest.raises(Unauthorized):
+ with (
+ patch("hass_nabucasa.remote.RemoteUI.disconnect") as mock_disconnect,
+ pytest.raises(Unauthorized),
+ ):
await hass.services.async_call(
DOMAIN, "remote_disconnect", blocking=True, context=non_admin_context
)
diff --git a/tests/components/cloudflare/test_init.py b/tests/components/cloudflare/test_init.py
index e070be749dd..2d66d3c8752 100644
--- a/tests/components/cloudflare/test_init.py
+++ b/tests/components/cloudflare/test_init.py
@@ -125,10 +125,13 @@ async def test_integration_services_with_issue(hass: HomeAssistant, cfupdate) ->
entry = await init_integration(hass)
assert entry.state is ConfigEntryState.LOADED
- with patch(
- "homeassistant.components.cloudflare.async_detect_location_info",
- return_value=None,
- ), pytest.raises(HomeAssistantError, match="Could not get external IPv4 address"):
+ with (
+ patch(
+ "homeassistant.components.cloudflare.async_detect_location_info",
+ return_value=None,
+ ),
+ pytest.raises(HomeAssistantError, match="Could not get external IPv4 address"),
+ ):
await hass.services.async_call(
DOMAIN,
SERVICE_UPDATE_RECORDS,
diff --git a/tests/components/co2signal/conftest.py b/tests/components/co2signal/conftest.py
index bcc22ae3d55..64972e6403f 100644
--- a/tests/components/co2signal/conftest.py
+++ b/tests/components/co2signal/conftest.py
@@ -18,12 +18,15 @@ from tests.components.co2signal import VALID_RESPONSE
def mock_electricity_maps() -> Generator[None, MagicMock, None]:
"""Mock the ElectricityMaps client."""
- with patch(
- "homeassistant.components.co2signal.ElectricityMaps",
- autospec=True,
- ) as electricity_maps, patch(
- "homeassistant.components.co2signal.config_flow.ElectricityMaps",
- new=electricity_maps,
+ with (
+ patch(
+ "homeassistant.components.co2signal.ElectricityMaps",
+ autospec=True,
+ ) as electricity_maps,
+ patch(
+ "homeassistant.components.co2signal.config_flow.ElectricityMaps",
+ new=electricity_maps,
+ ),
):
client = electricity_maps.return_value
client.latest_carbon_intensity_by_coordinates.return_value = VALID_RESPONSE
diff --git a/tests/components/coinbase/test_config_flow.py b/tests/components/coinbase/test_config_flow.py
index 971b6565d00..79b0115bc7c 100644
--- a/tests/components/coinbase/test_config_flow.py
+++ b/tests/components/coinbase/test_config_flow.py
@@ -35,18 +35,21 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "coinbase.wallet.client.Client.get_current_user",
- return_value=mock_get_current_user(),
- ), patch(
- "coinbase.wallet.client.Client.get_accounts", new=mocked_get_accounts
- ), patch(
- "coinbase.wallet.client.Client.get_exchange_rates",
- return_value=mock_get_exchange_rates(),
- ), patch(
- "homeassistant.components.coinbase.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "coinbase.wallet.client.Client.get_current_user",
+ return_value=mock_get_current_user(),
+ ),
+ patch("coinbase.wallet.client.Client.get_accounts", new=mocked_get_accounts),
+ patch(
+ "coinbase.wallet.client.Client.get_exchange_rates",
+ return_value=mock_get_exchange_rates(),
+ ),
+ patch(
+ "homeassistant.components.coinbase.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -190,17 +193,20 @@ async def test_form_catch_all_exception(hass: HomeAssistant) -> None:
async def test_option_form(hass: HomeAssistant) -> None:
"""Test we handle a good wallet currency option."""
- with patch(
- "coinbase.wallet.client.Client.get_current_user",
- return_value=mock_get_current_user(),
- ), patch(
- "coinbase.wallet.client.Client.get_accounts", new=mocked_get_accounts
- ), patch(
- "coinbase.wallet.client.Client.get_exchange_rates",
- return_value=mock_get_exchange_rates(),
- ), patch(
- "homeassistant.components.coinbase.update_listener"
- ) as mock_update_listener:
+ with (
+ patch(
+ "coinbase.wallet.client.Client.get_current_user",
+ return_value=mock_get_current_user(),
+ ),
+ patch("coinbase.wallet.client.Client.get_accounts", new=mocked_get_accounts),
+ patch(
+ "coinbase.wallet.client.Client.get_exchange_rates",
+ return_value=mock_get_exchange_rates(),
+ ),
+ patch(
+ "homeassistant.components.coinbase.update_listener"
+ ) as mock_update_listener,
+ ):
config_entry = await init_mock_coinbase(hass)
await hass.async_block_till_done()
result = await hass.config_entries.options.async_init(config_entry.entry_id)
@@ -220,14 +226,16 @@ async def test_option_form(hass: HomeAssistant) -> None:
async def test_form_bad_account_currency(hass: HomeAssistant) -> None:
"""Test we handle a bad currency option."""
- with patch(
- "coinbase.wallet.client.Client.get_current_user",
- return_value=mock_get_current_user(),
- ), patch(
- "coinbase.wallet.client.Client.get_accounts", new=mocked_get_accounts
- ), patch(
- "coinbase.wallet.client.Client.get_exchange_rates",
- return_value=mock_get_exchange_rates(),
+ with (
+ patch(
+ "coinbase.wallet.client.Client.get_current_user",
+ return_value=mock_get_current_user(),
+ ),
+ patch("coinbase.wallet.client.Client.get_accounts", new=mocked_get_accounts),
+ patch(
+ "coinbase.wallet.client.Client.get_exchange_rates",
+ return_value=mock_get_exchange_rates(),
+ ),
):
config_entry = await init_mock_coinbase(hass)
result = await hass.config_entries.options.async_init(config_entry.entry_id)
@@ -247,14 +255,16 @@ async def test_form_bad_account_currency(hass: HomeAssistant) -> None:
async def test_form_bad_exchange_rate(hass: HomeAssistant) -> None:
"""Test we handle a bad exchange rate."""
- with patch(
- "coinbase.wallet.client.Client.get_current_user",
- return_value=mock_get_current_user(),
- ), patch(
- "coinbase.wallet.client.Client.get_accounts", new=mocked_get_accounts
- ), patch(
- "coinbase.wallet.client.Client.get_exchange_rates",
- return_value=mock_get_exchange_rates(),
+ with (
+ patch(
+ "coinbase.wallet.client.Client.get_current_user",
+ return_value=mock_get_current_user(),
+ ),
+ patch("coinbase.wallet.client.Client.get_accounts", new=mocked_get_accounts),
+ patch(
+ "coinbase.wallet.client.Client.get_exchange_rates",
+ return_value=mock_get_exchange_rates(),
+ ),
):
config_entry = await init_mock_coinbase(hass)
result = await hass.config_entries.options.async_init(config_entry.entry_id)
@@ -273,14 +283,16 @@ async def test_form_bad_exchange_rate(hass: HomeAssistant) -> None:
async def test_option_catch_all_exception(hass: HomeAssistant) -> None:
"""Test we handle an unknown exception in the option flow."""
- with patch(
- "coinbase.wallet.client.Client.get_current_user",
- return_value=mock_get_current_user(),
- ), patch(
- "coinbase.wallet.client.Client.get_accounts", new=mocked_get_accounts
- ), patch(
- "coinbase.wallet.client.Client.get_exchange_rates",
- return_value=mock_get_exchange_rates(),
+ with (
+ patch(
+ "coinbase.wallet.client.Client.get_current_user",
+ return_value=mock_get_current_user(),
+ ),
+ patch("coinbase.wallet.client.Client.get_accounts", new=mocked_get_accounts),
+ patch(
+ "coinbase.wallet.client.Client.get_exchange_rates",
+ return_value=mock_get_exchange_rates(),
+ ),
):
config_entry = await init_mock_coinbase(hass)
result = await hass.config_entries.options.async_init(config_entry.entry_id)
diff --git a/tests/components/coinbase/test_diagnostics.py b/tests/components/coinbase/test_diagnostics.py
index 55454a48352..e30bdef30b8 100644
--- a/tests/components/coinbase/test_diagnostics.py
+++ b/tests/components/coinbase/test_diagnostics.py
@@ -24,14 +24,16 @@ async def test_entry_diagnostics(
) -> None:
"""Test we handle a and redact a diagnostics request."""
- with patch(
- "coinbase.wallet.client.Client.get_current_user",
- return_value=mock_get_current_user(),
- ), patch(
- "coinbase.wallet.client.Client.get_accounts", new=mocked_get_accounts
- ), patch(
- "coinbase.wallet.client.Client.get_exchange_rates",
- return_value=mock_get_exchange_rates(),
+ with (
+ patch(
+ "coinbase.wallet.client.Client.get_current_user",
+ return_value=mock_get_current_user(),
+ ),
+ patch("coinbase.wallet.client.Client.get_accounts", new=mocked_get_accounts),
+ patch(
+ "coinbase.wallet.client.Client.get_exchange_rates",
+ return_value=mock_get_exchange_rates(),
+ ),
):
config_entry = await init_mock_coinbase(hass)
await hass.async_block_till_done()
diff --git a/tests/components/coinbase/test_init.py b/tests/components/coinbase/test_init.py
index a2350654d08..5af762f557a 100644
--- a/tests/components/coinbase/test_init.py
+++ b/tests/components/coinbase/test_init.py
@@ -28,15 +28,19 @@ from .const import (
async def test_unload_entry(hass: HomeAssistant) -> None:
"""Test successful unload of entry."""
- with patch(
- "coinbase.wallet.client.Client.get_current_user",
- return_value=mock_get_current_user(),
- ), patch(
- "coinbase.wallet.client.Client.get_accounts",
- new=mocked_get_accounts,
- ), patch(
- "coinbase.wallet.client.Client.get_exchange_rates",
- return_value=mock_get_exchange_rates(),
+ with (
+ patch(
+ "coinbase.wallet.client.Client.get_current_user",
+ return_value=mock_get_current_user(),
+ ),
+ patch(
+ "coinbase.wallet.client.Client.get_accounts",
+ new=mocked_get_accounts,
+ ),
+ patch(
+ "coinbase.wallet.client.Client.get_exchange_rates",
+ return_value=mock_get_exchange_rates(),
+ ),
):
entry = await init_mock_coinbase(hass)
@@ -55,14 +59,16 @@ async def test_option_updates(
) -> None:
"""Test handling option updates."""
- with patch(
- "coinbase.wallet.client.Client.get_current_user",
- return_value=mock_get_current_user(),
- ), patch(
- "coinbase.wallet.client.Client.get_accounts", new=mocked_get_accounts
- ), patch(
- "coinbase.wallet.client.Client.get_exchange_rates",
- return_value=mock_get_exchange_rates(),
+ with (
+ patch(
+ "coinbase.wallet.client.Client.get_current_user",
+ return_value=mock_get_current_user(),
+ ),
+ patch("coinbase.wallet.client.Client.get_accounts", new=mocked_get_accounts),
+ patch(
+ "coinbase.wallet.client.Client.get_exchange_rates",
+ return_value=mock_get_exchange_rates(),
+ ),
):
config_entry = await init_mock_coinbase(hass)
await hass.async_block_till_done()
@@ -133,14 +139,16 @@ async def test_ignore_vaults_wallets(
) -> None:
"""Test vaults are ignored in wallet sensors."""
- with patch(
- "coinbase.wallet.client.Client.get_current_user",
- return_value=mock_get_current_user(),
- ), patch(
- "coinbase.wallet.client.Client.get_accounts", new=mocked_get_accounts
- ), patch(
- "coinbase.wallet.client.Client.get_exchange_rates",
- return_value=mock_get_exchange_rates(),
+ with (
+ patch(
+ "coinbase.wallet.client.Client.get_current_user",
+ return_value=mock_get_current_user(),
+ ),
+ patch("coinbase.wallet.client.Client.get_accounts", new=mocked_get_accounts),
+ patch(
+ "coinbase.wallet.client.Client.get_exchange_rates",
+ return_value=mock_get_exchange_rates(),
+ ),
):
config_entry = await init_mock_coinbase(hass, currencies=[GOOD_CURRENCY])
await hass.async_block_till_done()
diff --git a/tests/components/comelit/test_config_flow.py b/tests/components/comelit/test_config_flow.py
index dda29aaf922..851e179dd95 100644
--- a/tests/components/comelit/test_config_flow.py
+++ b/tests/components/comelit/test_config_flow.py
@@ -28,11 +28,15 @@ async def test_full_flow(
hass: HomeAssistant, class_api: str, user_input: dict[str, Any]
) -> None:
"""Test starting a flow by user."""
- with patch(
- f"aiocomelit.api.{class_api}.login",
- ), patch(
- f"aiocomelit.api.{class_api}.logout",
- ), patch("homeassistant.components.comelit.async_setup_entry") as mock_setup_entry:
+ with (
+ patch(
+ f"aiocomelit.api.{class_api}.login",
+ ),
+ patch(
+ f"aiocomelit.api.{class_api}.logout",
+ ),
+ patch("homeassistant.components.comelit.async_setup_entry") as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
@@ -69,13 +73,17 @@ async def test_exception_connection(hass: HomeAssistant, side_effect, error) ->
assert result.get("type") == FlowResultType.FORM
assert result.get("step_id") == "user"
- with patch(
- "aiocomelit.api.ComeliteSerialBridgeApi.login",
- side_effect=side_effect,
- ), patch(
- "aiocomelit.api.ComeliteSerialBridgeApi.logout",
- ), patch(
- "homeassistant.components.comelit.async_setup_entry",
+ with (
+ patch(
+ "aiocomelit.api.ComeliteSerialBridgeApi.login",
+ side_effect=side_effect,
+ ),
+ patch(
+ "aiocomelit.api.ComeliteSerialBridgeApi.logout",
+ ),
+ patch(
+ "homeassistant.components.comelit.async_setup_entry",
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_USER_BRIDGE_DATA
@@ -93,13 +101,16 @@ async def test_reauth_successful(hass: HomeAssistant) -> None:
mock_config = MockConfigEntry(domain=DOMAIN, data=MOCK_USER_BRIDGE_DATA)
mock_config.add_to_hass(hass)
- with patch(
- "aiocomelit.api.ComeliteSerialBridgeApi.login",
- ), patch(
- "aiocomelit.api.ComeliteSerialBridgeApi.logout",
- ), patch("homeassistant.components.comelit.async_setup_entry"), patch(
- "requests.get"
- ) as mock_request_get:
+ with (
+ patch(
+ "aiocomelit.api.ComeliteSerialBridgeApi.login",
+ ),
+ patch(
+ "aiocomelit.api.ComeliteSerialBridgeApi.logout",
+ ),
+ patch("homeassistant.components.comelit.async_setup_entry"),
+ patch("requests.get") as mock_request_get,
+ ):
mock_request_get.return_value.status_code = 200
result = await hass.config_entries.flow.async_init(
@@ -137,11 +148,13 @@ async def test_reauth_not_successful(hass: HomeAssistant, side_effect, error) ->
mock_config = MockConfigEntry(domain=DOMAIN, data=MOCK_USER_BRIDGE_DATA)
mock_config.add_to_hass(hass)
- with patch(
- "aiocomelit.api.ComeliteSerialBridgeApi.login", side_effect=side_effect
- ), patch(
- "aiocomelit.api.ComeliteSerialBridgeApi.logout",
- ), patch("homeassistant.components.comelit.async_setup_entry"):
+ with (
+ patch("aiocomelit.api.ComeliteSerialBridgeApi.login", side_effect=side_effect),
+ patch(
+ "aiocomelit.api.ComeliteSerialBridgeApi.logout",
+ ),
+ patch("homeassistant.components.comelit.async_setup_entry"),
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_REAUTH, "entry_id": mock_config.entry_id},
diff --git a/tests/components/config/conftest.py b/tests/components/config/conftest.py
index 2a0552b997f..ffd2f764922 100644
--- a/tests/components/config/conftest.py
+++ b/tests/components/config/conftest.py
@@ -51,18 +51,22 @@ def mock_config_store(data=None):
_LOGGER.info("Reading data from configuration.yaml: %s", result)
return result
- with patch(
- "homeassistant.components.config.view._read",
- side_effect=mock_read,
- autospec=True,
- ), patch(
- "homeassistant.components.config.view._write",
- side_effect=mock_write,
- autospec=True,
- ), patch(
- "homeassistant.config.async_hass_config_yaml",
- side_effect=mock_async_hass_config_yaml,
- autospec=True,
+ with (
+ patch(
+ "homeassistant.components.config.view._read",
+ side_effect=mock_read,
+ autospec=True,
+ ),
+ patch(
+ "homeassistant.components.config.view._write",
+ side_effect=mock_write,
+ autospec=True,
+ ),
+ patch(
+ "homeassistant.config.async_hass_config_yaml",
+ side_effect=mock_async_hass_config_yaml,
+ autospec=True,
+ ),
):
yield data
diff --git a/tests/components/config/test_core.py b/tests/components/config/test_core.py
index 408947be00e..da8a60ca6fd 100644
--- a/tests/components/config/test_core.py
+++ b/tests/components/config/test_core.py
@@ -120,9 +120,12 @@ async def test_websocket_core_update(hass: HomeAssistant, client) -> None:
assert hass.config.country != "SE"
assert hass.config.language != "sv"
- with patch("homeassistant.util.dt.set_default_time_zone") as mock_set_tz, patch(
- "homeassistant.components.config.core.async_update_suggested_units"
- ) as mock_update_sensor_units:
+ with (
+ patch("homeassistant.util.dt.set_default_time_zone") as mock_set_tz,
+ patch(
+ "homeassistant.components.config.core.async_update_suggested_units"
+ ) as mock_update_sensor_units,
+ ):
await client.send_json(
{
"id": 5,
@@ -160,9 +163,12 @@ async def test_websocket_core_update(hass: HomeAssistant, client) -> None:
assert len(mock_set_tz.mock_calls) == 1
assert mock_set_tz.mock_calls[0][1][0] == dt_util.get_time_zone("America/New_York")
- with patch("homeassistant.util.dt.set_default_time_zone") as mock_set_tz, patch(
- "homeassistant.components.config.core.async_update_suggested_units"
- ) as mock_update_sensor_units:
+ with (
+ patch("homeassistant.util.dt.set_default_time_zone") as mock_set_tz,
+ patch(
+ "homeassistant.components.config.core.async_update_suggested_units"
+ ) as mock_update_sensor_units,
+ ):
await client.send_json(
{
"id": 6,
diff --git a/tests/components/control4/test_config_flow.py b/tests/components/control4/test_config_flow.py
index b17a1cd6ea1..8ec6df063e5 100644
--- a/tests/components/control4/test_config_flow.py
+++ b/tests/components/control4/test_config_flow.py
@@ -53,16 +53,20 @@ async def test_form(hass: HomeAssistant) -> None:
c4_account = _get_mock_c4_account()
c4_director = _get_mock_c4_director()
- with patch(
- "homeassistant.components.control4.config_flow.C4Account",
- return_value=c4_account,
- ), patch(
- "homeassistant.components.control4.config_flow.C4Director",
- return_value=c4_director,
- ), patch(
- "homeassistant.components.control4.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.control4.config_flow.C4Account",
+ return_value=c4_account,
+ ),
+ patch(
+ "homeassistant.components.control4.config_flow.C4Director",
+ return_value=c4_director,
+ ),
+ patch(
+ "homeassistant.components.control4.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -136,12 +140,15 @@ async def test_form_cannot_connect(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "homeassistant.components.control4.config_flow.Control4Validator.authenticate",
- return_value=True,
- ), patch(
- "homeassistant.components.control4.config_flow.C4Director",
- side_effect=Unauthorized("message"),
+ with (
+ patch(
+ "homeassistant.components.control4.config_flow.Control4Validator.authenticate",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.control4.config_flow.C4Director",
+ side_effect=Unauthorized("message"),
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/conversation/conftest.py b/tests/components/conversation/conftest.py
index 99794dbea4a..cf6b4567228 100644
--- a/tests/components/conversation/conftest.py
+++ b/tests/components/conversation/conftest.py
@@ -36,8 +36,9 @@ def mock_agent_support_all(hass):
@pytest.fixture(autouse=True)
def mock_shopping_list_io():
"""Stub out the persistence."""
- with patch("homeassistant.components.shopping_list.ShoppingData.save"), patch(
- "homeassistant.components.shopping_list.ShoppingData.async_load"
+ with (
+ patch("homeassistant.components.shopping_list.ShoppingData.save"),
+ patch("homeassistant.components.shopping_list.ShoppingData.async_load"),
):
yield
diff --git a/tests/components/coolmaster/test_config_flow.py b/tests/components/coolmaster/test_config_flow.py
index 6c62ffa482d..ef7828e126d 100644
--- a/tests/components/coolmaster/test_config_flow.py
+++ b/tests/components/coolmaster/test_config_flow.py
@@ -24,13 +24,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] is None
- with patch(
- "homeassistant.components.coolmaster.config_flow.CoolMasterNet.status",
- return_value={"test_id": "test_unit"},
- ), patch(
- "homeassistant.components.coolmaster.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.coolmaster.config_flow.CoolMasterNet.status",
+ return_value={"test_id": "test_unit"},
+ ),
+ patch(
+ "homeassistant.components.coolmaster.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], _flow_data()
)
diff --git a/tests/components/datadog/test_init.py b/tests/components/datadog/test_init.py
index cbf77de3a69..51d698186b7 100644
--- a/tests/components/datadog/test_init.py
+++ b/tests/components/datadog/test_init.py
@@ -23,8 +23,9 @@ async def test_datadog_setup_full(hass: HomeAssistant) -> None:
"""Test setup with all data."""
config = {datadog.DOMAIN: {"host": "host", "port": 123, "rate": 1, "prefix": "foo"}}
- with patch("homeassistant.components.datadog.initialize") as mock_init, patch(
- "homeassistant.components.datadog.statsd"
+ with (
+ patch("homeassistant.components.datadog.initialize") as mock_init,
+ patch("homeassistant.components.datadog.statsd"),
):
assert await async_setup_component(hass, datadog.DOMAIN, config)
@@ -34,8 +35,9 @@ async def test_datadog_setup_full(hass: HomeAssistant) -> None:
async def test_datadog_setup_defaults(hass: HomeAssistant) -> None:
"""Test setup with defaults."""
- with patch("homeassistant.components.datadog.initialize") as mock_init, patch(
- "homeassistant.components.datadog.statsd"
+ with (
+ patch("homeassistant.components.datadog.initialize") as mock_init,
+ patch("homeassistant.components.datadog.statsd"),
):
assert await async_setup_component(
hass,
@@ -55,9 +57,10 @@ async def test_datadog_setup_defaults(hass: HomeAssistant) -> None:
async def test_logbook_entry(hass: HomeAssistant) -> None:
"""Test event listener."""
- with patch("homeassistant.components.datadog.initialize"), patch(
- "homeassistant.components.datadog.statsd"
- ) as mock_statsd:
+ with (
+ patch("homeassistant.components.datadog.initialize"),
+ patch("homeassistant.components.datadog.statsd") as mock_statsd,
+ ):
assert await async_setup_component(
hass,
datadog.DOMAIN,
@@ -85,9 +88,10 @@ async def test_logbook_entry(hass: HomeAssistant) -> None:
async def test_state_changed(hass: HomeAssistant) -> None:
"""Test event listener."""
- with patch("homeassistant.components.datadog.initialize"), patch(
- "homeassistant.components.datadog.statsd"
- ) as mock_statsd:
+ with (
+ patch("homeassistant.components.datadog.initialize"),
+ patch("homeassistant.components.datadog.statsd") as mock_statsd,
+ ):
assert await async_setup_component(
hass,
datadog.DOMAIN,
diff --git a/tests/components/deconz/test_gateway.py b/tests/components/deconz/test_gateway.py
index 447c1406bf4..5a55fb64090 100644
--- a/tests/components/deconz/test_gateway.py
+++ b/tests/components/deconz/test_gateway.py
@@ -305,8 +305,11 @@ async def test_get_deconz_api_fails(
) -> None:
"""Failed call."""
config_entry = MockConfigEntry(domain=DECONZ_DOMAIN, data=ENTRY_CONFIG)
- with patch(
- "pydeconz.DeconzSession.refresh_state",
- side_effect=side_effect,
- ), pytest.raises(raised_exception):
+ with (
+ patch(
+ "pydeconz.DeconzSession.refresh_state",
+ side_effect=side_effect,
+ ),
+ pytest.raises(raised_exception),
+ ):
assert await get_deconz_api(hass, config_entry)
diff --git a/tests/components/deconz/test_init.py b/tests/components/deconz/test_init.py
index 3405a1973c0..0555f70f5e6 100644
--- a/tests/components/deconz/test_init.py
+++ b/tests/components/deconz/test_init.py
@@ -31,8 +31,9 @@ ENTRY2_UUID = "789ACE"
async def setup_entry(hass, entry):
"""Test that setup entry works."""
- with patch.object(DeconzHub, "async_setup", return_value=True), patch.object(
- DeconzHub, "async_update_device_registry", return_value=True
+ with (
+ patch.object(DeconzHub, "async_setup", return_value=True),
+ patch.object(DeconzHub, "async_update_device_registry", return_value=True),
):
assert await async_setup_entry(hass, entry) is True
@@ -61,10 +62,13 @@ async def test_setup_entry_fails_config_entry_not_ready(hass: HomeAssistant) ->
async def test_setup_entry_fails_trigger_reauth_flow(hass: HomeAssistant) -> None:
"""Failed authentication trigger a reauthentication flow."""
- with patch(
- "homeassistant.components.deconz.get_deconz_api",
- side_effect=AuthenticationRequired,
- ), patch.object(hass.config_entries.flow, "async_init") as mock_flow_init:
+ with (
+ patch(
+ "homeassistant.components.deconz.get_deconz_api",
+ side_effect=AuthenticationRequired,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_flow_init,
+ ):
await setup_deconz_integration(hass)
mock_flow_init.assert_called_once()
diff --git a/tests/components/default_config/test_init.py b/tests/components/default_config/test_init.py
index b9ce596465e..222b2b14673 100644
--- a/tests/components/default_config/test_init.py
+++ b/tests/components/default_config/test_init.py
@@ -18,9 +18,11 @@ def stub_blueprint_populate_autouse(stub_blueprint_populate: None) -> None:
@pytest.fixture(autouse=True)
def mock_ssdp():
"""Mock ssdp."""
- with patch("homeassistant.components.ssdp.Scanner.async_scan"), patch(
- "homeassistant.components.ssdp.Server.async_start"
- ), patch("homeassistant.components.ssdp.Server.async_stop"):
+ with (
+ patch("homeassistant.components.ssdp.Scanner.async_scan"),
+ patch("homeassistant.components.ssdp.Server.async_start"),
+ patch("homeassistant.components.ssdp.Server.async_stop"),
+ ):
yield
diff --git a/tests/components/deluge/test_config_flow.py b/tests/components/deluge/test_config_flow.py
index 6cbde04b8bd..1e7cecd8850 100644
--- a/tests/components/deluge/test_config_flow.py
+++ b/tests/components/deluge/test_config_flow.py
@@ -18,8 +18,9 @@ from tests.common import MockConfigEntry
@pytest.fixture(name="api")
def mock_deluge_api():
"""Mock an api."""
- with patch("deluge_client.client.DelugeRPCClient.connect"), patch(
- "deluge_client.client.DelugeRPCClient._create_socket"
+ with (
+ patch("deluge_client.client.DelugeRPCClient.connect"),
+ patch("deluge_client.client.DelugeRPCClient._create_socket"),
):
yield
@@ -27,19 +28,23 @@ def mock_deluge_api():
@pytest.fixture(name="conn_error")
def mock_api_connection_error():
"""Mock an api."""
- with patch(
- "deluge_client.client.DelugeRPCClient.connect",
- side_effect=ConnectionRefusedError("111: Connection refused"),
- ), patch("deluge_client.client.DelugeRPCClient._create_socket"):
+ with (
+ patch(
+ "deluge_client.client.DelugeRPCClient.connect",
+ side_effect=ConnectionRefusedError("111: Connection refused"),
+ ),
+ patch("deluge_client.client.DelugeRPCClient._create_socket"),
+ ):
yield
@pytest.fixture(name="unknown_error")
def mock_api_unknown_error():
"""Mock an api."""
- with patch(
- "deluge_client.client.DelugeRPCClient.connect", side_effect=Exception
- ), patch("deluge_client.client.DelugeRPCClient._create_socket"):
+ with (
+ patch("deluge_client.client.DelugeRPCClient.connect", side_effect=Exception),
+ patch("deluge_client.client.DelugeRPCClient._create_socket"),
+ ):
yield
diff --git a/tests/components/demo/test_update.py b/tests/components/demo/test_update.py
index c8f46ff1b41..d8af9c21c75 100644
--- a/tests/components/demo/test_update.py
+++ b/tests/components/demo/test_update.py
@@ -174,10 +174,13 @@ async def test_update_with_progress_raising(hass: HomeAssistant) -> None:
callback(lambda event: events.append(event)),
)
- with patch(
- "homeassistant.components.demo.update._fake_install",
- side_effect=[None, None, None, None, RuntimeError],
- ) as fake_sleep, pytest.raises(RuntimeError):
+ with (
+ patch(
+ "homeassistant.components.demo.update._fake_install",
+ side_effect=[None, None, None, None, RuntimeError],
+ ) as fake_sleep,
+ pytest.raises(RuntimeError),
+ ):
await hass.services.async_call(
DOMAIN,
SERVICE_INSTALL,
diff --git a/tests/components/denonavr/test_config_flow.py b/tests/components/denonavr/test_config_flow.py
index bcadade5eb5..5f5a5c8f17c 100644
--- a/tests/components/denonavr/test_config_flow.py
+++ b/tests/components/denonavr/test_config_flow.py
@@ -41,33 +41,43 @@ TEST_DISCOVER_2_RECEIVER = [{CONF_HOST: TEST_HOST}, {CONF_HOST: TEST_HOST2}]
@pytest.fixture(name="denonavr_connect", autouse=True)
def denonavr_connect_fixture():
"""Mock denonavr connection and entry setup."""
- with patch(
- "homeassistant.components.denonavr.receiver.DenonAVR.async_setup",
- return_value=None,
- ), patch(
- "homeassistant.components.denonavr.receiver.DenonAVR.async_update",
- return_value=None,
- ), patch(
- "homeassistant.components.denonavr.receiver.DenonAVR.support_sound_mode",
- return_value=True,
- ), patch(
- "homeassistant.components.denonavr.receiver.DenonAVR.name",
- TEST_NAME,
- ), patch(
- "homeassistant.components.denonavr.receiver.DenonAVR.model_name",
- TEST_MODEL,
- ), patch(
- "homeassistant.components.denonavr.receiver.DenonAVR.serial_number",
- TEST_SERIALNUMBER,
- ), patch(
- "homeassistant.components.denonavr.receiver.DenonAVR.manufacturer",
- TEST_MANUFACTURER,
- ), patch(
- "homeassistant.components.denonavr.receiver.DenonAVR.receiver_type",
- TEST_RECEIVER_TYPE,
- ), patch(
- "homeassistant.components.denonavr.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.denonavr.receiver.DenonAVR.async_setup",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.denonavr.receiver.DenonAVR.async_update",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.denonavr.receiver.DenonAVR.support_sound_mode",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.denonavr.receiver.DenonAVR.name",
+ TEST_NAME,
+ ),
+ patch(
+ "homeassistant.components.denonavr.receiver.DenonAVR.model_name",
+ TEST_MODEL,
+ ),
+ patch(
+ "homeassistant.components.denonavr.receiver.DenonAVR.serial_number",
+ TEST_SERIALNUMBER,
+ ),
+ patch(
+ "homeassistant.components.denonavr.receiver.DenonAVR.manufacturer",
+ TEST_MANUFACTURER,
+ ),
+ patch(
+ "homeassistant.components.denonavr.receiver.DenonAVR.receiver_type",
+ TEST_RECEIVER_TYPE,
+ ),
+ patch(
+ "homeassistant.components.denonavr.async_setup_entry",
+ return_value=True,
+ ),
):
yield
@@ -252,12 +262,15 @@ async def test_config_flow_manual_host_connection_error(hass: HomeAssistant) ->
assert result["step_id"] == "user"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.denonavr.receiver.DenonAVR.async_setup",
- side_effect=AvrTimoutError("Timeout", "async_setup"),
- ), patch(
- "homeassistant.components.denonavr.receiver.DenonAVR.receiver_type",
- None,
+ with (
+ patch(
+ "homeassistant.components.denonavr.receiver.DenonAVR.async_setup",
+ side_effect=AvrTimoutError("Timeout", "async_setup"),
+ ),
+ patch(
+ "homeassistant.components.denonavr.receiver.DenonAVR.receiver_type",
+ None,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/denonavr/test_media_player.py b/tests/components/denonavr/test_media_player.py
index 8836e78ad5a..c294c449518 100644
--- a/tests/components/denonavr/test_media_player.py
+++ b/tests/components/denonavr/test_media_player.py
@@ -41,11 +41,12 @@ ENTITY_ID = f"{media_player.DOMAIN}.{TEST_NAME}"
@pytest.fixture(name="client")
def client_fixture():
"""Patch of client library for tests."""
- with patch(
- "homeassistant.components.denonavr.receiver.DenonAVR",
- autospec=True,
- ) as mock_client_class, patch(
- "homeassistant.components.denonavr.config_flow.denonavr.async_discover"
+ with (
+ patch(
+ "homeassistant.components.denonavr.receiver.DenonAVR",
+ autospec=True,
+ ) as mock_client_class,
+ patch("homeassistant.components.denonavr.config_flow.denonavr.async_discover"),
):
mock_client_class.return_value.name = TEST_NAME
mock_client_class.return_value.model_name = TEST_MODEL
diff --git a/tests/components/device_automation/test_init.py b/tests/components/device_automation/test_init.py
index 7de8c5c9adc..1a4488e43cd 100644
--- a/tests/components/device_automation/test_init.py
+++ b/tests/components/device_automation/test_init.py
@@ -1727,10 +1727,13 @@ async def test_async_get_device_automations_platform_reraises_exceptions(
) -> None:
"""Test InvalidDeviceAutomationConfig is raised when async_get_integration_with_requirements fails."""
await async_setup_component(hass, "device_automation", {})
- with patch(
- "homeassistant.components.device_automation.async_get_integration_with_requirements",
- side_effect=exc,
- ), pytest.raises(InvalidDeviceAutomationConfig):
+ with (
+ patch(
+ "homeassistant.components.device_automation.async_get_integration_with_requirements",
+ side_effect=exc,
+ ),
+ pytest.raises(InvalidDeviceAutomationConfig),
+ ):
await device_automation.async_get_device_automation_platform(
hass, "test", device_automation.DeviceAutomationType.TRIGGER
)
diff --git a/tests/components/device_tracker/test_init.py b/tests/components/device_tracker/test_init.py
index 188b581de40..3b95fc9582c 100644
--- a/tests/components/device_tracker/test_init.py
+++ b/tests/components/device_tracker/test_init.py
@@ -292,10 +292,13 @@ async def test_update_stale(
register_time = datetime(now.year + 1, 9, 15, 23, tzinfo=dt_util.UTC)
scan_time = datetime(now.year + 1, 9, 15, 23, 1, tzinfo=dt_util.UTC)
- with patch(
- "homeassistant.components.device_tracker.legacy.dt_util.utcnow",
- return_value=register_time,
- ), assert_setup_component(1, device_tracker.DOMAIN):
+ with (
+ patch(
+ "homeassistant.components.device_tracker.legacy.dt_util.utcnow",
+ return_value=register_time,
+ ),
+ assert_setup_component(1, device_tracker.DOMAIN),
+ ):
assert await async_setup_component(
hass,
device_tracker.DOMAIN,
@@ -548,10 +551,13 @@ async def test_see_passive_zone_state(
scanner.reset()
scanner.come_home("dev1")
- with patch(
- "homeassistant.components.device_tracker.legacy.dt_util.utcnow",
- return_value=register_time,
- ), assert_setup_component(1, device_tracker.DOMAIN):
+ with (
+ patch(
+ "homeassistant.components.device_tracker.legacy.dt_util.utcnow",
+ return_value=register_time,
+ ),
+ assert_setup_component(1, device_tracker.DOMAIN),
+ ):
assert await async_setup_component(
hass,
device_tracker.DOMAIN,
diff --git a/tests/components/device_tracker/test_legacy.py b/tests/components/device_tracker/test_legacy.py
index e22aa54b45c..dba069c410b 100644
--- a/tests/components/device_tracker/test_legacy.py
+++ b/tests/components/device_tracker/test_legacy.py
@@ -30,8 +30,9 @@ def test_remove_device_from_config(hass: HomeAssistant):
mopen = mock_open()
files = {legacy.YAML_DEVICES: dump(yaml_devices)}
- with patch_yaml_files(files, True), patch(
- "homeassistant.components.device_tracker.legacy.open", mopen
+ with (
+ patch_yaml_files(files, True),
+ patch("homeassistant.components.device_tracker.legacy.open", mopen),
):
legacy.remove_device_from_config(hass, "test")
diff --git a/tests/components/devolo_home_control/conftest.py b/tests/components/devolo_home_control/conftest.py
index 786652c7753..6ce9b73ff83 100644
--- a/tests/components/devolo_home_control/conftest.py
+++ b/tests/components/devolo_home_control/conftest.py
@@ -23,15 +23,19 @@ def patch_mydevolo(
credentials_valid: bool, maintenance: bool
) -> Generator[None, None, None]:
"""Fixture to patch mydevolo into a desired state."""
- with patch(
- "homeassistant.components.devolo_home_control.Mydevolo.credentials_valid",
- return_value=credentials_valid,
- ), patch(
- "homeassistant.components.devolo_home_control.Mydevolo.maintenance",
- return_value=maintenance,
- ), patch(
- "homeassistant.components.devolo_home_control.Mydevolo.get_gateway_ids",
- return_value=["1400000000000001", "1400000000000002"],
+ with (
+ patch(
+ "homeassistant.components.devolo_home_control.Mydevolo.credentials_valid",
+ return_value=credentials_valid,
+ ),
+ patch(
+ "homeassistant.components.devolo_home_control.Mydevolo.maintenance",
+ return_value=maintenance,
+ ),
+ patch(
+ "homeassistant.components.devolo_home_control.Mydevolo.get_gateway_ids",
+ return_value=["1400000000000001", "1400000000000002"],
+ ),
):
yield
diff --git a/tests/components/devolo_home_control/test_config_flow.py b/tests/components/devolo_home_control/test_config_flow.py
index 3ace53bfc3b..1aa8e7f829d 100644
--- a/tests/components/devolo_home_control/test_config_flow.py
+++ b/tests/components/devolo_home_control/test_config_flow.py
@@ -75,12 +75,15 @@ async def test_form_advanced_options(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.devolo_home_control.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.devolo_home_control.Mydevolo.uuid",
- return_value="123456",
+ with (
+ patch(
+ "homeassistant.components.devolo_home_control.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.devolo_home_control.Mydevolo.uuid",
+ return_value="123456",
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -179,12 +182,15 @@ async def test_form_reauth(hass: HomeAssistant) -> None:
assert result["step_id"] == "reauth_confirm"
assert result["type"] == FlowResultType.FORM
- with patch(
- "homeassistant.components.devolo_home_control.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.devolo_home_control.Mydevolo.uuid",
- return_value="123456",
+ with (
+ patch(
+ "homeassistant.components.devolo_home_control.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.devolo_home_control.Mydevolo.uuid",
+ return_value="123456",
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -242,12 +248,15 @@ async def test_form_uuid_change_reauth(hass: HomeAssistant) -> None:
assert result["step_id"] == "reauth_confirm"
assert result["type"] == FlowResultType.FORM
- with patch(
- "homeassistant.components.devolo_home_control.async_setup_entry",
- return_value=True,
- ), patch(
- "homeassistant.components.devolo_home_control.Mydevolo.uuid",
- return_value="789123",
+ with (
+ patch(
+ "homeassistant.components.devolo_home_control.async_setup_entry",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.devolo_home_control.Mydevolo.uuid",
+ return_value="789123",
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -261,12 +270,15 @@ async def test_form_uuid_change_reauth(hass: HomeAssistant) -> None:
async def _setup(hass: HomeAssistant, result: FlowResult) -> None:
"""Finish configuration steps."""
- with patch(
- "homeassistant.components.devolo_home_control.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.devolo_home_control.Mydevolo.uuid",
- return_value="123456",
+ with (
+ patch(
+ "homeassistant.components.devolo_home_control.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.devolo_home_control.Mydevolo.uuid",
+ return_value="123456",
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/devolo_home_network/test_init.py b/tests/components/devolo_home_network/test_init.py
index 60dfbe4596f..c4a02f9e375 100644
--- a/tests/components/devolo_home_network/test_init.py
+++ b/tests/components/devolo_home_network/test_init.py
@@ -53,10 +53,13 @@ async def test_setup_without_password(hass: HomeAssistant) -> None:
}
entry = MockConfigEntry(domain=DOMAIN, data=config)
entry.add_to_hass(hass)
- with patch(
- "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup",
- return_value=True,
- ), patch("homeassistant.core.EventBus.async_listen_once"):
+ with (
+ patch(
+ "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup",
+ return_value=True,
+ ),
+ patch("homeassistant.core.EventBus.async_listen_once"),
+ ):
assert await hass.config_entries.async_setup(entry.entry_id)
assert entry.state is ConfigEntryState.LOADED
diff --git a/tests/components/dexcom/__init__.py b/tests/components/dexcom/__init__.py
index acf03725d32..e9ca303765b 100644
--- a/tests/components/dexcom/__init__.py
+++ b/tests/components/dexcom/__init__.py
@@ -28,12 +28,15 @@ async def init_integration(hass) -> MockConfigEntry:
data=CONFIG,
options=None,
)
- with patch(
- "homeassistant.components.dexcom.Dexcom.get_current_glucose_reading",
- return_value=GLUCOSE_READING,
- ), patch(
- "homeassistant.components.dexcom.Dexcom.create_session",
- return_value="test_session_id",
+ with (
+ patch(
+ "homeassistant.components.dexcom.Dexcom.get_current_glucose_reading",
+ return_value=GLUCOSE_READING,
+ ),
+ patch(
+ "homeassistant.components.dexcom.Dexcom.create_session",
+ return_value="test_session_id",
+ ),
):
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
diff --git a/tests/components/dexcom/test_config_flow.py b/tests/components/dexcom/test_config_flow.py
index 802df9513d3..f87f365a7e6 100644
--- a/tests/components/dexcom/test_config_flow.py
+++ b/tests/components/dexcom/test_config_flow.py
@@ -23,13 +23,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.dexcom.config_flow.Dexcom.create_session",
- return_value="test_session_id",
- ), patch(
- "homeassistant.components.dexcom.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.dexcom.config_flow.Dexcom.create_session",
+ return_value="test_session_id",
+ ),
+ patch(
+ "homeassistant.components.dexcom.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
CONFIG,
diff --git a/tests/components/dexcom/test_sensor.py b/tests/components/dexcom/test_sensor.py
index e79cd0f4e01..1b7f0b026ab 100644
--- a/tests/components/dexcom/test_sensor.py
+++ b/tests/components/dexcom/test_sensor.py
@@ -69,12 +69,15 @@ async def test_sensors_options_changed(hass: HomeAssistant) -> None:
test_username_glucose_trend = hass.states.get("sensor.test_username_glucose_trend")
assert test_username_glucose_trend.state == GLUCOSE_READING.trend_description
- with patch(
- "homeassistant.components.dexcom.Dexcom.get_current_glucose_reading",
- return_value=GLUCOSE_READING,
- ), patch(
- "homeassistant.components.dexcom.Dexcom.create_session",
- return_value="test_session_id",
+ with (
+ patch(
+ "homeassistant.components.dexcom.Dexcom.get_current_glucose_reading",
+ return_value=GLUCOSE_READING,
+ ),
+ patch(
+ "homeassistant.components.dexcom.Dexcom.create_session",
+ return_value="test_session_id",
+ ),
):
hass.config_entries.async_update_entry(
entry=entry,
diff --git a/tests/components/dhcp/test_init.py b/tests/components/dhcp/test_init.py
index 2ba651307ed..7c652c8ea3e 100644
--- a/tests/components/dhcp/test_init.py
+++ b/tests/components/dhcp/test_init.py
@@ -535,11 +535,13 @@ async def test_setup_and_stop(hass: HomeAssistant) -> None:
)
await hass.async_block_till_done()
- with patch.object(
- interfaces,
- "resolve_iface",
- ) as resolve_iface_call, patch("scapy.arch.common.compile_filter"), patch(
- "homeassistant.components.dhcp.DiscoverHosts.async_discover"
+ with (
+ patch.object(
+ interfaces,
+ "resolve_iface",
+ ) as resolve_iface_call,
+ patch("scapy.arch.common.compile_filter"),
+ patch("homeassistant.components.dhcp.DiscoverHosts.async_discover"),
):
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
@@ -564,11 +566,15 @@ async def test_setup_fails_as_root(
wait_event = threading.Event()
- with patch("os.geteuid", return_value=0), patch.object(
- interfaces,
- "resolve_iface",
- side_effect=Scapy_Exception,
- ), patch("homeassistant.components.dhcp.DiscoverHosts.async_discover"):
+ with (
+ patch("os.geteuid", return_value=0),
+ patch.object(
+ interfaces,
+ "resolve_iface",
+ side_effect=Scapy_Exception,
+ ),
+ patch("homeassistant.components.dhcp.DiscoverHosts.async_discover"),
+ ):
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
@@ -590,13 +596,16 @@ async def test_setup_fails_non_root(
)
await hass.async_block_till_done()
- with patch("os.geteuid", return_value=10), patch(
- "scapy.arch.common.compile_filter"
- ), patch.object(
- interfaces,
- "resolve_iface",
- side_effect=Scapy_Exception,
- ), patch("homeassistant.components.dhcp.DiscoverHosts.async_discover"):
+ with (
+ patch("os.geteuid", return_value=10),
+ patch("scapy.arch.common.compile_filter"),
+ patch.object(
+ interfaces,
+ "resolve_iface",
+ side_effect=Scapy_Exception,
+ ),
+ patch("homeassistant.components.dhcp.DiscoverHosts.async_discover"),
+ ):
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
@@ -617,14 +626,16 @@ async def test_setup_fails_with_broken_libpcap(
)
await hass.async_block_till_done()
- with patch(
- "scapy.arch.common.compile_filter",
- side_effect=ImportError,
- ) as compile_filter, patch.object(
- interfaces,
- "resolve_iface",
- ) as resolve_iface_call, patch(
- "homeassistant.components.dhcp.DiscoverHosts.async_discover"
+ with (
+ patch(
+ "scapy.arch.common.compile_filter",
+ side_effect=ImportError,
+ ) as compile_filter,
+ patch.object(
+ interfaces,
+ "resolve_iface",
+ ) as resolve_iface_call,
+ patch("homeassistant.components.dhcp.DiscoverHosts.async_discover"),
):
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
@@ -967,15 +978,18 @@ async def test_device_tracker_ignore_self_assigned_ips_before_start(
async def test_aiodiscover_finds_new_hosts(hass: HomeAssistant) -> None:
"""Test aiodiscover finds new host."""
- with patch.object(hass.config_entries.flow, "async_init") as mock_init, patch(
- "homeassistant.components.dhcp.DiscoverHosts.async_discover",
- return_value=[
- {
- dhcp.DISCOVERY_IP_ADDRESS: "192.168.210.56",
- dhcp.DISCOVERY_HOSTNAME: "connect",
- dhcp.DISCOVERY_MAC_ADDRESS: "b8b7f16db533",
- }
- ],
+ with (
+ patch.object(hass.config_entries.flow, "async_init") as mock_init,
+ patch(
+ "homeassistant.components.dhcp.DiscoverHosts.async_discover",
+ return_value=[
+ {
+ dhcp.DISCOVERY_IP_ADDRESS: "192.168.210.56",
+ dhcp.DISCOVERY_HOSTNAME: "connect",
+ dhcp.DISCOVERY_MAC_ADDRESS: "b8b7f16db533",
+ }
+ ],
+ ),
):
device_tracker_watcher = dhcp.NetworkWatcher(
hass,
@@ -1016,25 +1030,28 @@ async def test_aiodiscover_does_not_call_again_on_shorter_hostname(
additional discovery where the hostname is longer and then
reject shorter ones.
"""
- with patch.object(hass.config_entries.flow, "async_init") as mock_init, patch(
- "homeassistant.components.dhcp.DiscoverHosts.async_discover",
- return_value=[
- {
- dhcp.DISCOVERY_IP_ADDRESS: "192.168.210.56",
- dhcp.DISCOVERY_HOSTNAME: "irobot-abc",
- dhcp.DISCOVERY_MAC_ADDRESS: "b8b7f16db533",
- },
- {
- dhcp.DISCOVERY_IP_ADDRESS: "192.168.210.56",
- dhcp.DISCOVERY_HOSTNAME: "irobot-abcdef",
- dhcp.DISCOVERY_MAC_ADDRESS: "b8b7f16db533",
- },
- {
- dhcp.DISCOVERY_IP_ADDRESS: "192.168.210.56",
- dhcp.DISCOVERY_HOSTNAME: "irobot-abc",
- dhcp.DISCOVERY_MAC_ADDRESS: "b8b7f16db533",
- },
- ],
+ with (
+ patch.object(hass.config_entries.flow, "async_init") as mock_init,
+ patch(
+ "homeassistant.components.dhcp.DiscoverHosts.async_discover",
+ return_value=[
+ {
+ dhcp.DISCOVERY_IP_ADDRESS: "192.168.210.56",
+ dhcp.DISCOVERY_HOSTNAME: "irobot-abc",
+ dhcp.DISCOVERY_MAC_ADDRESS: "b8b7f16db533",
+ },
+ {
+ dhcp.DISCOVERY_IP_ADDRESS: "192.168.210.56",
+ dhcp.DISCOVERY_HOSTNAME: "irobot-abcdef",
+ dhcp.DISCOVERY_MAC_ADDRESS: "b8b7f16db533",
+ },
+ {
+ dhcp.DISCOVERY_IP_ADDRESS: "192.168.210.56",
+ dhcp.DISCOVERY_HOSTNAME: "irobot-abc",
+ dhcp.DISCOVERY_MAC_ADDRESS: "b8b7f16db533",
+ },
+ ],
+ ),
):
device_tracker_watcher = dhcp.NetworkWatcher(
hass,
@@ -1077,9 +1094,12 @@ async def test_aiodiscover_does_not_call_again_on_shorter_hostname(
async def test_aiodiscover_finds_new_hosts_after_interval(hass: HomeAssistant) -> None:
"""Test aiodiscover finds new host after interval."""
- with patch.object(hass.config_entries.flow, "async_init") as mock_init, patch(
- "homeassistant.components.dhcp.DiscoverHosts.async_discover",
- return_value=[],
+ with (
+ patch.object(hass.config_entries.flow, "async_init") as mock_init,
+ patch(
+ "homeassistant.components.dhcp.DiscoverHosts.async_discover",
+ return_value=[],
+ ),
):
device_tracker_watcher = dhcp.NetworkWatcher(
hass,
@@ -1099,15 +1119,18 @@ async def test_aiodiscover_finds_new_hosts_after_interval(hass: HomeAssistant) -
assert len(mock_init.mock_calls) == 0
- with patch.object(hass.config_entries.flow, "async_init") as mock_init, patch(
- "homeassistant.components.dhcp.DiscoverHosts.async_discover",
- return_value=[
- {
- dhcp.DISCOVERY_IP_ADDRESS: "192.168.210.56",
- dhcp.DISCOVERY_HOSTNAME: "connect",
- dhcp.DISCOVERY_MAC_ADDRESS: "b8b7f16db533",
- }
- ],
+ with (
+ patch.object(hass.config_entries.flow, "async_init") as mock_init,
+ patch(
+ "homeassistant.components.dhcp.DiscoverHosts.async_discover",
+ return_value=[
+ {
+ dhcp.DISCOVERY_IP_ADDRESS: "192.168.210.56",
+ dhcp.DISCOVERY_HOSTNAME: "connect",
+ dhcp.DISCOVERY_MAC_ADDRESS: "b8b7f16db533",
+ }
+ ],
+ ),
):
async_fire_time_changed(hass, dt_util.utcnow() + datetime.timedelta(minutes=65))
await hass.async_block_till_done()
diff --git a/tests/components/discovergy/conftest.py b/tests/components/discovergy/conftest.py
index 2cf59adca04..d3ab3b831f0 100644
--- a/tests/components/discovergy/conftest.py
+++ b/tests/components/discovergy/conftest.py
@@ -27,12 +27,15 @@ def _meter_last_reading(meter_id: str) -> Reading:
@pytest.fixture(name="discovergy")
def mock_discovergy() -> Generator[AsyncMock, None, None]:
"""Mock the pydiscovergy client."""
- with patch(
- "homeassistant.components.discovergy.Discovergy",
- autospec=True,
- ) as mock_discovergy, patch(
- "homeassistant.components.discovergy.config_flow.Discovergy",
- new=mock_discovergy,
+ with (
+ patch(
+ "homeassistant.components.discovergy.Discovergy",
+ autospec=True,
+ ) as mock_discovergy,
+ patch(
+ "homeassistant.components.discovergy.config_flow.Discovergy",
+ new=mock_discovergy,
+ ),
):
mock = mock_discovergy.return_value
mock.meters.return_value = GET_METERS
diff --git a/tests/components/dlna_dmr/test_config_flow.py b/tests/components/dlna_dmr/test_config_flow.py
index 912b105bb58..32cfd8ad5a9 100644
--- a/tests/components/dlna_dmr/test_config_flow.py
+++ b/tests/components/dlna_dmr/test_config_flow.py
@@ -587,9 +587,9 @@ async def test_ssdp_ignore_device(hass: HomeAssistant) -> None:
discovery = dataclasses.replace(MOCK_DISCOVERY)
discovery.upnp = dict(discovery.upnp)
- discovery.upnp[
- ssdp.ATTR_UPNP_DEVICE_TYPE
- ] = "urn:schemas-upnp-org:device:ZonePlayer:1"
+ discovery.upnp[ssdp.ATTR_UPNP_DEVICE_TYPE] = (
+ "urn:schemas-upnp-org:device:ZonePlayer:1"
+ )
result = await hass.config_entries.flow.async_init(
DLNA_DOMAIN,
context={"source": config_entries.SOURCE_SSDP},
diff --git a/tests/components/dnsip/test_config_flow.py b/tests/components/dnsip/test_config_flow.py
index eb254908dd3..5bfa1539d44 100644
--- a/tests/components/dnsip/test_config_flow.py
+++ b/tests/components/dnsip/test_config_flow.py
@@ -36,13 +36,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["data_schema"] == DATA_SCHEMA
assert result["errors"] == {}
- with patch(
- "homeassistant.components.dnsip.config_flow.aiodns.DNSResolver",
- return_value=RetrieveDNS(),
- ), patch(
- "homeassistant.components.dnsip.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.dnsip.config_flow.aiodns.DNSResolver",
+ return_value=RetrieveDNS(),
+ ),
+ patch(
+ "homeassistant.components.dnsip.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -76,13 +79,16 @@ async def test_form_adv(hass: HomeAssistant) -> None:
assert result["data_schema"] == DATA_SCHEMA_ADV
- with patch(
- "homeassistant.components.dnsip.config_flow.aiodns.DNSResolver",
- return_value=RetrieveDNS(),
- ), patch(
- "homeassistant.components.dnsip.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.dnsip.config_flow.aiodns.DNSResolver",
+ return_value=RetrieveDNS(),
+ ),
+ patch(
+ "homeassistant.components.dnsip.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -154,12 +160,15 @@ async def test_flow_already_exist(hass: HomeAssistant) -> None:
)
dns_mock = RetrieveDNS()
- with patch(
- "homeassistant.components.dnsip.async_setup_entry",
- return_value=True,
- ), patch(
- "homeassistant.components.dnsip.config_flow.aiodns.DNSResolver",
- return_value=dns_mock,
+ with (
+ patch(
+ "homeassistant.components.dnsip.async_setup_entry",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.dnsip.config_flow.aiodns.DNSResolver",
+ return_value=dns_mock,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/doorbird/test_config_flow.py b/tests/components/doorbird/test_config_flow.py
index 7df281481ad..4939bada6f8 100644
--- a/tests/components/doorbird/test_config_flow.py
+++ b/tests/components/doorbird/test_config_flow.py
@@ -52,15 +52,19 @@ async def test_user_form(hass: HomeAssistant) -> None:
doorbirdapi = _get_mock_doorbirdapi_return_values(
ready=[True], info={"WIFI_MAC_ADDR": "macaddr"}
)
- with patch(
- "homeassistant.components.doorbird.config_flow.DoorBird",
- return_value=doorbirdapi,
- ), patch(
- "homeassistant.components.doorbird.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.doorbird.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.doorbird.config_flow.DoorBird",
+ return_value=doorbirdapi,
+ ),
+ patch(
+ "homeassistant.components.doorbird.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.doorbird.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
VALID_CONFIG,
@@ -195,15 +199,20 @@ async def test_form_zeroconf_correct_oui(hass: HomeAssistant) -> None:
assert result["step_id"] == "user"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.doorbird.config_flow.DoorBird",
- return_value=doorbirdapi,
- ), patch("homeassistant.components.logbook.async_setup", return_value=True), patch(
- "homeassistant.components.doorbird.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.doorbird.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.doorbird.config_flow.DoorBird",
+ return_value=doorbirdapi,
+ ),
+ patch("homeassistant.components.logbook.async_setup", return_value=True),
+ patch(
+ "homeassistant.components.doorbird.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.doorbird.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], VALID_CONFIG
)
diff --git a/tests/components/dormakaba_dkey/test_config_flow.py b/tests/components/dormakaba_dkey/test_config_flow.py
index bcb13cd788e..d29e176bb7e 100644
--- a/tests/components/dormakaba_dkey/test_config_flow.py
+++ b/tests/components/dormakaba_dkey/test_config_flow.py
@@ -165,13 +165,16 @@ async def test_bluetooth_step_success(hass: HomeAssistant) -> None:
async def _test_common_success(hass: HomeAssistant, result: FlowResult) -> None:
"""Test bluetooth and user flow success paths."""
- with patch(
- "homeassistant.components.dormakaba_dkey.config_flow.DKEYLock.associate",
- return_value=AssociationData(b"1234", b"AABBCCDD"),
- ) as mock_associate, patch(
- "homeassistant.components.dormakaba_dkey.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.dormakaba_dkey.config_flow.DKEYLock.associate",
+ return_value=AssociationData(b"1234", b"AABBCCDD"),
+ ) as mock_associate,
+ patch(
+ "homeassistant.components.dormakaba_dkey.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"activation_code": "1234-1234"}
)
@@ -343,12 +346,15 @@ async def test_reauth(hass: HomeAssistant) -> None:
assert result["step_id"] == "associate"
assert result["errors"] is None
- with patch(
- "homeassistant.components.dormakaba_dkey.config_flow.DKEYLock.associate",
- return_value=AssociationData(b"1234", b"AABBCCDD"),
- ) as mock_associate, patch(
- "homeassistant.components.dormakaba_dkey.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.dormakaba_dkey.config_flow.DKEYLock.associate",
+ return_value=AssociationData(b"1234", b"AABBCCDD"),
+ ) as mock_associate,
+ patch(
+ "homeassistant.components.dormakaba_dkey.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"activation_code": "1234-1234"}
diff --git a/tests/components/downloader/test_config_flow.py b/tests/components/downloader/test_config_flow.py
index 53c1be69830..5e75a9b33ba 100644
--- a/tests/components/downloader/test_config_flow.py
+++ b/tests/components/downloader/test_config_flow.py
@@ -40,11 +40,14 @@ async def test_user_form(hass: HomeAssistant) -> None:
assert result["step_id"] == "user"
assert result["errors"] == {"base": "cannot_connect"}
- with patch(
- "homeassistant.components.downloader.async_setup_entry", return_value=True
- ), patch(
- "homeassistant.components.downloader.config_flow.DownloaderConfigFlow._validate_input",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.components.downloader.async_setup_entry", return_value=True
+ ),
+ patch(
+ "homeassistant.components.downloader.config_flow.DownloaderConfigFlow._validate_input",
+ return_value=None,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -76,11 +79,14 @@ async def test_single_instance_allowed(
async def test_import_flow_success(hass: HomeAssistant) -> None:
"""Test import flow."""
- with patch(
- "homeassistant.components.downloader.async_setup_entry", return_value=True
- ), patch(
- "homeassistant.components.downloader.config_flow.DownloaderConfigFlow._validate_input",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.components.downloader.async_setup_entry", return_value=True
+ ),
+ patch(
+ "homeassistant.components.downloader.config_flow.DownloaderConfigFlow._validate_input",
+ return_value=None,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
diff --git a/tests/components/dremel_3d_printer/test_button.py b/tests/components/dremel_3d_printer/test_button.py
index e0ea0cf9eaf..48b39b09cf1 100644
--- a/tests/components/dremel_3d_printer/test_button.py
+++ b/tests/components/dremel_3d_printer/test_button.py
@@ -44,10 +44,13 @@ async def test_buttons(
)
assert mock.call_count == 1
- with patch(
- f"homeassistant.components.dremel_3d_printer.Dremel3DPrinter.{function}_print",
- side_effect=RuntimeError,
- ) as mock, pytest.raises(HomeAssistantError):
+ with (
+ patch(
+ f"homeassistant.components.dremel_3d_printer.Dremel3DPrinter.{function}_print",
+ side_effect=RuntimeError,
+ ) as mock,
+ pytest.raises(HomeAssistantError),
+ ):
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
diff --git a/tests/components/dsmr/conftest.py b/tests/components/dsmr/conftest.py
index 7b9e583253b..05881d9c877 100644
--- a/tests/components/dsmr/conftest.py
+++ b/tests/components/dsmr/conftest.py
@@ -30,11 +30,15 @@ async def dsmr_connection_fixture(hass):
connection_factory = MagicMock(wraps=connection_factory)
- with patch(
- "homeassistant.components.dsmr.sensor.create_dsmr_reader", connection_factory
- ), patch(
- "homeassistant.components.dsmr.sensor.create_tcp_dsmr_reader",
- connection_factory,
+ with (
+ patch(
+ "homeassistant.components.dsmr.sensor.create_dsmr_reader",
+ connection_factory,
+ ),
+ patch(
+ "homeassistant.components.dsmr.sensor.create_tcp_dsmr_reader",
+ connection_factory,
+ ),
):
yield (connection_factory, transport, protocol)
@@ -52,12 +56,15 @@ async def rfxtrx_dsmr_connection_fixture(hass):
connection_factory = MagicMock(wraps=connection_factory)
- with patch(
- "homeassistant.components.dsmr.sensor.create_rfxtrx_dsmr_reader",
- connection_factory,
- ), patch(
- "homeassistant.components.dsmr.sensor.create_rfxtrx_tcp_dsmr_reader",
- connection_factory,
+ with (
+ patch(
+ "homeassistant.components.dsmr.sensor.create_rfxtrx_dsmr_reader",
+ connection_factory,
+ ),
+ patch(
+ "homeassistant.components.dsmr.sensor.create_rfxtrx_tcp_dsmr_reader",
+ connection_factory,
+ ),
):
yield (connection_factory, transport, protocol)
@@ -130,12 +137,15 @@ async def dsmr_connection_send_validate_fixture(hass):
protocol.wait_closed = wait_closed
- with patch(
- "homeassistant.components.dsmr.config_flow.create_dsmr_reader",
- connection_factory,
- ), patch(
- "homeassistant.components.dsmr.config_flow.create_tcp_dsmr_reader",
- connection_factory,
+ with (
+ patch(
+ "homeassistant.components.dsmr.config_flow.create_dsmr_reader",
+ connection_factory,
+ ),
+ patch(
+ "homeassistant.components.dsmr.config_flow.create_tcp_dsmr_reader",
+ connection_factory,
+ ),
):
yield (connection_factory, transport, protocol)
@@ -176,11 +186,14 @@ async def rfxtrx_dsmr_connection_send_validate_fixture(hass):
protocol.wait_closed = wait_closed
- with patch(
- "homeassistant.components.dsmr.config_flow.create_rfxtrx_dsmr_reader",
- connection_factory,
- ), patch(
- "homeassistant.components.dsmr.config_flow.create_rfxtrx_tcp_dsmr_reader",
- connection_factory,
+ with (
+ patch(
+ "homeassistant.components.dsmr.config_flow.create_rfxtrx_dsmr_reader",
+ connection_factory,
+ ),
+ patch(
+ "homeassistant.components.dsmr.config_flow.create_rfxtrx_tcp_dsmr_reader",
+ connection_factory,
+ ),
):
yield (connection_factory, transport, protocol)
diff --git a/tests/components/dsmr/test_config_flow.py b/tests/components/dsmr/test_config_flow.py
index 5a677794e46..687c6b4a3bc 100644
--- a/tests/components/dsmr/test_config_flow.py
+++ b/tests/components/dsmr/test_config_flow.py
@@ -495,9 +495,10 @@ async def test_options_flow(hass: HomeAssistant) -> None:
},
)
- with patch(
- "homeassistant.components.dsmr.async_setup_entry", return_value=True
- ), patch("homeassistant.components.dsmr.async_unload_entry", return_value=True):
+ with (
+ patch("homeassistant.components.dsmr.async_setup_entry", return_value=True),
+ patch("homeassistant.components.dsmr.async_unload_entry", return_value=True),
+ ):
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
await hass.async_block_till_done()
diff --git a/tests/components/dunehd/test_config_flow.py b/tests/components/dunehd/test_config_flow.py
index 1ef799420a5..bf3137e0204 100644
--- a/tests/components/dunehd/test_config_flow.py
+++ b/tests/components/dunehd/test_config_flow.py
@@ -69,8 +69,9 @@ async def test_duplicate_error(hass: HomeAssistant) -> None:
async def test_create_entry(hass: HomeAssistant) -> None:
"""Test that the user step works."""
- with patch("homeassistant.components.dunehd.async_setup_entry"), patch(
- "pdunehd.DuneHDPlayer.update_state", return_value=DUNEHD_STATE
+ with (
+ patch("homeassistant.components.dunehd.async_setup_entry"),
+ patch("pdunehd.DuneHDPlayer.update_state", return_value=DUNEHD_STATE),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=CONFIG_HOSTNAME
@@ -83,8 +84,9 @@ async def test_create_entry(hass: HomeAssistant) -> None:
async def test_create_entry_with_ipv6_address(hass: HomeAssistant) -> None:
"""Test that the user step works with device IPv6 address.."""
- with patch("homeassistant.components.dunehd.async_setup_entry"), patch(
- "pdunehd.DuneHDPlayer.update_state", return_value=DUNEHD_STATE
+ with (
+ patch("homeassistant.components.dunehd.async_setup_entry"),
+ patch("pdunehd.DuneHDPlayer.update_state", return_value=DUNEHD_STATE),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
diff --git a/tests/components/dynalite/test_init.py b/tests/components/dynalite/test_init.py
index 94ff75d4a57..2c15c41e40b 100644
--- a/tests/components/dynalite/test_init.py
+++ b/tests/components/dynalite/test_init.py
@@ -85,13 +85,16 @@ async def test_async_setup(hass: HomeAssistant) -> None:
async def test_service_request_area_preset(hass: HomeAssistant) -> None:
"""Test requesting and area preset via service call."""
- with patch(
- "homeassistant.components.dynalite.bridge.DynaliteDevices.async_setup",
- return_value=True,
- ), patch(
- "dynalite_devices_lib.dynalite.Dynalite.request_area_preset",
- return_value=True,
- ) as mock_req_area_pres:
+ with (
+ patch(
+ "homeassistant.components.dynalite.bridge.DynaliteDevices.async_setup",
+ return_value=True,
+ ),
+ patch(
+ "dynalite_devices_lib.dynalite.Dynalite.request_area_preset",
+ return_value=True,
+ ) as mock_req_area_pres,
+ ):
assert await async_setup_component(
hass,
dynalite.DOMAIN,
@@ -157,13 +160,16 @@ async def test_service_request_area_preset(hass: HomeAssistant) -> None:
async def test_service_request_channel_level(hass: HomeAssistant) -> None:
"""Test requesting the level of a channel via service call."""
- with patch(
- "homeassistant.components.dynalite.bridge.DynaliteDevices.async_setup",
- return_value=True,
- ), patch(
- "dynalite_devices_lib.dynalite.Dynalite.request_channel_level",
- return_value=True,
- ) as mock_req_chan_lvl:
+ with (
+ patch(
+ "homeassistant.components.dynalite.bridge.DynaliteDevices.async_setup",
+ return_value=True,
+ ),
+ patch(
+ "dynalite_devices_lib.dynalite.Dynalite.request_channel_level",
+ return_value=True,
+ ) as mock_req_chan_lvl,
+ ):
assert await async_setup_component(
hass,
dynalite.DOMAIN,
diff --git a/tests/components/ecobee/test_config_flow.py b/tests/components/ecobee/test_config_flow.py
index 832e3f6c66f..91d9f848ffd 100644
--- a/tests/components/ecobee/test_config_flow.py
+++ b/tests/components/ecobee/test_config_flow.py
@@ -144,10 +144,13 @@ async def test_import_flow_triggered_with_ecobee_conf_and_valid_data_and_valid_t
MOCK_ECOBEE_CONF = {ECOBEE_API_KEY: None, ECOBEE_REFRESH_TOKEN: None}
- with patch(
- "homeassistant.components.ecobee.config_flow.load_json_object",
- return_value=MOCK_ECOBEE_CONF,
- ), patch("homeassistant.components.ecobee.config_flow.Ecobee") as mock_ecobee:
+ with (
+ patch(
+ "homeassistant.components.ecobee.config_flow.load_json_object",
+ return_value=MOCK_ECOBEE_CONF,
+ ),
+ patch("homeassistant.components.ecobee.config_flow.Ecobee") as mock_ecobee,
+ ):
mock_ecobee = mock_ecobee.return_value
mock_ecobee.refresh_tokens.return_value = True
mock_ecobee.api_key = "test-api-key"
@@ -173,10 +176,13 @@ async def test_import_flow_triggered_with_ecobee_conf_and_invalid_data(
MOCK_ECOBEE_CONF = {}
- with patch(
- "homeassistant.components.ecobee.config_flow.load_json_object",
- return_value=MOCK_ECOBEE_CONF,
- ), patch.object(flow, "async_step_user") as mock_async_step_user:
+ with (
+ patch(
+ "homeassistant.components.ecobee.config_flow.load_json_object",
+ return_value=MOCK_ECOBEE_CONF,
+ ),
+ patch.object(flow, "async_step_user") as mock_async_step_user,
+ ):
await flow.async_step_import(import_data=None)
mock_async_step_user.assert_called_once_with(
@@ -194,12 +200,14 @@ async def test_import_flow_triggered_with_ecobee_conf_and_valid_data_and_stale_t
MOCK_ECOBEE_CONF = {ECOBEE_API_KEY: None, ECOBEE_REFRESH_TOKEN: None}
- with patch(
- "homeassistant.components.ecobee.config_flow.load_json_object",
- return_value=MOCK_ECOBEE_CONF,
- ), patch(
- "homeassistant.components.ecobee.config_flow.Ecobee"
- ) as mock_ecobee, patch.object(flow, "async_step_user") as mock_async_step_user:
+ with (
+ patch(
+ "homeassistant.components.ecobee.config_flow.load_json_object",
+ return_value=MOCK_ECOBEE_CONF,
+ ),
+ patch("homeassistant.components.ecobee.config_flow.Ecobee") as mock_ecobee,
+ patch.object(flow, "async_step_user") as mock_async_step_user,
+ ):
mock_ecobee = mock_ecobee.return_value
mock_ecobee.refresh_tokens.return_value = False
diff --git a/tests/components/econet/test_config_flow.py b/tests/components/econet/test_config_flow.py
index 7cd6d35deeb..7647b77e0a6 100644
--- a/tests/components/econet/test_config_flow.py
+++ b/tests/components/econet/test_config_flow.py
@@ -23,10 +23,13 @@ async def test_bad_credentials(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "pyeconet.EcoNetApiInterface.login",
- side_effect=InvalidCredentialsError(),
- ), patch("homeassistant.components.econet.async_setup_entry", return_value=True):
+ with (
+ patch(
+ "pyeconet.EcoNetApiInterface.login",
+ side_effect=InvalidCredentialsError(),
+ ),
+ patch("homeassistant.components.econet.async_setup_entry", return_value=True),
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
@@ -51,10 +54,13 @@ async def test_generic_error_from_library(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "pyeconet.EcoNetApiInterface.login",
- side_effect=PyeconetError(),
- ), patch("homeassistant.components.econet.async_setup_entry", return_value=True):
+ with (
+ patch(
+ "pyeconet.EcoNetApiInterface.login",
+ side_effect=PyeconetError(),
+ ),
+ patch("homeassistant.components.econet.async_setup_entry", return_value=True),
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
@@ -79,10 +85,13 @@ async def test_auth_worked(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "pyeconet.EcoNetApiInterface.login",
- return_value=EcoNetApiInterface,
- ), patch("homeassistant.components.econet.async_setup_entry", return_value=True):
+ with (
+ patch(
+ "pyeconet.EcoNetApiInterface.login",
+ return_value=EcoNetApiInterface,
+ ),
+ patch("homeassistant.components.econet.async_setup_entry", return_value=True),
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
@@ -114,10 +123,13 @@ async def test_already_configured(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "pyeconet.EcoNetApiInterface.login",
- return_value=EcoNetApiInterface,
- ), patch("homeassistant.components.econet.async_setup_entry", return_value=True):
+ with (
+ patch(
+ "pyeconet.EcoNetApiInterface.login",
+ return_value=EcoNetApiInterface,
+ ),
+ patch("homeassistant.components.econet.async_setup_entry", return_value=True),
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
diff --git a/tests/components/ecovacs/conftest.py b/tests/components/ecovacs/conftest.py
index 29649e91573..1a313957c3e 100644
--- a/tests/components/ecovacs/conftest.py
+++ b/tests/components/ecovacs/conftest.py
@@ -55,12 +55,15 @@ def device_fixture() -> str:
@pytest.fixture
def mock_authenticator(device_fixture: str) -> Generator[Mock, None, None]:
"""Mock the authenticator."""
- with patch(
- "homeassistant.components.ecovacs.controller.Authenticator",
- autospec=True,
- ) as mock, patch(
- "homeassistant.components.ecovacs.config_flow.Authenticator",
- new=mock,
+ with (
+ patch(
+ "homeassistant.components.ecovacs.controller.Authenticator",
+ autospec=True,
+ ) as mock,
+ patch(
+ "homeassistant.components.ecovacs.config_flow.Authenticator",
+ new=mock,
+ ),
):
authenticator = mock.return_value
authenticator.authenticate.return_value = Credentials("token", "user_id", 0)
@@ -97,12 +100,15 @@ def mock_authenticator_authenticate(mock_authenticator: Mock) -> AsyncMock:
@pytest.fixture
def mock_mqtt_client(mock_authenticator: Mock) -> Mock:
"""Mock the MQTT client."""
- with patch(
- "homeassistant.components.ecovacs.controller.MqttClient",
- autospec=True,
- ) as mock, patch(
- "homeassistant.components.ecovacs.config_flow.MqttClient",
- new=mock,
+ with (
+ patch(
+ "homeassistant.components.ecovacs.controller.MqttClient",
+ autospec=True,
+ ) as mock,
+ patch(
+ "homeassistant.components.ecovacs.config_flow.MqttClient",
+ new=mock,
+ ),
):
client = mock.return_value
client._authenticator = mock_authenticator
diff --git a/tests/components/electrasmart/test_config_flow.py b/tests/components/electrasmart/test_config_flow.py
index 0da8ae4e400..957c140862f 100644
--- a/tests/components/electrasmart/test_config_flow.py
+++ b/tests/components/electrasmart/test_config_flow.py
@@ -49,15 +49,19 @@ async def test_one_time_password(hass: HomeAssistant):
mock_generate_token = loads(load_fixture("generate_token_response.json", DOMAIN))
mock_otp_response = loads(load_fixture("otp_response.json", DOMAIN))
- with patch(
- "electrasmart.api.ElectraAPI.generate_new_token",
- return_value=mock_generate_token,
- ), patch(
- "electrasmart.api.ElectraAPI.validate_one_time_password",
- return_value=mock_otp_response,
- ), patch(
- "electrasmart.api.ElectraAPI.fetch_devices",
- return_value=[],
+ with (
+ patch(
+ "electrasmart.api.ElectraAPI.generate_new_token",
+ return_value=mock_generate_token,
+ ),
+ patch(
+ "electrasmart.api.ElectraAPI.validate_one_time_password",
+ return_value=mock_otp_response,
+ ),
+ patch(
+ "electrasmart.api.ElectraAPI.fetch_devices",
+ return_value=[],
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -75,12 +79,15 @@ async def test_one_time_password(hass: HomeAssistant):
async def test_one_time_password_api_error(hass: HomeAssistant):
"""Test one time password."""
mock_generate_token = loads(load_fixture("generate_token_response.json", DOMAIN))
- with patch(
- "electrasmart.api.ElectraAPI.generate_new_token",
- return_value=mock_generate_token,
- ), patch(
- "electrasmart.api.ElectraAPI.validate_one_time_password",
- side_effect=ElectraApiError,
+ with (
+ patch(
+ "electrasmart.api.ElectraAPI.generate_new_token",
+ return_value=mock_generate_token,
+ ),
+ patch(
+ "electrasmart.api.ElectraAPI.validate_one_time_password",
+ side_effect=ElectraApiError,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -144,12 +151,15 @@ async def test_invalid_auth(hass: HomeAssistant):
)
mock_invalid_otp_response = loads(load_fixture("invalid_otp_response.json", DOMAIN))
- with patch(
- "electrasmart.api.ElectraAPI.generate_new_token",
- return_value=mock_generate_token_response,
- ), patch(
- "electrasmart.api.ElectraAPI.validate_one_time_password",
- return_value=mock_invalid_otp_response,
+ with (
+ patch(
+ "electrasmart.api.ElectraAPI.generate_new_token",
+ return_value=mock_generate_token_response,
+ ),
+ patch(
+ "electrasmart.api.ElectraAPI.validate_one_time_password",
+ return_value=mock_invalid_otp_response,
+ ),
):
# test with required
result = await hass.config_entries.flow.async_init(
diff --git a/tests/components/elgato/conftest.py b/tests/components/elgato/conftest.py
index b1dd94ce069..5a783c509c2 100644
--- a/tests/components/elgato/conftest.py
+++ b/tests/components/elgato/conftest.py
@@ -65,10 +65,11 @@ def mock_elgato(
device_fixtures: str, state_variant: str
) -> Generator[None, MagicMock, None]:
"""Return a mocked Elgato client."""
- with patch(
- "homeassistant.components.elgato.coordinator.Elgato", autospec=True
- ) as elgato_mock, patch(
- "homeassistant.components.elgato.config_flow.Elgato", new=elgato_mock
+ with (
+ patch(
+ "homeassistant.components.elgato.coordinator.Elgato", autospec=True
+ ) as elgato_mock,
+ patch("homeassistant.components.elgato.config_flow.Elgato", new=elgato_mock),
):
elgato = elgato_mock.return_value
elgato.info.return_value = Info.from_json(
diff --git a/tests/components/elkm1/__init__.py b/tests/components/elkm1/__init__.py
index cb34f78360a..bec83002f0f 100644
--- a/tests/components/elkm1/__init__.py
+++ b/tests/components/elkm1/__init__.py
@@ -50,12 +50,15 @@ def _patch_elk(elk=None):
@contextmanager
def _patcher():
- with patch(
- "homeassistant.components.elkm1.config_flow.Elk",
- new=_elk,
- ), patch(
- "homeassistant.components.elkm1.config_flow.Elk",
- new=_elk,
+ with (
+ patch(
+ "homeassistant.components.elkm1.config_flow.Elk",
+ new=_elk,
+ ),
+ patch(
+ "homeassistant.components.elkm1.config_flow.Elk",
+ new=_elk,
+ ),
):
yield
diff --git a/tests/components/elkm1/test_config_flow.py b/tests/components/elkm1/test_config_flow.py
index b69c23bf9cb..592efc16b5e 100644
--- a/tests/components/elkm1/test_config_flow.py
+++ b/tests/components/elkm1/test_config_flow.py
@@ -72,12 +72,17 @@ async def test_form_user_with_secure_elk_no_discovery(hass: HomeAssistant) -> No
mocked_elk = mock_elk(invalid_auth=False, sync_complete=True)
- with _patch_discovery(no_device=True), _patch_elk(elk=mocked_elk), patch(
- "homeassistant.components.elkm1.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.elkm1.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(no_device=True),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.elkm1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -124,12 +129,17 @@ async def test_form_user_with_insecure_elk_skip_discovery(hass: HomeAssistant) -
mocked_elk = mock_elk(invalid_auth=False, sync_complete=True)
- with _patch_discovery(), _patch_elk(elk=mocked_elk), patch(
- "homeassistant.components.elkm1.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.elkm1.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.elkm1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -176,12 +186,17 @@ async def test_form_user_with_insecure_elk_no_discovery(hass: HomeAssistant) ->
mocked_elk = mock_elk(invalid_auth=False, sync_complete=True)
- with _patch_discovery(no_device=True), _patch_elk(elk=mocked_elk), patch(
- "homeassistant.components.elkm1.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.elkm1.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(no_device=True),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.elkm1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -228,12 +243,15 @@ async def test_form_user_with_insecure_elk_times_out(hass: HomeAssistant) -> Non
mocked_elk = mock_elk(invalid_auth=False, sync_complete=False)
- with patch(
- "homeassistant.components.elkm1.config_flow.VALIDATE_TIMEOUT",
- 0,
- ), patch(
- "homeassistant.components.elkm1.config_flow.LOGIN_TIMEOUT", 0
- ), _patch_discovery(), _patch_elk(elk=mocked_elk):
+ with (
+ patch(
+ "homeassistant.components.elkm1.config_flow.VALIDATE_TIMEOUT",
+ 0,
+ ),
+ patch("homeassistant.components.elkm1.config_flow.LOGIN_TIMEOUT", 0),
+ _patch_discovery(),
+ _patch_elk(elk=mocked_elk),
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -312,12 +330,17 @@ async def test_form_user_with_secure_elk_with_discovery(hass: HomeAssistant) ->
)
await hass.async_block_till_done()
- with _patch_discovery(), _patch_elk(elk=mocked_elk), patch(
- "homeassistant.components.elkm1.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.elkm1.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.elkm1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
@@ -365,12 +388,17 @@ async def test_form_user_with_secure_elk_with_discovery_pick_manual(
)
await hass.async_block_till_done()
- with _patch_discovery(), _patch_elk(elk=mocked_elk), patch(
- "homeassistant.components.elkm1.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.elkm1.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.elkm1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
@@ -421,12 +449,17 @@ async def test_form_user_with_secure_elk_with_discovery_pick_manual_direct_disco
)
await hass.async_block_till_done()
- with _patch_discovery(), _patch_elk(elk=mocked_elk), patch(
- "homeassistant.components.elkm1.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.elkm1.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.elkm1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
@@ -468,12 +501,17 @@ async def test_form_user_with_tls_elk_no_discovery(hass: HomeAssistant) -> None:
mocked_elk = mock_elk(invalid_auth=False, sync_complete=True)
- with _patch_discovery(no_device=True), _patch_elk(elk=mocked_elk), patch(
- "homeassistant.components.elkm1.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.elkm1.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(no_device=True),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.elkm1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -514,12 +552,17 @@ async def test_form_user_with_non_secure_elk_no_discovery(hass: HomeAssistant) -
mocked_elk = mock_elk(invalid_auth=None, sync_complete=True)
- with _patch_discovery(no_device=True), _patch_elk(elk=mocked_elk), patch(
- "homeassistant.components.elkm1.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.elkm1.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(no_device=True),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.elkm1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -558,12 +601,17 @@ async def test_form_user_with_serial_elk_no_discovery(hass: HomeAssistant) -> No
mocked_elk = mock_elk(invalid_auth=None, sync_complete=True)
- with _patch_discovery(no_device=True), _patch_elk(elk=mocked_elk), patch(
- "homeassistant.components.elkm1.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.elkm1.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(no_device=True),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.elkm1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -596,12 +644,17 @@ async def test_form_cannot_connect(hass: HomeAssistant) -> None:
mocked_elk = mock_elk(invalid_auth=None, sync_complete=None)
- with _patch_discovery(no_device=True), _patch_elk(elk=mocked_elk), patch(
- "homeassistant.components.elkm1.config_flow.VALIDATE_TIMEOUT",
- 0,
- ), patch(
- "homeassistant.components.elkm1.config_flow.LOGIN_TIMEOUT",
- 0,
+ with (
+ _patch_discovery(no_device=True),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.config_flow.VALIDATE_TIMEOUT",
+ 0,
+ ),
+ patch(
+ "homeassistant.components.elkm1.config_flow.LOGIN_TIMEOUT",
+ 0,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -627,12 +680,17 @@ async def test_unknown_exception(hass: HomeAssistant) -> None:
mocked_elk = mock_elk(invalid_auth=None, sync_complete=None, exception=OSError)
- with _patch_discovery(no_device=True), _patch_elk(elk=mocked_elk), patch(
- "homeassistant.components.elkm1.config_flow.VALIDATE_TIMEOUT",
- 0,
- ), patch(
- "homeassistant.components.elkm1.config_flow.LOGIN_TIMEOUT",
- 0,
+ with (
+ _patch_discovery(no_device=True),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.config_flow.VALIDATE_TIMEOUT",
+ 0,
+ ),
+ patch(
+ "homeassistant.components.elkm1.config_flow.LOGIN_TIMEOUT",
+ 0,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -707,12 +765,17 @@ async def test_form_import(hass: HomeAssistant) -> None:
"""Test we get the form with import source."""
mocked_elk = mock_elk(invalid_auth=False, sync_complete=True)
- with _patch_discovery(no_device=True), _patch_elk(elk=mocked_elk), patch(
- "homeassistant.components.elkm1.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.elkm1.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(no_device=True),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.elkm1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
@@ -772,12 +835,17 @@ async def test_form_import_device_discovered(hass: HomeAssistant) -> None:
"""Test we can import with discovery."""
mocked_elk = mock_elk(invalid_auth=False, sync_complete=True)
- with _patch_discovery(), _patch_elk(elk=mocked_elk), patch(
- "homeassistant.components.elkm1.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.elkm1.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.elkm1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
@@ -837,12 +905,17 @@ async def test_form_import_non_secure_device_discovered(hass: HomeAssistant) ->
"""Test we can import non-secure with discovery."""
mocked_elk = mock_elk(invalid_auth=False, sync_complete=True)
- with _patch_discovery(), _patch_elk(elk=mocked_elk), patch(
- "homeassistant.components.elkm1.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.elkm1.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.elkm1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
@@ -876,12 +949,17 @@ async def test_form_import_non_secure_non_stanadard_port_device_discovered(
"""Test we can import non-secure non standard port with discovery."""
mocked_elk = mock_elk(invalid_auth=False, sync_complete=True)
- with _patch_discovery(), _patch_elk(elk=mocked_elk), patch(
- "homeassistant.components.elkm1.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.elkm1.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.elkm1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
@@ -1091,12 +1169,17 @@ async def test_discovered_by_discovery(hass: HomeAssistant) -> None:
mocked_elk = mock_elk(invalid_auth=False, sync_complete=True)
- with _patch_discovery(), _patch_elk(elk=mocked_elk), patch(
- "homeassistant.components.elkm1.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.elkm1.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.elkm1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -1136,12 +1219,17 @@ async def test_discovered_by_discovery_non_standard_port(hass: HomeAssistant) ->
mocked_elk = mock_elk(invalid_auth=False, sync_complete=True)
- with _patch_discovery(), _patch_elk(elk=mocked_elk), patch(
- "homeassistant.components.elkm1.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.elkm1.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.elkm1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -1202,12 +1290,17 @@ async def test_discovered_by_dhcp_udp_responds(hass: HomeAssistant) -> None:
mocked_elk = mock_elk(invalid_auth=False, sync_complete=True)
- with _patch_discovery(), _patch_elk(elk=mocked_elk), patch(
- "homeassistant.components.elkm1.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.elkm1.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.elkm1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -1247,14 +1340,17 @@ async def test_discovered_by_dhcp_udp_responds_with_nonsecure_port(
mocked_elk = mock_elk(invalid_auth=False, sync_complete=True)
- with _patch_discovery(device=ELK_NON_SECURE_DISCOVERY), _patch_elk(
- elk=mocked_elk
- ), patch(
- "homeassistant.components.elkm1.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.elkm1.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(device=ELK_NON_SECURE_DISCOVERY),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.elkm1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -1299,12 +1395,17 @@ async def test_discovered_by_dhcp_udp_responds_existing_config_entry(
mocked_elk = mock_elk(invalid_auth=False, sync_complete=True)
- with _patch_discovery(), _patch_elk(elk=mocked_elk), patch(
- "homeassistant.components.elkm1.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.elkm1.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.elkm1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"username": "test-username", "password": "test-password"},
@@ -1362,12 +1463,17 @@ async def test_multiple_instances_with_discovery(hass: HomeAssistant) -> None:
)
await hass.async_block_till_done()
- with _patch_discovery(device=elk_discovery_1), _patch_elk(elk=mocked_elk), patch(
- "homeassistant.components.elkm1.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.elkm1.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(device=elk_discovery_1),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.elkm1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
@@ -1409,10 +1515,14 @@ async def test_multiple_instances_with_discovery(hass: HomeAssistant) -> None:
)
await hass.async_block_till_done()
- with _patch_discovery(device=elk_discovery_2), _patch_elk(elk=mocked_elk), patch(
- "homeassistant.components.elkm1.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(device=elk_discovery_2),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
@@ -1447,10 +1557,14 @@ async def test_multiple_instances_with_discovery(hass: HomeAssistant) -> None:
mocked_elk = mock_elk(invalid_auth=None, sync_complete=True)
- with _patch_discovery(no_device=True), _patch_elk(elk=mocked_elk), patch(
- "homeassistant.components.elkm1.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(no_device=True),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -1501,12 +1615,17 @@ async def test_multiple_instances_with_tls_v12(hass: HomeAssistant) -> None:
assert result2["type"] == "form"
assert not result["errors"]
assert result2["step_id"] == "discovered_connection"
- with _patch_discovery(device=elk_discovery_1), _patch_elk(elk=mocked_elk), patch(
- "homeassistant.components.elkm1.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.elkm1.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(device=elk_discovery_1),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.elkm1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
@@ -1549,10 +1668,14 @@ async def test_multiple_instances_with_tls_v12(hass: HomeAssistant) -> None:
)
await hass.async_block_till_done()
- with _patch_discovery(device=elk_discovery_2), _patch_elk(elk=mocked_elk), patch(
- "homeassistant.components.elkm1.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(device=elk_discovery_2),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
@@ -1588,10 +1711,14 @@ async def test_multiple_instances_with_tls_v12(hass: HomeAssistant) -> None:
mocked_elk = mock_elk(invalid_auth=False, sync_complete=True)
- with _patch_discovery(no_device=True), _patch_elk(elk=mocked_elk), patch(
- "homeassistant.components.elkm1.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(no_device=True),
+ _patch_elk(elk=mocked_elk),
+ patch(
+ "homeassistant.components.elkm1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
diff --git a/tests/components/emonitor/test_config_flow.py b/tests/components/emonitor/test_config_flow.py
index 56474673f70..07809a83d89 100644
--- a/tests/components/emonitor/test_config_flow.py
+++ b/tests/components/emonitor/test_config_flow.py
@@ -35,13 +35,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.emonitor.config_flow.Emonitor.async_get_status",
- return_value=_mock_emonitor(),
- ), patch(
- "homeassistant.components.emonitor.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.emonitor.config_flow.Emonitor.async_get_status",
+ return_value=_mock_emonitor(),
+ ),
+ patch(
+ "homeassistant.components.emonitor.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -198,12 +201,15 @@ async def test_user_unique_id_already_exists(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.emonitor.config_flow.Emonitor.async_get_status",
- return_value=_mock_emonitor(),
- ), patch(
- "homeassistant.components.emonitor.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.emonitor.config_flow.Emonitor.async_get_status",
+ return_value=_mock_emonitor(),
+ ),
+ patch(
+ "homeassistant.components.emonitor.async_setup_entry",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/emulated_hue/test_init.py b/tests/components/emulated_hue/test_init.py
index 9bc29ce4899..6bc99db6e60 100644
--- a/tests/components/emulated_hue/test_init.py
+++ b/tests/components/emulated_hue/test_init.py
@@ -133,14 +133,16 @@ def test_config_alexa_entity_id_to_number() -> None:
async def test_setup_works(hass: HomeAssistant) -> None:
"""Test setup works."""
hass.config.components.add("network")
- with patch(
- "homeassistant.components.emulated_hue.async_create_upnp_datagram_endpoint",
- AsyncMock(),
- ) as mock_create_upnp_datagram_endpoint, patch(
- "homeassistant.components.emulated_hue.async_get_source_ip"
- ), patch(
- "homeassistant.components.emulated_hue.web.TCPSite",
- return_value=Mock(spec_set=web.TCPSite),
+ with (
+ patch(
+ "homeassistant.components.emulated_hue.async_create_upnp_datagram_endpoint",
+ AsyncMock(),
+ ) as mock_create_upnp_datagram_endpoint,
+ patch("homeassistant.components.emulated_hue.async_get_source_ip"),
+ patch(
+ "homeassistant.components.emulated_hue.web.TCPSite",
+ return_value=Mock(spec_set=web.TCPSite),
+ ),
):
mock_create_upnp_datagram_endpoint.return_value = AsyncMock(
spec=UPNPResponderProtocol
diff --git a/tests/components/emulated_roku/test_init.py b/tests/components/emulated_roku/test_init.py
index 17a6e106fc3..00316c66425 100644
--- a/tests/components/emulated_roku/test_init.py
+++ b/tests/components/emulated_roku/test_init.py
@@ -9,9 +9,12 @@ from homeassistant.setup import async_setup_component
async def test_config_required_fields(hass: HomeAssistant, mock_get_source_ip) -> None:
"""Test that configuration is successful with required fields."""
- with patch.object(emulated_roku, "configured_servers", return_value=[]), patch(
- "homeassistant.components.emulated_roku.binding.EmulatedRokuServer",
- return_value=Mock(start=AsyncMock(), close=AsyncMock()),
+ with (
+ patch.object(emulated_roku, "configured_servers", return_value=[]),
+ patch(
+ "homeassistant.components.emulated_roku.binding.EmulatedRokuServer",
+ return_value=Mock(start=AsyncMock(), close=AsyncMock()),
+ ),
):
assert (
await async_setup_component(
@@ -36,11 +39,14 @@ async def test_config_already_registered_not_configured(
hass: HomeAssistant, mock_get_source_ip
) -> None:
"""Test that an already registered name causes the entry to be ignored."""
- with patch(
- "homeassistant.components.emulated_roku.binding.EmulatedRokuServer",
- return_value=Mock(start=AsyncMock(), close=AsyncMock()),
- ) as instantiate, patch.object(
- emulated_roku, "configured_servers", return_value=["Emulated Roku Test"]
+ with (
+ patch(
+ "homeassistant.components.emulated_roku.binding.EmulatedRokuServer",
+ return_value=Mock(start=AsyncMock(), close=AsyncMock()),
+ ) as instantiate,
+ patch.object(
+ emulated_roku, "configured_servers", return_value=["Emulated Roku Test"]
+ ),
):
assert (
await async_setup_component(
diff --git a/tests/components/enocean/test_config_flow.py b/tests/components/enocean/test_config_flow.py
index 0acecd6c0b4..45a4e6e387f 100644
--- a/tests/components/enocean/test_config_flow.py
+++ b/tests/components/enocean/test_config_flow.py
@@ -75,8 +75,9 @@ async def test_detection_flow_with_custom_path(hass: HomeAssistant) -> None:
USER_PROVIDED_PATH = EnOceanFlowHandler.MANUAL_PATH_VALUE
FAKE_DONGLE_PATH = "/fake/dongle"
- with patch(DONGLE_VALIDATE_PATH_METHOD, Mock(return_value=True)), 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,
@@ -93,8 +94,9 @@ async def test_detection_flow_with_invalid_path(hass: HomeAssistant) -> None:
USER_PROVIDED_PATH = "/invalid/path"
FAKE_DONGLE_PATH = "/fake/dongle"
- with patch(DONGLE_VALIDATE_PATH_METHOD, Mock(return_value=False)), 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,
diff --git a/tests/components/enphase_envoy/conftest.py b/tests/components/enphase_envoy/conftest.py
index 91a37c7fa7f..40d409aea8e 100644
--- a/tests/components/enphase_envoy/conftest.py
+++ b/tests/components/enphase_envoy/conftest.py
@@ -344,12 +344,15 @@ def mock_envoy_fixture(
@pytest.fixture(name="setup_enphase_envoy")
async def setup_enphase_envoy_fixture(hass, config, mock_envoy):
"""Define a fixture to set up Enphase Envoy."""
- with patch(
- "homeassistant.components.enphase_envoy.config_flow.Envoy",
- return_value=mock_envoy,
- ), patch(
- "homeassistant.components.enphase_envoy.Envoy",
- return_value=mock_envoy,
+ with (
+ patch(
+ "homeassistant.components.enphase_envoy.config_flow.Envoy",
+ return_value=mock_envoy,
+ ),
+ patch(
+ "homeassistant.components.enphase_envoy.Envoy",
+ return_value=mock_envoy,
+ ),
):
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
diff --git a/tests/components/enphase_envoy/test_sensor.py b/tests/components/enphase_envoy/test_sensor.py
index 784fb47e8c1..3d6a0ec5757 100644
--- a/tests/components/enphase_envoy/test_sensor.py
+++ b/tests/components/enphase_envoy/test_sensor.py
@@ -17,15 +17,19 @@ from tests.common import MockConfigEntry
@pytest.fixture(name="setup_enphase_envoy_sensor")
async def setup_enphase_envoy_sensor_fixture(hass, config, mock_envoy):
"""Define a fixture to set up Enphase Envoy with sensor platform only."""
- with patch(
- "homeassistant.components.enphase_envoy.config_flow.Envoy",
- return_value=mock_envoy,
- ), patch(
- "homeassistant.components.enphase_envoy.Envoy",
- return_value=mock_envoy,
- ), patch(
- "homeassistant.components.enphase_envoy.PLATFORMS",
- [Platform.SENSOR],
+ with (
+ patch(
+ "homeassistant.components.enphase_envoy.config_flow.Envoy",
+ return_value=mock_envoy,
+ ),
+ patch(
+ "homeassistant.components.enphase_envoy.Envoy",
+ return_value=mock_envoy,
+ ),
+ patch(
+ "homeassistant.components.enphase_envoy.PLATFORMS",
+ [Platform.SENSOR],
+ ),
):
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
diff --git a/tests/components/environment_canada/test_config_flow.py b/tests/components/environment_canada/test_config_flow.py
index 3b6661b53bc..e9513644947 100644
--- a/tests/components/environment_canada/test_config_flow.py
+++ b/tests/components/environment_canada/test_config_flow.py
@@ -51,9 +51,12 @@ def mocked_ec(
async def test_create_entry(hass: HomeAssistant) -> None:
"""Test creating an entry."""
- with mocked_ec(), patch(
- "homeassistant.components.environment_canada.async_setup_entry",
- return_value=True,
+ with (
+ mocked_ec(),
+ patch(
+ "homeassistant.components.environment_canada.async_setup_entry",
+ return_value=True,
+ ),
):
flow = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@@ -76,9 +79,12 @@ async def test_create_same_entry_twice(hass: HomeAssistant) -> None:
)
entry.add_to_hass(hass)
- with mocked_ec(), patch(
- "homeassistant.components.environment_canada.async_setup_entry",
- return_value=True,
+ with (
+ mocked_ec(),
+ patch(
+ "homeassistant.components.environment_canada.async_setup_entry",
+ return_value=True,
+ ),
):
flow = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@@ -122,9 +128,12 @@ async def test_exception_handling(hass: HomeAssistant, error) -> None:
async def test_lat_lon_not_specified(hass: HomeAssistant) -> None:
"""Test that the import step works when coordinates are not specified."""
- with mocked_ec(), patch(
- "homeassistant.components.environment_canada.async_setup_entry",
- return_value=True,
+ with (
+ mocked_ec(),
+ patch(
+ "homeassistant.components.environment_canada.async_setup_entry",
+ return_value=True,
+ ),
):
fake_config = dict(FAKE_CONFIG)
del fake_config[CONF_LATITUDE]
diff --git a/tests/components/environment_canada/test_diagnostics.py b/tests/components/environment_canada/test_diagnostics.py
index 75389defb86..8f800111d39 100644
--- a/tests/components/environment_canada/test_diagnostics.py
+++ b/tests/components/environment_canada/test_diagnostics.py
@@ -52,17 +52,23 @@ async def init_integration(hass: HomeAssistant) -> MockConfigEntry:
radar_mock.image = b"GIF..."
radar_mock.timestamp = datetime(2022, 10, 4, tzinfo=UTC)
- with patch(
- "homeassistant.components.environment_canada.ECWeather",
- return_value=weather_mock,
- ), patch(
- "homeassistant.components.environment_canada.ECAirQuality",
- return_value=mock_ec(),
- ), patch(
- "homeassistant.components.environment_canada.ECRadar", return_value=radar_mock
- ), patch(
- "homeassistant.components.environment_canada.config_flow.ECWeather",
- return_value=weather_mock,
+ with (
+ patch(
+ "homeassistant.components.environment_canada.ECWeather",
+ return_value=weather_mock,
+ ),
+ patch(
+ "homeassistant.components.environment_canada.ECAirQuality",
+ return_value=mock_ec(),
+ ),
+ patch(
+ "homeassistant.components.environment_canada.ECRadar",
+ return_value=radar_mock,
+ ),
+ patch(
+ "homeassistant.components.environment_canada.config_flow.ECWeather",
+ return_value=weather_mock,
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/epion/conftest.py b/tests/components/epion/conftest.py
index 2290d0d4c8f..51fed636ca1 100644
--- a/tests/components/epion/conftest.py
+++ b/tests/components/epion/conftest.py
@@ -14,12 +14,15 @@ def mock_epion():
"epion/get_current_one_device.json"
)
mock_epion_api = MagicMock()
- with patch(
- "homeassistant.components.epion.config_flow.Epion",
- return_value=mock_epion_api,
- ) as mock_epion_api, patch(
- "homeassistant.components.epion.Epion",
- return_value=mock_epion_api,
+ with (
+ patch(
+ "homeassistant.components.epion.config_flow.Epion",
+ return_value=mock_epion_api,
+ ) as mock_epion_api,
+ patch(
+ "homeassistant.components.epion.Epion",
+ return_value=mock_epion_api,
+ ),
):
mock_epion_api.return_value.get_current.return_value = current_one_device_data
yield mock_epion_api
diff --git a/tests/components/epson/test_config_flow.py b/tests/components/epson/test_config_flow.py
index d18d7fe5f4a..c6ca921df0f 100644
--- a/tests/components/epson/test_config_flow.py
+++ b/tests/components/epson/test_config_flow.py
@@ -20,16 +20,20 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
assert result["step_id"] == config_entries.SOURCE_USER
- with patch(
- "homeassistant.components.epson.Projector.get_power",
- return_value="01",
- ), patch(
- "homeassistant.components.epson.Projector.get_serial_number",
- return_value="12345",
- ), patch(
- "homeassistant.components.epson.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.epson.Projector.get_power",
+ return_value="01",
+ ),
+ patch(
+ "homeassistant.components.epson.Projector.get_serial_number",
+ return_value="12345",
+ ),
+ patch(
+ "homeassistant.components.epson.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_HOST: "1.1.1.1", CONF_NAME: "test-epson"},
diff --git a/tests/components/epson/test_media_player.py b/tests/components/epson/test_media_player.py
index e5869777482..000071054f1 100644
--- a/tests/components/epson/test_media_player.py
+++ b/tests/components/epson/test_media_player.py
@@ -34,12 +34,15 @@ async def test_set_unique_id(
entity_entry = entity_registry.async_get("media_player.epson")
assert entity_entry
assert entity_entry.unique_id == entry.entry_id
- with patch(
- "homeassistant.components.epson.Projector.get_power", return_value="01"
- ), patch(
- "homeassistant.components.epson.Projector.get_serial_number", return_value="123"
- ), patch(
- "homeassistant.components.epson.Projector.get_property",
+ with (
+ patch("homeassistant.components.epson.Projector.get_power", return_value="01"),
+ patch(
+ "homeassistant.components.epson.Projector.get_serial_number",
+ return_value="123",
+ ),
+ patch(
+ "homeassistant.components.epson.Projector.get_property",
+ ),
):
freezer.tick(timedelta(seconds=30))
async_fire_time_changed(hass)
diff --git a/tests/components/escea/test_config_flow.py b/tests/components/escea/test_config_flow.py
index 0bb128f717e..7d467fc50a0 100644
--- a/tests/components/escea/test_config_flow.py
+++ b/tests/components/escea/test_config_flow.py
@@ -47,10 +47,11 @@ async def test_not_found(
) -> None:
"""Test not finding any Escea controllers."""
- with patch(
- "homeassistant.components.escea.discovery.pescea_discovery_service"
- ) as discovery_service, patch(
- "homeassistant.components.escea.config_flow.TIMEOUT_DISCOVERY", 0
+ with (
+ patch(
+ "homeassistant.components.escea.discovery.pescea_discovery_service"
+ ) as discovery_service,
+ patch("homeassistant.components.escea.config_flow.TIMEOUT_DISCOVERY", 0),
):
discovery_service.return_value = mock_discovery_service
@@ -75,12 +76,15 @@ async def test_found(
"""Test finding an Escea controller."""
mock_discovery_service.controllers["test-uid"] = mock_controller
- with patch(
- "homeassistant.components.escea.async_setup_entry",
- return_value=True,
- ) as mock_setup, patch(
- "homeassistant.components.escea.discovery.pescea_discovery_service"
- ) as discovery_service:
+ with (
+ patch(
+ "homeassistant.components.escea.async_setup_entry",
+ return_value=True,
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.escea.discovery.pescea_discovery_service"
+ ) as discovery_service,
+ ):
discovery_service.return_value = mock_discovery_service
mock_discovery_service.start_discovery.side_effect = _mock_start_discovery(
discovery_service, mock_controller
diff --git a/tests/components/esphome/conftest.py b/tests/components/esphome/conftest.py
index 09a23824054..e51fc663b59 100644
--- a/tests/components/esphome/conftest.py
+++ b/tests/components/esphome/conftest.py
@@ -152,11 +152,13 @@ def mock_client(mock_device_info) -> APIClient:
mock_client.address = "127.0.0.1"
mock_client.api_version = APIVersion(99, 99)
- with patch(
- "homeassistant.components.esphome.manager.ReconnectLogic",
- BaseMockReconnectLogic,
- ), patch("homeassistant.components.esphome.APIClient", mock_client), patch(
- "homeassistant.components.esphome.config_flow.APIClient", mock_client
+ with (
+ patch(
+ "homeassistant.components.esphome.manager.ReconnectLogic",
+ BaseMockReconnectLogic,
+ ),
+ patch("homeassistant.components.esphome.APIClient", mock_client),
+ patch("homeassistant.components.esphome.config_flow.APIClient", mock_client),
):
yield mock_client
diff --git a/tests/components/esphome/test_dashboard.py b/tests/components/esphome/test_dashboard.py
index 11234e790c5..51b9b535caa 100644
--- a/tests/components/esphome/test_dashboard.py
+++ b/tests/components/esphome/test_dashboard.py
@@ -98,11 +98,14 @@ async def test_setup_dashboard_fails_when_already_setup(
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
- with patch.object(
- dashboard.ESPHomeDashboardAPI, "get_devices", side_effect=TimeoutError
- ) as mock_get_devices, patch(
- "homeassistant.components.esphome.async_setup_entry", return_value=True
- ) as mock_setup:
+ with (
+ patch.object(
+ dashboard.ESPHomeDashboardAPI, "get_devices", side_effect=TimeoutError
+ ) as mock_get_devices,
+ patch(
+ "homeassistant.components.esphome.async_setup_entry", return_value=True
+ ) as mock_setup,
+ ):
await dashboard.async_set_dashboard_info(hass, "test-slug", "test-host", 6052)
await hass.async_block_till_done()
@@ -166,12 +169,15 @@ async def test_new_dashboard_fix_reauth(
await dashboard.async_get_dashboard(hass).async_refresh()
- with patch(
- "homeassistant.components.esphome.dashboard.ESPHomeDashboardAPI.get_encryption_key",
- return_value=VALID_NOISE_PSK,
- ) as mock_get_encryption_key, patch(
- "homeassistant.components.esphome.async_setup_entry", return_value=True
- ) as mock_setup:
+ with (
+ patch(
+ "homeassistant.components.esphome.dashboard.ESPHomeDashboardAPI.get_encryption_key",
+ return_value=VALID_NOISE_PSK,
+ ) as mock_get_encryption_key,
+ patch(
+ "homeassistant.components.esphome.async_setup_entry", return_value=True
+ ) as mock_setup,
+ ):
await dashboard.async_set_dashboard_info(hass, "test-slug", "test-host", 6052)
await hass.async_block_till_done()
diff --git a/tests/components/esphome/test_update.py b/tests/components/esphome/test_update.py
index d17f2f4623a..959ad12876d 100644
--- a/tests/components/esphome/test_update.py
+++ b/tests/components/esphome/test_update.py
@@ -101,13 +101,17 @@ async def test_update_entity(
return
# Compile failed, don't try to upload
- with patch(
- "esphome_dashboard_api.ESPHomeDashboardAPI.compile", return_value=False
- ) as mock_compile, patch(
- "esphome_dashboard_api.ESPHomeDashboardAPI.upload", return_value=True
- ) as mock_upload, pytest.raises(
- HomeAssistantError,
- match="compiling",
+ with (
+ patch(
+ "esphome_dashboard_api.ESPHomeDashboardAPI.compile", return_value=False
+ ) as mock_compile,
+ patch(
+ "esphome_dashboard_api.ESPHomeDashboardAPI.upload", return_value=True
+ ) as mock_upload,
+ pytest.raises(
+ HomeAssistantError,
+ match="compiling",
+ ),
):
await hass.services.async_call(
"update",
@@ -122,13 +126,17 @@ async def test_update_entity(
assert len(mock_upload.mock_calls) == 0
# Compile success, upload fails
- with patch(
- "esphome_dashboard_api.ESPHomeDashboardAPI.compile", return_value=True
- ) as mock_compile, patch(
- "esphome_dashboard_api.ESPHomeDashboardAPI.upload", return_value=False
- ) as mock_upload, pytest.raises(
- HomeAssistantError,
- match="OTA",
+ with (
+ patch(
+ "esphome_dashboard_api.ESPHomeDashboardAPI.compile", return_value=True
+ ) as mock_compile,
+ patch(
+ "esphome_dashboard_api.ESPHomeDashboardAPI.upload", return_value=False
+ ) as mock_upload,
+ pytest.raises(
+ HomeAssistantError,
+ match="OTA",
+ ),
):
await hass.services.async_call(
"update",
@@ -144,11 +152,14 @@ async def test_update_entity(
assert mock_upload.mock_calls[0][1][0] == "test.yaml"
# Everything works
- with patch(
- "esphome_dashboard_api.ESPHomeDashboardAPI.compile", return_value=True
- ) as mock_compile, patch(
- "esphome_dashboard_api.ESPHomeDashboardAPI.upload", return_value=True
- ) as mock_upload:
+ with (
+ patch(
+ "esphome_dashboard_api.ESPHomeDashboardAPI.compile", return_value=True
+ ) as mock_compile,
+ patch(
+ "esphome_dashboard_api.ESPHomeDashboardAPI.upload", return_value=True
+ ) as mock_upload,
+ ):
await hass.services.async_call(
"update",
"install",
@@ -260,12 +271,15 @@ async def test_update_entity_dashboard_not_available_startup(
mock_dashboard,
) -> None:
"""Test ESPHome update entity when dashboard is not available at startup."""
- with patch(
- "homeassistant.components.esphome.update.DomainData.get_entry_data",
- return_value=Mock(available=True, device_info=mock_device_info),
- ), patch(
- "esphome_dashboard_api.ESPHomeDashboardAPI.get_devices",
- side_effect=TimeoutError,
+ with (
+ patch(
+ "homeassistant.components.esphome.update.DomainData.get_entry_data",
+ return_value=Mock(available=True, device_info=mock_device_info),
+ ),
+ patch(
+ "esphome_dashboard_api.ESPHomeDashboardAPI.get_devices",
+ side_effect=TimeoutError,
+ ),
):
await async_get_dashboard(hass).async_refresh()
assert await hass.config_entries.async_forward_entry_setup(
diff --git a/tests/components/evil_genius_labs/conftest.py b/tests/components/evil_genius_labs/conftest.py
index dd3f5fe24f4..49092da75c7 100644
--- a/tests/components/evil_genius_labs/conftest.py
+++ b/tests/components/evil_genius_labs/conftest.py
@@ -42,18 +42,23 @@ async def setup_evil_genius_labs(
hass, config_entry, all_fixture, info_fixture, product_fixture, platforms
):
"""Test up Evil Genius Labs instance."""
- with patch(
- "pyevilgenius.EvilGeniusDevice.get_all",
- return_value=all_fixture,
- ), patch(
- "pyevilgenius.EvilGeniusDevice.get_info",
- return_value=info_fixture,
- ), patch(
- "pyevilgenius.EvilGeniusDevice.get_product",
- return_value=product_fixture,
- ), patch(
- "homeassistant.components.evil_genius_labs.PLATFORMS",
- platforms,
+ with (
+ patch(
+ "pyevilgenius.EvilGeniusDevice.get_all",
+ return_value=all_fixture,
+ ),
+ patch(
+ "pyevilgenius.EvilGeniusDevice.get_info",
+ return_value=info_fixture,
+ ),
+ patch(
+ "pyevilgenius.EvilGeniusDevice.get_product",
+ return_value=product_fixture,
+ ),
+ patch(
+ "homeassistant.components.evil_genius_labs.PLATFORMS",
+ platforms,
+ ),
):
assert await async_setup_component(hass, "evil_genius_labs", {})
await hass.async_block_till_done()
diff --git a/tests/components/evil_genius_labs/test_config_flow.py b/tests/components/evil_genius_labs/test_config_flow.py
index 0c3ab2298ea..b6bdae940ba 100644
--- a/tests/components/evil_genius_labs/test_config_flow.py
+++ b/tests/components/evil_genius_labs/test_config_flow.py
@@ -21,19 +21,24 @@ async def test_form(
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with patch(
- "pyevilgenius.EvilGeniusDevice.get_all",
- return_value=all_fixture,
- ), patch(
- "pyevilgenius.EvilGeniusDevice.get_info",
- return_value=info_fixture,
- ), patch(
- "pyevilgenius.EvilGeniusDevice.get_product",
- return_value=product_fixture,
- ), patch(
- "homeassistant.components.evil_genius_labs.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "pyevilgenius.EvilGeniusDevice.get_all",
+ return_value=all_fixture,
+ ),
+ patch(
+ "pyevilgenius.EvilGeniusDevice.get_info",
+ return_value=info_fixture,
+ ),
+ patch(
+ "pyevilgenius.EvilGeniusDevice.get_product",
+ return_value=product_fixture,
+ ),
+ patch(
+ "homeassistant.components.evil_genius_labs.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
diff --git a/tests/components/evil_genius_labs/test_light.py b/tests/components/evil_genius_labs/test_light.py
index e0ecb5415a7..9b93e8f66cf 100644
--- a/tests/components/evil_genius_labs/test_light.py
+++ b/tests/components/evil_genius_labs/test_light.py
@@ -29,11 +29,10 @@ async def test_works(hass: HomeAssistant, setup_evil_genius_labs) -> None:
@pytest.mark.parametrize("platforms", [("light",)])
async def test_turn_on_color(hass: HomeAssistant, setup_evil_genius_labs) -> None:
"""Test turning on with a color."""
- with patch(
- "pyevilgenius.EvilGeniusDevice.set_path_value"
- ) as mock_set_path_value, patch(
- "pyevilgenius.EvilGeniusDevice.set_rgb_color"
- ) as mock_set_rgb_color:
+ with (
+ patch("pyevilgenius.EvilGeniusDevice.set_path_value") as mock_set_path_value,
+ patch("pyevilgenius.EvilGeniusDevice.set_rgb_color") as mock_set_rgb_color,
+ ):
await hass.services.async_call(
"light",
"turn_on",
diff --git a/tests/components/ezviz/conftest.py b/tests/components/ezviz/conftest.py
index ccfa9616efa..10fd0406a1c 100644
--- a/tests/components/ezviz/conftest.py
+++ b/tests/components/ezviz/conftest.py
@@ -22,9 +22,12 @@ def mock_ffmpeg(hass):
@pytest.fixture
def ezviz_test_rtsp_config_flow(hass):
"""Mock the EzvizApi for easier testing."""
- with patch.object(TestRTSPAuth, "main", return_value=True), patch(
- "homeassistant.components.ezviz.config_flow.TestRTSPAuth"
- ) as mock_ezviz_test_rtsp:
+ with (
+ patch.object(TestRTSPAuth, "main", return_value=True),
+ patch(
+ "homeassistant.components.ezviz.config_flow.TestRTSPAuth"
+ ) as mock_ezviz_test_rtsp,
+ ):
instance = mock_ezviz_test_rtsp.return_value = TestRTSPAuth(
"test-ip",
"test-username",
@@ -39,9 +42,10 @@ def ezviz_test_rtsp_config_flow(hass):
@pytest.fixture
def ezviz_config_flow(hass):
"""Mock the EzvizAPI for easier config flow testing."""
- with patch.object(EzvizClient, "login", return_value=True), patch(
- "homeassistant.components.ezviz.config_flow.EzvizClient"
- ) as mock_ezviz:
+ with (
+ patch.object(EzvizClient, "login", return_value=True),
+ patch("homeassistant.components.ezviz.config_flow.EzvizClient") as mock_ezviz,
+ ):
instance = mock_ezviz.return_value = EzvizClient(
"test-username",
"test-password",
diff --git a/tests/components/faa_delays/test_config_flow.py b/tests/components/faa_delays/test_config_flow.py
index d164eab918f..92a8929afbf 100644
--- a/tests/components/faa_delays/test_config_flow.py
+++ b/tests/components/faa_delays/test_config_flow.py
@@ -28,10 +28,13 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch.object(faadelays.Airport, "update", new=mock_valid_airport), patch(
- "homeassistant.components.faa_delays.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch.object(faadelays.Airport, "update", new=mock_valid_airport),
+ patch(
+ "homeassistant.components.faa_delays.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
diff --git a/tests/components/feedreader/test_init.py b/tests/components/feedreader/test_init.py
index 898e46a7c84..f836d233670 100644
--- a/tests/components/feedreader/test_init.py
+++ b/tests/components/feedreader/test_init.py
@@ -198,10 +198,13 @@ async def test_storage_data_writing(
"""Test writing to storage."""
storage_data: dict[str, str] = {URL: "2018-04-30T05:10:00+00:00"}
- with patch(
- "feedparser.http.get",
- return_value=feed_one_event,
- ), patch("homeassistant.components.feedreader.DELAY_SAVE", new=0):
+ with (
+ patch(
+ "feedparser.http.get",
+ return_value=feed_one_event,
+ ),
+ patch("homeassistant.components.feedreader.DELAY_SAVE", new=0),
+ ):
assert await async_setup_component(hass, feedreader.DOMAIN, VALID_CONFIG_2)
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
@@ -297,13 +300,16 @@ async def test_feed_identical_timestamps(
hass: HomeAssistant, events, feed_identically_timed_events
) -> None:
"""Test feed with 2 entries with identical timestamps."""
- with patch(
- "feedparser.http.get",
- return_value=feed_identically_timed_events,
- ), patch(
- "homeassistant.components.feedreader.StoredData.get_timestamp",
- return_value=gmtime(
- datetime.fromisoformat("1970-01-01T00:00:00.0+0000").timestamp()
+ with (
+ patch(
+ "feedparser.http.get",
+ return_value=feed_identically_timed_events,
+ ),
+ patch(
+ "homeassistant.components.feedreader.StoredData.get_timestamp",
+ return_value=gmtime(
+ datetime.fromisoformat("1970-01-01T00:00:00.0+0000").timestamp()
+ ),
),
):
assert await async_setup_component(hass, feedreader.DOMAIN, VALID_CONFIG_2)
diff --git a/tests/components/ffmpeg/test_init.py b/tests/components/ffmpeg/test_init.py
index 2d79e593d2c..60d24baa302 100644
--- a/tests/components/ffmpeg/test_init.py
+++ b/tests/components/ffmpeg/test_init.py
@@ -269,9 +269,13 @@ async def test_legacy_ffmpeg(
hass: HomeAssistant,
) -> None:
"""Test legacy ffmpeg uses the old ffserver content type."""
- with assert_setup_component(1), patch(
- "homeassistant.components.ffmpeg.FFVersion.get_version", return_value="3.0"
- ), patch("homeassistant.components.ffmpeg.is_official_image", return_value=False):
+ with (
+ assert_setup_component(1),
+ patch(
+ "homeassistant.components.ffmpeg.FFVersion.get_version", return_value="3.0"
+ ),
+ patch("homeassistant.components.ffmpeg.is_official_image", return_value=False),
+ ):
await async_setup_component(hass, ffmpeg.DOMAIN, {ffmpeg.DOMAIN: {}})
manager = get_ffmpeg_manager(hass)
@@ -282,8 +286,9 @@ async def test_ffmpeg_using_official_image(
hass: HomeAssistant,
) -> None:
"""Test ffmpeg using official image is the new ffmpeg content type."""
- with assert_setup_component(1), patch(
- "homeassistant.components.ffmpeg.is_official_image", return_value=True
+ with (
+ assert_setup_component(1),
+ patch("homeassistant.components.ffmpeg.is_official_image", return_value=True),
):
await async_setup_component(hass, ffmpeg.DOMAIN, {ffmpeg.DOMAIN: {}})
diff --git a/tests/components/file/test_notify.py b/tests/components/file/test_notify.py
index 093be77c08f..3077d71bdde 100644
--- a/tests/components/file/test_notify.py
+++ b/tests/components/file/test_notify.py
@@ -56,9 +56,10 @@ async def test_notify_file(
freezer.move_to(dt_util.utcnow())
m_open = mock_open()
- with patch("homeassistant.components.file.notify.open", m_open, create=True), patch(
- "homeassistant.components.file.notify.os.stat"
- ) as mock_st:
+ with (
+ patch("homeassistant.components.file.notify.open", m_open, create=True),
+ patch("homeassistant.components.file.notify.os.stat") as mock_st,
+ ):
mock_st.return_value.st_size = 0
title = (
f"{ATTR_TITLE_DEFAULT} notifications "
diff --git a/tests/components/file_upload/test_init.py b/tests/components/file_upload/test_init.py
index deff64ff073..1ef238cafd0 100644
--- a/tests/components/file_upload/test_init.py
+++ b/tests/components/file_upload/test_init.py
@@ -21,11 +21,14 @@ async def uploaded_file_dir(hass: HomeAssistant, hass_client) -> Path:
assert await async_setup_component(hass, "file_upload", {})
client = await hass_client()
- with patch(
- # Patch temp dir name to avoid tests fail running in parallel
- "homeassistant.components.file_upload.TEMP_DIR_NAME",
- file_upload.TEMP_DIR_NAME + f"-{getrandbits(10):03x}",
- ), TEST_IMAGE.open("rb") as fp:
+ with (
+ patch(
+ # Patch temp dir name to avoid tests fail running in parallel
+ "homeassistant.components.file_upload.TEMP_DIR_NAME",
+ file_upload.TEMP_DIR_NAME + f"-{getrandbits(10):03x}",
+ ),
+ TEST_IMAGE.open("rb") as fp,
+ ):
res = await client.post("/api/file_upload", data={"file": fp})
assert res.status == 200
@@ -80,14 +83,17 @@ async def test_upload_large_file(
assert await async_setup_component(hass, "file_upload", {})
client = await hass_client()
- with patch(
- # Patch temp dir name to avoid tests fail running in parallel
- "homeassistant.components.file_upload.TEMP_DIR_NAME",
- file_upload.TEMP_DIR_NAME + f"-{getrandbits(10):03x}",
- ), patch(
- # Patch one megabyte to 8 bytes to prevent having to use big files in tests
- "homeassistant.components.file_upload.ONE_MEGABYTE",
- 8,
+ with (
+ patch(
+ # Patch temp dir name to avoid tests fail running in parallel
+ "homeassistant.components.file_upload.TEMP_DIR_NAME",
+ file_upload.TEMP_DIR_NAME + f"-{getrandbits(10):03x}",
+ ),
+ patch(
+ # Patch one megabyte to 8 bytes to prevent having to use big files in tests
+ "homeassistant.components.file_upload.ONE_MEGABYTE",
+ 8,
+ ),
):
res = await client.post("/api/file_upload", data={"file": large_file_io})
@@ -139,16 +145,20 @@ async def test_upload_large_file_fails(
def write(self, data: bytes) -> None:
raise OSError("Boom")
- with patch(
- # Patch temp dir name to avoid tests fail running in parallel
- "homeassistant.components.file_upload.TEMP_DIR_NAME",
- file_upload.TEMP_DIR_NAME + f"-{getrandbits(10):03x}",
- ), patch(
- # Patch one megabyte to 8 bytes to prevent having to use big files in tests
- "homeassistant.components.file_upload.ONE_MEGABYTE",
- 8,
- ), patch(
- "homeassistant.components.file_upload.Path.open", return_value=_mock_open()
+ with (
+ patch(
+ # Patch temp dir name to avoid tests fail running in parallel
+ "homeassistant.components.file_upload.TEMP_DIR_NAME",
+ file_upload.TEMP_DIR_NAME + f"-{getrandbits(10):03x}",
+ ),
+ patch(
+ # Patch one megabyte to 8 bytes to prevent having to use big files in tests
+ "homeassistant.components.file_upload.ONE_MEGABYTE",
+ 8,
+ ),
+ patch(
+ "homeassistant.components.file_upload.Path.open", return_value=_mock_open()
+ ),
):
res = await client.post("/api/file_upload", data={"file": large_file_io})
diff --git a/tests/components/filter/test_sensor.py b/tests/components/filter/test_sensor.py
index 66914bf32a6..67370bbcedc 100644
--- a/tests/components/filter/test_sensor.py
+++ b/tests/components/filter/test_sensor.py
@@ -130,12 +130,15 @@ async def test_chain_history(
]
}
- with patch(
- "homeassistant.components.recorder.history.state_changes_during_period",
- return_value=fake_states,
- ), patch(
- "homeassistant.components.recorder.history.get_last_state_changes",
- return_value=fake_states,
+ with (
+ patch(
+ "homeassistant.components.recorder.history.state_changes_during_period",
+ return_value=fake_states,
+ ),
+ patch(
+ "homeassistant.components.recorder.history.get_last_state_changes",
+ return_value=fake_states,
+ ),
):
with assert_setup_component(1, "sensor"):
assert await async_setup_component(hass, "sensor", config)
@@ -234,12 +237,15 @@ async def test_history_time(recorder_mock: Recorder, hass: HomeAssistant) -> Non
State("sensor.test_monitored", "18.2", last_changed=t_2),
]
}
- with patch(
- "homeassistant.components.recorder.history.state_changes_during_period",
- return_value=fake_states,
- ), patch(
- "homeassistant.components.recorder.history.get_last_state_changes",
- return_value=fake_states,
+ with (
+ patch(
+ "homeassistant.components.recorder.history.state_changes_during_period",
+ return_value=fake_states,
+ ),
+ patch(
+ "homeassistant.components.recorder.history.get_last_state_changes",
+ return_value=fake_states,
+ ),
):
with assert_setup_component(1, "sensor"):
assert await async_setup_component(hass, "sensor", config)
diff --git a/tests/components/fireservicerota/test_config_flow.py b/tests/components/fireservicerota/test_config_flow.py
index ffb3ac23f1b..e2bf5911089 100644
--- a/tests/components/fireservicerota/test_config_flow.py
+++ b/tests/components/fireservicerota/test_config_flow.py
@@ -77,12 +77,15 @@ async def test_invalid_credentials(hass: HomeAssistant) -> None:
async def test_step_user(hass: HomeAssistant) -> None:
"""Test the start of the config flow."""
- with patch(
- "homeassistant.components.fireservicerota.config_flow.FireServiceRota"
- ) as mock_fsr, patch(
- "homeassistant.components.fireservicerota.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.fireservicerota.config_flow.FireServiceRota"
+ ) as mock_fsr,
+ patch(
+ "homeassistant.components.fireservicerota.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
mock_fireservicerota = mock_fsr.return_value
mock_fireservicerota.request_tokens.return_value = MOCK_TOKEN_INFO
@@ -134,11 +137,14 @@ async def test_reauth(hass: HomeAssistant) -> None:
await hass.async_block_till_done()
assert result["type"] == data_entry_flow.FlowResultType.FORM
- with patch(
- "homeassistant.components.fireservicerota.config_flow.FireServiceRota"
- ) as mock_fsr, patch(
- "homeassistant.components.fireservicerota.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.fireservicerota.config_flow.FireServiceRota"
+ ) as mock_fsr,
+ patch(
+ "homeassistant.components.fireservicerota.async_setup_entry",
+ return_value=True,
+ ),
):
mock_fireservicerota = mock_fsr.return_value
mock_fireservicerota.request_tokens.return_value = MOCK_TOKEN_INFO
diff --git a/tests/components/firmata/test_config_flow.py b/tests/components/firmata/test_config_flow.py
index 4dc0dbc80ca..a3c8ca7e728 100644
--- a/tests/components/firmata/test_config_flow.py
+++ b/tests/components/firmata/test_config_flow.py
@@ -64,13 +64,15 @@ async def test_import_cannot_connect_serial_timeout(hass: HomeAssistant) -> None
async def test_import(hass: HomeAssistant) -> None:
"""Test we create an entry from config."""
- with patch(
- "homeassistant.components.firmata.board.PymataExpress", autospec=True
- ), patch(
- "homeassistant.components.firmata.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.firmata.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch("homeassistant.components.firmata.board.PymataExpress", autospec=True),
+ patch(
+ "homeassistant.components.firmata.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.firmata.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
diff --git a/tests/components/fitbit/conftest.py b/tests/components/fitbit/conftest.py
index a076be7f63d..a4bfed43cba 100644
--- a/tests/components/fitbit/conftest.py
+++ b/tests/components/fitbit/conftest.py
@@ -125,12 +125,15 @@ def mock_fitbit_config_setup(
) -> Generator[None, None, None]:
"""Fixture to mock out fitbit.conf file data loading and persistence."""
has_config = fitbit_config_yaml is not None
- with patch(
- "homeassistant.components.fitbit.sensor.os.path.isfile",
- return_value=has_config,
- ), patch(
- "homeassistant.components.fitbit.sensor.load_json_object",
- return_value=fitbit_config_yaml,
+ with (
+ patch(
+ "homeassistant.components.fitbit.sensor.os.path.isfile",
+ return_value=has_config,
+ ),
+ patch(
+ "homeassistant.components.fitbit.sensor.load_json_object",
+ return_value=fitbit_config_yaml,
+ ),
):
yield
diff --git a/tests/components/fivem/test_config_flow.py b/tests/components/fivem/test_config_flow.py
index 1596da01648..174078c5420 100644
--- a/tests/components/fivem/test_config_flow.py
+++ b/tests/components/fivem/test_config_flow.py
@@ -67,13 +67,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with patch(
- "fivem.fivem.FiveM.get_info_raw",
- return_value=_mock_fivem_info_success(),
- ), patch(
- "homeassistant.components.fivem.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "fivem.fivem.FiveM.get_info_raw",
+ return_value=_mock_fivem_info_success(),
+ ),
+ patch(
+ "homeassistant.components.fivem.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
USER_INPUT,
diff --git a/tests/components/flexit_bacnet/conftest.py b/tests/components/flexit_bacnet/conftest.py
index 55941dc44a9..fb4b2237833 100644
--- a/tests/components/flexit_bacnet/conftest.py
+++ b/tests/components/flexit_bacnet/conftest.py
@@ -32,12 +32,15 @@ async def flow_id(hass: HomeAssistant) -> str:
def mock_flexit_bacnet() -> Generator[AsyncMock, None, None]:
"""Mock data from the device."""
flexit_bacnet = AsyncMock(spec=FlexitBACnet)
- with patch(
- "homeassistant.components.flexit_bacnet.config_flow.FlexitBACnet",
- return_value=flexit_bacnet,
- ), patch(
- "homeassistant.components.flexit_bacnet.coordinator.FlexitBACnet",
- return_value=flexit_bacnet,
+ with (
+ patch(
+ "homeassistant.components.flexit_bacnet.config_flow.FlexitBACnet",
+ return_value=flexit_bacnet,
+ ),
+ patch(
+ "homeassistant.components.flexit_bacnet.coordinator.FlexitBACnet",
+ return_value=flexit_bacnet,
+ ),
):
flexit_bacnet.serial_number = "0000-0001"
flexit_bacnet.device_name = "Device Name"
diff --git a/tests/components/flick_electric/test_config_flow.py b/tests/components/flick_electric/test_config_flow.py
index 123232e8c52..9635f3a1526 100644
--- a/tests/components/flick_electric/test_config_flow.py
+++ b/tests/components/flick_electric/test_config_flow.py
@@ -31,13 +31,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.flick_electric.config_flow.SimpleFlickAuth.async_get_access_token",
- return_value="123456789abcdef",
- ), patch(
- "homeassistant.components.flick_electric.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.flick_electric.config_flow.SimpleFlickAuth.async_get_access_token",
+ return_value="123456789abcdef",
+ ),
+ patch(
+ "homeassistant.components.flick_electric.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
CONF,
diff --git a/tests/components/flume/test_config_flow.py b/tests/components/flume/test_config_flow.py
index 64c85a0b896..8fa66c03258 100644
--- a/tests/components/flume/test_config_flow.py
+++ b/tests/components/flume/test_config_flow.py
@@ -34,16 +34,20 @@ async def test_form(hass: HomeAssistant) -> None:
mock_flume_device_list = _get_mocked_flume_device_list()
- with patch(
- "homeassistant.components.flume.config_flow.FlumeAuth",
- return_value=True,
- ), patch(
- "homeassistant.components.flume.config_flow.FlumeDeviceList",
- return_value=mock_flume_device_list,
- ), patch(
- "homeassistant.components.flume.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.flume.config_flow.FlumeAuth",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.flume.config_flow.FlumeDeviceList",
+ return_value=mock_flume_device_list,
+ ),
+ patch(
+ "homeassistant.components.flume.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -72,12 +76,15 @@ async def test_form_invalid_auth(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "homeassistant.components.flume.config_flow.FlumeAuth",
- return_value=True,
- ), patch(
- "homeassistant.components.flume.config_flow.FlumeDeviceList",
- side_effect=Exception,
+ with (
+ patch(
+ "homeassistant.components.flume.config_flow.FlumeAuth",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.flume.config_flow.FlumeDeviceList",
+ side_effect=Exception,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -98,12 +105,15 @@ async def test_form_cannot_connect(hass: HomeAssistant) -> None:
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "homeassistant.components.flume.config_flow.FlumeAuth",
- return_value=True,
- ), patch(
- "homeassistant.components.flume.config_flow.FlumeDeviceList",
- side_effect=requests.exceptions.ConnectionError(),
+ with (
+ patch(
+ "homeassistant.components.flume.config_flow.FlumeAuth",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.flume.config_flow.FlumeDeviceList",
+ side_effect=requests.exceptions.ConnectionError(),
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -140,12 +150,15 @@ async def test_reauth(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["step_id"] == "reauth_confirm"
- with patch(
- "homeassistant.components.flume.config_flow.FlumeAuth",
- return_value=True,
- ), patch(
- "homeassistant.components.flume.config_flow.FlumeDeviceList",
- side_effect=Exception,
+ with (
+ patch(
+ "homeassistant.components.flume.config_flow.FlumeAuth",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.flume.config_flow.FlumeDeviceList",
+ side_effect=Exception,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -157,12 +170,15 @@ async def test_reauth(hass: HomeAssistant) -> None:
assert result2["type"] == "form"
assert result2["errors"] == {"password": "invalid_auth"}
- with patch(
- "homeassistant.components.flume.config_flow.FlumeAuth",
- return_value=True,
- ), patch(
- "homeassistant.components.flume.config_flow.FlumeDeviceList",
- side_effect=requests.exceptions.ConnectionError(),
+ with (
+ patch(
+ "homeassistant.components.flume.config_flow.FlumeAuth",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.flume.config_flow.FlumeDeviceList",
+ side_effect=requests.exceptions.ConnectionError(),
+ ),
):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
@@ -176,16 +192,20 @@ async def test_reauth(hass: HomeAssistant) -> None:
mock_flume_device_list = _get_mocked_flume_device_list()
- with patch(
- "homeassistant.components.flume.config_flow.FlumeAuth",
- return_value=True,
- ), patch(
- "homeassistant.components.flume.config_flow.FlumeDeviceList",
- return_value=mock_flume_device_list,
- ), patch(
- "homeassistant.components.flume.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.flume.config_flow.FlumeAuth",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.flume.config_flow.FlumeDeviceList",
+ return_value=mock_flume_device_list,
+ ),
+ patch(
+ "homeassistant.components.flume.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result4 = await hass.config_entries.flow.async_configure(
result3["flow_id"],
{
diff --git a/tests/components/flux/test_switch.py b/tests/components/flux/test_switch.py
index b0432e60ce1..a3eeec10fa5 100644
--- a/tests/components/flux/test_switch.py
+++ b/tests/components/flux/test_switch.py
@@ -166,9 +166,12 @@ async def test_flux_when_switch_is_off(
return sunrise_time
return sunset_time
- with freeze_time(test_time), patch(
- "homeassistant.components.flux.switch.get_astral_event_date",
- side_effect=event_date,
+ with (
+ freeze_time(test_time),
+ patch(
+ "homeassistant.components.flux.switch.get_astral_event_date",
+ side_effect=event_date,
+ ),
):
turn_on_calls = async_mock_service(hass, light.DOMAIN, SERVICE_TURN_ON)
assert await async_setup_component(
@@ -219,9 +222,12 @@ async def test_flux_before_sunrise(
return sunset_time
await hass.async_block_till_done()
- with freeze_time(test_time), patch(
- "homeassistant.components.flux.switch.get_astral_event_date",
- side_effect=event_date,
+ with (
+ freeze_time(test_time),
+ patch(
+ "homeassistant.components.flux.switch.get_astral_event_date",
+ side_effect=event_date,
+ ),
):
assert await async_setup_component(
hass,
@@ -337,9 +343,12 @@ async def test_flux_after_sunrise_before_sunset(
return sunrise_time
return sunset_time
- with freeze_time(test_time), patch(
- "homeassistant.components.flux.switch.get_astral_event_date",
- side_effect=event_date,
+ with (
+ freeze_time(test_time),
+ patch(
+ "homeassistant.components.flux.switch.get_astral_event_date",
+ side_effect=event_date,
+ ),
):
assert await async_setup_component(
hass,
@@ -396,9 +405,12 @@ async def test_flux_after_sunset_before_stop(
return sunrise_time
return sunset_time
- with freeze_time(test_time), patch(
- "homeassistant.components.flux.switch.get_astral_event_date",
- side_effect=event_date,
+ with (
+ freeze_time(test_time),
+ patch(
+ "homeassistant.components.flux.switch.get_astral_event_date",
+ side_effect=event_date,
+ ),
):
assert await async_setup_component(
hass,
@@ -456,9 +468,12 @@ async def test_flux_after_stop_before_sunrise(
return sunrise_time
return sunset_time
- with freeze_time(test_time), patch(
- "homeassistant.components.flux.switch.get_astral_event_date",
- side_effect=event_date,
+ with (
+ freeze_time(test_time),
+ patch(
+ "homeassistant.components.flux.switch.get_astral_event_date",
+ side_effect=event_date,
+ ),
):
assert await async_setup_component(
hass,
@@ -515,9 +530,12 @@ async def test_flux_with_custom_start_stop_times(
return sunrise_time
return sunset_time
- with freeze_time(test_time), patch(
- "homeassistant.components.flux.switch.get_astral_event_date",
- side_effect=event_date,
+ with (
+ freeze_time(test_time),
+ patch(
+ "homeassistant.components.flux.switch.get_astral_event_date",
+ side_effect=event_date,
+ ),
):
assert await async_setup_component(
hass,
@@ -579,9 +597,12 @@ async def test_flux_before_sunrise_stop_next_day(
return sunrise_time
return sunset_time
- with freeze_time(test_time), patch(
- "homeassistant.components.flux.switch.get_astral_event_date",
- side_effect=event_date,
+ with (
+ freeze_time(test_time),
+ patch(
+ "homeassistant.components.flux.switch.get_astral_event_date",
+ side_effect=event_date,
+ ),
):
assert await async_setup_component(
hass,
@@ -642,9 +663,12 @@ async def test_flux_after_sunrise_before_sunset_stop_next_day(
return sunrise_time
return sunset_time
- with freeze_time(test_time), patch(
- "homeassistant.components.flux.switch.get_astral_event_date",
- side_effect=event_date,
+ with (
+ freeze_time(test_time),
+ patch(
+ "homeassistant.components.flux.switch.get_astral_event_date",
+ side_effect=event_date,
+ ),
):
assert await async_setup_component(
hass,
@@ -707,9 +731,12 @@ async def test_flux_after_sunset_before_midnight_stop_next_day(
return sunrise_time
return sunset_time
- with freeze_time(test_time), patch(
- "homeassistant.components.flux.switch.get_astral_event_date",
- side_effect=event_date,
+ with (
+ freeze_time(test_time),
+ patch(
+ "homeassistant.components.flux.switch.get_astral_event_date",
+ side_effect=event_date,
+ ),
):
assert await async_setup_component(
hass,
@@ -770,9 +797,12 @@ async def test_flux_after_sunset_after_midnight_stop_next_day(
return sunrise_time
return sunset_time
- with freeze_time(test_time), patch(
- "homeassistant.components.flux.switch.get_astral_event_date",
- side_effect=event_date,
+ with (
+ freeze_time(test_time),
+ patch(
+ "homeassistant.components.flux.switch.get_astral_event_date",
+ side_effect=event_date,
+ ),
):
assert await async_setup_component(
hass,
@@ -833,9 +863,12 @@ async def test_flux_after_stop_before_sunrise_stop_next_day(
return sunrise_time
return sunset_time
- with freeze_time(test_time), patch(
- "homeassistant.components.flux.switch.get_astral_event_date",
- side_effect=event_date,
+ with (
+ freeze_time(test_time),
+ patch(
+ "homeassistant.components.flux.switch.get_astral_event_date",
+ side_effect=event_date,
+ ),
):
assert await async_setup_component(
hass,
@@ -893,9 +926,12 @@ async def test_flux_with_custom_colortemps(
return sunrise_time
return sunset_time
- with freeze_time(test_time), patch(
- "homeassistant.components.flux.switch.get_astral_event_date",
- side_effect=event_date,
+ with (
+ freeze_time(test_time),
+ patch(
+ "homeassistant.components.flux.switch.get_astral_event_date",
+ side_effect=event_date,
+ ),
):
assert await async_setup_component(
hass,
@@ -955,9 +991,12 @@ async def test_flux_with_custom_brightness(
return sunrise_time
return sunset_time
- with freeze_time(test_time), patch(
- "homeassistant.components.flux.switch.get_astral_event_date",
- side_effect=event_date,
+ with (
+ freeze_time(test_time),
+ patch(
+ "homeassistant.components.flux.switch.get_astral_event_date",
+ side_effect=event_date,
+ ),
):
assert await async_setup_component(
hass,
@@ -1033,9 +1072,12 @@ async def test_flux_with_multiple_lights(
return sunrise_time
return sunset_time
- with freeze_time(test_time), patch(
- "homeassistant.components.flux.switch.get_astral_event_date",
- side_effect=event_date,
+ with (
+ freeze_time(test_time),
+ patch(
+ "homeassistant.components.flux.switch.get_astral_event_date",
+ side_effect=event_date,
+ ),
):
assert await async_setup_component(
hass,
@@ -1097,9 +1139,12 @@ async def test_flux_with_mired(
return sunrise_time
return sunset_time
- with freeze_time(test_time), patch(
- "homeassistant.components.flux.switch.get_astral_event_date",
- side_effect=event_date,
+ with (
+ freeze_time(test_time),
+ patch(
+ "homeassistant.components.flux.switch.get_astral_event_date",
+ side_effect=event_date,
+ ),
):
assert await async_setup_component(
hass,
@@ -1155,9 +1200,12 @@ async def test_flux_with_rgb(
return sunrise_time
return sunset_time
- with freeze_time(test_time), patch(
- "homeassistant.components.flux.switch.get_astral_event_date",
- side_effect=event_date,
+ with (
+ freeze_time(test_time),
+ patch(
+ "homeassistant.components.flux.switch.get_astral_event_date",
+ side_effect=event_date,
+ ),
):
assert await async_setup_component(
hass,
diff --git a/tests/components/flux_led/__init__.py b/tests/components/flux_led/__init__.py
index 4b36826728a..d1cb892d548 100644
--- a/tests/components/flux_led/__init__.py
+++ b/tests/components/flux_led/__init__.py
@@ -241,12 +241,15 @@ def _patch_discovery(device=None, no_device=False):
@contextmanager
def _patcher():
- with patch(
- "homeassistant.components.flux_led.discovery.AIOBulbScanner.async_scan",
- new=_discovery,
- ), patch(
- "homeassistant.components.flux_led.discovery.AIOBulbScanner.getBulbInfo",
- return_value=[] if no_device else [device or FLUX_DISCOVERY],
+ with (
+ patch(
+ "homeassistant.components.flux_led.discovery.AIOBulbScanner.async_scan",
+ new=_discovery,
+ ),
+ patch(
+ "homeassistant.components.flux_led.discovery.AIOBulbScanner.getBulbInfo",
+ return_value=[] if no_device else [device or FLUX_DISCOVERY],
+ ),
):
yield
diff --git a/tests/components/flux_led/test_config_flow.py b/tests/components/flux_led/test_config_flow.py
index 183164e04a1..63a7a671871 100644
--- a/tests/components/flux_led/test_config_flow.py
+++ b/tests/components/flux_led/test_config_flow.py
@@ -79,11 +79,12 @@ async def test_discovery(hass: HomeAssistant) -> None:
assert result2["step_id"] == "pick_device"
assert not result2["errors"]
- with _patch_discovery(), _patch_wifibulb(), patch(
- f"{MODULE}.async_setup", return_value=True
- ) as mock_setup, patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_wifibulb(),
+ patch(f"{MODULE}.async_setup", return_value=True) as mock_setup,
+ patch(f"{MODULE}.async_setup_entry", return_value=True) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_DEVICE: MAC_ADDRESS},
@@ -153,11 +154,12 @@ async def test_discovery_legacy(hass: HomeAssistant) -> None:
assert result2["step_id"] == "pick_device"
assert not result2["errors"]
- with _patch_discovery(), _patch_wifibulb(), patch(
- f"{MODULE}.async_setup", return_value=True
- ) as mock_setup, patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_wifibulb(),
+ patch(f"{MODULE}.async_setup", return_value=True) as mock_setup,
+ patch(f"{MODULE}.async_setup_entry", return_value=True) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_DEVICE: MAC_ADDRESS},
@@ -239,9 +241,11 @@ async def test_discovery_with_existing_device_present(hass: HomeAssistant) -> No
assert result2["step_id"] == "pick_device"
assert not result2["errors"]
- with _patch_discovery(), _patch_wifibulb(), patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_wifibulb(),
+ patch(f"{MODULE}.async_setup_entry", return_value=True) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_DEVICE: MAC_ADDRESS}
)
@@ -313,9 +317,12 @@ async def test_manual_working_discovery(hass: HomeAssistant) -> None:
assert result2["errors"] == {"base": "cannot_connect"}
# Success
- with _patch_discovery(), _patch_wifibulb(), patch(
- f"{MODULE}.async_setup", return_value=True
- ), patch(f"{MODULE}.async_setup_entry", return_value=True):
+ with (
+ _patch_discovery(),
+ _patch_wifibulb(),
+ patch(f"{MODULE}.async_setup", return_value=True),
+ patch(f"{MODULE}.async_setup_entry", return_value=True),
+ ):
result4 = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: IP_ADDRESS}
)
@@ -357,9 +364,12 @@ async def test_manual_no_discovery_data(hass: HomeAssistant) -> None:
assert result["step_id"] == "user"
assert not result["errors"]
- with _patch_discovery(no_device=True), _patch_wifibulb(), patch(
- f"{MODULE}.async_setup", return_value=True
- ), patch(f"{MODULE}.async_setup_entry", return_value=True):
+ with (
+ _patch_discovery(no_device=True),
+ _patch_wifibulb(),
+ patch(f"{MODULE}.async_setup", return_value=True),
+ patch(f"{MODULE}.async_setup_entry", return_value=True),
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: IP_ADDRESS}
)
@@ -425,11 +435,14 @@ async def test_discovered_by_discovery(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with _patch_discovery(), _patch_wifibulb(), patch(
- f"{MODULE}.async_setup", return_value=True
- ) as mock_async_setup, patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_async_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_wifibulb(),
+ patch(f"{MODULE}.async_setup", return_value=True) as mock_async_setup,
+ patch(
+ f"{MODULE}.async_setup_entry", return_value=True
+ ) as mock_async_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(result["flow_id"], {})
await hass.async_block_till_done()
@@ -461,11 +474,14 @@ async def test_discovered_by_dhcp_udp_responds(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with _patch_discovery(), _patch_wifibulb(), patch(
- f"{MODULE}.async_setup", return_value=True
- ) as mock_async_setup, patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_async_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_wifibulb(),
+ patch(f"{MODULE}.async_setup", return_value=True) as mock_async_setup,
+ patch(
+ f"{MODULE}.async_setup_entry", return_value=True
+ ) as mock_async_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(result["flow_id"], {})
await hass.async_block_till_done()
@@ -497,11 +513,14 @@ async def test_discovered_by_dhcp_no_udp_response(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with _patch_discovery(no_device=True), _patch_wifibulb(), patch(
- f"{MODULE}.async_setup", return_value=True
- ) as mock_async_setup, patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_async_setup_entry:
+ with (
+ _patch_discovery(no_device=True),
+ _patch_wifibulb(),
+ patch(f"{MODULE}.async_setup", return_value=True) as mock_async_setup,
+ patch(
+ f"{MODULE}.async_setup_entry", return_value=True
+ ) as mock_async_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(result["flow_id"], {})
await hass.async_block_till_done()
@@ -529,11 +548,14 @@ async def test_discovered_by_dhcp_partial_udp_response_fallback_tcp(
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with _patch_discovery(device=FLUX_DISCOVERY_PARTIAL), _patch_wifibulb(), patch(
- f"{MODULE}.async_setup", return_value=True
- ) as mock_async_setup, patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_async_setup_entry:
+ with (
+ _patch_discovery(device=FLUX_DISCOVERY_PARTIAL),
+ _patch_wifibulb(),
+ patch(f"{MODULE}.async_setup", return_value=True) as mock_async_setup,
+ patch(
+ f"{MODULE}.async_setup_entry", return_value=True
+ ) as mock_async_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(result["flow_id"], {})
await hass.async_block_till_done()
diff --git a/tests/components/flux_led/test_init.py b/tests/components/flux_led/test_init.py
index 7c4917ea4dc..a42ba5dff37 100644
--- a/tests/components/flux_led/test_init.py
+++ b/tests/components/flux_led/test_init.py
@@ -47,11 +47,14 @@ from tests.common import MockConfigEntry, async_fire_time_changed
@pytest.mark.usefixtures("mock_single_broadcast_address")
async def test_configuring_flux_led_causes_discovery(hass: HomeAssistant) -> None:
"""Test that specifying empty config does discovery."""
- with patch(
- "homeassistant.components.flux_led.discovery.AIOBulbScanner.async_scan"
- ) as scan, patch(
- "homeassistant.components.flux_led.discovery.AIOBulbScanner.getBulbInfo"
- ) as discover:
+ with (
+ patch(
+ "homeassistant.components.flux_led.discovery.AIOBulbScanner.async_scan"
+ ) as scan,
+ patch(
+ "homeassistant.components.flux_led.discovery.AIOBulbScanner.getBulbInfo"
+ ) as discover,
+ ):
discover.return_value = [FLUX_DISCOVERY]
await async_setup_component(hass, flux_led.DOMAIN, {flux_led.DOMAIN: {}})
await hass.async_block_till_done()
@@ -68,11 +71,14 @@ async def test_configuring_flux_led_causes_discovery_multiple_addresses(
hass: HomeAssistant,
) -> None:
"""Test that specifying empty config does discovery."""
- with patch(
- "homeassistant.components.flux_led.discovery.AIOBulbScanner.async_scan"
- ) as scan, patch(
- "homeassistant.components.flux_led.discovery.AIOBulbScanner.getBulbInfo"
- ) as discover:
+ with (
+ patch(
+ "homeassistant.components.flux_led.discovery.AIOBulbScanner.async_scan"
+ ) as scan,
+ patch(
+ "homeassistant.components.flux_led.discovery.AIOBulbScanner.getBulbInfo"
+ ) as discover,
+ ):
discover.return_value = [FLUX_DISCOVERY]
await async_setup_component(hass, flux_led.DOMAIN, {flux_led.DOMAIN: {}})
await hass.async_block_till_done()
@@ -200,13 +206,17 @@ async def test_config_entry_fills_unique_id_with_directed_discovery(
nonlocal last_address
return [discovery] if last_address == IP_ADDRESS else []
- with patch(
- "homeassistant.components.flux_led.discovery.AIOBulbScanner.async_scan",
- new=_discovery,
- ), patch(
- "homeassistant.components.flux_led.discovery.AIOBulbScanner.getBulbInfo",
- new=_mock_getBulbInfo,
- ), _patch_wifibulb():
+ with (
+ patch(
+ "homeassistant.components.flux_led.discovery.AIOBulbScanner.async_scan",
+ new=_discovery,
+ ),
+ patch(
+ "homeassistant.components.flux_led.discovery.AIOBulbScanner.getBulbInfo",
+ new=_mock_getBulbInfo,
+ ),
+ _patch_wifibulb(),
+ ):
await async_setup_component(hass, flux_led.DOMAIN, {flux_led.DOMAIN: {}})
await hass.async_block_till_done()
assert config_entry.state == ConfigEntryState.LOADED
diff --git a/tests/components/forked_daapd/test_config_flow.py b/tests/components/forked_daapd/test_config_flow.py
index 7dc5e1e20f9..a7f0dc3f603 100644
--- a/tests/components/forked_daapd/test_config_flow.py
+++ b/tests/components/forked_daapd/test_config_flow.py
@@ -69,13 +69,16 @@ async def test_show_form(hass: HomeAssistant) -> None:
async def test_config_flow(hass: HomeAssistant, config_entry) -> None:
"""Test that the user step works."""
- with patch(
- "homeassistant.components.forked_daapd.config_flow.ForkedDaapdAPI.test_connection",
- new=AsyncMock(),
- ) as mock_test_connection, patch(
- "homeassistant.components.forked_daapd.media_player.ForkedDaapdAPI.get_request",
- autospec=True,
- ) as mock_get_request:
+ with (
+ patch(
+ "homeassistant.components.forked_daapd.config_flow.ForkedDaapdAPI.test_connection",
+ new=AsyncMock(),
+ ) as mock_test_connection,
+ patch(
+ "homeassistant.components.forked_daapd.media_player.ForkedDaapdAPI.get_request",
+ autospec=True,
+ ) as mock_get_request,
+ ):
mock_get_request.return_value = SAMPLE_CONFIG
mock_test_connection.return_value = ["ok", "My Music on myhost"]
config_data = config_entry.data
diff --git a/tests/components/foscam/test_config_flow.py b/tests/components/foscam/test_config_flow.py
index fc3bd1d5ad2..64ad2b946da 100644
--- a/tests/components/foscam/test_config_flow.py
+++ b/tests/components/foscam/test_config_flow.py
@@ -85,12 +85,15 @@ async def test_user_valid(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.foscam.config_flow.FoscamCamera",
- ) as mock_foscam_camera, patch(
- "homeassistant.components.foscam.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.foscam.config_flow.FoscamCamera",
+ ) as mock_foscam_camera,
+ patch(
+ "homeassistant.components.foscam.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
setup_mock_foscam_camera(mock_foscam_camera)
result = await hass.config_entries.flow.async_configure(
diff --git a/tests/components/freebox/conftest.py b/tests/components/freebox/conftest.py
index e223e868d83..cf520043755 100644
--- a/tests/components/freebox/conftest.py
+++ b/tests/components/freebox/conftest.py
@@ -29,8 +29,9 @@ from tests.common import MockConfigEntry
@pytest.fixture(autouse=True)
def mock_path():
"""Mock path lib."""
- with patch("homeassistant.components.freebox.router.Path"), patch(
- "homeassistant.components.freebox.router.os.makedirs"
+ with (
+ patch("homeassistant.components.freebox.router.Path"),
+ patch("homeassistant.components.freebox.router.os.makedirs"),
):
yield
diff --git a/tests/components/freedompro/conftest.py b/tests/components/freedompro/conftest.py
index 63efbc31ca5..27e6c767223 100644
--- a/tests/components/freedompro/conftest.py
+++ b/tests/components/freedompro/conftest.py
@@ -28,15 +28,18 @@ def mock_setup_entry() -> Generator[AsyncMock, None, None]:
@pytest.fixture(autouse=True)
def mock_freedompro():
"""Mock freedompro get_list and get_states."""
- with patch(
- "homeassistant.components.freedompro.coordinator.get_list",
- return_value={
- "state": True,
- "devices": DEVICES,
- },
- ), patch(
- "homeassistant.components.freedompro.coordinator.get_states",
- return_value=DEVICES_STATE,
+ with (
+ patch(
+ "homeassistant.components.freedompro.coordinator.get_list",
+ return_value={
+ "state": True,
+ "devices": DEVICES,
+ },
+ ),
+ patch(
+ "homeassistant.components.freedompro.coordinator.get_states",
+ return_value=DEVICES_STATE,
+ ),
):
yield
@@ -72,15 +75,18 @@ async def init_integration_no_state(hass) -> MockConfigEntry:
},
)
- with patch(
- "homeassistant.components.freedompro.coordinator.get_list",
- return_value={
- "state": True,
- "devices": DEVICES,
- },
- ), patch(
- "homeassistant.components.freedompro.coordinator.get_states",
- return_value=[],
+ with (
+ patch(
+ "homeassistant.components.freedompro.coordinator.get_list",
+ return_value={
+ "state": True,
+ "devices": DEVICES,
+ },
+ ),
+ patch(
+ "homeassistant.components.freedompro.coordinator.get_states",
+ return_value=[],
+ ),
):
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
diff --git a/tests/components/fritz/test_config_flow.py b/tests/components/fritz/test_config_flow.py
index 5db70e348dd..fbd9886f468 100644
--- a/tests/components/fritz/test_config_flow.py
+++ b/tests/components/fritz/test_config_flow.py
@@ -42,21 +42,26 @@ from tests.common import MockConfigEntry
async def test_user(hass: HomeAssistant, fc_class_mock, mock_get_source_ip) -> None:
"""Test starting a flow by user."""
- with patch(
- "homeassistant.components.fritz.config_flow.FritzConnection",
- side_effect=fc_class_mock,
- ), patch(
- "homeassistant.components.fritz.common.FritzBoxTools._update_device_info",
- return_value=MOCK_FIRMWARE_INFO,
- ), patch(
- "homeassistant.components.fritz.async_setup_entry"
- ) as mock_setup_entry, patch(
- "requests.get",
- ) as mock_request_get, patch(
- "requests.post",
- ) as mock_request_post, patch(
- "homeassistant.components.fritz.config_flow.socket.gethostbyname",
- return_value=MOCK_IPS["fritz.box"],
+ with (
+ patch(
+ "homeassistant.components.fritz.config_flow.FritzConnection",
+ side_effect=fc_class_mock,
+ ),
+ patch(
+ "homeassistant.components.fritz.common.FritzBoxTools._update_device_info",
+ return_value=MOCK_FIRMWARE_INFO,
+ ),
+ patch("homeassistant.components.fritz.async_setup_entry") as mock_setup_entry,
+ patch(
+ "requests.get",
+ ) as mock_request_get,
+ patch(
+ "requests.post",
+ ) as mock_request_post,
+ patch(
+ "homeassistant.components.fritz.config_flow.socket.gethostbyname",
+ return_value=MOCK_IPS["fritz.box"],
+ ),
):
mock_request_get.return_value.status_code = 200
mock_request_get.return_value.content = MOCK_REQUEST
@@ -94,19 +99,25 @@ async def test_user_already_configured(
mock_config = MockConfigEntry(domain=DOMAIN, data=MOCK_USER_DATA)
mock_config.add_to_hass(hass)
- with patch(
- "homeassistant.components.fritz.config_flow.FritzConnection",
- side_effect=fc_class_mock,
- ), patch(
- "homeassistant.components.fritz.common.FritzBoxTools._update_device_info",
- return_value=MOCK_FIRMWARE_INFO,
- ), patch(
- "requests.get",
- ) as mock_request_get, patch(
- "requests.post",
- ) as mock_request_post, patch(
- "homeassistant.components.fritz.config_flow.socket.gethostbyname",
- return_value=MOCK_IPS["fritz.box"],
+ with (
+ patch(
+ "homeassistant.components.fritz.config_flow.FritzConnection",
+ side_effect=fc_class_mock,
+ ),
+ patch(
+ "homeassistant.components.fritz.common.FritzBoxTools._update_device_info",
+ return_value=MOCK_FIRMWARE_INFO,
+ ),
+ patch(
+ "requests.get",
+ ) as mock_request_get,
+ patch(
+ "requests.post",
+ ) as mock_request_post,
+ patch(
+ "homeassistant.components.fritz.config_flow.socket.gethostbyname",
+ return_value=MOCK_IPS["fritz.box"],
+ ),
):
mock_request_get.return_value.status_code = 200
mock_request_get.return_value.content = MOCK_REQUEST
@@ -207,19 +218,25 @@ async def test_reauth_successful(
mock_config = MockConfigEntry(domain=DOMAIN, data=MOCK_USER_DATA)
mock_config.add_to_hass(hass)
- with patch(
- "homeassistant.components.fritz.config_flow.FritzConnection",
- side_effect=fc_class_mock,
- ), patch(
- "homeassistant.components.fritz.common.FritzBoxTools._update_device_info",
- return_value=MOCK_FIRMWARE_INFO,
- ), patch(
- "homeassistant.components.fritz.async_setup_entry",
- ) as mock_setup_entry, patch(
- "requests.get",
- ) as mock_request_get, patch(
- "requests.post",
- ) as mock_request_post:
+ with (
+ patch(
+ "homeassistant.components.fritz.config_flow.FritzConnection",
+ side_effect=fc_class_mock,
+ ),
+ patch(
+ "homeassistant.components.fritz.common.FritzBoxTools._update_device_info",
+ return_value=MOCK_FIRMWARE_INFO,
+ ),
+ patch(
+ "homeassistant.components.fritz.async_setup_entry",
+ ) as mock_setup_entry,
+ patch(
+ "requests.get",
+ ) as mock_request_get,
+ patch(
+ "requests.post",
+ ) as mock_request_post,
+ ):
mock_request_get.return_value.status_code = 200
mock_request_get.return_value.content = MOCK_REQUEST
mock_request_post.return_value.status_code = 200
@@ -302,12 +319,15 @@ async def test_ssdp_already_configured(
)
mock_config.add_to_hass(hass)
- with patch(
- "homeassistant.components.fritz.config_flow.FritzConnection",
- side_effect=fc_class_mock,
- ), patch(
- "homeassistant.components.fritz.config_flow.socket.gethostbyname",
- return_value=MOCK_IPS["fritz.box"],
+ with (
+ patch(
+ "homeassistant.components.fritz.config_flow.FritzConnection",
+ side_effect=fc_class_mock,
+ ),
+ patch(
+ "homeassistant.components.fritz.config_flow.socket.gethostbyname",
+ return_value=MOCK_IPS["fritz.box"],
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_SSDP}, data=MOCK_SSDP_DATA
@@ -328,12 +348,15 @@ async def test_ssdp_already_configured_host(
)
mock_config.add_to_hass(hass)
- with patch(
- "homeassistant.components.fritz.config_flow.FritzConnection",
- side_effect=fc_class_mock,
- ), patch(
- "homeassistant.components.fritz.config_flow.socket.gethostbyname",
- return_value=MOCK_IPS["fritz.box"],
+ with (
+ patch(
+ "homeassistant.components.fritz.config_flow.FritzConnection",
+ side_effect=fc_class_mock,
+ ),
+ patch(
+ "homeassistant.components.fritz.config_flow.socket.gethostbyname",
+ return_value=MOCK_IPS["fritz.box"],
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_SSDP}, data=MOCK_SSDP_DATA
@@ -354,12 +377,15 @@ async def test_ssdp_already_configured_host_uuid(
)
mock_config.add_to_hass(hass)
- with patch(
- "homeassistant.components.fritz.config_flow.FritzConnection",
- side_effect=fc_class_mock,
- ), patch(
- "homeassistant.components.fritz.config_flow.socket.gethostbyname",
- return_value=MOCK_IPS["fritz.box"],
+ with (
+ patch(
+ "homeassistant.components.fritz.config_flow.FritzConnection",
+ side_effect=fc_class_mock,
+ ),
+ patch(
+ "homeassistant.components.fritz.config_flow.socket.gethostbyname",
+ return_value=MOCK_IPS["fritz.box"],
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_SSDP}, data=MOCK_SSDP_DATA
@@ -394,17 +420,19 @@ async def test_ssdp_already_in_progress_host(
async def test_ssdp(hass: HomeAssistant, fc_class_mock, mock_get_source_ip) -> None:
"""Test starting a flow from discovery."""
- with patch(
- "homeassistant.components.fritz.config_flow.FritzConnection",
- side_effect=fc_class_mock,
- ), patch(
- "homeassistant.components.fritz.common.FritzBoxTools._update_device_info",
- return_value=MOCK_FIRMWARE_INFO,
- ), patch(
- "homeassistant.components.fritz.async_setup_entry"
- ) as mock_setup_entry, patch("requests.get") as mock_request_get, patch(
- "requests.post"
- ) as mock_request_post:
+ with (
+ patch(
+ "homeassistant.components.fritz.config_flow.FritzConnection",
+ side_effect=fc_class_mock,
+ ),
+ patch(
+ "homeassistant.components.fritz.common.FritzBoxTools._update_device_info",
+ return_value=MOCK_FIRMWARE_INFO,
+ ),
+ patch("homeassistant.components.fritz.async_setup_entry") as mock_setup_entry,
+ patch("requests.get") as mock_request_get,
+ patch("requests.post") as mock_request_post,
+ ):
mock_request_get.return_value.status_code = 200
mock_request_get.return_value.content = MOCK_REQUEST
mock_request_post.return_value.status_code = 200
diff --git a/tests/components/fritzbox/conftest.py b/tests/components/fritzbox/conftest.py
index 02a3eed011e..836a8bc127f 100644
--- a/tests/components/fritzbox/conftest.py
+++ b/tests/components/fritzbox/conftest.py
@@ -8,8 +8,9 @@ import pytest
@pytest.fixture(name="fritz")
def fritz_fixture() -> Mock:
"""Patch libraries."""
- with patch("homeassistant.components.fritzbox.Fritzhome") as fritz, patch(
- "homeassistant.components.fritzbox.config_flow.Fritzhome"
+ with (
+ patch("homeassistant.components.fritzbox.Fritzhome") as fritz,
+ patch("homeassistant.components.fritzbox.config_flow.Fritzhome"),
):
fritz.return_value.get_prefixed_host.return_value = "http://1.2.3.4"
yield fritz
diff --git a/tests/components/fritzbox/test_config_flow.py b/tests/components/fritzbox/test_config_flow.py
index cf93e74edac..690082085f8 100644
--- a/tests/components/fritzbox/test_config_flow.py
+++ b/tests/components/fritzbox/test_config_flow.py
@@ -56,9 +56,10 @@ MOCK_SSDP_DATA = {
@pytest.fixture(name="fritz")
def fritz_fixture() -> Mock:
"""Patch libraries."""
- with patch("homeassistant.components.fritzbox.async_setup_entry"), patch(
- "homeassistant.components.fritzbox.config_flow.Fritzhome"
- ) as fritz:
+ with (
+ patch("homeassistant.components.fritzbox.async_setup_entry"),
+ patch("homeassistant.components.fritzbox.config_flow.Fritzhome") as fritz,
+ ):
yield fritz
diff --git a/tests/components/fritzbox_callmonitor/test_config_flow.py b/tests/components/fritzbox_callmonitor/test_config_flow.py
index accdad3a70d..33e2d8fb125 100644
--- a/tests/components/fritzbox_callmonitor/test_config_flow.py
+++ b/tests/components/fritzbox_callmonitor/test_config_flow.py
@@ -93,30 +93,38 @@ async def test_setup_one_phonebook(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.fritzbox_callmonitor.base.FritzPhonebook.__init__",
- return_value=None,
- ), patch(
- "homeassistant.components.fritzbox_callmonitor.base.FritzPhonebook.phonebook_ids",
- new_callable=PropertyMock,
- return_value=[0],
- ), patch(
- "homeassistant.components.fritzbox_callmonitor.base.FritzPhonebook.phonebook_info",
- return_value=MOCK_PHONEBOOK_INFO_1,
- ), patch(
- "homeassistant.components.fritzbox_callmonitor.base.FritzPhonebook.modelname",
- return_value=MOCK_PHONEBOOK_NAME_1,
- ), patch(
- "homeassistant.components.fritzbox_callmonitor.config_flow.FritzConnection.__init__",
- return_value=None,
- ), patch(
- "homeassistant.components.fritzbox_callmonitor.config_flow.FritzConnection.updatecheck",
- new_callable=PropertyMock,
- return_value=MOCK_DEVICE_INFO,
- ), patch(
- "homeassistant.components.fritzbox_callmonitor.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.fritzbox_callmonitor.base.FritzPhonebook.__init__",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.fritzbox_callmonitor.base.FritzPhonebook.phonebook_ids",
+ new_callable=PropertyMock,
+ return_value=[0],
+ ),
+ patch(
+ "homeassistant.components.fritzbox_callmonitor.base.FritzPhonebook.phonebook_info",
+ return_value=MOCK_PHONEBOOK_INFO_1,
+ ),
+ patch(
+ "homeassistant.components.fritzbox_callmonitor.base.FritzPhonebook.modelname",
+ return_value=MOCK_PHONEBOOK_NAME_1,
+ ),
+ patch(
+ "homeassistant.components.fritzbox_callmonitor.config_flow.FritzConnection.__init__",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.fritzbox_callmonitor.config_flow.FritzConnection.updatecheck",
+ new_callable=PropertyMock,
+ return_value=MOCK_DEVICE_INFO,
+ ),
+ patch(
+ "homeassistant.components.fritzbox_callmonitor.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_USER_DATA
)
@@ -136,23 +144,29 @@ async def test_setup_multiple_phonebooks(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.fritzbox_callmonitor.base.FritzPhonebook.__init__",
- return_value=None,
- ), patch(
- "homeassistant.components.fritzbox_callmonitor.base.FritzPhonebook.phonebook_ids",
- new_callable=PropertyMock,
- return_value=[0, 1],
- ), patch(
- "homeassistant.components.fritzbox_callmonitor.config_flow.FritzConnection.__init__",
- return_value=None,
- ), patch(
- "homeassistant.components.fritzbox_callmonitor.config_flow.FritzConnection.updatecheck",
- new_callable=PropertyMock,
- return_value=MOCK_DEVICE_INFO,
- ), patch(
- "homeassistant.components.fritzbox_callmonitor.base.FritzPhonebook.phonebook_info",
- side_effect=[MOCK_PHONEBOOK_INFO_1, MOCK_PHONEBOOK_INFO_2],
+ with (
+ patch(
+ "homeassistant.components.fritzbox_callmonitor.base.FritzPhonebook.__init__",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.fritzbox_callmonitor.base.FritzPhonebook.phonebook_ids",
+ new_callable=PropertyMock,
+ return_value=[0, 1],
+ ),
+ patch(
+ "homeassistant.components.fritzbox_callmonitor.config_flow.FritzConnection.__init__",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.fritzbox_callmonitor.config_flow.FritzConnection.updatecheck",
+ new_callable=PropertyMock,
+ return_value=MOCK_DEVICE_INFO,
+ ),
+ patch(
+ "homeassistant.components.fritzbox_callmonitor.base.FritzPhonebook.phonebook_info",
+ side_effect=[MOCK_PHONEBOOK_INFO_1, MOCK_PHONEBOOK_INFO_2],
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_USER_DATA
@@ -162,13 +176,16 @@ async def test_setup_multiple_phonebooks(hass: HomeAssistant) -> None:
assert result["step_id"] == "phonebook"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.fritzbox_callmonitor.base.FritzPhonebook.modelname",
- return_value=MOCK_PHONEBOOK_NAME_1,
- ), patch(
- "homeassistant.components.fritzbox_callmonitor.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.fritzbox_callmonitor.base.FritzPhonebook.modelname",
+ return_value=MOCK_PHONEBOOK_NAME_1,
+ ),
+ patch(
+ "homeassistant.components.fritzbox_callmonitor.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_PHONEBOOK: MOCK_PHONEBOOK_NAME_2},
diff --git a/tests/components/fronius/test_config_flow.py b/tests/components/fronius/test_config_flow.py
index d0dd32ad801..c09baeb2d22 100644
--- a/tests/components/fronius/test_config_flow.py
+++ b/tests/components/fronius/test_config_flow.py
@@ -52,13 +52,16 @@ async def test_form_with_logger(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with patch(
- "pyfronius.Fronius.current_logger_info",
- return_value=LOGGER_INFO_RETURN_VALUE,
- ), patch(
- "homeassistant.components.fronius.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "pyfronius.Fronius.current_logger_info",
+ return_value=LOGGER_INFO_RETURN_VALUE,
+ ),
+ patch(
+ "homeassistant.components.fronius.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -84,16 +87,20 @@ async def test_form_with_inverter(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with patch(
- "pyfronius.Fronius.current_logger_info",
- side_effect=FroniusError,
- ), patch(
- "pyfronius.Fronius.inverter_info",
- return_value=INVERTER_INFO_RETURN_VALUE,
- ), patch(
- "homeassistant.components.fronius.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "pyfronius.Fronius.current_logger_info",
+ side_effect=FroniusError,
+ ),
+ patch(
+ "pyfronius.Fronius.inverter_info",
+ return_value=INVERTER_INFO_RETURN_VALUE,
+ ),
+ patch(
+ "homeassistant.components.fronius.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -117,12 +124,15 @@ async def test_form_cannot_connect(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "pyfronius.Fronius.current_logger_info",
- side_effect=FroniusError,
- ), patch(
- "pyfronius.Fronius.inverter_info",
- side_effect=FroniusError,
+ with (
+ patch(
+ "pyfronius.Fronius.current_logger_info",
+ side_effect=FroniusError,
+ ),
+ patch(
+ "pyfronius.Fronius.inverter_info",
+ side_effect=FroniusError,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -141,12 +151,15 @@ async def test_form_no_device(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "pyfronius.Fronius.current_logger_info",
- side_effect=FroniusError,
- ), patch(
- "pyfronius.Fronius.inverter_info",
- return_value={"inverters": []},
+ with (
+ patch(
+ "pyfronius.Fronius.current_logger_info",
+ side_effect=FroniusError,
+ ),
+ patch(
+ "pyfronius.Fronius.inverter_info",
+ return_value={"inverters": []},
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -260,11 +273,12 @@ async def test_form_updates_host(
async def test_dhcp(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None:
"""Test starting a flow from discovery."""
- with patch(
- "homeassistant.components.fronius.config_flow.DHCP_REQUEST_DELAY", 0
- ), patch(
- "pyfronius.Fronius.current_logger_info",
- return_value=LOGGER_INFO_RETURN_VALUE,
+ with (
+ patch("homeassistant.components.fronius.config_flow.DHCP_REQUEST_DELAY", 0),
+ patch(
+ "pyfronius.Fronius.current_logger_info",
+ return_value=LOGGER_INFO_RETURN_VALUE,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_DHCP}, data=MOCK_DHCP_DATA
@@ -308,14 +322,16 @@ async def test_dhcp_invalid(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test starting a flow from discovery."""
- with patch(
- "homeassistant.components.fronius.config_flow.DHCP_REQUEST_DELAY", 0
- ), patch(
- "pyfronius.Fronius.current_logger_info",
- side_effect=FroniusError,
- ), patch(
- "pyfronius.Fronius.inverter_info",
- side_effect=FroniusError,
+ with (
+ patch("homeassistant.components.fronius.config_flow.DHCP_REQUEST_DELAY", 0),
+ patch(
+ "pyfronius.Fronius.current_logger_info",
+ side_effect=FroniusError,
+ ),
+ patch(
+ "pyfronius.Fronius.inverter_info",
+ side_effect=FroniusError,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_DHCP}, data=MOCK_DHCP_DATA
diff --git a/tests/components/gardena_bluetooth/conftest.py b/tests/components/gardena_bluetooth/conftest.py
index c840ad9bf77..af882e35751 100644
--- a/tests/components/gardena_bluetooth/conftest.py
+++ b/tests/components/gardena_bluetooth/conftest.py
@@ -101,10 +101,13 @@ def mock_client(
client.read_char_raw.side_effect = _read_char_raw
client.get_all_characteristics_uuid.side_effect = _all_char
- with patch(
- "homeassistant.components.gardena_bluetooth.config_flow.Client",
- return_value=client,
- ), patch("homeassistant.components.gardena_bluetooth.Client", return_value=client):
+ with (
+ patch(
+ "homeassistant.components.gardena_bluetooth.config_flow.Client",
+ return_value=client,
+ ),
+ patch("homeassistant.components.gardena_bluetooth.Client", return_value=client),
+ ):
yield client
diff --git a/tests/components/gardena_bluetooth/test_number.py b/tests/components/gardena_bluetooth/test_number.py
index 0bbe2e926cd..4c053fca0fa 100644
--- a/tests/components/gardena_bluetooth/test_number.py
+++ b/tests/components/gardena_bluetooth/test_number.py
@@ -130,12 +130,12 @@ async def test_bluetooth_error_unavailable(
) -> None:
"""Verify that a connectivity error makes all entities unavailable."""
- mock_read_char_raw[
- Valve.manual_watering_time.uuid
- ] = Valve.manual_watering_time.encode(0)
- mock_read_char_raw[
- Valve.remaining_open_time.uuid
- ] = Valve.remaining_open_time.encode(0)
+ mock_read_char_raw[Valve.manual_watering_time.uuid] = (
+ Valve.manual_watering_time.encode(0)
+ )
+ mock_read_char_raw[Valve.remaining_open_time.uuid] = (
+ Valve.remaining_open_time.encode(0)
+ )
await setup_entry(hass, mock_entry, [Platform.NUMBER])
assert hass.states.get("number.mock_title_remaining_open_time") == snapshot
diff --git a/tests/components/gardena_bluetooth/test_switch.py b/tests/components/gardena_bluetooth/test_switch.py
index 8478788de04..4a29f8f91ae 100644
--- a/tests/components/gardena_bluetooth/test_switch.py
+++ b/tests/components/gardena_bluetooth/test_switch.py
@@ -25,12 +25,12 @@ from tests.common import MockConfigEntry
def mock_switch_chars(mock_read_char_raw):
"""Mock data on device."""
mock_read_char_raw[Valve.state.uuid] = b"\x00"
- mock_read_char_raw[
- Valve.remaining_open_time.uuid
- ] = Valve.remaining_open_time.encode(0)
- mock_read_char_raw[
- Valve.manual_watering_time.uuid
- ] = Valve.manual_watering_time.encode(1000)
+ mock_read_char_raw[Valve.remaining_open_time.uuid] = (
+ Valve.remaining_open_time.encode(0)
+ )
+ mock_read_char_raw[Valve.manual_watering_time.uuid] = (
+ Valve.manual_watering_time.encode(1000)
+ )
return mock_read_char_raw
diff --git a/tests/components/gdacs/test_geo_location.py b/tests/components/gdacs/test_geo_location.py
index 467b6dc2fc4..4ea28bd8fd3 100644
--- a/tests/components/gdacs/test_geo_location.py
+++ b/tests/components/gdacs/test_geo_location.py
@@ -93,9 +93,10 @@ async def test_setup(
# Patching 'utcnow' to gain more control over the timed update.
utcnow = dt_util.utcnow()
- with freeze_time(utcnow), patch(
- "aio_georss_client.feed.GeoRssFeed.update"
- ) as mock_feed_update:
+ with (
+ freeze_time(utcnow),
+ patch("aio_georss_client.feed.GeoRssFeed.update") as mock_feed_update,
+ ):
mock_feed_update.return_value = "OK", [mock_entry_1, mock_entry_2, mock_entry_3]
config_entry.add_to_hass(hass)
@@ -227,10 +228,10 @@ async def test_setup_imperial(
# Patching 'utcnow' to gain more control over the timed update.
utcnow = dt_util.utcnow()
- with freeze_time(utcnow), patch(
- "aio_georss_client.feed.GeoRssFeed.update"
- ) as mock_feed_update, patch(
- "aio_georss_client.feed.GeoRssFeed.last_timestamp", create=True
+ with (
+ freeze_time(utcnow),
+ patch("aio_georss_client.feed.GeoRssFeed.update") as mock_feed_update,
+ patch("aio_georss_client.feed.GeoRssFeed.last_timestamp", create=True),
):
mock_feed_update.return_value = "OK", [mock_entry_1]
config_entry.add_to_hass(hass)
diff --git a/tests/components/gdacs/test_sensor.py b/tests/components/gdacs/test_sensor.py
index a21df176bdd..87b66295006 100644
--- a/tests/components/gdacs/test_sensor.py
+++ b/tests/components/gdacs/test_sensor.py
@@ -57,9 +57,10 @@ async def test_setup(hass: HomeAssistant) -> None:
# Patching 'utcnow' to gain more control over the timed update.
utcnow = dt_util.utcnow()
- with freeze_time(utcnow), patch(
- "aio_georss_client.feed.GeoRssFeed.update"
- ) as mock_feed_update:
+ with (
+ freeze_time(utcnow),
+ patch("aio_georss_client.feed.GeoRssFeed.update") as mock_feed_update,
+ ):
mock_feed_update.return_value = "OK", [mock_entry_1, mock_entry_2, mock_entry_3]
latitude = 32.87336
longitude = -117.22743
diff --git a/tests/components/generic/test_camera.py b/tests/components/generic/test_camera.py
index ac882716103..e359ddaca9d 100644
--- a/tests/components/generic/test_camera.py
+++ b/tests/components/generic/test_camera.py
@@ -273,8 +273,9 @@ async def test_limit_refetch(
hass.states.async_set("sensor.temp", "5")
- with pytest.raises(aiohttp.ServerTimeoutError), patch(
- "asyncio.timeout", side_effect=TimeoutError()
+ with (
+ pytest.raises(aiohttp.ServerTimeoutError),
+ patch("asyncio.timeout", side_effect=TimeoutError()),
):
resp = await client.get("/api/camera_proxy/camera.config_test")
diff --git a/tests/components/generic/test_config_flow.py b/tests/components/generic/test_config_flow.py
index 7eee5f1bd9e..d9b3c848eb6 100644
--- a/tests/components/generic/test_config_flow.py
+++ b/tests/components/generic/test_config_flow.py
@@ -74,9 +74,12 @@ async def test_form(
"""Test the form with a normal set of settings."""
respx.get("http://127.0.0.1/testurl/1").respond(stream=fakeimgbytes_png)
- with mock_create_stream as mock_setup, patch(
- "homeassistant.components.generic.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ mock_create_stream as mock_setup,
+ patch(
+ "homeassistant.components.generic.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
result1 = await hass.config_entries.flow.async_configure(
user_flow["flow_id"],
TESTDATA,
@@ -187,10 +190,13 @@ async def test_form_still_preview_cam_off(
hass_client: ClientSessionGenerator,
) -> None:
"""Test camera errors are triggered during preview."""
- with patch(
- "homeassistant.components.generic.camera.GenericCamera.is_on",
- new_callable=PropertyMock(return_value=False),
- ), mock_create_stream:
+ with (
+ patch(
+ "homeassistant.components.generic.camera.GenericCamera.is_on",
+ new_callable=PropertyMock(return_value=False),
+ ),
+ mock_create_stream,
+ ):
result1 = await hass.config_entries.flow.async_configure(
user_flow["flow_id"],
TESTDATA,
@@ -358,8 +364,9 @@ async def test_form_rtsp_mode(
data = TESTDATA.copy()
data[CONF_RTSP_TRANSPORT] = "tcp"
data[CONF_STREAM_SOURCE] = "rtsp://127.0.0.1/testurl/2"
- with mock_create_stream as mock_setup, patch(
- "homeassistant.components.generic.async_setup_entry", return_value=True
+ with (
+ mock_create_stream as mock_setup,
+ patch("homeassistant.components.generic.async_setup_entry", return_value=True),
):
result1 = await hass.config_entries.flow.async_configure(
user_flow["flow_id"], data
@@ -640,10 +647,13 @@ async def test_form_stream_io_error(
@respx.mock
async def test_form_oserror(hass: HomeAssistant, fakeimg_png, user_flow) -> None:
"""Test we handle OS error when setting up stream."""
- with patch(
- "homeassistant.components.generic.config_flow.create_stream",
- side_effect=OSError("Some other OSError"),
- ), pytest.raises(OSError):
+ with (
+ patch(
+ "homeassistant.components.generic.config_flow.create_stream",
+ side_effect=OSError("Some other OSError"),
+ ),
+ pytest.raises(OSError),
+ ):
await hass.config_entries.flow.async_configure(
user_flow["flow_id"],
TESTDATA,
@@ -878,9 +888,10 @@ async def test_use_wallclock_as_timestamps_option(
)
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "init"
- with patch(
- "homeassistant.components.generic.async_setup_entry", return_value=True
- ), mock_create_stream:
+ with (
+ patch("homeassistant.components.generic.async_setup_entry", return_value=True),
+ mock_create_stream,
+ ):
result2 = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input={CONF_USE_WALLCLOCK_AS_TIMESTAMPS: True, **TESTDATA},
@@ -892,9 +903,10 @@ async def test_use_wallclock_as_timestamps_option(
)
assert result3["type"] == FlowResultType.FORM
assert result3["step_id"] == "init"
- with patch(
- "homeassistant.components.generic.async_setup_entry", return_value=True
- ), mock_create_stream:
+ with (
+ patch("homeassistant.components.generic.async_setup_entry", return_value=True),
+ mock_create_stream,
+ ):
result4 = await hass.config_entries.options.async_configure(
result3["flow_id"],
user_input={CONF_USE_WALLCLOCK_AS_TIMESTAMPS: True, **TESTDATA},
diff --git a/tests/components/geo_json_events/test_geo_location.py b/tests/components/geo_json_events/test_geo_location.py
index ac9f3f2347f..365c4ca27bc 100644
--- a/tests/components/geo_json_events/test_geo_location.py
+++ b/tests/components/geo_json_events/test_geo_location.py
@@ -66,9 +66,10 @@ async def test_entity_lifecycle(
mock_entry_4 = _generate_mock_feed_entry("4567", "Title 4", 12.5, (-31.3, 150.3))
utcnow = dt_util.utcnow()
- with freeze_time(utcnow), patch(
- "aio_geojson_client.feed.GeoJsonFeed.update"
- ) as mock_feed_update:
+ with (
+ freeze_time(utcnow),
+ patch("aio_geojson_client.feed.GeoJsonFeed.update") as mock_feed_update,
+ ):
mock_feed_update.return_value = "OK", [mock_entry_1, mock_entry_2, mock_entry_3]
# Load config entry.
diff --git a/tests/components/geonetnz_quakes/test_config_flow.py b/tests/components/geonetnz_quakes/test_config_flow.py
index 75e595c9900..d4b406cf054 100644
--- a/tests/components/geonetnz_quakes/test_config_flow.py
+++ b/tests/components/geonetnz_quakes/test_config_flow.py
@@ -52,9 +52,15 @@ async def test_step_import(hass: HomeAssistant) -> None:
CONF_MINIMUM_MAGNITUDE: 2.5,
}
- with patch(
- "homeassistant.components.geonetnz_quakes.async_setup_entry", return_value=True
- ), patch("homeassistant.components.geonetnz_quakes.async_setup", return_value=True):
+ with (
+ patch(
+ "homeassistant.components.geonetnz_quakes.async_setup_entry",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.geonetnz_quakes.async_setup", return_value=True
+ ),
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=conf
)
@@ -77,9 +83,15 @@ async def test_step_user(hass: HomeAssistant) -> None:
hass.config.longitude = 174.7
conf = {CONF_RADIUS: 25, CONF_MMI: 4}
- with patch(
- "homeassistant.components.geonetnz_quakes.async_setup_entry", return_value=True
- ), patch("homeassistant.components.geonetnz_quakes.async_setup", return_value=True):
+ with (
+ patch(
+ "homeassistant.components.geonetnz_quakes.async_setup_entry",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.geonetnz_quakes.async_setup", return_value=True
+ ),
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}, data=conf
)
diff --git a/tests/components/geonetnz_quakes/test_geo_location.py b/tests/components/geonetnz_quakes/test_geo_location.py
index 19f1954d06a..163bca775c9 100644
--- a/tests/components/geonetnz_quakes/test_geo_location.py
+++ b/tests/components/geonetnz_quakes/test_geo_location.py
@@ -183,8 +183,9 @@ async def test_setup_imperial(
# Patching 'utcnow' to gain more control over the timed update.
freezer.move_to(dt_util.utcnow())
- with patch("aio_geojson_client.feed.GeoJsonFeed.update") as mock_feed_update, patch(
- "aio_geojson_client.feed.GeoJsonFeed.last_timestamp", create=True
+ with (
+ patch("aio_geojson_client.feed.GeoJsonFeed.update") as mock_feed_update,
+ patch("aio_geojson_client.feed.GeoJsonFeed.last_timestamp", create=True),
):
mock_feed_update.return_value = "OK", [mock_entry_1]
assert await async_setup_component(hass, geonetnz_quakes.DOMAIN, CONFIG)
diff --git a/tests/components/geonetnz_quakes/test_sensor.py b/tests/components/geonetnz_quakes/test_sensor.py
index 02edfc910b2..82143baa374 100644
--- a/tests/components/geonetnz_quakes/test_sensor.py
+++ b/tests/components/geonetnz_quakes/test_sensor.py
@@ -58,9 +58,10 @@ async def test_setup(hass: HomeAssistant) -> None:
# Patching 'utcnow' to gain more control over the timed update.
utcnow = dt_util.utcnow()
- with freeze_time(utcnow), patch(
- "aio_geojson_client.feed.GeoJsonFeed.update"
- ) as mock_feed_update:
+ with (
+ freeze_time(utcnow),
+ patch("aio_geojson_client.feed.GeoJsonFeed.update") as mock_feed_update,
+ ):
mock_feed_update.return_value = "OK", [mock_entry_1, mock_entry_2, mock_entry_3]
assert await async_setup_component(hass, geonetnz_quakes.DOMAIN, CONFIG)
# Artificially trigger update and collect events.
diff --git a/tests/components/geonetnz_volcano/test_config_flow.py b/tests/components/geonetnz_volcano/test_config_flow.py
index 6bc211e72be..e314896dd6b 100644
--- a/tests/components/geonetnz_volcano/test_config_flow.py
+++ b/tests/components/geonetnz_volcano/test_config_flow.py
@@ -51,10 +51,14 @@ async def test_step_import(hass: HomeAssistant) -> None:
flow = config_flow.GeonetnzVolcanoFlowHandler()
flow.hass = hass
- with patch(
- "homeassistant.components.geonetnz_volcano.async_setup_entry", return_value=True
- ), patch(
- "homeassistant.components.geonetnz_volcano.async_setup", return_value=True
+ with (
+ patch(
+ "homeassistant.components.geonetnz_volcano.async_setup_entry",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.geonetnz_volcano.async_setup", return_value=True
+ ),
):
result = await flow.async_step_import(import_config=conf)
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
@@ -77,10 +81,14 @@ async def test_step_user(hass: HomeAssistant) -> None:
flow = config_flow.GeonetnzVolcanoFlowHandler()
flow.hass = hass
- with patch(
- "homeassistant.components.geonetnz_volcano.async_setup_entry", return_value=True
- ), patch(
- "homeassistant.components.geonetnz_volcano.async_setup", return_value=True
+ with (
+ patch(
+ "homeassistant.components.geonetnz_volcano.async_setup_entry",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.geonetnz_volcano.async_setup", return_value=True
+ ),
):
result = await flow.async_step_user(user_input=conf)
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
diff --git a/tests/components/geonetnz_volcano/test_sensor.py b/tests/components/geonetnz_volcano/test_sensor.py
index f97b89053fd..d6ebbcd6582 100644
--- a/tests/components/geonetnz_volcano/test_sensor.py
+++ b/tests/components/geonetnz_volcano/test_sensor.py
@@ -54,9 +54,12 @@ async def test_setup(hass: HomeAssistant) -> None:
# Patching 'utcnow' to gain more control over the timed update.
utcnow = dt_util.utcnow()
- with freeze_time(utcnow), patch(
- "aio_geojson_client.feed.GeoJsonFeed.update", new_callable=AsyncMock
- ) as mock_feed_update:
+ with (
+ freeze_time(utcnow),
+ patch(
+ "aio_geojson_client.feed.GeoJsonFeed.update", new_callable=AsyncMock
+ ) as mock_feed_update,
+ ):
mock_feed_update.return_value = "OK", [mock_entry_1, mock_entry_2, mock_entry_3]
assert await async_setup_component(hass, geonetnz_volcano.DOMAIN, CONFIG)
# Artificially trigger update and collect events.
@@ -161,11 +164,12 @@ async def test_setup_imperial(
# Patching 'utcnow' to gain more control over the timed update.
freezer.move_to(dt_util.utcnow())
- with patch(
- "aio_geojson_client.feed.GeoJsonFeed.update", new_callable=AsyncMock
- ) as mock_feed_update, patch(
- "aio_geojson_client.feed.GeoJsonFeed.__init__"
- ) as mock_feed_init:
+ with (
+ patch(
+ "aio_geojson_client.feed.GeoJsonFeed.update", new_callable=AsyncMock
+ ) as mock_feed_update,
+ patch("aio_geojson_client.feed.GeoJsonFeed.__init__") as mock_feed_init,
+ ):
mock_feed_update.return_value = "OK", [mock_entry_1]
assert await async_setup_component(hass, geonetnz_volcano.DOMAIN, CONFIG)
# Artificially trigger update and collect events.
diff --git a/tests/components/gios/__init__.py b/tests/components/gios/__init__.py
index 482b58ad7ad..d5c43c8acc0 100644
--- a/tests/components/gios/__init__.py
+++ b/tests/components/gios/__init__.py
@@ -35,17 +35,22 @@ async def init_integration(
if invalid_indexes:
indexes = {}
- with patch(
- "homeassistant.components.gios.Gios._get_stations", return_value=STATIONS
- ), patch(
- "homeassistant.components.gios.Gios._get_station",
- return_value=station,
- ), patch(
- "homeassistant.components.gios.Gios._get_all_sensors",
- return_value=sensors,
- ), patch(
- "homeassistant.components.gios.Gios._get_indexes",
- return_value=indexes,
+ with (
+ patch(
+ "homeassistant.components.gios.Gios._get_stations", return_value=STATIONS
+ ),
+ patch(
+ "homeassistant.components.gios.Gios._get_station",
+ return_value=station,
+ ),
+ patch(
+ "homeassistant.components.gios.Gios._get_all_sensors",
+ return_value=sensors,
+ ),
+ patch(
+ "homeassistant.components.gios.Gios._get_indexes",
+ return_value=indexes,
+ ),
):
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
diff --git a/tests/components/gios/test_config_flow.py b/tests/components/gios/test_config_flow.py
index a735b45975a..4471cfa64ec 100644
--- a/tests/components/gios/test_config_flow.py
+++ b/tests/components/gios/test_config_flow.py
@@ -50,14 +50,18 @@ async def test_invalid_station_id(hass: HomeAssistant) -> None:
async def test_invalid_sensor_data(hass: HomeAssistant) -> None:
"""Test that errors are shown when sensor data is invalid."""
- with patch(
- "homeassistant.components.gios.Gios._get_stations", return_value=STATIONS
- ), patch(
- "homeassistant.components.gios.Gios._get_station",
- return_value=json.loads(load_fixture("gios/station.json")),
- ), patch(
- "homeassistant.components.gios.Gios._get_sensor",
- return_value={},
+ with (
+ patch(
+ "homeassistant.components.gios.Gios._get_stations", return_value=STATIONS
+ ),
+ patch(
+ "homeassistant.components.gios.Gios._get_station",
+ return_value=json.loads(load_fixture("gios/station.json")),
+ ),
+ patch(
+ "homeassistant.components.gios.Gios._get_sensor",
+ return_value={},
+ ),
):
flow = config_flow.GiosFlowHandler()
flow.hass = hass
@@ -84,18 +88,23 @@ async def test_cannot_connect(hass: HomeAssistant) -> None:
async def test_create_entry(hass: HomeAssistant) -> None:
"""Test that the user step works."""
- with patch(
- "homeassistant.components.gios.Gios._get_stations",
- return_value=STATIONS,
- ), patch(
- "homeassistant.components.gios.Gios._get_station",
- return_value=json.loads(load_fixture("gios/station.json")),
- ), patch(
- "homeassistant.components.gios.Gios._get_all_sensors",
- return_value=json.loads(load_fixture("gios/sensors.json")),
- ), patch(
- "homeassistant.components.gios.Gios._get_indexes",
- return_value=json.loads(load_fixture("gios/indexes.json")),
+ with (
+ patch(
+ "homeassistant.components.gios.Gios._get_stations",
+ return_value=STATIONS,
+ ),
+ patch(
+ "homeassistant.components.gios.Gios._get_station",
+ return_value=json.loads(load_fixture("gios/station.json")),
+ ),
+ patch(
+ "homeassistant.components.gios.Gios._get_all_sensors",
+ return_value=json.loads(load_fixture("gios/sensors.json")),
+ ),
+ patch(
+ "homeassistant.components.gios.Gios._get_indexes",
+ return_value=json.loads(load_fixture("gios/indexes.json")),
+ ),
):
flow = config_flow.GiosFlowHandler()
flow.hass = hass
diff --git a/tests/components/gios/test_init.py b/tests/components/gios/test_init.py
index 6082fa8c522..e5f3454bcd9 100644
--- a/tests/components/gios/test_init.py
+++ b/tests/components/gios/test_init.py
@@ -75,15 +75,20 @@ async def test_migrate_device_and_config_entry(
station = json.loads(load_fixture("gios/station.json"))
sensors = json.loads(load_fixture("gios/sensors.json"))
- with patch(
- "homeassistant.components.gios.Gios._get_stations", return_value=STATIONS
- ), patch(
- "homeassistant.components.gios.Gios._get_station",
- return_value=station,
- ), patch(
- "homeassistant.components.gios.Gios._get_all_sensors",
- return_value=sensors,
- ), patch("homeassistant.components.gios.Gios._get_indexes", return_value=indexes):
+ with (
+ patch(
+ "homeassistant.components.gios.Gios._get_stations", return_value=STATIONS
+ ),
+ patch(
+ "homeassistant.components.gios.Gios._get_station",
+ return_value=station,
+ ),
+ patch(
+ "homeassistant.components.gios.Gios._get_all_sensors",
+ return_value=sensors,
+ ),
+ patch("homeassistant.components.gios.Gios._get_indexes", return_value=indexes),
+ ):
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
diff --git a/tests/components/gios/test_sensor.py b/tests/components/gios/test_sensor.py
index 6714882ad3f..60e8722ba24 100644
--- a/tests/components/gios/test_sensor.py
+++ b/tests/components/gios/test_sensor.py
@@ -293,12 +293,15 @@ async def test_availability(hass: HomeAssistant) -> None:
incomplete_sensors = deepcopy(sensors)
incomplete_sensors["pm2.5"] = {}
future = utcnow() + timedelta(minutes=120)
- with patch(
- "homeassistant.components.gios.Gios._get_all_sensors",
- return_value=incomplete_sensors,
- ), patch(
- "homeassistant.components.gios.Gios._get_indexes",
- return_value={},
+ with (
+ patch(
+ "homeassistant.components.gios.Gios._get_all_sensors",
+ return_value=incomplete_sensors,
+ ),
+ patch(
+ "homeassistant.components.gios.Gios._get_indexes",
+ return_value={},
+ ),
):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
@@ -319,11 +322,14 @@ async def test_availability(hass: HomeAssistant) -> None:
assert state.state == STATE_UNAVAILABLE
future = utcnow() + timedelta(minutes=180)
- with patch(
- "homeassistant.components.gios.Gios._get_all_sensors", return_value=sensors
- ), patch(
- "homeassistant.components.gios.Gios._get_indexes",
- return_value=indexes,
+ with (
+ patch(
+ "homeassistant.components.gios.Gios._get_all_sensors", return_value=sensors
+ ),
+ patch(
+ "homeassistant.components.gios.Gios._get_indexes",
+ return_value=indexes,
+ ),
):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
diff --git a/tests/components/gogogate2/test_init.py b/tests/components/gogogate2/test_init.py
index abc7e4a2326..f7e58296a43 100644
--- a/tests/components/gogogate2/test_init.py
+++ b/tests/components/gogogate2/test_init.py
@@ -92,8 +92,11 @@ async def test_api_failure_on_startup(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.gogogate2.common.ISmartGateApi.async_info",
- side_effect=TimeoutError,
- ), pytest.raises(ConfigEntryNotReady):
+ with (
+ patch(
+ "homeassistant.components.gogogate2.common.ISmartGateApi.async_info",
+ side_effect=TimeoutError,
+ ),
+ pytest.raises(ConfigEntryNotReady),
+ ):
await async_setup_entry(hass, config_entry)
diff --git a/tests/components/goodwe/test_config_flow.py b/tests/components/goodwe/test_config_flow.py
index b1aabe0be09..0d0a1249ea1 100644
--- a/tests/components/goodwe/test_config_flow.py
+++ b/tests/components/goodwe/test_config_flow.py
@@ -36,12 +36,15 @@ async def test_manual_setup(hass: HomeAssistant) -> None:
assert result["step_id"] == "user"
assert not result["errors"]
- with patch(
- "homeassistant.components.goodwe.config_flow.connect",
- return_value=mock_inverter(),
- ), patch(
- "homeassistant.components.goodwe.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.goodwe.config_flow.connect",
+ return_value=mock_inverter(),
+ ),
+ patch(
+ "homeassistant.components.goodwe.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: TEST_HOST}
)
@@ -69,10 +72,13 @@ async def test_manual_setup_already_exists(hass: HomeAssistant) -> None:
assert result["step_id"] == "user"
assert not result["errors"]
- with patch(
- "homeassistant.components.goodwe.config_flow.connect",
- return_value=mock_inverter(),
- ), patch("homeassistant.components.goodwe.async_setup_entry", return_value=True):
+ with (
+ patch(
+ "homeassistant.components.goodwe.config_flow.connect",
+ return_value=mock_inverter(),
+ ),
+ patch("homeassistant.components.goodwe.async_setup_entry", return_value=True),
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: TEST_HOST}
)
diff --git a/tests/components/google_assistant/test_http.py b/tests/components/google_assistant/test_http.py
index cc1332a372b..1dac75875a6 100644
--- a/tests/components/google_assistant/test_http.py
+++ b/tests/components/google_assistant/test_http.py
@@ -99,13 +99,17 @@ async def test_update_access_token(hass: HomeAssistant) -> None:
await config.async_initialize()
base_time = datetime(2019, 10, 14, tzinfo=UTC)
- with patch(
- "homeassistant.components.google_assistant.http._get_homegraph_token"
- ) as mock_get_token, patch(
- "homeassistant.components.google_assistant.http._get_homegraph_jwt"
- ) as mock_get_jwt, patch(
- "homeassistant.core.dt_util.utcnow",
- ) as mock_utcnow:
+ with (
+ patch(
+ "homeassistant.components.google_assistant.http._get_homegraph_token"
+ ) as mock_get_token,
+ patch(
+ "homeassistant.components.google_assistant.http._get_homegraph_jwt"
+ ) as mock_get_jwt,
+ patch(
+ "homeassistant.core.dt_util.utcnow",
+ ) as mock_utcnow,
+ ):
mock_utcnow.return_value = base_time
mock_get_jwt.return_value = jwt
mock_get_token.return_value = MOCK_TOKEN
diff --git a/tests/components/google_assistant/test_report_state.py b/tests/components/google_assistant/test_report_state.py
index a4829e6140f..758ebf63db9 100644
--- a/tests/components/google_assistant/test_report_state.py
+++ b/tests/components/google_assistant/test_report_state.py
@@ -27,9 +27,12 @@ async def test_report_state(
"event.doorbell", "unknown", attributes={"device_class": "doorbell"}
)
- with patch.object(
- BASIC_CONFIG, "async_report_state_all", AsyncMock()
- ) as mock_report, patch.object(report_state, "INITIAL_REPORT_DELAY", 0):
+ with (
+ patch.object(
+ BASIC_CONFIG, "async_report_state_all", AsyncMock()
+ ) as mock_report,
+ patch.object(report_state, "INITIAL_REPORT_DELAY", 0),
+ ):
unsub = report_state.async_enable_report_state(hass, BASIC_CONFIG)
async_fire_time_changed(hass, utcnow())
@@ -74,10 +77,15 @@ async def test_report_state(
}
# Test that if serialize returns same value, we don't send
- with patch(
- "homeassistant.components.google_assistant.helpers.GoogleEntity.query_serialize",
- return_value={"same": "info"},
- ), patch.object(BASIC_CONFIG, "async_report_state_all", AsyncMock()) as mock_report:
+ with (
+ patch(
+ "homeassistant.components.google_assistant.helpers.GoogleEntity.query_serialize",
+ return_value={"same": "info"},
+ ),
+ patch.object(
+ BASIC_CONFIG, "async_report_state_all", AsyncMock()
+ ) as mock_report,
+ ):
# New state, so reported
hass.states.async_set("light.double_report", "on")
await hass.async_block_till_done()
@@ -107,11 +115,14 @@ async def test_report_state(
assert len(mock_report.mock_calls) == 0
# Test that entities that we can't query don't report a state
- with patch.object(
- BASIC_CONFIG, "async_report_state_all", AsyncMock()
- ) as mock_report, patch(
- "homeassistant.components.google_assistant.helpers.GoogleEntity.query_serialize",
- side_effect=error.SmartHomeError("mock-error", "mock-msg"),
+ with (
+ patch.object(
+ BASIC_CONFIG, "async_report_state_all", AsyncMock()
+ ) as mock_report,
+ patch(
+ "homeassistant.components.google_assistant.helpers.GoogleEntity.query_serialize",
+ side_effect=error.SmartHomeError("mock-error", "mock-msg"),
+ ),
):
hass.states.async_set("light.kitchen", "off")
async_fire_time_changed(
@@ -148,9 +159,10 @@ async def test_report_notifications(
"event.doorbell", "unknown", attributes={"device_class": "doorbell"}
)
- with patch.object(
- config, "async_report_state_all", AsyncMock()
- ) as mock_report, patch.object(report_state, "INITIAL_REPORT_DELAY", 0):
+ with (
+ patch.object(config, "async_report_state_all", AsyncMock()) as mock_report,
+ patch.object(report_state, "INITIAL_REPORT_DELAY", 0),
+ ):
report_state.async_enable_report_state(hass, config)
async_fire_time_changed(
@@ -243,9 +255,12 @@ async def test_report_notifications(
# Test disconnecting agent user
caplog.clear()
- with patch.object(
- config, "async_report_state", return_value=HTTPStatus.NOT_FOUND
- ) as mock_report_state, patch.object(config, "async_disconnect_agent_user"):
+ with (
+ patch.object(
+ config, "async_report_state", return_value=HTTPStatus.NOT_FOUND
+ ) as mock_report_state,
+ patch.object(config, "async_disconnect_agent_user"),
+ ):
event_time = datetime.fromisoformat("2023-08-01T01:03:57+00:00")
epoc_event_time = event_time.timestamp()
hass.states.async_set(
diff --git a/tests/components/google_generative_ai_conversation/test_config_flow.py b/tests/components/google_generative_ai_conversation/test_config_flow.py
index bff560dfb29..6ae42a350e6 100644
--- a/tests/components/google_generative_ai_conversation/test_config_flow.py
+++ b/tests/components/google_generative_ai_conversation/test_config_flow.py
@@ -39,12 +39,15 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with patch(
- "homeassistant.components.google_generative_ai_conversation.config_flow.genai.list_models",
- ), patch(
- "homeassistant.components.google_generative_ai_conversation.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.google_generative_ai_conversation.config_flow.genai.list_models",
+ ),
+ patch(
+ "homeassistant.components.google_generative_ai_conversation.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
diff --git a/tests/components/google_generative_ai_conversation/test_init.py b/tests/components/google_generative_ai_conversation/test_init.py
index bcf0600373f..b77fa14b4cf 100644
--- a/tests/components/google_generative_ai_conversation/test_init.py
+++ b/tests/components/google_generative_ai_conversation/test_init.py
@@ -130,9 +130,12 @@ async def test_template_error(
"prompt": "talk like a {% if True %}smarthome{% else %}pirate please.",
},
)
- with patch(
- "google.generativeai.get_model",
- ), patch("google.generativeai.GenerativeModel"):
+ with (
+ patch(
+ "google.generativeai.get_model",
+ ),
+ patch("google.generativeai.GenerativeModel"),
+ ):
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
result = await conversation.async_converse(
@@ -198,11 +201,14 @@ async def test_generate_content_service_with_image(
"A mail carrier is at your front door delivering a package"
)
- with patch("google.generativeai.GenerativeModel") as mock_model, patch(
- "homeassistant.components.google_generative_ai_conversation.Path.read_bytes",
- return_value=b"image bytes",
- ), patch("pathlib.Path.exists", return_value=True), patch.object(
- hass.config, "is_allowed_path", return_value=True
+ with (
+ patch("google.generativeai.GenerativeModel") as mock_model,
+ patch(
+ "homeassistant.components.google_generative_ai_conversation.Path.read_bytes",
+ return_value=b"image bytes",
+ ),
+ patch("pathlib.Path.exists", return_value=True),
+ patch.object(hass.config, "is_allowed_path", return_value=True),
):
mock_response = MagicMock()
mock_response.text = stubbed_generated_content
@@ -232,8 +238,11 @@ async def test_generate_content_service_error(
mock_config_entry: MockConfigEntry,
) -> None:
"""Test generate content service handles errors."""
- with patch("google.generativeai.GenerativeModel") as mock_model, pytest.raises(
- HomeAssistantError, match="Error generating content: None reason"
+ with (
+ patch("google.generativeai.GenerativeModel") as mock_model,
+ pytest.raises(
+ HomeAssistantError, match="Error generating content: None reason"
+ ),
):
mock_model.return_value.generate_content_async = AsyncMock(
side_effect=ClientError("reason")
@@ -254,14 +263,16 @@ async def test_generate_content_service_with_image_not_allowed_path(
snapshot: SnapshotAssertion,
) -> None:
"""Test generate content service with an image in a not allowed path."""
- with patch("pathlib.Path.exists", return_value=True), patch.object(
- hass.config, "is_allowed_path", return_value=False
- ), pytest.raises(
- HomeAssistantError,
- match=(
- "Cannot read `doorbell_snapshot.jpg`, no access to path; "
- "`allowlist_external_dirs` may need to be adjusted in "
- "`configuration.yaml`"
+ with (
+ patch("pathlib.Path.exists", return_value=True),
+ patch.object(hass.config, "is_allowed_path", return_value=False),
+ pytest.raises(
+ HomeAssistantError,
+ match=(
+ "Cannot read `doorbell_snapshot.jpg`, no access to path; "
+ "`allowlist_external_dirs` may need to be adjusted in "
+ "`configuration.yaml`"
+ ),
),
):
await hass.services.async_call(
@@ -283,10 +294,13 @@ async def test_generate_content_service_with_image_not_exists(
snapshot: SnapshotAssertion,
) -> None:
"""Test generate content service with an image that does not exist."""
- with patch("pathlib.Path.exists", return_value=True), patch.object(
- hass.config, "is_allowed_path", return_value=True
- ), patch("pathlib.Path.exists", return_value=False), pytest.raises(
- HomeAssistantError, match="`doorbell_snapshot.jpg` does not exist"
+ with (
+ patch("pathlib.Path.exists", return_value=True),
+ patch.object(hass.config, "is_allowed_path", return_value=True),
+ patch("pathlib.Path.exists", return_value=False),
+ pytest.raises(
+ HomeAssistantError, match="`doorbell_snapshot.jpg` does not exist"
+ ),
):
await hass.services.async_call(
"google_generative_ai_conversation",
@@ -307,10 +321,13 @@ async def test_generate_content_service_with_non_image(
snapshot: SnapshotAssertion,
) -> None:
"""Test generate content service with a non image."""
- with patch("pathlib.Path.exists", return_value=True), patch.object(
- hass.config, "is_allowed_path", return_value=True
- ), patch("pathlib.Path.exists", return_value=True), pytest.raises(
- HomeAssistantError, match="`doorbell_snapshot.mp4` is not an image"
+ with (
+ patch("pathlib.Path.exists", return_value=True),
+ patch.object(hass.config, "is_allowed_path", return_value=True),
+ patch("pathlib.Path.exists", return_value=True),
+ pytest.raises(
+ HomeAssistantError, match="`doorbell_snapshot.mp4` is not an image"
+ ),
):
await hass.services.async_call(
"google_generative_ai_conversation",
diff --git a/tests/components/google_mail/test_config_flow.py b/tests/components/google_mail/test_config_flow.py
index 6456e38b3fc..62db6603988 100644
--- a/tests/components/google_mail/test_config_flow.py
+++ b/tests/components/google_mail/test_config_flow.py
@@ -46,13 +46,16 @@ async def test_full_flow(
assert resp.status == 200
assert resp.headers["content-type"] == "text/html; charset=utf-8"
- with patch(
- "homeassistant.components.google_mail.async_setup_entry", return_value=True
- ) as mock_setup, patch(
- "httplib2.Http.request",
- return_value=(
- Response({}),
- bytes(load_fixture("google_mail/get_profile.json"), encoding="UTF-8"),
+ with (
+ patch(
+ "homeassistant.components.google_mail.async_setup_entry", return_value=True
+ ) as mock_setup,
+ patch(
+ "httplib2.Http.request",
+ return_value=(
+ Response({}),
+ bytes(load_fixture("google_mail/get_profile.json"), encoding="UTF-8"),
+ ),
),
):
result = await hass.config_entries.flow.async_configure(result["flow_id"])
@@ -141,13 +144,16 @@ async def test_reauth(
},
)
- with patch(
- "homeassistant.components.google_mail.async_setup_entry", return_value=True
- ) as mock_setup, patch(
- "httplib2.Http.request",
- return_value=(
- Response({}),
- bytes(load_fixture(f"google_mail/{fixture}.json"), encoding="UTF-8"),
+ with (
+ patch(
+ "homeassistant.components.google_mail.async_setup_entry", return_value=True
+ ) as mock_setup,
+ patch(
+ "httplib2.Http.request",
+ return_value=(
+ Response({}),
+ bytes(load_fixture(f"google_mail/{fixture}.json"), encoding="UTF-8"),
+ ),
),
):
result = await hass.config_entries.flow.async_configure(result["flow_id"])
diff --git a/tests/components/google_sheets/test_init.py b/tests/components/google_sheets/test_init.py
index 8f7ce7603e8..f474e44e925 100644
--- a/tests/components/google_sheets/test_init.py
+++ b/tests/components/google_sheets/test_init.py
@@ -229,9 +229,12 @@ async def test_append_sheet_api_error(
response = Response()
response.status_code = 503
- with pytest.raises(HomeAssistantError), patch(
- "homeassistant.components.google_sheets.Client.request",
- side_effect=APIError(response),
+ with (
+ pytest.raises(HomeAssistantError),
+ patch(
+ "homeassistant.components.google_sheets.Client.request",
+ side_effect=APIError(response),
+ ),
):
await hass.services.async_call(
DOMAIN,
diff --git a/tests/components/google_tasks/test_config_flow.py b/tests/components/google_tasks/test_config_flow.py
index e92da605697..d7ad21292fc 100644
--- a/tests/components/google_tasks/test_config_flow.py
+++ b/tests/components/google_tasks/test_config_flow.py
@@ -63,9 +63,12 @@ async def test_full_flow(
},
)
- with patch(
- "homeassistant.components.google_tasks.async_setup_entry", return_value=True
- ) as mock_setup, patch("homeassistant.components.google_tasks.config_flow.build"):
+ with (
+ patch(
+ "homeassistant.components.google_tasks.async_setup_entry", return_value=True
+ ) as mock_setup,
+ patch("homeassistant.components.google_tasks.config_flow.build"),
+ ):
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == FlowResultType.CREATE_ENTRY
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
diff --git a/tests/components/google_travel_time/conftest.py b/tests/components/google_travel_time/conftest.py
index d5a1447f767..141b40eff29 100644
--- a/tests/components/google_travel_time/conftest.py
+++ b/tests/components/google_travel_time/conftest.py
@@ -48,9 +48,12 @@ def bypass_platform_setup_fixture():
@pytest.fixture(name="validate_config_entry")
def validate_config_entry_fixture():
"""Return valid config entry."""
- with patch("homeassistant.components.google_travel_time.helpers.Client"), patch(
- "homeassistant.components.google_travel_time.helpers.distance_matrix"
- ) as distance_matrix_mock:
+ with (
+ patch("homeassistant.components.google_travel_time.helpers.Client"),
+ patch(
+ "homeassistant.components.google_travel_time.helpers.distance_matrix"
+ ) as distance_matrix_mock,
+ ):
distance_matrix_mock.return_value = None
yield distance_matrix_mock
diff --git a/tests/components/google_travel_time/test_sensor.py b/tests/components/google_travel_time/test_sensor.py
index bb1ba722540..a7fb263d4c9 100644
--- a/tests/components/google_travel_time/test_sensor.py
+++ b/tests/components/google_travel_time/test_sensor.py
@@ -26,9 +26,12 @@ from tests.common import MockConfigEntry
@pytest.fixture(name="mock_update")
def mock_update_fixture():
"""Mock an update to the sensor."""
- with patch("homeassistant.components.google_travel_time.sensor.Client"), patch(
- "homeassistant.components.google_travel_time.sensor.distance_matrix"
- ) as distance_matrix_mock:
+ with (
+ patch("homeassistant.components.google_travel_time.sensor.Client"),
+ patch(
+ "homeassistant.components.google_travel_time.sensor.distance_matrix"
+ ) as distance_matrix_mock,
+ ):
distance_matrix_mock.return_value = {
"rows": [
{
@@ -224,9 +227,12 @@ async def test_sensor_unit_system(
entry_id="test",
)
config_entry.add_to_hass(hass)
- with patch("homeassistant.components.google_travel_time.sensor.Client"), patch(
- "homeassistant.components.google_travel_time.sensor.distance_matrix"
- ) as distance_matrix_mock:
+ with (
+ patch("homeassistant.components.google_travel_time.sensor.Client"),
+ patch(
+ "homeassistant.components.google_travel_time.sensor.distance_matrix"
+ ) as distance_matrix_mock,
+ ):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/govee_ble/test_sensor.py b/tests/components/govee_ble/test_sensor.py
index 099fff7d413..caed4a5c469 100644
--- a/tests/components/govee_ble/test_sensor.py
+++ b/tests/components/govee_ble/test_sensor.py
@@ -114,9 +114,12 @@ async def test_gvh5178_multi_sensor(hass: HomeAssistant) -> None:
# Fastforward time without BLE advertisements
monotonic_now = start_monotonic + FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 1
- with patch_bluetooth_time(
- monotonic_now,
- ), patch_all_discovered_devices([]):
+ with (
+ patch_bluetooth_time(
+ monotonic_now,
+ ),
+ patch_all_discovered_devices([]),
+ ):
async_fire_time_changed(
hass,
dt_util.utcnow()
@@ -140,9 +143,12 @@ async def test_gvh5178_multi_sensor(hass: HomeAssistant) -> None:
assert primary_temp_sensor.state == "1.0"
# Fastforward time without BLE advertisements
- with patch_bluetooth_time(
- monotonic_now,
- ), patch_all_discovered_devices([]):
+ with (
+ patch_bluetooth_time(
+ monotonic_now,
+ ),
+ patch_all_discovered_devices([]),
+ ):
async_fire_time_changed(
hass,
dt_util.utcnow()
diff --git a/tests/components/govee_light_local/test_config_flow.py b/tests/components/govee_light_local/test_config_flow.py
index b76d13a82fc..79baef33969 100644
--- a/tests/components/govee_light_local/test_config_flow.py
+++ b/tests/components/govee_light_local/test_config_flow.py
@@ -1,4 +1,5 @@
"""Test Govee light local config flow."""
+
from unittest.mock import AsyncMock, patch
from govee_local_api import GoveeDevice
@@ -17,12 +18,15 @@ async def test_creating_entry_has_no_devices(
mock_govee_api.devices = []
- with patch(
- "homeassistant.components.govee_light_local.config_flow.GoveeController",
- return_value=mock_govee_api,
- ), patch(
- "homeassistant.components.govee_light_local.config_flow.DISCOVERY_TIMEOUT",
- 0,
+ with (
+ patch(
+ "homeassistant.components.govee_light_local.config_flow.GoveeController",
+ return_value=mock_govee_api,
+ ),
+ patch(
+ "homeassistant.components.govee_light_local.config_flow.DISCOVERY_TIMEOUT",
+ 0,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
diff --git a/tests/components/gree/test_init.py b/tests/components/gree/test_init.py
index 1da965e001b..026660cf2d1 100644
--- a/tests/components/gree/test_init.py
+++ b/tests/components/gree/test_init.py
@@ -15,13 +15,16 @@ async def test_setup_simple(hass: HomeAssistant) -> None:
entry = MockConfigEntry(domain=GREE_DOMAIN)
entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.gree.climate.async_setup_entry",
- return_value=True,
- ) as climate_setup, patch(
- "homeassistant.components.gree.switch.async_setup_entry",
- return_value=True,
- ) as switch_setup:
+ with (
+ patch(
+ "homeassistant.components.gree.climate.async_setup_entry",
+ return_value=True,
+ ) as climate_setup,
+ patch(
+ "homeassistant.components.gree.switch.async_setup_entry",
+ return_value=True,
+ ) as switch_setup,
+ ):
assert await async_setup_component(hass, GREE_DOMAIN, {})
await hass.async_block_till_done()
diff --git a/tests/components/growatt_server/test_config_flow.py b/tests/components/growatt_server/test_config_flow.py
index 5703ed02a8a..57777a57783 100644
--- a/tests/components/growatt_server/test_config_flow.py
+++ b/tests/components/growatt_server/test_config_flow.py
@@ -84,9 +84,10 @@ async def test_no_plants_on_account(hass: HomeAssistant) -> None:
plant_list = deepcopy(GROWATT_PLANT_LIST_RESPONSE)
plant_list["data"] = []
- with patch(
- "growattServer.GrowattApi.login", return_value=GROWATT_LOGIN_RESPONSE
- ), patch("growattServer.GrowattApi.plant_list", return_value=plant_list):
+ with (
+ patch("growattServer.GrowattApi.login", return_value=GROWATT_LOGIN_RESPONSE),
+ patch("growattServer.GrowattApi.plant_list", return_value=plant_list),
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input
)
@@ -104,10 +105,13 @@ async def test_multiple_plant_ids(hass: HomeAssistant) -> None:
plant_list = deepcopy(GROWATT_PLANT_LIST_RESPONSE)
plant_list["data"].append(plant_list["data"][0])
- with patch(
- "growattServer.GrowattApi.login", return_value=GROWATT_LOGIN_RESPONSE
- ), patch("growattServer.GrowattApi.plant_list", return_value=plant_list), patch(
- "homeassistant.components.growatt_server.async_setup_entry", return_value=True
+ with (
+ patch("growattServer.GrowattApi.login", return_value=GROWATT_LOGIN_RESPONSE),
+ patch("growattServer.GrowattApi.plant_list", return_value=plant_list),
+ patch(
+ "homeassistant.components.growatt_server.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input
@@ -134,13 +138,16 @@ async def test_one_plant_on_account(hass: HomeAssistant) -> None:
)
user_input = FIXTURE_USER_INPUT.copy()
- with patch(
- "growattServer.GrowattApi.login", return_value=GROWATT_LOGIN_RESPONSE
- ), patch(
- "growattServer.GrowattApi.plant_list",
- return_value=GROWATT_PLANT_LIST_RESPONSE,
- ), patch(
- "homeassistant.components.growatt_server.async_setup_entry", return_value=True
+ with (
+ patch("growattServer.GrowattApi.login", return_value=GROWATT_LOGIN_RESPONSE),
+ patch(
+ "growattServer.GrowattApi.plant_list",
+ return_value=GROWATT_PLANT_LIST_RESPONSE,
+ ),
+ patch(
+ "homeassistant.components.growatt_server.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input
@@ -161,11 +168,12 @@ async def test_existing_plant_configured(hass: HomeAssistant) -> None:
)
user_input = FIXTURE_USER_INPUT.copy()
- with patch(
- "growattServer.GrowattApi.login", return_value=GROWATT_LOGIN_RESPONSE
- ), patch(
- "growattServer.GrowattApi.plant_list",
- return_value=GROWATT_PLANT_LIST_RESPONSE,
+ with (
+ patch("growattServer.GrowattApi.login", return_value=GROWATT_LOGIN_RESPONSE),
+ patch(
+ "growattServer.GrowattApi.plant_list",
+ return_value=GROWATT_PLANT_LIST_RESPONSE,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input
diff --git a/tests/components/guardian/conftest.py b/tests/components/guardian/conftest.py
index 9f9b0f95e0d..df517aba603 100644
--- a/tests/components/guardian/conftest.py
+++ b/tests/components/guardian/conftest.py
@@ -107,35 +107,47 @@ async def setup_guardian_fixture(
data_wifi_status,
):
"""Define a fixture to set up Guardian."""
- with patch("aioguardian.client.Client.connect"), patch(
- "aioguardian.commands.sensor.SensorCommands.pair_dump",
- return_value=data_sensor_pair_dump,
- ), patch(
- "aioguardian.commands.sensor.SensorCommands.pair_sensor",
- return_value=data_sensor_pair_sensor,
- ), patch(
- "aioguardian.commands.sensor.SensorCommands.paired_sensor_status",
- return_value=data_sensor_paired_sensor_status,
- ), patch(
- "aioguardian.commands.system.SystemCommands.diagnostics",
- return_value=data_system_diagnostics,
- ), patch(
- "aioguardian.commands.system.SystemCommands.onboard_sensor_status",
- return_value=data_system_onboard_sensor_status,
- ), patch(
- "aioguardian.commands.system.SystemCommands.ping",
- return_value=data_system_ping,
- ), patch(
- "aioguardian.commands.valve.ValveCommands.status",
- return_value=data_valve_status,
- ), patch(
- "aioguardian.commands.wifi.WiFiCommands.status",
- return_value=data_wifi_status,
- ), patch(
- "aioguardian.client.Client.disconnect",
- ), patch(
- "homeassistant.components.guardian.PLATFORMS",
- [],
+ with (
+ patch("aioguardian.client.Client.connect"),
+ patch(
+ "aioguardian.commands.sensor.SensorCommands.pair_dump",
+ return_value=data_sensor_pair_dump,
+ ),
+ patch(
+ "aioguardian.commands.sensor.SensorCommands.pair_sensor",
+ return_value=data_sensor_pair_sensor,
+ ),
+ patch(
+ "aioguardian.commands.sensor.SensorCommands.paired_sensor_status",
+ return_value=data_sensor_paired_sensor_status,
+ ),
+ patch(
+ "aioguardian.commands.system.SystemCommands.diagnostics",
+ return_value=data_system_diagnostics,
+ ),
+ patch(
+ "aioguardian.commands.system.SystemCommands.onboard_sensor_status",
+ return_value=data_system_onboard_sensor_status,
+ ),
+ patch(
+ "aioguardian.commands.system.SystemCommands.ping",
+ return_value=data_system_ping,
+ ),
+ patch(
+ "aioguardian.commands.valve.ValveCommands.status",
+ return_value=data_valve_status,
+ ),
+ patch(
+ "aioguardian.commands.wifi.WiFiCommands.status",
+ return_value=data_wifi_status,
+ ),
+ patch(
+ "aioguardian.client.Client.disconnect",
+ ),
+ patch(
+ "homeassistant.components.guardian.PLATFORMS",
+ [],
+ ),
):
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
diff --git a/tests/components/habitica/test_config_flow.py b/tests/components/habitica/test_config_flow.py
index 1fcddb0f766..fe5ddcacdea 100644
--- a/tests/components/habitica/test_config_flow.py
+++ b/tests/components/habitica/test_config_flow.py
@@ -23,15 +23,19 @@ async def test_form(hass: HomeAssistant) -> None:
mock_obj = MagicMock()
mock_obj.user.get = AsyncMock()
- with patch(
- "homeassistant.components.habitica.config_flow.HabitipyAsync",
- return_value=mock_obj,
- ), patch(
- "homeassistant.components.habitica.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.habitica.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.habitica.config_flow.HabitipyAsync",
+ return_value=mock_obj,
+ ),
+ patch(
+ "homeassistant.components.habitica.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.habitica.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"api_user": "test-api-user", "api_key": "test-api-key"},
diff --git a/tests/components/hardware/test_websocket_api.py b/tests/components/hardware/test_websocket_api.py
index fe33d1d0c09..e8099069a9c 100644
--- a/tests/components/hardware/test_websocket_api.py
+++ b/tests/components/hardware/test_websocket_api.py
@@ -64,14 +64,17 @@ async def test_system_status_subscription(
VirtualMem = namedtuple("VirtualMemory", ["available", "percent", "total"])
vmem = VirtualMem(10 * 1024**2, 50, 30 * 1024**2)
- with patch.object(
- mock_psutil.psutil,
- "cpu_percent",
- return_value=123,
- ), patch.object(
- mock_psutil.psutil,
- "virtual_memory",
- return_value=vmem,
+ with (
+ patch.object(
+ mock_psutil.psutil,
+ "cpu_percent",
+ return_value=123,
+ ),
+ patch.object(
+ mock_psutil.psutil,
+ "virtual_memory",
+ return_value=vmem,
+ ),
):
freezer.tick(TEST_TIME_ADVANCE_INTERVAL)
await hass.async_block_till_done()
@@ -91,9 +94,10 @@ async def test_system_status_subscription(
response = await client.receive_json()
assert response["success"]
- with patch.object(mock_psutil.psutil, "cpu_percent") as cpu_mock, patch.object(
- mock_psutil.psutil, "virtual_memory"
- ) as vmem_mock:
+ with (
+ patch.object(mock_psutil.psutil, "cpu_percent") as cpu_mock,
+ patch.object(mock_psutil.psutil, "virtual_memory") as vmem_mock,
+ ):
freezer.tick(TEST_TIME_ADVANCE_INTERVAL)
await hass.async_block_till_done()
cpu_mock.assert_not_called()
diff --git a/tests/components/harmony/test_config_flow.py b/tests/components/harmony/test_config_flow.py
index 2451a59afa3..c2daa98728b 100644
--- a/tests/components/harmony/test_config_flow.py
+++ b/tests/components/harmony/test_config_flow.py
@@ -32,13 +32,16 @@ async def test_user_form(hass: HomeAssistant) -> None:
assert result["errors"] == {}
harmonyapi = _get_mock_harmonyapi(connect=True)
- with patch(
- "homeassistant.components.harmony.util.HarmonyAPI",
- return_value=harmonyapi,
- ), patch(
- "homeassistant.components.harmony.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.harmony.util.HarmonyAPI",
+ return_value=harmonyapi,
+ ),
+ patch(
+ "homeassistant.components.harmony.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"host": "1.2.3.4", "name": "friend"},
@@ -84,13 +87,16 @@ async def test_form_ssdp(hass: HomeAssistant) -> None:
harmonyapi = _get_mock_harmonyapi(connect=True)
- with patch(
- "homeassistant.components.harmony.util.HarmonyAPI",
- return_value=harmonyapi,
- ), patch(
- "homeassistant.components.harmony.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.harmony.util.HarmonyAPI",
+ return_value=harmonyapi,
+ ),
+ patch(
+ "homeassistant.components.harmony.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{},
diff --git a/tests/components/hassio/conftest.py b/tests/components/hassio/conftest.py
index f795e19d91f..21eeedb89ad 100644
--- a/tests/components/hassio/conftest.py
+++ b/tests/components/hassio/conftest.py
@@ -29,12 +29,17 @@ def disable_security_filter():
@pytest.fixture
def hassio_env():
"""Fixture to inject hassio env."""
- with patch.dict(os.environ, {"SUPERVISOR": "127.0.0.1"}), patch(
- "homeassistant.components.hassio.HassIO.is_connected",
- return_value={"result": "ok", "data": {}},
- ), patch.dict(os.environ, {"SUPERVISOR_TOKEN": SUPERVISOR_TOKEN}), patch(
- "homeassistant.components.hassio.HassIO.get_info",
- Mock(side_effect=HassioAPIError()),
+ with (
+ patch.dict(os.environ, {"SUPERVISOR": "127.0.0.1"}),
+ patch(
+ "homeassistant.components.hassio.HassIO.is_connected",
+ return_value={"result": "ok", "data": {}},
+ ),
+ patch.dict(os.environ, {"SUPERVISOR_TOKEN": SUPERVISOR_TOKEN}),
+ patch(
+ "homeassistant.components.hassio.HassIO.get_info",
+ Mock(side_effect=HassioAPIError()),
+ ),
):
yield
@@ -42,22 +47,29 @@ def hassio_env():
@pytest.fixture
def hassio_stubs(hassio_env, hass, hass_client, aioclient_mock):
"""Create mock hassio http client."""
- with patch(
- "homeassistant.components.hassio.HassIO.update_hass_api",
- return_value={"result": "ok"},
- ) as hass_api, patch(
- "homeassistant.components.hassio.HassIO.update_hass_timezone",
- return_value={"result": "ok"},
- ), patch(
- "homeassistant.components.hassio.HassIO.get_info",
- side_effect=HassioAPIError(),
- ), patch(
- "homeassistant.components.hassio.HassIO.get_ingress_panels",
- return_value={"panels": []},
- ), patch(
- "homeassistant.components.hassio.issues.SupervisorIssues.setup",
- ), patch(
- "homeassistant.components.hassio.HassIO.refresh_updates",
+ with (
+ patch(
+ "homeassistant.components.hassio.HassIO.update_hass_api",
+ return_value={"result": "ok"},
+ ) as hass_api,
+ patch(
+ "homeassistant.components.hassio.HassIO.update_hass_timezone",
+ return_value={"result": "ok"},
+ ),
+ patch(
+ "homeassistant.components.hassio.HassIO.get_info",
+ side_effect=HassioAPIError(),
+ ),
+ patch(
+ "homeassistant.components.hassio.HassIO.get_ingress_panels",
+ return_value={"panels": []},
+ ),
+ patch(
+ "homeassistant.components.hassio.issues.SupervisorIssues.setup",
+ ),
+ patch(
+ "homeassistant.components.hassio.HassIO.refresh_updates",
+ ),
):
hass.set_state(CoreState.starting)
hass.loop.run_until_complete(async_setup_component(hass, "hassio", {}))
diff --git a/tests/components/hassio/test_config_flow.py b/tests/components/hassio/test_config_flow.py
index 4067c9e9afe..1c56f4e25f5 100644
--- a/tests/components/hassio/test_config_flow.py
+++ b/tests/components/hassio/test_config_flow.py
@@ -9,12 +9,15 @@ from homeassistant.core import HomeAssistant
async def test_config_flow(hass: HomeAssistant) -> None:
"""Test we get the form."""
- with patch(
- "homeassistant.components.hassio.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.hassio.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.hassio.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.hassio.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "system"}
)
diff --git a/tests/components/hassio/test_discovery.py b/tests/components/hassio/test_discovery.py
index 7a7d543afb7..0783ee77932 100644
--- a/tests/components/hassio/test_discovery.py
+++ b/tests/components/hassio/test_discovery.py
@@ -125,12 +125,15 @@ async def test_hassio_discovery_startup_done(
json={"result": "ok", "data": {"name": "Mosquitto Test"}},
)
- with patch(
- "homeassistant.components.hassio.HassIO.update_hass_api",
- return_value={"result": "ok"},
- ), patch(
- "homeassistant.components.hassio.HassIO.get_info",
- Mock(side_effect=HassioAPIError()),
+ with (
+ patch(
+ "homeassistant.components.hassio.HassIO.update_hass_api",
+ return_value={"result": "ok"},
+ ),
+ patch(
+ "homeassistant.components.hassio.HassIO.get_info",
+ Mock(side_effect=HassioAPIError()),
+ ),
):
await hass.async_start()
await async_setup_component(hass, "hassio", {})
diff --git a/tests/components/hassio/test_init.py b/tests/components/hassio/test_init.py
index 099b75d3686..da49b8d9f16 100644
--- a/tests/components/hassio/test_init.py
+++ b/tests/components/hassio/test_init.py
@@ -439,8 +439,9 @@ async def test_setup_hassio_no_additional_data(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test setup with API push default data."""
- with patch.dict(os.environ, MOCK_ENVIRON), patch.dict(
- os.environ, {"SUPERVISOR_TOKEN": "123456"}
+ with (
+ patch.dict(os.environ, MOCK_ENVIRON),
+ patch.dict(os.environ, {"SUPERVISOR_TOKEN": "123456"}),
):
result = await async_setup_component(hass, "hassio", {"hassio": {}})
await hass.async_block_till_done()
@@ -461,9 +462,12 @@ async def test_warn_when_cannot_connect(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Fail warn when we cannot connect."""
- with patch.dict(os.environ, MOCK_ENVIRON), patch(
- "homeassistant.components.hassio.HassIO.is_connected",
- return_value=None,
+ with (
+ patch.dict(os.environ, MOCK_ENVIRON),
+ patch(
+ "homeassistant.components.hassio.HassIO.is_connected",
+ return_value=None,
+ ),
):
result = await async_setup_component(hass, "hassio", {})
assert result
@@ -496,9 +500,12 @@ async def test_service_calls(
caplog: pytest.LogCaptureFixture,
) -> None:
"""Call service and check the API calls behind that."""
- with patch.dict(os.environ, MOCK_ENVIRON), patch(
- "homeassistant.components.hassio.HassIO.is_connected",
- return_value=None,
+ with (
+ patch.dict(os.environ, MOCK_ENVIRON),
+ patch(
+ "homeassistant.components.hassio.HassIO.is_connected",
+ return_value=None,
+ ),
):
assert await async_setup_component(hass, "hassio", {})
await hass.async_block_till_done()
@@ -641,9 +648,12 @@ async def test_invalid_service_calls(
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Call service with invalid input and check that it raises."""
- with patch.dict(os.environ, MOCK_ENVIRON), patch(
- "homeassistant.components.hassio.HassIO.is_connected",
- return_value=None,
+ with (
+ patch.dict(os.environ, MOCK_ENVIRON),
+ patch(
+ "homeassistant.components.hassio.HassIO.is_connected",
+ return_value=None,
+ ),
):
assert await async_setup_component(hass, "hassio", {})
await hass.async_block_till_done()
@@ -680,12 +690,16 @@ async def test_addon_service_call_with_complex_slug(
},
],
}
- with patch.dict(os.environ, MOCK_ENVIRON), patch(
- "homeassistant.components.hassio.HassIO.is_connected",
- return_value=None,
- ), patch(
- "homeassistant.components.hassio.HassIO.get_supervisor_info",
- return_value=supervisor_mock_data,
+ with (
+ patch.dict(os.environ, MOCK_ENVIRON),
+ patch(
+ "homeassistant.components.hassio.HassIO.is_connected",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.hassio.HassIO.get_supervisor_info",
+ return_value=supervisor_mock_data,
+ ),
):
assert await async_setup_component(hass, "hassio", {})
await hass.async_block_till_done()
@@ -790,12 +804,16 @@ async def test_device_registry_calls(hass: HomeAssistant) -> None:
"version_latest": "5.12",
}
- with patch.dict(os.environ, MOCK_ENVIRON), patch(
- "homeassistant.components.hassio.HassIO.get_supervisor_info",
- return_value=supervisor_mock_data,
- ), patch(
- "homeassistant.components.hassio.HassIO.get_os_info",
- return_value=os_mock_data,
+ with (
+ patch.dict(os.environ, MOCK_ENVIRON),
+ patch(
+ "homeassistant.components.hassio.HassIO.get_supervisor_info",
+ return_value=supervisor_mock_data,
+ ),
+ patch(
+ "homeassistant.components.hassio.HassIO.get_os_info",
+ return_value=os_mock_data,
+ ),
):
config_entry = MockConfigEntry(domain=DOMAIN, data={}, unique_id=DOMAIN)
config_entry.add_to_hass(hass)
@@ -823,12 +841,15 @@ async def test_device_registry_calls(hass: HomeAssistant) -> None:
}
# Test that when addon is removed, next update will remove the add-on and subsequent updates won't
- with patch(
- "homeassistant.components.hassio.HassIO.get_supervisor_info",
- return_value=supervisor_mock_data,
- ), patch(
- "homeassistant.components.hassio.HassIO.get_os_info",
- return_value=os_mock_data,
+ with (
+ patch(
+ "homeassistant.components.hassio.HassIO.get_supervisor_info",
+ return_value=supervisor_mock_data,
+ ),
+ patch(
+ "homeassistant.components.hassio.HassIO.get_os_info",
+ return_value=os_mock_data,
+ ),
):
async_fire_time_changed(hass, dt_util.now() + timedelta(hours=1))
await hass.async_block_till_done(wait_background_tasks=True)
@@ -870,19 +891,23 @@ async def test_device_registry_calls(hass: HomeAssistant) -> None:
# Test that when addon is added, next update will reload the entry so we register
# a new device
- with patch(
- "homeassistant.components.hassio.HassIO.get_supervisor_info",
- return_value=supervisor_mock_data,
- ), patch(
- "homeassistant.components.hassio.HassIO.get_os_info",
- return_value=os_mock_data,
- ), patch(
- "homeassistant.components.hassio.HassIO.get_info",
- return_value={
- "supervisor": "222",
- "homeassistant": "0.110.0",
- "hassos": None,
- },
+ with (
+ patch(
+ "homeassistant.components.hassio.HassIO.get_supervisor_info",
+ return_value=supervisor_mock_data,
+ ),
+ patch(
+ "homeassistant.components.hassio.HassIO.get_os_info",
+ return_value=os_mock_data,
+ ),
+ patch(
+ "homeassistant.components.hassio.HassIO.get_info",
+ return_value={
+ "supervisor": "222",
+ "homeassistant": "0.110.0",
+ "hassos": None,
+ },
+ ),
):
async_fire_time_changed(hass, dt_util.now() + timedelta(hours=3))
await hass.async_block_till_done()
@@ -894,9 +919,12 @@ async def test_coordinator_updates(
) -> None:
"""Test coordinator updates."""
await async_setup_component(hass, "homeassistant", {})
- with patch.dict(os.environ, MOCK_ENVIRON), patch(
- "homeassistant.components.hassio.HassIO.refresh_updates"
- ) as refresh_updates_mock:
+ with (
+ patch.dict(os.environ, MOCK_ENVIRON),
+ patch(
+ "homeassistant.components.hassio.HassIO.refresh_updates"
+ ) as refresh_updates_mock,
+ ):
config_entry = MockConfigEntry(domain=DOMAIN, data={}, unique_id=DOMAIN)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
@@ -968,9 +996,12 @@ async def test_coordinator_updates_stats_entities_enabled(
) -> None:
"""Test coordinator updates with stats entities enabled."""
await async_setup_component(hass, "homeassistant", {})
- with patch.dict(os.environ, MOCK_ENVIRON), patch(
- "homeassistant.components.hassio.HassIO.refresh_updates"
- ) as refresh_updates_mock:
+ with (
+ patch.dict(os.environ, MOCK_ENVIRON),
+ patch(
+ "homeassistant.components.hassio.HassIO.refresh_updates"
+ ) as refresh_updates_mock,
+ ):
config_entry = MockConfigEntry(domain=DOMAIN, data={}, unique_id=DOMAIN)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
@@ -1059,10 +1090,13 @@ async def test_setup_hardware_integration(
) -> None:
"""Test setup initiates hardware integration."""
- with patch.dict(os.environ, MOCK_ENVIRON), patch(
- f"homeassistant.components.{integration}.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch.dict(os.environ, MOCK_ENVIRON),
+ patch(
+ f"homeassistant.components.{integration}.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await async_setup_component(hass, "hassio", {"hassio": {}})
await hass.async_block_till_done()
diff --git a/tests/components/hassio/test_update.py b/tests/components/hassio/test_update.py
index c89636cb65b..f6b61aeedab 100644
--- a/tests/components/hassio/test_update.py
+++ b/tests/components/hassio/test_update.py
@@ -470,9 +470,12 @@ async def test_release_notes_between_versions(
config_entry = MockConfigEntry(domain=DOMAIN, data={}, unique_id=DOMAIN)
config_entry.add_to_hass(hass)
- with patch.dict(os.environ, MOCK_ENVIRON), patch(
- "homeassistant.components.hassio.data.get_addons_changelogs",
- return_value={"test": "# 2.0.1\nNew updates\n# 2.0.0\nOld updates"},
+ with (
+ patch.dict(os.environ, MOCK_ENVIRON),
+ patch(
+ "homeassistant.components.hassio.data.get_addons_changelogs",
+ return_value={"test": "# 2.0.1\nNew updates\n# 2.0.0\nOld updates"},
+ ),
):
result = await async_setup_component(
hass,
@@ -506,9 +509,12 @@ async def test_release_notes_full(
config_entry = MockConfigEntry(domain=DOMAIN, data={}, unique_id=DOMAIN)
config_entry.add_to_hass(hass)
- with patch.dict(os.environ, MOCK_ENVIRON), patch(
- "homeassistant.components.hassio.data.get_addons_changelogs",
- return_value={"test": "# 2.0.0\nNew updates\n# 2.0.0\nOld updates"},
+ with (
+ patch.dict(os.environ, MOCK_ENVIRON),
+ patch(
+ "homeassistant.components.hassio.data.get_addons_changelogs",
+ return_value={"test": "# 2.0.0\nNew updates\n# 2.0.0\nOld updates"},
+ ),
):
result = await async_setup_component(
hass,
@@ -542,9 +548,12 @@ async def test_not_release_notes(
config_entry = MockConfigEntry(domain=DOMAIN, data={}, unique_id=DOMAIN)
config_entry.add_to_hass(hass)
- with patch.dict(os.environ, MOCK_ENVIRON), patch(
- "homeassistant.components.hassio.data.get_addons_changelogs",
- return_value={"test": None},
+ with (
+ patch.dict(os.environ, MOCK_ENVIRON),
+ patch(
+ "homeassistant.components.hassio.data.get_addons_changelogs",
+ return_value={"test": None},
+ ),
):
result = await async_setup_component(
hass,
@@ -570,13 +579,16 @@ async def test_not_release_notes(
async def test_no_os_entity(hass: HomeAssistant) -> None:
"""Test handling where there is no os entity."""
- with patch.dict(os.environ, MOCK_ENVIRON), patch(
- "homeassistant.components.hassio.HassIO.get_info",
- return_value={
- "supervisor": "222",
- "homeassistant": "0.110.0",
- "hassos": None,
- },
+ with (
+ patch.dict(os.environ, MOCK_ENVIRON),
+ patch(
+ "homeassistant.components.hassio.HassIO.get_info",
+ return_value={
+ "supervisor": "222",
+ "homeassistant": "0.110.0",
+ "hassos": None,
+ },
+ ),
):
result = await async_setup_component(
hass,
@@ -594,15 +606,20 @@ async def test_setting_up_core_update_when_addon_fails(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test setting up core update when single addon fails."""
- with patch.dict(os.environ, MOCK_ENVIRON), patch(
- "homeassistant.components.hassio.HassIO.get_addon_stats",
- side_effect=HassioAPIError("add-on is not running"),
- ), patch(
- "homeassistant.components.hassio.HassIO.get_addon_changelog",
- side_effect=HassioAPIError("add-on is not running"),
- ), patch(
- "homeassistant.components.hassio.HassIO.get_addon_info",
- side_effect=HassioAPIError("add-on is not running"),
+ with (
+ patch.dict(os.environ, MOCK_ENVIRON),
+ patch(
+ "homeassistant.components.hassio.HassIO.get_addon_stats",
+ side_effect=HassioAPIError("add-on is not running"),
+ ),
+ patch(
+ "homeassistant.components.hassio.HassIO.get_addon_changelog",
+ side_effect=HassioAPIError("add-on is not running"),
+ ),
+ patch(
+ "homeassistant.components.hassio.HassIO.get_addon_info",
+ side_effect=HassioAPIError("add-on is not running"),
+ ),
):
result = await async_setup_component(
hass,
diff --git a/tests/components/heos/conftest.py b/tests/components/heos/conftest.py
index 785d7c1d619..a12f4c610ad 100644
--- a/tests/components/heos/conftest.py
+++ b/tests/components/heos/conftest.py
@@ -53,8 +53,9 @@ def controller_fixture(
mock_heos.create_group.return_value = None
mock = Mock(return_value=mock_heos)
- with patch("homeassistant.components.heos.Heos", new=mock), patch(
- "homeassistant.components.heos.config_flow.Heos", new=mock
+ with (
+ patch("homeassistant.components.heos.Heos", new=mock),
+ patch("homeassistant.components.heos.config_flow.Heos", new=mock),
):
yield mock_heos
diff --git a/tests/components/here_travel_time/conftest.py b/tests/components/here_travel_time/conftest.py
index 3cbbc6d8c78..f318016315a 100644
--- a/tests/components/here_travel_time/conftest.py
+++ b/tests/components/here_travel_time/conftest.py
@@ -20,35 +20,40 @@ BIKE_RESPONSE = json.loads(load_fixture("here_travel_time/bike_response.json"))
@pytest.fixture(name="valid_response")
def valid_response_fixture():
"""Return valid api response."""
- with patch(
- "here_transit.HERETransitApi.route", return_value=TRANSIT_RESPONSE
- ), patch(
- "here_routing.HERERoutingApi.route",
- return_value=RESPONSE,
- ) as mock:
+ with (
+ patch("here_transit.HERETransitApi.route", return_value=TRANSIT_RESPONSE),
+ patch(
+ "here_routing.HERERoutingApi.route",
+ return_value=RESPONSE,
+ ) as mock,
+ ):
yield mock
@pytest.fixture(name="bike_response")
def bike_response_fixture():
"""Return valid api response."""
- with patch(
- "here_transit.HERETransitApi.route", return_value=TRANSIT_RESPONSE
- ), patch(
- "here_routing.HERERoutingApi.route",
- return_value=BIKE_RESPONSE,
- ) as mock:
+ with (
+ patch("here_transit.HERETransitApi.route", return_value=TRANSIT_RESPONSE),
+ patch(
+ "here_routing.HERERoutingApi.route",
+ return_value=BIKE_RESPONSE,
+ ) as mock,
+ ):
yield mock
@pytest.fixture(name="no_attribution_response")
def no_attribution_response_fixture():
"""Return valid api response without attribution."""
- with patch(
- "here_transit.HERETransitApi.route",
- return_value=NO_ATTRIBUTION_TRANSIT_RESPONSE,
- ), patch(
- "here_routing.HERERoutingApi.route",
- return_value=RESPONSE,
- ) as mock:
+ with (
+ patch(
+ "here_transit.HERETransitApi.route",
+ return_value=NO_ATTRIBUTION_TRANSIT_RESPONSE,
+ ),
+ patch(
+ "here_routing.HERERoutingApi.route",
+ return_value=RESPONSE,
+ ) as mock,
+ ):
yield mock
diff --git a/tests/components/hisense_aehw4a1/test_init.py b/tests/components/hisense_aehw4a1/test_init.py
index ff49879d344..1abac3421a6 100644
--- a/tests/components/hisense_aehw4a1/test_init.py
+++ b/tests/components/hisense_aehw4a1/test_init.py
@@ -12,13 +12,16 @@ from homeassistant.setup import async_setup_component
async def test_creating_entry_sets_up_climate_discovery(hass: HomeAssistant) -> None:
"""Test setting up Hisense AEH-W4A1 loads the climate component."""
- with patch(
- "homeassistant.components.hisense_aehw4a1.config_flow.AehW4a1.discovery",
- return_value=["1.2.3.4"],
- ), patch(
- "homeassistant.components.hisense_aehw4a1.climate.async_setup_entry",
- return_value=True,
- ) as mock_setup:
+ with (
+ patch(
+ "homeassistant.components.hisense_aehw4a1.config_flow.AehW4a1.discovery",
+ return_value=["1.2.3.4"],
+ ),
+ 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}
)
@@ -36,13 +39,16 @@ async def test_creating_entry_sets_up_climate_discovery(hass: HomeAssistant) ->
async def test_configuring_hisense_w4a1_create_entry(hass: HomeAssistant) -> None:
"""Test that specifying config will create an entry."""
- with patch(
- "homeassistant.components.hisense_aehw4a1.config_flow.AehW4a1.check",
- return_value=True,
- ), patch(
- "homeassistant.components.hisense_aehw4a1.async_setup_entry",
- return_value=True,
- ) as mock_setup:
+ with (
+ patch(
+ "homeassistant.components.hisense_aehw4a1.config_flow.AehW4a1.check",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.hisense_aehw4a1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup,
+ ):
await async_setup_component(
hass,
hisense_aehw4a1.DOMAIN,
@@ -57,13 +63,16 @@ async def test_configuring_hisense_w4a1_not_creates_entry_for_device_not_found(
hass: HomeAssistant,
) -> None:
"""Test that specifying config will not create an entry."""
- with patch(
- "homeassistant.components.hisense_aehw4a1.config_flow.AehW4a1.check",
- side_effect=exceptions.ConnectionError,
- ), patch(
- "homeassistant.components.hisense_aehw4a1.async_setup_entry",
- return_value=True,
- ) as mock_setup:
+ with (
+ patch(
+ "homeassistant.components.hisense_aehw4a1.config_flow.AehW4a1.check",
+ side_effect=exceptions.ConnectionError,
+ ),
+ patch(
+ "homeassistant.components.hisense_aehw4a1.async_setup_entry",
+ return_value=True,
+ ) as mock_setup,
+ ):
await async_setup_component(
hass,
hisense_aehw4a1.DOMAIN,
diff --git a/tests/components/history_stats/test_sensor.py b/tests/components/history_stats/test_sensor.py
index e51fba9990e..1982ec12188 100644
--- a/tests/components/history_stats/test_sensor.py
+++ b/tests/components/history_stats/test_sensor.py
@@ -611,10 +611,13 @@ 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,
- ), freeze_time(start_time):
+ with (
+ patch(
+ "homeassistant.components.recorder.history.state_changes_during_period",
+ _fake_states,
+ ),
+ freeze_time(start_time),
+ ):
await async_setup_component(
hass,
"sensor",
@@ -709,10 +712,13 @@ 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,
- ), freeze_time(start_time):
+ with (
+ patch(
+ "homeassistant.components.recorder.history.state_changes_during_period",
+ _fake_states,
+ ),
+ freeze_time(start_time),
+ ):
await async_setup_component(
hass,
"sensor",
@@ -823,10 +829,13 @@ 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,
- ), freeze_time(start_time):
+ with (
+ patch(
+ "homeassistant.components.recorder.history.state_changes_during_period",
+ _fake_states,
+ ),
+ freeze_time(start_time),
+ ):
await async_setup_component(
hass,
"sensor",
@@ -1050,10 +1059,13 @@ async def test_does_not_work_into_the_future(
assert hass.states.get("sensor.sensor2").state == "0.0833333333333333"
past_the_window = start_time + timedelta(hours=25)
- with patch(
- "homeassistant.components.recorder.history.state_changes_during_period",
- return_value=[],
- ), freeze_time(past_the_window):
+ with (
+ patch(
+ "homeassistant.components.recorder.history.state_changes_during_period",
+ return_value=[],
+ ),
+ freeze_time(past_the_window),
+ ):
async_fire_time_changed(hass, past_the_window)
await hass.async_block_till_done(wait_background_tasks=True)
@@ -1072,20 +1084,26 @@ async def test_does_not_work_into_the_future(
}
past_the_window_with_data = start_time + timedelta(hours=26)
- with patch(
- "homeassistant.components.recorder.history.state_changes_during_period",
- _fake_off_states,
- ), freeze_time(past_the_window_with_data):
+ with (
+ patch(
+ "homeassistant.components.recorder.history.state_changes_during_period",
+ _fake_off_states,
+ ),
+ freeze_time(past_the_window_with_data),
+ ):
async_fire_time_changed(hass, past_the_window_with_data)
await hass.async_block_till_done(wait_background_tasks=True)
assert hass.states.get("sensor.sensor1").state == STATE_UNKNOWN
at_the_next_window_with_data = start_time + timedelta(days=1, hours=23)
- with patch(
- "homeassistant.components.recorder.history.state_changes_during_period",
- _fake_off_states,
- ), freeze_time(at_the_next_window_with_data):
+ with (
+ patch(
+ "homeassistant.components.recorder.history.state_changes_during_period",
+ _fake_off_states,
+ ),
+ freeze_time(at_the_next_window_with_data),
+ ):
async_fire_time_changed(hass, at_the_next_window_with_data)
await hass.async_block_till_done(wait_background_tasks=True)
@@ -1204,10 +1222,13 @@ async def test_measure_sliding_window(
)
await hass.async_block_till_done()
- with patch(
- "homeassistant.components.recorder.history.state_changes_during_period",
- _fake_states,
- ), freeze_time(start_time):
+ with (
+ patch(
+ "homeassistant.components.recorder.history.state_changes_during_period",
+ _fake_states,
+ ),
+ freeze_time(start_time),
+ ):
for i in range(1, 5):
await async_update_entity(hass, f"sensor.sensor{i}")
await hass.async_block_till_done()
@@ -1218,10 +1239,13 @@ async def test_measure_sliding_window(
assert hass.states.get("sensor.sensor4").state == "41.7"
past_next_update = start_time + timedelta(minutes=30)
- with patch(
- "homeassistant.components.recorder.history.state_changes_during_period",
- _fake_states,
- ), freeze_time(past_next_update):
+ with (
+ patch(
+ "homeassistant.components.recorder.history.state_changes_during_period",
+ _fake_states,
+ ),
+ freeze_time(past_next_update),
+ ):
async_fire_time_changed(hass, past_next_update)
await hass.async_block_till_done()
@@ -1253,10 +1277,13 @@ async def test_measure_from_end_going_backwards(
]
}
- with patch(
- "homeassistant.components.recorder.history.state_changes_during_period",
- _fake_states,
- ), freeze_time(start_time):
+ with (
+ patch(
+ "homeassistant.components.recorder.history.state_changes_during_period",
+ _fake_states,
+ ),
+ freeze_time(start_time),
+ ):
await async_setup_component(
hass,
"sensor",
@@ -1313,10 +1340,13 @@ async def test_measure_from_end_going_backwards(
assert hass.states.get("sensor.sensor4").state == "83.3"
past_next_update = start_time + timedelta(minutes=30)
- with patch(
- "homeassistant.components.recorder.history.state_changes_during_period",
- _fake_states,
- ), freeze_time(past_next_update):
+ with (
+ patch(
+ "homeassistant.components.recorder.history.state_changes_during_period",
+ _fake_states,
+ ),
+ freeze_time(past_next_update),
+ ):
async_fire_time_changed(hass, past_next_update)
await hass.async_block_till_done()
@@ -1446,9 +1476,12 @@ async def test_end_time_with_microseconds_zeroed(
]
}
- with freeze_time(time_200), patch(
- "homeassistant.components.recorder.history.state_changes_during_period",
- _fake_states,
+ with (
+ freeze_time(time_200),
+ patch(
+ "homeassistant.components.recorder.history.state_changes_during_period",
+ _fake_states,
+ ),
):
await async_setup_component(
hass,
@@ -1637,10 +1670,13 @@ async def test_history_stats_handles_floored_timestamps(
]
}
- with patch(
- "homeassistant.components.recorder.history.state_changes_during_period",
- _fake_states,
- ), freeze_time(start_time):
+ with (
+ patch(
+ "homeassistant.components.recorder.history.state_changes_during_period",
+ _fake_states,
+ ),
+ freeze_time(start_time),
+ ):
await async_setup_component(
hass,
"sensor",
diff --git a/tests/components/hive/test_config_flow.py b/tests/components/hive/test_config_flow.py
index 383e4c78ace..b1553b2c485 100644
--- a/tests/components/hive/test_config_flow.py
+++ b/tests/components/hive/test_config_flow.py
@@ -27,21 +27,25 @@ MFA_INVALID_CODE = "HIVE"
async def test_import_flow(hass: HomeAssistant) -> None:
"""Check import flow."""
- with patch(
- "homeassistant.components.hive.config_flow.Auth.login",
- return_value={
- "ChallengeName": "SUCCESS",
- "AuthenticationResult": {
- "RefreshToken": "mock-refresh-token",
- "AccessToken": "mock-access-token",
+ with (
+ patch(
+ "homeassistant.components.hive.config_flow.Auth.login",
+ return_value={
+ "ChallengeName": "SUCCESS",
+ "AuthenticationResult": {
+ "RefreshToken": "mock-refresh-token",
+ "AccessToken": "mock-access-token",
+ },
},
- },
- ), patch(
- "homeassistant.components.hive.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.hive.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ ),
+ patch(
+ "homeassistant.components.hive.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.hive.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
@@ -75,21 +79,25 @@ async def test_user_flow(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.hive.config_flow.Auth.login",
- return_value={
- "ChallengeName": "SUCCESS",
- "AuthenticationResult": {
- "RefreshToken": "mock-refresh-token",
- "AccessToken": "mock-access-token",
+ with (
+ patch(
+ "homeassistant.components.hive.config_flow.Auth.login",
+ return_value={
+ "ChallengeName": "SUCCESS",
+ "AuthenticationResult": {
+ "RefreshToken": "mock-refresh-token",
+ "AccessToken": "mock-access-token",
+ },
},
- },
- ), patch(
- "homeassistant.components.hive.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.hive.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ ),
+ patch(
+ "homeassistant.components.hive.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.hive.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD},
@@ -163,22 +171,27 @@ async def test_user_flow_2fa(hass: HomeAssistant) -> None:
assert result3["step_id"] == "configuration"
assert result3["errors"] == {}
- with patch(
- "homeassistant.components.hive.config_flow.Auth.device_registration",
- return_value=True,
- ), patch(
- "homeassistant.components.hive.config_flow.Auth.get_device_data",
- return_value=[
- "mock-device-group-key",
- "mock-device-key",
- "mock-device-password",
- ],
- ), patch(
- "homeassistant.components.hive.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.hive.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.hive.config_flow.Auth.device_registration",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.hive.config_flow.Auth.get_device_data",
+ return_value=[
+ "mock-device-group-key",
+ "mock-device-key",
+ "mock-device-password",
+ ],
+ ),
+ patch(
+ "homeassistant.components.hive.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.hive.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result4 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -317,19 +330,22 @@ async def test_reauth_2fa_flow(hass: HomeAssistant) -> None:
},
)
- with patch(
- "homeassistant.components.hive.config_flow.Auth.sms_2fa",
- return_value={
- "ChallengeName": "SUCCESS",
- "AuthenticationResult": {
- "RefreshToken": "mock-refresh-token",
- "AccessToken": "mock-access-token",
+ with (
+ patch(
+ "homeassistant.components.hive.config_flow.Auth.sms_2fa",
+ return_value={
+ "ChallengeName": "SUCCESS",
+ "AuthenticationResult": {
+ "RefreshToken": "mock-refresh-token",
+ "AccessToken": "mock-access-token",
+ },
},
- },
- ), patch(
- "homeassistant.components.hive.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ ),
+ patch(
+ "homeassistant.components.hive.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
@@ -446,22 +462,27 @@ async def test_user_flow_2fa_send_new_code(hass: HomeAssistant) -> None:
assert result4["step_id"] == "configuration"
assert result4["errors"] == {}
- with patch(
- "homeassistant.components.hive.config_flow.Auth.device_registration",
- return_value=True,
- ), patch(
- "homeassistant.components.hive.config_flow.Auth.get_device_data",
- return_value=[
- "mock-device-group-key",
- "mock-device-key",
- "mock-device-password",
- ],
- ), patch(
- "homeassistant.components.hive.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.hive.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.hive.config_flow.Auth.device_registration",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.hive.config_flow.Auth.get_device_data",
+ return_value=[
+ "mock-device-group-key",
+ "mock-device-key",
+ "mock-device-password",
+ ],
+ ),
+ patch(
+ "homeassistant.components.hive.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.hive.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result5 = await hass.config_entries.flow.async_configure(
result4["flow_id"], {CONF_DEVICE_NAME: DEVICE_NAME}
)
@@ -718,16 +739,19 @@ async def test_user_flow_2fa_unknown_error(hass: HomeAssistant) -> None:
assert result3["step_id"] == "configuration"
assert result3["errors"] == {}
- with patch(
- "homeassistant.components.hive.config_flow.Auth.device_registration",
- return_value=True,
- ), patch(
- "homeassistant.components.hive.config_flow.Auth.get_device_data",
- return_value=[
- "mock-device-group-key",
- "mock-device-key",
- "mock-device-password",
- ],
+ with (
+ patch(
+ "homeassistant.components.hive.config_flow.Auth.device_registration",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.hive.config_flow.Auth.get_device_data",
+ return_value=[
+ "mock-device-group-key",
+ "mock-device-key",
+ "mock-device-password",
+ ],
+ ),
):
result4 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/hlk_sw16/test_config_flow.py b/tests/components/hlk_sw16/test_config_flow.py
index 3079d72baf8..e4770343114 100644
--- a/tests/components/hlk_sw16/test_config_flow.py
+++ b/tests/components/hlk_sw16/test_config_flow.py
@@ -65,15 +65,19 @@ async def test_form(hass: HomeAssistant) -> None:
mock_hlk_sw16_connection = await create_mock_hlk_sw16_connection(False)
- with patch(
- "homeassistant.components.hlk_sw16.config_flow.create_hlk_sw16_connection",
- return_value=mock_hlk_sw16_connection,
- ), patch(
- "homeassistant.components.hlk_sw16.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.hlk_sw16.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.hlk_sw16.config_flow.create_hlk_sw16_connection",
+ return_value=mock_hlk_sw16_connection,
+ ),
+ patch(
+ "homeassistant.components.hlk_sw16.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.hlk_sw16.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
conf,
@@ -126,15 +130,19 @@ async def test_import(hass: HomeAssistant) -> None:
mock_hlk_sw16_connection = await create_mock_hlk_sw16_connection(False)
- with patch(
- "homeassistant.components.hlk_sw16.config_flow.connect_client",
- return_value=mock_hlk_sw16_connection,
- ), patch(
- "homeassistant.components.hlk_sw16.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.hlk_sw16.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.hlk_sw16.config_flow.connect_client",
+ return_value=mock_hlk_sw16_connection,
+ ),
+ patch(
+ "homeassistant.components.hlk_sw16.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.hlk_sw16.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
conf,
diff --git a/tests/components/homeassistant/test_init.py b/tests/components/homeassistant/test_init.py
index faa2f34d33c..84319df2888 100644
--- a/tests/components/homeassistant/test_init.py
+++ b/tests/components/homeassistant/test_init.py
@@ -473,10 +473,13 @@ async def test_raises_when_db_upgrade_in_progress(
"""Test an exception is raised when the database migration is in progress."""
await async_setup_component(hass, "homeassistant", {})
- with pytest.raises(HomeAssistantError), patch(
- "homeassistant.helpers.recorder.async_migration_in_progress",
- return_value=True,
- ) as mock_async_migration_in_progress:
+ with (
+ pytest.raises(HomeAssistantError),
+ patch(
+ "homeassistant.helpers.recorder.async_migration_in_progress",
+ return_value=True,
+ ) as mock_async_migration_in_progress,
+ ):
await hass.services.async_call(
"homeassistant",
service,
@@ -488,11 +491,12 @@ async def test_raises_when_db_upgrade_in_progress(
assert mock_async_migration_in_progress.called
caplog.clear()
- with patch(
- "homeassistant.helpers.recorder.async_migration_in_progress",
- return_value=False,
- ) as mock_async_migration_in_progress, patch(
- "homeassistant.config.async_check_ha_config_file", return_value=None
+ with (
+ patch(
+ "homeassistant.helpers.recorder.async_migration_in_progress",
+ return_value=False,
+ ) as mock_async_migration_in_progress,
+ patch("homeassistant.config.async_check_ha_config_file", return_value=None),
):
await hass.services.async_call(
"homeassistant",
@@ -511,12 +515,16 @@ async def test_raises_when_config_is_invalid(
"""Test an exception is raised when the configuration is invalid."""
await async_setup_component(hass, "homeassistant", {})
- with pytest.raises(HomeAssistantError), patch(
- "homeassistant.helpers.recorder.async_migration_in_progress",
- return_value=False,
- ), patch(
- "homeassistant.config.async_check_ha_config_file", return_value=["Error 1"]
- ) as mock_async_check_ha_config_file:
+ with (
+ pytest.raises(HomeAssistantError),
+ patch(
+ "homeassistant.helpers.recorder.async_migration_in_progress",
+ return_value=False,
+ ),
+ patch(
+ "homeassistant.config.async_check_ha_config_file", return_value=["Error 1"]
+ ) as mock_async_check_ha_config_file,
+ ):
await hass.services.async_call(
"homeassistant",
SERVICE_HOMEASSISTANT_RESTART,
@@ -529,12 +537,15 @@ async def test_raises_when_config_is_invalid(
assert mock_async_check_ha_config_file.called
caplog.clear()
- with patch(
- "homeassistant.helpers.recorder.async_migration_in_progress",
- return_value=False,
- ), patch(
- "homeassistant.config.async_check_ha_config_file", return_value=None
- ) as mock_async_check_ha_config_file:
+ with (
+ patch(
+ "homeassistant.helpers.recorder.async_migration_in_progress",
+ return_value=False,
+ ),
+ patch(
+ "homeassistant.config.async_check_ha_config_file", return_value=None
+ ) as mock_async_check_ha_config_file,
+ ):
await hass.services.async_call(
"homeassistant",
SERVICE_HOMEASSISTANT_RESTART,
@@ -553,13 +564,15 @@ async def test_restart_homeassistant(
) -> None:
"""Test we can restart when there is no configuration error."""
await async_setup_component(hass, "homeassistant", {})
- with patch(
- "homeassistant.config.async_check_ha_config_file", return_value=None
- ) as mock_check, patch(
- "homeassistant.config.async_enable_safe_mode"
- ) as mock_safe_mode, patch(
- "homeassistant.core.HomeAssistant.async_stop", return_value=None
- ) as mock_restart:
+ with (
+ patch(
+ "homeassistant.config.async_check_ha_config_file", return_value=None
+ ) as mock_check,
+ patch("homeassistant.config.async_enable_safe_mode") as mock_safe_mode,
+ patch(
+ "homeassistant.core.HomeAssistant.async_stop", return_value=None
+ ) as mock_restart,
+ ):
await hass.services.async_call(
"homeassistant",
SERVICE_HOMEASSISTANT_RESTART,
@@ -575,11 +588,14 @@ async def test_restart_homeassistant(
async def test_stop_homeassistant(hass: HomeAssistant) -> None:
"""Test we can stop when there is a configuration error."""
await async_setup_component(hass, "homeassistant", {})
- with patch(
- "homeassistant.config.async_check_ha_config_file", return_value=None
- ) as mock_check, patch(
- "homeassistant.core.HomeAssistant.async_stop", return_value=None
- ) as mock_restart:
+ with (
+ patch(
+ "homeassistant.config.async_check_ha_config_file", return_value=None
+ ) as mock_check,
+ patch(
+ "homeassistant.core.HomeAssistant.async_stop", return_value=None
+ ) as mock_restart,
+ ):
await hass.services.async_call(
"homeassistant",
SERVICE_HOMEASSISTANT_STOP,
@@ -651,16 +667,19 @@ async def test_reload_all(
assert len(core_config) == 1
assert len(themes) == 1
- with pytest.raises(
- HomeAssistantError,
- match=(
- "Cannot quick reload all YAML configurations because the configuration is "
- "not valid: Oh no, drama!"
+ with (
+ pytest.raises(
+ HomeAssistantError,
+ match=(
+ "Cannot quick reload all YAML configurations because the configuration is "
+ "not valid: Oh no, drama!"
+ ),
),
- ), patch(
- "homeassistant.config.async_check_ha_config_file",
- return_value="Oh no, drama!",
- ) as mock_async_check_ha_config_file:
+ patch(
+ "homeassistant.config.async_check_ha_config_file",
+ return_value="Oh no, drama!",
+ ) as mock_async_check_ha_config_file,
+ ):
await hass.services.async_call(
"homeassistant",
SERVICE_RELOAD_ALL,
diff --git a/tests/components/homeassistant_alerts/test_init.py b/tests/components/homeassistant_alerts/test_init.py
index 7e41169d3d1..761eb5dec13 100644
--- a/tests/components/homeassistant_alerts/test_init.py
+++ b/tests/components/homeassistant_alerts/test_init.py
@@ -132,15 +132,19 @@ async def test_alerts(
if supervisor_info is not None:
hass.config.components.add("hassio")
- with patch(
- "homeassistant.components.homeassistant_alerts.__version__",
- ha_version,
- ), patch(
- "homeassistant.components.homeassistant_alerts.is_hassio",
- return_value=supervisor_info is not None,
- ), patch(
- "homeassistant.components.homeassistant_alerts.get_supervisor_info",
- return_value=supervisor_info,
+ with (
+ patch(
+ "homeassistant.components.homeassistant_alerts.__version__",
+ ha_version,
+ ),
+ patch(
+ "homeassistant.components.homeassistant_alerts.is_hassio",
+ return_value=supervisor_info is not None,
+ ),
+ patch(
+ "homeassistant.components.homeassistant_alerts.get_supervisor_info",
+ return_value=supervisor_info,
+ ),
):
assert await async_setup_component(hass, DOMAIN, {})
@@ -311,15 +315,19 @@ async def test_alerts_refreshed_on_component_load(
for domain in initial_components:
hass.config.components.add(domain)
- with patch(
- "homeassistant.components.homeassistant_alerts.__version__",
- ha_version,
- ), patch(
- "homeassistant.components.homeassistant_alerts.is_hassio",
- return_value=supervisor_info is not None,
- ), patch(
- "homeassistant.components.homeassistant_alerts.get_supervisor_info",
- return_value=supervisor_info,
+ with (
+ patch(
+ "homeassistant.components.homeassistant_alerts.__version__",
+ ha_version,
+ ),
+ patch(
+ "homeassistant.components.homeassistant_alerts.is_hassio",
+ return_value=supervisor_info is not None,
+ ),
+ patch(
+ "homeassistant.components.homeassistant_alerts.get_supervisor_info",
+ return_value=supervisor_info,
+ ),
):
assert await async_setup_component(hass, DOMAIN, {})
@@ -351,15 +359,19 @@ async def test_alerts_refreshed_on_component_load(
]
}
- with patch(
- "homeassistant.components.homeassistant_alerts.__version__",
- ha_version,
- ), patch(
- "homeassistant.components.homeassistant_alerts.is_hassio",
- return_value=supervisor_info is not None,
- ), patch(
- "homeassistant.components.homeassistant_alerts.get_supervisor_info",
- return_value=supervisor_info,
+ with (
+ patch(
+ "homeassistant.components.homeassistant_alerts.__version__",
+ ha_version,
+ ),
+ patch(
+ "homeassistant.components.homeassistant_alerts.is_hassio",
+ return_value=supervisor_info is not None,
+ ),
+ patch(
+ "homeassistant.components.homeassistant_alerts.get_supervisor_info",
+ return_value=supervisor_info,
+ ),
):
# Fake component_loaded events and wait for debounce
for domain in late_components:
diff --git a/tests/components/homeassistant_hardware/conftest.py b/tests/components/homeassistant_hardware/conftest.py
index 9656b3d2e60..ae9ee6e1d2e 100644
--- a/tests/components/homeassistant_hardware/conftest.py
+++ b/tests/components/homeassistant_hardware/conftest.py
@@ -21,14 +21,19 @@ def mock_zha_config_flow_setup() -> Generator[None, None, None]:
MagicMock()
)
- with patch(
- "bellows.zigbee.application.ControllerApplication.probe", side_effect=mock_probe
- ), patch(
- "homeassistant.components.zha.radio_manager.ZhaRadioManager.connect_zigpy_app",
- return_value=mock_connect_app,
- ), patch(
- "homeassistant.components.zha.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "bellows.zigbee.application.ControllerApplication.probe",
+ side_effect=mock_probe,
+ ),
+ patch(
+ "homeassistant.components.zha.radio_manager.ZhaRadioManager.connect_zigpy_app",
+ return_value=mock_connect_app,
+ ),
+ patch(
+ "homeassistant.components.zha.async_setup_entry",
+ return_value=True,
+ ),
):
yield
diff --git a/tests/components/homeassistant_hardware/test_silabs_multiprotocol_addon.py b/tests/components/homeassistant_hardware/test_silabs_multiprotocol_addon.py
index 6221ac3ecb5..82b6fd0c092 100644
--- a/tests/components/homeassistant_hardware/test_silabs_multiprotocol_addon.py
+++ b/tests/components/homeassistant_hardware/test_silabs_multiprotocol_addon.py
@@ -1610,13 +1610,16 @@ async def test_active_plaforms(
async def test_check_multi_pan_addon_no_hassio(hass: HomeAssistant) -> None:
"""Test `check_multi_pan_addon` without hassio."""
- with patch(
- "homeassistant.components.homeassistant_hardware.silabs_multiprotocol_addon.is_hassio",
- return_value=False,
- ), patch(
- "homeassistant.components.homeassistant_hardware.silabs_multiprotocol_addon.get_multiprotocol_addon_manager",
- autospec=True,
- ) as mock_get_addon_manager:
+ with (
+ patch(
+ "homeassistant.components.homeassistant_hardware.silabs_multiprotocol_addon.is_hassio",
+ return_value=False,
+ ),
+ patch(
+ "homeassistant.components.homeassistant_hardware.silabs_multiprotocol_addon.get_multiprotocol_addon_manager",
+ autospec=True,
+ ) as mock_get_addon_manager,
+ ):
await silabs_multiprotocol_addon.check_multi_pan_addon(hass)
mock_get_addon_manager.assert_not_called()
diff --git a/tests/components/homeassistant_sky_connect/conftest.py b/tests/components/homeassistant_sky_connect/conftest.py
index 6ab78fe53ef..de8576e2a0a 100644
--- a/tests/components/homeassistant_sky_connect/conftest.py
+++ b/tests/components/homeassistant_sky_connect/conftest.py
@@ -25,12 +25,15 @@ def mock_zha():
MagicMock()
)
- with patch(
- "homeassistant.components.zha.radio_manager.ZhaRadioManager.connect_zigpy_app",
- return_value=mock_connect_app,
- ), patch(
- "homeassistant.components.zha.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.zha.radio_manager.ZhaRadioManager.connect_zigpy_app",
+ return_value=mock_connect_app,
+ ),
+ patch(
+ "homeassistant.components.zha.async_setup_entry",
+ return_value=True,
+ ),
):
yield
diff --git a/tests/components/homeassistant_sky_connect/test_config_flow.py b/tests/components/homeassistant_sky_connect/test_config_flow.py
index 85a8f8d2668..9374cbc9457 100644
--- a/tests/components/homeassistant_sky_connect/test_config_flow.py
+++ b/tests/components/homeassistant_sky_connect/test_config_flow.py
@@ -146,13 +146,16 @@ async def test_config_flow_update_device(hass: HomeAssistant) -> None:
assert await hass.config_entries.async_setup(config_entry.entry_id)
assert len(mock_setup_entry.mock_calls) == 1
- with patch(
- "homeassistant.components.homeassistant_sky_connect.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.homeassistant_sky_connect.async_unload_entry",
- wraps=homeassistant_sky_connect.async_unload_entry,
- ) as mock_unload_entry:
+ with (
+ patch(
+ "homeassistant.components.homeassistant_sky_connect.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.homeassistant_sky_connect.async_unload_entry",
+ wraps=homeassistant_sky_connect.async_unload_entry,
+ ) as mock_unload_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "usb"}, data=usb_data
)
diff --git a/tests/components/homeassistant_sky_connect/test_init.py b/tests/components/homeassistant_sky_connect/test_init.py
index fd70d1fb696..a1fa4a5c743 100644
--- a/tests/components/homeassistant_sky_connect/test_init.py
+++ b/tests/components/homeassistant_sky_connect/test_init.py
@@ -43,11 +43,15 @@ def mock_zha_config_flow_setup() -> Generator[None, None, None]:
mock_connect_app = MagicMock()
mock_connect_app.__aenter__.return_value.backups.backups = []
- with patch(
- "bellows.zigbee.application.ControllerApplication.probe", side_effect=mock_probe
- ), patch(
- "homeassistant.components.zha.radio_manager.ZhaRadioManager.connect_zigpy_app",
- return_value=mock_connect_app,
+ with (
+ patch(
+ "bellows.zigbee.application.ControllerApplication.probe",
+ side_effect=mock_probe,
+ ),
+ patch(
+ "homeassistant.components.zha.radio_manager.ZhaRadioManager.connect_zigpy_app",
+ return_value=mock_connect_app,
+ ),
):
yield
@@ -75,11 +79,15 @@ async def test_setup_entry(
title="Home Assistant SkyConnect",
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.homeassistant_sky_connect.usb.async_is_plugged_in",
- return_value=True,
- ) as mock_is_plugged_in, patch(
- "homeassistant.components.onboarding.async_is_onboarded", return_value=onboarded
+ with (
+ patch(
+ "homeassistant.components.homeassistant_sky_connect.usb.async_is_plugged_in",
+ return_value=True,
+ ) as mock_is_plugged_in,
+ patch(
+ "homeassistant.components.onboarding.async_is_onboarded",
+ return_value=onboarded,
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -123,11 +131,14 @@ async def test_setup_zha(
title="Home Assistant SkyConnect",
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.homeassistant_sky_connect.usb.async_is_plugged_in",
- return_value=True,
- ) as mock_is_plugged_in, patch(
- "homeassistant.components.onboarding.async_is_onboarded", return_value=False
+ with (
+ patch(
+ "homeassistant.components.homeassistant_sky_connect.usb.async_is_plugged_in",
+ return_value=True,
+ ) as mock_is_plugged_in,
+ patch(
+ "homeassistant.components.onboarding.async_is_onboarded", return_value=False
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -174,14 +185,18 @@ async def test_setup_zha_multipan(
title="Home Assistant SkyConnect",
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.homeassistant_sky_connect.usb.async_is_plugged_in",
- return_value=True,
- ) as mock_is_plugged_in, patch(
- "homeassistant.components.onboarding.async_is_onboarded", return_value=False
- ), patch(
- "homeassistant.components.homeassistant_hardware.silabs_multiprotocol_addon.is_hassio",
- side_effect=Mock(return_value=True),
+ with (
+ patch(
+ "homeassistant.components.homeassistant_sky_connect.usb.async_is_plugged_in",
+ return_value=True,
+ ) as mock_is_plugged_in,
+ patch(
+ "homeassistant.components.onboarding.async_is_onboarded", return_value=False
+ ),
+ patch(
+ "homeassistant.components.homeassistant_hardware.silabs_multiprotocol_addon.is_hassio",
+ side_effect=Mock(return_value=True),
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -228,14 +243,18 @@ async def test_setup_zha_multipan_other_device(
title="Home Assistant Yellow",
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.homeassistant_sky_connect.usb.async_is_plugged_in",
- return_value=True,
- ) as mock_is_plugged_in, patch(
- "homeassistant.components.onboarding.async_is_onboarded", return_value=False
- ), patch(
- "homeassistant.components.homeassistant_hardware.silabs_multiprotocol_addon.is_hassio",
- side_effect=Mock(return_value=True),
+ with (
+ patch(
+ "homeassistant.components.homeassistant_sky_connect.usb.async_is_plugged_in",
+ return_value=True,
+ ) as mock_is_plugged_in,
+ patch(
+ "homeassistant.components.onboarding.async_is_onboarded", return_value=False
+ ),
+ patch(
+ "homeassistant.components.homeassistant_hardware.silabs_multiprotocol_addon.is_hassio",
+ side_effect=Mock(return_value=True),
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -306,14 +325,18 @@ async def test_setup_entry_addon_info_fails(
title="Home Assistant SkyConnect",
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.homeassistant_sky_connect.usb.async_is_plugged_in",
- return_value=True,
- ), patch(
- "homeassistant.components.onboarding.async_is_onboarded", return_value=False
- ), patch(
- "homeassistant.components.homeassistant_hardware.silabs_multiprotocol_addon.is_hassio",
- side_effect=Mock(return_value=True),
+ with (
+ patch(
+ "homeassistant.components.homeassistant_sky_connect.usb.async_is_plugged_in",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.onboarding.async_is_onboarded", return_value=False
+ ),
+ patch(
+ "homeassistant.components.homeassistant_hardware.silabs_multiprotocol_addon.is_hassio",
+ side_effect=Mock(return_value=True),
+ ),
):
assert not await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -335,14 +358,18 @@ async def test_setup_entry_addon_not_running(
title="Home Assistant SkyConnect",
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.homeassistant_sky_connect.usb.async_is_plugged_in",
- return_value=True,
- ), patch(
- "homeassistant.components.onboarding.async_is_onboarded", return_value=False
- ), patch(
- "homeassistant.components.homeassistant_hardware.silabs_multiprotocol_addon.is_hassio",
- side_effect=Mock(return_value=True),
+ with (
+ patch(
+ "homeassistant.components.homeassistant_sky_connect.usb.async_is_plugged_in",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.onboarding.async_is_onboarded", return_value=False
+ ),
+ patch(
+ "homeassistant.components.homeassistant_hardware.silabs_multiprotocol_addon.is_hassio",
+ side_effect=Mock(return_value=True),
+ ),
):
assert not await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/homeassistant_yellow/conftest.py b/tests/components/homeassistant_yellow/conftest.py
index 39ce00c59d4..070047648fc 100644
--- a/tests/components/homeassistant_yellow/conftest.py
+++ b/tests/components/homeassistant_yellow/conftest.py
@@ -21,14 +21,19 @@ def mock_zha_config_flow_setup() -> Generator[None, None, None]:
MagicMock()
)
- with patch(
- "bellows.zigbee.application.ControllerApplication.probe", side_effect=mock_probe
- ), patch(
- "homeassistant.components.zha.radio_manager.ZhaRadioManager.connect_zigpy_app",
- return_value=mock_connect_app,
- ), patch(
- "homeassistant.components.zha.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "bellows.zigbee.application.ControllerApplication.probe",
+ side_effect=mock_probe,
+ ),
+ patch(
+ "homeassistant.components.zha.radio_manager.ZhaRadioManager.connect_zigpy_app",
+ return_value=mock_connect_app,
+ ),
+ patch(
+ "homeassistant.components.zha.async_setup_entry",
+ return_value=True,
+ ),
):
yield
diff --git a/tests/components/homeassistant_yellow/test_init.py b/tests/components/homeassistant_yellow/test_init.py
index c3a9819c14b..e94dbbc1438 100644
--- a/tests/components/homeassistant_yellow/test_init.py
+++ b/tests/components/homeassistant_yellow/test_init.py
@@ -33,11 +33,15 @@ async def test_setup_entry(
title="Home Assistant Yellow",
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.homeassistant_yellow.get_os_info",
- return_value={"board": "yellow"},
- ) as mock_get_os_info, patch(
- "homeassistant.components.onboarding.async_is_onboarded", return_value=onboarded
+ with (
+ patch(
+ "homeassistant.components.homeassistant_yellow.get_os_info",
+ return_value={"board": "yellow"},
+ ) as mock_get_os_info,
+ patch(
+ "homeassistant.components.onboarding.async_is_onboarded",
+ return_value=onboarded,
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -76,11 +80,14 @@ async def test_setup_zha(hass: HomeAssistant, addon_store_info) -> None:
title="Home Assistant Yellow",
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.homeassistant_yellow.get_os_info",
- return_value={"board": "yellow"},
- ) as mock_get_os_info, patch(
- "homeassistant.components.onboarding.async_is_onboarded", return_value=False
+ with (
+ patch(
+ "homeassistant.components.homeassistant_yellow.get_os_info",
+ return_value={"board": "yellow"},
+ ) as mock_get_os_info,
+ patch(
+ "homeassistant.components.onboarding.async_is_onboarded", return_value=False
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -127,11 +134,14 @@ async def test_setup_zha_multipan(
title="Home Assistant Yellow",
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.homeassistant_yellow.get_os_info",
- return_value={"board": "yellow"},
- ) as mock_get_os_info, patch(
- "homeassistant.components.onboarding.async_is_onboarded", return_value=False
+ with (
+ patch(
+ "homeassistant.components.homeassistant_yellow.get_os_info",
+ return_value={"board": "yellow"},
+ ) as mock_get_os_info,
+ patch(
+ "homeassistant.components.onboarding.async_is_onboarded", return_value=False
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -178,11 +188,14 @@ async def test_setup_zha_multipan_other_device(
title="Home Assistant Yellow",
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.homeassistant_yellow.get_os_info",
- return_value={"board": "yellow"},
- ) as mock_get_os_info, patch(
- "homeassistant.components.onboarding.async_is_onboarded", return_value=False
+ with (
+ patch(
+ "homeassistant.components.homeassistant_yellow.get_os_info",
+ return_value={"board": "yellow"},
+ ) as mock_get_os_info,
+ patch(
+ "homeassistant.components.onboarding.async_is_onboarded", return_value=False
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -300,11 +313,14 @@ async def test_setup_entry_addon_info_fails(
title="Home Assistant Yellow",
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.homeassistant_yellow.get_os_info",
- return_value={"board": "yellow"},
- ), patch(
- "homeassistant.components.onboarding.async_is_onboarded", return_value=False
+ with (
+ patch(
+ "homeassistant.components.homeassistant_yellow.get_os_info",
+ return_value={"board": "yellow"},
+ ),
+ patch(
+ "homeassistant.components.onboarding.async_is_onboarded", return_value=False
+ ),
):
assert not await hass.config_entries.async_setup(config_entry.entry_id)
@@ -327,11 +343,14 @@ async def test_setup_entry_addon_not_running(
title="Home Assistant Yellow",
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.homeassistant_yellow.get_os_info",
- return_value={"board": "yellow"},
- ), patch(
- "homeassistant.components.onboarding.async_is_onboarded", return_value=False
+ with (
+ patch(
+ "homeassistant.components.homeassistant_yellow.get_os_info",
+ return_value={"board": "yellow"},
+ ),
+ patch(
+ "homeassistant.components.onboarding.async_is_onboarded", return_value=False
+ ),
):
assert not await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/homekit/conftest.py b/tests/components/homekit/conftest.py
index 39df14a47ef..fcbeafa3b60 100644
--- a/tests/components/homekit/conftest.py
+++ b/tests/components/homekit/conftest.py
@@ -27,12 +27,14 @@ def run_driver(hass, event_loop, iid_storage):
This mock does not mock async_stop, so the driver will not be stopped
"""
- with patch("pyhap.accessory_driver.AsyncZeroconf"), patch(
- "pyhap.accessory_driver.AccessoryEncoder"
- ), patch("pyhap.accessory_driver.HAPServer"), patch(
- "pyhap.accessory_driver.AccessoryDriver.publish"
- ), patch(
- "pyhap.accessory_driver.AccessoryDriver.persist",
+ with (
+ patch("pyhap.accessory_driver.AsyncZeroconf"),
+ patch("pyhap.accessory_driver.AccessoryEncoder"),
+ patch("pyhap.accessory_driver.HAPServer"),
+ patch("pyhap.accessory_driver.AccessoryDriver.publish"),
+ patch(
+ "pyhap.accessory_driver.AccessoryDriver.persist",
+ ),
):
yield HomeDriver(
hass,
@@ -49,14 +51,17 @@ def run_driver(hass, event_loop, iid_storage):
@pytest.fixture
def hk_driver(hass, event_loop, iid_storage):
"""Return a custom AccessoryDriver instance for HomeKit accessory init."""
- with patch("pyhap.accessory_driver.AsyncZeroconf"), patch(
- "pyhap.accessory_driver.AccessoryEncoder"
- ), patch("pyhap.accessory_driver.HAPServer.async_stop"), patch(
- "pyhap.accessory_driver.HAPServer.async_start"
- ), patch(
- "pyhap.accessory_driver.AccessoryDriver.publish",
- ), patch(
- "pyhap.accessory_driver.AccessoryDriver.persist",
+ with (
+ patch("pyhap.accessory_driver.AsyncZeroconf"),
+ patch("pyhap.accessory_driver.AccessoryEncoder"),
+ patch("pyhap.accessory_driver.HAPServer.async_stop"),
+ patch("pyhap.accessory_driver.HAPServer.async_start"),
+ patch(
+ "pyhap.accessory_driver.AccessoryDriver.publish",
+ ),
+ patch(
+ "pyhap.accessory_driver.AccessoryDriver.persist",
+ ),
):
yield HomeDriver(
hass,
@@ -73,18 +78,23 @@ def hk_driver(hass, event_loop, iid_storage):
@pytest.fixture
def mock_hap(hass, event_loop, iid_storage, mock_zeroconf):
"""Return a custom AccessoryDriver instance for HomeKit accessory init."""
- with patch("pyhap.accessory_driver.AsyncZeroconf"), patch(
- "pyhap.accessory_driver.AccessoryEncoder"
- ), patch("pyhap.accessory_driver.HAPServer.async_stop"), patch(
- "pyhap.accessory_driver.HAPServer.async_start"
- ), patch(
- "pyhap.accessory_driver.AccessoryDriver.publish",
- ), patch(
- "pyhap.accessory_driver.AccessoryDriver.async_start",
- ), patch(
- "pyhap.accessory_driver.AccessoryDriver.async_stop",
- ), patch(
- "pyhap.accessory_driver.AccessoryDriver.persist",
+ with (
+ patch("pyhap.accessory_driver.AsyncZeroconf"),
+ patch("pyhap.accessory_driver.AccessoryEncoder"),
+ patch("pyhap.accessory_driver.HAPServer.async_stop"),
+ patch("pyhap.accessory_driver.HAPServer.async_start"),
+ patch(
+ "pyhap.accessory_driver.AccessoryDriver.publish",
+ ),
+ patch(
+ "pyhap.accessory_driver.AccessoryDriver.async_start",
+ ),
+ patch(
+ "pyhap.accessory_driver.AccessoryDriver.async_stop",
+ ),
+ patch(
+ "pyhap.accessory_driver.AccessoryDriver.persist",
+ ),
):
yield HomeDriver(
hass,
diff --git a/tests/components/homekit/test_accessories.py b/tests/components/homekit/test_accessories.py
index 5d8b940a7cd..11a2675382a 100644
--- a/tests/components/homekit/test_accessories.py
+++ b/tests/components/homekit/test_accessories.py
@@ -756,18 +756,24 @@ def test_home_driver(iid_storage) -> None:
driver.accessory = Mock(display_name="any", xhm_uri=xhm_uri_mock)
# pair
- with patch("pyhap.accessory_driver.AccessoryDriver.pair") as mock_pair, patch(
- "homeassistant.components.homekit.accessories.async_dismiss_setup_message"
- ) as mock_dissmiss_msg:
+ with (
+ patch("pyhap.accessory_driver.AccessoryDriver.pair") as mock_pair,
+ patch(
+ "homeassistant.components.homekit.accessories.async_dismiss_setup_message"
+ ) as mock_dissmiss_msg,
+ ):
driver.pair("client_uuid", "client_public", b"1")
mock_pair.assert_called_with("client_uuid", "client_public", b"1")
mock_dissmiss_msg.assert_called_with("hass", "entry_id")
# unpair
- with patch("pyhap.accessory_driver.AccessoryDriver.unpair") as mock_unpair, patch(
- "homeassistant.components.homekit.accessories.async_show_setup_message"
- ) as mock_show_msg:
+ with (
+ patch("pyhap.accessory_driver.AccessoryDriver.unpair") as mock_unpair,
+ patch(
+ "homeassistant.components.homekit.accessories.async_show_setup_message"
+ ) as mock_show_msg,
+ ):
driver.unpair("client_uuid")
mock_unpair.assert_called_with("client_uuid")
diff --git a/tests/components/homekit/test_config_flow.py b/tests/components/homekit/test_config_flow.py
index fbcc33b9c7d..b3b8a70b1a1 100644
--- a/tests/components/homekit/test_config_flow.py
+++ b/tests/components/homekit/test_config_flow.py
@@ -60,15 +60,19 @@ async def test_setup_in_bridge_mode(hass: HomeAssistant, mock_get_source_ip) ->
assert result2["type"] == data_entry_flow.FlowResultType.FORM
assert result2["step_id"] == "pairing"
- with patch(
- "homeassistant.components.homekit.config_flow.async_find_next_available_port",
- return_value=12345,
- ), patch(
- "homeassistant.components.homekit.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.homekit.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.homekit.config_flow.async_find_next_available_port",
+ return_value=12345,
+ ),
+ patch(
+ "homeassistant.components.homekit.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.homekit.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{},
@@ -118,15 +122,19 @@ async def test_setup_in_bridge_mode_name_taken(
assert result2["type"] == data_entry_flow.FlowResultType.FORM
assert result2["step_id"] == "pairing"
- with patch(
- "homeassistant.components.homekit.config_flow.async_find_next_available_port",
- return_value=12345,
- ), patch(
- "homeassistant.components.homekit.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.homekit.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.homekit.config_flow.async_find_next_available_port",
+ return_value=12345,
+ ),
+ patch(
+ "homeassistant.components.homekit.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.homekit.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{},
@@ -200,15 +208,19 @@ async def test_setup_creates_entries_for_accessory_mode_devices(
assert result2["type"] == data_entry_flow.FlowResultType.FORM
assert result2["step_id"] == "pairing"
- with patch(
- "homeassistant.components.homekit.config_flow.async_find_next_available_port",
- return_value=12345,
- ), patch(
- "homeassistant.components.homekit.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.homekit.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.homekit.config_flow.async_find_next_available_port",
+ return_value=12345,
+ ),
+ patch(
+ "homeassistant.components.homekit.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.homekit.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{},
@@ -263,12 +275,15 @@ async def test_import(hass: HomeAssistant, mock_get_source_ip) -> None:
assert result["type"] == data_entry_flow.FlowResultType.ABORT
assert result["reason"] == "port_name_in_use"
- with patch(
- "homeassistant.components.homekit.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.homekit.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.homekit.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.homekit.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
@@ -1286,13 +1301,16 @@ async def test_converting_bridge_to_accessory_mode(
# We need to actually setup the config entry or the data
# will not get migrated to options
- with patch(
- "homeassistant.components.homekit.config_flow.async_find_next_available_port",
- return_value=12345,
- ), patch(
- "homeassistant.components.homekit.HomeKit.async_start",
- return_value=True,
- ) as mock_async_start:
+ with (
+ patch(
+ "homeassistant.components.homekit.config_flow.async_find_next_available_port",
+ return_value=12345,
+ ),
+ patch(
+ "homeassistant.components.homekit.HomeKit.async_start",
+ return_value=True,
+ ) as mock_async_start,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{},
@@ -1348,11 +1366,12 @@ async def test_converting_bridge_to_accessory_mode(
assert result2["type"] == data_entry_flow.FlowResultType.FORM
assert result2["step_id"] == "cameras"
- with patch(
- "homeassistant.components.homekit.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.homekit.async_port_is_available"
+ with (
+ patch(
+ "homeassistant.components.homekit.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch("homeassistant.components.homekit.async_port_is_available"),
):
result3 = await hass.config_entries.options.async_configure(
result2["flow_id"],
diff --git a/tests/components/homekit/test_diagnostics.py b/tests/components/homekit/test_diagnostics.py
index 1d6dec16991..9fe4fc6fcc7 100644
--- a/tests/components/homekit/test_diagnostics.py
+++ b/tests/components/homekit/test_diagnostics.py
@@ -143,9 +143,11 @@ async def test_config_entry_running(
"status": 1,
}
- with patch("pyhap.accessory_driver.AccessoryDriver.async_start"), patch(
- "homeassistant.components.homekit.HomeKit.async_stop"
- ), patch("homeassistant.components.homekit.async_port_is_available"):
+ with (
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start"),
+ patch("homeassistant.components.homekit.HomeKit.async_stop"),
+ patch("homeassistant.components.homekit.async_port_is_available"),
+ ):
assert await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
@@ -303,9 +305,11 @@ async def test_config_entry_accessory(
},
"status": 1,
}
- with patch("pyhap.accessory_driver.AccessoryDriver.async_start"), patch(
- "homeassistant.components.homekit.HomeKit.async_stop"
- ), patch("homeassistant.components.homekit.async_port_is_available"):
+ with (
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start"),
+ patch("homeassistant.components.homekit.HomeKit.async_stop"),
+ patch("homeassistant.components.homekit.async_port_is_available"),
+ ):
assert await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
@@ -622,8 +626,10 @@ async def test_config_entry_with_trigger_accessory(
"pairing_id": ANY,
"status": 1,
}
- with patch("pyhap.accessory_driver.AccessoryDriver.async_start"), patch(
- "homeassistant.components.homekit.HomeKit.async_stop"
- ), patch("homeassistant.components.homekit.async_port_is_available"):
+ with (
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start"),
+ patch("homeassistant.components.homekit.HomeKit.async_stop"),
+ patch("homeassistant.components.homekit.async_port_is_available"),
+ ):
assert await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/homekit/test_homekit.py b/tests/components/homekit/test_homekit.py
index 5ca5b5e386f..e0f0786f15d 100644
--- a/tests/components/homekit/test_homekit.py
+++ b/tests/components/homekit/test_homekit.py
@@ -164,8 +164,12 @@ async def test_setup_min(hass: HomeAssistant, mock_async_zeroconf: None) -> None
)
entry.add_to_hass(hass)
- with patch(f"{PATH_HOMEKIT}.HomeKit") as mock_homekit, patch(
- "homeassistant.components.network.async_get_source_ip", return_value="1.2.3.4"
+ with (
+ patch(f"{PATH_HOMEKIT}.HomeKit") as mock_homekit,
+ patch(
+ "homeassistant.components.network.async_get_source_ip",
+ return_value="1.2.3.4",
+ ),
):
mock_homekit.return_value = homekit = Mock()
type(homekit).async_start = AsyncMock()
@@ -206,8 +210,12 @@ async def test_removing_entry(
)
entry.add_to_hass(hass)
- with patch(f"{PATH_HOMEKIT}.HomeKit") as mock_homekit, patch(
- "homeassistant.components.network.async_get_source_ip", return_value="1.2.3.4"
+ with (
+ patch(f"{PATH_HOMEKIT}.HomeKit") as mock_homekit,
+ patch(
+ "homeassistant.components.network.async_get_source_ip",
+ return_value="1.2.3.4",
+ ),
):
mock_homekit.return_value = homekit = Mock()
type(homekit).async_start = AsyncMock()
@@ -729,11 +737,11 @@ async def test_homekit_start(
hass.states.async_set("light.demo2", "on")
state = hass.states.async_all()[0]
- with patch(f"{PATH_HOMEKIT}.HomeKit.add_bridge_accessory") as mock_add_acc, patch(
- f"{PATH_HOMEKIT}.async_show_setup_message"
- ) as mock_setup_msg, patch(
- "pyhap.accessory_driver.AccessoryDriver.async_start"
- ) as hk_driver_start:
+ with (
+ patch(f"{PATH_HOMEKIT}.HomeKit.add_bridge_accessory") as mock_add_acc,
+ patch(f"{PATH_HOMEKIT}.async_show_setup_message") as mock_setup_msg,
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start") as hk_driver_start,
+ ):
await homekit.async_start()
await hass.async_block_till_done()
@@ -761,15 +769,14 @@ async def test_homekit_start(
# Start again to make sure the registry entry is kept
homekit.status = STATUS_READY
- with patch(f"{PATH_HOMEKIT}.HomeKit.add_bridge_accessory") as mock_add_acc, patch(
- f"{PATH_HOMEKIT}.async_show_setup_message"
- ) as mock_setup_msg, patch(
- "pyhap.accessory_driver.AccessoryDriver.async_start"
- ) as hk_driver_start, patch(
- "pyhap.accessory_driver.AccessoryDriver.load"
- ) as load_mock, patch(
- "pyhap.accessory_driver.AccessoryDriver.persist"
- ) as persist_mock, patch(f"{PATH_HOMEKIT}.os.path.exists", return_value=True):
+ with (
+ patch(f"{PATH_HOMEKIT}.HomeKit.add_bridge_accessory") as mock_add_acc,
+ patch(f"{PATH_HOMEKIT}.async_show_setup_message") as mock_setup_msg,
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start") as hk_driver_start,
+ patch("pyhap.accessory_driver.AccessoryDriver.load") as load_mock,
+ patch("pyhap.accessory_driver.AccessoryDriver.persist") as persist_mock,
+ patch(f"{PATH_HOMEKIT}.os.path.exists", return_value=True),
+ ):
await homekit.async_stop()
await homekit.async_start()
@@ -807,11 +814,11 @@ async def test_homekit_start_with_a_broken_accessory(
hass.states.async_set("light.demo", "on")
hass.states.async_set("light.broken", "on")
- with patch(f"{PATH_HOMEKIT}.get_accessory", side_effect=Exception), patch(
- f"{PATH_HOMEKIT}.async_show_setup_message"
- ) as mock_setup_msg, patch(
- "pyhap.accessory_driver.AccessoryDriver.async_start"
- ) as hk_driver_start:
+ with (
+ patch(f"{PATH_HOMEKIT}.get_accessory", side_effect=Exception),
+ patch(f"{PATH_HOMEKIT}.async_show_setup_message") as mock_setup_msg,
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start") as hk_driver_start,
+ ):
await homekit.async_start()
await hass.async_block_till_done()
@@ -853,9 +860,10 @@ async def test_homekit_start_with_a_device(
homekit.driver = hk_driver
homekit.aid_storage = MagicMock()
- with patch(f"{PATH_HOMEKIT}.get_accessory", side_effect=Exception), patch(
- f"{PATH_HOMEKIT}.async_show_setup_message"
- ) as mock_setup_msg:
+ with (
+ patch(f"{PATH_HOMEKIT}.get_accessory", side_effect=Exception),
+ patch(f"{PATH_HOMEKIT}.async_show_setup_message") as mock_setup_msg,
+ ):
await homekit.async_start()
await hass.async_block_till_done()
@@ -912,12 +920,12 @@ async def test_homekit_reset_accessories(
hass.states.async_set("light.demo", "on")
homekit = _mock_homekit(hass, entry, HOMEKIT_MODE_BRIDGE)
- with patch(f"{PATH_HOMEKIT}.HomeKit", return_value=homekit), patch(
- "pyhap.accessory_driver.AccessoryDriver.config_changed"
- ), patch("pyhap.accessory_driver.AccessoryDriver.async_start"), patch(
- f"{PATH_HOMEKIT}.accessories.HomeAccessory.run"
- ) as mock_run_accessory, patch.object(
- homekit_base, "_HOMEKIT_CONFIG_UPDATE_TIME", 0
+ with (
+ patch(f"{PATH_HOMEKIT}.HomeKit", return_value=homekit),
+ patch("pyhap.accessory_driver.AccessoryDriver.config_changed"),
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start"),
+ patch(f"{PATH_HOMEKIT}.accessories.HomeAccessory.run") as mock_run_accessory,
+ patch.object(homekit_base, "_HOMEKIT_CONFIG_UPDATE_TIME", 0),
):
await async_init_entry(hass, entry)
@@ -1064,8 +1072,9 @@ async def test_homekit_unpair(
hass.states.async_set("light.demo", "on")
homekit = _mock_homekit(hass, entry, HOMEKIT_MODE_BRIDGE)
- with patch(f"{PATH_HOMEKIT}.HomeKit", return_value=homekit), patch(
- "pyhap.accessory_driver.AccessoryDriver.async_start"
+ with (
+ patch(f"{PATH_HOMEKIT}.HomeKit", return_value=homekit),
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start"),
):
await async_init_entry(hass, entry)
@@ -1113,8 +1122,9 @@ async def test_homekit_unpair_missing_device_id(
hass.states.async_set("light.demo", "on")
homekit = _mock_homekit(hass, entry, HOMEKIT_MODE_BRIDGE)
- with patch(f"{PATH_HOMEKIT}.HomeKit", return_value=homekit), patch(
- "pyhap.accessory_driver.AccessoryDriver.async_start"
+ with (
+ patch(f"{PATH_HOMEKIT}.HomeKit", return_value=homekit),
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start"),
):
await async_init_entry(hass, entry)
@@ -1158,8 +1168,9 @@ async def test_homekit_unpair_not_homekit_device(
hass.states.async_set("light.demo", "on")
homekit = _mock_homekit(hass, entry, HOMEKIT_MODE_BRIDGE)
- with patch(f"{PATH_HOMEKIT}.HomeKit", return_value=homekit), patch(
- "pyhap.accessory_driver.AccessoryDriver.async_start"
+ with (
+ patch(f"{PATH_HOMEKIT}.HomeKit", return_value=homekit),
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start"),
):
await async_init_entry(hass, entry)
@@ -1206,13 +1217,15 @@ async def test_homekit_reset_accessories_not_supported(
hass.states.async_set("not_supported.demo", "on")
homekit = _mock_homekit(hass, entry, HOMEKIT_MODE_BRIDGE)
- with patch(f"{PATH_HOMEKIT}.HomeKit", return_value=homekit), patch(
- "pyhap.accessory.Bridge.add_accessory"
- ) as mock_add_accessory, patch(
- "pyhap.accessory_driver.AccessoryDriver.async_update_advertisement"
- ) as hk_driver_async_update_advertisement, patch(
- "pyhap.accessory_driver.AccessoryDriver.async_start"
- ), patch.object(homekit_base, "_HOMEKIT_CONFIG_UPDATE_TIME", 0):
+ with (
+ patch(f"{PATH_HOMEKIT}.HomeKit", return_value=homekit),
+ patch("pyhap.accessory.Bridge.add_accessory") as mock_add_accessory,
+ patch(
+ "pyhap.accessory_driver.AccessoryDriver.async_update_advertisement"
+ ) as hk_driver_async_update_advertisement,
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start"),
+ patch.object(homekit_base, "_HOMEKIT_CONFIG_UPDATE_TIME", 0),
+ ):
await async_init_entry(hass, entry)
acc_mock = MagicMock()
@@ -1249,13 +1262,15 @@ async def test_homekit_reset_accessories_state_missing(
entity_id = "light.demo"
homekit = _mock_homekit(hass, entry, HOMEKIT_MODE_BRIDGE)
- with patch(f"{PATH_HOMEKIT}.HomeKit", return_value=homekit), patch(
- "pyhap.accessory.Bridge.add_accessory"
- ) as mock_add_accessory, patch(
- "pyhap.accessory_driver.AccessoryDriver.config_changed"
- ) as hk_driver_config_changed, patch(
- "pyhap.accessory_driver.AccessoryDriver.async_start"
- ), patch.object(homekit_base, "_HOMEKIT_CONFIG_UPDATE_TIME", 0):
+ with (
+ patch(f"{PATH_HOMEKIT}.HomeKit", return_value=homekit),
+ patch("pyhap.accessory.Bridge.add_accessory") as mock_add_accessory,
+ patch(
+ "pyhap.accessory_driver.AccessoryDriver.config_changed"
+ ) as hk_driver_config_changed,
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start"),
+ patch.object(homekit_base, "_HOMEKIT_CONFIG_UPDATE_TIME", 0),
+ ):
await async_init_entry(hass, entry)
acc_mock = MagicMock()
@@ -1291,13 +1306,15 @@ async def test_homekit_reset_accessories_not_bridged(
entity_id = "light.demo"
homekit = _mock_homekit(hass, entry, HOMEKIT_MODE_BRIDGE)
- with patch(f"{PATH_HOMEKIT}.HomeKit", return_value=homekit), patch(
- "pyhap.accessory.Bridge.add_accessory"
- ) as mock_add_accessory, patch(
- "pyhap.accessory_driver.AccessoryDriver.async_update_advertisement"
- ) as hk_driver_async_update_advertisement, patch(
- "pyhap.accessory_driver.AccessoryDriver.async_start"
- ), patch.object(homekit_base, "_HOMEKIT_CONFIG_UPDATE_TIME", 0):
+ with (
+ patch(f"{PATH_HOMEKIT}.HomeKit", return_value=homekit),
+ patch("pyhap.accessory.Bridge.add_accessory") as mock_add_accessory,
+ patch(
+ "pyhap.accessory_driver.AccessoryDriver.async_update_advertisement"
+ ) as hk_driver_async_update_advertisement,
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start"),
+ patch.object(homekit_base, "_HOMEKIT_CONFIG_UPDATE_TIME", 0),
+ ):
await async_init_entry(hass, entry)
assert hk_driver_async_update_advertisement.call_count == 0
@@ -1337,13 +1354,16 @@ async def test_homekit_reset_single_accessory(
hass.states.async_set("light.demo", "on")
homekit = _mock_homekit(hass, entry, HOMEKIT_MODE_ACCESSORY)
- with patch(f"{PATH_HOMEKIT}.HomeKit", return_value=homekit), patch(
- "pyhap.accessory_driver.AccessoryDriver.async_update_advertisement"
- ) as hk_driver_async_update_advertisement, patch(
- "pyhap.accessory_driver.AccessoryDriver.async_start"
- ), patch(
- f"{PATH_HOMEKIT}.accessories.HomeAccessory.run",
- ) as mock_run:
+ with (
+ patch(f"{PATH_HOMEKIT}.HomeKit", return_value=homekit),
+ patch(
+ "pyhap.accessory_driver.AccessoryDriver.async_update_advertisement"
+ ) as hk_driver_async_update_advertisement,
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start"),
+ patch(
+ f"{PATH_HOMEKIT}.accessories.HomeAccessory.run",
+ ) as mock_run,
+ ):
await async_init_entry(hass, entry)
homekit.status = STATUS_RUNNING
homekit.driver.aio_stop_event = MagicMock()
@@ -1373,10 +1393,12 @@ async def test_homekit_reset_single_accessory_unsupported(
hass.states.async_set("not_supported.demo", "on")
homekit = _mock_homekit(hass, entry, HOMEKIT_MODE_ACCESSORY)
- with patch(f"{PATH_HOMEKIT}.HomeKit", return_value=homekit), patch(
- "pyhap.accessory_driver.AccessoryDriver.config_changed"
- ) as hk_driver_config_changed, patch(
- "pyhap.accessory_driver.AccessoryDriver.async_start"
+ with (
+ patch(f"{PATH_HOMEKIT}.HomeKit", return_value=homekit),
+ patch(
+ "pyhap.accessory_driver.AccessoryDriver.config_changed"
+ ) as hk_driver_config_changed,
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start"),
):
await async_init_entry(hass, entry)
@@ -1411,10 +1433,12 @@ async def test_homekit_reset_single_accessory_state_missing(
entity_id = "light.demo"
homekit = _mock_homekit(hass, entry, HOMEKIT_MODE_ACCESSORY)
- with patch(f"{PATH_HOMEKIT}.HomeKit", return_value=homekit), patch(
- "pyhap.accessory_driver.AccessoryDriver.config_changed"
- ) as hk_driver_config_changed, patch(
- "pyhap.accessory_driver.AccessoryDriver.async_start"
+ with (
+ patch(f"{PATH_HOMEKIT}.HomeKit", return_value=homekit),
+ patch(
+ "pyhap.accessory_driver.AccessoryDriver.config_changed"
+ ) as hk_driver_config_changed,
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start"),
):
await async_init_entry(hass, entry)
@@ -1449,10 +1473,12 @@ async def test_homekit_reset_single_accessory_no_match(
entity_id = "light.demo"
homekit = _mock_homekit(hass, entry, HOMEKIT_MODE_ACCESSORY)
- with patch(f"{PATH_HOMEKIT}.HomeKit", return_value=homekit), patch(
- "pyhap.accessory_driver.AccessoryDriver.config_changed"
- ) as hk_driver_config_changed, patch(
- "pyhap.accessory_driver.AccessoryDriver.async_start"
+ with (
+ patch(f"{PATH_HOMEKIT}.HomeKit", return_value=homekit),
+ patch(
+ "pyhap.accessory_driver.AccessoryDriver.config_changed"
+ ) as hk_driver_config_changed,
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start"),
):
await async_init_entry(hass, entry)
@@ -1502,9 +1528,11 @@ async def test_homekit_too_many_accessories(
hass.states.async_set("light.demo2", "on")
hass.states.async_set("light.demo3", "on")
- with patch("pyhap.accessory_driver.AccessoryDriver.async_start"), patch(
- f"{PATH_HOMEKIT}.async_show_setup_message"
- ), patch(f"{PATH_HOMEKIT}.HomeBridge", _mock_bridge):
+ with (
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start"),
+ patch(f"{PATH_HOMEKIT}.async_show_setup_message"),
+ patch(f"{PATH_HOMEKIT}.HomeBridge", _mock_bridge),
+ ):
await homekit.async_start()
await hass.async_block_till_done()
assert "would exceed" in caplog.text
@@ -1564,9 +1592,11 @@ async def test_homekit_finds_linked_batteries(
)
hass.states.async_set(light.entity_id, STATE_ON)
- with patch(f"{PATH_HOMEKIT}.async_show_setup_message"), patch(
- f"{PATH_HOMEKIT}.get_accessory"
- ) as mock_get_acc, patch("pyhap.accessory_driver.AccessoryDriver.async_start"):
+ with (
+ patch(f"{PATH_HOMEKIT}.async_show_setup_message"),
+ patch(f"{PATH_HOMEKIT}.get_accessory") as mock_get_acc,
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start"),
+ ):
await homekit.async_start()
await hass.async_block_till_done()
@@ -1638,10 +1668,11 @@ async def test_homekit_async_get_integration_fails(
)
hass.states.async_set(light.entity_id, STATE_ON)
- with patch.object(homekit.bridge, "add_accessory"), patch(
- f"{PATH_HOMEKIT}.async_show_setup_message"
- ), patch(f"{PATH_HOMEKIT}.get_accessory") as mock_get_acc, patch(
- "pyhap.accessory_driver.AccessoryDriver.async_start"
+ with (
+ patch.object(homekit.bridge, "add_accessory"),
+ patch(f"{PATH_HOMEKIT}.async_show_setup_message"),
+ patch(f"{PATH_HOMEKIT}.get_accessory") as mock_get_acc,
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start"),
):
await homekit.async_start()
await hass.async_block_till_done()
@@ -1674,8 +1705,12 @@ async def test_yaml_updates_update_config_entry_for_name(
)
entry.add_to_hass(hass)
- with patch(f"{PATH_HOMEKIT}.HomeKit") as mock_homekit, patch(
- "homeassistant.components.network.async_get_source_ip", return_value="1.2.3.4"
+ with (
+ patch(f"{PATH_HOMEKIT}.HomeKit") as mock_homekit,
+ patch(
+ "homeassistant.components.network.async_get_source_ip",
+ return_value="1.2.3.4",
+ ),
):
mock_homekit.return_value = homekit = Mock()
type(homekit).async_start = AsyncMock()
@@ -1719,8 +1754,12 @@ async def test_yaml_can_link_with_default_name(
)
entry.add_to_hass(hass)
- with patch(f"{PATH_HOMEKIT}.HomeKit") as mock_homekit, patch(
- "homeassistant.components.network.async_get_source_ip", return_value="1.2.3.4"
+ with (
+ patch(f"{PATH_HOMEKIT}.HomeKit") as mock_homekit,
+ patch(
+ "homeassistant.components.network.async_get_source_ip",
+ return_value="1.2.3.4",
+ ),
):
mock_homekit.return_value = homekit = Mock()
type(homekit).async_start = AsyncMock()
@@ -1762,8 +1801,12 @@ async def test_yaml_can_link_with_port(
options={},
)
entry3.add_to_hass(hass)
- with patch(f"{PATH_HOMEKIT}.HomeKit") as mock_homekit, patch(
- "homeassistant.components.network.async_get_source_ip", return_value="1.2.3.4"
+ with (
+ patch(f"{PATH_HOMEKIT}.HomeKit") as mock_homekit,
+ patch(
+ "homeassistant.components.network.async_get_source_ip",
+ return_value="1.2.3.4",
+ ),
):
mock_homekit.return_value = homekit = Mock()
type(homekit).async_start = AsyncMock()
@@ -1799,9 +1842,11 @@ async def test_homekit_uses_system_zeroconf(
assert await async_setup_component(hass, "zeroconf", {"zeroconf": {}})
system_async_zc = await zeroconf.async_get_async_instance(hass)
- with patch("pyhap.accessory_driver.AccessoryDriver.async_start"), patch(
- f"{PATH_HOMEKIT}.HomeKit.async_stop"
- ), patch(f"{PATH_HOMEKIT}.async_port_is_available"):
+ with (
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start"),
+ patch(f"{PATH_HOMEKIT}.HomeKit.async_stop"),
+ patch(f"{PATH_HOMEKIT}.async_port_is_available"),
+ ):
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
@@ -1881,9 +1926,11 @@ async def test_homekit_ignored_missing_devices(
hass.states.async_set(light.entity_id, STATE_ON)
hass.states.async_set("light.two", STATE_ON)
- with patch(f"{PATH_HOMEKIT}.get_accessory") as mock_get_acc, patch(
- f"{PATH_HOMEKIT}.HomeBridge", return_value=homekit.bridge
- ), patch("pyhap.accessory_driver.AccessoryDriver.async_start"):
+ with (
+ patch(f"{PATH_HOMEKIT}.get_accessory") as mock_get_acc,
+ patch(f"{PATH_HOMEKIT}.HomeBridge", return_value=homekit.bridge),
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start"),
+ ):
await homekit.async_start()
await hass.async_block_till_done()
@@ -1943,10 +1990,11 @@ async def test_homekit_finds_linked_motion_sensors(
)
hass.states.async_set(camera.entity_id, STATE_ON)
- with patch.object(homekit.bridge, "add_accessory"), patch(
- f"{PATH_HOMEKIT}.async_show_setup_message"
- ), patch(f"{PATH_HOMEKIT}.get_accessory") as mock_get_acc, patch(
- "pyhap.accessory_driver.AccessoryDriver.async_start"
+ with (
+ patch.object(homekit.bridge, "add_accessory"),
+ patch(f"{PATH_HOMEKIT}.async_show_setup_message"),
+ patch(f"{PATH_HOMEKIT}.get_accessory") as mock_get_acc,
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start"),
):
await homekit.async_start()
await hass.async_block_till_done()
@@ -2012,10 +2060,11 @@ async def test_homekit_finds_linked_humidity_sensors(
)
hass.states.async_set(humidifier.entity_id, STATE_ON)
- with patch.object(homekit.bridge, "add_accessory"), patch(
- f"{PATH_HOMEKIT}.async_show_setup_message"
- ), patch(f"{PATH_HOMEKIT}.get_accessory") as mock_get_acc, patch(
- "pyhap.accessory_driver.AccessoryDriver.async_start"
+ with (
+ patch.object(homekit.bridge, "add_accessory"),
+ patch(f"{PATH_HOMEKIT}.async_show_setup_message"),
+ patch(f"{PATH_HOMEKIT}.get_accessory") as mock_get_acc,
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start"),
):
await homekit.async_start()
await hass.async_block_till_done()
@@ -2046,8 +2095,12 @@ async def test_reload(hass: HomeAssistant, mock_async_zeroconf: None) -> None:
)
entry.add_to_hass(hass)
- with patch(f"{PATH_HOMEKIT}.HomeKit") as mock_homekit, patch(
- "homeassistant.components.network.async_get_source_ip", return_value="1.2.3.4"
+ with (
+ patch(f"{PATH_HOMEKIT}.HomeKit") as mock_homekit,
+ patch(
+ "homeassistant.components.network.async_get_source_ip",
+ return_value="1.2.3.4",
+ ),
):
mock_homekit.return_value = homekit = Mock()
type(homekit).async_start = AsyncMock()
@@ -2071,14 +2124,21 @@ async def test_reload(hass: HomeAssistant, mock_async_zeroconf: None) -> None:
devices=[],
)
yaml_path = get_fixture_path("configuration.yaml", "homekit")
- with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path), patch(
- f"{PATH_HOMEKIT}.HomeKit"
- ) as mock_homekit2, patch(f"{PATH_HOMEKIT}.async_show_setup_message"), patch(
- f"{PATH_HOMEKIT}.get_accessory",
- ), patch(f"{PATH_HOMEKIT}.async_port_is_available", return_value=True), patch(
- "pyhap.accessory_driver.AccessoryDriver.async_start",
- ), patch(
- "homeassistant.components.network.async_get_source_ip", return_value="1.2.3.4"
+ with (
+ patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path),
+ patch(f"{PATH_HOMEKIT}.HomeKit") as mock_homekit2,
+ patch(f"{PATH_HOMEKIT}.async_show_setup_message"),
+ patch(
+ f"{PATH_HOMEKIT}.get_accessory",
+ ),
+ patch(f"{PATH_HOMEKIT}.async_port_is_available", return_value=True),
+ patch(
+ "pyhap.accessory_driver.AccessoryDriver.async_start",
+ ),
+ patch(
+ "homeassistant.components.network.async_get_source_ip",
+ return_value="1.2.3.4",
+ ),
):
mock_homekit2.return_value = homekit = Mock()
type(homekit).async_start = AsyncMock()
@@ -2124,11 +2184,11 @@ async def test_homekit_start_in_accessory_mode(
hass.states.async_set("light.demo", "on")
- with patch(f"{PATH_HOMEKIT}.HomeKit.add_bridge_accessory") as mock_add_acc, patch(
- f"{PATH_HOMEKIT}.async_show_setup_message"
- ) as mock_setup_msg, patch(
- "pyhap.accessory_driver.AccessoryDriver.async_start"
- ) as hk_driver_start:
+ with (
+ patch(f"{PATH_HOMEKIT}.HomeKit.add_bridge_accessory") as mock_add_acc,
+ patch(f"{PATH_HOMEKIT}.async_show_setup_message") as mock_setup_msg,
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start") as hk_driver_start,
+ ):
await homekit.async_start()
await hass.async_block_till_done()
@@ -2169,11 +2229,11 @@ async def test_homekit_start_in_accessory_mode_unsupported_entity(
hass.states.async_set("notsupported.demo", "on")
- with patch(f"{PATH_HOMEKIT}.HomeKit.add_bridge_accessory") as mock_add_acc, patch(
- f"{PATH_HOMEKIT}.async_show_setup_message"
- ) as mock_setup_msg, patch(
- "pyhap.accessory_driver.AccessoryDriver.async_start"
- ) as hk_driver_start:
+ with (
+ patch(f"{PATH_HOMEKIT}.HomeKit.add_bridge_accessory") as mock_add_acc,
+ patch(f"{PATH_HOMEKIT}.async_show_setup_message") as mock_setup_msg,
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start") as hk_driver_start,
+ ):
await homekit.async_start()
await hass.async_block_till_done()
@@ -2201,9 +2261,11 @@ async def test_homekit_start_in_accessory_mode_missing_entity(
homekit.driver = hk_driver
homekit.driver.accessory = Accessory(hk_driver, "any")
- with patch(f"{PATH_HOMEKIT}.HomeKit.add_bridge_accessory") as mock_add_acc, patch(
- f"{PATH_HOMEKIT}.async_show_setup_message"
- ), patch("pyhap.accessory_driver.AccessoryDriver.async_start"):
+ with (
+ patch(f"{PATH_HOMEKIT}.HomeKit.add_bridge_accessory") as mock_add_acc,
+ patch(f"{PATH_HOMEKIT}.async_show_setup_message"),
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start"),
+ ):
await homekit.async_start()
await hass.async_block_till_done()
@@ -2228,9 +2290,13 @@ async def test_wait_for_port_to_free(
)
entry.add_to_hass(hass)
- with patch("pyhap.accessory_driver.AccessoryDriver.async_start"), patch(
- f"{PATH_HOMEKIT}.HomeKit.async_stop"
- ), patch(f"{PATH_HOMEKIT}.async_port_is_available", return_value=True) as port_mock:
+ with (
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start"),
+ patch(f"{PATH_HOMEKIT}.HomeKit.async_stop"),
+ patch(
+ f"{PATH_HOMEKIT}.async_port_is_available", return_value=True
+ ) as port_mock,
+ ):
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert await hass.config_entries.async_unload(entry.entry_id)
@@ -2238,11 +2304,14 @@ async def test_wait_for_port_to_free(
assert "Waiting for the HomeKit server to shutdown" not in caplog.text
assert port_mock.called
- with patch("pyhap.accessory_driver.AccessoryDriver.async_start"), patch(
- f"{PATH_HOMEKIT}.HomeKit.async_stop"
- ), patch.object(homekit_base, "PORT_CLEANUP_CHECK_INTERVAL_SECS", 0), patch(
- f"{PATH_HOMEKIT}.async_port_is_available", return_value=False
- ) as port_mock:
+ with (
+ patch("pyhap.accessory_driver.AccessoryDriver.async_start"),
+ patch(f"{PATH_HOMEKIT}.HomeKit.async_stop"),
+ patch.object(homekit_base, "PORT_CLEANUP_CHECK_INTERVAL_SECS", 0),
+ patch(
+ f"{PATH_HOMEKIT}.async_port_is_available", return_value=False
+ ) as port_mock,
+ ):
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert await hass.config_entries.async_unload(entry.entry_id)
diff --git a/tests/components/homekit/test_init.py b/tests/components/homekit/test_init.py
index b56d01bd871..e8fb7e1d92e 100644
--- a/tests/components/homekit/test_init.py
+++ b/tests/components/homekit/test_init.py
@@ -114,9 +114,13 @@ async def test_bridge_with_triggers(
)
entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.network.async_get_source_ip", return_value="1.2.3.4"
- ), patch(f"{PATH_HOMEKIT}.async_port_is_available", return_value=True):
+ with (
+ patch(
+ "homeassistant.components.network.async_get_source_ip",
+ return_value="1.2.3.4",
+ ),
+ patch(f"{PATH_HOMEKIT}.async_port_is_available", return_value=True),
+ ):
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
diff --git a/tests/components/homekit/test_type_cameras.py b/tests/components/homekit/test_type_cameras.py
index 34770428d89..184ce1b6521 100644
--- a/tests/components/homekit/test_type_cameras.py
+++ b/tests/components/homekit/test_type_cameras.py
@@ -173,12 +173,15 @@ async def test_camera_stream_source_configured(
working_ffmpeg = _get_working_mock_ffmpeg()
session_info = acc.sessions[MOCK_START_STREAM_SESSION_UUID]
- with patch(
- "homeassistant.components.demo.camera.DemoCamera.stream_source",
- return_value=None,
- ), patch(
- "homeassistant.components.homekit.type_cameras.HAFFmpeg",
- return_value=working_ffmpeg,
+ with (
+ patch(
+ "homeassistant.components.demo.camera.DemoCamera.stream_source",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.homekit.type_cameras.HAFFmpeg",
+ return_value=working_ffmpeg,
+ ),
):
await _async_start_streaming(hass, acc)
await _async_stop_all_streams(hass, acc)
@@ -208,12 +211,15 @@ async def test_camera_stream_source_configured(
working_ffmpeg = _get_working_mock_ffmpeg()
session_info = acc.sessions[MOCK_START_STREAM_SESSION_UUID]
- with patch(
- "homeassistant.components.demo.camera.DemoCamera.stream_source",
- return_value="rtsp://example.local",
- ), patch(
- "homeassistant.components.homekit.type_cameras.HAFFmpeg",
- return_value=working_ffmpeg,
+ with (
+ patch(
+ "homeassistant.components.demo.camera.DemoCamera.stream_source",
+ return_value="rtsp://example.local",
+ ),
+ patch(
+ "homeassistant.components.homekit.type_cameras.HAFFmpeg",
+ return_value=working_ffmpeg,
+ ),
):
await _async_start_streaming(hass, acc)
await _async_stop_all_streams(hass, acc)
@@ -286,12 +292,15 @@ async def test_camera_stream_source_configured_with_failing_ffmpeg(
await _async_setup_endpoints(hass, acc)
- with patch(
- "homeassistant.components.demo.camera.DemoCamera.stream_source",
- return_value="rtsp://example.local",
- ), patch(
- "homeassistant.components.homekit.type_cameras.HAFFmpeg",
- return_value=_get_failing_mock_ffmpeg(),
+ with (
+ patch(
+ "homeassistant.components.demo.camera.DemoCamera.stream_source",
+ return_value="rtsp://example.local",
+ ),
+ patch(
+ "homeassistant.components.homekit.type_cameras.HAFFmpeg",
+ return_value=_get_failing_mock_ffmpeg(),
+ ),
):
await _async_start_streaming(hass, acc)
await _async_stop_all_streams(hass, acc)
@@ -330,12 +339,15 @@ async def test_camera_stream_source_found(
working_ffmpeg = _get_working_mock_ffmpeg()
session_info = acc.sessions[MOCK_START_STREAM_SESSION_UUID]
- with patch(
- "homeassistant.components.demo.camera.DemoCamera.stream_source",
- return_value="rtsp://example.local",
- ), patch(
- "homeassistant.components.homekit.type_cameras.HAFFmpeg",
- return_value=working_ffmpeg,
+ with (
+ patch(
+ "homeassistant.components.demo.camera.DemoCamera.stream_source",
+ return_value="rtsp://example.local",
+ ),
+ patch(
+ "homeassistant.components.homekit.type_cameras.HAFFmpeg",
+ return_value=working_ffmpeg,
+ ),
):
await _async_start_streaming(hass, acc)
await _async_stop_all_streams(hass, acc)
@@ -361,12 +373,15 @@ async def test_camera_stream_source_found(
working_ffmpeg = _get_working_mock_ffmpeg()
session_info = acc.sessions[MOCK_START_STREAM_SESSION_UUID]
- with patch(
- "homeassistant.components.demo.camera.DemoCamera.stream_source",
- return_value="rtsp://example2.local",
- ), patch(
- "homeassistant.components.homekit.type_cameras.HAFFmpeg",
- return_value=working_ffmpeg,
+ with (
+ patch(
+ "homeassistant.components.demo.camera.DemoCamera.stream_source",
+ return_value="rtsp://example2.local",
+ ),
+ patch(
+ "homeassistant.components.homekit.type_cameras.HAFFmpeg",
+ return_value=working_ffmpeg,
+ ),
):
await _async_start_streaming(hass, acc)
await _async_stop_all_streams(hass, acc)
@@ -410,12 +425,15 @@ async def test_camera_stream_source_fails(
await _async_setup_endpoints(hass, acc)
- with patch(
- "homeassistant.components.demo.camera.DemoCamera.stream_source",
- side_effect=OSError,
- ), patch(
- "homeassistant.components.homekit.type_cameras.HAFFmpeg",
- return_value=_get_working_mock_ffmpeg(),
+ with (
+ patch(
+ "homeassistant.components.demo.camera.DemoCamera.stream_source",
+ side_effect=OSError,
+ ),
+ patch(
+ "homeassistant.components.homekit.type_cameras.HAFFmpeg",
+ return_value=_get_working_mock_ffmpeg(),
+ ),
):
await _async_start_streaming(hass, acc)
await _async_stop_all_streams(hass, acc)
@@ -493,12 +511,15 @@ async def test_camera_stream_source_configured_and_copy_codec(
working_ffmpeg = _get_working_mock_ffmpeg()
- with patch(
- "homeassistant.components.demo.camera.DemoCamera.stream_source",
- return_value=None,
- ), patch(
- "homeassistant.components.homekit.type_cameras.HAFFmpeg",
- return_value=working_ffmpeg,
+ with (
+ patch(
+ "homeassistant.components.demo.camera.DemoCamera.stream_source",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.homekit.type_cameras.HAFFmpeg",
+ return_value=working_ffmpeg,
+ ),
):
await _async_start_streaming(hass, acc)
await _async_reconfigure_stream(hass, acc, session_info, {})
@@ -566,12 +587,15 @@ async def test_camera_stream_source_configured_and_override_profile_names(
working_ffmpeg = _get_working_mock_ffmpeg()
- with patch(
- "homeassistant.components.demo.camera.DemoCamera.stream_source",
- return_value=None,
- ), patch(
- "homeassistant.components.homekit.type_cameras.HAFFmpeg",
- return_value=working_ffmpeg,
+ with (
+ patch(
+ "homeassistant.components.demo.camera.DemoCamera.stream_source",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.homekit.type_cameras.HAFFmpeg",
+ return_value=working_ffmpeg,
+ ),
):
await _async_start_streaming(hass, acc)
await _async_reconfigure_stream(hass, acc, session_info, {})
@@ -638,12 +662,15 @@ async def test_camera_streaming_fails_after_starting_ffmpeg(
ffmpeg_with_invalid_pid = _get_exits_after_startup_mock_ffmpeg()
- with patch(
- "homeassistant.components.demo.camera.DemoCamera.stream_source",
- return_value=None,
- ), patch(
- "homeassistant.components.homekit.type_cameras.HAFFmpeg",
- return_value=ffmpeg_with_invalid_pid,
+ with (
+ patch(
+ "homeassistant.components.demo.camera.DemoCamera.stream_source",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.homekit.type_cameras.HAFFmpeg",
+ return_value=ffmpeg_with_invalid_pid,
+ ),
):
await _async_start_streaming(hass, acc)
await _async_reconfigure_stream(hass, acc, session_info, {})
diff --git a/tests/components/homekit/test_util.py b/tests/components/homekit/test_util.py
index 9d8f5c5417e..c419f7c19e7 100644
--- a/tests/components/homekit/test_util.py
+++ b/tests/components/homekit/test_util.py
@@ -342,9 +342,12 @@ async def test_port_is_available_skips_existing_entries(hass: HomeAssistant) ->
):
assert async_port_is_available(next_port)
- with pytest.raises(OSError), patch(
- "homeassistant.components.homekit.util.socket.socket",
- return_value=_mock_socket(10),
+ with (
+ pytest.raises(OSError),
+ patch(
+ "homeassistant.components.homekit.util.socket.socket",
+ return_value=_mock_socket(10),
+ ),
):
async_find_next_available_port(hass, 65530)
diff --git a/tests/components/homematicip_cloud/conftest.py b/tests/components/homematicip_cloud/conftest.py
index af663a150ac..88298521f75 100644
--- a/tests/components/homematicip_cloud/conftest.py
+++ b/tests/components/homematicip_cloud/conftest.py
@@ -145,12 +145,15 @@ def simple_mock_home_fixture():
def mock_connection_init_fixture():
"""Return a simple mocked connection."""
- with patch(
- "homeassistant.components.homematicip_cloud.hap.AsyncHome.init",
- return_value=None,
- ), patch(
- "homeassistant.components.homematicip_cloud.hap.AsyncAuth.init",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.components.homematicip_cloud.hap.AsyncHome.init",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.homematicip_cloud.hap.AsyncAuth.init",
+ return_value=None,
+ ),
):
yield
diff --git a/tests/components/homematicip_cloud/test_config_flow.py b/tests/components/homematicip_cloud/test_config_flow.py
index d560293dd66..4b0d1c26b8f 100644
--- a/tests/components/homematicip_cloud/test_config_flow.py
+++ b/tests/components/homematicip_cloud/test_config_flow.py
@@ -22,12 +22,15 @@ IMPORT_CONFIG = {HMIPC_HAPID: "ABC123", HMIPC_AUTHTOKEN: "123", HMIPC_NAME: "hmi
async def test_flow_works(hass: HomeAssistant, simple_mock_home) -> None:
"""Test config flow."""
- with patch(
- "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_checkbutton",
- return_value=False,
- ), patch(
- "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.get_auth",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_checkbutton",
+ return_value=False,
+ ),
+ patch(
+ "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.get_auth",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_init(
HMIPC_DOMAIN,
@@ -46,17 +49,22 @@ async def test_flow_works(hass: HomeAssistant, simple_mock_home) -> None:
)
assert flow["context"]["unique_id"] == "ABC123"
- with patch(
- "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_checkbutton",
- return_value=True,
- ), patch(
- "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_setup",
- return_value=True,
- ), patch(
- "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_register",
- return_value=True,
- ), patch(
- "homeassistant.components.homematicip_cloud.hap.HomematicipHAP.async_connect",
+ with (
+ patch(
+ "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_checkbutton",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_setup",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_register",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.homematicip_cloud.hap.HomematicipHAP.async_connect",
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
@@ -86,15 +94,19 @@ async def test_flow_init_connection_error(hass: HomeAssistant) -> None:
async def test_flow_link_connection_error(hass: HomeAssistant) -> None:
"""Test config flow client registration connection error."""
- with patch(
- "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_checkbutton",
- return_value=True,
- ), patch(
- "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_setup",
- return_value=True,
- ), patch(
- "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_register",
- return_value=False,
+ with (
+ patch(
+ "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_checkbutton",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_setup",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_register",
+ return_value=False,
+ ),
):
result = await hass.config_entries.flow.async_init(
HMIPC_DOMAIN,
@@ -108,12 +120,15 @@ async def test_flow_link_connection_error(hass: HomeAssistant) -> None:
async def test_flow_link_press_button(hass: HomeAssistant) -> None:
"""Test config flow ask for pressing the blue button."""
- with patch(
- "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_checkbutton",
- return_value=False,
- ), patch(
- "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_setup",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_checkbutton",
+ return_value=False,
+ ),
+ patch(
+ "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_setup",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_init(
HMIPC_DOMAIN,
@@ -155,17 +170,22 @@ async def test_init_already_configured(hass: HomeAssistant) -> None:
async def test_import_config(hass: HomeAssistant, simple_mock_home) -> None:
"""Test importing a host with an existing config file."""
- with patch(
- "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_checkbutton",
- return_value=True,
- ), patch(
- "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_setup",
- return_value=True,
- ), patch(
- "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_register",
- return_value=True,
- ), patch(
- "homeassistant.components.homematicip_cloud.hap.HomematicipHAP.async_connect",
+ with (
+ patch(
+ "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_checkbutton",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_setup",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_register",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.homematicip_cloud.hap.HomematicipHAP.async_connect",
+ ),
):
result = await hass.config_entries.flow.async_init(
HMIPC_DOMAIN,
@@ -182,15 +202,19 @@ async def test_import_config(hass: HomeAssistant, simple_mock_home) -> None:
async def test_import_existing_config(hass: HomeAssistant) -> None:
"""Test abort of an existing accesspoint from config."""
MockConfigEntry(domain=HMIPC_DOMAIN, unique_id="ABC123").add_to_hass(hass)
- with patch(
- "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_checkbutton",
- return_value=True,
- ), patch(
- "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_setup",
- return_value=True,
- ), patch(
- "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_register",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_checkbutton",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_setup",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.homematicip_cloud.hap.HomematicipAuth.async_register",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_init(
HMIPC_DOMAIN,
diff --git a/tests/components/homematicip_cloud/test_device.py b/tests/components/homematicip_cloud/test_device.py
index facb12ed8ea..9fc1f518c64 100644
--- a/tests/components/homematicip_cloud/test_device.py
+++ b/tests/components/homematicip_cloud/test_device.py
@@ -97,13 +97,16 @@ async def test_hmip_add_device(
assert len(mock_hap.hmip_device_by_entity_id) == pre_mapping_count - 3
reloaded_hap = HomematicipHAP(hass, hmip_config_entry)
- with patch(
- "homeassistant.components.homematicip_cloud.HomematicipHAP",
- return_value=reloaded_hap,
- ), patch.object(reloaded_hap, "async_connect"), patch.object(
- reloaded_hap, "get_hap", return_value=mock_hap.home
- ), patch(
- "homeassistant.components.homematicip_cloud.hap.asyncio.sleep",
+ with (
+ patch(
+ "homeassistant.components.homematicip_cloud.HomematicipHAP",
+ return_value=reloaded_hap,
+ ),
+ patch.object(reloaded_hap, "async_connect"),
+ patch.object(reloaded_hap, "get_hap", return_value=mock_hap.home),
+ patch(
+ "homeassistant.components.homematicip_cloud.hap.asyncio.sleep",
+ ),
):
mock_hap.home.fire_create_event(event_type=EventType.DEVICE_ADDED)
await hass.async_block_till_done()
diff --git a/tests/components/homematicip_cloud/test_hap.py b/tests/components/homematicip_cloud/test_hap.py
index 72bdb5cc0fc..cddade7cec5 100644
--- a/tests/components/homematicip_cloud/test_hap.py
+++ b/tests/components/homematicip_cloud/test_hap.py
@@ -49,13 +49,13 @@ async def test_auth_auth_check_and_register(hass: HomeAssistant) -> None:
hmip_auth = HomematicipAuth(hass, config)
hmip_auth.auth = Mock(spec=AsyncAuth)
- with patch.object(
- hmip_auth.auth, "isRequestAcknowledged", return_value=True
- ), patch.object(
- hmip_auth.auth, "requestAuthToken", return_value="ABC"
- ), patch.object(
- hmip_auth.auth,
- "confirmAuthToken",
+ with (
+ patch.object(hmip_auth.auth, "isRequestAcknowledged", return_value=True),
+ patch.object(hmip_auth.auth, "requestAuthToken", return_value="ABC"),
+ patch.object(
+ hmip_auth.auth,
+ "confirmAuthToken",
+ ),
):
assert await hmip_auth.async_checkbutton()
assert await hmip_auth.async_register() == "ABC"
@@ -66,10 +66,13 @@ async def test_auth_auth_check_and_register_with_exception(hass: HomeAssistant)
config = {HMIPC_HAPID: "ABC123", HMIPC_PIN: "123", HMIPC_NAME: "hmip"}
hmip_auth = HomematicipAuth(hass, config)
hmip_auth.auth = Mock(spec=AsyncAuth)
- with patch.object(
- hmip_auth.auth, "isRequestAcknowledged", side_effect=HmipConnectionError
- ), patch.object(
- hmip_auth.auth, "requestAuthToken", side_effect=HmipConnectionError
+ with (
+ patch.object(
+ hmip_auth.auth, "isRequestAcknowledged", side_effect=HmipConnectionError
+ ),
+ patch.object(
+ hmip_auth.auth, "requestAuthToken", side_effect=HmipConnectionError
+ ),
):
assert not await hmip_auth.async_checkbutton()
assert await hmip_auth.async_register() is False
@@ -96,8 +99,9 @@ async def test_hap_setup_connection_error() -> None:
entry = Mock()
entry.data = {HMIPC_HAPID: "ABC123", HMIPC_AUTHTOKEN: "123", HMIPC_NAME: "hmip"}
hap = HomematicipHAP(hass, entry)
- with patch.object(hap, "get_hap", side_effect=HmipcConnectionError), pytest.raises(
- ConfigEntryNotReady
+ with (
+ patch.object(hap, "get_hap", side_effect=HmipcConnectionError),
+ pytest.raises(ConfigEntryNotReady),
):
assert not await hap.async_setup()
@@ -146,10 +150,13 @@ async def test_hap_create_exception(
):
assert not await hap.async_setup()
- with patch(
- "homeassistant.components.homematicip_cloud.hap.AsyncHome.get_current_state",
- side_effect=HmipConnectionError,
- ), pytest.raises(ConfigEntryNotReady):
+ with (
+ patch(
+ "homeassistant.components.homematicip_cloud.hap.AsyncHome.get_current_state",
+ side_effect=HmipConnectionError,
+ ),
+ pytest.raises(ConfigEntryNotReady),
+ ):
await hap.async_setup()
diff --git a/tests/components/homematicip_cloud/test_init.py b/tests/components/homematicip_cloud/test_init.py
index d3e89e1bbb9..9303a755e89 100644
--- a/tests/components/homematicip_cloud/test_init.py
+++ b/tests/components/homematicip_cloud/test_init.py
@@ -121,11 +121,14 @@ async def test_load_entry_fails_due_to_generic_exception(
"""Test load entry fails due to generic exception."""
hmip_config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.homematicip_cloud.hap.AsyncHome.get_current_state",
- side_effect=Exception,
- ), patch(
- "homematicip.aio.connection.AsyncConnection.init",
+ with (
+ patch(
+ "homeassistant.components.homematicip_cloud.hap.AsyncHome.get_current_state",
+ side_effect=Exception,
+ ),
+ patch(
+ "homematicip.aio.connection.AsyncConnection.init",
+ ),
):
assert await async_setup_component(hass, HMIPC_DOMAIN, {})
diff --git a/tests/components/homewizard/conftest.py b/tests/components/homewizard/conftest.py
index 4f78449af82..bc661da390d 100644
--- a/tests/components/homewizard/conftest.py
+++ b/tests/components/homewizard/conftest.py
@@ -25,12 +25,15 @@ def mock_homewizardenergy(
device_fixture: str,
) -> MagicMock:
"""Return a mock bridge."""
- with patch(
- "homeassistant.components.homewizard.coordinator.HomeWizardEnergy",
- autospec=True,
- ) as homewizard, patch(
- "homeassistant.components.homewizard.config_flow.HomeWizardEnergy",
- new=homewizard,
+ with (
+ patch(
+ "homeassistant.components.homewizard.coordinator.HomeWizardEnergy",
+ autospec=True,
+ ) as homewizard,
+ patch(
+ "homeassistant.components.homewizard.config_flow.HomeWizardEnergy",
+ new=homewizard,
+ ),
):
client = homewizard.return_value
diff --git a/tests/components/homeworks/conftest.py b/tests/components/homeworks/conftest.py
index b446ce03c5e..ccff56ae3d1 100644
--- a/tests/components/homeworks/conftest.py
+++ b/tests/components/homeworks/conftest.py
@@ -90,10 +90,14 @@ def mock_empty_config_entry() -> MockConfigEntry:
@pytest.fixture
def mock_homeworks() -> Generator[None, MagicMock, None]:
"""Return a mocked Homeworks client."""
- with patch(
- "homeassistant.components.homeworks.Homeworks", autospec=True
- ) as homeworks_mock, patch(
- "homeassistant.components.homeworks.config_flow.Homeworks", new=homeworks_mock
+ with (
+ patch(
+ "homeassistant.components.homeworks.Homeworks", autospec=True
+ ) as homeworks_mock,
+ patch(
+ "homeassistant.components.homeworks.config_flow.Homeworks",
+ new=homeworks_mock,
+ ),
):
yield homeworks_mock
diff --git a/tests/components/honeywell/test_sensor.py b/tests/components/honeywell/test_sensor.py
index 424764847be..ed46fd4cdd2 100644
--- a/tests/components/honeywell/test_sensor.py
+++ b/tests/components/honeywell/test_sensor.py
@@ -20,9 +20,9 @@ async def test_outdoor_sensor(
) -> None:
"""Test outdoor temperature sensor."""
device_with_outdoor_sensor.temperature_unit = unit
- location.devices_by_id[
- device_with_outdoor_sensor.deviceid
- ] = device_with_outdoor_sensor
+ location.devices_by_id[device_with_outdoor_sensor.deviceid] = (
+ device_with_outdoor_sensor
+ )
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/http/test_ban.py b/tests/components/http/test_ban.py
index ee8f8c80864..a10aa740268 100644
--- a/tests/components/http/test_ban.py
+++ b/tests/components/http/test_ban.py
@@ -36,10 +36,14 @@ BANNED_IPS_WITH_SUPERVISOR = [*BANNED_IPS, SUPERVISOR_IP]
@pytest.fixture(name="hassio_env")
def hassio_env_fixture():
"""Fixture to inject hassio env."""
- with patch.dict(os.environ, {"SUPERVISOR": "127.0.0.1"}), patch(
- "homeassistant.components.hassio.HassIO.is_connected",
- return_value={"result": "ok", "data": {}},
- ), patch.dict(os.environ, {"SUPERVISOR_TOKEN": "123456"}):
+ with (
+ patch.dict(os.environ, {"SUPERVISOR": "127.0.0.1"}),
+ patch(
+ "homeassistant.components.hassio.HassIO.is_connected",
+ return_value={"result": "ok", "data": {}},
+ ),
+ patch.dict(os.environ, {"SUPERVISOR_TOKEN": "123456"}),
+ ):
yield
@@ -231,8 +235,9 @@ async def test_access_from_supervisor_ip(
m_open = mock_open()
- with patch.dict(os.environ, {"SUPERVISOR": SUPERVISOR_IP}), patch(
- "homeassistant.components.http.ban.open", m_open, create=True
+ with (
+ patch.dict(os.environ, {"SUPERVISOR": SUPERVISOR_IP}),
+ patch("homeassistant.components.http.ban.open", m_open, create=True),
):
resp = await client.get("/")
assert resp.status == HTTPStatus.UNAUTHORIZED
diff --git a/tests/components/http/test_init.py b/tests/components/http/test_init.py
index 35678c08d38..98e97d0fe57 100644
--- a/tests/components/http/test_init.py
+++ b/tests/components/http/test_init.py
@@ -173,10 +173,13 @@ async def test_ssl_profile_defaults_modern(hass: HomeAssistant, tmp_path: Path)
_setup_empty_ssl_pem_files, tmp_path
)
- with patch("ssl.SSLContext.load_cert_chain"), patch(
- "homeassistant.util.ssl.server_context_modern",
- side_effect=server_context_modern,
- ) as mock_context:
+ with (
+ patch("ssl.SSLContext.load_cert_chain"),
+ patch(
+ "homeassistant.util.ssl.server_context_modern",
+ side_effect=server_context_modern,
+ ) as mock_context,
+ ):
assert (
await async_setup_component(
hass,
@@ -200,10 +203,13 @@ async def test_ssl_profile_change_intermediate(
_setup_empty_ssl_pem_files, tmp_path
)
- with patch("ssl.SSLContext.load_cert_chain"), patch(
- "homeassistant.util.ssl.server_context_intermediate",
- side_effect=server_context_intermediate,
- ) as mock_context:
+ with (
+ patch("ssl.SSLContext.load_cert_chain"),
+ patch(
+ "homeassistant.util.ssl.server_context_intermediate",
+ side_effect=server_context_intermediate,
+ ) as mock_context,
+ ):
assert (
await async_setup_component(
hass,
@@ -231,10 +237,13 @@ async def test_ssl_profile_change_modern(hass: HomeAssistant, tmp_path: Path) ->
_setup_empty_ssl_pem_files, tmp_path
)
- with patch("ssl.SSLContext.load_cert_chain"), patch(
- "homeassistant.util.ssl.server_context_modern",
- side_effect=server_context_modern,
- ) as mock_context:
+ with (
+ patch("ssl.SSLContext.load_cert_chain"),
+ patch(
+ "homeassistant.util.ssl.server_context_modern",
+ side_effect=server_context_modern,
+ ) as mock_context,
+ ):
assert (
await async_setup_component(
hass,
@@ -261,12 +270,14 @@ async def test_peer_cert(hass: HomeAssistant, tmp_path: Path) -> None:
_setup_empty_ssl_pem_files, tmp_path
)
- with patch("ssl.SSLContext.load_cert_chain"), patch(
- "ssl.SSLContext.load_verify_locations"
- ) as mock_load_verify_locations, patch(
- "homeassistant.util.ssl.server_context_modern",
- side_effect=server_context_modern,
- ) as mock_context:
+ with (
+ patch("ssl.SSLContext.load_cert_chain"),
+ patch("ssl.SSLContext.load_verify_locations") as mock_load_verify_locations,
+ patch(
+ "homeassistant.util.ssl.server_context_modern",
+ side_effect=server_context_modern,
+ ) as mock_context,
+ ):
assert (
await async_setup_component(
hass,
diff --git a/tests/components/huawei_lte/test_config_flow.py b/tests/components/huawei_lte/test_config_flow.py
index cc4a32a7df5..f8ddaa42ac1 100644
--- a/tests/components/huawei_lte/test_config_flow.py
+++ b/tests/components/huawei_lte/test_config_flow.py
@@ -239,8 +239,9 @@ async def test_success(hass: HomeAssistant, login_requests_mock, scheme: str) ->
f"{user_input[CONF_URL]}api/user/login",
text="OK",
)
- with patch("homeassistant.components.huawei_lte.async_setup"), patch(
- "homeassistant.components.huawei_lte.async_setup_entry"
+ with (
+ patch("homeassistant.components.huawei_lte.async_setup"),
+ patch("homeassistant.components.huawei_lte.async_setup_entry"),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
diff --git a/tests/components/hue/test_bridge.py b/tests/components/hue/test_bridge.py
index ce1b3f34674..5d103e47870 100644
--- a/tests/components/hue/test_bridge.py
+++ b/tests/components/hue/test_bridge.py
@@ -29,9 +29,10 @@ async def test_bridge_setup_v1(hass: HomeAssistant, mock_api_v1) -> None:
options={CONF_ALLOW_HUE_GROUPS: False, CONF_ALLOW_UNREACHABLE: False},
)
- with patch.object(bridge, "HueBridgeV1", return_value=mock_api_v1), patch.object(
- hass.config_entries, "async_forward_entry_setups"
- ) as mock_forward:
+ with (
+ patch.object(bridge, "HueBridgeV1", return_value=mock_api_v1),
+ patch.object(hass.config_entries, "async_forward_entry_setups") as mock_forward,
+ ):
hue_bridge = bridge.HueBridge(hass, config_entry)
assert await hue_bridge.async_initialize_bridge() is True
@@ -50,9 +51,10 @@ async def test_bridge_setup_v2(hass: HomeAssistant, mock_api_v2) -> None:
data={"host": "1.2.3.4", "api_key": "mock-api-key", "api_version": 2},
)
- with patch.object(bridge, "HueBridgeV2", return_value=mock_api_v2), patch.object(
- hass.config_entries, "async_forward_entry_setups"
- ) as mock_forward:
+ with (
+ patch.object(bridge, "HueBridgeV2", return_value=mock_api_v2),
+ patch.object(hass.config_entries, "async_forward_entry_setups") as mock_forward,
+ ):
hue_bridge = bridge.HueBridge(hass, config_entry)
assert await hue_bridge.async_initialize_bridge() is True
@@ -80,9 +82,10 @@ async def test_bridge_setup_invalid_api_key(hass: HomeAssistant) -> None:
)
hue_bridge = bridge.HueBridge(hass, entry)
- with patch.object(
- hue_bridge.api, "initialize", side_effect=Unauthorized
- ), patch.object(hass.config_entries.flow, "async_init") as mock_init:
+ with (
+ patch.object(hue_bridge.api, "initialize", side_effect=Unauthorized),
+ patch.object(hass.config_entries.flow, "async_init") as mock_init,
+ ):
assert await hue_bridge.async_initialize_bridge() is False
assert len(mock_init.mock_calls) == 1
@@ -98,11 +101,14 @@ async def test_bridge_setup_timeout(hass: HomeAssistant) -> None:
)
hue_bridge = bridge.HueBridge(hass, entry)
- with patch.object(
- hue_bridge.api,
- "initialize",
- side_effect=client_exceptions.ServerDisconnectedError,
- ), pytest.raises(ConfigEntryNotReady):
+ with (
+ patch.object(
+ hue_bridge.api,
+ "initialize",
+ side_effect=client_exceptions.ServerDisconnectedError,
+ ),
+ pytest.raises(ConfigEntryNotReady),
+ ):
await hue_bridge.async_initialize_bridge()
@@ -114,9 +120,10 @@ async def test_reset_unloads_entry_if_setup(hass: HomeAssistant, mock_api_v1) ->
options={CONF_ALLOW_HUE_GROUPS: False, CONF_ALLOW_UNREACHABLE: False},
)
- with patch.object(bridge, "HueBridgeV1", return_value=mock_api_v1), patch.object(
- hass.config_entries, "async_forward_entry_setups"
- ) as mock_forward:
+ with (
+ patch.object(bridge, "HueBridgeV1", return_value=mock_api_v1),
+ patch.object(hass.config_entries, "async_forward_entry_setups") as mock_forward,
+ ):
hue_bridge = bridge.HueBridge(hass, config_entry)
assert await hue_bridge.async_initialize_bridge() is True
diff --git a/tests/components/hue/test_config_flow.py b/tests/components/hue/test_config_flow.py
index 7d7ef0eaf38..74cceb03aba 100644
--- a/tests/components/hue/test_config_flow.py
+++ b/tests/components/hue/test_config_flow.py
@@ -126,8 +126,9 @@ async def test_manual_flow_works(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["step_id"] == "link"
- with patch.object(config_flow, "create_app_key", return_value="123456789"), patch(
- "homeassistant.components.hue.async_unload_entry", return_value=True
+ with (
+ patch.object(config_flow, "create_app_key", return_value="123456789"),
+ patch("homeassistant.components.hue.async_unload_entry", return_value=True),
):
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
@@ -387,10 +388,13 @@ async def test_creating_entry_removes_entries_for_same_host_or_bridge(
assert result["type"] == "form"
assert result["step_id"] == "link"
- with patch(
- "homeassistant.components.hue.config_flow.create_app_key",
- return_value="123456789",
- ), patch("homeassistant.components.hue.async_unload_entry", return_value=True):
+ with (
+ patch(
+ "homeassistant.components.hue.config_flow.create_app_key",
+ return_value="123456789",
+ ),
+ patch("homeassistant.components.hue.async_unload_entry", return_value=True),
+ ):
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] == "create_entry"
diff --git a/tests/components/hue/test_init.py b/tests/components/hue/test_init.py
index 8f5820baf1c..5ce0d78ead9 100644
--- a/tests/components/hue/test_init.py
+++ b/tests/components/hue/test_init.py
@@ -148,15 +148,18 @@ async def test_security_vuln_check(hass: HomeAssistant) -> None:
)
config.name = "Hue"
- with patch.object(hue.migration, "is_v2_bridge", return_value=False), patch.object(
- hue,
- "HueBridge",
- Mock(
- return_value=Mock(
- async_initialize_bridge=AsyncMock(return_value=True),
- api=Mock(config=config),
- api_version=1,
- )
+ with (
+ patch.object(hue.migration, "is_v2_bridge", return_value=False),
+ patch.object(
+ hue,
+ "HueBridge",
+ Mock(
+ return_value=Mock(
+ async_initialize_bridge=AsyncMock(return_value=True),
+ api=Mock(config=config),
+ api_version=1,
+ )
+ ),
),
):
assert await async_setup_component(hass, "hue", {})
diff --git a/tests/components/hue/test_migration.py b/tests/components/hue/test_migration.py
index 88e7de47b07..adcc582a314 100644
--- a/tests/components/hue/test_migration.py
+++ b/tests/components/hue/test_migration.py
@@ -33,9 +33,10 @@ async def test_auto_switchover(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with patch.object(hue.migration, "is_v2_bridge", retun_value=True), patch.object(
- hue.migration, "handle_v2_migration"
- ) as mock_mig:
+ with (
+ patch.object(hue.migration, "is_v2_bridge", retun_value=True),
+ patch.object(hue.migration, "handle_v2_migration") as mock_mig,
+ ):
await hue.migration.check_migration(hass, config_entry)
assert len(mock_mig.mock_calls) == 1
# the api version should now be version 2
diff --git a/tests/components/hue/test_services.py b/tests/components/hue/test_services.py
index 0e80bb2ea08..8139bfa034c 100644
--- a/tests/components/hue/test_services.py
+++ b/tests/components/hue/test_services.py
@@ -62,8 +62,9 @@ async def test_hue_activate_scene(hass: HomeAssistant, mock_api_v1) -> None:
mock_api_v1.mock_group_responses.append(GROUP_RESPONSE)
mock_api_v1.mock_scene_responses.append(SCENE_RESPONSE)
- with patch.object(bridge, "HueBridgeV1", return_value=mock_api_v1), patch.object(
- hass.config_entries, "async_forward_entry_setups"
+ with (
+ patch.object(bridge, "HueBridgeV1", return_value=mock_api_v1),
+ patch.object(hass.config_entries, "async_forward_entry_setups"),
):
hue_bridge = bridge.HueBridge(hass, config_entry)
assert await hue_bridge.async_initialize_bridge() is True
@@ -99,8 +100,9 @@ async def test_hue_activate_scene_transition(hass: HomeAssistant, mock_api_v1) -
mock_api_v1.mock_group_responses.append(GROUP_RESPONSE)
mock_api_v1.mock_scene_responses.append(SCENE_RESPONSE)
- with patch.object(bridge, "HueBridgeV1", return_value=mock_api_v1), patch.object(
- hass.config_entries, "async_forward_entry_setups"
+ with (
+ patch.object(bridge, "HueBridgeV1", return_value=mock_api_v1),
+ patch.object(hass.config_entries, "async_forward_entry_setups"),
):
hue_bridge = bridge.HueBridge(hass, config_entry)
assert await hue_bridge.async_initialize_bridge() is True
@@ -138,8 +140,9 @@ async def test_hue_activate_scene_group_not_found(
mock_api_v1.mock_group_responses.append({})
mock_api_v1.mock_scene_responses.append(SCENE_RESPONSE)
- with patch.object(bridge, "HueBridgeV1", return_value=mock_api_v1), patch.object(
- hass.config_entries, "async_forward_entry_setups"
+ with (
+ patch.object(bridge, "HueBridgeV1", return_value=mock_api_v1),
+ patch.object(hass.config_entries, "async_forward_entry_setups"),
):
hue_bridge = bridge.HueBridge(hass, config_entry)
assert await hue_bridge.async_initialize_bridge() is True
@@ -172,8 +175,9 @@ async def test_hue_activate_scene_scene_not_found(
mock_api_v1.mock_group_responses.append(GROUP_RESPONSE)
mock_api_v1.mock_scene_responses.append({})
- with patch.object(bridge, "HueBridgeV1", return_value=mock_api_v1), patch.object(
- hass.config_entries, "async_forward_entry_setups"
+ with (
+ patch.object(bridge, "HueBridgeV1", return_value=mock_api_v1),
+ patch.object(hass.config_entries, "async_forward_entry_setups"),
):
hue_bridge = bridge.HueBridge(hass, config_entry)
assert await hue_bridge.async_initialize_bridge() is True
diff --git a/tests/components/huisbaasje/test_config_flow.py b/tests/components/huisbaasje/test_config_flow.py
index 0283f4d3fb0..0c65d425d4d 100644
--- a/tests/components/huisbaasje/test_config_flow.py
+++ b/tests/components/huisbaasje/test_config_flow.py
@@ -24,17 +24,22 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "energyflip.EnergyFlip.authenticate", return_value=None
- ) as mock_authenticate, patch(
- "energyflip.EnergyFlip.customer_overview", return_value=None
- ) as mock_customer_overview, patch(
- "energyflip.EnergyFlip.get_user_id",
- return_value="test-id",
- ) as mock_get_user_id, patch(
- "homeassistant.components.huisbaasje.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "energyflip.EnergyFlip.authenticate", return_value=None
+ ) as mock_authenticate,
+ patch(
+ "energyflip.EnergyFlip.customer_overview", return_value=None
+ ) as mock_customer_overview,
+ patch(
+ "energyflip.EnergyFlip.get_user_id",
+ return_value="test-id",
+ ) as mock_get_user_id,
+ patch(
+ "homeassistant.components.huisbaasje.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
form_result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -129,9 +134,12 @@ async def test_form_customer_overview_cannot_connect(hass: HomeAssistant) -> Non
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch("energyflip.EnergyFlip.authenticate", return_value=None), patch(
- "energyflip.EnergyFlip.customer_overview",
- side_effect=EnergyFlipConnectionException,
+ with (
+ patch("energyflip.EnergyFlip.authenticate", return_value=None),
+ patch(
+ "energyflip.EnergyFlip.customer_overview",
+ side_effect=EnergyFlipConnectionException,
+ ),
):
form_result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -151,9 +159,12 @@ async def test_form_customer_overview_authentication_error(hass: HomeAssistant)
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch("energyflip.EnergyFlip.authenticate", return_value=None), patch(
- "energyflip.EnergyFlip.customer_overview",
- side_effect=EnergyFlipUnauthenticatedException,
+ with (
+ patch("energyflip.EnergyFlip.authenticate", return_value=None),
+ patch(
+ "energyflip.EnergyFlip.customer_overview",
+ side_effect=EnergyFlipUnauthenticatedException,
+ ),
):
form_result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -173,9 +184,12 @@ async def test_form_customer_overview_unknown_error(hass: HomeAssistant) -> None
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch("energyflip.EnergyFlip.authenticate", return_value=None), patch(
- "energyflip.EnergyFlip.customer_overview",
- side_effect=Exception,
+ with (
+ patch("energyflip.EnergyFlip.authenticate", return_value=None),
+ patch(
+ "energyflip.EnergyFlip.customer_overview",
+ side_effect=Exception,
+ ),
):
form_result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -206,14 +220,17 @@ async def test_form_entry_exists(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch("energyflip.EnergyFlip.authenticate", return_value=None), patch(
- "energyflip.EnergyFlip.customer_overview", return_value=None
- ), patch(
- "energyflip.EnergyFlip.get_user_id",
- return_value="test-id",
- ), patch(
- "homeassistant.components.huisbaasje.async_setup_entry",
- return_value=True,
+ with (
+ patch("energyflip.EnergyFlip.authenticate", return_value=None),
+ patch("energyflip.EnergyFlip.customer_overview", return_value=None),
+ patch(
+ "energyflip.EnergyFlip.get_user_id",
+ return_value="test-id",
+ ),
+ patch(
+ "homeassistant.components.huisbaasje.async_setup_entry",
+ return_value=True,
+ ),
):
form_result = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/huisbaasje/test_init.py b/tests/components/huisbaasje/test_init.py
index c465ae02490..5f1bcb0094d 100644
--- a/tests/components/huisbaasje/test_init.py
+++ b/tests/components/huisbaasje/test_init.py
@@ -24,14 +24,18 @@ async def test_setup(hass: HomeAssistant) -> None:
async def test_setup_entry(hass: HomeAssistant) -> None:
"""Test for successfully setting a config entry."""
- with patch(
- "energyflip.EnergyFlip.authenticate", return_value=None
- ) as mock_authenticate, patch(
- "energyflip.EnergyFlip.is_authenticated", return_value=True
- ) as mock_is_authenticated, patch(
- "energyflip.EnergyFlip.current_measurements",
- return_value=MOCK_CURRENT_MEASUREMENTS,
- ) as mock_current_measurements:
+ with (
+ patch(
+ "energyflip.EnergyFlip.authenticate", return_value=None
+ ) as mock_authenticate,
+ patch(
+ "energyflip.EnergyFlip.is_authenticated", return_value=True
+ ) as mock_is_authenticated,
+ patch(
+ "energyflip.EnergyFlip.current_measurements",
+ return_value=MOCK_CURRENT_MEASUREMENTS,
+ ) as mock_current_measurements,
+ ):
hass.config.components.add(huisbaasje.DOMAIN)
config_entry = MockConfigEntry(
version=1,
@@ -103,14 +107,18 @@ async def test_setup_entry_error(hass: HomeAssistant) -> None:
async def test_unload_entry(hass: HomeAssistant) -> None:
"""Test for successfully unloading the config entry."""
- with patch(
- "energyflip.EnergyFlip.authenticate", return_value=None
- ) as mock_authenticate, patch(
- "energyflip.EnergyFlip.is_authenticated", return_value=True
- ) as mock_is_authenticated, patch(
- "energyflip.EnergyFlip.current_measurements",
- return_value=MOCK_CURRENT_MEASUREMENTS,
- ) as mock_current_measurements:
+ with (
+ patch(
+ "energyflip.EnergyFlip.authenticate", return_value=None
+ ) as mock_authenticate,
+ patch(
+ "energyflip.EnergyFlip.is_authenticated", return_value=True
+ ) as mock_is_authenticated,
+ patch(
+ "energyflip.EnergyFlip.current_measurements",
+ return_value=MOCK_CURRENT_MEASUREMENTS,
+ ) as mock_current_measurements,
+ ):
hass.config.components.add(huisbaasje.DOMAIN)
config_entry = MockConfigEntry(
version=1,
diff --git a/tests/components/huisbaasje/test_sensor.py b/tests/components/huisbaasje/test_sensor.py
index d04ad8cf35f..02a05c78763 100644
--- a/tests/components/huisbaasje/test_sensor.py
+++ b/tests/components/huisbaasje/test_sensor.py
@@ -28,14 +28,18 @@ from tests.common import MockConfigEntry
async def test_setup_entry(hass: HomeAssistant) -> None:
"""Test for successfully loading sensor states."""
- with patch(
- "energyflip.EnergyFlip.authenticate", return_value=None
- ) as mock_authenticate, patch(
- "energyflip.EnergyFlip.is_authenticated", return_value=True
- ) as mock_is_authenticated, patch(
- "energyflip.EnergyFlip.current_measurements",
- return_value=MOCK_CURRENT_MEASUREMENTS,
- ) as mock_current_measurements:
+ with (
+ patch(
+ "energyflip.EnergyFlip.authenticate", return_value=None
+ ) as mock_authenticate,
+ patch(
+ "energyflip.EnergyFlip.is_authenticated", return_value=True
+ ) as mock_is_authenticated,
+ patch(
+ "energyflip.EnergyFlip.current_measurements",
+ return_value=MOCK_CURRENT_MEASUREMENTS,
+ ) as mock_current_measurements,
+ ):
hass.config.components.add(huisbaasje.DOMAIN)
config_entry = MockConfigEntry(
version=1,
@@ -315,14 +319,18 @@ async def test_setup_entry(hass: HomeAssistant) -> None:
async def test_setup_entry_absent_measurement(hass: HomeAssistant) -> None:
"""Test for successfully loading sensor states when response does not contain all measurements."""
- with patch(
- "energyflip.EnergyFlip.authenticate", return_value=None
- ) as mock_authenticate, patch(
- "energyflip.EnergyFlip.is_authenticated", return_value=True
- ) as mock_is_authenticated, patch(
- "energyflip.EnergyFlip.current_measurements",
- return_value=MOCK_LIMITED_CURRENT_MEASUREMENTS,
- ) as mock_current_measurements:
+ with (
+ patch(
+ "energyflip.EnergyFlip.authenticate", return_value=None
+ ) as mock_authenticate,
+ patch(
+ "energyflip.EnergyFlip.is_authenticated", return_value=True
+ ) as mock_is_authenticated,
+ patch(
+ "energyflip.EnergyFlip.current_measurements",
+ return_value=MOCK_LIMITED_CURRENT_MEASUREMENTS,
+ ) as mock_current_measurements,
+ ):
hass.config.components.add(huisbaasje.DOMAIN)
config_entry = MockConfigEntry(
version=1,
diff --git a/tests/components/hunterdouglas_powerview/conftest.py b/tests/components/hunterdouglas_powerview/conftest.py
index be7dec42dea..e55e252f670 100644
--- a/tests/components/hunterdouglas_powerview/conftest.py
+++ b/tests/components/hunterdouglas_powerview/conftest.py
@@ -31,30 +31,39 @@ def mock_hunterdouglas_hub(
shades_json: str,
) -> Generator[MagicMock, None, None]:
"""Return a mocked Powerview Hub with all data populated."""
- with patch(
- "homeassistant.components.hunterdouglas_powerview.Hub.request_raw_data",
- return_value=load_json_object_fixture(device_json, DOMAIN),
- ), patch(
- "homeassistant.components.hunterdouglas_powerview.Hub.request_home_data",
- return_value=load_json_object_fixture(home_json, DOMAIN),
- ), patch(
- "homeassistant.components.hunterdouglas_powerview.Hub.request_raw_firmware",
- return_value=load_json_object_fixture(firmware_json, DOMAIN),
- ), patch(
- "homeassistant.components.hunterdouglas_powerview.Rooms.get_resources",
- return_value=load_json_value_fixture(rooms_json, DOMAIN),
- ), patch(
- "homeassistant.components.hunterdouglas_powerview.Scenes.get_resources",
- return_value=load_json_value_fixture(scenes_json, DOMAIN),
- ), patch(
- "homeassistant.components.hunterdouglas_powerview.Shades.get_resources",
- return_value=load_json_value_fixture(shades_json, DOMAIN),
- ), patch(
- "homeassistant.components.hunterdouglas_powerview.cover.BaseShade.refresh",
- ), patch(
- "homeassistant.components.hunterdouglas_powerview.cover.BaseShade.current_position",
- new_callable=PropertyMock,
- return_value=ShadePosition(primary=0, secondary=0, tilt=0, velocity=0),
+ with (
+ patch(
+ "homeassistant.components.hunterdouglas_powerview.Hub.request_raw_data",
+ return_value=load_json_object_fixture(device_json, DOMAIN),
+ ),
+ patch(
+ "homeassistant.components.hunterdouglas_powerview.Hub.request_home_data",
+ return_value=load_json_object_fixture(home_json, DOMAIN),
+ ),
+ patch(
+ "homeassistant.components.hunterdouglas_powerview.Hub.request_raw_firmware",
+ return_value=load_json_object_fixture(firmware_json, DOMAIN),
+ ),
+ patch(
+ "homeassistant.components.hunterdouglas_powerview.Rooms.get_resources",
+ return_value=load_json_value_fixture(rooms_json, DOMAIN),
+ ),
+ patch(
+ "homeassistant.components.hunterdouglas_powerview.Scenes.get_resources",
+ return_value=load_json_value_fixture(scenes_json, DOMAIN),
+ ),
+ patch(
+ "homeassistant.components.hunterdouglas_powerview.Shades.get_resources",
+ return_value=load_json_value_fixture(shades_json, DOMAIN),
+ ),
+ patch(
+ "homeassistant.components.hunterdouglas_powerview.cover.BaseShade.refresh",
+ ),
+ patch(
+ "homeassistant.components.hunterdouglas_powerview.cover.BaseShade.current_position",
+ new_callable=PropertyMock,
+ return_value=ShadePosition(primary=0, secondary=0, tilt=0, velocity=0),
+ ),
):
yield
diff --git a/tests/components/hunterdouglas_powerview/test_config_flow.py b/tests/components/hunterdouglas_powerview/test_config_flow.py
index b98af94870b..ac4f6368f38 100644
--- a/tests/components/hunterdouglas_powerview/test_config_flow.py
+++ b/tests/components/hunterdouglas_powerview/test_config_flow.py
@@ -242,12 +242,15 @@ async def test_form_no_data(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "homeassistant.components.hunterdouglas_powerview.Hub.request_raw_data",
- return_value={},
- ), patch(
- "homeassistant.components.hunterdouglas_powerview.Hub.request_home_data",
- return_value={},
+ with (
+ patch(
+ "homeassistant.components.hunterdouglas_powerview.Hub.request_raw_data",
+ return_value={},
+ ),
+ patch(
+ "homeassistant.components.hunterdouglas_powerview.Hub.request_home_data",
+ return_value={},
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/husqvarna_automower/test_diagnostics.py b/tests/components/husqvarna_automower/test_diagnostics.py
index 56eb0fdadde..c19345e507e 100644
--- a/tests/components/husqvarna_automower/test_diagnostics.py
+++ b/tests/components/husqvarna_automower/test_diagnostics.py
@@ -1,4 +1,5 @@
"""Test the Husqvarna Automower Diagnostics."""
+
import datetime
from unittest.mock import AsyncMock
diff --git a/tests/components/huum/test_config_flow.py b/tests/components/huum/test_config_flow.py
index ce5e2cf37c0..219783079e3 100644
--- a/tests/components/huum/test_config_flow.py
+++ b/tests/components/huum/test_config_flow.py
@@ -26,13 +26,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.huum.config_flow.Huum.status",
- return_value=True,
- ), patch(
- "homeassistant.components.huum.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.huum.config_flow.Huum.status",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.huum.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -68,12 +71,15 @@ async def test_signup_flow_already_set_up(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "homeassistant.components.huum.config_flow.Huum.status",
- return_value=True,
- ), patch(
- "homeassistant.components.huum.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.huum.config_flow.Huum.status",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.huum.async_setup_entry",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -119,12 +125,15 @@ async def test_huum_errors(
assert result2["type"] == FlowResultType.FORM
assert result2["errors"] == {"base": error_base}
- with patch(
- "homeassistant.components.huum.config_flow.Huum.status",
- return_value=True,
- ), patch(
- "homeassistant.components.huum.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.huum.config_flow.Huum.status",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.huum.async_setup_entry",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/hvv_departures/test_config_flow.py b/tests/components/hvv_departures/test_config_flow.py
index 11e5da00d11..2712e1bbca9 100644
--- a/tests/components/hvv_departures/test_config_flow.py
+++ b/tests/components/hvv_departures/test_config_flow.py
@@ -31,18 +31,23 @@ FIXTURE_DEPARTURE_LIST = json.loads(load_fixture("hvv_departures/departure_list.
async def test_user_flow(hass: HomeAssistant) -> None:
"""Test that config flow works."""
- with patch(
- "homeassistant.components.hvv_departures.hub.GTI.init",
- return_value=FIXTURE_INIT,
- ), patch(
- "homeassistant.components.hvv_departures.hub.GTI.checkName",
- return_value=FIXTURE_CHECK_NAME,
- ), patch(
- "homeassistant.components.hvv_departures.hub.GTI.stationInformation",
- return_value=FIXTURE_STATION_INFORMATION,
- ), patch(
- "homeassistant.components.hvv_departures.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.hvv_departures.hub.GTI.init",
+ return_value=FIXTURE_INIT,
+ ),
+ patch(
+ "homeassistant.components.hvv_departures.hub.GTI.checkName",
+ return_value=FIXTURE_CHECK_NAME,
+ ),
+ patch(
+ "homeassistant.components.hvv_departures.hub.GTI.stationInformation",
+ return_value=FIXTURE_STATION_INFORMATION,
+ ),
+ patch(
+ "homeassistant.components.hvv_departures.async_setup_entry",
+ return_value=True,
+ ),
):
# step: user
@@ -94,15 +99,19 @@ async def test_user_flow(hass: HomeAssistant) -> None:
async def test_user_flow_no_results(hass: HomeAssistant) -> None:
"""Test that config flow works when there are no results."""
- with patch(
- "homeassistant.components.hvv_departures.hub.GTI.init",
- return_value=FIXTURE_INIT,
- ), patch(
- "homeassistant.components.hvv_departures.hub.GTI.checkName",
- return_value={"returnCode": "OK", "results": []},
- ), patch(
- "homeassistant.components.hvv_departures.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.hvv_departures.hub.GTI.init",
+ return_value=FIXTURE_INIT,
+ ),
+ patch(
+ "homeassistant.components.hvv_departures.hub.GTI.checkName",
+ return_value={"returnCode": "OK", "results": []},
+ ),
+ patch(
+ "homeassistant.components.hvv_departures.async_setup_entry",
+ return_value=True,
+ ),
):
# step: user
@@ -179,12 +188,15 @@ async def test_user_flow_cannot_connect(hass: HomeAssistant) -> None:
async def test_user_flow_station(hass: HomeAssistant) -> None:
"""Test that config flow handles empty data on step station."""
- with patch(
- "homeassistant.components.hvv_departures.hub.GTI.init",
- return_value=True,
- ), patch(
- "homeassistant.components.hvv_departures.hub.GTI.checkName",
- return_value={"returnCode": "OK", "results": []},
+ with (
+ patch(
+ "homeassistant.components.hvv_departures.hub.GTI.init",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.hvv_departures.hub.GTI.checkName",
+ return_value={"returnCode": "OK", "results": []},
+ ),
):
# step: user
@@ -212,12 +224,15 @@ async def test_user_flow_station(hass: HomeAssistant) -> None:
async def test_user_flow_station_select(hass: HomeAssistant) -> None:
"""Test that config flow handles empty data on step station_select."""
- with patch(
- "homeassistant.components.hvv_departures.hub.GTI.init",
- return_value=True,
- ), patch(
- "homeassistant.components.hvv_departures.hub.GTI.checkName",
- return_value=FIXTURE_CHECK_NAME,
+ with (
+ patch(
+ "homeassistant.components.hvv_departures.hub.GTI.init",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.hvv_departures.hub.GTI.checkName",
+ return_value=FIXTURE_CHECK_NAME,
+ ),
):
result_user = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -258,12 +273,16 @@ async def test_options_flow(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with patch("homeassistant.components.hvv_departures.PLATFORMS", new=[]), patch(
- "homeassistant.components.hvv_departures.hub.GTI.init",
- return_value=True,
- ), patch(
- "homeassistant.components.hvv_departures.hub.GTI.departureList",
- return_value=FIXTURE_DEPARTURE_LIST,
+ with (
+ patch("homeassistant.components.hvv_departures.PLATFORMS", new=[]),
+ patch(
+ "homeassistant.components.hvv_departures.hub.GTI.init",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.hvv_departures.hub.GTI.departureList",
+ return_value=FIXTURE_DEPARTURE_LIST,
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -307,11 +326,15 @@ async def test_options_flow_invalid_auth(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with patch("homeassistant.components.hvv_departures.PLATFORMS", new=[]), patch(
- "homeassistant.components.hvv_departures.hub.GTI.init", return_value=True
- ), patch(
- "homeassistant.components.hvv_departures.hub.GTI.departureList",
- return_value=FIXTURE_DEPARTURE_LIST,
+ with (
+ patch("homeassistant.components.hvv_departures.PLATFORMS", new=[]),
+ patch(
+ "homeassistant.components.hvv_departures.hub.GTI.init", return_value=True
+ ),
+ patch(
+ "homeassistant.components.hvv_departures.hub.GTI.departureList",
+ return_value=FIXTURE_DEPARTURE_LIST,
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -346,11 +369,15 @@ async def test_options_flow_cannot_connect(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with patch("homeassistant.components.hvv_departures.PLATFORMS", new=[]), patch(
- "homeassistant.components.hvv_departures.hub.GTI.init", return_value=True
- ), patch(
- "homeassistant.components.hvv_departures.hub.GTI.departureList",
- return_value=FIXTURE_DEPARTURE_LIST,
+ with (
+ patch("homeassistant.components.hvv_departures.PLATFORMS", new=[]),
+ patch(
+ "homeassistant.components.hvv_departures.hub.GTI.init", return_value=True
+ ),
+ patch(
+ "homeassistant.components.hvv_departures.hub.GTI.departureList",
+ return_value=FIXTURE_DEPARTURE_LIST,
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/hyperion/test_config_flow.py b/tests/components/hyperion/test_config_flow.py
index 17f635eef4f..86dc4c5c39d 100644
--- a/tests/components/hyperion/test_config_flow.py
+++ b/tests/components/hyperion/test_config_flow.py
@@ -376,11 +376,15 @@ async def test_auth_create_token_approval_declined(hass: HomeAssistant) -> None:
assert result["step_id"] == "auth"
client.async_request_token = AsyncMock(return_value=TEST_REQUEST_TOKEN_FAIL)
- with patch(
- "homeassistant.components.hyperion.client.HyperionClient", return_value=client
- ), patch(
- "homeassistant.components.hyperion.config_flow.client.generate_random_auth_id",
- return_value=TEST_AUTH_ID,
+ with (
+ patch(
+ "homeassistant.components.hyperion.client.HyperionClient",
+ return_value=client,
+ ),
+ patch(
+ "homeassistant.components.hyperion.config_flow.client.generate_random_auth_id",
+ return_value=TEST_AUTH_ID,
+ ),
):
result = await _configure_flow(
hass, result, user_input={CONF_CREATE_TOKEN: True}
@@ -440,11 +444,15 @@ async def test_auth_create_token_approval_declined_task_canceled(
task_coro = arg
return mock_task
- with patch(
- "homeassistant.components.hyperion.client.HyperionClient", return_value=client
- ), patch(
- "homeassistant.components.hyperion.config_flow.client.generate_random_auth_id",
- return_value=TEST_AUTH_ID,
+ with (
+ patch(
+ "homeassistant.components.hyperion.client.HyperionClient",
+ return_value=client,
+ ),
+ patch(
+ "homeassistant.components.hyperion.config_flow.client.generate_random_auth_id",
+ return_value=TEST_AUTH_ID,
+ ),
):
result = await _configure_flow(
hass, result, user_input={CONF_CREATE_TOKEN: True}
@@ -482,11 +490,15 @@ async def test_auth_create_token_when_issued_token_fails(
assert result["step_id"] == "auth"
client.async_request_token = AsyncMock(return_value=TEST_REQUEST_TOKEN_SUCCESS)
- with patch(
- "homeassistant.components.hyperion.client.HyperionClient", return_value=client
- ), patch(
- "homeassistant.components.hyperion.config_flow.client.generate_random_auth_id",
- return_value=TEST_AUTH_ID,
+ with (
+ patch(
+ "homeassistant.components.hyperion.client.HyperionClient",
+ return_value=client,
+ ),
+ patch(
+ "homeassistant.components.hyperion.config_flow.client.generate_random_auth_id",
+ return_value=TEST_AUTH_ID,
+ ),
):
result = await _configure_flow(
hass, result, user_input={CONF_CREATE_TOKEN: True}
@@ -526,11 +538,15 @@ async def test_auth_create_token_success(hass: HomeAssistant) -> None:
assert result["step_id"] == "auth"
client.async_request_token = AsyncMock(return_value=TEST_REQUEST_TOKEN_SUCCESS)
- with patch(
- "homeassistant.components.hyperion.client.HyperionClient", return_value=client
- ), patch(
- "homeassistant.components.hyperion.config_flow.client.generate_random_auth_id",
- return_value=TEST_AUTH_ID,
+ with (
+ patch(
+ "homeassistant.components.hyperion.client.HyperionClient",
+ return_value=client,
+ ),
+ patch(
+ "homeassistant.components.hyperion.config_flow.client.generate_random_auth_id",
+ return_value=TEST_AUTH_ID,
+ ),
):
result = await _configure_flow(
hass, result, user_input={CONF_CREATE_TOKEN: True}
@@ -572,11 +588,15 @@ async def test_auth_create_token_success_but_login_fail(
assert result["step_id"] == "auth"
client.async_request_token = AsyncMock(return_value=TEST_REQUEST_TOKEN_SUCCESS)
- with patch(
- "homeassistant.components.hyperion.client.HyperionClient", return_value=client
- ), patch(
- "homeassistant.components.hyperion.config_flow.client.generate_random_auth_id",
- return_value=TEST_AUTH_ID,
+ with (
+ patch(
+ "homeassistant.components.hyperion.client.HyperionClient",
+ return_value=client,
+ ),
+ patch(
+ "homeassistant.components.hyperion.config_flow.client.generate_random_auth_id",
+ return_value=TEST_AUTH_ID,
+ ),
):
result = await _configure_flow(
hass, result, user_input={CONF_CREATE_TOKEN: True}
@@ -684,11 +704,15 @@ async def test_ssdp_failure_bad_port_ui(hass: HomeAssistant) -> None:
bad_data = dataclasses.replace(TEST_SSDP_SERVICE_INFO)
bad_data.ssdp_location = f"http://{TEST_HOST}:not_a_port/description.xml"
- with patch(
- "homeassistant.components.hyperion.client.HyperionClient", return_value=client
- ), patch(
- "homeassistant.components.hyperion.config_flow.client.generate_random_auth_id",
- return_value=TEST_AUTH_ID,
+ with (
+ patch(
+ "homeassistant.components.hyperion.client.HyperionClient",
+ return_value=client,
+ ),
+ patch(
+ "homeassistant.components.hyperion.config_flow.client.generate_random_auth_id",
+ return_value=TEST_AUTH_ID,
+ ),
):
result = await _init_flow(hass, source=SOURCE_SSDP, data=bad_data)
@@ -830,9 +854,13 @@ async def test_reauth_success(hass: HomeAssistant) -> None:
client = create_mock_client()
client.async_is_auth_required = AsyncMock(return_value=TEST_AUTH_REQUIRED_RESP)
- with patch(
- "homeassistant.components.hyperion.client.HyperionClient", return_value=client
- ), patch("homeassistant.components.hyperion.async_setup_entry", return_value=True):
+ with (
+ patch(
+ "homeassistant.components.hyperion.client.HyperionClient",
+ return_value=client,
+ ),
+ patch("homeassistant.components.hyperion.async_setup_entry", return_value=True),
+ ):
result = await _init_flow(
hass,
source=SOURCE_REAUTH,
diff --git a/tests/components/hyperion/test_light.py b/tests/components/hyperion/test_light.py
index 797107b0c34..e1e7711e702 100644
--- a/tests/components/hyperion/test_light.py
+++ b/tests/components/hyperion/test_light.py
@@ -713,9 +713,13 @@ async def test_setup_entry_no_token_reauth(hass: HomeAssistant) -> None:
config_entry = add_test_config_entry(hass)
client.async_is_auth_required = AsyncMock(return_value=TEST_AUTH_REQUIRED_RESP)
- with patch(
- "homeassistant.components.hyperion.client.HyperionClient", return_value=client
- ), patch.object(hass.config_entries.flow, "async_init") as mock_flow_init:
+ with (
+ patch(
+ "homeassistant.components.hyperion.client.HyperionClient",
+ return_value=client,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_flow_init,
+ ):
assert not await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert client.async_client_disconnect.called
@@ -743,9 +747,13 @@ async def test_setup_entry_bad_token_reauth(hass: HomeAssistant) -> None:
# Fail to log in.
client.async_client_login = AsyncMock(return_value=False)
- with patch(
- "homeassistant.components.hyperion.client.HyperionClient", return_value=client
- ), patch.object(hass.config_entries.flow, "async_init") as mock_flow_init:
+ with (
+ patch(
+ "homeassistant.components.hyperion.client.HyperionClient",
+ return_value=client,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_flow_init,
+ ):
assert not await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert client.async_client_disconnect.called
diff --git a/tests/components/ialarm/test_config_flow.py b/tests/components/ialarm/test_config_flow.py
index 18fd9d03015..816f03efa9e 100644
--- a/tests/components/ialarm/test_config_flow.py
+++ b/tests/components/ialarm/test_config_flow.py
@@ -23,16 +23,20 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] is None
- with patch(
- "homeassistant.components.ialarm.config_flow.IAlarm.get_status",
- return_value=1,
- ), patch(
- "homeassistant.components.ialarm.config_flow.IAlarm.get_mac",
- return_value=TEST_MAC,
- ), patch(
- "homeassistant.components.ialarm.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.ialarm.config_flow.IAlarm.get_status",
+ return_value=1,
+ ),
+ patch(
+ "homeassistant.components.ialarm.config_flow.IAlarm.get_mac",
+ return_value=TEST_MAC,
+ ),
+ patch(
+ "homeassistant.components.ialarm.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], TEST_DATA
)
diff --git a/tests/components/iaqualink/test_init.py b/tests/components/iaqualink/test_init.py
index 8c64b1072d6..d450ced1fd7 100644
--- a/tests/components/iaqualink/test_init.py
+++ b/tests/components/iaqualink/test_init.py
@@ -68,12 +68,15 @@ async def test_setup_systems_exception(hass: HomeAssistant, config_entry) -> Non
"""Test setup encountering an exception while retrieving systems."""
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.iaqualink.AqualinkClient.login",
- return_value=None,
- ), patch(
- "homeassistant.components.iaqualink.AqualinkClient.get_systems",
- side_effect=AqualinkServiceException,
+ with (
+ patch(
+ "homeassistant.components.iaqualink.AqualinkClient.login",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.iaqualink.AqualinkClient.get_systems",
+ side_effect=AqualinkServiceException,
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -85,12 +88,15 @@ async def test_setup_no_systems_recognized(hass: HomeAssistant, config_entry) ->
"""Test setup ending in no systems recognized."""
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.iaqualink.AqualinkClient.login",
- return_value=None,
- ), patch(
- "homeassistant.components.iaqualink.AqualinkClient.get_systems",
- return_value={},
+ with (
+ patch(
+ "homeassistant.components.iaqualink.AqualinkClient.login",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.iaqualink.AqualinkClient.get_systems",
+ return_value={},
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -107,16 +113,20 @@ async def test_setup_devices_exception(
system = get_aqualink_system(client, cls=IaquaSystem)
systems = {system.serial: system}
- with patch(
- "homeassistant.components.iaqualink.AqualinkClient.login",
- return_value=None,
- ), patch(
- "homeassistant.components.iaqualink.AqualinkClient.get_systems",
- return_value=systems,
- ), patch.object(
- system,
- "get_devices",
- ) as mock_get_devices:
+ with (
+ patch(
+ "homeassistant.components.iaqualink.AqualinkClient.login",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.iaqualink.AqualinkClient.get_systems",
+ return_value=systems,
+ ),
+ patch.object(
+ system,
+ "get_devices",
+ ) as mock_get_devices,
+ ):
mock_get_devices.side_effect = AqualinkServiceException
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -136,16 +146,20 @@ async def test_setup_all_good_no_recognized_devices(
device = get_aqualink_device(system, name="dev_1")
devices = {device.name: device}
- with patch(
- "homeassistant.components.iaqualink.AqualinkClient.login",
- return_value=None,
- ), patch(
- "homeassistant.components.iaqualink.AqualinkClient.get_systems",
- return_value=systems,
- ), patch.object(
- system,
- "get_devices",
- ) as mock_get_devices:
+ with (
+ patch(
+ "homeassistant.components.iaqualink.AqualinkClient.login",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.iaqualink.AqualinkClient.get_systems",
+ return_value=systems,
+ ),
+ patch.object(
+ system,
+ "get_devices",
+ ) as mock_get_devices,
+ ):
mock_get_devices.return_value = devices
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -184,12 +198,15 @@ async def test_setup_all_good_all_device_types(
system.get_devices = AsyncMock(return_value=devices)
- with patch(
- "homeassistant.components.iaqualink.AqualinkClient.login",
- return_value=None,
- ), patch(
- "homeassistant.components.iaqualink.AqualinkClient.get_systems",
- return_value=systems,
+ with (
+ patch(
+ "homeassistant.components.iaqualink.AqualinkClient.login",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.iaqualink.AqualinkClient.get_systems",
+ return_value=systems,
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -221,12 +238,15 @@ async def test_multiple_updates(
caplog.set_level(logging.WARNING)
- with patch(
- "homeassistant.components.iaqualink.AqualinkClient.login",
- return_value=None,
- ), patch(
- "homeassistant.components.iaqualink.AqualinkClient.get_systems",
- return_value=systems,
+ with (
+ patch(
+ "homeassistant.components.iaqualink.AqualinkClient.login",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.iaqualink.AqualinkClient.get_systems",
+ return_value=systems,
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -330,12 +350,15 @@ async def test_entity_assumed_and_available(
system.get_devices = AsyncMock(return_value=devices)
system.update = AsyncMock()
- with patch(
- "homeassistant.components.iaqualink.AqualinkClient.login",
- return_value=None,
- ), patch(
- "homeassistant.components.iaqualink.AqualinkClient.get_systems",
- return_value=systems,
+ with (
+ patch(
+ "homeassistant.components.iaqualink.AqualinkClient.login",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.iaqualink.AqualinkClient.get_systems",
+ return_value=systems,
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/ibeacon/test_coordinator.py b/tests/components/ibeacon/test_coordinator.py
index f94214fa47a..0880f745ec2 100644
--- a/tests/components/ibeacon/test_coordinator.py
+++ b/tests/components/ibeacon/test_coordinator.py
@@ -236,9 +236,12 @@ async def test_default_name_allowlisted_restore_late(hass: HomeAssistant) -> Non
# Fastforward time until the device is no longer advertised
monotonic_now = start_monotonic + FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 1
- with patch_bluetooth_time(
- monotonic_now,
- ), patch_all_discovered_devices([]):
+ with (
+ patch_bluetooth_time(
+ monotonic_now,
+ ),
+ patch_all_discovered_devices([]),
+ ):
async_fire_time_changed(
hass,
dt_util.utcnow()
diff --git a/tests/components/ibeacon/test_device_tracker.py b/tests/components/ibeacon/test_device_tracker.py
index 6a8d079ba46..77f8271370e 100644
--- a/tests/components/ibeacon/test_device_tracker.py
+++ b/tests/components/ibeacon/test_device_tracker.py
@@ -104,9 +104,12 @@ async def test_device_tracker_random_address(hass: HomeAssistant) -> None:
assert tracker_attributes[ATTR_FRIENDLY_NAME] == "RandomAddress_1234"
await hass.async_block_till_done()
- with patch_all_discovered_devices([]), patch(
- "homeassistant.components.ibeacon.coordinator.MONOTONIC_TIME",
- return_value=start_time + UNAVAILABLE_TIMEOUT + 1,
+ with (
+ patch_all_discovered_devices([]),
+ patch(
+ "homeassistant.components.ibeacon.coordinator.MONOTONIC_TIME",
+ return_value=start_time + UNAVAILABLE_TIMEOUT + 1,
+ ),
):
async_fire_time_changed(
hass, dt_util.utcnow() + timedelta(seconds=UNAVAILABLE_TIMEOUT)
@@ -169,9 +172,12 @@ async def test_device_tracker_random_address_infrequent_changes(
assert tracker_attributes[ATTR_FRIENDLY_NAME] == "RandomAddress_1234"
await hass.async_block_till_done()
- with patch_all_discovered_devices([]), patch(
- "homeassistant.components.ibeacon.coordinator.MONOTONIC_TIME",
- return_value=start_time + UNAVAILABLE_TIMEOUT + 1,
+ with (
+ patch_all_discovered_devices([]),
+ patch(
+ "homeassistant.components.ibeacon.coordinator.MONOTONIC_TIME",
+ return_value=start_time + UNAVAILABLE_TIMEOUT + 1,
+ ),
):
async_fire_time_changed(
hass, dt_util.utcnow() + timedelta(seconds=UNAVAILABLE_TIMEOUT)
@@ -196,9 +202,12 @@ async def test_device_tracker_random_address_infrequent_changes(
)
device = async_ble_device_from_address(hass, "AA:BB:CC:DD:EE:14", False)
- with patch_all_discovered_devices([device]), patch(
- "homeassistant.components.ibeacon.coordinator.MONOTONIC_TIME",
- return_value=start_time + UPDATE_INTERVAL.total_seconds() + 1,
+ with (
+ patch_all_discovered_devices([device]),
+ patch(
+ "homeassistant.components.ibeacon.coordinator.MONOTONIC_TIME",
+ return_value=start_time + UPDATE_INTERVAL.total_seconds() + 1,
+ ),
):
async_fire_time_changed(hass, dt_util.utcnow() + UPDATE_INTERVAL)
await hass.async_block_till_done()
@@ -234,9 +243,12 @@ async def test_device_tracker_random_address_infrequent_changes(
== one_day_future
)
- with patch_all_discovered_devices([device]), patch(
- "homeassistant.components.ibeacon.coordinator.MONOTONIC_TIME",
- return_value=start_time + UNAVAILABLE_TIMEOUT + 1,
+ with (
+ patch_all_discovered_devices([device]),
+ patch(
+ "homeassistant.components.ibeacon.coordinator.MONOTONIC_TIME",
+ return_value=start_time + UNAVAILABLE_TIMEOUT + 1,
+ ),
):
async_fire_time_changed(
hass, dt_util.utcnow() + timedelta(seconds=UNAVAILABLE_TIMEOUT + 1)
diff --git a/tests/components/idasen_desk/test_config_flow.py b/tests/components/idasen_desk/test_config_flow.py
index 32ed6b89f30..78eacfb6942 100644
--- a/tests/components/idasen_desk/test_config_flow.py
+++ b/tests/components/idasen_desk/test_config_flow.py
@@ -30,12 +30,14 @@ async def test_user_step_success(hass: HomeAssistant) -> None:
assert result["step_id"] == "user"
assert result["errors"] == {}
- with patch("homeassistant.components.idasen_desk.config_flow.Desk.connect"), patch(
- "homeassistant.components.idasen_desk.config_flow.Desk.disconnect"
- ), patch(
- "homeassistant.components.idasen_desk.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("homeassistant.components.idasen_desk.config_flow.Desk.connect"),
+ patch("homeassistant.components.idasen_desk.config_flow.Desk.disconnect"),
+ patch(
+ "homeassistant.components.idasen_desk.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -103,10 +105,13 @@ async def test_user_step_cannot_connect(
assert result["step_id"] == "user"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.idasen_desk.config_flow.Desk.connect",
- side_effect=exception,
- ), patch("homeassistant.components.idasen_desk.config_flow.Desk.disconnect"):
+ with (
+ patch(
+ "homeassistant.components.idasen_desk.config_flow.Desk.connect",
+ side_effect=exception,
+ ),
+ patch("homeassistant.components.idasen_desk.config_flow.Desk.disconnect"),
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -119,12 +124,14 @@ async def test_user_step_cannot_connect(
assert result2["step_id"] == "user"
assert result2["errors"] == {"base": "cannot_connect"}
- with patch("homeassistant.components.idasen_desk.config_flow.Desk.connect"), patch(
- "homeassistant.components.idasen_desk.config_flow.Desk.disconnect"
- ), patch(
- "homeassistant.components.idasen_desk.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("homeassistant.components.idasen_desk.config_flow.Desk.connect"),
+ patch("homeassistant.components.idasen_desk.config_flow.Desk.disconnect"),
+ patch(
+ "homeassistant.components.idasen_desk.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
@@ -155,10 +162,13 @@ async def test_user_step_auth_failed(hass: HomeAssistant) -> None:
assert result["step_id"] == "user"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.idasen_desk.config_flow.Desk.connect",
- side_effect=AuthFailedError,
- ), patch("homeassistant.components.idasen_desk.config_flow.Desk.disconnect"):
+ with (
+ patch(
+ "homeassistant.components.idasen_desk.config_flow.Desk.connect",
+ side_effect=AuthFailedError,
+ ),
+ patch("homeassistant.components.idasen_desk.config_flow.Desk.disconnect"),
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -171,12 +181,14 @@ async def test_user_step_auth_failed(hass: HomeAssistant) -> None:
assert result2["step_id"] == "user"
assert result2["errors"] == {"base": "auth_failed"}
- with patch("homeassistant.components.idasen_desk.config_flow.Desk.connect"), patch(
- "homeassistant.components.idasen_desk.config_flow.Desk.disconnect"
- ), patch(
- "homeassistant.components.idasen_desk.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("homeassistant.components.idasen_desk.config_flow.Desk.connect"),
+ patch("homeassistant.components.idasen_desk.config_flow.Desk.disconnect"),
+ patch(
+ "homeassistant.components.idasen_desk.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
@@ -207,11 +219,14 @@ async def test_user_step_unknown_exception(hass: HomeAssistant) -> None:
assert result["step_id"] == "user"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.idasen_desk.config_flow.Desk.connect",
- side_effect=RuntimeError,
- ), patch(
- "homeassistant.components.idasen_desk.config_flow.Desk.disconnect",
+ with (
+ patch(
+ "homeassistant.components.idasen_desk.config_flow.Desk.connect",
+ side_effect=RuntimeError,
+ ),
+ patch(
+ "homeassistant.components.idasen_desk.config_flow.Desk.disconnect",
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -225,14 +240,18 @@ async def test_user_step_unknown_exception(hass: HomeAssistant) -> None:
assert result2["step_id"] == "user"
assert result2["errors"] == {"base": "unknown"}
- with patch(
- "homeassistant.components.idasen_desk.config_flow.Desk.connect",
- ), patch(
- "homeassistant.components.idasen_desk.config_flow.Desk.disconnect",
- ), patch(
- "homeassistant.components.idasen_desk.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.idasen_desk.config_flow.Desk.connect",
+ ),
+ patch(
+ "homeassistant.components.idasen_desk.config_flow.Desk.disconnect",
+ ),
+ patch(
+ "homeassistant.components.idasen_desk.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
@@ -261,14 +280,16 @@ async def test_bluetooth_step_success(hass: HomeAssistant) -> None:
assert result["step_id"] == "user"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.idasen_desk.config_flow.Desk.connect"
- ) as desk_connect, patch(
- "homeassistant.components.idasen_desk.config_flow.Desk.disconnect"
- ), patch(
- "homeassistant.components.idasen_desk.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.idasen_desk.config_flow.Desk.connect"
+ ) as desk_connect,
+ patch("homeassistant.components.idasen_desk.config_flow.Desk.disconnect"),
+ patch(
+ "homeassistant.components.idasen_desk.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
diff --git a/tests/components/ign_sismologia/test_geo_location.py b/tests/components/ign_sismologia/test_geo_location.py
index d9b268ff575..c26eae28086 100644
--- a/tests/components/ign_sismologia/test_geo_location.py
+++ b/tests/components/ign_sismologia/test_geo_location.py
@@ -205,10 +205,13 @@ async def test_setup_with_custom_location(hass: HomeAssistant) -> None:
# Set up some mock feed entries for this test.
mock_entry_1 = _generate_mock_feed_entry("1234", "Title 1", 20.5, (38.1, -3.1))
- with patch(
- "georss_ign_sismologia_client.feed_manager.IgnSismologiaFeed",
- wraps=IgnSismologiaFeed,
- ) as mock_feed, patch("georss_client.feed.GeoRssFeed.update") as mock_feed_update:
+ with (
+ patch(
+ "georss_ign_sismologia_client.feed_manager.IgnSismologiaFeed",
+ wraps=IgnSismologiaFeed,
+ ) as mock_feed,
+ patch("georss_client.feed.GeoRssFeed.update") as mock_feed_update,
+ ):
mock_feed_update.return_value = "OK", [mock_entry_1]
with assert_setup_component(1, geo_location.DOMAIN):
diff --git a/tests/components/image_upload/test_init.py b/tests/components/image_upload/test_init.py
index 394c0672485..1117befc7fd 100644
--- a/tests/components/image_upload/test_init.py
+++ b/tests/components/image_upload/test_init.py
@@ -27,8 +27,9 @@ async def test_upload_image(
now = dt_util.utcnow()
freezer.move_to(now)
- with tempfile.TemporaryDirectory() as tempdir, patch.object(
- hass.config, "path", return_value=tempdir
+ with (
+ tempfile.TemporaryDirectory() as tempdir,
+ patch.object(hass.config, "path", return_value=tempdir),
):
assert await async_setup_component(hass, "image_upload", {})
ws_client: ClientWebSocketResponse = await hass_ws_client()
diff --git a/tests/components/improv_ble/test_config_flow.py b/tests/components/improv_ble/test_config_flow.py
index 81efd10cc3d..bafc32907ab 100644
--- a/tests/components/improv_ble/test_config_flow.py
+++ b/tests/components/improv_ble/test_config_flow.py
@@ -253,13 +253,16 @@ async def _test_common_success(
) -> None:
"""Test bluetooth and user flow success paths."""
- with patch(
- f"{IMPROV_BLE}.config_flow.ImprovBLEClient.need_authorization",
- return_value=False,
- ), patch(
- f"{IMPROV_BLE}.config_flow.ImprovBLEClient.provision",
- return_value=url,
- ) as mock_provision:
+ with (
+ patch(
+ f"{IMPROV_BLE}.config_flow.ImprovBLEClient.need_authorization",
+ return_value=False,
+ ),
+ patch(
+ f"{IMPROV_BLE}.config_flow.ImprovBLEClient.provision",
+ return_value=url,
+ ) as mock_provision,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"ssid": "MyWIFI", "password": "secret"}
)
@@ -305,13 +308,16 @@ async def _test_common_success_w_authorize(
state_callback(State.AUTHORIZED)
return lambda: None
- with patch(
- f"{IMPROV_BLE}.config_flow.ImprovBLEClient.need_authorization",
- return_value=True,
- ), patch(
- f"{IMPROV_BLE}.config_flow.ImprovBLEClient.subscribe_state_updates",
- side_effect=subscribe_state_updates,
- ) as mock_subscribe_state_updates:
+ with (
+ patch(
+ f"{IMPROV_BLE}.config_flow.ImprovBLEClient.need_authorization",
+ return_value=True,
+ ),
+ patch(
+ f"{IMPROV_BLE}.config_flow.ImprovBLEClient.subscribe_state_updates",
+ side_effect=subscribe_state_updates,
+ ) as mock_subscribe_state_updates,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"ssid": "MyWIFI", "password": "secret"}
)
@@ -321,13 +327,16 @@ async def _test_common_success_w_authorize(
mock_subscribe_state_updates.assert_awaited_once()
await hass.async_block_till_done()
- with patch(
- f"{IMPROV_BLE}.config_flow.ImprovBLEClient.need_authorization",
- return_value=False,
- ), patch(
- f"{IMPROV_BLE}.config_flow.ImprovBLEClient.provision",
- return_value="http://blabla.local",
- ) as mock_provision:
+ with (
+ patch(
+ f"{IMPROV_BLE}.config_flow.ImprovBLEClient.need_authorization",
+ return_value=False,
+ ),
+ patch(
+ f"{IMPROV_BLE}.config_flow.ImprovBLEClient.provision",
+ return_value="http://blabla.local",
+ ) as mock_provision,
+ ):
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == FlowResultType.SHOW_PROGRESS
assert result["progress_action"] == "provisioning"
@@ -517,12 +526,15 @@ async def test_authorize_fails(hass: HomeAssistant, exc, error) -> None:
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "provision"
- with patch(
- f"{IMPROV_BLE}.config_flow.ImprovBLEClient.need_authorization",
- return_value=True,
- ), patch(
- f"{IMPROV_BLE}.config_flow.ImprovBLEClient.subscribe_state_updates",
- side_effect=exc,
+ with (
+ patch(
+ f"{IMPROV_BLE}.config_flow.ImprovBLEClient.need_authorization",
+ return_value=True,
+ ),
+ patch(
+ f"{IMPROV_BLE}.config_flow.ImprovBLEClient.subscribe_state_updates",
+ side_effect=exc,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"ssid": "MyWIFI", "password": "secret"}
@@ -557,12 +569,15 @@ async def _test_provision_error(hass: HomeAssistant, exc) -> None:
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "provision"
- with patch(
- f"{IMPROV_BLE}.config_flow.ImprovBLEClient.need_authorization",
- return_value=False,
- ), patch(
- f"{IMPROV_BLE}.config_flow.ImprovBLEClient.provision",
- side_effect=exc,
+ with (
+ patch(
+ f"{IMPROV_BLE}.config_flow.ImprovBLEClient.need_authorization",
+ return_value=False,
+ ),
+ patch(
+ f"{IMPROV_BLE}.config_flow.ImprovBLEClient.provision",
+ side_effect=exc,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"ssid": "MyWIFI", "password": "secret"}
diff --git a/tests/components/influxdb/test_init.py b/tests/components/influxdb/test_init.py
index 883b40ab1df..41f14aa78e3 100644
--- a/tests/components/influxdb/test_init.py
+++ b/tests/components/influxdb/test_init.py
@@ -258,8 +258,9 @@ async def test_setup_config_ssl(
config = {"influxdb": config_base.copy()}
config["influxdb"].update(config_ext)
- with patch("os.access", return_value=True), 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()
diff --git a/tests/components/influxdb/test_sensor.py b/tests/components/influxdb/test_sensor.py
index dc88e04b4cf..395d33004a7 100644
--- a/tests/components/influxdb/test_sensor.py
+++ b/tests/components/influxdb/test_sensor.py
@@ -93,9 +93,10 @@ def mock_client_fixture(request):
@pytest.fixture(autouse=True, scope="module")
def mock_client_close():
"""Mock close method of clients at module scope."""
- with patch(f"{INFLUXDB_CLIENT_PATH}.close") as close_v1, patch(
- f"{INFLUXDB_CLIENT_PATH}V2.close"
- ) as close_v2:
+ with (
+ patch(f"{INFLUXDB_CLIENT_PATH}.close") as close_v1,
+ patch(f"{INFLUXDB_CLIENT_PATH}V2.close") as close_v2,
+ ):
yield (close_v1, close_v2)
diff --git a/tests/components/insteon/test_api_scenes.py b/tests/components/insteon/test_api_scenes.py
index aa4eb774229..04fc74c89d1 100644
--- a/tests/components/insteon/test_api_scenes.py
+++ b/tests/components/insteon/test_api_scenes.py
@@ -101,9 +101,10 @@ async def test_save_scene(
mock_add_or_update_scene = AsyncMock(return_value=(20, ResponseStatus.SUCCESS))
- with patch.object(
- pyinsteon.managers.scene_manager, "devices", devices
- ), patch.object(scenes, "async_add_or_update_scene", mock_add_or_update_scene):
+ with (
+ patch.object(pyinsteon.managers.scene_manager, "devices", devices),
+ patch.object(scenes, "async_add_or_update_scene", mock_add_or_update_scene),
+ ):
scene = await pyinsteon.managers.scene_manager.async_get_scene(20)
scene["devices"]["1a1a1a"] = []
links = _scene_to_array(scene)
@@ -132,9 +133,10 @@ async def test_save_new_scene(
mock_add_or_update_scene = AsyncMock(return_value=(21, ResponseStatus.SUCCESS))
- with patch.object(
- pyinsteon.managers.scene_manager, "devices", devices
- ), patch.object(scenes, "async_add_or_update_scene", mock_add_or_update_scene):
+ with (
+ patch.object(pyinsteon.managers.scene_manager, "devices", devices),
+ patch.object(scenes, "async_add_or_update_scene", mock_add_or_update_scene),
+ ):
scene = await pyinsteon.managers.scene_manager.async_get_scene(20)
scene["devices"]["1a1a1a"] = []
links = _scene_to_array(scene)
@@ -163,9 +165,10 @@ async def test_save_scene_error(
mock_add_or_update_scene = AsyncMock(return_value=(20, ResponseStatus.FAILURE))
- with patch.object(
- pyinsteon.managers.scene_manager, "devices", devices
- ), patch.object(scenes, "async_add_or_update_scene", mock_add_or_update_scene):
+ with (
+ patch.object(pyinsteon.managers.scene_manager, "devices", devices),
+ patch.object(scenes, "async_add_or_update_scene", mock_add_or_update_scene),
+ ):
scene = await pyinsteon.managers.scene_manager.async_get_scene(20)
scene["devices"]["1a1a1a"] = []
links = _scene_to_array(scene)
@@ -194,9 +197,10 @@ async def test_delete_scene(
mock_delete_scene = AsyncMock(return_value=ResponseStatus.SUCCESS)
- with patch.object(
- pyinsteon.managers.scene_manager, "devices", devices
- ), patch.object(scenes, "async_delete_scene", mock_delete_scene):
+ with (
+ patch.object(pyinsteon.managers.scene_manager, "devices", devices),
+ patch.object(scenes, "async_delete_scene", mock_delete_scene),
+ ):
await ws_client.send_json(
{
ID: 1,
diff --git a/tests/components/insteon/test_config_flow.py b/tests/components/insteon/test_config_flow.py
index f9636488d93..df7430bc254 100644
--- a/tests/components/insteon/test_config_flow.py
+++ b/tests/components/insteon/test_config_flow.py
@@ -102,13 +102,17 @@ async def _init_form(hass, modem_type):
async def _device_form(hass, flow_id, connection, user_input):
"""Test the PLM, Hub v1 or Hub v2 form."""
- with patch(
- PATCH_CONNECTION,
- new=connection,
- ), patch(PATCH_ASYNC_SETUP, return_value=True) as mock_setup, patch(
- PATCH_ASYNC_SETUP_ENTRY,
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ PATCH_CONNECTION,
+ new=connection,
+ ),
+ patch(PATCH_ASYNC_SETUP, return_value=True) as mock_setup,
+ patch(
+ PATCH_ASYNC_SETUP_ENTRY,
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(flow_id, user_input)
await hass.async_block_till_done()
return result, mock_setup, mock_setup_entry
@@ -311,10 +315,11 @@ async def _options_form(
mock_devices = MockDevices(connected=True)
await mock_devices.async_load()
mock_devices.modem = mock_devices["AA.AA.AA"]
- with patch(PATCH_CONNECTION, new=connection), patch(
- PATCH_ASYNC_SETUP_ENTRY, return_value=True
- ) as mock_setup_entry, patch(PATCH_DEVICES, mock_devices), patch(
- PATCH_CONNECTION_CLOSE
+ with (
+ patch(PATCH_CONNECTION, new=connection),
+ patch(PATCH_ASYNC_SETUP_ENTRY, return_value=True) as mock_setup_entry,
+ patch(PATCH_DEVICES, mock_devices),
+ patch(PATCH_CONNECTION_CLOSE),
):
result = await hass.config_entries.options.async_configure(flow_id, user_input)
return result, mock_setup_entry
diff --git a/tests/components/insteon/test_init.py b/tests/components/insteon/test_init.py
index bfc8a8b8cc1..a4e8da03345 100644
--- a/tests/components/insteon/test_init.py
+++ b/tests/components/insteon/test_init.py
@@ -32,10 +32,10 @@ async def test_setup_entry(hass: HomeAssistant) -> None:
config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_USER_INPUT_PLM)
config_entry.add_to_hass(hass)
- with patch.object(
- insteon, "async_connect", new=mock_successful_connection
- ), patch.object(insteon, "async_close") as mock_close, patch.object(
- insteon, "devices", new=MockDevices()
+ with (
+ patch.object(insteon, "async_connect", new=mock_successful_connection),
+ patch.object(insteon, "async_close") as mock_close,
+ patch.object(insteon, "devices", new=MockDevices()),
):
assert await async_setup_component(
hass,
@@ -56,9 +56,10 @@ async def test_setup_entry_failed_connection(
config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_USER_INPUT_PLM)
config_entry.add_to_hass(hass)
- with patch.object(
- insteon, "async_connect", new=mock_failed_connection
- ), patch.object(insteon, "devices", new=MockDevices(connected=False)):
+ with (
+ patch.object(insteon, "async_connect", new=mock_failed_connection),
+ patch.object(insteon, "devices", new=MockDevices(connected=False)),
+ ):
assert await async_setup_component(
hass,
insteon.DOMAIN,
@@ -72,13 +73,14 @@ async def test_import_frontend_dev_url(hass: HomeAssistant) -> None:
config = {}
config[DOMAIN] = {CONF_DEV_PATH: "/some/path"}
- with patch.object(
- insteon, "async_connect", new=mock_successful_connection
- ), patch.object(insteon, "close_insteon_connection"), patch.object(
- insteon, "devices", new=MockDevices()
- ), patch(
- PATCH_CONNECTION,
- new=mock_successful_connection,
+ with (
+ patch.object(insteon, "async_connect", new=mock_successful_connection),
+ patch.object(insteon, "close_insteon_connection"),
+ patch.object(insteon, "devices", new=MockDevices()),
+ patch(
+ PATCH_CONNECTION,
+ new=mock_successful_connection,
+ ),
):
assert await async_setup_component(
hass,
diff --git a/tests/components/insteon/test_lock.py b/tests/components/insteon/test_lock.py
index 43b50e78cb1..a782e006a62 100644
--- a/tests/components/insteon/test_lock.py
+++ b/tests/components/insteon/test_lock.py
@@ -43,14 +43,16 @@ def lock_platform_only():
@pytest.fixture(autouse=True)
def patch_setup_and_devices():
"""Patch the Insteon setup process and devices."""
- with patch.object(insteon, "async_connect", new=mock_connection), patch.object(
- insteon, "async_close"
- ), patch.object(insteon, "devices", devices), patch.object(
- insteon_utils, "devices", devices
- ), patch.object(
- insteon_entity,
- "devices",
- devices,
+ with (
+ patch.object(insteon, "async_connect", new=mock_connection),
+ patch.object(insteon, "async_close"),
+ patch.object(insteon, "devices", devices),
+ patch.object(insteon_utils, "devices", devices),
+ patch.object(
+ insteon_entity,
+ "devices",
+ devices,
+ ),
):
yield
diff --git a/tests/components/iotawatt/test_config_flow.py b/tests/components/iotawatt/test_config_flow.py
index 6ed781b2f5b..d4980ba978e 100644
--- a/tests/components/iotawatt/test_config_flow.py
+++ b/tests/components/iotawatt/test_config_flow.py
@@ -19,13 +19,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == config_entries.SOURCE_USER
- with patch(
- "homeassistant.components.iotawatt.async_setup_entry",
- return_value=True,
- ), patch(
- "homeassistant.components.iotawatt.config_flow.Iotawatt.connect",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.iotawatt.async_setup_entry",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.iotawatt.config_flow.Iotawatt.connect",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -80,12 +83,15 @@ async def test_form_auth(hass: HomeAssistant) -> None:
assert result3["step_id"] == "auth"
assert result3["errors"] == {"base": "invalid_auth"}
- with patch(
- "homeassistant.components.iotawatt.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.iotawatt.config_flow.Iotawatt.connect",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.iotawatt.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.iotawatt.config_flow.Iotawatt.connect",
+ return_value=True,
+ ),
):
result4 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/iotawatt/test_sensor.py b/tests/components/iotawatt/test_sensor.py
index aa6180e306b..ecf2f97c67a 100644
--- a/tests/components/iotawatt/test_sensor.py
+++ b/tests/components/iotawatt/test_sensor.py
@@ -63,9 +63,9 @@ async def test_sensor_type_output(
hass: HomeAssistant, freezer: FrozenDateTimeFactory, mock_iotawatt
) -> None:
"""Tests the sensor type of Output."""
- mock_iotawatt.getSensors.return_value["sensors"][
- "my_watthour_sensor_key"
- ] = OUTPUT_SENSOR
+ mock_iotawatt.getSensors.return_value["sensors"]["my_watthour_sensor_key"] = (
+ OUTPUT_SENSOR
+ )
assert await async_setup_component(hass, "iotawatt", {})
await hass.async_block_till_done()
diff --git a/tests/components/iqvia/conftest.py b/tests/components/iqvia/conftest.py
index c1d0341aaa6..6fb14ca4d28 100644
--- a/tests/components/iqvia/conftest.py
+++ b/tests/components/iqvia/conftest.py
@@ -87,18 +87,17 @@ async def setup_iqvia_fixture(
data_disease_index,
):
"""Define a fixture to set up IQVIA."""
- with patch(
- "pyiqvia.allergens.Allergens.extended", return_value=data_allergy_forecast
- ), patch(
- "pyiqvia.allergens.Allergens.current", return_value=data_allergy_index
- ), patch(
- "pyiqvia.allergens.Allergens.outlook", return_value=data_allergy_outlook
- ), patch(
- "pyiqvia.asthma.Asthma.extended", return_value=data_asthma_forecast
- ), patch("pyiqvia.asthma.Asthma.current", return_value=data_asthma_index), patch(
- "pyiqvia.disease.Disease.extended", return_value=data_disease_forecast
- ), patch("pyiqvia.disease.Disease.current", return_value=data_disease_index), patch(
- "homeassistant.components.iqvia.PLATFORMS", []
+ with (
+ patch(
+ "pyiqvia.allergens.Allergens.extended", return_value=data_allergy_forecast
+ ),
+ patch("pyiqvia.allergens.Allergens.current", return_value=data_allergy_index),
+ patch("pyiqvia.allergens.Allergens.outlook", return_value=data_allergy_outlook),
+ patch("pyiqvia.asthma.Asthma.extended", return_value=data_asthma_forecast),
+ patch("pyiqvia.asthma.Asthma.current", return_value=data_asthma_index),
+ patch("pyiqvia.disease.Disease.extended", return_value=data_disease_forecast),
+ patch("pyiqvia.disease.Disease.current", return_value=data_disease_index),
+ patch("homeassistant.components.iqvia.PLATFORMS", []),
):
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
diff --git a/tests/components/islamic_prayer_times/test_init.py b/tests/components/islamic_prayer_times/test_init.py
index 33828de41cd..3c7565a37ef 100644
--- a/tests/components/islamic_prayer_times/test_init.py
+++ b/tests/components/islamic_prayer_times/test_init.py
@@ -89,10 +89,13 @@ async def test_options_listener(hass: HomeAssistant) -> None:
entry = MockConfigEntry(domain=islamic_prayer_times.DOMAIN, data={})
entry.add_to_hass(hass)
- with patch(
- "prayer_times_calculator.PrayerTimesCalculator.fetch_prayer_times",
- return_value=PRAYER_TIMES,
- ) as mock_fetch_prayer_times, freeze_time(NOW):
+ with (
+ patch(
+ "prayer_times_calculator.PrayerTimesCalculator.fetch_prayer_times",
+ return_value=PRAYER_TIMES,
+ ) as mock_fetch_prayer_times,
+ freeze_time(NOW),
+ ):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert mock_fetch_prayer_times.call_count == 1
@@ -109,10 +112,13 @@ async def test_update_failed(hass: HomeAssistant) -> None:
entry = MockConfigEntry(domain=islamic_prayer_times.DOMAIN, data={})
entry.add_to_hass(hass)
- with patch(
- "prayer_times_calculator.PrayerTimesCalculator.fetch_prayer_times",
- return_value=PRAYER_TIMES,
- ), freeze_time(NOW):
+ with (
+ patch(
+ "prayer_times_calculator.PrayerTimesCalculator.fetch_prayer_times",
+ return_value=PRAYER_TIMES,
+ ),
+ freeze_time(NOW),
+ ):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
@@ -176,10 +182,13 @@ async def test_migrate_unique_id(
)
assert entity.unique_id == old_unique_id
- with patch(
- "prayer_times_calculator.PrayerTimesCalculator.fetch_prayer_times",
- return_value=PRAYER_TIMES,
- ), freeze_time(NOW):
+ with (
+ patch(
+ "prayer_times_calculator.PrayerTimesCalculator.fetch_prayer_times",
+ return_value=PRAYER_TIMES,
+ ),
+ freeze_time(NOW),
+ ):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
@@ -196,10 +205,13 @@ async def test_migration_from_1_1_to_1_2(hass: HomeAssistant) -> None:
)
entry.add_to_hass(hass)
- with patch(
- "prayer_times_calculator.PrayerTimesCalculator.fetch_prayer_times",
- return_value=PRAYER_TIMES,
- ), freeze_time(NOW):
+ with (
+ patch(
+ "prayer_times_calculator.PrayerTimesCalculator.fetch_prayer_times",
+ return_value=PRAYER_TIMES,
+ ),
+ freeze_time(NOW),
+ ):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/islamic_prayer_times/test_sensor.py b/tests/components/islamic_prayer_times/test_sensor.py
index 2e323e4f5d6..22629819e05 100644
--- a/tests/components/islamic_prayer_times/test_sensor.py
+++ b/tests/components/islamic_prayer_times/test_sensor.py
@@ -38,10 +38,13 @@ async def test_islamic_prayer_times_sensors(
entry = MockConfigEntry(domain=DOMAIN, data={})
entry.add_to_hass(hass)
- with patch(
- "prayer_times_calculator.PrayerTimesCalculator.fetch_prayer_times",
- return_value=PRAYER_TIMES,
- ), freeze_time(NOW):
+ with (
+ patch(
+ "prayer_times_calculator.PrayerTimesCalculator.fetch_prayer_times",
+ return_value=PRAYER_TIMES,
+ ),
+ freeze_time(NOW),
+ ):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert hass.states.get(sensor_name).state == PRAYER_TIMES[key]
diff --git a/tests/components/isy994/test_config_flow.py b/tests/components/isy994/test_config_flow.py
index e20c4f0b185..b29b1dbc775 100644
--- a/tests/components/isy994/test_config_flow.py
+++ b/tests/components/isy994/test_config_flow.py
@@ -91,10 +91,13 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] == {}
- with patch(PATCH_CONNECTION, return_value=MOCK_CONFIG_RESPONSE), patch(
- PATCH_ASYNC_SETUP_ENTRY,
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(PATCH_CONNECTION, return_value=MOCK_CONFIG_RESPONSE),
+ patch(
+ PATCH_ASYNC_SETUP_ENTRY,
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
MOCK_USER_INPUT,
@@ -284,10 +287,13 @@ async def test_form_ssdp(hass: HomeAssistant) -> None:
assert result["step_id"] == "user"
assert result["errors"] == {}
- with patch(PATCH_CONNECTION, return_value=MOCK_CONFIG_RESPONSE), patch(
- PATCH_ASYNC_SETUP_ENTRY,
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(PATCH_CONNECTION, return_value=MOCK_CONFIG_RESPONSE),
+ patch(
+ PATCH_ASYNC_SETUP_ENTRY,
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
MOCK_USER_INPUT,
@@ -443,10 +449,13 @@ async def test_form_dhcp(hass: HomeAssistant) -> None:
assert result["step_id"] == "user"
assert result["errors"] == {}
- with patch(PATCH_CONNECTION, return_value=MOCK_CONFIG_RESPONSE), patch(
- PATCH_ASYNC_SETUP_ENTRY,
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(PATCH_CONNECTION, return_value=MOCK_CONFIG_RESPONSE),
+ patch(
+ PATCH_ASYNC_SETUP_ENTRY,
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
MOCK_USER_INPUT,
@@ -480,10 +489,13 @@ async def test_form_dhcp_with_polisy(hass: HomeAssistant) -> None:
== "http://1.2.3.4:8080"
)
- with patch(PATCH_CONNECTION, return_value=MOCK_CONFIG_RESPONSE), patch(
- PATCH_ASYNC_SETUP_ENTRY,
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(PATCH_CONNECTION, return_value=MOCK_CONFIG_RESPONSE),
+ patch(
+ PATCH_ASYNC_SETUP_ENTRY,
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
MOCK_IOX_USER_INPUT,
@@ -517,10 +529,13 @@ async def test_form_dhcp_with_eisy(hass: HomeAssistant) -> None:
== "http://1.2.3.4:8080"
)
- with patch(PATCH_CONNECTION, return_value=MOCK_CONFIG_RESPONSE), patch(
- PATCH_ASYNC_SETUP_ENTRY,
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(PATCH_CONNECTION, return_value=MOCK_CONFIG_RESPONSE),
+ patch(
+ PATCH_ASYNC_SETUP_ENTRY,
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
MOCK_IOX_USER_INPUT,
@@ -666,10 +681,13 @@ async def test_reauth(hass: HomeAssistant) -> None:
assert result3["type"] == "form"
assert result3["errors"] == {"base": "cannot_connect"}
- with patch(PATCH_CONNECTION, return_value=MOCK_CONFIG_RESPONSE), patch(
- "homeassistant.components.isy994.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(PATCH_CONNECTION, return_value=MOCK_CONFIG_RESPONSE),
+ patch(
+ "homeassistant.components.isy994.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result4 = await hass.config_entries.flow.async_configure(
result3["flow_id"],
{
diff --git a/tests/components/izone/test_config_flow.py b/tests/components/izone/test_config_flow.py
index 7043baae11a..0988640d644 100644
--- a/tests/components/izone/test_config_flow.py
+++ b/tests/components/izone/test_config_flow.py
@@ -31,12 +31,15 @@ def _mock_start_discovery(hass, mock_disco):
async def test_not_found(hass: HomeAssistant, mock_disco) -> None:
"""Test not finding iZone controller."""
- with patch(
- "homeassistant.components.izone.config_flow.async_start_discovery_service"
- ) as start_disco, patch(
- "homeassistant.components.izone.config_flow.async_stop_discovery_service",
- return_value=None,
- ) as stop_disco:
+ with (
+ patch(
+ "homeassistant.components.izone.config_flow.async_start_discovery_service"
+ ) as start_disco,
+ patch(
+ "homeassistant.components.izone.config_flow.async_stop_discovery_service",
+ return_value=None,
+ ) as stop_disco,
+ ):
start_disco.side_effect = _mock_start_discovery(hass, mock_disco)
result = await hass.config_entries.flow.async_init(
IZONE, context={"source": config_entries.SOURCE_USER}
@@ -57,14 +60,18 @@ async def test_found(hass: HomeAssistant, mock_disco) -> None:
"""Test not finding iZone controller."""
mock_disco.pi_disco.controllers["blah"] = object()
- with patch(
- "homeassistant.components.izone.climate.async_setup_entry",
- return_value=True,
- ) as mock_setup, patch(
- "homeassistant.components.izone.config_flow.async_start_discovery_service"
- ) as start_disco, patch(
- "homeassistant.components.izone.async_start_discovery_service",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.components.izone.climate.async_setup_entry",
+ return_value=True,
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.izone.config_flow.async_start_discovery_service"
+ ) as start_disco,
+ patch(
+ "homeassistant.components.izone.async_start_discovery_service",
+ return_value=None,
+ ),
):
start_disco.side_effect = _mock_start_discovery(hass, mock_disco)
result = await hass.config_entries.flow.async_init(
diff --git a/tests/components/juicenet/test_config_flow.py b/tests/components/juicenet/test_config_flow.py
index 2a2d55549cd..2a4be10b49b 100644
--- a/tests/components/juicenet/test_config_flow.py
+++ b/tests/components/juicenet/test_config_flow.py
@@ -26,14 +26,18 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.juicenet.config_flow.Api.get_devices",
- return_value=MagicMock(),
- ), patch(
- "homeassistant.components.juicenet.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.juicenet.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.juicenet.config_flow.Api.get_devices",
+ return_value=MagicMock(),
+ ),
+ patch(
+ "homeassistant.components.juicenet.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.juicenet.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_ACCESS_TOKEN: "access_token"}
)
@@ -103,14 +107,18 @@ async def test_form_catch_unknown_errors(hass: HomeAssistant) -> None:
async def test_import(hass: HomeAssistant) -> None:
"""Test that import works as expected."""
- with patch(
- "homeassistant.components.juicenet.config_flow.Api.get_devices",
- return_value=MagicMock(),
- ), patch(
- "homeassistant.components.juicenet.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.juicenet.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.juicenet.config_flow.Api.get_devices",
+ return_value=MagicMock(),
+ ),
+ patch(
+ "homeassistant.components.juicenet.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.juicenet.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
diff --git a/tests/components/justnimbus/test_config_flow.py b/tests/components/justnimbus/test_config_flow.py
index 2b2caeed929..b96b6c8aa5c 100644
--- a/tests/components/justnimbus/test_config_flow.py
+++ b/tests/components/justnimbus/test_config_flow.py
@@ -95,10 +95,13 @@ async def test_abort_already_configured(hass: HomeAssistant) -> None:
async def _set_up_justnimbus(hass: HomeAssistant, flow_id: str) -> None:
"""Reusable successful setup of JustNimbus sensor."""
- with patch("justnimbus.JustNimbusClient.get_data"), patch(
- "homeassistant.components.justnimbus.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("justnimbus.JustNimbusClient.get_data"),
+ patch(
+ "homeassistant.components.justnimbus.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
flow_id=flow_id,
user_input=FIXTURE_USER_INPUT,
diff --git a/tests/components/keymitt_ble/test_config_flow.py b/tests/components/keymitt_ble/test_config_flow.py
index d2c76c14c6d..7e60bdfca53 100644
--- a/tests/components/keymitt_ble/test_config_flow.py
+++ b/tests/components/keymitt_ble/test_config_flow.py
@@ -131,9 +131,12 @@ async def test_user_setup_already_configured(hass: HomeAssistant) -> None:
async def test_user_no_devices(hass: HomeAssistant) -> None:
"""Test the user initiated form with valid mac."""
- with patch_microbot_api(), patch(
- "homeassistant.components.keymitt_ble.config_flow.async_discovered_service_info",
- return_value=[],
+ with (
+ patch_microbot_api(),
+ patch(
+ "homeassistant.components.keymitt_ble.config_flow.async_discovered_service_info",
+ return_value=[],
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
@@ -145,9 +148,12 @@ async def test_user_no_devices(hass: HomeAssistant) -> None:
async def test_no_link(hass: HomeAssistant) -> None:
"""Test the user initiated form with invalid response."""
- with patch_microbot_api(), patch(
- "homeassistant.components.keymitt_ble.config_flow.async_discovered_service_info",
- return_value=[SERVICE_INFO],
+ with (
+ patch_microbot_api(),
+ patch(
+ "homeassistant.components.keymitt_ble.config_flow.async_discovered_service_info",
+ return_value=[SERVICE_INFO],
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
@@ -164,10 +170,13 @@ async def test_no_link(hass: HomeAssistant) -> None:
assert result2["type"] == FlowResultType.FORM
assert result2["step_id"] == "link"
- with patch(
- "homeassistant.components.keymitt_ble.config_flow.MicroBotApiClient",
- MockMicroBotApiClientFail,
- ), patch_async_setup_entry() as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.keymitt_ble.config_flow.MicroBotApiClient",
+ MockMicroBotApiClientFail,
+ ),
+ patch_async_setup_entry() as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
USER_INPUT,
diff --git a/tests/components/knx/test_config_flow.py b/tests/components/knx/test_config_flow.py
index 717d362265e..f5b3d9595d0 100644
--- a/tests/components/knx/test_config_flow.py
+++ b/tests/components/knx/test_config_flow.py
@@ -62,26 +62,34 @@ GATEWAY_INDIVIDUAL_ADDRESS = IndividualAddress("1.0.0")
@pytest.fixture(name="knx_setup")
def fixture_knx_setup():
"""Mock KNX entry setup."""
- with patch("homeassistant.components.knx.async_setup", return_value=True), patch(
- "homeassistant.components.knx.async_setup_entry", return_value=True
- ) as mock_async_setup_entry:
+ with (
+ patch("homeassistant.components.knx.async_setup", return_value=True),
+ patch(
+ "homeassistant.components.knx.async_setup_entry", return_value=True
+ ) as mock_async_setup_entry,
+ ):
yield mock_async_setup_entry
@contextmanager
def patch_file_upload(return_value=FIXTURE_KEYRING, side_effect=None):
"""Patch file upload. Yields the Keyring instance (return_value)."""
- with patch(
- "homeassistant.components.knx.helpers.keyring.process_uploaded_file"
- ) as file_upload_mock, patch(
- "homeassistant.components.knx.helpers.keyring.sync_load_keyring",
- return_value=return_value,
- side_effect=side_effect,
- ), patch(
- "pathlib.Path.mkdir",
- ) as mkdir_mock, patch(
- "shutil.move",
- ) as shutil_move_mock:
+ with (
+ patch(
+ "homeassistant.components.knx.helpers.keyring.process_uploaded_file"
+ ) as file_upload_mock,
+ patch(
+ "homeassistant.components.knx.helpers.keyring.sync_load_keyring",
+ return_value=return_value,
+ side_effect=side_effect,
+ ),
+ patch(
+ "pathlib.Path.mkdir",
+ ) as mkdir_mock,
+ patch(
+ "shutil.move",
+ ) as shutil_move_mock,
+ ):
file_upload_mock.return_value.__enter__.return_value = Mock()
yield return_value
if side_effect:
diff --git a/tests/components/knx/test_init.py b/tests/components/knx/test_init.py
index 5a6770dc92e..2d2889e7718 100644
--- a/tests/components/knx/test_init.py
+++ b/tests/components/knx/test_init.py
@@ -277,9 +277,10 @@ async def test_async_remove_entry(
knx.mock_config_entry = config_entry
await knx.setup_integration({})
- with patch("pathlib.Path.unlink") as unlink_mock, patch(
- "pathlib.Path.rmdir"
- ) as rmdir_mock:
+ with (
+ patch("pathlib.Path.unlink") as unlink_mock,
+ patch("pathlib.Path.rmdir") as rmdir_mock,
+ ):
assert await hass.config_entries.async_remove(config_entry.entry_id)
assert unlink_mock.call_count == 3
rmdir_mock.assert_called_once()
diff --git a/tests/components/knx/test_services.py b/tests/components/knx/test_services.py
index a6688f7a14c..e93f59ba574 100644
--- a/tests/components/knx/test_services.py
+++ b/tests/components/knx/test_services.py
@@ -271,11 +271,13 @@ async def test_reload_service(
"""Test reload service."""
await knx.setup_integration({})
- with patch(
- "homeassistant.components.knx.async_unload_entry", wraps=knx_async_unload_entry
- ) as mock_unload_entry, patch(
- "homeassistant.components.knx.async_setup_entry"
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.knx.async_unload_entry",
+ wraps=knx_async_unload_entry,
+ ) as mock_unload_entry,
+ patch("homeassistant.components.knx.async_setup_entry") as mock_setup_entry,
+ ):
await hass.services.async_call(
"knx",
"reload",
diff --git a/tests/components/knx/test_websocket.py b/tests/components/knx/test_websocket.py
index f36d5bb5f7a..78cbb98a7a0 100644
--- a/tests/components/knx/test_websocket.py
+++ b/tests/components/knx/test_websocket.py
@@ -73,11 +73,12 @@ async def test_knx_project_file_process(
"password": _password,
}
)
- with patch(
- "homeassistant.components.knx.project.process_uploaded_file",
- ) as file_upload_mock, patch(
- "xknxproject.XKNXProj.parse", return_value=_parse_result
- ) as parse_mock:
+ with (
+ patch(
+ "homeassistant.components.knx.project.process_uploaded_file",
+ ) as file_upload_mock,
+ patch("xknxproject.XKNXProj.parse", return_value=_parse_result) as parse_mock,
+ ):
file_upload_mock.return_value.__enter__.return_value = ""
res = await client.receive_json()
@@ -106,11 +107,12 @@ async def test_knx_project_file_process_error(
"password": "",
}
)
- with patch(
- "homeassistant.components.knx.project.process_uploaded_file",
- ) as file_upload_mock, patch(
- "xknxproject.XKNXProj.parse", side_effect=ValueError
- ) as parse_mock:
+ with (
+ patch(
+ "homeassistant.components.knx.project.process_uploaded_file",
+ ) as file_upload_mock,
+ patch("xknxproject.XKNXProj.parse", side_effect=ValueError) as parse_mock,
+ ):
file_upload_mock.return_value.__enter__.return_value = ""
res = await client.receive_json()
parse_mock.assert_called_once_with()
diff --git a/tests/components/kodi/__init__.py b/tests/components/kodi/__init__.py
index a15d1e6681d..d55a67ba235 100644
--- a/tests/components/kodi/__init__.py
+++ b/tests/components/kodi/__init__.py
@@ -31,12 +31,16 @@ async def init_integration(hass) -> MockConfigEntry:
entry = MockConfigEntry(domain=DOMAIN, data=entry_data, title="name")
entry.add_to_hass(hass)
- with patch("homeassistant.components.kodi.Kodi.ping", return_value=True), patch(
- "homeassistant.components.kodi.Kodi.get_application_properties",
- return_value={"version": {"major": 1, "minor": 1}},
- ), patch(
- "homeassistant.components.kodi.get_kodi_connection",
- return_value=MockConnection(),
+ with (
+ patch("homeassistant.components.kodi.Kodi.ping", return_value=True),
+ patch(
+ "homeassistant.components.kodi.Kodi.get_application_properties",
+ return_value={"version": {"major": 1, "minor": 1}},
+ ),
+ patch(
+ "homeassistant.components.kodi.get_kodi_connection",
+ return_value=MockConnection(),
+ ),
):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/kodi/test_config_flow.py b/tests/components/kodi/test_config_flow.py
index 83795978522..ecc3bc1f672 100644
--- a/tests/components/kodi/test_config_flow.py
+++ b/tests/components/kodi/test_config_flow.py
@@ -42,16 +42,20 @@ async def user_flow(hass):
async def test_user_flow(hass: HomeAssistant, user_flow) -> None:
"""Test a successful user initiated flow."""
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- return_value=True,
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- return_value=MockConnection(),
- ), patch(
- "homeassistant.components.kodi.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ return_value=MockConnection(),
+ ),
+ patch(
+ "homeassistant.components.kodi.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(user_flow, TEST_HOST)
await hass.async_block_till_done()
@@ -71,12 +75,15 @@ async def test_user_flow(hass: HomeAssistant, user_flow) -> None:
async def test_form_valid_auth(hass: HomeAssistant, user_flow) -> None:
"""Test we handle valid auth."""
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- side_effect=InvalidAuthError,
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- return_value=MockConnection(),
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ side_effect=InvalidAuthError,
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ return_value=MockConnection(),
+ ),
):
result = await hass.config_entries.flow.async_configure(user_flow, TEST_HOST)
@@ -84,16 +91,20 @@ async def test_form_valid_auth(hass: HomeAssistant, user_flow) -> None:
assert result["step_id"] == "credentials"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- return_value=True,
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- return_value=MockConnection(),
- ), patch(
- "homeassistant.components.kodi.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ return_value=MockConnection(),
+ ),
+ patch(
+ "homeassistant.components.kodi.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], TEST_CREDENTIALS
)
@@ -114,16 +125,20 @@ async def test_form_valid_auth(hass: HomeAssistant, user_flow) -> None:
async def test_form_valid_ws_port(hass: HomeAssistant, user_flow) -> None:
"""Test we handle valid websocket port."""
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- return_value=True,
- ), patch.object(
- MockWSConnection,
- "connect",
- AsyncMock(side_effect=CannotConnectError),
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- new=get_kodi_connection,
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ return_value=True,
+ ),
+ patch.object(
+ MockWSConnection,
+ "connect",
+ AsyncMock(side_effect=CannotConnectError),
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ new=get_kodi_connection,
+ ),
):
result = await hass.config_entries.flow.async_configure(user_flow, TEST_HOST)
@@ -131,16 +146,20 @@ async def test_form_valid_ws_port(hass: HomeAssistant, user_flow) -> None:
assert result["step_id"] == "ws_port"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- return_value=True,
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- return_value=MockConnection(),
- ), patch(
- "homeassistant.components.kodi.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ return_value=MockConnection(),
+ ),
+ patch(
+ "homeassistant.components.kodi.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], TEST_WS_PORT
)
@@ -162,16 +181,20 @@ async def test_form_valid_ws_port(hass: HomeAssistant, user_flow) -> None:
async def test_form_empty_ws_port(hass: HomeAssistant, user_flow) -> None:
"""Test we handle an empty websocket port input."""
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- return_value=True,
- ), patch.object(
- MockWSConnection,
- "connect",
- AsyncMock(side_effect=CannotConnectError),
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- new=get_kodi_connection,
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ return_value=True,
+ ),
+ patch.object(
+ MockWSConnection,
+ "connect",
+ AsyncMock(side_effect=CannotConnectError),
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ new=get_kodi_connection,
+ ),
):
result = await hass.config_entries.flow.async_configure(user_flow, TEST_HOST)
@@ -204,12 +227,15 @@ async def test_form_empty_ws_port(hass: HomeAssistant, user_flow) -> None:
async def test_form_invalid_auth(hass: HomeAssistant, user_flow) -> None:
"""Test we handle invalid auth."""
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- side_effect=InvalidAuthError,
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- return_value=MockConnection(),
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ side_effect=InvalidAuthError,
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ return_value=MockConnection(),
+ ),
):
result = await hass.config_entries.flow.async_configure(user_flow, TEST_HOST)
@@ -217,12 +243,15 @@ async def test_form_invalid_auth(hass: HomeAssistant, user_flow) -> None:
assert result["step_id"] == "credentials"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- side_effect=InvalidAuthError,
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- return_value=MockConnection(),
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ side_effect=InvalidAuthError,
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ return_value=MockConnection(),
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], TEST_CREDENTIALS
@@ -232,12 +261,15 @@ async def test_form_invalid_auth(hass: HomeAssistant, user_flow) -> None:
assert result["step_id"] == "credentials"
assert result["errors"] == {"base": "invalid_auth"}
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- side_effect=CannotConnectError,
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- return_value=MockConnection(),
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ side_effect=CannotConnectError,
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ return_value=MockConnection(),
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], TEST_CREDENTIALS
@@ -247,12 +279,15 @@ async def test_form_invalid_auth(hass: HomeAssistant, user_flow) -> None:
assert result["step_id"] == "credentials"
assert result["errors"] == {"base": "cannot_connect"}
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- side_effect=Exception,
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- return_value=MockConnection(),
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ side_effect=Exception,
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ return_value=MockConnection(),
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], TEST_CREDENTIALS
@@ -262,16 +297,20 @@ async def test_form_invalid_auth(hass: HomeAssistant, user_flow) -> None:
assert result["step_id"] == "credentials"
assert result["errors"] == {"base": "unknown"}
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- return_value=True,
- ), patch.object(
- MockWSConnection,
- "connect",
- AsyncMock(side_effect=CannotConnectError),
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- new=get_kodi_connection,
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ return_value=True,
+ ),
+ patch.object(
+ MockWSConnection,
+ "connect",
+ AsyncMock(side_effect=CannotConnectError),
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ new=get_kodi_connection,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], TEST_CREDENTIALS
@@ -284,12 +323,15 @@ async def test_form_invalid_auth(hass: HomeAssistant, user_flow) -> None:
async def test_form_cannot_connect_http(hass: HomeAssistant, user_flow) -> None:
"""Test we handle cannot connect over HTTP error."""
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- side_effect=CannotConnectError,
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- return_value=MockConnection(),
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ side_effect=CannotConnectError,
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ return_value=MockConnection(),
+ ),
):
result = await hass.config_entries.flow.async_configure(user_flow, TEST_HOST)
@@ -300,12 +342,15 @@ async def test_form_cannot_connect_http(hass: HomeAssistant, user_flow) -> None:
async def test_form_exception_http(hass: HomeAssistant, user_flow) -> None:
"""Test we handle generic exception over HTTP."""
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- side_effect=Exception,
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- return_value=MockConnection(),
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ side_effect=Exception,
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ return_value=MockConnection(),
+ ),
):
result = await hass.config_entries.flow.async_configure(user_flow, TEST_HOST)
@@ -316,16 +361,20 @@ async def test_form_exception_http(hass: HomeAssistant, user_flow) -> None:
async def test_form_cannot_connect_ws(hass: HomeAssistant, user_flow) -> None:
"""Test we handle cannot connect over WebSocket error."""
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- return_value=True,
- ), patch.object(
- MockWSConnection,
- "connect",
- AsyncMock(side_effect=CannotConnectError),
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- new=get_kodi_connection,
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ return_value=True,
+ ),
+ patch.object(
+ MockWSConnection,
+ "connect",
+ AsyncMock(side_effect=CannotConnectError),
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ new=get_kodi_connection,
+ ),
):
result = await hass.config_entries.flow.async_configure(user_flow, TEST_HOST)
@@ -333,14 +382,18 @@ async def test_form_cannot_connect_ws(hass: HomeAssistant, user_flow) -> None:
assert result["step_id"] == "ws_port"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- return_value=True,
- ), patch.object(
- MockWSConnection, "connected", new_callable=PropertyMock(return_value=False)
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- new=get_kodi_connection,
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ return_value=True,
+ ),
+ patch.object(
+ MockWSConnection, "connected", new_callable=PropertyMock(return_value=False)
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ new=get_kodi_connection,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], TEST_WS_PORT
@@ -350,12 +403,15 @@ async def test_form_cannot_connect_ws(hass: HomeAssistant, user_flow) -> None:
assert result["step_id"] == "ws_port"
assert result["errors"] == {"base": "cannot_connect"}
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- side_effect=CannotConnectError,
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- new=get_kodi_connection,
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ side_effect=CannotConnectError,
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ new=get_kodi_connection,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], TEST_WS_PORT
@@ -368,16 +424,20 @@ async def test_form_cannot_connect_ws(hass: HomeAssistant, user_flow) -> None:
async def test_form_exception_ws(hass: HomeAssistant, user_flow) -> None:
"""Test we handle generic exception over WebSocket."""
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- return_value=True,
- ), patch.object(
- MockWSConnection,
- "connect",
- AsyncMock(side_effect=CannotConnectError),
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- new=get_kodi_connection,
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ return_value=True,
+ ),
+ patch.object(
+ MockWSConnection,
+ "connect",
+ AsyncMock(side_effect=CannotConnectError),
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ new=get_kodi_connection,
+ ),
):
result = await hass.config_entries.flow.async_configure(user_flow, TEST_HOST)
@@ -385,14 +445,16 @@ async def test_form_exception_ws(hass: HomeAssistant, user_flow) -> None:
assert result["step_id"] == "ws_port"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- return_value=True,
- ), patch.object(
- MockWSConnection, "connect", AsyncMock(side_effect=Exception)
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- new=get_kodi_connection,
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ return_value=True,
+ ),
+ patch.object(MockWSConnection, "connect", AsyncMock(side_effect=Exception)),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ new=get_kodi_connection,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], TEST_WS_PORT
@@ -405,12 +467,15 @@ async def test_form_exception_ws(hass: HomeAssistant, user_flow) -> None:
async def test_discovery(hass: HomeAssistant) -> None:
"""Test discovery flow works."""
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- return_value=True,
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- return_value=MockConnection(),
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ return_value=MockConnection(),
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -446,12 +511,15 @@ async def test_discovery(hass: HomeAssistant) -> None:
async def test_discovery_cannot_connect_http(hass: HomeAssistant) -> None:
"""Test discovery aborts if cannot connect."""
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- side_effect=CannotConnectError,
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- return_value=MockConnection(),
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ side_effect=CannotConnectError,
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ return_value=MockConnection(),
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -465,16 +533,20 @@ async def test_discovery_cannot_connect_http(hass: HomeAssistant) -> None:
async def test_discovery_cannot_connect_ws(hass: HomeAssistant) -> None:
"""Test discovery aborts if cannot connect to websocket."""
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- return_value=True,
- ), patch.object(
- MockWSConnection,
- "connect",
- AsyncMock(side_effect=CannotConnectError),
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- new=get_kodi_connection,
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ return_value=True,
+ ),
+ patch.object(
+ MockWSConnection,
+ "connect",
+ AsyncMock(side_effect=CannotConnectError),
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ new=get_kodi_connection,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -489,12 +561,15 @@ async def test_discovery_cannot_connect_ws(hass: HomeAssistant) -> None:
async def test_discovery_exception_http(hass: HomeAssistant, user_flow) -> None:
"""Test we handle generic exception during discovery validation."""
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- side_effect=Exception,
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- return_value=MockConnection(),
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ side_effect=Exception,
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ return_value=MockConnection(),
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -508,12 +583,15 @@ async def test_discovery_exception_http(hass: HomeAssistant, user_flow) -> None:
async def test_discovery_invalid_auth(hass: HomeAssistant) -> None:
"""Test we handle invalid auth during discovery."""
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- side_effect=InvalidAuthError,
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- return_value=MockConnection(),
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ side_effect=InvalidAuthError,
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ return_value=MockConnection(),
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -528,12 +606,15 @@ async def test_discovery_invalid_auth(hass: HomeAssistant) -> None:
async def test_discovery_duplicate_data(hass: HomeAssistant) -> None:
"""Test discovery aborts if same mDNS packet arrives."""
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- return_value=True,
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- return_value=MockConnection(),
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ return_value=MockConnection(),
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -588,16 +669,20 @@ async def test_discovery_without_unique_id(hass: HomeAssistant) -> None:
async def test_form_import(hass: HomeAssistant) -> None:
"""Test we get the form with import source."""
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- return_value=True,
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- return_value=MockConnection(),
- ), patch(
- "homeassistant.components.kodi.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ return_value=MockConnection(),
+ ),
+ patch(
+ "homeassistant.components.kodi.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
@@ -614,12 +699,15 @@ async def test_form_import(hass: HomeAssistant) -> None:
async def test_form_import_invalid_auth(hass: HomeAssistant) -> None:
"""Test we handle invalid auth on import."""
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- side_effect=InvalidAuthError,
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- return_value=MockConnection(),
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ side_effect=InvalidAuthError,
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ return_value=MockConnection(),
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -633,12 +721,15 @@ async def test_form_import_invalid_auth(hass: HomeAssistant) -> None:
async def test_form_import_cannot_connect(hass: HomeAssistant) -> None:
"""Test we handle cannot connect on import."""
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- side_effect=CannotConnectError,
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- return_value=MockConnection(),
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ side_effect=CannotConnectError,
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ return_value=MockConnection(),
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -652,12 +743,15 @@ async def test_form_import_cannot_connect(hass: HomeAssistant) -> None:
async def test_form_import_exception(hass: HomeAssistant) -> None:
"""Test we handle unknown exception on import."""
- with patch(
- "homeassistant.components.kodi.config_flow.Kodi.ping",
- side_effect=Exception,
- ), patch(
- "homeassistant.components.kodi.config_flow.get_kodi_connection",
- return_value=MockConnection(),
+ with (
+ patch(
+ "homeassistant.components.kodi.config_flow.Kodi.ping",
+ side_effect=Exception,
+ ),
+ patch(
+ "homeassistant.components.kodi.config_flow.get_kodi_connection",
+ return_value=MockConnection(),
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
diff --git a/tests/components/kraken/test_config_flow.py b/tests/components/kraken/test_config_flow.py
index 3d04e3183c3..e6639264291 100644
--- a/tests/components/kraken/test_config_flow.py
+++ b/tests/components/kraken/test_config_flow.py
@@ -59,15 +59,19 @@ async def test_options(hass: HomeAssistant) -> None:
)
entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.kraken.config_flow.KrakenAPI.get_tradable_asset_pairs",
- return_value=TRADEABLE_ASSET_PAIR_RESPONSE,
- ), patch(
- "pykrakenapi.KrakenAPI.get_tradable_asset_pairs",
- return_value=TRADEABLE_ASSET_PAIR_RESPONSE,
- ), patch(
- "pykrakenapi.KrakenAPI.get_ticker_information",
- return_value=TICKER_INFORMATION_RESPONSE,
+ with (
+ patch(
+ "homeassistant.components.kraken.config_flow.KrakenAPI.get_tradable_asset_pairs",
+ return_value=TRADEABLE_ASSET_PAIR_RESPONSE,
+ ),
+ patch(
+ "pykrakenapi.KrakenAPI.get_tradable_asset_pairs",
+ return_value=TRADEABLE_ASSET_PAIR_RESPONSE,
+ ),
+ patch(
+ "pykrakenapi.KrakenAPI.get_ticker_information",
+ return_value=TICKER_INFORMATION_RESPONSE,
+ ),
):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/kraken/test_init.py b/tests/components/kraken/test_init.py
index 2564fb97b26..8aeb7f18121 100644
--- a/tests/components/kraken/test_init.py
+++ b/tests/components/kraken/test_init.py
@@ -15,12 +15,15 @@ from tests.common import MockConfigEntry
async def test_unload_entry(hass: HomeAssistant) -> None:
"""Test unload for Kraken."""
- with patch(
- "pykrakenapi.KrakenAPI.get_tradable_asset_pairs",
- return_value=TRADEABLE_ASSET_PAIR_RESPONSE,
- ), patch(
- "pykrakenapi.KrakenAPI.get_ticker_information",
- return_value=TICKER_INFORMATION_RESPONSE,
+ with (
+ patch(
+ "pykrakenapi.KrakenAPI.get_tradable_asset_pairs",
+ return_value=TRADEABLE_ASSET_PAIR_RESPONSE,
+ ),
+ patch(
+ "pykrakenapi.KrakenAPI.get_ticker_information",
+ return_value=TICKER_INFORMATION_RESPONSE,
+ ),
):
entry = MockConfigEntry(domain=DOMAIN)
entry.add_to_hass(hass)
@@ -35,12 +38,15 @@ async def test_unknown_error(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test unload for Kraken."""
- with patch(
- "pykrakenapi.KrakenAPI.get_tradable_asset_pairs",
- return_value=TRADEABLE_ASSET_PAIR_RESPONSE,
- ), patch(
- "pykrakenapi.KrakenAPI.get_ticker_information",
- side_effect=KrakenAPIError("EQuery: Error"),
+ with (
+ patch(
+ "pykrakenapi.KrakenAPI.get_tradable_asset_pairs",
+ return_value=TRADEABLE_ASSET_PAIR_RESPONSE,
+ ),
+ patch(
+ "pykrakenapi.KrakenAPI.get_ticker_information",
+ side_effect=KrakenAPIError("EQuery: Error"),
+ ),
):
entry = MockConfigEntry(domain=DOMAIN)
entry.add_to_hass(hass)
@@ -54,12 +60,15 @@ async def test_callrate_limit(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test unload for Kraken."""
- with patch(
- "pykrakenapi.KrakenAPI.get_tradable_asset_pairs",
- return_value=TRADEABLE_ASSET_PAIR_RESPONSE,
- ), patch(
- "pykrakenapi.KrakenAPI.get_ticker_information",
- side_effect=CallRateLimitError(),
+ with (
+ patch(
+ "pykrakenapi.KrakenAPI.get_tradable_asset_pairs",
+ return_value=TRADEABLE_ASSET_PAIR_RESPONSE,
+ ),
+ patch(
+ "pykrakenapi.KrakenAPI.get_ticker_information",
+ side_effect=CallRateLimitError(),
+ ),
):
entry = MockConfigEntry(domain=DOMAIN)
entry.add_to_hass(hass)
diff --git a/tests/components/kraken/test_sensor.py b/tests/components/kraken/test_sensor.py
index 398177070df..fd0a1dc72d1 100644
--- a/tests/components/kraken/test_sensor.py
+++ b/tests/components/kraken/test_sensor.py
@@ -32,12 +32,15 @@ async def test_sensor(
entity_registry_enabled_by_default: None,
) -> None:
"""Test that sensor has a value."""
- with patch(
- "pykrakenapi.KrakenAPI.get_tradable_asset_pairs",
- return_value=TRADEABLE_ASSET_PAIR_RESPONSE,
- ), patch(
- "pykrakenapi.KrakenAPI.get_ticker_information",
- return_value=TICKER_INFORMATION_RESPONSE,
+ with (
+ patch(
+ "pykrakenapi.KrakenAPI.get_tradable_asset_pairs",
+ return_value=TRADEABLE_ASSET_PAIR_RESPONSE,
+ ),
+ patch(
+ "pykrakenapi.KrakenAPI.get_ticker_information",
+ return_value=TICKER_INFORMATION_RESPONSE,
+ ),
):
entry = MockConfigEntry(
domain=DOMAIN,
@@ -140,12 +143,15 @@ async def test_sensors_available_after_restart(
freezer: FrozenDateTimeFactory,
) -> None:
"""Test that all sensors are added again after a restart."""
- with patch(
- "pykrakenapi.KrakenAPI.get_tradable_asset_pairs",
- return_value=TRADEABLE_ASSET_PAIR_RESPONSE,
- ), patch(
- "pykrakenapi.KrakenAPI.get_ticker_information",
- return_value=TICKER_INFORMATION_RESPONSE,
+ with (
+ patch(
+ "pykrakenapi.KrakenAPI.get_tradable_asset_pairs",
+ return_value=TRADEABLE_ASSET_PAIR_RESPONSE,
+ ),
+ patch(
+ "pykrakenapi.KrakenAPI.get_ticker_information",
+ return_value=TICKER_INFORMATION_RESPONSE,
+ ),
):
entry = MockConfigEntry(
domain=DOMAIN,
@@ -179,12 +185,15 @@ async def test_sensors_added_after_config_update(
hass: HomeAssistant, freezer: FrozenDateTimeFactory
) -> None:
"""Test that sensors are added when another tracked asset pair is added."""
- with patch(
- "pykrakenapi.KrakenAPI.get_tradable_asset_pairs",
- return_value=TRADEABLE_ASSET_PAIR_RESPONSE,
- ), patch(
- "pykrakenapi.KrakenAPI.get_ticker_information",
- return_value=TICKER_INFORMATION_RESPONSE,
+ with (
+ patch(
+ "pykrakenapi.KrakenAPI.get_tradable_asset_pairs",
+ return_value=TRADEABLE_ASSET_PAIR_RESPONSE,
+ ),
+ patch(
+ "pykrakenapi.KrakenAPI.get_ticker_information",
+ return_value=TICKER_INFORMATION_RESPONSE,
+ ),
):
entry = MockConfigEntry(
domain=DOMAIN,
@@ -224,13 +233,16 @@ async def test_missing_pair_marks_sensor_unavailable(
hass: HomeAssistant, freezer: FrozenDateTimeFactory
) -> None:
"""Test that a missing tradable asset pair marks the sensor unavailable."""
- with patch(
- "pykrakenapi.KrakenAPI.get_tradable_asset_pairs",
- return_value=TRADEABLE_ASSET_PAIR_RESPONSE,
- ) as tradeable_asset_pairs_mock, patch(
- "pykrakenapi.KrakenAPI.get_ticker_information",
- return_value=TICKER_INFORMATION_RESPONSE,
- ) as ticket_information_mock:
+ with (
+ patch(
+ "pykrakenapi.KrakenAPI.get_tradable_asset_pairs",
+ return_value=TRADEABLE_ASSET_PAIR_RESPONSE,
+ ) as tradeable_asset_pairs_mock,
+ patch(
+ "pykrakenapi.KrakenAPI.get_ticker_information",
+ return_value=TICKER_INFORMATION_RESPONSE,
+ ) as ticket_information_mock,
+ ):
entry = MockConfigEntry(
domain=DOMAIN,
options={
diff --git a/tests/components/kulersky/test_config_flow.py b/tests/components/kulersky/test_config_flow.py
index 5ff3f51f1ad..9638df360c8 100644
--- a/tests/components/kulersky/test_config_flow.py
+++ b/tests/components/kulersky/test_config_flow.py
@@ -21,13 +21,16 @@ async def test_flow_success(hass: HomeAssistant) -> None:
light = MagicMock(spec=pykulersky.Light)
light.address = "AA:BB:CC:11:22:33"
light.name = "Bedroom"
- with patch(
- "homeassistant.components.kulersky.config_flow.pykulersky.discover",
- return_value=[light],
- ), patch(
- "homeassistant.components.kulersky.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.kulersky.config_flow.pykulersky.discover",
+ return_value=[light],
+ ),
+ patch(
+ "homeassistant.components.kulersky.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{},
@@ -50,13 +53,16 @@ async def test_flow_no_devices_found(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] is None
- with patch(
- "homeassistant.components.kulersky.config_flow.pykulersky.discover",
- return_value=[],
- ), patch(
- "homeassistant.components.kulersky.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.kulersky.config_flow.pykulersky.discover",
+ return_value=[],
+ ),
+ patch(
+ "homeassistant.components.kulersky.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{},
@@ -77,13 +83,16 @@ async def test_flow_exceptions_caught(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] is None
- with patch(
- "homeassistant.components.kulersky.config_flow.pykulersky.discover",
- side_effect=pykulersky.PykulerskyException("TEST"),
- ), patch(
- "homeassistant.components.kulersky.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.kulersky.config_flow.pykulersky.discover",
+ side_effect=pykulersky.PykulerskyException("TEST"),
+ ),
+ patch(
+ "homeassistant.components.kulersky.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{},
diff --git a/tests/components/lacrosse_view/test_config_flow.py b/tests/components/lacrosse_view/test_config_flow.py
index b80dab1a7ec..195c004179b 100644
--- a/tests/components/lacrosse_view/test_config_flow.py
+++ b/tests/components/lacrosse_view/test_config_flow.py
@@ -23,12 +23,15 @@ async def test_form(hass: HomeAssistant, mock_setup_entry: AsyncMock) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with patch(
- "lacrosse_view.LaCrosse.login",
- return_value=True,
- ), patch(
- "lacrosse_view.LaCrosse.get_locations",
- return_value=[Location(id=1, name="Test")],
+ with (
+ patch(
+ "lacrosse_view.LaCrosse.login",
+ return_value=True,
+ ),
+ patch(
+ "lacrosse_view.LaCrosse.get_locations",
+ return_value=[Location(id=1, name="Test")],
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -109,8 +112,9 @@ async def test_form_login_first(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch("lacrosse_view.LaCrosse.login", return_value=True), patch(
- "lacrosse_view.LaCrosse.get_locations", side_effect=LoginError
+ with (
+ patch("lacrosse_view.LaCrosse.login", return_value=True),
+ patch("lacrosse_view.LaCrosse.get_locations", side_effect=LoginError),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -130,9 +134,12 @@ async def test_form_no_locations(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch("lacrosse_view.LaCrosse.login", return_value=True), patch(
- "lacrosse_view.LaCrosse.get_locations",
- return_value=None,
+ with (
+ patch("lacrosse_view.LaCrosse.login", return_value=True),
+ patch(
+ "lacrosse_view.LaCrosse.get_locations",
+ return_value=None,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -192,12 +199,15 @@ async def test_already_configured_device(
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with patch(
- "lacrosse_view.LaCrosse.login",
- return_value=True,
- ), patch(
- "lacrosse_view.LaCrosse.get_locations",
- return_value=[Location(id=1, name="Test")],
+ with (
+ patch(
+ "lacrosse_view.LaCrosse.login",
+ return_value=True,
+ ),
+ patch(
+ "lacrosse_view.LaCrosse.get_locations",
+ return_value=[Location(id=1, name="Test")],
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -257,9 +267,12 @@ async def test_reauth(hass: HomeAssistant) -> None:
new_username = "new-username"
new_password = "new-password"
- with patch("lacrosse_view.LaCrosse.login", return_value=True), patch(
- "lacrosse_view.LaCrosse.get_locations",
- return_value=[Location(id=1, name="Test")],
+ with (
+ patch("lacrosse_view.LaCrosse.login", return_value=True),
+ patch(
+ "lacrosse_view.LaCrosse.get_locations",
+ return_value=[Location(id=1, name="Test")],
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/lacrosse_view/test_diagnostics.py b/tests/components/lacrosse_view/test_diagnostics.py
index 9fef7bf5955..08cef64a935 100644
--- a/tests/components/lacrosse_view/test_diagnostics.py
+++ b/tests/components/lacrosse_view/test_diagnostics.py
@@ -25,8 +25,9 @@ async def test_entry_diagnostics(
)
config_entry.add_to_hass(hass)
- with patch("lacrosse_view.LaCrosse.login", return_value=True), patch(
- "lacrosse_view.LaCrosse.get_sensors", return_value=[TEST_SENSOR]
+ with (
+ patch("lacrosse_view.LaCrosse.login", return_value=True),
+ patch("lacrosse_view.LaCrosse.get_sensors", return_value=[TEST_SENSOR]),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/lacrosse_view/test_init.py b/tests/components/lacrosse_view/test_init.py
index 7036371d323..cf11e787ad8 100644
--- a/tests/components/lacrosse_view/test_init.py
+++ b/tests/components/lacrosse_view/test_init.py
@@ -20,9 +20,12 @@ async def test_unload_entry(hass: HomeAssistant) -> None:
config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_ENTRY_DATA)
config_entry.add_to_hass(hass)
- with patch("lacrosse_view.LaCrosse.login", return_value=True), patch(
- "lacrosse_view.LaCrosse.get_sensors",
- return_value=[TEST_SENSOR],
+ with (
+ patch("lacrosse_view.LaCrosse.login", return_value=True),
+ patch(
+ "lacrosse_view.LaCrosse.get_sensors",
+ return_value=[TEST_SENSOR],
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -63,8 +66,9 @@ async def test_http_error(hass: HomeAssistant) -> None:
config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_ENTRY_DATA)
config_entry.add_to_hass(hass)
- with patch("lacrosse_view.LaCrosse.login", return_value=True), patch(
- "lacrosse_view.LaCrosse.get_sensors", side_effect=HTTPError
+ with (
+ patch("lacrosse_view.LaCrosse.login", return_value=True),
+ patch("lacrosse_view.LaCrosse.get_sensors", side_effect=HTTPError),
):
assert not await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -80,9 +84,12 @@ async def test_new_token(hass: HomeAssistant, freezer: FrozenDateTimeFactory) ->
config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_ENTRY_DATA)
config_entry.add_to_hass(hass)
- with patch("lacrosse_view.LaCrosse.login", return_value=True) as login, patch(
- "lacrosse_view.LaCrosse.get_sensors",
- return_value=[TEST_SENSOR],
+ with (
+ patch("lacrosse_view.LaCrosse.login", return_value=True) as login,
+ patch(
+ "lacrosse_view.LaCrosse.get_sensors",
+ return_value=[TEST_SENSOR],
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -93,9 +100,12 @@ async def test_new_token(hass: HomeAssistant, freezer: FrozenDateTimeFactory) ->
assert len(entries) == 1
assert entries[0].state == ConfigEntryState.LOADED
- with patch("lacrosse_view.LaCrosse.login", return_value=True) as login, patch(
- "lacrosse_view.LaCrosse.get_sensors",
- return_value=[TEST_SENSOR],
+ with (
+ patch("lacrosse_view.LaCrosse.login", return_value=True) as login,
+ patch(
+ "lacrosse_view.LaCrosse.get_sensors",
+ return_value=[TEST_SENSOR],
+ ),
):
freezer.tick(timedelta(hours=1))
async_fire_time_changed(hass)
@@ -111,9 +121,12 @@ async def test_failed_token(
config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_ENTRY_DATA)
config_entry.add_to_hass(hass)
- with patch("lacrosse_view.LaCrosse.login", return_value=True) as login, patch(
- "lacrosse_view.LaCrosse.get_sensors",
- return_value=[TEST_SENSOR],
+ with (
+ patch("lacrosse_view.LaCrosse.login", return_value=True) as login,
+ patch(
+ "lacrosse_view.LaCrosse.get_sensors",
+ return_value=[TEST_SENSOR],
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/lacrosse_view/test_sensor.py b/tests/components/lacrosse_view/test_sensor.py
index f9e52850685..b9140e6173f 100644
--- a/tests/components/lacrosse_view/test_sensor.py
+++ b/tests/components/lacrosse_view/test_sensor.py
@@ -32,8 +32,9 @@ async def test_entities_added(hass: HomeAssistant) -> None:
config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_ENTRY_DATA)
config_entry.add_to_hass(hass)
- with patch("lacrosse_view.LaCrosse.login", return_value=True), patch(
- "lacrosse_view.LaCrosse.get_sensors", return_value=[TEST_SENSOR]
+ with (
+ patch("lacrosse_view.LaCrosse.login", return_value=True),
+ patch("lacrosse_view.LaCrosse.get_sensors", return_value=[TEST_SENSOR]),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -53,8 +54,12 @@ async def test_sensor_permission(
config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_ENTRY_DATA)
config_entry.add_to_hass(hass)
- with patch("lacrosse_view.LaCrosse.login", return_value=True), patch(
- "lacrosse_view.LaCrosse.get_sensors", return_value=[TEST_NO_PERMISSION_SENSOR]
+ with (
+ patch("lacrosse_view.LaCrosse.login", return_value=True),
+ patch(
+ "lacrosse_view.LaCrosse.get_sensors",
+ return_value=[TEST_NO_PERMISSION_SENSOR],
+ ),
):
assert not await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -74,8 +79,11 @@ async def test_field_not_supported(
config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_ENTRY_DATA)
config_entry.add_to_hass(hass)
- with patch("lacrosse_view.LaCrosse.login", return_value=True), patch(
- "lacrosse_view.LaCrosse.get_sensors", return_value=[TEST_UNSUPPORTED_SENSOR]
+ with (
+ patch("lacrosse_view.LaCrosse.login", return_value=True),
+ patch(
+ "lacrosse_view.LaCrosse.get_sensors", return_value=[TEST_UNSUPPORTED_SENSOR]
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -106,9 +114,12 @@ async def test_field_types(
config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_ENTRY_DATA)
config_entry.add_to_hass(hass)
- with patch("lacrosse_view.LaCrosse.login", return_value=True), patch(
- "lacrosse_view.LaCrosse.get_sensors",
- return_value=[test_input],
+ with (
+ patch("lacrosse_view.LaCrosse.login", return_value=True),
+ patch(
+ "lacrosse_view.LaCrosse.get_sensors",
+ return_value=[test_input],
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -126,9 +137,12 @@ async def test_no_field(hass: HomeAssistant, caplog: pytest.LogCaptureFixture) -
config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_ENTRY_DATA)
config_entry.add_to_hass(hass)
- with patch("lacrosse_view.LaCrosse.login", return_value=True), patch(
- "lacrosse_view.LaCrosse.get_sensors",
- return_value=[TEST_NO_FIELD_SENSOR],
+ with (
+ patch("lacrosse_view.LaCrosse.login", return_value=True),
+ patch(
+ "lacrosse_view.LaCrosse.get_sensors",
+ return_value=[TEST_NO_FIELD_SENSOR],
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -146,9 +160,12 @@ async def test_field_data_missing(hass: HomeAssistant) -> None:
config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_ENTRY_DATA)
config_entry.add_to_hass(hass)
- with patch("lacrosse_view.LaCrosse.login", return_value=True), patch(
- "lacrosse_view.LaCrosse.get_sensors",
- return_value=[TEST_MISSING_FIELD_DATA_SENSOR],
+ with (
+ patch("lacrosse_view.LaCrosse.login", return_value=True),
+ patch(
+ "lacrosse_view.LaCrosse.get_sensors",
+ return_value=[TEST_MISSING_FIELD_DATA_SENSOR],
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/lametric/conftest.py b/tests/components/lametric/conftest.py
index b321041461a..bd2ae275970 100644
--- a/tests/components/lametric/conftest.py
+++ b/tests/components/lametric/conftest.py
@@ -76,11 +76,15 @@ def device_fixture() -> str:
@pytest.fixture
def mock_lametric(request, device_fixture: str) -> Generator[MagicMock, None, None]:
"""Return a mocked LaMetric TIME client."""
- with patch(
- "homeassistant.components.lametric.coordinator.LaMetricDevice", autospec=True
- ) as lametric_mock, patch(
- "homeassistant.components.lametric.config_flow.LaMetricDevice",
- new=lametric_mock,
+ with (
+ patch(
+ "homeassistant.components.lametric.coordinator.LaMetricDevice",
+ autospec=True,
+ ) as lametric_mock,
+ patch(
+ "homeassistant.components.lametric.config_flow.LaMetricDevice",
+ new=lametric_mock,
+ ),
):
lametric = lametric_mock.return_value
lametric.api_key = "mock-api-key"
diff --git a/tests/components/lastfm/test_config_flow.py b/tests/components/lastfm/test_config_flow.py
index 0b5906c5268..93fc9e5a206 100644
--- a/tests/components/lastfm/test_config_flow.py
+++ b/tests/components/lastfm/test_config_flow.py
@@ -141,9 +141,10 @@ async def test_flow_friends_no_friends(
hass: HomeAssistant, default_user_no_friends: MockUser
) -> None:
"""Test options is empty when user has no friends."""
- with patch(
- "pylast.User", return_value=default_user_no_friends
- ), patch_setup_entry():
+ with (
+ patch("pylast.User", return_value=default_user_no_friends),
+ patch_setup_entry(),
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
diff --git a/tests/components/laundrify/conftest.py b/tests/components/laundrify/conftest.py
index 18884cdfb7b..91aeebf81ee 100644
--- a/tests/components/laundrify/conftest.py
+++ b/tests/components/laundrify/conftest.py
@@ -42,11 +42,14 @@ def laundrify_validate_token_fixture():
@pytest.fixture(name="laundrify_api_mock", autouse=True)
def laundrify_api_fixture(laundrify_exchange_code, laundrify_validate_token):
"""Mock valid laundrify API responses."""
- with patch(
- "laundrify_aio.LaundrifyAPI.get_account_id",
- return_value=VALID_ACCOUNT_ID,
- ), patch(
- "laundrify_aio.LaundrifyAPI.get_machines",
- return_value=json.loads(load_fixture("laundrify/machines.json")),
- ) as get_machines_mock:
+ with (
+ patch(
+ "laundrify_aio.LaundrifyAPI.get_account_id",
+ return_value=VALID_ACCOUNT_ID,
+ ),
+ patch(
+ "laundrify_aio.LaundrifyAPI.get_machines",
+ return_value=json.loads(load_fixture("laundrify/machines.json")),
+ ) as get_machines_mock,
+ ):
yield get_machines_mock
diff --git a/tests/components/lcn/test_config_flow.py b/tests/components/lcn/test_config_flow.py
index 6580fb35d02..aa1b5086e65 100644
--- a/tests/components/lcn/test_config_flow.py
+++ b/tests/components/lcn/test_config_flow.py
@@ -36,9 +36,11 @@ IMPORT_DATA = {
async def test_step_import(hass: HomeAssistant) -> None:
"""Test for import step."""
- with patch("pypck.connection.PchkConnectionManager.async_connect"), patch(
- "homeassistant.components.lcn.async_setup", return_value=True
- ), patch("homeassistant.components.lcn.async_setup_entry", return_value=True):
+ with (
+ patch("pypck.connection.PchkConnectionManager.async_connect"),
+ patch("homeassistant.components.lcn.async_setup", return_value=True),
+ patch("homeassistant.components.lcn.async_setup_entry", return_value=True),
+ ):
data = IMPORT_DATA.copy()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=data
diff --git a/tests/components/lcn/test_init.py b/tests/components/lcn/test_init.py
index cfa518a9367..292ebc045b2 100644
--- a/tests/components/lcn/test_init.py
+++ b/tests/components/lcn/test_init.py
@@ -127,9 +127,10 @@ async def test_async_setup_entry_raises_timeout_error(
async def test_async_setup_from_configuration_yaml(hass: HomeAssistant) -> None:
"""Test a successful setup using data from configuration.yaml."""
- with patch(
- "pypck.connection.PchkConnectionManager", MockPchkConnectionManager
- ), patch("homeassistant.components.lcn.async_setup_entry") as async_setup_entry:
+ with (
+ patch("pypck.connection.PchkConnectionManager", MockPchkConnectionManager),
+ patch("homeassistant.components.lcn.async_setup_entry") as async_setup_entry,
+ ):
await setup_component(hass)
assert async_setup_entry.await_count == 2
diff --git a/tests/components/ld2410_ble/test_config_flow.py b/tests/components/ld2410_ble/test_config_flow.py
index 1c87b72330d..74e7e8a2c8e 100644
--- a/tests/components/ld2410_ble/test_config_flow.py
+++ b/tests/components/ld2410_ble/test_config_flow.py
@@ -28,12 +28,15 @@ async def test_user_step_success(hass: HomeAssistant) -> None:
assert result["step_id"] == "user"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.ld2410_ble.config_flow.LD2410BLE.initialise",
- ), patch(
- "homeassistant.components.ld2410_ble.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.ld2410_ble.config_flow.LD2410BLE.initialise",
+ ),
+ patch(
+ "homeassistant.components.ld2410_ble.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -114,12 +117,15 @@ async def test_user_step_cannot_connect(hass: HomeAssistant) -> None:
assert result2["step_id"] == "user"
assert result2["errors"] == {"base": "cannot_connect"}
- with patch(
- "homeassistant.components.ld2410_ble.config_flow.LD2410BLE.initialise",
- ), patch(
- "homeassistant.components.ld2410_ble.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.ld2410_ble.config_flow.LD2410BLE.initialise",
+ ),
+ patch(
+ "homeassistant.components.ld2410_ble.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
@@ -166,12 +172,15 @@ async def test_user_step_unknown_exception(hass: HomeAssistant) -> None:
assert result2["step_id"] == "user"
assert result2["errors"] == {"base": "unknown"}
- with patch(
- "homeassistant.components.ld2410_ble.config_flow.LD2410BLE.initialise",
- ), patch(
- "homeassistant.components.ld2410_ble.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.ld2410_ble.config_flow.LD2410BLE.initialise",
+ ),
+ patch(
+ "homeassistant.components.ld2410_ble.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
@@ -200,12 +209,15 @@ async def test_bluetooth_step_success(hass: HomeAssistant) -> None:
assert result["step_id"] == "user"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.ld2410_ble.config_flow.LD2410BLE.initialise",
- ), patch(
- "homeassistant.components.ld2410_ble.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.ld2410_ble.config_flow.LD2410BLE.initialise",
+ ),
+ patch(
+ "homeassistant.components.ld2410_ble.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
diff --git a/tests/components/led_ble/test_config_flow.py b/tests/components/led_ble/test_config_flow.py
index d0274e9a6dc..5ceda954ba8 100644
--- a/tests/components/led_ble/test_config_flow.py
+++ b/tests/components/led_ble/test_config_flow.py
@@ -32,12 +32,15 @@ async def test_user_step_success(hass: HomeAssistant) -> None:
assert result["step_id"] == "user"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.led_ble.config_flow.LEDBLE.update",
- ), patch(
- "homeassistant.components.led_ble.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.led_ble.config_flow.LEDBLE.update",
+ ),
+ patch(
+ "homeassistant.components.led_ble.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -118,12 +121,15 @@ async def test_user_step_cannot_connect(hass: HomeAssistant) -> None:
assert result2["step_id"] == "user"
assert result2["errors"] == {"base": "cannot_connect"}
- with patch(
- "homeassistant.components.led_ble.config_flow.LEDBLE.update",
- ), patch(
- "homeassistant.components.led_ble.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.led_ble.config_flow.LEDBLE.update",
+ ),
+ patch(
+ "homeassistant.components.led_ble.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
@@ -170,12 +176,15 @@ async def test_user_step_unknown_exception(hass: HomeAssistant) -> None:
assert result2["step_id"] == "user"
assert result2["errors"] == {"base": "unknown"}
- with patch(
- "homeassistant.components.led_ble.config_flow.LEDBLE.update",
- ), patch(
- "homeassistant.components.led_ble.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.led_ble.config_flow.LEDBLE.update",
+ ),
+ patch(
+ "homeassistant.components.led_ble.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
@@ -204,12 +213,15 @@ async def test_bluetooth_step_success(hass: HomeAssistant) -> None:
assert result["step_id"] == "user"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.led_ble.config_flow.LEDBLE.update",
- ), patch(
- "homeassistant.components.led_ble.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.led_ble.config_flow.LEDBLE.update",
+ ),
+ patch(
+ "homeassistant.components.led_ble.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
diff --git a/tests/components/lg_soundbar/test_config_flow.py b/tests/components/lg_soundbar/test_config_flow.py
index e41466f3204..4fab919c555 100644
--- a/tests/components/lg_soundbar/test_config_flow.py
+++ b/tests/components/lg_soundbar/test_config_flow.py
@@ -61,11 +61,14 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.lg_soundbar.config_flow.temescal"
- ) as mock_temescal, patch(
- "homeassistant.components.lg_soundbar.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.lg_soundbar.config_flow.temescal"
+ ) as mock_temescal,
+ patch(
+ "homeassistant.components.lg_soundbar.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
setup_mock_temescal(
hass=hass,
mock_temescal=mock_temescal,
@@ -99,11 +102,14 @@ async def test_form_mac_info_response_empty(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.lg_soundbar.config_flow.temescal"
- ) as mock_temescal, patch(
- "homeassistant.components.lg_soundbar.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.lg_soundbar.config_flow.temescal"
+ ) as mock_temescal,
+ patch(
+ "homeassistant.components.lg_soundbar.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
setup_mock_temescal(
hass=hass,
mock_temescal=mock_temescal,
@@ -142,11 +148,14 @@ async def test_form_uuid_present_in_both_functions_uuid_q_empty(
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.lg_soundbar.config_flow.temescal"
- ) as mock_temescal, patch(
- "homeassistant.components.lg_soundbar.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.lg_soundbar.config_flow.temescal"
+ ) as mock_temescal,
+ patch(
+ "homeassistant.components.lg_soundbar.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
setup_mock_temescal(
hass=hass,
mock_temescal=mock_temescal,
@@ -187,14 +196,18 @@ async def test_form_uuid_present_in_both_functions_uuid_q_not_empty(
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.lg_soundbar.config_flow.QUEUE_TIMEOUT",
- new=0.1,
- ), patch(
- "homeassistant.components.lg_soundbar.config_flow.temescal"
- ) as mock_temescal, patch(
- "homeassistant.components.lg_soundbar.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.lg_soundbar.config_flow.QUEUE_TIMEOUT",
+ new=0.1,
+ ),
+ patch(
+ "homeassistant.components.lg_soundbar.config_flow.temescal"
+ ) as mock_temescal,
+ patch(
+ "homeassistant.components.lg_soundbar.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
setup_mock_temescal(
hass=hass,
mock_temescal=mock_temescal,
@@ -230,11 +243,14 @@ async def test_form_uuid_missing_from_mac_info(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.lg_soundbar.config_flow.temescal"
- ) as mock_temescal, patch(
- "homeassistant.components.lg_soundbar.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.lg_soundbar.config_flow.temescal"
+ ) as mock_temescal,
+ patch(
+ "homeassistant.components.lg_soundbar.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
setup_mock_temescal(
hass=hass,
mock_temescal=mock_temescal,
@@ -269,14 +285,18 @@ async def test_form_uuid_not_provided_by_api(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.lg_soundbar.config_flow.QUEUE_TIMEOUT",
- new=0.1,
- ), patch(
- "homeassistant.components.lg_soundbar.config_flow.temescal"
- ) as mock_temescal, patch(
- "homeassistant.components.lg_soundbar.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.lg_soundbar.config_flow.QUEUE_TIMEOUT",
+ new=0.1,
+ ),
+ patch(
+ "homeassistant.components.lg_soundbar.config_flow.temescal"
+ ) as mock_temescal,
+ patch(
+ "homeassistant.components.lg_soundbar.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
setup_mock_temescal(
hass=hass,
mock_temescal=mock_temescal,
@@ -310,14 +330,18 @@ async def test_form_both_queues_empty(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.lg_soundbar.config_flow.QUEUE_TIMEOUT",
- new=0.1,
- ), patch(
- "homeassistant.components.lg_soundbar.config_flow.temescal"
- ) as mock_temescal, patch(
- "homeassistant.components.lg_soundbar.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.lg_soundbar.config_flow.QUEUE_TIMEOUT",
+ new=0.1,
+ ),
+ patch(
+ "homeassistant.components.lg_soundbar.config_flow.temescal"
+ ) as mock_temescal,
+ patch(
+ "homeassistant.components.lg_soundbar.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
setup_mock_temescal(hass=hass, mock_temescal=mock_temescal)
result2 = await hass.config_entries.flow.async_configure(
@@ -352,12 +376,15 @@ async def test_no_uuid_host_already_configured(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.lg_soundbar.config_flow.QUEUE_TIMEOUT",
- new=0.1,
- ), patch(
- "homeassistant.components.lg_soundbar.config_flow.temescal"
- ) as mock_temescal:
+ with (
+ patch(
+ "homeassistant.components.lg_soundbar.config_flow.QUEUE_TIMEOUT",
+ new=0.1,
+ ),
+ patch(
+ "homeassistant.components.lg_soundbar.config_flow.temescal"
+ ) as mock_temescal,
+ ):
setup_mock_temescal(
hass=hass, mock_temescal=mock_temescal, info={"s_user_name": "name"}
)
diff --git a/tests/components/lifx/__init__.py b/tests/components/lifx/__init__.py
index dc730565cc7..505d212a352 100644
--- a/tests/components/lifx/__init__.py
+++ b/tests/components/lifx/__init__.py
@@ -243,8 +243,12 @@ def _patch_discovery(device: Light | None = None, no_device: bool = False):
@contextmanager
def _patcher():
- with patch.object(discovery, "DEFAULT_TIMEOUT", 0), patch(
- "homeassistant.components.lifx.discovery.LifxDiscovery", MockLifxDiscovery
+ with (
+ patch.object(discovery, "DEFAULT_TIMEOUT", 0),
+ patch(
+ "homeassistant.components.lifx.discovery.LifxDiscovery",
+ MockLifxDiscovery,
+ ),
):
yield
diff --git a/tests/components/lifx/conftest.py b/tests/components/lifx/conftest.py
index 15fe8898a5f..c126ca20ecd 100644
--- a/tests/components/lifx/conftest.py
+++ b/tests/components/lifx/conftest.py
@@ -49,10 +49,11 @@ def lifx_mock_get_source_ip(mock_get_source_ip):
@pytest.fixture(autouse=True)
def lifx_no_wait_for_timeouts():
"""Avoid waiting for timeouts in tests."""
- with patch.object(util, "OVERALL_TIMEOUT", 0), patch.object(
- config_flow, "OVERALL_TIMEOUT", 0
- ), patch.object(coordinator, "OVERALL_TIMEOUT", 0), patch.object(
- coordinator, "MAX_UPDATE_TIME", 0
+ with (
+ patch.object(util, "OVERALL_TIMEOUT", 0),
+ patch.object(config_flow, "OVERALL_TIMEOUT", 0),
+ patch.object(coordinator, "OVERALL_TIMEOUT", 0),
+ patch.object(coordinator, "MAX_UPDATE_TIME", 0),
):
yield
diff --git a/tests/components/lifx/test_binary_sensor.py b/tests/components/lifx/test_binary_sensor.py
index fa57591e305..9221ac79149 100644
--- a/tests/components/lifx/test_binary_sensor.py
+++ b/tests/components/lifx/test_binary_sensor.py
@@ -47,9 +47,11 @@ async def test_hev_cycle_state(
)
config_entry.add_to_hass(hass)
bulb = _mocked_clean_bulb()
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
diff --git a/tests/components/lifx/test_button.py b/tests/components/lifx/test_button.py
index 4b0a33e8d0c..b2adf4f4c15 100644
--- a/tests/components/lifx/test_button.py
+++ b/tests/components/lifx/test_button.py
@@ -44,9 +44,11 @@ async def test_button_restart(
)
config_entry.add_to_hass(hass)
bulb = _mocked_bulb()
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -77,9 +79,11 @@ async def test_button_identify(
)
config_entry.add_to_hass(hass)
bulb = _mocked_bulb()
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
diff --git a/tests/components/lifx/test_config_flow.py b/tests/components/lifx/test_config_flow.py
index 78e852e2cab..0a0c26da424 100644
--- a/tests/components/lifx/test_config_flow.py
+++ b/tests/components/lifx/test_config_flow.py
@@ -65,11 +65,12 @@ async def test_discovery(hass: HomeAssistant) -> None:
assert result2["step_id"] == "pick_device"
assert not result2["errors"]
- with _patch_discovery(), _patch_config_flow_try_connect(), patch(
- f"{MODULE}.async_setup", return_value=True
- ) as mock_setup, patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_config_flow_try_connect(),
+ patch(f"{MODULE}.async_setup", return_value=True) as mock_setup,
+ patch(f"{MODULE}.async_setup_entry", return_value=True) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_DEVICE: SERIAL},
@@ -168,9 +169,11 @@ async def test_discovery_with_existing_device_present(hass: HomeAssistant) -> No
assert result2["step_id"] == "pick_device"
assert not result2["errors"]
- with _patch_discovery(), _patch_config_flow_try_connect(), patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_config_flow_try_connect(),
+ patch(f"{MODULE}.async_setup_entry", return_value=True) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_DEVICE: SERIAL}
)
@@ -205,8 +208,9 @@ async def test_discovery_no_device(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with _patch_discovery(no_device=True), _patch_config_flow_try_connect(
- no_device=True
+ with (
+ _patch_discovery(no_device=True),
+ _patch_config_flow_try_connect(no_device=True),
):
result2 = await hass.config_entries.flow.async_configure(result["flow_id"], {})
await hass.async_block_till_done()
@@ -225,8 +229,9 @@ async def test_manual(hass: HomeAssistant) -> None:
assert not result["errors"]
# Cannot connect (timeout)
- with _patch_discovery(no_device=True), _patch_config_flow_try_connect(
- no_device=True
+ with (
+ _patch_discovery(no_device=True),
+ _patch_config_flow_try_connect(no_device=True),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: IP_ADDRESS}
@@ -238,9 +243,12 @@ async def test_manual(hass: HomeAssistant) -> None:
assert result2["errors"] == {"base": "cannot_connect"}
# Success
- with _patch_discovery(), _patch_config_flow_try_connect(), patch(
- f"{MODULE}.async_setup", return_value=True
- ), patch(f"{MODULE}.async_setup_entry", return_value=True):
+ with (
+ _patch_discovery(),
+ _patch_config_flow_try_connect(),
+ patch(f"{MODULE}.async_setup", return_value=True),
+ patch(f"{MODULE}.async_setup_entry", return_value=True),
+ ):
result4 = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: IP_ADDRESS}
)
@@ -255,8 +263,9 @@ async def test_manual(hass: HomeAssistant) -> None:
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with _patch_discovery(no_device=True), _patch_config_flow_try_connect(
- no_device=True
+ with (
+ _patch_discovery(no_device=True),
+ _patch_config_flow_try_connect(no_device=True),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: IP_ADDRESS}
@@ -291,9 +300,12 @@ async def test_manual_dns_error(hass: HomeAssistant) -> None:
"""Mock teardown."""
# Cannot connect due to dns error
- with _patch_discovery(no_device=True), patch(
- "homeassistant.components.lifx.config_flow.LIFXConnection",
- MockLifxConnectonDnsError,
+ with (
+ _patch_discovery(no_device=True),
+ patch(
+ "homeassistant.components.lifx.config_flow.LIFXConnection",
+ MockLifxConnectonDnsError,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "does.not.resolve"}
@@ -314,9 +326,12 @@ async def test_manual_no_capabilities(hass: HomeAssistant) -> None:
assert result["step_id"] == "user"
assert not result["errors"]
- with _patch_discovery(no_device=True), _patch_config_flow_try_connect(), patch(
- f"{MODULE}.async_setup", return_value=True
- ), patch(f"{MODULE}.async_setup_entry", return_value=True):
+ with (
+ _patch_discovery(no_device=True),
+ _patch_config_flow_try_connect(),
+ patch(f"{MODULE}.async_setup", return_value=True),
+ patch(f"{MODULE}.async_setup_entry", return_value=True),
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: IP_ADDRESS}
)
@@ -365,8 +380,9 @@ async def test_discovered_by_discovery_and_dhcp(hass: HomeAssistant) -> None:
assert result3["type"] == FlowResultType.ABORT
assert result3["reason"] == "already_in_progress"
- with _patch_discovery(no_device=True), _patch_config_flow_try_connect(
- no_device=True
+ with (
+ _patch_discovery(no_device=True),
+ _patch_config_flow_try_connect(no_device=True),
):
result3 = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -421,11 +437,14 @@ async def test_discovered_by_dhcp_or_discovery(
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with _patch_discovery(), _patch_config_flow_try_connect(), patch(
- f"{MODULE}.async_setup", return_value=True
- ) as mock_async_setup, patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_async_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_config_flow_try_connect(),
+ patch(f"{MODULE}.async_setup", return_value=True) as mock_async_setup,
+ patch(
+ f"{MODULE}.async_setup_entry", return_value=True
+ ) as mock_async_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(result["flow_id"], {})
await hass.async_block_till_done()
@@ -469,8 +488,9 @@ async def test_discovered_by_dhcp_or_discovery_failed_to_get_device(
) -> None:
"""Test we abort if we cannot get the unique id when discovered from dhcp."""
- with _patch_discovery(no_device=True), _patch_config_flow_try_connect(
- no_device=True
+ with (
+ _patch_discovery(no_device=True),
+ _patch_config_flow_try_connect(no_device=True),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": source}, data=data
@@ -532,8 +552,9 @@ async def test_refuse_relays(hass: HomeAssistant) -> None:
assert result["step_id"] == "user"
assert not result["errors"]
- with _patch_discovery(device=_mocked_relay()), _patch_config_flow_try_connect(
- device=_mocked_relay()
+ with (
+ _patch_discovery(device=_mocked_relay()),
+ _patch_config_flow_try_connect(device=_mocked_relay()),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: IP_ADDRESS}
@@ -572,9 +593,11 @@ async def test_suggested_area(
bulb.group = None
bulb.get_group = MockLifxCommandGetGroup(bulb, lifx_group="My LIFX Group")
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
diff --git a/tests/components/lifx/test_diagnostics.py b/tests/components/lifx/test_diagnostics.py
index b0fa2bf4d6a..e3588dd3ed1 100644
--- a/tests/components/lifx/test_diagnostics.py
+++ b/tests/components/lifx/test_diagnostics.py
@@ -35,9 +35,11 @@ async def test_bulb_diagnostics(
)
config_entry.add_to_hass(hass)
bulb = _mocked_bulb()
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -82,9 +84,11 @@ async def test_clean_bulb_diagnostics(
)
config_entry.add_to_hass(hass)
bulb = _mocked_clean_bulb()
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -134,9 +138,11 @@ async def test_infrared_bulb_diagnostics(
)
config_entry.add_to_hass(hass)
bulb = _mocked_infrared_bulb()
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -193,9 +199,11 @@ async def test_legacy_multizone_bulb_diagnostics(
(46420, 65535, 65535, 3500),
(46420, 65535, 65535, 3500),
]
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -305,9 +313,11 @@ async def test_multizone_bulb_diagnostics(
(46420, 65535, 65535, 3500),
(46420, 65535, 65535, 3500),
]
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
diff --git a/tests/components/lifx/test_init.py b/tests/components/lifx/test_init.py
index 01003e6e7f1..3d0d127bf5c 100644
--- a/tests/components/lifx/test_init.py
+++ b/tests/components/lifx/test_init.py
@@ -50,10 +50,12 @@ async def test_configuring_lifx_causes_discovery(hass: HomeAssistant) -> None:
def cleanup(self):
"""Mock cleanup."""
- with _patch_config_flow_try_connect(), patch.object(
- discovery, "DEFAULT_TIMEOUT", 0
- ), patch(
- "homeassistant.components.lifx.discovery.LifxDiscovery", MockLifxDiscovery
+ with (
+ _patch_config_flow_try_connect(),
+ patch.object(discovery, "DEFAULT_TIMEOUT", 0),
+ patch(
+ "homeassistant.components.lifx.discovery.LifxDiscovery", MockLifxDiscovery
+ ),
):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -97,9 +99,11 @@ async def test_config_entry_retry(hass: HomeAssistant) -> None:
domain=DOMAIN, data={CONF_HOST: IP_ADDRESS}, unique_id=SERIAL
)
already_migrated_config_entry.add_to_hass(hass)
- with _patch_discovery(no_device=True), _patch_config_flow_try_connect(
- no_device=True
- ), _patch_device(no_device=True):
+ with (
+ _patch_discovery(no_device=True),
+ _patch_config_flow_try_connect(no_device=True),
+ _patch_device(no_device=True),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
assert already_migrated_config_entry.state == ConfigEntryState.SETUP_RETRY
@@ -145,9 +149,12 @@ async def test_dns_error_at_startup(hass: HomeAssistant) -> None:
"""Mock teardown."""
# Cannot connect due to dns error
- with _patch_discovery(device=bulb), patch(
- "homeassistant.components.lifx.LIFXConnection",
- MockLifxConnectonDnsError,
+ with (
+ _patch_discovery(device=bulb),
+ patch(
+ "homeassistant.components.lifx.LIFXConnection",
+ MockLifxConnectonDnsError,
+ ),
):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
diff --git a/tests/components/lifx/test_light.py b/tests/components/lifx/test_light.py
index 452112d2235..56630053cc0 100644
--- a/tests/components/lifx/test_light.py
+++ b/tests/components/lifx/test_light.py
@@ -92,9 +92,11 @@ async def test_light_unique_id(
)
already_migrated_config_entry.add_to_hass(hass)
bulb = _mocked_bulb()
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -118,9 +120,11 @@ async def test_light_unique_id_new_firmware(
)
already_migrated_config_entry.add_to_hass(hass)
bulb = _mocked_bulb_new_firmware()
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -141,9 +145,11 @@ async def test_light_strip(hass: HomeAssistant) -> None:
bulb = _mocked_light_strip()
bulb.power_level = 65535
bulb.color = [65535, 65535, 65535, 65535]
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -438,9 +444,11 @@ async def test_extended_multizone_messages(hass: HomeAssistant) -> None:
bulb.color = [65535, 65535, 65535, 3500]
bulb.color_zones = [(65535, 65535, 65535, 3500)] * 8
bulb.zones_count = 8
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -673,9 +681,11 @@ async def test_matrix_flame_morph_effects(hass: HomeAssistant) -> None:
bulb = _mocked_tile()
bulb.power_level = 0
bulb.color = [65535, 65535, 65535, 65535]
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -815,9 +825,11 @@ async def test_lightstrip_move_effect(hass: HomeAssistant) -> None:
bulb.product = 38
bulb.power_level = 0
bulb.color = [65535, 65535, 65535, 65535]
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -912,9 +924,11 @@ async def test_color_light_with_temp(
bulb = _mocked_bulb()
bulb.power_level = 65535
bulb.color = [65535, 65535, 65535, 65535]
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -1073,9 +1087,11 @@ async def test_white_bulb(hass: HomeAssistant) -> None:
bulb = _mocked_white_bulb()
bulb.power_level = 65535
bulb.color = [32000, None, 32000, 6000]
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -1254,9 +1270,11 @@ async def test_brightness_bulb(hass: HomeAssistant) -> None:
bulb = _mocked_brightness_bulb()
bulb.power_level = 65535
bulb.color = [32000, None, 32000, 6000]
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -1301,9 +1319,11 @@ async def test_transitions_brightness_only(hass: HomeAssistant) -> None:
bulb = _mocked_brightness_bulb()
bulb.power_level = 65535
bulb.color = [32000, None, 32000, 6000]
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -1368,9 +1388,11 @@ async def test_transitions_color_bulb(hass: HomeAssistant) -> None:
bulb = _mocked_bulb_new_firmware()
bulb.power_level = 65535
bulb.color = [32000, None, 32000, 6000]
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -1479,9 +1501,11 @@ async def test_lifx_set_state_color(hass: HomeAssistant) -> None:
bulb = _mocked_bulb_new_firmware()
bulb.power_level = 65535
bulb.color = [32000, None, 32000, 2700]
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -1557,9 +1581,11 @@ async def test_lifx_set_state_kelvin(hass: HomeAssistant) -> None:
bulb = _mocked_bulb_new_firmware()
bulb.power_level = 65535
bulb.color = [32000, None, 32000, 6000]
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -1613,9 +1639,11 @@ async def test_infrared_color_bulb(hass: HomeAssistant) -> None:
bulb = _mocked_bulb_new_firmware()
bulb.power_level = 65535
bulb.color = [32000, None, 32000, 6000]
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -1654,9 +1682,11 @@ async def test_color_bulb_is_actually_off(hass: HomeAssistant) -> None:
bulb = _mocked_bulb_new_firmware()
bulb.power_level = 65535
bulb.color = [32000, None, 32000, 6000]
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -1705,9 +1735,11 @@ async def test_clean_bulb(hass: HomeAssistant) -> None:
bulb = _mocked_clean_bulb()
bulb.power_level = 0
bulb.hev_cycle = {"duration": 7200, "remaining": 0, "last_power": False}
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -1735,9 +1767,11 @@ async def test_set_hev_cycle_state_fails_for_color_bulb(hass: HomeAssistant) ->
config_entry.add_to_hass(hass)
bulb = _mocked_bulb()
bulb.power_level = 0
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -1766,9 +1800,11 @@ async def test_light_strip_zones_not_populated_yet(hass: HomeAssistant) -> None:
bulb.color = [65535, 65535, 65535, 65535]
assert bulb.get_color_zones.calls == []
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
diff --git a/tests/components/lifx/test_migration.py b/tests/components/lifx/test_migration.py
index 3621eb165fa..0604ee1c8a7 100644
--- a/tests/components/lifx/test_migration.py
+++ b/tests/components/lifx/test_migration.py
@@ -130,10 +130,13 @@ async def test_discovery_is_more_frequent_during_migration(
def cleanup(self):
"""Mock cleanup."""
- with _patch_device(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), patch.object(discovery, "DEFAULT_TIMEOUT", 0), patch(
- "homeassistant.components.lifx.discovery.LifxDiscovery", MockLifxDiscovery
+ with (
+ _patch_device(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ patch.object(discovery, "DEFAULT_TIMEOUT", 0),
+ patch(
+ "homeassistant.components.lifx.discovery.LifxDiscovery", MockLifxDiscovery
+ ),
):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
diff --git a/tests/components/lifx/test_select.py b/tests/components/lifx/test_select.py
index c639dd441e7..a6338566ed4 100644
--- a/tests/components/lifx/test_select.py
+++ b/tests/components/lifx/test_select.py
@@ -43,9 +43,11 @@ async def test_theme_select(
bulb.product = 38
bulb.power_level = 0
bulb.color = [0, 0, 65535, 3500]
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -79,9 +81,11 @@ async def test_infrared_brightness(
)
config_entry.add_to_hass(hass)
bulb = _mocked_infrared_bulb()
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -109,9 +113,11 @@ async def test_set_infrared_brightness_25_percent(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
bulb = _mocked_infrared_bulb()
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -149,9 +155,11 @@ async def test_set_infrared_brightness_50_percent(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
bulb = _mocked_infrared_bulb()
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -189,9 +197,11 @@ async def test_set_infrared_brightness_100_percent(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
bulb = _mocked_infrared_bulb()
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -229,9 +239,11 @@ async def test_disable_infrared(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
bulb = _mocked_infrared_bulb()
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -269,9 +281,11 @@ async def test_invalid_infrared_brightness(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
bulb = _mocked_infrared_bulb()
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
diff --git a/tests/components/lifx/test_sensor.py b/tests/components/lifx/test_sensor.py
index 5a94963ca18..b7ff563bdbc 100644
--- a/tests/components/lifx/test_sensor.py
+++ b/tests/components/lifx/test_sensor.py
@@ -45,9 +45,11 @@ async def test_rssi_sensor(
)
config_entry.add_to_hass(hass)
bulb = _mocked_bulb()
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -63,9 +65,11 @@ async def test_rssi_sensor(
entry.entity_id, disabled_by=None
)
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await hass.config_entries.async_reload(config_entry.entry_id)
await hass.async_block_till_done()
@@ -97,9 +101,11 @@ async def test_rssi_sensor_old_firmware(
)
config_entry.add_to_hass(hass)
bulb = _mocked_bulb_old_firmware()
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}})
await hass.async_block_till_done()
@@ -115,9 +121,11 @@ async def test_rssi_sensor_old_firmware(
entry.entity_id, disabled_by=None
)
- with _patch_discovery(device=bulb), _patch_config_flow_try_connect(
- device=bulb
- ), _patch_device(device=bulb):
+ with (
+ _patch_discovery(device=bulb),
+ _patch_config_flow_try_connect(device=bulb),
+ _patch_device(device=bulb),
+ ):
await hass.config_entries.async_reload(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/linear_garage_door/test_config_flow.py b/tests/components/linear_garage_door/test_config_flow.py
index 5d1ed36ecb7..1851b61fc15 100644
--- a/tests/components/linear_garage_door/test_config_flow.py
+++ b/tests/components/linear_garage_door/test_config_flow.py
@@ -20,18 +20,23 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with patch(
- "homeassistant.components.linear_garage_door.config_flow.Linear.login",
- return_value=True,
- ), patch(
- "homeassistant.components.linear_garage_door.config_flow.Linear.get_sites",
- return_value=[{"id": "test-site-id", "name": "test-site-name"}],
- ), patch(
- "homeassistant.components.linear_garage_door.config_flow.Linear.close",
- return_value=None,
- ), patch(
- "uuid.uuid4",
- return_value="test-uuid",
+ with (
+ patch(
+ "homeassistant.components.linear_garage_door.config_flow.Linear.login",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.linear_garage_door.config_flow.Linear.get_sites",
+ return_value=[{"id": "test-site-id", "name": "test-site-name"}],
+ ),
+ patch(
+ "homeassistant.components.linear_garage_door.config_flow.Linear.close",
+ return_value=None,
+ ),
+ patch(
+ "uuid.uuid4",
+ return_value="test-uuid",
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -84,18 +89,23 @@ async def test_reauth(hass: HomeAssistant) -> None:
assert result1["type"] == FlowResultType.FORM
assert result1["step_id"] == "user"
- with patch(
- "homeassistant.components.linear_garage_door.config_flow.Linear.login",
- return_value=True,
- ), patch(
- "homeassistant.components.linear_garage_door.config_flow.Linear.get_sites",
- return_value=[{"id": "test-site-id", "name": "test-site-name"}],
- ), patch(
- "homeassistant.components.linear_garage_door.config_flow.Linear.close",
- return_value=None,
- ), patch(
- "uuid.uuid4",
- return_value="test-uuid",
+ with (
+ patch(
+ "homeassistant.components.linear_garage_door.config_flow.Linear.login",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.linear_garage_door.config_flow.Linear.get_sites",
+ return_value=[{"id": "test-site-id", "name": "test-site-name"}],
+ ),
+ patch(
+ "homeassistant.components.linear_garage_door.config_flow.Linear.close",
+ return_value=None,
+ ),
+ patch(
+ "uuid.uuid4",
+ return_value="test-uuid",
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result1["flow_id"],
@@ -125,12 +135,15 @@ async def test_form_invalid_login(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "homeassistant.components.linear_garage_door.config_flow.Linear.login",
- side_effect=InvalidLoginError,
- ), patch(
- "homeassistant.components.linear_garage_door.config_flow.Linear.close",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.components.linear_garage_door.config_flow.Linear.login",
+ side_effect=InvalidLoginError,
+ ),
+ patch(
+ "homeassistant.components.linear_garage_door.config_flow.Linear.close",
+ return_value=None,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/linear_garage_door/test_cover.py b/tests/components/linear_garage_door/test_cover.py
index 428411d39e0..e692d1867dc 100644
--- a/tests/components/linear_garage_door/test_cover.py
+++ b/tests/components/linear_garage_door/test_cover.py
@@ -56,15 +56,19 @@ async def test_open_cover(hass: HomeAssistant) -> None:
assert operate_device.call_count == 0
- with patch(
- "homeassistant.components.linear_garage_door.cover.Linear.login",
- return_value=True,
- ), patch(
- "homeassistant.components.linear_garage_door.cover.Linear.operate_device",
- return_value=None,
- ) as operate_device, patch(
- "homeassistant.components.linear_garage_door.cover.Linear.close",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.linear_garage_door.cover.Linear.login",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.linear_garage_door.cover.Linear.operate_device",
+ return_value=None,
+ ) as operate_device,
+ patch(
+ "homeassistant.components.linear_garage_door.cover.Linear.close",
+ return_value=True,
+ ),
):
await hass.services.async_call(
COVER_DOMAIN,
@@ -74,38 +78,51 @@ async def test_open_cover(hass: HomeAssistant) -> None:
)
assert operate_device.call_count == 1
- with patch(
- "homeassistant.components.linear_garage_door.cover.Linear.login",
- return_value=True,
- ), patch(
- "homeassistant.components.linear_garage_door.cover.Linear.get_devices",
- return_value=[
- {"id": "test1", "name": "Test Garage 1", "subdevices": ["GDO", "Light"]},
- {"id": "test2", "name": "Test Garage 2", "subdevices": ["GDO", "Light"]},
- ],
- ), patch(
- "homeassistant.components.linear_garage_door.cover.Linear.get_device_state",
- side_effect=lambda id: {
- "test1": {
- "GDO": {"Open_B": "true", "Open_P": "100"},
- "Light": {"On_B": "true", "On_P": "100"},
- },
- "test2": {
- "GDO": {"Open_B": "false", "Opening_P": "0"},
- "Light": {"On_B": "false", "On_P": "0"},
- },
- "test3": {
- "GDO": {"Open_B": "false", "Opening_P": "0"},
- "Light": {"On_B": "false", "On_P": "0"},
- },
- "test4": {
- "GDO": {"Open_B": "true", "Opening_P": "100"},
- "Light": {"On_B": "true", "On_P": "100"},
- },
- }[id],
- ), patch(
- "homeassistant.components.linear_garage_door.cover.Linear.close",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.linear_garage_door.cover.Linear.login",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.linear_garage_door.cover.Linear.get_devices",
+ return_value=[
+ {
+ "id": "test1",
+ "name": "Test Garage 1",
+ "subdevices": ["GDO", "Light"],
+ },
+ {
+ "id": "test2",
+ "name": "Test Garage 2",
+ "subdevices": ["GDO", "Light"],
+ },
+ ],
+ ),
+ patch(
+ "homeassistant.components.linear_garage_door.cover.Linear.get_device_state",
+ side_effect=lambda id: {
+ "test1": {
+ "GDO": {"Open_B": "true", "Open_P": "100"},
+ "Light": {"On_B": "true", "On_P": "100"},
+ },
+ "test2": {
+ "GDO": {"Open_B": "false", "Opening_P": "0"},
+ "Light": {"On_B": "false", "On_P": "0"},
+ },
+ "test3": {
+ "GDO": {"Open_B": "false", "Opening_P": "0"},
+ "Light": {"On_B": "false", "On_P": "0"},
+ },
+ "test4": {
+ "GDO": {"Open_B": "true", "Opening_P": "100"},
+ "Light": {"On_B": "true", "On_P": "100"},
+ },
+ }[id],
+ ),
+ patch(
+ "homeassistant.components.linear_garage_door.cover.Linear.close",
+ return_value=True,
+ ),
):
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=60))
await hass.async_block_till_done()
@@ -130,15 +147,19 @@ async def test_close_cover(hass: HomeAssistant) -> None:
assert operate_device.call_count == 0
- with patch(
- "homeassistant.components.linear_garage_door.cover.Linear.login",
- return_value=True,
- ), patch(
- "homeassistant.components.linear_garage_door.cover.Linear.operate_device",
- return_value=None,
- ) as operate_device, patch(
- "homeassistant.components.linear_garage_door.cover.Linear.close",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.linear_garage_door.cover.Linear.login",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.linear_garage_door.cover.Linear.operate_device",
+ return_value=None,
+ ) as operate_device,
+ patch(
+ "homeassistant.components.linear_garage_door.cover.Linear.close",
+ return_value=True,
+ ),
):
await hass.services.async_call(
COVER_DOMAIN,
@@ -148,38 +169,51 @@ async def test_close_cover(hass: HomeAssistant) -> None:
)
assert operate_device.call_count == 1
- with patch(
- "homeassistant.components.linear_garage_door.cover.Linear.login",
- return_value=True,
- ), patch(
- "homeassistant.components.linear_garage_door.cover.Linear.get_devices",
- return_value=[
- {"id": "test1", "name": "Test Garage 1", "subdevices": ["GDO", "Light"]},
- {"id": "test2", "name": "Test Garage 2", "subdevices": ["GDO", "Light"]},
- ],
- ), patch(
- "homeassistant.components.linear_garage_door.cover.Linear.get_device_state",
- side_effect=lambda id: {
- "test1": {
- "GDO": {"Open_B": "true", "Opening_P": "100"},
- "Light": {"On_B": "true", "On_P": "100"},
- },
- "test2": {
- "GDO": {"Open_B": "false", "Open_P": "0"},
- "Light": {"On_B": "false", "On_P": "0"},
- },
- "test3": {
- "GDO": {"Open_B": "false", "Opening_P": "0"},
- "Light": {"On_B": "false", "On_P": "0"},
- },
- "test4": {
- "GDO": {"Open_B": "true", "Opening_P": "100"},
- "Light": {"On_B": "true", "On_P": "100"},
- },
- }[id],
- ), patch(
- "homeassistant.components.linear_garage_door.cover.Linear.close",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.linear_garage_door.cover.Linear.login",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.linear_garage_door.cover.Linear.get_devices",
+ return_value=[
+ {
+ "id": "test1",
+ "name": "Test Garage 1",
+ "subdevices": ["GDO", "Light"],
+ },
+ {
+ "id": "test2",
+ "name": "Test Garage 2",
+ "subdevices": ["GDO", "Light"],
+ },
+ ],
+ ),
+ patch(
+ "homeassistant.components.linear_garage_door.cover.Linear.get_device_state",
+ side_effect=lambda id: {
+ "test1": {
+ "GDO": {"Open_B": "true", "Opening_P": "100"},
+ "Light": {"On_B": "true", "On_P": "100"},
+ },
+ "test2": {
+ "GDO": {"Open_B": "false", "Open_P": "0"},
+ "Light": {"On_B": "false", "On_P": "0"},
+ },
+ "test3": {
+ "GDO": {"Open_B": "false", "Opening_P": "0"},
+ "Light": {"On_B": "false", "On_P": "0"},
+ },
+ "test4": {
+ "GDO": {"Open_B": "true", "Opening_P": "100"},
+ "Light": {"On_B": "true", "On_P": "100"},
+ },
+ }[id],
+ ),
+ patch(
+ "homeassistant.components.linear_garage_door.cover.Linear.close",
+ return_value=True,
+ ),
):
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=60))
await hass.async_block_till_done()
diff --git a/tests/components/linear_garage_door/test_init.py b/tests/components/linear_garage_door/test_init.py
index e8d76770050..32ebda7e125 100644
--- a/tests/components/linear_garage_door/test_init.py
+++ b/tests/components/linear_garage_door/test_init.py
@@ -22,23 +22,28 @@ async def test_unload_entry(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.linear_garage_door.coordinator.Linear.login",
- return_value=True,
- ), patch(
- "homeassistant.components.linear_garage_door.coordinator.Linear.get_devices",
- return_value=[
- {"id": "test", "name": "Test Garage", "subdevices": ["GDO", "Light"]}
- ],
- ), patch(
- "homeassistant.components.linear_garage_door.coordinator.Linear.get_device_state",
- return_value={
- "GDO": {"Open_B": "true", "Open_P": "100"},
- "Light": {"On_B": "true", "On_P": "10"},
- },
- ), patch(
- "homeassistant.components.linear_garage_door.coordinator.Linear.close",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.linear_garage_door.coordinator.Linear.login",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.linear_garage_door.coordinator.Linear.get_devices",
+ return_value=[
+ {"id": "test", "name": "Test Garage", "subdevices": ["GDO", "Light"]}
+ ],
+ ),
+ patch(
+ "homeassistant.components.linear_garage_door.coordinator.Linear.get_device_state",
+ return_value={
+ "GDO": {"Open_B": "true", "Open_P": "100"},
+ "Light": {"On_B": "true", "On_P": "10"},
+ },
+ ),
+ patch(
+ "homeassistant.components.linear_garage_door.coordinator.Linear.close",
+ return_value=True,
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/linear_garage_door/util.py b/tests/components/linear_garage_door/util.py
index d8348b9bb64..1a849ae2348 100644
--- a/tests/components/linear_garage_door/util.py
+++ b/tests/components/linear_garage_door/util.py
@@ -21,40 +21,61 @@ async def async_init_integration(hass: HomeAssistant) -> MockConfigEntry:
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.linear_garage_door.coordinator.Linear.login",
- return_value=True,
- ), patch(
- "homeassistant.components.linear_garage_door.coordinator.Linear.get_devices",
- return_value=[
- {"id": "test1", "name": "Test Garage 1", "subdevices": ["GDO", "Light"]},
- {"id": "test2", "name": "Test Garage 2", "subdevices": ["GDO", "Light"]},
- {"id": "test3", "name": "Test Garage 3", "subdevices": ["GDO", "Light"]},
- {"id": "test4", "name": "Test Garage 4", "subdevices": ["GDO", "Light"]},
- ],
- ), patch(
- "homeassistant.components.linear_garage_door.coordinator.Linear.get_device_state",
- side_effect=lambda id: {
- "test1": {
- "GDO": {"Open_B": "true", "Open_P": "100"},
- "Light": {"On_B": "true", "On_P": "100"},
- },
- "test2": {
- "GDO": {"Open_B": "false", "Open_P": "0"},
- "Light": {"On_B": "false", "On_P": "0"},
- },
- "test3": {
- "GDO": {"Open_B": "false", "Opening_P": "0"},
- "Light": {"On_B": "false", "On_P": "0"},
- },
- "test4": {
- "GDO": {"Open_B": "true", "Opening_P": "100"},
- "Light": {"On_B": "true", "On_P": "100"},
- },
- }[id],
- ), patch(
- "homeassistant.components.linear_garage_door.coordinator.Linear.close",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.linear_garage_door.coordinator.Linear.login",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.linear_garage_door.coordinator.Linear.get_devices",
+ return_value=[
+ {
+ "id": "test1",
+ "name": "Test Garage 1",
+ "subdevices": ["GDO", "Light"],
+ },
+ {
+ "id": "test2",
+ "name": "Test Garage 2",
+ "subdevices": ["GDO", "Light"],
+ },
+ {
+ "id": "test3",
+ "name": "Test Garage 3",
+ "subdevices": ["GDO", "Light"],
+ },
+ {
+ "id": "test4",
+ "name": "Test Garage 4",
+ "subdevices": ["GDO", "Light"],
+ },
+ ],
+ ),
+ patch(
+ "homeassistant.components.linear_garage_door.coordinator.Linear.get_device_state",
+ side_effect=lambda id: {
+ "test1": {
+ "GDO": {"Open_B": "true", "Open_P": "100"},
+ "Light": {"On_B": "true", "On_P": "100"},
+ },
+ "test2": {
+ "GDO": {"Open_B": "false", "Open_P": "0"},
+ "Light": {"On_B": "false", "On_P": "0"},
+ },
+ "test3": {
+ "GDO": {"Open_B": "false", "Opening_P": "0"},
+ "Light": {"On_B": "false", "On_P": "0"},
+ },
+ "test4": {
+ "GDO": {"Open_B": "true", "Opening_P": "100"},
+ "Light": {"On_B": "true", "On_P": "100"},
+ },
+ }[id],
+ ),
+ patch(
+ "homeassistant.components.linear_garage_door.coordinator.Linear.close",
+ return_value=True,
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/litterrobot/conftest.py b/tests/components/litterrobot/conftest.py
index d8d6ecd171d..181e4fc1a90 100644
--- a/tests/components/litterrobot/conftest.py
+++ b/tests/components/litterrobot/conftest.py
@@ -124,11 +124,15 @@ async def setup_integration(
)
entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.litterrobot.hub.Account", return_value=mock_account
- ), patch(
- "homeassistant.components.litterrobot.PLATFORMS_BY_TYPE",
- {Robot: (platform_domain,)} if platform_domain else {},
+ with (
+ patch(
+ "homeassistant.components.litterrobot.hub.Account",
+ return_value=mock_account,
+ ),
+ patch(
+ "homeassistant.components.litterrobot.PLATFORMS_BY_TYPE",
+ {Robot: (platform_domain,)} if platform_domain else {},
+ ),
):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/litterrobot/test_config_flow.py b/tests/components/litterrobot/test_config_flow.py
index e2c5290a946..d516a3f14a2 100644
--- a/tests/components/litterrobot/test_config_flow.py
+++ b/tests/components/litterrobot/test_config_flow.py
@@ -25,13 +25,16 @@ async def test_form(hass: HomeAssistant, mock_account) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.litterrobot.config_flow.Account.connect",
- return_value=mock_account,
- ), patch(
- "homeassistant.components.litterrobot.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.litterrobot.config_flow.Account.connect",
+ return_value=mock_account,
+ ),
+ patch(
+ "homeassistant.components.litterrobot.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], CONFIG[DOMAIN]
)
@@ -134,13 +137,16 @@ async def test_step_reauth(hass: HomeAssistant, mock_account: Account) -> None:
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
- with patch(
- "homeassistant.components.litterrobot.config_flow.Account.connect",
- return_value=mock_account,
- ), patch(
- "homeassistant.components.litterrobot.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.litterrobot.config_flow.Account.connect",
+ return_value=mock_account,
+ ),
+ patch(
+ "homeassistant.components.litterrobot.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_PASSWORD: CONFIG[litterrobot.DOMAIN][CONF_PASSWORD]},
@@ -183,13 +189,16 @@ async def test_step_reauth_failed(hass: HomeAssistant, mock_account: Account) ->
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {"base": "invalid_auth"}
- with patch(
- "homeassistant.components.litterrobot.config_flow.Account.connect",
- return_value=mock_account,
- ), patch(
- "homeassistant.components.litterrobot.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.litterrobot.config_flow.Account.connect",
+ return_value=mock_account,
+ ),
+ patch(
+ "homeassistant.components.litterrobot.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_PASSWORD: CONFIG[litterrobot.DOMAIN][CONF_PASSWORD]},
diff --git a/tests/components/local_file/test_camera.py b/tests/components/local_file/test_camera.py
index 38d6bdd84cc..4455d47469c 100644
--- a/tests/components/local_file/test_camera.py
+++ b/tests/components/local_file/test_camera.py
@@ -16,11 +16,13 @@ async def test_loading_file(
hass: HomeAssistant, hass_client: ClientSessionGenerator
) -> None:
"""Test that it loads image from disk."""
- with mock.patch("os.path.isfile", mock.Mock(return_value=True)), mock.patch(
- "os.access", mock.Mock(return_value=True)
- ), mock.patch(
- "homeassistant.components.local_file.camera.mimetypes.guess_type",
- mock.Mock(return_value=(None, None)),
+ with (
+ mock.patch("os.path.isfile", mock.Mock(return_value=True)),
+ mock.patch("os.access", mock.Mock(return_value=True)),
+ mock.patch(
+ "homeassistant.components.local_file.camera.mimetypes.guess_type",
+ mock.Mock(return_value=(None, None)),
+ ),
):
await async_setup_component(
hass,
@@ -52,8 +54,9 @@ async def test_file_not_readable(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test a warning is shown setup when file is not readable."""
- with mock.patch("os.path.isfile", mock.Mock(return_value=True)), mock.patch(
- "os.access", mock.Mock(return_value=False)
+ with (
+ mock.patch("os.path.isfile", mock.Mock(return_value=True)),
+ mock.patch("os.access", mock.Mock(return_value=False)),
):
await async_setup_component(
hass,
@@ -142,11 +145,13 @@ async def test_camera_content_type(
async def test_update_file_path(hass: HomeAssistant) -> None:
"""Test update_file_path service."""
# Setup platform
- with mock.patch("os.path.isfile", mock.Mock(return_value=True)), mock.patch(
- "os.access", mock.Mock(return_value=True)
- ), mock.patch(
- "homeassistant.components.local_file.camera.mimetypes.guess_type",
- mock.Mock(return_value=(None, None)),
+ with (
+ mock.patch("os.path.isfile", mock.Mock(return_value=True)),
+ mock.patch("os.access", mock.Mock(return_value=True)),
+ mock.patch(
+ "homeassistant.components.local_file.camera.mimetypes.guess_type",
+ mock.Mock(return_value=(None, None)),
+ ),
):
camera_1 = {"platform": "local_file", "file_path": "mock/path.jpg"}
camera_2 = {
diff --git a/tests/components/logbook/test_websocket_api.py b/tests/components/logbook/test_websocket_api.py
index f3689c379c5..1be0e5bd9af 100644
--- a/tests/components/logbook/test_websocket_api.py
+++ b/tests/components/logbook/test_websocket_api.py
@@ -2400,8 +2400,9 @@ async def test_stream_consumer_stop_processing(
after_ws_created_listeners = hass.bus.async_listeners()
- with patch.object(websocket_api, "MAX_PENDING_LOGBOOK_EVENTS", 5), patch.object(
- websocket_api, "_async_events_consumer"
+ with (
+ patch.object(websocket_api, "MAX_PENDING_LOGBOOK_EVENTS", 5),
+ patch.object(websocket_api, "_async_events_consumer"),
):
await websocket_client.send_json(
{
diff --git a/tests/components/logger/test_websocket_api.py b/tests/components/logger/test_websocket_api.py
index 15252ad2661..c2fcc7f208e 100644
--- a/tests/components/logger/test_websocket_api.py
+++ b/tests/components/logger/test_websocket_api.py
@@ -102,12 +102,15 @@ async def test_custom_integration_log_level(
},
)
- with patch(
- "homeassistant.components.logger.helpers.async_get_integration",
- return_value=integration,
- ), patch(
- "homeassistant.components.logger.websocket_api.async_get_integration",
- return_value=integration,
+ with (
+ patch(
+ "homeassistant.components.logger.helpers.async_get_integration",
+ return_value=integration,
+ ),
+ patch(
+ "homeassistant.components.logger.websocket_api.async_get_integration",
+ return_value=integration,
+ ),
):
await websocket_client.send_json(
{
diff --git a/tests/components/lookin/test_config_flow.py b/tests/components/lookin/test_config_flow.py
index d489cee8101..18cbe33db3a 100644
--- a/tests/components/lookin/test_config_flow.py
+++ b/tests/components/lookin/test_config_flow.py
@@ -35,9 +35,10 @@ async def test_manual_setup(hass: HomeAssistant) -> None:
assert result["step_id"] == "user"
assert not result["errors"]
- with _patch_get_info(), patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ _patch_get_info(),
+ patch(f"{MODULE}.async_setup_entry", return_value=True) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: IP_ADDRESS}
)
@@ -124,9 +125,12 @@ async def test_discovered_zeroconf(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with _patch_get_info(), patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_async_setup_entry:
+ with (
+ _patch_get_info(),
+ patch(
+ f"{MODULE}.async_setup_entry", return_value=True
+ ) as mock_async_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(result["flow_id"], {})
await hass.async_block_till_done()
@@ -139,9 +143,12 @@ async def test_discovered_zeroconf(hass: HomeAssistant) -> None:
zc_data_new_ip = dataclasses.replace(ZEROCONF_DATA)
zc_data_new_ip.ip_address = ip_address("127.0.0.2")
- with _patch_get_info(), patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_async_setup_entry:
+ with (
+ _patch_get_info(),
+ patch(
+ f"{MODULE}.async_setup_entry", return_value=True
+ ) as mock_async_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_ZEROCONF},
diff --git a/tests/components/loqed/conftest.py b/tests/components/loqed/conftest.py
index 616c0cb0552..b4265873457 100644
--- a/tests/components/loqed/conftest.py
+++ b/tests/components/loqed/conftest.py
@@ -88,8 +88,11 @@ async def integration_fixture(
lock_status = json.loads(load_fixture("loqed/status_ok.json"))
- with patch("loqedAPI.loqed.LoqedAPI.async_get_lock", return_value=lock), patch(
- "loqedAPI.loqed.LoqedAPI.async_get_lock_details", return_value=lock_status
+ with (
+ patch("loqedAPI.loqed.LoqedAPI.async_get_lock", return_value=lock),
+ patch(
+ "loqedAPI.loqed.LoqedAPI.async_get_lock_details", return_value=lock_status
+ ),
):
await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
diff --git a/tests/components/loqed/test_config_flow.py b/tests/components/loqed/test_config_flow.py
index 87c531b67dc..ed18f0ae40e 100644
--- a/tests/components/loqed/test_config_flow.py
+++ b/tests/components/loqed/test_config_flow.py
@@ -49,17 +49,23 @@ async def test_create_entry_zeroconf(hass: HomeAssistant) -> None:
webhook_id = "Webhook_ID"
all_locks_response = json.loads(load_fixture("loqed/get_all_locks.json"))
- with patch(
- "loqedAPI.cloud_loqed.LoqedCloudAPI.async_get_locks",
- return_value=all_locks_response,
- ), patch(
- "loqedAPI.loqed.LoqedAPI.async_get_lock",
- return_value=mock_lock,
- ), patch(
- "homeassistant.components.loqed.async_setup_entry",
- return_value=True,
- ), patch(
- "homeassistant.components.webhook.async_generate_id", return_value=webhook_id
+ with (
+ patch(
+ "loqedAPI.cloud_loqed.LoqedCloudAPI.async_get_locks",
+ return_value=all_locks_response,
+ ),
+ patch(
+ "loqedAPI.loqed.LoqedAPI.async_get_lock",
+ return_value=mock_lock,
+ ),
+ patch(
+ "homeassistant.components.loqed.async_setup_entry",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.webhook.async_generate_id",
+ return_value=webhook_id,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -104,19 +110,26 @@ async def test_create_entry_user(
all_locks_response = json.loads(load_fixture("loqed/get_all_locks.json"))
found_lock = all_locks_response["data"][0]
- with patch(
- "loqedAPI.cloud_loqed.LoqedCloudAPI.async_get_locks",
- return_value=all_locks_response,
- ), patch(
- "loqedAPI.loqed.LoqedAPI.async_get_lock",
- return_value=mock_lock,
- ), patch(
- "homeassistant.components.loqed.async_setup_entry",
- return_value=True,
- ), patch(
- "homeassistant.components.webhook.async_generate_id", return_value=webhook_id
- ), patch(
- "loqedAPI.loqed.LoqedAPI.async_get_lock_details", return_value=lock_result
+ with (
+ patch(
+ "loqedAPI.cloud_loqed.LoqedCloudAPI.async_get_locks",
+ return_value=all_locks_response,
+ ),
+ patch(
+ "loqedAPI.loqed.LoqedAPI.async_get_lock",
+ return_value=mock_lock,
+ ),
+ patch(
+ "homeassistant.components.loqed.async_setup_entry",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.webhook.async_generate_id",
+ return_value=webhook_id,
+ ),
+ patch(
+ "loqedAPI.loqed.LoqedAPI.async_get_lock_details", return_value=lock_result
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -208,10 +221,15 @@ async def test_cannot_connect_when_lock_not_reachable(
all_locks_response = json.loads(load_fixture("loqed/get_all_locks.json"))
- with patch(
- "loqedAPI.cloud_loqed.LoqedCloudAPI.async_get_locks",
- return_value=all_locks_response,
- ), patch("loqedAPI.loqed.LoqedAPI.async_get_lock", side_effect=aiohttp.ClientError):
+ with (
+ patch(
+ "loqedAPI.cloud_loqed.LoqedCloudAPI.async_get_locks",
+ return_value=all_locks_response,
+ ),
+ patch(
+ "loqedAPI.loqed.LoqedAPI.async_get_lock", side_effect=aiohttp.ClientError
+ ),
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_API_TOKEN: "eyadiuyfasiuasf", CONF_NAME: "MyLock"},
diff --git a/tests/components/loqed/test_init.py b/tests/components/loqed/test_init.py
index 47f53a1ad20..3d52feead79 100644
--- a/tests/components/loqed/test_init.py
+++ b/tests/components/loqed/test_init.py
@@ -50,8 +50,11 @@ async def test_setup_webhook_in_bridge(
webhooks_fixture = json.loads(load_fixture("loqed/get_all_webhooks.json"))
lock.getWebhooks = AsyncMock(side_effect=[[], webhooks_fixture])
- with patch("loqedAPI.loqed.LoqedAPI.async_get_lock", return_value=lock), patch(
- "loqedAPI.loqed.LoqedAPI.async_get_lock_details", return_value=lock_status
+ with (
+ patch("loqedAPI.loqed.LoqedAPI.async_get_lock", return_value=lock),
+ patch(
+ "loqedAPI.loqed.LoqedAPI.async_get_lock_details", return_value=lock_status
+ ),
):
await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
@@ -86,13 +89,19 @@ async def test_setup_cloudhook_in_bridge(
webhooks_fixture = json.loads(load_fixture("loqed/get_all_webhooks.json"))
lock.getWebhooks = AsyncMock(side_effect=[[], webhooks_fixture])
- with patch("loqedAPI.loqed.LoqedAPI.async_get_lock", return_value=lock), patch(
- "loqedAPI.loqed.LoqedAPI.async_get_lock_details", return_value=lock_status
- ), patch(
- "homeassistant.components.cloud.async_active_subscription", return_value=True
- ), patch(
- "homeassistant.components.cloud.async_create_cloudhook",
- return_value=webhooks_fixture[0]["url"],
+ with (
+ patch("loqedAPI.loqed.LoqedAPI.async_get_lock", return_value=lock),
+ patch(
+ "loqedAPI.loqed.LoqedAPI.async_get_lock_details", return_value=lock_status
+ ),
+ patch(
+ "homeassistant.components.cloud.async_active_subscription",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.cloud.async_create_cloudhook",
+ return_value=webhooks_fixture[0]["url"],
+ ),
):
await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
@@ -113,13 +122,19 @@ async def test_setup_cloudhook_from_entry_in_bridge(
lock.getWebhooks = AsyncMock(side_effect=[[], webhooks_fixture])
- with patch("loqedAPI.loqed.LoqedAPI.async_get_lock", return_value=lock), patch(
- "loqedAPI.loqed.LoqedAPI.async_get_lock_details", return_value=lock_status
- ), patch(
- "homeassistant.components.cloud.async_active_subscription", return_value=True
- ), patch(
- "homeassistant.components.cloud.async_create_cloudhook",
- return_value=webhooks_fixture[0]["url"],
+ with (
+ patch("loqedAPI.loqed.LoqedAPI.async_get_lock", return_value=lock),
+ patch(
+ "loqedAPI.loqed.LoqedAPI.async_get_lock_details", return_value=lock_status
+ ),
+ patch(
+ "homeassistant.components.cloud.async_active_subscription",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.cloud.async_create_cloudhook",
+ return_value=webhooks_fixture[0]["url"],
+ ),
):
await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
diff --git a/tests/components/lovelace/test_cast.py b/tests/components/lovelace/test_cast.py
index 5fdce538d4c..f0a193ec705 100644
--- a/tests/components/lovelace/test_cast.py
+++ b/tests/components/lovelace/test_cast.py
@@ -58,20 +58,23 @@ async def mock_yaml_dashboard(hass):
},
)
- with patch(
- "homeassistant.components.lovelace.dashboard.load_yaml_dict",
- return_value={
- "title": "YAML Title",
- "views": [
- {
- "title": "Hello",
- },
- {"path": "second-view"},
- ],
- },
- ), patch(
- "homeassistant.components.lovelace.dashboard.os.path.getmtime",
- return_value=time() + 10,
+ with (
+ patch(
+ "homeassistant.components.lovelace.dashboard.load_yaml_dict",
+ return_value={
+ "title": "YAML Title",
+ "views": [
+ {
+ "title": "Hello",
+ },
+ {"path": "second-view"},
+ ],
+ },
+ ),
+ patch(
+ "homeassistant.components.lovelace.dashboard.os.path.getmtime",
+ return_value=time() + 10,
+ ),
):
yield
diff --git a/tests/components/luftdaten/conftest.py b/tests/components/luftdaten/conftest.py
index e6fb0d37288..e083e8c97c7 100644
--- a/tests/components/luftdaten/conftest.py
+++ b/tests/components/luftdaten/conftest.py
@@ -37,10 +37,14 @@ def mock_setup_entry() -> Generator[None, None, None]:
@pytest.fixture
def mock_luftdaten() -> Generator[None, MagicMock, None]:
"""Return a mocked Luftdaten client."""
- with patch(
- "homeassistant.components.luftdaten.Luftdaten", autospec=True
- ) as luftdaten_mock, patch(
- "homeassistant.components.luftdaten.config_flow.Luftdaten", new=luftdaten_mock
+ with (
+ patch(
+ "homeassistant.components.luftdaten.Luftdaten", autospec=True
+ ) as luftdaten_mock,
+ patch(
+ "homeassistant.components.luftdaten.config_flow.Luftdaten",
+ new=luftdaten_mock,
+ ),
):
luftdaten = luftdaten_mock.return_value
luftdaten.validate_sensor.return_value = True
diff --git a/tests/components/lupusec/test_config_flow.py b/tests/components/lupusec/test_config_flow.py
index 89adedb86cb..2ca313139dc 100644
--- a/tests/components/lupusec/test_config_flow.py
+++ b/tests/components/lupusec/test_config_flow.py
@@ -48,12 +48,15 @@ async def test_form_valid_input(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.lupusec.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.lupusec.config_flow.lupupy.Lupusec",
- ) as mock_initialize_lupusec:
+ with (
+ patch(
+ "homeassistant.components.lupusec.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.lupusec.config_flow.lupupy.Lupusec",
+ ) as mock_initialize_lupusec,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
MOCK_DATA_STEP,
@@ -101,12 +104,15 @@ async def test_flow_user_init_data_error_and_recover(
assert len(mock_initialize_lupusec.mock_calls) == 1
# Recover
- with patch(
- "homeassistant.components.lupusec.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.lupusec.config_flow.lupupy.Lupusec",
- ) as mock_initialize_lupusec:
+ with (
+ patch(
+ "homeassistant.components.lupusec.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.lupusec.config_flow.lupupy.Lupusec",
+ ) as mock_initialize_lupusec,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"],
MOCK_DATA_STEP,
@@ -160,12 +166,15 @@ async def test_flow_source_import(
hass: HomeAssistant, mock_import_step, mock_title
) -> None:
"""Test configuration import from YAML."""
- with patch(
- "homeassistant.components.lupusec.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.lupusec.config_flow.lupupy.Lupusec",
- ) as mock_initialize_lupusec:
+ with (
+ patch(
+ "homeassistant.components.lupusec.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.lupusec.config_flow.lupupy.Lupusec",
+ ) as mock_initialize_lupusec,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
diff --git a/tests/components/lutron/test_config_flow.py b/tests/components/lutron/test_config_flow.py
index 0d641e4c2e4..db3faa7f911 100644
--- a/tests/components/lutron/test_config_flow.py
+++ b/tests/components/lutron/test_config_flow.py
@@ -30,8 +30,9 @@ async def test_full_flow(hass: HomeAssistant, mock_setup_entry: AsyncMock) -> No
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
- with patch("homeassistant.components.lutron.config_flow.Lutron.load_xml_db"), patch(
- "homeassistant.components.lutron.config_flow.Lutron.guid", "12345678901"
+ with (
+ patch("homeassistant.components.lutron.config_flow.Lutron.load_xml_db"),
+ patch("homeassistant.components.lutron.config_flow.Lutron.guid", "12345678901"),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -77,8 +78,9 @@ async def test_flow_failure(
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {"base": text_error}
- with patch("homeassistant.components.lutron.config_flow.Lutron.load_xml_db"), patch(
- "homeassistant.components.lutron.config_flow.Lutron.guid", "12345678901"
+ with (
+ patch("homeassistant.components.lutron.config_flow.Lutron.load_xml_db"),
+ patch("homeassistant.components.lutron.config_flow.Lutron.guid", "12345678901"),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -102,8 +104,9 @@ async def test_flow_incorrect_guid(
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
- with patch("homeassistant.components.lutron.config_flow.Lutron.load_xml_db"), patch(
- "homeassistant.components.lutron.config_flow.Lutron.guid", "12345"
+ with (
+ patch("homeassistant.components.lutron.config_flow.Lutron.load_xml_db"),
+ patch("homeassistant.components.lutron.config_flow.Lutron.guid", "12345"),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -113,8 +116,9 @@ async def test_flow_incorrect_guid(
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {"base": "cannot_connect"}
- with patch("homeassistant.components.lutron.config_flow.Lutron.load_xml_db"), patch(
- "homeassistant.components.lutron.config_flow.Lutron.guid", "12345678901"
+ with (
+ patch("homeassistant.components.lutron.config_flow.Lutron.load_xml_db"),
+ patch("homeassistant.components.lutron.config_flow.Lutron.guid", "12345678901"),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -149,8 +153,9 @@ async def test_import(
mock_setup_entry: AsyncMock,
) -> None:
"""Test import flow."""
- with patch("homeassistant.components.lutron.config_flow.Lutron.load_xml_db"), patch(
- "homeassistant.components.lutron.config_flow.Lutron.guid", "12345678901"
+ with (
+ patch("homeassistant.components.lutron.config_flow.Lutron.load_xml_db"),
+ patch("homeassistant.components.lutron.config_flow.Lutron.guid", "12345678901"),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data=MOCK_DATA_IMPORT
@@ -189,8 +194,9 @@ async def test_import_flow_failure(
async def test_import_flow_guid_failure(hass: HomeAssistant) -> None:
"""Test handling errors while importing."""
- with patch("homeassistant.components.lutron.config_flow.Lutron.load_xml_db"), patch(
- "homeassistant.components.lutron.config_flow.Lutron.guid", "123"
+ with (
+ patch("homeassistant.components.lutron.config_flow.Lutron.load_xml_db"),
+ patch("homeassistant.components.lutron.config_flow.Lutron.guid", "123"),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data=MOCK_DATA_IMPORT
diff --git a/tests/components/lutron_caseta/test_config_flow.py b/tests/components/lutron_caseta/test_config_flow.py
index 5531796c20a..15a4fca7d33 100644
--- a/tests/components/lutron_caseta/test_config_flow.py
+++ b/tests/components/lutron_caseta/test_config_flow.py
@@ -54,15 +54,17 @@ async def test_bridge_import_flow(hass: HomeAssistant) -> None:
CONF_CA_CERTS: "",
}
- with patch(
- "homeassistant.components.lutron_caseta.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.lutron_caseta.async_setup", return_value=True
- ), patch.object(
- Smartbridge,
- "create_tls",
- ) as create_tls:
+ with (
+ patch(
+ "homeassistant.components.lutron_caseta.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch("homeassistant.components.lutron_caseta.async_setup", return_value=True),
+ patch.object(
+ Smartbridge,
+ "create_tls",
+ ) as create_tls,
+ ):
create_tls.return_value = MockBridge(can_connect=True)
result = await hass.config_entries.flow.async_init(
@@ -218,15 +220,19 @@ async def test_form_user(hass: HomeAssistant, tmp_path: Path) -> None:
assert result2["type"] == "form"
assert result2["step_id"] == "link"
- with patch(
- "homeassistant.components.lutron_caseta.config_flow.async_pair",
- return_value=MOCK_ASYNC_PAIR_SUCCESS,
- ), patch(
- "homeassistant.components.lutron_caseta.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.lutron_caseta.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.lutron_caseta.config_flow.async_pair",
+ return_value=MOCK_ASYNC_PAIR_SUCCESS,
+ ),
+ patch(
+ "homeassistant.components.lutron_caseta.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.lutron_caseta.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{},
@@ -268,15 +274,19 @@ async def test_form_user_pairing_fails(hass: HomeAssistant, tmp_path: Path) -> N
assert result2["type"] == "form"
assert result2["step_id"] == "link"
- with patch(
- "homeassistant.components.lutron_caseta.config_flow.async_pair",
- side_effect=TimeoutError,
- ), patch(
- "homeassistant.components.lutron_caseta.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.lutron_caseta.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.lutron_caseta.config_flow.async_pair",
+ side_effect=TimeoutError,
+ ),
+ patch(
+ "homeassistant.components.lutron_caseta.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.lutron_caseta.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{},
@@ -314,15 +324,19 @@ async def test_form_user_reuses_existing_assets_when_pairing_again(
assert result2["type"] == "form"
assert result2["step_id"] == "link"
- with patch(
- "homeassistant.components.lutron_caseta.config_flow.async_pair",
- return_value=MOCK_ASYNC_PAIR_SUCCESS,
- ), patch(
- "homeassistant.components.lutron_caseta.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.lutron_caseta.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.lutron_caseta.config_flow.async_pair",
+ return_value=MOCK_ASYNC_PAIR_SUCCESS,
+ ),
+ patch(
+ "homeassistant.components.lutron_caseta.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.lutron_caseta.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{},
@@ -368,11 +382,12 @@ async def test_form_user_reuses_existing_assets_when_pairing_again(
assert result2["type"] == "form"
assert result2["step_id"] == "link"
- with patch(
- "homeassistant.components.lutron_caseta.async_setup", return_value=True
- ), patch(
- "homeassistant.components.lutron_caseta.async_setup_entry",
- return_value=True,
+ with (
+ patch("homeassistant.components.lutron_caseta.async_setup", return_value=True),
+ patch(
+ "homeassistant.components.lutron_caseta.async_setup_entry",
+ return_value=True,
+ ),
):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
@@ -499,15 +514,19 @@ async def test_zeroconf(hass: HomeAssistant, source, tmp_path: Path) -> None:
assert result["type"] == "form"
assert result["step_id"] == "link"
- with patch(
- "homeassistant.components.lutron_caseta.config_flow.async_pair",
- return_value=MOCK_ASYNC_PAIR_SUCCESS,
- ), patch(
- "homeassistant.components.lutron_caseta.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.lutron_caseta.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.lutron_caseta.config_flow.async_pair",
+ return_value=MOCK_ASYNC_PAIR_SUCCESS,
+ ),
+ patch(
+ "homeassistant.components.lutron_caseta.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.lutron_caseta.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{},
diff --git a/tests/components/lyric/test_config_flow.py b/tests/components/lyric/test_config_flow.py
index 7f1e0549ee8..00d623ea3ce 100644
--- a/tests/components/lyric/test_config_flow.py
+++ b/tests/components/lyric/test_config_flow.py
@@ -84,9 +84,12 @@ async def test_full_flow(
},
)
- with patch("homeassistant.components.lyric.api.ConfigEntryLyricClient"), patch(
- "homeassistant.components.lyric.async_setup_entry", return_value=True
- ) as mock_setup:
+ 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"] == "cred"
@@ -152,9 +155,12 @@ async def test_reauthentication_flow(
},
)
- with patch("homeassistant.components.lyric.api.ConfigEntryLyricClient"), patch(
- "homeassistant.components.lyric.async_setup_entry", return_value=True
- ) as mock_setup:
+ 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["type"] == data_entry_flow.FlowResultType.ABORT
diff --git a/tests/components/medcom_ble/test_config_flow.py b/tests/components/medcom_ble/test_config_flow.py
index 34fc145e7dc..ca75dfd80ab 100644
--- a/tests/components/medcom_ble/test_config_flow.py
+++ b/tests/components/medcom_ble/test_config_flow.py
@@ -35,14 +35,17 @@ async def test_bluetooth_discovery(hass: HomeAssistant) -> None:
assert result["step_id"] == "bluetooth_confirm"
assert result["description_placeholders"] == {"name": "InspectorBLE-D9A0"}
- with patch_async_ble_device_from_address(MEDCOM_SERVICE_INFO), patch_medcom_ble(
- MedcomBleDevice(
- manufacturer="International Medcom",
- model="Inspector BLE",
- model_raw="Inspector-BLE",
- name="Inspector BLE",
- identifier="a0d95a570b00",
- )
+ with (
+ patch_async_ble_device_from_address(MEDCOM_SERVICE_INFO),
+ patch_medcom_ble(
+ MedcomBleDevice(
+ manufacturer="International Medcom",
+ model="Inspector BLE",
+ model_raw="Inspector-BLE",
+ name="Inspector BLE",
+ identifier="a0d95a570b00",
+ )
+ ),
):
with patch_async_setup_entry():
result = await hass.config_entries.flow.async_configure(
@@ -89,17 +92,21 @@ async def test_user_setup(hass: HomeAssistant) -> None:
"a0:d9:5a:57:0b:00": "InspectorBLE-D9A0"
}
- with patch_async_ble_device_from_address(MEDCOM_SERVICE_INFO), patch_medcom_ble(
- MedcomBleDevice(
- manufacturer="International Medcom",
- model="Inspector BLE",
- model_raw="Inspector-BLE",
- name="Inspector BLE",
- identifier="a0d95a570b00",
- )
- ), patch(
- "homeassistant.components.medcom_ble.async_setup_entry",
- return_value=True,
+ with (
+ patch_async_ble_device_from_address(MEDCOM_SERVICE_INFO),
+ patch_medcom_ble(
+ MedcomBleDevice(
+ manufacturer="International Medcom",
+ model="Inspector BLE",
+ model_raw="Inspector-BLE",
+ name="Inspector BLE",
+ identifier="a0d95a570b00",
+ )
+ ),
+ patch(
+ "homeassistant.components.medcom_ble.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_ADDRESS: "a0:d9:5a:57:0b:00"}
@@ -178,8 +185,9 @@ async def test_user_setup_unknown_error(hass: HomeAssistant) -> None:
assert result["errors"] is None
assert result["data_schema"] is not None
- with patch_async_ble_device_from_address(MEDCOM_SERVICE_INFO), patch_medcom_ble(
- None, Exception()
+ with (
+ patch_async_ble_device_from_address(MEDCOM_SERVICE_INFO),
+ patch_medcom_ble(None, Exception()),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_ADDRESS: "a0:d9:5a:57:0b:00"}
@@ -208,8 +216,9 @@ async def test_user_setup_unable_to_connect(hass: HomeAssistant) -> None:
"a0:d9:5a:57:0b:00": "InspectorBLE-D9A0"
}
- with patch_async_ble_device_from_address(MEDCOM_SERVICE_INFO), patch_medcom_ble(
- side_effect=BleakError("An error")
+ with (
+ patch_async_ble_device_from_address(MEDCOM_SERVICE_INFO),
+ patch_medcom_ble(side_effect=BleakError("An error")),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_ADDRESS: "a0:d9:5a:57:0b:00"}
diff --git a/tests/components/media_extractor/test_init.py b/tests/components/media_extractor/test_init.py
index 35570e3257d..e47f0ae1470 100644
--- a/tests/components/media_extractor/test_init.py
+++ b/tests/components/media_extractor/test_init.py
@@ -190,12 +190,17 @@ async def test_query_error(
) -> None:
"""Test handling error with query."""
- with patch(
- "homeassistant.components.media_extractor.YoutubeDL.extract_info",
- return_value=load_json_object_fixture("media_extractor/youtube_1_info.json"),
- ), patch(
- "homeassistant.components.media_extractor.YoutubeDL.process_ie_result",
- side_effect=DownloadError("Message"),
+ with (
+ patch(
+ "homeassistant.components.media_extractor.YoutubeDL.extract_info",
+ return_value=load_json_object_fixture(
+ "media_extractor/youtube_1_info.json"
+ ),
+ ),
+ patch(
+ "homeassistant.components.media_extractor.YoutubeDL.process_ie_result",
+ side_effect=DownloadError("Message"),
+ ),
):
await async_setup_component(hass, DOMAIN, empty_media_extractor_config)
await hass.async_block_till_done()
diff --git a/tests/components/media_player/test_browse_media.py b/tests/components/media_player/test_browse_media.py
index e3c5614d815..2b7e40923bf 100644
--- a/tests/components/media_player/test_browse_media.py
+++ b/tests/components/media_player/test_browse_media.py
@@ -57,9 +57,12 @@ async def test_process_play_media_url(hass: HomeAssistant, mock_sign_path) -> No
async_process_play_media_url(hass, "http://192.168.123.123:8123/path")
== "http://192.168.123.123:8123/path?authSig=bla"
)
- with pytest.raises(HomeAssistantError), patch(
- "homeassistant.components.media_player.browse_media.get_url",
- side_effect=NoURLAvailableError,
+ with (
+ pytest.raises(HomeAssistantError),
+ patch(
+ "homeassistant.components.media_player.browse_media.get_url",
+ side_effect=NoURLAvailableError,
+ ),
):
async_process_play_media_url(hass, "/path")
diff --git a/tests/components/melnor/test_number.py b/tests/components/melnor/test_number.py
index 4b185c3700c..f50d0d79edb 100644
--- a/tests/components/melnor/test_number.py
+++ b/tests/components/melnor/test_number.py
@@ -17,7 +17,11 @@ async def test_manual_watering_minutes(hass: HomeAssistant) -> None:
entry = mock_config_entry(hass)
- with patch_async_ble_device_from_address(), patch_melnor_device() as device_patch, patch_async_register_callback():
+ with (
+ patch_async_ble_device_from_address(),
+ patch_melnor_device() as device_patch,
+ patch_async_register_callback(),
+ ):
device = device_patch.return_value
assert await hass.config_entries.async_setup(entry.entry_id)
@@ -52,7 +56,11 @@ async def test_frequency_interval_hours(hass: HomeAssistant) -> None:
entry = mock_config_entry(hass)
- with patch_async_ble_device_from_address(), patch_melnor_device() as device_patch, patch_async_register_callback():
+ with (
+ patch_async_ble_device_from_address(),
+ patch_melnor_device() as device_patch,
+ patch_async_register_callback(),
+ ):
device = device_patch.return_value
assert await hass.config_entries.async_setup(entry.entry_id)
@@ -87,7 +95,11 @@ async def test_frequency_duration_minutes(hass: HomeAssistant) -> None:
entry = mock_config_entry(hass)
- with patch_async_ble_device_from_address(), patch_melnor_device() as device_patch, patch_async_register_callback():
+ with (
+ patch_async_ble_device_from_address(),
+ patch_melnor_device() as device_patch,
+ patch_async_register_callback(),
+ ):
device = device_patch.return_value
assert await hass.config_entries.async_setup(entry.entry_id)
diff --git a/tests/components/melnor/test_sensor.py b/tests/components/melnor/test_sensor.py
index 0f7eec0bbd4..d04494d44ad 100644
--- a/tests/components/melnor/test_sensor.py
+++ b/tests/components/melnor/test_sensor.py
@@ -26,7 +26,11 @@ async def test_battery_sensor(hass: HomeAssistant) -> None:
entry = mock_config_entry(hass)
- with patch_async_ble_device_from_address(), patch_melnor_device(), patch_async_register_callback():
+ with (
+ patch_async_ble_device_from_address(),
+ patch_melnor_device(),
+ patch_async_register_callback(),
+ ):
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
@@ -53,9 +57,12 @@ async def test_minutes_remaining_sensor(hass: HomeAssistant) -> None:
device.zone1._end_time = (end_time).timestamp()
- with freeze_time(now), patch_async_ble_device_from_address(), patch_melnor_device(
- device
- ), patch_async_register_callback():
+ with (
+ freeze_time(now),
+ patch_async_ble_device_from_address(),
+ patch_melnor_device(device),
+ patch_async_register_callback(),
+ ):
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
@@ -92,9 +99,12 @@ async def test_schedule_next_cycle_sensor(hass: HomeAssistant) -> None:
# we control this mock
device.zone1.frequency._next_run_time = next_cycle
- with freeze_time(now), patch_async_ble_device_from_address(), patch_melnor_device(
- device
- ), patch_async_register_callback():
+ with (
+ freeze_time(now),
+ patch_async_ble_device_from_address(),
+ patch_melnor_device(device),
+ patch_async_register_callback(),
+ ):
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
@@ -127,9 +137,11 @@ async def test_rssi_sensor(
device = mock_melnor_device()
- with patch_async_ble_device_from_address(), patch_melnor_device(
- device
- ), patch_async_register_callback():
+ with (
+ patch_async_ble_device_from_address(),
+ patch_melnor_device(device),
+ patch_async_register_callback(),
+ ):
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/melnor/test_switch.py b/tests/components/melnor/test_switch.py
index a5efcaef18e..0da0195fe75 100644
--- a/tests/components/melnor/test_switch.py
+++ b/tests/components/melnor/test_switch.py
@@ -19,7 +19,11 @@ async def test_manual_watering_switch_metadata(hass: HomeAssistant) -> None:
entry = mock_config_entry(hass)
- with patch_async_ble_device_from_address(), patch_melnor_device(), patch_async_register_callback():
+ with (
+ patch_async_ble_device_from_address(),
+ patch_melnor_device(),
+ patch_async_register_callback(),
+ ):
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
@@ -34,7 +38,11 @@ async def test_manual_watering_switch_on_off(hass: HomeAssistant) -> None:
entry = mock_config_entry(hass)
- with patch_async_ble_device_from_address(), patch_melnor_device() as device_patch, patch_async_register_callback():
+ with (
+ patch_async_ble_device_from_address(),
+ patch_melnor_device() as device_patch,
+ patch_async_register_callback(),
+ ):
device = device_patch.return_value
assert await hass.config_entries.async_setup(entry.entry_id)
@@ -77,7 +85,11 @@ async def test_schedule_enabled_switch_on_off(hass: HomeAssistant) -> None:
entry = mock_config_entry(hass)
- with patch_async_ble_device_from_address(), patch_melnor_device() as device_patch, patch_async_register_callback():
+ with (
+ patch_async_ble_device_from_address(),
+ patch_melnor_device() as device_patch,
+ patch_async_register_callback(),
+ ):
device = device_patch.return_value
assert await hass.config_entries.async_setup(entry.entry_id)
diff --git a/tests/components/melnor/test_time.py b/tests/components/melnor/test_time.py
index a49999d507b..1d12c3b47f8 100644
--- a/tests/components/melnor/test_time.py
+++ b/tests/components/melnor/test_time.py
@@ -24,7 +24,11 @@ async def test_schedule_start_time(hass: HomeAssistant) -> None:
entry = mock_config_entry(hass)
- with patch_async_ble_device_from_address(), patch_melnor_device() as device_patch, patch_async_register_callback():
+ with (
+ patch_async_ble_device_from_address(),
+ patch_melnor_device() as device_patch,
+ patch_async_register_callback(),
+ ):
device = device_patch.return_value
assert await hass.config_entries.async_setup(entry.entry_id)
diff --git a/tests/components/mfi/test_sensor.py b/tests/components/mfi/test_sensor.py
index fda318489fb..24f6a52fa5c 100644
--- a/tests/components/mfi/test_sensor.py
+++ b/tests/components/mfi/test_sensor.py
@@ -93,11 +93,12 @@ async def test_setup_with_tls_disabled(hass: HomeAssistant) -> None:
async def test_setup_adds_proper_devices(hass: HomeAssistant) -> None:
"""Test if setup adds devices."""
- with mock.patch(
- "homeassistant.components.mfi.sensor.MFiClient"
- ) as mock_client, mock.patch(
- "homeassistant.components.mfi.sensor.MfiSensor", side_effect=mfi.MfiSensor
- ) as mock_sensor:
+ with (
+ mock.patch("homeassistant.components.mfi.sensor.MFiClient") as mock_client,
+ mock.patch(
+ "homeassistant.components.mfi.sensor.MfiSensor", side_effect=mfi.MfiSensor
+ ) as mock_sensor,
+ ):
ports = {
i: mock.MagicMock(model=model, label=f"Port {i}", value=0)
for i, model in enumerate(mfi.SENSOR_MODELS)
diff --git a/tests/components/mfi/test_switch.py b/tests/components/mfi/test_switch.py
index fb4e42fb137..6c69787beef 100644
--- a/tests/components/mfi/test_switch.py
+++ b/tests/components/mfi/test_switch.py
@@ -27,11 +27,12 @@ GOOD_CONFIG = {
async def test_setup_adds_proper_devices(hass: HomeAssistant) -> None:
"""Test if setup adds devices."""
- with mock.patch(
- "homeassistant.components.mfi.switch.MFiClient"
- ) as mock_client, mock.patch(
- "homeassistant.components.mfi.switch.MfiSwitch", side_effect=mfi.MfiSwitch
- ) as mock_switch:
+ with (
+ mock.patch("homeassistant.components.mfi.switch.MFiClient") as mock_client,
+ mock.patch(
+ "homeassistant.components.mfi.switch.MfiSwitch", side_effect=mfi.MfiSwitch
+ ) as mock_switch,
+ ):
ports = {
i: mock.MagicMock(
model=model, label=f"Port {i}", output=False, data={}, ident=f"abcd-{i}"
diff --git a/tests/components/microbees/conftest.py b/tests/components/microbees/conftest.py
index e89d4780ad9..60df0377e4d 100644
--- a/tests/components/microbees/conftest.py
+++ b/tests/components/microbees/conftest.py
@@ -84,11 +84,14 @@ def mock_microbees():
mock.getBees.return_value = devices
mock.getMyProfile.return_value = profile
- with patch(
- "homeassistant.components.microbees.config_flow.MicroBees",
- return_value=mock,
- ) as mock, patch(
- "homeassistant.components.microbees.MicroBees",
- return_value=mock,
+ with (
+ patch(
+ "homeassistant.components.microbees.config_flow.MicroBees",
+ return_value=mock,
+ ) as mock,
+ patch(
+ "homeassistant.components.microbees.MicroBees",
+ return_value=mock,
+ ),
):
yield mock
diff --git a/tests/components/mikrotik/__init__.py b/tests/components/mikrotik/__init__.py
index acf5fcb2d5e..ad8521c7787 100644
--- a/tests/components/mikrotik/__init__.py
+++ b/tests/components/mikrotik/__init__.py
@@ -208,8 +208,9 @@ async def setup_mikrotik_entry(hass: HomeAssistant, **kwargs: Any) -> None:
)
config_entry.add_to_hass(hass)
- with patch("librouteros.connect"), patch.object(
- mikrotik.hub.MikrotikData, "command", new=mock_command
+ with (
+ patch("librouteros.connect"),
+ patch.object(mikrotik.hub.MikrotikData, "command", new=mock_command),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/mikrotik/test_init.py b/tests/components/mikrotik/test_init.py
index a42db5f84da..96ec0f5771e 100644
--- a/tests/components/mikrotik/test_init.py
+++ b/tests/components/mikrotik/test_init.py
@@ -18,9 +18,10 @@ from tests.common import MockConfigEntry
@pytest.fixture(autouse=True)
def mock_api():
"""Mock api."""
- with patch("librouteros.create_transport"), patch(
- "librouteros.Api.readResponse"
- ) as mock_api:
+ with (
+ patch("librouteros.create_transport"),
+ patch("librouteros.Api.readResponse") as mock_api,
+ ):
yield mock_api
diff --git a/tests/components/mill/test_init.py b/tests/components/mill/test_init.py
index 21201e955d7..bf0026b8c6c 100644
--- a/tests/components/mill/test_init.py
+++ b/tests/components/mill/test_init.py
@@ -22,9 +22,10 @@ async def test_setup_with_cloud_config(hass: HomeAssistant) -> None:
},
)
entry.add_to_hass(hass)
- with patch(
- "mill.Mill.fetch_heater_and_sensor_data", return_value={}
- ) as mock_fetch, patch("mill.Mill.connect", return_value=True) as mock_connect:
+ with (
+ patch("mill.Mill.fetch_heater_and_sensor_data", return_value={}) as mock_fetch,
+ patch("mill.Mill.connect", return_value=True) as mock_connect,
+ ):
assert await async_setup_component(hass, "mill", {})
assert len(mock_fetch.mock_calls) == 1
assert len(mock_connect.mock_calls) == 1
@@ -72,9 +73,10 @@ async def test_setup_with_old_cloud_config(hass: HomeAssistant) -> None:
},
)
entry.add_to_hass(hass)
- with patch("mill.Mill.fetch_heater_and_sensor_data", return_value={}), patch(
- "mill.Mill.connect", return_value=True
- ) as mock_connect:
+ with (
+ patch("mill.Mill.fetch_heater_and_sensor_data", return_value={}),
+ patch("mill.Mill.connect", return_value=True) as mock_connect,
+ ):
assert await async_setup_component(hass, "mill", {})
assert len(mock_connect.mock_calls) == 1
@@ -90,24 +92,27 @@ async def test_setup_with_local_config(hass: HomeAssistant) -> None:
},
)
entry.add_to_hass(hass)
- with patch(
- "mill_local.Mill.fetch_heater_and_sensor_data",
- return_value={
- "ambient_temperature": 20,
- "set_temperature": 22,
- "current_power": 0,
- "control_signal": 0,
- "raw_ambient_temperature": 19,
- },
- ) as mock_fetch, patch(
- "mill_local.Mill.connect",
- return_value={
- "name": "panel heater gen. 3",
- "version": "0x210927",
- "operation_key": "",
- "status": "ok",
- },
- ) as mock_connect:
+ with (
+ patch(
+ "mill_local.Mill.fetch_heater_and_sensor_data",
+ return_value={
+ "ambient_temperature": 20,
+ "set_temperature": 22,
+ "current_power": 0,
+ "control_signal": 0,
+ "raw_ambient_temperature": 19,
+ },
+ ) as mock_fetch,
+ patch(
+ "mill_local.Mill.connect",
+ return_value={
+ "name": "panel heater gen. 3",
+ "version": "0x210927",
+ "operation_key": "",
+ "status": "ok",
+ },
+ ) as mock_connect,
+ ):
assert await async_setup_component(hass, "mill", {})
assert len(mock_fetch.mock_calls) == 1
@@ -126,15 +131,17 @@ async def test_unload_entry(hass: HomeAssistant) -> None:
)
entry.add_to_hass(hass)
- with patch.object(
- hass.config_entries,
- "async_forward_entry_unload",
- return_value=True,
- ) as unload_entry, patch(
- "mill.Mill.fetch_heater_and_sensor_data", return_value={}
- ), patch(
- "mill.Mill.connect",
- return_value=True,
+ with (
+ patch.object(
+ hass.config_entries,
+ "async_forward_entry_unload",
+ return_value=True,
+ ) as unload_entry,
+ patch("mill.Mill.fetch_heater_and_sensor_data", return_value={}),
+ patch(
+ "mill.Mill.connect",
+ return_value=True,
+ ),
):
assert await async_setup_component(hass, "mill", {})
diff --git a/tests/components/minecraft_server/test_binary_sensor.py b/tests/components/minecraft_server/test_binary_sensor.py
index 40b8a6c5c0c..6321c91d74a 100644
--- a/tests/components/minecraft_server/test_binary_sensor.py
+++ b/tests/components/minecraft_server/test_binary_sensor.py
@@ -52,12 +52,15 @@ async def test_binary_sensor(
mock_config_entry = request.getfixturevalue(mock_config_entry)
mock_config_entry.add_to_hass(hass)
- with patch(
- f"homeassistant.components.minecraft_server.api.{server.__name__}.{lookup_function_name}",
- return_value=server(host=TEST_HOST, port=TEST_PORT),
- ), patch(
- f"homeassistant.components.minecraft_server.api.{server.__name__}.async_status",
- return_value=status_response,
+ with (
+ patch(
+ f"homeassistant.components.minecraft_server.api.{server.__name__}.{lookup_function_name}",
+ return_value=server(host=TEST_HOST, port=TEST_PORT),
+ ),
+ patch(
+ f"homeassistant.components.minecraft_server.api.{server.__name__}.async_status",
+ return_value=status_response,
+ ),
):
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
@@ -95,12 +98,15 @@ async def test_binary_sensor_update(
mock_config_entry = request.getfixturevalue(mock_config_entry)
mock_config_entry.add_to_hass(hass)
- with patch(
- f"homeassistant.components.minecraft_server.api.{server.__name__}.{lookup_function_name}",
- return_value=server(host=TEST_HOST, port=TEST_PORT),
- ), patch(
- f"homeassistant.components.minecraft_server.api.{server.__name__}.async_status",
- return_value=status_response,
+ with (
+ patch(
+ f"homeassistant.components.minecraft_server.api.{server.__name__}.{lookup_function_name}",
+ return_value=server(host=TEST_HOST, port=TEST_PORT),
+ ),
+ patch(
+ f"homeassistant.components.minecraft_server.api.{server.__name__}.async_status",
+ return_value=status_response,
+ ),
):
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
@@ -140,12 +146,15 @@ async def test_binary_sensor_update_failure(
mock_config_entry = request.getfixturevalue(mock_config_entry)
mock_config_entry.add_to_hass(hass)
- with patch(
- f"homeassistant.components.minecraft_server.api.{server.__name__}.{lookup_function_name}",
- return_value=server(host=TEST_HOST, port=TEST_PORT),
- ), patch(
- f"homeassistant.components.minecraft_server.api.{server.__name__}.async_status",
- return_value=status_response,
+ with (
+ patch(
+ f"homeassistant.components.minecraft_server.api.{server.__name__}.{lookup_function_name}",
+ return_value=server(host=TEST_HOST, port=TEST_PORT),
+ ),
+ patch(
+ f"homeassistant.components.minecraft_server.api.{server.__name__}.async_status",
+ return_value=status_response,
+ ),
):
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/minecraft_server/test_config_flow.py b/tests/components/minecraft_server/test_config_flow.py
index 2a0208f2251..188b68ce5af 100644
--- a/tests/components/minecraft_server/test_config_flow.py
+++ b/tests/components/minecraft_server/test_config_flow.py
@@ -37,12 +37,15 @@ async def test_show_config_form(hass: HomeAssistant) -> None:
async def test_address_validation_failure(hass: HomeAssistant) -> None:
"""Test error in case of a failed connection."""
- with patch(
- "homeassistant.components.minecraft_server.api.BedrockServer.lookup",
- side_effect=ValueError,
- ), patch(
- "homeassistant.components.minecraft_server.api.JavaServer.async_lookup",
- side_effect=ValueError,
+ with (
+ patch(
+ "homeassistant.components.minecraft_server.api.BedrockServer.lookup",
+ side_effect=ValueError,
+ ),
+ patch(
+ "homeassistant.components.minecraft_server.api.JavaServer.async_lookup",
+ side_effect=ValueError,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT
@@ -54,15 +57,19 @@ async def test_address_validation_failure(hass: HomeAssistant) -> None:
async def test_java_connection_failure(hass: HomeAssistant) -> None:
"""Test error in case of a failed connection to a Java Edition server."""
- with patch(
- "homeassistant.components.minecraft_server.api.BedrockServer.lookup",
- side_effect=ValueError,
- ), patch(
- "homeassistant.components.minecraft_server.api.JavaServer.async_lookup",
- return_value=JavaServer(host=TEST_HOST, port=TEST_PORT),
- ), patch(
- "homeassistant.components.minecraft_server.api.JavaServer.async_status",
- side_effect=OSError,
+ with (
+ patch(
+ "homeassistant.components.minecraft_server.api.BedrockServer.lookup",
+ side_effect=ValueError,
+ ),
+ patch(
+ "homeassistant.components.minecraft_server.api.JavaServer.async_lookup",
+ return_value=JavaServer(host=TEST_HOST, port=TEST_PORT),
+ ),
+ patch(
+ "homeassistant.components.minecraft_server.api.JavaServer.async_status",
+ side_effect=OSError,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT
@@ -74,12 +81,15 @@ async def test_java_connection_failure(hass: HomeAssistant) -> None:
async def test_bedrock_connection_failure(hass: HomeAssistant) -> None:
"""Test error in case of a failed connection to a Bedrock Edition server."""
- with patch(
- "homeassistant.components.minecraft_server.api.BedrockServer.lookup",
- return_value=BedrockServer(host=TEST_HOST, port=TEST_PORT),
- ), patch(
- "homeassistant.components.minecraft_server.api.BedrockServer.async_status",
- side_effect=OSError,
+ with (
+ patch(
+ "homeassistant.components.minecraft_server.api.BedrockServer.lookup",
+ return_value=BedrockServer(host=TEST_HOST, port=TEST_PORT),
+ ),
+ patch(
+ "homeassistant.components.minecraft_server.api.BedrockServer.async_status",
+ side_effect=OSError,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT
@@ -91,15 +101,19 @@ async def test_bedrock_connection_failure(hass: HomeAssistant) -> None:
async def test_java_connection(hass: HomeAssistant) -> None:
"""Test config entry in case of a successful connection to a Java Edition server."""
- with patch(
- "homeassistant.components.minecraft_server.api.BedrockServer.lookup",
- side_effect=ValueError,
- ), patch(
- "homeassistant.components.minecraft_server.api.JavaServer.async_lookup",
- return_value=JavaServer(host=TEST_HOST, port=TEST_PORT),
- ), patch(
- "homeassistant.components.minecraft_server.api.JavaServer.async_status",
- return_value=TEST_JAVA_STATUS_RESPONSE,
+ with (
+ patch(
+ "homeassistant.components.minecraft_server.api.BedrockServer.lookup",
+ side_effect=ValueError,
+ ),
+ patch(
+ "homeassistant.components.minecraft_server.api.JavaServer.async_lookup",
+ return_value=JavaServer(host=TEST_HOST, port=TEST_PORT),
+ ),
+ patch(
+ "homeassistant.components.minecraft_server.api.JavaServer.async_status",
+ return_value=TEST_JAVA_STATUS_RESPONSE,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT
@@ -114,12 +128,15 @@ async def test_java_connection(hass: HomeAssistant) -> None:
async def test_bedrock_connection(hass: HomeAssistant) -> None:
"""Test config entry in case of a successful connection to a Bedrock Edition server."""
- with patch(
- "homeassistant.components.minecraft_server.api.BedrockServer.lookup",
- return_value=BedrockServer(host=TEST_HOST, port=TEST_PORT),
- ), patch(
- "homeassistant.components.minecraft_server.api.BedrockServer.async_status",
- return_value=TEST_BEDROCK_STATUS_RESPONSE,
+ with (
+ patch(
+ "homeassistant.components.minecraft_server.api.BedrockServer.lookup",
+ return_value=BedrockServer(host=TEST_HOST, port=TEST_PORT),
+ ),
+ patch(
+ "homeassistant.components.minecraft_server.api.BedrockServer.async_status",
+ return_value=TEST_BEDROCK_STATUS_RESPONSE,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT
@@ -134,12 +151,15 @@ async def test_bedrock_connection(hass: HomeAssistant) -> None:
async def test_recovery(hass: HomeAssistant) -> None:
"""Test config flow recovery (successful connection after a failed connection)."""
- with patch(
- "homeassistant.components.minecraft_server.api.BedrockServer.lookup",
- side_effect=ValueError,
- ), patch(
- "homeassistant.components.minecraft_server.api.JavaServer.async_lookup",
- side_effect=ValueError,
+ with (
+ patch(
+ "homeassistant.components.minecraft_server.api.BedrockServer.lookup",
+ side_effect=ValueError,
+ ),
+ patch(
+ "homeassistant.components.minecraft_server.api.JavaServer.async_lookup",
+ side_effect=ValueError,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT
@@ -147,12 +167,15 @@ async def test_recovery(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {"base": "cannot_connect"}
- with patch(
- "homeassistant.components.minecraft_server.api.BedrockServer.lookup",
- return_value=BedrockServer(host=TEST_HOST, port=TEST_PORT),
- ), patch(
- "homeassistant.components.minecraft_server.api.BedrockServer.async_status",
- return_value=TEST_BEDROCK_STATUS_RESPONSE,
+ with (
+ patch(
+ "homeassistant.components.minecraft_server.api.BedrockServer.lookup",
+ return_value=BedrockServer(host=TEST_HOST, port=TEST_PORT),
+ ),
+ patch(
+ "homeassistant.components.minecraft_server.api.BedrockServer.async_status",
+ return_value=TEST_BEDROCK_STATUS_RESPONSE,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
flow_id=result["flow_id"], user_input=USER_INPUT
diff --git a/tests/components/minecraft_server/test_diagnostics.py b/tests/components/minecraft_server/test_diagnostics.py
index ce51a38b88f..e72d0c5f8db 100644
--- a/tests/components/minecraft_server/test_diagnostics.py
+++ b/tests/components/minecraft_server/test_diagnostics.py
@@ -49,12 +49,15 @@ async def test_config_entry_diagnostics(
lookup_function_name = "lookup"
# Setup mock entry.
- with patch(
- f"mcstatus.server.{server.__name__}.{lookup_function_name}",
- return_value=server(host=TEST_HOST, port=TEST_PORT),
- ), patch(
- f"mcstatus.server.{server.__name__}.async_status",
- return_value=status_response,
+ with (
+ patch(
+ f"mcstatus.server.{server.__name__}.{lookup_function_name}",
+ return_value=server(host=TEST_HOST, port=TEST_PORT),
+ ),
+ patch(
+ f"mcstatus.server.{server.__name__}.async_status",
+ return_value=status_response,
+ ),
):
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/minecraft_server/test_init.py b/tests/components/minecraft_server/test_init.py
index 86f592f3d76..9c02fb56d91 100644
--- a/tests/components/minecraft_server/test_init.py
+++ b/tests/components/minecraft_server/test_init.py
@@ -122,12 +122,15 @@ async def test_setup_and_unload_entry(
"""Test successful entry setup and unload."""
java_mock_config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.minecraft_server.api.JavaServer.async_lookup",
- return_value=JavaServer(host=TEST_HOST, port=TEST_PORT),
- ), patch(
- "homeassistant.components.minecraft_server.api.JavaServer.async_status",
- return_value=TEST_JAVA_STATUS_RESPONSE,
+ with (
+ patch(
+ "homeassistant.components.minecraft_server.api.JavaServer.async_lookup",
+ return_value=JavaServer(host=TEST_HOST, port=TEST_PORT),
+ ),
+ patch(
+ "homeassistant.components.minecraft_server.api.JavaServer.async_status",
+ return_value=TEST_JAVA_STATUS_RESPONSE,
+ ),
):
assert await hass.config_entries.async_setup(java_mock_config_entry.entry_id)
await hass.async_block_till_done()
@@ -181,12 +184,15 @@ async def test_setup_entry_not_ready(
"""Test entry setup not ready."""
java_mock_config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.minecraft_server.api.JavaServer.async_lookup",
- return_value=JavaServer(host=TEST_HOST, port=TEST_PORT),
- ), patch(
- "homeassistant.components.minecraft_server.api.JavaServer.async_status",
- return_value=OSError,
+ with (
+ patch(
+ "homeassistant.components.minecraft_server.api.JavaServer.async_lookup",
+ return_value=JavaServer(host=TEST_HOST, port=TEST_PORT),
+ ),
+ patch(
+ "homeassistant.components.minecraft_server.api.JavaServer.async_status",
+ return_value=OSError,
+ ),
):
assert not await hass.config_entries.async_setup(
java_mock_config_entry.entry_id
@@ -214,16 +220,19 @@ async def test_entry_migration(
)
# Trigger migration.
- with patch(
- "homeassistant.components.minecraft_server.api.JavaServer.async_lookup",
- side_effect=[
- ValueError, # async_migrate_entry
- JavaServer(host=TEST_HOST, port=TEST_PORT), # async_migrate_entry
- JavaServer(host=TEST_HOST, port=TEST_PORT), # async_setup_entry
- ],
- ), patch(
- "homeassistant.components.minecraft_server.api.JavaServer.async_status",
- return_value=TEST_JAVA_STATUS_RESPONSE,
+ with (
+ patch(
+ "homeassistant.components.minecraft_server.api.JavaServer.async_lookup",
+ side_effect=[
+ ValueError, # async_migrate_entry
+ JavaServer(host=TEST_HOST, port=TEST_PORT), # async_migrate_entry
+ JavaServer(host=TEST_HOST, port=TEST_PORT), # async_setup_entry
+ ],
+ ),
+ patch(
+ "homeassistant.components.minecraft_server.api.JavaServer.async_status",
+ return_value=TEST_JAVA_STATUS_RESPONSE,
+ ),
):
assert await hass.config_entries.async_setup(v1_mock_config_entry.entry_id)
await hass.async_block_till_done()
@@ -276,12 +285,15 @@ async def test_entry_migration_host_only(
)
# Trigger migration.
- with patch(
- "homeassistant.components.minecraft_server.api.JavaServer.async_lookup",
- return_value=JavaServer(host=TEST_HOST, port=TEST_PORT),
- ), patch(
- "homeassistant.components.minecraft_server.api.JavaServer.async_status",
- return_value=TEST_JAVA_STATUS_RESPONSE,
+ with (
+ patch(
+ "homeassistant.components.minecraft_server.api.JavaServer.async_lookup",
+ return_value=JavaServer(host=TEST_HOST, port=TEST_PORT),
+ ),
+ patch(
+ "homeassistant.components.minecraft_server.api.JavaServer.async_status",
+ return_value=TEST_JAVA_STATUS_RESPONSE,
+ ),
):
assert await hass.config_entries.async_setup(v1_mock_config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/minecraft_server/test_sensor.py b/tests/components/minecraft_server/test_sensor.py
index 512f6bf3f78..ff62f8ddf36 100644
--- a/tests/components/minecraft_server/test_sensor.py
+++ b/tests/components/minecraft_server/test_sensor.py
@@ -94,12 +94,15 @@ async def test_sensor(
mock_config_entry = request.getfixturevalue(mock_config_entry)
mock_config_entry.add_to_hass(hass)
- with patch(
- f"homeassistant.components.minecraft_server.api.{server.__name__}.{lookup_function_name}",
- return_value=server(host=TEST_HOST, port=TEST_PORT),
- ), patch(
- f"homeassistant.components.minecraft_server.api.{server.__name__}.async_status",
- return_value=status_response,
+ with (
+ patch(
+ f"homeassistant.components.minecraft_server.api.{server.__name__}.{lookup_function_name}",
+ return_value=server(host=TEST_HOST, port=TEST_PORT),
+ ),
+ patch(
+ f"homeassistant.components.minecraft_server.api.{server.__name__}.async_status",
+ return_value=status_response,
+ ),
):
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
@@ -145,12 +148,15 @@ async def test_sensor_disabled_by_default(
mock_config_entry = request.getfixturevalue(mock_config_entry)
mock_config_entry.add_to_hass(hass)
- with patch(
- f"homeassistant.components.minecraft_server.api.{server.__name__}.{lookup_function_name}",
- return_value=server(host=TEST_HOST, port=TEST_PORT),
- ), patch(
- f"homeassistant.components.minecraft_server.api.{server.__name__}.async_status",
- return_value=status_response,
+ with (
+ patch(
+ f"homeassistant.components.minecraft_server.api.{server.__name__}.{lookup_function_name}",
+ return_value=server(host=TEST_HOST, port=TEST_PORT),
+ ),
+ patch(
+ f"homeassistant.components.minecraft_server.api.{server.__name__}.async_status",
+ return_value=status_response,
+ ),
):
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
@@ -199,12 +205,15 @@ async def test_sensor_update(
mock_config_entry = request.getfixturevalue(mock_config_entry)
mock_config_entry.add_to_hass(hass)
- with patch(
- f"homeassistant.components.minecraft_server.api.{server.__name__}.{lookup_function_name}",
- return_value=server(host=TEST_HOST, port=TEST_PORT),
- ), patch(
- f"homeassistant.components.minecraft_server.api.{server.__name__}.async_status",
- return_value=status_response,
+ with (
+ patch(
+ f"homeassistant.components.minecraft_server.api.{server.__name__}.{lookup_function_name}",
+ return_value=server(host=TEST_HOST, port=TEST_PORT),
+ ),
+ patch(
+ f"homeassistant.components.minecraft_server.api.{server.__name__}.async_status",
+ return_value=status_response,
+ ),
):
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
@@ -255,12 +264,15 @@ async def test_sensor_update_failure(
mock_config_entry = request.getfixturevalue(mock_config_entry)
mock_config_entry.add_to_hass(hass)
- with patch(
- f"homeassistant.components.minecraft_server.api.{server.__name__}.{lookup_function_name}",
- return_value=server(host=TEST_HOST, port=TEST_PORT),
- ), patch(
- f"homeassistant.components.minecraft_server.api.{server.__name__}.async_status",
- return_value=status_response,
+ with (
+ patch(
+ f"homeassistant.components.minecraft_server.api.{server.__name__}.{lookup_function_name}",
+ return_value=server(host=TEST_HOST, port=TEST_PORT),
+ ),
+ patch(
+ f"homeassistant.components.minecraft_server.api.{server.__name__}.async_status",
+ return_value=status_response,
+ ),
):
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/mobile_app/test_init.py b/tests/components/mobile_app/test_init.py
index c6c724cc20b..15380a0d8d7 100644
--- a/tests/components/mobile_app/test_init.py
+++ b/tests/components/mobile_app/test_init.py
@@ -84,14 +84,17 @@ async def _test_create_cloud_hook(
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.cloud.async_active_subscription",
- return_value=async_active_subscription_return_value,
- ), patch(
- "homeassistant.components.cloud.async_is_connected", return_value=True
- ), patch(
- "homeassistant.components.cloud.async_get_or_create_cloudhook", autospec=True
- ) as mock_async_get_or_create_cloudhook:
+ with (
+ patch(
+ "homeassistant.components.cloud.async_active_subscription",
+ return_value=async_active_subscription_return_value,
+ ),
+ patch("homeassistant.components.cloud.async_is_connected", return_value=True),
+ patch(
+ "homeassistant.components.cloud.async_get_or_create_cloudhook",
+ autospec=True,
+ ) as mock_async_get_or_create_cloudhook,
+ ):
cloud_hook = "https://hook-url"
mock_async_get_or_create_cloudhook.return_value = cloud_hook
diff --git a/tests/components/mochad/test_switch.py b/tests/components/mochad/test_switch.py
index e89a9ec6269..96c3ba60b65 100644
--- a/tests/components/mochad/test_switch.py
+++ b/tests/components/mochad/test_switch.py
@@ -13,8 +13,9 @@ from homeassistant.setup import async_setup_component
@pytest.fixture(autouse=True)
def pymochad_mock():
"""Mock pymochad."""
- with mock.patch("homeassistant.components.mochad.switch.device"), mock.patch(
- "homeassistant.components.mochad.switch.MochadException"
+ with (
+ mock.patch("homeassistant.components.mochad.switch.device"),
+ mock.patch("homeassistant.components.mochad.switch.MochadException"),
):
yield
diff --git a/tests/components/modbus/conftest.py b/tests/components/modbus/conftest.py
index 2a81fa3d4fb..f6eff0fd64b 100644
--- a/tests/components/modbus/conftest.py
+++ b/tests/components/modbus/conftest.py
@@ -52,18 +52,22 @@ def mock_pymodbus_fixture():
"""Mock pymodbus."""
mock_pb = mock.AsyncMock()
mock_pb.close = mock.MagicMock()
- with mock.patch(
- "homeassistant.components.modbus.modbus.AsyncModbusTcpClient",
- return_value=mock_pb,
- autospec=True,
- ), mock.patch(
- "homeassistant.components.modbus.modbus.AsyncModbusSerialClient",
- return_value=mock_pb,
- autospec=True,
- ), mock.patch(
- "homeassistant.components.modbus.modbus.AsyncModbusUdpClient",
- return_value=mock_pb,
- autospec=True,
+ with (
+ mock.patch(
+ "homeassistant.components.modbus.modbus.AsyncModbusTcpClient",
+ return_value=mock_pb,
+ autospec=True,
+ ),
+ mock.patch(
+ "homeassistant.components.modbus.modbus.AsyncModbusSerialClient",
+ return_value=mock_pb,
+ autospec=True,
+ ),
+ mock.patch(
+ "homeassistant.components.modbus.modbus.AsyncModbusUdpClient",
+ return_value=mock_pb,
+ autospec=True,
+ ),
):
yield mock_pb
diff --git a/tests/components/modbus/test_init.py b/tests/components/modbus/test_init.py
index 598fcd7bea7..0ca4703aa5f 100644
--- a/tests/components/modbus/test_init.py
+++ b/tests/components/modbus/test_init.py
@@ -1653,9 +1653,10 @@ async def test_integration_reload_failed(
caplog.clear()
yaml_path = get_fixture_path("configuration.yaml", "modbus")
- with mock.patch.object(
- hass_config, "YAML_CONFIG_FILE", yaml_path
- ), mock.patch.object(mock_modbus, "connect", side_effect=ModbusException("error")):
+ with (
+ mock.patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path),
+ mock.patch.object(mock_modbus, "connect", side_effect=ModbusException("error")),
+ ):
await hass.services.async_call(DOMAIN, SERVICE_RELOAD, blocking=True)
await hass.async_block_till_done()
diff --git a/tests/components/modem_callerid/test_init.py b/tests/components/modem_callerid/test_init.py
index b1edf44acf3..ccf97f60e10 100644
--- a/tests/components/modem_callerid/test_init.py
+++ b/tests/components/modem_callerid/test_init.py
@@ -21,10 +21,14 @@ async def test_setup_entry(hass: HomeAssistant) -> None:
data={CONF_DEVICE: com_port().device},
)
entry.add_to_hass(hass)
- with patch("aioserial.AioSerial", autospec=True), patch(
- "homeassistant.components.modem_callerid.PhoneModem._get_response",
- return_value="OK",
- ), patch("phone_modem.PhoneModem._modem_sm"):
+ with (
+ patch("aioserial.AioSerial", autospec=True),
+ patch(
+ "homeassistant.components.modem_callerid.PhoneModem._get_response",
+ return_value="OK",
+ ),
+ patch("phone_modem.PhoneModem._modem_sm"),
+ ):
await hass.config_entries.async_setup(entry.entry_id)
assert entry.state == ConfigEntryState.LOADED
diff --git a/tests/components/modern_forms/test_fan.py b/tests/components/modern_forms/test_fan.py
index 92660643bfc..82ab6407c12 100644
--- a/tests/components/modern_forms/test_fan.py
+++ b/tests/components/modern_forms/test_fan.py
@@ -210,9 +210,12 @@ async def test_fan_connection_error(
"""Test error handling of the Moder Forms fans."""
await init_integration(hass, aioclient_mock)
- with patch("homeassistant.components.modern_forms.ModernFormsDevice.update"), patch(
- "homeassistant.components.modern_forms.ModernFormsDevice.fan",
- side_effect=ModernFormsConnectionError,
+ with (
+ patch("homeassistant.components.modern_forms.ModernFormsDevice.update"),
+ patch(
+ "homeassistant.components.modern_forms.ModernFormsDevice.fan",
+ side_effect=ModernFormsConnectionError,
+ ),
):
await hass.services.async_call(
FAN_DOMAIN,
diff --git a/tests/components/modern_forms/test_light.py b/tests/components/modern_forms/test_light.py
index 42415214116..3b1cfdd90d2 100644
--- a/tests/components/modern_forms/test_light.py
+++ b/tests/components/modern_forms/test_light.py
@@ -138,9 +138,12 @@ async def test_light_connection_error(
"""Test error handling of the Moder Forms lights."""
await init_integration(hass, aioclient_mock)
- with patch("homeassistant.components.modern_forms.ModernFormsDevice.update"), patch(
- "homeassistant.components.modern_forms.ModernFormsDevice.light",
- side_effect=ModernFormsConnectionError,
+ with (
+ patch("homeassistant.components.modern_forms.ModernFormsDevice.update"),
+ patch(
+ "homeassistant.components.modern_forms.ModernFormsDevice.light",
+ side_effect=ModernFormsConnectionError,
+ ),
):
await hass.services.async_call(
LIGHT_DOMAIN,
diff --git a/tests/components/modern_forms/test_switch.py b/tests/components/modern_forms/test_switch.py
index 42a52375c3c..8a2012bbd5f 100644
--- a/tests/components/modern_forms/test_switch.py
+++ b/tests/components/modern_forms/test_switch.py
@@ -130,9 +130,12 @@ async def test_switch_connection_error(
"""Test error handling of the Modern Forms switches."""
await init_integration(hass, aioclient_mock)
- with patch("homeassistant.components.modern_forms.ModernFormsDevice.update"), patch(
- "homeassistant.components.modern_forms.ModernFormsDevice.away",
- side_effect=ModernFormsConnectionError,
+ with (
+ patch("homeassistant.components.modern_forms.ModernFormsDevice.update"),
+ patch(
+ "homeassistant.components.modern_forms.ModernFormsDevice.away",
+ side_effect=ModernFormsConnectionError,
+ ),
):
await hass.services.async_call(
SWITCH_DOMAIN,
diff --git a/tests/components/moehlenhoff_alpha2/test_config_flow.py b/tests/components/moehlenhoff_alpha2/test_config_flow.py
index f3b37792287..fcce2d139d2 100644
--- a/tests/components/moehlenhoff_alpha2/test_config_flow.py
+++ b/tests/components/moehlenhoff_alpha2/test_config_flow.py
@@ -32,10 +32,13 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert not result["errors"]
- with patch("moehlenhoff_alpha2.Alpha2Base.update_data", mock_update_data), patch(
- "homeassistant.components.moehlenhoff_alpha2.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("moehlenhoff_alpha2.Alpha2Base.update_data", mock_update_data),
+ patch(
+ "homeassistant.components.moehlenhoff_alpha2.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
flow_id=result["flow_id"],
user_input={"host": MOCK_BASE_HOST},
diff --git a/tests/components/monoprice/test_config_flow.py b/tests/components/monoprice/test_config_flow.py
index ae9ffea921c..74c69078b1d 100644
--- a/tests/components/monoprice/test_config_flow.py
+++ b/tests/components/monoprice/test_config_flow.py
@@ -34,13 +34,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.monoprice.config_flow.get_monoprice",
- return_value=True,
- ), patch(
- "homeassistant.components.monoprice.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.monoprice.config_flow.get_monoprice",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.monoprice.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], CONFIG
)
diff --git a/tests/components/motion_blinds/test_config_flow.py b/tests/components/motion_blinds/test_config_flow.py
index 5ffb0b356ad..8d290b0b380 100644
--- a/tests/components/motion_blinds/test_config_flow.py
+++ b/tests/components/motion_blinds/test_config_flow.py
@@ -73,41 +73,55 @@ TEST_INTERFACES = [
@pytest.fixture(name="motion_blinds_connect", autouse=True)
def motion_blinds_connect_fixture(mock_get_source_ip):
"""Mock Motionblinds connection and entry setup."""
- with patch(
- "homeassistant.components.motion_blinds.gateway.MotionGateway.GetDeviceList",
- return_value=True,
- ), patch(
- "homeassistant.components.motion_blinds.gateway.MotionGateway.Update",
- return_value=True,
- ), patch(
- "homeassistant.components.motion_blinds.gateway.MotionGateway.Check_gateway_multicast",
- return_value=True,
- ), patch(
- "homeassistant.components.motion_blinds.gateway.MotionGateway.device_list",
- TEST_DEVICE_LIST,
- ), patch(
- "homeassistant.components.motion_blinds.gateway.MotionGateway.mac",
- TEST_MAC,
- ), patch(
- "homeassistant.components.motion_blinds.config_flow.MotionDiscovery.discover",
- return_value=TEST_DISCOVERY_1,
- ), patch(
- "homeassistant.components.motion_blinds.config_flow.MotionGateway.GetDeviceList",
- return_value=True,
- ), patch(
- "homeassistant.components.motion_blinds.config_flow.MotionGateway.available",
- True,
- ), patch(
- "homeassistant.components.motion_blinds.gateway.AsyncMotionMulticast.Start_listen",
- return_value=True,
- ), patch(
- "homeassistant.components.motion_blinds.gateway.AsyncMotionMulticast.Stop_listen",
- return_value=True,
- ), patch(
- "homeassistant.components.motion_blinds.gateway.network.async_get_adapters",
- return_value=TEST_INTERFACES,
- ), patch(
- "homeassistant.components.motion_blinds.async_setup_entry", return_value=True
+ with (
+ patch(
+ "homeassistant.components.motion_blinds.gateway.MotionGateway.GetDeviceList",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.motion_blinds.gateway.MotionGateway.Update",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.motion_blinds.gateway.MotionGateway.Check_gateway_multicast",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.motion_blinds.gateway.MotionGateway.device_list",
+ TEST_DEVICE_LIST,
+ ),
+ patch(
+ "homeassistant.components.motion_blinds.gateway.MotionGateway.mac",
+ TEST_MAC,
+ ),
+ patch(
+ "homeassistant.components.motion_blinds.config_flow.MotionDiscovery.discover",
+ return_value=TEST_DISCOVERY_1,
+ ),
+ patch(
+ "homeassistant.components.motion_blinds.config_flow.MotionGateway.GetDeviceList",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.motion_blinds.config_flow.MotionGateway.available",
+ True,
+ ),
+ patch(
+ "homeassistant.components.motion_blinds.gateway.AsyncMotionMulticast.Start_listen",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.motion_blinds.gateway.AsyncMotionMulticast.Stop_listen",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.motion_blinds.gateway.network.async_get_adapters",
+ return_value=TEST_INTERFACES,
+ ),
+ patch(
+ "homeassistant.components.motion_blinds.async_setup_entry",
+ return_value=True,
+ ),
):
yield
diff --git a/tests/components/motioneye/test_config_flow.py b/tests/components/motioneye/test_config_flow.py
index a5b2763182c..7163f2c8152 100644
--- a/tests/components/motioneye/test_config_flow.py
+++ b/tests/components/motioneye/test_config_flow.py
@@ -39,13 +39,16 @@ async def test_user_success(hass: HomeAssistant) -> None:
mock_client = create_mock_motioneye_client()
- with patch(
- "homeassistant.components.motioneye.MotionEyeClient",
- return_value=mock_client,
- ), patch(
- "homeassistant.components.motioneye.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.motioneye.MotionEyeClient",
+ return_value=mock_client,
+ ),
+ patch(
+ "homeassistant.components.motioneye.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -95,13 +98,16 @@ async def test_hassio_success(hass: HomeAssistant) -> None:
mock_client = create_mock_motioneye_client()
- with patch(
- "homeassistant.components.motioneye.MotionEyeClient",
- return_value=mock_client,
- ), patch(
- "homeassistant.components.motioneye.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.motioneye.MotionEyeClient",
+ return_value=mock_client,
+ ),
+ patch(
+ "homeassistant.components.motioneye.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
@@ -278,13 +284,16 @@ async def test_reauth(hass: HomeAssistant) -> None:
CONF_SURVEILLANCE_PASSWORD: "surveillance-password",
}
- with patch(
- "homeassistant.components.motioneye.MotionEyeClient",
- return_value=mock_client,
- ), patch(
- "homeassistant.components.motioneye.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.motioneye.MotionEyeClient",
+ return_value=mock_client,
+ ),
+ patch(
+ "homeassistant.components.motioneye.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
new_data,
@@ -430,13 +439,16 @@ async def test_hassio_clean_up_on_user_flow(hass: HomeAssistant) -> None:
mock_client = create_mock_motioneye_client()
- with patch(
- "homeassistant.components.motioneye.MotionEyeClient",
- return_value=mock_client,
- ), patch(
- "homeassistant.components.motioneye.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.motioneye.MotionEyeClient",
+ return_value=mock_client,
+ ),
+ patch(
+ "homeassistant.components.motioneye.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
@@ -462,12 +474,15 @@ async def test_options(hass: HomeAssistant) -> None:
config_entry = create_mock_motioneye_config_entry(hass)
client = create_mock_motioneye_client()
- with patch(
- "homeassistant.components.motioneye.MotionEyeClient",
- return_value=client,
- ), patch(
- "homeassistant.components.motioneye.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.motioneye.MotionEyeClient",
+ return_value=client,
+ ),
+ patch(
+ "homeassistant.components.motioneye.async_setup_entry",
+ return_value=True,
+ ),
):
await hass.async_block_till_done()
@@ -495,13 +510,16 @@ async def test_advanced_options(hass: HomeAssistant) -> None:
config_entry = create_mock_motioneye_config_entry(hass)
mock_client = create_mock_motioneye_client()
- with patch(
- "homeassistant.components.motioneye.MotionEyeClient",
- return_value=mock_client,
- ) as mock_setup, patch(
- "homeassistant.components.motioneye.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.motioneye.MotionEyeClient",
+ return_value=mock_client,
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.motioneye.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
await hass.async_block_till_done()
result = await hass.config_entries.options.async_init(
diff --git a/tests/components/motioneye/test_web_hooks.py b/tests/components/motioneye/test_web_hooks.py
index a828e5964d0..fae7fccbb6d 100644
--- a/tests/components/motioneye/test_web_hooks.py
+++ b/tests/components/motioneye/test_web_hooks.py
@@ -222,18 +222,18 @@ async def test_setup_camera_with_correct_webhook(
cameras = copy.deepcopy(TEST_CAMERAS)
cameras[KEY_CAMERAS][0][KEY_WEB_HOOK_NOTIFICATIONS_ENABLED] = True
- cameras[KEY_CAMERAS][0][
- KEY_WEB_HOOK_NOTIFICATIONS_HTTP_METHOD
- ] = KEY_HTTP_METHOD_POST_JSON
+ cameras[KEY_CAMERAS][0][KEY_WEB_HOOK_NOTIFICATIONS_HTTP_METHOD] = (
+ KEY_HTTP_METHOD_POST_JSON
+ )
cameras[KEY_CAMERAS][0][KEY_WEB_HOOK_NOTIFICATIONS_URL] = (
"https://internal.url"
+ URL_WEBHOOK_PATH.format(webhook_id=config_entry.data[CONF_WEBHOOK_ID])
+ f"?{WEB_HOOK_MOTION_DETECTED_QUERY_STRING}&device_id={device.id}"
)
cameras[KEY_CAMERAS][0][KEY_WEB_HOOK_STORAGE_ENABLED] = True
- cameras[KEY_CAMERAS][0][
- KEY_WEB_HOOK_STORAGE_HTTP_METHOD
- ] = KEY_HTTP_METHOD_POST_JSON
+ cameras[KEY_CAMERAS][0][KEY_WEB_HOOK_STORAGE_HTTP_METHOD] = (
+ KEY_HTTP_METHOD_POST_JSON
+ )
cameras[KEY_CAMERAS][0][KEY_WEB_HOOK_STORAGE_URL] = (
"https://internal.url"
+ URL_WEBHOOK_PATH.format(webhook_id=config_entry.data[CONF_WEBHOOK_ID])
diff --git a/tests/components/mqtt/test_alarm_control_panel.py b/tests/components/mqtt/test_alarm_control_panel.py
index 055724a4659..ff78d96d37e 100644
--- a/tests/components/mqtt/test_alarm_control_panel.py
+++ b/tests/components/mqtt/test_alarm_control_panel.py
@@ -1332,9 +1332,13 @@ async def test_reload_after_invalid_config(
},
]
}
- with patch(
- "homeassistant.config.load_yaml_config_file", return_value=invalid_config
- ), pytest.raises(HomeAssistantError):
+ with (
+ patch(
+ "homeassistant.config.load_yaml_config_file",
+ return_value=invalid_config,
+ ),
+ pytest.raises(HomeAssistantError),
+ ):
await hass.services.async_call(
"mqtt",
SERVICE_RELOAD,
diff --git a/tests/components/mqtt/test_common.py b/tests/components/mqtt/test_common.py
index 6d9f56c531e..9dc52871529 100644
--- a/tests/components/mqtt/test_common.py
+++ b/tests/components/mqtt/test_common.py
@@ -385,9 +385,10 @@ async def help_test_default_availability_list_single(
]
config[mqtt.DOMAIN][domain]["availability_topic"] = "availability-topic"
- with patch(
- "homeassistant.config.load_yaml_config_file", return_value=config
- ), suppress(vol.MultipleInvalid):
+ with (
+ patch("homeassistant.config.load_yaml_config_file", return_value=config),
+ suppress(vol.MultipleInvalid),
+ ):
await mqtt_mock_entry()
assert (
@@ -590,9 +591,9 @@ async def help_test_setting_attribute_with_template(
# Add JSON attributes settings to config
config = copy.deepcopy(config)
config[mqtt.DOMAIN][domain]["json_attributes_topic"] = "attr-topic"
- config[mqtt.DOMAIN][domain][
- "json_attributes_template"
- ] = "{{ value_json['Timer1'] | tojson }}"
+ config[mqtt.DOMAIN][domain]["json_attributes_template"] = (
+ "{{ value_json['Timer1'] | tojson }}"
+ )
with patch("homeassistant.config.load_yaml_config_file", return_value=config):
await mqtt_mock_entry()
@@ -1698,9 +1699,9 @@ async def help_test_publishing_with_custom_encoding(
if test_data["encoding"] is not None:
test_config_setup["encoding"] = test_data["encoding"]
if template and test_data["cmd_tpl"]:
- test_config_setup[
- template
- ] = f"{{{{ (('%.1f'|format({tpl_par}))[0] if is_number({tpl_par}) else {tpl_par}[0]) | ord | pack('b') }}}}"
+ test_config_setup[template] = (
+ f"{{{{ (('%.1f'|format({tpl_par}))[0] if is_number({tpl_par}) else {tpl_par}[0]) | ord | pack('b') }}}}"
+ )
setup_config.append(test_config_setup)
# setup service data
diff --git a/tests/components/mqtt/test_config_flow.py b/tests/components/mqtt/test_config_flow.py
index 329d6077300..719117e59a9 100644
--- a/tests/components/mqtt/test_config_flow.py
+++ b/tests/components/mqtt/test_config_flow.py
@@ -55,13 +55,15 @@ def mock_client_key_check_fail() -> Generator[MagicMock, None, None]:
@pytest.fixture
def mock_ssl_context() -> Generator[dict[str, MagicMock], None, None]:
"""Mock the SSL context used to load the cert chain and to load verify locations."""
- with patch(
- "homeassistant.components.mqtt.config_flow.SSLContext"
- ) as mock_context, patch(
- "homeassistant.components.mqtt.config_flow.load_pem_private_key"
- ) as mock_key_check, patch(
- "homeassistant.components.mqtt.config_flow.load_pem_x509_certificate"
- ) as mock_cert_check:
+ with (
+ patch("homeassistant.components.mqtt.config_flow.SSLContext") as mock_context,
+ patch(
+ "homeassistant.components.mqtt.config_flow.load_pem_private_key"
+ ) as mock_key_check,
+ patch(
+ "homeassistant.components.mqtt.config_flow.load_pem_x509_certificate"
+ ) as mock_cert_check,
+ ):
yield {
"context": mock_context,
"load_pem_x509_certificate": mock_cert_check,
@@ -123,8 +125,9 @@ def mock_try_connection_time_out() -> Generator[MagicMock, None, None]:
"""Mock the try connection method with a time out."""
# Patch prevent waiting 5 sec for a timeout
- with patch("paho.mqtt.client.Client") as mock_client, patch(
- "homeassistant.components.mqtt.config_flow.MQTT_TIMEOUT", 0
+ with (
+ patch("paho.mqtt.client.Client") as mock_client,
+ patch("homeassistant.components.mqtt.config_flow.MQTT_TIMEOUT", 0),
):
mock_client().loop_start = lambda *args: 1
yield mock_client()
diff --git a/tests/components/mqtt/test_discovery.py b/tests/components/mqtt/test_discovery.py
index baa3542a22d..24891895fad 100644
--- a/tests/components/mqtt/test_discovery.py
+++ b/tests/components/mqtt/test_discovery.py
@@ -1506,8 +1506,9 @@ async def test_mqtt_integration_discovery_subscribe_unsubscribe(
wait_unsub.set()
return (0, 0)
- with mock_config_flow("comp", TestFlow), patch.object(
- mqtt_client_mock, "unsubscribe", side_effect=_mock_unsubscribe
+ with (
+ mock_config_flow("comp", TestFlow),
+ patch.object(mqtt_client_mock, "unsubscribe", side_effect=_mock_unsubscribe),
):
async_fire_mqtt_message(hass, "comp/discovery/bla/config", "")
await wait_unsub.wait()
diff --git a/tests/components/mqtt/test_event.py b/tests/components/mqtt/test_event.py
index 488612a0fa3..64a2003606c 100644
--- a/tests/components/mqtt/test_event.py
+++ b/tests/components/mqtt/test_event.py
@@ -463,12 +463,12 @@ async def test_discovery_update_event_template(
config2["name"] = "Milk"
config1["state_topic"] = "event/state1"
config2["state_topic"] = "event/state1"
- config1[
- "value_template"
- ] = '{"event_type": "press", "val": "{{ value_json.val | int }}"}'
- config2[
- "value_template"
- ] = '{"event_type": "press", "val": "{{ value_json.val | int * 2 }}"}'
+ config1["value_template"] = (
+ '{"event_type": "press", "val": "{{ value_json.val | int }}"}'
+ )
+ config2["value_template"] = (
+ '{"event_type": "press", "val": "{{ value_json.val | int * 2 }}"}'
+ )
async_fire_mqtt_message(hass, "homeassistant/event/bla/config", json.dumps(config1))
await hass.async_block_till_done()
diff --git a/tests/components/mullvad/test_config_flow.py b/tests/components/mullvad/test_config_flow.py
index 2154513d6d1..e1e6570fa67 100644
--- a/tests/components/mullvad/test_config_flow.py
+++ b/tests/components/mullvad/test_config_flow.py
@@ -21,12 +21,15 @@ async def test_form_user(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert not result["errors"]
- with patch(
- "homeassistant.components.mullvad.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.mullvad.config_flow.MullvadAPI"
- ) as mock_mullvad_api:
+ with (
+ patch(
+ "homeassistant.components.mullvad.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.mullvad.config_flow.MullvadAPI"
+ ) as mock_mullvad_api,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{},
diff --git a/tests/components/mutesync/test_config_flow.py b/tests/components/mutesync/test_config_flow.py
index 18cc7e68aa4..f667671da74 100644
--- a/tests/components/mutesync/test_config_flow.py
+++ b/tests/components/mutesync/test_config_flow.py
@@ -19,13 +19,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] is None
- with patch(
- "mutesync.authenticate",
- return_value="bla",
- ), patch(
- "homeassistant.components.mutesync.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "mutesync.authenticate",
+ return_value="bla",
+ ),
+ patch(
+ "homeassistant.components.mutesync.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
diff --git a/tests/components/mysensors/conftest.py b/tests/components/mysensors/conftest.py
index a892730ef6a..bcf852e1368 100644
--- a/tests/components/mysensors/conftest.py
+++ b/tests/components/mysensors/conftest.py
@@ -55,14 +55,17 @@ async def serial_transport_fixture(
is_serial_port: MagicMock,
) -> AsyncGenerator[dict[int, Sensor], None]:
"""Mock a serial transport."""
- with patch(
- "mysensors.gateway_serial.AsyncTransport", autospec=True
- ) as transport_class, patch("mysensors.task.OTAFirmware", autospec=True), patch(
- "mysensors.task.load_fw", autospec=True
- ), patch(
- "mysensors.task.Persistence",
- autospec=True,
- ) as persistence_class:
+ with (
+ patch(
+ "mysensors.gateway_serial.AsyncTransport", autospec=True
+ ) as transport_class,
+ patch("mysensors.task.OTAFirmware", autospec=True),
+ patch("mysensors.task.load_fw", autospec=True),
+ patch(
+ "mysensors.task.Persistence",
+ autospec=True,
+ ) as persistence_class,
+ ):
persistence = persistence_class.return_value
mock_gateway_features(persistence, transport_class, gateway_nodes)
diff --git a/tests/components/mysensors/test_config_flow.py b/tests/components/mysensors/test_config_flow.py
index 2506e350e89..f532d09c6bf 100644
--- a/tests/components/mysensors/test_config_flow.py
+++ b/tests/components/mysensors/test_config_flow.py
@@ -113,15 +113,20 @@ async def test_config_serial(hass: HomeAssistant) -> None:
step = await get_form(hass, CONF_GATEWAY_TYPE_SERIAL, "gw_serial")
flow_id = step["flow_id"]
- with patch( # mock is_serial_port because otherwise the test will be platform dependent (/dev/ttyACMx vs COMx)
- "homeassistant.components.mysensors.config_flow.is_serial_port",
- return_value=True,
- ), patch(
- "homeassistant.components.mysensors.config_flow.try_connect", return_value=True
- ), patch(
- "homeassistant.components.mysensors.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch( # mock is_serial_port because otherwise the test will be platform dependent (/dev/ttyACMx vs COMx)
+ "homeassistant.components.mysensors.config_flow.is_serial_port",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.mysensors.config_flow.try_connect",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.mysensors.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
flow_id,
{
@@ -150,12 +155,16 @@ async def test_config_tcp(hass: HomeAssistant) -> None:
step = await get_form(hass, CONF_GATEWAY_TYPE_TCP, "gw_tcp")
flow_id = step["flow_id"]
- with patch(
- "homeassistant.components.mysensors.config_flow.try_connect", return_value=True
- ), patch(
- "homeassistant.components.mysensors.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.mysensors.config_flow.try_connect",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.mysensors.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
flow_id,
{
@@ -184,12 +193,16 @@ async def test_fail_to_connect(hass: HomeAssistant) -> None:
step = await get_form(hass, CONF_GATEWAY_TYPE_TCP, "gw_tcp")
flow_id = step["flow_id"]
- with patch(
- "homeassistant.components.mysensors.config_flow.try_connect", return_value=False
- ), patch(
- "homeassistant.components.mysensors.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.mysensors.config_flow.try_connect",
+ return_value=False,
+ ),
+ patch(
+ "homeassistant.components.mysensors.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
flow_id,
{
@@ -341,15 +354,20 @@ async def test_config_invalid(
step = await get_form(hass, gateway_type, expected_step_id)
flow_id = step["flow_id"]
- with patch(
- "homeassistant.components.mysensors.config_flow.try_connect", return_value=True
- ), patch(
- "homeassistant.components.mysensors.gateway.socket.getaddrinfo",
- side_effect=OSError,
- ), patch(
- "homeassistant.components.mysensors.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.mysensors.config_flow.try_connect",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.mysensors.gateway.socket.getaddrinfo",
+ side_effect=OSError,
+ ),
+ patch(
+ "homeassistant.components.mysensors.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
flow_id,
user_input,
@@ -653,11 +671,16 @@ async def test_duplicate(
) -> None:
"""Test duplicate detection."""
- with patch("sys.platform", "win32"), patch(
- "homeassistant.components.mysensors.config_flow.try_connect", return_value=True
- ), patch(
- "homeassistant.components.mysensors.async_setup_entry",
- return_value=True,
+ with (
+ patch("sys.platform", "win32"),
+ patch(
+ "homeassistant.components.mysensors.config_flow.try_connect",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.mysensors.async_setup_entry",
+ return_value=True,
+ ),
):
MockConfigEntry(domain=DOMAIN, data=first_input).add_to_hass(hass)
diff --git a/tests/components/mystrom/test_init.py b/tests/components/mystrom/test_init.py
index 0c49eecf88d..0304a0eb270 100644
--- a/tests/components/mystrom/test_init.py
+++ b/tests/components/mystrom/test_init.py
@@ -27,15 +27,21 @@ async def init_integration(
device_type: int,
) -> None:
"""Initialize integration for testing."""
- with patch(
- "pymystrom.get_device_info",
- side_effect=AsyncMock(return_value=get_default_device_response(device_type)),
- ), patch(
- "homeassistant.components.mystrom._get_mystrom_bulb",
- return_value=MyStromBulbMock("6001940376EB", get_default_bulb_state()),
- ), patch(
- "homeassistant.components.mystrom._get_mystrom_switch",
- return_value=MyStromSwitchMock(get_default_switch_state()),
+ with (
+ patch(
+ "pymystrom.get_device_info",
+ side_effect=AsyncMock(
+ return_value=get_default_device_response(device_type)
+ ),
+ ),
+ patch(
+ "homeassistant.components.mystrom._get_mystrom_bulb",
+ return_value=MyStromBulbMock("6001940376EB", get_default_bulb_state()),
+ ),
+ patch(
+ "homeassistant.components.mystrom._get_mystrom_switch",
+ return_value=MyStromSwitchMock(get_default_switch_state()),
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -91,15 +97,18 @@ async def test_init_of_unknown_bulb(
hass: HomeAssistant, config_entry: MockConfigEntry
) -> None:
"""Test the initialization of a unknown myStrom bulb."""
- with patch(
- "pymystrom.get_device_info",
- side_effect=AsyncMock(return_value={"type": 102, "mac": DEVICE_MAC}),
- ), patch("pymystrom.bulb.MyStromBulb.get_state", return_value={}), patch(
- "pymystrom.bulb.MyStromBulb.bulb_type", "new_type"
- ), patch(
- "pymystrom.bulb.MyStromBulb.mac",
- new_callable=PropertyMock,
- return_value=DEVICE_MAC,
+ with (
+ patch(
+ "pymystrom.get_device_info",
+ side_effect=AsyncMock(return_value={"type": 102, "mac": DEVICE_MAC}),
+ ),
+ patch("pymystrom.bulb.MyStromBulb.get_state", return_value={}),
+ patch("pymystrom.bulb.MyStromBulb.bulb_type", "new_type"),
+ patch(
+ "pymystrom.bulb.MyStromBulb.mac",
+ new_callable=PropertyMock,
+ return_value=DEVICE_MAC,
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -125,11 +134,13 @@ async def test_init_cannot_connect_because_of_device_info(
hass: HomeAssistant, config_entry: MockConfigEntry
) -> None:
"""Test error handling for failing get_device_info."""
- with patch(
- "pymystrom.get_device_info",
- side_effect=MyStromConnectionError(),
- ), patch("pymystrom.switch.MyStromSwitch.get_state", return_value={}), patch(
- "pymystrom.bulb.MyStromBulb.get_state", return_value={}
+ with (
+ patch(
+ "pymystrom.get_device_info",
+ side_effect=MyStromConnectionError(),
+ ),
+ patch("pymystrom.switch.MyStromSwitch.get_state", return_value={}),
+ patch("pymystrom.bulb.MyStromBulb.get_state", return_value={}),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -141,13 +152,18 @@ async def test_init_cannot_connect_because_of_get_state(
hass: HomeAssistant, config_entry: MockConfigEntry
) -> None:
"""Test error handling for failing get_state."""
- with patch(
- "pymystrom.get_device_info",
- side_effect=AsyncMock(return_value=get_default_device_response(101)),
- ), patch(
- "pymystrom.switch.MyStromSwitch.get_state", side_effect=MyStromConnectionError()
- ), patch(
- "pymystrom.bulb.MyStromBulb.get_state", side_effect=MyStromConnectionError()
+ with (
+ patch(
+ "pymystrom.get_device_info",
+ side_effect=AsyncMock(return_value=get_default_device_response(101)),
+ ),
+ patch(
+ "pymystrom.switch.MyStromSwitch.get_state",
+ side_effect=MyStromConnectionError(),
+ ),
+ patch(
+ "pymystrom.bulb.MyStromBulb.get_state", side_effect=MyStromConnectionError()
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/nam/__init__.py b/tests/components/nam/__init__.py
index 3d95d6cc7e0..0484fc12bd6 100644
--- a/tests/components/nam/__init__.py
+++ b/tests/components/nam/__init__.py
@@ -58,9 +58,12 @@ async def init_integration(hass, co2_sensor=True) -> MockConfigEntry:
update_response = Mock(json=AsyncMock(return_value=nam_data))
- with patch("homeassistant.components.nam.NettigoAirMonitor.initialize"), patch(
- "homeassistant.components.nam.NettigoAirMonitor._async_http_request",
- return_value=update_response,
+ with (
+ patch("homeassistant.components.nam.NettigoAirMonitor.initialize"),
+ patch(
+ "homeassistant.components.nam.NettigoAirMonitor._async_http_request",
+ return_value=update_response,
+ ),
):
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
diff --git a/tests/components/nam/test_button.py b/tests/components/nam/test_button.py
index 32c69c91202..39c37d57f89 100644
--- a/tests/components/nam/test_button.py
+++ b/tests/components/nam/test_button.py
@@ -30,9 +30,12 @@ async def test_button_press(hass: HomeAssistant) -> None:
await init_integration(hass)
now = dt_util.utcnow()
- with patch(
- "homeassistant.components.nam.NettigoAirMonitor.async_restart"
- ) as mock_restart, patch("homeassistant.core.dt_util.utcnow", return_value=now):
+ with (
+ patch(
+ "homeassistant.components.nam.NettigoAirMonitor.async_restart"
+ ) as mock_restart,
+ patch("homeassistant.core.dt_util.utcnow", return_value=now),
+ ):
await hass.services.async_call(
BUTTON_DOMAIN,
"press",
diff --git a/tests/components/nam/test_config_flow.py b/tests/components/nam/test_config_flow.py
index 9081bfbb7b5..71bf3cf1525 100644
--- a/tests/components/nam/test_config_flow.py
+++ b/tests/components/nam/test_config_flow.py
@@ -38,15 +38,19 @@ async def test_form_create_entry_without_auth(hass: HomeAssistant) -> None:
assert result["step_id"] == "user"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials",
- return_value=DEVICE_CONFIG,
- ), patch(
- "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address",
- return_value="aa:bb:cc:dd:ee:ff",
- ), patch(
- "homeassistant.components.nam.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials",
+ return_value=DEVICE_CONFIG,
+ ),
+ patch(
+ "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address",
+ return_value="aa:bb:cc:dd:ee:ff",
+ ),
+ patch(
+ "homeassistant.components.nam.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
VALID_CONFIG,
@@ -68,15 +72,19 @@ async def test_form_create_entry_with_auth(hass: HomeAssistant) -> None:
assert result["step_id"] == "user"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials",
- return_value=DEVICE_CONFIG_AUTH,
- ), patch(
- "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address",
- return_value="aa:bb:cc:dd:ee:ff",
- ), patch(
- "homeassistant.components.nam.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials",
+ return_value=DEVICE_CONFIG_AUTH,
+ ),
+ patch(
+ "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address",
+ return_value="aa:bb:cc:dd:ee:ff",
+ ),
+ patch(
+ "homeassistant.components.nam.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
VALID_CONFIG,
@@ -109,12 +117,15 @@ async def test_reauth_successful(hass: HomeAssistant) -> None:
)
entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials",
- return_value=DEVICE_CONFIG_AUTH,
- ), patch(
- "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address",
- return_value="aa:bb:cc:dd:ee:ff",
+ with (
+ patch(
+ "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials",
+ return_value=DEVICE_CONFIG_AUTH,
+ ),
+ patch(
+ "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address",
+ return_value="aa:bb:cc:dd:ee:ff",
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -178,12 +189,15 @@ async def test_reauth_unsuccessful(hass: HomeAssistant) -> None:
async def test_form_with_auth_errors(hass: HomeAssistant, error) -> None:
"""Test we handle errors when auth is required."""
exc, base_error = error
- with patch(
- "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials",
- side_effect=AuthFailedError("Auth Error"),
- ), patch(
- "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address",
- return_value="aa:bb:cc:dd:ee:ff",
+ with (
+ patch(
+ "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials",
+ side_effect=AuthFailedError("Auth Error"),
+ ),
+ patch(
+ "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address",
+ return_value="aa:bb:cc:dd:ee:ff",
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -232,12 +246,15 @@ async def test_form_errors(hass: HomeAssistant, error) -> None:
async def test_form_abort(hass: HomeAssistant) -> None:
"""Test we handle abort after error."""
- with patch(
- "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials",
- return_value=DEVICE_CONFIG,
- ), patch(
- "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address",
- side_effect=CannotGetMacError("Cannot get MAC address from device"),
+ with (
+ patch(
+ "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials",
+ return_value=DEVICE_CONFIG,
+ ),
+ patch(
+ "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address",
+ side_effect=CannotGetMacError("Cannot get MAC address from device"),
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -260,12 +277,15 @@ async def test_form_already_configured(hass: HomeAssistant) -> None:
DOMAIN, context={"source": SOURCE_USER}
)
- with patch(
- "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials",
- return_value=DEVICE_CONFIG,
- ), patch(
- "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address",
- return_value="aa:bb:cc:dd:ee:ff",
+ with (
+ patch(
+ "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials",
+ return_value=DEVICE_CONFIG,
+ ),
+ patch(
+ "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address",
+ return_value="aa:bb:cc:dd:ee:ff",
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -281,12 +301,15 @@ async def test_form_already_configured(hass: HomeAssistant) -> None:
async def test_zeroconf(hass: HomeAssistant) -> None:
"""Test we get the form."""
- with patch(
- "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials",
- return_value=DEVICE_CONFIG,
- ), patch(
- "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address",
- return_value="aa:bb:cc:dd:ee:ff",
+ with (
+ patch(
+ "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials",
+ return_value=DEVICE_CONFIG,
+ ),
+ patch(
+ "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address",
+ return_value="aa:bb:cc:dd:ee:ff",
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -322,12 +345,15 @@ async def test_zeroconf(hass: HomeAssistant) -> None:
async def test_zeroconf_with_auth(hass: HomeAssistant) -> None:
"""Test that the zeroconf step with auth works."""
- with patch(
- "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials",
- side_effect=AuthFailedError("Auth Error"),
- ), patch(
- "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address",
- return_value="aa:bb:cc:dd:ee:ff",
+ with (
+ patch(
+ "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials",
+ side_effect=AuthFailedError("Auth Error"),
+ ),
+ patch(
+ "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address",
+ return_value="aa:bb:cc:dd:ee:ff",
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -345,15 +371,19 @@ async def test_zeroconf_with_auth(hass: HomeAssistant) -> None:
assert result["errors"] == {}
assert context["title_placeholders"]["host"] == "10.10.2.3"
- with patch(
- "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials",
- return_value=DEVICE_CONFIG_AUTH,
- ), patch(
- "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address",
- return_value="aa:bb:cc:dd:ee:ff",
- ), patch(
- "homeassistant.components.nam.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials",
+ return_value=DEVICE_CONFIG_AUTH,
+ ),
+ patch(
+ "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address",
+ return_value="aa:bb:cc:dd:ee:ff",
+ ),
+ patch(
+ "homeassistant.components.nam.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
VALID_AUTH,
diff --git a/tests/components/nam/test_init.py b/tests/components/nam/test_init.py
index 372c6fb8e66..8b8c3a4835a 100644
--- a/tests/components/nam/test_init.py
+++ b/tests/components/nam/test_init.py
@@ -54,9 +54,12 @@ async def test_config_not_ready_while_checking_credentials(hass: HomeAssistant)
)
entry.add_to_hass(hass)
- with patch("homeassistant.components.nam.NettigoAirMonitor.initialize"), patch(
- "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials",
- side_effect=ApiError("API Error"),
+ with (
+ patch("homeassistant.components.nam.NettigoAirMonitor.initialize"),
+ patch(
+ "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials",
+ side_effect=ApiError("API Error"),
+ ),
):
await hass.config_entries.async_setup(entry.entry_id)
assert entry.state is ConfigEntryState.SETUP_RETRY
diff --git a/tests/components/nam/test_sensor.py b/tests/components/nam/test_sensor.py
index 44bf6552042..c88a34ae497 100644
--- a/tests/components/nam/test_sensor.py
+++ b/tests/components/nam/test_sensor.py
@@ -507,9 +507,12 @@ async def test_incompleta_data_after_device_restart(hass: HomeAssistant) -> None
future = utcnow() + timedelta(minutes=6)
update_response = Mock(json=AsyncMock(return_value=INCOMPLETE_NAM_DATA))
- with patch("homeassistant.components.nam.NettigoAirMonitor.initialize"), patch(
- "homeassistant.components.nam.NettigoAirMonitor._async_http_request",
- return_value=update_response,
+ with (
+ patch("homeassistant.components.nam.NettigoAirMonitor.initialize"),
+ patch(
+ "homeassistant.components.nam.NettigoAirMonitor._async_http_request",
+ return_value=update_response,
+ ),
):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
@@ -529,9 +532,12 @@ async def test_availability(hass: HomeAssistant) -> None:
assert state.state == "7.6"
future = utcnow() + timedelta(minutes=6)
- with patch("homeassistant.components.nam.NettigoAirMonitor.initialize"), patch(
- "homeassistant.components.nam.NettigoAirMonitor._async_http_request",
- side_effect=ApiError("API Error"),
+ with (
+ patch("homeassistant.components.nam.NettigoAirMonitor.initialize"),
+ patch(
+ "homeassistant.components.nam.NettigoAirMonitor._async_http_request",
+ side_effect=ApiError("API Error"),
+ ),
):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
@@ -542,9 +548,12 @@ async def test_availability(hass: HomeAssistant) -> None:
future = utcnow() + timedelta(minutes=12)
update_response = Mock(json=AsyncMock(return_value=nam_data))
- with patch("homeassistant.components.nam.NettigoAirMonitor.initialize"), patch(
- "homeassistant.components.nam.NettigoAirMonitor._async_http_request",
- return_value=update_response,
+ with (
+ patch("homeassistant.components.nam.NettigoAirMonitor.initialize"),
+ patch(
+ "homeassistant.components.nam.NettigoAirMonitor._async_http_request",
+ return_value=update_response,
+ ),
):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
@@ -562,10 +571,13 @@ async def test_manual_update_entity(hass: HomeAssistant) -> None:
await async_setup_component(hass, "homeassistant", {})
update_response = Mock(json=AsyncMock(return_value=nam_data))
- with patch("homeassistant.components.nam.NettigoAirMonitor.initialize"), patch(
- "homeassistant.components.nam.NettigoAirMonitor._async_http_request",
- return_value=update_response,
- ) as mock_get_data:
+ with (
+ patch("homeassistant.components.nam.NettigoAirMonitor.initialize"),
+ patch(
+ "homeassistant.components.nam.NettigoAirMonitor._async_http_request",
+ return_value=update_response,
+ ) as mock_get_data,
+ ):
await hass.services.async_call(
"homeassistant",
"update_entity",
diff --git a/tests/components/nanoleaf/test_config_flow.py b/tests/components/nanoleaf/test_config_flow.py
index 2f3620a6a12..5fe32c81eba 100644
--- a/tests/components/nanoleaf/test_config_flow.py
+++ b/tests/components/nanoleaf/test_config_flow.py
@@ -109,11 +109,14 @@ async def test_user_error_setup_finish(
assert result2["type"] == "form"
assert result2["step_id"] == "link"
- with patch(
- "homeassistant.components.nanoleaf.config_flow.Nanoleaf.authorize",
- ), patch(
- "homeassistant.components.nanoleaf.config_flow.Nanoleaf.get_info",
- side_effect=error,
+ with (
+ patch(
+ "homeassistant.components.nanoleaf.config_flow.Nanoleaf.authorize",
+ ),
+ patch(
+ "homeassistant.components.nanoleaf.config_flow.Nanoleaf.get_info",
+ side_effect=error,
+ ),
):
result3 = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result3["type"] == "abort"
@@ -124,12 +127,15 @@ async def test_user_not_authorizing_new_tokens_user_step_link_step(
hass: HomeAssistant,
) -> None:
"""Test we handle NotAuthorizingNewTokens in user step and link step."""
- with patch(
- "homeassistant.components.nanoleaf.config_flow.Nanoleaf",
- return_value=_mock_nanoleaf(authorize_error=Unauthorized()),
- ) as mock_nanoleaf, patch(
- "homeassistant.components.nanoleaf.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.nanoleaf.config_flow.Nanoleaf",
+ return_value=_mock_nanoleaf(authorize_error=Unauthorized()),
+ ) as mock_nanoleaf,
+ patch(
+ "homeassistant.components.nanoleaf.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
@@ -229,11 +235,14 @@ async def test_discovery_link_unavailable(
hass: HomeAssistant, source: type, type_in_discovery_info: str
) -> None:
"""Test discovery and abort if device is unavailable."""
- with patch(
- "homeassistant.components.nanoleaf.config_flow.Nanoleaf.get_info",
- ), patch(
- "homeassistant.components.nanoleaf.config_flow.load_json_object",
- return_value={},
+ with (
+ patch(
+ "homeassistant.components.nanoleaf.config_flow.Nanoleaf.get_info",
+ ),
+ patch(
+ "homeassistant.components.nanoleaf.config_flow.load_json_object",
+ return_value={},
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -277,12 +286,15 @@ async def test_reauth(hass: HomeAssistant) -> None:
)
entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.nanoleaf.config_flow.Nanoleaf",
- return_value=_mock_nanoleaf(),
- ), patch(
- "homeassistant.components.nanoleaf.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.nanoleaf.config_flow.Nanoleaf",
+ return_value=_mock_nanoleaf(),
+ ),
+ patch(
+ "homeassistant.components.nanoleaf.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -354,22 +366,28 @@ async def test_import_discovery_integration(
Test removing the .nanoleaf_conf file if it was the only device in the file.
Test updating the .nanoleaf_conf file if it was not the only device in the file.
"""
- with patch(
- "homeassistant.components.nanoleaf.config_flow.load_json_object",
- return_value=dict(nanoleaf_conf_file),
- ), patch(
- "homeassistant.components.nanoleaf.config_flow.Nanoleaf",
- return_value=_mock_nanoleaf(TEST_HOST, TEST_TOKEN),
- ), patch(
- "homeassistant.components.nanoleaf.config_flow.save_json",
- return_value=None,
- ) as mock_save_json, patch(
- "homeassistant.components.nanoleaf.config_flow.os.remove",
- return_value=None,
- ) as mock_remove, patch(
- "homeassistant.components.nanoleaf.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.nanoleaf.config_flow.load_json_object",
+ return_value=dict(nanoleaf_conf_file),
+ ),
+ patch(
+ "homeassistant.components.nanoleaf.config_flow.Nanoleaf",
+ return_value=_mock_nanoleaf(TEST_HOST, TEST_TOKEN),
+ ),
+ patch(
+ "homeassistant.components.nanoleaf.config_flow.save_json",
+ return_value=None,
+ ) as mock_save_json,
+ patch(
+ "homeassistant.components.nanoleaf.config_flow.os.remove",
+ return_value=None,
+ ) as mock_remove,
+ patch(
+ "homeassistant.components.nanoleaf.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": source},
@@ -404,16 +422,20 @@ async def test_import_discovery_integration(
async def test_ssdp_discovery(hass: HomeAssistant) -> None:
"""Test SSDP discovery."""
- with patch(
- "homeassistant.components.nanoleaf.config_flow.load_json_object",
- return_value={},
- ), patch(
- "homeassistant.components.nanoleaf.config_flow.Nanoleaf",
- return_value=_mock_nanoleaf(TEST_HOST, TEST_TOKEN),
- ), patch(
- "homeassistant.components.nanoleaf.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.nanoleaf.config_flow.load_json_object",
+ return_value={},
+ ),
+ patch(
+ "homeassistant.components.nanoleaf.config_flow.Nanoleaf",
+ return_value=_mock_nanoleaf(TEST_HOST, TEST_TOKEN),
+ ),
+ patch(
+ "homeassistant.components.nanoleaf.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_SSDP},
diff --git a/tests/components/nest/test_events.py b/tests/components/nest/test_events.py
index 1bd01f699cf..caa86a3d93b 100644
--- a/tests/components/nest/test_events.py
+++ b/tests/components/nest/test_events.py
@@ -461,9 +461,12 @@ async def test_structure_update_event(
},
auth=None,
)
- with patch("homeassistant.components.nest.PLATFORMS", [PLATFORM]), patch(
- "homeassistant.components.nest.api.GoogleNestSubscriber",
- return_value=subscriber,
+ with (
+ patch("homeassistant.components.nest.PLATFORMS", [PLATFORM]),
+ patch(
+ "homeassistant.components.nest.api.GoogleNestSubscriber",
+ return_value=subscriber,
+ ),
):
await subscriber.async_receive_event(message)
await hass.async_block_till_done()
diff --git a/tests/components/nest/test_init.py b/tests/components/nest/test_init.py
index 2f11aed7969..3cac8649c9c 100644
--- a/tests/components/nest/test_init.py
+++ b/tests/components/nest/test_init.py
@@ -123,11 +123,12 @@ async def test_setup_device_manager_failure(
hass: HomeAssistant, caplog, setup_base_platform
) -> None:
"""Test device manager api failure."""
- with patch(
- "homeassistant.components.nest.api.GoogleNestSubscriber.start_async"
- ), patch(
- "homeassistant.components.nest.api.GoogleNestSubscriber.async_get_device_manager",
- side_effect=ApiException(),
+ with (
+ patch("homeassistant.components.nest.api.GoogleNestSubscriber.start_async"),
+ patch(
+ "homeassistant.components.nest.api.GoogleNestSubscriber.async_get_device_manager",
+ side_effect=ApiException(),
+ ),
):
await setup_base_platform()
@@ -227,11 +228,12 @@ async def test_remove_entry(
assert entry.data.get("subscriber_id") == SUBSCRIBER_ID
assert entry.data.get("project_id") == PROJECT_ID
- with patch(
- "homeassistant.components.nest.api.GoogleNestSubscriber.subscriber_id"
- ), patch(
- "homeassistant.components.nest.api.GoogleNestSubscriber.delete_subscription",
- ) as delete:
+ with (
+ patch("homeassistant.components.nest.api.GoogleNestSubscriber.subscriber_id"),
+ patch(
+ "homeassistant.components.nest.api.GoogleNestSubscriber.delete_subscription",
+ ) as delete,
+ ):
assert await hass.config_entries.async_remove(entry.entry_id)
assert delete.called
diff --git a/tests/components/netatmo/common.py b/tests/components/netatmo/common.py
index ffaddd73bb3..08c8679acf3 100644
--- a/tests/components/netatmo/common.py
+++ b/tests/components/netatmo/common.py
@@ -111,11 +111,13 @@ async def simulate_webhook(hass: HomeAssistant, webhook_id: str, response) -> No
@contextmanager
def selected_platforms(platforms: list[Platform]) -> AsyncMock:
"""Restrict loaded platforms to list given."""
- with patch(
- "homeassistant.components.netatmo.data_handler.PLATFORMS", platforms
- ), patch(
- "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
- ), patch(
- "homeassistant.components.netatmo.webhook_generate_url",
+ with (
+ patch("homeassistant.components.netatmo.data_handler.PLATFORMS", platforms),
+ patch(
+ "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
+ ),
+ patch(
+ "homeassistant.components.netatmo.webhook_generate_url",
+ ),
):
yield
diff --git a/tests/components/netatmo/test_camera.py b/tests/components/netatmo/test_camera.py
index 771bd62de1c..c7398d64e1d 100644
--- a/tests/components/netatmo/test_camera.py
+++ b/tests/components/netatmo/test_camera.py
@@ -382,9 +382,10 @@ async def test_service_set_camera_light_invalid_type(
"camera_light_mode": "on",
}
- with patch("pyatmo.home.Home.async_set_state") as mock_set_state, pytest.raises(
- HomeAssistantError
- ) as excinfo:
+ with (
+ patch("pyatmo.home.Home.async_set_state") as mock_set_state,
+ pytest.raises(HomeAssistantError) as excinfo,
+ ):
await hass.services.async_call(
"netatmo",
SERVICE_SET_CAMERA_LIGHT,
@@ -409,15 +410,18 @@ async def test_camera_reconnect_webhook(
fake_post_hits += 1
return await fake_post_request(*args, **kwargs)
- with patch(
- "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth"
- ) as mock_auth, patch(
- "homeassistant.components.netatmo.data_handler.PLATFORMS", ["camera"]
- ), patch(
- "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
- ), patch(
- "homeassistant.components.netatmo.webhook_generate_url",
- ) as mock_webhook:
+ with (
+ patch(
+ "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth"
+ ) as mock_auth,
+ patch("homeassistant.components.netatmo.data_handler.PLATFORMS", ["camera"]),
+ patch(
+ "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
+ ),
+ patch(
+ "homeassistant.components.netatmo.webhook_generate_url",
+ ) as mock_webhook,
+ ):
mock_auth.return_value.async_post_api_request.side_effect = fake_post
mock_auth.return_value.async_addwebhook.side_effect = AsyncMock()
mock_auth.return_value.async_dropwebhook.side_effect = AsyncMock()
@@ -505,14 +509,17 @@ async def test_setup_component_no_devices(
fake_post_hits += 1
return await fake_post_request(*args, **kwargs)
- with patch(
- "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth"
- ) as mock_auth, patch(
- "homeassistant.components.netatmo.data_handler.PLATFORMS", ["camera"]
- ), patch(
- "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
- ), patch(
- "homeassistant.components.netatmo.webhook_generate_url",
+ with (
+ patch(
+ "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth"
+ ) as mock_auth,
+ patch("homeassistant.components.netatmo.data_handler.PLATFORMS", ["camera"]),
+ patch(
+ "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
+ ),
+ patch(
+ "homeassistant.components.netatmo.webhook_generate_url",
+ ),
):
mock_auth.return_value.async_post_api_request.side_effect = fake_post_no_data
mock_auth.return_value.async_addwebhook.side_effect = AsyncMock()
@@ -545,14 +552,17 @@ async def test_camera_image_raises_exception(
return await fake_post_request(*args, **kwargs)
- with patch(
- "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth"
- ) as mock_auth, patch(
- "homeassistant.components.netatmo.data_handler.PLATFORMS", ["camera"]
- ), patch(
- "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
- ), patch(
- "homeassistant.components.netatmo.webhook_generate_url",
+ with (
+ patch(
+ "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth"
+ ) as mock_auth,
+ patch("homeassistant.components.netatmo.data_handler.PLATFORMS", ["camera"]),
+ patch(
+ "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
+ ),
+ patch(
+ "homeassistant.components.netatmo.webhook_generate_url",
+ ),
):
mock_auth.return_value.async_post_api_request.side_effect = fake_post
mock_auth.return_value.async_get_image.side_effect = fake_post
diff --git a/tests/components/netatmo/test_diagnostics.py b/tests/components/netatmo/test_diagnostics.py
index 7c781e7522c..48f021295e1 100644
--- a/tests/components/netatmo/test_diagnostics.py
+++ b/tests/components/netatmo/test_diagnostics.py
@@ -22,12 +22,16 @@ async def test_entry_diagnostics(
config_entry: MockConfigEntry,
) -> None:
"""Test config entry diagnostics."""
- with patch(
- "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth",
- ) as mock_auth, patch(
- "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
- ), patch(
- "homeassistant.components.netatmo.webhook_generate_url",
+ with (
+ patch(
+ "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth",
+ ) as mock_auth,
+ patch(
+ "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
+ ),
+ patch(
+ "homeassistant.components.netatmo.webhook_generate_url",
+ ),
):
mock_auth.return_value.async_post_api_request.side_effect = fake_post_request
mock_auth.return_value.async_addwebhook.side_effect = AsyncMock()
diff --git a/tests/components/netatmo/test_init.py b/tests/components/netatmo/test_init.py
index 4e82d7f1b59..e4869b73e2e 100644
--- a/tests/components/netatmo/test_init.py
+++ b/tests/components/netatmo/test_init.py
@@ -62,13 +62,15 @@ async def test_setup_component(
hass: HomeAssistant, config_entry: MockConfigEntry
) -> None:
"""Test setup and teardown of the netatmo component."""
- with patch(
- "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth",
- ) as mock_auth, patch(
- "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
- ) as mock_impl, patch(
- "homeassistant.components.netatmo.webhook_generate_url"
- ) as mock_webhook:
+ with (
+ patch(
+ "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth",
+ ) as mock_auth,
+ patch(
+ "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
+ ) as mock_impl,
+ patch("homeassistant.components.netatmo.webhook_generate_url") as mock_webhook,
+ ):
mock_auth.return_value.async_post_api_request.side_effect = fake_post_request
mock_auth.return_value.async_addwebhook.side_effect = AsyncMock()
mock_auth.return_value.async_dropwebhook.side_effect = AsyncMock()
@@ -104,14 +106,15 @@ async def test_setup_component_with_config(
fake_post_hits += 1
return await fake_post_request(*args, **kwargs)
- with patch(
- "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
- ) as mock_impl, patch(
- "homeassistant.components.netatmo.webhook_generate_url"
- ) as mock_webhook, patch(
- "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth",
- ) as mock_auth, patch(
- "homeassistant.components.netatmo.data_handler.PLATFORMS", ["sensor"]
+ with (
+ patch(
+ "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
+ ) as mock_impl,
+ patch("homeassistant.components.netatmo.webhook_generate_url") as mock_webhook,
+ patch(
+ "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth",
+ ) as mock_auth,
+ patch("homeassistant.components.netatmo.data_handler.PLATFORMS", ["sensor"]),
):
mock_auth.return_value.async_post_api_request.side_effect = fake_post
mock_auth.return_value.async_addwebhook.side_effect = AsyncMock()
@@ -169,16 +172,21 @@ async def test_setup_without_https(
) -> None:
"""Test if set up with cloud link and without https."""
hass.config.components.add("cloud")
- with patch(
- "homeassistant.helpers.network.get_url",
- return_value="http://example.nabu.casa",
- ), patch(
- "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth"
- ) as mock_auth, patch(
- "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
- ), patch(
- "homeassistant.components.netatmo.webhook_generate_url"
- ) as mock_async_generate_url:
+ with (
+ patch(
+ "homeassistant.helpers.network.get_url",
+ return_value="http://example.nabu.casa",
+ ),
+ patch(
+ "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth"
+ ) as mock_auth,
+ patch(
+ "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
+ ),
+ patch(
+ "homeassistant.components.netatmo.webhook_generate_url"
+ ) as mock_async_generate_url,
+ ):
mock_auth.return_value.async_post_api_request.side_effect = fake_post_request
mock_async_generate_url.return_value = "http://example.com"
assert await async_setup_component(
@@ -199,23 +207,27 @@ async def test_setup_with_cloud(
await mock_cloud(hass)
await hass.async_block_till_done()
- with patch(
- "homeassistant.components.cloud.async_is_logged_in", return_value=True
- ), patch.object(cloud, "async_is_connected", return_value=True), patch.object(
- cloud, "async_active_subscription", return_value=True
- ), patch(
- "homeassistant.components.cloud.async_create_cloudhook",
- return_value="https://hooks.nabu.casa/ABCD",
- ) as fake_create_cloudhook, patch(
- "homeassistant.components.cloud.async_delete_cloudhook"
- ) as fake_delete_cloudhook, patch(
- "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth"
- ) as mock_auth, patch(
- "homeassistant.components.netatmo.data_handler.PLATFORMS", []
- ), patch(
- "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
- ), patch(
- "homeassistant.components.netatmo.webhook_generate_url",
+ with (
+ patch("homeassistant.components.cloud.async_is_logged_in", return_value=True),
+ patch.object(cloud, "async_is_connected", return_value=True),
+ patch.object(cloud, "async_active_subscription", return_value=True),
+ patch(
+ "homeassistant.components.cloud.async_create_cloudhook",
+ return_value="https://hooks.nabu.casa/ABCD",
+ ) as fake_create_cloudhook,
+ patch(
+ "homeassistant.components.cloud.async_delete_cloudhook"
+ ) as fake_delete_cloudhook,
+ patch(
+ "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth"
+ ) as mock_auth,
+ patch("homeassistant.components.netatmo.data_handler.PLATFORMS", []),
+ patch(
+ "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
+ ),
+ patch(
+ "homeassistant.components.netatmo.webhook_generate_url",
+ ),
):
mock_auth.return_value.async_post_api_request.side_effect = fake_post_request
assert await async_setup_component(
@@ -263,23 +275,27 @@ async def test_setup_with_cloudhook(hass: HomeAssistant) -> None:
await mock_cloud(hass)
await hass.async_block_till_done()
- with patch(
- "homeassistant.components.cloud.async_is_logged_in", return_value=True
- ), patch(
- "homeassistant.components.cloud.async_is_connected", return_value=True
- ), patch.object(cloud, "async_active_subscription", return_value=True), patch(
- "homeassistant.components.cloud.async_create_cloudhook",
- return_value="https://hooks.nabu.casa/ABCD",
- ) as fake_create_cloudhook, patch(
- "homeassistant.components.cloud.async_delete_cloudhook"
- ) as fake_delete_cloudhook, patch(
- "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth"
- ) as mock_auth, patch(
- "homeassistant.components.netatmo.data_handler.PLATFORMS", []
- ), patch(
- "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
- ), patch(
- "homeassistant.components.netatmo.webhook_generate_url",
+ with (
+ patch("homeassistant.components.cloud.async_is_logged_in", return_value=True),
+ patch("homeassistant.components.cloud.async_is_connected", return_value=True),
+ patch.object(cloud, "async_active_subscription", return_value=True),
+ patch(
+ "homeassistant.components.cloud.async_create_cloudhook",
+ return_value="https://hooks.nabu.casa/ABCD",
+ ) as fake_create_cloudhook,
+ patch(
+ "homeassistant.components.cloud.async_delete_cloudhook"
+ ) as fake_delete_cloudhook,
+ patch(
+ "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth"
+ ) as mock_auth,
+ patch("homeassistant.components.netatmo.data_handler.PLATFORMS", []),
+ patch(
+ "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
+ ),
+ patch(
+ "homeassistant.components.netatmo.webhook_generate_url",
+ ),
):
mock_auth.return_value.async_post_api_request.side_effect = fake_post_request
mock_auth.return_value.async_addwebhook.side_effect = AsyncMock()
@@ -310,18 +326,22 @@ async def test_setup_component_with_delay(
"""Test setup of the netatmo component with delayed startup."""
hass.set_state(CoreState.not_running)
- with patch(
- "pyatmo.AbstractAsyncAuth.async_addwebhook", side_effect=AsyncMock()
- ) as mock_addwebhook, patch(
- "pyatmo.AbstractAsyncAuth.async_dropwebhook", side_effect=AsyncMock()
- ) as mock_dropwebhook, patch(
- "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
- ) as mock_impl, patch(
- "homeassistant.components.netatmo.webhook_generate_url"
- ) as mock_webhook, patch(
- "pyatmo.AbstractAsyncAuth.async_post_api_request", side_effect=fake_post_request
- ) as mock_post_api_request, patch(
- "homeassistant.components.netatmo.data_handler.PLATFORMS", ["light"]
+ with (
+ patch(
+ "pyatmo.AbstractAsyncAuth.async_addwebhook", side_effect=AsyncMock()
+ ) as mock_addwebhook,
+ patch(
+ "pyatmo.AbstractAsyncAuth.async_dropwebhook", side_effect=AsyncMock()
+ ) as mock_dropwebhook,
+ patch(
+ "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
+ ) as mock_impl,
+ patch("homeassistant.components.netatmo.webhook_generate_url") as mock_webhook,
+ patch(
+ "pyatmo.AbstractAsyncAuth.async_post_api_request",
+ side_effect=fake_post_request,
+ ) as mock_post_api_request,
+ patch("homeassistant.components.netatmo.data_handler.PLATFORMS", ["light"]),
):
assert await async_setup_component(
hass, "netatmo", {"netatmo": {"client_id": "123", "client_secret": "abc"}}
@@ -385,13 +405,15 @@ async def test_setup_component_invalid_token_scope(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth",
- ) as mock_auth, patch(
- "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
- ) as mock_impl, patch(
- "homeassistant.components.netatmo.webhook_generate_url"
- ) as mock_webhook:
+ with (
+ patch(
+ "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth",
+ ) as mock_auth,
+ patch(
+ "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
+ ) as mock_impl,
+ patch("homeassistant.components.netatmo.webhook_generate_url") as mock_webhook,
+ ):
mock_auth.return_value.async_post_api_request.side_effect = fake_post_request
mock_auth.return_value.async_addwebhook.side_effect = AsyncMock()
mock_auth.return_value.async_dropwebhook.side_effect = AsyncMock()
@@ -431,15 +453,18 @@ async def test_setup_component_invalid_token(
history=(),
)
- with patch(
- "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth",
- ) as mock_auth, patch(
- "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
- ) as mock_impl, patch(
- "homeassistant.components.netatmo.webhook_generate_url"
- ) as mock_webhook, patch(
- "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session"
- ) as mock_session:
+ with (
+ patch(
+ "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth",
+ ) as mock_auth,
+ patch(
+ "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
+ ) as mock_impl,
+ patch("homeassistant.components.netatmo.webhook_generate_url") as mock_webhook,
+ patch(
+ "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session"
+ ) as mock_session,
+ ):
mock_auth.return_value.async_post_api_request.side_effect = fake_post_request
mock_auth.return_value.async_addwebhook.side_effect = AsyncMock()
mock_auth.return_value.async_dropwebhook.side_effect = AsyncMock()
diff --git a/tests/components/netatmo/test_light.py b/tests/components/netatmo/test_light.py
index 5ae368522a3..c90d67e7630 100644
--- a/tests/components/netatmo/test_light.py
+++ b/tests/components/netatmo/test_light.py
@@ -123,14 +123,17 @@ async def test_setup_component_no_devices(hass: HomeAssistant, config_entry) ->
json={},
)
- with patch(
- "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth"
- ) as mock_auth, patch(
- "homeassistant.components.netatmo.data_handler.PLATFORMS", ["light"]
- ), patch(
- "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
- ), patch(
- "homeassistant.components.netatmo.webhook_generate_url",
+ with (
+ patch(
+ "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth"
+ ) as mock_auth,
+ patch("homeassistant.components.netatmo.data_handler.PLATFORMS", ["light"]),
+ patch(
+ "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
+ ),
+ patch(
+ "homeassistant.components.netatmo.webhook_generate_url",
+ ),
):
mock_auth.return_value.async_post_api_request.side_effect = (
fake_post_request_no_data
diff --git a/tests/components/netgear/test_config_flow.py b/tests/components/netgear/test_config_flow.py
index 34df3a50c1b..c0649d3646e 100644
--- a/tests/components/netgear/test_config_flow.py
+++ b/tests/components/netgear/test_config_flow.py
@@ -68,9 +68,10 @@ SSDP_URL_SLL = f"https://{HOST}:{PORT}/rootDesc.xml"
@pytest.fixture(name="service")
def mock_controller_service():
"""Mock a successful service."""
- with patch(
- "homeassistant.components.netgear.async_setup_entry", return_value=True
- ), patch("homeassistant.components.netgear.router.Netgear") as service_mock:
+ with (
+ patch("homeassistant.components.netgear.async_setup_entry", return_value=True),
+ patch("homeassistant.components.netgear.router.Netgear") as service_mock,
+ ):
service_mock.return_value.get_info = Mock(return_value=ROUTER_INFOS)
service_mock.return_value.port = 80
service_mock.return_value.ssl = False
diff --git a/tests/components/network/test_init.py b/tests/components/network/test_init.py
index 7aea83a84e2..b02692e5086 100644
--- a/tests/components/network/test_init.py
+++ b/tests/components/network/test_init.py
@@ -75,12 +75,15 @@ async def test_async_detect_interfaces_setting_non_loopback_route(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test without default interface config and the route returns a non-loopback address."""
- with patch(
- "homeassistant.components.network.util.socket.socket",
- return_value=_mock_socket([_NO_LOOPBACK_IPADDR]),
- ), patch(
- "homeassistant.components.network.util.ifaddr.get_adapters",
- return_value=_generate_mock_adapters(),
+ with (
+ patch(
+ "homeassistant.components.network.util.socket.socket",
+ return_value=_mock_socket([_NO_LOOPBACK_IPADDR]),
+ ),
+ patch(
+ "homeassistant.components.network.util.ifaddr.get_adapters",
+ return_value=_generate_mock_adapters(),
+ ),
):
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
@@ -139,12 +142,15 @@ async def test_async_detect_interfaces_setting_loopback_route(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test without default interface config and the route returns a loopback address."""
- with patch(
- "homeassistant.components.network.util.socket.socket",
- return_value=_mock_socket([_LOOPBACK_IPADDR]),
- ), patch(
- "homeassistant.components.network.util.ifaddr.get_adapters",
- return_value=_generate_mock_adapters(),
+ with (
+ patch(
+ "homeassistant.components.network.util.socket.socket",
+ return_value=_mock_socket([_LOOPBACK_IPADDR]),
+ ),
+ patch(
+ "homeassistant.components.network.util.ifaddr.get_adapters",
+ return_value=_generate_mock_adapters(),
+ ),
):
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
@@ -202,12 +208,15 @@ async def test_async_detect_interfaces_setting_empty_route(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test without default interface config and the route returns nothing."""
- with patch(
- "homeassistant.components.network.util.socket.socket",
- return_value=_mock_socket([]),
- ), patch(
- "homeassistant.components.network.util.ifaddr.get_adapters",
- return_value=_generate_mock_adapters(),
+ with (
+ patch(
+ "homeassistant.components.network.util.socket.socket",
+ return_value=_mock_socket([]),
+ ),
+ patch(
+ "homeassistant.components.network.util.ifaddr.get_adapters",
+ return_value=_generate_mock_adapters(),
+ ),
):
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
@@ -265,12 +274,15 @@ async def test_async_detect_interfaces_setting_exception(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test without default interface config and the route throws an exception."""
- with patch(
- "homeassistant.components.network.util.socket.socket",
- return_value=_mock_socket_exception(AttributeError),
- ), patch(
- "homeassistant.components.network.util.ifaddr.get_adapters",
- return_value=_generate_mock_adapters(),
+ with (
+ patch(
+ "homeassistant.components.network.util.socket.socket",
+ return_value=_mock_socket_exception(AttributeError),
+ ),
+ patch(
+ "homeassistant.components.network.util.ifaddr.get_adapters",
+ return_value=_generate_mock_adapters(),
+ ),
):
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
@@ -333,12 +345,15 @@ async def test_interfaces_configured_from_storage(
"key": STORAGE_KEY,
"data": {ATTR_CONFIGURED_ADAPTERS: ["eth0", "eth1", "vtun0"]},
}
- with patch(
- "homeassistant.components.network.util.socket.socket",
- return_value=_mock_socket([_NO_LOOPBACK_IPADDR]),
- ), patch(
- "homeassistant.components.network.util.ifaddr.get_adapters",
- return_value=_generate_mock_adapters(),
+ with (
+ patch(
+ "homeassistant.components.network.util.socket.socket",
+ return_value=_mock_socket([_NO_LOOPBACK_IPADDR]),
+ ),
+ patch(
+ "homeassistant.components.network.util.ifaddr.get_adapters",
+ return_value=_generate_mock_adapters(),
+ ),
):
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
@@ -402,12 +417,15 @@ async def test_interfaces_configured_from_storage_websocket_update(
"key": STORAGE_KEY,
"data": {ATTR_CONFIGURED_ADAPTERS: ["eth0", "eth1", "vtun0"]},
}
- with patch(
- "homeassistant.components.network.util.socket.socket",
- return_value=_mock_socket([_NO_LOOPBACK_IPADDR]),
- ), patch(
- "homeassistant.components.network.util.ifaddr.get_adapters",
- return_value=_generate_mock_adapters(),
+ with (
+ patch(
+ "homeassistant.components.network.util.socket.socket",
+ return_value=_mock_socket([_NO_LOOPBACK_IPADDR]),
+ ),
+ patch(
+ "homeassistant.components.network.util.ifaddr.get_adapters",
+ return_value=_generate_mock_adapters(),
+ ),
):
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
@@ -533,12 +551,15 @@ async def test_async_get_source_ip_matching_interface(
"data": {ATTR_CONFIGURED_ADAPTERS: ["eth1"]},
}
- with patch(
- "homeassistant.components.network.util.ifaddr.get_adapters",
- return_value=_generate_mock_adapters(),
- ), patch(
- "homeassistant.components.network.util.socket.socket",
- return_value=_mock_socket(["192.168.1.5"]),
+ with (
+ patch(
+ "homeassistant.components.network.util.ifaddr.get_adapters",
+ return_value=_generate_mock_adapters(),
+ ),
+ patch(
+ "homeassistant.components.network.util.socket.socket",
+ return_value=_mock_socket(["192.168.1.5"]),
+ ),
):
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
@@ -556,12 +577,15 @@ async def test_async_get_source_ip_interface_not_match(
"data": {ATTR_CONFIGURED_ADAPTERS: ["vtun0"]},
}
- with patch(
- "homeassistant.components.network.util.ifaddr.get_adapters",
- return_value=_generate_mock_adapters(),
- ), patch(
- "homeassistant.components.network.util.socket.socket",
- return_value=_mock_socket(["192.168.1.5"]),
+ with (
+ patch(
+ "homeassistant.components.network.util.ifaddr.get_adapters",
+ return_value=_generate_mock_adapters(),
+ ),
+ patch(
+ "homeassistant.components.network.util.socket.socket",
+ return_value=_mock_socket(["192.168.1.5"]),
+ ),
):
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
@@ -579,12 +603,15 @@ async def test_async_get_source_ip_cannot_determine_target(
"data": {ATTR_CONFIGURED_ADAPTERS: ["eth1"]},
}
- with patch(
- "homeassistant.components.network.util.ifaddr.get_adapters",
- return_value=_generate_mock_adapters(),
- ), patch(
- "homeassistant.components.network.util.socket.socket",
- return_value=_mock_socket([None]),
+ with (
+ patch(
+ "homeassistant.components.network.util.ifaddr.get_adapters",
+ return_value=_generate_mock_adapters(),
+ ),
+ patch(
+ "homeassistant.components.network.util.socket.socket",
+ return_value=_mock_socket([None]),
+ ),
):
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
@@ -602,12 +629,15 @@ async def test_async_get_ipv4_broadcast_addresses_default(
"data": {ATTR_CONFIGURED_ADAPTERS: ["eth1"]},
}
- with patch(
- "homeassistant.components.network.util.socket.socket",
- return_value=_mock_socket(["192.168.1.5"]),
- ), patch(
- "homeassistant.components.network.util.ifaddr.get_adapters",
- return_value=_generate_mock_adapters(),
+ with (
+ patch(
+ "homeassistant.components.network.util.socket.socket",
+ return_value=_mock_socket(["192.168.1.5"]),
+ ),
+ patch(
+ "homeassistant.components.network.util.ifaddr.get_adapters",
+ return_value=_generate_mock_adapters(),
+ ),
):
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
@@ -627,12 +657,15 @@ async def test_async_get_ipv4_broadcast_addresses_multiple(
"data": {ATTR_CONFIGURED_ADAPTERS: ["eth1", "vtun0"]},
}
- with patch(
- "homeassistant.components.network.util.socket.socket",
- return_value=_mock_socket([_LOOPBACK_IPADDR]),
- ), patch(
- "homeassistant.components.network.util.ifaddr.get_adapters",
- return_value=_generate_mock_adapters(),
+ with (
+ patch(
+ "homeassistant.components.network.util.socket.socket",
+ return_value=_mock_socket([_LOOPBACK_IPADDR]),
+ ),
+ patch(
+ "homeassistant.components.network.util.ifaddr.get_adapters",
+ return_value=_generate_mock_adapters(),
+ ),
):
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
@@ -654,12 +687,15 @@ async def test_async_get_source_ip_no_enabled_addresses(
"data": {ATTR_CONFIGURED_ADAPTERS: ["eth1"]},
}
- with patch(
- "homeassistant.components.network.util.ifaddr.get_adapters",
- return_value=[],
- ), patch(
- "homeassistant.components.network.util.socket.socket",
- return_value=_mock_socket(["192.168.1.5"]),
+ with (
+ patch(
+ "homeassistant.components.network.util.ifaddr.get_adapters",
+ return_value=[],
+ ),
+ patch(
+ "homeassistant.components.network.util.socket.socket",
+ return_value=_mock_socket(["192.168.1.5"]),
+ ),
):
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
@@ -679,12 +715,15 @@ async def test_async_get_source_ip_cannot_be_determined_and_no_enabled_addresses
"data": {ATTR_CONFIGURED_ADAPTERS: ["eth1"]},
}
- with patch(
- "homeassistant.components.network.util.ifaddr.get_adapters",
- return_value=[],
- ), patch(
- "homeassistant.components.network.util.socket.socket",
- return_value=_mock_socket([None]),
+ with (
+ patch(
+ "homeassistant.components.network.util.ifaddr.get_adapters",
+ return_value=[],
+ ),
+ patch(
+ "homeassistant.components.network.util.socket.socket",
+ return_value=_mock_socket([None]),
+ ),
):
assert not await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
@@ -702,12 +741,15 @@ async def test_async_get_source_ip_no_ip_loopback(
"data": {ATTR_CONFIGURED_ADAPTERS: ["eth1"]},
}
- with patch(
- "homeassistant.components.network.util.ifaddr.get_adapters",
- return_value=[],
- ), patch(
- "homeassistant.components.network.util.socket.socket",
- return_value=_mock_cond_socket(_LOOPBACK_IPADDR),
+ with (
+ patch(
+ "homeassistant.components.network.util.ifaddr.get_adapters",
+ return_value=[],
+ ),
+ patch(
+ "homeassistant.components.network.util.socket.socket",
+ return_value=_mock_cond_socket(_LOOPBACK_IPADDR),
+ ),
):
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
@@ -778,12 +820,15 @@ _ADAPTERS_WITH_MANUAL_CONFIG = [
async def test_async_get_announce_addresses(hass: HomeAssistant) -> None:
"""Test addresses for mDNS/etc announcement."""
first_ip = "172.16.1.5"
- with patch(
- "homeassistant.components.network.async_get_source_ip",
- return_value=first_ip,
- ), patch(
- "homeassistant.components.network.async_get_adapters",
- return_value=_ADAPTERS_WITH_MANUAL_CONFIG,
+ with (
+ patch(
+ "homeassistant.components.network.async_get_source_ip",
+ return_value=first_ip,
+ ),
+ patch(
+ "homeassistant.components.network.async_get_adapters",
+ return_value=_ADAPTERS_WITH_MANUAL_CONFIG,
+ ),
):
actual = await network.async_get_announce_addresses(hass)
assert actual[0] == first_ip and actual == [
@@ -795,12 +840,15 @@ async def test_async_get_announce_addresses(hass: HomeAssistant) -> None:
]
first_ip = "192.168.1.5"
- with patch(
- "homeassistant.components.network.async_get_source_ip",
- return_value=first_ip,
- ), patch(
- "homeassistant.components.network.async_get_adapters",
- return_value=_ADAPTERS_WITH_MANUAL_CONFIG,
+ with (
+ patch(
+ "homeassistant.components.network.async_get_source_ip",
+ return_value=first_ip,
+ ),
+ patch(
+ "homeassistant.components.network.async_get_adapters",
+ return_value=_ADAPTERS_WITH_MANUAL_CONFIG,
+ ),
):
actual = await network.async_get_announce_addresses(hass)
@@ -815,12 +863,15 @@ async def test_async_get_announce_addresses(hass: HomeAssistant) -> None:
async def test_async_get_announce_addresses_no_source_ip(hass: HomeAssistant) -> None:
"""Test addresses for mDNS/etc announcement without source ip."""
- with patch(
- "homeassistant.components.network.async_get_source_ip",
- return_value=None,
- ), patch(
- "homeassistant.components.network.async_get_adapters",
- return_value=_ADAPTERS_WITH_MANUAL_CONFIG,
+ with (
+ patch(
+ "homeassistant.components.network.async_get_source_ip",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.network.async_get_adapters",
+ return_value=_ADAPTERS_WITH_MANUAL_CONFIG,
+ ),
):
actual = await network.async_get_announce_addresses(hass)
assert actual == [
diff --git a/tests/components/nexia/test_config_flow.py b/tests/components/nexia/test_config_flow.py
index 7ed5ecec675..02a3cf06728 100644
--- a/tests/components/nexia/test_config_flow.py
+++ b/tests/components/nexia/test_config_flow.py
@@ -22,16 +22,20 @@ async def test_form(hass: HomeAssistant, brand) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.nexia.config_flow.NexiaHome.get_name",
- return_value="myhouse",
- ), patch(
- "homeassistant.components.nexia.config_flow.NexiaHome.login",
- side_effect=MagicMock(),
- ), patch(
- "homeassistant.components.nexia.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.nexia.config_flow.NexiaHome.get_name",
+ return_value="myhouse",
+ ),
+ patch(
+ "homeassistant.components.nexia.config_flow.NexiaHome.login",
+ side_effect=MagicMock(),
+ ),
+ patch(
+ "homeassistant.components.nexia.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_BRAND: brand, CONF_USERNAME: "username", CONF_PASSWORD: "password"},
@@ -54,11 +58,14 @@ async def test_form_invalid_auth(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "homeassistant.components.nexia.config_flow.NexiaHome.login",
- ), patch(
- "homeassistant.components.nexia.config_flow.NexiaHome.get_name",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.components.nexia.config_flow.NexiaHome.login",
+ ),
+ patch(
+ "homeassistant.components.nexia.config_flow.NexiaHome.get_name",
+ return_value=None,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/nexia/util.py b/tests/components/nexia/util.py
index f49058e0033..98d5312f0a1 100644
--- a/tests/components/nexia/util.py
+++ b/tests/components/nexia/util.py
@@ -24,8 +24,9 @@ async def async_init_integration(
session_fixture = "nexia/session_123456.json"
sign_in_fixture = "nexia/sign_in.json"
set_fan_speed_fixture = "nexia/set_fan_speed_2293892.json"
- with mock_aiohttp_client() as mock_session, patch(
- "nexia.home.load_or_create_uuid", return_value=uuid.uuid4()
+ with (
+ mock_aiohttp_client() as mock_session,
+ patch("nexia.home.load_or_create_uuid", return_value=uuid.uuid4()),
):
nexia = NexiaHome(mock_session)
if exception:
diff --git a/tests/components/nextdns/__init__.py b/tests/components/nextdns/__init__.py
index d741811acf0..e4948a9358f 100644
--- a/tests/components/nextdns/__init__.py
+++ b/tests/components/nextdns/__init__.py
@@ -123,29 +123,39 @@ async def init_integration(hass: HomeAssistant) -> MockConfigEntry:
entry_id="d9aa37407ddac7b964a99e86312288d6",
)
- with patch(
- "homeassistant.components.nextdns.NextDns.get_profiles", return_value=PROFILES
- ), patch(
- "homeassistant.components.nextdns.NextDns.get_analytics_status",
- return_value=STATUS,
- ), patch(
- "homeassistant.components.nextdns.NextDns.get_analytics_encryption",
- return_value=ENCRYPTION,
- ), patch(
- "homeassistant.components.nextdns.NextDns.get_analytics_dnssec",
- return_value=DNSSEC,
- ), patch(
- "homeassistant.components.nextdns.NextDns.get_analytics_ip_versions",
- return_value=IP_VERSIONS,
- ), patch(
- "homeassistant.components.nextdns.NextDns.get_analytics_protocols",
- return_value=PROTOCOLS,
- ), patch(
- "homeassistant.components.nextdns.NextDns.get_settings",
- return_value=SETTINGS,
- ), patch(
- "homeassistant.components.nextdns.NextDns.connection_status",
- return_value=CONNECTION_STATUS,
+ with (
+ patch(
+ "homeassistant.components.nextdns.NextDns.get_profiles",
+ return_value=PROFILES,
+ ),
+ patch(
+ "homeassistant.components.nextdns.NextDns.get_analytics_status",
+ return_value=STATUS,
+ ),
+ patch(
+ "homeassistant.components.nextdns.NextDns.get_analytics_encryption",
+ return_value=ENCRYPTION,
+ ),
+ patch(
+ "homeassistant.components.nextdns.NextDns.get_analytics_dnssec",
+ return_value=DNSSEC,
+ ),
+ patch(
+ "homeassistant.components.nextdns.NextDns.get_analytics_ip_versions",
+ return_value=IP_VERSIONS,
+ ),
+ patch(
+ "homeassistant.components.nextdns.NextDns.get_analytics_protocols",
+ return_value=PROTOCOLS,
+ ),
+ patch(
+ "homeassistant.components.nextdns.NextDns.get_settings",
+ return_value=SETTINGS,
+ ),
+ patch(
+ "homeassistant.components.nextdns.NextDns.connection_status",
+ return_value=CONNECTION_STATUS,
+ ),
):
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
diff --git a/tests/components/nextdns/test_button.py b/tests/components/nextdns/test_button.py
index 66c83169813..b5f7b01aee2 100644
--- a/tests/components/nextdns/test_button.py
+++ b/tests/components/nextdns/test_button.py
@@ -31,9 +31,10 @@ async def test_button_press(hass: HomeAssistant) -> None:
await init_integration(hass)
now = dt_util.utcnow()
- with patch(
- "homeassistant.components.nextdns.NextDns.clear_logs"
- ) as mock_clear_logs, patch("homeassistant.core.dt_util.utcnow", return_value=now):
+ with (
+ patch("homeassistant.components.nextdns.NextDns.clear_logs") as mock_clear_logs,
+ patch("homeassistant.core.dt_util.utcnow", return_value=now),
+ ):
await hass.services.async_call(
BUTTON_DOMAIN,
"press",
diff --git a/tests/components/nextdns/test_config_flow.py b/tests/components/nextdns/test_config_flow.py
index e1b669c17e8..4d9961474c5 100644
--- a/tests/components/nextdns/test_config_flow.py
+++ b/tests/components/nextdns/test_config_flow.py
@@ -23,11 +23,15 @@ async def test_form_create_entry(hass: HomeAssistant) -> None:
assert result["step_id"] == "user"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.nextdns.NextDns.get_profiles", return_value=PROFILES
- ), patch(
- "homeassistant.components.nextdns.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.nextdns.NextDns.get_profiles",
+ return_value=PROFILES,
+ ),
+ patch(
+ "homeassistant.components.nextdns.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_API_KEY: "fake_api_key"},
diff --git a/tests/components/nextdns/test_sensor.py b/tests/components/nextdns/test_sensor.py
index de303fd6cad..a6d9b4c545f 100644
--- a/tests/components/nextdns/test_sensor.py
+++ b/tests/components/nextdns/test_sensor.py
@@ -309,21 +309,27 @@ async def test_availability(
assert state.state == "90"
future = utcnow() + timedelta(minutes=10)
- with patch(
- "homeassistant.components.nextdns.NextDns.get_analytics_status",
- side_effect=ApiError("API Error"),
- ), patch(
- "homeassistant.components.nextdns.NextDns.get_analytics_dnssec",
- side_effect=ApiError("API Error"),
- ), patch(
- "homeassistant.components.nextdns.NextDns.get_analytics_encryption",
- side_effect=ApiError("API Error"),
- ), patch(
- "homeassistant.components.nextdns.NextDns.get_analytics_ip_versions",
- side_effect=ApiError("API Error"),
- ), patch(
- "homeassistant.components.nextdns.NextDns.get_analytics_protocols",
- side_effect=ApiError("API Error"),
+ with (
+ patch(
+ "homeassistant.components.nextdns.NextDns.get_analytics_status",
+ side_effect=ApiError("API Error"),
+ ),
+ patch(
+ "homeassistant.components.nextdns.NextDns.get_analytics_dnssec",
+ side_effect=ApiError("API Error"),
+ ),
+ patch(
+ "homeassistant.components.nextdns.NextDns.get_analytics_encryption",
+ side_effect=ApiError("API Error"),
+ ),
+ patch(
+ "homeassistant.components.nextdns.NextDns.get_analytics_ip_versions",
+ side_effect=ApiError("API Error"),
+ ),
+ patch(
+ "homeassistant.components.nextdns.NextDns.get_analytics_protocols",
+ side_effect=ApiError("API Error"),
+ ),
):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
@@ -349,21 +355,27 @@ async def test_availability(
assert state.state == STATE_UNAVAILABLE
future = utcnow() + timedelta(minutes=20)
- with patch(
- "homeassistant.components.nextdns.NextDns.get_analytics_status",
- return_value=STATUS,
- ), patch(
- "homeassistant.components.nextdns.NextDns.get_analytics_encryption",
- return_value=ENCRYPTION,
- ), patch(
- "homeassistant.components.nextdns.NextDns.get_analytics_dnssec",
- return_value=DNSSEC,
- ), patch(
- "homeassistant.components.nextdns.NextDns.get_analytics_ip_versions",
- return_value=IP_VERSIONS,
- ), patch(
- "homeassistant.components.nextdns.NextDns.get_analytics_protocols",
- return_value=PROTOCOLS,
+ with (
+ patch(
+ "homeassistant.components.nextdns.NextDns.get_analytics_status",
+ return_value=STATUS,
+ ),
+ patch(
+ "homeassistant.components.nextdns.NextDns.get_analytics_encryption",
+ return_value=ENCRYPTION,
+ ),
+ patch(
+ "homeassistant.components.nextdns.NextDns.get_analytics_dnssec",
+ return_value=DNSSEC,
+ ),
+ patch(
+ "homeassistant.components.nextdns.NextDns.get_analytics_ip_versions",
+ return_value=IP_VERSIONS,
+ ),
+ patch(
+ "homeassistant.components.nextdns.NextDns.get_analytics_protocols",
+ return_value=PROTOCOLS,
+ ),
):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
diff --git a/tests/components/nextdns/test_switch.py b/tests/components/nextdns/test_switch.py
index 7e1d592c1f4..f51ee32fd10 100644
--- a/tests/components/nextdns/test_switch.py
+++ b/tests/components/nextdns/test_switch.py
@@ -726,9 +726,10 @@ 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
- ), 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,
diff --git a/tests/components/nibe_heatpump/conftest.py b/tests/components/nibe_heatpump/conftest.py
index 010a79980c4..00d4c92c68b 100644
--- a/tests/components/nibe_heatpump/conftest.py
+++ b/tests/components/nibe_heatpump/conftest.py
@@ -71,8 +71,9 @@ async def fixture_coils(mock_connection: MockConnection):
raise CoilNotFoundException
return coils_data
- with patch.object(HeatPump, "get_coils", new=get_coils), patch.object(
- HeatPump, "get_coil_by_address", new=get_coil_by_address
+ with (
+ patch.object(HeatPump, "get_coils", new=get_coils),
+ patch.object(HeatPump, "get_coil_by_address", new=get_coil_by_address),
):
yield mock_connection.coils
diff --git a/tests/components/nightscout/__init__.py b/tests/components/nightscout/__init__.py
index 3433e889b92..da421d5bba9 100644
--- a/tests/components/nightscout/__init__.py
+++ b/tests/components/nightscout/__init__.py
@@ -36,12 +36,15 @@ async def init_integration(hass) -> MockConfigEntry:
domain=DOMAIN,
data={CONF_URL: "https://some.url:1234"},
)
- with patch(
- "homeassistant.components.nightscout.NightscoutAPI.get_sgvs",
- return_value=GLUCOSE_READINGS,
- ), patch(
- "homeassistant.components.nightscout.NightscoutAPI.get_server_status",
- return_value=SERVER_STATUS,
+ with (
+ patch(
+ "homeassistant.components.nightscout.NightscoutAPI.get_sgvs",
+ return_value=GLUCOSE_READINGS,
+ ),
+ patch(
+ "homeassistant.components.nightscout.NightscoutAPI.get_server_status",
+ return_value=SERVER_STATUS,
+ ),
):
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
@@ -56,12 +59,15 @@ async def init_integration_unavailable(hass) -> MockConfigEntry:
domain=DOMAIN,
data={CONF_URL: "https://some.url:1234"},
)
- with patch(
- "homeassistant.components.nightscout.NightscoutAPI.get_sgvs",
- side_effect=ClientConnectionError(),
- ), patch(
- "homeassistant.components.nightscout.NightscoutAPI.get_server_status",
- return_value=SERVER_STATUS,
+ with (
+ patch(
+ "homeassistant.components.nightscout.NightscoutAPI.get_sgvs",
+ side_effect=ClientConnectionError(),
+ ),
+ patch(
+ "homeassistant.components.nightscout.NightscoutAPI.get_server_status",
+ return_value=SERVER_STATUS,
+ ),
):
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
@@ -76,11 +82,15 @@ async def init_integration_empty_response(hass) -> MockConfigEntry:
domain=DOMAIN,
data={CONF_URL: "https://some.url:1234"},
)
- with patch(
- "homeassistant.components.nightscout.NightscoutAPI.get_sgvs", return_value=[]
- ), patch(
- "homeassistant.components.nightscout.NightscoutAPI.get_server_status",
- return_value=SERVER_STATUS,
+ with (
+ patch(
+ "homeassistant.components.nightscout.NightscoutAPI.get_sgvs",
+ return_value=[],
+ ),
+ patch(
+ "homeassistant.components.nightscout.NightscoutAPI.get_server_status",
+ return_value=SERVER_STATUS,
+ ),
):
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
diff --git a/tests/components/nightscout/test_config_flow.py b/tests/components/nightscout/test_config_flow.py
index 43f238ffa13..c3723596a84 100644
--- a/tests/components/nightscout/test_config_flow.py
+++ b/tests/components/nightscout/test_config_flow.py
@@ -27,7 +27,11 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] == {}
- with _patch_glucose_readings(), _patch_server_status(), _patch_async_setup_entry() as mock_setup_entry:
+ with (
+ _patch_glucose_readings(),
+ _patch_server_status(),
+ _patch_async_setup_entry() as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
CONFIG,
@@ -65,12 +69,15 @@ async def test_user_form_api_key_required(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "homeassistant.components.nightscout.NightscoutAPI.get_server_status",
- return_value=SERVER_STATUS_STATUS_ONLY,
- ), patch(
- "homeassistant.components.nightscout.NightscoutAPI.get_sgvs",
- side_effect=ClientResponseError(None, None, status=HTTPStatus.UNAUTHORIZED),
+ with (
+ patch(
+ "homeassistant.components.nightscout.NightscoutAPI.get_server_status",
+ return_value=SERVER_STATUS_STATUS_ONLY,
+ ),
+ patch(
+ "homeassistant.components.nightscout.NightscoutAPI.get_sgvs",
+ side_effect=ClientResponseError(None, None, status=HTTPStatus.UNAUTHORIZED),
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/nina/test_config_flow.py b/tests/components/nina/test_config_flow.py
index 10de928feb8..d3c44258c23 100644
--- a/tests/components/nina/test_config_flow.py
+++ b/tests/components/nina/test_config_flow.py
@@ -94,12 +94,15 @@ async def test_step_user_unexpected_exception(hass: HomeAssistant) -> None:
async def test_step_user(hass: HomeAssistant) -> None:
"""Test starting a flow by user with valid values."""
- with patch(
- "pynina.baseApi.BaseAPI._makeRequest",
- wraps=mocked_request_function,
- ), patch(
- "homeassistant.components.nina.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "pynina.baseApi.BaseAPI._makeRequest",
+ wraps=mocked_request_function,
+ ),
+ patch(
+ "homeassistant.components.nina.async_setup_entry",
+ return_value=True,
+ ),
):
result: dict[str, Any] = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=deepcopy(DUMMY_DATA)
@@ -157,11 +160,12 @@ async def test_options_flow_init(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.nina.async_setup_entry", return_value=True
- ), patch(
- "pynina.baseApi.BaseAPI._makeRequest",
- wraps=mocked_request_function,
+ with (
+ patch("homeassistant.components.nina.async_setup_entry", return_value=True),
+ patch(
+ "pynina.baseApi.BaseAPI._makeRequest",
+ wraps=mocked_request_function,
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -211,11 +215,12 @@ async def test_options_flow_with_no_selection(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.nina.async_setup_entry", return_value=True
- ), patch(
- "pynina.baseApi.BaseAPI._makeRequest",
- wraps=mocked_request_function,
+ with (
+ patch("homeassistant.components.nina.async_setup_entry", return_value=True),
+ patch(
+ "pynina.baseApi.BaseAPI._makeRequest",
+ wraps=mocked_request_function,
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -252,12 +257,15 @@ async def test_options_flow_connection_error(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with patch(
- "pynina.baseApi.BaseAPI._makeRequest",
- side_effect=ApiError("Could not connect to Api"),
- ), patch(
- "homeassistant.components.nina.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "pynina.baseApi.BaseAPI._makeRequest",
+ side_effect=ApiError("Could not connect to Api"),
+ ),
+ patch(
+ "homeassistant.components.nina.async_setup_entry",
+ return_value=True,
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -277,12 +285,15 @@ async def test_options_flow_unexpected_exception(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with patch(
- "pynina.baseApi.BaseAPI._makeRequest",
- side_effect=Exception("DUMMY"),
- ), patch(
- "homeassistant.components.nina.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "pynina.baseApi.BaseAPI._makeRequest",
+ side_effect=Exception("DUMMY"),
+ ),
+ patch(
+ "homeassistant.components.nina.async_setup_entry",
+ return_value=True,
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -301,12 +312,15 @@ async def test_options_flow_entity_removal(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with patch(
- "pynina.baseApi.BaseAPI._makeRequest",
- wraps=mocked_request_function,
- ), patch(
- "homeassistant.components.nina._async_update_listener"
- ) as mock_update_listener:
+ with (
+ patch(
+ "pynina.baseApi.BaseAPI._makeRequest",
+ wraps=mocked_request_function,
+ ),
+ patch(
+ "homeassistant.components.nina._async_update_listener"
+ ) as mock_update_listener,
+ ):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/nobo_hub/test_config_flow.py b/tests/components/nobo_hub/test_config_flow.py
index eed287abbb0..1d6feb6e28a 100644
--- a/tests/components/nobo_hub/test_config_flow.py
+++ b/tests/components/nobo_hub/test_config_flow.py
@@ -31,17 +31,19 @@ async def test_configure_with_discover(hass: HomeAssistant) -> None:
assert result2["errors"] == {}
assert result2["step_id"] == "selected"
- with patch(
- "pynobo.nobo.async_connect_hub", return_value=True
- ) as mock_connect, patch(
- "pynobo.nobo.hub_info",
- new_callable=PropertyMock,
- create=True,
- return_value={"name": "My Nobø Ecohub"},
- ), patch(
- "homeassistant.components.nobo_hub.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("pynobo.nobo.async_connect_hub", return_value=True) as mock_connect,
+ patch(
+ "pynobo.nobo.hub_info",
+ new_callable=PropertyMock,
+ create=True,
+ return_value={"name": "My Nobø Ecohub"},
+ ),
+ patch(
+ "homeassistant.components.nobo_hub.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
@@ -74,17 +76,19 @@ async def test_configure_manual(hass: HomeAssistant) -> None:
assert result["errors"] == {}
assert result["step_id"] == "manual"
- with patch(
- "pynobo.nobo.async_connect_hub", return_value=True
- ) as mock_connect, patch(
- "pynobo.nobo.hub_info",
- new_callable=PropertyMock,
- create=True,
- return_value={"name": "My Nobø Ecohub"},
- ), patch(
- "homeassistant.components.nobo_hub.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("pynobo.nobo.async_connect_hub", return_value=True) as mock_connect,
+ patch(
+ "pynobo.nobo.hub_info",
+ new_callable=PropertyMock,
+ create=True,
+ return_value={"name": "My Nobø Ecohub"},
+ ),
+ patch(
+ "homeassistant.components.nobo_hub.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -125,17 +129,19 @@ async def test_configure_user_selected_manual(hass: HomeAssistant) -> None:
assert result2["errors"] == {}
assert result2["step_id"] == "manual"
- with patch(
- "pynobo.nobo.async_connect_hub", return_value=True
- ) as mock_connect, patch(
- "pynobo.nobo.hub_info",
- new_callable=PropertyMock,
- create=True,
- return_value={"name": "My Nobø Ecohub"},
- ), patch(
- "homeassistant.components.nobo_hub.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("pynobo.nobo.async_connect_hub", return_value=True) as mock_connect,
+ patch(
+ "pynobo.nobo.hub_info",
+ new_callable=PropertyMock,
+ create=True,
+ return_value={"name": "My Nobø Ecohub"},
+ ),
+ patch(
+ "homeassistant.components.nobo_hub.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
diff --git a/tests/components/notion/conftest.py b/tests/components/notion/conftest.py
index 3f98491ddb6..e69905ed72c 100644
--- a/tests/components/notion/conftest.py
+++ b/tests/components/notion/conftest.py
@@ -120,15 +120,19 @@ def get_client_fixture(client):
@pytest.fixture(name="mock_aionotion")
async def mock_aionotion_fixture(client):
"""Define a fixture to patch aionotion."""
- with patch(
- "homeassistant.components.notion.async_get_client_with_credentials",
- AsyncMock(return_value=client),
- ), patch(
- "homeassistant.components.notion.async_get_client_with_refresh_token",
- AsyncMock(return_value=client),
- ), patch(
- "homeassistant.components.notion.config_flow.async_get_client_with_credentials",
- AsyncMock(return_value=client),
+ with (
+ patch(
+ "homeassistant.components.notion.async_get_client_with_credentials",
+ AsyncMock(return_value=client),
+ ),
+ patch(
+ "homeassistant.components.notion.async_get_client_with_refresh_token",
+ AsyncMock(return_value=client),
+ ),
+ patch(
+ "homeassistant.components.notion.config_flow.async_get_client_with_credentials",
+ AsyncMock(return_value=client),
+ ),
):
yield
diff --git a/tests/components/nsw_rural_fire_service_feed/test_geo_location.py b/tests/components/nsw_rural_fire_service_feed/test_geo_location.py
index f329e456db1..ad987325b97 100644
--- a/tests/components/nsw_rural_fire_service_feed/test_geo_location.py
+++ b/tests/components/nsw_rural_fire_service_feed/test_geo_location.py
@@ -231,12 +231,13 @@ async def test_setup_with_custom_location(hass: HomeAssistant) -> None:
# Set up some mock feed entries for this test.
mock_entry_1 = _generate_mock_feed_entry("1234", "Title 1", 20.5, (-31.1, 150.1))
- with patch(
- "aio_geojson_nsw_rfs_incidents.feed_manager.NswRuralFireServiceIncidentsFeed",
- wraps=NswRuralFireServiceIncidentsFeed,
- ) as mock_feed_manager, patch(
- "aio_geojson_client.feed.GeoJsonFeed.update"
- ) as mock_feed_update:
+ with (
+ patch(
+ "aio_geojson_nsw_rfs_incidents.feed_manager.NswRuralFireServiceIncidentsFeed",
+ wraps=NswRuralFireServiceIncidentsFeed,
+ ) as mock_feed_manager,
+ patch("aio_geojson_client.feed.GeoJsonFeed.update") as mock_feed_update,
+ ):
mock_feed_update.return_value = "OK", [mock_entry_1]
with assert_setup_component(1, geo_location.DOMAIN):
diff --git a/tests/components/nuheat/test_config_flow.py b/tests/components/nuheat/test_config_flow.py
index 37e2af0d307..1e7a6215143 100644
--- a/tests/components/nuheat/test_config_flow.py
+++ b/tests/components/nuheat/test_config_flow.py
@@ -24,15 +24,19 @@ async def test_form_user(hass: HomeAssistant) -> None:
mock_thermostat = _get_mock_thermostat_run()
- with patch(
- "homeassistant.components.nuheat.config_flow.nuheat.NuHeat.authenticate",
- return_value=True,
- ), patch(
- "homeassistant.components.nuheat.config_flow.nuheat.NuHeat.get_thermostat",
- return_value=mock_thermostat,
- ), patch(
- "homeassistant.components.nuheat.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.nuheat.config_flow.nuheat.NuHeat.authenticate",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.nuheat.config_flow.nuheat.NuHeat.get_thermostat",
+ return_value=mock_thermostat,
+ ),
+ patch(
+ "homeassistant.components.nuheat.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -103,12 +107,15 @@ async def test_form_invalid_thermostat(hass: HomeAssistant) -> None:
response_mock = MagicMock()
type(response_mock).status_code = HTTPStatus.INTERNAL_SERVER_ERROR
- with patch(
- "homeassistant.components.nuheat.config_flow.nuheat.NuHeat.authenticate",
- return_value=True,
- ), patch(
- "homeassistant.components.nuheat.config_flow.nuheat.NuHeat.get_thermostat",
- side_effect=requests.HTTPError(response=response_mock),
+ with (
+ patch(
+ "homeassistant.components.nuheat.config_flow.nuheat.NuHeat.authenticate",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.nuheat.config_flow.nuheat.NuHeat.get_thermostat",
+ side_effect=requests.HTTPError(response=response_mock),
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/nuki/test_config_flow.py b/tests/components/nuki/test_config_flow.py
index cc0a9b67b21..c7575f71545 100644
--- a/tests/components/nuki/test_config_flow.py
+++ b/tests/components/nuki/test_config_flow.py
@@ -23,13 +23,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.nuki.config_flow.NukiBridge.info",
- return_value=MOCK_INFO,
- ), patch(
- "homeassistant.components.nuki.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.nuki.config_flow.NukiBridge.info",
+ return_value=MOCK_INFO,
+ ),
+ patch(
+ "homeassistant.components.nuki.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -156,13 +159,16 @@ async def test_dhcp_flow(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == config_entries.SOURCE_USER
- with patch(
- "homeassistant.components.nuki.config_flow.NukiBridge.info",
- return_value=MOCK_INFO,
- ), patch(
- "homeassistant.components.nuki.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.nuki.config_flow.NukiBridge.info",
+ return_value=MOCK_INFO,
+ ),
+ patch(
+ "homeassistant.components.nuki.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -209,12 +215,15 @@ async def test_reauth_success(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
- with patch(
- "homeassistant.components.nuki.config_flow.NukiBridge.info",
- return_value=MOCK_INFO,
- ), patch(
- "homeassistant.components.nuki.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.nuki.config_flow.NukiBridge.info",
+ return_value=MOCK_INFO,
+ ),
+ patch(
+ "homeassistant.components.nuki.async_setup_entry",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/nut/test_config_flow.py b/tests/components/nut/test_config_flow.py
index 0fd9949ff37..56a7d7d9089 100644
--- a/tests/components/nut/test_config_flow.py
+++ b/tests/components/nut/test_config_flow.py
@@ -55,13 +55,16 @@ async def test_form_zeroconf(hass: HomeAssistant) -> None:
list_vars={"battery.voltage": "voltage", "ups.status": "OL"}, list_ups=["ups1"]
)
- with patch(
- "homeassistant.components.nut.AIONUTClient",
- return_value=mock_pynut,
- ), patch(
- "homeassistant.components.nut.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.nut.AIONUTClient",
+ return_value=mock_pynut,
+ ),
+ patch(
+ "homeassistant.components.nut.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_USERNAME: "test-username", CONF_PASSWORD: "test-password"},
@@ -93,13 +96,16 @@ async def test_form_user_one_ups(hass: HomeAssistant) -> None:
list_vars={"battery.voltage": "voltage", "ups.status": "OL"}, list_ups=["ups1"]
)
- with patch(
- "homeassistant.components.nut.AIONUTClient",
- return_value=mock_pynut,
- ), patch(
- "homeassistant.components.nut.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.nut.AIONUTClient",
+ return_value=mock_pynut,
+ ),
+ patch(
+ "homeassistant.components.nut.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -160,13 +166,16 @@ async def test_form_user_multiple_ups(hass: HomeAssistant) -> None:
assert result2["step_id"] == "ups"
assert result2["type"] == data_entry_flow.FlowResultType.FORM
- with patch(
- "homeassistant.components.nut.AIONUTClient",
- return_value=mock_pynut,
- ), patch(
- "homeassistant.components.nut.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.nut.AIONUTClient",
+ return_value=mock_pynut,
+ ),
+ patch(
+ "homeassistant.components.nut.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{CONF_ALIAS: "ups2"},
@@ -203,13 +212,16 @@ async def test_form_user_one_ups_with_ignored_entry(hass: HomeAssistant) -> None
list_vars={"battery.voltage": "voltage", "ups.status": "OL"}, list_ups=["ups1"]
)
- with patch(
- "homeassistant.components.nut.AIONUTClient",
- return_value=mock_pynut,
- ), patch(
- "homeassistant.components.nut.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.nut.AIONUTClient",
+ return_value=mock_pynut,
+ ),
+ patch(
+ "homeassistant.components.nut.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -264,12 +276,15 @@ async def test_form_cannot_connect(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "homeassistant.components.nut.AIONUTClient.list_ups",
- side_effect=NUTError("no route to host"),
- ), patch(
- "homeassistant.components.nut.AIONUTClient.list_vars",
- side_effect=NUTError("no route to host"),
+ with (
+ patch(
+ "homeassistant.components.nut.AIONUTClient.list_ups",
+ side_effect=NUTError("no route to host"),
+ ),
+ patch(
+ "homeassistant.components.nut.AIONUTClient.list_vars",
+ side_effect=NUTError("no route to host"),
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -285,12 +300,15 @@ async def test_form_cannot_connect(hass: HomeAssistant) -> None:
assert result2["errors"] == {"base": "cannot_connect"}
assert result2["description_placeholders"] == {"error": "no route to host"}
- with patch(
- "homeassistant.components.nut.AIONUTClient.list_ups",
- return_value={"ups1"},
- ), patch(
- "homeassistant.components.nut.AIONUTClient.list_vars",
- side_effect=Exception,
+ with (
+ patch(
+ "homeassistant.components.nut.AIONUTClient.list_ups",
+ return_value={"ups1"},
+ ),
+ patch(
+ "homeassistant.components.nut.AIONUTClient.list_vars",
+ side_effect=Exception,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -308,13 +326,16 @@ async def test_form_cannot_connect(hass: HomeAssistant) -> None:
mock_pynut = _get_mock_nutclient(
list_vars={"battery.voltage": "voltage", "ups.status": "OL"}, list_ups=["ups1"]
)
- with patch(
- "homeassistant.components.nut.AIONUTClient",
- return_value=mock_pynut,
- ), patch(
- "homeassistant.components.nut.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.nut.AIONUTClient",
+ return_value=mock_pynut,
+ ),
+ patch(
+ "homeassistant.components.nut.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -343,12 +364,15 @@ async def test_auth_failures(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "homeassistant.components.nut.AIONUTClient.list_ups",
- side_effect=NUTLoginError,
- ), patch(
- "homeassistant.components.nut.AIONUTClient.list_vars",
- side_effect=NUTLoginError,
+ with (
+ patch(
+ "homeassistant.components.nut.AIONUTClient.list_ups",
+ side_effect=NUTLoginError,
+ ),
+ patch(
+ "homeassistant.components.nut.AIONUTClient.list_vars",
+ side_effect=NUTLoginError,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -366,13 +390,16 @@ async def test_auth_failures(hass: HomeAssistant) -> None:
mock_pynut = _get_mock_nutclient(
list_vars={"battery.voltage": "voltage", "ups.status": "OL"}, list_ups=["ups1"]
)
- with patch(
- "homeassistant.components.nut.AIONUTClient",
- return_value=mock_pynut,
- ), patch(
- "homeassistant.components.nut.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.nut.AIONUTClient",
+ return_value=mock_pynut,
+ ),
+ patch(
+ "homeassistant.components.nut.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -412,12 +439,15 @@ async def test_reauth(hass: HomeAssistant) -> None:
assert len(flows) == 1
flow = flows[0]
- with patch(
- "homeassistant.components.nut.AIONUTClient.list_ups",
- side_effect=NUTLoginError,
- ), patch(
- "homeassistant.components.nut.AIONUTClient.list_vars",
- side_effect=NUTLoginError,
+ with (
+ patch(
+ "homeassistant.components.nut.AIONUTClient.list_ups",
+ side_effect=NUTLoginError,
+ ),
+ patch(
+ "homeassistant.components.nut.AIONUTClient.list_vars",
+ side_effect=NUTLoginError,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
flow["flow_id"],
@@ -433,13 +463,16 @@ async def test_reauth(hass: HomeAssistant) -> None:
mock_pynut = _get_mock_nutclient(
list_vars={"battery.voltage": "voltage", "ups.status": "OL"}, list_ups=["ups1"]
)
- with patch(
- "homeassistant.components.nut.AIONUTClient",
- return_value=mock_pynut,
- ), patch(
- "homeassistant.components.nut.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.nut.AIONUTClient",
+ return_value=mock_pynut,
+ ),
+ patch(
+ "homeassistant.components.nut.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
flow["flow_id"],
{
diff --git a/tests/components/nut/test_init.py b/tests/components/nut/test_init.py
index 4dd5f2357e8..61a5187407b 100644
--- a/tests/components/nut/test_init.py
+++ b/tests/components/nut/test_init.py
@@ -56,12 +56,15 @@ async def test_config_not_ready(hass: HomeAssistant) -> None:
)
entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.nut.AIONUTClient.list_ups",
- return_value={"ups1"},
- ), patch(
- "homeassistant.components.nut.AIONUTClient.list_vars",
- side_effect=NUTError,
+ with (
+ patch(
+ "homeassistant.components.nut.AIONUTClient.list_ups",
+ return_value={"ups1"},
+ ),
+ patch(
+ "homeassistant.components.nut.AIONUTClient.list_vars",
+ side_effect=NUTError,
+ ),
):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
@@ -76,12 +79,15 @@ async def test_auth_fails(hass: HomeAssistant) -> None:
)
entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.nut.AIONUTClient.list_ups",
- return_value={"ups1"},
- ), patch(
- "homeassistant.components.nut.AIONUTClient.list_vars",
- side_effect=NUTLoginError,
+ with (
+ patch(
+ "homeassistant.components.nut.AIONUTClient.list_ups",
+ return_value={"ups1"},
+ ),
+ patch(
+ "homeassistant.components.nut.AIONUTClient.list_vars",
+ side_effect=NUTLoginError,
+ ),
):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/nws/test_weather.py b/tests/components/nws/test_weather.py
index da365c52ffc..1d202277e6f 100644
--- a/tests/components/nws/test_weather.py
+++ b/tests/components/nws/test_weather.py
@@ -201,9 +201,10 @@ async def test_error_observation(
) -> None:
"""Test error during update observation."""
utc_time = dt_util.utcnow()
- with patch("homeassistant.components.nws.utcnow") as mock_utc, patch(
- "homeassistant.components.nws.weather.utcnow"
- ) as mock_utc_weather:
+ with (
+ patch("homeassistant.components.nws.utcnow") as mock_utc,
+ patch("homeassistant.components.nws.weather.utcnow") as mock_utc_weather,
+ ):
def increment_time(time):
mock_utc.return_value += time
diff --git a/tests/components/nzbget/test_config_flow.py b/tests/components/nzbget/test_config_flow.py
index 56ca19b0c95..c299d1d6dd5 100644
--- a/tests/components/nzbget/test_config_flow.py
+++ b/tests/components/nzbget/test_config_flow.py
@@ -31,7 +31,12 @@ async def test_user_form(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with _patch_version(), _patch_status(), _patch_history(), _patch_async_setup_entry() as mock_setup_entry:
+ with (
+ _patch_version(),
+ _patch_status(),
+ _patch_history(),
+ _patch_async_setup_entry() as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
USER_INPUT,
@@ -59,7 +64,12 @@ async def test_user_form_show_advanced_options(hass: HomeAssistant) -> None:
CONF_VERIFY_SSL: True,
}
- with _patch_version(), _patch_status(), _patch_history(), _patch_async_setup_entry() as mock_setup_entry:
+ with (
+ _patch_version(),
+ _patch_status(),
+ _patch_history(),
+ _patch_async_setup_entry() as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input_advanced,
diff --git a/tests/components/nzbget/test_init.py b/tests/components/nzbget/test_init.py
index a12cacf944e..a119bb953ce 100644
--- a/tests/components/nzbget/test_init.py
+++ b/tests/components/nzbget/test_init.py
@@ -32,9 +32,12 @@ async def test_async_setup_raises_entry_not_ready(hass: HomeAssistant) -> None:
config_entry = MockConfigEntry(domain=DOMAIN, data=ENTRY_CONFIG)
config_entry.add_to_hass(hass)
- with _patch_version(), patch(
- "homeassistant.components.nzbget.coordinator.NZBGetAPI.status",
- side_effect=NZBGetAPIException(),
+ with (
+ _patch_version(),
+ patch(
+ "homeassistant.components.nzbget.coordinator.NZBGetAPI.status",
+ side_effect=NZBGetAPIException(),
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
diff --git a/tests/components/octoprint/__init__.py b/tests/components/octoprint/__init__.py
index d97e4b1ce21..4a896736329 100644
--- a/tests/components/octoprint/__init__.py
+++ b/tests/components/octoprint/__init__.py
@@ -46,20 +46,25 @@ async def init_integration(
printer_info = OctoprintPrinterInfo(printer)
if job is None:
job = DEFAULT_JOB
- with patch("homeassistant.components.octoprint.PLATFORMS", [platform]), patch(
- "pyoctoprintapi.OctoprintClient.get_server_info", return_value={}
- ), patch(
- "pyoctoprintapi.OctoprintClient.get_printer_info",
- return_value=printer_info,
- ), patch(
- "pyoctoprintapi.OctoprintClient.get_job_info",
- return_value=OctoprintJobInfo(job),
- ), patch(
- "pyoctoprintapi.OctoprintClient.get_tracking_info",
- return_value=TrackingSetting({"unique_id": "uuid"}),
- ), patch(
- "pyoctoprintapi.OctoprintClient.get_discovery_info",
- return_value=DiscoverySettings({"upnpUuid": "uuid"}),
+ with (
+ patch("homeassistant.components.octoprint.PLATFORMS", [platform]),
+ patch("pyoctoprintapi.OctoprintClient.get_server_info", return_value={}),
+ patch(
+ "pyoctoprintapi.OctoprintClient.get_printer_info",
+ return_value=printer_info,
+ ),
+ patch(
+ "pyoctoprintapi.OctoprintClient.get_job_info",
+ return_value=OctoprintJobInfo(job),
+ ),
+ patch(
+ "pyoctoprintapi.OctoprintClient.get_tracking_info",
+ return_value=TrackingSetting({"unique_id": "uuid"}),
+ ),
+ patch(
+ "pyoctoprintapi.OctoprintClient.get_discovery_info",
+ return_value=DiscoverySettings({"upnpUuid": "uuid"}),
+ ),
):
config_entry = MockConfigEntry(
domain=DOMAIN,
diff --git a/tests/components/octoprint/test_button.py b/tests/components/octoprint/test_button.py
index 39e8fa5886c..7f272f9927e 100644
--- a/tests/components/octoprint/test_button.py
+++ b/tests/components/octoprint/test_button.py
@@ -57,9 +57,10 @@ async def test_pause_job(hass: HomeAssistant) -> None:
assert len(pause_command.mock_calls) == 0
# Test pausing the printer when it is stopped
- with patch(
- "pyoctoprintapi.OctoprintClient.pause_job"
- ) as pause_command, pytest.raises(InvalidPrinterState):
+ with (
+ patch("pyoctoprintapi.OctoprintClient.pause_job") as pause_command,
+ pytest.raises(InvalidPrinterState),
+ ):
coordinator.data["printer"] = OctoprintPrinterInfo(
{
"state": {"flags": {"printing": False, "paused": False}},
@@ -117,9 +118,10 @@ async def test_resume_job(hass: HomeAssistant) -> None:
assert len(resume_command.mock_calls) == 0
# Test resuming the printer when it is stopped
- with patch(
- "pyoctoprintapi.OctoprintClient.resume_job"
- ) as resume_command, pytest.raises(InvalidPrinterState):
+ with (
+ patch("pyoctoprintapi.OctoprintClient.resume_job") as resume_command,
+ pytest.raises(InvalidPrinterState),
+ ):
coordinator.data["printer"] = OctoprintPrinterInfo(
{
"state": {"flags": {"printing": False, "paused": False}},
diff --git a/tests/components/octoprint/test_config_flow.py b/tests/components/octoprint/test_config_flow.py
index 95e0ab0bb2b..4c8e22e524c 100644
--- a/tests/components/octoprint/test_config_flow.py
+++ b/tests/components/octoprint/test_config_flow.py
@@ -38,18 +38,23 @@ async def test_form(hass: HomeAssistant) -> None:
await hass.async_block_till_done()
assert result["type"] == "progress"
- with patch(
- "pyoctoprintapi.OctoprintClient.get_server_info",
- return_value=True,
- ), patch(
- "pyoctoprintapi.OctoprintClient.get_discovery_info",
- return_value=DiscoverySettings({"upnpUuid": "uuid"}),
- ), patch(
- "homeassistant.components.octoprint.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.octoprint.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "pyoctoprintapi.OctoprintClient.get_server_info",
+ return_value=True,
+ ),
+ patch(
+ "pyoctoprintapi.OctoprintClient.get_discovery_info",
+ return_value=DiscoverySettings({"upnpUuid": "uuid"}),
+ ),
+ patch(
+ "homeassistant.components.octoprint.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.octoprint.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
)
@@ -208,17 +213,20 @@ async def test_show_zerconf_form(hass: HomeAssistant) -> None:
assert result["type"] == "progress"
- with patch(
- "pyoctoprintapi.OctoprintClient.get_server_info",
- return_value=True,
- ), patch(
- "pyoctoprintapi.OctoprintClient.get_discovery_info",
- return_value=DiscoverySettings({"upnpUuid": "uuid"}),
- ), patch(
- "homeassistant.components.octoprint.async_setup", return_value=True
- ), patch(
- "homeassistant.components.octoprint.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "pyoctoprintapi.OctoprintClient.get_server_info",
+ return_value=True,
+ ),
+ patch(
+ "pyoctoprintapi.OctoprintClient.get_discovery_info",
+ return_value=DiscoverySettings({"upnpUuid": "uuid"}),
+ ),
+ patch("homeassistant.components.octoprint.async_setup", return_value=True),
+ patch(
+ "homeassistant.components.octoprint.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -274,17 +282,20 @@ async def test_show_ssdp_form(hass: HomeAssistant) -> None:
assert result["type"] == "progress"
- with patch(
- "pyoctoprintapi.OctoprintClient.get_server_info",
- return_value=True,
- ), patch(
- "pyoctoprintapi.OctoprintClient.get_discovery_info",
- return_value=DiscoverySettings({"upnpUuid": "uuid"}),
- ), patch(
- "homeassistant.components.octoprint.async_setup", return_value=True
- ), patch(
- "homeassistant.components.octoprint.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "pyoctoprintapi.OctoprintClient.get_server_info",
+ return_value=True,
+ ),
+ patch(
+ "pyoctoprintapi.OctoprintClient.get_discovery_info",
+ return_value=DiscoverySettings({"upnpUuid": "uuid"}),
+ ),
+ patch("homeassistant.components.octoprint.async_setup", return_value=True),
+ patch(
+ "homeassistant.components.octoprint.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -305,19 +316,23 @@ async def test_show_ssdp_form(hass: HomeAssistant) -> None:
async def test_import_yaml(hass: HomeAssistant) -> None:
"""Test that the yaml import works."""
- with patch(
- "pyoctoprintapi.OctoprintClient.get_server_info",
- return_value=True,
- ), patch(
- "pyoctoprintapi.OctoprintClient.get_discovery_info",
- return_value=DiscoverySettings({"upnpUuid": "uuid"}),
- ), patch(
- "pyoctoprintapi.OctoprintClient.request_app_key", return_value="test-key"
- ), patch(
- "homeassistant.components.octoprint.async_setup", return_value=True
- ), patch(
- "homeassistant.components.octoprint.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "pyoctoprintapi.OctoprintClient.get_server_info",
+ return_value=True,
+ ),
+ patch(
+ "pyoctoprintapi.OctoprintClient.get_discovery_info",
+ return_value=DiscoverySettings({"upnpUuid": "uuid"}),
+ ),
+ patch(
+ "pyoctoprintapi.OctoprintClient.request_app_key", return_value="test-key"
+ ),
+ patch("homeassistant.components.octoprint.async_setup", return_value=True),
+ patch(
+ "homeassistant.components.octoprint.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -345,12 +360,15 @@ async def test_import_duplicate_yaml(hass: HomeAssistant) -> None:
unique_id="uuid",
).add_to_hass(hass)
- with patch(
- "pyoctoprintapi.OctoprintClient.get_discovery_info",
- return_value=DiscoverySettings({"upnpUuid": "uuid"}),
- ), patch(
- "pyoctoprintapi.OctoprintClient.request_app_key", return_value="test-key"
- ) as request_app_key:
+ with (
+ patch(
+ "pyoctoprintapi.OctoprintClient.get_discovery_info",
+ return_value=DiscoverySettings({"upnpUuid": "uuid"}),
+ ),
+ patch(
+ "pyoctoprintapi.OctoprintClient.request_app_key", return_value="test-key"
+ ) as request_app_key,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
@@ -466,18 +484,23 @@ async def test_user_duplicate_entry(hass: HomeAssistant) -> None:
await hass.async_block_till_done()
assert result["type"] == "progress"
- with patch(
- "pyoctoprintapi.OctoprintClient.get_server_info",
- return_value=True,
- ), patch(
- "pyoctoprintapi.OctoprintClient.get_discovery_info",
- return_value=DiscoverySettings({"upnpUuid": "uuid"}),
- ), patch(
- "homeassistant.components.octoprint.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.octoprint.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "pyoctoprintapi.OctoprintClient.get_server_info",
+ return_value=True,
+ ),
+ patch(
+ "pyoctoprintapi.OctoprintClient.get_discovery_info",
+ return_value=DiscoverySettings({"upnpUuid": "uuid"}),
+ ),
+ patch(
+ "homeassistant.components.octoprint.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.octoprint.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
)
diff --git a/tests/components/omnilogic/test_config_flow.py b/tests/components/omnilogic/test_config_flow.py
index efcad70e7b6..1c0d6aefcf8 100644
--- a/tests/components/omnilogic/test_config_flow.py
+++ b/tests/components/omnilogic/test_config_flow.py
@@ -22,13 +22,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.omnilogic.config_flow.OmniLogic.connect",
- return_value=True,
- ), patch(
- "homeassistant.components.omnilogic.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.omnilogic.config_flow.OmniLogic.connect",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.omnilogic.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
DATA,
diff --git a/tests/components/onboarding/test_init.py b/tests/components/onboarding/test_init.py
index f6941098b18..6688ecccb5d 100644
--- a/tests/components/onboarding/test_init.py
+++ b/tests/components/onboarding/test_init.py
@@ -80,9 +80,10 @@ async def test_having_owner_finishes_user_step(
"""If owner user already exists, mark user step as complete."""
MockUser(is_owner=True).add_to_hass(hass)
- with patch(
- "homeassistant.components.onboarding.views.async_setup"
- ) as mock_setup, patch.object(onboarding, "STEPS", [onboarding.STEP_USER]):
+ with (
+ patch("homeassistant.components.onboarding.views.async_setup") as mock_setup,
+ patch.object(onboarding, "STEPS", [onboarding.STEP_USER]),
+ ):
assert await async_setup_component(hass, "onboarding", {})
assert len(mock_setup.mock_calls) == 0
diff --git a/tests/components/onboarding/test_views.py b/tests/components/onboarding/test_views.py
index 272d0e99773..556b590e746 100644
--- a/tests/components/onboarding/test_views.py
+++ b/tests/components/onboarding/test_views.py
@@ -80,30 +80,40 @@ async def mock_supervisor_fixture(hass, aioclient_mock):
},
},
)
- with patch.dict(os.environ, {"SUPERVISOR": "127.0.0.1"}), patch(
- "homeassistant.components.hassio.HassIO.is_connected",
- return_value=True,
- ), patch(
- "homeassistant.components.hassio.HassIO.get_info",
- return_value={},
- ), patch(
- "homeassistant.components.hassio.HassIO.get_host_info",
- return_value={},
- ), patch(
- "homeassistant.components.hassio.HassIO.get_store",
- return_value={},
- ), patch(
- "homeassistant.components.hassio.HassIO.get_supervisor_info",
- return_value={"diagnostics": True},
- ), patch(
- "homeassistant.components.hassio.HassIO.get_os_info",
- return_value={},
- ), patch(
- "homeassistant.components.hassio.HassIO.get_ingress_panels",
- return_value={"panels": {}},
- ), patch.dict(
- os.environ,
- {"SUPERVISOR_TOKEN": "123456"},
+ with (
+ patch.dict(os.environ, {"SUPERVISOR": "127.0.0.1"}),
+ patch(
+ "homeassistant.components.hassio.HassIO.is_connected",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.hassio.HassIO.get_info",
+ return_value={},
+ ),
+ patch(
+ "homeassistant.components.hassio.HassIO.get_host_info",
+ return_value={},
+ ),
+ patch(
+ "homeassistant.components.hassio.HassIO.get_store",
+ return_value={},
+ ),
+ patch(
+ "homeassistant.components.hassio.HassIO.get_supervisor_info",
+ return_value={"diagnostics": True},
+ ),
+ patch(
+ "homeassistant.components.hassio.HassIO.get_os_info",
+ return_value={},
+ ),
+ patch(
+ "homeassistant.components.hassio.HassIO.get_ingress_panels",
+ return_value={"panels": {}},
+ ),
+ patch.dict(
+ os.environ,
+ {"SUPERVISOR_TOKEN": "123456"},
+ ),
):
yield
@@ -111,16 +121,18 @@ async def mock_supervisor_fixture(hass, aioclient_mock):
@pytest.fixture
def mock_default_integrations():
"""Mock the default integrations set up during onboarding."""
- with patch(
- "homeassistant.components.rpi_power.config_flow.new_under_voltage"
- ), patch(
- "homeassistant.components.rpi_power.binary_sensor.new_under_voltage"
- ), patch(
- "homeassistant.components.met.async_setup_entry", return_value=True
- ), patch(
- "homeassistant.components.radio_browser.async_setup_entry", return_value=True
- ), patch(
- "homeassistant.components.shopping_list.async_setup_entry", return_value=True
+ with (
+ patch("homeassistant.components.rpi_power.config_flow.new_under_voltage"),
+ patch("homeassistant.components.rpi_power.binary_sensor.new_under_voltage"),
+ patch("homeassistant.components.met.async_setup_entry", return_value=True),
+ patch(
+ "homeassistant.components.radio_browser.async_setup_entry",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.shopping_list.async_setup_entry",
+ return_value=True,
+ ),
):
yield
diff --git a/tests/components/oncue/__init__.py b/tests/components/oncue/__init__.py
index b90f9df4f89..df1452b176e 100644
--- a/tests/components/oncue/__init__.py
+++ b/tests/components/oncue/__init__.py
@@ -802,11 +802,14 @@ MOCK_ASYNC_FETCH_ALL_UNAVAILABLE_DEVICE = {
def _patch_login_and_data():
@contextmanager
def _patcher():
- with patch(
- "homeassistant.components.oncue.Oncue.async_login",
- ), patch(
- "homeassistant.components.oncue.Oncue.async_fetch_all",
- return_value=MOCK_ASYNC_FETCH_ALL,
+ with (
+ patch(
+ "homeassistant.components.oncue.Oncue.async_login",
+ ),
+ patch(
+ "homeassistant.components.oncue.Oncue.async_fetch_all",
+ return_value=MOCK_ASYNC_FETCH_ALL,
+ ),
):
yield
@@ -816,11 +819,14 @@ def _patch_login_and_data():
def _patch_login_and_data_offline_device():
@contextmanager
def _patcher():
- with patch(
- "homeassistant.components.oncue.Oncue.async_login",
- ), patch(
- "homeassistant.components.oncue.Oncue.async_fetch_all",
- return_value=MOCK_ASYNC_FETCH_ALL_OFFLINE_DEVICE,
+ with (
+ patch(
+ "homeassistant.components.oncue.Oncue.async_login",
+ ),
+ patch(
+ "homeassistant.components.oncue.Oncue.async_fetch_all",
+ return_value=MOCK_ASYNC_FETCH_ALL_OFFLINE_DEVICE,
+ ),
):
yield
@@ -830,9 +836,12 @@ def _patch_login_and_data_offline_device():
def _patch_login_and_data_unavailable():
@contextmanager
def _patcher():
- with patch("homeassistant.components.oncue.Oncue.async_login"), patch(
- "homeassistant.components.oncue.Oncue.async_fetch_all",
- return_value=MOCK_ASYNC_FETCH_ALL_UNAVAILABLE_DEVICE,
+ with (
+ patch("homeassistant.components.oncue.Oncue.async_login"),
+ patch(
+ "homeassistant.components.oncue.Oncue.async_fetch_all",
+ return_value=MOCK_ASYNC_FETCH_ALL_UNAVAILABLE_DEVICE,
+ ),
):
yield
@@ -842,9 +851,12 @@ def _patch_login_and_data_unavailable():
def _patch_login_and_data_unavailable_device():
@contextmanager
def _patcher():
- with patch("homeassistant.components.oncue.Oncue.async_login"), patch(
- "homeassistant.components.oncue.Oncue.async_fetch_all",
- return_value=MOCK_ASYNC_FETCH_ALL_UNAVAILABLE_DEVICE,
+ with (
+ patch("homeassistant.components.oncue.Oncue.async_login"),
+ patch(
+ "homeassistant.components.oncue.Oncue.async_fetch_all",
+ return_value=MOCK_ASYNC_FETCH_ALL_UNAVAILABLE_DEVICE,
+ ),
):
yield
diff --git a/tests/components/oncue/test_config_flow.py b/tests/components/oncue/test_config_flow.py
index a58bcb98c0b..d757adec771 100644
--- a/tests/components/oncue/test_config_flow.py
+++ b/tests/components/oncue/test_config_flow.py
@@ -20,10 +20,13 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch("homeassistant.components.oncue.config_flow.Oncue.async_login"), patch(
- "homeassistant.components.oncue.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("homeassistant.components.oncue.config_flow.Oncue.async_login"),
+ patch(
+ "homeassistant.components.oncue.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
diff --git a/tests/components/onvif/__init__.py b/tests/components/onvif/__init__.py
index fea27f501e8..1e7c3273ced 100644
--- a/tests/components/onvif/__init__.py
+++ b/tests/components/onvif/__init__.py
@@ -187,13 +187,15 @@ async def setup_onvif_integration(
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.onvif.config_flow.get_device"
- ) as mock_onvif_camera, patch(
- "homeassistant.components.onvif.config_flow.wsdiscovery"
- ) as mock_discovery, patch(
- "homeassistant.components.onvif.ONVIFDevice"
- ) as mock_device:
+ with (
+ patch(
+ "homeassistant.components.onvif.config_flow.get_device"
+ ) as mock_onvif_camera,
+ patch(
+ "homeassistant.components.onvif.config_flow.wsdiscovery"
+ ) as mock_discovery,
+ patch("homeassistant.components.onvif.ONVIFDevice") as mock_device,
+ ):
setup_mock_onvif_camera(mock_onvif_camera, two_profiles=True)
# no discovery
mock_discovery.return_value = []
diff --git a/tests/components/onvif/test_config_flow.py b/tests/components/onvif/test_config_flow.py
index 5640472d6a2..e59db13d3bb 100644
--- a/tests/components/onvif/test_config_flow.py
+++ b/tests/components/onvif/test_config_flow.py
@@ -110,13 +110,15 @@ async def test_flow_discovered_devices(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.onvif.config_flow.get_device"
- ) as mock_onvif_camera, patch(
- "homeassistant.components.onvif.config_flow.WSDiscovery"
- ) as mock_discovery, patch(
- "homeassistant.components.onvif.ONVIFDevice"
- ) as mock_device:
+ with (
+ patch(
+ "homeassistant.components.onvif.config_flow.get_device"
+ ) as mock_onvif_camera,
+ patch(
+ "homeassistant.components.onvif.config_flow.WSDiscovery"
+ ) as mock_discovery,
+ patch("homeassistant.components.onvif.ONVIFDevice") as mock_device,
+ ):
setup_mock_onvif_camera(mock_onvif_camera)
setup_mock_discovery(mock_discovery)
setup_mock_device(mock_device)
@@ -181,13 +183,15 @@ async def test_flow_discovered_devices_ignore_configured_manual_input(
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.onvif.config_flow.get_device"
- ) as mock_onvif_camera, patch(
- "homeassistant.components.onvif.config_flow.WSDiscovery"
- ) as mock_discovery, patch(
- "homeassistant.components.onvif.ONVIFDevice"
- ) as mock_device:
+ with (
+ patch(
+ "homeassistant.components.onvif.config_flow.get_device"
+ ) as mock_onvif_camera,
+ patch(
+ "homeassistant.components.onvif.config_flow.WSDiscovery"
+ ) as mock_discovery,
+ patch("homeassistant.components.onvif.ONVIFDevice") as mock_device,
+ ):
setup_mock_onvif_camera(mock_onvif_camera)
setup_mock_discovery(mock_discovery, with_mac=True)
setup_mock_device(mock_device)
@@ -220,13 +224,15 @@ async def test_flow_discovered_no_device(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.onvif.config_flow.get_device"
- ) as mock_onvif_camera, patch(
- "homeassistant.components.onvif.config_flow.WSDiscovery"
- ) as mock_discovery, patch(
- "homeassistant.components.onvif.ONVIFDevice"
- ) as mock_device:
+ with (
+ patch(
+ "homeassistant.components.onvif.config_flow.get_device"
+ ) as mock_onvif_camera,
+ patch(
+ "homeassistant.components.onvif.config_flow.WSDiscovery"
+ ) as mock_discovery,
+ patch("homeassistant.components.onvif.ONVIFDevice") as mock_device,
+ ):
setup_mock_onvif_camera(mock_onvif_camera)
setup_mock_discovery(mock_discovery, no_devices=True)
setup_mock_device(mock_device)
@@ -263,13 +269,15 @@ async def test_flow_discovery_ignore_existing_and_abort(hass: HomeAssistant) ->
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.onvif.config_flow.get_device"
- ) as mock_onvif_camera, patch(
- "homeassistant.components.onvif.config_flow.WSDiscovery"
- ) as mock_discovery, patch(
- "homeassistant.components.onvif.ONVIFDevice"
- ) as mock_device:
+ with (
+ patch(
+ "homeassistant.components.onvif.config_flow.get_device"
+ ) as mock_onvif_camera,
+ patch(
+ "homeassistant.components.onvif.config_flow.WSDiscovery"
+ ) as mock_discovery,
+ patch("homeassistant.components.onvif.ONVIFDevice") as mock_device,
+ ):
setup_mock_onvif_camera(mock_onvif_camera)
setup_mock_discovery(mock_discovery, with_name=True, with_mac=True)
setup_mock_device(mock_device)
@@ -307,13 +315,15 @@ async def test_flow_manual_entry(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.onvif.config_flow.get_device"
- ) as mock_onvif_camera, patch(
- "homeassistant.components.onvif.config_flow.WSDiscovery"
- ) as mock_discovery, patch(
- "homeassistant.components.onvif.ONVIFDevice"
- ) as mock_device:
+ with (
+ patch(
+ "homeassistant.components.onvif.config_flow.get_device"
+ ) as mock_onvif_camera,
+ patch(
+ "homeassistant.components.onvif.config_flow.WSDiscovery"
+ ) as mock_discovery,
+ patch("homeassistant.components.onvif.ONVIFDevice") as mock_device,
+ ):
setup_mock_onvif_camera(mock_onvif_camera, two_profiles=True)
# no discovery
mock_discovery.return_value = []
@@ -364,13 +374,15 @@ async def test_flow_manual_entry_no_profiles(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.onvif.config_flow.get_device"
- ) as mock_onvif_camera, patch(
- "homeassistant.components.onvif.config_flow.WSDiscovery"
- ) as mock_discovery, patch(
- "homeassistant.components.onvif.ONVIFDevice"
- ) as mock_device:
+ with (
+ patch(
+ "homeassistant.components.onvif.config_flow.get_device"
+ ) as mock_onvif_camera,
+ patch(
+ "homeassistant.components.onvif.config_flow.WSDiscovery"
+ ) as mock_discovery,
+ patch("homeassistant.components.onvif.ONVIFDevice") as mock_device,
+ ):
setup_mock_onvif_camera(mock_onvif_camera, no_profiles=True)
# no discovery
mock_discovery.return_value = []
@@ -404,13 +416,15 @@ async def test_flow_manual_entry_no_mac(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.onvif.config_flow.get_device"
- ) as mock_onvif_camera, patch(
- "homeassistant.components.onvif.config_flow.WSDiscovery"
- ) as mock_discovery, patch(
- "homeassistant.components.onvif.ONVIFDevice"
- ) as mock_device:
+ with (
+ patch(
+ "homeassistant.components.onvif.config_flow.get_device"
+ ) as mock_onvif_camera,
+ patch(
+ "homeassistant.components.onvif.config_flow.WSDiscovery"
+ ) as mock_discovery,
+ patch("homeassistant.components.onvif.ONVIFDevice") as mock_device,
+ ):
setup_mock_onvif_camera(
mock_onvif_camera, with_serial=False, with_interfaces=False
)
@@ -446,13 +460,15 @@ async def test_flow_manual_entry_fails(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.onvif.config_flow.get_device"
- ) as mock_onvif_camera, patch(
- "homeassistant.components.onvif.config_flow.WSDiscovery"
- ) as mock_discovery, patch(
- "homeassistant.components.onvif.ONVIFDevice"
- ) as mock_device:
+ with (
+ patch(
+ "homeassistant.components.onvif.config_flow.get_device"
+ ) as mock_onvif_camera,
+ patch(
+ "homeassistant.components.onvif.config_flow.WSDiscovery"
+ ) as mock_discovery,
+ patch("homeassistant.components.onvif.ONVIFDevice") as mock_device,
+ ):
setup_mock_onvif_camera(
mock_onvif_camera, two_profiles=True, profiles_transient_failure=True
)
@@ -554,13 +570,15 @@ async def test_flow_manual_entry_wrong_password(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.onvif.config_flow.get_device"
- ) as mock_onvif_camera, patch(
- "homeassistant.components.onvif.config_flow.WSDiscovery"
- ) as mock_discovery, patch(
- "homeassistant.components.onvif.ONVIFDevice"
- ) as mock_device:
+ with (
+ patch(
+ "homeassistant.components.onvif.config_flow.get_device"
+ ) as mock_onvif_camera,
+ patch(
+ "homeassistant.components.onvif.config_flow.WSDiscovery"
+ ) as mock_discovery,
+ patch("homeassistant.components.onvif.ONVIFDevice") as mock_device,
+ ):
setup_mock_onvif_camera(mock_onvif_camera, two_profiles=True, auth_fail=True)
# no discovery
mock_discovery.return_value = []
@@ -764,14 +782,16 @@ async def test_form_reauth(hass: HomeAssistant) -> None:
== entry.data[CONF_USERNAME]
)
- with patch(
- "homeassistant.components.onvif.config_flow.get_device"
- ) as mock_onvif_camera, patch(
- "homeassistant.components.onvif.ONVIFDevice"
- ) as mock_device, patch(
- "homeassistant.components.onvif.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.onvif.config_flow.get_device"
+ ) as mock_onvif_camera,
+ patch("homeassistant.components.onvif.ONVIFDevice") as mock_device,
+ patch(
+ "homeassistant.components.onvif.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
setup_mock_onvif_camera(mock_onvif_camera, auth_failure=True)
setup_mock_device(mock_device)
@@ -791,14 +811,16 @@ async def test_form_reauth(hass: HomeAssistant) -> None:
"error": "not authorized (subcodes:NotAuthorized)"
}
- with patch(
- "homeassistant.components.onvif.config_flow.get_device"
- ) as mock_onvif_camera, patch(
- "homeassistant.components.onvif.ONVIFDevice"
- ) as mock_device, patch(
- "homeassistant.components.onvif.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.onvif.config_flow.get_device"
+ ) as mock_onvif_camera,
+ patch("homeassistant.components.onvif.ONVIFDevice") as mock_device,
+ patch(
+ "homeassistant.components.onvif.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
setup_mock_onvif_camera(mock_onvif_camera)
setup_mock_device(mock_device)
@@ -831,13 +853,15 @@ async def test_flow_manual_entry_updates_existing_user_password(
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.onvif.config_flow.get_device"
- ) as mock_onvif_camera, patch(
- "homeassistant.components.onvif.config_flow.WSDiscovery"
- ) as mock_discovery, patch(
- "homeassistant.components.onvif.ONVIFDevice"
- ) as mock_device:
+ with (
+ patch(
+ "homeassistant.components.onvif.config_flow.get_device"
+ ) as mock_onvif_camera,
+ patch(
+ "homeassistant.components.onvif.config_flow.WSDiscovery"
+ ) as mock_discovery,
+ patch("homeassistant.components.onvif.ONVIFDevice") as mock_device,
+ ):
setup_mock_onvif_camera(mock_onvif_camera, two_profiles=True)
# no discovery
mock_discovery.return_value = []
@@ -882,13 +906,15 @@ async def test_flow_manual_entry_wrong_port(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.onvif.config_flow.get_device"
- ) as mock_onvif_camera, patch(
- "homeassistant.components.onvif.config_flow.WSDiscovery"
- ) as mock_discovery, patch(
- "homeassistant.components.onvif.ONVIFDevice"
- ) as mock_device:
+ with (
+ patch(
+ "homeassistant.components.onvif.config_flow.get_device"
+ ) as mock_onvif_camera,
+ patch(
+ "homeassistant.components.onvif.config_flow.WSDiscovery"
+ ) as mock_discovery,
+ patch("homeassistant.components.onvif.ONVIFDevice") as mock_device,
+ ):
setup_mock_onvif_camera(mock_onvif_camera, wrong_port=True)
# no discovery
mock_discovery.return_value = []
diff --git a/tests/components/openai_conversation/test_config_flow.py b/tests/components/openai_conversation/test_config_flow.py
index 85fd70f6b84..659b3825472 100644
--- a/tests/components/openai_conversation/test_config_flow.py
+++ b/tests/components/openai_conversation/test_config_flow.py
@@ -33,12 +33,15 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with patch(
- "homeassistant.components.openai_conversation.config_flow.openai.resources.models.AsyncModels.list",
- ), patch(
- "homeassistant.components.openai_conversation.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.openai_conversation.config_flow.openai.resources.models.AsyncModels.list",
+ ),
+ patch(
+ "homeassistant.components.openai_conversation.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
diff --git a/tests/components/openai_conversation/test_init.py b/tests/components/openai_conversation/test_init.py
index ebacc08700e..3a8db2a71c0 100644
--- a/tests/components/openai_conversation/test_init.py
+++ b/tests/components/openai_conversation/test_init.py
@@ -169,11 +169,14 @@ async def test_template_error(
"prompt": "talk like a {% if True %}smarthome{% else %}pirate please.",
},
)
- with patch(
- "openai.resources.models.AsyncModels.list",
- ), patch(
- "openai.resources.chat.completions.AsyncCompletions.create",
- new_callable=AsyncMock,
+ with (
+ patch(
+ "openai.resources.models.AsyncModels.list",
+ ),
+ patch(
+ "openai.resources.chat.completions.AsyncCompletions.create",
+ new_callable=AsyncMock,
+ ),
):
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
@@ -314,12 +317,17 @@ async def test_generate_image_service_error(
mock_config_entry: MockConfigEntry,
) -> None:
"""Test generate image service handles errors."""
- with patch(
- "openai.resources.images.AsyncImages.generate",
- side_effect=RateLimitError(
- response=Response(status_code=None, request=""), body=None, message="Reason"
+ with (
+ patch(
+ "openai.resources.images.AsyncImages.generate",
+ side_effect=RateLimitError(
+ response=Response(status_code=None, request=""),
+ body=None,
+ message="Reason",
+ ),
),
- ), pytest.raises(HomeAssistantError, match="Error generating image: Reason"):
+ pytest.raises(HomeAssistantError, match="Error generating image: Reason"),
+ ):
await hass.services.async_call(
"openai_conversation",
"generate_image",
diff --git a/tests/components/opengarage/test_config_flow.py b/tests/components/opengarage/test_config_flow.py
index f730cf95703..7d3e44017b0 100644
--- a/tests/components/opengarage/test_config_flow.py
+++ b/tests/components/opengarage/test_config_flow.py
@@ -21,13 +21,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with patch(
- "opengarage.OpenGarage.update_state",
- return_value={"name": "Name of the device", "mac": "unique"},
- ), patch(
- "homeassistant.components.opengarage.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "opengarage.OpenGarage.update_state",
+ return_value={"name": "Name of the device", "mac": "unique"},
+ ),
+ patch(
+ "homeassistant.components.opengarage.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"host": "http://1.1.1.1", "device_key": "AfsasdnfkjDD"},
diff --git a/tests/components/openhome/test_update.py b/tests/components/openhome/test_update.py
index 74fecdb4ed6..d3a328b9f9e 100644
--- a/tests/components/openhome/test_update.py
+++ b/tests/components/openhome/test_update.py
@@ -72,9 +72,10 @@ async def setup_integration(
)
entry.add_to_hass(hass)
- with patch("homeassistant.components.openhome.PLATFORMS", [Platform.UPDATE]), patch(
- "homeassistant.components.openhome.Device", MagicMock()
- ) as mock_device:
+ with (
+ patch("homeassistant.components.openhome.PLATFORMS", [Platform.UPDATE]),
+ patch("homeassistant.components.openhome.Device", MagicMock()) as mock_device,
+ ):
mock_device.return_value.init = AsyncMock()
mock_device.return_value.uuid = MagicMock(return_value="uuid")
mock_device.return_value.manufacturer = MagicMock(return_value="manufacturer")
diff --git a/tests/components/opensky/test_config_flow.py b/tests/components/opensky/test_config_flow.py
index 43192cdaff2..c3ae876d36e 100644
--- a/tests/components/opensky/test_config_flow.py
+++ b/tests/components/opensky/test_config_flow.py
@@ -106,9 +106,12 @@ async def test_options_flow_failures(
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "init"
assert result["errors"]["base"] == error
- with patch("python_opensky.OpenSky.authenticate"), patch(
- "python_opensky.OpenSky.get_states",
- return_value=get_states_response_fixture("opensky/states_1.json"),
+ with (
+ patch("python_opensky.OpenSky.authenticate"),
+ patch(
+ "python_opensky.OpenSky.get_states",
+ return_value=get_states_response_fixture("opensky/states_1.json"),
+ ),
):
result = await hass.config_entries.options.async_configure(
result["flow_id"],
@@ -140,9 +143,12 @@ async def test_options_flow(
entry = hass.config_entries.async_entries(DOMAIN)[0]
result = await hass.config_entries.options.async_init(entry.entry_id)
await hass.async_block_till_done()
- with patch("python_opensky.OpenSky.authenticate"), patch(
- "python_opensky.OpenSky.get_states",
- return_value=get_states_response_fixture("opensky/states_1.json"),
+ with (
+ patch("python_opensky.OpenSky.authenticate"),
+ patch(
+ "python_opensky.OpenSky.get_states",
+ return_value=get_states_response_fixture("opensky/states_1.json"),
+ ),
):
result = await hass.config_entries.options.async_configure(
result["flow_id"],
diff --git a/tests/components/opentherm_gw/test_config_flow.py b/tests/components/opentherm_gw/test_config_flow.py
index 57229d3b49f..c92f23f46b4 100644
--- a/tests/components/opentherm_gw/test_config_flow.py
+++ b/tests/components/opentherm_gw/test_config_flow.py
@@ -37,18 +37,22 @@ async def test_form_user(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.opentherm_gw.async_setup",
- return_value=True,
- ) as mock_setup, patch(
- "homeassistant.components.opentherm_gw.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "pyotgw.OpenThermGateway.connect", return_value=MINIMAL_STATUS
- ) as mock_pyotgw_connect, patch(
- "pyotgw.OpenThermGateway.disconnect", return_value=None
- ) as mock_pyotgw_disconnect, patch(
- "pyotgw.status.StatusManager._process_updates", return_value=None
+ with (
+ patch(
+ "homeassistant.components.opentherm_gw.async_setup",
+ return_value=True,
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.opentherm_gw.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "pyotgw.OpenThermGateway.connect", return_value=MINIMAL_STATUS
+ ) as mock_pyotgw_connect,
+ patch(
+ "pyotgw.OpenThermGateway.disconnect", return_value=None
+ ) as mock_pyotgw_disconnect,
+ patch("pyotgw.status.StatusManager._process_updates", return_value=None),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_NAME: "Test Entry 1", CONF_DEVICE: "/dev/ttyUSB0"}
@@ -71,18 +75,22 @@ async def test_form_user(hass: HomeAssistant) -> None:
async def test_form_import(hass: HomeAssistant) -> None:
"""Test import from existing config."""
- with patch(
- "homeassistant.components.opentherm_gw.async_setup",
- return_value=True,
- ) as mock_setup, patch(
- "homeassistant.components.opentherm_gw.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "pyotgw.OpenThermGateway.connect", return_value=MINIMAL_STATUS
- ) as mock_pyotgw_connect, patch(
- "pyotgw.OpenThermGateway.disconnect", return_value=None
- ) as mock_pyotgw_disconnect, patch(
- "pyotgw.status.StatusManager._process_updates", return_value=None
+ with (
+ patch(
+ "homeassistant.components.opentherm_gw.async_setup",
+ return_value=True,
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.opentherm_gw.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "pyotgw.OpenThermGateway.connect", return_value=MINIMAL_STATUS
+ ) as mock_pyotgw_connect,
+ patch(
+ "pyotgw.OpenThermGateway.disconnect", return_value=None
+ ) as mock_pyotgw_disconnect,
+ patch("pyotgw.status.StatusManager._process_updates", return_value=None),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -115,18 +123,22 @@ async def test_form_duplicate_entries(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "homeassistant.components.opentherm_gw.async_setup",
- return_value=True,
- ) as mock_setup, patch(
- "homeassistant.components.opentherm_gw.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "pyotgw.OpenThermGateway.connect", return_value=MINIMAL_STATUS
- ) as mock_pyotgw_connect, patch(
- "pyotgw.OpenThermGateway.disconnect", return_value=None
- ) as mock_pyotgw_disconnect, patch(
- "pyotgw.status.StatusManager._process_updates", return_value=None
+ with (
+ patch(
+ "homeassistant.components.opentherm_gw.async_setup",
+ return_value=True,
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.opentherm_gw.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "pyotgw.OpenThermGateway.connect", return_value=MINIMAL_STATUS
+ ) as mock_pyotgw_connect,
+ patch(
+ "pyotgw.OpenThermGateway.disconnect", return_value=None
+ ) as mock_pyotgw_disconnect,
+ patch("pyotgw.status.StatusManager._process_updates", return_value=None),
):
result1 = await hass.config_entries.flow.async_configure(
flow1["flow_id"], {CONF_NAME: "Test Entry 1", CONF_DEVICE: "/dev/ttyUSB0"}
@@ -154,10 +166,11 @@ async def test_form_connection_timeout(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "pyotgw.OpenThermGateway.connect", side_effect=(TimeoutError)
- ) as mock_connect, patch(
- "pyotgw.status.StatusManager._process_updates", return_value=None
+ with (
+ patch(
+ "pyotgw.OpenThermGateway.connect", side_effect=(TimeoutError)
+ ) as mock_connect,
+ patch("pyotgw.status.StatusManager._process_updates", return_value=None),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -175,10 +188,11 @@ async def test_form_connection_error(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "pyotgw.OpenThermGateway.connect", side_effect=(SerialException)
- ) as mock_connect, patch(
- "pyotgw.status.StatusManager._process_updates", return_value=None
+ with (
+ patch(
+ "pyotgw.OpenThermGateway.connect", side_effect=(SerialException)
+ ) as mock_connect,
+ patch("pyotgw.status.StatusManager._process_updates", return_value=None),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_NAME: "Test Entry 1", CONF_DEVICE: "/dev/ttyUSB0"}
@@ -206,15 +220,19 @@ async def test_options_migration(hass: HomeAssistant) -> None:
)
entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.opentherm_gw.OpenThermGatewayDevice.connect_and_subscribe",
- return_value=True,
- ), patch(
- "homeassistant.components.opentherm_gw.async_setup",
- return_value=True,
- ), patch(
- "pyotgw.status.StatusManager._process_updates",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.components.opentherm_gw.OpenThermGatewayDevice.connect_and_subscribe",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.opentherm_gw.async_setup",
+ return_value=True,
+ ),
+ patch(
+ "pyotgw.status.StatusManager._process_updates",
+ return_value=None,
+ ),
):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
@@ -251,10 +269,11 @@ async def test_options_form(hass: HomeAssistant) -> None:
)
entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.opentherm_gw.async_setup", return_value=True
- ), patch(
- "homeassistant.components.opentherm_gw.async_setup_entry", return_value=True
+ with (
+ patch("homeassistant.components.opentherm_gw.async_setup", return_value=True),
+ patch(
+ "homeassistant.components.opentherm_gw.async_setup_entry", return_value=True
+ ),
):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/opentherm_gw/test_init.py b/tests/components/opentherm_gw/test_init.py
index c068686a607..77d43039c2b 100644
--- a/tests/components/opentherm_gw/test_init.py
+++ b/tests/components/opentherm_gw/test_init.py
@@ -36,10 +36,13 @@ async def test_device_registry_insert(hass: HomeAssistant) -> None:
"""Test that the device registry is initialized correctly."""
MOCK_CONFIG_ENTRY.add_to_hass(hass)
- with patch(
- "homeassistant.components.opentherm_gw.OpenThermGatewayDevice.cleanup",
- return_value=None,
- ), patch("pyotgw.OpenThermGateway.connect", return_value=MINIMAL_STATUS):
+ with (
+ patch(
+ "homeassistant.components.opentherm_gw.OpenThermGatewayDevice.cleanup",
+ return_value=None,
+ ),
+ patch("pyotgw.OpenThermGateway.connect", return_value=MINIMAL_STATUS),
+ ):
await setup.async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
@@ -67,10 +70,13 @@ async def test_device_registry_update(
sw_version=VERSION_OLD,
)
- with patch(
- "homeassistant.components.opentherm_gw.OpenThermGatewayDevice.cleanup",
- return_value=None,
- ), patch("pyotgw.OpenThermGateway.connect", return_value=MINIMAL_STATUS_UPD):
+ with (
+ patch(
+ "homeassistant.components.opentherm_gw.OpenThermGatewayDevice.cleanup",
+ return_value=None,
+ ),
+ patch("pyotgw.OpenThermGateway.connect", return_value=MINIMAL_STATUS_UPD),
+ ):
await setup.async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
diff --git a/tests/components/openuv/conftest.py b/tests/components/openuv/conftest.py
index 414a73435fc..5aad7d5b1a6 100644
--- a/tests/components/openuv/conftest.py
+++ b/tests/components/openuv/conftest.py
@@ -79,9 +79,12 @@ def data_uv_index_fixture():
@pytest.fixture(name="mock_pyopenuv")
async def mock_pyopenuv_fixture(client):
"""Define a fixture to patch pyopenuv."""
- with patch(
- "homeassistant.components.openuv.config_flow.Client", return_value=client
- ), patch("homeassistant.components.openuv.Client", return_value=client):
+ with (
+ patch(
+ "homeassistant.components.openuv.config_flow.Client", return_value=client
+ ),
+ patch("homeassistant.components.openuv.Client", return_value=client),
+ ):
yield
diff --git a/tests/components/oralb/test_sensor.py b/tests/components/oralb/test_sensor.py
index b1210712e7a..82f9b86b352 100644
--- a/tests/components/oralb/test_sensor.py
+++ b/tests/components/oralb/test_sensor.py
@@ -58,9 +58,12 @@ async def test_sensors(
# Fastforward time without BLE advertisements
monotonic_now = start_monotonic + FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 1
- with patch_bluetooth_time(
- monotonic_now,
- ), patch_all_discovered_devices([]):
+ with (
+ patch_bluetooth_time(
+ monotonic_now,
+ ),
+ patch_all_discovered_devices([]),
+ ):
async_fire_time_changed(
hass,
dt_util.utcnow()
@@ -107,9 +110,12 @@ async def test_sensors_io_series_4(
# Fast-forward time without BLE advertisements
monotonic_now = start_monotonic + FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 1
- with patch_bluetooth_time(
- monotonic_now,
- ), patch_all_discovered_devices([]):
+ with (
+ patch_bluetooth_time(
+ monotonic_now,
+ ),
+ patch_all_discovered_devices([]),
+ ):
async_fire_time_changed(
hass,
dt_util.utcnow()
diff --git a/tests/components/osoenergy/test_config_flow.py b/tests/components/osoenergy/test_config_flow.py
index 3a2de0e44f5..c88035eef28 100644
--- a/tests/components/osoenergy/test_config_flow.py
+++ b/tests/components/osoenergy/test_config_flow.py
@@ -26,12 +26,15 @@ async def test_user_flow(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.osoenergy.config_flow.OSOEnergy.get_user_email",
- return_value=TEST_USER_EMAIL,
- ), patch(
- "homeassistant.components.osoenergy.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.osoenergy.config_flow.OSOEnergy.get_user_email",
+ return_value=TEST_USER_EMAIL,
+ ),
+ patch(
+ "homeassistant.components.osoenergy.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_API_KEY: SUBSCRIPTION_KEY},
diff --git a/tests/components/otbr/conftest.py b/tests/components/otbr/conftest.py
index 8b102f32b8e..82f167cdd23 100644
--- a/tests/components/otbr/conftest.py
+++ b/tests/components/otbr/conftest.py
@@ -28,15 +28,19 @@ async def otbr_config_entry_multipan_fixture(hass):
title="Open Thread Border Router",
)
config_entry.add_to_hass(hass)
- with patch(
- "python_otbr_api.OTBR.get_active_dataset_tlvs", return_value=DATASET_CH16
- ), patch(
- "python_otbr_api.OTBR.get_border_agent_id", return_value=TEST_BORDER_AGENT_ID
- ), patch(
- "python_otbr_api.OTBR.get_extended_address",
- return_value=TEST_BORDER_AGENT_EXTENDED_ADDRESS,
- ), patch(
- "homeassistant.components.otbr.util.compute_pskc"
+ with (
+ patch(
+ "python_otbr_api.OTBR.get_active_dataset_tlvs", return_value=DATASET_CH16
+ ),
+ patch(
+ "python_otbr_api.OTBR.get_border_agent_id",
+ return_value=TEST_BORDER_AGENT_ID,
+ ),
+ patch(
+ "python_otbr_api.OTBR.get_extended_address",
+ return_value=TEST_BORDER_AGENT_EXTENDED_ADDRESS,
+ ),
+ patch("homeassistant.components.otbr.util.compute_pskc"),
): # Patch to speed up tests
assert await hass.config_entries.async_setup(config_entry.entry_id)
@@ -51,15 +55,19 @@ async def otbr_config_entry_thread_fixture(hass):
title="Open Thread Border Router",
)
config_entry.add_to_hass(hass)
- with patch(
- "python_otbr_api.OTBR.get_active_dataset_tlvs", return_value=DATASET_CH16
- ), patch(
- "python_otbr_api.OTBR.get_border_agent_id", return_value=TEST_BORDER_AGENT_ID
- ), patch(
- "python_otbr_api.OTBR.get_extended_address",
- return_value=TEST_BORDER_AGENT_EXTENDED_ADDRESS,
- ), patch(
- "homeassistant.components.otbr.util.compute_pskc"
+ with (
+ patch(
+ "python_otbr_api.OTBR.get_active_dataset_tlvs", return_value=DATASET_CH16
+ ),
+ patch(
+ "python_otbr_api.OTBR.get_border_agent_id",
+ return_value=TEST_BORDER_AGENT_ID,
+ ),
+ patch(
+ "python_otbr_api.OTBR.get_extended_address",
+ return_value=TEST_BORDER_AGENT_EXTENDED_ADDRESS,
+ ),
+ patch("homeassistant.components.otbr.util.compute_pskc"),
): # Patch to speed up tests
assert await hass.config_entries.async_setup(config_entry.entry_id)
diff --git a/tests/components/otbr/test_config_flow.py b/tests/components/otbr/test_config_flow.py
index 18c62257803..e9ad5681549 100644
--- a/tests/components/otbr/test_config_flow.py
+++ b/tests/components/otbr/test_config_flow.py
@@ -105,13 +105,16 @@ async def test_user_flow_router_not_setup(
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.otbr.config_flow.async_get_preferred_dataset",
- return_value=None,
- ), patch(
- "homeassistant.components.otbr.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.otbr.config_flow.async_get_preferred_dataset",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.otbr.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -249,11 +252,12 @@ async def test_hassio_discovery_flow_yellow(
"version": None,
}
- with patch(
- "homeassistant.components.otbr.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.otbr.config_flow.yellow_hardware.async_info"
+ with (
+ patch(
+ "homeassistant.components.otbr.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch("homeassistant.components.otbr.config_flow.yellow_hardware.async_info"),
):
result = await hass.config_entries.flow.async_init(
otbr.DOMAIN, context={"source": "hassio"}, data=HASSIO_DATA
@@ -414,13 +418,16 @@ async def test_hassio_discovery_flow_router_not_setup(
aioclient_mock.put(f"{url}/node/dataset/active", status=HTTPStatus.CREATED)
aioclient_mock.put(f"{url}/node/state", status=HTTPStatus.OK)
- with patch(
- "homeassistant.components.otbr.config_flow.async_get_preferred_dataset",
- return_value=None,
- ), patch(
- "homeassistant.components.otbr.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.otbr.config_flow.async_get_preferred_dataset",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.otbr.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
otbr.DOMAIN, context={"source": "hassio"}, data=HASSIO_DATA
)
@@ -468,13 +475,16 @@ async def test_hassio_discovery_flow_router_not_setup_has_preferred(
aioclient_mock.put(f"{url}/node/dataset/active", status=HTTPStatus.CREATED)
aioclient_mock.put(f"{url}/node/state", status=HTTPStatus.OK)
- with patch(
- "homeassistant.components.otbr.config_flow.async_get_preferred_dataset",
- return_value=DATASET_CH15.hex(),
- ), patch(
- "homeassistant.components.otbr.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.otbr.config_flow.async_get_preferred_dataset",
+ return_value=DATASET_CH15.hex(),
+ ),
+ patch(
+ "homeassistant.components.otbr.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
otbr.DOMAIN, context={"source": "hassio"}, data=HASSIO_DATA
)
@@ -523,13 +533,16 @@ async def test_hassio_discovery_flow_router_not_setup_has_preferred_2(
multiprotocol_addon_manager_mock.async_get_channel.return_value = 15
- with patch(
- "homeassistant.components.otbr.config_flow.async_get_preferred_dataset",
- return_value=DATASET_CH16.hex(),
- ), patch(
- "homeassistant.components.otbr.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.otbr.config_flow.async_get_preferred_dataset",
+ return_value=DATASET_CH16.hex(),
+ ),
+ patch(
+ "homeassistant.components.otbr.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
otbr.DOMAIN, context={"source": "hassio"}, data=HASSIO_DATA
)
diff --git a/tests/components/otbr/test_init.py b/tests/components/otbr/test_init.py
index 39805728a3e..7fd4ef6b016 100644
--- a/tests/components/otbr/test_init.py
+++ b/tests/components/otbr/test_init.py
@@ -64,16 +64,22 @@ async def test_import_dataset(hass: HomeAssistant, mock_async_zeroconf: None) ->
)
config_entry.add_to_hass(hass)
- with patch(
- "python_otbr_api.OTBR.get_active_dataset_tlvs", return_value=DATASET_CH16
- ), patch(
- "python_otbr_api.OTBR.get_border_agent_id", return_value=TEST_BORDER_AGENT_ID
- ), patch(
- "python_otbr_api.OTBR.get_extended_address",
- return_value=TEST_BORDER_AGENT_EXTENDED_ADDRESS,
- ), patch(
- "homeassistant.components.thread.dataset_store.BORDER_AGENT_DISCOVERY_TIMEOUT",
- 0.1,
+ with (
+ patch(
+ "python_otbr_api.OTBR.get_active_dataset_tlvs", return_value=DATASET_CH16
+ ),
+ patch(
+ "python_otbr_api.OTBR.get_border_agent_id",
+ return_value=TEST_BORDER_AGENT_ID,
+ ),
+ patch(
+ "python_otbr_api.OTBR.get_extended_address",
+ return_value=TEST_BORDER_AGENT_EXTENDED_ADDRESS,
+ ),
+ patch(
+ "homeassistant.components.thread.dataset_store.BORDER_AGENT_DISCOVERY_TIMEOUT",
+ 0.1,
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
@@ -135,16 +141,22 @@ async def test_import_share_radio_channel_collision(
title="My OTBR",
)
config_entry.add_to_hass(hass)
- with patch(
- "python_otbr_api.OTBR.get_active_dataset_tlvs", return_value=DATASET_CH16
- ), patch(
- "python_otbr_api.OTBR.get_border_agent_id", return_value=TEST_BORDER_AGENT_ID
- ), patch(
- "python_otbr_api.OTBR.get_extended_address",
- return_value=TEST_BORDER_AGENT_EXTENDED_ADDRESS,
- ), patch(
- "homeassistant.components.thread.dataset_store.DatasetStore.async_add"
- ) as mock_add:
+ with (
+ patch(
+ "python_otbr_api.OTBR.get_active_dataset_tlvs", return_value=DATASET_CH16
+ ),
+ patch(
+ "python_otbr_api.OTBR.get_border_agent_id",
+ return_value=TEST_BORDER_AGENT_ID,
+ ),
+ patch(
+ "python_otbr_api.OTBR.get_extended_address",
+ return_value=TEST_BORDER_AGENT_EXTENDED_ADDRESS,
+ ),
+ patch(
+ "homeassistant.components.thread.dataset_store.DatasetStore.async_add"
+ ) as mock_add,
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id)
mock_add.assert_called_once_with(
@@ -178,16 +190,20 @@ async def test_import_share_radio_no_channel_collision(
title="My OTBR",
)
config_entry.add_to_hass(hass)
- with patch(
- "python_otbr_api.OTBR.get_active_dataset_tlvs", return_value=dataset
- ), patch(
- "python_otbr_api.OTBR.get_border_agent_id", return_value=TEST_BORDER_AGENT_ID
- ), patch(
- "python_otbr_api.OTBR.get_extended_address",
- return_value=TEST_BORDER_AGENT_EXTENDED_ADDRESS,
- ), patch(
- "homeassistant.components.thread.dataset_store.DatasetStore.async_add"
- ) as mock_add:
+ with (
+ patch("python_otbr_api.OTBR.get_active_dataset_tlvs", return_value=dataset),
+ patch(
+ "python_otbr_api.OTBR.get_border_agent_id",
+ return_value=TEST_BORDER_AGENT_ID,
+ ),
+ patch(
+ "python_otbr_api.OTBR.get_extended_address",
+ return_value=TEST_BORDER_AGENT_EXTENDED_ADDRESS,
+ ),
+ patch(
+ "homeassistant.components.thread.dataset_store.DatasetStore.async_add"
+ ) as mock_add,
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id)
mock_add.assert_called_once_with(
@@ -219,16 +235,20 @@ async def test_import_insecure_dataset(hass: HomeAssistant, dataset: bytes) -> N
title="My OTBR",
)
config_entry.add_to_hass(hass)
- with patch(
- "python_otbr_api.OTBR.get_active_dataset_tlvs", return_value=dataset
- ), patch(
- "python_otbr_api.OTBR.get_border_agent_id", return_value=TEST_BORDER_AGENT_ID
- ), patch(
- "python_otbr_api.OTBR.get_extended_address",
- return_value=TEST_BORDER_AGENT_EXTENDED_ADDRESS,
- ), patch(
- "homeassistant.components.thread.dataset_store.DatasetStore.async_add"
- ) as mock_add:
+ with (
+ patch("python_otbr_api.OTBR.get_active_dataset_tlvs", return_value=dataset),
+ patch(
+ "python_otbr_api.OTBR.get_border_agent_id",
+ return_value=TEST_BORDER_AGENT_ID,
+ ),
+ patch(
+ "python_otbr_api.OTBR.get_extended_address",
+ return_value=TEST_BORDER_AGENT_EXTENDED_ADDRESS,
+ ),
+ patch(
+ "homeassistant.components.thread.dataset_store.DatasetStore.async_add"
+ ) as mock_add,
+ ):
assert await hass.config_entries.async_setup(config_entry.entry_id)
mock_add.assert_called_once_with(
@@ -274,11 +294,14 @@ async def test_border_agent_id_not_supported(hass: HomeAssistant) -> None:
title="My OTBR",
)
config_entry.add_to_hass(hass)
- with patch(
- "python_otbr_api.OTBR.get_active_dataset_tlvs", return_value=DATASET_CH16
- ), patch(
- "python_otbr_api.OTBR.get_border_agent_id",
- side_effect=python_otbr_api.GetBorderAgentIdNotSupportedError,
+ with (
+ patch(
+ "python_otbr_api.OTBR.get_active_dataset_tlvs", return_value=DATASET_CH16
+ ),
+ patch(
+ "python_otbr_api.OTBR.get_border_agent_id",
+ side_effect=python_otbr_api.GetBorderAgentIdNotSupportedError,
+ ),
):
assert not await hass.config_entries.async_setup(config_entry.entry_id)
@@ -412,10 +435,11 @@ async def test_remove_extra_entries(
config_entry1.add_to_hass(hass)
config_entry2.add_to_hass(hass)
assert len(hass.config_entries.async_entries(otbr.DOMAIN)) == 2
- with patch(
- "python_otbr_api.OTBR.get_active_dataset_tlvs", return_value=DATASET_CH16
- ), patch(
- "homeassistant.components.otbr.util.compute_pskc"
+ with (
+ patch(
+ "python_otbr_api.OTBR.get_active_dataset_tlvs", return_value=DATASET_CH16
+ ),
+ patch("homeassistant.components.otbr.util.compute_pskc"),
): # Patch to speed up tests
assert await async_setup_component(hass, otbr.DOMAIN, {})
assert len(hass.config_entries.async_entries(otbr.DOMAIN)) == 1
diff --git a/tests/components/otbr/test_silabs_multiprotocol.py b/tests/components/otbr/test_silabs_multiprotocol.py
index 569d507d087..8d7bed13df6 100644
--- a/tests/components/otbr/test_silabs_multiprotocol.py
+++ b/tests/components/otbr/test_silabs_multiprotocol.py
@@ -41,9 +41,12 @@ async def test_async_change_channel(
assert len(store.datasets) == 1
assert list(store.datasets.values())[0].tlv == DATASET_CH16.hex()
- with patch("python_otbr_api.OTBR.set_channel") as mock_set_channel, patch(
- "python_otbr_api.OTBR.get_pending_dataset_tlvs",
- return_value=bytes.fromhex(DATASET_CH16_PENDING),
+ with (
+ patch("python_otbr_api.OTBR.set_channel") as mock_set_channel,
+ patch(
+ "python_otbr_api.OTBR.get_pending_dataset_tlvs",
+ return_value=bytes.fromhex(DATASET_CH16_PENDING),
+ ),
):
await otbr_silabs_multiprotocol.async_change_channel(hass, 15, delay=5 * 300)
mock_set_channel.assert_awaited_once_with(15, delay=5 * 300 * 1000)
@@ -66,12 +69,16 @@ async def test_async_change_channel_no_pending(
assert len(store.datasets) == 1
assert list(store.datasets.values())[0].tlv == DATASET_CH16.hex()
- with patch("python_otbr_api.OTBR.set_channel") as mock_set_channel, patch(
- "python_otbr_api.OTBR.get_active_dataset_tlvs",
- return_value=bytes.fromhex(DATASET_CH16_PENDING),
- ), patch(
- "python_otbr_api.OTBR.get_pending_dataset_tlvs",
- return_value=None,
+ with (
+ patch("python_otbr_api.OTBR.set_channel") as mock_set_channel,
+ patch(
+ "python_otbr_api.OTBR.get_active_dataset_tlvs",
+ return_value=bytes.fromhex(DATASET_CH16_PENDING),
+ ),
+ patch(
+ "python_otbr_api.OTBR.get_pending_dataset_tlvs",
+ return_value=None,
+ ),
):
await otbr_silabs_multiprotocol.async_change_channel(hass, 15, delay=5 * 300)
mock_set_channel.assert_awaited_once_with(15, delay=5 * 300 * 1000)
@@ -94,12 +101,16 @@ async def test_async_change_channel_no_update(
assert len(store.datasets) == 1
assert list(store.datasets.values())[0].tlv == DATASET_CH16.hex()
- with patch("python_otbr_api.OTBR.set_channel") as mock_set_channel, patch(
- "python_otbr_api.OTBR.get_active_dataset_tlvs",
- return_value=None,
- ), patch(
- "python_otbr_api.OTBR.get_pending_dataset_tlvs",
- return_value=None,
+ with (
+ patch("python_otbr_api.OTBR.set_channel") as mock_set_channel,
+ patch(
+ "python_otbr_api.OTBR.get_active_dataset_tlvs",
+ return_value=None,
+ ),
+ patch(
+ "python_otbr_api.OTBR.get_pending_dataset_tlvs",
+ return_value=None,
+ ),
):
await otbr_silabs_multiprotocol.async_change_channel(hass, 15, delay=5 * 300)
mock_set_channel.assert_awaited_once_with(15, delay=5 * 300 * 1000)
diff --git a/tests/components/otbr/test_util.py b/tests/components/otbr/test_util.py
index ac072ffd513..3b1edcfeb5b 100644
--- a/tests/components/otbr/test_util.py
+++ b/tests/components/otbr/test_util.py
@@ -35,9 +35,12 @@ async def test_factory_reset(hass: HomeAssistant, otbr_config_entry_multipan) ->
"""Test factory_reset."""
data: otbr.OTBRData = hass.data[otbr.DOMAIN]
- with patch("python_otbr_api.OTBR.factory_reset") as factory_reset_mock, patch(
- "python_otbr_api.OTBR.delete_active_dataset"
- ) as delete_active_dataset_mock:
+ with (
+ patch("python_otbr_api.OTBR.factory_reset") as factory_reset_mock,
+ patch(
+ "python_otbr_api.OTBR.delete_active_dataset"
+ ) as delete_active_dataset_mock,
+ ):
await data.factory_reset()
delete_active_dataset_mock.assert_not_called()
@@ -50,12 +53,15 @@ async def test_factory_reset_not_supported(
"""Test factory_reset."""
data: otbr.OTBRData = hass.data[otbr.DOMAIN]
- with patch(
- "python_otbr_api.OTBR.factory_reset",
- side_effect=python_otbr_api.FactoryResetNotSupportedError,
- ) as factory_reset_mock, patch(
- "python_otbr_api.OTBR.delete_active_dataset"
- ) as delete_active_dataset_mock:
+ with (
+ patch(
+ "python_otbr_api.OTBR.factory_reset",
+ side_effect=python_otbr_api.FactoryResetNotSupportedError,
+ ) as factory_reset_mock,
+ patch(
+ "python_otbr_api.OTBR.delete_active_dataset"
+ ) as delete_active_dataset_mock,
+ ):
await data.factory_reset()
delete_active_dataset_mock.assert_called_once_with()
@@ -68,13 +74,17 @@ async def test_factory_reset_error_1(
"""Test factory_reset."""
data: otbr.OTBRData = hass.data[otbr.DOMAIN]
- with patch(
- "python_otbr_api.OTBR.factory_reset",
- side_effect=python_otbr_api.OTBRError,
- ) as factory_reset_mock, patch(
- "python_otbr_api.OTBR.delete_active_dataset"
- ) as delete_active_dataset_mock, pytest.raises(
- HomeAssistantError,
+ with (
+ patch(
+ "python_otbr_api.OTBR.factory_reset",
+ side_effect=python_otbr_api.OTBRError,
+ ) as factory_reset_mock,
+ patch(
+ "python_otbr_api.OTBR.delete_active_dataset"
+ ) as delete_active_dataset_mock,
+ pytest.raises(
+ HomeAssistantError,
+ ),
):
await data.factory_reset()
@@ -88,14 +98,18 @@ async def test_factory_reset_error_2(
"""Test factory_reset."""
data: otbr.OTBRData = hass.data[otbr.DOMAIN]
- with patch(
- "python_otbr_api.OTBR.factory_reset",
- side_effect=python_otbr_api.FactoryResetNotSupportedError,
- ) as factory_reset_mock, patch(
- "python_otbr_api.OTBR.delete_active_dataset",
- side_effect=python_otbr_api.OTBRError,
- ) as delete_active_dataset_mock, pytest.raises(
- HomeAssistantError,
+ with (
+ patch(
+ "python_otbr_api.OTBR.factory_reset",
+ side_effect=python_otbr_api.FactoryResetNotSupportedError,
+ ) as factory_reset_mock,
+ patch(
+ "python_otbr_api.OTBR.delete_active_dataset",
+ side_effect=python_otbr_api.OTBRError,
+ ) as delete_active_dataset_mock,
+ pytest.raises(
+ HomeAssistantError,
+ ),
):
await data.factory_reset()
diff --git a/tests/components/otbr/test_websocket_api.py b/tests/components/otbr/test_websocket_api.py
index a872206f833..c8ac839f629 100644
--- a/tests/components/otbr/test_websocket_api.py
+++ b/tests/components/otbr/test_websocket_api.py
@@ -35,16 +35,22 @@ async def test_get_info(
) -> None:
"""Test async_get_info."""
- with patch(
- "python_otbr_api.OTBR.get_active_dataset",
- return_value=python_otbr_api.ActiveDataSet(channel=16),
- ), patch(
- "python_otbr_api.OTBR.get_active_dataset_tlvs", return_value=DATASET_CH16
- ), patch(
- "python_otbr_api.OTBR.get_border_agent_id", return_value=TEST_BORDER_AGENT_ID
- ), patch(
- "python_otbr_api.OTBR.get_extended_address",
- return_value=TEST_BORDER_AGENT_EXTENDED_ADDRESS,
+ with (
+ patch(
+ "python_otbr_api.OTBR.get_active_dataset",
+ return_value=python_otbr_api.ActiveDataSet(channel=16),
+ ),
+ patch(
+ "python_otbr_api.OTBR.get_active_dataset_tlvs", return_value=DATASET_CH16
+ ),
+ patch(
+ "python_otbr_api.OTBR.get_border_agent_id",
+ return_value=TEST_BORDER_AGENT_ID,
+ ),
+ patch(
+ "python_otbr_api.OTBR.get_extended_address",
+ return_value=TEST_BORDER_AGENT_EXTENDED_ADDRESS,
+ ),
):
await websocket_client.send_json_auto_id({"type": "otbr/info"})
msg = await websocket_client.receive_json()
@@ -81,11 +87,15 @@ async def test_get_info_fetch_fails(
websocket_client,
) -> None:
"""Test async_get_info."""
- with patch(
- "python_otbr_api.OTBR.get_active_dataset",
- side_effect=python_otbr_api.OTBRError,
- ), patch(
- "python_otbr_api.OTBR.get_border_agent_id", return_value=TEST_BORDER_AGENT_ID
+ with (
+ patch(
+ "python_otbr_api.OTBR.get_active_dataset",
+ side_effect=python_otbr_api.OTBRError,
+ ),
+ patch(
+ "python_otbr_api.OTBR.get_border_agent_id",
+ return_value=TEST_BORDER_AGENT_ID,
+ ),
):
await websocket_client.send_json_auto_id({"type": "otbr/info"})
msg = await websocket_client.receive_json()
@@ -102,19 +112,20 @@ async def test_create_network(
) -> None:
"""Test create network."""
- with patch(
- "python_otbr_api.OTBR.create_active_dataset"
- ) as create_dataset_mock, patch(
- "python_otbr_api.OTBR.factory_reset"
- ) as factory_reset_mock, patch(
- "python_otbr_api.OTBR.set_enabled"
- ) as set_enabled_mock, patch(
- "python_otbr_api.OTBR.get_active_dataset_tlvs", return_value=DATASET_CH16
- ) as get_active_dataset_tlvs_mock, patch(
- "homeassistant.components.thread.dataset_store.DatasetStore.async_add"
- ) as mock_add, patch(
- "homeassistant.components.otbr.util.random.randint",
- return_value=0x1234,
+ with (
+ patch("python_otbr_api.OTBR.create_active_dataset") as create_dataset_mock,
+ patch("python_otbr_api.OTBR.factory_reset") as factory_reset_mock,
+ patch("python_otbr_api.OTBR.set_enabled") as set_enabled_mock,
+ patch(
+ "python_otbr_api.OTBR.get_active_dataset_tlvs", return_value=DATASET_CH16
+ ) as get_active_dataset_tlvs_mock,
+ patch(
+ "homeassistant.components.thread.dataset_store.DatasetStore.async_add"
+ ) as mock_add,
+ patch(
+ "homeassistant.components.otbr.util.random.randint",
+ return_value=0x1234,
+ ),
):
await websocket_client.send_json_auto_id({"type": "otbr/create_network"})
@@ -175,12 +186,16 @@ async def test_create_network_fails_2(
websocket_client,
) -> None:
"""Test create network."""
- with patch(
- "python_otbr_api.OTBR.set_enabled",
- ), patch(
- "python_otbr_api.OTBR.create_active_dataset",
- side_effect=python_otbr_api.OTBRError,
- ), patch("python_otbr_api.OTBR.factory_reset"):
+ with (
+ patch(
+ "python_otbr_api.OTBR.set_enabled",
+ ),
+ patch(
+ "python_otbr_api.OTBR.create_active_dataset",
+ side_effect=python_otbr_api.OTBRError,
+ ),
+ patch("python_otbr_api.OTBR.factory_reset"),
+ ):
await websocket_client.send_json_auto_id({"type": "otbr/create_network"})
msg = await websocket_client.receive_json()
@@ -195,13 +210,17 @@ async def test_create_network_fails_3(
websocket_client,
) -> None:
"""Test create network."""
- with patch(
- "python_otbr_api.OTBR.set_enabled",
- side_effect=[None, python_otbr_api.OTBRError],
- ), patch(
- "python_otbr_api.OTBR.create_active_dataset",
- ), patch(
- "python_otbr_api.OTBR.factory_reset",
+ with (
+ patch(
+ "python_otbr_api.OTBR.set_enabled",
+ side_effect=[None, python_otbr_api.OTBRError],
+ ),
+ patch(
+ "python_otbr_api.OTBR.create_active_dataset",
+ ),
+ patch(
+ "python_otbr_api.OTBR.factory_reset",
+ ),
):
await websocket_client.send_json_auto_id({"type": "otbr/create_network"})
msg = await websocket_client.receive_json()
@@ -217,13 +236,16 @@ async def test_create_network_fails_4(
websocket_client,
) -> None:
"""Test create network."""
- with patch("python_otbr_api.OTBR.set_enabled"), patch(
- "python_otbr_api.OTBR.create_active_dataset"
- ), patch(
- "python_otbr_api.OTBR.get_active_dataset_tlvs",
- side_effect=python_otbr_api.OTBRError,
- ), patch(
- "python_otbr_api.OTBR.factory_reset",
+ with (
+ patch("python_otbr_api.OTBR.set_enabled"),
+ patch("python_otbr_api.OTBR.create_active_dataset"),
+ patch(
+ "python_otbr_api.OTBR.get_active_dataset_tlvs",
+ side_effect=python_otbr_api.OTBRError,
+ ),
+ patch(
+ "python_otbr_api.OTBR.factory_reset",
+ ),
):
await websocket_client.send_json_auto_id({"type": "otbr/create_network"})
msg = await websocket_client.receive_json()
@@ -239,10 +261,11 @@ async def test_create_network_fails_5(
websocket_client,
) -> None:
"""Test create network."""
- with patch("python_otbr_api.OTBR.set_enabled"), patch(
- "python_otbr_api.OTBR.create_active_dataset"
- ), patch("python_otbr_api.OTBR.get_active_dataset_tlvs", return_value=None), patch(
- "python_otbr_api.OTBR.factory_reset"
+ with (
+ patch("python_otbr_api.OTBR.set_enabled"),
+ patch("python_otbr_api.OTBR.create_active_dataset"),
+ patch("python_otbr_api.OTBR.get_active_dataset_tlvs", return_value=None),
+ patch("python_otbr_api.OTBR.factory_reset"),
):
await websocket_client.send_json_auto_id({"type": "otbr/create_network"})
msg = await websocket_client.receive_json()
@@ -258,11 +281,14 @@ async def test_create_network_fails_6(
websocket_client,
) -> None:
"""Test create network."""
- with patch("python_otbr_api.OTBR.set_enabled"), patch(
- "python_otbr_api.OTBR.create_active_dataset"
- ), patch("python_otbr_api.OTBR.get_active_dataset_tlvs", return_value=None), patch(
- "python_otbr_api.OTBR.factory_reset",
- side_effect=python_otbr_api.OTBRError,
+ with (
+ patch("python_otbr_api.OTBR.set_enabled"),
+ patch("python_otbr_api.OTBR.create_active_dataset"),
+ patch("python_otbr_api.OTBR.get_active_dataset_tlvs", return_value=None),
+ patch(
+ "python_otbr_api.OTBR.factory_reset",
+ side_effect=python_otbr_api.OTBRError,
+ ),
):
await websocket_client.send_json_auto_id({"type": "otbr/create_network"})
msg = await websocket_client.receive_json()
@@ -283,11 +309,12 @@ async def test_set_network(
dataset_store = await thread.dataset_store.async_get_store(hass)
dataset_id = list(dataset_store.datasets)[1]
- with patch(
- "python_otbr_api.OTBR.set_active_dataset_tlvs"
- ) as set_active_dataset_tlvs_mock, patch(
- "python_otbr_api.OTBR.set_enabled"
- ) as set_enabled_mock:
+ with (
+ patch(
+ "python_otbr_api.OTBR.set_active_dataset_tlvs"
+ ) as set_active_dataset_tlvs_mock,
+ patch("python_otbr_api.OTBR.set_enabled") as set_enabled_mock,
+ ):
await websocket_client.send_json_auto_id(
{
"type": "otbr/set_network",
@@ -411,11 +438,14 @@ async def test_set_network_fails_2(
dataset_store = await thread.dataset_store.async_get_store(hass)
dataset_id = list(dataset_store.datasets)[1]
- with patch(
- "python_otbr_api.OTBR.set_enabled",
- ), patch(
- "python_otbr_api.OTBR.set_active_dataset_tlvs",
- side_effect=python_otbr_api.OTBRError,
+ with (
+ patch(
+ "python_otbr_api.OTBR.set_enabled",
+ ),
+ patch(
+ "python_otbr_api.OTBR.set_active_dataset_tlvs",
+ side_effect=python_otbr_api.OTBRError,
+ ),
):
await websocket_client.send_json_auto_id(
{
@@ -440,11 +470,14 @@ async def test_set_network_fails_3(
dataset_store = await thread.dataset_store.async_get_store(hass)
dataset_id = list(dataset_store.datasets)[1]
- with patch(
- "python_otbr_api.OTBR.set_enabled",
- side_effect=[None, python_otbr_api.OTBRError],
- ), patch(
- "python_otbr_api.OTBR.set_active_dataset_tlvs",
+ with (
+ patch(
+ "python_otbr_api.OTBR.set_enabled",
+ side_effect=[None, python_otbr_api.OTBRError],
+ ),
+ patch(
+ "python_otbr_api.OTBR.set_active_dataset_tlvs",
+ ),
):
await websocket_client.send_json_auto_id(
{
diff --git a/tests/components/overkiz/test_config_flow.py b/tests/components/overkiz/test_config_flow.py
index 6754452dea1..dbe8c690bc4 100644
--- a/tests/components/overkiz/test_config_flow.py
+++ b/tests/components/overkiz/test_config_flow.py
@@ -96,9 +96,12 @@ async def test_form_cloud(hass: HomeAssistant, mock_setup_entry: AsyncMock) -> N
assert result3["type"] == "form"
assert result3["step_id"] == "cloud"
- with patch("pyoverkiz.client.OverkizClient.login", return_value=True), patch(
- "pyoverkiz.client.OverkizClient.get_gateways",
- return_value=MOCK_GATEWAY_RESPONSE,
+ with (
+ patch("pyoverkiz.client.OverkizClient.login", return_value=True),
+ patch(
+ "pyoverkiz.client.OverkizClient.get_gateways",
+ return_value=MOCK_GATEWAY_RESPONSE,
+ ),
):
await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -128,9 +131,12 @@ async def test_form_only_cloud_supported(
assert result2["type"] == "form"
assert result2["step_id"] == "cloud"
- with patch("pyoverkiz.client.OverkizClient.login", return_value=True), patch(
- "pyoverkiz.client.OverkizClient.get_gateways",
- return_value=MOCK_GATEWAY_RESPONSE,
+ with (
+ patch("pyoverkiz.client.OverkizClient.login", return_value=True),
+ patch(
+ "pyoverkiz.client.OverkizClient.get_gateways",
+ return_value=MOCK_GATEWAY_RESPONSE,
+ ),
):
await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -418,9 +424,12 @@ async def test_cloud_abort_on_duplicate_entry(
assert result3["type"] == "form"
assert result3["step_id"] == "cloud"
- with patch("pyoverkiz.client.OverkizClient.login", return_value=True), patch(
- "pyoverkiz.client.OverkizClient.get_gateways",
- return_value=MOCK_GATEWAY_RESPONSE,
+ with (
+ patch("pyoverkiz.client.OverkizClient.login", return_value=True),
+ patch(
+ "pyoverkiz.client.OverkizClient.get_gateways",
+ return_value=MOCK_GATEWAY_RESPONSE,
+ ),
):
result4 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -525,9 +534,12 @@ async def test_cloud_allow_multiple_unique_entries(
assert result3["type"] == "form"
assert result3["step_id"] == "cloud"
- with patch("pyoverkiz.client.OverkizClient.login", return_value=True), patch(
- "pyoverkiz.client.OverkizClient.get_gateways",
- return_value=MOCK_GATEWAY_RESPONSE,
+ with (
+ patch("pyoverkiz.client.OverkizClient.login", return_value=True),
+ patch(
+ "pyoverkiz.client.OverkizClient.get_gateways",
+ return_value=MOCK_GATEWAY_RESPONSE,
+ ),
):
result4 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -573,9 +585,12 @@ async def test_cloud_reauth_success(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "cloud"
- with patch("pyoverkiz.client.OverkizClient.login", return_value=True), patch(
- "pyoverkiz.client.OverkizClient.get_gateways",
- return_value=MOCK_GATEWAY_RESPONSE,
+ with (
+ patch("pyoverkiz.client.OverkizClient.login", return_value=True),
+ patch(
+ "pyoverkiz.client.OverkizClient.get_gateways",
+ return_value=MOCK_GATEWAY_RESPONSE,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -620,9 +635,12 @@ async def test_cloud_reauth_wrong_account(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "cloud"
- with patch("pyoverkiz.client.OverkizClient.login", return_value=True), patch(
- "pyoverkiz.client.OverkizClient.get_gateways",
- return_value=MOCK_GATEWAY2_RESPONSE,
+ with (
+ patch("pyoverkiz.client.OverkizClient.login", return_value=True),
+ patch(
+ "pyoverkiz.client.OverkizClient.get_gateways",
+ return_value=MOCK_GATEWAY2_RESPONSE,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -779,8 +797,9 @@ async def test_dhcp_flow(hass: HomeAssistant, mock_setup_entry: AsyncMock) -> No
{"api_type": "cloud"},
)
- with patch("pyoverkiz.client.OverkizClient.login", return_value=True), patch(
- "pyoverkiz.client.OverkizClient.get_gateways", return_value=None
+ with (
+ patch("pyoverkiz.client.OverkizClient.login", return_value=True),
+ patch("pyoverkiz.client.OverkizClient.get_gateways", return_value=None),
):
result4 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -852,9 +871,12 @@ async def test_zeroconf_flow(hass: HomeAssistant, mock_setup_entry: AsyncMock) -
assert result3["type"] == "form"
assert result3["step_id"] == "cloud"
- with patch("pyoverkiz.client.OverkizClient.login", return_value=True), patch(
- "pyoverkiz.client.OverkizClient.get_gateways",
- return_value=MOCK_GATEWAY_RESPONSE,
+ with (
+ patch("pyoverkiz.client.OverkizClient.login", return_value=True),
+ patch(
+ "pyoverkiz.client.OverkizClient.get_gateways",
+ return_value=MOCK_GATEWAY_RESPONSE,
+ ),
):
result4 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/ovo_energy/test_config_flow.py b/tests/components/ovo_energy/test_config_flow.py
index 84b2719ae9b..3975be7cf80 100644
--- a/tests/components/ovo_energy/test_config_flow.py
+++ b/tests/components/ovo_energy/test_config_flow.py
@@ -82,15 +82,19 @@ async def test_full_flow_implementation(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.ovo_energy.config_flow.OVOEnergy.authenticate",
- return_value=True,
- ), patch(
- "homeassistant.components.ovo_energy.config_flow.OVOEnergy.username",
- "some_name",
- ), patch(
- "homeassistant.components.ovo_energy.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.ovo_energy.config_flow.OVOEnergy.authenticate",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.ovo_energy.config_flow.OVOEnergy.username",
+ "some_name",
+ ),
+ patch(
+ "homeassistant.components.ovo_energy.async_setup_entry",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -175,12 +179,15 @@ async def test_reauth_flow(hass: HomeAssistant) -> None:
assert result["step_id"] == "reauth"
assert result["errors"] == {"base": "authorization_error"}
- with patch(
- "homeassistant.components.ovo_energy.config_flow.OVOEnergy.authenticate",
- return_value=True,
- ), patch(
- "homeassistant.components.ovo_energy.config_flow.OVOEnergy.username",
- return_value=FIXTURE_USER_INPUT[CONF_USERNAME],
+ with (
+ patch(
+ "homeassistant.components.ovo_energy.config_flow.OVOEnergy.authenticate",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.ovo_energy.config_flow.OVOEnergy.username",
+ return_value=FIXTURE_USER_INPUT[CONF_USERNAME],
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/owntracks/test_config_flow.py b/tests/components/owntracks/test_config_flow.py
index d8e700c3754..8b353789c83 100644
--- a/tests/components/owntracks/test_config_flow.py
+++ b/tests/components/owntracks/test_config_flow.py
@@ -153,15 +153,17 @@ async def test_with_cloud_sub(hass: HomeAssistant) -> None:
"""Test creating a config flow while subscribed."""
assert await async_setup_component(hass, "cloud", {})
- with patch(
- "homeassistant.components.cloud.async_active_subscription", return_value=True
- ), patch(
- "homeassistant.components.cloud.async_is_logged_in", return_value=True
- ), patch(
- "homeassistant.components.cloud.async_is_connected", return_value=True
- ), patch(
- "hass_nabucasa.cloudhooks.Cloudhooks.async_create",
- return_value={"cloudhook_url": "https://hooks.nabu.casa/ABCD"},
+ with (
+ patch(
+ "homeassistant.components.cloud.async_active_subscription",
+ return_value=True,
+ ),
+ patch("homeassistant.components.cloud.async_is_logged_in", return_value=True),
+ patch("homeassistant.components.cloud.async_is_connected", return_value=True),
+ patch(
+ "hass_nabucasa.cloudhooks.Cloudhooks.async_create",
+ return_value={"cloudhook_url": "https://hooks.nabu.casa/ABCD"},
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}, data={}
@@ -180,15 +182,17 @@ async def test_with_cloud_sub_not_connected(hass: HomeAssistant) -> None:
"""Test creating a config flow while subscribed."""
assert await async_setup_component(hass, "cloud", {})
- with patch(
- "homeassistant.components.cloud.async_active_subscription", return_value=True
- ), patch(
- "homeassistant.components.cloud.async_is_logged_in", return_value=True
- ), patch(
- "homeassistant.components.cloud.async_is_connected", return_value=False
- ), patch(
- "hass_nabucasa.cloudhooks.Cloudhooks.async_create",
- return_value={"cloudhook_url": "https://hooks.nabu.casa/ABCD"},
+ with (
+ patch(
+ "homeassistant.components.cloud.async_active_subscription",
+ return_value=True,
+ ),
+ patch("homeassistant.components.cloud.async_is_logged_in", return_value=True),
+ patch("homeassistant.components.cloud.async_is_connected", return_value=False),
+ patch(
+ "hass_nabucasa.cloudhooks.Cloudhooks.async_create",
+ return_value={"cloudhook_url": "https://hooks.nabu.casa/ABCD"},
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}, data={}
diff --git a/tests/components/p1_monitor/test_config_flow.py b/tests/components/p1_monitor/test_config_flow.py
index 754fd31f19e..ec1af77a646 100644
--- a/tests/components/p1_monitor/test_config_flow.py
+++ b/tests/components/p1_monitor/test_config_flow.py
@@ -20,11 +20,14 @@ async def test_full_user_flow(hass: HomeAssistant) -> None:
assert result.get("type") == FlowResultType.FORM
assert result.get("step_id") == "user"
- with patch(
- "homeassistant.components.p1_monitor.config_flow.P1Monitor.smartmeter"
- ) as mock_p1monitor, patch(
- "homeassistant.components.p1_monitor.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.p1_monitor.config_flow.P1Monitor.smartmeter"
+ ) as mock_p1monitor,
+ patch(
+ "homeassistant.components.p1_monitor.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_HOST: "example.com"},
diff --git a/tests/components/peco/test_config_flow.py b/tests/components/peco/test_config_flow.py
index 1a91145624a..df178e125e1 100644
--- a/tests/components/peco/test_config_flow.py
+++ b/tests/components/peco/test_config_flow.py
@@ -49,10 +49,13 @@ async def test_invalid_county(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.peco.async_setup_entry",
- return_value=True,
- ), pytest.raises(Invalid):
+ with (
+ patch(
+ "homeassistant.components.peco.async_setup_entry",
+ return_value=True,
+ ),
+ pytest.raises(Invalid),
+ ):
await hass.config_entries.flow.async_configure(
result["flow_id"],
{
diff --git a/tests/components/peco/test_init.py b/tests/components/peco/test_init.py
index 261624f382f..55dc0a15a4b 100644
--- a/tests/components/peco/test_init.py
+++ b/tests/components/peco/test_init.py
@@ -28,18 +28,21 @@ async def test_unload_entry(hass: HomeAssistant) -> None:
config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_ENTRY_DATA)
config_entry.add_to_hass(hass)
- with patch(
- "peco.PecoOutageApi.get_outage_totals",
- return_value=OutageResults(
- customers_out=0,
- percent_customers_out=0,
- outage_count=0,
- customers_served=350394,
+ with (
+ patch(
+ "peco.PecoOutageApi.get_outage_totals",
+ return_value=OutageResults(
+ customers_out=0,
+ percent_customers_out=0,
+ outage_count=0,
+ customers_served=350394,
+ ),
),
- ), patch(
- "peco.PecoOutageApi.get_map_alerts",
- return_value=AlertResults(
- alert_content="Testing 1234", alert_title="Testing 4321"
+ patch(
+ "peco.PecoOutageApi.get_map_alerts",
+ return_value=AlertResults(
+ alert_content="Testing 1234", alert_title="Testing 4321"
+ ),
),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
@@ -164,21 +167,25 @@ async def test_unresponsive_meter_error(hass: HomeAssistant) -> None:
config_entry = MockConfigEntry(domain=DOMAIN, data=METER_DATA)
config_entry.add_to_hass(hass)
- with patch(
- "peco.PecoOutageApi.meter_check",
- side_effect=UnresponsiveMeterError(),
- ), patch(
- "peco.PecoOutageApi.get_outage_count",
- return_value=OutageResults(
- customers_out=0,
- percent_customers_out=0,
- outage_count=0,
- customers_served=350394,
+ with (
+ patch(
+ "peco.PecoOutageApi.meter_check",
+ side_effect=UnresponsiveMeterError(),
),
- ), patch(
- "peco.PecoOutageApi.get_map_alerts",
- return_value=AlertResults(
- alert_content="Testing 1234", alert_title="Testing 4321"
+ patch(
+ "peco.PecoOutageApi.get_outage_count",
+ return_value=OutageResults(
+ customers_out=0,
+ percent_customers_out=0,
+ outage_count=0,
+ customers_served=350394,
+ ),
+ ),
+ patch(
+ "peco.PecoOutageApi.get_map_alerts",
+ return_value=AlertResults(
+ alert_content="Testing 1234", alert_title="Testing 4321"
+ ),
),
):
assert not await hass.config_entries.async_setup(config_entry.entry_id)
@@ -194,21 +201,25 @@ async def test_meter_http_error(hass: HomeAssistant) -> None:
config_entry = MockConfigEntry(domain=DOMAIN, data=METER_DATA)
config_entry.add_to_hass(hass)
- with patch(
- "peco.PecoOutageApi.meter_check",
- side_effect=HttpError(),
- ), patch(
- "peco.PecoOutageApi.get_outage_count",
- return_value=OutageResults(
- customers_out=0,
- percent_customers_out=0,
- outage_count=0,
- customers_served=350394,
+ with (
+ patch(
+ "peco.PecoOutageApi.meter_check",
+ side_effect=HttpError(),
),
- ), patch(
- "peco.PecoOutageApi.get_map_alerts",
- return_value=AlertResults(
- alert_content="Testing 1234", alert_title="Testing 4321"
+ patch(
+ "peco.PecoOutageApi.get_outage_count",
+ return_value=OutageResults(
+ customers_out=0,
+ percent_customers_out=0,
+ outage_count=0,
+ customers_served=350394,
+ ),
+ ),
+ patch(
+ "peco.PecoOutageApi.get_map_alerts",
+ return_value=AlertResults(
+ alert_content="Testing 1234", alert_title="Testing 4321"
+ ),
),
):
assert not await hass.config_entries.async_setup(config_entry.entry_id)
@@ -224,21 +235,25 @@ async def test_meter_bad_json(hass: HomeAssistant) -> None:
config_entry = MockConfigEntry(domain=DOMAIN, data=METER_DATA)
config_entry.add_to_hass(hass)
- with patch(
- "peco.PecoOutageApi.meter_check",
- side_effect=BadJSONError(),
- ), patch(
- "peco.PecoOutageApi.get_outage_count",
- return_value=OutageResults(
- customers_out=0,
- percent_customers_out=0,
- outage_count=0,
- customers_served=350394,
+ with (
+ patch(
+ "peco.PecoOutageApi.meter_check",
+ side_effect=BadJSONError(),
),
- ), patch(
- "peco.PecoOutageApi.get_map_alerts",
- return_value=AlertResults(
- alert_content="Testing 1234", alert_title="Testing 4321"
+ patch(
+ "peco.PecoOutageApi.get_outage_count",
+ return_value=OutageResults(
+ customers_out=0,
+ percent_customers_out=0,
+ outage_count=0,
+ customers_served=350394,
+ ),
+ ),
+ patch(
+ "peco.PecoOutageApi.get_map_alerts",
+ return_value=AlertResults(
+ alert_content="Testing 1234", alert_title="Testing 4321"
+ ),
),
):
assert not await hass.config_entries.async_setup(config_entry.entry_id)
@@ -254,21 +269,25 @@ async def test_meter_timeout(hass: HomeAssistant) -> None:
config_entry = MockConfigEntry(domain=DOMAIN, data=METER_DATA)
config_entry.add_to_hass(hass)
- with patch(
- "peco.PecoOutageApi.meter_check",
- side_effect=TimeoutError(),
- ), patch(
- "peco.PecoOutageApi.get_outage_count",
- return_value=OutageResults(
- customers_out=0,
- percent_customers_out=0,
- outage_count=0,
- customers_served=350394,
+ with (
+ patch(
+ "peco.PecoOutageApi.meter_check",
+ side_effect=TimeoutError(),
),
- ), patch(
- "peco.PecoOutageApi.get_map_alerts",
- return_value=AlertResults(
- alert_content="Testing 1234", alert_title="Testing 4321"
+ patch(
+ "peco.PecoOutageApi.get_outage_count",
+ return_value=OutageResults(
+ customers_out=0,
+ percent_customers_out=0,
+ outage_count=0,
+ customers_served=350394,
+ ),
+ ),
+ patch(
+ "peco.PecoOutageApi.get_map_alerts",
+ return_value=AlertResults(
+ alert_content="Testing 1234", alert_title="Testing 4321"
+ ),
),
):
assert not await hass.config_entries.async_setup(config_entry.entry_id)
@@ -284,21 +303,25 @@ async def test_meter_data(hass: HomeAssistant) -> None:
config_entry = MockConfigEntry(domain=DOMAIN, data=METER_DATA)
config_entry.add_to_hass(hass)
- with patch(
- "peco.PecoOutageApi.meter_check",
- return_value=True,
- ), patch(
- "peco.PecoOutageApi.get_outage_count",
- return_value=OutageResults(
- customers_out=0,
- percent_customers_out=0,
- outage_count=0,
- customers_served=350394,
+ with (
+ patch(
+ "peco.PecoOutageApi.meter_check",
+ return_value=True,
),
- ), patch(
- "peco.PecoOutageApi.get_map_alerts",
- return_value=AlertResults(
- alert_content="Testing 1234", alert_title="Testing 4321"
+ patch(
+ "peco.PecoOutageApi.get_outage_count",
+ return_value=OutageResults(
+ customers_out=0,
+ percent_customers_out=0,
+ outage_count=0,
+ customers_served=350394,
+ ),
+ ),
+ patch(
+ "peco.PecoOutageApi.get_map_alerts",
+ return_value=AlertResults(
+ alert_content="Testing 1234", alert_title="Testing 4321"
+ ),
),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
diff --git a/tests/components/peco/test_sensor.py b/tests/components/peco/test_sensor.py
index 2734ed4b8d1..2546b7c8996 100644
--- a/tests/components/peco/test_sensor.py
+++ b/tests/components/peco/test_sensor.py
@@ -34,18 +34,21 @@ async def test_sensor_available(
config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_ENTRY_DATA)
config_entry.add_to_hass(hass)
- with patch(
- "peco.PecoOutageApi.get_outage_totals",
- return_value=OutageResults(
- customers_out=123,
- percent_customers_out=15.589,
- outage_count=456,
- customers_served=789,
+ with (
+ patch(
+ "peco.PecoOutageApi.get_outage_totals",
+ return_value=OutageResults(
+ customers_out=123,
+ percent_customers_out=15.589,
+ outage_count=456,
+ customers_served=789,
+ ),
),
- ), patch(
- "peco.PecoOutageApi.get_map_alerts",
- return_value=AlertResults(
- alert_content="Testing 1234", alert_title="Testing 4321"
+ patch(
+ "peco.PecoOutageApi.get_map_alerts",
+ return_value=AlertResults(
+ alert_content="Testing 1234", alert_title="Testing 4321"
+ ),
),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
@@ -66,18 +69,21 @@ async def test_sensor_available(
config_entry = MockConfigEntry(domain=DOMAIN, data=COUNTY_ENTRY_DATA)
config_entry.add_to_hass(hass)
- with patch(
- "peco.PecoOutageApi.get_outage_count",
- return_value=OutageResults(
- customers_out=123,
- percent_customers_out=15.589,
- outage_count=456,
- customers_served=789,
+ with (
+ patch(
+ "peco.PecoOutageApi.get_outage_count",
+ return_value=OutageResults(
+ customers_out=123,
+ percent_customers_out=15.589,
+ outage_count=456,
+ customers_served=789,
+ ),
),
- ), patch(
- "peco.PecoOutageApi.get_map_alerts",
- return_value=AlertResults(
- alert_content="Testing 1234", alert_title="Testing 4321"
+ patch(
+ "peco.PecoOutageApi.get_map_alerts",
+ return_value=AlertResults(
+ alert_content="Testing 1234", alert_title="Testing 4321"
+ ),
),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
diff --git a/tests/components/pegel_online/test_config_flow.py b/tests/components/pegel_online/test_config_flow.py
index c9b22174424..fedcba94616 100644
--- a/tests/components/pegel_online/test_config_flow.py
+++ b/tests/components/pegel_online/test_config_flow.py
@@ -36,11 +36,14 @@ async def test_user(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.pegel_online.async_setup_entry", return_value=True
- ) as mock_setup_entry, patch(
- "homeassistant.components.pegel_online.config_flow.PegelOnline",
- ) as pegelonline:
+ with (
+ patch(
+ "homeassistant.components.pegel_online.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.pegel_online.config_flow.PegelOnline",
+ ) as pegelonline,
+ ):
pegelonline.return_value = PegelOnlineMock(nearby_stations=MOCK_NEARBY_STATIONS)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_USER_DATA_STEP1
@@ -100,11 +103,14 @@ async def test_connection_error(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.pegel_online.async_setup_entry", return_value=True
- ) as mock_setup_entry, patch(
- "homeassistant.components.pegel_online.config_flow.PegelOnline",
- ) as pegelonline:
+ with (
+ patch(
+ "homeassistant.components.pegel_online.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.pegel_online.config_flow.PegelOnline",
+ ) as pegelonline,
+ ):
# connection issue during setup
pegelonline.return_value = PegelOnlineMock(side_effect=ClientError)
result = await hass.config_entries.flow.async_configure(
@@ -142,11 +148,14 @@ async def test_user_no_stations(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.pegel_online.async_setup_entry", return_value=True
- ) as mock_setup_entry, patch(
- "homeassistant.components.pegel_online.config_flow.PegelOnline",
- ) as pegelonline:
+ with (
+ patch(
+ "homeassistant.components.pegel_online.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.pegel_online.config_flow.PegelOnline",
+ ) as pegelonline,
+ ):
# no stations found
pegelonline.return_value = PegelOnlineMock(nearby_stations={})
result = await hass.config_entries.flow.async_configure(
diff --git a/tests/components/philips_js/conftest.py b/tests/components/philips_js/conftest.py
index 15e796ec86e..3591546dfe9 100644
--- a/tests/components/philips_js/conftest.py
+++ b/tests/components/philips_js/conftest.py
@@ -16,10 +16,13 @@ from tests.common import MockConfigEntry, mock_device_registry
@pytest.fixture
def mock_setup_entry() -> Generator[AsyncMock, None, None]:
"""Disable component setup."""
- with patch(
- "homeassistant.components.philips_js.async_setup_entry", return_value=True
- ) as mock_setup_entry, patch(
- "homeassistant.components.philips_js.async_unload_entry", return_value=True
+ with (
+ patch(
+ "homeassistant.components.philips_js.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.philips_js.async_unload_entry", return_value=True
+ ),
):
yield mock_setup_entry
@@ -49,9 +52,12 @@ def mock_tv():
tv.ambilight_styles = {}
tv.ambilight_cached = {}
- with patch(
- "homeassistant.components.philips_js.config_flow.PhilipsTV", return_value=tv
- ), patch("homeassistant.components.philips_js.PhilipsTV", return_value=tv):
+ with (
+ patch(
+ "homeassistant.components.philips_js.config_flow.PhilipsTV", return_value=tv
+ ),
+ patch("homeassistant.components.philips_js.PhilipsTV", return_value=tv),
+ ):
yield tv
diff --git a/tests/components/pilight/test_init.py b/tests/components/pilight/test_init.py
index e5ff016b5f3..621d002bb62 100644
--- a/tests/components/pilight/test_init.py
+++ b/tests/components/pilight/test_init.py
@@ -71,9 +71,10 @@ class PilightDaemonSim:
@patch("homeassistant.components.pilight._LOGGER.error")
async def test_connection_failed_error(mock_error, hass: HomeAssistant) -> None:
"""Try to connect at 127.0.0.1:5001 with socket error."""
- with assert_setup_component(4), 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: {}}
)
@@ -86,9 +87,10 @@ async def test_connection_failed_error(mock_error, hass: HomeAssistant) -> None:
@patch("homeassistant.components.pilight._LOGGER.error")
async def test_connection_timeout_error(mock_error, hass: HomeAssistant) -> None:
"""Try to connect at 127.0.0.1:5001 with socket timeout."""
- with assert_setup_component(4), 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: {}}
)
@@ -142,8 +144,9 @@ async def test_send_code(mock_pilight_error, hass: HomeAssistant) -> None:
@patch("homeassistant.components.pilight._LOGGER.error")
async def test_send_code_fail(mock_pilight_error, hass: HomeAssistant) -> None:
"""Check IOError exception error message."""
- with assert_setup_component(4), patch(
- "pilight.pilight.Client.send_code", side_effect=IOError
+ with (
+ assert_setup_component(4),
+ patch("pilight.pilight.Client.send_code", side_effect=IOError),
):
assert await async_setup_component(hass, pilight.DOMAIN, {pilight.DOMAIN: {}})
diff --git a/tests/components/ping/conftest.py b/tests/components/ping/conftest.py
index db5de50e659..9bbbc9e6e32 100644
--- a/tests/components/ping/conftest.py
+++ b/tests/components/ping/conftest.py
@@ -17,10 +17,13 @@ from tests.common import MockConfigEntry
@pytest.fixture
def patch_setup(*args, **kwargs):
"""Patch setup methods."""
- with patch(
- "homeassistant.components.ping.async_setup_entry",
- return_value=True,
- ), patch("homeassistant.components.ping.async_setup", return_value=True):
+ with (
+ patch(
+ "homeassistant.components.ping.async_setup_entry",
+ return_value=True,
+ ),
+ patch("homeassistant.components.ping.async_setup", return_value=True),
+ ):
yield
@@ -29,9 +32,10 @@ async def patch_ping():
"""Patch icmplib async_ping."""
mock = Host("10.10.10.10", 5, [10, 1, 2, 5, 6])
- with patch(
- "homeassistant.components.ping.helpers.async_ping", return_value=mock
- ), patch("homeassistant.components.ping.async_ping", return_value=mock):
+ with (
+ patch("homeassistant.components.ping.helpers.async_ping", return_value=mock),
+ patch("homeassistant.components.ping.async_ping", return_value=mock),
+ ):
yield mock
diff --git a/tests/components/ping/test_device_tracker.py b/tests/components/ping/test_device_tracker.py
index 288231a609b..a01bd0fa1bf 100644
--- a/tests/components/ping/test_device_tracker.py
+++ b/tests/components/ping/test_device_tracker.py
@@ -123,9 +123,12 @@ async def test_import_delete_known_devices(
}
files = {legacy.YAML_DEVICES: dump(yaml_devices)}
- with patch_yaml_files(files, True), patch(
- "homeassistant.components.ping.device_tracker.remove_device_from_config"
- ) as remove_device_from_config:
+ with (
+ patch_yaml_files(files, True),
+ patch(
+ "homeassistant.components.ping.device_tracker.remove_device_from_config"
+ ) as remove_device_from_config,
+ ):
await async_setup_component(
hass,
"device_tracker",
diff --git a/tests/components/plaato/test_config_flow.py b/tests/components/plaato/test_config_flow.py
index 6b61ca8a649..7088b672f69 100644
--- a/tests/components/plaato/test_config_flow.py
+++ b/tests/components/plaato/test_config_flow.py
@@ -27,10 +27,15 @@ UNIQUE_ID = "plaato_unique_id"
@pytest.fixture(name="webhook_id")
def mock_webhook_id():
"""Mock webhook_id."""
- with patch(
- "homeassistant.components.webhook.async_generate_id", return_value=WEBHOOK_ID
- ), patch(
- "homeassistant.components.webhook.async_generate_url", return_value="hook_id"
+ with (
+ patch(
+ "homeassistant.components.webhook.async_generate_id",
+ return_value=WEBHOOK_ID,
+ ),
+ patch(
+ "homeassistant.components.webhook.async_generate_url",
+ return_value="hook_id",
+ ),
):
yield
@@ -101,15 +106,17 @@ async def test_show_config_form_validate_webhook(
assert result["step_id"] == "api_method"
assert await async_setup_component(hass, "cloud", {})
- with patch(
- "homeassistant.components.cloud.async_active_subscription", return_value=True
- ), patch(
- "homeassistant.components.cloud.async_is_logged_in", return_value=True
- ), patch(
- "homeassistant.components.cloud.async_is_connected", return_value=True
- ), patch(
- "hass_nabucasa.cloudhooks.Cloudhooks.async_create",
- return_value={"cloudhook_url": "https://hooks.nabu.casa/ABCD"},
+ with (
+ patch(
+ "homeassistant.components.cloud.async_active_subscription",
+ return_value=True,
+ ),
+ patch("homeassistant.components.cloud.async_is_logged_in", return_value=True),
+ patch("homeassistant.components.cloud.async_is_connected", return_value=True),
+ patch(
+ "hass_nabucasa.cloudhooks.Cloudhooks.async_create",
+ return_value={"cloudhook_url": "https://hooks.nabu.casa/ABCD"},
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -147,15 +154,17 @@ async def test_show_config_form_validate_webhook_not_connected(
assert result["step_id"] == "api_method"
assert await async_setup_component(hass, "cloud", {})
- with patch(
- "homeassistant.components.cloud.async_active_subscription", return_value=True
- ), patch(
- "homeassistant.components.cloud.async_is_logged_in", return_value=True
- ), patch(
- "homeassistant.components.cloud.async_is_connected", return_value=False
- ), patch(
- "hass_nabucasa.cloudhooks.Cloudhooks.async_create",
- return_value={"cloudhook_url": "https://hooks.nabu.casa/ABCD"},
+ with (
+ patch(
+ "homeassistant.components.cloud.async_active_subscription",
+ return_value=True,
+ ),
+ patch("homeassistant.components.cloud.async_is_logged_in", return_value=True),
+ patch("homeassistant.components.cloud.async_is_connected", return_value=False),
+ patch(
+ "hass_nabucasa.cloudhooks.Cloudhooks.async_create",
+ return_value={"cloudhook_url": "https://hooks.nabu.casa/ABCD"},
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/plex/test_config_flow.py b/tests/components/plex/test_config_flow.py
index 30b20eec4ab..9cfcda1b29d 100644
--- a/tests/components/plex/test_config_flow.py
+++ b/tests/components/plex/test_config_flow.py
@@ -59,10 +59,12 @@ async def test_bad_credentials(
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "plexapi.myplex.MyPlexAccount", side_effect=plexapi.exceptions.Unauthorized
- ), patch("plexauth.PlexAuth.initiate_auth"), patch(
- "plexauth.PlexAuth.token", return_value="BAD TOKEN"
+ with (
+ patch(
+ "plexapi.myplex.MyPlexAccount", side_effect=plexapi.exceptions.Unauthorized
+ ),
+ patch("plexauth.PlexAuth.initiate_auth"),
+ patch("plexauth.PlexAuth.token", return_value="BAD TOKEN"),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
@@ -89,11 +91,13 @@ async def test_bad_hostname(
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "plexapi.myplex.MyPlexResource.connect",
- side_effect=requests.exceptions.ConnectionError,
- ), patch("plexauth.PlexAuth.initiate_auth"), patch(
- "plexauth.PlexAuth.token", return_value=MOCK_TOKEN
+ with (
+ patch(
+ "plexapi.myplex.MyPlexResource.connect",
+ side_effect=requests.exceptions.ConnectionError,
+ ),
+ patch("plexauth.PlexAuth.initiate_auth"),
+ patch("plexauth.PlexAuth.token", return_value=MOCK_TOKEN),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
@@ -120,9 +124,11 @@ async def test_unknown_exception(
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
- with patch("plexapi.myplex.MyPlexAccount", side_effect=Exception), patch(
- "plexauth.PlexAuth.initiate_auth"
- ), patch("plexauth.PlexAuth.token", return_value="MOCK_TOKEN"):
+ with (
+ patch("plexapi.myplex.MyPlexAccount", side_effect=Exception),
+ patch("plexauth.PlexAuth.initiate_auth"),
+ patch("plexauth.PlexAuth.token", return_value="MOCK_TOKEN"),
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
@@ -152,8 +158,9 @@ async def test_no_servers_found(
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
- with patch("plexauth.PlexAuth.initiate_auth"), patch(
- "plexauth.PlexAuth.token", return_value=MOCK_TOKEN
+ with (
+ patch("plexauth.PlexAuth.initiate_auth"),
+ patch("plexauth.PlexAuth.token", return_value=MOCK_TOKEN),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
@@ -182,8 +189,9 @@ async def test_single_available_server(
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
- with patch("plexauth.PlexAuth.initiate_auth"), patch(
- "plexauth.PlexAuth.token", return_value=MOCK_TOKEN
+ with (
+ patch("plexauth.PlexAuth.initiate_auth"),
+ patch("plexauth.PlexAuth.token", return_value=MOCK_TOKEN),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
@@ -229,8 +237,9 @@ async def test_multiple_servers_with_selection(
"https://plex.tv/api/v2/resources",
text=plextv_resources_two_servers,
)
- with patch("plexauth.PlexAuth.initiate_auth"), patch(
- "plexauth.PlexAuth.token", return_value=MOCK_TOKEN
+ with (
+ patch("plexauth.PlexAuth.initiate_auth"),
+ patch("plexauth.PlexAuth.token", return_value=MOCK_TOKEN),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
@@ -294,8 +303,9 @@ async def test_adding_last_unconfigured_server(
text=plextv_resources_two_servers,
)
- with patch("plexauth.PlexAuth.initiate_auth"), patch(
- "plexauth.PlexAuth.token", return_value=MOCK_TOKEN
+ with (
+ patch("plexauth.PlexAuth.initiate_auth"),
+ patch("plexauth.PlexAuth.token", return_value=MOCK_TOKEN),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
@@ -353,8 +363,9 @@ async def test_all_available_servers_configured(
text=plextv_resources_two_servers,
)
- with patch("plexauth.PlexAuth.initiate_auth"), patch(
- "plexauth.PlexAuth.token", return_value=MOCK_TOKEN
+ with (
+ patch("plexauth.PlexAuth.initiate_auth"),
+ patch("plexauth.PlexAuth.token", return_value=MOCK_TOKEN),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
@@ -478,8 +489,9 @@ async def test_external_timed_out(
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
- with patch("plexauth.PlexAuth.initiate_auth"), patch(
- "plexauth.PlexAuth.token", return_value=None
+ with (
+ patch("plexauth.PlexAuth.initiate_auth"),
+ patch("plexauth.PlexAuth.token", return_value=None),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
@@ -506,8 +518,9 @@ async def test_callback_view(
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
- with patch("plexauth.PlexAuth.initiate_auth"), patch(
- "plexauth.PlexAuth.token", return_value=MOCK_TOKEN
+ with (
+ patch("plexauth.PlexAuth.initiate_auth"),
+ patch("plexauth.PlexAuth.token", return_value=MOCK_TOKEN),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
@@ -637,8 +650,9 @@ async def test_manual_config(
assert result["step_id"] == "manual_setup"
assert result["errors"]["base"] == "ssl_error"
- with patch("homeassistant.components.plex.PlexWebsocket", autospec=True), patch(
- "homeassistant.components.plex.GDM", return_value=MockGDM(disabled=True)
+ with (
+ patch("homeassistant.components.plex.PlexWebsocket", autospec=True),
+ patch("homeassistant.components.plex.GDM", return_value=MockGDM(disabled=True)),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MANUAL_SERVER
@@ -678,9 +692,10 @@ async def test_manual_config_with_token(
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "manual_setup"
- with patch(
- "homeassistant.components.plex.GDM", return_value=MockGDM(disabled=True)
- ), patch("homeassistant.components.plex.PlexWebsocket", autospec=True):
+ with (
+ patch("homeassistant.components.plex.GDM", return_value=MockGDM(disabled=True)),
+ patch("homeassistant.components.plex.PlexWebsocket", autospec=True),
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_TOKEN: MOCK_TOKEN}
)
@@ -741,8 +756,9 @@ async def test_reauth(
)
flow_id = result["flow_id"]
- with patch("plexauth.PlexAuth.initiate_auth"), patch(
- "plexauth.PlexAuth.token", return_value="BRAND_NEW_TOKEN"
+ with (
+ patch("plexauth.PlexAuth.initiate_auth"),
+ patch("plexauth.PlexAuth.token", return_value="BRAND_NEW_TOKEN"),
):
result = await hass.config_entries.flow.async_configure(flow_id, user_input={})
assert result["type"] == FlowResultType.EXTERNAL_STEP
@@ -792,8 +808,9 @@ async def test_reauth_multiple_servers_available(
flow_id = result["flow_id"]
- with patch("plexauth.PlexAuth.initiate_auth"), patch(
- "plexauth.PlexAuth.token", return_value="BRAND_NEW_TOKEN"
+ with (
+ patch("plexauth.PlexAuth.initiate_auth"),
+ patch("plexauth.PlexAuth.token", return_value="BRAND_NEW_TOKEN"),
):
result = await hass.config_entries.flow.async_configure(flow_id, user_input={})
assert result["type"] == FlowResultType.EXTERNAL_STEP
@@ -826,9 +843,11 @@ async def test_client_request_missing(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
- with patch("plexauth.PlexAuth.initiate_auth"), patch(
- "plexauth.PlexAuth.token", return_value=None
- ), pytest.raises(RuntimeError):
+ with (
+ patch("plexauth.PlexAuth.initiate_auth"),
+ patch("plexauth.PlexAuth.token", return_value=None),
+ pytest.raises(RuntimeError),
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
@@ -848,12 +867,16 @@ async def test_client_header_issues(
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
- with patch("plexauth.PlexAuth.initiate_auth"), patch(
- "plexauth.PlexAuth.token", return_value=None
- ), patch(
- "homeassistant.components.http.current_request.get", return_value=MockRequest()
- ), pytest.raises(
- RuntimeError,
+ with (
+ patch("plexauth.PlexAuth.initiate_auth"),
+ patch("plexauth.PlexAuth.token", return_value=None),
+ patch(
+ "homeassistant.components.http.current_request.get",
+ return_value=MockRequest(),
+ ),
+ pytest.raises(
+ RuntimeError,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
diff --git a/tests/components/plex/test_init.py b/tests/components/plex/test_init.py
index e514ea7baa3..a1a05db9d9a 100644
--- a/tests/components/plex/test_init.py
+++ b/tests/components/plex/test_init.py
@@ -351,9 +351,13 @@ async def test_trigger_reauth(
assert entry.state is ConfigEntryState.LOADED
- with patch(
- "plexapi.server.PlexServer.clients", side_effect=plexapi.exceptions.Unauthorized
- ), patch("plexapi.server.PlexServer", side_effect=plexapi.exceptions.Unauthorized):
+ with (
+ patch(
+ "plexapi.server.PlexServer.clients",
+ side_effect=plexapi.exceptions.Unauthorized,
+ ),
+ patch("plexapi.server.PlexServer", side_effect=plexapi.exceptions.Unauthorized),
+ ):
trigger_plex_update(mock_websocket)
await wait_for_debouncer(hass)
diff --git a/tests/components/plex/test_media_search.py b/tests/components/plex/test_media_search.py
index 517fdd2f689..5578ecd2550 100644
--- a/tests/components/plex/test_media_search.py
+++ b/tests/components/plex/test_media_search.py
@@ -41,8 +41,9 @@ async def test_media_lookups(
},
True,
)
- with pytest.raises(MediaNotFound) as excinfo, patch(
- "plexapi.server.PlexServer.fetchItem", side_effect=NotFound
+ with (
+ pytest.raises(MediaNotFound) as excinfo,
+ patch("plexapi.server.PlexServer.fetchItem", side_effect=NotFound),
):
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
diff --git a/tests/components/plex/test_playback.py b/tests/components/plex/test_playback.py
index 0006ea49efb..33c8b130749 100644
--- a/tests/components/plex/test_playback.py
+++ b/tests/components/plex/test_playback.py
@@ -65,11 +65,14 @@ 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,
- __qualname__="search",
- ), pytest.raises(HomeAssistantError) as excinfo:
+ with (
+ patch(
+ "plexapi.library.LibrarySection.search",
+ return_value=None,
+ __qualname__="search",
+ ),
+ pytest.raises(HomeAssistantError) as excinfo,
+ ):
await hass.services.async_call(
MP_DOMAIN,
SERVICE_PLAY_MEDIA,
@@ -216,13 +219,16 @@ async def test_media_player_playback(
# Test multiple choices with allow_multiple
movies = [movie1, movie2, movie3]
- with patch(
- "plexapi.library.LibrarySection.search",
- return_value=movies,
- __qualname__="search",
- ), patch(
- "homeassistant.components.plex.server.PlexServer.create_playqueue"
- ) as mock_create_playqueue:
+ with (
+ patch(
+ "plexapi.library.LibrarySection.search",
+ return_value=movies,
+ __qualname__="search",
+ ),
+ patch(
+ "homeassistant.components.plex.server.PlexServer.create_playqueue"
+ ) as mock_create_playqueue,
+ ):
await hass.services.async_call(
MP_DOMAIN,
SERVICE_PLAY_MEDIA,
diff --git a/tests/components/plugwise/test_climate.py b/tests/components/plugwise/test_climate.py
index c5ab3a209c2..8041d2778ef 100644
--- a/tests/components/plugwise/test_climate.py
+++ b/tests/components/plugwise/test_climate.py
@@ -98,9 +98,9 @@ async def test_adam_3_climate_entity_attributes(
HVACMode.COOL,
]
data = mock_smile_adam_3.async_update.return_value
- data.devices["da224107914542988a88561b4452b0f6"][
- "select_regulation_mode"
- ] = "heating"
+ data.devices["da224107914542988a88561b4452b0f6"]["select_regulation_mode"] = (
+ "heating"
+ )
data.devices["ad4838d7d35c4d6ea796ee12ae5aedf8"]["control_state"] = "heating"
data.devices["056ee145a816487eaa69243c3280f8bf"]["binary_sensors"][
"cooling_state"
@@ -121,9 +121,9 @@ async def test_adam_3_climate_entity_attributes(
HVACMode.HEAT,
]
data = mock_smile_adam_3.async_update.return_value
- data.devices["da224107914542988a88561b4452b0f6"][
- "select_regulation_mode"
- ] = "cooling"
+ data.devices["da224107914542988a88561b4452b0f6"]["select_regulation_mode"] = (
+ "cooling"
+ )
data.devices["ad4838d7d35c4d6ea796ee12ae5aedf8"]["control_state"] = "cooling"
data.devices["056ee145a816487eaa69243c3280f8bf"]["binary_sensors"][
"cooling_state"
diff --git a/tests/components/plum_lightpad/test_config_flow.py b/tests/components/plum_lightpad/test_config_flow.py
index bfa870dd3b1..37934942734 100644
--- a/tests/components/plum_lightpad/test_config_flow.py
+++ b/tests/components/plum_lightpad/test_config_flow.py
@@ -20,12 +20,13 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.plum_lightpad.utils.Plum.loadCloudData"
- ), patch(
- "homeassistant.components.plum_lightpad.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("homeassistant.components.plum_lightpad.utils.Plum.loadCloudData"),
+ patch(
+ "homeassistant.components.plum_lightpad.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"username": "test-plum-username", "password": "test-plum-password"},
@@ -72,11 +73,12 @@ async def test_form_one_entry_per_email_allowed(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "homeassistant.components.plum_lightpad.utils.Plum.loadCloudData"
- ), patch(
- "homeassistant.components.plum_lightpad.async_setup_entry"
- ) as mock_setup_entry:
+ with (
+ patch("homeassistant.components.plum_lightpad.utils.Plum.loadCloudData"),
+ patch(
+ "homeassistant.components.plum_lightpad.async_setup_entry"
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"username": "test-plum-username", "password": "test-plum-password"},
diff --git a/tests/components/plum_lightpad/test_init.py b/tests/components/plum_lightpad/test_init.py
index 6035713a24f..c34ecfd8deb 100644
--- a/tests/components/plum_lightpad/test_init.py
+++ b/tests/components/plum_lightpad/test_init.py
@@ -28,11 +28,14 @@ async def test_async_setup_entry_sets_up_light(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.plum_lightpad.utils.Plum.loadCloudData"
- ) as mock_loadCloudData, patch(
- "homeassistant.components.plum_lightpad.light.async_setup_entry"
- ) as mock_light_async_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.plum_lightpad.utils.Plum.loadCloudData"
+ ) as mock_loadCloudData,
+ patch(
+ "homeassistant.components.plum_lightpad.light.async_setup_entry"
+ ) as mock_light_async_setup_entry,
+ ):
result = await hass.config_entries.async_setup(config_entry.entry_id)
assert result is True
@@ -50,12 +53,15 @@ async def test_async_setup_entry_handles_auth_error(hass: HomeAssistant) -> None
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.plum_lightpad.utils.Plum.loadCloudData",
- side_effect=ContentTypeError(Mock(), None),
- ), patch(
- "homeassistant.components.plum_lightpad.light.async_setup_entry"
- ) as mock_light_async_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.plum_lightpad.utils.Plum.loadCloudData",
+ side_effect=ContentTypeError(Mock(), None),
+ ),
+ patch(
+ "homeassistant.components.plum_lightpad.light.async_setup_entry"
+ ) as mock_light_async_setup_entry,
+ ):
result = await hass.config_entries.async_setup(config_entry.entry_id)
assert result is False
@@ -70,12 +76,15 @@ async def test_async_setup_entry_handles_http_error(hass: HomeAssistant) -> None
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.plum_lightpad.utils.Plum.loadCloudData",
- side_effect=HTTPError,
- ), patch(
- "homeassistant.components.plum_lightpad.light.async_setup_entry"
- ) as mock_light_async_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.plum_lightpad.utils.Plum.loadCloudData",
+ side_effect=HTTPError,
+ ),
+ patch(
+ "homeassistant.components.plum_lightpad.light.async_setup_entry"
+ ) as mock_light_async_setup_entry,
+ ):
result = await hass.config_entries.async_setup(config_entry.entry_id)
assert result is False
diff --git a/tests/components/poolsense/test_config_flow.py b/tests/components/poolsense/test_config_flow.py
index 76766ef1d87..7a91e546a59 100644
--- a/tests/components/poolsense/test_config_flow.py
+++ b/tests/components/poolsense/test_config_flow.py
@@ -37,11 +37,12 @@ async def test_invalid_credentials(hass: HomeAssistant) -> None:
async def test_valid_credentials(hass: HomeAssistant) -> None:
"""Test we handle invalid credentials."""
- with patch(
- "poolsense.PoolSense.test_poolsense_credentials", return_value=True
- ), patch(
- "homeassistant.components.poolsense.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch("poolsense.PoolSense.test_poolsense_credentials", return_value=True),
+ patch(
+ "homeassistant.components.poolsense.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
diff --git a/tests/components/powerwall/test_binary_sensor.py b/tests/components/powerwall/test_binary_sensor.py
index 1fc576543c3..6b7e73373ee 100644
--- a/tests/components/powerwall/test_binary_sensor.py
+++ b/tests/components/powerwall/test_binary_sensor.py
@@ -18,11 +18,14 @@ async def test_sensors(hass: HomeAssistant) -> None:
config_entry = MockConfigEntry(domain=DOMAIN, data={CONF_IP_ADDRESS: "1.2.3.4"})
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.powerwall.config_flow.Powerwall",
- return_value=mock_powerwall,
- ), patch(
- "homeassistant.components.powerwall.Powerwall", return_value=mock_powerwall
+ with (
+ patch(
+ "homeassistant.components.powerwall.config_flow.Powerwall",
+ return_value=mock_powerwall,
+ ),
+ patch(
+ "homeassistant.components.powerwall.Powerwall", return_value=mock_powerwall
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -85,11 +88,14 @@ async def test_sensors_with_empty_meters(hass: HomeAssistant) -> None:
config_entry = MockConfigEntry(domain=DOMAIN, data={CONF_IP_ADDRESS: "1.2.3.4"})
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.powerwall.config_flow.Powerwall",
- return_value=mock_powerwall,
- ), patch(
- "homeassistant.components.powerwall.Powerwall", return_value=mock_powerwall
+ with (
+ patch(
+ "homeassistant.components.powerwall.config_flow.Powerwall",
+ return_value=mock_powerwall,
+ ),
+ patch(
+ "homeassistant.components.powerwall.Powerwall", return_value=mock_powerwall
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/powerwall/test_config_flow.py b/tests/components/powerwall/test_config_flow.py
index 1b78a4a7212..83156ffb170 100644
--- a/tests/components/powerwall/test_config_flow.py
+++ b/tests/components/powerwall/test_config_flow.py
@@ -41,13 +41,16 @@ async def test_form_source_user(hass: HomeAssistant) -> None:
mock_powerwall = await _mock_powerwall_site_name(hass, "MySite")
- with patch(
- "homeassistant.components.powerwall.config_flow.Powerwall",
- return_value=mock_powerwall,
- ), patch(
- "homeassistant.components.powerwall.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.powerwall.config_flow.Powerwall",
+ return_value=mock_powerwall,
+ ),
+ patch(
+ "homeassistant.components.powerwall.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
VALID_CONFIG,
@@ -193,13 +196,16 @@ async def test_already_configured_with_ignored(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] is None
- with patch(
- "homeassistant.components.powerwall.config_flow.Powerwall",
- return_value=mock_powerwall,
- ), patch(
- "homeassistant.components.powerwall.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.powerwall.config_flow.Powerwall",
+ return_value=mock_powerwall,
+ ),
+ patch(
+ "homeassistant.components.powerwall.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{},
@@ -232,13 +238,16 @@ async def test_dhcp_discovery_manual_configure(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.powerwall.config_flow.Powerwall",
- return_value=mock_powerwall,
- ), patch(
- "homeassistant.components.powerwall.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.powerwall.config_flow.Powerwall",
+ return_value=mock_powerwall,
+ ),
+ patch(
+ "homeassistant.components.powerwall.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
VALID_CONFIG,
@@ -271,13 +280,16 @@ async def test_dhcp_discovery_auto_configure(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] is None
- with patch(
- "homeassistant.components.powerwall.config_flow.Powerwall",
- return_value=mock_powerwall,
- ), patch(
- "homeassistant.components.powerwall.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.powerwall.config_flow.Powerwall",
+ return_value=mock_powerwall,
+ ),
+ patch(
+ "homeassistant.components.powerwall.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{},
@@ -333,13 +345,16 @@ async def test_form_reauth(hass: HomeAssistant) -> None:
mock_powerwall = await _mock_powerwall_site_name(hass, "My site")
- with patch(
- "homeassistant.components.powerwall.config_flow.Powerwall",
- return_value=mock_powerwall,
- ), patch(
- "homeassistant.components.powerwall.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.powerwall.config_flow.Powerwall",
+ return_value=mock_powerwall,
+ ),
+ patch(
+ "homeassistant.components.powerwall.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -364,12 +379,15 @@ async def test_dhcp_discovery_update_ip_address(hass: HomeAssistant) -> None:
mock_powerwall = MagicMock(login=MagicMock(side_effect=PowerwallUnreachableError))
mock_powerwall.__aenter__.return_value = mock_powerwall
- with patch(
- "homeassistant.components.powerwall.config_flow.Powerwall",
- return_value=mock_powerwall,
- ), patch(
- "homeassistant.components.powerwall.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.powerwall.config_flow.Powerwall",
+ return_value=mock_powerwall,
+ ),
+ patch(
+ "homeassistant.components.powerwall.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -398,12 +416,15 @@ async def test_dhcp_discovery_does_not_update_ip_when_auth_fails(
entry.add_to_hass(hass)
mock_powerwall = MagicMock(login=MagicMock(side_effect=AccessDeniedError("any")))
- with patch(
- "homeassistant.components.powerwall.config_flow.Powerwall",
- return_value=mock_powerwall,
- ), patch(
- "homeassistant.components.powerwall.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.powerwall.config_flow.Powerwall",
+ return_value=mock_powerwall,
+ ),
+ patch(
+ "homeassistant.components.powerwall.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -432,12 +453,15 @@ async def test_dhcp_discovery_does_not_update_ip_when_auth_successful(
entry.add_to_hass(hass)
mock_powerwall = MagicMock(login=MagicMock(return_value=True))
- with patch(
- "homeassistant.components.powerwall.config_flow.Powerwall",
- return_value=mock_powerwall,
- ), patch(
- "homeassistant.components.powerwall.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.powerwall.config_flow.Powerwall",
+ return_value=mock_powerwall,
+ ),
+ patch(
+ "homeassistant.components.powerwall.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -464,12 +488,15 @@ async def test_dhcp_discovery_updates_unique_id(hass: HomeAssistant) -> None:
entry.add_to_hass(hass)
mock_powerwall = await _mock_powerwall_site_name(hass, "Some site")
- with patch(
- "homeassistant.components.powerwall.config_flow.Powerwall",
- return_value=mock_powerwall,
- ), patch(
- "homeassistant.components.powerwall.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.powerwall.config_flow.Powerwall",
+ return_value=mock_powerwall,
+ ),
+ patch(
+ "homeassistant.components.powerwall.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -500,12 +527,15 @@ async def test_dhcp_discovery_updates_unique_id_when_entry_is_failed(
entry.mock_state(hass, config_entries.ConfigEntryState.SETUP_ERROR)
mock_powerwall = await _mock_powerwall_site_name(hass, "Some site")
- with patch(
- "homeassistant.components.powerwall.config_flow.Powerwall",
- return_value=mock_powerwall,
- ), patch(
- "homeassistant.components.powerwall.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.powerwall.config_flow.Powerwall",
+ return_value=mock_powerwall,
+ ),
+ patch(
+ "homeassistant.components.powerwall.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -535,11 +565,14 @@ async def test_discovered_wifi_does_not_update_ip_if_is_still_online(
entry.add_to_hass(hass)
mock_powerwall = await _mock_powerwall_with_fixtures(hass)
- with patch(
- "homeassistant.components.powerwall.config_flow.Powerwall",
- return_value=mock_powerwall,
- ), patch(
- "homeassistant.components.powerwall.Powerwall", return_value=mock_powerwall
+ with (
+ patch(
+ "homeassistant.components.powerwall.config_flow.Powerwall",
+ return_value=mock_powerwall,
+ ),
+ patch(
+ "homeassistant.components.powerwall.Powerwall", return_value=mock_powerwall
+ ),
):
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
@@ -572,11 +605,14 @@ async def test_discovered_wifi_does_not_update_ip_online_but_access_denied(
mock_powerwall_no_access = await _mock_powerwall_with_fixtures(hass)
mock_powerwall_no_access.login.side_effect = AccessDeniedError("any")
- with patch(
- "homeassistant.components.powerwall.config_flow.Powerwall",
- return_value=mock_powerwall_no_access,
- ), patch(
- "homeassistant.components.powerwall.Powerwall", return_value=mock_powerwall
+ with (
+ patch(
+ "homeassistant.components.powerwall.config_flow.Powerwall",
+ return_value=mock_powerwall_no_access,
+ ),
+ patch(
+ "homeassistant.components.powerwall.Powerwall", return_value=mock_powerwall
+ ),
):
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/powerwall/test_init.py b/tests/components/powerwall/test_init.py
index ed0dc0ebde8..de8da12ccb5 100644
--- a/tests/components/powerwall/test_init.py
+++ b/tests/components/powerwall/test_init.py
@@ -40,11 +40,14 @@ async def test_update_data_reauthenticate_on_access_denied(hass: HomeAssistant)
domain=DOMAIN, data={CONF_IP_ADDRESS: "1.2.3.4", CONF_PASSWORD: "password"}
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.powerwall.config_flow.Powerwall",
- return_value=mock_powerwall,
- ), patch(
- "homeassistant.components.powerwall.Powerwall", return_value=mock_powerwall
+ with (
+ patch(
+ "homeassistant.components.powerwall.config_flow.Powerwall",
+ return_value=mock_powerwall,
+ ),
+ patch(
+ "homeassistant.components.powerwall.Powerwall", return_value=mock_powerwall
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/powerwall/test_sensor.py b/tests/components/powerwall/test_sensor.py
index 8ef577f8eee..2ec9f44bd0e 100644
--- a/tests/components/powerwall/test_sensor.py
+++ b/tests/components/powerwall/test_sensor.py
@@ -34,11 +34,14 @@ async def test_sensors(
config_entry = MockConfigEntry(domain=DOMAIN, data={CONF_IP_ADDRESS: "1.2.3.4"})
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.powerwall.config_flow.Powerwall",
- return_value=mock_powerwall,
- ), patch(
- "homeassistant.components.powerwall.Powerwall", return_value=mock_powerwall
+ with (
+ patch(
+ "homeassistant.components.powerwall.config_flow.Powerwall",
+ return_value=mock_powerwall,
+ ),
+ patch(
+ "homeassistant.components.powerwall.Powerwall", return_value=mock_powerwall
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -203,11 +206,14 @@ async def test_sensor_backup_reserve_unavailable(hass: HomeAssistant) -> None:
config_entry = MockConfigEntry(domain=DOMAIN, data={CONF_IP_ADDRESS: "1.2.3.4"})
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.powerwall.config_flow.Powerwall",
- return_value=mock_powerwall,
- ), patch(
- "homeassistant.components.powerwall.Powerwall", return_value=mock_powerwall
+ with (
+ patch(
+ "homeassistant.components.powerwall.config_flow.Powerwall",
+ return_value=mock_powerwall,
+ ),
+ patch(
+ "homeassistant.components.powerwall.Powerwall", return_value=mock_powerwall
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -223,11 +229,14 @@ async def test_sensors_with_empty_meters(hass: HomeAssistant) -> None:
config_entry = MockConfigEntry(domain=DOMAIN, data={CONF_IP_ADDRESS: "1.2.3.4"})
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.powerwall.config_flow.Powerwall",
- return_value=mock_powerwall,
- ), patch(
- "homeassistant.components.powerwall.Powerwall", return_value=mock_powerwall
+ with (
+ patch(
+ "homeassistant.components.powerwall.config_flow.Powerwall",
+ return_value=mock_powerwall,
+ ),
+ patch(
+ "homeassistant.components.powerwall.Powerwall", return_value=mock_powerwall
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -261,11 +270,14 @@ async def test_unique_id_migrate(
)
assert old_mysite_load_power_entity.entity_id == "sensor.mysite_load_power"
- with patch(
- "homeassistant.components.powerwall.config_flow.Powerwall",
- return_value=mock_powerwall,
- ), patch(
- "homeassistant.components.powerwall.Powerwall", return_value=mock_powerwall
+ with (
+ patch(
+ "homeassistant.components.powerwall.config_flow.Powerwall",
+ return_value=mock_powerwall,
+ ),
+ patch(
+ "homeassistant.components.powerwall.Powerwall", return_value=mock_powerwall
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/profiler/test_init.py b/tests/components/profiler/test_init.py
index 8847e779b9e..1140dc74849 100644
--- a/tests/components/profiler/test_init.py
+++ b/tests/components/profiler/test_init.py
@@ -337,8 +337,9 @@ async def test_log_object_sources(
fake_object2 = FakeObject()
- with patch("gc.collect"), patch(
- "gc.get_objects", return_value=[fake_object, fake_object2]
+ with (
+ patch("gc.collect"),
+ patch("gc.get_objects", return_value=[fake_object, fake_object2]),
):
caplog.clear()
diff --git a/tests/components/prosegur/conftest.py b/tests/components/prosegur/conftest.py
index bab871d9952..0b18c2c5e17 100644
--- a/tests/components/prosegur/conftest.py
+++ b/tests/components/prosegur/conftest.py
@@ -62,9 +62,12 @@ async def init_integration(
"""Set up the Prosegur integration for testing."""
mock_config_entry.add_to_hass(hass)
- with patch(
- "pyprosegur.installation.Installation.retrieve", return_value=mock_install
- ), patch("pyprosegur.auth.Auth.login"):
+ with (
+ patch(
+ "pyprosegur.installation.Installation.retrieve", return_value=mock_install
+ ),
+ patch("pyprosegur.auth.Auth.login"),
+ ):
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/prosegur/test_camera.py b/tests/components/prosegur/test_camera.py
index fdf13e30359..ed503d676ff 100644
--- a/tests/components/prosegur/test_camera.py
+++ b/tests/components/prosegur/test_camera.py
@@ -34,9 +34,10 @@ async def test_camera_fail(
return_value=b"ABC", side_effect=ProsegurException()
)
- with caplog.at_level(
- logging.ERROR, logger="homeassistant.components.prosegur"
- ), pytest.raises(HomeAssistantError) as exc:
+ with (
+ caplog.at_level(logging.ERROR, logger="homeassistant.components.prosegur"),
+ pytest.raises(HomeAssistantError) as exc,
+ ):
await camera.async_get_image(hass, "camera.contract_1234abcd_test_cam")
assert "Unable to get image" in str(exc.value)
diff --git a/tests/components/prosegur/test_config_flow.py b/tests/components/prosegur/test_config_flow.py
index c0a7ffcb1eb..3c3c2468696 100644
--- a/tests/components/prosegur/test_config_flow.py
+++ b/tests/components/prosegur/test_config_flow.py
@@ -22,13 +22,16 @@ async def test_form(hass: HomeAssistant, mock_list_contracts) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.prosegur.config_flow.Installation.list",
- return_value=mock_list_contracts,
- ) as mock_retrieve, patch(
- "homeassistant.components.prosegur.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.prosegur.config_flow.Installation.list",
+ return_value=mock_list_contracts,
+ ) as mock_retrieve,
+ patch(
+ "homeassistant.components.prosegur.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -153,13 +156,16 @@ async def test_reauth_flow(hass: HomeAssistant, mock_list_contracts) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.prosegur.config_flow.Installation.list",
- return_value=mock_list_contracts,
- ) as mock_installation, patch(
- "homeassistant.components.prosegur.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.prosegur.config_flow.Installation.list",
+ return_value=mock_list_contracts,
+ ) as mock_installation,
+ patch(
+ "homeassistant.components.prosegur.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
diff --git a/tests/components/prusalink/test_button.py b/tests/components/prusalink/test_button.py
index e99cf9c2180..54f3854161c 100644
--- a/tests/components/prusalink/test_button.py
+++ b/tests/components/prusalink/test_button.py
@@ -55,8 +55,9 @@ async def test_button_pause_cancel(
assert len(mock_meth.mock_calls) == 1
# Verify it calls correct method + does error handling
- with pytest.raises(HomeAssistantError), patch(
- f"pyprusalink.PrusaLink.{method}", side_effect=Conflict
+ with (
+ pytest.raises(HomeAssistantError),
+ patch(f"pyprusalink.PrusaLink.{method}", side_effect=Conflict),
):
await hass.services.async_call(
"button",
@@ -89,8 +90,11 @@ async def test_button_resume_cancel(
assert state is not None
assert state.state == "unknown"
- with patch(f"pyprusalink.PrusaLink.{method}") as mock_meth, patch(
- "homeassistant.components.prusalink.PrusaLinkUpdateCoordinator._fetch_data"
+ with (
+ patch(f"pyprusalink.PrusaLink.{method}") as mock_meth,
+ patch(
+ "homeassistant.components.prusalink.PrusaLinkUpdateCoordinator._fetch_data"
+ ),
):
await hass.services.async_call(
"button",
@@ -102,8 +106,9 @@ async def test_button_resume_cancel(
assert len(mock_meth.mock_calls) == 1
# Verify it calls correct method + does error handling
- with pytest.raises(HomeAssistantError), patch(
- f"pyprusalink.PrusaLink.{method}", side_effect=Conflict
+ with (
+ pytest.raises(HomeAssistantError),
+ patch(f"pyprusalink.PrusaLink.{method}", side_effect=Conflict),
):
await hass.services.async_call(
"button",
diff --git a/tests/components/prusalink/test_init.py b/tests/components/prusalink/test_init.py
index a462a64ca31..1160143ea11 100644
--- a/tests/components/prusalink/test_init.py
+++ b/tests/components/prusalink/test_init.py
@@ -44,18 +44,23 @@ async def test_failed_update(
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
assert mock_config_entry.state == ConfigEntryState.LOADED
- with patch(
- "homeassistant.components.prusalink.PrusaLink.get_version",
- side_effect=exception,
- ), patch(
- "homeassistant.components.prusalink.PrusaLink.get_status",
- side_effect=exception,
- ), patch(
- "homeassistant.components.prusalink.PrusaLink.get_legacy_printer",
- side_effect=exception,
- ), patch(
- "homeassistant.components.prusalink.PrusaLink.get_job",
- side_effect=exception,
+ with (
+ patch(
+ "homeassistant.components.prusalink.PrusaLink.get_version",
+ side_effect=exception,
+ ),
+ patch(
+ "homeassistant.components.prusalink.PrusaLink.get_status",
+ side_effect=exception,
+ ),
+ patch(
+ "homeassistant.components.prusalink.PrusaLink.get_legacy_printer",
+ side_effect=exception,
+ ),
+ patch(
+ "homeassistant.components.prusalink.PrusaLink.get_job",
+ side_effect=exception,
+ ),
):
async_fire_time_changed(hass, utcnow() + timedelta(seconds=30), fire_all=True)
await hass.async_block_till_done()
diff --git a/tests/components/prusalink/test_sensor.py b/tests/components/prusalink/test_sensor.py
index 366f2d3abc8..bba06f66146 100644
--- a/tests/components/prusalink/test_sensor.py
+++ b/tests/components/prusalink/test_sensor.py
@@ -27,11 +27,12 @@ from homeassistant.setup import async_setup_component
@pytest.fixture(autouse=True)
def setup_sensor_platform_only():
"""Only setup sensor platform."""
- with patch(
- "homeassistant.components.prusalink.PLATFORMS", [Platform.SENSOR]
- ), patch(
- "homeassistant.helpers.entity.Entity.entity_registry_enabled_default",
- PropertyMock(return_value=True),
+ with (
+ patch("homeassistant.components.prusalink.PLATFORMS", [Platform.SENSOR]),
+ patch(
+ "homeassistant.helpers.entity.Entity.entity_registry_enabled_default",
+ PropertyMock(return_value=True),
+ ),
):
yield
diff --git a/tests/components/ps4/test_config_flow.py b/tests/components/ps4/test_config_flow.py
index 61bf01f0a91..db478903d1e 100644
--- a/tests/components/ps4/test_config_flow.py
+++ b/tests/components/ps4/test_config_flow.py
@@ -127,8 +127,11 @@ async def test_full_flow_implementation(hass: HomeAssistant) -> None:
assert result["step_id"] == "link"
# User Input results in created entry.
- with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch(
- "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}]
+ with (
+ patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)),
+ patch(
+ "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}]
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_CONFIG
@@ -169,9 +172,12 @@ async def test_multiple_flow_implementation(hass: HomeAssistant) -> None:
assert result["step_id"] == "link"
# User Input results in created entry.
- with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch(
- "pyps4_2ndscreen.Helper.has_devices",
- return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}],
+ with (
+ patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)),
+ patch(
+ "pyps4_2ndscreen.Helper.has_devices",
+ return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}],
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_CONFIG
@@ -191,9 +197,12 @@ async def test_multiple_flow_implementation(hass: HomeAssistant) -> None:
# Test additional flow.
# User Step Started, results in Step Mode:
- with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None), patch(
- "pyps4_2ndscreen.Helper.has_devices",
- return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}],
+ with (
+ patch("pyps4_2ndscreen.Helper.port_bind", return_value=None),
+ patch(
+ "pyps4_2ndscreen.Helper.has_devices",
+ return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}],
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@@ -221,10 +230,13 @@ async def test_multiple_flow_implementation(hass: HomeAssistant) -> None:
assert result["step_id"] == "link"
# Step Link
- with patch(
- "pyps4_2ndscreen.Helper.has_devices",
- return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}],
- ), patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)):
+ with (
+ patch(
+ "pyps4_2ndscreen.Helper.has_devices",
+ return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}],
+ ),
+ patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)),
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL
)
@@ -341,11 +353,14 @@ async def test_0_pin(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "mode"
- with patch(
- "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}]
- ), patch(
- "homeassistant.components.ps4.config_flow.location.async_detect_location_info",
- return_value=MOCK_LOCATION,
+ with (
+ patch(
+ "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}]
+ ),
+ patch(
+ "homeassistant.components.ps4.config_flow.location.async_detect_location_info",
+ return_value=MOCK_LOCATION,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], MOCK_AUTO
@@ -355,10 +370,11 @@ async def test_0_pin(hass: HomeAssistant) -> None:
mock_config = MOCK_CONFIG
mock_config[CONF_CODE] = MOCK_CODE_LEAD_0
- with patch(
- "pyps4_2ndscreen.Helper.link", return_value=(True, True)
- ) as mock_call, patch(
- "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}]
+ with (
+ patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)) as mock_call,
+ patch(
+ "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}]
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], mock_config
diff --git a/tests/components/ps4/test_init.py b/tests/components/ps4/test_init.py
index cc2ec5fde1b..238c3c15112 100644
--- a/tests/components/ps4/test_init.py
+++ b/tests/components/ps4/test_init.py
@@ -122,10 +122,13 @@ async def test_ps4_integration_setup(hass: HomeAssistant) -> None:
async def test_creating_entry_sets_up_media_player(hass: HomeAssistant) -> None:
"""Test setting up PS4 loads the media player."""
mock_flow = "homeassistant.components.ps4.PlayStation4FlowHandler.async_step_user"
- with patch(
- "homeassistant.components.ps4.media_player.async_setup_entry",
- return_value=True,
- ) as mock_setup, patch(mock_flow, return_value=MOCK_FLOW_RESULT):
+ with (
+ patch(
+ "homeassistant.components.ps4.media_player.async_setup_entry",
+ return_value=True,
+ ) as mock_setup,
+ patch(mock_flow, return_value=MOCK_FLOW_RESULT),
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
@@ -156,12 +159,15 @@ async def test_config_flow_entry_migrate(
assert mock_e_entry.entity_id == mock_entity_id
assert mock_e_entry.unique_id == MOCK_UNIQUE_ID
- with patch(
- "homeassistant.util.location.async_detect_location_info",
- return_value=MOCK_LOCATION,
- ), patch(
- "homeassistant.helpers.entity_registry.async_get",
- return_value=entity_registry,
+ with (
+ patch(
+ "homeassistant.util.location.async_detect_location_info",
+ return_value=MOCK_LOCATION,
+ ),
+ patch(
+ "homeassistant.helpers.entity_registry.async_get",
+ return_value=entity_registry,
+ ),
):
await ps4.async_migrate_entry(hass, mock_entry)
@@ -205,9 +211,10 @@ def test_games_reformat_to_dict(
) -> None:
"""Test old data format is converted to new format."""
patch_load_json_object.return_value = MOCK_GAMES_DATA_OLD_STR_FORMAT
- with patch(
- "homeassistant.components.ps4.save_json", side_effect=MagicMock()
- ), patch("os.path.isfile", return_value=True):
+ with (
+ patch("homeassistant.components.ps4.save_json", side_effect=MagicMock()),
+ patch("os.path.isfile", return_value=True),
+ ):
mock_games = ps4.load_games(hass, MOCK_ENTRY_ID)
# New format is a nested dict.
@@ -226,9 +233,10 @@ def test_games_reformat_to_dict(
def test_load_games(hass: HomeAssistant, patch_load_json_object: MagicMock) -> None:
"""Test that games are loaded correctly."""
patch_load_json_object.return_value = MOCK_GAMES
- with patch(
- "homeassistant.components.ps4.save_json", side_effect=MagicMock()
- ), patch("os.path.isfile", return_value=True):
+ with (
+ patch("homeassistant.components.ps4.save_json", side_effect=MagicMock()),
+ patch("os.path.isfile", return_value=True),
+ ):
mock_games = ps4.load_games(hass, MOCK_ENTRY_ID)
assert isinstance(mock_games, dict)
@@ -246,9 +254,10 @@ def test_loading_games_returns_dict(
) -> None:
"""Test that loading games always returns a dict."""
patch_load_json_object.side_effect = HomeAssistantError
- with patch(
- "homeassistant.components.ps4.save_json", side_effect=MagicMock()
- ), patch("os.path.isfile", return_value=True):
+ with (
+ patch("homeassistant.components.ps4.save_json", side_effect=MagicMock()),
+ patch("os.path.isfile", return_value=True),
+ ):
mock_games = ps4.load_games(hass, MOCK_ENTRY_ID)
assert isinstance(mock_games, dict)
diff --git a/tests/components/ps4/test_media_player.py b/tests/components/ps4/test_media_player.py
index a21a0800711..875b049d8c3 100644
--- a/tests/components/ps4/test_media_player.py
+++ b/tests/components/ps4/test_media_player.py
@@ -461,8 +461,9 @@ async def test_select_source(
with patch("pyps4_2ndscreen.ps4.get_status", return_value=MOCK_STATUS_IDLE):
mock_entity_id = await setup_mock_component(hass)
- with patch("pyps4_2ndscreen.ps4.Ps4Async.start_title") as mock_call, patch(
- "homeassistant.components.ps4.media_player.PS4Device.async_update"
+ with (
+ patch("pyps4_2ndscreen.ps4.Ps4Async.start_title") as mock_call,
+ patch("homeassistant.components.ps4.media_player.PS4Device.async_update"),
):
# Test with title name.
await hass.services.async_call(
@@ -483,8 +484,9 @@ async def test_select_source_caps(
with patch("pyps4_2ndscreen.ps4.get_status", return_value=MOCK_STATUS_IDLE):
mock_entity_id = await setup_mock_component(hass)
- with patch("pyps4_2ndscreen.ps4.Ps4Async.start_title") as mock_call, patch(
- "homeassistant.components.ps4.media_player.PS4Device.async_update"
+ with (
+ patch("pyps4_2ndscreen.ps4.Ps4Async.start_title") as mock_call,
+ patch("homeassistant.components.ps4.media_player.PS4Device.async_update"),
):
# Test with title name in caps.
await hass.services.async_call(
@@ -508,8 +510,9 @@ async def test_select_source_id(
with patch("pyps4_2ndscreen.ps4.get_status", return_value=MOCK_STATUS_IDLE):
mock_entity_id = await setup_mock_component(hass)
- with patch("pyps4_2ndscreen.ps4.Ps4Async.start_title") as mock_call, patch(
- "homeassistant.components.ps4.media_player.PS4Device.async_update"
+ with (
+ patch("pyps4_2ndscreen.ps4.Ps4Async.start_title") as mock_call,
+ patch("homeassistant.components.ps4.media_player.PS4Device.async_update"),
):
# Test with title ID.
await hass.services.async_call(
diff --git a/tests/components/purpleair/conftest.py b/tests/components/purpleair/conftest.py
index 7299616ad35..1305c98308d 100644
--- a/tests/components/purpleair/conftest.py
+++ b/tests/components/purpleair/conftest.py
@@ -74,9 +74,10 @@ def get_sensors_response_fixture():
@pytest.fixture(name="mock_aiopurpleair")
async def mock_aiopurpleair_fixture(api):
"""Define a fixture to patch aiopurpleair."""
- with patch(
- "homeassistant.components.purpleair.config_flow.API", return_value=api
- ), patch("homeassistant.components.purpleair.coordinator.API", return_value=api):
+ with (
+ patch("homeassistant.components.purpleair.config_flow.API", return_value=api),
+ patch("homeassistant.components.purpleair.coordinator.API", return_value=api),
+ ):
yield api
diff --git a/tests/components/pvoutput/conftest.py b/tests/components/pvoutput/conftest.py
index 118bed94d77..122b55ca4c2 100644
--- a/tests/components/pvoutput/conftest.py
+++ b/tests/components/pvoutput/conftest.py
@@ -38,10 +38,13 @@ def mock_setup_entry() -> Generator[AsyncMock, None, None]:
@pytest.fixture
def mock_pvoutput() -> Generator[None, MagicMock, None]:
"""Return a mocked PVOutput client."""
- with patch(
- "homeassistant.components.pvoutput.coordinator.PVOutput", autospec=True
- ) as pvoutput_mock, patch(
- "homeassistant.components.pvoutput.config_flow.PVOutput", new=pvoutput_mock
+ with (
+ patch(
+ "homeassistant.components.pvoutput.coordinator.PVOutput", autospec=True
+ ) as pvoutput_mock,
+ patch(
+ "homeassistant.components.pvoutput.config_flow.PVOutput", new=pvoutput_mock
+ ),
):
pvoutput = pvoutput_mock.return_value
pvoutput.status.return_value = Status.from_dict(
diff --git a/tests/components/python_script/test_init.py b/tests/components/python_script/test_init.py
index ced279b2f9a..bec94db71f9 100644
--- a/tests/components/python_script/test_init.py
+++ b/tests/components/python_script/test_init.py
@@ -20,20 +20,28 @@ async def test_setup(hass: HomeAssistant) -> None:
"/some/config/dir/python_scripts/hello.py",
"/some/config/dir/python_scripts/world_beer.py",
]
- with patch(
- "homeassistant.components.python_script.os.path.isdir", return_value=True
- ), patch("homeassistant.components.python_script.glob.iglob", return_value=scripts):
+ with (
+ patch(
+ "homeassistant.components.python_script.os.path.isdir", return_value=True
+ ),
+ patch(
+ "homeassistant.components.python_script.glob.iglob", return_value=scripts
+ ),
+ ):
res = await async_setup_component(hass, "python_script", {})
assert res
assert hass.services.has_service("python_script", "hello")
assert hass.services.has_service("python_script", "world_beer")
- with patch(
- "homeassistant.components.python_script.open",
- mock_open(read_data="fake source"),
- create=True,
- ), patch("homeassistant.components.python_script.execute") as mock_ex:
+ with (
+ patch(
+ "homeassistant.components.python_script.open",
+ mock_open(read_data="fake source"),
+ create=True,
+ ),
+ patch("homeassistant.components.python_script.execute") as mock_ex,
+ ):
await hass.services.async_call(
"python_script", "hello", {"some": "data"}, blocking=True
)
@@ -357,9 +365,14 @@ async def test_reload(hass: HomeAssistant) -> None:
"/some/config/dir/python_scripts/hello.py",
"/some/config/dir/python_scripts/world_beer.py",
]
- with patch(
- "homeassistant.components.python_script.os.path.isdir", return_value=True
- ), patch("homeassistant.components.python_script.glob.iglob", return_value=scripts):
+ with (
+ patch(
+ "homeassistant.components.python_script.os.path.isdir", return_value=True
+ ),
+ patch(
+ "homeassistant.components.python_script.glob.iglob", return_value=scripts
+ ),
+ ):
res = await async_setup_component(hass, "python_script", {})
assert res
@@ -371,9 +384,14 @@ async def test_reload(hass: HomeAssistant) -> None:
"/some/config/dir/python_scripts/hello2.py",
"/some/config/dir/python_scripts/world_beer.py",
]
- with patch(
- "homeassistant.components.python_script.os.path.isdir", return_value=True
- ), patch("homeassistant.components.python_script.glob.iglob", return_value=scripts):
+ with (
+ patch(
+ "homeassistant.components.python_script.os.path.isdir", return_value=True
+ ),
+ patch(
+ "homeassistant.components.python_script.glob.iglob", return_value=scripts
+ ),
+ ):
await hass.services.async_call("python_script", "reload", {}, blocking=True)
assert not hass.services.has_service("python_script", "hello")
@@ -403,14 +421,19 @@ async def test_service_descriptions(hass: HomeAssistant) -> None:
f"{hass.config.config_dir}/{FOLDER}/services.yaml": service_descriptions1
}
- with patch(
- "homeassistant.components.python_script.os.path.isdir", return_value=True
- ), patch(
- "homeassistant.components.python_script.glob.iglob", return_value=scripts1
- ), patch(
- "homeassistant.components.python_script.os.path.exists", return_value=True
- ), patch_yaml_files(
- services_yaml1,
+ with (
+ patch(
+ "homeassistant.components.python_script.os.path.isdir", return_value=True
+ ),
+ patch(
+ "homeassistant.components.python_script.glob.iglob", return_value=scripts1
+ ),
+ patch(
+ "homeassistant.components.python_script.os.path.exists", return_value=True
+ ),
+ patch_yaml_files(
+ services_yaml1,
+ ),
):
await async_setup_component(hass, DOMAIN, {})
@@ -452,14 +475,19 @@ async def test_service_descriptions(hass: HomeAssistant) -> None:
f"{hass.config.config_dir}/{FOLDER}/services.yaml": service_descriptions2
}
- with patch(
- "homeassistant.components.python_script.os.path.isdir", return_value=True
- ), patch(
- "homeassistant.components.python_script.glob.iglob", return_value=scripts2
- ), patch(
- "homeassistant.components.python_script.os.path.exists", return_value=True
- ), patch_yaml_files(
- services_yaml2,
+ with (
+ patch(
+ "homeassistant.components.python_script.os.path.isdir", return_value=True
+ ),
+ patch(
+ "homeassistant.components.python_script.glob.iglob", return_value=scripts2
+ ),
+ patch(
+ "homeassistant.components.python_script.os.path.exists", return_value=True
+ ),
+ patch_yaml_files(
+ services_yaml2,
+ ),
):
await hass.services.async_call(DOMAIN, "reload", {}, blocking=True)
descriptions = await async_get_all_descriptions(hass)
@@ -503,9 +531,14 @@ async def test_execute_with_output(
scripts = [
"/some/config/dir/python_scripts/hello.py",
]
- with patch(
- "homeassistant.components.python_script.os.path.isdir", return_value=True
- ), patch("homeassistant.components.python_script.glob.iglob", return_value=scripts):
+ with (
+ patch(
+ "homeassistant.components.python_script.os.path.isdir", return_value=True
+ ),
+ patch(
+ "homeassistant.components.python_script.glob.iglob", return_value=scripts
+ ),
+ ):
await async_setup_component(hass, "python_script", {})
source = """
@@ -542,9 +575,14 @@ async def test_execute_no_output(
scripts = [
"/some/config/dir/python_scripts/hello.py",
]
- with patch(
- "homeassistant.components.python_script.os.path.isdir", return_value=True
- ), patch("homeassistant.components.python_script.glob.iglob", return_value=scripts):
+ with (
+ patch(
+ "homeassistant.components.python_script.os.path.isdir", return_value=True
+ ),
+ patch(
+ "homeassistant.components.python_script.glob.iglob", return_value=scripts
+ ),
+ ):
await async_setup_component(hass, "python_script", {})
source = """
@@ -576,20 +614,28 @@ async def test_execute_wrong_output_type(hass: HomeAssistant) -> None:
scripts = [
"/some/config/dir/python_scripts/hello.py",
]
- with patch(
- "homeassistant.components.python_script.os.path.isdir", return_value=True
- ), patch("homeassistant.components.python_script.glob.iglob", return_value=scripts):
+ with (
+ patch(
+ "homeassistant.components.python_script.os.path.isdir", return_value=True
+ ),
+ patch(
+ "homeassistant.components.python_script.glob.iglob", return_value=scripts
+ ),
+ ):
await async_setup_component(hass, "python_script", {})
source = """
output = f"hello {data.get('name', 'World')}"
"""
- with patch(
- "homeassistant.components.python_script.open",
- mock_open(read_data=source),
- create=True,
- ), pytest.raises(ServiceValidationError):
+ with (
+ patch(
+ "homeassistant.components.python_script.open",
+ mock_open(read_data=source),
+ create=True,
+ ),
+ pytest.raises(ServiceValidationError),
+ ):
await hass.services.async_call(
"python_script",
"hello",
diff --git a/tests/components/qingping/test_binary_sensor.py b/tests/components/qingping/test_binary_sensor.py
index b05a213ef5c..adf7686b20e 100644
--- a/tests/components/qingping/test_binary_sensor.py
+++ b/tests/components/qingping/test_binary_sensor.py
@@ -73,9 +73,12 @@ async def test_binary_sensor_restore_state(hass: HomeAssistant) -> None:
# Fastforward time without BLE advertisements
monotonic_now = start_monotonic + FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 1
- with patch_bluetooth_time(
- monotonic_now,
- ), patch_all_discovered_devices([]):
+ with (
+ patch_bluetooth_time(
+ monotonic_now,
+ ),
+ patch_all_discovered_devices([]),
+ ):
async_fire_time_changed(
hass,
dt_util.utcnow()
diff --git a/tests/components/qingping/test_sensor.py b/tests/components/qingping/test_sensor.py
index 135eaf296ea..160841d9ff5 100644
--- a/tests/components/qingping/test_sensor.py
+++ b/tests/components/qingping/test_sensor.py
@@ -83,9 +83,12 @@ async def test_binary_sensor_restore_state(hass: HomeAssistant) -> None:
# Fastforward time without BLE advertisements
monotonic_now = start_monotonic + FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 1
- with patch_bluetooth_time(
- monotonic_now,
- ), patch_all_discovered_devices([]):
+ with (
+ patch_bluetooth_time(
+ monotonic_now,
+ ),
+ patch_all_discovered_devices([]),
+ ):
async_fire_time_changed(
hass,
dt_util.utcnow()
diff --git a/tests/components/qld_bushfire/test_geo_location.py b/tests/components/qld_bushfire/test_geo_location.py
index 997d2f96aab..522c5fabe90 100644
--- a/tests/components/qld_bushfire/test_geo_location.py
+++ b/tests/components/qld_bushfire/test_geo_location.py
@@ -199,10 +199,13 @@ async def test_setup_with_custom_location(hass: HomeAssistant) -> None:
"1234", "Title 1", 20.5, (38.1, -3.1), category="Category 1"
)
- with patch(
- "georss_qld_bushfire_alert_client.feed_manager.QldBushfireAlertFeed",
- wraps=QldBushfireAlertFeed,
- ) as mock_feed, patch("georss_client.feed.GeoRssFeed.update") as mock_feed_update:
+ with (
+ patch(
+ "georss_qld_bushfire_alert_client.feed_manager.QldBushfireAlertFeed",
+ wraps=QldBushfireAlertFeed,
+ ) as mock_feed,
+ patch("georss_client.feed.GeoRssFeed.update") as mock_feed_update,
+ ):
mock_feed_update.return_value = "OK", [mock_entry_1]
with assert_setup_component(1, geo_location.DOMAIN):
diff --git a/tests/components/qnap_qsw/test_button.py b/tests/components/qnap_qsw/test_button.py
index 27b5fcb075d..01a1951791c 100644
--- a/tests/components/qnap_qsw/test_button.py
+++ b/tests/components/qnap_qsw/test_button.py
@@ -18,13 +18,16 @@ async def test_qnap_buttons(hass: HomeAssistant) -> None:
assert state
assert state.state == STATE_UNKNOWN
- with patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_users_verification",
- return_value=USERS_VERIFICATION_MOCK,
- ) as mock_users_verification, patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.post_system_command",
- return_value=SYSTEM_COMMAND_MOCK,
- ) as mock_post_system_command:
+ with (
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_users_verification",
+ return_value=USERS_VERIFICATION_MOCK,
+ ) as mock_users_verification,
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.post_system_command",
+ return_value=SYSTEM_COMMAND_MOCK,
+ ) as mock_post_system_command,
+ ):
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
diff --git a/tests/components/qnap_qsw/test_config_flow.py b/tests/components/qnap_qsw/test_config_flow.py
index 57f6094c850..26a6581b207 100644
--- a/tests/components/qnap_qsw/test_config_flow.py
+++ b/tests/components/qnap_qsw/test_config_flow.py
@@ -31,18 +31,23 @@ TEST_USERNAME = "test-username"
async def test_form(hass: HomeAssistant) -> None:
"""Test that the form is served with valid input."""
- with patch(
- "homeassistant.components.qnap_qsw.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_live",
- return_value=LIVE_MOCK,
- ), patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_system_board",
- return_value=SYSTEM_BOARD_MOCK,
- ), patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.post_users_login",
- return_value=USERS_LOGIN_MOCK,
+ with (
+ patch(
+ "homeassistant.components.qnap_qsw.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_live",
+ return_value=LIVE_MOCK,
+ ),
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_system_board",
+ return_value=SYSTEM_BOARD_MOCK,
+ ),
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.post_users_login",
+ return_value=USERS_LOGIN_MOCK,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
@@ -162,18 +167,23 @@ async def test_dhcp_flow(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "discovered_connection"
- with patch(
- "homeassistant.components.qnap_qsw.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_live",
- return_value=LIVE_MOCK,
- ), patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_system_board",
- return_value=SYSTEM_BOARD_MOCK,
- ), patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.post_users_login",
- return_value=USERS_LOGIN_MOCK,
+ with (
+ patch(
+ "homeassistant.components.qnap_qsw.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_live",
+ return_value=LIVE_MOCK,
+ ),
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_system_board",
+ return_value=SYSTEM_BOARD_MOCK,
+ ),
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.post_users_login",
+ return_value=USERS_LOGIN_MOCK,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/qnap_qsw/test_coordinator.py b/tests/components/qnap_qsw/test_coordinator.py
index 893a86b262d..388bab635c8 100644
--- a/tests/components/qnap_qsw/test_coordinator.py
+++ b/tests/components/qnap_qsw/test_coordinator.py
@@ -39,40 +39,52 @@ async def test_coordinator_client_connector_error(
entry = MockConfigEntry(domain=DOMAIN, data=CONFIG)
entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_firmware_condition",
- return_value=FIRMWARE_CONDITION_MOCK,
- ) as mock_firmware_condition, patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_firmware_info",
- return_value=FIRMWARE_INFO_MOCK,
- ) as mock_firmware_info, patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_firmware_update_check",
- return_value=FIRMWARE_UPDATE_CHECK_MOCK,
- ) as mock_firmware_update_check, patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_lacp_info",
- return_value=LACP_INFO_MOCK,
- ) as mock_lacp_info, patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_ports_statistics",
- return_value=PORTS_STATISTICS_MOCK,
- ) as mock_ports_statistics, patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_ports_status",
- return_value=PORTS_STATUS_MOCK,
- ) as mock_ports_status, patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_system_board",
- return_value=SYSTEM_BOARD_MOCK,
- ) as mock_system_board, patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_system_sensor",
- return_value=SYSTEM_SENSOR_MOCK,
- ) as mock_system_sensor, patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_system_time",
- return_value=SYSTEM_TIME_MOCK,
- ) as mock_system_time, patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_users_verification",
- return_value=USERS_VERIFICATION_MOCK,
- ) as mock_users_verification, patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.post_users_login",
- return_value=USERS_LOGIN_MOCK,
- ) as mock_users_login:
+ with (
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_firmware_condition",
+ return_value=FIRMWARE_CONDITION_MOCK,
+ ) as mock_firmware_condition,
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_firmware_info",
+ return_value=FIRMWARE_INFO_MOCK,
+ ) as mock_firmware_info,
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_firmware_update_check",
+ return_value=FIRMWARE_UPDATE_CHECK_MOCK,
+ ) as mock_firmware_update_check,
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_lacp_info",
+ return_value=LACP_INFO_MOCK,
+ ) as mock_lacp_info,
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_ports_statistics",
+ return_value=PORTS_STATISTICS_MOCK,
+ ) as mock_ports_statistics,
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_ports_status",
+ return_value=PORTS_STATUS_MOCK,
+ ) as mock_ports_status,
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_system_board",
+ return_value=SYSTEM_BOARD_MOCK,
+ ) as mock_system_board,
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_system_sensor",
+ return_value=SYSTEM_SENSOR_MOCK,
+ ) as mock_system_sensor,
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_system_time",
+ return_value=SYSTEM_TIME_MOCK,
+ ) as mock_system_time,
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_users_verification",
+ return_value=USERS_VERIFICATION_MOCK,
+ ) as mock_users_verification,
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.post_users_login",
+ return_value=USERS_LOGIN_MOCK,
+ ) as mock_users_login,
+ ):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/qnap_qsw/test_init.py b/tests/components/qnap_qsw/test_init.py
index fedfdd26543..9b2d10f1ed0 100644
--- a/tests/components/qnap_qsw/test_init.py
+++ b/tests/components/qnap_qsw/test_init.py
@@ -21,15 +21,19 @@ async def test_firmware_check_error(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.check_firmware",
- side_effect=APIError,
- ), patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.validate",
- return_value=None,
- ), patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.update",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.check_firmware",
+ side_effect=APIError,
+ ),
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.validate",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.update",
+ return_value=None,
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -44,15 +48,19 @@ async def test_unload_entry(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.check_firmware",
- return_value=None,
- ), patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.validate",
- return_value=None,
- ), patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.update",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.check_firmware",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.validate",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.update",
+ return_value=None,
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/qnap_qsw/test_update.py b/tests/components/qnap_qsw/test_update.py
index f6eb9705912..df7b4b9af6b 100644
--- a/tests/components/qnap_qsw/test_update.py
+++ b/tests/components/qnap_qsw/test_update.py
@@ -47,16 +47,20 @@ async def test_qnap_qsw_update(hass: HomeAssistant) -> None:
)
assert update.attributes[ATTR_IN_PROGRESS] is False
- with patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_firmware_update_check",
- return_value=FIRMWARE_UPDATE_CHECK_MOCK,
- ) as mock_firmware_update_check, patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_users_verification",
- return_value=USERS_VERIFICATION_MOCK,
- ) as mock_users_verification, patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.post_firmware_update_live",
- return_value=FIRMWARE_UPDATE_LIVE_MOCK,
- ) as mock_firmware_update_live:
+ with (
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_firmware_update_check",
+ return_value=FIRMWARE_UPDATE_CHECK_MOCK,
+ ) as mock_firmware_update_check,
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_users_verification",
+ return_value=USERS_VERIFICATION_MOCK,
+ ) as mock_users_verification,
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.post_firmware_update_live",
+ return_value=FIRMWARE_UPDATE_LIVE_MOCK,
+ ) as mock_firmware_update_live,
+ ):
await hass.services.async_call(
UPDATE_DOMAIN,
SERVICE_INSTALL,
diff --git a/tests/components/qnap_qsw/util.py b/tests/components/qnap_qsw/util.py
index b0dd5d5bf60..63238bb30a1 100644
--- a/tests/components/qnap_qsw/util.py
+++ b/tests/components/qnap_qsw/util.py
@@ -503,39 +503,51 @@ async def async_init_integration(
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_firmware_condition",
- return_value=FIRMWARE_CONDITION_MOCK,
- ), patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_firmware_info",
- return_value=FIRMWARE_INFO_MOCK,
- ), patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_firmware_update_check",
- return_value=FIRMWARE_UPDATE_CHECK_MOCK,
- ), patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_lacp_info",
- return_value=LACP_INFO_MOCK,
- ), patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_ports_statistics",
- return_value=PORTS_STATISTICS_MOCK,
- ), patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_ports_status",
- return_value=PORTS_STATUS_MOCK,
- ), patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_system_board",
- return_value=SYSTEM_BOARD_MOCK,
- ), patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_system_sensor",
- return_value=SYSTEM_SENSOR_MOCK,
- ), patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_system_time",
- return_value=SYSTEM_TIME_MOCK,
- ), patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.get_users_verification",
- return_value=USERS_VERIFICATION_MOCK,
- ), patch(
- "homeassistant.components.qnap_qsw.QnapQswApi.post_users_login",
- return_value=USERS_LOGIN_MOCK,
+ with (
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_firmware_condition",
+ return_value=FIRMWARE_CONDITION_MOCK,
+ ),
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_firmware_info",
+ return_value=FIRMWARE_INFO_MOCK,
+ ),
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_firmware_update_check",
+ return_value=FIRMWARE_UPDATE_CHECK_MOCK,
+ ),
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_lacp_info",
+ return_value=LACP_INFO_MOCK,
+ ),
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_ports_statistics",
+ return_value=PORTS_STATISTICS_MOCK,
+ ),
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_ports_status",
+ return_value=PORTS_STATUS_MOCK,
+ ),
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_system_board",
+ return_value=SYSTEM_BOARD_MOCK,
+ ),
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_system_sensor",
+ return_value=SYSTEM_SENSOR_MOCK,
+ ),
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_system_time",
+ return_value=SYSTEM_TIME_MOCK,
+ ),
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.get_users_verification",
+ return_value=USERS_VERIFICATION_MOCK,
+ ),
+ patch(
+ "homeassistant.components.qnap_qsw.QnapQswApi.post_users_login",
+ return_value=USERS_LOGIN_MOCK,
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/rabbitair/test_config_flow.py b/tests/components/rabbitair/test_config_flow.py
index 5f2295fd7f9..4b5867b441b 100644
--- a/tests/components/rabbitair/test_config_flow.py
+++ b/tests/components/rabbitair/test_config_flow.py
@@ -45,8 +45,9 @@ def use_mocked_zeroconf(mock_async_zeroconf):
@pytest.fixture
def rabbitair_connect() -> Generator[None, None, None]:
"""Mock connection."""
- with patch("rabbitair.UdpClient.get_info", return_value=get_mock_info()), patch(
- "rabbitair.UdpClient.get_state", return_value=get_mock_state()
+ with (
+ patch("rabbitair.UdpClient.get_info", return_value=get_mock_info()),
+ patch("rabbitair.UdpClient.get_state", return_value=get_mock_state()),
):
yield
diff --git a/tests/components/rachio/test_config_flow.py b/tests/components/rachio/test_config_flow.py
index a5a4def94bb..b7325349746 100644
--- a/tests/components/rachio/test_config_flow.py
+++ b/tests/components/rachio/test_config_flow.py
@@ -39,12 +39,16 @@ async def test_form(hass: HomeAssistant) -> None:
info=({"status": 200}, {"id": "myid"}),
)
- with patch(
- "homeassistant.components.rachio.config_flow.Rachio", return_value=rachio_mock
- ), patch(
- "homeassistant.components.rachio.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.rachio.config_flow.Rachio",
+ return_value=rachio_mock,
+ ),
+ patch(
+ "homeassistant.components.rachio.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
diff --git a/tests/components/radiotherm/test_config_flow.py b/tests/components/radiotherm/test_config_flow.py
index 8da7c850aa5..7729dfb86b7 100644
--- a/tests/components/radiotherm/test_config_flow.py
+++ b/tests/components/radiotherm/test_config_flow.py
@@ -33,13 +33,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.radiotherm.data.radiotherm.get_thermostat",
- return_value=_mock_radiotherm(),
- ), patch(
- "homeassistant.components.radiotherm.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.radiotherm.data.radiotherm.get_thermostat",
+ return_value=_mock_radiotherm(),
+ ),
+ patch(
+ "homeassistant.components.radiotherm.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -209,12 +212,15 @@ async def test_user_unique_id_already_exists(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.radiotherm.data.radiotherm.get_thermostat",
- return_value=_mock_radiotherm(),
- ), patch(
- "homeassistant.components.radiotherm.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.radiotherm.data.radiotherm.get_thermostat",
+ return_value=_mock_radiotherm(),
+ ),
+ patch(
+ "homeassistant.components.radiotherm.async_setup_entry",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/rainbird/conftest.py b/tests/components/rainbird/conftest.py
index 53df24264df..10101986007 100644
--- a/tests/components/rainbird/conftest.py
+++ b/tests/components/rainbird/conftest.py
@@ -171,12 +171,15 @@ def aioclient_mock(hass: HomeAssistant) -> Generator[AiohttpClientMocker, None,
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_CLOSE, close_session)
return session
- with patch(
- "homeassistant.components.rainbird.async_create_clientsession",
- side_effect=create_session,
- ), patch(
- "homeassistant.components.rainbird.config_flow.async_create_clientsession",
- side_effect=create_session,
+ with (
+ patch(
+ "homeassistant.components.rainbird.async_create_clientsession",
+ side_effect=create_session,
+ ),
+ patch(
+ "homeassistant.components.rainbird.config_flow.async_create_clientsession",
+ side_effect=create_session,
+ ),
):
yield mocker
diff --git a/tests/components/rainforest_eagle/test_config_flow.py b/tests/components/rainforest_eagle/test_config_flow.py
index 4eaf26cb767..191a7a4793e 100644
--- a/tests/components/rainforest_eagle/test_config_flow.py
+++ b/tests/components/rainforest_eagle/test_config_flow.py
@@ -25,13 +25,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with patch(
- "homeassistant.components.rainforest_eagle.data.async_get_type",
- return_value=(TYPE_EAGLE_200, "mock-hw"),
- ), patch(
- "homeassistant.components.rainforest_eagle.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.rainforest_eagle.data.async_get_type",
+ return_value=(TYPE_EAGLE_200, "mock-hw"),
+ ),
+ patch(
+ "homeassistant.components.rainforest_eagle.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
diff --git a/tests/components/rainmachine/conftest.py b/tests/components/rainmachine/conftest.py
index c3724334776..9b0f8f0442a 100644
--- a/tests/components/rainmachine/conftest.py
+++ b/tests/components/rainmachine/conftest.py
@@ -130,13 +130,16 @@ def data_zones_fixture():
@pytest.fixture(name="setup_rainmachine")
async def setup_rainmachine_fixture(hass, client, config):
"""Define a fixture to set up RainMachine."""
- with patch(
- "homeassistant.components.rainmachine.Client", return_value=client
- ), patch(
- "homeassistant.components.rainmachine.config_flow.Client", return_value=client
- ), patch(
- "homeassistant.components.rainmachine.PLATFORMS",
- [],
+ with (
+ patch("homeassistant.components.rainmachine.Client", return_value=client),
+ patch(
+ "homeassistant.components.rainmachine.config_flow.Client",
+ return_value=client,
+ ),
+ patch(
+ "homeassistant.components.rainmachine.PLATFORMS",
+ [],
+ ),
):
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
diff --git a/tests/components/rainmachine/test_config_flow.py b/tests/components/rainmachine/test_config_flow.py
index 8b8104fe7a7..1c065a8f7ce 100644
--- a/tests/components/rainmachine/test_config_flow.py
+++ b/tests/components/rainmachine/test_config_flow.py
@@ -82,10 +82,14 @@ async def test_migrate_1_2(
assert entity_entry.entity_id == entity_id
assert entity_entry.unique_id == old_unique_id
- with patch(
- "homeassistant.components.rainmachine.async_setup_entry", return_value=True
- ), patch(
- "homeassistant.components.rainmachine.config_flow.Client", return_value=client
+ with (
+ patch(
+ "homeassistant.components.rainmachine.async_setup_entry", return_value=True
+ ),
+ patch(
+ "homeassistant.components.rainmachine.config_flow.Client",
+ return_value=client,
+ ),
):
await setup.async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
@@ -235,10 +239,14 @@ async def test_step_homekit_zeroconf_new_controller_when_some_exist(
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.rainmachine.async_setup_entry", return_value=True
- ), patch(
- "homeassistant.components.rainmachine.config_flow.Client", return_value=client
+ with (
+ patch(
+ "homeassistant.components.rainmachine.async_setup_entry", return_value=True
+ ),
+ patch(
+ "homeassistant.components.rainmachine.config_flow.Client",
+ return_value=client,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/raspberry_pi/test_init.py b/tests/components/raspberry_pi/test_init.py
index ebe04ed8384..80b5eedf2af 100644
--- a/tests/components/raspberry_pi/test_init.py
+++ b/tests/components/raspberry_pi/test_init.py
@@ -37,11 +37,12 @@ async def test_setup_entry(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
assert not hass.config_entries.async_entries("rpi_power")
- with patch(
- "homeassistant.components.raspberry_pi.get_os_info",
- return_value={"board": "rpi"},
- ) as mock_get_os_info, patch(
- "homeassistant.components.rpi_power.config_flow.new_under_voltage"
+ with (
+ patch(
+ "homeassistant.components.raspberry_pi.get_os_info",
+ return_value={"board": "rpi"},
+ ) as mock_get_os_info,
+ patch("homeassistant.components.rpi_power.config_flow.new_under_voltage"),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/recollect_waste/conftest.py b/tests/components/recollect_waste/conftest.py
index 746a2203992..360dd8aac98 100644
--- a/tests/components/recollect_waste/conftest.py
+++ b/tests/components/recollect_waste/conftest.py
@@ -56,12 +56,15 @@ def pickup_events_fixture():
@pytest.fixture(name="mock_aiorecollect")
async def mock_aiorecollect_fixture(client):
"""Define a fixture to patch aiorecollect."""
- with patch(
- "homeassistant.components.recollect_waste.Client",
- return_value=client,
- ), patch(
- "homeassistant.components.recollect_waste.config_flow.Client",
- return_value=client,
+ with (
+ patch(
+ "homeassistant.components.recollect_waste.Client",
+ return_value=client,
+ ),
+ patch(
+ "homeassistant.components.recollect_waste.config_flow.Client",
+ return_value=client,
+ ),
):
yield
diff --git a/tests/components/recorder/auto_repairs/events/test_schema.py b/tests/components/recorder/auto_repairs/events/test_schema.py
index a09da8a688a..5713e287222 100644
--- a/tests/components/recorder/auto_repairs/events/test_schema.py
+++ b/tests/components/recorder/auto_repairs/events/test_schema.py
@@ -23,14 +23,18 @@ async def test_validate_db_schema_fix_float_issue(
Note: The test uses SQLite, the purpose is only to exercise the code.
"""
- with patch(
- "homeassistant.components.recorder.core.Recorder.dialect_name", db_engine
- ), patch(
- "homeassistant.components.recorder.auto_repairs.schema._validate_db_schema_precision",
- return_value={"events.double precision"},
- ), patch(
- "homeassistant.components.recorder.migration._modify_columns"
- ) as modify_columns_mock:
+ with (
+ patch(
+ "homeassistant.components.recorder.core.Recorder.dialect_name", db_engine
+ ),
+ patch(
+ "homeassistant.components.recorder.auto_repairs.schema._validate_db_schema_precision",
+ return_value={"events.double precision"},
+ ),
+ patch(
+ "homeassistant.components.recorder.migration._modify_columns"
+ ) as modify_columns_mock,
+ ):
await async_setup_recorder_instance(hass)
await async_wait_recording_done(hass)
@@ -55,11 +59,12 @@ async def test_validate_db_schema_fix_utf8_issue_event_data(
Note: The test uses SQLite, the purpose is only to exercise the code.
"""
- with patch(
- "homeassistant.components.recorder.core.Recorder.dialect_name", "mysql"
- ), patch(
- "homeassistant.components.recorder.auto_repairs.schema._validate_table_schema_supports_utf8",
- return_value={"event_data.4-byte UTF-8"},
+ with (
+ patch("homeassistant.components.recorder.core.Recorder.dialect_name", "mysql"),
+ patch(
+ "homeassistant.components.recorder.auto_repairs.schema._validate_table_schema_supports_utf8",
+ return_value={"event_data.4-byte UTF-8"},
+ ),
):
await async_setup_recorder_instance(hass)
await async_wait_recording_done(hass)
@@ -85,11 +90,12 @@ async def test_validate_db_schema_fix_collation_issue(
Note: The test uses SQLite, the purpose is only to exercise the code.
"""
- with patch(
- "homeassistant.components.recorder.core.Recorder.dialect_name", "mysql"
- ), patch(
- "homeassistant.components.recorder.auto_repairs.schema._validate_table_schema_has_correct_collation",
- return_value={"events.utf8mb4_unicode_ci"},
+ with (
+ patch("homeassistant.components.recorder.core.Recorder.dialect_name", "mysql"),
+ patch(
+ "homeassistant.components.recorder.auto_repairs.schema._validate_table_schema_has_correct_collation",
+ return_value={"events.utf8mb4_unicode_ci"},
+ ),
):
await async_setup_recorder_instance(hass)
await async_wait_recording_done(hass)
diff --git a/tests/components/recorder/auto_repairs/states/test_schema.py b/tests/components/recorder/auto_repairs/states/test_schema.py
index 75d968f19d1..c0a9e930966 100644
--- a/tests/components/recorder/auto_repairs/states/test_schema.py
+++ b/tests/components/recorder/auto_repairs/states/test_schema.py
@@ -23,14 +23,18 @@ async def test_validate_db_schema_fix_float_issue(
Note: The test uses SQLite, the purpose is only to exercise the code.
"""
- with patch(
- "homeassistant.components.recorder.core.Recorder.dialect_name", db_engine
- ), patch(
- "homeassistant.components.recorder.auto_repairs.schema._validate_db_schema_precision",
- return_value={"states.double precision"},
- ), patch(
- "homeassistant.components.recorder.migration._modify_columns"
- ) as modify_columns_mock:
+ with (
+ patch(
+ "homeassistant.components.recorder.core.Recorder.dialect_name", db_engine
+ ),
+ patch(
+ "homeassistant.components.recorder.auto_repairs.schema._validate_db_schema_precision",
+ return_value={"states.double precision"},
+ ),
+ patch(
+ "homeassistant.components.recorder.migration._modify_columns"
+ ) as modify_columns_mock,
+ ):
await async_setup_recorder_instance(hass)
await async_wait_recording_done(hass)
@@ -56,11 +60,12 @@ async def test_validate_db_schema_fix_utf8_issue_states(
Note: The test uses SQLite, the purpose is only to exercise the code.
"""
- with patch(
- "homeassistant.components.recorder.core.Recorder.dialect_name", "mysql"
- ), patch(
- "homeassistant.components.recorder.auto_repairs.schema._validate_table_schema_supports_utf8",
- return_value={"states.4-byte UTF-8"},
+ with (
+ patch("homeassistant.components.recorder.core.Recorder.dialect_name", "mysql"),
+ patch(
+ "homeassistant.components.recorder.auto_repairs.schema._validate_table_schema_supports_utf8",
+ return_value={"states.4-byte UTF-8"},
+ ),
):
await async_setup_recorder_instance(hass)
await async_wait_recording_done(hass)
@@ -85,11 +90,12 @@ async def test_validate_db_schema_fix_utf8_issue_state_attributes(
Note: The test uses SQLite, the purpose is only to exercise the code.
"""
- with patch(
- "homeassistant.components.recorder.core.Recorder.dialect_name", "mysql"
- ), patch(
- "homeassistant.components.recorder.auto_repairs.schema._validate_table_schema_supports_utf8",
- return_value={"state_attributes.4-byte UTF-8"},
+ with (
+ patch("homeassistant.components.recorder.core.Recorder.dialect_name", "mysql"),
+ patch(
+ "homeassistant.components.recorder.auto_repairs.schema._validate_table_schema_supports_utf8",
+ return_value={"state_attributes.4-byte UTF-8"},
+ ),
):
await async_setup_recorder_instance(hass)
await async_wait_recording_done(hass)
@@ -115,11 +121,12 @@ async def test_validate_db_schema_fix_collation_issue(
Note: The test uses SQLite, the purpose is only to exercise the code.
"""
- with patch(
- "homeassistant.components.recorder.core.Recorder.dialect_name", "mysql"
- ), patch(
- "homeassistant.components.recorder.auto_repairs.schema._validate_table_schema_has_correct_collation",
- return_value={"states.utf8mb4_unicode_ci"},
+ with (
+ patch("homeassistant.components.recorder.core.Recorder.dialect_name", "mysql"),
+ patch(
+ "homeassistant.components.recorder.auto_repairs.schema._validate_table_schema_has_correct_collation",
+ return_value={"states.utf8mb4_unicode_ci"},
+ ),
):
await async_setup_recorder_instance(hass)
await async_wait_recording_done(hass)
diff --git a/tests/components/recorder/auto_repairs/statistics/test_duplicates.py b/tests/components/recorder/auto_repairs/statistics/test_duplicates.py
index 5dea61f0795..2a1c3c5d209 100644
--- a/tests/components/recorder/auto_repairs/statistics/test_duplicates.py
+++ b/tests/components/recorder/auto_repairs/statistics/test_duplicates.py
@@ -78,11 +78,12 @@ def test_duplicate_statistics_handle_integrity_error(
}
]
- with patch.object(
- statistics, "_statistics_exists", return_value=False
- ), patch.object(
- statistics, "_insert_statistics", wraps=statistics._insert_statistics
- ) as insert_statistics_mock:
+ with (
+ patch.object(statistics, "_statistics_exists", return_value=False),
+ patch.object(
+ statistics, "_insert_statistics", wraps=statistics._insert_statistics
+ ) as insert_statistics_mock,
+ ):
async_add_external_statistics(
hass, external_energy_metadata_1, external_energy_statistics_1
)
@@ -164,11 +165,17 @@ def test_delete_metadata_duplicates(
}
# Create some duplicated statistics_meta with schema version 28
- with patch.object(recorder, "db_schema", old_db_schema), patch.object(
- recorder.migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION
- ), patch(
- "homeassistant.components.recorder.core.create_engine", new=_create_engine_28
- ), get_test_home_assistant() as hass:
+ with (
+ patch.object(recorder, "db_schema", old_db_schema),
+ patch.object(
+ recorder.migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION
+ ),
+ patch(
+ "homeassistant.components.recorder.core.create_engine",
+ new=_create_engine_28,
+ ),
+ get_test_home_assistant() as hass,
+ ):
recorder_helper.async_initialize_recorder(hass)
setup_component(hass, "recorder", {"recorder": {"db_url": dburl}})
wait_recording_done(hass)
@@ -256,11 +263,17 @@ def test_delete_metadata_duplicates_many(
}
# Create some duplicated statistics with schema version 28
- with patch.object(recorder, "db_schema", old_db_schema), patch.object(
- recorder.migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION
- ), patch(
- "homeassistant.components.recorder.core.create_engine", new=_create_engine_28
- ), get_test_home_assistant() as hass:
+ with (
+ patch.object(recorder, "db_schema", old_db_schema),
+ patch.object(
+ recorder.migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION
+ ),
+ patch(
+ "homeassistant.components.recorder.core.create_engine",
+ new=_create_engine_28,
+ ),
+ get_test_home_assistant() as hass,
+ ):
recorder_helper.async_initialize_recorder(hass)
setup_component(hass, "recorder", {"recorder": {"db_url": dburl}})
wait_recording_done(hass)
diff --git a/tests/components/recorder/auto_repairs/statistics/test_schema.py b/tests/components/recorder/auto_repairs/statistics/test_schema.py
index c5abb013d99..0badceee0d2 100644
--- a/tests/components/recorder/auto_repairs/statistics/test_schema.py
+++ b/tests/components/recorder/auto_repairs/statistics/test_schema.py
@@ -21,11 +21,12 @@ async def test_validate_db_schema_fix_utf8_issue(
Note: The test uses SQLite, the purpose is only to exercise the code.
"""
- with patch(
- "homeassistant.components.recorder.core.Recorder.dialect_name", "mysql"
- ), patch(
- "homeassistant.components.recorder.auto_repairs.schema._validate_table_schema_supports_utf8",
- return_value={"statistics_meta.4-byte UTF-8"},
+ with (
+ patch("homeassistant.components.recorder.core.Recorder.dialect_name", "mysql"),
+ patch(
+ "homeassistant.components.recorder.auto_repairs.schema._validate_table_schema_supports_utf8",
+ return_value={"statistics_meta.4-byte UTF-8"},
+ ),
):
await async_setup_recorder_instance(hass)
await async_wait_recording_done(hass)
@@ -55,14 +56,18 @@ async def test_validate_db_schema_fix_float_issue(
Note: The test uses SQLite, the purpose is only to exercise the code.
"""
- with patch(
- "homeassistant.components.recorder.core.Recorder.dialect_name", db_engine
- ), patch(
- "homeassistant.components.recorder.auto_repairs.schema._validate_db_schema_precision",
- return_value={f"{table}.double precision"},
- ), patch(
- "homeassistant.components.recorder.migration._modify_columns"
- ) as modify_columns_mock:
+ with (
+ patch(
+ "homeassistant.components.recorder.core.Recorder.dialect_name", db_engine
+ ),
+ patch(
+ "homeassistant.components.recorder.auto_repairs.schema._validate_db_schema_precision",
+ return_value={f"{table}.double precision"},
+ ),
+ patch(
+ "homeassistant.components.recorder.migration._modify_columns"
+ ) as modify_columns_mock,
+ ):
await async_setup_recorder_instance(hass)
await async_wait_recording_done(hass)
@@ -94,11 +99,12 @@ async def test_validate_db_schema_fix_collation_issue(
Note: The test uses SQLite, the purpose is only to exercise the code.
"""
- with patch(
- "homeassistant.components.recorder.core.Recorder.dialect_name", "mysql"
- ), patch(
- "homeassistant.components.recorder.auto_repairs.schema._validate_table_schema_has_correct_collation",
- return_value={"statistics.utf8mb4_unicode_ci"},
+ with (
+ patch("homeassistant.components.recorder.core.Recorder.dialect_name", "mysql"),
+ patch(
+ "homeassistant.components.recorder.auto_repairs.schema._validate_table_schema_has_correct_collation",
+ return_value={"statistics.utf8mb4_unicode_ci"},
+ ),
):
await async_setup_recorder_instance(hass)
await async_wait_recording_done(hass)
diff --git a/tests/components/recorder/common.py b/tests/components/recorder/common.py
index 816378c2f2e..1c44511678e 100644
--- a/tests/components/recorder/common.py
+++ b/tests/components/recorder/common.py
@@ -415,19 +415,24 @@ def old_db_schema(schema_version_postfix: str) -> Iterator[None]:
importlib.import_module(schema_module)
old_db_schema = sys.modules[schema_module]
- with patch.object(recorder, "db_schema", old_db_schema), patch.object(
- recorder.migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION
- ), patch.object(core, "StatesMeta", old_db_schema.StatesMeta), patch.object(
- core, "EventTypes", old_db_schema.EventTypes
- ), patch.object(core, "EventData", old_db_schema.EventData), patch.object(
- core, "States", old_db_schema.States
- ), patch.object(core, "Events", old_db_schema.Events), patch.object(
- core, "StateAttributes", old_db_schema.StateAttributes
- ), patch.object(migration.EntityIDMigration, "task", core.RecorderTask), patch(
- CREATE_ENGINE_TARGET,
- new=partial(
- create_engine_test_for_schema_version_postfix,
- schema_version_postfix=schema_version_postfix,
+ with (
+ patch.object(recorder, "db_schema", old_db_schema),
+ patch.object(
+ recorder.migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION
+ ),
+ patch.object(core, "StatesMeta", old_db_schema.StatesMeta),
+ patch.object(core, "EventTypes", old_db_schema.EventTypes),
+ patch.object(core, "EventData", old_db_schema.EventData),
+ patch.object(core, "States", old_db_schema.States),
+ patch.object(core, "Events", old_db_schema.Events),
+ patch.object(core, "StateAttributes", old_db_schema.StateAttributes),
+ patch.object(migration.EntityIDMigration, "task", core.RecorderTask),
+ patch(
+ CREATE_ENGINE_TARGET,
+ new=partial(
+ create_engine_test_for_schema_version_postfix,
+ schema_version_postfix=schema_version_postfix,
+ ),
),
):
yield
diff --git a/tests/components/recorder/db_schema_22.py b/tests/components/recorder/db_schema_22.py
index 329e5d262bc..0d336c96403 100644
--- a/tests/components/recorder/db_schema_22.py
+++ b/tests/components/recorder/db_schema_22.py
@@ -439,13 +439,11 @@ class StatisticsRuns(Base): # type: ignore
@overload
-def process_timestamp(ts: None) -> None:
- ...
+def process_timestamp(ts: None) -> None: ...
@overload
-def process_timestamp(ts: datetime) -> datetime:
- ...
+def process_timestamp(ts: datetime) -> datetime: ...
def process_timestamp(ts: datetime | None) -> datetime | None:
@@ -459,13 +457,11 @@ def process_timestamp(ts: datetime | None) -> datetime | None:
@overload
-def process_timestamp_to_utc_isoformat(ts: None) -> None:
- ...
+def process_timestamp_to_utc_isoformat(ts: None) -> None: ...
@overload
-def process_timestamp_to_utc_isoformat(ts: datetime) -> str:
- ...
+def process_timestamp_to_utc_isoformat(ts: datetime) -> str: ...
def process_timestamp_to_utc_isoformat(ts: datetime | None) -> str | None:
diff --git a/tests/components/recorder/db_schema_23.py b/tests/components/recorder/db_schema_23.py
index c145767a838..d4b6e8b0a73 100644
--- a/tests/components/recorder/db_schema_23.py
+++ b/tests/components/recorder/db_schema_23.py
@@ -429,13 +429,11 @@ class StatisticsRuns(Base): # type: ignore
@overload
-def process_timestamp(ts: None) -> None:
- ...
+def process_timestamp(ts: None) -> None: ...
@overload
-def process_timestamp(ts: datetime) -> datetime:
- ...
+def process_timestamp(ts: datetime) -> datetime: ...
def process_timestamp(ts: datetime | None) -> datetime | None:
@@ -449,13 +447,11 @@ def process_timestamp(ts: datetime | None) -> datetime | None:
@overload
-def process_timestamp_to_utc_isoformat(ts: None) -> None:
- ...
+def process_timestamp_to_utc_isoformat(ts: None) -> None: ...
@overload
-def process_timestamp_to_utc_isoformat(ts: datetime) -> str:
- ...
+def process_timestamp_to_utc_isoformat(ts: datetime) -> str: ...
def process_timestamp_to_utc_isoformat(ts: datetime | None) -> str | None:
diff --git a/tests/components/recorder/db_schema_23_with_newer_columns.py b/tests/components/recorder/db_schema_23_with_newer_columns.py
index 92c3f7a75ff..6893a7257f4 100644
--- a/tests/components/recorder/db_schema_23_with_newer_columns.py
+++ b/tests/components/recorder/db_schema_23_with_newer_columns.py
@@ -553,13 +553,11 @@ class StatisticsRuns(Base): # type: ignore
@overload
-def process_timestamp(ts: None) -> None:
- ...
+def process_timestamp(ts: None) -> None: ...
@overload
-def process_timestamp(ts: datetime) -> datetime:
- ...
+def process_timestamp(ts: datetime) -> datetime: ...
def process_timestamp(ts: datetime | None) -> datetime | None:
@@ -573,13 +571,11 @@ def process_timestamp(ts: datetime | None) -> datetime | None:
@overload
-def process_timestamp_to_utc_isoformat(ts: None) -> None:
- ...
+def process_timestamp_to_utc_isoformat(ts: None) -> None: ...
@overload
-def process_timestamp_to_utc_isoformat(ts: datetime) -> str:
- ...
+def process_timestamp_to_utc_isoformat(ts: datetime) -> str: ...
def process_timestamp_to_utc_isoformat(ts: datetime | None) -> str | None:
diff --git a/tests/components/recorder/db_schema_25.py b/tests/components/recorder/db_schema_25.py
index 84c06a95d2e..0d763f91b67 100644
--- a/tests/components/recorder/db_schema_25.py
+++ b/tests/components/recorder/db_schema_25.py
@@ -489,13 +489,11 @@ class StatisticsRuns(Base): # type: ignore[misc,valid-type]
@overload
-def process_timestamp(ts: None) -> None:
- ...
+def process_timestamp(ts: None) -> None: ...
@overload
-def process_timestamp(ts: datetime) -> datetime:
- ...
+def process_timestamp(ts: datetime) -> datetime: ...
def process_timestamp(ts: datetime | None) -> datetime | None:
@@ -509,13 +507,11 @@ def process_timestamp(ts: datetime | None) -> datetime | None:
@overload
-def process_timestamp_to_utc_isoformat(ts: None) -> None:
- ...
+def process_timestamp_to_utc_isoformat(ts: None) -> None: ...
@overload
-def process_timestamp_to_utc_isoformat(ts: datetime) -> str:
- ...
+def process_timestamp_to_utc_isoformat(ts: datetime) -> str: ...
def process_timestamp_to_utc_isoformat(ts: datetime | None) -> str | None:
diff --git a/tests/components/recorder/db_schema_28.py b/tests/components/recorder/db_schema_28.py
index 3593ad37e59..feaf877b36f 100644
--- a/tests/components/recorder/db_schema_28.py
+++ b/tests/components/recorder/db_schema_28.py
@@ -654,13 +654,11 @@ class StatisticsRuns(Base): # type: ignore[misc,valid-type]
@overload
-def process_timestamp(ts: None) -> None:
- ...
+def process_timestamp(ts: None) -> None: ...
@overload
-def process_timestamp(ts: datetime) -> datetime:
- ...
+def process_timestamp(ts: datetime) -> datetime: ...
def process_timestamp(ts: datetime | None) -> datetime | None:
@@ -674,13 +672,11 @@ def process_timestamp(ts: datetime | None) -> datetime | None:
@overload
-def process_timestamp_to_utc_isoformat(ts: None) -> None:
- ...
+def process_timestamp_to_utc_isoformat(ts: None) -> None: ...
@overload
-def process_timestamp_to_utc_isoformat(ts: datetime) -> str:
- ...
+def process_timestamp_to_utc_isoformat(ts: datetime) -> str: ...
def process_timestamp_to_utc_isoformat(ts: datetime | None) -> str | None:
diff --git a/tests/components/recorder/db_schema_30.py b/tests/components/recorder/db_schema_30.py
index facb61a5942..0fba51d588e 100644
--- a/tests/components/recorder/db_schema_30.py
+++ b/tests/components/recorder/db_schema_30.py
@@ -738,13 +738,11 @@ OLD_STATE = aliased(States, name="old_state")
@overload
-def process_timestamp(ts: None) -> None:
- ...
+def process_timestamp(ts: None) -> None: ...
@overload
-def process_timestamp(ts: datetime) -> datetime:
- ...
+def process_timestamp(ts: datetime) -> datetime: ...
def process_timestamp(ts: datetime | None) -> datetime | None:
diff --git a/tests/components/recorder/db_schema_32.py b/tests/components/recorder/db_schema_32.py
index bd245f9013f..7def9867373 100644
--- a/tests/components/recorder/db_schema_32.py
+++ b/tests/components/recorder/db_schema_32.py
@@ -739,13 +739,11 @@ OLD_STATE = aliased(States, name="old_state")
@overload
-def process_timestamp(ts: None) -> None:
- ...
+def process_timestamp(ts: None) -> None: ...
@overload
-def process_timestamp(ts: datetime) -> datetime:
- ...
+def process_timestamp(ts: datetime) -> datetime: ...
def process_timestamp(ts: datetime | None) -> datetime | None:
diff --git a/tests/components/recorder/table_managers/test_statistics_meta.py b/tests/components/recorder/table_managers/test_statistics_meta.py
index a1dc777d80d..66edb84c3ef 100644
--- a/tests/components/recorder/table_managers/test_statistics_meta.py
+++ b/tests/components/recorder/table_managers/test_statistics_meta.py
@@ -45,8 +45,11 @@ async def test_unsafe_calls_to_statistics_meta_manager(
instance = await async_setup_recorder_instance(
hass, {recorder.CONF_COMMIT_INTERVAL: 0}
)
- with session_scope(session=instance.get_session()) as session, pytest.raises(
- RuntimeError, match="Detected unsafe call not in recorder thread"
+ with (
+ session_scope(session=instance.get_session()) as session,
+ pytest.raises(
+ RuntimeError, match="Detected unsafe call not in recorder thread"
+ ),
):
instance.statistics_meta_manager.delete(
session,
diff --git a/tests/components/recorder/test_backup.py b/tests/components/recorder/test_backup.py
index 4953504786a..d181c449bbf 100644
--- a/tests/components/recorder/test_backup.py
+++ b/tests/components/recorder/test_backup.py
@@ -23,10 +23,13 @@ async def test_async_pre_backup_with_timeout(
recorder_mock: Recorder, hass: HomeAssistant
) -> None:
"""Test pre backup with timeout."""
- with patch(
- "homeassistant.components.recorder.core.Recorder.lock_database",
- side_effect=TimeoutError(),
- ) as lock_mock, pytest.raises(TimeoutError):
+ with (
+ patch(
+ "homeassistant.components.recorder.core.Recorder.lock_database",
+ side_effect=TimeoutError(),
+ ) as lock_mock,
+ pytest.raises(TimeoutError),
+ ):
await async_pre_backup(hass)
assert lock_mock.called
@@ -35,10 +38,13 @@ async def test_async_pre_backup_with_migration(
recorder_mock: Recorder, hass: HomeAssistant
) -> None:
"""Test pre backup with migration."""
- with patch(
- "homeassistant.components.recorder.backup.async_migration_in_progress",
- return_value=True,
- ), pytest.raises(HomeAssistantError):
+ with (
+ patch(
+ "homeassistant.components.recorder.backup.async_migration_in_progress",
+ return_value=True,
+ ),
+ pytest.raises(HomeAssistantError),
+ ):
await async_pre_backup(hass)
@@ -55,9 +61,12 @@ async def test_async_post_backup_failure(
recorder_mock: Recorder, hass: HomeAssistant
) -> None:
"""Test post backup failure."""
- with patch(
- "homeassistant.components.recorder.core.Recorder.unlock_database",
- return_value=False,
- ) as unlock_mock, pytest.raises(HomeAssistantError):
+ with (
+ patch(
+ "homeassistant.components.recorder.core.Recorder.unlock_database",
+ return_value=False,
+ ) as unlock_mock,
+ pytest.raises(HomeAssistantError),
+ ):
await async_post_backup(hass)
assert unlock_mock.called
diff --git a/tests/components/recorder/test_history_db_schema_30.py b/tests/components/recorder/test_history_db_schema_30.py
index ed4418deb22..cbe4c3ac5c8 100644
--- a/tests/components/recorder/test_history_db_schema_30.py
+++ b/tests/components/recorder/test_history_db_schema_30.py
@@ -45,8 +45,9 @@ def test_get_full_significant_states_with_session_entity_no_matches(
now = dt_util.utcnow()
time_before_recorder_ran = now - timedelta(days=1000)
instance = recorder.get_instance(hass)
- with session_scope(hass=hass) as session, patch.object(
- instance.states_meta_manager, "active", False
+ with (
+ session_scope(hass=hass) as session,
+ patch.object(instance.states_meta_manager, "active", False),
):
assert (
history.get_full_significant_states_with_session(
@@ -74,8 +75,9 @@ def test_significant_states_with_session_entity_minimal_response_no_matches(
now = dt_util.utcnow()
time_before_recorder_ran = now - timedelta(days=1000)
instance = recorder.get_instance(hass)
- with session_scope(hass=hass) as session, patch.object(
- instance.states_meta_manager, "active", False
+ with (
+ session_scope(hass=hass) as session,
+ patch.object(instance.states_meta_manager, "active", False),
):
assert (
history.get_significant_states_with_session(
diff --git a/tests/components/recorder/test_history_db_schema_32.py b/tests/components/recorder/test_history_db_schema_32.py
index 70f8c636d0e..b926aa1903b 100644
--- a/tests/components/recorder/test_history_db_schema_32.py
+++ b/tests/components/recorder/test_history_db_schema_32.py
@@ -45,8 +45,9 @@ def test_get_full_significant_states_with_session_entity_no_matches(
now = dt_util.utcnow()
time_before_recorder_ran = now - timedelta(days=1000)
instance = recorder.get_instance(hass)
- with session_scope(hass=hass) as session, patch.object(
- instance.states_meta_manager, "active", False
+ with (
+ session_scope(hass=hass) as session,
+ patch.object(instance.states_meta_manager, "active", False),
):
assert (
history.get_full_significant_states_with_session(
@@ -74,8 +75,9 @@ def test_significant_states_with_session_entity_minimal_response_no_matches(
now = dt_util.utcnow()
time_before_recorder_ran = now - timedelta(days=1000)
instance = recorder.get_instance(hass)
- with session_scope(hass=hass) as session, patch.object(
- instance.states_meta_manager, "active", False
+ with (
+ session_scope(hass=hass) as session,
+ patch.object(instance.states_meta_manager, "active", False),
):
assert (
history.get_significant_states_with_session(
diff --git a/tests/components/recorder/test_init.py b/tests/components/recorder/test_init.py
index 3154ebf7ffc..cde2da3cc83 100644
--- a/tests/components/recorder/test_init.py
+++ b/tests/components/recorder/test_init.py
@@ -102,8 +102,9 @@ from tests.typing import RecorderInstanceGenerator
@pytest.fixture
def small_cache_size() -> None:
"""Patch the default cache size to 8."""
- with patch.object(state_attributes_table_manager, "CACHE_SIZE", 8), patch.object(
- states_meta_table_manager, "CACHE_SIZE", 8
+ with (
+ patch.object(state_attributes_table_manager, "CACHE_SIZE", 8),
+ patch.object(states_meta_table_manager, "CACHE_SIZE", 8),
):
yield
@@ -326,8 +327,9 @@ async def test_saving_many_states(
entity_id = "test.recorder"
attributes = {"test_attr": 5, "test_attr_10": "nice"}
- with patch.object(instance.event_session, "expire_all") as expire_all, patch.object(
- recorder.core, "EXPIRE_AFTER_COMMITS", 2
+ with (
+ patch.object(instance.event_session, "expire_all") as expire_all,
+ patch.object(recorder.core, "EXPIRE_AFTER_COMMITS", 2),
):
for _ in range(3):
hass.states.async_set(entity_id, "on", attributes)
@@ -386,10 +388,13 @@ def test_saving_state_with_exception(
"insert the state", "fake params", "forced to fail"
)
- with patch("time.sleep"), patch.object(
- get_instance(hass).event_session,
- "flush",
- side_effect=_throw_if_state_in_session,
+ with (
+ patch("time.sleep"),
+ patch.object(
+ get_instance(hass).event_session,
+ "flush",
+ side_effect=_throw_if_state_in_session,
+ ),
):
hass.states.set(entity_id, "fail", attributes)
wait_recording_done(hass)
@@ -428,10 +433,13 @@ def test_saving_state_with_sqlalchemy_exception(
"insert the state", "fake params", "forced to fail"
)
- with patch("time.sleep"), patch.object(
- get_instance(hass).event_session,
- "flush",
- side_effect=_throw_if_state_in_session,
+ with (
+ patch("time.sleep"),
+ patch.object(
+ get_instance(hass).event_session,
+ "flush",
+ side_effect=_throw_if_state_in_session,
+ ),
):
hass.states.set(entity_id, "fail", attributes)
wait_recording_done(hass)
@@ -464,11 +472,14 @@ async def test_force_shutdown_with_queue_of_writes_that_generate_exceptions(
await async_wait_recording_done(hass)
- with patch.object(instance, "db_retry_wait", 0.01), patch.object(
- instance.event_session,
- "flush",
- side_effect=OperationalError(
- "insert the state", "fake params", "forced to fail"
+ with (
+ patch.object(instance, "db_retry_wait", 0.01),
+ patch.object(
+ instance.event_session,
+ "flush",
+ side_effect=OperationalError(
+ "insert the state", "fake params", "forced to fail"
+ ),
),
):
for _ in range(100):
@@ -898,8 +909,9 @@ def test_saving_event_invalid_context_ulid(
def test_recorder_setup_failure(hass: HomeAssistant) -> None:
"""Test some exceptions."""
recorder_helper.async_initialize_recorder(hass)
- with patch.object(Recorder, "_setup_connection") as setup, patch(
- "homeassistant.components.recorder.core.time.sleep"
+ with (
+ patch.object(Recorder, "_setup_connection") as setup,
+ patch("homeassistant.components.recorder.core.time.sleep"),
):
setup.side_effect = ImportError("driver not found")
rec = _default_recorder(hass)
@@ -913,10 +925,11 @@ def test_recorder_setup_failure(hass: HomeAssistant) -> None:
def test_recorder_validate_schema_failure(hass: HomeAssistant) -> None:
"""Test some exceptions."""
recorder_helper.async_initialize_recorder(hass)
- with patch(
- "homeassistant.components.recorder.migration._get_schema_version"
- ) as inspect_schema_version, patch(
- "homeassistant.components.recorder.core.time.sleep"
+ with (
+ patch(
+ "homeassistant.components.recorder.migration._get_schema_version"
+ ) as inspect_schema_version,
+ patch("homeassistant.components.recorder.core.time.sleep"),
):
inspect_schema_version.side_effect = ImportError("driver not found")
rec = _default_recorder(hass)
@@ -930,8 +943,9 @@ def test_recorder_validate_schema_failure(hass: HomeAssistant) -> None:
def test_recorder_setup_failure_without_event_listener(hass: HomeAssistant) -> None:
"""Test recorder setup failure when the event listener is not setup."""
recorder_helper.async_initialize_recorder(hass)
- with patch.object(Recorder, "_setup_connection") as setup, patch(
- "homeassistant.components.recorder.core.time.sleep"
+ with (
+ patch.object(Recorder, "_setup_connection") as setup,
+ patch("homeassistant.components.recorder.core.time.sleep"),
):
setup.side_effect = ImportError("driver not found")
rec = _default_recorder(hass)
@@ -987,11 +1001,14 @@ def test_auto_purge(hass_recorder: Callable[..., HomeAssistant]) -> None:
test_time = datetime(now.year + 2, 1, 1, 4, 15, 0, tzinfo=tz)
run_tasks_at_time(hass, test_time)
- with patch(
- "homeassistant.components.recorder.purge.purge_old_data", return_value=True
- ) as purge_old_data, patch(
- "homeassistant.components.recorder.tasks.periodic_db_cleanups"
- ) as periodic_db_cleanups:
+ with (
+ patch(
+ "homeassistant.components.recorder.purge.purge_old_data", return_value=True
+ ) as purge_old_data,
+ patch(
+ "homeassistant.components.recorder.tasks.periodic_db_cleanups"
+ ) as periodic_db_cleanups,
+ ):
# Advance one day, and the purge task should run
test_time = test_time + timedelta(days=1)
run_tasks_at_time(hass, test_time)
@@ -1047,13 +1064,17 @@ def test_auto_purge_auto_repack_on_second_sunday(
test_time = datetime(now.year + 2, 1, 1, 4, 15, 0, tzinfo=tz)
run_tasks_at_time(hass, test_time)
- with patch(
- "homeassistant.components.recorder.core.is_second_sunday", return_value=True
- ), patch(
- "homeassistant.components.recorder.purge.purge_old_data", return_value=True
- ) as purge_old_data, patch(
- "homeassistant.components.recorder.tasks.periodic_db_cleanups"
- ) as periodic_db_cleanups:
+ with (
+ patch(
+ "homeassistant.components.recorder.core.is_second_sunday", return_value=True
+ ),
+ patch(
+ "homeassistant.components.recorder.purge.purge_old_data", return_value=True
+ ) as purge_old_data,
+ patch(
+ "homeassistant.components.recorder.tasks.periodic_db_cleanups"
+ ) as periodic_db_cleanups,
+ ):
# Advance one day, and the purge task should run
test_time = test_time + timedelta(days=1)
run_tasks_at_time(hass, test_time)
@@ -1087,13 +1108,17 @@ def test_auto_purge_auto_repack_disabled_on_second_sunday(
test_time = datetime(now.year + 2, 1, 1, 4, 15, 0, tzinfo=tz)
run_tasks_at_time(hass, test_time)
- with patch(
- "homeassistant.components.recorder.core.is_second_sunday", return_value=True
- ), patch(
- "homeassistant.components.recorder.purge.purge_old_data", return_value=True
- ) as purge_old_data, patch(
- "homeassistant.components.recorder.tasks.periodic_db_cleanups"
- ) as periodic_db_cleanups:
+ with (
+ patch(
+ "homeassistant.components.recorder.core.is_second_sunday", return_value=True
+ ),
+ patch(
+ "homeassistant.components.recorder.purge.purge_old_data", return_value=True
+ ) as purge_old_data,
+ patch(
+ "homeassistant.components.recorder.tasks.periodic_db_cleanups"
+ ) as periodic_db_cleanups,
+ ):
# Advance one day, and the purge task should run
test_time = test_time + timedelta(days=1)
run_tasks_at_time(hass, test_time)
@@ -1127,14 +1152,18 @@ def test_auto_purge_no_auto_repack_on_not_second_sunday(
test_time = datetime(now.year + 2, 1, 1, 4, 15, 0, tzinfo=tz)
run_tasks_at_time(hass, test_time)
- with patch(
- "homeassistant.components.recorder.core.is_second_sunday",
- return_value=False,
- ), patch(
- "homeassistant.components.recorder.purge.purge_old_data", return_value=True
- ) as purge_old_data, patch(
- "homeassistant.components.recorder.tasks.periodic_db_cleanups"
- ) as periodic_db_cleanups:
+ with (
+ patch(
+ "homeassistant.components.recorder.core.is_second_sunday",
+ return_value=False,
+ ),
+ patch(
+ "homeassistant.components.recorder.purge.purge_old_data", return_value=True
+ ) as purge_old_data,
+ patch(
+ "homeassistant.components.recorder.tasks.periodic_db_cleanups"
+ ) as periodic_db_cleanups,
+ ):
# Advance one day, and the purge task should run
test_time = test_time + timedelta(days=1)
run_tasks_at_time(hass, test_time)
@@ -1165,11 +1194,14 @@ def test_auto_purge_disabled(hass_recorder: Callable[..., HomeAssistant]) -> Non
test_time = datetime(now.year + 2, 1, 1, 4, 15, 0, tzinfo=tz)
run_tasks_at_time(hass, test_time)
- with patch(
- "homeassistant.components.recorder.purge.purge_old_data", return_value=True
- ) as purge_old_data, patch(
- "homeassistant.components.recorder.tasks.periodic_db_cleanups"
- ) as periodic_db_cleanups:
+ with (
+ patch(
+ "homeassistant.components.recorder.purge.purge_old_data", return_value=True
+ ) as purge_old_data,
+ patch(
+ "homeassistant.components.recorder.tasks.periodic_db_cleanups"
+ ) as periodic_db_cleanups,
+ ):
# Advance one day, and the purge task should run
test_time = test_time + timedelta(days=1)
run_tasks_at_time(hass, test_time)
@@ -1810,9 +1842,11 @@ async def test_database_lock_and_overflow(
)
)
- with patch.object(recorder.core, "MAX_QUEUE_BACKLOG_MIN_VALUE", 1), patch.object(
- recorder.core, "DB_LOCK_QUEUE_CHECK_TIMEOUT", 0.01
- ), patch.object(recorder.core, "QUEUE_PERCENTAGE_ALLOWED_AVAILABLE_MEMORY", 0):
+ with (
+ patch.object(recorder.core, "MAX_QUEUE_BACKLOG_MIN_VALUE", 1),
+ patch.object(recorder.core, "DB_LOCK_QUEUE_CHECK_TIMEOUT", 0.01),
+ patch.object(recorder.core, "QUEUE_PERCENTAGE_ALLOWED_AVAILABLE_MEMORY", 0),
+ ):
await async_setup_recorder_instance(hass, config)
await hass.async_block_till_done()
event_type = "EVENT_TEST"
@@ -1879,12 +1913,15 @@ async def test_database_lock_and_overflow_checks_available_memory(
event_types = (event_type,)
await async_wait_recording_done(hass)
- with patch.object(recorder.core, "MAX_QUEUE_BACKLOG_MIN_VALUE", 1), patch.object(
- recorder.core, "QUEUE_PERCENTAGE_ALLOWED_AVAILABLE_MEMORY", 1
- ), patch.object(recorder.core, "DB_LOCK_QUEUE_CHECK_TIMEOUT", 0.01), patch.object(
- recorder.core.Recorder,
- "_available_memory",
- return_value=recorder.core.ESTIMATED_QUEUE_ITEM_SIZE * 4,
+ with (
+ patch.object(recorder.core, "MAX_QUEUE_BACKLOG_MIN_VALUE", 1),
+ patch.object(recorder.core, "QUEUE_PERCENTAGE_ALLOWED_AVAILABLE_MEMORY", 1),
+ patch.object(recorder.core, "DB_LOCK_QUEUE_CHECK_TIMEOUT", 0.01),
+ patch.object(
+ recorder.core.Recorder,
+ "_available_memory",
+ return_value=recorder.core.ESTIMATED_QUEUE_ITEM_SIZE * 4,
+ ),
):
instance = get_instance(hass)
@@ -2136,10 +2173,11 @@ async def test_disable_echo(
callback(None, None)
mock_event = MockEvent()
- with patch(
- "homeassistant.components.recorder.core.create_engine"
- ) as create_engine_mock, patch(
- "homeassistant.components.recorder.core.sqlalchemy_event", mock_event
+ with (
+ patch(
+ "homeassistant.components.recorder.core.create_engine"
+ ) as create_engine_mock,
+ patch("homeassistant.components.recorder.core.sqlalchemy_event", mock_event),
):
await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_DB_URL: db_url}})
create_engine_mock.assert_called_once()
@@ -2194,10 +2232,11 @@ async def test_mysql_missing_utf8mb4(
callback(None, None)
mock_event = MockEvent()
- with patch(
- "homeassistant.components.recorder.core.create_engine"
- ) as create_engine_mock, patch(
- "homeassistant.components.recorder.core.sqlalchemy_event", mock_event
+ with (
+ patch(
+ "homeassistant.components.recorder.core.create_engine"
+ ) as create_engine_mock,
+ patch("homeassistant.components.recorder.core.sqlalchemy_event", mock_event),
):
await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_DB_URL: config_url}})
create_engine_mock.assert_called_once()
@@ -2226,8 +2265,7 @@ async def test_connect_args_priority(hass: HomeAssistant, config_url) -> None:
__bases__ = []
_has_events = False
- def __init__(*args, **kwargs):
- ...
+ def __init__(*args, **kwargs): ...
@property
def is_async(self):
@@ -2246,33 +2284,29 @@ async def test_connect_args_priority(hass: HomeAssistant, config_url) -> None:
return "mysql"
@classmethod
- def import_dbapi(cls):
- ...
+ def import_dbapi(cls): ...
- def engine_created(*args):
- ...
+ def engine_created(*args): ...
def get_dialect_pool_class(self, *args):
return pool.RecorderPool
- def initialize(*args):
- ...
+ def initialize(*args): ...
def on_connect_url(self, url):
return False
- def _builtin_onconnect(self):
- ...
+ def _builtin_onconnect(self): ...
class MockEntrypoint:
- def engine_created(*_):
- ...
+ def engine_created(*_): ...
def get_dialect_cls(*_):
return MockDialect
- with patch("sqlalchemy.engine.url.URL._get_entrypoint", MockEntrypoint), patch(
- "sqlalchemy.engine.create.util.get_cls_kwargs", return_value=["echo"]
+ with (
+ patch("sqlalchemy.engine.url.URL._get_entrypoint", MockEntrypoint),
+ patch("sqlalchemy.engine.create.util.get_cls_kwargs", return_value=["echo"]),
):
await async_setup_component(
hass,
@@ -2363,8 +2397,9 @@ async def test_clean_shutdown_when_recorder_thread_raises_during_initialize_data
hass: HomeAssistant,
) -> None:
"""Test we still shutdown cleanly when the recorder thread raises during initialize_database."""
- with patch.object(migration, "initialize_database", side_effect=Exception), patch(
- "homeassistant.components.recorder.ALLOW_IN_MEMORY_DB", True
+ with (
+ patch.object(migration, "initialize_database", side_effect=Exception),
+ patch("homeassistant.components.recorder.ALLOW_IN_MEMORY_DB", True),
):
if recorder.DOMAIN not in hass.data:
recorder_helper.async_initialize_recorder(hass)
@@ -2390,8 +2425,9 @@ async def test_clean_shutdown_when_recorder_thread_raises_during_validate_db_sch
hass: HomeAssistant,
) -> None:
"""Test we still shutdown cleanly when the recorder thread raises during validate_db_schema."""
- with patch.object(migration, "validate_db_schema", side_effect=Exception), patch(
- "homeassistant.components.recorder.ALLOW_IN_MEMORY_DB", True
+ with (
+ patch.object(migration, "validate_db_schema", side_effect=Exception),
+ patch("homeassistant.components.recorder.ALLOW_IN_MEMORY_DB", True),
):
if recorder.DOMAIN not in hass.data:
recorder_helper.async_initialize_recorder(hass)
@@ -2415,16 +2451,18 @@ async def test_clean_shutdown_when_recorder_thread_raises_during_validate_db_sch
async def test_clean_shutdown_when_schema_migration_fails(hass: HomeAssistant) -> None:
"""Test we still shutdown cleanly when schema migration fails."""
- with patch.object(
- migration,
- "validate_db_schema",
- return_value=MagicMock(valid=False, current_version=1),
- ), patch(
- "homeassistant.components.recorder.ALLOW_IN_MEMORY_DB", True
- ), patch.object(
- migration,
- "migrate_schema",
- side_effect=Exception,
+ with (
+ patch.object(
+ migration,
+ "validate_db_schema",
+ return_value=MagicMock(valid=False, current_version=1),
+ ),
+ patch("homeassistant.components.recorder.ALLOW_IN_MEMORY_DB", True),
+ patch.object(
+ migration,
+ "migrate_schema",
+ side_effect=Exception,
+ ),
):
if recorder.DOMAIN not in hass.data:
recorder_helper.async_initialize_recorder(hass)
diff --git a/tests/components/recorder/test_migrate.py b/tests/components/recorder/test_migrate.py
index 141ffc31cc0..01d5912a683 100644
--- a/tests/components/recorder/test_migrate.py
+++ b/tests/components/recorder/test_migrate.py
@@ -52,13 +52,17 @@ async def test_schema_update_calls(recorder_db_url: str, hass: HomeAssistant) ->
"""Test that schema migrations occur in correct order."""
assert recorder.util.async_migration_in_progress(hass) is False
- with patch("homeassistant.components.recorder.ALLOW_IN_MEMORY_DB", True), patch(
- "homeassistant.components.recorder.core.create_engine",
- new=create_engine_test,
- ), patch(
- "homeassistant.components.recorder.migration._apply_update",
- wraps=migration._apply_update,
- ) as update:
+ with (
+ patch("homeassistant.components.recorder.ALLOW_IN_MEMORY_DB", True),
+ patch(
+ "homeassistant.components.recorder.core.create_engine",
+ new=create_engine_test,
+ ),
+ patch(
+ "homeassistant.components.recorder.migration._apply_update",
+ wraps=migration._apply_update,
+ ) as update,
+ ):
recorder_helper.async_initialize_recorder(hass)
await async_setup_component(
hass, "recorder", {"recorder": {"db_url": recorder_db_url}}
@@ -89,9 +93,12 @@ async def test_migration_in_progress(recorder_db_url: str, hass: HomeAssistant)
assert recorder.util.async_migration_in_progress(hass) is False
- with patch("homeassistant.components.recorder.ALLOW_IN_MEMORY_DB", True), patch(
- "homeassistant.components.recorder.core.create_engine",
- new=create_engine_test,
+ with (
+ patch("homeassistant.components.recorder.ALLOW_IN_MEMORY_DB", True),
+ patch(
+ "homeassistant.components.recorder.core.create_engine",
+ new=create_engine_test,
+ ),
):
recorder_helper.async_initialize_recorder(hass)
await async_setup_component(
@@ -111,18 +118,25 @@ async def test_database_migration_failed(
"""Test we notify if the migration fails."""
assert recorder.util.async_migration_in_progress(hass) is False
- with patch("homeassistant.components.recorder.ALLOW_IN_MEMORY_DB", True), patch(
- "homeassistant.components.recorder.core.create_engine",
- new=create_engine_test,
- ), patch(
- "homeassistant.components.recorder.migration._apply_update",
- side_effect=ValueError,
- ), patch(
- "homeassistant.components.persistent_notification.create", side_effect=pn.create
- ) as mock_create, patch(
- "homeassistant.components.persistent_notification.dismiss",
- side_effect=pn.dismiss,
- ) as mock_dismiss:
+ with (
+ patch("homeassistant.components.recorder.ALLOW_IN_MEMORY_DB", True),
+ patch(
+ "homeassistant.components.recorder.core.create_engine",
+ new=create_engine_test,
+ ),
+ patch(
+ "homeassistant.components.recorder.migration._apply_update",
+ side_effect=ValueError,
+ ),
+ patch(
+ "homeassistant.components.persistent_notification.create",
+ side_effect=pn.create,
+ ) as mock_create,
+ patch(
+ "homeassistant.components.persistent_notification.dismiss",
+ side_effect=pn.dismiss,
+ ) as mock_dismiss,
+ ):
recorder_helper.async_initialize_recorder(hass)
await async_setup_component(
hass, "recorder", {"recorder": {"db_url": recorder_db_url}}
@@ -152,16 +166,22 @@ async def test_database_migration_encounters_corruption(
sqlite3_exception = DatabaseError("statement", {}, [])
sqlite3_exception.__cause__ = sqlite3.DatabaseError()
- with patch("homeassistant.components.recorder.ALLOW_IN_MEMORY_DB", True), patch(
- "homeassistant.components.recorder.migration._schema_is_current",
- side_effect=[False],
- ), patch(
- "homeassistant.components.recorder.migration.migrate_schema",
- side_effect=sqlite3_exception,
- ), patch(
- "homeassistant.components.recorder.core.move_away_broken_database"
- ) as move_away, patch(
- "homeassistant.components.recorder.Recorder._schedule_compile_missing_statistics",
+ with (
+ patch("homeassistant.components.recorder.ALLOW_IN_MEMORY_DB", True),
+ patch(
+ "homeassistant.components.recorder.migration._schema_is_current",
+ side_effect=[False],
+ ),
+ patch(
+ "homeassistant.components.recorder.migration.migrate_schema",
+ side_effect=sqlite3_exception,
+ ),
+ patch(
+ "homeassistant.components.recorder.core.move_away_broken_database"
+ ) as move_away,
+ patch(
+ "homeassistant.components.recorder.Recorder._schedule_compile_missing_statistics",
+ ),
):
recorder_helper.async_initialize_recorder(hass)
await async_setup_component(
@@ -181,20 +201,28 @@ async def test_database_migration_encounters_corruption_not_sqlite(
"""Test we fail on database error when we cannot recover."""
assert recorder.util.async_migration_in_progress(hass) is False
- with patch("homeassistant.components.recorder.ALLOW_IN_MEMORY_DB", True), patch(
- "homeassistant.components.recorder.migration._schema_is_current",
- side_effect=[False],
- ), patch(
- "homeassistant.components.recorder.migration.migrate_schema",
- side_effect=DatabaseError("statement", {}, []),
- ), patch(
- "homeassistant.components.recorder.core.move_away_broken_database"
- ) as move_away, patch(
- "homeassistant.components.persistent_notification.create", side_effect=pn.create
- ) as mock_create, patch(
- "homeassistant.components.persistent_notification.dismiss",
- side_effect=pn.dismiss,
- ) as mock_dismiss:
+ with (
+ patch("homeassistant.components.recorder.ALLOW_IN_MEMORY_DB", True),
+ patch(
+ "homeassistant.components.recorder.migration._schema_is_current",
+ side_effect=[False],
+ ),
+ patch(
+ "homeassistant.components.recorder.migration.migrate_schema",
+ side_effect=DatabaseError("statement", {}, []),
+ ),
+ patch(
+ "homeassistant.components.recorder.core.move_away_broken_database"
+ ) as move_away,
+ patch(
+ "homeassistant.components.persistent_notification.create",
+ side_effect=pn.create,
+ ) as mock_create,
+ patch(
+ "homeassistant.components.persistent_notification.dismiss",
+ side_effect=pn.dismiss,
+ ) as mock_dismiss,
+ ):
recorder_helper.async_initialize_recorder(hass)
await async_setup_component(
hass, "recorder", {"recorder": {"db_url": recorder_db_url}}
@@ -218,12 +246,15 @@ async def test_events_during_migration_are_queued(
assert recorder.util.async_migration_in_progress(hass) is False
- with patch(
- "homeassistant.components.recorder.ALLOW_IN_MEMORY_DB",
- True,
- ), patch(
- "homeassistant.components.recorder.core.create_engine",
- new=create_engine_test,
+ with (
+ patch(
+ "homeassistant.components.recorder.ALLOW_IN_MEMORY_DB",
+ True,
+ ),
+ patch(
+ "homeassistant.components.recorder.core.create_engine",
+ new=create_engine_test,
+ ),
):
recorder_helper.async_initialize_recorder(hass)
await async_setup_component(
@@ -254,11 +285,14 @@ async def test_events_during_migration_queue_exhausted(
assert recorder.util.async_migration_in_progress(hass) is False
- with patch("homeassistant.components.recorder.ALLOW_IN_MEMORY_DB", True), patch(
- "homeassistant.components.recorder.core.create_engine",
- new=create_engine_test,
- ), patch.object(recorder.core, "MAX_QUEUE_BACKLOG_MIN_VALUE", 1), patch.object(
- recorder.core, "QUEUE_PERCENTAGE_ALLOWED_AVAILABLE_MEMORY", 0
+ with (
+ patch("homeassistant.components.recorder.ALLOW_IN_MEMORY_DB", True),
+ patch(
+ "homeassistant.components.recorder.core.create_engine",
+ new=create_engine_test,
+ ),
+ patch.object(recorder.core, "MAX_QUEUE_BACKLOG_MIN_VALUE", 1),
+ patch.object(recorder.core, "QUEUE_PERCENTAGE_ALLOWED_AVAILABLE_MEMORY", 0),
):
recorder_helper.async_initialize_recorder(hass)
await async_setup_component(
@@ -372,32 +406,42 @@ async def test_schema_migrate(
raise mysql_exception
real_create_index(*args)
- with patch("homeassistant.components.recorder.ALLOW_IN_MEMORY_DB", True), patch(
- "homeassistant.components.recorder.core.create_engine",
- new=_create_engine_test,
- ), patch(
- "homeassistant.components.recorder.Recorder._setup_run",
- side_effect=_mock_setup_run,
- autospec=True,
- ) as setup_run, patch(
- "homeassistant.components.recorder.migration.migrate_schema",
- wraps=_instrument_migrate_schema,
- ), patch(
- "homeassistant.components.recorder.migration._apply_update",
- wraps=_instrument_apply_update,
- ) as apply_update_mock, patch(
- "homeassistant.components.recorder.util.time.sleep"
- ), patch(
- "homeassistant.components.recorder.migration._create_index",
- wraps=_sometimes_failing_create_index,
- ), patch(
- "homeassistant.components.recorder.Recorder._schedule_compile_missing_statistics",
- ), patch(
- "homeassistant.components.recorder.Recorder._process_state_changed_event_into_session",
- ), patch(
- "homeassistant.components.recorder.Recorder._process_non_state_changed_event_into_session",
- ), patch(
- "homeassistant.components.recorder.Recorder._pre_process_startup_events",
+ with (
+ patch("homeassistant.components.recorder.ALLOW_IN_MEMORY_DB", True),
+ patch(
+ "homeassistant.components.recorder.core.create_engine",
+ new=_create_engine_test,
+ ),
+ patch(
+ "homeassistant.components.recorder.Recorder._setup_run",
+ side_effect=_mock_setup_run,
+ autospec=True,
+ ) as setup_run,
+ patch(
+ "homeassistant.components.recorder.migration.migrate_schema",
+ wraps=_instrument_migrate_schema,
+ ),
+ patch(
+ "homeassistant.components.recorder.migration._apply_update",
+ wraps=_instrument_apply_update,
+ ) as apply_update_mock,
+ patch("homeassistant.components.recorder.util.time.sleep"),
+ patch(
+ "homeassistant.components.recorder.migration._create_index",
+ wraps=_sometimes_failing_create_index,
+ ),
+ patch(
+ "homeassistant.components.recorder.Recorder._schedule_compile_missing_statistics",
+ ),
+ patch(
+ "homeassistant.components.recorder.Recorder._process_state_changed_event_into_session",
+ ),
+ patch(
+ "homeassistant.components.recorder.Recorder._process_non_state_changed_event_into_session",
+ ),
+ patch(
+ "homeassistant.components.recorder.Recorder._pre_process_startup_events",
+ ),
):
recorder_helper.async_initialize_recorder(hass)
hass.async_create_task(
@@ -497,11 +541,14 @@ def test_forgiving_drop_index(
instance.get_session, "states", "ix_states_context_id_bin"
)
- with patch(
- "homeassistant.components.recorder.migration.get_index_by_name",
- return_value="ix_states_context_id_bin",
- ), patch.object(
- session, "connection", side_effect=SQLAlchemyError("connection failure")
+ with (
+ patch(
+ "homeassistant.components.recorder.migration.get_index_by_name",
+ return_value="ix_states_context_id_bin",
+ ),
+ patch.object(
+ session, "connection", side_effect=SQLAlchemyError("connection failure")
+ ),
):
migration._drop_index(
instance.get_session, "states", "ix_states_context_id_bin"
@@ -509,11 +556,14 @@ def test_forgiving_drop_index(
assert "Failed to drop index" in caplog.text
assert "connection failure" in caplog.text
caplog.clear()
- with patch(
- "homeassistant.components.recorder.migration.get_index_by_name",
- return_value="ix_states_context_id_bin",
- ), patch.object(
- session, "connection", side_effect=SQLAlchemyError("connection failure")
+ with (
+ patch(
+ "homeassistant.components.recorder.migration.get_index_by_name",
+ return_value="ix_states_context_id_bin",
+ ),
+ patch.object(
+ session, "connection", side_effect=SQLAlchemyError("connection failure")
+ ),
):
migration._drop_index(
instance.get_session, "states", "ix_states_context_id_bin", quiet=True
diff --git a/tests/components/recorder/test_migration_from_schema_32.py b/tests/components/recorder/test_migration_from_schema_32.py
index e9f51caaee2..646cd338949 100644
--- a/tests/components/recorder/test_migration_from_schema_32.py
+++ b/tests/components/recorder/test_migration_from_schema_32.py
@@ -92,16 +92,19 @@ def db_schema_32():
importlib.import_module(SCHEMA_MODULE)
old_db_schema = sys.modules[SCHEMA_MODULE]
- with patch.object(recorder, "db_schema", old_db_schema), patch.object(
- recorder.migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION
- ), patch.object(core, "StatesMeta", old_db_schema.StatesMeta), patch.object(
- core, "EventTypes", old_db_schema.EventTypes
- ), patch.object(core, "EventData", old_db_schema.EventData), patch.object(
- core, "States", old_db_schema.States
- ), patch.object(core, "Events", old_db_schema.Events), patch.object(
- core, "StateAttributes", old_db_schema.StateAttributes
- ), patch.object(migration.EntityIDMigration, "task", core.RecorderTask), patch(
- CREATE_ENGINE_TARGET, new=_create_engine_test
+ with (
+ patch.object(recorder, "db_schema", old_db_schema),
+ patch.object(
+ recorder.migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION
+ ),
+ patch.object(core, "StatesMeta", old_db_schema.StatesMeta),
+ patch.object(core, "EventTypes", old_db_schema.EventTypes),
+ patch.object(core, "EventData", old_db_schema.EventData),
+ patch.object(core, "States", old_db_schema.States),
+ patch.object(core, "Events", old_db_schema.Events),
+ patch.object(core, "StateAttributes", old_db_schema.StateAttributes),
+ patch.object(migration.EntityIDMigration, "task", core.RecorderTask),
+ patch(CREATE_ENGINE_TARGET, new=_create_engine_test),
):
yield
@@ -1294,14 +1297,17 @@ async def test_stats_timestamp_with_one_by_one_removes_duplicates(
one_month_ago = now - datetime.timedelta(days=30)
def _do_migration():
- with patch.object(
- migration,
- "_migrate_statistics_columns_to_timestamp",
- side_effect=IntegrityError("test", "test", "test"),
- ), patch.object(
- migration,
- "migrate_single_statistics_row_to_timestamp",
- side_effect=IntegrityError("test", "test", "test"),
+ with (
+ patch.object(
+ migration,
+ "_migrate_statistics_columns_to_timestamp",
+ side_effect=IntegrityError("test", "test", "test"),
+ ),
+ patch.object(
+ migration,
+ "migrate_single_statistics_row_to_timestamp",
+ side_effect=IntegrityError("test", "test", "test"),
+ ),
):
migration._migrate_statistics_columns_to_timestamp_removing_duplicates(
hass, instance, instance.get_session, instance.engine
diff --git a/tests/components/recorder/test_migration_run_time_migrations_remember.py b/tests/components/recorder/test_migration_run_time_migrations_remember.py
index 770d5d684a9..4f59edb097f 100644
--- a/tests/components/recorder/test_migration_run_time_migrations_remember.py
+++ b/tests/components/recorder/test_migration_run_time_migrations_remember.py
@@ -89,16 +89,19 @@ async def test_migration_changes_prevent_trying_to_migrate_again(
old_db_schema = sys.modules[SCHEMA_MODULE]
# Start with db schema that needs migration (version 32)
- with patch.object(recorder, "db_schema", old_db_schema), patch.object(
- recorder.migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION
- ), patch.object(core, "StatesMeta", old_db_schema.StatesMeta), patch.object(
- core, "EventTypes", old_db_schema.EventTypes
- ), patch.object(core, "EventData", old_db_schema.EventData), patch.object(
- core, "States", old_db_schema.States
- ), patch.object(core, "Events", old_db_schema.Events), patch.object(
- core, "StateAttributes", old_db_schema.StateAttributes
- ), patch.object(migration.EntityIDMigration, "task", core.RecorderTask), patch(
- CREATE_ENGINE_TARGET, new=_create_engine_test
+ with (
+ patch.object(recorder, "db_schema", old_db_schema),
+ patch.object(
+ recorder.migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION
+ ),
+ patch.object(core, "StatesMeta", old_db_schema.StatesMeta),
+ patch.object(core, "EventTypes", old_db_schema.EventTypes),
+ patch.object(core, "EventData", old_db_schema.EventData),
+ patch.object(core, "States", old_db_schema.States),
+ patch.object(core, "Events", old_db_schema.Events),
+ patch.object(core, "StateAttributes", old_db_schema.StateAttributes),
+ patch.object(migration.EntityIDMigration, "task", core.RecorderTask),
+ patch(CREATE_ENGINE_TARGET, new=_create_engine_test),
):
async with async_test_home_assistant() as hass:
await async_setup_recorder_instance(hass, config)
@@ -136,12 +139,16 @@ async def test_migration_changes_prevent_trying_to_migrate_again(
# Finally verify we did not call needs_migrate_query on StatesContextIDMigration
async with async_test_home_assistant() as hass:
- with patch(
- "homeassistant.components.recorder.core.Recorder.queue_task", _queue_task
- ), patch.object(
- migration.StatesContextIDMigration,
- "needs_migrate_query",
- side_effect=RuntimeError("Should not be called"),
+ with (
+ patch(
+ "homeassistant.components.recorder.core.Recorder.queue_task",
+ _queue_task,
+ ),
+ patch.object(
+ migration.StatesContextIDMigration,
+ "needs_migrate_query",
+ side_effect=RuntimeError("Should not be called"),
+ ),
):
await async_setup_recorder_instance(hass, config)
await hass.async_block_till_done()
diff --git a/tests/components/recorder/test_purge.py b/tests/components/recorder/test_purge.py
index a58dd2e91dd..b2da3f1d62f 100644
--- a/tests/components/recorder/test_purge.py
+++ b/tests/components/recorder/test_purge.py
@@ -79,9 +79,11 @@ async def test_purge_big_database(
await _add_test_states(hass, wait_recording_done=False)
await async_wait_recording_done(hass)
- with patch.object(instance, "max_bind_vars", 72), patch.object(
- instance.database_engine, "max_bind_vars", 72
- ), session_scope(hass=hass) as session:
+ with (
+ patch.object(instance, "max_bind_vars", 72),
+ patch.object(instance.database_engine, "max_bind_vars", 72),
+ session_scope(hass=hass) as session,
+ ):
states = session.query(States)
state_attributes = session.query(StateAttributes)
assert states.count() == 72
@@ -208,11 +210,14 @@ async def test_purge_old_states_encouters_database_corruption(
sqlite3_exception = DatabaseError("statement", {}, [])
sqlite3_exception.__cause__ = sqlite3.DatabaseError()
- with patch(
- "homeassistant.components.recorder.core.move_away_broken_database"
- ) as move_away, patch(
- "homeassistant.components.recorder.purge.purge_old_data",
- side_effect=sqlite3_exception,
+ with (
+ patch(
+ "homeassistant.components.recorder.core.move_away_broken_database"
+ ) as move_away,
+ patch(
+ "homeassistant.components.recorder.purge.purge_old_data",
+ side_effect=sqlite3_exception,
+ ),
):
await hass.services.async_call(recorder.DOMAIN, SERVICE_PURGE, {"keep_days": 0})
await hass.async_block_till_done()
@@ -240,12 +245,14 @@ async def test_purge_old_states_encounters_temporary_mysql_error(
mysql_exception = OperationalError("statement", {}, [])
mysql_exception.orig = Exception(1205, "retryable")
- with patch(
- "homeassistant.components.recorder.util.time.sleep"
- ) as sleep_mock, patch(
- "homeassistant.components.recorder.purge._purge_old_recorder_runs",
- side_effect=[mysql_exception, None],
- ), patch.object(instance.engine.dialect, "name", "mysql"):
+ with (
+ patch("homeassistant.components.recorder.util.time.sleep") as sleep_mock,
+ patch(
+ "homeassistant.components.recorder.purge._purge_old_recorder_runs",
+ side_effect=[mysql_exception, None],
+ ),
+ patch.object(instance.engine.dialect, "name", "mysql"),
+ ):
await hass.services.async_call(recorder.DOMAIN, SERVICE_PURGE, {"keep_days": 0})
await hass.async_block_till_done()
await async_wait_recording_done(hass)
@@ -1654,8 +1661,9 @@ async def test_purge_many_old_events(
old_events_count = 5
instance = await async_setup_recorder_instance(hass)
- with patch.object(instance, "max_bind_vars", old_events_count), patch.object(
- instance.database_engine, "max_bind_vars", old_events_count
+ with (
+ patch.object(instance, "max_bind_vars", old_events_count),
+ patch.object(instance.database_engine, "max_bind_vars", old_events_count),
):
await _add_test_events(hass, old_events_count)
diff --git a/tests/components/recorder/test_purge_v32_schema.py b/tests/components/recorder/test_purge_v32_schema.py
index cc210f2d780..3946d8896f7 100644
--- a/tests/components/recorder/test_purge_v32_schema.py
+++ b/tests/components/recorder/test_purge_v32_schema.py
@@ -174,11 +174,14 @@ async def test_purge_old_states_encouters_database_corruption(
sqlite3_exception = DatabaseError("statement", {}, [])
sqlite3_exception.__cause__ = sqlite3.DatabaseError()
- with patch(
- "homeassistant.components.recorder.core.move_away_broken_database"
- ) as move_away, patch(
- "homeassistant.components.recorder.purge.purge_old_data",
- side_effect=sqlite3_exception,
+ with (
+ patch(
+ "homeassistant.components.recorder.core.move_away_broken_database"
+ ) as move_away,
+ patch(
+ "homeassistant.components.recorder.purge.purge_old_data",
+ side_effect=sqlite3_exception,
+ ),
):
await hass.services.async_call(recorder.DOMAIN, SERVICE_PURGE, {"keep_days": 0})
await hass.async_block_till_done()
@@ -207,12 +210,14 @@ async def test_purge_old_states_encounters_temporary_mysql_error(
mysql_exception = OperationalError("statement", {}, [])
mysql_exception.orig = Exception(1205, "retryable")
- with patch(
- "homeassistant.components.recorder.util.time.sleep"
- ) as sleep_mock, patch(
- "homeassistant.components.recorder.purge._purge_old_recorder_runs",
- side_effect=[mysql_exception, None],
- ), patch.object(instance.engine.dialect, "name", "mysql"):
+ with (
+ patch("homeassistant.components.recorder.util.time.sleep") as sleep_mock,
+ patch(
+ "homeassistant.components.recorder.purge._purge_old_recorder_runs",
+ side_effect=[mysql_exception, None],
+ ),
+ patch.object(instance.engine.dialect, "name", "mysql"),
+ ):
await hass.services.async_call(recorder.DOMAIN, SERVICE_PURGE, {"keep_days": 0})
await hass.async_block_till_done()
await async_wait_recording_done(hass)
@@ -937,8 +942,9 @@ async def test_purge_many_old_events(
await async_attach_db_engine(hass)
old_events_count = 5
- with patch.object(instance, "max_bind_vars", old_events_count), patch.object(
- instance.database_engine, "max_bind_vars", old_events_count
+ with (
+ patch.object(instance, "max_bind_vars", old_events_count),
+ patch.object(instance.database_engine, "max_bind_vars", old_events_count),
):
await _add_test_events(hass, old_events_count)
diff --git a/tests/components/recorder/test_statistics_v23_migration.py b/tests/components/recorder/test_statistics_v23_migration.py
index c7b68f29b1c..28c7613e761 100644
--- a/tests/components/recorder/test_statistics_v23_migration.py
+++ b/tests/components/recorder/test_statistics_v23_migration.py
@@ -160,15 +160,20 @@ def test_delete_duplicates(caplog: pytest.LogCaptureFixture, tmp_path: Path) ->
}
# Create some duplicated statistics with schema version 23
- with patch.object(recorder, "db_schema", old_db_schema), patch.object(
- recorder.migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION
- ), patch(
- CREATE_ENGINE_TARGET,
- new=partial(
- create_engine_test_for_schema_version_postfix,
- schema_version_postfix=SCHEMA_VERSION_POSTFIX,
+ with (
+ patch.object(recorder, "db_schema", old_db_schema),
+ patch.object(
+ recorder.migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION
),
- ), get_test_home_assistant() as hass:
+ patch(
+ CREATE_ENGINE_TARGET,
+ new=partial(
+ create_engine_test_for_schema_version_postfix,
+ schema_version_postfix=SCHEMA_VERSION_POSTFIX,
+ ),
+ ),
+ get_test_home_assistant() as hass,
+ ):
recorder_helper.async_initialize_recorder(hass)
setup_component(hass, "recorder", {"recorder": {"db_url": dburl}})
wait_recording_done(hass)
@@ -337,15 +342,20 @@ def test_delete_duplicates_many(
}
# Create some duplicated statistics with schema version 23
- with patch.object(recorder, "db_schema", old_db_schema), patch.object(
- recorder.migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION
- ), patch(
- CREATE_ENGINE_TARGET,
- new=partial(
- create_engine_test_for_schema_version_postfix,
- schema_version_postfix=SCHEMA_VERSION_POSTFIX,
+ with (
+ patch.object(recorder, "db_schema", old_db_schema),
+ patch.object(
+ recorder.migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION
),
- ), get_test_home_assistant() as hass:
+ patch(
+ CREATE_ENGINE_TARGET,
+ new=partial(
+ create_engine_test_for_schema_version_postfix,
+ schema_version_postfix=SCHEMA_VERSION_POSTFIX,
+ ),
+ ),
+ get_test_home_assistant() as hass,
+ ):
recorder_helper.async_initialize_recorder(hass)
setup_component(hass, "recorder", {"recorder": {"db_url": dburl}})
wait_recording_done(hass)
@@ -491,15 +501,20 @@ def test_delete_duplicates_non_identical(
}
# Create some duplicated statistics with schema version 23
- with patch.object(recorder, "db_schema", old_db_schema), patch.object(
- recorder.migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION
- ), patch(
- CREATE_ENGINE_TARGET,
- new=partial(
- create_engine_test_for_schema_version_postfix,
- schema_version_postfix=SCHEMA_VERSION_POSTFIX,
+ with (
+ patch.object(recorder, "db_schema", old_db_schema),
+ patch.object(
+ recorder.migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION
),
- ), get_test_home_assistant() as hass:
+ patch(
+ CREATE_ENGINE_TARGET,
+ new=partial(
+ create_engine_test_for_schema_version_postfix,
+ schema_version_postfix=SCHEMA_VERSION_POSTFIX,
+ ),
+ ),
+ get_test_home_assistant() as hass,
+ ):
recorder_helper.async_initialize_recorder(hass)
setup_component(hass, "recorder", {"recorder": {"db_url": dburl}})
wait_recording_done(hass)
@@ -600,15 +615,20 @@ def test_delete_duplicates_short_term(
}
# Create some duplicated statistics with schema version 23
- with patch.object(recorder, "db_schema", old_db_schema), patch.object(
- recorder.migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION
- ), patch(
- CREATE_ENGINE_TARGET,
- new=partial(
- create_engine_test_for_schema_version_postfix,
- schema_version_postfix=SCHEMA_VERSION_POSTFIX,
+ with (
+ patch.object(recorder, "db_schema", old_db_schema),
+ patch.object(
+ recorder.migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION
),
- ), get_test_home_assistant() as hass:
+ patch(
+ CREATE_ENGINE_TARGET,
+ new=partial(
+ create_engine_test_for_schema_version_postfix,
+ schema_version_postfix=SCHEMA_VERSION_POSTFIX,
+ ),
+ ),
+ get_test_home_assistant() as hass,
+ ):
recorder_helper.async_initialize_recorder(hass)
setup_component(hass, "recorder", {"recorder": {"db_url": dburl}})
wait_recording_done(hass)
diff --git a/tests/components/recorder/test_system_health.py b/tests/components/recorder/test_system_health.py
index 456a9d7de36..ee4217dab69 100644
--- a/tests/components/recorder/test_system_health.py
+++ b/tests/components/recorder/test_system_health.py
@@ -45,11 +45,14 @@ async def test_recorder_system_health_alternate_dbms(
"""Test recorder system health."""
assert await async_setup_component(hass, "system_health", {})
await async_wait_recording_done(hass)
- with patch(
- "homeassistant.components.recorder.core.Recorder.dialect_name", dialect_name
- ), patch(
- "sqlalchemy.orm.session.Session.execute",
- return_value=Mock(scalar=Mock(return_value=("1048576"))),
+ with (
+ patch(
+ "homeassistant.components.recorder.core.Recorder.dialect_name", dialect_name
+ ),
+ patch(
+ "sqlalchemy.orm.session.Session.execute",
+ return_value=Mock(scalar=Mock(return_value=("1048576"))),
+ ),
):
info = await get_system_health_info(hass, "recorder")
instance = get_instance(hass)
@@ -73,15 +76,19 @@ async def test_recorder_system_health_db_url_missing_host(
await async_wait_recording_done(hass)
instance = get_instance(hass)
- with patch(
- "homeassistant.components.recorder.core.Recorder.dialect_name", dialect_name
- ), patch.object(
- instance,
- "db_url",
- "postgresql://homeassistant:blabla@/home_assistant?host=/config/socket",
- ), patch(
- "sqlalchemy.orm.session.Session.execute",
- return_value=Mock(scalar=Mock(return_value=("1048576"))),
+ with (
+ patch(
+ "homeassistant.components.recorder.core.Recorder.dialect_name", dialect_name
+ ),
+ patch.object(
+ instance,
+ "db_url",
+ "postgresql://homeassistant:blabla@/home_assistant?host=/config/socket",
+ ),
+ patch(
+ "sqlalchemy.orm.session.Session.execute",
+ return_value=Mock(scalar=Mock(return_value=("1048576"))),
+ ),
):
info = await get_system_health_info(hass, "recorder")
assert info == {
diff --git a/tests/components/recorder/test_util.py b/tests/components/recorder/test_util.py
index c199d980f69..9a5b91fa8f8 100644
--- a/tests/components/recorder/test_util.py
+++ b/tests/components/recorder/test_util.py
@@ -46,9 +46,11 @@ from tests.typing import RecorderInstanceGenerator
def test_session_scope_not_setup(hass_recorder: Callable[..., HomeAssistant]) -> None:
"""Try to create a session scope when not setup."""
hass = hass_recorder()
- with patch.object(
- util.get_instance(hass), "get_session", return_value=None
- ), pytest.raises(RuntimeError), util.session_scope(hass=hass):
+ with (
+ patch.object(util.get_instance(hass), "get_session", return_value=None),
+ pytest.raises(RuntimeError),
+ util.session_scope(hass=hass),
+ ):
pass
@@ -65,9 +67,10 @@ def test_recorder_bad_execute(hass_recorder: Callable[..., HomeAssistant]) -> No
mck1 = MagicMock()
mck1.to_native = to_native
- with pytest.raises(SQLAlchemyError), patch(
- "homeassistant.components.recorder.core.time.sleep"
- ) as e_mock:
+ with (
+ pytest.raises(SQLAlchemyError),
+ patch("homeassistant.components.recorder.core.time.sleep") as e_mock,
+ ):
util.execute((mck1,), to_native=True)
assert e_mock.call_count == 2
@@ -146,12 +149,15 @@ async def test_last_run_was_recently_clean(
thirty_min_future_time = dt_util.utcnow() + timedelta(minutes=30)
async with async_test_home_assistant() as hass:
- with patch(
- "homeassistant.components.recorder.util.last_run_was_recently_clean",
- wraps=_last_run_was_recently_clean,
- ) as last_run_was_recently_clean_mock, patch(
- "homeassistant.components.recorder.core.dt_util.utcnow",
- return_value=thirty_min_future_time,
+ with (
+ patch(
+ "homeassistant.components.recorder.util.last_run_was_recently_clean",
+ wraps=_last_run_was_recently_clean,
+ ) as last_run_was_recently_clean_mock,
+ patch(
+ "homeassistant.components.recorder.core.dt_util.utcnow",
+ return_value=thirty_min_future_time,
+ ),
):
await async_setup_recorder_instance(hass, config)
last_run_was_recently_clean_mock.assert_called_once()
@@ -752,17 +758,23 @@ def test_combined_checks(
assert "restarted cleanly and passed the basic sanity check" in caplog.text
caplog.clear()
- with patch(
- "homeassistant.components.recorder.util.last_run_was_recently_clean",
- side_effect=sqlite3.DatabaseError,
- ), pytest.raises(sqlite3.DatabaseError):
+ with (
+ patch(
+ "homeassistant.components.recorder.util.last_run_was_recently_clean",
+ side_effect=sqlite3.DatabaseError,
+ ),
+ pytest.raises(sqlite3.DatabaseError),
+ ):
util.run_checks_on_open_db("fake_db_path", cursor)
caplog.clear()
- with patch(
- "homeassistant.components.recorder.util.last_run_was_recently_clean",
- side_effect=sqlite3.DatabaseError,
- ), pytest.raises(sqlite3.DatabaseError):
+ with (
+ patch(
+ "homeassistant.components.recorder.util.last_run_was_recently_clean",
+ side_effect=sqlite3.DatabaseError,
+ ),
+ pytest.raises(sqlite3.DatabaseError),
+ ):
util.run_checks_on_open_db("fake_db_path", cursor)
cursor.execute("DROP TABLE events;")
diff --git a/tests/components/recorder/test_v32_migration.py b/tests/components/recorder/test_v32_migration.py
index 4f2eb4c7585..a07c63b3376 100644
--- a/tests/components/recorder/test_v32_migration.py
+++ b/tests/components/recorder/test_v32_migration.py
@@ -92,26 +92,33 @@ async def test_migrate_times(caplog: pytest.LogCaptureFixture, tmp_path: Path) -
with session_scope(hass=hass) as session:
return inspect(session.connection()).get_indexes("states")
- with patch.object(recorder, "db_schema", old_db_schema), patch.object(
- recorder.migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION
- ), patch.object(core, "StatesMeta", old_db_schema.StatesMeta), patch.object(
- core, "EventTypes", old_db_schema.EventTypes
- ), patch.object(core, "EventData", old_db_schema.EventData), patch.object(
- core, "States", old_db_schema.States
- ), patch.object(core, "Events", old_db_schema.Events), patch(
- CREATE_ENGINE_TARGET, new=_create_engine_test
- ), patch(
- "homeassistant.components.recorder.Recorder._migrate_events_context_ids",
- ), patch(
- "homeassistant.components.recorder.Recorder._migrate_states_context_ids",
- ), patch(
- "homeassistant.components.recorder.Recorder._migrate_event_type_ids",
- ), patch(
- "homeassistant.components.recorder.Recorder._migrate_entity_ids",
- ), patch(
- "homeassistant.components.recorder.Recorder._post_migrate_entity_ids"
- ), patch(
- "homeassistant.components.recorder.Recorder._cleanup_legacy_states_event_ids"
+ with (
+ patch.object(recorder, "db_schema", old_db_schema),
+ patch.object(
+ recorder.migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION
+ ),
+ patch.object(core, "StatesMeta", old_db_schema.StatesMeta),
+ patch.object(core, "EventTypes", old_db_schema.EventTypes),
+ patch.object(core, "EventData", old_db_schema.EventData),
+ patch.object(core, "States", old_db_schema.States),
+ patch.object(core, "Events", old_db_schema.Events),
+ patch(CREATE_ENGINE_TARGET, new=_create_engine_test),
+ patch(
+ "homeassistant.components.recorder.Recorder._migrate_events_context_ids",
+ ),
+ patch(
+ "homeassistant.components.recorder.Recorder._migrate_states_context_ids",
+ ),
+ patch(
+ "homeassistant.components.recorder.Recorder._migrate_event_type_ids",
+ ),
+ patch(
+ "homeassistant.components.recorder.Recorder._migrate_entity_ids",
+ ),
+ patch("homeassistant.components.recorder.Recorder._post_migrate_entity_ids"),
+ patch(
+ "homeassistant.components.recorder.Recorder._cleanup_legacy_states_event_ids"
+ ),
):
async with async_test_home_assistant() as hass:
recorder_helper.async_initialize_recorder(hass)
@@ -256,26 +263,33 @@ async def test_migrate_can_resume_entity_id_post_migration(
with session_scope(hass=hass) as session:
return inspect(session.connection()).get_indexes("states")
- with patch.object(recorder, "db_schema", old_db_schema), patch.object(
- recorder.migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION
- ), patch.object(core, "StatesMeta", old_db_schema.StatesMeta), patch.object(
- core, "EventTypes", old_db_schema.EventTypes
- ), patch.object(core, "EventData", old_db_schema.EventData), patch.object(
- core, "States", old_db_schema.States
- ), patch.object(core, "Events", old_db_schema.Events), patch(
- CREATE_ENGINE_TARGET, new=_create_engine_test
- ), patch(
- "homeassistant.components.recorder.Recorder._migrate_events_context_ids",
- ), patch(
- "homeassistant.components.recorder.Recorder._migrate_states_context_ids",
- ), patch(
- "homeassistant.components.recorder.Recorder._migrate_event_type_ids",
- ), patch(
- "homeassistant.components.recorder.Recorder._migrate_entity_ids",
- ), patch(
- "homeassistant.components.recorder.Recorder._post_migrate_entity_ids"
- ), patch(
- "homeassistant.components.recorder.Recorder._cleanup_legacy_states_event_ids"
+ with (
+ patch.object(recorder, "db_schema", old_db_schema),
+ patch.object(
+ recorder.migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION
+ ),
+ patch.object(core, "StatesMeta", old_db_schema.StatesMeta),
+ patch.object(core, "EventTypes", old_db_schema.EventTypes),
+ patch.object(core, "EventData", old_db_schema.EventData),
+ patch.object(core, "States", old_db_schema.States),
+ patch.object(core, "Events", old_db_schema.Events),
+ patch(CREATE_ENGINE_TARGET, new=_create_engine_test),
+ patch(
+ "homeassistant.components.recorder.Recorder._migrate_events_context_ids",
+ ),
+ patch(
+ "homeassistant.components.recorder.Recorder._migrate_states_context_ids",
+ ),
+ patch(
+ "homeassistant.components.recorder.Recorder._migrate_event_type_ids",
+ ),
+ patch(
+ "homeassistant.components.recorder.Recorder._migrate_entity_ids",
+ ),
+ patch("homeassistant.components.recorder.Recorder._post_migrate_entity_ids"),
+ patch(
+ "homeassistant.components.recorder.Recorder._cleanup_legacy_states_event_ids"
+ ),
):
async with async_test_home_assistant() as hass:
recorder_helper.async_initialize_recorder(hass)
diff --git a/tests/components/recorder/test_websocket_api.py b/tests/components/recorder/test_websocket_api.py
index 08217d6003c..d594218e9d4 100644
--- a/tests/components/recorder/test_websocket_api.py
+++ b/tests/components/recorder/test_websocket_api.py
@@ -2166,16 +2166,19 @@ async def test_recorder_info_migration_queue_exhausted(
migration_done.wait()
return real_migration(*args)
- with patch("homeassistant.components.recorder.ALLOW_IN_MEMORY_DB", True), patch(
- "homeassistant.components.recorder.Recorder.async_periodic_statistics"
- ), patch(
- "homeassistant.components.recorder.core.create_engine",
- new=create_engine_test,
- ), patch.object(recorder.core, "MAX_QUEUE_BACKLOG_MIN_VALUE", 1), patch.object(
- recorder.core, "QUEUE_PERCENTAGE_ALLOWED_AVAILABLE_MEMORY", 0
- ), patch(
- "homeassistant.components.recorder.migration._apply_update",
- wraps=stalled_migration,
+ with (
+ patch("homeassistant.components.recorder.ALLOW_IN_MEMORY_DB", True),
+ patch("homeassistant.components.recorder.Recorder.async_periodic_statistics"),
+ patch(
+ "homeassistant.components.recorder.core.create_engine",
+ new=create_engine_test,
+ ),
+ patch.object(recorder.core, "MAX_QUEUE_BACKLOG_MIN_VALUE", 1),
+ patch.object(recorder.core, "QUEUE_PERCENTAGE_ALLOWED_AVAILABLE_MEMORY", 0),
+ patch(
+ "homeassistant.components.recorder.migration._apply_update",
+ wraps=stalled_migration,
+ ),
):
recorder_helper.async_initialize_recorder(hass)
hass.create_task(
diff --git a/tests/components/refoss/test_config_flow.py b/tests/components/refoss/test_config_flow.py
index e16974a9d71..f022c950635 100644
--- a/tests/components/refoss/test_config_flow.py
+++ b/tests/components/refoss/test_config_flow.py
@@ -14,15 +14,19 @@ async def test_creating_entry_sets_up(
hass: HomeAssistant, mock_setup_entry: AsyncMock
) -> None:
"""Test setting up refoss."""
- with patch(
- "homeassistant.components.refoss.util.Discovery",
- return_value=FakeDiscovery(),
- ), patch(
- "homeassistant.components.refoss.bridge.async_build_base_device",
- return_value=build_base_device_mock(),
- ), patch(
- "homeassistant.components.refoss.switch.isinstance",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.refoss.util.Discovery",
+ return_value=FakeDiscovery(),
+ ),
+ patch(
+ "homeassistant.components.refoss.bridge.async_build_base_device",
+ return_value=build_base_device_mock(),
+ ),
+ patch(
+ "homeassistant.components.refoss.switch.isinstance",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
diff --git a/tests/components/remember_the_milk/test_init.py b/tests/components/remember_the_milk/test_init.py
index bda9f406f4b..c68fe14430a 100644
--- a/tests/components/remember_the_milk/test_init.py
+++ b/tests/components/remember_the_milk/test_init.py
@@ -10,9 +10,11 @@ from .const import JSON_STRING, PROFILE, TOKEN
def test_create_new(hass: HomeAssistant) -> None:
"""Test creating a new config file."""
- with patch("builtins.open", mock_open()), patch(
- "os.path.isfile", Mock(return_value=False)
- ), patch.object(rtm.RememberTheMilkConfiguration, "save_config"):
+ with (
+ patch("builtins.open", mock_open()),
+ patch("os.path.isfile", Mock(return_value=False)),
+ patch.object(rtm.RememberTheMilkConfiguration, "save_config"),
+ ):
config = rtm.RememberTheMilkConfiguration(hass)
config.set_token(PROFILE, TOKEN)
assert config.get_token(PROFILE) == TOKEN
@@ -20,8 +22,9 @@ def test_create_new(hass: HomeAssistant) -> None:
def test_load_config(hass: HomeAssistant) -> None:
"""Test loading an existing token from the file."""
- with patch("builtins.open", mock_open(read_data=JSON_STRING)), patch(
- "os.path.isfile", Mock(return_value=True)
+ with (
+ patch("builtins.open", mock_open(read_data=JSON_STRING)),
+ patch("os.path.isfile", Mock(return_value=True)),
):
config = rtm.RememberTheMilkConfiguration(hass)
assert config.get_token(PROFILE) == TOKEN
@@ -29,8 +32,9 @@ def test_load_config(hass: HomeAssistant) -> None:
def test_invalid_data(hass: HomeAssistant) -> None:
"""Test starts with invalid data and should not raise an exception."""
- with patch("builtins.open", mock_open(read_data="random characters")), patch(
- "os.path.isfile", Mock(return_value=True)
+ with (
+ patch("builtins.open", mock_open(read_data="random characters")),
+ patch("os.path.isfile", Mock(return_value=True)),
):
config = rtm.RememberTheMilkConfiguration(hass)
assert config is not None
@@ -42,9 +46,11 @@ def test_id_map(hass: HomeAssistant) -> None:
list_id = "mylist"
timeseries_id = "my_timeseries"
rtm_id = "rtm-id-4567"
- with patch("builtins.open", mock_open()), patch(
- "os.path.isfile", Mock(return_value=False)
- ), patch.object(rtm.RememberTheMilkConfiguration, "save_config"):
+ with (
+ patch("builtins.open", mock_open()),
+ patch("os.path.isfile", Mock(return_value=False)),
+ patch.object(rtm.RememberTheMilkConfiguration, "save_config"),
+ ):
config = rtm.RememberTheMilkConfiguration(hass)
assert config.get_rtm_id(PROFILE, hass_id) is None
@@ -56,8 +62,9 @@ def test_id_map(hass: HomeAssistant) -> None:
def test_load_key_map(hass: HomeAssistant) -> None:
"""Test loading an existing key map from the file."""
- with patch("builtins.open", mock_open(read_data=JSON_STRING)), patch(
- "os.path.isfile", Mock(return_value=True)
+ with (
+ patch("builtins.open", mock_open(read_data=JSON_STRING)),
+ patch("os.path.isfile", Mock(return_value=True)),
):
config = rtm.RememberTheMilkConfiguration(hass)
assert config.get_rtm_id(PROFILE, "1234") == ("0", "1", "2")
diff --git a/tests/components/renault/conftest.py b/tests/components/renault/conftest.py
index c4855742e5b..c06abc8efd0 100644
--- a/tests/components/renault/conftest.py
+++ b/tests/components/renault/conftest.py
@@ -57,9 +57,12 @@ async def patch_renault_account(hass: HomeAssistant) -> RenaultAccount:
MOCK_ACCOUNT_ID,
websession=aiohttp_client.async_get_clientsession(hass),
)
- with patch("renault_api.renault_session.RenaultSession.login"), patch(
- "renault_api.renault_client.RenaultClient.get_api_account",
- return_value=renault_account,
+ with (
+ patch("renault_api.renault_session.RenaultSession.login"),
+ patch(
+ "renault_api.renault_client.RenaultClient.get_api_account",
+ return_value=renault_account,
+ ),
):
yield renault_account
@@ -125,27 +128,35 @@ def patch_fixtures_with_data(vehicle_type: str):
"""Mock fixtures."""
mock_fixtures = _get_fixtures(vehicle_type)
- with patch(
- "renault_api.renault_vehicle.RenaultVehicle.get_battery_status",
- return_value=mock_fixtures["battery_status"],
- ), patch(
- "renault_api.renault_vehicle.RenaultVehicle.get_charge_mode",
- return_value=mock_fixtures["charge_mode"],
- ), patch(
- "renault_api.renault_vehicle.RenaultVehicle.get_cockpit",
- return_value=mock_fixtures["cockpit"],
- ), patch(
- "renault_api.renault_vehicle.RenaultVehicle.get_hvac_status",
- return_value=mock_fixtures["hvac_status"],
- ), patch(
- "renault_api.renault_vehicle.RenaultVehicle.get_location",
- return_value=mock_fixtures["location"],
- ), patch(
- "renault_api.renault_vehicle.RenaultVehicle.get_lock_status",
- return_value=mock_fixtures["lock_status"],
- ), patch(
- "renault_api.renault_vehicle.RenaultVehicle.get_res_state",
- return_value=mock_fixtures["res_state"],
+ with (
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.get_battery_status",
+ return_value=mock_fixtures["battery_status"],
+ ),
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.get_charge_mode",
+ return_value=mock_fixtures["charge_mode"],
+ ),
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.get_cockpit",
+ return_value=mock_fixtures["cockpit"],
+ ),
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.get_hvac_status",
+ return_value=mock_fixtures["hvac_status"],
+ ),
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.get_location",
+ return_value=mock_fixtures["location"],
+ ),
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.get_lock_status",
+ return_value=mock_fixtures["lock_status"],
+ ),
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.get_res_state",
+ return_value=mock_fixtures["res_state"],
+ ),
):
yield
@@ -155,27 +166,35 @@ def patch_fixtures_with_no_data():
"""Mock fixtures."""
mock_fixtures = _get_fixtures("")
- with patch(
- "renault_api.renault_vehicle.RenaultVehicle.get_battery_status",
- return_value=mock_fixtures["battery_status"],
- ), patch(
- "renault_api.renault_vehicle.RenaultVehicle.get_charge_mode",
- return_value=mock_fixtures["charge_mode"],
- ), patch(
- "renault_api.renault_vehicle.RenaultVehicle.get_cockpit",
- return_value=mock_fixtures["cockpit"],
- ), patch(
- "renault_api.renault_vehicle.RenaultVehicle.get_hvac_status",
- return_value=mock_fixtures["hvac_status"],
- ), patch(
- "renault_api.renault_vehicle.RenaultVehicle.get_location",
- return_value=mock_fixtures["location"],
- ), patch(
- "renault_api.renault_vehicle.RenaultVehicle.get_lock_status",
- return_value=mock_fixtures["lock_status"],
- ), patch(
- "renault_api.renault_vehicle.RenaultVehicle.get_res_state",
- return_value=mock_fixtures["res_state"],
+ with (
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.get_battery_status",
+ return_value=mock_fixtures["battery_status"],
+ ),
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.get_charge_mode",
+ return_value=mock_fixtures["charge_mode"],
+ ),
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.get_cockpit",
+ return_value=mock_fixtures["cockpit"],
+ ),
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.get_hvac_status",
+ return_value=mock_fixtures["hvac_status"],
+ ),
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.get_location",
+ return_value=mock_fixtures["location"],
+ ),
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.get_lock_status",
+ return_value=mock_fixtures["lock_status"],
+ ),
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.get_res_state",
+ return_value=mock_fixtures["res_state"],
+ ),
):
yield
@@ -183,27 +202,35 @@ def patch_fixtures_with_no_data():
@contextlib.contextmanager
def _patch_fixtures_with_side_effect(side_effect: Any):
"""Mock fixtures."""
- with patch(
- "renault_api.renault_vehicle.RenaultVehicle.get_battery_status",
- side_effect=side_effect,
- ), patch(
- "renault_api.renault_vehicle.RenaultVehicle.get_charge_mode",
- side_effect=side_effect,
- ), patch(
- "renault_api.renault_vehicle.RenaultVehicle.get_cockpit",
- side_effect=side_effect,
- ), patch(
- "renault_api.renault_vehicle.RenaultVehicle.get_hvac_status",
- side_effect=side_effect,
- ), patch(
- "renault_api.renault_vehicle.RenaultVehicle.get_location",
- side_effect=side_effect,
- ), patch(
- "renault_api.renault_vehicle.RenaultVehicle.get_lock_status",
- side_effect=side_effect,
- ), patch(
- "renault_api.renault_vehicle.RenaultVehicle.get_res_state",
- side_effect=side_effect,
+ with (
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.get_battery_status",
+ side_effect=side_effect,
+ ),
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.get_charge_mode",
+ side_effect=side_effect,
+ ),
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.get_cockpit",
+ side_effect=side_effect,
+ ),
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.get_hvac_status",
+ side_effect=side_effect,
+ ),
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.get_location",
+ side_effect=side_effect,
+ ),
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.get_lock_status",
+ side_effect=side_effect,
+ ),
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.get_res_state",
+ side_effect=side_effect,
+ ),
):
yield
diff --git a/tests/components/renault/test_config_flow.py b/tests/components/renault/test_config_flow.py
index 48b20071525..eca7991a27c 100644
--- a/tests/components/renault/test_config_flow.py
+++ b/tests/components/renault/test_config_flow.py
@@ -61,11 +61,15 @@ async def test_config_flow_single_account(
)
# Account list single
- with patch("renault_api.renault_session.RenaultSession.login"), patch(
- "renault_api.renault_account.RenaultAccount.account_id", return_value="123"
- ), patch(
- "renault_api.renault_client.RenaultClient.get_api_accounts",
- return_value=[renault_account],
+ with (
+ patch("renault_api.renault_session.RenaultSession.login"),
+ patch(
+ "renault_api.renault_account.RenaultAccount.account_id", return_value="123"
+ ),
+ patch(
+ "renault_api.renault_client.RenaultClient.get_api_accounts",
+ return_value=[renault_account],
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -97,9 +101,12 @@ async def test_config_flow_no_account(
assert result["errors"] == {}
# Account list empty
- with patch("renault_api.renault_session.RenaultSession.login"), patch(
- "renault_api.renault_client.RenaultClient.get_api_accounts",
- return_value=[],
+ with (
+ patch("renault_api.renault_session.RenaultSession.login"),
+ patch(
+ "renault_api.renault_client.RenaultClient.get_api_accounts",
+ return_value=[],
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -136,10 +143,14 @@ async def test_config_flow_multiple_accounts(
)
# Multiple accounts
- with patch("renault_api.renault_session.RenaultSession.login"), patch(
- "renault_api.renault_client.RenaultClient.get_api_accounts",
- return_value=[renault_account_1, renault_account_2],
- ), patch("renault_api.renault_account.RenaultAccount.get_vehicles"):
+ with (
+ patch("renault_api.renault_session.RenaultSession.login"),
+ patch(
+ "renault_api.renault_client.RenaultClient.get_api_accounts",
+ return_value=[renault_account_1, renault_account_2],
+ ),
+ patch("renault_api.renault_account.RenaultAccount.get_vehicles"),
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
@@ -184,10 +195,14 @@ async def test_config_flow_duplicate(
"account_id_1",
websession=aiohttp_client.async_get_clientsession(hass),
)
- with patch("renault_api.renault_session.RenaultSession.login"), patch(
- "renault_api.renault_client.RenaultClient.get_api_accounts",
- return_value=[renault_account],
- ), patch("renault_api.renault_account.RenaultAccount.get_vehicles"):
+ with (
+ patch("renault_api.renault_session.RenaultSession.login"),
+ patch(
+ "renault_api.renault_client.RenaultClient.get_api_accounts",
+ return_value=[renault_account],
+ ),
+ patch("renault_api.renault_account.RenaultAccount.get_vehicles"),
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
diff --git a/tests/components/renault/test_services.py b/tests/components/renault/test_services.py
index 0dba6a9adae..e97988a09f7 100644
--- a/tests/components/renault/test_services.py
+++ b/tests/components/renault/test_services.py
@@ -90,10 +90,13 @@ async def test_service_set_ac_cancel(
ATTR_VEHICLE: get_device_id(hass),
}
- with patch(
- "renault_api.renault_vehicle.RenaultVehicle.set_ac_stop",
- side_effect=RenaultException("Didn't work"),
- ) as mock_action, pytest.raises(HomeAssistantError, match="Didn't work"):
+ with (
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.set_ac_stop",
+ side_effect=RenaultException("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
)
@@ -172,19 +175,22 @@ async def test_service_set_charge_schedule(
ATTR_SCHEDULES: schedules,
}
- with patch(
- "renault_api.renault_vehicle.RenaultVehicle.get_charging_settings",
- return_value=schemas.KamereonVehicleDataResponseSchema.loads(
- load_fixture("renault/charging_settings.json")
- ).get_attributes(schemas.KamereonVehicleChargingSettingsDataSchema),
- ), patch(
- "renault_api.renault_vehicle.RenaultVehicle.set_charge_schedules",
- return_value=(
- schemas.KamereonVehicleHvacStartActionDataSchema.loads(
- load_fixture("renault/action.set_charge_schedules.json")
- )
+ with (
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.get_charging_settings",
+ return_value=schemas.KamereonVehicleDataResponseSchema.loads(
+ load_fixture("renault/charging_settings.json")
+ ).get_attributes(schemas.KamereonVehicleChargingSettingsDataSchema),
),
- ) as mock_action:
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.set_charge_schedules",
+ return_value=(
+ schemas.KamereonVehicleHvacStartActionDataSchema.loads(
+ load_fixture("renault/action.set_charge_schedules.json")
+ )
+ ),
+ ) as mock_action,
+ ):
await hass.services.async_call(
DOMAIN, SERVICE_CHARGE_SET_SCHEDULES, service_data=data, blocking=True
)
@@ -218,19 +224,22 @@ async def test_service_set_charge_schedule_multi(
ATTR_SCHEDULES: schedules,
}
- with patch(
- "renault_api.renault_vehicle.RenaultVehicle.get_charging_settings",
- return_value=schemas.KamereonVehicleDataResponseSchema.loads(
- load_fixture("renault/charging_settings.json")
- ).get_attributes(schemas.KamereonVehicleChargingSettingsDataSchema),
- ), patch(
- "renault_api.renault_vehicle.RenaultVehicle.set_charge_schedules",
- return_value=(
- schemas.KamereonVehicleHvacStartActionDataSchema.loads(
- load_fixture("renault/action.set_charge_schedules.json")
- )
+ with (
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.get_charging_settings",
+ return_value=schemas.KamereonVehicleDataResponseSchema.loads(
+ load_fixture("renault/charging_settings.json")
+ ).get_attributes(schemas.KamereonVehicleChargingSettingsDataSchema),
),
- ) as mock_action:
+ patch(
+ "renault_api.renault_vehicle.RenaultVehicle.set_charge_schedules",
+ return_value=(
+ schemas.KamereonVehicleHvacStartActionDataSchema.loads(
+ load_fixture("renault/action.set_charge_schedules.json")
+ )
+ ),
+ ) as mock_action,
+ ):
await hass.services.async_call(
DOMAIN, SERVICE_CHARGE_SET_SCHEDULES, service_data=data, blocking=True
)
diff --git a/tests/components/renson/test_config_flow.py b/tests/components/renson/test_config_flow.py
index 185d21aead8..6d51605824e 100644
--- a/tests/components/renson/test_config_flow.py
+++ b/tests/components/renson/test_config_flow.py
@@ -16,13 +16,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with patch(
- "homeassistant.components.renson.config_flow.renson",
- return_value={"title": "Renson"},
- ), patch(
- "homeassistant.components.renson.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.renson.config_flow.renson",
+ return_value={"title": "Renson"},
+ ),
+ patch(
+ "homeassistant.components.renson.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
diff --git a/tests/components/reolink/conftest.py b/tests/components/reolink/conftest.py
index a340e8cebbe..5fd52b97b6b 100644
--- a/tests/components/reolink/conftest.py
+++ b/tests/components/reolink/conftest.py
@@ -51,12 +51,15 @@ def reolink_connect_class(
mock_get_source_ip: None,
) -> Generator[MagicMock, None, None]:
"""Mock reolink connection and return both the host_mock and host_mock_class."""
- with patch(
- "homeassistant.components.reolink.host.webhook.async_register",
- return_value=True,
- ), patch(
- "homeassistant.components.reolink.host.Host", autospec=True
- ) as host_mock_class:
+ with (
+ patch(
+ "homeassistant.components.reolink.host.webhook.async_register",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.reolink.host.Host", autospec=True
+ ) as host_mock_class,
+ ):
host_mock = host_mock_class.return_value
host_mock.get_host_data.return_value = None
host_mock.get_states.return_value = None
diff --git a/tests/components/reolink/test_init.py b/tests/components/reolink/test_init.py
index abf97ee96ca..8ebce5d350e 100644
--- a/tests/components/reolink/test_init.py
+++ b/tests/components/reolink/test_init.py
@@ -236,12 +236,14 @@ async def test_https_repair_issue(
hass, {"country": "GB", "internal_url": "https://test_homeassistant_address"}
)
- with patch(
- "homeassistant.components.reolink.host.FIRST_ONVIF_TIMEOUT", new=0
- ), patch(
- "homeassistant.components.reolink.host.FIRST_ONVIF_LONG_POLL_TIMEOUT", new=0
- ), patch(
- "homeassistant.components.reolink.host.ReolinkHost._async_long_polling",
+ with (
+ patch("homeassistant.components.reolink.host.FIRST_ONVIF_TIMEOUT", new=0),
+ patch(
+ "homeassistant.components.reolink.host.FIRST_ONVIF_LONG_POLL_TIMEOUT", new=0
+ ),
+ patch(
+ "homeassistant.components.reolink.host.ReolinkHost._async_long_polling",
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -261,12 +263,14 @@ async def test_ssl_repair_issue(
hass, {"country": "GB", "internal_url": "http://test_homeassistant_address"}
)
- with patch(
- "homeassistant.components.reolink.host.FIRST_ONVIF_TIMEOUT", new=0
- ), patch(
- "homeassistant.components.reolink.host.FIRST_ONVIF_LONG_POLL_TIMEOUT", new=0
- ), patch(
- "homeassistant.components.reolink.host.ReolinkHost._async_long_polling",
+ with (
+ patch("homeassistant.components.reolink.host.FIRST_ONVIF_TIMEOUT", new=0),
+ patch(
+ "homeassistant.components.reolink.host.FIRST_ONVIF_LONG_POLL_TIMEOUT", new=0
+ ),
+ patch(
+ "homeassistant.components.reolink.host.ReolinkHost._async_long_polling",
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -299,12 +303,14 @@ async def test_webhook_repair_issue(
hass: HomeAssistant, config_entry: MockConfigEntry
) -> None:
"""Test repairs issue is raised when the webhook url is unreachable."""
- with patch(
- "homeassistant.components.reolink.host.FIRST_ONVIF_TIMEOUT", new=0
- ), patch(
- "homeassistant.components.reolink.host.FIRST_ONVIF_LONG_POLL_TIMEOUT", new=0
- ), patch(
- "homeassistant.components.reolink.host.ReolinkHost._async_long_polling",
+ with (
+ patch("homeassistant.components.reolink.host.FIRST_ONVIF_TIMEOUT", new=0),
+ patch(
+ "homeassistant.components.reolink.host.FIRST_ONVIF_LONG_POLL_TIMEOUT", new=0
+ ),
+ patch(
+ "homeassistant.components.reolink.host.ReolinkHost._async_long_polling",
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/rfxtrx/conftest.py b/tests/components/rfxtrx/conftest.py
index 536672b66cd..5e0223173f9 100644
--- a/tests/components/rfxtrx/conftest.py
+++ b/tests/components/rfxtrx/conftest.py
@@ -69,8 +69,9 @@ async def setup_rfx_test_cfg(
async def transport_mock(hass):
"""Fixture that make sure all transports are fake."""
transport = Mock(spec=RFXtrxTransport)
- with patch("RFXtrx.PySerialTransport", new=transport), patch(
- "RFXtrx.PyNetworkTransport", transport
+ with (
+ patch("RFXtrx.PySerialTransport", new=transport),
+ patch("RFXtrx.PyNetworkTransport", transport),
):
yield transport
diff --git a/tests/components/ridwell/conftest.py b/tests/components/ridwell/conftest.py
index aed5a00b1a8..32907ac8037 100644
--- a/tests/components/ridwell/conftest.py
+++ b/tests/components/ridwell/conftest.py
@@ -79,12 +79,15 @@ def config_fixture(hass):
@pytest.fixture(name="mock_aioridwell")
async def mock_aioridwell_fixture(hass, client, config):
"""Define a fixture to patch aioridwell."""
- with patch(
- "homeassistant.components.ridwell.config_flow.async_get_client",
- return_value=client,
- ), patch(
- "homeassistant.components.ridwell.coordinator.async_get_client",
- return_value=client,
+ with (
+ patch(
+ "homeassistant.components.ridwell.config_flow.async_get_client",
+ return_value=client,
+ ),
+ patch(
+ "homeassistant.components.ridwell.coordinator.async_get_client",
+ return_value=client,
+ ),
):
yield
diff --git a/tests/components/risco/conftest.py b/tests/components/risco/conftest.py
index 6d810ec6abd..ab3b64b245d 100644
--- a/tests/components/risco/conftest.py
+++ b/tests/components/risco/conftest.py
@@ -36,25 +36,30 @@ def two_zone_cloud():
"""Fixture to mock alarm with two zones."""
zone_mocks = {0: zone_mock(), 1: zone_mock()}
alarm_mock = MagicMock()
- with patch.object(
- zone_mocks[0], "id", new_callable=PropertyMock(return_value=0)
- ), patch.object(
- zone_mocks[0], "name", new_callable=PropertyMock(return_value="Zone 0")
- ), patch.object(
- zone_mocks[0], "bypassed", new_callable=PropertyMock(return_value=False)
- ), patch.object(
- zone_mocks[1], "id", new_callable=PropertyMock(return_value=1)
- ), patch.object(
- zone_mocks[1], "name", new_callable=PropertyMock(return_value="Zone 1")
- ), patch.object(
- zone_mocks[1], "bypassed", new_callable=PropertyMock(return_value=False)
- ), patch.object(
- alarm_mock,
- "zones",
- new_callable=PropertyMock(return_value=zone_mocks),
- ), patch(
- "homeassistant.components.risco.RiscoCloud.get_state",
- return_value=alarm_mock,
+ with (
+ patch.object(zone_mocks[0], "id", new_callable=PropertyMock(return_value=0)),
+ patch.object(
+ zone_mocks[0], "name", new_callable=PropertyMock(return_value="Zone 0")
+ ),
+ patch.object(
+ zone_mocks[0], "bypassed", new_callable=PropertyMock(return_value=False)
+ ),
+ patch.object(zone_mocks[1], "id", new_callable=PropertyMock(return_value=1)),
+ patch.object(
+ zone_mocks[1], "name", new_callable=PropertyMock(return_value="Zone 1")
+ ),
+ patch.object(
+ zone_mocks[1], "bypassed", new_callable=PropertyMock(return_value=False)
+ ),
+ patch.object(
+ alarm_mock,
+ "zones",
+ new_callable=PropertyMock(return_value=zone_mocks),
+ ),
+ patch(
+ "homeassistant.components.risco.RiscoCloud.get_state",
+ return_value=alarm_mock,
+ ),
):
yield zone_mocks
@@ -64,37 +69,48 @@ def two_zone_local():
"""Fixture to mock alarm with two zones."""
zone_mocks = {0: zone_mock(), 1: zone_mock()}
system = system_mock()
- with patch.object(
- zone_mocks[0], "id", new_callable=PropertyMock(return_value=0)
- ), patch.object(
- zone_mocks[0], "name", new_callable=PropertyMock(return_value="Zone 0")
- ), patch.object(
- zone_mocks[0], "alarmed", new_callable=PropertyMock(return_value=False)
- ), patch.object(
- zone_mocks[0], "bypassed", new_callable=PropertyMock(return_value=False)
- ), patch.object(
- zone_mocks[0], "armed", new_callable=PropertyMock(return_value=False)
- ), patch.object(
- zone_mocks[1], "id", new_callable=PropertyMock(return_value=1)
- ), patch.object(
- zone_mocks[1], "name", new_callable=PropertyMock(return_value="Zone 1")
- ), patch.object(
- zone_mocks[1], "alarmed", new_callable=PropertyMock(return_value=False)
- ), patch.object(
- zone_mocks[1], "bypassed", new_callable=PropertyMock(return_value=False)
- ), patch.object(
- zone_mocks[1], "armed", new_callable=PropertyMock(return_value=False)
- ), patch.object(
- system, "name", new_callable=PropertyMock(return_value=TEST_SITE_NAME)
- ), patch(
- "homeassistant.components.risco.RiscoLocal.partitions",
- new_callable=PropertyMock(return_value={}),
- ), patch(
- "homeassistant.components.risco.RiscoLocal.zones",
- new_callable=PropertyMock(return_value=zone_mocks),
- ), patch(
- "homeassistant.components.risco.RiscoLocal.system",
- new_callable=PropertyMock(return_value=system),
+ with (
+ patch.object(zone_mocks[0], "id", new_callable=PropertyMock(return_value=0)),
+ patch.object(
+ zone_mocks[0], "name", new_callable=PropertyMock(return_value="Zone 0")
+ ),
+ patch.object(
+ zone_mocks[0], "alarmed", new_callable=PropertyMock(return_value=False)
+ ),
+ patch.object(
+ zone_mocks[0], "bypassed", new_callable=PropertyMock(return_value=False)
+ ),
+ patch.object(
+ zone_mocks[0], "armed", new_callable=PropertyMock(return_value=False)
+ ),
+ patch.object(zone_mocks[1], "id", new_callable=PropertyMock(return_value=1)),
+ patch.object(
+ zone_mocks[1], "name", new_callable=PropertyMock(return_value="Zone 1")
+ ),
+ patch.object(
+ zone_mocks[1], "alarmed", new_callable=PropertyMock(return_value=False)
+ ),
+ patch.object(
+ zone_mocks[1], "bypassed", new_callable=PropertyMock(return_value=False)
+ ),
+ patch.object(
+ zone_mocks[1], "armed", new_callable=PropertyMock(return_value=False)
+ ),
+ patch.object(
+ system, "name", new_callable=PropertyMock(return_value=TEST_SITE_NAME)
+ ),
+ patch(
+ "homeassistant.components.risco.RiscoLocal.partitions",
+ new_callable=PropertyMock(return_value={}),
+ ),
+ patch(
+ "homeassistant.components.risco.RiscoLocal.zones",
+ new_callable=PropertyMock(return_value=zone_mocks),
+ ),
+ patch(
+ "homeassistant.components.risco.RiscoLocal.system",
+ new_callable=PropertyMock(return_value=system),
+ ),
):
yield zone_mocks
@@ -137,20 +153,26 @@ def login_with_error(exception):
@pytest.fixture
async def setup_risco_cloud(hass, cloud_config_entry, events):
"""Set up a Risco integration for testing."""
- with patch(
- "homeassistant.components.risco.RiscoCloud.login",
- return_value=True,
- ), patch(
- "homeassistant.components.risco.RiscoCloud.site_uuid",
- new_callable=PropertyMock(return_value=TEST_SITE_UUID),
- ), patch(
- "homeassistant.components.risco.RiscoCloud.site_name",
- new_callable=PropertyMock(return_value=TEST_SITE_NAME),
- ), patch(
- "homeassistant.components.risco.RiscoCloud.close",
- ), patch(
- "homeassistant.components.risco.RiscoCloud.get_events",
- return_value=events,
+ with (
+ patch(
+ "homeassistant.components.risco.RiscoCloud.login",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.risco.RiscoCloud.site_uuid",
+ new_callable=PropertyMock(return_value=TEST_SITE_UUID),
+ ),
+ patch(
+ "homeassistant.components.risco.RiscoCloud.site_name",
+ new_callable=PropertyMock(return_value=TEST_SITE_NAME),
+ ),
+ patch(
+ "homeassistant.components.risco.RiscoCloud.close",
+ ),
+ patch(
+ "homeassistant.components.risco.RiscoCloud.get_events",
+ return_value=events,
+ ),
):
await hass.config_entries.async_setup(cloud_config_entry.entry_id)
await hass.async_block_till_done()
@@ -181,14 +203,18 @@ def connect_with_error(exception):
@pytest.fixture
async def setup_risco_local(hass, local_config_entry):
"""Set up a local Risco integration for testing."""
- with patch(
- "homeassistant.components.risco.RiscoLocal.connect",
- return_value=True,
- ), patch(
- "homeassistant.components.risco.RiscoLocal.id",
- new_callable=PropertyMock(return_value=TEST_SITE_UUID),
- ), patch(
- "homeassistant.components.risco.RiscoLocal.disconnect",
+ with (
+ patch(
+ "homeassistant.components.risco.RiscoLocal.connect",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.risco.RiscoLocal.id",
+ new_callable=PropertyMock(return_value=TEST_SITE_UUID),
+ ),
+ patch(
+ "homeassistant.components.risco.RiscoLocal.disconnect",
+ ),
):
await hass.config_entries.async_setup(local_config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/risco/test_alarm_control_panel.py b/tests/components/risco/test_alarm_control_panel.py
index ee8b844c167..ff831b59062 100644
--- a/tests/components/risco/test_alarm_control_panel.py
+++ b/tests/components/risco/test_alarm_control_panel.py
@@ -92,17 +92,22 @@ def two_part_cloud_alarm():
"""Fixture to mock alarm with two partitions."""
partition_mocks = {0: _partition_mock(), 1: _partition_mock()}
alarm_mock = MagicMock()
- with patch.object(
- partition_mocks[0], "id", new_callable=PropertyMock(return_value=0)
- ), patch.object(
- partition_mocks[1], "id", new_callable=PropertyMock(return_value=1)
- ), patch.object(
- alarm_mock,
- "partitions",
- new_callable=PropertyMock(return_value=partition_mocks),
- ), patch(
- "homeassistant.components.risco.RiscoCloud.get_state",
- return_value=alarm_mock,
+ with (
+ patch.object(
+ partition_mocks[0], "id", new_callable=PropertyMock(return_value=0)
+ ),
+ patch.object(
+ partition_mocks[1], "id", new_callable=PropertyMock(return_value=1)
+ ),
+ patch.object(
+ alarm_mock,
+ "partitions",
+ new_callable=PropertyMock(return_value=partition_mocks),
+ ),
+ patch(
+ "homeassistant.components.risco.RiscoCloud.get_state",
+ return_value=alarm_mock,
+ ),
):
yield partition_mocks
@@ -111,20 +116,27 @@ def two_part_cloud_alarm():
def two_part_local_alarm():
"""Fixture to mock alarm with two partitions."""
partition_mocks = {0: _partition_mock(), 1: _partition_mock()}
- with patch.object(
- partition_mocks[0], "id", new_callable=PropertyMock(return_value=0)
- ), patch.object(
- partition_mocks[0], "name", new_callable=PropertyMock(return_value="Name 0")
- ), patch.object(
- partition_mocks[1], "id", new_callable=PropertyMock(return_value=1)
- ), patch.object(
- partition_mocks[1], "name", new_callable=PropertyMock(return_value="Name 1")
- ), patch(
- "homeassistant.components.risco.RiscoLocal.zones",
- new_callable=PropertyMock(return_value={}),
- ), patch(
- "homeassistant.components.risco.RiscoLocal.partitions",
- new_callable=PropertyMock(return_value=partition_mocks),
+ with (
+ patch.object(
+ partition_mocks[0], "id", new_callable=PropertyMock(return_value=0)
+ ),
+ patch.object(
+ partition_mocks[0], "name", new_callable=PropertyMock(return_value="Name 0")
+ ),
+ patch.object(
+ partition_mocks[1], "id", new_callable=PropertyMock(return_value=1)
+ ),
+ patch.object(
+ partition_mocks[1], "name", new_callable=PropertyMock(return_value="Name 1")
+ ),
+ patch(
+ "homeassistant.components.risco.RiscoLocal.zones",
+ new_callable=PropertyMock(return_value={}),
+ ),
+ patch(
+ "homeassistant.components.risco.RiscoLocal.partitions",
+ new_callable=PropertyMock(return_value=partition_mocks),
+ ),
):
yield partition_mocks
diff --git a/tests/components/risco/test_binary_sensor.py b/tests/components/risco/test_binary_sensor.py
index eae4ef5e472..ea18c59e236 100644
--- a/tests/components/risco/test_binary_sensor.py
+++ b/tests/components/risco/test_binary_sensor.py
@@ -237,17 +237,22 @@ def mock_system_handler():
def system_only_local():
"""Fixture to mock a system with no zones or partitions."""
system = system_mock()
- with patch.object(
- system, "name", new_callable=PropertyMock(return_value=TEST_SITE_NAME)
- ), patch(
- "homeassistant.components.risco.RiscoLocal.zones",
- new_callable=PropertyMock(return_value={}),
- ), patch(
- "homeassistant.components.risco.RiscoLocal.partitions",
- new_callable=PropertyMock(return_value={}),
- ), patch(
- "homeassistant.components.risco.RiscoLocal.system",
- new_callable=PropertyMock(return_value=system),
+ with (
+ patch.object(
+ system, "name", new_callable=PropertyMock(return_value=TEST_SITE_NAME)
+ ),
+ patch(
+ "homeassistant.components.risco.RiscoLocal.zones",
+ new_callable=PropertyMock(return_value={}),
+ ),
+ patch(
+ "homeassistant.components.risco.RiscoLocal.partitions",
+ new_callable=PropertyMock(return_value={}),
+ ),
+ patch(
+ "homeassistant.components.risco.RiscoLocal.system",
+ new_callable=PropertyMock(return_value=system),
+ ),
):
yield system
diff --git a/tests/components/risco/test_config_flow.py b/tests/components/risco/test_config_flow.py
index d4dd4e3fac5..d031f4e8542 100644
--- a/tests/components/risco/test_config_flow.py
+++ b/tests/components/risco/test_config_flow.py
@@ -66,18 +66,23 @@ async def test_cloud_form(hass: HomeAssistant) -> None:
assert result2["type"] == FlowResultType.FORM
assert result2["errors"] == {}
- with patch(
- "homeassistant.components.risco.config_flow.RiscoCloud.login",
- return_value=True,
- ), patch(
- "homeassistant.components.risco.config_flow.RiscoCloud.site_name",
- new_callable=PropertyMock(return_value=TEST_SITE_NAME),
- ), patch(
- "homeassistant.components.risco.config_flow.RiscoCloud.close"
- ) as mock_close, patch(
- "homeassistant.components.risco.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.risco.config_flow.RiscoCloud.login",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.risco.config_flow.RiscoCloud.site_name",
+ new_callable=PropertyMock(return_value=TEST_SITE_NAME),
+ ),
+ patch(
+ "homeassistant.components.risco.config_flow.RiscoCloud.close"
+ ) as mock_close,
+ patch(
+ "homeassistant.components.risco.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"], TEST_CLOUD_DATA
)
@@ -156,18 +161,23 @@ async def test_form_reauth(hass: HomeAssistant, cloud_config_entry) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.risco.config_flow.RiscoCloud.login",
- return_value=True,
- ), patch(
- "homeassistant.components.risco.config_flow.RiscoCloud.site_name",
- new_callable=PropertyMock(return_value=TEST_SITE_NAME),
- ), patch(
- "homeassistant.components.risco.config_flow.RiscoCloud.close",
- ), patch(
- "homeassistant.components.risco.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.risco.config_flow.RiscoCloud.login",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.risco.config_flow.RiscoCloud.site_name",
+ new_callable=PropertyMock(return_value=TEST_SITE_NAME),
+ ),
+ patch(
+ "homeassistant.components.risco.config_flow.RiscoCloud.close",
+ ),
+ patch(
+ "homeassistant.components.risco.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], {**TEST_CLOUD_DATA, CONF_PASSWORD: "new_password"}
)
@@ -192,18 +202,23 @@ async def test_form_reauth_with_new_username(
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.risco.config_flow.RiscoCloud.login",
- return_value=True,
- ), patch(
- "homeassistant.components.risco.config_flow.RiscoCloud.site_name",
- new_callable=PropertyMock(return_value=TEST_SITE_NAME),
- ), patch(
- "homeassistant.components.risco.config_flow.RiscoCloud.close",
- ), patch(
- "homeassistant.components.risco.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.risco.config_flow.RiscoCloud.login",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.risco.config_flow.RiscoCloud.site_name",
+ new_callable=PropertyMock(return_value=TEST_SITE_NAME),
+ ),
+ patch(
+ "homeassistant.components.risco.config_flow.RiscoCloud.close",
+ ),
+ patch(
+ "homeassistant.components.risco.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], {**TEST_CLOUD_DATA, CONF_USERNAME: "new_user"}
)
@@ -230,18 +245,23 @@ async def test_local_form(hass: HomeAssistant) -> None:
assert result2["type"] == FlowResultType.FORM
assert result2["errors"] == {}
- with patch(
- "homeassistant.components.risco.config_flow.RiscoLocal.connect",
- return_value=True,
- ), patch(
- "homeassistant.components.risco.config_flow.RiscoLocal.id",
- new_callable=PropertyMock(return_value=TEST_SITE_NAME),
- ), patch(
- "homeassistant.components.risco.config_flow.RiscoLocal.disconnect"
- ) as mock_close, patch(
- "homeassistant.components.risco.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.risco.config_flow.RiscoLocal.connect",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.risco.config_flow.RiscoLocal.id",
+ new_callable=PropertyMock(return_value=TEST_SITE_NAME),
+ ),
+ patch(
+ "homeassistant.components.risco.config_flow.RiscoLocal.disconnect"
+ ) as mock_close,
+ patch(
+ "homeassistant.components.risco.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"], TEST_LOCAL_DATA
)
@@ -302,14 +322,18 @@ async def test_form_local_already_exists(hass: HomeAssistant) -> None:
result["flow_id"], {"next_step_id": "local"}
)
- with patch(
- "homeassistant.components.risco.config_flow.RiscoLocal.connect",
- return_value=True,
- ), patch(
- "homeassistant.components.risco.config_flow.RiscoLocal.id",
- new_callable=PropertyMock(return_value=TEST_SITE_NAME),
- ), patch(
- "homeassistant.components.risco.config_flow.RiscoLocal.disconnect",
+ with (
+ patch(
+ "homeassistant.components.risco.config_flow.RiscoLocal.connect",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.risco.config_flow.RiscoLocal.id",
+ new_callable=PropertyMock(return_value=TEST_SITE_NAME),
+ ),
+ patch(
+ "homeassistant.components.risco.config_flow.RiscoLocal.disconnect",
+ ),
):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"], TEST_LOCAL_DATA
diff --git a/tests/components/risco/test_sensor.py b/tests/components/risco/test_sensor.py
index be909254d70..157eb3e62b5 100644
--- a/tests/components/risco/test_sensor.py
+++ b/tests/components/risco/test_sensor.py
@@ -111,12 +111,15 @@ CATEGORIES_TO_EVENTS = {
@pytest.fixture
def _no_zones_and_partitions():
- with patch(
- "homeassistant.components.risco.RiscoLocal.zones",
- new_callable=PropertyMock(return_value=[]),
- ), patch(
- "homeassistant.components.risco.RiscoLocal.partitions",
- new_callable=PropertyMock(return_value=[]),
+ with (
+ patch(
+ "homeassistant.components.risco.RiscoLocal.zones",
+ new_callable=PropertyMock(return_value=[]),
+ ),
+ patch(
+ "homeassistant.components.risco.RiscoLocal.partitions",
+ new_callable=PropertyMock(return_value=[]),
+ ),
):
yield
@@ -188,11 +191,14 @@ async def test_cloud_setup(
for category, entity_id in ENTITY_IDS.items():
_check_state(hass, category, entity_id)
- with patch(
- "homeassistant.components.risco.RiscoCloud.get_events", return_value=[]
- ) as events_mock, patch(
- "homeassistant.components.risco.Store.async_load",
- return_value={LAST_EVENT_TIMESTAMP_KEY: TEST_EVENTS[0].time},
+ with (
+ patch(
+ "homeassistant.components.risco.RiscoCloud.get_events", return_value=[]
+ ) as events_mock,
+ patch(
+ "homeassistant.components.risco.Store.async_load",
+ return_value={LAST_EVENT_TIMESTAMP_KEY: TEST_EVENTS[0].time},
+ ),
):
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=65))
await hass.async_block_till_done()
diff --git a/tests/components/rituals_perfume_genie/test_config_flow.py b/tests/components/rituals_perfume_genie/test_config_flow.py
index b601c6c7c47..45f14399f15 100644
--- a/tests/components/rituals_perfume_genie/test_config_flow.py
+++ b/tests/components/rituals_perfume_genie/test_config_flow.py
@@ -32,13 +32,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] is None
- with patch(
- "homeassistant.components.rituals_perfume_genie.config_flow.Account",
- side_effect=_mock_account,
- ), patch(
- "homeassistant.components.rituals_perfume_genie.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.rituals_perfume_genie.config_flow.Account",
+ side_effect=_mock_account,
+ ),
+ patch(
+ "homeassistant.components.rituals_perfume_genie.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
diff --git a/tests/components/roborock/conftest.py b/tests/components/roborock/conftest.py
index b556804e46a..91331a1486a 100644
--- a/tests/components/roborock/conftest.py
+++ b/tests/components/roborock/conftest.py
@@ -30,41 +30,50 @@ from tests.common import MockConfigEntry
@pytest.fixture(name="bypass_api_fixture")
def bypass_api_fixture() -> None:
"""Skip calls to the API."""
- with patch(
- "homeassistant.components.roborock.RoborockMqttClient.async_connect"
- ), patch(
- "homeassistant.components.roborock.RoborockMqttClient._send_command"
- ), patch(
- "homeassistant.components.roborock.RoborockApiClient.get_home_data",
- return_value=HOME_DATA,
- ), patch(
- "homeassistant.components.roborock.RoborockMqttClient.get_networking",
- return_value=NETWORK_INFO,
- ), patch(
- "homeassistant.components.roborock.coordinator.RoborockLocalClient.get_prop",
- return_value=PROP,
- ), patch(
- "homeassistant.components.roborock.coordinator.RoborockMqttClient.get_multi_maps_list",
- return_value=MULTI_MAP_LIST,
- ), patch(
- "homeassistant.components.roborock.coordinator.RoborockLocalClient.get_multi_maps_list",
- return_value=MULTI_MAP_LIST,
- ), patch(
- "homeassistant.components.roborock.image.RoborockMapDataParser.parse",
- return_value=MAP_DATA,
- ), patch(
- "homeassistant.components.roborock.coordinator.RoborockLocalClient.send_message"
- ), patch(
- "homeassistant.components.roborock.RoborockMqttClient._wait_response"
- ), patch(
- "homeassistant.components.roborock.coordinator.RoborockLocalClient._wait_response"
- ), patch(
- "roborock.api.AttributeCache.async_value",
- ), patch(
- "roborock.api.AttributeCache.value",
- ), patch(
- "homeassistant.components.roborock.image.MAP_SLEEP",
- 0,
+ with (
+ patch("homeassistant.components.roborock.RoborockMqttClient.async_connect"),
+ patch("homeassistant.components.roborock.RoborockMqttClient._send_command"),
+ patch(
+ "homeassistant.components.roborock.RoborockApiClient.get_home_data",
+ return_value=HOME_DATA,
+ ),
+ patch(
+ "homeassistant.components.roborock.RoborockMqttClient.get_networking",
+ return_value=NETWORK_INFO,
+ ),
+ patch(
+ "homeassistant.components.roborock.coordinator.RoborockLocalClient.get_prop",
+ return_value=PROP,
+ ),
+ patch(
+ "homeassistant.components.roborock.coordinator.RoborockMqttClient.get_multi_maps_list",
+ return_value=MULTI_MAP_LIST,
+ ),
+ patch(
+ "homeassistant.components.roborock.coordinator.RoborockLocalClient.get_multi_maps_list",
+ return_value=MULTI_MAP_LIST,
+ ),
+ patch(
+ "homeassistant.components.roborock.image.RoborockMapDataParser.parse",
+ return_value=MAP_DATA,
+ ),
+ patch(
+ "homeassistant.components.roborock.coordinator.RoborockLocalClient.send_message"
+ ),
+ patch("homeassistant.components.roborock.RoborockMqttClient._wait_response"),
+ patch(
+ "homeassistant.components.roborock.coordinator.RoborockLocalClient._wait_response"
+ ),
+ patch(
+ "roborock.api.AttributeCache.async_value",
+ ),
+ patch(
+ "roborock.api.AttributeCache.value",
+ ),
+ patch(
+ "homeassistant.components.roborock.image.MAP_SLEEP",
+ 0,
+ ),
):
yield
diff --git a/tests/components/roborock/test_image.py b/tests/components/roborock/test_image.py
index b8d1dc408a2..77829e5aaa6 100644
--- a/tests/components/roborock/test_image.py
+++ b/tests/components/roborock/test_image.py
@@ -35,11 +35,14 @@ async def test_floorplan_image(
# Copy the device prop so we don't override it
prop = copy.deepcopy(PROP)
prop.status.in_cleaning = 1
- with patch(
- "homeassistant.components.roborock.coordinator.RoborockLocalClient.get_prop",
- return_value=prop,
- ), patch(
- "homeassistant.components.roborock.image.dt_util.utcnow", return_value=now
+ with (
+ patch(
+ "homeassistant.components.roborock.coordinator.RoborockLocalClient.get_prop",
+ return_value=prop,
+ ),
+ patch(
+ "homeassistant.components.roborock.image.dt_util.utcnow", return_value=now
+ ),
):
async_fire_time_changed(hass, now)
await hass.async_block_till_done()
@@ -63,14 +66,18 @@ async def test_floorplan_image_failed_parse(
prop = copy.deepcopy(PROP)
prop.status.in_cleaning = 1
# Update image, but get none for parse image.
- with patch(
- "homeassistant.components.roborock.image.RoborockMapDataParser.parse",
- return_value=map_data,
- ), patch(
- "homeassistant.components.roborock.coordinator.RoborockLocalClient.get_prop",
- return_value=prop,
- ), patch(
- "homeassistant.components.roborock.image.dt_util.utcnow", return_value=now
+ with (
+ patch(
+ "homeassistant.components.roborock.image.RoborockMapDataParser.parse",
+ return_value=map_data,
+ ),
+ patch(
+ "homeassistant.components.roborock.coordinator.RoborockLocalClient.get_prop",
+ return_value=prop,
+ ),
+ patch(
+ "homeassistant.components.roborock.image.dt_util.utcnow", return_value=now
+ ),
):
async_fire_time_changed(hass, now)
resp = await client.get("/api/image_proxy/image.roborock_s7_maxv_upstairs")
diff --git a/tests/components/roborock/test_init.py b/tests/components/roborock/test_init.py
index 8f9bc56d07b..08a3afe6c5e 100644
--- a/tests/components/roborock/test_init.py
+++ b/tests/components/roborock/test_init.py
@@ -32,11 +32,14 @@ async def test_config_entry_not_ready(
hass: HomeAssistant, mock_roborock_entry: MockConfigEntry
) -> None:
"""Test that when coordinator update fails, entry retries."""
- with patch(
- "homeassistant.components.roborock.RoborockApiClient.get_home_data",
- ), patch(
- "homeassistant.components.roborock.coordinator.RoborockLocalClient.get_prop",
- side_effect=RoborockException(),
+ with (
+ patch(
+ "homeassistant.components.roborock.RoborockApiClient.get_home_data",
+ ),
+ patch(
+ "homeassistant.components.roborock.coordinator.RoborockLocalClient.get_prop",
+ side_effect=RoborockException(),
+ ),
):
await async_setup_component(hass, DOMAIN, {})
assert mock_roborock_entry.state is ConfigEntryState.SETUP_RETRY
@@ -46,12 +49,15 @@ async def test_config_entry_not_ready_home_data(
hass: HomeAssistant, mock_roborock_entry: MockConfigEntry
) -> None:
"""Test that when we fail to get home data, entry retries."""
- with patch(
- "homeassistant.components.roborock.RoborockApiClient.get_home_data",
- side_effect=RoborockException(),
- ), patch(
- "homeassistant.components.roborock.coordinator.RoborockLocalClient.get_prop",
- side_effect=RoborockException(),
+ with (
+ patch(
+ "homeassistant.components.roborock.RoborockApiClient.get_home_data",
+ side_effect=RoborockException(),
+ ),
+ patch(
+ "homeassistant.components.roborock.coordinator.RoborockLocalClient.get_prop",
+ side_effect=RoborockException(),
+ ),
):
await async_setup_component(hass, DOMAIN, {})
assert mock_roborock_entry.state is ConfigEntryState.SETUP_RETRY
@@ -85,12 +91,15 @@ async def test_cloud_client_fails_props(
hass: HomeAssistant, mock_roborock_entry: MockConfigEntry, bypass_api_fixture
) -> None:
"""Test that if networking succeeds, but we can't communicate with the vacuum, we can't get props, fail."""
- with patch(
- "homeassistant.components.roborock.coordinator.RoborockLocalClient.ping",
- side_effect=RoborockException(),
- ), patch(
- "homeassistant.components.roborock.coordinator.RoborockMqttClient.get_prop",
- side_effect=RoborockException(),
+ with (
+ patch(
+ "homeassistant.components.roborock.coordinator.RoborockLocalClient.ping",
+ side_effect=RoborockException(),
+ ),
+ patch(
+ "homeassistant.components.roborock.coordinator.RoborockMqttClient.get_prop",
+ side_effect=RoborockException(),
+ ),
):
await async_setup_component(hass, DOMAIN, {})
assert mock_roborock_entry.state is ConfigEntryState.SETUP_RETRY
diff --git a/tests/components/roborock/test_select.py b/tests/components/roborock/test_select.py
index 67fefee7afb..9310d4e2e9a 100644
--- a/tests/components/roborock/test_select.py
+++ b/tests/components/roborock/test_select.py
@@ -48,10 +48,13 @@ async def test_update_failure(
setup_entry: MockConfigEntry,
) -> None:
"""Test that changing a value will raise a homeassistanterror when it fails."""
- with patch(
- "homeassistant.components.roborock.coordinator.RoborockLocalClient.send_message",
- side_effect=RoborockException(),
- ), pytest.raises(HomeAssistantError):
+ with (
+ patch(
+ "homeassistant.components.roborock.coordinator.RoborockLocalClient.send_message",
+ side_effect=RoborockException(),
+ ),
+ pytest.raises(HomeAssistantError),
+ ):
await hass.services.async_call(
"select",
SERVICE_SELECT_OPTION,
diff --git a/tests/components/roborock/test_vacuum.py b/tests/components/roborock/test_vacuum.py
index 4b683da88fc..a3d5854edd1 100644
--- a/tests/components/roborock/test_vacuum.py
+++ b/tests/components/roborock/test_vacuum.py
@@ -141,10 +141,13 @@ async def test_failed_user_command(
) -> None:
"""Test that when a user sends an invalid command, we raise HomeAssistantError."""
data = {ATTR_ENTITY_ID: ENTITY_ID, "command": "fake_command"}
- with patch(
- "homeassistant.components.roborock.coordinator.RoborockLocalClient.send_command",
- side_effect=RoborockException(),
- ), pytest.raises(HomeAssistantError, match="Error while calling fake_command"):
+ with (
+ patch(
+ "homeassistant.components.roborock.coordinator.RoborockLocalClient.send_command",
+ side_effect=RoborockException(),
+ ),
+ pytest.raises(HomeAssistantError, match="Error while calling fake_command"),
+ ):
await hass.services.async_call(
Platform.VACUUM,
SERVICE_SEND_COMMAND,
diff --git a/tests/components/roomba/test_config_flow.py b/tests/components/roomba/test_config_flow.py
index af82d4a690e..2eaf3b14e38 100644
--- a/tests/components/roomba/test_config_flow.py
+++ b/tests/components/roomba/test_config_flow.py
@@ -174,16 +174,20 @@ async def test_form_user_discovery_and_password_fetch(hass: HomeAssistant) -> No
assert result2["errors"] is None
assert result2["step_id"] == "link"
- with patch(
- "homeassistant.components.roomba.config_flow.RoombaFactory.create_roomba",
- return_value=mocked_roomba,
- ), patch(
- "homeassistant.components.roomba.config_flow.RoombaPassword",
- _mocked_getpassword,
- ), patch(
- "homeassistant.components.roomba.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.roomba.config_flow.RoombaFactory.create_roomba",
+ return_value=mocked_roomba,
+ ),
+ patch(
+ "homeassistant.components.roomba.config_flow.RoombaPassword",
+ _mocked_getpassword,
+ ),
+ patch(
+ "homeassistant.components.roomba.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{},
@@ -295,16 +299,20 @@ async def test_form_user_discovery_manual_and_auto_password_fetch(
assert result3["type"] == data_entry_flow.FlowResultType.FORM
assert result3["errors"] is None
- with patch(
- "homeassistant.components.roomba.config_flow.RoombaFactory.create_roomba",
- return_value=mocked_roomba,
- ), patch(
- "homeassistant.components.roomba.config_flow.RoombaPassword",
- _mocked_getpassword,
- ), patch(
- "homeassistant.components.roomba.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.roomba.config_flow.RoombaFactory.create_roomba",
+ return_value=mocked_roomba,
+ ),
+ patch(
+ "homeassistant.components.roomba.config_flow.RoombaPassword",
+ _mocked_getpassword,
+ ),
+ patch(
+ "homeassistant.components.roomba.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result4 = await hass.config_entries.flow.async_configure(
result3["flow_id"],
{},
@@ -428,16 +436,20 @@ async def test_form_user_discovery_no_devices_found_and_auto_password_fetch(
assert result2["type"] == data_entry_flow.FlowResultType.FORM
assert result2["errors"] is None
- with patch(
- "homeassistant.components.roomba.config_flow.RoombaFactory.create_roomba",
- return_value=mocked_roomba,
- ), patch(
- "homeassistant.components.roomba.config_flow.RoombaPassword",
- _mocked_getpassword,
- ), patch(
- "homeassistant.components.roomba.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.roomba.config_flow.RoombaFactory.create_roomba",
+ return_value=mocked_roomba,
+ ),
+ patch(
+ "homeassistant.components.roomba.config_flow.RoombaPassword",
+ _mocked_getpassword,
+ ),
+ patch(
+ "homeassistant.components.roomba.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{},
@@ -501,13 +513,16 @@ async def test_form_user_discovery_no_devices_found_and_password_fetch_fails(
)
await hass.async_block_till_done()
- with patch(
- "homeassistant.components.roomba.config_flow.RoombaFactory.create_roomba",
- return_value=mocked_roomba,
- ), patch(
- "homeassistant.components.roomba.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.roomba.config_flow.RoombaFactory.create_roomba",
+ return_value=mocked_roomba,
+ ),
+ patch(
+ "homeassistant.components.roomba.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result4 = await hass.config_entries.flow.async_configure(
result3["flow_id"],
{CONF_PASSWORD: "password"},
@@ -572,13 +587,16 @@ async def test_form_user_discovery_not_devices_found_and_password_fetch_fails_an
)
await hass.async_block_till_done()
- with patch(
- "homeassistant.components.roomba.config_flow.RoombaFactory.create_roomba",
- return_value=mocked_roomba,
- ), patch(
- "homeassistant.components.roomba.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.roomba.config_flow.RoombaFactory.create_roomba",
+ return_value=mocked_roomba,
+ ),
+ patch(
+ "homeassistant.components.roomba.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result4 = await hass.config_entries.flow.async_configure(
result3["flow_id"],
{CONF_PASSWORD: "password"},
@@ -631,13 +649,16 @@ async def test_form_user_discovery_and_password_fetch_gets_connection_refused(
)
await hass.async_block_till_done()
- with patch(
- "homeassistant.components.roomba.config_flow.RoombaFactory.create_roomba",
- return_value=mocked_roomba,
- ), patch(
- "homeassistant.components.roomba.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.roomba.config_flow.RoombaFactory.create_roomba",
+ return_value=mocked_roomba,
+ ),
+ patch(
+ "homeassistant.components.roomba.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result4 = await hass.config_entries.flow.async_configure(
result3["flow_id"],
{CONF_PASSWORD: "password"},
@@ -685,16 +706,20 @@ async def test_dhcp_discovery_and_roomba_discovery_finds(
assert result["step_id"] == "link"
assert result["description_placeholders"] == {"name": "robot_name"}
- with patch(
- "homeassistant.components.roomba.config_flow.RoombaFactory.create_roomba",
- return_value=mocked_roomba,
- ), patch(
- "homeassistant.components.roomba.config_flow.RoombaPassword",
- _mocked_getpassword,
- ), patch(
- "homeassistant.components.roomba.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.roomba.config_flow.RoombaFactory.create_roomba",
+ return_value=mocked_roomba,
+ ),
+ patch(
+ "homeassistant.components.roomba.config_flow.RoombaPassword",
+ _mocked_getpassword,
+ ),
+ patch(
+ "homeassistant.components.roomba.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{},
@@ -759,16 +784,20 @@ async def test_dhcp_discovery_falls_back_to_manual(
assert result3["type"] == data_entry_flow.FlowResultType.FORM
assert result3["errors"] is None
- with patch(
- "homeassistant.components.roomba.config_flow.RoombaFactory.create_roomba",
- return_value=mocked_roomba,
- ), patch(
- "homeassistant.components.roomba.config_flow.RoombaPassword",
- _mocked_getpassword,
- ), patch(
- "homeassistant.components.roomba.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.roomba.config_flow.RoombaFactory.create_roomba",
+ return_value=mocked_roomba,
+ ),
+ patch(
+ "homeassistant.components.roomba.config_flow.RoombaPassword",
+ _mocked_getpassword,
+ ),
+ patch(
+ "homeassistant.components.roomba.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result4 = await hass.config_entries.flow.async_configure(
result3["flow_id"],
{},
@@ -825,16 +854,20 @@ async def test_dhcp_discovery_no_devices_falls_back_to_manual(
assert result2["type"] == data_entry_flow.FlowResultType.FORM
assert result2["errors"] is None
- with patch(
- "homeassistant.components.roomba.config_flow.RoombaFactory.create_roomba",
- return_value=mocked_roomba,
- ), patch(
- "homeassistant.components.roomba.config_flow.RoombaPassword",
- _mocked_getpassword,
- ), patch(
- "homeassistant.components.roomba.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.roomba.config_flow.RoombaFactory.create_roomba",
+ return_value=mocked_roomba,
+ ),
+ patch(
+ "homeassistant.components.roomba.config_flow.RoombaPassword",
+ _mocked_getpassword,
+ ),
+ patch(
+ "homeassistant.components.roomba.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{},
diff --git a/tests/components/roon/test_config_flow.py b/tests/components/roon/test_config_flow.py
index ce7203caf66..c31e689e05b 100644
--- a/tests/components/roon/test_config_flow.py
+++ b/tests/components/roon/test_config_flow.py
@@ -73,15 +73,19 @@ class RoonDiscoveryFailedMock(RoonDiscoveryMock):
async def test_successful_discovery_and_auth(hass: HomeAssistant) -> None:
"""Test when discovery and auth both work ok."""
- with patch(
- "homeassistant.components.roon.config_flow.RoonApi",
- return_value=RoonApiMock(),
- ), patch(
- "homeassistant.components.roon.config_flow.RoonDiscovery",
- return_value=RoonDiscoveryMock(),
- ), patch(
- "homeassistant.components.roon.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.roon.config_flow.RoonApi",
+ return_value=RoonApiMock(),
+ ),
+ patch(
+ "homeassistant.components.roon.config_flow.RoonDiscovery",
+ return_value=RoonDiscoveryMock(),
+ ),
+ patch(
+ "homeassistant.components.roon.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@@ -111,15 +115,19 @@ async def test_successful_discovery_and_auth(hass: HomeAssistant) -> None:
async def test_unsuccessful_discovery_user_form_and_auth(hass: HomeAssistant) -> None:
"""Test unsuccessful discover, user adding the host via the form and then successful auth."""
- with patch(
- "homeassistant.components.roon.config_flow.RoonApi",
- return_value=RoonApiMock(),
- ), patch(
- "homeassistant.components.roon.config_flow.RoonDiscovery",
- return_value=RoonDiscoveryFailedMock(),
- ), patch(
- "homeassistant.components.roon.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.roon.config_flow.RoonApi",
+ return_value=RoonApiMock(),
+ ),
+ patch(
+ "homeassistant.components.roon.config_flow.RoonDiscovery",
+ return_value=RoonDiscoveryFailedMock(),
+ ),
+ patch(
+ "homeassistant.components.roon.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@@ -158,12 +166,15 @@ async def test_duplicate_config(hass: HomeAssistant) -> None:
hass
)
- with patch(
- "homeassistant.components.roon.config_flow.RoonApi",
- return_value=RoonApiMock(),
- ), patch(
- "homeassistant.components.roon.config_flow.RoonDiscovery",
- return_value=RoonDiscoveryFailedMock(),
+ with (
+ patch(
+ "homeassistant.components.roon.config_flow.RoonApi",
+ return_value=RoonApiMock(),
+ ),
+ patch(
+ "homeassistant.components.roon.config_flow.RoonDiscovery",
+ return_value=RoonDiscoveryFailedMock(),
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@@ -190,21 +201,27 @@ async def test_duplicate_config(hass: HomeAssistant) -> None:
async def test_successful_discovery_no_auth(hass: HomeAssistant) -> None:
"""Test successful discover, but failed auth."""
- with patch(
- "homeassistant.components.roon.config_flow.RoonApi",
- return_value=RoonApiMockNoToken(),
- ), patch(
- "homeassistant.components.roon.config_flow.RoonDiscovery",
- return_value=RoonDiscoveryMock(),
- ), patch(
- "homeassistant.components.roon.config_flow.TIMEOUT",
- 0,
- ), patch(
- "homeassistant.components.roon.config_flow.AUTHENTICATE_TIMEOUT",
- 0.01,
- ), patch(
- "homeassistant.components.roon.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.roon.config_flow.RoonApi",
+ return_value=RoonApiMockNoToken(),
+ ),
+ patch(
+ "homeassistant.components.roon.config_flow.RoonDiscovery",
+ return_value=RoonDiscoveryMock(),
+ ),
+ patch(
+ "homeassistant.components.roon.config_flow.TIMEOUT",
+ 0,
+ ),
+ patch(
+ "homeassistant.components.roon.config_flow.AUTHENTICATE_TIMEOUT",
+ 0.01,
+ ),
+ patch(
+ "homeassistant.components.roon.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@@ -227,15 +244,19 @@ async def test_successful_discovery_no_auth(hass: HomeAssistant) -> None:
async def test_unexpected_exception(hass: HomeAssistant) -> None:
"""Test successful discover, and unexpected exception during auth."""
- with patch(
- "homeassistant.components.roon.config_flow.RoonApi",
- return_value=RoonApiMockException(),
- ), patch(
- "homeassistant.components.roon.config_flow.RoonDiscovery",
- return_value=RoonDiscoveryMock(),
- ), patch(
- "homeassistant.components.roon.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.roon.config_flow.RoonApi",
+ return_value=RoonApiMockException(),
+ ),
+ patch(
+ "homeassistant.components.roon.config_flow.RoonDiscovery",
+ return_value=RoonDiscoveryMock(),
+ ),
+ patch(
+ "homeassistant.components.roon.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
diff --git a/tests/components/rova/conftest.py b/tests/components/rova/conftest.py
index 99dcd29fdf3..51cb94c64f7 100644
--- a/tests/components/rova/conftest.py
+++ b/tests/components/rova/conftest.py
@@ -10,9 +10,12 @@ def mock_rova():
"""Mock a successful Rova API."""
api = MagicMock()
- with patch(
- "homeassistant.components.rova.config_flow.Rova",
- return_value=api,
- ) as api, patch("homeassistant.components.rova.Rova", return_value=api):
+ with (
+ patch(
+ "homeassistant.components.rova.config_flow.Rova",
+ return_value=api,
+ ) as api,
+ patch("homeassistant.components.rova.Rova", return_value=api),
+ ):
api.is_rova_area.return_value = True
yield api
diff --git a/tests/components/rtsp_to_webrtc/conftest.py b/tests/components/rtsp_to_webrtc/conftest.py
index edb8c7c4aca..e968df9d860 100644
--- a/tests/components/rtsp_to_webrtc/conftest.py
+++ b/tests/components/rtsp_to_webrtc/conftest.py
@@ -45,12 +45,15 @@ async def mock_camera(hass) -> AsyncGenerator[None, None]:
hass, "camera", {camera.DOMAIN: {"platform": "demo"}}
)
await hass.async_block_till_done()
- with patch(
- "homeassistant.components.demo.camera.Path.read_bytes",
- return_value=b"Test",
- ), patch(
- "homeassistant.components.camera.Camera.stream_source",
- return_value=STREAM_SOURCE,
+ with (
+ patch(
+ "homeassistant.components.demo.camera.Path.read_bytes",
+ return_value=b"Test",
+ ),
+ patch(
+ "homeassistant.components.camera.Camera.stream_source",
+ return_value=STREAM_SOURCE,
+ ),
):
yield
diff --git a/tests/components/rtsp_to_webrtc/test_config_flow.py b/tests/components/rtsp_to_webrtc/test_config_flow.py
index 13885f06d3e..16d4779a92c 100644
--- a/tests/components/rtsp_to_webrtc/test_config_flow.py
+++ b/tests/components/rtsp_to_webrtc/test_config_flow.py
@@ -26,10 +26,13 @@ async def test_web_full_flow(hass: HomeAssistant) -> None:
assert result.get("step_id") == "user"
assert result.get("data_schema").schema.get("server_url") == str
assert not result.get("errors")
- with patch("rtsp_to_webrtc.client.Client.heartbeat"), patch(
- "homeassistant.components.rtsp_to_webrtc.async_setup_entry",
- return_value=True,
- ) as mock_setup:
+ with (
+ patch("rtsp_to_webrtc.client.Client.heartbeat"),
+ patch(
+ "homeassistant.components.rtsp_to_webrtc.async_setup_entry",
+ return_value=True,
+ ) as mock_setup,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"server_url": "https://example.com"}
)
@@ -131,10 +134,13 @@ async def test_hassio_discovery(hass: HomeAssistant) -> None:
assert result.get("step_id") == "hassio_confirm"
assert result.get("description_placeholders") == {"addon": "RTSPtoWebRTC"}
- with patch("rtsp_to_webrtc.client.Client.heartbeat"), patch(
- "homeassistant.components.rtsp_to_webrtc.async_setup_entry",
- return_value=True,
- ) as mock_setup:
+ with (
+ patch("rtsp_to_webrtc.client.Client.heartbeat"),
+ patch(
+ "homeassistant.components.rtsp_to_webrtc.async_setup_entry",
+ return_value=True,
+ ) as mock_setup,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
diff --git a/tests/components/ruckus_unleashed/test_config_flow.py b/tests/components/ruckus_unleashed/test_config_flow.py
index c9f321a1da6..ae0ccb0a9b1 100644
--- a/tests/components/ruckus_unleashed/test_config_flow.py
+++ b/tests/components/ruckus_unleashed/test_config_flow.py
@@ -40,10 +40,13 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] == {}
- with RuckusAjaxApiPatchContext(), patch(
- "homeassistant.components.ruckus_unleashed.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ RuckusAjaxApiPatchContext(),
+ patch(
+ "homeassistant.components.ruckus_unleashed.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
CONFIG,
diff --git a/tests/components/rympro/test_config_flow.py b/tests/components/rympro/test_config_flow.py
index e61384107cb..f5591d8e0c7 100644
--- a/tests/components/rympro/test_config_flow.py
+++ b/tests/components/rympro/test_config_flow.py
@@ -44,16 +44,20 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with patch(
- "homeassistant.components.rympro.config_flow.RymPro.login",
- return_value="test-token",
- ), patch(
- "homeassistant.components.rympro.config_flow.RymPro.account_info",
- return_value={"accountNumber": TEST_DATA[CONF_UNIQUE_ID]},
- ), patch(
- "homeassistant.components.rympro.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.rympro.config_flow.RymPro.login",
+ return_value="test-token",
+ ),
+ patch(
+ "homeassistant.components.rympro.config_flow.RymPro.account_info",
+ return_value={"accountNumber": TEST_DATA[CONF_UNIQUE_ID]},
+ ),
+ patch(
+ "homeassistant.components.rympro.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -98,16 +102,20 @@ async def test_login_error(hass: HomeAssistant, exception, error) -> None:
assert result2["type"] == FlowResultType.FORM
assert result2["errors"] == {"base": error}
- with patch(
- "homeassistant.components.rympro.config_flow.RymPro.login",
- return_value="test-token",
- ), patch(
- "homeassistant.components.rympro.config_flow.RymPro.account_info",
- return_value={"accountNumber": TEST_DATA[CONF_UNIQUE_ID]},
- ), patch(
- "homeassistant.components.rympro.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.rympro.config_flow.RymPro.login",
+ return_value="test-token",
+ ),
+ patch(
+ "homeassistant.components.rympro.config_flow.RymPro.account_info",
+ return_value={"accountNumber": TEST_DATA[CONF_UNIQUE_ID]},
+ ),
+ patch(
+ "homeassistant.components.rympro.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
@@ -129,12 +137,15 @@ async def test_form_already_exists(hass: HomeAssistant, config_entry) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "homeassistant.components.rympro.config_flow.RymPro.login",
- return_value="test-token",
- ), patch(
- "homeassistant.components.rympro.config_flow.RymPro.account_info",
- return_value={"accountNumber": TEST_DATA[CONF_UNIQUE_ID]},
+ with (
+ patch(
+ "homeassistant.components.rympro.config_flow.RymPro.login",
+ return_value="test-token",
+ ),
+ patch(
+ "homeassistant.components.rympro.config_flow.RymPro.account_info",
+ return_value={"accountNumber": TEST_DATA[CONF_UNIQUE_ID]},
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -163,16 +174,20 @@ async def test_form_reauth(hass: HomeAssistant, config_entry) -> None:
assert result["type"] == "form"
assert result["errors"] is None
- with patch(
- "homeassistant.components.rympro.config_flow.RymPro.login",
- return_value="test-token",
- ), patch(
- "homeassistant.components.rympro.config_flow.RymPro.account_info",
- return_value={"accountNumber": TEST_DATA[CONF_UNIQUE_ID]},
- ), patch(
- "homeassistant.components.rympro.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.rympro.config_flow.RymPro.login",
+ return_value="test-token",
+ ),
+ patch(
+ "homeassistant.components.rympro.config_flow.RymPro.account_info",
+ return_value={"accountNumber": TEST_DATA[CONF_UNIQUE_ID]},
+ ),
+ patch(
+ "homeassistant.components.rympro.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -202,16 +217,20 @@ async def test_form_reauth_with_new_account(hass: HomeAssistant, config_entry) -
assert result["type"] == "form"
assert result["errors"] is None
- with patch(
- "homeassistant.components.rympro.config_flow.RymPro.login",
- return_value="test-token",
- ), patch(
- "homeassistant.components.rympro.config_flow.RymPro.account_info",
- return_value={"accountNumber": "new-account-number"},
- ), patch(
- "homeassistant.components.rympro.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.rympro.config_flow.RymPro.login",
+ return_value="test-token",
+ ),
+ patch(
+ "homeassistant.components.rympro.config_flow.RymPro.account_info",
+ return_value={"accountNumber": "new-account-number"},
+ ),
+ patch(
+ "homeassistant.components.rympro.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
diff --git a/tests/components/samsungtv/conftest.py b/tests/components/samsungtv/conftest.py
index ad0c3a21db6..8bef7317918 100644
--- a/tests/components/samsungtv/conftest.py
+++ b/tests/components/samsungtv/conftest.py
@@ -41,14 +41,16 @@ def mock_setup_entry() -> Generator[AsyncMock, None, None]:
@pytest.fixture(autouse=True)
async def silent_ssdp_scanner(hass):
"""Start SSDP component and get Scanner, prevent actual SSDP traffic."""
- with patch(
- "homeassistant.components.ssdp.Scanner._async_start_ssdp_listeners"
- ), patch("homeassistant.components.ssdp.Scanner._async_stop_ssdp_listeners"), patch(
- "homeassistant.components.ssdp.Scanner.async_scan"
- ), patch(
- "homeassistant.components.ssdp.Server._async_start_upnp_servers",
- ), patch(
- "homeassistant.components.ssdp.Server._async_stop_upnp_servers",
+ with (
+ patch("homeassistant.components.ssdp.Scanner._async_start_ssdp_listeners"),
+ patch("homeassistant.components.ssdp.Scanner._async_stop_ssdp_listeners"),
+ patch("homeassistant.components.ssdp.Scanner.async_scan"),
+ patch(
+ "homeassistant.components.ssdp.Server._async_start_upnp_servers",
+ ),
+ patch(
+ "homeassistant.components.ssdp.Server._async_stop_upnp_servers",
+ ),
):
yield
diff --git a/tests/components/samsungtv/test_config_flow.py b/tests/components/samsungtv/test_config_flow.py
index 78f72dfd299..a300c28b945 100644
--- a/tests/components/samsungtv/test_config_flow.py
+++ b/tests/components/samsungtv/test_config_flow.py
@@ -392,12 +392,15 @@ async def test_user_legacy_not_supported(hass: HomeAssistant) -> None:
@pytest.mark.usefixtures("rest_api", "remoteencws_failing")
async def test_user_websocket_not_supported(hass: HomeAssistant) -> None:
"""Test starting a flow by user for not supported device."""
- with patch(
- "homeassistant.components.samsungtv.bridge.Remote",
- side_effect=OSError("Boom"),
- ), patch(
- "homeassistant.components.samsungtv.bridge.SamsungTVWSAsyncRemote.open",
- side_effect=WebSocketProtocolError("Boom"),
+ with (
+ patch(
+ "homeassistant.components.samsungtv.bridge.Remote",
+ side_effect=OSError("Boom"),
+ ),
+ patch(
+ "homeassistant.components.samsungtv.bridge.SamsungTVWSAsyncRemote.open",
+ side_effect=WebSocketProtocolError("Boom"),
+ ),
):
# websocket device not supported
result = await hass.config_entries.flow.async_init(
@@ -412,12 +415,15 @@ async def test_user_websocket_access_denied(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test starting a flow by user for not supported device."""
- with patch(
- "homeassistant.components.samsungtv.bridge.Remote",
- side_effect=OSError("Boom"),
- ), patch(
- "homeassistant.components.samsungtv.bridge.SamsungTVWSAsyncRemote.open",
- side_effect=ConnectionClosedError(rcvd=None, sent=frames.Close(1002, "")),
+ with (
+ patch(
+ "homeassistant.components.samsungtv.bridge.Remote",
+ side_effect=OSError("Boom"),
+ ),
+ patch(
+ "homeassistant.components.samsungtv.bridge.SamsungTVWSAsyncRemote.open",
+ side_effect=ConnectionClosedError(rcvd=None, sent=frames.Close(1002, "")),
+ ),
):
# websocket device not supported
result = await hass.config_entries.flow.async_init(
@@ -431,12 +437,15 @@ async def test_user_websocket_access_denied(
@pytest.mark.usefixtures("rest_api", "remoteencws_failing")
async def test_user_websocket_auth_retry(hass: HomeAssistant) -> None:
"""Test starting a flow by user for not supported device."""
- with patch(
- "homeassistant.components.samsungtv.bridge.Remote",
- side_effect=OSError("Boom"),
- ), patch(
- "homeassistant.components.samsungtv.bridge.SamsungTVWSAsyncRemote.open",
- side_effect=UnauthorizedError,
+ with (
+ patch(
+ "homeassistant.components.samsungtv.bridge.Remote",
+ side_effect=OSError("Boom"),
+ ),
+ patch(
+ "homeassistant.components.samsungtv.bridge.SamsungTVWSAsyncRemote.open",
+ side_effect=UnauthorizedError,
+ ),
):
# websocket device not supported
result = await hass.config_entries.flow.async_init(
@@ -445,11 +454,14 @@ async def test_user_websocket_auth_retry(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "pairing"
assert result["errors"] == {"base": "auth_missing"}
- with patch(
- "homeassistant.components.samsungtv.bridge.Remote",
- side_effect=OSError("Boom"),
- ), patch(
- "homeassistant.components.samsungtv.bridge.SamsungTVWSAsyncRemote.open",
+ with (
+ patch(
+ "homeassistant.components.samsungtv.bridge.Remote",
+ side_effect=OSError("Boom"),
+ ),
+ patch(
+ "homeassistant.components.samsungtv.bridge.SamsungTVWSAsyncRemote.open",
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
@@ -466,12 +478,15 @@ async def test_user_websocket_auth_retry(hass: HomeAssistant) -> None:
@pytest.mark.usefixtures("rest_api_failing")
async def test_user_not_successful(hass: HomeAssistant) -> None:
"""Test starting a flow by user but no connection found."""
- with patch(
- "homeassistant.components.samsungtv.bridge.Remote",
- side_effect=OSError("Boom"),
- ), patch(
- "homeassistant.components.samsungtv.bridge.SamsungTVWSAsyncRemote.open",
- side_effect=OSError("Boom"),
+ with (
+ patch(
+ "homeassistant.components.samsungtv.bridge.Remote",
+ side_effect=OSError("Boom"),
+ ),
+ patch(
+ "homeassistant.components.samsungtv.bridge.SamsungTVWSAsyncRemote.open",
+ side_effect=OSError("Boom"),
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}, data=MOCK_USER_DATA
@@ -483,12 +498,15 @@ async def test_user_not_successful(hass: HomeAssistant) -> None:
@pytest.mark.usefixtures("rest_api_failing")
async def test_user_not_successful_2(hass: HomeAssistant) -> None:
"""Test starting a flow by user but no connection found."""
- with patch(
- "homeassistant.components.samsungtv.bridge.Remote",
- side_effect=OSError("Boom"),
- ), patch(
- "homeassistant.components.samsungtv.bridge.SamsungTVWSAsyncRemote.open",
- side_effect=ConnectionFailure("Boom"),
+ with (
+ patch(
+ "homeassistant.components.samsungtv.bridge.Remote",
+ side_effect=OSError("Boom"),
+ ),
+ patch(
+ "homeassistant.components.samsungtv.bridge.SamsungTVWSAsyncRemote.open",
+ side_effect=ConnectionFailure("Boom"),
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}, data=MOCK_USER_DATA
@@ -757,16 +775,19 @@ async def test_ssdp_encrypted_websocket_not_supported(
@pytest.mark.usefixtures("rest_api_failing")
async def test_ssdp_websocket_cannot_connect(hass: HomeAssistant) -> None:
"""Test starting a flow from discovery and we cannot connect."""
- with patch(
- "homeassistant.components.samsungtv.bridge.Remote",
- side_effect=OSError("Boom"),
- ), patch(
- "homeassistant.components.samsungtv.bridge.SamsungTVEncryptedWSAsyncRemote.start_listening",
- side_effect=WebSocketProtocolError("Boom"),
- ), patch(
- "homeassistant.components.samsungtv.bridge.SamsungTVWSAsyncRemote",
- ) as remotews, patch.object(
- remotews, "open", side_effect=WebSocketProtocolError("Boom")
+ with (
+ patch(
+ "homeassistant.components.samsungtv.bridge.Remote",
+ side_effect=OSError("Boom"),
+ ),
+ patch(
+ "homeassistant.components.samsungtv.bridge.SamsungTVEncryptedWSAsyncRemote.start_listening",
+ side_effect=WebSocketProtocolError("Boom"),
+ ),
+ patch(
+ "homeassistant.components.samsungtv.bridge.SamsungTVWSAsyncRemote",
+ ) as remotews,
+ patch.object(remotews, "open", side_effect=WebSocketProtocolError("Boom")),
):
# device not supported
result = await hass.config_entries.flow.async_init(
@@ -793,15 +814,19 @@ async def test_ssdp_model_not_supported(hass: HomeAssistant) -> None:
@pytest.mark.usefixtures("remoteencws_failing")
async def test_ssdp_not_successful(hass: HomeAssistant) -> None:
"""Test starting a flow from discovery but no device found."""
- with patch(
- "homeassistant.components.samsungtv.bridge.Remote",
- side_effect=OSError("Boom"),
- ), patch(
- "homeassistant.components.samsungtv.bridge.SamsungTVWSAsyncRemote.open",
- side_effect=OSError("Boom"),
- ), patch(
- "homeassistant.components.samsungtv.bridge.SamsungTVWSBridge.async_device_info",
- return_value=MOCK_DEVICE_INFO,
+ with (
+ patch(
+ "homeassistant.components.samsungtv.bridge.Remote",
+ side_effect=OSError("Boom"),
+ ),
+ patch(
+ "homeassistant.components.samsungtv.bridge.SamsungTVWSAsyncRemote.open",
+ side_effect=OSError("Boom"),
+ ),
+ patch(
+ "homeassistant.components.samsungtv.bridge.SamsungTVWSBridge.async_device_info",
+ return_value=MOCK_DEVICE_INFO,
+ ),
):
# confirm to add the entry
result = await hass.config_entries.flow.async_init(
@@ -821,15 +846,19 @@ async def test_ssdp_not_successful(hass: HomeAssistant) -> None:
@pytest.mark.usefixtures("remoteencws_failing")
async def test_ssdp_not_successful_2(hass: HomeAssistant) -> None:
"""Test starting a flow from discovery but no device found."""
- with patch(
- "homeassistant.components.samsungtv.bridge.Remote",
- side_effect=OSError("Boom"),
- ), patch(
- "homeassistant.components.samsungtv.bridge.SamsungTVWSAsyncRemote.open",
- side_effect=ConnectionFailure("Boom"),
- ), patch(
- "homeassistant.components.samsungtv.bridge.SamsungTVWSBridge.async_device_info",
- return_value=MOCK_DEVICE_INFO,
+ with (
+ patch(
+ "homeassistant.components.samsungtv.bridge.Remote",
+ side_effect=OSError("Boom"),
+ ),
+ patch(
+ "homeassistant.components.samsungtv.bridge.SamsungTVWSAsyncRemote.open",
+ side_effect=ConnectionFailure("Boom"),
+ ),
+ patch(
+ "homeassistant.components.samsungtv.bridge.SamsungTVWSBridge.async_device_info",
+ return_value=MOCK_DEVICE_INFO,
+ ),
):
# confirm to add the entry
result = await hass.config_entries.flow.async_init(
@@ -1039,14 +1068,18 @@ async def test_zeroconf_and_dhcp_same_time(hass: HomeAssistant) -> None:
@pytest.mark.usefixtures("remoteencws_failing")
async def test_autodetect_websocket(hass: HomeAssistant) -> None:
"""Test for send key with autodetection of protocol."""
- with patch(
- "homeassistant.components.samsungtv.bridge.Remote",
- side_effect=OSError("Boom"),
- ), patch(
- "homeassistant.components.samsungtv.bridge.SamsungTVWSAsyncRemote"
- ) as remotews, patch(
- "homeassistant.components.samsungtv.bridge.SamsungTVAsyncRest",
- ) as rest_api_class:
+ with (
+ patch(
+ "homeassistant.components.samsungtv.bridge.Remote",
+ side_effect=OSError("Boom"),
+ ),
+ patch(
+ "homeassistant.components.samsungtv.bridge.SamsungTVWSAsyncRemote"
+ ) as remotews,
+ patch(
+ "homeassistant.components.samsungtv.bridge.SamsungTVAsyncRest",
+ ) as rest_api_class,
+ ):
remote = Mock(SamsungTVWSAsyncRemote)
remote.__aenter__ = AsyncMock(return_value=remote)
remote.__aexit__ = AsyncMock(return_value=False)
@@ -1086,14 +1119,18 @@ async def test_autodetect_websocket(hass: HomeAssistant) -> None:
async def test_websocket_no_mac(hass: HomeAssistant, mac_address: Mock) -> None:
"""Test for send key with autodetection of protocol."""
mac_address.return_value = "gg:ee:tt:mm:aa:cc"
- with patch(
- "homeassistant.components.samsungtv.bridge.Remote",
- side_effect=OSError("Boom"),
- ), patch(
- "homeassistant.components.samsungtv.bridge.SamsungTVWSAsyncRemote"
- ) as remotews, patch(
- "homeassistant.components.samsungtv.bridge.SamsungTVAsyncRest",
- ) as rest_api_class:
+ with (
+ patch(
+ "homeassistant.components.samsungtv.bridge.Remote",
+ side_effect=OSError("Boom"),
+ ),
+ patch(
+ "homeassistant.components.samsungtv.bridge.SamsungTVWSAsyncRemote"
+ ) as remotews,
+ patch(
+ "homeassistant.components.samsungtv.bridge.SamsungTVAsyncRest",
+ ) as rest_api_class,
+ ):
remote = Mock(SamsungTVWSAsyncRemote)
remote.__aenter__ = AsyncMock(return_value=remote)
remote.__aexit__ = AsyncMock(return_value=False)
@@ -1189,13 +1226,16 @@ async def test_autodetect_legacy(hass: HomeAssistant) -> None:
async def test_autodetect_none(hass: HomeAssistant) -> None:
"""Test for send key with autodetection of protocol."""
- with patch(
- "homeassistant.components.samsungtv.bridge.Remote",
- side_effect=OSError("Boom"),
- ) as remote, patch(
- "homeassistant.components.samsungtv.bridge.SamsungTVAsyncRest.rest_device_info",
- side_effect=ResponseError,
- ) as rest_device_info:
+ with (
+ patch(
+ "homeassistant.components.samsungtv.bridge.Remote",
+ side_effect=OSError("Boom"),
+ ) as remote,
+ patch(
+ "homeassistant.components.samsungtv.bridge.SamsungTVAsyncRest.rest_device_info",
+ side_effect=ResponseError,
+ ) as rest_device_info,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}, data=MOCK_USER_DATA
)
@@ -1618,12 +1658,15 @@ async def test_update_legacy_missing_mac_from_dhcp_no_unique_id(
data=MOCK_LEGACY_ENTRY,
)
entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.samsungtv.bridge.Remote.__enter__",
- return_value=True,
- ), patch(
- "homeassistant.components.samsungtv.bridge.SamsungTVEncryptedWSAsyncRemote.start_listening",
- side_effect=WebSocketProtocolError("Boom"),
+ with (
+ patch(
+ "homeassistant.components.samsungtv.bridge.Remote.__enter__",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.samsungtv.bridge.SamsungTVEncryptedWSAsyncRemote.start_listening",
+ side_effect=WebSocketProtocolError("Boom"),
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
diff --git a/tests/components/samsungtv/test_init.py b/tests/components/samsungtv/test_init.py
index fa7aec9a421..5bf8f2cacac 100644
--- a/tests/components/samsungtv/test_init.py
+++ b/tests/components/samsungtv/test_init.py
@@ -76,17 +76,20 @@ async def test_setup(hass: HomeAssistant) -> None:
async def test_setup_without_port_device_offline(hass: HomeAssistant) -> None:
"""Test import from yaml when the device is offline."""
- with patch(
- "homeassistant.components.samsungtv.bridge.Remote", side_effect=OSError
- ), patch(
- "homeassistant.components.samsungtv.bridge.SamsungTVEncryptedWSAsyncRemote.start_listening",
- side_effect=OSError,
- ), patch(
- "homeassistant.components.samsungtv.bridge.SamsungTVWSAsyncRemote.open",
- side_effect=OSError,
- ), patch(
- "homeassistant.components.samsungtv.bridge.SamsungTVWSBridge.async_device_info",
- return_value=None,
+ with (
+ patch("homeassistant.components.samsungtv.bridge.Remote", side_effect=OSError),
+ patch(
+ "homeassistant.components.samsungtv.bridge.SamsungTVEncryptedWSAsyncRemote.start_listening",
+ side_effect=OSError,
+ ),
+ patch(
+ "homeassistant.components.samsungtv.bridge.SamsungTVWSAsyncRemote.open",
+ side_effect=OSError,
+ ),
+ patch(
+ "homeassistant.components.samsungtv.bridge.SamsungTVWSBridge.async_device_info",
+ return_value=None,
+ ),
):
await setup_samsungtv_entry(hass, MOCK_CONFIG)
diff --git a/tests/components/samsungtv/test_media_player.py b/tests/components/samsungtv/test_media_player.py
index 4cfb2195310..f874b92305b 100644
--- a/tests/components/samsungtv/test_media_player.py
+++ b/tests/components/samsungtv/test_media_player.py
@@ -306,11 +306,14 @@ async def test_update_off_ws_with_power_state(
mock_now: datetime,
) -> None:
"""Testing update tv off."""
- with patch.object(
- rest_api, "rest_device_info", side_effect=HttpApiError
- ) as mock_device_info, patch.object(
- remotews, "start_listening", side_effect=WebSocketException("Boom")
- ) as mock_start_listening:
+ with (
+ patch.object(
+ rest_api, "rest_device_info", side_effect=HttpApiError
+ ) as mock_device_info,
+ patch.object(
+ remotews, "start_listening", side_effect=WebSocketException("Boom")
+ ) as mock_start_listening,
+ ):
await setup_samsungtv_entry(hass, MOCK_CONFIGWS)
mock_device_info.assert_called_once()
@@ -434,11 +437,14 @@ async def test_update_ws_connection_failure(
"""Testing update tv connection failure exception."""
await setup_samsungtv_entry(hass, MOCK_CONFIGWS)
- with patch.object(
- remotews,
- "start_listening",
- side_effect=ConnectionFailure('{"event": "ms.voiceApp.hide"}'),
- ), patch.object(remotews, "is_alive", return_value=False):
+ with (
+ patch.object(
+ remotews,
+ "start_listening",
+ side_effect=ConnectionFailure('{"event": "ms.voiceApp.hide"}'),
+ ),
+ patch.object(remotews, "is_alive", return_value=False),
+ ):
next_update = mock_now + timedelta(minutes=5)
freezer.move_to(next_update)
async_fire_time_changed(hass, next_update)
@@ -464,9 +470,12 @@ async def test_update_ws_connection_closed(
"""Testing update tv connection failure exception."""
await setup_samsungtv_entry(hass, MOCK_CONFIGWS)
- with patch.object(
- remotews, "start_listening", side_effect=ConnectionClosedError(None, None)
- ), patch.object(remotews, "is_alive", return_value=False):
+ with (
+ patch.object(
+ remotews, "start_listening", side_effect=ConnectionClosedError(None, None)
+ ),
+ patch.object(remotews, "is_alive", return_value=False),
+ ):
next_update = mock_now + timedelta(minutes=5)
freezer.move_to(next_update)
async_fire_time_changed(hass, next_update)
@@ -486,9 +495,10 @@ async def test_update_ws_unauthorized_error(
"""Testing update tv unauthorized failure exception."""
await setup_samsungtv_entry(hass, MOCK_CONFIGWS)
- with patch.object(
- remotews, "start_listening", side_effect=UnauthorizedError
- ), patch.object(remotews, "is_alive", return_value=False):
+ with (
+ patch.object(remotews, "start_listening", side_effect=UnauthorizedError),
+ patch.object(remotews, "is_alive", return_value=False),
+ ):
next_update = mock_now + timedelta(minutes=5)
freezer.move_to(next_update)
async_fire_time_changed(hass, next_update)
@@ -1438,9 +1448,12 @@ async def test_upnp_re_subscribe_events(
assert dmr_device.async_subscribe_services.call_count == 1
assert dmr_device.async_unsubscribe_services.call_count == 0
- with patch.object(
- remotews, "start_listening", side_effect=WebSocketException("Boom")
- ), patch.object(remotews, "is_alive", return_value=False):
+ with (
+ patch.object(
+ remotews, "start_listening", side_effect=WebSocketException("Boom")
+ ),
+ patch.object(remotews, "is_alive", return_value=False),
+ ):
next_update = mock_now + timedelta(minutes=5)
freezer.move_to(next_update)
async_fire_time_changed(hass, next_update)
@@ -1484,9 +1497,12 @@ async def test_upnp_failed_re_subscribe_events(
assert dmr_device.async_subscribe_services.call_count == 1
assert dmr_device.async_unsubscribe_services.call_count == 0
- with patch.object(
- remotews, "start_listening", side_effect=WebSocketException("Boom")
- ), patch.object(remotews, "is_alive", return_value=False):
+ with (
+ patch.object(
+ remotews, "start_listening", side_effect=WebSocketException("Boom")
+ ),
+ patch.object(remotews, "is_alive", return_value=False),
+ ):
next_update = mock_now + timedelta(minutes=5)
freezer.move_to(next_update)
async_fire_time_changed(hass, next_update)
diff --git a/tests/components/scrape/test_config_flow.py b/tests/components/scrape/test_config_flow.py
index 6baecae50c5..8e281e148fc 100644
--- a/tests/components/scrape/test_config_flow.py
+++ b/tests/components/scrape/test_config_flow.py
@@ -331,9 +331,12 @@ async def test_options_add_remove_sensor_flow(
assert result["step_id"] == "add_sensor"
mocker = MockRestData("test_scrape_sensor2")
- with patch("homeassistant.components.rest.RestData", return_value=mocker), patch(
- "homeassistant.components.scrape.config_flow.uuid.uuid1",
- return_value=uuid.UUID("3699ef88-69e6-11ed-a1eb-0242ac120003"),
+ with (
+ patch("homeassistant.components.rest.RestData", return_value=mocker),
+ patch(
+ "homeassistant.components.scrape.config_flow.uuid.uuid1",
+ return_value=uuid.UUID("3699ef88-69e6-11ed-a1eb-0242ac120003"),
+ ),
):
result = await hass.config_entries.options.async_configure(
result["flow_id"],
diff --git a/tests/components/screenlogic/test_config_flow.py b/tests/components/screenlogic/test_config_flow.py
index 81913e76e27..be1617e3105 100644
--- a/tests/components/screenlogic/test_config_flow.py
+++ b/tests/components/screenlogic/test_config_flow.py
@@ -100,12 +100,15 @@ async def test_flow_discover_error(hass: HomeAssistant) -> None:
assert result["errors"] == {}
assert result["step_id"] == "gateway_entry"
- with patch(
- "homeassistant.components.screenlogic.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.screenlogic.config_flow.login.async_get_mac_address",
- return_value="00-C0-33-01-01-01",
+ with (
+ patch(
+ "homeassistant.components.screenlogic.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.screenlogic.config_flow.login.async_get_mac_address",
+ return_value="00-C0-33-01-01-01",
+ ),
):
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -141,12 +144,15 @@ async def test_dhcp(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["step_id"] == "gateway_entry"
- with patch(
- "homeassistant.components.screenlogic.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.screenlogic.config_flow.login.async_get_mac_address",
- return_value="00-C0-33-01-01-01",
+ with (
+ patch(
+ "homeassistant.components.screenlogic.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.screenlogic.config_flow.login.async_get_mac_address",
+ return_value="00-C0-33-01-01-01",
+ ),
):
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -196,12 +202,15 @@ async def test_form_manual_entry(hass: HomeAssistant) -> None:
assert result2["errors"] == {}
assert result2["step_id"] == "gateway_entry"
- with patch(
- "homeassistant.components.screenlogic.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.screenlogic.config_flow.login.async_get_mac_address",
- return_value="00-C0-33-01-01-01",
+ with (
+ patch(
+ "homeassistant.components.screenlogic.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.screenlogic.config_flow.login.async_get_mac_address",
+ return_value="00-C0-33-01-01-01",
+ ),
):
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/screenlogic/test_data.py b/tests/components/screenlogic/test_data.py
index a14b2f93169..d17db6c5b33 100644
--- a/tests/components/screenlogic/test_data.py
+++ b/tests/components/screenlogic/test_data.py
@@ -53,16 +53,19 @@ async def test_async_cleanup_entries(
assert unused_entity
assert unused_entity.unique_id == TEST_UNUSED_ENTRY["unique_id"]
- with patch(
- GATEWAY_DISCOVERY_IMPORT_PATH,
- return_value={},
- ), patch.multiple(
- ScreenLogicGateway,
- async_connect=lambda *args, **kwargs: stub_async_connect(
- DATA_MIN_ENTITY_CLEANUP, *args, **kwargs
+ with (
+ patch(
+ GATEWAY_DISCOVERY_IMPORT_PATH,
+ return_value={},
+ ),
+ patch.multiple(
+ ScreenLogicGateway,
+ async_connect=lambda *args, **kwargs: stub_async_connect(
+ DATA_MIN_ENTITY_CLEANUP, *args, **kwargs
+ ),
+ is_connected=True,
+ _async_connected_request=DEFAULT,
),
- is_connected=True,
- _async_connected_request=DEFAULT,
):
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/screenlogic/test_diagnostics.py b/tests/components/screenlogic/test_diagnostics.py
index b66aa26a203..0b587bcd0e5 100644
--- a/tests/components/screenlogic/test_diagnostics.py
+++ b/tests/components/screenlogic/test_diagnostics.py
@@ -35,17 +35,20 @@ async def test_diagnostics(
config_entry_id=mock_config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, MOCK_ADAPTER_MAC)},
)
- with patch(
- GATEWAY_DISCOVERY_IMPORT_PATH,
- return_value={},
- ), patch.multiple(
- ScreenLogicGateway,
- async_connect=lambda *args, **kwargs: stub_async_connect(
- DATA_FULL_CHEM, *args, **kwargs
+ with (
+ patch(
+ GATEWAY_DISCOVERY_IMPORT_PATH,
+ return_value={},
+ ),
+ patch.multiple(
+ ScreenLogicGateway,
+ async_connect=lambda *args, **kwargs: stub_async_connect(
+ DATA_FULL_CHEM, *args, **kwargs
+ ),
+ is_connected=True,
+ _async_connected_request=DEFAULT,
+ get_debug=lambda self: {},
),
- is_connected=True,
- _async_connected_request=DEFAULT,
- get_debug=lambda self: {},
):
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/screenlogic/test_init.py b/tests/components/screenlogic/test_init.py
index 5b75517da6e..9c296fd8afd 100644
--- a/tests/components/screenlogic/test_init.py
+++ b/tests/components/screenlogic/test_init.py
@@ -157,14 +157,17 @@ async def test_async_migrate_entries(
assert entity.unique_id == old_uid
assert entity.entity_id == old_eid
- with patch(
- GATEWAY_DISCOVERY_IMPORT_PATH,
- return_value={},
- ), patch.multiple(
- ScreenLogicGateway,
- async_connect=MIGRATION_CONNECT,
- is_connected=True,
- _async_connected_request=DEFAULT,
+ with (
+ patch(
+ GATEWAY_DISCOVERY_IMPORT_PATH,
+ return_value={},
+ ),
+ patch.multiple(
+ ScreenLogicGateway,
+ async_connect=MIGRATION_CONNECT,
+ is_connected=True,
+ _async_connected_request=DEFAULT,
+ ),
):
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
@@ -216,23 +219,27 @@ async def test_entity_migration_data(
)
# This patch simulates bad data being added to ENTITY_MIGRATIONS
- with patch.dict(
- "homeassistant.components.screenlogic.data.ENTITY_MIGRATIONS",
- {
- "missing_device": {
- "new_key": "state",
- "old_name": "Missing Migration Device",
- "new_name": "Bad ENTITY_MIGRATIONS Entry",
+ with (
+ patch.dict(
+ "homeassistant.components.screenlogic.data.ENTITY_MIGRATIONS",
+ {
+ "missing_device": {
+ "new_key": "state",
+ "old_name": "Missing Migration Device",
+ "new_name": "Bad ENTITY_MIGRATIONS Entry",
+ },
},
- },
- ), patch(
- GATEWAY_DISCOVERY_IMPORT_PATH,
- return_value={},
- ), patch.multiple(
- ScreenLogicGateway,
- async_connect=MIGRATION_CONNECT,
- is_connected=True,
- _async_connected_request=DEFAULT,
+ ),
+ patch(
+ GATEWAY_DISCOVERY_IMPORT_PATH,
+ return_value={},
+ ),
+ patch.multiple(
+ ScreenLogicGateway,
+ async_connect=MIGRATION_CONNECT,
+ is_connected=True,
+ _async_connected_request=DEFAULT,
+ ),
):
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
@@ -264,14 +271,17 @@ async def test_platform_setup(
mock_config_entry.add_to_hass(hass)
- with patch(
- GATEWAY_DISCOVERY_IMPORT_PATH,
- return_value={},
- ), patch.multiple(
- ScreenLogicGateway,
- async_connect=stub_connect,
- is_connected=True,
- _async_connected_request=DEFAULT,
+ with (
+ patch(
+ GATEWAY_DISCOVERY_IMPORT_PATH,
+ return_value={},
+ ),
+ patch.multiple(
+ ScreenLogicGateway,
+ async_connect=stub_connect,
+ is_connected=True,
+ _async_connected_request=DEFAULT,
+ ),
):
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/sensibo/conftest.py b/tests/components/sensibo/conftest.py
index 01f77d7d40c..d98b19c3833 100644
--- a/tests/components/sensibo/conftest.py
+++ b/tests/components/sensibo/conftest.py
@@ -34,15 +34,19 @@ async def load_int(hass: HomeAssistant, get_data: SensiboData) -> MockConfigEntr
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
- return_value={"result": [{"id": "xyzxyz"}, {"id": "abcabc"}]},
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
- return_value={"result": {"username": "username"}},
+ with (
+ patch(
+ "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
+ return_value={"result": [{"id": "xyzxyz"}, {"id": "abcabc"}]},
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
+ return_value={"result": {"username": "username"}},
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/sensibo/test_button.py b/tests/components/sensibo/test_button.py
index e94a3c00fd5..6d7ce442562 100644
--- a/tests/components/sensibo/test_button.py
+++ b/tests/components/sensibo/test_button.py
@@ -42,12 +42,15 @@ async def test_button(
today_str = today.isoformat()
freezer.move_to(today)
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_reset_filter",
- return_value={"status": "success"},
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_reset_filter",
+ return_value={"status": "success"},
+ ),
):
await hass.services.async_call(
BUTTON_DOMAIN,
@@ -94,14 +97,18 @@ async def test_button_failure(
state_button = hass.states.get("button.hallway_reset_filter")
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_reset_filter",
- return_value={"status": "failure"},
- ), pytest.raises(
- HomeAssistantError,
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_reset_filter",
+ return_value={"status": "failure"},
+ ),
+ pytest.raises(
+ HomeAssistantError,
+ ),
):
await hass.services.async_call(
BUTTON_DOMAIN,
diff --git a/tests/components/sensibo/test_climate.py b/tests/components/sensibo/test_climate.py
index 9634abc66fc..061e31f9771 100644
--- a/tests/components/sensibo/test_climate.py
+++ b/tests/components/sensibo/test_climate.py
@@ -121,12 +121,15 @@ async def test_climate_fan(
state1 = hass.states.get("climate.hallway")
assert state1.attributes["fan_mode"] == "high"
- with patch(
- "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
- return_value={"result": {"status": "Success"}},
+ with (
+ patch(
+ "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
+ return_value={"result": {"status": "Success"}},
+ ),
):
await hass.services.async_call(
CLIMATE_DOMAIN,
@@ -162,9 +165,12 @@ async def test_climate_fan(
)
await hass.async_block_till_done()
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
- ), pytest.raises(HomeAssistantError):
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
+ ),
+ pytest.raises(HomeAssistantError),
+ ):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_FAN_MODE,
@@ -188,12 +194,15 @@ async def test_climate_swing(
state1 = hass.states.get("climate.hallway")
assert state1.attributes["swing_mode"] == "stopped"
- with patch(
- "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
- return_value={"result": {"status": "Success"}},
+ with (
+ patch(
+ "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
+ return_value={"result": {"status": "Success"}},
+ ),
):
await hass.services.async_call(
CLIMATE_DOMAIN,
@@ -228,9 +237,12 @@ async def test_climate_swing(
)
await hass.async_block_till_done()
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
- ), pytest.raises(HomeAssistantError):
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
+ ),
+ pytest.raises(HomeAssistantError),
+ ):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_SWING_MODE,
@@ -254,12 +266,15 @@ async def test_climate_temperatures(
state1 = hass.states.get("climate.hallway")
assert state1.attributes["temperature"] == 25
- with patch(
- "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
- return_value={"result": {"status": "Success"}},
+ with (
+ patch(
+ "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
+ return_value={"result": {"status": "Success"}},
+ ),
):
await hass.services.async_call(
CLIMATE_DOMAIN,
@@ -272,12 +287,15 @@ async def test_climate_temperatures(
state2 = hass.states.get("climate.hallway")
assert state2.attributes["temperature"] == 20
- with patch(
- "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
- return_value={"result": {"status": "Success"}},
+ with (
+ patch(
+ "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
+ return_value={"result": {"status": "Success"}},
+ ),
):
await hass.services.async_call(
CLIMATE_DOMAIN,
@@ -290,12 +308,15 @@ async def test_climate_temperatures(
state2 = hass.states.get("climate.hallway")
assert state2.attributes["temperature"] == 16
- with patch(
- "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
- return_value={"result": {"status": "Success"}},
+ with (
+ patch(
+ "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
+ return_value={"result": {"status": "Success"}},
+ ),
):
await hass.services.async_call(
CLIMATE_DOMAIN,
@@ -308,12 +329,15 @@ async def test_climate_temperatures(
state2 = hass.states.get("climate.hallway")
assert state2.attributes["temperature"] == 19
- with patch(
- "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
- return_value={"result": {"status": "Success"}},
+ with (
+ patch(
+ "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
+ return_value={"result": {"status": "Success"}},
+ ),
):
await hass.services.async_call(
CLIMATE_DOMAIN,
@@ -326,12 +350,15 @@ async def test_climate_temperatures(
state2 = hass.states.get("climate.hallway")
assert state2.attributes["temperature"] == 20
- with patch(
- "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
- return_value={"result": {"status": "Success"}},
+ with (
+ patch(
+ "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
+ return_value={"result": {"status": "Success"}},
+ ),
):
await hass.services.async_call(
CLIMATE_DOMAIN,
@@ -344,10 +371,13 @@ async def test_climate_temperatures(
state2 = hass.states.get("climate.hallway")
assert state2.attributes["temperature"] == 20
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
- return_value={"result": {"status": "Success"}},
- ), pytest.raises(MultipleInvalid):
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
+ return_value={"result": {"status": "Success"}},
+ ),
+ pytest.raises(MultipleInvalid),
+ ):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
@@ -381,10 +411,13 @@ async def test_climate_temperatures(
)
await hass.async_block_till_done()
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
- return_value={"result": {"status": "Success"}},
- ), pytest.raises(HomeAssistantError):
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
+ return_value={"result": {"status": "Success"}},
+ ),
+ pytest.raises(HomeAssistantError),
+ ):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
@@ -437,9 +470,12 @@ async def test_climate_temperature_is_none(
state1 = hass.states.get("climate.hallway")
assert state1.attributes["temperature"] == 25
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
- ), pytest.raises(ServiceValidationError):
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
+ ),
+ pytest.raises(ServiceValidationError),
+ ):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
@@ -491,12 +527,15 @@ async def test_climate_hvac_mode(
state1 = hass.states.get("climate.hallway")
assert state1.state == "heat"
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
- return_value={"result": {"status": "Success"}},
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
+ return_value={"result": {"status": "Success"}},
+ ),
):
await hass.services.async_call(
CLIMATE_DOMAIN,
@@ -520,12 +559,15 @@ async def test_climate_hvac_mode(
)
await hass.async_block_till_done()
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
- return_value={"result": {"status": "Success"}},
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
+ return_value={"result": {"status": "Success"}},
+ ),
):
await hass.services.async_call(
CLIMATE_DOMAIN,
@@ -562,12 +604,15 @@ async def test_climate_on_off(
state1 = hass.states.get("climate.hallway")
assert state1.state == "heat"
- with patch(
- "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
- return_value={"result": {"status": "Success"}},
+ with (
+ patch(
+ "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
+ return_value={"result": {"status": "Success"}},
+ ),
):
await hass.services.async_call(
CLIMATE_DOMAIN,
@@ -580,12 +625,15 @@ async def test_climate_on_off(
state2 = hass.states.get("climate.hallway")
assert state2.state == "off"
- with patch(
- "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
- return_value={"result": {"status": "Success"}},
+ with (
+ patch(
+ "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
+ return_value={"result": {"status": "Success"}},
+ ),
):
await hass.services.async_call(
CLIMATE_DOMAIN,
@@ -622,10 +670,15 @@ async def test_climate_service_failed(
state1 = hass.states.get("climate.hallway")
assert state1.state == "heat"
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
- return_value={"result": {"status": "Error", "failureReason": "Did not work"}},
- ), pytest.raises(HomeAssistantError):
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
+ return_value={
+ "result": {"status": "Error", "failureReason": "Did not work"}
+ },
+ ),
+ pytest.raises(HomeAssistantError),
+ ):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_TURN_OFF,
@@ -661,12 +714,15 @@ async def test_climate_assumed_state(
state1 = hass.states.get("climate.hallway")
assert state1.state == "heat"
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
- return_value={"result": {"status": "Success"}},
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
+ return_value={"result": {"status": "Success"}},
+ ),
):
await hass.services.async_call(
DOMAIN,
@@ -736,14 +792,18 @@ async def test_climate_set_timer(
state_climate = hass.states.get("climate.hallway")
assert hass.states.get("sensor.hallway_timer_end_time").state == STATE_UNKNOWN
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_timer",
- return_value={"status": "failure"},
- ), pytest.raises(
- MultipleInvalid,
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_timer",
+ return_value={"status": "failure"},
+ ),
+ pytest.raises(
+ MultipleInvalid,
+ ),
):
await hass.services.async_call(
DOMAIN,
@@ -755,14 +815,18 @@ async def test_climate_set_timer(
)
await hass.async_block_till_done()
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_timer",
- return_value={"status": "failure"},
- ), pytest.raises(
- HomeAssistantError,
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_timer",
+ return_value={"status": "failure"},
+ ),
+ pytest.raises(
+ HomeAssistantError,
+ ),
):
await hass.services.async_call(
DOMAIN,
@@ -775,12 +839,15 @@ async def test_climate_set_timer(
)
await hass.async_block_till_done()
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_timer",
- return_value={"status": "success", "result": {"id": "SzTGE4oZ4D"}},
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_timer",
+ return_value={"status": "success", "result": {"id": "SzTGE4oZ4D"}},
+ ),
):
await hass.services.async_call(
DOMAIN,
@@ -841,12 +908,16 @@ async def test_climate_pure_boost(
state2 = hass.states.get("switch.kitchen_pure_boost")
assert state2.state == "off"
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_pureboost",
- ), pytest.raises(
- MultipleInvalid,
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_pureboost",
+ ),
+ pytest.raises(
+ MultipleInvalid,
+ ),
):
await hass.services.async_call(
DOMAIN,
@@ -861,22 +932,25 @@ async def test_climate_pure_boost(
)
await hass.async_block_till_done()
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_pureboost",
- return_value={
- "status": "success",
- "result": {
- "enabled": True,
- "sensitivity": "S",
- "measurements_integration": True,
- "ac_integration": False,
- "geo_integration": False,
- "prime_integration": True,
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_pureboost",
+ return_value={
+ "status": "success",
+ "result": {
+ "enabled": True,
+ "sensitivity": "S",
+ "measurements_integration": True,
+ "ac_integration": False,
+ "geo_integration": False,
+ "prime_integration": True,
+ },
},
- },
+ ),
):
await hass.services.async_call(
DOMAIN,
@@ -943,12 +1017,16 @@ async def test_climate_climate_react(
state_climate = hass.states.get("climate.hallway")
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_climate_react",
- ), pytest.raises(
- MultipleInvalid,
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_climate_react",
+ ),
+ pytest.raises(
+ MultipleInvalid,
+ ),
):
await hass.services.async_call(
DOMAIN,
@@ -963,41 +1041,44 @@ async def test_climate_climate_react(
)
await hass.async_block_till_done()
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_climate_react",
- return_value={
- "status": "success",
- "result": {
- "enabled": True,
- "deviceUid": "ABC999111",
- "highTemperatureState": {
- "on": True,
- "targetTemperature": 15,
- "temperatureUnit": "C",
- "mode": "cool",
- "fanLevel": "high",
- "swing": "stopped",
- "horizontalSwing": "stopped",
- "light": "on",
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_climate_react",
+ return_value={
+ "status": "success",
+ "result": {
+ "enabled": True,
+ "deviceUid": "ABC999111",
+ "highTemperatureState": {
+ "on": True,
+ "targetTemperature": 15,
+ "temperatureUnit": "C",
+ "mode": "cool",
+ "fanLevel": "high",
+ "swing": "stopped",
+ "horizontalSwing": "stopped",
+ "light": "on",
+ },
+ "highTemperatureThreshold": 30.5,
+ "lowTemperatureState": {
+ "on": True,
+ "targetTemperature": 25,
+ "temperatureUnit": "C",
+ "mode": "heat",
+ "fanLevel": "low",
+ "swing": "stopped",
+ "horizontalSwing": "stopped",
+ "light": "on",
+ },
+ "lowTemperatureThreshold": 5.5,
+ "type": "temperature",
},
- "highTemperatureThreshold": 30.5,
- "lowTemperatureState": {
- "on": True,
- "targetTemperature": 25,
- "temperatureUnit": "C",
- "mode": "heat",
- "fanLevel": "low",
- "swing": "stopped",
- "horizontalSwing": "stopped",
- "light": "on",
- },
- "lowTemperatureThreshold": 5.5,
- "type": "temperature",
},
- },
+ ),
):
await hass.services.async_call(
DOMAIN,
@@ -1106,41 +1187,44 @@ async def test_climate_climate_react_fahrenheit(
state_climate = hass.states.get("climate.hallway")
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_climate_react",
- return_value={
- "status": "success",
- "result": {
- "enabled": True,
- "deviceUid": "ABC999111",
- "highTemperatureState": {
- "on": True,
- "targetTemperature": 65,
- "temperatureUnit": "F",
- "mode": "cool",
- "fanLevel": "high",
- "swing": "stopped",
- "horizontalSwing": "stopped",
- "light": "on",
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_climate_react",
+ return_value={
+ "status": "success",
+ "result": {
+ "enabled": True,
+ "deviceUid": "ABC999111",
+ "highTemperatureState": {
+ "on": True,
+ "targetTemperature": 65,
+ "temperatureUnit": "F",
+ "mode": "cool",
+ "fanLevel": "high",
+ "swing": "stopped",
+ "horizontalSwing": "stopped",
+ "light": "on",
+ },
+ "highTemperatureThreshold": 77,
+ "lowTemperatureState": {
+ "on": True,
+ "targetTemperature": 85,
+ "temperatureUnit": "F",
+ "mode": "heat",
+ "fanLevel": "low",
+ "swing": "stopped",
+ "horizontalSwing": "stopped",
+ "light": "on",
+ },
+ "lowTemperatureThreshold": 32,
+ "type": "temperature",
},
- "highTemperatureThreshold": 77,
- "lowTemperatureState": {
- "on": True,
- "targetTemperature": 85,
- "temperatureUnit": "F",
- "mode": "heat",
- "fanLevel": "low",
- "swing": "stopped",
- "horizontalSwing": "stopped",
- "light": "on",
- },
- "lowTemperatureThreshold": 32,
- "type": "temperature",
},
- },
+ ),
):
await hass.services.async_call(
DOMAIN,
@@ -1250,12 +1334,16 @@ async def test_climate_full_ac_state(
state_climate = hass.states.get("climate.hallway")
assert state_climate.state == "heat"
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_states",
- ), pytest.raises(
- MultipleInvalid,
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_states",
+ ),
+ pytest.raises(
+ MultipleInvalid,
+ ),
):
await hass.services.async_call(
DOMAIN,
@@ -1268,12 +1356,15 @@ async def test_climate_full_ac_state(
)
await hass.async_block_till_done()
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_states",
- return_value={"result": {"status": "Success"}},
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_states",
+ return_value={"result": {"status": "Success"}},
+ ),
):
await hass.services.async_call(
DOMAIN,
@@ -1329,9 +1420,12 @@ async def test_climate_fan_mode_and_swing_mode_not_supported(
assert state1.attributes["fan_mode"] == "high"
assert state1.attributes["swing_mode"] == "stopped"
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
- ), pytest.raises(ServiceValidationError):
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
+ ),
+ pytest.raises(ServiceValidationError),
+ ):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_SWING_MODE,
@@ -1339,9 +1433,12 @@ async def test_climate_fan_mode_and_swing_mode_not_supported(
blocking=True,
)
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
- ), pytest.raises(ServiceValidationError):
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
+ ),
+ pytest.raises(ServiceValidationError),
+ ):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_FAN_MODE,
diff --git a/tests/components/sensibo/test_config_flow.py b/tests/components/sensibo/test_config_flow.py
index 12c4e187550..3b1117f0908 100644
--- a/tests/components/sensibo/test_config_flow.py
+++ b/tests/components/sensibo/test_config_flow.py
@@ -29,16 +29,20 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
- return_value={"result": [{"id": "xyzxyz"}, {"id": "abcabc"}]},
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
- return_value={"result": {"username": "username"}},
- ), patch(
- "homeassistant.components.sensibo.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
+ return_value={"result": [{"id": "xyzxyz"}, {"id": "abcabc"}]},
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
+ return_value={"result": {"username": "username"}},
+ ),
+ patch(
+ "homeassistant.components.sensibo.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -90,15 +94,19 @@ async def test_flow_fails(
assert result2["errors"] == {"base": p_error}
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
- return_value={"result": [{"id": "xyzxyz"}, {"id": "abcabc"}]},
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
- return_value={"result": {"username": "username"}},
- ), patch(
- "homeassistant.components.sensibo.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
+ return_value={"result": [{"id": "xyzxyz"}, {"id": "abcabc"}]},
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
+ return_value={"result": {"username": "username"}},
+ ),
+ patch(
+ "homeassistant.components.sensibo.async_setup_entry",
+ return_value=True,
+ ),
):
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -124,12 +132,15 @@ async def test_flow_get_no_devices(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == config_entries.SOURCE_USER
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
- return_value={"result": []},
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
- return_value={"result": {}},
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
+ return_value={"result": []},
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
+ return_value={"result": {}},
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -151,12 +162,15 @@ async def test_flow_get_no_username(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == config_entries.SOURCE_USER
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
- return_value={"result": [{"id": "xyzxyz"}, {"id": "abcabc"}]},
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
- return_value={"result": {}},
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
+ return_value={"result": [{"id": "xyzxyz"}, {"id": "abcabc"}]},
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
+ return_value={"result": {}},
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -191,16 +205,20 @@ async def test_reauth_flow(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
- return_value={"result": [{"id": "xyzxyz"}, {"id": "abcabc"}]},
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
- return_value={"result": {"username": "username"}},
- ) as mock_sensibo, patch(
- "homeassistant.components.sensibo.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
+ return_value={"result": [{"id": "xyzxyz"}, {"id": "abcabc"}]},
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
+ return_value={"result": {"username": "username"}},
+ ) as mock_sensibo,
+ patch(
+ "homeassistant.components.sensibo.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_API_KEY: "1234567891"},
@@ -260,15 +278,19 @@ async def test_reauth_flow_error(
assert result2["type"] == FlowResultType.FORM
assert result2["errors"] == {"base": p_error}
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
- return_value={"result": [{"id": "xyzxyz"}, {"id": "abcabc"}]},
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
- return_value={"result": {"username": "username"}},
- ), patch(
- "homeassistant.components.sensibo.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
+ return_value={"result": [{"id": "xyzxyz"}, {"id": "abcabc"}]},
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
+ return_value={"result": {"username": "username"}},
+ ),
+ patch(
+ "homeassistant.components.sensibo.async_setup_entry",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -329,12 +351,15 @@ async def test_flow_reauth_no_username_or_device(
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
- return_value=get_devices,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
- return_value=get_me,
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
+ return_value=get_devices,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
+ return_value=get_me,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/sensibo/test_coordinator.py b/tests/components/sensibo/test_coordinator.py
index ba07cec2eda..d81b7fd613c 100644
--- a/tests/components/sensibo/test_coordinator.py
+++ b/tests/components/sensibo/test_coordinator.py
@@ -35,14 +35,18 @@ async def test_coordinator(
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
- ) as mock_data, patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
- return_value={"result": [{"id": "xyzxyz"}, {"id": "abcabc"}]},
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
- return_value={"result": {"username": "username"}},
+ with (
+ patch(
+ "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
+ ) as mock_data,
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
+ return_value={"result": [{"id": "xyzxyz"}, {"id": "abcabc"}]},
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
+ return_value={"result": {"username": "username"}},
+ ),
):
monkeypatch.setattr(get_data.parsed["ABC999111"], "hvac_mode", "heat")
monkeypatch.setattr(get_data.parsed["ABC999111"], "device_on", True)
diff --git a/tests/components/sensibo/test_entity.py b/tests/components/sensibo/test_entity.py
index dbd6b76d0bf..071e5473e5c 100644
--- a/tests/components/sensibo/test_entity.py
+++ b/tests/components/sensibo/test_entity.py
@@ -73,10 +73,13 @@ async def test_entity_failed_service_calls(
state = hass.states.get("climate.hallway")
assert state.attributes["fan_mode"] == "low"
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
- side_effect=p_error,
- ), pytest.raises(HomeAssistantError):
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
+ side_effect=p_error,
+ ),
+ pytest.raises(HomeAssistantError),
+ ):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_FAN_MODE,
diff --git a/tests/components/sensibo/test_init.py b/tests/components/sensibo/test_init.py
index 49aa629d159..9698d5241cc 100644
--- a/tests/components/sensibo/test_init.py
+++ b/tests/components/sensibo/test_init.py
@@ -32,15 +32,19 @@ async def test_setup_entry(hass: HomeAssistant, get_data: SensiboData) -> None:
)
entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
- return_value={"result": [{"id": "xyzxyz"}, {"id": "abcabc"}]},
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
- return_value={"result": {"username": "username"}},
+ with (
+ patch(
+ "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
+ return_value={"result": [{"id": "xyzxyz"}, {"id": "abcabc"}]},
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
+ return_value={"result": {"username": "username"}},
+ ),
):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
@@ -60,15 +64,19 @@ async def test_migrate_entry(hass: HomeAssistant, get_data: SensiboData) -> None
)
entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
- return_value={"result": [{"id": "xyzxyz"}, {"id": "abcabc"}]},
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
- return_value={"result": {"username": "username"}},
+ with (
+ patch(
+ "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
+ return_value={"result": [{"id": "xyzxyz"}, {"id": "abcabc"}]},
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
+ return_value={"result": {"username": "username"}},
+ ),
):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
@@ -90,13 +98,17 @@ async def test_migrate_entry_fails(hass: HomeAssistant, get_data: SensiboData) -
)
entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
- side_effect=NoUsernameError("No username returned"),
+ with (
+ patch(
+ "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
+ side_effect=NoUsernameError("No username returned"),
+ ),
):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
@@ -118,15 +130,19 @@ async def test_unload_entry(hass: HomeAssistant, get_data: SensiboData) -> None:
)
entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
- return_value={"result": [{"id": "xyzxyz"}, {"id": "abcabc"}]},
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
- return_value={"result": {"username": "username"}},
+ with (
+ patch(
+ "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices",
+ return_value={"result": [{"id": "xyzxyz"}, {"id": "abcabc"}]},
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_me",
+ return_value={"result": {"username": "username"}},
+ ),
):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/sensibo/test_number.py b/tests/components/sensibo/test_number.py
index fc692b8ecc0..e0a5a6a8bde 100644
--- a/tests/components/sensibo/test_number.py
+++ b/tests/components/sensibo/test_number.py
@@ -63,12 +63,15 @@ async def test_number_set_value(
state1 = hass.states.get("number.hallway_temperature_calibration")
assert state1.state == "0.1"
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_calibration",
- return_value={"status": "failure"},
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_calibration",
+ return_value={"status": "failure"},
+ ),
):
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
@@ -82,12 +85,15 @@ async def test_number_set_value(
state2 = hass.states.get("number.hallway_temperature_calibration")
assert state2.state == "0.1"
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_calibration",
- return_value={"status": "success"},
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_calibration",
+ return_value={"status": "success"},
+ ),
):
await hass.services.async_call(
NUMBER_DOMAIN,
diff --git a/tests/components/sensibo/test_select.py b/tests/components/sensibo/test_select.py
index 6ff4afa5d47..7a9c89ef612 100644
--- a/tests/components/sensibo/test_select.py
+++ b/tests/components/sensibo/test_select.py
@@ -84,14 +84,18 @@ async def test_select_set_option(
state1 = hass.states.get("select.hallway_horizontal_swing")
assert state1.state == "stopped"
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
- return_value={"result": {"status": "failed"}},
- ), pytest.raises(
- HomeAssistantError,
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
+ return_value={"result": {"status": "failed"}},
+ ),
+ pytest.raises(
+ HomeAssistantError,
+ ),
):
await hass.services.async_call(
SELECT_DOMAIN,
@@ -127,13 +131,19 @@ async def test_select_set_option(
)
await hass.async_block_till_done()
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
- return_value={"result": {"status": "Failed", "failureReason": "No connection"}},
- ), pytest.raises(
- HomeAssistantError,
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
+ return_value={
+ "result": {"status": "Failed", "failureReason": "No connection"}
+ },
+ ),
+ pytest.raises(
+ HomeAssistantError,
+ ),
):
await hass.services.async_call(
SELECT_DOMAIN,
@@ -146,12 +156,15 @@ async def test_select_set_option(
state2 = hass.states.get("select.hallway_horizontal_swing")
assert state2.state == "stopped"
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
- return_value={"result": {"status": "Success"}},
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property",
+ return_value={"result": {"status": "Success"}},
+ ),
):
await hass.services.async_call(
SELECT_DOMAIN,
diff --git a/tests/components/sensibo/test_switch.py b/tests/components/sensibo/test_switch.py
index b0f9a8d2a59..cc3c8881bec 100644
--- a/tests/components/sensibo/test_switch.py
+++ b/tests/components/sensibo/test_switch.py
@@ -37,12 +37,15 @@ async def test_switch_timer(
assert state1.attributes["id"] is None
assert state1.attributes["turn_on"] is None
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_timer",
- return_value={"status": "success", "result": {"id": "SzTGE4oZ4D"}},
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_timer",
+ return_value={"status": "success", "result": {"id": "SzTGE4oZ4D"}},
+ ),
):
await hass.services.async_call(
SWITCH_DOMAIN,
@@ -71,12 +74,15 @@ async def test_switch_timer(
assert state1.attributes["id"] == "SzTGE4oZ4D"
assert state1.attributes["turn_on"] is False
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_del_timer",
- return_value={"status": "success", "result": {"id": "SzTGE4oZ4D"}},
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_del_timer",
+ return_value={"status": "success", "result": {"id": "SzTGE4oZ4D"}},
+ ),
):
await hass.services.async_call(
SWITCH_DOMAIN,
@@ -115,12 +121,15 @@ async def test_switch_pure_boost(
state1 = hass.states.get("switch.kitchen_pure_boost")
assert state1.state == STATE_OFF
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_pureboost",
- return_value={"status": "success"},
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_pureboost",
+ return_value={"status": "success"},
+ ),
):
await hass.services.async_call(
SWITCH_DOMAIN,
@@ -147,12 +156,15 @@ async def test_switch_pure_boost(
state1 = hass.states.get("switch.kitchen_pure_boost")
assert state1.state == STATE_ON
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_pureboost",
- return_value={"status": "success"},
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_pureboost",
+ return_value={"status": "success"},
+ ),
):
await hass.services.async_call(
SWITCH_DOMAIN,
@@ -190,14 +202,18 @@ async def test_switch_command_failure(
state1 = hass.states.get("switch.hallway_timer")
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_set_timer",
- return_value={"status": "failure"},
- ), pytest.raises(
- HomeAssistantError,
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_set_timer",
+ return_value={"status": "failure"},
+ ),
+ pytest.raises(
+ HomeAssistantError,
+ ),
):
await hass.services.async_call(
SWITCH_DOMAIN,
@@ -208,14 +224,18 @@ async def test_switch_command_failure(
blocking=True,
)
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_del_timer",
- return_value={"status": "failure"},
- ), pytest.raises(
- HomeAssistantError,
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_del_timer",
+ return_value={"status": "failure"},
+ ),
+ pytest.raises(
+ HomeAssistantError,
+ ),
):
await hass.services.async_call(
SWITCH_DOMAIN,
@@ -238,12 +258,15 @@ async def test_switch_climate_react(
state1 = hass.states.get("switch.hallway_climate_react")
assert state1.state == STATE_OFF
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_enable_climate_react",
- return_value={"status": "success"},
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_enable_climate_react",
+ return_value={"status": "success"},
+ ),
):
await hass.services.async_call(
SWITCH_DOMAIN,
@@ -269,12 +292,15 @@ async def test_switch_climate_react(
state1 = hass.states.get("switch.hallway_climate_react")
assert state1.state == STATE_ON
- with patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
- return_value=get_data,
- ), patch(
- "homeassistant.components.sensibo.util.SensiboClient.async_enable_climate_react",
- return_value={"status": "success"},
+ with (
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_get_devices_data",
+ return_value=get_data,
+ ),
+ patch(
+ "homeassistant.components.sensibo.util.SensiboClient.async_enable_climate_react",
+ return_value={"status": "success"},
+ ),
):
await hass.services.async_call(
SWITCH_DOMAIN,
diff --git a/tests/components/sensorpush/test_sensor.py b/tests/components/sensorpush/test_sensor.py
index 1054f97fb12..cf69fc903f6 100644
--- a/tests/components/sensorpush/test_sensor.py
+++ b/tests/components/sensorpush/test_sensor.py
@@ -56,9 +56,12 @@ async def test_sensors(hass: HomeAssistant) -> None:
# Fastforward time without BLE advertisements
monotonic_now = start_monotonic + FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 1
- with patch_bluetooth_time(
- monotonic_now,
- ), patch_all_discovered_devices([]):
+ with (
+ patch_bluetooth_time(
+ monotonic_now,
+ ),
+ patch_all_discovered_devices([]),
+ ):
async_fire_time_changed(
hass,
dt_util.utcnow()
diff --git a/tests/components/sentry/test_config_flow.py b/tests/components/sentry/test_config_flow.py
index edcd87cd5d9..0c3fc45b68b 100644
--- a/tests/components/sentry/test_config_flow.py
+++ b/tests/components/sentry/test_config_flow.py
@@ -32,10 +32,13 @@ async def test_full_user_flow_implementation(hass: HomeAssistant) -> None:
assert result.get("type") == FlowResultType.FORM
assert result.get("errors") == {}
- with patch("homeassistant.components.sentry.config_flow.Dsn"), patch(
- "homeassistant.components.sentry.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("homeassistant.components.sentry.config_flow.Dsn"),
+ patch(
+ "homeassistant.components.sentry.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"dsn": "http://public@sentry.local/1"},
diff --git a/tests/components/sentry/test_init.py b/tests/components/sentry/test_init.py
index b8c5c4cbde9..3dd1dcd9b46 100644
--- a/tests/components/sentry/test_init.py
+++ b/tests/components/sentry/test_init.py
@@ -30,15 +30,18 @@ async def test_setup_entry(hass: HomeAssistant) -> None:
)
entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.sentry.AioHttpIntegration"
- ) as sentry_aiohttp_mock, patch(
- "homeassistant.components.sentry.SqlalchemyIntegration"
- ) as sentry_sqlalchemy_mock, patch(
- "homeassistant.components.sentry.LoggingIntegration"
- ) as sentry_logging_mock, patch(
- "homeassistant.components.sentry.sentry_sdk"
- ) as sentry_mock:
+ with (
+ patch(
+ "homeassistant.components.sentry.AioHttpIntegration"
+ ) as sentry_aiohttp_mock,
+ patch(
+ "homeassistant.components.sentry.SqlalchemyIntegration"
+ ) as sentry_sqlalchemy_mock,
+ patch(
+ "homeassistant.components.sentry.LoggingIntegration"
+ ) as sentry_logging_mock,
+ patch("homeassistant.components.sentry.sentry_sdk") as sentry_mock,
+ ):
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
@@ -84,11 +87,12 @@ async def test_setup_entry_with_tracing(hass: HomeAssistant) -> None:
)
entry.add_to_hass(hass)
- with patch("homeassistant.components.sentry.AioHttpIntegration"), patch(
- "homeassistant.components.sentry.SqlalchemyIntegration"
- ), patch("homeassistant.components.sentry.LoggingIntegration"), patch(
- "homeassistant.components.sentry.sentry_sdk"
- ) as sentry_mock:
+ with (
+ patch("homeassistant.components.sentry.AioHttpIntegration"),
+ patch("homeassistant.components.sentry.SqlalchemyIntegration"),
+ patch("homeassistant.components.sentry.LoggingIntegration"),
+ patch("homeassistant.components.sentry.sentry_sdk") as sentry_mock,
+ ):
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/sfr_box/test_button.py b/tests/components/sfr_box/test_button.py
index a83c46dbd87..618ad6fc34b 100644
--- a/tests/components/sfr_box/test_button.py
+++ b/tests/components/sfr_box/test_button.py
@@ -20,9 +20,12 @@ pytestmark = pytest.mark.usefixtures("system_get_info", "dsl_get_info", "wan_get
@pytest.fixture(autouse=True)
def override_platforms() -> Generator[None, None, None]:
"""Override PLATFORMS_WITH_AUTH."""
- with patch(
- "homeassistant.components.sfr_box.PLATFORMS_WITH_AUTH", [Platform.BUTTON]
- ), patch("homeassistant.components.sfr_box.coordinator.SFRBox.authenticate"):
+ with (
+ patch(
+ "homeassistant.components.sfr_box.PLATFORMS_WITH_AUTH", [Platform.BUTTON]
+ ),
+ patch("homeassistant.components.sfr_box.coordinator.SFRBox.authenticate"),
+ ):
yield
@@ -73,10 +76,13 @@ async def test_reboot(hass: HomeAssistant, config_entry_with_auth: ConfigEntry)
# Reboot failed
service_data = {ATTR_ENTITY_ID: "button.sfr_box_restart"}
- with patch(
- "homeassistant.components.sfr_box.button.SFRBox.system_reboot",
- side_effect=SFRBoxError,
- ) as mock_action, pytest.raises(HomeAssistantError):
+ with (
+ patch(
+ "homeassistant.components.sfr_box.button.SFRBox.system_reboot",
+ side_effect=SFRBoxError,
+ ) as mock_action,
+ pytest.raises(HomeAssistantError),
+ ):
await hass.services.async_call(
BUTTON_DOMAIN, SERVICE_PRESS, service_data=service_data, blocking=True
)
diff --git a/tests/components/sharkiq/test_config_flow.py b/tests/components/sharkiq/test_config_flow.py
index da185968127..a81c185fd71 100644
--- a/tests/components/sharkiq/test_config_flow.py
+++ b/tests/components/sharkiq/test_config_flow.py
@@ -44,10 +44,13 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch("sharkiq.AylaApi.async_sign_in", return_value=True), patch(
- "homeassistant.components.sharkiq.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("sharkiq.AylaApi.async_sign_in", return_value=True),
+ patch(
+ "homeassistant.components.sharkiq.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
CONFIG,
diff --git a/tests/components/shell_command/test_init.py b/tests/components/shell_command/test_init.py
index 89fb768db2d..93b06ddf9d8 100644
--- a/tests/components/shell_command/test_init.py
+++ b/tests/components/shell_command/test_init.py
@@ -251,9 +251,12 @@ async def test_do_not_run_forever(
)
await hass.async_block_till_done()
- with patch.object(shell_command, "COMMAND_TIMEOUT", 0.001), patch(
- "homeassistant.components.shell_command.asyncio.create_subprocess_shell",
- side_effect=mock_create_subprocess_shell,
+ with (
+ patch.object(shell_command, "COMMAND_TIMEOUT", 0.001),
+ patch(
+ "homeassistant.components.shell_command.asyncio.create_subprocess_shell",
+ side_effect=mock_create_subprocess_shell,
+ ),
):
with pytest.raises(TimeoutError):
await hass.services.async_call(
diff --git a/tests/components/shelly/conftest.py b/tests/components/shelly/conftest.py
index 9e8dd3999a6..9a73252ca6c 100644
--- a/tests/components/shelly/conftest.py
+++ b/tests/components/shelly/conftest.py
@@ -355,8 +355,9 @@ def _mock_rpc_device(version: str | None = None):
@pytest.fixture
async def mock_rpc_device():
"""Mock rpc (Gen2, Websocket) device with BLE support."""
- with patch("aioshelly.rpc_device.RpcDevice.create") as rpc_device_mock, patch(
- "homeassistant.components.shelly.bluetooth.async_start_scanner"
+ with (
+ patch("aioshelly.rpc_device.RpcDevice.create") as rpc_device_mock,
+ patch("homeassistant.components.shelly.bluetooth.async_start_scanner"),
):
def update():
diff --git a/tests/components/shelly/test_config_flow.py b/tests/components/shelly/test_config_flow.py
index 99b30062d43..1e7bbc01d6d 100644
--- a/tests/components/shelly/test_config_flow.py
+++ b/tests/components/shelly/test_config_flow.py
@@ -77,21 +77,25 @@ async def test_form(
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.shelly.config_flow.get_info",
- return_value={
- "mac": "test-mac",
- "type": MODEL_1,
- "auth": False,
- "gen": gen,
- "port": port,
- },
- ), patch(
- "homeassistant.components.shelly.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.shelly.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.shelly.config_flow.get_info",
+ return_value={
+ "mac": "test-mac",
+ "type": MODEL_1,
+ "auth": False,
+ "gen": gen,
+ "port": port,
+ },
+ ),
+ patch(
+ "homeassistant.components.shelly.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.shelly.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"host": "1.1.1.1", "port": port},
@@ -122,12 +126,15 @@ async def test_form_gen1_custom_port(
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.shelly.config_flow.get_info",
- return_value={"mac": "test-mac", "type": MODEL_1, "gen": 1},
- ), patch(
- "aioshelly.block_device.BlockDevice.create",
- side_effect=CustomPortNotSupported,
+ with (
+ patch(
+ "homeassistant.components.shelly.config_flow.get_info",
+ return_value={"mac": "test-mac", "type": MODEL_1, "gen": 1},
+ ),
+ patch(
+ "aioshelly.block_device.BlockDevice.create",
+ side_effect=CustomPortNotSupported,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -189,12 +196,15 @@ async def test_form_auth(
assert result2["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.shelly.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.shelly.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.shelly.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.shelly.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"], user_input
)
@@ -333,11 +343,14 @@ async def test_form_errors_test_connection(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "homeassistant.components.shelly.config_flow.get_info",
- return_value={"mac": "test-mac", "auth": False},
- ), patch(
- "aioshelly.block_device.BlockDevice.create", new=AsyncMock(side_effect=exc)
+ with (
+ patch(
+ "homeassistant.components.shelly.config_flow.get_info",
+ return_value={"mac": "test-mac", "auth": False},
+ ),
+ patch(
+ "aioshelly.block_device.BlockDevice.create", new=AsyncMock(side_effect=exc)
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -393,15 +406,19 @@ async def test_user_setup_ignored_device(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "homeassistant.components.shelly.config_flow.get_info",
- return_value={"mac": "test-mac", "type": MODEL_1, "auth": False},
- ), patch(
- "homeassistant.components.shelly.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.shelly.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.shelly.config_flow.get_info",
+ return_value={"mac": "test-mac", "type": MODEL_1, "auth": False},
+ ),
+ patch(
+ "homeassistant.components.shelly.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.shelly.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"host": "1.1.1.1"},
@@ -554,12 +571,15 @@ async def test_zeroconf(
)
assert context["title_placeholders"]["name"] == "shelly1pm-12345"
assert context["confirm_only"] is True
- with patch(
- "homeassistant.components.shelly.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.shelly.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.shelly.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.shelly.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{},
@@ -609,12 +629,15 @@ async def test_zeroconf_sleeping_device(
if flow["flow_id"] == result["flow_id"]
)
assert context["title_placeholders"]["name"] == "shelly1pm-12345"
- with patch(
- "homeassistant.components.shelly.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.shelly.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.shelly.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.shelly.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{},
@@ -635,17 +658,20 @@ async def test_zeroconf_sleeping_device(
async def test_zeroconf_sleeping_device_error(hass: HomeAssistant) -> None:
"""Test sleeping device configuration via zeroconf with error."""
- with patch(
- "homeassistant.components.shelly.config_flow.get_info",
- return_value={
- "mac": "test-mac",
- "type": MODEL_1,
- "auth": False,
- "sleep_mode": True,
- },
- ), patch(
- "aioshelly.block_device.BlockDevice.create",
- new=AsyncMock(side_effect=DeviceConnectionError),
+ with (
+ patch(
+ "homeassistant.components.shelly.config_flow.get_info",
+ return_value={
+ "mac": "test-mac",
+ "type": MODEL_1,
+ "auth": False,
+ "sleep_mode": True,
+ },
+ ),
+ patch(
+ "aioshelly.block_device.BlockDevice.create",
+ new=AsyncMock(side_effect=DeviceConnectionError),
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -778,12 +804,15 @@ async def test_zeroconf_require_auth(
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.shelly.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.shelly.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.shelly.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.shelly.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"username": "test username", "password": "test password"},
@@ -865,15 +894,19 @@ async def test_reauth_unsuccessful(
)
entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.shelly.config_flow.get_info",
- return_value={"mac": "test-mac", "type": MODEL_1, "auth": True, "gen": gen},
- ), patch(
- "aioshelly.block_device.BlockDevice.create",
- new=AsyncMock(side_effect=InvalidAuthError),
- ), patch(
- "aioshelly.rpc_device.RpcDevice.create",
- new=AsyncMock(side_effect=InvalidAuthError),
+ with (
+ patch(
+ "homeassistant.components.shelly.config_flow.get_info",
+ return_value={"mac": "test-mac", "type": MODEL_1, "auth": True, "gen": gen},
+ ),
+ patch(
+ "aioshelly.block_device.BlockDevice.create",
+ new=AsyncMock(side_effect=InvalidAuthError),
+ ),
+ patch(
+ "aioshelly.rpc_device.RpcDevice.create",
+ new=AsyncMock(side_effect=InvalidAuthError),
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -1167,12 +1200,16 @@ async def test_sleeping_device_gen2_with_new_firmware(
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.shelly.config_flow.get_info",
- return_value={"mac": "test-mac", "gen": 2},
- ), patch("homeassistant.components.shelly.async_setup", return_value=True), patch(
- "homeassistant.components.shelly.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.shelly.config_flow.get_info",
+ return_value={"mac": "test-mac", "gen": 2},
+ ),
+ patch("homeassistant.components.shelly.async_setup", return_value=True),
+ patch(
+ "homeassistant.components.shelly.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/shelly/test_init.py b/tests/components/shelly/test_init.py
index eb621a6e044..754f1111548 100644
--- a/tests/components/shelly/test_init.py
+++ b/tests/components/shelly/test_init.py
@@ -58,16 +58,20 @@ async def test_ip_address_with_only_default_interface(
hass: HomeAssistant, mock_block_device: Mock, caplog: pytest.LogCaptureFixture
) -> None:
"""Test more local ip addresses with only the default interface.."""
- with patch(
- "homeassistant.components.network.async_only_default_interface_enabled",
- return_value=True,
- ), patch(
- "homeassistant.components.network.async_get_enabled_source_ips",
- return_value=[IPv4Address("192.168.1.10"), IPv4Address("10.10.10.10")],
- ), patch(
- "homeassistant.components.shelly.utils.COAP",
- autospec=COAP,
- ) as mock_coap_init:
+ with (
+ patch(
+ "homeassistant.components.network.async_only_default_interface_enabled",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.network.async_get_enabled_source_ips",
+ return_value=[IPv4Address("192.168.1.10"), IPv4Address("10.10.10.10")],
+ ),
+ patch(
+ "homeassistant.components.shelly.utils.COAP",
+ autospec=COAP,
+ ) as mock_coap_init,
+ ):
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {"coap_port": 7632}})
await hass.async_block_till_done()
@@ -83,16 +87,20 @@ async def test_ip_address_without_only_default_interface(
hass: HomeAssistant, mock_block_device: Mock, caplog: pytest.LogCaptureFixture
) -> None:
"""Test more local ip addresses without only the default interface.."""
- with patch(
- "homeassistant.components.network.async_only_default_interface_enabled",
- return_value=False,
- ), patch(
- "homeassistant.components.network.async_get_enabled_source_ips",
- return_value=[IPv4Address("192.168.1.10"), IPv4Address("10.10.10.10")],
- ), patch(
- "homeassistant.components.shelly.utils.COAP",
- autospec=COAP,
- ) as mock_coap_init:
+ with (
+ patch(
+ "homeassistant.components.network.async_only_default_interface_enabled",
+ return_value=False,
+ ),
+ patch(
+ "homeassistant.components.network.async_get_enabled_source_ips",
+ return_value=[IPv4Address("192.168.1.10"), IPv4Address("10.10.10.10")],
+ ),
+ patch(
+ "homeassistant.components.shelly.utils.COAP",
+ autospec=COAP,
+ ) as mock_coap_init,
+ ):
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {"coap_port": 7632}})
await hass.async_block_till_done()
diff --git a/tests/components/shopping_list/conftest.py b/tests/components/shopping_list/conftest.py
index 3af5d30972e..dd1b690e1e3 100644
--- a/tests/components/shopping_list/conftest.py
+++ b/tests/components/shopping_list/conftest.py
@@ -13,8 +13,9 @@ from tests.common import MockConfigEntry
@pytest.fixture(autouse=True)
def mock_shopping_list_io():
"""Stub out the persistence."""
- with patch("homeassistant.components.shopping_list.ShoppingData.save"), patch(
- "homeassistant.components.shopping_list.ShoppingData.async_load"
+ with (
+ patch("homeassistant.components.shopping_list.ShoppingData.save"),
+ patch("homeassistant.components.shopping_list.ShoppingData.async_load"),
):
yield
diff --git a/tests/components/signal_messenger/test_notify.py b/tests/components/signal_messenger/test_notify.py
index 87b51bdef7c..e2f76d54c87 100644
--- a/tests/components/signal_messenger/test_notify.py
+++ b/tests/components/signal_messenger/test_notify.py
@@ -71,9 +71,12 @@ def test_send_message_to_api_with_bad_data_throws_error(
) -> None:
"""Test sending a message with bad data to the API throws an error."""
signal_requests_mock = signal_requests_mock_factory(False)
- with caplog.at_level(
- logging.DEBUG, logger="homeassistant.components.signal_messenger.notify"
- ), pytest.raises(SignalCliRestApiError) as exc:
+ with (
+ caplog.at_level(
+ logging.DEBUG, logger="homeassistant.components.signal_messenger.notify"
+ ),
+ pytest.raises(SignalCliRestApiError) as exc,
+ ):
signal_notification_service.send_message(MESSAGE)
assert "Sending signal message" in caplog.text
@@ -88,9 +91,12 @@ def test_send_message_with_bad_data_throws_vol_error(
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test sending a message with bad data throws an error."""
- with caplog.at_level(
- logging.DEBUG, logger="homeassistant.components.signal_messenger.notify"
- ), pytest.raises(vol.Invalid) as exc:
+ with (
+ caplog.at_level(
+ logging.DEBUG, logger="homeassistant.components.signal_messenger.notify"
+ ),
+ pytest.raises(vol.Invalid) as exc,
+ ):
data = {"test": "test"}
signal_notification_service.send_message(MESSAGE, data=data)
@@ -105,11 +111,14 @@ def test_send_message_with_attachment(
) -> None:
"""Test send message with attachment."""
signal_requests_mock = signal_requests_mock_factory()
- with caplog.at_level(
- logging.DEBUG, logger="homeassistant.components.signal_messenger.notify"
- ), tempfile.NamedTemporaryFile(
- mode="w", suffix=".png", prefix=os.path.basename(__file__)
- ) as temp_file:
+ with (
+ caplog.at_level(
+ logging.DEBUG, logger="homeassistant.components.signal_messenger.notify"
+ ),
+ tempfile.NamedTemporaryFile(
+ mode="w", suffix=".png", prefix=os.path.basename(__file__)
+ ) as temp_file,
+ ):
temp_file.write("attachment_data")
data = {"attachments": [temp_file.name]}
signal_notification_service.send_message(MESSAGE, data=data)
diff --git a/tests/components/simplisafe/conftest.py b/tests/components/simplisafe/conftest.py
index 0594ac51850..cc387ee765b 100644
--- a/tests/components/simplisafe/conftest.py
+++ b/tests/components/simplisafe/conftest.py
@@ -95,20 +95,26 @@ def reauth_config_fixture():
@pytest.fixture(name="setup_simplisafe")
async def setup_simplisafe_fixture(hass, api, config):
"""Define a fixture to set up SimpliSafe."""
- with patch(
- "homeassistant.components.simplisafe.config_flow.API.async_from_auth",
- return_value=api,
- ), patch(
- "homeassistant.components.simplisafe.API.async_from_auth",
- return_value=api,
- ), patch(
- "homeassistant.components.simplisafe.API.async_from_refresh_token",
- return_value=api,
- ), patch(
- "homeassistant.components.simplisafe.SimpliSafe._async_start_websocket_loop"
- ), patch(
- "homeassistant.components.simplisafe.PLATFORMS",
- [],
+ with (
+ patch(
+ "homeassistant.components.simplisafe.config_flow.API.async_from_auth",
+ return_value=api,
+ ),
+ patch(
+ "homeassistant.components.simplisafe.API.async_from_auth",
+ return_value=api,
+ ),
+ patch(
+ "homeassistant.components.simplisafe.API.async_from_refresh_token",
+ return_value=api,
+ ),
+ patch(
+ "homeassistant.components.simplisafe.SimpliSafe._async_start_websocket_loop"
+ ),
+ patch(
+ "homeassistant.components.simplisafe.PLATFORMS",
+ [],
+ ),
):
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
diff --git a/tests/components/simplisafe/test_config_flow.py b/tests/components/simplisafe/test_config_flow.py
index 308f04d12a1..af92833eb5b 100644
--- a/tests/components/simplisafe/test_config_flow.py
+++ b/tests/components/simplisafe/test_config_flow.py
@@ -99,9 +99,12 @@ async def test_step_reauth(config_entry, hass: HomeAssistant, setup_simplisafe)
)
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.simplisafe.async_setup_entry", return_value=True
- ), patch("homeassistant.config_entries.ConfigEntries.async_reload"):
+ with (
+ patch(
+ "homeassistant.components.simplisafe.async_setup_entry", return_value=True
+ ),
+ patch("homeassistant.config_entries.ConfigEntries.async_reload"),
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_AUTH_CODE: VALID_AUTH_CODE}
)
@@ -125,9 +128,12 @@ async def test_step_reauth_wrong_account(
)
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.simplisafe.async_setup_entry", return_value=True
- ), patch("homeassistant.config_entries.ConfigEntries.async_reload"):
+ with (
+ patch(
+ "homeassistant.components.simplisafe.async_setup_entry", return_value=True
+ ),
+ patch("homeassistant.config_entries.ConfigEntries.async_reload"),
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_AUTH_CODE: VALID_AUTH_CODE}
)
@@ -163,9 +169,12 @@ async def test_step_user(
)
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.simplisafe.async_setup_entry", return_value=True
- ), patch("homeassistant.config_entries.ConfigEntries.async_reload"):
+ with (
+ patch(
+ "homeassistant.components.simplisafe.async_setup_entry", return_value=True
+ ),
+ patch("homeassistant.config_entries.ConfigEntries.async_reload"),
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_AUTH_CODE: auth_code}
)
diff --git a/tests/components/simplisafe/test_init.py b/tests/components/simplisafe/test_init.py
index 3a89caeb891..f626f479a2f 100644
--- a/tests/components/simplisafe/test_init.py
+++ b/tests/components/simplisafe/test_init.py
@@ -23,20 +23,26 @@ async def test_base_station_migration(
name="old",
)
- with patch(
- "homeassistant.components.simplisafe.config_flow.API.async_from_auth",
- return_value=api,
- ), patch(
- "homeassistant.components.simplisafe.API.async_from_auth",
- return_value=api,
- ), patch(
- "homeassistant.components.simplisafe.API.async_from_refresh_token",
- return_value=api,
- ), patch(
- "homeassistant.components.simplisafe.SimpliSafe._async_start_websocket_loop"
- ), patch(
- "homeassistant.components.simplisafe.PLATFORMS",
- [],
+ with (
+ patch(
+ "homeassistant.components.simplisafe.config_flow.API.async_from_auth",
+ return_value=api,
+ ),
+ patch(
+ "homeassistant.components.simplisafe.API.async_from_auth",
+ return_value=api,
+ ),
+ patch(
+ "homeassistant.components.simplisafe.API.async_from_refresh_token",
+ return_value=api,
+ ),
+ patch(
+ "homeassistant.components.simplisafe.SimpliSafe._async_start_websocket_loop"
+ ),
+ patch(
+ "homeassistant.components.simplisafe.PLATFORMS",
+ [],
+ ),
):
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
diff --git a/tests/components/skybell/conftest.py b/tests/components/skybell/conftest.py
index 9b95cfd79bb..6120d168572 100644
--- a/tests/components/skybell/conftest.py
+++ b/tests/components/skybell/conftest.py
@@ -36,10 +36,13 @@ def skybell_mock():
mocked_skybell.async_send_request.return_value = {"id": USER_ID}
mocked_skybell.user_id = USER_ID
- with patch(
- "homeassistant.components.skybell.config_flow.Skybell",
- return_value=mocked_skybell,
- ), patch("homeassistant.components.skybell.Skybell", return_value=mocked_skybell):
+ with (
+ patch(
+ "homeassistant.components.skybell.config_flow.Skybell",
+ return_value=mocked_skybell,
+ ),
+ patch("homeassistant.components.skybell.Skybell", return_value=mocked_skybell),
+ ):
yield mocked_skybell
diff --git a/tests/components/sma/conftest.py b/tests/components/sma/conftest.py
index 2da12c249d7..a98eda673e4 100644
--- a/tests/components/sma/conftest.py
+++ b/tests/components/sma/conftest.py
@@ -32,8 +32,11 @@ async def init_integration(hass, mock_config_entry):
"""Create a fake SMA Config Entry."""
mock_config_entry.add_to_hass(hass)
- with patch("pysma.SMA.read"), patch(
- "pysma.SMA.get_sensors", return_value=Sensors(sensor_map[GENERIC_SENSORS])
+ with (
+ patch("pysma.SMA.read"),
+ patch(
+ "pysma.SMA.get_sensors", return_value=Sensors(sensor_map[GENERIC_SENSORS])
+ ),
):
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/sma/test_config_flow.py b/tests/components/sma/test_config_flow.py
index afb4da9aff7..d73d8eb9728 100644
--- a/tests/components/sma/test_config_flow.py
+++ b/tests/components/sma/test_config_flow.py
@@ -25,9 +25,11 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch("pysma.SMA.new_session", return_value=True), patch(
- "pysma.SMA.device_info", return_value=MOCK_DEVICE
- ), _patch_async_setup_entry() as mock_setup_entry:
+ with (
+ patch("pysma.SMA.new_session", return_value=True),
+ patch("pysma.SMA.device_info", return_value=MOCK_DEVICE),
+ _patch_async_setup_entry() as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
MOCK_USER_INPUT,
@@ -47,9 +49,10 @@ async def test_form_cannot_connect(hass: HomeAssistant) -> None:
DOMAIN, context={"source": SOURCE_USER}
)
- with patch(
- "pysma.SMA.new_session", side_effect=SmaConnectionException
- ), _patch_async_setup_entry() as mock_setup_entry:
+ with (
+ patch("pysma.SMA.new_session", side_effect=SmaConnectionException),
+ _patch_async_setup_entry() as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
MOCK_USER_INPUT,
@@ -66,9 +69,10 @@ async def test_form_invalid_auth(hass: HomeAssistant) -> None:
DOMAIN, context={"source": SOURCE_USER}
)
- with patch(
- "pysma.SMA.new_session", side_effect=SmaAuthenticationException
- ), _patch_async_setup_entry() as mock_setup_entry:
+ with (
+ patch("pysma.SMA.new_session", side_effect=SmaAuthenticationException),
+ _patch_async_setup_entry() as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
MOCK_USER_INPUT,
@@ -85,9 +89,11 @@ async def test_form_cannot_retrieve_device_info(hass: HomeAssistant) -> None:
DOMAIN, context={"source": SOURCE_USER}
)
- with patch("pysma.SMA.new_session", return_value=True), patch(
- "pysma.SMA.read", side_effect=SmaReadException
- ), _patch_async_setup_entry() as mock_setup_entry:
+ with (
+ patch("pysma.SMA.new_session", return_value=True),
+ patch("pysma.SMA.read", side_effect=SmaReadException),
+ _patch_async_setup_entry() as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
MOCK_USER_INPUT,
@@ -104,9 +110,10 @@ async def test_form_unexpected_exception(hass: HomeAssistant) -> None:
DOMAIN, context={"source": SOURCE_USER}
)
- with patch(
- "pysma.SMA.new_session", side_effect=Exception
- ), _patch_async_setup_entry() as mock_setup_entry:
+ with (
+ patch("pysma.SMA.new_session", side_effect=Exception),
+ _patch_async_setup_entry() as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
MOCK_USER_INPUT,
@@ -125,11 +132,12 @@ async def test_form_already_configured(hass: HomeAssistant, mock_config_entry) -
DOMAIN, context={"source": SOURCE_USER}
)
- with patch("pysma.SMA.new_session", return_value=True), patch(
- "pysma.SMA.device_info", return_value=MOCK_DEVICE
- ), patch(
- "pysma.SMA.close_session", return_value=True
- ), _patch_async_setup_entry() as mock_setup_entry:
+ with (
+ patch("pysma.SMA.new_session", return_value=True),
+ patch("pysma.SMA.device_info", return_value=MOCK_DEVICE),
+ patch("pysma.SMA.close_session", return_value=True),
+ _patch_async_setup_entry() as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
MOCK_USER_INPUT,
diff --git a/tests/components/smappee/test_config_flow.py b/tests/components/smappee/test_config_flow.py
index 794510366e2..b5551c03c77 100644
--- a/tests/components/smappee/test_config_flow.py
+++ b/tests/components/smappee/test_config_flow.py
@@ -118,8 +118,9 @@ async def test_show_zeroconf_connection_error_form_next_generation(
async def test_connection_error(hass: HomeAssistant) -> None:
"""Test we show user form on Smappee connection error."""
- with patch("pysmappee.api.SmappeeLocalApi.logon", return_value=None), patch(
- "pysmappee.mqtt.SmappeeLocalMqtt.start_attempt", return_value=None
+ with (
+ patch("pysmappee.api.SmappeeLocalApi.logon", return_value=None),
+ patch("pysmappee.mqtt.SmappeeLocalMqtt.start_attempt", return_value=None),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -143,11 +144,13 @@ async def test_connection_error(hass: HomeAssistant) -> None:
async def test_user_local_connection_error(hass: HomeAssistant) -> None:
"""Test we show user form on Smappee connection error in local next generation option."""
- with patch("pysmappee.api.SmappeeLocalApi.logon", return_value=None), patch(
- "pysmappee.mqtt.SmappeeLocalMqtt.start_attempt", return_value=True
- ), patch("pysmappee.mqtt.SmappeeLocalMqtt.start", return_value=True), patch(
- "pysmappee.mqtt.SmappeeLocalMqtt.stop", return_value=True
- ), patch("pysmappee.mqtt.SmappeeLocalMqtt.is_config_ready", return_value=None):
+ with (
+ patch("pysmappee.api.SmappeeLocalApi.logon", return_value=None),
+ patch("pysmappee.mqtt.SmappeeLocalMqtt.start_attempt", return_value=True),
+ patch("pysmappee.mqtt.SmappeeLocalMqtt.start", return_value=True),
+ patch("pysmappee.mqtt.SmappeeLocalMqtt.stop", return_value=True),
+ patch("pysmappee.mqtt.SmappeeLocalMqtt.is_config_ready", return_value=None),
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
@@ -190,14 +193,19 @@ async def test_zeroconf_wrong_mdns(hass: HomeAssistant) -> None:
async def test_full_user_wrong_mdns(hass: HomeAssistant) -> None:
"""Test we abort user flow if unsupported mDNS name got resolved."""
- with patch("pysmappee.api.SmappeeLocalApi.logon", return_value={}), patch(
- "pysmappee.api.SmappeeLocalApi.load_advanced_config",
- return_value=[{"key": "mdnsHostName", "value": "Smappee5100000001"}],
- ), patch(
- "pysmappee.api.SmappeeLocalApi.load_command_control_config", return_value=[]
- ), patch(
- "pysmappee.api.SmappeeLocalApi.load_instantaneous",
- return_value=[{"key": "phase0ActivePower", "value": 0}],
+ with (
+ patch("pysmappee.api.SmappeeLocalApi.logon", return_value={}),
+ patch(
+ "pysmappee.api.SmappeeLocalApi.load_advanced_config",
+ return_value=[{"key": "mdnsHostName", "value": "Smappee5100000001"}],
+ ),
+ patch(
+ "pysmappee.api.SmappeeLocalApi.load_command_control_config", return_value=[]
+ ),
+ patch(
+ "pysmappee.api.SmappeeLocalApi.load_instantaneous",
+ return_value=[{"key": "phase0ActivePower", "value": 0}],
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -221,14 +229,19 @@ async def test_full_user_wrong_mdns(hass: HomeAssistant) -> None:
async def test_user_device_exists_abort(hass: HomeAssistant) -> None:
"""Test we abort user flow if Smappee device already configured."""
- with patch("pysmappee.api.SmappeeLocalApi.logon", return_value={}), patch(
- "pysmappee.api.SmappeeLocalApi.load_advanced_config",
- return_value=[{"key": "mdnsHostName", "value": "Smappee1006000212"}],
- ), patch(
- "pysmappee.api.SmappeeLocalApi.load_command_control_config", return_value=[]
- ), patch(
- "pysmappee.api.SmappeeLocalApi.load_instantaneous",
- return_value=[{"key": "phase0ActivePower", "value": 0}],
+ with (
+ patch("pysmappee.api.SmappeeLocalApi.logon", return_value={}),
+ patch(
+ "pysmappee.api.SmappeeLocalApi.load_advanced_config",
+ return_value=[{"key": "mdnsHostName", "value": "Smappee1006000212"}],
+ ),
+ patch(
+ "pysmappee.api.SmappeeLocalApi.load_command_control_config", return_value=[]
+ ),
+ patch(
+ "pysmappee.api.SmappeeLocalApi.load_instantaneous",
+ return_value=[{"key": "phase0ActivePower", "value": 0}],
+ ),
):
config_entry = MockConfigEntry(
domain=DOMAIN,
@@ -262,14 +275,19 @@ async def test_user_device_exists_abort(hass: HomeAssistant) -> None:
async def test_zeroconf_device_exists_abort(hass: HomeAssistant) -> None:
"""Test we abort zeroconf flow if Smappee device already configured."""
- with patch("pysmappee.api.SmappeeLocalApi.logon", return_value={}), patch(
- "pysmappee.api.SmappeeLocalApi.load_advanced_config",
- return_value=[{"key": "mdnsHostName", "value": "Smappee1006000212"}],
- ), patch(
- "pysmappee.api.SmappeeLocalApi.load_command_control_config", return_value=[]
- ), patch(
- "pysmappee.api.SmappeeLocalApi.load_instantaneous",
- return_value=[{"key": "phase0ActivePower", "value": 0}],
+ with (
+ patch("pysmappee.api.SmappeeLocalApi.logon", return_value={}),
+ patch(
+ "pysmappee.api.SmappeeLocalApi.load_advanced_config",
+ return_value=[{"key": "mdnsHostName", "value": "Smappee1006000212"}],
+ ),
+ patch(
+ "pysmappee.api.SmappeeLocalApi.load_command_control_config", return_value=[]
+ ),
+ patch(
+ "pysmappee.api.SmappeeLocalApi.load_instantaneous",
+ return_value=[{"key": "phase0ActivePower", "value": 0}],
+ ),
):
config_entry = MockConfigEntry(
domain=DOMAIN,
@@ -465,15 +483,21 @@ async def test_full_user_flow(
async def test_full_zeroconf_flow(hass: HomeAssistant) -> None:
"""Test the full zeroconf flow."""
- with patch("pysmappee.api.SmappeeLocalApi.logon", return_value={}), patch(
- "pysmappee.api.SmappeeLocalApi.load_advanced_config",
- return_value=[{"key": "mdnsHostName", "value": "Smappee1006000212"}],
- ), patch(
- "pysmappee.api.SmappeeLocalApi.load_command_control_config", return_value=[]
- ), patch(
- "pysmappee.api.SmappeeLocalApi.load_instantaneous",
- return_value=[{"key": "phase0ActivePower", "value": 0}],
- ), patch("homeassistant.components.smappee.async_setup_entry", return_value=True):
+ with (
+ patch("pysmappee.api.SmappeeLocalApi.logon", return_value={}),
+ patch(
+ "pysmappee.api.SmappeeLocalApi.load_advanced_config",
+ return_value=[{"key": "mdnsHostName", "value": "Smappee1006000212"}],
+ ),
+ patch(
+ "pysmappee.api.SmappeeLocalApi.load_command_control_config", return_value=[]
+ ),
+ patch(
+ "pysmappee.api.SmappeeLocalApi.load_instantaneous",
+ return_value=[{"key": "phase0ActivePower", "value": 0}],
+ ),
+ patch("homeassistant.components.smappee.async_setup_entry", return_value=True),
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
@@ -505,15 +529,21 @@ async def test_full_zeroconf_flow(hass: HomeAssistant) -> None:
async def test_full_user_local_flow(hass: HomeAssistant) -> None:
"""Test the full zeroconf flow."""
- with patch("pysmappee.api.SmappeeLocalApi.logon", return_value={}), patch(
- "pysmappee.api.SmappeeLocalApi.load_advanced_config",
- return_value=[{"key": "mdnsHostName", "value": "Smappee1006000212"}],
- ), patch(
- "pysmappee.api.SmappeeLocalApi.load_command_control_config", return_value=[]
- ), patch(
- "pysmappee.api.SmappeeLocalApi.load_instantaneous",
- return_value=[{"key": "phase0ActivePower", "value": 0}],
- ), patch("homeassistant.components.smappee.async_setup_entry", return_value=True):
+ with (
+ patch("pysmappee.api.SmappeeLocalApi.logon", return_value={}),
+ patch(
+ "pysmappee.api.SmappeeLocalApi.load_advanced_config",
+ return_value=[{"key": "mdnsHostName", "value": "Smappee1006000212"}],
+ ),
+ patch(
+ "pysmappee.api.SmappeeLocalApi.load_command_control_config", return_value=[]
+ ),
+ patch(
+ "pysmappee.api.SmappeeLocalApi.load_instantaneous",
+ return_value=[{"key": "phase0ActivePower", "value": 0}],
+ ),
+ patch("homeassistant.components.smappee.async_setup_entry", return_value=True),
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
@@ -542,14 +572,16 @@ async def test_full_user_local_flow(hass: HomeAssistant) -> None:
async def test_full_zeroconf_flow_next_generation(hass: HomeAssistant) -> None:
"""Test the full zeroconf flow."""
- with patch(
- "pysmappee.mqtt.SmappeeLocalMqtt.start_attempt", return_value=True
- ), patch(
- "pysmappee.mqtt.SmappeeLocalMqtt.start",
- return_value=None,
- ), patch(
- "pysmappee.mqtt.SmappeeLocalMqtt.is_config_ready",
- return_value=None,
+ with (
+ patch("pysmappee.mqtt.SmappeeLocalMqtt.start_attempt", return_value=True),
+ patch(
+ "pysmappee.mqtt.SmappeeLocalMqtt.start",
+ return_value=None,
+ ),
+ patch(
+ "pysmappee.mqtt.SmappeeLocalMqtt.is_config_ready",
+ return_value=None,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
diff --git a/tests/components/smappee/test_init.py b/tests/components/smappee/test_init.py
index 489b60572e3..cc752964a27 100644
--- a/tests/components/smappee/test_init.py
+++ b/tests/components/smappee/test_init.py
@@ -11,14 +11,19 @@ from tests.common import MockConfigEntry
async def test_unload_config_entry(hass: HomeAssistant) -> None:
"""Test unload config entry flow."""
- with patch("pysmappee.api.SmappeeLocalApi.logon", return_value={}), patch(
- "pysmappee.api.SmappeeLocalApi.load_advanced_config",
- return_value=[{"key": "mdnsHostName", "value": "Smappee1006000212"}],
- ), patch(
- "pysmappee.api.SmappeeLocalApi.load_command_control_config", return_value=[]
- ), patch(
- "pysmappee.api.SmappeeLocalApi.load_instantaneous",
- return_value=[{"key": "phase0ActivePower", "value": 0}],
+ with (
+ patch("pysmappee.api.SmappeeLocalApi.logon", return_value={}),
+ patch(
+ "pysmappee.api.SmappeeLocalApi.load_advanced_config",
+ return_value=[{"key": "mdnsHostName", "value": "Smappee1006000212"}],
+ ),
+ patch(
+ "pysmappee.api.SmappeeLocalApi.load_command_control_config", return_value=[]
+ ),
+ patch(
+ "pysmappee.api.SmappeeLocalApi.load_instantaneous",
+ return_value=[{"key": "phase0ActivePower", "value": 0}],
+ ),
):
config_entry = MockConfigEntry(
domain=DOMAIN,
diff --git a/tests/components/smart_meter_texas/test_config_flow.py b/tests/components/smart_meter_texas/test_config_flow.py
index e63a7f4530b..53f7a2eb5fd 100644
--- a/tests/components/smart_meter_texas/test_config_flow.py
+++ b/tests/components/smart_meter_texas/test_config_flow.py
@@ -28,10 +28,13 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch("smart_meter_texas.Client.authenticate", return_value=True), patch(
- "homeassistant.components.smart_meter_texas.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("smart_meter_texas.Client.authenticate", return_value=True),
+ patch(
+ "homeassistant.components.smart_meter_texas.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], TEST_LOGIN
)
diff --git a/tests/components/smartthings/conftest.py b/tests/components/smartthings/conftest.py
index 283b478fdb0..f15ba85c07e 100644
--- a/tests/components/smartthings/conftest.py
+++ b/tests/components/smartthings/conftest.py
@@ -183,9 +183,11 @@ def smartthings_mock_fixture(locations):
smartthings_mock = Mock(SmartThings)
smartthings_mock.location.side_effect = _location
mock = Mock(return_value=smartthings_mock)
- with patch(COMPONENT_PREFIX + "SmartThings", new=mock), patch(
- COMPONENT_PREFIX + "config_flow.SmartThings", new=mock
- ), patch(COMPONENT_PREFIX + "smartapp.SmartThings", new=mock):
+ with (
+ patch(COMPONENT_PREFIX + "SmartThings", new=mock),
+ patch(COMPONENT_PREFIX + "config_flow.SmartThings", new=mock),
+ patch(COMPONENT_PREFIX + "smartapp.SmartThings", new=mock),
+ ):
yield smartthings_mock
diff --git a/tests/components/smartthings/test_config_flow.py b/tests/components/smartthings/test_config_flow.py
index b8a850443d5..e3dcf76bbaf 100644
--- a/tests/components/smartthings/test_config_flow.py
+++ b/tests/components/smartthings/test_config_flow.py
@@ -359,15 +359,18 @@ async def test_entry_created_with_cloudhook(
request.location_id = location.location_id
request.refresh_token = refresh_token
- with patch.object(
- smartapp.cloud,
- "async_active_subscription",
- Mock(return_value=True),
- ), patch.object(
- smartapp.cloud,
- "async_create_cloudhook",
- AsyncMock(return_value="http://cloud.test"),
- ) as mock_create_cloudhook:
+ with (
+ patch.object(
+ smartapp.cloud,
+ "async_active_subscription",
+ Mock(return_value=True),
+ ),
+ patch.object(
+ smartapp.cloud,
+ "async_create_cloudhook",
+ AsyncMock(return_value="http://cloud.test"),
+ ) as mock_create_cloudhook,
+ ):
await smartapp.setup_smartapp_endpoint(hass, True)
# Webhook confirmation shown
diff --git a/tests/components/smartthings/test_init.py b/tests/components/smartthings/test_init.py
index dcce19a68d1..6ff640e012a 100644
--- a/tests/components/smartthings/test_init.py
+++ b/tests/components/smartthings/test_init.py
@@ -296,11 +296,12 @@ async def test_remove_entry_cloudhook(
config_entry.add_to_hass(hass)
hass.data[DOMAIN][CONF_CLOUDHOOK_URL] = "https://test.cloud"
# Act
- with patch.object(
- cloud, "async_is_logged_in", return_value=True
- ) as mock_async_is_logged_in, patch.object(
- cloud, "async_delete_cloudhook"
- ) as mock_async_delete_cloudhook:
+ with (
+ patch.object(
+ cloud, "async_is_logged_in", return_value=True
+ ) as mock_async_is_logged_in,
+ patch.object(cloud, "async_delete_cloudhook") as mock_async_delete_cloudhook,
+ ):
await smartthings.async_remove_entry(hass, config_entry)
# Assert
assert smartthings_mock.delete_installed_app.call_count == 1
diff --git a/tests/components/smhi/test_config_flow.py b/tests/components/smhi/test_config_flow.py
index 783e2d7eec1..7d8701eca45 100644
--- a/tests/components/smhi/test_config_flow.py
+++ b/tests/components/smhi/test_config_flow.py
@@ -29,13 +29,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.smhi.config_flow.Smhi.async_get_forecast",
- return_value={"test": "something", "test2": "something else"},
- ), patch(
- "homeassistant.components.smhi.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.smhi.config_flow.Smhi.async_get_forecast",
+ return_value={"test": "something", "test2": "something else"},
+ ),
+ patch(
+ "homeassistant.components.smhi.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -62,12 +65,15 @@ async def test_form(hass: HomeAssistant) -> None:
result3 = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "homeassistant.components.smhi.config_flow.Smhi.async_get_forecast",
- return_value={"test": "something", "test2": "something else"},
- ), patch(
- "homeassistant.components.smhi.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.smhi.config_flow.Smhi.async_get_forecast",
+ return_value={"test": "something", "test2": "something else"},
+ ),
+ patch(
+ "homeassistant.components.smhi.async_setup_entry",
+ return_value=True,
+ ),
):
result4 = await hass.config_entries.flow.async_configure(
result3["flow_id"],
@@ -116,12 +122,15 @@ async def test_form_invalid_coordinates(hass: HomeAssistant) -> None:
assert result2["errors"] == {"base": "wrong_location"}
# Continue flow with new coordinates
- with patch(
- "homeassistant.components.smhi.config_flow.Smhi.async_get_forecast",
- return_value={"test": "something", "test2": "something else"},
- ), patch(
- "homeassistant.components.smhi.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.smhi.config_flow.Smhi.async_get_forecast",
+ return_value={"test": "something", "test2": "something else"},
+ ),
+ patch(
+ "homeassistant.components.smhi.async_setup_entry",
+ return_value=True,
+ ),
):
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -235,13 +244,16 @@ async def test_reconfigure_flow(
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {"base": "wrong_location"}
- with patch(
- "homeassistant.components.smhi.config_flow.Smhi.async_get_forecast",
- return_value={"test": "something", "test2": "something else"},
- ), patch(
- "homeassistant.components.smhi.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.smhi.config_flow.Smhi.async_get_forecast",
+ return_value={"test": "something", "test2": "something else"},
+ ),
+ patch(
+ "homeassistant.components.smhi.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
diff --git a/tests/components/smhi/test_weather.py b/tests/components/smhi/test_weather.py
index 65d3782c2b4..87aae74e71d 100644
--- a/tests/components/smhi/test_weather.py
+++ b/tests/components/smhi/test_weather.py
@@ -165,12 +165,15 @@ async def test_properties_unknown_symbol(hass: HomeAssistant) -> None:
entry = MockConfigEntry(domain="smhi", data=TEST_CONFIG, version=2)
entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.smhi.weather.Smhi.async_get_forecast",
- return_value=testdata,
- ), patch(
- "homeassistant.components.smhi.weather.Smhi.async_get_forecast_hour",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.components.smhi.weather.Smhi.async_get_forecast",
+ return_value=testdata,
+ ),
+ patch(
+ "homeassistant.components.smhi.weather.Smhi.async_get_forecast_hour",
+ return_value=None,
+ ),
):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/smtp/test_notify.py b/tests/components/smtp/test_notify.py
index 73911de7ed4..b27a7c2d863 100644
--- a/tests/components/smtp/test_notify.py
+++ b/tests/components/smtp/test_notify.py
@@ -51,8 +51,11 @@ async def test_reload_notify(hass: HomeAssistant) -> None:
assert hass.services.has_service(notify.DOMAIN, DOMAIN)
yaml_path = get_fixture_path("configuration.yaml", "smtp")
- with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path), patch(
- "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid"
+ with (
+ patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path),
+ patch(
+ "homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid"
+ ),
):
await hass.services.async_call(
DOMAIN,
@@ -166,9 +169,10 @@ def test_sending_insecure_files_fails(
"""Verify if we cannot send messages with insecure attachments."""
sample_email = ""
message.hass = hass
- with patch("email.utils.make_msgid", return_value=sample_email), pytest.raises(
- ServiceValidationError
- ) as exc:
+ with (
+ patch("email.utils.make_msgid", return_value=sample_email),
+ pytest.raises(ServiceValidationError) as exc,
+ ):
result, _ = message.send_message(message_data, data=data)
assert content_type in result
assert exc.value.translation_key == "remote_path_not_allowed"
diff --git a/tests/components/snooz/__init__.py b/tests/components/snooz/__init__.py
index 3f04ddbbc03..c314fde5c90 100644
--- a/tests/components/snooz/__init__.py
+++ b/tests/components/snooz/__init__.py
@@ -100,11 +100,12 @@ async def create_mock_snooz_config_entry(
) -> MockConfigEntry:
"""Create a mock config entry."""
- with patch(
- "homeassistant.components.snooz.SnoozDevice", return_value=device
- ), patch(
- "homeassistant.components.snooz.async_ble_device_from_address",
- return_value=generate_ble_device(device.address, device.name),
+ with (
+ patch("homeassistant.components.snooz.SnoozDevice", return_value=device),
+ patch(
+ "homeassistant.components.snooz.async_ble_device_from_address",
+ return_value=generate_ble_device(device.address, device.name),
+ ),
):
entry = MockConfigEntry(
domain=DOMAIN,
diff --git a/tests/components/solarlog/test_config_flow.py b/tests/components/solarlog/test_config_flow.py
index e80e49bc9e1..16f25264b9d 100644
--- a/tests/components/solarlog/test_config_flow.py
+++ b/tests/components/solarlog/test_config_flow.py
@@ -25,13 +25,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.solarlog.config_flow.SolarLogConfigFlow._test_connection",
- return_value={"title": "solarlog test 1 2 3"},
- ), patch(
- "homeassistant.components.solarlog.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.solarlog.config_flow.SolarLogConfigFlow._test_connection",
+ return_value={"title": "solarlog test 1 2 3"},
+ ),
+ patch(
+ "homeassistant.components.solarlog.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": HOST, "name": NAME}
)
diff --git a/tests/components/solax/test_config_flow.py b/tests/components/solax/test_config_flow.py
index 47e588d34a3..c671fe39cec 100644
--- a/tests/components/solax/test_config_flow.py
+++ b/tests/components/solax/test_config_flow.py
@@ -30,13 +30,17 @@ async def test_form_success(hass: HomeAssistant) -> None:
assert flow["type"] == "form"
assert flow["errors"] == {}
- with patch(
- "homeassistant.components.solax.config_flow.real_time_api",
- return_value=__mock_real_time_api_success(),
- ), patch("solax.RealTimeAPI.get_data", return_value=__mock_get_data()), patch(
- "homeassistant.components.solax.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.solax.config_flow.real_time_api",
+ return_value=__mock_real_time_api_success(),
+ ),
+ patch("solax.RealTimeAPI.get_data", return_value=__mock_get_data()),
+ patch(
+ "homeassistant.components.solax.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
entry_result = await hass.config_entries.flow.async_configure(
flow["flow_id"],
{CONF_IP_ADDRESS: "192.168.1.87", CONF_PORT: 80, CONF_PASSWORD: "password"},
diff --git a/tests/components/somfy_mylink/test_config_flow.py b/tests/components/somfy_mylink/test_config_flow.py
index c5d1c726a8f..a01f4d640a1 100644
--- a/tests/components/somfy_mylink/test_config_flow.py
+++ b/tests/components/somfy_mylink/test_config_flow.py
@@ -26,13 +26,16 @@ async def test_form_user(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.somfy_mylink.config_flow.SomfyMyLinkSynergy.status_info",
- return_value={"any": "data"},
- ), patch(
- "homeassistant.components.somfy_mylink.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.somfy_mylink.config_flow.SomfyMyLinkSynergy.status_info",
+ return_value={"any": "data"},
+ ),
+ patch(
+ "homeassistant.components.somfy_mylink.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -67,13 +70,16 @@ async def test_form_user_already_configured(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.somfy_mylink.config_flow.SomfyMyLinkSynergy.status_info",
- return_value={"any": "data"},
- ), patch(
- "homeassistant.components.somfy_mylink.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.somfy_mylink.config_flow.SomfyMyLinkSynergy.status_info",
+ return_value={"any": "data"},
+ ),
+ patch(
+ "homeassistant.components.somfy_mylink.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -243,13 +249,16 @@ async def test_form_user_already_configured_from_dhcp(hass: HomeAssistant) -> No
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.somfy_mylink.config_flow.SomfyMyLinkSynergy.status_info",
- return_value={"any": "data"},
- ), patch(
- "homeassistant.components.somfy_mylink.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.somfy_mylink.config_flow.SomfyMyLinkSynergy.status_info",
+ return_value={"any": "data"},
+ ),
+ patch(
+ "homeassistant.components.somfy_mylink.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_DHCP},
@@ -301,13 +310,16 @@ async def test_dhcp_discovery(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.somfy_mylink.config_flow.SomfyMyLinkSynergy.status_info",
- return_value={"any": "data"},
- ), patch(
- "homeassistant.components.somfy_mylink.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.somfy_mylink.config_flow.SomfyMyLinkSynergy.status_info",
+ return_value={"any": "data"},
+ ),
+ patch(
+ "homeassistant.components.somfy_mylink.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
diff --git a/tests/components/songpal/test_init.py b/tests/components/songpal/test_init.py
index 6bc14e06153..c49b290f805 100644
--- a/tests/components/songpal/test_init.py
+++ b/tests/components/songpal/test_init.py
@@ -58,8 +58,9 @@ async def test_unload(hass: HomeAssistant) -> None:
entry.add_to_hass(hass)
mocked_device = _create_mocked_device()
- with _patch_config_flow_device(mocked_device), _patch_media_player_device(
- mocked_device
+ with (
+ _patch_config_flow_device(mocked_device),
+ _patch_media_player_device(mocked_device),
):
assert await async_setup_component(hass, songpal.DOMAIN, {}) is True
await hass.async_block_till_done()
diff --git a/tests/components/sonos/conftest.py b/tests/components/sonos/conftest.py
index d9600b9f1e5..0b3834992d8 100644
--- a/tests/components/sonos/conftest.py
+++ b/tests/components/sonos/conftest.py
@@ -209,9 +209,11 @@ def soco_factory(
factory = SoCoMockFactory(
music_library, speaker_info, current_track_info_empty, battery_info, alarm_clock
)
- with patch("homeassistant.components.sonos.SoCo", new=factory.get_mock), patch(
- "socket.gethostbyname", side_effect=patch_gethostbyname
- ), patch("homeassistant.components.sonos.ZGS_SUBSCRIPTION_TIMEOUT", 0):
+ with (
+ patch("homeassistant.components.sonos.SoCo", new=factory.get_mock),
+ patch("socket.gethostbyname", side_effect=patch_gethostbyname),
+ patch("homeassistant.components.sonos.ZGS_SUBSCRIPTION_TIMEOUT", 0),
+ ):
yield factory
@@ -224,14 +226,16 @@ def soco_fixture(soco_factory):
@pytest.fixture(autouse=True)
async def silent_ssdp_scanner(hass):
"""Start SSDP component and get Scanner, prevent actual SSDP traffic."""
- with patch(
- "homeassistant.components.ssdp.Scanner._async_start_ssdp_listeners"
- ), patch("homeassistant.components.ssdp.Scanner._async_stop_ssdp_listeners"), patch(
- "homeassistant.components.ssdp.Scanner.async_scan"
- ), patch(
- "homeassistant.components.ssdp.Server._async_start_upnp_servers",
- ), patch(
- "homeassistant.components.ssdp.Server._async_stop_upnp_servers",
+ with (
+ patch("homeassistant.components.ssdp.Scanner._async_start_ssdp_listeners"),
+ patch("homeassistant.components.ssdp.Scanner._async_stop_ssdp_listeners"),
+ patch("homeassistant.components.ssdp.Scanner.async_scan"),
+ patch(
+ "homeassistant.components.ssdp.Server._async_start_upnp_servers",
+ ),
+ patch(
+ "homeassistant.components.ssdp.Server._async_stop_upnp_servers",
+ ),
):
yield
diff --git a/tests/components/sonos/test_config_flow.py b/tests/components/sonos/test_config_flow.py
index 2b408f1fa74..186e45e3d84 100644
--- a/tests/components/sonos/test_config_flow.py
+++ b/tests/components/sonos/test_config_flow.py
@@ -42,13 +42,16 @@ async def test_user_form(
)
assert result["type"] == "form"
assert result["errors"] is None
- with patch(
- "homeassistant.components.sonos.async_setup",
- return_value=True,
- ) as mock_setup, patch(
- "homeassistant.components.sonos.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.sonos.async_setup",
+ return_value=True,
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.sonos.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{},
@@ -93,13 +96,16 @@ async def test_zeroconf_form(
assert result["type"] == "form"
assert result["errors"] is None
- with patch(
- "homeassistant.components.sonos.async_setup",
- return_value=True,
- ) as mock_setup, patch(
- "homeassistant.components.sonos.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.sonos.async_setup",
+ return_value=True,
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.sonos.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{},
@@ -135,13 +141,16 @@ async def test_ssdp_discovery(hass: HomeAssistant, soco) -> None:
assert len(flows) == 1
flow = flows[0]
- with patch(
- "homeassistant.components.sonos.async_setup",
- return_value=True,
- ) as mock_setup, patch(
- "homeassistant.components.sonos.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.sonos.async_setup",
+ return_value=True,
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.sonos.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
flow["flow_id"],
{},
@@ -185,13 +194,16 @@ async def test_zeroconf_sonos_v1(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] is None
- with patch(
- "homeassistant.components.sonos.async_setup",
- return_value=True,
- ) as mock_setup, patch(
- "homeassistant.components.sonos.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.sonos.async_setup",
+ return_value=True,
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.sonos.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{},
diff --git a/tests/components/sonos/test_init.py b/tests/components/sonos/test_init.py
index 964984e777a..77bf9a5d12b 100644
--- a/tests/components/sonos/test_init.py
+++ b/tests/components/sonos/test_init.py
@@ -96,21 +96,23 @@ async def test_async_poll_manual_hosts_warnings(
await hass.async_block_till_done()
manager: SonosDiscoveryManager = hass.data[DATA_SONOS_DISCOVERY_MANAGER]
manager.hosts.add("10.10.10.10")
- with caplog.at_level(logging.DEBUG), patch.object(
- manager, "_async_handle_discovery_message"
- ), patch(
- "homeassistant.components.sonos.async_call_later"
- ) as mock_async_call_later, patch(
- "homeassistant.components.sonos.async_dispatcher_send"
- ), patch(
- "homeassistant.components.sonos.sync_get_visible_zones",
- side_effect=[
- OSError(),
- OSError(),
- [],
- [],
- OSError(),
- ],
+ with (
+ caplog.at_level(logging.DEBUG),
+ patch.object(manager, "_async_handle_discovery_message"),
+ patch(
+ "homeassistant.components.sonos.async_call_later"
+ ) as mock_async_call_later,
+ patch("homeassistant.components.sonos.async_dispatcher_send"),
+ patch(
+ "homeassistant.components.sonos.sync_get_visible_zones",
+ side_effect=[
+ OSError(),
+ OSError(),
+ [],
+ [],
+ OSError(),
+ ],
+ ),
):
# First call fails, it should be logged as a WARNING message
caplog.clear()
diff --git a/tests/components/sonos/test_plex_playback.py b/tests/components/sonos/test_plex_playback.py
index d5d5884bb50..428e970697e 100644
--- a/tests/components/sonos/test_plex_playback.py
+++ b/tests/components/sonos/test_plex_playback.py
@@ -28,12 +28,16 @@ async def test_plex_play_media(hass: HomeAssistant, async_autosetup_sonos) -> No
'{"library_name": "Music", "artist_name": "Artist", "album_name": "Album"}'
)
- with patch(
- "homeassistant.components.plex.services.get_plex_server",
- return_value=mock_plex_server,
- ), patch("soco.plugins.plex.PlexPlugin.add_to_queue") as mock_add_to_queue, patch(
- "homeassistant.components.sonos.media_player.SonosMediaPlayerEntity.set_shuffle"
- ) as mock_shuffle:
+ with (
+ patch(
+ "homeassistant.components.plex.services.get_plex_server",
+ return_value=mock_plex_server,
+ ),
+ patch("soco.plugins.plex.PlexPlugin.add_to_queue") as mock_add_to_queue,
+ patch(
+ "homeassistant.components.sonos.media_player.SonosMediaPlayerEntity.set_shuffle"
+ ) as mock_shuffle,
+ ):
# Test successful Plex service call
await hass.services.async_call(
MP_DOMAIN,
diff --git a/tests/components/sonos/test_services.py b/tests/components/sonos/test_services.py
index adea75f74ab..da894ff4548 100644
--- a/tests/components/sonos/test_services.py
+++ b/tests/components/sonos/test_services.py
@@ -28,11 +28,12 @@ async def test_media_player_join(hass: HomeAssistant, async_autosetup_sonos) ->
mocked_speaker = Mock()
mock_entity_id_mappings = {mocked_entity_id: mocked_speaker}
- with patch.dict(
- hass.data[DATA_SONOS].entity_id_mappings, mock_entity_id_mappings
- ), patch(
- "homeassistant.components.sonos.speaker.SonosSpeaker.join_multi"
- ) as mock_join_multi:
+ with (
+ patch.dict(hass.data[DATA_SONOS].entity_id_mappings, mock_entity_id_mappings),
+ patch(
+ "homeassistant.components.sonos.speaker.SonosSpeaker.join_multi"
+ ) as mock_join_multi,
+ ):
await hass.services.async_call(
MP_DOMAIN,
SERVICE_JOIN,
diff --git a/tests/components/sonos/test_speaker.py b/tests/components/sonos/test_speaker.py
index 8ae1d0bae03..e0fc4c3baf9 100644
--- a/tests/components/sonos/test_speaker.py
+++ b/tests/components/sonos/test_speaker.py
@@ -23,8 +23,11 @@ async def test_fallback_to_polling(
caplog.clear()
# Ensure subscriptions are cancelled and polling methods are called when subscriptions time out
- with patch("homeassistant.components.sonos.media.SonosMedia.poll_media"), patch(
- "homeassistant.components.sonos.speaker.SonosSpeaker.subscription_address"
+ with (
+ patch("homeassistant.components.sonos.media.SonosMedia.poll_media"),
+ patch(
+ "homeassistant.components.sonos.speaker.SonosSpeaker.subscription_address"
+ ),
):
async_fire_time_changed(hass, dt_util.utcnow() + SCAN_INTERVAL)
await hass.async_block_till_done()
diff --git a/tests/components/spider/test_config_flow.py b/tests/components/spider/test_config_flow.py
index e0a3e16e350..1fb61573216 100644
--- a/tests/components/spider/test_config_flow.py
+++ b/tests/components/spider/test_config_flow.py
@@ -37,11 +37,14 @@ async def test_user(hass: HomeAssistant, spider) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.spider.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.spider.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.spider.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.spider.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=SPIDER_USER_DATA
)
@@ -60,13 +63,16 @@ async def test_user(hass: HomeAssistant, spider) -> None:
async def test_import(hass: HomeAssistant, spider) -> None:
"""Test import step."""
- with patch(
- "homeassistant.components.spider.async_setup",
- return_value=True,
- ) as mock_setup, patch(
- "homeassistant.components.spider.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.spider.async_setup",
+ return_value=True,
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.spider.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
diff --git a/tests/components/spotify/test_config_flow.py b/tests/components/spotify/test_config_flow.py
index 9a36942aafd..1ab4e46bd55 100644
--- a/tests/components/spotify/test_config_flow.py
+++ b/tests/components/spotify/test_config_flow.py
@@ -122,9 +122,10 @@ async def test_full_flow(
},
)
- with patch(
- "homeassistant.components.spotify.async_setup_entry", return_value=True
- ), patch("homeassistant.components.spotify.config_flow.Spotify") as spotify_mock:
+ with (
+ patch("homeassistant.components.spotify.async_setup_entry", return_value=True),
+ patch("homeassistant.components.spotify.config_flow.Spotify") as spotify_mock,
+ ):
spotify_mock.return_value.current_user.return_value = {
"id": "fake_id",
"display_name": "frenck",
@@ -235,9 +236,10 @@ async def test_reauthentication(
},
)
- with patch(
- "homeassistant.components.spotify.async_setup_entry", return_value=True
- ), patch("homeassistant.components.spotify.config_flow.Spotify") as spotify_mock:
+ with (
+ patch("homeassistant.components.spotify.async_setup_entry", return_value=True),
+ patch("homeassistant.components.spotify.config_flow.Spotify") as spotify_mock,
+ ):
spotify_mock.return_value.current_user.return_value = {"id": "frenck"}
result = await hass.config_entries.flow.async_configure(result["flow_id"])
diff --git a/tests/components/sql/test_config_flow.py b/tests/components/sql/test_config_flow.py
index f1dec1871ed..7b3b0aaf350 100644
--- a/tests/components/sql/test_config_flow.py
+++ b/tests/components/sql/test_config_flow.py
@@ -592,11 +592,14 @@ async def test_options_flow_db_url_empty(
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "init"
- with patch(
- "homeassistant.components.sql.async_setup_entry",
- return_value=True,
- ), patch(
- "homeassistant.components.sql.config_flow.sqlalchemy.create_engine",
+ with (
+ patch(
+ "homeassistant.components.sql.async_setup_entry",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.sql.config_flow.sqlalchemy.create_engine",
+ ),
):
result = await hass.config_entries.options.async_configure(
result["flow_id"],
@@ -627,11 +630,14 @@ async def test_full_flow_not_recorder_db(
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.sql.async_setup_entry",
- return_value=True,
- ), patch(
- "homeassistant.components.sql.config_flow.sqlalchemy.create_engine",
+ with (
+ patch(
+ "homeassistant.components.sql.async_setup_entry",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.sql.config_flow.sqlalchemy.create_engine",
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -660,11 +666,14 @@ async def test_full_flow_not_recorder_db(
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "init"
- with patch(
- "homeassistant.components.sql.async_setup_entry",
- return_value=True,
- ), patch(
- "homeassistant.components.sql.config_flow.sqlalchemy.create_engine",
+ with (
+ patch(
+ "homeassistant.components.sql.async_setup_entry",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.sql.config_flow.sqlalchemy.create_engine",
+ ),
):
result = await hass.config_entries.options.async_configure(
result["flow_id"],
diff --git a/tests/components/sql/test_sensor.py b/tests/components/sql/test_sensor.py
index 9eabffd9421..14442aa5181 100644
--- a/tests/components/sql/test_sensor.py
+++ b/tests/components/sql/test_sensor.py
@@ -153,9 +153,12 @@ async def test_query_mssql_no_result(
"column": "value",
"name": "count_tables",
}
- with patch("homeassistant.components.sql.sensor.sqlalchemy"), patch(
- "homeassistant.components.sql.sensor.sqlalchemy.text",
- return_value=sql_text("SELECT TOP 1 5 as value where 1=2"),
+ with (
+ patch("homeassistant.components.sql.sensor.sqlalchemy"),
+ patch(
+ "homeassistant.components.sql.sensor.sqlalchemy.text",
+ return_value=sql_text("SELECT TOP 1 5 as value where 1=2"),
+ ),
):
await init_integration(hass, config)
diff --git a/tests/components/squeezebox/test_config_flow.py b/tests/components/squeezebox/test_config_flow.py
index af100e28232..dc82b658163 100644
--- a/tests/components/squeezebox/test_config_flow.py
+++ b/tests/components/squeezebox/test_config_flow.py
@@ -38,14 +38,19 @@ async def patch_async_query_unauthorized(self, *args):
async def test_user_form(hass: HomeAssistant) -> None:
"""Test user-initiated flow, including discovery and the edit step."""
- with patch(
- "pysqueezebox.Server.async_query",
- return_value={"uuid": UUID},
- ), patch(
- "homeassistant.components.squeezebox.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.squeezebox.config_flow.async_discover", mock_discover
+ with (
+ patch(
+ "pysqueezebox.Server.async_query",
+ return_value={"uuid": UUID},
+ ),
+ patch(
+ "homeassistant.components.squeezebox.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.squeezebox.config_flow.async_discover",
+ mock_discover,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@@ -84,10 +89,13 @@ async def test_user_form(hass: HomeAssistant) -> None:
async def test_user_form_timeout(hass: HomeAssistant) -> None:
"""Test we handle server search timeout."""
- with patch(
- "homeassistant.components.squeezebox.config_flow.async_discover",
- mock_failed_discover,
- ), patch("homeassistant.components.squeezebox.config_flow.TIMEOUT", 0.1):
+ with (
+ patch(
+ "homeassistant.components.squeezebox.config_flow.async_discover",
+ mock_failed_discover,
+ ),
+ patch("homeassistant.components.squeezebox.config_flow.TIMEOUT", 0.1),
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
@@ -108,12 +116,16 @@ async def test_user_form_timeout(hass: HomeAssistant) -> None:
async def test_user_form_duplicate(hass: HomeAssistant) -> None:
"""Test duplicate discovered servers are skipped."""
- with patch(
- "homeassistant.components.squeezebox.config_flow.async_discover",
- mock_discover,
- ), patch("homeassistant.components.squeezebox.config_flow.TIMEOUT", 0.1), patch(
- "homeassistant.components.squeezebox.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.squeezebox.config_flow.async_discover",
+ mock_discover,
+ ),
+ patch("homeassistant.components.squeezebox.config_flow.TIMEOUT", 0.1),
+ patch(
+ "homeassistant.components.squeezebox.async_setup_entry",
+ return_value=True,
+ ),
):
entry = MockConfigEntry(
domain=DOMAIN,
@@ -207,11 +219,15 @@ async def test_discovery_no_uuid(hass: HomeAssistant) -> None:
async def test_dhcp_discovery(hass: HomeAssistant) -> None:
"""Test we can process discovery from dhcp."""
- with patch(
- "pysqueezebox.Server.async_query",
- return_value={"uuid": UUID},
- ), patch(
- "homeassistant.components.squeezebox.config_flow.async_discover", mock_discover
+ with (
+ patch(
+ "pysqueezebox.Server.async_query",
+ return_value={"uuid": UUID},
+ ),
+ patch(
+ "homeassistant.components.squeezebox.config_flow.async_discover",
+ mock_discover,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -228,10 +244,13 @@ async def test_dhcp_discovery(hass: HomeAssistant) -> None:
async def test_dhcp_discovery_no_server_found(hass: HomeAssistant) -> None:
"""Test we can handle dhcp discovery when no server is found."""
- with patch(
- "homeassistant.components.squeezebox.config_flow.async_discover",
- mock_failed_discover,
- ), patch("homeassistant.components.squeezebox.config_flow.TIMEOUT", 0.1):
+ with (
+ patch(
+ "homeassistant.components.squeezebox.config_flow.async_discover",
+ mock_failed_discover,
+ ),
+ patch("homeassistant.components.squeezebox.config_flow.TIMEOUT", 0.1),
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_DHCP},
diff --git a/tests/components/srp_energy/test_sensor.py b/tests/components/srp_energy/test_sensor.py
index 70b4eae14df..a46caf904b7 100644
--- a/tests/components/srp_energy/test_sensor.py
+++ b/tests/components/srp_energy/test_sensor.py
@@ -72,10 +72,11 @@ async def test_srp_entity_timeout(
) -> None:
"""Test the SrpEntity timing out."""
- with patch(
- "homeassistant.components.srp_energy.SrpEnergyClient", autospec=True
- ) as srp_energy_mock, patch(
- "homeassistant.components.srp_energy.coordinator.TIMEOUT", 0
+ with (
+ patch(
+ "homeassistant.components.srp_energy.SrpEnergyClient", autospec=True
+ ) as srp_energy_mock,
+ patch("homeassistant.components.srp_energy.coordinator.TIMEOUT", 0),
):
client = srp_energy_mock.return_value
client.validate.return_value = True
diff --git a/tests/components/ssdp/conftest.py b/tests/components/ssdp/conftest.py
index 157e6d0daa9..8b06163cd95 100644
--- a/tests/components/ssdp/conftest.py
+++ b/tests/components/ssdp/conftest.py
@@ -10,9 +10,11 @@ import pytest
@pytest.fixture(autouse=True)
async def silent_ssdp_listener():
"""Patch SsdpListener class, preventing any actual SSDP traffic."""
- with patch("homeassistant.components.ssdp.SsdpListener.async_start"), patch(
- "homeassistant.components.ssdp.SsdpListener.async_stop"
- ), patch("homeassistant.components.ssdp.SsdpListener.async_search"):
+ with (
+ patch("homeassistant.components.ssdp.SsdpListener.async_start"),
+ patch("homeassistant.components.ssdp.SsdpListener.async_stop"),
+ patch("homeassistant.components.ssdp.SsdpListener.async_search"),
+ ):
# Fixtures are initialized before patches. When the component is started here,
# certain functions/methods might not be patched in time.
yield SsdpListener
@@ -21,9 +23,11 @@ async def silent_ssdp_listener():
@pytest.fixture(autouse=True)
async def disabled_upnp_server():
"""Disable UPnpServer."""
- with patch("homeassistant.components.ssdp.UpnpServer.async_start"), patch(
- "homeassistant.components.ssdp.UpnpServer.async_stop"
- ), patch("homeassistant.components.ssdp._async_find_next_available_port"):
+ with (
+ patch("homeassistant.components.ssdp.UpnpServer.async_start"),
+ patch("homeassistant.components.ssdp.UpnpServer.async_stop"),
+ patch("homeassistant.components.ssdp._async_find_next_available_port"),
+ ):
yield UpnpServer
diff --git a/tests/components/ssdp/test_init.py b/tests/components/ssdp/test_init.py
index 7af2287c893..5131388c4e3 100644
--- a/tests/components/ssdp/test_init.py
+++ b/tests/components/ssdp/test_init.py
@@ -861,13 +861,14 @@ async def test_flow_dismiss_on_byebye(
mock_ssdp_advertisement["nts"] = "ssdp:byebye"
# ssdp:byebye advertisement should dismiss existing flows
- with patch.object(
- hass.config_entries.flow,
- "async_progress_by_init_data_type",
- return_value=[{"flow_id": "mock_flow_id"}],
- ) as mock_async_progress_by_init_data_type, patch.object(
- hass.config_entries.flow, "async_abort"
- ) as mock_async_abort:
+ with (
+ patch.object(
+ hass.config_entries.flow,
+ "async_progress_by_init_data_type",
+ return_value=[{"flow_id": "mock_flow_id"}],
+ ) as mock_async_progress_by_init_data_type,
+ patch.object(hass.config_entries.flow, "async_abort") as mock_async_abort,
+ ):
ssdp_listener._on_byebye(mock_ssdp_advertisement)
await hass.async_block_till_done(wait_background_tasks=True)
diff --git a/tests/components/starlink/test_diagnostics.py b/tests/components/starlink/test_diagnostics.py
index 22e1d6e84be..c5876e5e9f2 100644
--- a/tests/components/starlink/test_diagnostics.py
+++ b/tests/components/starlink/test_diagnostics.py
@@ -28,7 +28,11 @@ async def test_diagnostics(
data={CONF_IP_ADDRESS: "1.2.3.4:0000"},
)
- with STATUS_DATA_SUCCESS_PATCHER, LOCATION_DATA_SUCCESS_PATCHER, SLEEP_DATA_SUCCESS_PATCHER:
+ with (
+ STATUS_DATA_SUCCESS_PATCHER,
+ LOCATION_DATA_SUCCESS_PATCHER,
+ SLEEP_DATA_SUCCESS_PATCHER,
+ ):
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
diff --git a/tests/components/starlink/test_init.py b/tests/components/starlink/test_init.py
index 4fdb6afc3ed..03e9787b6c0 100644
--- a/tests/components/starlink/test_init.py
+++ b/tests/components/starlink/test_init.py
@@ -21,7 +21,11 @@ async def test_successful_entry(hass: HomeAssistant) -> None:
data={CONF_IP_ADDRESS: "1.2.3.4:0000"},
)
- with STATUS_DATA_SUCCESS_PATCHER, LOCATION_DATA_SUCCESS_PATCHER, SLEEP_DATA_SUCCESS_PATCHER:
+ with (
+ STATUS_DATA_SUCCESS_PATCHER,
+ LOCATION_DATA_SUCCESS_PATCHER,
+ SLEEP_DATA_SUCCESS_PATCHER,
+ ):
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
@@ -38,7 +42,11 @@ async def test_unload_entry(hass: HomeAssistant) -> None:
data={CONF_IP_ADDRESS: "1.2.3.4:0000"},
)
- with STATUS_DATA_SUCCESS_PATCHER, LOCATION_DATA_SUCCESS_PATCHER, SLEEP_DATA_SUCCESS_PATCHER:
+ with (
+ STATUS_DATA_SUCCESS_PATCHER,
+ LOCATION_DATA_SUCCESS_PATCHER,
+ SLEEP_DATA_SUCCESS_PATCHER,
+ ):
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
diff --git a/tests/components/statistics/test_sensor.py b/tests/components/statistics/test_sensor.py
index d2891cf7b87..fd9a5ca85bd 100644
--- a/tests/components/statistics/test_sensor.py
+++ b/tests/components/statistics/test_sensor.py
@@ -1530,8 +1530,9 @@ async def test_initialize_from_database_with_maxage(
await hass.async_block_till_done()
await async_wait_recording_done(hass)
- with freeze_time(current_time) as freezer, patch.object(
- StatisticsSensor, "_purge_old_states", mock_purge
+ with (
+ freeze_time(current_time) as freezer,
+ patch.object(StatisticsSensor, "_purge_old_states", mock_purge),
):
for value in VALUES_NUMERIC:
hass.states.async_set(
diff --git a/tests/components/steam_online/test_config_flow.py b/tests/components/steam_online/test_config_flow.py
index cbe02e1c3b6..00b47ea48bd 100644
--- a/tests/components/steam_online/test_config_flow.py
+++ b/tests/components/steam_online/test_config_flow.py
@@ -27,9 +27,12 @@ from . import (
async def test_flow_user(hass: HomeAssistant) -> None:
"""Test user initialized flow."""
- with patch_interface(), patch(
- "homeassistant.components.steam_online.async_setup_entry",
- return_value=True,
+ with (
+ patch_interface(),
+ patch(
+ "homeassistant.components.steam_online.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -139,9 +142,12 @@ async def test_flow_reauth(hass: HomeAssistant) -> None:
async def test_options_flow(hass: HomeAssistant) -> None:
"""Test updating options."""
entry = create_entry(hass)
- with patch_interface(), patch(
- "homeassistant.components.steam_online.config_flow.MAX_IDS_TO_REQUEST",
- return_value=2,
+ with (
+ patch_interface(),
+ patch(
+ "homeassistant.components.steam_online.config_flow.MAX_IDS_TO_REQUEST",
+ return_value=2,
+ ),
):
await hass.config_entries.async_setup(entry.entry_id)
result = await hass.config_entries.options.async_init(entry.entry_id)
@@ -163,17 +169,23 @@ async def test_options_flow(hass: HomeAssistant) -> None:
async def test_options_flow_deselect(hass: HomeAssistant) -> None:
"""Test deselecting user."""
entry = create_entry(hass)
- with patch_interface(), patch(
- "homeassistant.components.steam_online.config_flow.MAX_IDS_TO_REQUEST",
- return_value=2,
+ with (
+ patch_interface(),
+ patch(
+ "homeassistant.components.steam_online.config_flow.MAX_IDS_TO_REQUEST",
+ return_value=2,
+ ),
):
await hass.config_entries.async_setup(entry.entry_id)
result = await hass.config_entries.options.async_init(entry.entry_id)
await hass.async_block_till_done()
- with patch_interface(), patch(
- "homeassistant.components.steam_online.async_setup_entry",
- return_value=True,
+ with (
+ patch_interface(),
+ patch(
+ "homeassistant.components.steam_online.async_setup_entry",
+ return_value=True,
+ ),
):
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "init"
diff --git a/tests/components/steamist/test_config_flow.py b/tests/components/steamist/test_config_flow.py
index 34dc92495a9..9480703af9f 100644
--- a/tests/components/steamist/test_config_flow.py
+++ b/tests/components/steamist/test_config_flow.py
@@ -45,12 +45,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with _patch_discovery(no_device=True), patch(
- "homeassistant.components.steamist.config_flow.Steamist.async_get_status"
- ), patch(
- "homeassistant.components.steamist.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(no_device=True),
+ patch(
+ "homeassistant.components.steamist.config_flow.Steamist.async_get_status"
+ ),
+ patch(
+ "homeassistant.components.steamist.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -75,12 +79,16 @@ async def test_form_with_discovery(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with _patch_discovery(), patch(
- "homeassistant.components.steamist.config_flow.Steamist.async_get_status"
- ), patch(
- "homeassistant.components.steamist.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(),
+ patch(
+ "homeassistant.components.steamist.config_flow.Steamist.async_get_status"
+ ),
+ patch(
+ "homeassistant.components.steamist.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -169,11 +177,12 @@ async def test_discovery(hass: HomeAssistant) -> None:
assert result2["step_id"] == "pick_device"
assert not result2["errors"]
- with _patch_discovery(), _patch_status(MOCK_ASYNC_GET_STATUS_INACTIVE), patch(
- f"{MODULE}.async_setup", return_value=True
- ) as mock_setup, patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_status(MOCK_ASYNC_GET_STATUS_INACTIVE),
+ patch(f"{MODULE}.async_setup", return_value=True) as mock_setup,
+ patch(f"{MODULE}.async_setup_entry", return_value=True) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_DEVICE: FORMATTED_MAC_ADDRESS},
@@ -254,11 +263,14 @@ async def test_discovered_by_discovery(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with _patch_discovery(), _patch_status(MOCK_ASYNC_GET_STATUS_INACTIVE), patch(
- f"{MODULE}.async_setup", return_value=True
- ) as mock_async_setup, patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_async_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_status(MOCK_ASYNC_GET_STATUS_INACTIVE),
+ patch(f"{MODULE}.async_setup", return_value=True) as mock_async_setup,
+ patch(
+ f"{MODULE}.async_setup_entry", return_value=True
+ ) as mock_async_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(result["flow_id"], {})
await hass.async_block_till_done()
@@ -282,11 +294,14 @@ async def test_discovered_by_dhcp(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with _patch_discovery(), _patch_status(MOCK_ASYNC_GET_STATUS_INACTIVE), patch(
- f"{MODULE}.async_setup", return_value=True
- ) as mock_async_setup, patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_async_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_status(MOCK_ASYNC_GET_STATUS_INACTIVE),
+ patch(f"{MODULE}.async_setup", return_value=True) as mock_async_setup,
+ patch(
+ f"{MODULE}.async_setup_entry", return_value=True
+ ) as mock_async_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(result["flow_id"], {})
await hass.async_block_till_done()
@@ -299,8 +314,9 @@ async def test_discovered_by_dhcp(hass: HomeAssistant) -> None:
async def test_discovered_by_dhcp_discovery_fails(hass: HomeAssistant) -> None:
"""Test we can setup when discovered from dhcp but then we cannot get the device name."""
- with _patch_discovery(no_device=True), _patch_status(
- MOCK_ASYNC_GET_STATUS_INACTIVE
+ with (
+ _patch_discovery(no_device=True),
+ _patch_status(MOCK_ASYNC_GET_STATUS_INACTIVE),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -318,8 +334,9 @@ async def test_discovered_by_dhcp_discovery_finds_non_steamist_device(
) -> None:
"""Test we can setup when discovered from dhcp but its not a steamist device."""
- with _patch_discovery(device=DEVICE_30303_NOT_STEAMIST), _patch_status(
- MOCK_ASYNC_GET_STATUS_INACTIVE
+ with (
+ _patch_discovery(device=DEVICE_30303_NOT_STEAMIST),
+ _patch_status(MOCK_ASYNC_GET_STATUS_INACTIVE),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -346,11 +363,12 @@ async def test_discovered_by_dhcp_or_discovery_adds_missing_unique_id(
config_entry = MockConfigEntry(domain=DOMAIN, data={CONF_HOST: DEVICE_IP_ADDRESS})
config_entry.add_to_hass(hass)
- with _patch_discovery(), _patch_status(MOCK_ASYNC_GET_STATUS_INACTIVE), patch(
- f"{MODULE}.async_setup", return_value=True
- ) as mock_setup, patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_status(MOCK_ASYNC_GET_STATUS_INACTIVE),
+ patch(f"{MODULE}.async_setup", return_value=True) as mock_setup,
+ patch(f"{MODULE}.async_setup_entry", return_value=True) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": source}, data=data
)
@@ -380,11 +398,12 @@ async def test_discovered_by_dhcp_or_discovery_existing_unique_id_does_not_reloa
)
config_entry.add_to_hass(hass)
- with _patch_discovery(), _patch_status(MOCK_ASYNC_GET_STATUS_INACTIVE), patch(
- f"{MODULE}.async_setup", return_value=True
- ) as mock_setup, patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_status(MOCK_ASYNC_GET_STATUS_INACTIVE),
+ patch(f"{MODULE}.async_setup", return_value=True) as mock_setup,
+ patch(f"{MODULE}.async_setup_entry", return_value=True) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": source}, data=data
)
diff --git a/tests/components/steamist/test_init.py b/tests/components/steamist/test_init.py
index a38b14ab15d..32400449d0d 100644
--- a/tests/components/steamist/test_init.py
+++ b/tests/components/steamist/test_init.py
@@ -92,9 +92,12 @@ async def test_config_entry_fills_unique_id_with_directed_discovery(
mock_aio_discovery.async_scan = _async_scan
type(mock_aio_discovery).found_devices = found_devices
- with _patch_status(MOCK_ASYNC_GET_STATUS_ACTIVE), patch(
- "homeassistant.components.steamist.discovery.AIODiscovery30303",
- return_value=mock_aio_discovery,
+ with (
+ _patch_status(MOCK_ASYNC_GET_STATUS_ACTIVE),
+ patch(
+ "homeassistant.components.steamist.discovery.AIODiscovery30303",
+ return_value=mock_aio_discovery,
+ ),
):
await async_setup_component(hass, steamist.DOMAIN, {steamist.DOMAIN: {}})
await hass.async_block_till_done()
@@ -124,10 +127,13 @@ async def test_discovery_happens_at_interval(
config_entry.add_to_hass(hass)
mock_aio_discovery = MagicMock(auto_spec=AIODiscovery30303)
mock_aio_discovery.async_scan = AsyncMock()
- with patch(
- "homeassistant.components.steamist.discovery.AIODiscovery30303",
- return_value=mock_aio_discovery,
- ), _patch_status(MOCK_ASYNC_GET_STATUS_ACTIVE):
+ with (
+ patch(
+ "homeassistant.components.steamist.discovery.AIODiscovery30303",
+ return_value=mock_aio_discovery,
+ ),
+ _patch_status(MOCK_ASYNC_GET_STATUS_ACTIVE),
+ ):
await async_setup_component(hass, steamist.DOMAIN, {steamist.DOMAIN: {}})
await hass.async_block_till_done(wait_background_tasks=True)
diff --git a/tests/components/stream/conftest.py b/tests/components/stream/conftest.py
index dd8b99f2af0..9ce23d99152 100644
--- a/tests/components/stream/conftest.py
+++ b/tests/components/stream/conftest.py
@@ -143,23 +143,29 @@ class HLSSync:
def hls_sync():
"""Patch HLSOutput to allow test to synchronize playlist requests and responses."""
sync = HLSSync()
- with patch(
- "homeassistant.components.stream.core.StreamOutput.recv",
- side_effect=sync.recv,
- autospec=True,
- ), patch(
- "homeassistant.components.stream.core.StreamOutput.part_recv",
- side_effect=sync.part_recv,
- autospec=True,
- ), patch(
- "homeassistant.components.stream.hls.web.HTTPBadRequest",
- side_effect=sync.bad_request,
- ), patch(
- "homeassistant.components.stream.hls.web.HTTPNotFound",
- side_effect=sync.not_found,
- ), patch(
- "homeassistant.components.stream.hls.web.Response",
- side_effect=sync.response,
+ with (
+ patch(
+ "homeassistant.components.stream.core.StreamOutput.recv",
+ side_effect=sync.recv,
+ autospec=True,
+ ),
+ patch(
+ "homeassistant.components.stream.core.StreamOutput.part_recv",
+ side_effect=sync.part_recv,
+ autospec=True,
+ ),
+ patch(
+ "homeassistant.components.stream.hls.web.HTTPBadRequest",
+ side_effect=sync.bad_request,
+ ),
+ patch(
+ "homeassistant.components.stream.hls.web.HTTPNotFound",
+ side_effect=sync.not_found,
+ ),
+ patch(
+ "homeassistant.components.stream.hls.web.Response",
+ side_effect=sync.response,
+ ),
):
yield sync
diff --git a/tests/components/stream/test_hls.py b/tests/components/stream/test_hls.py
index 7f9afaf1234..6a20914250e 100644
--- a/tests/components/stream/test_hls.py
+++ b/tests/components/stream/test_hls.py
@@ -311,9 +311,11 @@ async def test_stream_retries(
hass.loop.call_soon_threadsafe(futures.pop().set_result, None)
raise av.error.InvalidDataError(-2, "error")
- with patch("av.open") as av_open, patch(
- "homeassistant.components.stream.Stream._set_state", set_state_wrapper
- ), patch("homeassistant.components.stream.STREAM_RESTART_INCREMENT", 0):
+ with (
+ patch("av.open") as av_open,
+ patch("homeassistant.components.stream.Stream._set_state", set_state_wrapper),
+ patch("homeassistant.components.stream.STREAM_RESTART_INCREMENT", 0),
+ ):
av_open.side_effect = av_open_side_effect
# Request stream. Enable retries which are disabled by default in tests.
should_retry.return_value = True
diff --git a/tests/components/stream/test_recorder.py b/tests/components/stream/test_recorder.py
index 35b8c2442f4..515f3fff82d 100644
--- a/tests/components/stream/test_recorder.py
+++ b/tests/components/stream/test_recorder.py
@@ -101,9 +101,10 @@ async def test_record_path_not_allowed(hass: HomeAssistant, h264_video) -> None:
"""Test where the output path is not allowed by home assistant configuration."""
stream = create_stream(hass, h264_video, {}, dynamic_stream_settings())
- with patch.object(
- hass.config, "is_allowed_path", return_value=False
- ), pytest.raises(HomeAssistantError):
+ with (
+ patch.object(hass.config, "is_allowed_path", return_value=False),
+ pytest.raises(HomeAssistantError),
+ ):
await stream.async_record("/example/path")
@@ -149,9 +150,11 @@ async def test_recorder_discontinuity(
provider_ready.set()
return provider
- with patch.object(hass.config, "is_allowed_path", return_value=True), patch(
- "homeassistant.components.stream.Stream", wraps=MockStream
- ), patch("homeassistant.components.stream.recorder.RecorderOutput.recv"):
+ with (
+ patch.object(hass.config, "is_allowed_path", return_value=True),
+ patch("homeassistant.components.stream.Stream", wraps=MockStream),
+ patch("homeassistant.components.stream.recorder.RecorderOutput.recv"),
+ ):
stream = create_stream(hass, "blank", {}, dynamic_stream_settings())
make_recording = hass.async_create_task(stream.async_record(filename))
await provider_ready.wait()
diff --git a/tests/components/stream/test_worker.py b/tests/components/stream/test_worker.py
index 92221ebb88d..0d47a63a000 100644
--- a/tests/components/stream/test_worker.py
+++ b/tests/components/stream/test_worker.py
@@ -311,9 +311,12 @@ async def async_decode_stream(hass, packets, py_av=None, stream_settings=None):
py_av = MockPyAv()
py_av.container.packets = iter(packets) # Can't be rewound
- with patch("av.open", new=py_av.open), patch(
- "homeassistant.components.stream.core.StreamOutput.put",
- side_effect=py_av.capture_buffer.capture_output_segment,
+ with (
+ patch("av.open", new=py_av.open),
+ patch(
+ "homeassistant.components.stream.core.StreamOutput.put",
+ side_effect=py_av.capture_buffer.capture_output_segment,
+ ),
):
try:
run_worker(hass, stream, STREAM_SOURCE, stream_settings)
@@ -986,8 +989,9 @@ async def test_get_image(hass: HomeAssistant, h264_video, filename) -> None:
worker_wake.wait()
return temp_av_open(stream_source, *args, **kwargs)
- with patch.object(hass.config, "is_allowed_path", return_value=True), patch(
- "av.open", new=blocking_open
+ with (
+ patch.object(hass.config, "is_allowed_path", return_value=True),
+ patch("av.open", new=blocking_open),
):
make_recording = hass.async_create_task(stream.async_record(filename))
assert stream._keyframe_converter._image is None
diff --git a/tests/components/subaru/conftest.py b/tests/components/subaru/conftest.py
index 3f01ad2da18..446f025e077 100644
--- a/tests/components/subaru/conftest.py
+++ b/tests/components/subaru/conftest.py
@@ -112,46 +112,61 @@ async def setup_subaru_config_entry(
fetch_effect=None,
):
"""Run async_setup with API mocks in place."""
- with patch(
- MOCK_API_CONNECT,
- return_value=connect_effect is None,
- side_effect=connect_effect,
- ), patch(
- MOCK_API_GET_VEHICLES,
- return_value=vehicle_list,
- ), patch(
- MOCK_API_VIN_TO_NAME,
- return_value=vehicle_data[VEHICLE_NAME],
- ), patch(
- MOCK_API_GET_API_GEN,
- return_value=vehicle_data[VEHICLE_API_GEN],
- ), patch(
- MOCK_API_GET_MODEL_NAME,
- return_value=vehicle_data[VEHICLE_MODEL_NAME],
- ), patch(
- MOCK_API_GET_MODEL_YEAR,
- return_value=vehicle_data[VEHICLE_MODEL_YEAR],
- ), patch(
- MOCK_API_GET_EV_STATUS,
- return_value=vehicle_data[VEHICLE_HAS_EV],
- ), patch(
- MOCK_API_GET_RES_STATUS,
- return_value=vehicle_data[VEHICLE_HAS_REMOTE_START],
- ), patch(
- MOCK_API_GET_REMOTE_STATUS,
- return_value=vehicle_data[VEHICLE_HAS_REMOTE_SERVICE],
- ), patch(
- MOCK_API_GET_SAFETY_STATUS,
- return_value=vehicle_data[VEHICLE_HAS_SAFETY_SERVICE],
- ), patch(
- MOCK_API_GET_SUBSCRIPTION_STATUS,
- return_value=True,
- ), patch(
- MOCK_API_GET_DATA,
- return_value=vehicle_status,
- ), patch(
- MOCK_API_UPDATE,
- ), patch(MOCK_API_FETCH, side_effect=fetch_effect):
+ with (
+ patch(
+ MOCK_API_CONNECT,
+ return_value=connect_effect is None,
+ side_effect=connect_effect,
+ ),
+ patch(
+ MOCK_API_GET_VEHICLES,
+ return_value=vehicle_list,
+ ),
+ patch(
+ MOCK_API_VIN_TO_NAME,
+ return_value=vehicle_data[VEHICLE_NAME],
+ ),
+ patch(
+ MOCK_API_GET_API_GEN,
+ return_value=vehicle_data[VEHICLE_API_GEN],
+ ),
+ patch(
+ MOCK_API_GET_MODEL_NAME,
+ return_value=vehicle_data[VEHICLE_MODEL_NAME],
+ ),
+ patch(
+ MOCK_API_GET_MODEL_YEAR,
+ return_value=vehicle_data[VEHICLE_MODEL_YEAR],
+ ),
+ patch(
+ MOCK_API_GET_EV_STATUS,
+ return_value=vehicle_data[VEHICLE_HAS_EV],
+ ),
+ patch(
+ MOCK_API_GET_RES_STATUS,
+ return_value=vehicle_data[VEHICLE_HAS_REMOTE_START],
+ ),
+ patch(
+ MOCK_API_GET_REMOTE_STATUS,
+ return_value=vehicle_data[VEHICLE_HAS_REMOTE_SERVICE],
+ ),
+ patch(
+ MOCK_API_GET_SAFETY_STATUS,
+ return_value=vehicle_data[VEHICLE_HAS_SAFETY_SERVICE],
+ ),
+ patch(
+ MOCK_API_GET_SUBSCRIPTION_STATUS,
+ return_value=True,
+ ),
+ patch(
+ MOCK_API_GET_DATA,
+ return_value=vehicle_status,
+ ),
+ patch(
+ MOCK_API_UPDATE,
+ ),
+ patch(MOCK_API_FETCH, side_effect=fetch_effect),
+ ):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/subaru/test_config_flow.py b/tests/components/subaru/test_config_flow.py
index 919c59c6d1b..76bad81bff4 100644
--- a/tests/components/subaru/test_config_flow.py
+++ b/tests/components/subaru/test_config_flow.py
@@ -102,15 +102,17 @@ async def test_user_form_pin_not_required(
hass: HomeAssistant, two_factor_verify_form
) -> None:
"""Test successful login when no PIN is required."""
- with patch(
- MOCK_API_2FA_VERIFY,
- return_value=True,
- ) as mock_two_factor_verify, patch(
- MOCK_API_IS_PIN_REQUIRED,
- return_value=False,
- ) as mock_is_pin_required, patch(
- ASYNC_SETUP_ENTRY, return_value=True
- ) as mock_setup_entry:
+ with (
+ patch(
+ MOCK_API_2FA_VERIFY,
+ return_value=True,
+ ) as mock_two_factor_verify,
+ patch(
+ MOCK_API_IS_PIN_REQUIRED,
+ return_value=False,
+ ) as mock_is_pin_required,
+ patch(ASYNC_SETUP_ENTRY, return_value=True) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
two_factor_verify_form["flow_id"],
user_input={config_flow.CONF_VALIDATION_CODE: "123456"},
@@ -141,9 +143,13 @@ async def test_user_form_pin_not_required(
async def test_registered_pin_required(hass: HomeAssistant, user_form) -> None:
"""Test if the device is already registered and PIN required."""
- with patch(MOCK_API_CONNECT, return_value=True), patch(
- MOCK_API_DEVICE_REGISTERED, new_callable=PropertyMock
- ) as mock_device_registered, patch(MOCK_API_IS_PIN_REQUIRED, return_value=True):
+ with (
+ patch(MOCK_API_CONNECT, return_value=True),
+ patch(
+ MOCK_API_DEVICE_REGISTERED, new_callable=PropertyMock
+ ) as mock_device_registered,
+ patch(MOCK_API_IS_PIN_REQUIRED, return_value=True),
+ ):
mock_device_registered.return_value = True
await hass.config_entries.flow.async_configure(
user_form["flow_id"], user_input=TEST_CREDS
@@ -152,9 +158,13 @@ async def test_registered_pin_required(hass: HomeAssistant, user_form) -> None:
async def test_registered_no_pin_required(hass: HomeAssistant, user_form) -> None:
"""Test if the device is already registered and PIN not required."""
- with patch(MOCK_API_CONNECT, return_value=True), patch(
- MOCK_API_DEVICE_REGISTERED, new_callable=PropertyMock
- ) as mock_device_registered, patch(MOCK_API_IS_PIN_REQUIRED, return_value=False):
+ with (
+ patch(MOCK_API_CONNECT, return_value=True),
+ patch(
+ MOCK_API_DEVICE_REGISTERED, new_callable=PropertyMock
+ ) as mock_device_registered,
+ patch(MOCK_API_IS_PIN_REQUIRED, return_value=False),
+ ):
mock_device_registered.return_value = True
await hass.config_entries.flow.async_configure(
user_form["flow_id"], user_input=TEST_CREDS
@@ -165,12 +175,13 @@ async def test_two_factor_request_success(
hass: HomeAssistant, two_factor_start_form
) -> None:
"""Test two factor contact method selection."""
- with patch(
- MOCK_API_2FA_REQUEST,
- return_value=True,
- ) as mock_two_factor_request, patch(
- MOCK_API_2FA_CONTACTS, new_callable=PropertyMock
- ) as mock_contacts:
+ with (
+ patch(
+ MOCK_API_2FA_REQUEST,
+ return_value=True,
+ ) as mock_two_factor_request,
+ patch(MOCK_API_2FA_CONTACTS, new_callable=PropertyMock) as mock_contacts,
+ ):
mock_contacts.return_value = MOCK_2FA_CONTACTS
await hass.config_entries.flow.async_configure(
two_factor_start_form["flow_id"],
@@ -183,12 +194,13 @@ async def test_two_factor_request_fail(
hass: HomeAssistant, two_factor_start_form
) -> None:
"""Test two factor auth request failure."""
- with patch(
- MOCK_API_2FA_REQUEST,
- return_value=False,
- ) as mock_two_factor_request, patch(
- MOCK_API_2FA_CONTACTS, new_callable=PropertyMock
- ) as mock_contacts:
+ with (
+ patch(
+ MOCK_API_2FA_REQUEST,
+ return_value=False,
+ ) as mock_two_factor_request,
+ patch(MOCK_API_2FA_CONTACTS, new_callable=PropertyMock) as mock_contacts,
+ ):
mock_contacts.return_value = MOCK_2FA_CONTACTS
result = await hass.config_entries.flow.async_configure(
two_factor_start_form["flow_id"],
@@ -203,12 +215,13 @@ async def test_two_factor_verify_success(
hass: HomeAssistant, two_factor_verify_form
) -> None:
"""Test two factor verification."""
- with patch(
- MOCK_API_2FA_VERIFY,
- return_value=True,
- ) as mock_two_factor_verify, patch(
- MOCK_API_IS_PIN_REQUIRED, return_value=True
- ) as mock_is_in_required:
+ with (
+ patch(
+ MOCK_API_2FA_VERIFY,
+ return_value=True,
+ ) as mock_two_factor_verify,
+ patch(MOCK_API_IS_PIN_REQUIRED, return_value=True) as mock_is_in_required,
+ ):
await hass.config_entries.flow.async_configure(
two_factor_verify_form["flow_id"],
user_input={config_flow.CONF_VALIDATION_CODE: "123456"},
@@ -221,12 +234,13 @@ async def test_two_factor_verify_bad_format(
hass: HomeAssistant, two_factor_verify_form
) -> None:
"""Test two factor verification bad format."""
- with patch(
- MOCK_API_2FA_VERIFY,
- return_value=False,
- ) as mock_two_factor_verify, patch(
- MOCK_API_IS_PIN_REQUIRED, return_value=True
- ) as mock_is_pin_required:
+ with (
+ patch(
+ MOCK_API_2FA_VERIFY,
+ return_value=False,
+ ) as mock_two_factor_verify,
+ patch(MOCK_API_IS_PIN_REQUIRED, return_value=True) as mock_is_pin_required,
+ ):
result = await hass.config_entries.flow.async_configure(
two_factor_verify_form["flow_id"],
user_input={config_flow.CONF_VALIDATION_CODE: "1234567"},
@@ -240,12 +254,13 @@ async def test_two_factor_verify_fail(
hass: HomeAssistant, two_factor_verify_form
) -> None:
"""Test two factor verification failure."""
- with patch(
- MOCK_API_2FA_VERIFY,
- return_value=False,
- ) as mock_two_factor_verify, patch(
- MOCK_API_IS_PIN_REQUIRED, return_value=True
- ) as mock_is_pin_required:
+ with (
+ patch(
+ MOCK_API_2FA_VERIFY,
+ return_value=False,
+ ) as mock_two_factor_verify,
+ patch(MOCK_API_IS_PIN_REQUIRED, return_value=True) as mock_is_pin_required,
+ ):
result = await hass.config_entries.flow.async_configure(
two_factor_verify_form["flow_id"],
user_input={config_flow.CONF_VALIDATION_CODE: "123456"},
@@ -273,12 +288,15 @@ async def test_pin_form_init(pin_form) -> None:
async def test_pin_form_bad_pin_format(hass: HomeAssistant, pin_form) -> None:
"""Test we handle invalid pin."""
- with patch(
- MOCK_API_TEST_PIN,
- ) as mock_test_pin, patch(
- MOCK_API_UPDATE_SAVED_PIN,
- return_value=True,
- ) as mock_update_saved_pin:
+ with (
+ patch(
+ MOCK_API_TEST_PIN,
+ ) as mock_test_pin,
+ patch(
+ MOCK_API_UPDATE_SAVED_PIN,
+ return_value=True,
+ ) as mock_update_saved_pin,
+ ):
result = await hass.config_entries.flow.async_configure(
pin_form["flow_id"], user_input={CONF_PIN: "abcd"}
)
@@ -290,15 +308,17 @@ async def test_pin_form_bad_pin_format(hass: HomeAssistant, pin_form) -> None:
async def test_pin_form_success(hass: HomeAssistant, pin_form) -> None:
"""Test successful PIN entry."""
- with patch(
- MOCK_API_TEST_PIN,
- return_value=True,
- ) as mock_test_pin, patch(
- MOCK_API_UPDATE_SAVED_PIN,
- return_value=True,
- ) as mock_update_saved_pin, patch(
- ASYNC_SETUP_ENTRY, return_value=True
- ) as mock_setup_entry:
+ with (
+ patch(
+ MOCK_API_TEST_PIN,
+ return_value=True,
+ ) as mock_test_pin,
+ patch(
+ MOCK_API_UPDATE_SAVED_PIN,
+ return_value=True,
+ ) as mock_update_saved_pin,
+ patch(ASYNC_SETUP_ENTRY, return_value=True) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
pin_form["flow_id"], user_input={CONF_PIN: TEST_PIN}
)
@@ -326,13 +346,16 @@ async def test_pin_form_success(hass: HomeAssistant, pin_form) -> None:
async def test_pin_form_incorrect_pin(hass: HomeAssistant, pin_form) -> None:
"""Test we handle invalid pin."""
- with patch(
- MOCK_API_TEST_PIN,
- side_effect=InvalidPIN("invalidPin"),
- ) as mock_test_pin, patch(
- MOCK_API_UPDATE_SAVED_PIN,
- return_value=True,
- ) as mock_update_saved_pin:
+ with (
+ patch(
+ MOCK_API_TEST_PIN,
+ side_effect=InvalidPIN("invalidPin"),
+ ) as mock_test_pin,
+ patch(
+ MOCK_API_UPDATE_SAVED_PIN,
+ return_value=True,
+ ) as mock_update_saved_pin,
+ ):
result = await hass.config_entries.flow.async_configure(
pin_form["flow_id"], user_input={CONF_PIN: TEST_PIN}
)
@@ -375,9 +398,10 @@ async def user_form(hass):
@pytest.fixture
async def two_factor_start_form(hass, user_form):
"""Return two factor form for Subaru config flow."""
- with patch(MOCK_API_CONNECT, return_value=True), patch(
- MOCK_API_2FA_CONTACTS, new_callable=PropertyMock
- ) as mock_contacts:
+ with (
+ patch(MOCK_API_CONNECT, return_value=True),
+ patch(MOCK_API_2FA_CONTACTS, new_callable=PropertyMock) as mock_contacts,
+ ):
mock_contacts.return_value = MOCK_2FA_CONTACTS
return await hass.config_entries.flow.async_configure(
user_form["flow_id"], user_input=TEST_CREDS
@@ -387,10 +411,13 @@ async def two_factor_start_form(hass, user_form):
@pytest.fixture
async def two_factor_verify_form(hass, two_factor_start_form):
"""Return two factor form for Subaru config flow."""
- with patch(
- MOCK_API_2FA_REQUEST,
- return_value=True,
- ), patch(MOCK_API_2FA_CONTACTS, new_callable=PropertyMock) as mock_contacts:
+ with (
+ patch(
+ MOCK_API_2FA_REQUEST,
+ return_value=True,
+ ),
+ patch(MOCK_API_2FA_CONTACTS, new_callable=PropertyMock) as mock_contacts,
+ ):
mock_contacts.return_value = MOCK_2FA_CONTACTS
return await hass.config_entries.flow.async_configure(
two_factor_start_form["flow_id"],
@@ -401,10 +428,13 @@ async def two_factor_verify_form(hass, two_factor_start_form):
@pytest.fixture
async def pin_form(hass, two_factor_verify_form):
"""Return PIN input form for Subaru config flow."""
- with patch(
- MOCK_API_2FA_VERIFY,
- return_value=True,
- ), patch(MOCK_API_IS_PIN_REQUIRED, return_value=True):
+ with (
+ patch(
+ MOCK_API_2FA_VERIFY,
+ return_value=True,
+ ),
+ patch(MOCK_API_IS_PIN_REQUIRED, return_value=True),
+ ):
return await hass.config_entries.flow.async_configure(
two_factor_verify_form["flow_id"],
user_input={config_flow.CONF_VALIDATION_CODE: "123456"},
diff --git a/tests/components/subaru/test_init.py b/tests/components/subaru/test_init.py
index da5a754bedc..e25a8681bef 100644
--- a/tests/components/subaru/test_init.py
+++ b/tests/components/subaru/test_init.py
@@ -126,12 +126,15 @@ async def test_update_skip_unsubscribed(
async def test_update_disabled(hass: HomeAssistant, ev_entry) -> None:
"""Test update function disable option."""
- with patch(
- MOCK_API_FETCH,
- side_effect=SubaruException("403 Error"),
- ), patch(
- MOCK_API_UPDATE,
- ) as mock_update:
+ with (
+ patch(
+ MOCK_API_FETCH,
+ side_effect=SubaruException("403 Error"),
+ ),
+ patch(
+ MOCK_API_UPDATE,
+ ) as mock_update,
+ ):
await hass.services.async_call(
HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
diff --git a/tests/components/subaru/test_lock.py b/tests/components/subaru/test_lock.py
index e90a0278ee5..4d19d49579e 100644
--- a/tests/components/subaru/test_lock.py
+++ b/tests/components/subaru/test_lock.py
@@ -53,8 +53,9 @@ async def test_unlock_cmd(hass: HomeAssistant, ev_entry) -> None:
async def test_lock_cmd_fails(hass: HomeAssistant, ev_entry) -> None:
"""Test subaru lock request that initiates but fails."""
- with patch(MOCK_API_LOCK, return_value=False) as mock_lock, pytest.raises(
- HomeAssistantError
+ with (
+ patch(MOCK_API_LOCK, return_value=False) as mock_lock,
+ pytest.raises(HomeAssistantError),
):
await hass.services.async_call(
LOCK_DOMAIN, SERVICE_UNLOCK, {ATTR_ENTITY_ID: DEVICE_ID}, blocking=True
diff --git a/tests/components/subaru/test_sensor.py b/tests/components/subaru/test_sensor.py
index faf57e4a5cf..de1df044d71 100644
--- a/tests/components/subaru/test_sensor.py
+++ b/tests/components/subaru/test_sensor.py
@@ -35,8 +35,9 @@ async def test_sensors_ev_imperial(hass: HomeAssistant, ev_entry) -> None:
"""Test sensors supporting imperial units."""
hass.config.units = US_CUSTOMARY_SYSTEM
- with patch(MOCK_API_FETCH), patch(
- MOCK_API_GET_DATA, return_value=VEHICLE_STATUS_EV
+ with (
+ patch(MOCK_API_FETCH),
+ patch(MOCK_API_GET_DATA, return_value=VEHICLE_STATUS_EV),
):
advance_time_to_next_fetch(hass)
await hass.async_block_till_done()
diff --git a/tests/components/suez_water/test_config_flow.py b/tests/components/suez_water/test_config_flow.py
index 73d3c572498..a4ab52151d1 100644
--- a/tests/components/suez_water/test_config_flow.py
+++ b/tests/components/suez_water/test_config_flow.py
@@ -49,12 +49,15 @@ async def test_form_invalid_auth(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "homeassistant.components.suez_water.config_flow.SuezClient.__init__",
- return_value=None,
- ), patch(
- "homeassistant.components.suez_water.config_flow.SuezClient.check_credentials",
- return_value=False,
+ with (
+ patch(
+ "homeassistant.components.suez_water.config_flow.SuezClient.__init__",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.suez_water.config_flow.SuezClient.check_credentials",
+ return_value=False,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -179,12 +182,15 @@ async def test_import_error(
async def test_importing_invalid_auth(hass: HomeAssistant) -> None:
"""Test we handle invalid auth when importing."""
- with patch(
- "homeassistant.components.suez_water.config_flow.SuezClient.__init__",
- return_value=None,
- ), patch(
- "homeassistant.components.suez_water.config_flow.SuezClient.check_credentials",
- return_value=False,
+ with (
+ patch(
+ "homeassistant.components.suez_water.config_flow.SuezClient.__init__",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.suez_water.config_flow.SuezClient.check_credentials",
+ return_value=False,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=MOCK_DATA
diff --git a/tests/components/sunweg/test_config_flow.py b/tests/components/sunweg/test_config_flow.py
index e45e671f752..84957a419dd 100644
--- a/tests/components/sunweg/test_config_flow.py
+++ b/tests/components/sunweg/test_config_flow.py
@@ -46,8 +46,9 @@ async def test_no_plants_on_account(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch.object(APIHelper, "authenticate", return_value=True), patch.object(
- APIHelper, "listPlants", return_value=[]
+ with (
+ patch.object(APIHelper, "authenticate", return_value=True),
+ patch.object(APIHelper, "listPlants", return_value=[]),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], SUNWEG_USER_INPUT
@@ -65,8 +66,9 @@ async def test_multiple_plant_ids(hass: HomeAssistant, plant_fixture) -> None:
user_input = SUNWEG_USER_INPUT.copy()
plant_list = [plant_fixture, plant_fixture]
- with patch.object(APIHelper, "authenticate", return_value=True), patch.object(
- APIHelper, "listPlants", return_value=plant_list
+ with (
+ patch.object(APIHelper, "authenticate", return_value=True),
+ patch.object(APIHelper, "listPlants", return_value=plant_list),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input
@@ -93,10 +95,13 @@ async def test_one_plant_on_account(hass: HomeAssistant, plant_fixture) -> None:
)
user_input = SUNWEG_USER_INPUT.copy()
- with patch.object(APIHelper, "authenticate", return_value=True), patch.object(
- APIHelper,
- "listPlants",
- return_value=[plant_fixture],
+ with (
+ patch.object(APIHelper, "authenticate", return_value=True),
+ patch.object(
+ APIHelper,
+ "listPlants",
+ return_value=[plant_fixture],
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input
@@ -117,10 +122,13 @@ async def test_existing_plant_configured(hass: HomeAssistant, plant_fixture) ->
)
user_input = SUNWEG_USER_INPUT.copy()
- with patch.object(APIHelper, "authenticate", return_value=True), patch.object(
- APIHelper,
- "listPlants",
- return_value=[plant_fixture],
+ with (
+ patch.object(APIHelper, "authenticate", return_value=True),
+ patch.object(
+ APIHelper,
+ "listPlants",
+ return_value=[plant_fixture],
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input
diff --git a/tests/components/sunweg/test_init.py b/tests/components/sunweg/test_init.py
index 5707fd93b99..cc2e880d82e 100644
--- a/tests/components/sunweg/test_init.py
+++ b/tests/components/sunweg/test_init.py
@@ -21,11 +21,13 @@ async def test_methods(hass: HomeAssistant, plant_fixture, inverter_fixture) ->
mock_entry = SUNWEG_MOCK_ENTRY
mock_entry.add_to_hass(hass)
- with patch.object(APIHelper, "authenticate", return_value=True), patch.object(
- APIHelper, "listPlants", return_value=[plant_fixture]
- ), patch.object(APIHelper, "plant", return_value=plant_fixture), patch.object(
- APIHelper, "inverter", return_value=inverter_fixture
- ), patch.object(APIHelper, "complete_inverter"):
+ with (
+ patch.object(APIHelper, "authenticate", return_value=True),
+ patch.object(APIHelper, "listPlants", return_value=[plant_fixture]),
+ patch.object(APIHelper, "plant", return_value=plant_fixture),
+ patch.object(APIHelper, "inverter", return_value=inverter_fixture),
+ patch.object(APIHelper, "complete_inverter"),
+ ):
assert await async_setup_component(hass, DOMAIN, mock_entry.data)
await hass.async_block_till_done()
assert await hass.config_entries.async_unload(mock_entry.entry_id)
diff --git a/tests/components/switchbee/test_config_flow.py b/tests/components/switchbee/test_config_flow.py
index c31ada589c8..99c44365353 100644
--- a/tests/components/switchbee/test_config_flow.py
+++ b/tests/components/switchbee/test_config_flow.py
@@ -32,15 +32,20 @@ async def test_form(hass: HomeAssistant, test_cucode_in_coordinator_data) -> Non
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "switchbee.api.polling.CentralUnitPolling.get_configuration",
- return_value=coordinator_data,
- ), patch(
- "homeassistant.components.switchbee.async_setup_entry",
- return_value=True,
- ), patch(
- "switchbee.api.polling.CentralUnitPolling.fetch_states", return_value=None
- ), patch("switchbee.api.polling.CentralUnitPolling._login", return_value=None):
+ with (
+ patch(
+ "switchbee.api.polling.CentralUnitPolling.get_configuration",
+ return_value=coordinator_data,
+ ),
+ patch(
+ "homeassistant.components.switchbee.async_setup_entry",
+ return_value=True,
+ ),
+ patch(
+ "switchbee.api.polling.CentralUnitPolling.fetch_states", return_value=None
+ ),
+ patch("switchbee.api.polling.CentralUnitPolling._login", return_value=None),
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -149,16 +154,19 @@ async def test_form_entry_exists(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "switchbee.api.polling.CentralUnitPolling._login", return_value=None
- ), patch(
- "homeassistant.components.switchbee.async_setup_entry",
- return_value=True,
- ), patch(
- "switchbee.api.polling.CentralUnitPolling.get_configuration",
- return_value=coordinator_data,
- ), patch(
- "switchbee.api.polling.CentralUnitPolling.fetch_states", return_value=None
+ with (
+ patch("switchbee.api.polling.CentralUnitPolling._login", return_value=None),
+ patch(
+ "homeassistant.components.switchbee.async_setup_entry",
+ return_value=True,
+ ),
+ patch(
+ "switchbee.api.polling.CentralUnitPolling.get_configuration",
+ return_value=coordinator_data,
+ ),
+ patch(
+ "switchbee.api.polling.CentralUnitPolling.fetch_states", return_value=None
+ ),
):
form_result = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/switchbot/test_config_flow.py b/tests/components/switchbot/test_config_flow.py
index 350957db0dd..3d53dd2848e 100644
--- a/tests/components/switchbot/test_config_flow.py
+++ b/tests/components/switchbot/test_config_flow.py
@@ -129,9 +129,12 @@ async def test_bluetooth_discovery_lock_key(hass: HomeAssistant) -> None:
assert result["step_id"] == "lock_key"
assert result["errors"] == {"base": "encryption_key_invalid"}
- with patch_async_setup_entry() as mock_setup_entry, patch(
- "homeassistant.components.switchbot.config_flow.SwitchbotLock.verify_encryption_key",
- return_value=True,
+ with (
+ patch_async_setup_entry() as mock_setup_entry,
+ patch(
+ "homeassistant.components.switchbot.config_flow.SwitchbotLock.verify_encryption_key",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -434,9 +437,12 @@ async def test_user_setup_wolock_key(hass: HomeAssistant) -> None:
assert result["step_id"] == "lock_key"
assert result["errors"] == {"base": "encryption_key_invalid"}
- with patch_async_setup_entry() as mock_setup_entry, patch(
- "homeassistant.components.switchbot.config_flow.SwitchbotLock.verify_encryption_key",
- return_value=True,
+ with (
+ patch_async_setup_entry() as mock_setup_entry,
+ patch(
+ "homeassistant.components.switchbot.config_flow.SwitchbotLock.verify_encryption_key",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -497,15 +503,19 @@ async def test_user_setup_wolock_auth(hass: HomeAssistant) -> None:
assert result["errors"] == {"base": "auth_failed"}
assert "error from api" in result["description_placeholders"]["error_detail"]
- with patch_async_setup_entry() as mock_setup_entry, patch(
- "homeassistant.components.switchbot.config_flow.SwitchbotLock.verify_encryption_key",
- return_value=True,
- ), patch(
- "homeassistant.components.switchbot.config_flow.SwitchbotLock.retrieve_encryption_key",
- return_value={
- CONF_KEY_ID: "ff",
- CONF_ENCRYPTION_KEY: "ffffffffffffffffffffffffffffffff",
- },
+ with (
+ patch_async_setup_entry() as mock_setup_entry,
+ patch(
+ "homeassistant.components.switchbot.config_flow.SwitchbotLock.verify_encryption_key",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.switchbot.config_flow.SwitchbotLock.retrieve_encryption_key",
+ return_value={
+ CONF_KEY_ID: "ff",
+ CONF_ENCRYPTION_KEY: "ffffffffffffffffffffffffffffffff",
+ },
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -598,9 +608,12 @@ async def test_user_setup_wolock_or_bot(hass: HomeAssistant) -> None:
assert result["step_id"] == "lock_key"
assert result["errors"] == {}
- with patch_async_setup_entry() as mock_setup_entry, patch(
- "homeassistant.components.switchbot.config_flow.SwitchbotLock.verify_encryption_key",
- return_value=True,
+ with (
+ patch_async_setup_entry() as mock_setup_entry,
+ patch(
+ "homeassistant.components.switchbot.config_flow.SwitchbotLock.verify_encryption_key",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/syncthing/test_config_flow.py b/tests/components/syncthing/test_config_flow.py
index c7b3c1a3498..d97226e422c 100644
--- a/tests/components/syncthing/test_config_flow.py
+++ b/tests/components/syncthing/test_config_flow.py
@@ -37,12 +37,13 @@ async def test_show_setup_form(hass: HomeAssistant) -> None:
async def test_flow_successful(hass: HomeAssistant) -> None:
"""Test with required fields only."""
- with patch(
- "aiosyncthing.system.System.status", return_value={"myID": "server-id"}
- ), patch(
- "homeassistant.components.syncthing.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("aiosyncthing.system.System.status", return_value={"myID": "server-id"}),
+ patch(
+ "homeassistant.components.syncthing.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": "user"},
diff --git a/tests/components/syncthru/test_config_flow.py b/tests/components/syncthru/test_config_flow.py
index a413789dc60..90470431ade 100644
--- a/tests/components/syncthru/test_config_flow.py
+++ b/tests/components/syncthru/test_config_flow.py
@@ -91,8 +91,9 @@ async def test_syncthru_not_supported(hass: HomeAssistant) -> None:
async def test_unknown_state(hass: HomeAssistant) -> None:
"""Test we show user form on unsupported device."""
- with patch.object(SyncThru, "update"), patch.object(
- SyncThru, "is_unknown_state", return_value=True
+ with (
+ patch.object(SyncThru, "update"),
+ patch.object(SyncThru, "is_unknown_state", return_value=True),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
diff --git a/tests/components/synology_dsm/test_config_flow.py b/tests/components/synology_dsm/test_config_flow.py
index d0fd3d37b13..67da3712983 100644
--- a/tests/components/synology_dsm/test_config_flow.py
+++ b/tests/components/synology_dsm/test_config_flow.py
@@ -381,12 +381,15 @@ async def test_reconfig_user(hass: HomeAssistant, service: MagicMock) -> None:
unique_id=SERIAL,
).add_to_hass(hass)
- with patch(
- "homeassistant.config_entries.ConfigEntries.async_reload",
- return_value=True,
- ), patch(
- "homeassistant.components.synology_dsm.config_flow.SynologyDSM",
- return_value=service,
+ with (
+ patch(
+ "homeassistant.config_entries.ConfigEntries.async_reload",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.synology_dsm.config_flow.SynologyDSM",
+ return_value=service,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
diff --git a/tests/components/synology_dsm/test_init.py b/tests/components/synology_dsm/test_init.py
index bc8086b8d38..25c4d69dfee 100644
--- a/tests/components/synology_dsm/test_init.py
+++ b/tests/components/synology_dsm/test_init.py
@@ -23,10 +23,13 @@ from tests.common import MockConfigEntry
async def test_services_registered(hass: HomeAssistant, mock_dsm: MagicMock) -> None:
"""Test if all services are registered."""
- with patch(
- "homeassistant.components.synology_dsm.common.SynologyDSM",
- return_value=mock_dsm,
- ), patch("homeassistant.components.synology_dsm.PLATFORMS", return_value=[]):
+ with (
+ patch(
+ "homeassistant.components.synology_dsm.common.SynologyDSM",
+ return_value=mock_dsm,
+ ),
+ patch("homeassistant.components.synology_dsm.PLATFORMS", return_value=[]),
+ ):
entry = MockConfigEntry(
domain=DOMAIN,
data={
@@ -46,17 +49,20 @@ async def test_services_registered(hass: HomeAssistant, mock_dsm: MagicMock) ->
async def test_reauth_triggered(hass: HomeAssistant) -> None:
"""Test if reauthentication flow is triggered."""
- with patch(
- "homeassistant.components.synology_dsm.SynoApi.async_setup",
- side_effect=SynologyDSMLoginInvalidException(USERNAME),
- ), patch(
- "homeassistant.components.synology_dsm.config_flow.SynologyDSMFlowHandler.async_step_reauth",
- return_value={
- "type": data_entry_flow.FlowResultType.FORM,
- "flow_id": "mock_flow",
- "step_id": "reauth_confirm",
- },
- ) as mock_async_step_reauth:
+ with (
+ patch(
+ "homeassistant.components.synology_dsm.SynoApi.async_setup",
+ side_effect=SynologyDSMLoginInvalidException(USERNAME),
+ ),
+ patch(
+ "homeassistant.components.synology_dsm.config_flow.SynologyDSMFlowHandler.async_step_reauth",
+ return_value={
+ "type": data_entry_flow.FlowResultType.FORM,
+ "flow_id": "mock_flow",
+ "step_id": "reauth_confirm",
+ },
+ ) as mock_async_step_reauth,
+ ):
entry = MockConfigEntry(
domain=DOMAIN,
data={
diff --git a/tests/components/synology_dsm/test_media_source.py b/tests/components/synology_dsm/test_media_source.py
index e0aadf9260c..e806014dcd6 100644
--- a/tests/components/synology_dsm/test_media_source.py
+++ b/tests/components/synology_dsm/test_media_source.py
@@ -130,10 +130,13 @@ async def test_browse_media_album_error(
hass: HomeAssistant, dsm_with_photos: MagicMock
) -> None:
"""Test browse_media with unknown album."""
- with patch(
- "homeassistant.components.synology_dsm.common.SynologyDSM",
- return_value=dsm_with_photos,
- ), patch("homeassistant.components.synology_dsm.PLATFORMS", return_value=[]):
+ with (
+ patch(
+ "homeassistant.components.synology_dsm.common.SynologyDSM",
+ return_value=dsm_with_photos,
+ ),
+ patch("homeassistant.components.synology_dsm.PLATFORMS", return_value=[]),
+ ):
entry = MockConfigEntry(
domain=DOMAIN,
data={
@@ -169,10 +172,13 @@ async def test_browse_media_get_root(
hass: HomeAssistant, dsm_with_photos: MagicMock
) -> None:
"""Test browse_media returning root media sources."""
- with patch(
- "homeassistant.components.synology_dsm.common.SynologyDSM",
- return_value=dsm_with_photos,
- ), patch("homeassistant.components.synology_dsm.PLATFORMS", return_value=[]):
+ with (
+ patch(
+ "homeassistant.components.synology_dsm.common.SynologyDSM",
+ return_value=dsm_with_photos,
+ ),
+ patch("homeassistant.components.synology_dsm.PLATFORMS", return_value=[]),
+ ):
entry = MockConfigEntry(
domain=DOMAIN,
data={
@@ -203,10 +209,13 @@ async def test_browse_media_get_albums(
hass: HomeAssistant, dsm_with_photos: MagicMock
) -> None:
"""Test browse_media returning albums."""
- with patch(
- "homeassistant.components.synology_dsm.common.SynologyDSM",
- return_value=dsm_with_photos,
- ), patch("homeassistant.components.synology_dsm.PLATFORMS", return_value=[]):
+ with (
+ patch(
+ "homeassistant.components.synology_dsm.common.SynologyDSM",
+ return_value=dsm_with_photos,
+ ),
+ patch("homeassistant.components.synology_dsm.PLATFORMS", return_value=[]),
+ ):
entry = MockConfigEntry(
domain=DOMAIN,
data={
@@ -241,10 +250,13 @@ async def test_browse_media_get_items_error(
hass: HomeAssistant, dsm_with_photos: MagicMock
) -> None:
"""Test browse_media returning albums."""
- with patch(
- "homeassistant.components.synology_dsm.common.SynologyDSM",
- return_value=dsm_with_photos,
- ), patch("homeassistant.components.synology_dsm.PLATFORMS", return_value=[]):
+ with (
+ patch(
+ "homeassistant.components.synology_dsm.common.SynologyDSM",
+ return_value=dsm_with_photos,
+ ),
+ patch("homeassistant.components.synology_dsm.PLATFORMS", return_value=[]),
+ ):
entry = MockConfigEntry(
domain=DOMAIN,
data={
@@ -288,10 +300,13 @@ async def test_browse_media_get_items_thumbnail_error(
hass: HomeAssistant, dsm_with_photos: MagicMock
) -> None:
"""Test browse_media returning albums."""
- with patch(
- "homeassistant.components.synology_dsm.common.SynologyDSM",
- return_value=dsm_with_photos,
- ), patch("homeassistant.components.synology_dsm.PLATFORMS", return_value=[]):
+ with (
+ patch(
+ "homeassistant.components.synology_dsm.common.SynologyDSM",
+ return_value=dsm_with_photos,
+ ),
+ patch("homeassistant.components.synology_dsm.PLATFORMS", return_value=[]),
+ ):
entry = MockConfigEntry(
domain=DOMAIN,
data={
@@ -327,10 +342,13 @@ async def test_browse_media_get_items(
hass: HomeAssistant, dsm_with_photos: MagicMock
) -> None:
"""Test browse_media returning albums."""
- with patch(
- "homeassistant.components.synology_dsm.common.SynologyDSM",
- return_value=dsm_with_photos,
- ), patch("homeassistant.components.synology_dsm.PLATFORMS", return_value=[]):
+ with (
+ patch(
+ "homeassistant.components.synology_dsm.common.SynologyDSM",
+ return_value=dsm_with_photos,
+ ),
+ patch("homeassistant.components.synology_dsm.PLATFORMS", return_value=[]),
+ ):
entry = MockConfigEntry(
domain=DOMAIN,
data={
@@ -376,10 +394,13 @@ async def test_media_view(
with pytest.raises(web.HTTPNotFound):
await view.get(request, "", "")
- with patch(
- "homeassistant.components.synology_dsm.common.SynologyDSM",
- return_value=dsm_with_photos,
- ), patch("homeassistant.components.synology_dsm.PLATFORMS", return_value=[]):
+ with (
+ patch(
+ "homeassistant.components.synology_dsm.common.SynologyDSM",
+ return_value=dsm_with_photos,
+ ),
+ patch("homeassistant.components.synology_dsm.PLATFORMS", return_value=[]),
+ ):
entry = MockConfigEntry(
domain=DOMAIN,
data={
diff --git a/tests/components/system_bridge/test_config_flow.py b/tests/components/system_bridge/test_config_flow.py
index d9a30610d65..0047cc62365 100644
--- a/tests/components/system_bridge/test_config_flow.py
+++ b/tests/components/system_bridge/test_config_flow.py
@@ -45,18 +45,23 @@ async def test_user_flow(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] is None
- with patch(
- "homeassistant.components.system_bridge.config_flow.WebSocketClient.connect"
- ), patch(
- "systembridgeconnector.websocket_client.WebSocketClient.get_data",
- return_value=FIXTURE_DATA_RESPONSE,
- ), patch(
- "systembridgeconnector.websocket_client.WebSocketClient.listen",
- new=mock_data_listener,
- ), patch(
- "homeassistant.components.system_bridge.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.system_bridge.config_flow.WebSocketClient.connect"
+ ),
+ patch(
+ "systembridgeconnector.websocket_client.WebSocketClient.get_data",
+ return_value=FIXTURE_DATA_RESPONSE,
+ ),
+ patch(
+ "systembridgeconnector.websocket_client.WebSocketClient.listen",
+ new=mock_data_listener,
+ ),
+ patch(
+ "homeassistant.components.system_bridge.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], FIXTURE_USER_INPUT
)
@@ -100,14 +105,18 @@ async def test_form_connection_closed_cannot_connect(hass: HomeAssistant) -> Non
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] is None
- with patch(
- "homeassistant.components.system_bridge.config_flow.WebSocketClient.connect"
- ), patch(
- "systembridgeconnector.websocket_client.WebSocketClient.get_data",
- side_effect=ConnectionClosedException,
- ), patch(
- "systembridgeconnector.websocket_client.WebSocketClient.listen",
- new=mock_data_listener,
+ with (
+ patch(
+ "homeassistant.components.system_bridge.config_flow.WebSocketClient.connect"
+ ),
+ patch(
+ "systembridgeconnector.websocket_client.WebSocketClient.get_data",
+ side_effect=ConnectionClosedException,
+ ),
+ patch(
+ "systembridgeconnector.websocket_client.WebSocketClient.listen",
+ new=mock_data_listener,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], FIXTURE_USER_INPUT
@@ -128,14 +137,18 @@ async def test_form_timeout_cannot_connect(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] is None
- with patch(
- "homeassistant.components.system_bridge.config_flow.WebSocketClient.connect"
- ), patch(
- "systembridgeconnector.websocket_client.WebSocketClient.get_data",
- side_effect=TimeoutError,
- ), patch(
- "systembridgeconnector.websocket_client.WebSocketClient.listen",
- new=mock_data_listener,
+ with (
+ patch(
+ "homeassistant.components.system_bridge.config_flow.WebSocketClient.connect"
+ ),
+ patch(
+ "systembridgeconnector.websocket_client.WebSocketClient.get_data",
+ side_effect=TimeoutError,
+ ),
+ patch(
+ "systembridgeconnector.websocket_client.WebSocketClient.listen",
+ new=mock_data_listener,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], FIXTURE_USER_INPUT
@@ -156,14 +169,18 @@ async def test_form_invalid_auth(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] is None
- with patch(
- "homeassistant.components.system_bridge.config_flow.WebSocketClient.connect"
- ), patch(
- "systembridgeconnector.websocket_client.WebSocketClient.get_data",
- side_effect=AuthenticationException,
- ), patch(
- "systembridgeconnector.websocket_client.WebSocketClient.listen",
- new=mock_data_listener,
+ with (
+ patch(
+ "homeassistant.components.system_bridge.config_flow.WebSocketClient.connect"
+ ),
+ patch(
+ "systembridgeconnector.websocket_client.WebSocketClient.get_data",
+ side_effect=AuthenticationException,
+ ),
+ patch(
+ "systembridgeconnector.websocket_client.WebSocketClient.listen",
+ new=mock_data_listener,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], FIXTURE_USER_INPUT
@@ -184,14 +201,18 @@ async def test_form_uuid_error(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] is None
- with patch(
- "homeassistant.components.system_bridge.config_flow.WebSocketClient.connect"
- ), patch(
- "systembridgeconnector.websocket_client.WebSocketClient.get_data",
- side_effect=ValueError,
- ), patch(
- "systembridgeconnector.websocket_client.WebSocketClient.listen",
- new=mock_data_listener,
+ with (
+ patch(
+ "homeassistant.components.system_bridge.config_flow.WebSocketClient.connect"
+ ),
+ patch(
+ "systembridgeconnector.websocket_client.WebSocketClient.get_data",
+ side_effect=ValueError,
+ ),
+ patch(
+ "systembridgeconnector.websocket_client.WebSocketClient.listen",
+ new=mock_data_listener,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], FIXTURE_USER_INPUT
@@ -212,14 +233,18 @@ async def test_form_unknown_error(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] is None
- with patch(
- "homeassistant.components.system_bridge.config_flow.WebSocketClient.connect"
- ), patch(
- "systembridgeconnector.websocket_client.WebSocketClient.get_data",
- side_effect=Exception,
- ), patch(
- "systembridgeconnector.websocket_client.WebSocketClient.listen",
- new=mock_data_listener,
+ with (
+ patch(
+ "homeassistant.components.system_bridge.config_flow.WebSocketClient.connect"
+ ),
+ patch(
+ "systembridgeconnector.websocket_client.WebSocketClient.get_data",
+ side_effect=Exception,
+ ),
+ patch(
+ "systembridgeconnector.websocket_client.WebSocketClient.listen",
+ new=mock_data_listener,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], FIXTURE_USER_INPUT
@@ -240,14 +265,18 @@ async def test_reauth_authorization_error(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "authenticate"
- with patch(
- "homeassistant.components.system_bridge.config_flow.WebSocketClient.connect"
- ), patch(
- "systembridgeconnector.websocket_client.WebSocketClient.get_data",
- side_effect=AuthenticationException,
- ), patch(
- "systembridgeconnector.websocket_client.WebSocketClient.listen",
- new=mock_data_listener,
+ with (
+ patch(
+ "homeassistant.components.system_bridge.config_flow.WebSocketClient.connect"
+ ),
+ patch(
+ "systembridgeconnector.websocket_client.WebSocketClient.get_data",
+ side_effect=AuthenticationException,
+ ),
+ patch(
+ "systembridgeconnector.websocket_client.WebSocketClient.listen",
+ new=mock_data_listener,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], FIXTURE_AUTH_INPUT
@@ -281,14 +310,18 @@ async def test_reauth_connection_error(hass: HomeAssistant) -> None:
assert result2["step_id"] == "authenticate"
assert result2["errors"] == {"base": "cannot_connect"}
- with patch(
- "systembridgeconnector.websocket_client.WebSocketClient.connect",
- ), patch(
- "systembridgeconnector.websocket_client.WebSocketClient.get_data",
- return_value=None,
- ), patch(
- "systembridgeconnector.websocket_client.WebSocketClient.listen",
- new=mock_data_listener,
+ with (
+ patch(
+ "systembridgeconnector.websocket_client.WebSocketClient.connect",
+ ),
+ patch(
+ "systembridgeconnector.websocket_client.WebSocketClient.get_data",
+ return_value=None,
+ ),
+ patch(
+ "systembridgeconnector.websocket_client.WebSocketClient.listen",
+ new=mock_data_listener,
+ ),
):
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"], FIXTURE_AUTH_INPUT
@@ -309,14 +342,18 @@ async def test_reauth_connection_closed_error(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "authenticate"
- with patch(
- "homeassistant.components.system_bridge.config_flow.WebSocketClient.connect"
- ), patch(
- "systembridgeconnector.websocket_client.WebSocketClient.get_data",
- side_effect=ConnectionClosedException,
- ), patch(
- "systembridgeconnector.websocket_client.WebSocketClient.listen",
- new=mock_data_listener,
+ with (
+ patch(
+ "homeassistant.components.system_bridge.config_flow.WebSocketClient.connect"
+ ),
+ patch(
+ "systembridgeconnector.websocket_client.WebSocketClient.get_data",
+ side_effect=ConnectionClosedException,
+ ),
+ patch(
+ "systembridgeconnector.websocket_client.WebSocketClient.listen",
+ new=mock_data_listener,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], FIXTURE_AUTH_INPUT
@@ -342,17 +379,22 @@ async def test_reauth_flow(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "authenticate"
- with patch(
- "homeassistant.components.system_bridge.config_flow.WebSocketClient.connect"
- ), patch(
- "systembridgeconnector.websocket_client.WebSocketClient.get_data",
- return_value=FIXTURE_DATA_RESPONSE,
- ), patch(
- "systembridgeconnector.websocket_client.WebSocketClient.listen",
- new=mock_data_listener,
- ), patch(
- "homeassistant.components.system_bridge.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.system_bridge.config_flow.WebSocketClient.connect"
+ ),
+ patch(
+ "systembridgeconnector.websocket_client.WebSocketClient.get_data",
+ return_value=FIXTURE_DATA_RESPONSE,
+ ),
+ patch(
+ "systembridgeconnector.websocket_client.WebSocketClient.listen",
+ new=mock_data_listener,
+ ),
+ patch(
+ "homeassistant.components.system_bridge.async_setup_entry",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], FIXTURE_AUTH_INPUT
@@ -375,18 +417,23 @@ async def test_zeroconf_flow(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert not result["errors"]
- with patch(
- "homeassistant.components.system_bridge.config_flow.WebSocketClient.connect"
- ), patch(
- "systembridgeconnector.websocket_client.WebSocketClient.get_data",
- return_value=FIXTURE_DATA_RESPONSE,
- ), patch(
- "systembridgeconnector.websocket_client.WebSocketClient.listen",
- new=mock_data_listener,
- ), patch(
- "homeassistant.components.system_bridge.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.system_bridge.config_flow.WebSocketClient.connect"
+ ),
+ patch(
+ "systembridgeconnector.websocket_client.WebSocketClient.get_data",
+ return_value=FIXTURE_DATA_RESPONSE,
+ ),
+ patch(
+ "systembridgeconnector.websocket_client.WebSocketClient.listen",
+ new=mock_data_listener,
+ ),
+ patch(
+ "homeassistant.components.system_bridge.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], FIXTURE_AUTH_INPUT
)
diff --git a/tests/components/system_log/test_init.py b/tests/components/system_log/test_init.py
index 22cef15b1ab..5e4eda7d643 100644
--- a/tests/components/system_log/test_init.py
+++ b/tests/components/system_log/test_init.py
@@ -376,11 +376,14 @@ async def async_log_error_from_test_path(hass, path, watcher):
call_path_frame = get_frame(call_path, path_frame)
logger_frame = get_frame("venv_path/logging/log.py", call_path_frame)
- with patch.object(
- _LOGGER, "findCaller", MagicMock(return_value=(call_path, 0, None, None))
- ), patch(
- "homeassistant.components.system_log.sys._getframe",
- return_value=logger_frame,
+ with (
+ patch.object(
+ _LOGGER, "findCaller", MagicMock(return_value=(call_path, 0, None, None))
+ ),
+ patch(
+ "homeassistant.components.system_log.sys._getframe",
+ return_value=logger_frame,
+ ),
):
wait_empty = watcher.add_watcher("error message")
_LOGGER.error("error message")
diff --git a/tests/components/systemmonitor/conftest.py b/tests/components/systemmonitor/conftest.py
index e6e1b35e66d..c8cf614e04d 100644
--- a/tests/components/systemmonitor/conftest.py
+++ b/tests/components/systemmonitor/conftest.py
@@ -193,11 +193,10 @@ def mock_os() -> Generator:
"""Mock os.path.isdir."""
return path != "/etc/hosts"
- with patch(
- "homeassistant.components.systemmonitor.coordinator.os"
- ) as mock_os, patch(
- "homeassistant.components.systemmonitor.util.os"
- ) as mock_os_util:
+ with (
+ patch("homeassistant.components.systemmonitor.coordinator.os") as mock_os,
+ patch("homeassistant.components.systemmonitor.util.os") as mock_os_util,
+ ):
mock_os_util.name = "nt"
mock_os.getloadavg.return_value = (1, 2, 3)
mock_os_util.path.isdir = isdir
diff --git a/tests/components/tado/test_config_flow.py b/tests/components/tado/test_config_flow.py
index 5f20e0e95b3..c2bbe4f37de 100644
--- a/tests/components/tado/test_config_flow.py
+++ b/tests/components/tado/test_config_flow.py
@@ -62,13 +62,16 @@ async def test_form_exceptions(
# Test a retry to recover, upon failure
mock_tado_api = _get_mock_tado_api(getMe={"homes": [{"id": 1, "name": "myhome"}]})
- with patch(
- "homeassistant.components.tado.config_flow.Tado",
- return_value=mock_tado_api,
- ), patch(
- "homeassistant.components.tado.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.tado.config_flow.Tado",
+ return_value=mock_tado_api,
+ ),
+ patch(
+ "homeassistant.components.tado.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"username": "test-username", "password": "test-password"},
@@ -129,13 +132,16 @@ async def test_create_entry(hass: HomeAssistant) -> None:
mock_tado_api = _get_mock_tado_api(getMe={"homes": [{"id": 1, "name": "myhome"}]})
- with patch(
- "homeassistant.components.tado.config_flow.Tado",
- return_value=mock_tado_api,
- ), patch(
- "homeassistant.components.tado.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.tado.config_flow.Tado",
+ return_value=mock_tado_api,
+ ),
+ patch(
+ "homeassistant.components.tado.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"username": "test-username", "password": "test-password"},
@@ -268,13 +274,16 @@ async def test_import_step(hass: HomeAssistant) -> None:
"""Test import step."""
mock_tado_api = _get_mock_tado_api(getMe={"homes": [{"id": 1, "name": "myhome"}]})
- with patch(
- "homeassistant.components.tado.config_flow.Tado",
- return_value=mock_tado_api,
- ), patch(
- "homeassistant.components.tado.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.tado.config_flow.Tado",
+ return_value=mock_tado_api,
+ ),
+ patch(
+ "homeassistant.components.tado.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
diff --git a/tests/components/tailwind/conftest.py b/tests/components/tailwind/conftest.py
index b03bb0ab0ec..b7443e59581 100644
--- a/tests/components/tailwind/conftest.py
+++ b/tests/components/tailwind/conftest.py
@@ -47,11 +47,14 @@ def mock_setup_entry() -> Generator[AsyncMock, None, None]:
@pytest.fixture
def mock_tailwind(device_fixture: str) -> Generator[MagicMock, None, None]:
"""Return a mocked Tailwind client."""
- with patch(
- "homeassistant.components.tailwind.coordinator.Tailwind", autospec=True
- ) as tailwind_mock, patch(
- "homeassistant.components.tailwind.config_flow.Tailwind",
- new=tailwind_mock,
+ with (
+ patch(
+ "homeassistant.components.tailwind.coordinator.Tailwind", autospec=True
+ ) as tailwind_mock,
+ patch(
+ "homeassistant.components.tailwind.config_flow.Tailwind",
+ new=tailwind_mock,
+ ),
):
tailwind = tailwind_mock.return_value
tailwind.status.return_value = TailwindDeviceStatus.from_json(
diff --git a/tests/components/tankerkoenig/conftest.py b/tests/components/tankerkoenig/conftest.py
index 7f71ce8cb19..4400082a45f 100644
--- a/tests/components/tankerkoenig/conftest.py
+++ b/tests/components/tankerkoenig/conftest.py
@@ -27,12 +27,15 @@ from tests.common import MockConfigEntry
@pytest.fixture(name="tankerkoenig")
def mock_tankerkoenig() -> Generator[AsyncMock, None, None]:
"""Mock the aiotankerkoenig client."""
- with patch(
- "homeassistant.components.tankerkoenig.coordinator.Tankerkoenig",
- autospec=True,
- ) as mock_tankerkoenig, patch(
- "homeassistant.components.tankerkoenig.config_flow.Tankerkoenig",
- new=mock_tankerkoenig,
+ with (
+ patch(
+ "homeassistant.components.tankerkoenig.coordinator.Tankerkoenig",
+ autospec=True,
+ ) as mock_tankerkoenig,
+ patch(
+ "homeassistant.components.tankerkoenig.config_flow.Tankerkoenig",
+ new=mock_tankerkoenig,
+ ),
):
mock = mock_tankerkoenig.return_value
mock.station_details.return_value = STATION
diff --git a/tests/components/tankerkoenig/test_config_flow.py b/tests/components/tankerkoenig/test_config_flow.py
index f7cdc44021e..b954598c12a 100644
--- a/tests/components/tankerkoenig/test_config_flow.py
+++ b/tests/components/tankerkoenig/test_config_flow.py
@@ -59,11 +59,14 @@ async def test_user(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.tankerkoenig.async_setup_entry", return_value=True
- ) as mock_setup_entry, patch(
- "homeassistant.components.tankerkoenig.config_flow.Tankerkoenig.nearby_stations",
- return_value=NEARBY_STATIONS,
+ with (
+ patch(
+ "homeassistant.components.tankerkoenig.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.tankerkoenig.config_flow.Tankerkoenig.nearby_stations",
+ return_value=NEARBY_STATIONS,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_USER_DATA
@@ -159,11 +162,14 @@ async def test_reauth(hass: HomeAssistant, config_entry: MockConfigEntry) -> Non
"""Test starting a flow by user to re-auth."""
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.tankerkoenig.async_setup_entry", return_value=True
- ) as mock_setup_entry, patch(
- "homeassistant.components.tankerkoenig.config_flow.Tankerkoenig.nearby_stations",
- ) as mock_nearby_stations:
+ with (
+ patch(
+ "homeassistant.components.tankerkoenig.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.tankerkoenig.config_flow.Tankerkoenig.nearby_stations",
+ ) as mock_nearby_stations,
+ ):
# re-auth initialized
result = await hass.config_entries.flow.async_init(
DOMAIN,
diff --git a/tests/components/tautulli/test_config_flow.py b/tests/components/tautulli/test_config_flow.py
index f867b5d0fb1..e51fbfbad0d 100644
--- a/tests/components/tautulli/test_config_flow.py
+++ b/tests/components/tautulli/test_config_flow.py
@@ -171,9 +171,10 @@ async def test_flow_reauth(
new_conf = {CONF_API_KEY: "efgh"}
CONF_DATA[CONF_API_KEY] = "efgh"
- with patch_config_flow_tautulli(AsyncMock()), patch(
- "homeassistant.components.tautulli.async_setup_entry"
- ) as mock_entry:
+ with (
+ patch_config_flow_tautulli(AsyncMock()),
+ patch("homeassistant.components.tautulli.async_setup_entry") as mock_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=new_conf,
diff --git a/tests/components/tcp/test_binary_sensor.py b/tests/components/tcp/test_binary_sensor.py
index 089e5748cb7..959c1f050fd 100644
--- a/tests/components/tcp/test_binary_sensor.py
+++ b/tests/components/tcp/test_binary_sensor.py
@@ -22,11 +22,12 @@ TEST_ENTITY = "binary_sensor.test_name"
@pytest.fixture(name="mock_socket")
def mock_socket_fixture():
"""Mock the socket."""
- with patch(
- "homeassistant.components.tcp.common.socket.socket"
- ) as mock_socket, patch(
- "homeassistant.components.tcp.common.select.select",
- return_value=(True, False, False),
+ with (
+ patch("homeassistant.components.tcp.common.socket.socket") as mock_socket,
+ patch(
+ "homeassistant.components.tcp.common.select.select",
+ return_value=(True, False, False),
+ ),
):
# yield the return value of the socket context manager
yield mock_socket.return_value.__enter__.return_value
diff --git a/tests/components/technove/conftest.py b/tests/components/technove/conftest.py
index 4f4e5e4c978..06db6e24f47 100644
--- a/tests/components/technove/conftest.py
+++ b/tests/components/technove/conftest.py
@@ -51,10 +51,13 @@ def device_fixture() -> TechnoVEStation:
@pytest.fixture
def mock_technove(device_fixture: TechnoVEStation) -> Generator[MagicMock, None, None]:
"""Return a mocked TechnoVE client."""
- with patch(
- "homeassistant.components.technove.coordinator.TechnoVE", autospec=True
- ) as technove_mock, patch(
- "homeassistant.components.technove.config_flow.TechnoVE", new=technove_mock
+ with (
+ patch(
+ "homeassistant.components.technove.coordinator.TechnoVE", autospec=True
+ ) as technove_mock,
+ patch(
+ "homeassistant.components.technove.config_flow.TechnoVE", new=technove_mock
+ ),
):
technove = technove_mock.return_value
technove.update.return_value = device_fixture
diff --git a/tests/components/tedee/conftest.py b/tests/components/tedee/conftest.py
index b5597ee2faa..9f0730992d2 100644
--- a/tests/components/tedee/conftest.py
+++ b/tests/components/tedee/conftest.py
@@ -43,11 +43,14 @@ def mock_setup_entry() -> Generator[AsyncMock, None, None]:
@pytest.fixture
def mock_tedee(request) -> Generator[MagicMock, None, None]:
"""Return a mocked Tedee client."""
- with patch(
- "homeassistant.components.tedee.coordinator.TedeeClient", autospec=True
- ) as tedee_mock, patch(
- "homeassistant.components.tedee.config_flow.TedeeClient",
- new=tedee_mock,
+ with (
+ patch(
+ "homeassistant.components.tedee.coordinator.TedeeClient", autospec=True
+ ) as tedee_mock,
+ patch(
+ "homeassistant.components.tedee.config_flow.TedeeClient",
+ new=tedee_mock,
+ ),
):
tedee = tedee_mock.return_value
diff --git a/tests/components/telegram_bot/conftest.py b/tests/components/telegram_bot/conftest.py
index 864c9eba9ec..0906b6afcbd 100644
--- a/tests/components/telegram_bot/conftest.py
+++ b/tests/components/telegram_bot/conftest.py
@@ -62,12 +62,15 @@ def config_polling():
@pytest.fixture
def mock_register_webhook():
"""Mock calls made by telegram_bot when (de)registering webhook."""
- with patch(
- "homeassistant.components.telegram_bot.webhooks.PushBot.register_webhook",
- return_value=True,
- ), patch(
- "homeassistant.components.telegram_bot.webhooks.PushBot.deregister_webhook",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.telegram_bot.webhooks.PushBot.register_webhook",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.telegram_bot.webhooks.PushBot.deregister_webhook",
+ return_value=True,
+ ),
):
yield
@@ -76,16 +79,21 @@ def mock_register_webhook():
def mock_external_calls():
"""Mock calls that make calls to the live Telegram API."""
test_user = User(123456, "Testbot", True)
- with patch(
- "telegram.Bot.get_me",
- return_value=test_user,
- ), patch(
- "telegram.Bot._bot_user",
- test_user,
- ), patch(
- "telegram.Bot.bot",
- test_user,
- ), patch("telegram.ext.Updater._bootstrap"):
+ with (
+ patch(
+ "telegram.Bot.get_me",
+ return_value=test_user,
+ ),
+ patch(
+ "telegram.Bot._bot_user",
+ test_user,
+ ),
+ patch(
+ "telegram.Bot.bot",
+ test_user,
+ ),
+ patch("telegram.ext.Updater._bootstrap"),
+ ):
yield
diff --git a/tests/components/tellduslive/test_config_flow.py b/tests/components/tellduslive/test_config_flow.py
index cf107477897..3cd157fd8b5 100644
--- a/tests/components/tellduslive/test_config_flow.py
+++ b/tests/components/tellduslive/test_config_flow.py
@@ -43,11 +43,12 @@ def authorize():
@pytest.fixture
def mock_tellduslive(supports_local_api, authorize):
"""Mock tellduslive."""
- with patch(
- "homeassistant.components.tellduslive.config_flow.Session"
- ) as Session, patch(
- "homeassistant.components.tellduslive.config_flow.supports_local_api"
- ) as tellduslive_supports_local_api:
+ with (
+ patch("homeassistant.components.tellduslive.config_flow.Session") as Session,
+ patch(
+ "homeassistant.components.tellduslive.config_flow.supports_local_api"
+ ) as tellduslive_supports_local_api,
+ ):
tellduslive_supports_local_api.return_value = supports_local_api
Session().authorize.return_value = authorize
Session().access_token = "token"
@@ -139,10 +140,13 @@ async def test_step_import_load_json_matching_host(
"""Test that we add host and trigger user when configuring from import."""
flow = init_config_flow(hass)
- with patch(
- "homeassistant.components.tellduslive.config_flow.load_json_object",
- return_value={"tellduslive": {}},
- ), patch("os.path.isfile"):
+ with (
+ patch(
+ "homeassistant.components.tellduslive.config_flow.load_json_object",
+ return_value={"tellduslive": {}},
+ ),
+ patch("os.path.isfile"),
+ ):
result = await flow.async_step_import(
{CONF_HOST: "Cloud API", KEY_SCAN_INTERVAL: 0}
)
@@ -154,10 +158,13 @@ async def test_step_import_load_json(hass: HomeAssistant, mock_tellduslive) -> N
"""Test that we create entry when configuring from import."""
flow = init_config_flow(hass)
- with patch(
- "homeassistant.components.tellduslive.config_flow.load_json_object",
- return_value={"localhost": {}},
- ), patch("os.path.isfile"):
+ with (
+ patch(
+ "homeassistant.components.tellduslive.config_flow.load_json_object",
+ return_value={"localhost": {}},
+ ),
+ patch("os.path.isfile"),
+ ):
result = await flow.async_step_import(
{CONF_HOST: "localhost", KEY_SCAN_INTERVAL: SCAN_INTERVAL}
)
diff --git a/tests/components/template/test_sensor.py b/tests/components/template/test_sensor.py
index c046e961fac..fdcc0587a73 100644
--- a/tests/components/template/test_sensor.py
+++ b/tests/components/template/test_sensor.py
@@ -394,12 +394,15 @@ async def test_creating_sensor_loads_group(hass: HomeAssistant) -> None:
hass.bus.async_listen(EVENT_COMPONENT_LOADED, set_after_dep_event)
- with patch(
- "homeassistant.components.group.async_setup",
- new=async_setup_group,
- ), patch(
- "homeassistant.components.template.sensor.async_setup_platform",
- new=async_setup_template,
+ with (
+ patch(
+ "homeassistant.components.group.async_setup",
+ new=async_setup_group,
+ ),
+ patch(
+ "homeassistant.components.template.sensor.async_setup_platform",
+ new=async_setup_template,
+ ),
):
await async_from_config_dict(
{"sensor": {"platform": "template", "sensors": {}}, "group": {}}, hass
@@ -1602,11 +1605,15 @@ async def test_entity_last_reset_parsing(
# State of timestamp sensors are always in UTC
now = dt_util.utcnow()
- with patch(
- "homeassistant.components.template.sensor._LOGGER.warning"
- ) as mocked_warning, patch(
- "homeassistant.components.template.template_entity._LOGGER.error"
- ) as mocked_error, patch("homeassistant.util.dt.now", return_value=now):
+ with (
+ patch(
+ "homeassistant.components.template.sensor._LOGGER.warning"
+ ) as mocked_warning,
+ patch(
+ "homeassistant.components.template.template_entity._LOGGER.error"
+ ) as mocked_error,
+ patch("homeassistant.util.dt.now", return_value=now),
+ ):
assert await async_setup_component(
hass,
"template",
diff --git a/tests/components/tesla_wall_connector/conftest.py b/tests/components/tesla_wall_connector/conftest.py
index 7ff5db504d2..a31df11dcd0 100644
--- a/tests/components/tesla_wall_connector/conftest.py
+++ b/tests/components/tesla_wall_connector/conftest.py
@@ -63,18 +63,22 @@ async def create_wall_connector_entry(
entry.add_to_hass(hass)
- with patch(
- "tesla_wall_connector.WallConnector.async_get_version",
- return_value=get_default_version_data(),
- side_effect=side_effect,
- ), patch(
- "tesla_wall_connector.WallConnector.async_get_vitals",
- return_value=vitals_data,
- side_effect=side_effect,
- ), patch(
- "tesla_wall_connector.WallConnector.async_get_lifetime",
- return_value=lifetime_data,
- side_effect=side_effect,
+ with (
+ patch(
+ "tesla_wall_connector.WallConnector.async_get_version",
+ return_value=get_default_version_data(),
+ side_effect=side_effect,
+ ),
+ patch(
+ "tesla_wall_connector.WallConnector.async_get_vitals",
+ return_value=vitals_data,
+ side_effect=side_effect,
+ ),
+ patch(
+ "tesla_wall_connector.WallConnector.async_get_lifetime",
+ return_value=lifetime_data,
+ side_effect=side_effect,
+ ),
):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
@@ -127,12 +131,15 @@ async def _test_sensors(
), f"First update: {entity.entity_id} is expected to have state {entity.first_value} but has {state.state}"
# Simulate second data update
- with patch(
- "tesla_wall_connector.WallConnector.async_get_vitals",
- return_value=vitals_second_update,
- ), patch(
- "tesla_wall_connector.WallConnector.async_get_lifetime",
- return_value=lifetime_second_update,
+ with (
+ patch(
+ "tesla_wall_connector.WallConnector.async_get_vitals",
+ return_value=vitals_second_update,
+ ),
+ patch(
+ "tesla_wall_connector.WallConnector.async_get_lifetime",
+ return_value=lifetime_second_update,
+ ),
):
async_fire_time_changed(
hass, dt_util.utcnow() + timedelta(seconds=DEFAULT_SCAN_INTERVAL)
diff --git a/tests/components/teslemetry/test_climate.py b/tests/components/teslemetry/test_climate.py
index 2e791f68b93..e83e9d648cd 100644
--- a/tests/components/teslemetry/test_climate.py
+++ b/tests/components/teslemetry/test_climate.py
@@ -94,10 +94,13 @@ async def test_errors(
await setup_platform(hass, platforms=[Platform.CLIMATE])
entity_id = "climate.test_climate"
- with patch(
- "homeassistant.components.teslemetry.VehicleSpecific.auto_conditioning_start",
- side_effect=InvalidCommand,
- ) as mock_on, pytest.raises(HomeAssistantError) as error:
+ with (
+ patch(
+ "homeassistant.components.teslemetry.VehicleSpecific.auto_conditioning_start",
+ side_effect=InvalidCommand,
+ ) as mock_on,
+ pytest.raises(HomeAssistantError) as error,
+ ):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_TURN_ON,
@@ -148,9 +151,10 @@ async def test_asleep_or_offline(
# Run a command but timeout trying to wake up the vehicle
mock_wake_up.return_value = WAKE_UP_ASLEEP
mock_vehicle.return_value = WAKE_UP_ASLEEP
- with patch(
- "homeassistant.components.teslemetry.entity.asyncio.sleep"
- ), pytest.raises(HomeAssistantError) as error:
+ with (
+ patch("homeassistant.components.teslemetry.entity.asyncio.sleep"),
+ pytest.raises(HomeAssistantError) as error,
+ ):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_TURN_ON,
diff --git a/tests/components/tessie/common.py b/tests/components/tessie/common.py
index c57dbda8b53..2f213c4e798 100644
--- a/tests/components/tessie/common.py
+++ b/tests/components/tessie/common.py
@@ -57,11 +57,14 @@ async def setup_platform(
)
mock_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.tessie.get_state_of_all_vehicles",
- return_value=TEST_STATE_OF_ALL_VEHICLES,
- side_effect=side_effect,
- ), patch("homeassistant.components.tessie.PLATFORMS", platforms):
+ with (
+ patch(
+ "homeassistant.components.tessie.get_state_of_all_vehicles",
+ return_value=TEST_STATE_OF_ALL_VEHICLES,
+ side_effect=side_effect,
+ ),
+ patch("homeassistant.components.tessie.PLATFORMS", platforms),
+ ):
await hass.config_entries.async_setup(mock_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/tessie/test_climate.py b/tests/components/tessie/test_climate.py
index 88499a7736c..df86f0b2986 100644
--- a/tests/components/tessie/test_climate.py
+++ b/tests/components/tessie/test_climate.py
@@ -52,13 +52,16 @@ async def test_climate(
assert state.state == HVACMode.HEAT_COOL
# Test setting climate temp
- with patch(
- "homeassistant.components.tessie.climate.set_temperature",
- return_value=TEST_RESPONSE,
- ) as mock_set, patch(
- "homeassistant.components.tessie.climate.start_climate_preconditioning",
- return_value=TEST_RESPONSE,
- ) as mock_set2:
+ with (
+ patch(
+ "homeassistant.components.tessie.climate.set_temperature",
+ return_value=TEST_RESPONSE,
+ ) as mock_set,
+ patch(
+ "homeassistant.components.tessie.climate.start_climate_preconditioning",
+ return_value=TEST_RESPONSE,
+ ) as mock_set2,
+ ):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
@@ -112,10 +115,13 @@ async def test_errors(hass: HomeAssistant) -> None:
entity_id = "climate.test_climate"
# Test setting climate on with unknown error
- with patch(
- "homeassistant.components.tessie.climate.stop_climate",
- side_effect=ERROR_UNKNOWN,
- ) as mock_set, pytest.raises(HomeAssistantError) as error:
+ with (
+ patch(
+ "homeassistant.components.tessie.climate.stop_climate",
+ side_effect=ERROR_UNKNOWN,
+ ) as mock_set,
+ pytest.raises(HomeAssistantError) as error,
+ ):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_TURN_OFF,
diff --git a/tests/components/tessie/test_cover.py b/tests/components/tessie/test_cover.py
index c4dbd8cb704..ebf4c503110 100644
--- a/tests/components/tessie/test_cover.py
+++ b/tests/components/tessie/test_cover.py
@@ -81,10 +81,13 @@ async def test_errors(hass: HomeAssistant) -> None:
entity_id = "cover.test_charge_port_door"
# Test setting cover open with unknown error
- with patch(
- "homeassistant.components.tessie.cover.open_unlock_charge_port",
- side_effect=ERROR_UNKNOWN,
- ) as mock_set, pytest.raises(HomeAssistantError) as error:
+ with (
+ patch(
+ "homeassistant.components.tessie.cover.open_unlock_charge_port",
+ side_effect=ERROR_UNKNOWN,
+ ) as mock_set,
+ pytest.raises(HomeAssistantError) as error,
+ ):
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_OPEN_COVER,
@@ -95,10 +98,13 @@ async def test_errors(hass: HomeAssistant) -> None:
assert error.from_exception == ERROR_UNKNOWN
# Test setting cover open with unknown error
- with patch(
- "homeassistant.components.tessie.cover.open_unlock_charge_port",
- return_value=TEST_RESPONSE_ERROR,
- ) as mock_set, pytest.raises(HomeAssistantError) as error:
+ with (
+ patch(
+ "homeassistant.components.tessie.cover.open_unlock_charge_port",
+ return_value=TEST_RESPONSE_ERROR,
+ ) as mock_set,
+ pytest.raises(HomeAssistantError) as error,
+ ):
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_OPEN_COVER,
diff --git a/tests/components/tessie/test_select.py b/tests/components/tessie/test_select.py
index 0a6d56621b3..7f79dbe3297 100644
--- a/tests/components/tessie/test_select.py
+++ b/tests/components/tessie/test_select.py
@@ -53,10 +53,13 @@ async def test_errors(hass: HomeAssistant) -> None:
entity_id = "select.test_seat_heater_left"
# Test setting cover open with unknown error
- with patch(
- "homeassistant.components.tessie.select.set_seat_heat",
- side_effect=ERROR_UNKNOWN,
- ) as mock_set, pytest.raises(HomeAssistantError) as error:
+ with (
+ patch(
+ "homeassistant.components.tessie.select.set_seat_heat",
+ side_effect=ERROR_UNKNOWN,
+ ) as mock_set,
+ pytest.raises(HomeAssistantError) as error,
+ ):
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
diff --git a/tests/components/thread/test_config_flow.py b/tests/components/thread/test_config_flow.py
index e46b5b70961..9f4930947ef 100644
--- a/tests/components/thread/test_config_flow.py
+++ b/tests/components/thread/test_config_flow.py
@@ -132,12 +132,15 @@ async def test_zeroconf(hass: HomeAssistant) -> None:
async def test_zeroconf_setup_onboarding(hass: HomeAssistant) -> None:
"""Test we automatically finish a zeroconf flow during onboarding."""
- with patch(
- "homeassistant.components.onboarding.async_is_onboarded", return_value=False
- ), patch(
- "homeassistant.components.thread.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.onboarding.async_is_onboarded", return_value=False
+ ),
+ patch(
+ "homeassistant.components.thread.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
thread.DOMAIN, context={"source": "zeroconf"}, data=TEST_ZEROCONF_RECORD
)
diff --git a/tests/components/tibber/test_diagnostics.py b/tests/components/tibber/test_diagnostics.py
index 7047d995819..34ecb63dfec 100644
--- a/tests/components/tibber/test_diagnostics.py
+++ b/tests/components/tibber/test_diagnostics.py
@@ -19,10 +19,13 @@ async def test_entry_diagnostics(
config_entry,
) -> None:
"""Test config entry diagnostics."""
- with patch(
- "tibber.Tibber.update_info",
- return_value=None,
- ), patch("homeassistant.components.tibber.discovery.async_load_platform"):
+ with (
+ patch(
+ "tibber.Tibber.update_info",
+ return_value=None,
+ ),
+ patch("homeassistant.components.tibber.discovery.async_load_platform"),
+ ):
assert await async_setup_component(hass, "tibber", {})
await hass.async_block_till_done()
diff --git a/tests/components/tile/conftest.py b/tests/components/tile/conftest.py
index 964986ba151..e3b55c49ae7 100644
--- a/tests/components/tile/conftest.py
+++ b/tests/components/tile/conftest.py
@@ -54,9 +54,12 @@ def data_tile_details_fixture():
@pytest.fixture(name="mock_pytile")
async def mock_pytile_fixture(api):
"""Define a fixture to patch pytile."""
- with patch(
- "homeassistant.components.tile.config_flow.async_login", return_value=api
- ), patch("homeassistant.components.tile.async_login", return_value=api):
+ with (
+ patch(
+ "homeassistant.components.tile.config_flow.async_login", return_value=api
+ ),
+ patch("homeassistant.components.tile.async_login", return_value=api),
+ ):
yield
diff --git a/tests/components/todoist/conftest.py b/tests/components/todoist/conftest.py
index 773fc0eb195..4968b6beefb 100644
--- a/tests/components/todoist/conftest.py
+++ b/tests/components/todoist/conftest.py
@@ -153,9 +153,10 @@ async def mock_setup_integration(
"""Mock setup of the todoist integration."""
if todoist_config_entry is not None:
todoist_config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.todoist.TodoistAPIAsync", return_value=api
- ), patch("homeassistant.components.todoist.PLATFORMS", platforms):
+ with (
+ patch("homeassistant.components.todoist.TodoistAPIAsync", return_value=api),
+ patch("homeassistant.components.todoist.PLATFORMS", platforms),
+ ):
assert await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
yield
diff --git a/tests/components/tomorrowio/conftest.py b/tests/components/tomorrowio/conftest.py
index 94adda43f23..3e7095210fe 100644
--- a/tests/components/tomorrowio/conftest.py
+++ b/tests/components/tomorrowio/conftest.py
@@ -21,16 +21,20 @@ def tomorrowio_config_flow_connect():
@pytest.fixture(name="tomorrowio_config_entry_update", autouse=True)
def tomorrowio_config_entry_update_fixture():
"""Mock valid tomorrowio config entry setup."""
- with patch(
- "homeassistant.components.tomorrowio.TomorrowioV4.realtime_and_all_forecasts",
- return_value=json.loads(load_fixture("v4.json", "tomorrowio")),
- ) as mock_update, patch(
- "homeassistant.components.tomorrowio.TomorrowioV4.max_requests_per_day",
- new_callable=PropertyMock,
- ) as mock_max_requests_per_day, patch(
- "homeassistant.components.tomorrowio.TomorrowioV4.num_api_requests",
- new_callable=PropertyMock,
- ) as mock_num_api_requests:
+ with (
+ patch(
+ "homeassistant.components.tomorrowio.TomorrowioV4.realtime_and_all_forecasts",
+ return_value=json.loads(load_fixture("v4.json", "tomorrowio")),
+ ) as mock_update,
+ patch(
+ "homeassistant.components.tomorrowio.TomorrowioV4.max_requests_per_day",
+ new_callable=PropertyMock,
+ ) as mock_max_requests_per_day,
+ patch(
+ "homeassistant.components.tomorrowio.TomorrowioV4.num_api_requests",
+ new_callable=PropertyMock,
+ ) as mock_num_api_requests,
+ ):
mock_max_requests_per_day.return_value = 100
mock_num_api_requests.return_value = 2
yield mock_update
diff --git a/tests/components/totalconnect/common.py b/tests/components/totalconnect/common.py
index 2661c18772d..0dde43a9710 100644
--- a/tests/components/totalconnect/common.py
+++ b/tests/components/totalconnect/common.py
@@ -389,10 +389,13 @@ async def setup_platform(hass, platform):
RESPONSE_DISARMED,
]
- with patch("homeassistant.components.totalconnect.PLATFORMS", [platform]), patch(
- TOTALCONNECT_REQUEST,
- side_effect=responses,
- ) as mock_request:
+ with (
+ patch("homeassistant.components.totalconnect.PLATFORMS", [platform]),
+ patch(
+ TOTALCONNECT_REQUEST,
+ side_effect=responses,
+ ) as mock_request,
+ ):
assert await async_setup_component(hass, DOMAIN, {})
assert mock_request.call_count == 5
await hass.async_block_till_done()
diff --git a/tests/components/totalconnect/test_config_flow.py b/tests/components/totalconnect/test_config_flow.py
index 39ba30a93a8..940542bf3ad 100644
--- a/tests/components/totalconnect/test_config_flow.py
+++ b/tests/components/totalconnect/test_config_flow.py
@@ -55,11 +55,14 @@ async def test_user_show_locations(hass: HomeAssistant) -> None:
RESPONSE_SUCCESS,
]
- with patch(
- TOTALCONNECT_REQUEST,
- side_effect=responses,
- ) as mock_request, patch(
- "homeassistant.components.totalconnect.async_setup_entry", return_value=True
+ with (
+ patch(
+ TOTALCONNECT_REQUEST,
+ side_effect=responses,
+ ) as mock_request,
+ patch(
+ "homeassistant.components.totalconnect.async_setup_entry", return_value=True
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -144,10 +147,13 @@ async def test_reauth(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
- with patch(
- "homeassistant.components.totalconnect.config_flow.TotalConnectClient"
- ) as client_mock, patch(
- "homeassistant.components.totalconnect.async_setup_entry", return_value=True
+ with (
+ patch(
+ "homeassistant.components.totalconnect.config_flow.TotalConnectClient"
+ ) as client_mock,
+ patch(
+ "homeassistant.components.totalconnect.async_setup_entry", return_value=True
+ ),
):
# first test with an invalid password
client_mock.side_effect = AuthenticationError()
@@ -181,14 +187,18 @@ async def test_no_locations(hass: HomeAssistant) -> None:
RESPONSE_DISARMED,
]
- with patch(
- TOTALCONNECT_REQUEST,
- side_effect=responses,
- ) as mock_request, patch(
- "homeassistant.components.totalconnect.async_setup_entry", return_value=True
- ), patch(
- "homeassistant.components.totalconnect.TotalConnectClient.get_number_locations",
- return_value=0,
+ with (
+ patch(
+ TOTALCONNECT_REQUEST,
+ side_effect=responses,
+ ) as mock_request,
+ patch(
+ "homeassistant.components.totalconnect.async_setup_entry", return_value=True
+ ),
+ patch(
+ "homeassistant.components.totalconnect.TotalConnectClient.get_number_locations",
+ return_value=0,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
diff --git a/tests/components/tplink/__init__.py b/tests/components/tplink/__init__.py
index 4c188fcddcc..d1454d12e68 100644
--- a/tests/components/tplink/__init__.py
+++ b/tests/components/tplink/__init__.py
@@ -311,9 +311,11 @@ async def initialize_config_entry_for_device(
)
config_entry.add_to_hass(hass)
- with _patch_discovery(device=dev), _patch_single_discovery(
- device=dev
- ), _patch_connect(device=dev):
+ with (
+ _patch_discovery(device=dev),
+ _patch_single_discovery(device=dev),
+ _patch_connect(device=dev),
+ ):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/tplink/test_config_flow.py b/tests/components/tplink/test_config_flow.py
index 0f5f2e0d542..4c1cc999f16 100644
--- a/tests/components/tplink/test_config_flow.py
+++ b/tests/components/tplink/test_config_flow.py
@@ -79,11 +79,13 @@ async def test_discovery(hass: HomeAssistant) -> None:
assert result2["step_id"] == "pick_device"
assert not result2["errors"]
- with _patch_discovery(), _patch_single_discovery(), _patch_connect(), patch(
- f"{MODULE}.async_setup", return_value=True
- ) as mock_setup, patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_single_discovery(),
+ _patch_connect(),
+ patch(f"{MODULE}.async_setup", return_value=True) as mock_setup,
+ patch(f"{MODULE}.async_setup_entry", return_value=True) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_DEVICE: MAC_ADDRESS},
@@ -325,8 +327,10 @@ async def test_discovery_with_existing_device_present(hass: HomeAssistant) -> No
)
config_entry.add_to_hass(hass)
- with _patch_discovery(), _patch_single_discovery(no_device=True), _patch_connect(
- no_device=True
+ with (
+ _patch_discovery(),
+ _patch_single_discovery(no_device=True),
+ _patch_connect(no_device=True),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -363,9 +367,12 @@ async def test_discovery_with_existing_device_present(hass: HomeAssistant) -> No
assert result2["step_id"] == "pick_device"
assert not result2["errors"]
- with _patch_discovery(), _patch_single_discovery(), _patch_connect(), patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_single_discovery(),
+ _patch_connect(),
+ patch(f"{MODULE}.async_setup_entry", return_value=True) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_DEVICE: MAC_ADDRESS}
)
@@ -417,9 +424,11 @@ async def test_manual(hass: HomeAssistant) -> None:
assert not result["errors"]
# Cannot connect (timeout)
- with _patch_discovery(no_device=True), _patch_single_discovery(
- no_device=True
- ), _patch_connect(no_device=True):
+ with (
+ _patch_discovery(no_device=True),
+ _patch_single_discovery(no_device=True),
+ _patch_connect(no_device=True),
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: IP_ADDRESS}
)
@@ -430,9 +439,13 @@ async def test_manual(hass: HomeAssistant) -> None:
assert result2["errors"] == {"base": "cannot_connect"}
# Success
- with _patch_discovery(), _patch_single_discovery(), _patch_connect(), patch(
- f"{MODULE}.async_setup", return_value=True
- ), patch(f"{MODULE}.async_setup_entry", return_value=True):
+ with (
+ _patch_discovery(),
+ _patch_single_discovery(),
+ _patch_connect(),
+ patch(f"{MODULE}.async_setup", return_value=True),
+ patch(f"{MODULE}.async_setup_entry", return_value=True),
+ ):
result4 = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: IP_ADDRESS}
)
@@ -446,9 +459,11 @@ async def test_manual(hass: HomeAssistant) -> None:
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with _patch_discovery(no_device=True), _patch_single_discovery(
- no_device=True
- ), _patch_connect(no_device=True):
+ with (
+ _patch_discovery(no_device=True),
+ _patch_single_discovery(no_device=True),
+ _patch_connect(no_device=True),
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: IP_ADDRESS}
)
@@ -467,11 +482,13 @@ async def test_manual_no_capabilities(hass: HomeAssistant) -> None:
assert result["step_id"] == "user"
assert not result["errors"]
- with _patch_discovery(
- no_device=True
- ), _patch_single_discovery(), _patch_connect(), patch(
- f"{MODULE}.async_setup", return_value=True
- ), patch(f"{MODULE}.async_setup_entry", return_value=True):
+ with (
+ _patch_discovery(no_device=True),
+ _patch_single_discovery(),
+ _patch_connect(),
+ patch(f"{MODULE}.async_setup", return_value=True),
+ patch(f"{MODULE}.async_setup_entry", return_value=True),
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: IP_ADDRESS}
)
@@ -631,9 +648,11 @@ async def test_discovered_by_discovery_and_dhcp(hass: HomeAssistant) -> None:
assert result3["type"] is FlowResultType.ABORT
assert result3["reason"] == "already_in_progress"
- with _patch_discovery(no_device=True), _patch_single_discovery(
- no_device=True
- ), _patch_connect(no_device=True):
+ with (
+ _patch_discovery(no_device=True),
+ _patch_single_discovery(no_device=True),
+ _patch_connect(no_device=True),
+ ):
result3 = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_DHCP},
@@ -680,11 +699,15 @@ async def test_discovered_by_dhcp_or_discovery(
assert result["type"] is FlowResultType.FORM
assert result["errors"] is None
- with _patch_discovery(), _patch_single_discovery(), _patch_connect(), patch(
- f"{MODULE}.async_setup", return_value=True
- ) as mock_async_setup, patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_async_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_single_discovery(),
+ _patch_connect(),
+ patch(f"{MODULE}.async_setup", return_value=True) as mock_async_setup,
+ patch(
+ f"{MODULE}.async_setup_entry", return_value=True
+ ) as mock_async_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(result["flow_id"], {})
await hass.async_block_till_done()
@@ -721,9 +744,11 @@ async def test_discovered_by_dhcp_or_discovery_failed_to_get_device(
) -> None:
"""Test we abort if we cannot get the unique id when discovered from dhcp."""
- with _patch_discovery(no_device=True), _patch_single_discovery(
- no_device=True
- ), _patch_connect(no_device=True):
+ with (
+ _patch_discovery(no_device=True),
+ _patch_single_discovery(no_device=True),
+ _patch_connect(no_device=True),
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": source}, data=data
)
diff --git a/tests/components/tplink/test_init.py b/tests/components/tplink/test_init.py
index 384949c3493..176f2aab7ae 100644
--- a/tests/components/tplink/test_init.py
+++ b/tests/components/tplink/test_init.py
@@ -46,8 +46,9 @@ async def test_configuring_tplink_causes_discovery(
hass: HomeAssistant, freezer: FrozenDateTimeFactory
) -> None:
"""Test that specifying empty config does discovery."""
- with patch("homeassistant.components.tplink.Discover.discover") as discover, patch(
- "homeassistant.components.tplink.Discover.discover_single"
+ with (
+ patch("homeassistant.components.tplink.Discover.discover") as discover,
+ patch("homeassistant.components.tplink.Discover.discover_single"),
):
discover.return_value = {MagicMock(): MagicMock()}
await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}})
@@ -88,9 +89,11 @@ async def test_config_entry_retry(hass: HomeAssistant) -> None:
domain=DOMAIN, data={CONF_HOST: IP_ADDRESS}, unique_id=MAC_ADDRESS
)
already_migrated_config_entry.add_to_hass(hass)
- with _patch_discovery(no_device=True), _patch_single_discovery(
- no_device=True
- ), _patch_connect(no_device=True):
+ with (
+ _patch_discovery(no_device=True),
+ _patch_single_discovery(no_device=True),
+ _patch_connect(no_device=True),
+ ):
await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}})
await hass.async_block_till_done()
assert already_migrated_config_entry.state == ConfigEntryState.SETUP_RETRY
@@ -120,9 +123,11 @@ async def test_dimmer_switch_unique_id_fix_original_entity_still_exists(
original_name="Rollout dimmer",
)
- with _patch_discovery(device=dimmer), _patch_single_discovery(
- device=dimmer
- ), _patch_connect(device=dimmer):
+ with (
+ _patch_discovery(device=dimmer),
+ _patch_single_discovery(device=dimmer),
+ _patch_connect(device=dimmer),
+ ):
await setup.async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
diff --git a/tests/components/tplink/test_light.py b/tests/components/tplink/test_light.py
index 6a34afd7260..767ff4a122c 100644
--- a/tests/components/tplink/test_light.py
+++ b/tests/components/tplink/test_light.py
@@ -419,9 +419,11 @@ async def test_smart_strip_effects(hass: HomeAssistant) -> None:
already_migrated_config_entry.add_to_hass(hass)
strip = _mocked_smart_light_strip()
- with _patch_discovery(device=strip), _patch_single_discovery(
- device=strip
- ), _patch_connect(device=strip):
+ with (
+ _patch_discovery(device=strip),
+ _patch_single_discovery(device=strip),
+ _patch_connect(device=strip),
+ ):
await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}})
await hass.async_block_till_done()
diff --git a/tests/components/tplink_omada/test_config_flow.py b/tests/components/tplink_omada/test_config_flow.py
index 4c1f05deb67..230f0d2a68e 100644
--- a/tests/components/tplink_omada/test_config_flow.py
+++ b/tests/components/tplink_omada/test_config_flow.py
@@ -46,15 +46,18 @@ async def test_form_single_site(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.tplink_omada.config_flow._validate_input",
- return_value=HubInfo(
- "omada_id", "OC200", [OmadaSite("Display Name", "SiteId")]
- ),
- ) as mocked_validate, patch(
- "homeassistant.components.tplink_omada.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.tplink_omada.config_flow._validate_input",
+ return_value=HubInfo(
+ "omada_id", "OC200", [OmadaSite("Display Name", "SiteId")]
+ ),
+ ) as mocked_validate,
+ patch(
+ "homeassistant.components.tplink_omada.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
MOCK_USER_DATA,
@@ -77,17 +80,20 @@ async def test_form_multiple_sites(hass: HomeAssistant) -> None:
assert result["step_id"] == "user"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.tplink_omada.config_flow._validate_input",
- return_value=HubInfo(
- "omada_id",
- "OC200",
- [OmadaSite("Site 1", "first"), OmadaSite("Site 2", "second")],
+ with (
+ patch(
+ "homeassistant.components.tplink_omada.config_flow._validate_input",
+ return_value=HubInfo(
+ "omada_id",
+ "OC200",
+ [OmadaSite("Site 1", "first"), OmadaSite("Site 2", "second")],
+ ),
),
- ), patch(
- "homeassistant.components.tplink_omada.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ patch(
+ "homeassistant.components.tplink_omada.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
MOCK_USER_DATA,
@@ -321,12 +327,15 @@ async def test_async_step_reauth_invalid_auth(hass: HomeAssistant) -> None:
async def test_validate_input(hass: HomeAssistant) -> None:
"""Test validate returns HubInfo."""
- with patch(
- "tplink_omada_client.omadaclient.OmadaClient", autospec=True
- ) as mock_client, patch(
- "homeassistant.components.tplink_omada.config_flow.create_omada_client",
- return_value=mock_client,
- ) as create_mock:
+ with (
+ patch(
+ "tplink_omada_client.omadaclient.OmadaClient", autospec=True
+ ) as mock_client,
+ patch(
+ "homeassistant.components.tplink_omada.config_flow.create_omada_client",
+ return_value=mock_client,
+ ) as create_mock,
+ ):
mock_client.login.return_value = "Id"
mock_client.get_controller_name.return_value = "Name"
mock_client.get_sites.return_value = [OmadaSite("x", "y")]
@@ -344,12 +353,16 @@ async def test_validate_input(hass: HomeAssistant) -> None:
async def test_create_omada_client_parses_args(hass: HomeAssistant) -> None:
"""Test config arguments are passed to Omada client."""
- with patch(
- "homeassistant.components.tplink_omada.config_flow.OmadaClient", autospec=True
- ) as mock_client, patch(
- "homeassistant.components.tplink_omada.config_flow.async_get_clientsession",
- return_value="ws",
- ) as mock_clientsession:
+ with (
+ patch(
+ "homeassistant.components.tplink_omada.config_flow.OmadaClient",
+ autospec=True,
+ ) as mock_client,
+ patch(
+ "homeassistant.components.tplink_omada.config_flow.async_get_clientsession",
+ return_value="ws",
+ ) as mock_clientsession,
+ ):
result = await create_omada_client(hass, MOCK_USER_DATA)
assert result is not None
@@ -362,12 +375,16 @@ async def test_create_omada_client_parses_args(hass: HomeAssistant) -> None:
async def test_create_omada_client_adds_missing_scheme(hass: HomeAssistant) -> None:
"""Test config arguments are passed to Omada client."""
- with patch(
- "homeassistant.components.tplink_omada.config_flow.OmadaClient", autospec=True
- ) as mock_client, patch(
- "homeassistant.components.tplink_omada.config_flow.async_get_clientsession",
- return_value="ws",
- ) as mock_clientsession:
+ with (
+ patch(
+ "homeassistant.components.tplink_omada.config_flow.OmadaClient",
+ autospec=True,
+ ) as mock_client,
+ patch(
+ "homeassistant.components.tplink_omada.config_flow.async_get_clientsession",
+ return_value="ws",
+ ) as mock_clientsession,
+ ):
result = await create_omada_client(
hass,
{
@@ -390,14 +407,19 @@ async def test_create_omada_client_with_ip_creates_clientsession(
) -> None:
"""Test config arguments are passed to Omada client."""
- with patch(
- "homeassistant.components.tplink_omada.config_flow.OmadaClient", autospec=True
- ) as mock_client, patch(
- "homeassistant.components.tplink_omada.config_flow.CookieJar", autospec=True
- ) as mock_jar, patch(
- "homeassistant.components.tplink_omada.config_flow.async_create_clientsession",
- return_value="ws",
- ) as mock_create_clientsession:
+ with (
+ patch(
+ "homeassistant.components.tplink_omada.config_flow.OmadaClient",
+ autospec=True,
+ ) as mock_client,
+ patch(
+ "homeassistant.components.tplink_omada.config_flow.CookieJar", autospec=True
+ ) as mock_jar,
+ patch(
+ "homeassistant.components.tplink_omada.config_flow.async_create_clientsession",
+ return_value="ws",
+ ) as mock_create_clientsession,
+ ):
result = await create_omada_client(
hass,
{
diff --git a/tests/components/traccar_server/conftest.py b/tests/components/traccar_server/conftest.py
index c0836455bd8..e5a65bfeabd 100644
--- a/tests/components/traccar_server/conftest.py
+++ b/tests/components/traccar_server/conftest.py
@@ -32,12 +32,15 @@ from tests.common import (
@pytest.fixture
def mock_traccar_api_client() -> Generator[AsyncMock, None, None]:
"""Mock a Traccar ApiClient client."""
- with patch(
- "homeassistant.components.traccar_server.ApiClient",
- autospec=True,
- ) as mock_client, patch(
- "homeassistant.components.traccar_server.config_flow.ApiClient",
- new=mock_client,
+ with (
+ patch(
+ "homeassistant.components.traccar_server.ApiClient",
+ autospec=True,
+ ) as mock_client,
+ patch(
+ "homeassistant.components.traccar_server.config_flow.ApiClient",
+ new=mock_client,
+ ),
):
client: ApiClient = mock_client.return_value
client.subscription_status = SubscriptionStatus.DISCONNECTED
diff --git a/tests/components/tractive/test_config_flow.py b/tests/components/tractive/test_config_flow.py
index 014526c9651..45a37730ff4 100644
--- a/tests/components/tractive/test_config_flow.py
+++ b/tests/components/tractive/test_config_flow.py
@@ -25,10 +25,13 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] is None
- with patch("aiotractive.api.API.user_id", return_value="user_id"), patch(
- "homeassistant.components.tractive.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("aiotractive.api.API.user_id", return_value="user_id"),
+ patch(
+ "homeassistant.components.tractive.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
USER_INPUT,
@@ -120,10 +123,13 @@ async def test_reauthentication(hass: HomeAssistant) -> None:
assert result["errors"] == {}
assert result["step_id"] == "reauth_confirm"
- with patch("aiotractive.api.API.user_id", return_value="USERID"), patch(
- "homeassistant.components.tractive.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("aiotractive.api.API.user_id", return_value="USERID"),
+ patch(
+ "homeassistant.components.tractive.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
USER_INPUT,
diff --git a/tests/components/trafikverket_camera/test_config_flow.py b/tests/components/trafikverket_camera/test_config_flow.py
index 356a0efcfaf..eb14636d6c9 100644
--- a/tests/components/trafikverket_camera/test_config_flow.py
+++ b/tests/components/trafikverket_camera/test_config_flow.py
@@ -26,13 +26,16 @@ async def test_form(hass: HomeAssistant, get_camera: CameraInfo) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.trafikverket_camera.config_flow.TrafikverketCamera.async_get_cameras",
- return_value=[get_camera],
- ), patch(
- "homeassistant.components.trafikverket_camera.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.trafikverket_camera.config_flow.TrafikverketCamera.async_get_cameras",
+ return_value=[get_camera],
+ ),
+ patch(
+ "homeassistant.components.trafikverket_camera.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -76,13 +79,16 @@ async def test_form_multiple_cameras(
)
await hass.async_block_till_done()
- with patch(
- "homeassistant.components.trafikverket_camera.config_flow.TrafikverketCamera.async_get_cameras",
- return_value=[get_camera2],
- ), patch(
- "homeassistant.components.trafikverket_camera.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.trafikverket_camera.config_flow.TrafikverketCamera.async_get_cameras",
+ return_value=[get_camera2],
+ ),
+ patch(
+ "homeassistant.components.trafikverket_camera.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -112,13 +118,16 @@ async def test_form_no_location_data(
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.trafikverket_camera.config_flow.TrafikverketCamera.async_get_cameras",
- return_value=[get_camera_no_location],
- ), patch(
- "homeassistant.components.trafikverket_camera.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.trafikverket_camera.config_flow.TrafikverketCamera.async_get_cameras",
+ return_value=[get_camera_no_location],
+ ),
+ patch(
+ "homeassistant.components.trafikverket_camera.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -210,11 +219,14 @@ async def test_reauth_flow(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.trafikverket_camera.config_flow.TrafikverketCamera.async_get_cameras",
- ), patch(
- "homeassistant.components.trafikverket_camera.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.trafikverket_camera.config_flow.TrafikverketCamera.async_get_cameras",
+ ),
+ patch(
+ "homeassistant.components.trafikverket_camera.async_setup_entry",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -290,11 +302,14 @@ async def test_reauth_flow_error(
assert result2["type"] == FlowResultType.FORM
assert result2["errors"] == {error_key: p_error}
- with patch(
- "homeassistant.components.trafikverket_camera.config_flow.TrafikverketCamera.async_get_cameras",
- ), patch(
- "homeassistant.components.trafikverket_camera.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.trafikverket_camera.config_flow.TrafikverketCamera.async_get_cameras",
+ ),
+ patch(
+ "homeassistant.components.trafikverket_camera.async_setup_entry",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/trafikverket_ferry/test_config_flow.py b/tests/components/trafikverket_ferry/test_config_flow.py
index 228357e666c..2a0a0ae6cd6 100644
--- a/tests/components/trafikverket_ferry/test_config_flow.py
+++ b/tests/components/trafikverket_ferry/test_config_flow.py
@@ -30,12 +30,15 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.trafikverket_ferry.config_flow.TrafikverketFerry.async_get_next_ferry_stop",
- ), patch(
- "homeassistant.components.trafikverket_ferry.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.trafikverket_ferry.config_flow.TrafikverketFerry.async_get_next_ferry_stop",
+ ),
+ patch(
+ "homeassistant.components.trafikverket_ferry.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -138,11 +141,14 @@ async def test_reauth_flow(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.trafikverket_ferry.config_flow.TrafikverketFerry.async_get_next_ferry_stop",
- ), patch(
- "homeassistant.components.trafikverket_ferry.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.trafikverket_ferry.config_flow.TrafikverketFerry.async_get_next_ferry_stop",
+ ),
+ patch(
+ "homeassistant.components.trafikverket_ferry.async_setup_entry",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -221,11 +227,14 @@ async def test_reauth_flow_error(
assert result2["type"] == FlowResultType.FORM
assert result2["errors"] == {"base": p_error}
- with patch(
- "homeassistant.components.trafikverket_ferry.config_flow.TrafikverketFerry.async_get_next_ferry_stop",
- ), patch(
- "homeassistant.components.trafikverket_ferry.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.trafikverket_ferry.config_flow.TrafikverketFerry.async_get_next_ferry_stop",
+ ),
+ patch(
+ "homeassistant.components.trafikverket_ferry.async_setup_entry",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/trafikverket_train/conftest.py b/tests/components/trafikverket_train/conftest.py
index e299b115014..880701e8bdc 100644
--- a/tests/components/trafikverket_train/conftest.py
+++ b/tests/components/trafikverket_train/conftest.py
@@ -43,14 +43,18 @@ async def load_integration_from_entry(
)
config_entry2.add_to_hass(hass)
- with patch(
- "homeassistant.components.trafikverket_train.coordinator.TrafikverketTrain.async_get_next_train_stops",
- return_value=get_trains,
- ), patch(
- "homeassistant.components.trafikverket_train.coordinator.TrafikverketTrain.async_get_train_stop",
- return_value=get_train_stop,
- ), patch(
- "homeassistant.components.trafikverket_train.TrafikverketTrain.async_get_train_station",
+ with (
+ patch(
+ "homeassistant.components.trafikverket_train.coordinator.TrafikverketTrain.async_get_next_train_stops",
+ return_value=get_trains,
+ ),
+ patch(
+ "homeassistant.components.trafikverket_train.coordinator.TrafikverketTrain.async_get_train_stop",
+ return_value=get_train_stop,
+ ),
+ patch(
+ "homeassistant.components.trafikverket_train.TrafikverketTrain.async_get_train_station",
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/trafikverket_train/test_config_flow.py b/tests/components/trafikverket_train/test_config_flow.py
index 85cbfae61f5..3a5afa7431c 100644
--- a/tests/components/trafikverket_train/test_config_flow.py
+++ b/tests/components/trafikverket_train/test_config_flow.py
@@ -37,14 +37,18 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_station",
- ), patch(
- "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_stop",
- ), patch(
- "homeassistant.components.trafikverket_train.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_station",
+ ),
+ patch(
+ "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_stop",
+ ),
+ patch(
+ "homeassistant.components.trafikverket_train.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -97,13 +101,17 @@ async def test_form_entry_already_exist(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_station",
- ), patch(
- "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_stop",
- ), patch(
- "homeassistant.components.trafikverket_train.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_station",
+ ),
+ patch(
+ "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_stop",
+ ),
+ patch(
+ "homeassistant.components.trafikverket_train.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -153,11 +161,14 @@ async def test_flow_fails(
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == config_entries.SOURCE_USER
- with patch(
- "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_station",
- side_effect=side_effect(),
- ), patch(
- "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_stop",
+ with (
+ patch(
+ "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_station",
+ side_effect=side_effect(),
+ ),
+ patch(
+ "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_stop",
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -195,13 +206,17 @@ async def test_flow_fails_departures(
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == config_entries.SOURCE_USER
- with patch(
- "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_station",
- ), patch(
- "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_next_train_stops",
- side_effect=side_effect(),
- ), patch(
- "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_stop",
+ with (
+ patch(
+ "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_station",
+ ),
+ patch(
+ "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_next_train_stops",
+ side_effect=side_effect(),
+ ),
+ patch(
+ "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_stop",
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -244,13 +259,17 @@ async def test_reauth_flow(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_station",
- ), patch(
- "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_stop",
- ), patch(
- "homeassistant.components.trafikverket_train.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_station",
+ ),
+ patch(
+ "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_stop",
+ ),
+ patch(
+ "homeassistant.components.trafikverket_train.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -319,11 +338,14 @@ async def test_reauth_flow_error(
data=entry.data,
)
- with patch(
- "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_station",
- side_effect=side_effect(),
- ), patch(
- "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_stop",
+ with (
+ patch(
+ "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_station",
+ side_effect=side_effect(),
+ ),
+ patch(
+ "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_stop",
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -335,13 +357,17 @@ async def test_reauth_flow_error(
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {"base": p_error}
- with patch(
- "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_station",
- ), patch(
- "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_stop",
- ), patch(
- "homeassistant.components.trafikverket_train.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_station",
+ ),
+ patch(
+ "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_stop",
+ ),
+ patch(
+ "homeassistant.components.trafikverket_train.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -402,11 +428,14 @@ async def test_reauth_flow_error_departures(
data=entry.data,
)
- with patch(
- "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_station",
- ), patch(
- "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_stop",
- side_effect=side_effect(),
+ with (
+ patch(
+ "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_station",
+ ),
+ patch(
+ "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_stop",
+ side_effect=side_effect(),
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -418,13 +447,17 @@ async def test_reauth_flow_error_departures(
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {"base": p_error}
- with patch(
- "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_station",
- ), patch(
- "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_stop",
- ), patch(
- "homeassistant.components.trafikverket_train.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_station",
+ ),
+ patch(
+ "homeassistant.components.trafikverket_train.config_flow.TrafikverketTrain.async_get_train_stop",
+ ),
+ patch(
+ "homeassistant.components.trafikverket_train.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -464,14 +497,18 @@ async def test_options_flow(
)
entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.trafikverket_train.TrafikverketTrain.async_get_train_station",
- ), patch(
- "homeassistant.components.trafikverket_train.coordinator.TrafikverketTrain.async_get_next_train_stops",
- return_value=get_trains,
- ), patch(
- "homeassistant.components.trafikverket_train.coordinator.TrafikverketTrain.async_get_train_stop",
- return_value=get_train_stop,
+ with (
+ patch(
+ "homeassistant.components.trafikverket_train.TrafikverketTrain.async_get_train_station",
+ ),
+ patch(
+ "homeassistant.components.trafikverket_train.coordinator.TrafikverketTrain.async_get_next_train_stops",
+ return_value=get_trains,
+ ),
+ patch(
+ "homeassistant.components.trafikverket_train.coordinator.TrafikverketTrain.async_get_train_stop",
+ return_value=get_train_stop,
+ ),
):
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/trafikverket_train/test_init.py b/tests/components/trafikverket_train/test_init.py
index 175a71f42df..f68c32b5b90 100644
--- a/tests/components/trafikverket_train/test_init.py
+++ b/tests/components/trafikverket_train/test_init.py
@@ -31,12 +31,15 @@ async def test_unload_entry(hass: HomeAssistant, get_trains: list[TrainStop]) ->
)
entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.trafikverket_train.TrafikverketTrain.async_get_train_station",
- ), patch(
- "homeassistant.components.trafikverket_train.coordinator.TrafikverketTrain.async_get_next_train_stops",
- return_value=get_trains,
- ) as mock_tv_train:
+ with (
+ patch(
+ "homeassistant.components.trafikverket_train.TrafikverketTrain.async_get_train_station",
+ ),
+ patch(
+ "homeassistant.components.trafikverket_train.coordinator.TrafikverketTrain.async_get_next_train_stops",
+ return_value=get_trains,
+ ) as mock_tv_train,
+ ):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
@@ -129,11 +132,14 @@ async def test_migrate_entity_unique_id(
original_name="Stockholm C to Uppsala C",
)
- with patch(
- "homeassistant.components.trafikverket_train.TrafikverketTrain.async_get_train_station",
- ), patch(
- "homeassistant.components.trafikverket_train.coordinator.TrafikverketTrain.async_get_next_train_stops",
- return_value=get_trains,
+ with (
+ patch(
+ "homeassistant.components.trafikverket_train.TrafikverketTrain.async_get_train_station",
+ ),
+ patch(
+ "homeassistant.components.trafikverket_train.coordinator.TrafikverketTrain.async_get_next_train_stops",
+ return_value=get_trains,
+ ),
):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/trafikverket_train/test_sensor.py b/tests/components/trafikverket_train/test_sensor.py
index 915dd6a6d57..099bcf5ae1e 100644
--- a/tests/components/trafikverket_train/test_sensor.py
+++ b/tests/components/trafikverket_train/test_sensor.py
@@ -38,12 +38,15 @@ async def test_sensor_next(
state = hass.states.get(entity)
assert state == snapshot
- with patch(
- "homeassistant.components.trafikverket_train.coordinator.TrafikverketTrain.async_get_next_train_stops",
- return_value=get_trains_next,
- ), patch(
- "homeassistant.components.trafikverket_train.coordinator.TrafikverketTrain.async_get_train_stop",
- return_value=get_train_stop,
+ with (
+ patch(
+ "homeassistant.components.trafikverket_train.coordinator.TrafikverketTrain.async_get_next_train_stops",
+ return_value=get_trains_next,
+ ),
+ patch(
+ "homeassistant.components.trafikverket_train.coordinator.TrafikverketTrain.async_get_train_stop",
+ return_value=get_train_stop,
+ ),
):
freezer.tick(timedelta(minutes=6))
async_fire_time_changed(hass)
@@ -89,12 +92,15 @@ async def test_sensor_update_auth_failure(
state = hass.states.get("sensor.stockholm_c_to_uppsala_c_departure_time_2")
assert state.state == "2023-05-01T11:00:00+00:00"
- with patch(
- "homeassistant.components.trafikverket_train.coordinator.TrafikverketTrain.async_get_next_train_stops",
- side_effect=InvalidAuthentication,
- ), patch(
- "homeassistant.components.trafikverket_train.coordinator.TrafikverketTrain.async_get_train_stop",
- side_effect=InvalidAuthentication,
+ with (
+ patch(
+ "homeassistant.components.trafikverket_train.coordinator.TrafikverketTrain.async_get_next_train_stops",
+ side_effect=InvalidAuthentication,
+ ),
+ patch(
+ "homeassistant.components.trafikverket_train.coordinator.TrafikverketTrain.async_get_train_stop",
+ side_effect=InvalidAuthentication,
+ ),
):
freezer.tick(timedelta(minutes=6))
async_fire_time_changed(hass)
@@ -119,12 +125,15 @@ async def test_sensor_update_failure(
state = hass.states.get("sensor.stockholm_c_to_uppsala_c_departure_time_2")
assert state.state == "2023-05-01T11:00:00+00:00"
- with patch(
- "homeassistant.components.trafikverket_train.coordinator.TrafikverketTrain.async_get_next_train_stops",
- side_effect=NoTrainAnnouncementFound,
- ), patch(
- "homeassistant.components.trafikverket_train.coordinator.TrafikverketTrain.async_get_train_stop",
- side_effect=NoTrainAnnouncementFound,
+ with (
+ patch(
+ "homeassistant.components.trafikverket_train.coordinator.TrafikverketTrain.async_get_next_train_stops",
+ side_effect=NoTrainAnnouncementFound,
+ ),
+ patch(
+ "homeassistant.components.trafikverket_train.coordinator.TrafikverketTrain.async_get_train_stop",
+ side_effect=NoTrainAnnouncementFound,
+ ),
):
freezer.tick(timedelta(minutes=6))
async_fire_time_changed(hass)
diff --git a/tests/components/trafikverket_weatherstation/test_config_flow.py b/tests/components/trafikverket_weatherstation/test_config_flow.py
index 8967f6c73aa..4a1c50cbaf1 100644
--- a/tests/components/trafikverket_weatherstation/test_config_flow.py
+++ b/tests/components/trafikverket_weatherstation/test_config_flow.py
@@ -31,12 +31,15 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.trafikverket_weatherstation.config_flow.TrafikverketWeather.async_get_weather",
- ), patch(
- "homeassistant.components.trafikverket_weatherstation.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.trafikverket_weatherstation.config_flow.TrafikverketWeather.async_get_weather",
+ ),
+ patch(
+ "homeassistant.components.trafikverket_weatherstation.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -125,11 +128,14 @@ async def test_reauth_flow(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.trafikverket_weatherstation.config_flow.TrafikverketWeather.async_get_weather",
- ), patch(
- "homeassistant.components.trafikverket_weatherstation.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.trafikverket_weatherstation.config_flow.TrafikverketWeather.async_get_weather",
+ ),
+ patch(
+ "homeassistant.components.trafikverket_weatherstation.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/tts/test_init.py b/tests/components/tts/test_init.py
index 5626f91b2a3..2c58c25a509 100644
--- a/tests/components/tts/test_init.py
+++ b/tests/components/tts/test_init.py
@@ -1399,10 +1399,10 @@ def test_resolve_engine(hass: HomeAssistant, setup: str, engine_id: str) -> None
assert tts.async_resolve_engine(hass, engine_id) == engine_id
assert tts.async_resolve_engine(hass, "non-existing") is None
- with patch.dict(
- hass.data[tts.DATA_TTS_MANAGER].providers, {}, clear=True
- ), patch.dict(hass.data[tts.DOMAIN]._platforms, {}, clear=True), patch.dict(
- hass.data[tts.DOMAIN]._entities, {}, clear=True
+ with (
+ patch.dict(hass.data[tts.DATA_TTS_MANAGER].providers, {}, clear=True),
+ patch.dict(hass.data[tts.DOMAIN]._platforms, {}, clear=True),
+ patch.dict(hass.data[tts.DOMAIN]._entities, {}, clear=True),
):
assert tts.async_resolve_engine(hass, None) is None
diff --git a/tests/components/twentemilieu/conftest.py b/tests/components/twentemilieu/conftest.py
index 5d64f3ad066..670bd648cac 100644
--- a/tests/components/twentemilieu/conftest.py
+++ b/tests/components/twentemilieu/conftest.py
@@ -49,11 +49,14 @@ def mock_setup_entry() -> Generator[None, None, None]:
@pytest.fixture
def mock_twentemilieu() -> Generator[MagicMock, None, None]:
"""Return a mocked Twente Milieu client."""
- with patch(
- "homeassistant.components.twentemilieu.TwenteMilieu", autospec=True
- ) as twentemilieu_mock, patch(
- "homeassistant.components.twentemilieu.config_flow.TwenteMilieu",
- new=twentemilieu_mock,
+ with (
+ patch(
+ "homeassistant.components.twentemilieu.TwenteMilieu", autospec=True
+ ) as twentemilieu_mock,
+ patch(
+ "homeassistant.components.twentemilieu.config_flow.TwenteMilieu",
+ new=twentemilieu_mock,
+ ),
):
twentemilieu = twentemilieu_mock.return_value
twentemilieu.unique_id.return_value = 12345
diff --git a/tests/components/twinkly/test_config_flow.py b/tests/components/twinkly/test_config_flow.py
index 2e8337bc860..f797f9b01b6 100644
--- a/tests/components/twinkly/test_config_flow.py
+++ b/tests/components/twinkly/test_config_flow.py
@@ -39,9 +39,12 @@ async def test_invalid_host(hass: HomeAssistant) -> None:
async def test_success_flow(hass: HomeAssistant) -> None:
"""Test that an entity is created when the flow completes."""
client = ClientMock()
- with patch(
- "homeassistant.components.twinkly.config_flow.Twinkly", return_value=client
- ), patch("homeassistant.components.twinkly.async_setup_entry", return_value=True):
+ with (
+ patch(
+ "homeassistant.components.twinkly.config_flow.Twinkly", return_value=client
+ ),
+ patch("homeassistant.components.twinkly.async_setup_entry", return_value=True),
+ ):
result = await hass.config_entries.flow.async_init(
TWINKLY_DOMAIN, context={"source": config_entries.SOURCE_USER}
)
@@ -89,9 +92,12 @@ async def test_dhcp_can_confirm(hass: HomeAssistant) -> None:
async def test_dhcp_success(hass: HomeAssistant) -> None:
"""Test DHCP discovery flow success."""
client = ClientMock()
- with patch(
- "homeassistant.components.twinkly.config_flow.Twinkly", return_value=client
- ), patch("homeassistant.components.twinkly.async_setup_entry", return_value=True):
+ with (
+ patch(
+ "homeassistant.components.twinkly.config_flow.Twinkly", return_value=client
+ ),
+ patch("homeassistant.components.twinkly.async_setup_entry", return_value=True),
+ ):
result = await hass.config_entries.flow.async_init(
TWINKLY_DOMAIN,
context={"source": config_entries.SOURCE_DHCP},
diff --git a/tests/components/twitch/conftest.py b/tests/components/twitch/conftest.py
index bf997314092..1cebc068831 100644
--- a/tests/components/twitch/conftest.py
+++ b/tests/components/twitch/conftest.py
@@ -101,11 +101,14 @@ def twitch_mock() -> TwitchMock:
@pytest.fixture(name="twitch")
def mock_twitch(twitch_mock: TwitchMock):
"""Mock Twitch."""
- with patch(
- "homeassistant.components.twitch.Twitch",
- return_value=twitch_mock,
- ), patch(
- "homeassistant.components.twitch.config_flow.Twitch",
- return_value=twitch_mock,
+ with (
+ patch(
+ "homeassistant.components.twitch.Twitch",
+ return_value=twitch_mock,
+ ),
+ patch(
+ "homeassistant.components.twitch.config_flow.Twitch",
+ return_value=twitch_mock,
+ ),
):
yield twitch_mock
diff --git a/tests/components/uk_transport/test_sensor.py b/tests/components/uk_transport/test_sensor.py
index a93ebedd5a8..a4a9aea18c8 100644
--- a/tests/components/uk_transport/test_sensor.py
+++ b/tests/components/uk_transport/test_sensor.py
@@ -69,8 +69,9 @@ async def test_bus(hass: HomeAssistant) -> None:
async def test_train(hass: HomeAssistant) -> None:
"""Test for operational uk_transport sensor with proper attributes."""
- with requests_mock.Mocker() as mock_req, patch(
- "homeassistant.util.dt.now", return_value=now().replace(hour=13)
+ with (
+ requests_mock.Mocker() as mock_req,
+ patch("homeassistant.util.dt.now", return_value=now().replace(hour=13)),
):
uri = re.compile(UkTransportSensor.TRANSPORT_API_URL_BASE + "*")
mock_req.get(uri, text=load_fixture("uk_transport/train.json"))
diff --git a/tests/components/unifi/test_hub.py b/tests/components/unifi/test_hub.py
index 48aca0b407e..1fddb623930 100644
--- a/tests/components/unifi/test_hub.py
+++ b/tests/components/unifi/test_hub.py
@@ -306,10 +306,13 @@ async def test_hub_not_accessible(hass: HomeAssistant) -> None:
async def test_hub_trigger_reauth_flow(hass: HomeAssistant) -> None:
"""Failed authentication trigger a reauthentication flow."""
- with patch(
- "homeassistant.components.unifi.get_unifi_api",
- side_effect=AuthenticationRequired,
- ), patch.object(hass.config_entries.flow, "async_init") as mock_flow_init:
+ with (
+ patch(
+ "homeassistant.components.unifi.get_unifi_api",
+ side_effect=AuthenticationRequired,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_flow_init,
+ ):
await setup_unifi_integration(hass)
mock_flow_init.assert_called_once()
assert hass.data[UNIFI_DOMAIN] == {}
@@ -440,9 +443,12 @@ async def test_reconnect_mechanism_exceptions(
"""Verify async_reconnect calls expected methods."""
await setup_unifi_integration(hass, aioclient_mock)
- with patch("aiounifi.Controller.login", side_effect=exception), patch(
- "homeassistant.components.unifi.hub.hub.UnifiWebsocket.reconnect"
- ) as mock_reconnect:
+ with (
+ patch("aiounifi.Controller.login", side_effect=exception),
+ patch(
+ "homeassistant.components.unifi.hub.hub.UnifiWebsocket.reconnect"
+ ) as mock_reconnect,
+ ):
await websocket_mock.disconnect()
await websocket_mock.reconnect()
@@ -481,7 +487,8 @@ async def test_get_unifi_api_fails_to_connect(
hass: HomeAssistant, side_effect, raised_exception
) -> None:
"""Check that get_unifi_api can handle UniFi Network being unavailable."""
- with patch("aiounifi.Controller.login", side_effect=side_effect), pytest.raises(
- raised_exception
+ with (
+ patch("aiounifi.Controller.login", side_effect=side_effect),
+ pytest.raises(raised_exception),
):
await get_unifi_api(hass, ENTRY_CONFIG)
diff --git a/tests/components/unifi/test_init.py b/tests/components/unifi/test_init.py
index dd0442edb5c..9053b47cbaf 100644
--- a/tests/components/unifi/test_init.py
+++ b/tests/components/unifi/test_init.py
@@ -42,10 +42,13 @@ async def test_setup_entry_fails_config_entry_not_ready(hass: HomeAssistant) ->
async def test_setup_entry_fails_trigger_reauth_flow(hass: HomeAssistant) -> None:
"""Failed authentication trigger a reauthentication flow."""
- with patch(
- "homeassistant.components.unifi.get_unifi_api",
- side_effect=AuthenticationRequired,
- ), patch.object(hass.config_entries.flow, "async_init") as mock_flow_init:
+ with (
+ patch(
+ "homeassistant.components.unifi.get_unifi_api",
+ side_effect=AuthenticationRequired,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_flow_init,
+ ):
await setup_unifi_integration(hass)
mock_flow_init.assert_called_once()
diff --git a/tests/components/unifiprotect/conftest.py b/tests/components/unifiprotect/conftest.py
index 37e7dceecf5..5b3f9653d75 100644
--- a/tests/components/unifiprotect/conftest.py
+++ b/tests/components/unifiprotect/conftest.py
@@ -132,9 +132,12 @@ def mock_entry(
):
"""Mock ProtectApiClient for testing."""
- with _patch_discovery(no_device=True), patch(
- "homeassistant.components.unifiprotect.utils.ProtectApiClient"
- ) as mock_api:
+ with (
+ _patch_discovery(no_device=True),
+ patch(
+ "homeassistant.components.unifiprotect.utils.ProtectApiClient"
+ ) as mock_api,
+ ):
ufp_config_entry.add_to_hass(hass)
mock_api.return_value = ufp_client
diff --git a/tests/components/unifiprotect/test_config_flow.py b/tests/components/unifiprotect/test_config_flow.py
index be315b72d17..7c9f584af15 100644
--- a/tests/components/unifiprotect/test_config_flow.py
+++ b/tests/components/unifiprotect/test_config_flow.py
@@ -67,16 +67,20 @@ async def test_form(hass: HomeAssistant, bootstrap: Bootstrap, nvr: NVR) -> None
assert not result["errors"]
bootstrap.nvr = nvr
- with patch(
- "homeassistant.components.unifiprotect.config_flow.ProtectApiClient.get_bootstrap",
- return_value=bootstrap,
- ), patch(
- "homeassistant.components.unifiprotect.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.unifiprotect.async_setup",
- return_value=True,
- ) as mock_setup:
+ with (
+ patch(
+ "homeassistant.components.unifiprotect.config_flow.ProtectApiClient.get_bootstrap",
+ return_value=bootstrap,
+ ),
+ patch(
+ "homeassistant.components.unifiprotect.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.unifiprotect.async_setup",
+ return_value=True,
+ ) as mock_setup,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -251,13 +255,16 @@ async def test_form_reauth_auth(
assert result2["step_id"] == "reauth_confirm"
bootstrap.nvr = nvr
- with patch(
- "homeassistant.components.unifiprotect.config_flow.ProtectApiClient.get_bootstrap",
- return_value=bootstrap,
- ), patch(
- "homeassistant.components.unifiprotect.async_setup",
- return_value=True,
- ) as mock_setup:
+ with (
+ patch(
+ "homeassistant.components.unifiprotect.config_flow.ProtectApiClient.get_bootstrap",
+ return_value=bootstrap,
+ ),
+ patch(
+ "homeassistant.components.unifiprotect.async_setup",
+ return_value=True,
+ ) as mock_setup,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
@@ -290,9 +297,12 @@ async def test_form_options(hass: HomeAssistant, ufp_client: ProtectApiClient) -
)
mock_config.add_to_hass(hass)
- with _patch_discovery(), patch(
- "homeassistant.components.unifiprotect.utils.ProtectApiClient"
- ) as mock_api:
+ with (
+ _patch_discovery(),
+ patch(
+ "homeassistant.components.unifiprotect.utils.ProtectApiClient"
+ ) as mock_api,
+ ):
mock_api.return_value = ufp_client
await hass.config_entries.async_setup(mock_config.entry_id)
@@ -372,16 +382,20 @@ async def test_discovered_by_unifi_discovery_direct_connect(
assert not result["errors"]
bootstrap.nvr = nvr
- with patch(
- "homeassistant.components.unifiprotect.config_flow.ProtectApiClient.get_bootstrap",
- return_value=bootstrap,
- ), patch(
- "homeassistant.components.unifiprotect.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.unifiprotect.async_setup",
- return_value=True,
- ) as mock_setup:
+ with (
+ patch(
+ "homeassistant.components.unifiprotect.config_flow.ProtectApiClient.get_bootstrap",
+ return_value=bootstrap,
+ ),
+ patch(
+ "homeassistant.components.unifiprotect.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.unifiprotect.async_setup",
+ return_value=True,
+ ) as mock_setup,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -456,9 +470,12 @@ async def test_discovered_by_unifi_discovery_direct_connect_updated_but_not_usin
)
mock_config.add_to_hass(hass)
- with _patch_discovery(), patch(
- "homeassistant.components.unifiprotect.config_flow.async_console_is_alive",
- return_value=False,
+ with (
+ _patch_discovery(),
+ patch(
+ "homeassistant.components.unifiprotect.config_flow.async_console_is_alive",
+ return_value=False,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -491,9 +508,12 @@ async def test_discovered_by_unifi_discovery_does_not_update_ip_when_console_is_
)
mock_config.add_to_hass(hass)
- with _patch_discovery(), patch(
- "homeassistant.components.unifiprotect.config_flow.async_console_is_alive",
- return_value=True,
+ with (
+ _patch_discovery(),
+ patch(
+ "homeassistant.components.unifiprotect.config_flow.async_console_is_alive",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -562,16 +582,20 @@ async def test_discovered_by_unifi_discovery(
assert not result["errors"]
bootstrap.nvr = nvr
- with patch(
- "homeassistant.components.unifiprotect.config_flow.ProtectApiClient.get_bootstrap",
- side_effect=[NotAuthorized, bootstrap],
- ), patch(
- "homeassistant.components.unifiprotect.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.unifiprotect.async_setup",
- return_value=True,
- ) as mock_setup:
+ with (
+ patch(
+ "homeassistant.components.unifiprotect.config_flow.ProtectApiClient.get_bootstrap",
+ side_effect=[NotAuthorized, bootstrap],
+ ),
+ patch(
+ "homeassistant.components.unifiprotect.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.unifiprotect.async_setup",
+ return_value=True,
+ ) as mock_setup,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -619,16 +643,20 @@ async def test_discovered_by_unifi_discovery_partial(
assert not result["errors"]
bootstrap.nvr = nvr
- with patch(
- "homeassistant.components.unifiprotect.config_flow.ProtectApiClient.get_bootstrap",
- return_value=bootstrap,
- ), patch(
- "homeassistant.components.unifiprotect.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.unifiprotect.async_setup",
- return_value=True,
- ) as mock_setup:
+ with (
+ patch(
+ "homeassistant.components.unifiprotect.config_flow.ProtectApiClient.get_bootstrap",
+ return_value=bootstrap,
+ ),
+ patch(
+ "homeassistant.components.unifiprotect.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.unifiprotect.async_setup",
+ return_value=True,
+ ) as mock_setup,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -734,10 +762,13 @@ async def test_discovered_by_unifi_discovery_direct_connect_on_different_interfa
other_ip_dict["source_ip"] = "127.0.0.1"
other_ip_dict["direct_connect_domain"] = "nomatchsameip.ui.direct"
- with _patch_discovery(), patch.object(
- hass.loop,
- "getaddrinfo",
- return_value=[(socket.AF_INET, None, None, None, ("127.0.0.1", 443))],
+ with (
+ _patch_discovery(),
+ patch.object(
+ hass.loop,
+ "getaddrinfo",
+ return_value=[(socket.AF_INET, None, None, None, ("127.0.0.1", 443))],
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -772,8 +803,9 @@ async def test_discovered_by_unifi_discovery_direct_connect_on_different_interfa
other_ip_dict["source_ip"] = "127.0.0.2"
other_ip_dict["direct_connect_domain"] = "nomatchsameip.ui.direct"
- with _patch_discovery(), patch.object(
- hass.loop, "getaddrinfo", side_effect=OSError
+ with (
+ _patch_discovery(),
+ patch.object(hass.loop, "getaddrinfo", side_effect=OSError),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -793,16 +825,20 @@ async def test_discovered_by_unifi_discovery_direct_connect_on_different_interfa
assert not result["errors"]
bootstrap.nvr = nvr
- with patch(
- "homeassistant.components.unifiprotect.config_flow.ProtectApiClient.get_bootstrap",
- return_value=bootstrap,
- ), patch(
- "homeassistant.components.unifiprotect.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.unifiprotect.async_setup",
- return_value=True,
- ) as mock_setup:
+ with (
+ patch(
+ "homeassistant.components.unifiprotect.config_flow.ProtectApiClient.get_bootstrap",
+ return_value=bootstrap,
+ ),
+ patch(
+ "homeassistant.components.unifiprotect.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.unifiprotect.async_setup",
+ return_value=True,
+ ) as mock_setup,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
diff --git a/tests/components/unifiprotect/test_init.py b/tests/components/unifiprotect/test_init.py
index 681f22b327e..f123abb9861 100644
--- a/tests/components/unifiprotect/test_init.py
+++ b/tests/components/unifiprotect/test_init.py
@@ -239,9 +239,12 @@ async def test_setup_starts_discovery(
hass: HomeAssistant, ufp_config_entry: ConfigEntry, ufp_client: ProtectApiClient
) -> None:
"""Test setting up will start discovery."""
- with _patch_discovery(), patch(
- "homeassistant.components.unifiprotect.utils.ProtectApiClient"
- ) as mock_api:
+ with (
+ _patch_discovery(),
+ patch(
+ "homeassistant.components.unifiprotect.utils.ProtectApiClient"
+ ) as mock_api,
+ ):
ufp_config_entry.add_to_hass(hass)
mock_api.return_value = ufp_client
ufp = MockUFPFixture(ufp_config_entry, ufp_client)
diff --git a/tests/components/unifiprotect/test_sensor.py b/tests/components/unifiprotect/test_sensor.py
index 52c70719acd..1e5eca47b9b 100644
--- a/tests/components/unifiprotect/test_sensor.py
+++ b/tests/components/unifiprotect/test_sensor.py
@@ -538,9 +538,9 @@ async def test_camera_update_licenseplate(
new_camera = camera.copy()
new_camera.is_smart_detected = True
- new_camera.last_smart_detect_event_ids[
- SmartDetectObjectType.LICENSE_PLATE
- ] = event.id
+ new_camera.last_smart_detect_event_ids[SmartDetectObjectType.LICENSE_PLATE] = (
+ event.id
+ )
mock_msg = Mock()
mock_msg.changed_data = {}
diff --git a/tests/components/universal/test_media_player.py b/tests/components/universal/test_media_player.py
index 9fa55ae6725..9df9247900f 100644
--- a/tests/components/universal/test_media_player.py
+++ b/tests/components/universal/test_media_player.py
@@ -1123,12 +1123,15 @@ async def test_browse_media(hass: HomeAssistant) -> None:
ump.entity_id = media_player.ENTITY_ID_FORMAT.format(config["name"])
await ump.async_update()
- with patch(
- "homeassistant.components.demo.media_player.MediaPlayerEntity.supported_features",
- MediaPlayerEntityFeature.BROWSE_MEDIA,
- ), patch(
- "homeassistant.components.demo.media_player.MediaPlayerEntity.async_browse_media",
- return_value=MOCK_BROWSE_MEDIA,
+ with (
+ patch(
+ "homeassistant.components.demo.media_player.MediaPlayerEntity.supported_features",
+ MediaPlayerEntityFeature.BROWSE_MEDIA,
+ ),
+ patch(
+ "homeassistant.components.demo.media_player.MediaPlayerEntity.async_browse_media",
+ return_value=MOCK_BROWSE_MEDIA,
+ ),
):
result = await ump.async_browse_media()
assert result == MOCK_BROWSE_MEDIA
@@ -1155,12 +1158,15 @@ async def test_browse_media_override(hass: HomeAssistant) -> None:
ump.entity_id = media_player.ENTITY_ID_FORMAT.format(config["name"])
await ump.async_update()
- with patch(
- "homeassistant.components.demo.media_player.MediaPlayerEntity.supported_features",
- MediaPlayerEntityFeature.BROWSE_MEDIA,
- ), patch(
- "homeassistant.components.demo.media_player.MediaPlayerEntity.async_browse_media",
- return_value=MOCK_BROWSE_MEDIA,
+ with (
+ patch(
+ "homeassistant.components.demo.media_player.MediaPlayerEntity.supported_features",
+ MediaPlayerEntityFeature.BROWSE_MEDIA,
+ ),
+ patch(
+ "homeassistant.components.demo.media_player.MediaPlayerEntity.async_browse_media",
+ return_value=MOCK_BROWSE_MEDIA,
+ ),
):
result = await ump.async_browse_media()
assert result == MOCK_BROWSE_MEDIA
diff --git a/tests/components/upb/test_config_flow.py b/tests/components/upb/test_config_flow.py
index 7641e64fece..b3c3dfce15c 100644
--- a/tests/components/upb/test_config_flow.py
+++ b/tests/components/upb/test_config_flow.py
@@ -26,8 +26,9 @@ def mocked_upb(sync_complete=True, config_ok=True):
async def valid_tcp_flow(hass, sync_complete=True, config_ok=True):
"""Get result dict that are standard for most tests."""
- with mocked_upb(sync_complete, config_ok), patch(
- "homeassistant.components.upb.async_setup_entry", return_value=True
+ with (
+ mocked_upb(sync_complete, config_ok),
+ patch("homeassistant.components.upb.async_setup_entry", return_value=True),
):
flow = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@@ -42,9 +43,12 @@ async def valid_tcp_flow(hass, sync_complete=True, config_ok=True):
async def test_full_upb_flow_with_serial_port(hass: HomeAssistant) -> None:
"""Test a full UPB config flow with serial port."""
- with mocked_upb(), patch(
- "homeassistant.components.upb.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ mocked_upb(),
+ patch(
+ "homeassistant.components.upb.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
flow = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
@@ -111,9 +115,12 @@ async def test_form_user_with_already_configured(hass: HomeAssistant) -> None:
async def test_form_import(hass: HomeAssistant) -> None:
"""Test we get the form with import source."""
- with mocked_upb(), patch(
- "homeassistant.components.upb.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ mocked_upb(),
+ patch(
+ "homeassistant.components.upb.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
diff --git a/tests/components/update/test_init.py b/tests/components/update/test_init.py
index 106273a3b0e..252bac578a1 100644
--- a/tests/components/update/test_init.py
+++ b/tests/components/update/test_init.py
@@ -636,10 +636,13 @@ async def test_entity_without_progress_support_raising(
hass, "update.update_available", callback(lambda event: events.append(event))
)
- with patch(
- "homeassistant.components.update.UpdateEntity.async_install",
- side_effect=RuntimeError,
- ), pytest.raises(RuntimeError):
+ with (
+ patch(
+ "homeassistant.components.update.UpdateEntity.async_install",
+ side_effect=RuntimeError,
+ ),
+ pytest.raises(RuntimeError),
+ ):
await hass.services.async_call(
DOMAIN,
SERVICE_INSTALL,
diff --git a/tests/components/upnp/conftest.py b/tests/components/upnp/conftest.py
index c1d1903878e..0959e8e31da 100644
--- a/tests/components/upnp/conftest.py
+++ b/tests/components/upnp/conftest.py
@@ -139,14 +139,16 @@ def mock_setup_entry():
@pytest.fixture(autouse=True)
async def silent_ssdp_scanner(hass):
"""Start SSDP component and get Scanner, prevent actual SSDP traffic."""
- with patch(
- "homeassistant.components.ssdp.Scanner._async_start_ssdp_listeners"
- ), patch("homeassistant.components.ssdp.Scanner._async_stop_ssdp_listeners"), patch(
- "homeassistant.components.ssdp.Scanner.async_scan"
- ), patch(
- "homeassistant.components.ssdp.Server._async_start_upnp_servers",
- ), patch(
- "homeassistant.components.ssdp.Server._async_stop_upnp_servers",
+ with (
+ patch("homeassistant.components.ssdp.Scanner._async_start_ssdp_listeners"),
+ patch("homeassistant.components.ssdp.Scanner._async_stop_ssdp_listeners"),
+ patch("homeassistant.components.ssdp.Scanner.async_scan"),
+ patch(
+ "homeassistant.components.ssdp.Server._async_start_upnp_servers",
+ ),
+ patch(
+ "homeassistant.components.ssdp.Server._async_stop_upnp_servers",
+ ),
):
yield
@@ -161,13 +163,16 @@ async def ssdp_instant_discovery():
await callback(TEST_DISCOVERY, ssdp.SsdpChange.ALIVE)
return MagicMock()
- with patch(
- "homeassistant.components.ssdp.async_register_callback",
- side_effect=register_callback,
- ) as mock_register, patch(
- "homeassistant.components.ssdp.async_get_discovery_info_by_st",
- return_value=[TEST_DISCOVERY],
- ) as mock_get_info:
+ with (
+ patch(
+ "homeassistant.components.ssdp.async_register_callback",
+ side_effect=register_callback,
+ ) as mock_register,
+ patch(
+ "homeassistant.components.ssdp.async_get_discovery_info_by_st",
+ return_value=[TEST_DISCOVERY],
+ ) as mock_get_info,
+ ):
yield (mock_register, mock_get_info)
@@ -185,13 +190,16 @@ async def ssdp_instant_discovery_multi_location():
await callback(test_discovery, ssdp.SsdpChange.ALIVE)
return MagicMock()
- with patch(
- "homeassistant.components.ssdp.async_register_callback",
- side_effect=register_callback,
- ) as mock_register, patch(
- "homeassistant.components.ssdp.async_get_discovery_info_by_st",
- return_value=[test_discovery],
- ) as mock_get_info:
+ with (
+ patch(
+ "homeassistant.components.ssdp.async_register_callback",
+ side_effect=register_callback,
+ ) as mock_register,
+ patch(
+ "homeassistant.components.ssdp.async_get_discovery_info_by_st",
+ return_value=[test_discovery],
+ ) as mock_get_info,
+ ):
yield (mock_register, mock_get_info)
@@ -204,13 +212,16 @@ async def ssdp_no_discovery():
"""Don't do callback."""
return MagicMock()
- with patch(
- "homeassistant.components.ssdp.async_register_callback",
- side_effect=register_callback,
- ) as mock_register, patch(
- "homeassistant.components.ssdp.async_get_discovery_info_by_st",
- return_value=[],
- ) as mock_get_info:
+ with (
+ patch(
+ "homeassistant.components.ssdp.async_register_callback",
+ side_effect=register_callback,
+ ) as mock_register,
+ patch(
+ "homeassistant.components.ssdp.async_get_discovery_info_by_st",
+ return_value=[],
+ ) as mock_get_info,
+ ):
yield (mock_register, mock_get_info)
diff --git a/tests/components/upnp/test_init.py b/tests/components/upnp/test_init.py
index 5c59ddd9da7..eab279b479e 100644
--- a/tests/components/upnp/test_init.py
+++ b/tests/components/upnp/test_init.py
@@ -132,12 +132,15 @@ async def test_async_setup_udn_mismatch(
await callback(test_discovery, ssdp.SsdpChange.ALIVE)
return MagicMock()
- with patch(
- "homeassistant.components.ssdp.async_register_callback",
- side_effect=register_callback,
- ), patch(
- "homeassistant.components.ssdp.async_get_discovery_info_by_st",
- return_value=[test_discovery],
+ with (
+ patch(
+ "homeassistant.components.ssdp.async_register_callback",
+ side_effect=register_callback,
+ ),
+ patch(
+ "homeassistant.components.ssdp.async_get_discovery_info_by_st",
+ return_value=[test_discovery],
+ ),
):
# Load config_entry.
entry.add_to_hass(hass)
diff --git a/tests/components/uptimerobot/test_config_flow.py b/tests/components/uptimerobot/test_config_flow.py
index 721338ee6e7..58faa524d6f 100644
--- a/tests/components/uptimerobot/test_config_flow.py
+++ b/tests/components/uptimerobot/test_config_flow.py
@@ -33,13 +33,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with patch(
- "pyuptimerobot.UptimeRobot.async_get_account_details",
- return_value=mock_uptimerobot_api_response(key=MockApiResponseKey.ACCOUNT),
- ), patch(
- "homeassistant.components.uptimerobot.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "pyuptimerobot.UptimeRobot.async_get_account_details",
+ return_value=mock_uptimerobot_api_response(key=MockApiResponseKey.ACCOUNT),
+ ),
+ patch(
+ "homeassistant.components.uptimerobot.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_API_KEY: MOCK_UPTIMEROBOT_API_KEY},
@@ -137,13 +140,16 @@ async def test_user_unique_id_already_exists(
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with patch(
- "pyuptimerobot.UptimeRobot.async_get_account_details",
- return_value=mock_uptimerobot_api_response(key=MockApiResponseKey.ACCOUNT),
- ), patch(
- "homeassistant.components.uptimerobot.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "pyuptimerobot.UptimeRobot.async_get_account_details",
+ return_value=mock_uptimerobot_api_response(key=MockApiResponseKey.ACCOUNT),
+ ),
+ patch(
+ "homeassistant.components.uptimerobot.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_API_KEY: "12345"},
@@ -176,12 +182,15 @@ async def test_reauthentication(
assert result["errors"] is None
assert result["step_id"] == "reauth_confirm"
- with patch(
- "pyuptimerobot.UptimeRobot.async_get_account_details",
- return_value=mock_uptimerobot_api_response(key=MockApiResponseKey.ACCOUNT),
- ), patch(
- "homeassistant.components.uptimerobot.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "pyuptimerobot.UptimeRobot.async_get_account_details",
+ return_value=mock_uptimerobot_api_response(key=MockApiResponseKey.ACCOUNT),
+ ),
+ patch(
+ "homeassistant.components.uptimerobot.async_setup_entry",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -214,12 +223,15 @@ async def test_reauthentication_failure(
assert result["errors"] is None
assert result["step_id"] == "reauth_confirm"
- with patch(
- "pyuptimerobot.UptimeRobot.async_get_account_details",
- return_value=mock_uptimerobot_api_response(key=MockApiResponseKey.ERROR),
- ), patch(
- "homeassistant.components.uptimerobot.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "pyuptimerobot.UptimeRobot.async_get_account_details",
+ return_value=mock_uptimerobot_api_response(key=MockApiResponseKey.ERROR),
+ ),
+ patch(
+ "homeassistant.components.uptimerobot.async_setup_entry",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -255,12 +267,15 @@ async def test_reauthentication_failure_no_existing_entry(
assert result["errors"] is None
assert result["step_id"] == "reauth_confirm"
- with patch(
- "pyuptimerobot.UptimeRobot.async_get_account_details",
- return_value=mock_uptimerobot_api_response(key=MockApiResponseKey.ACCOUNT),
- ), patch(
- "homeassistant.components.uptimerobot.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "pyuptimerobot.UptimeRobot.async_get_account_details",
+ return_value=mock_uptimerobot_api_response(key=MockApiResponseKey.ACCOUNT),
+ ),
+ patch(
+ "homeassistant.components.uptimerobot.async_setup_entry",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -293,15 +308,18 @@ async def test_reauthentication_failure_account_not_matching(
assert result["errors"] is None
assert result["step_id"] == "reauth_confirm"
- with patch(
- "pyuptimerobot.UptimeRobot.async_get_account_details",
- return_value=mock_uptimerobot_api_response(
- key=MockApiResponseKey.ACCOUNT,
- data={**MOCK_UPTIMEROBOT_ACCOUNT, "user_id": 1234567891},
+ with (
+ patch(
+ "pyuptimerobot.UptimeRobot.async_get_account_details",
+ return_value=mock_uptimerobot_api_response(
+ key=MockApiResponseKey.ACCOUNT,
+ data={**MOCK_UPTIMEROBOT_ACCOUNT, "user_id": 1234567891},
+ ),
+ ),
+ patch(
+ "homeassistant.components.uptimerobot.async_setup_entry",
+ return_value=True,
),
- ), patch(
- "homeassistant.components.uptimerobot.async_setup_entry",
- return_value=True,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/uptimerobot/test_switch.py b/tests/components/uptimerobot/test_switch.py
index 82b8ca55831..8c2cffe504a 100644
--- a/tests/components/uptimerobot/test_switch.py
+++ b/tests/components/uptimerobot/test_switch.py
@@ -44,14 +44,17 @@ async def test_switch_off(hass: HomeAssistant) -> None:
mock_entry = MockConfigEntry(**MOCK_UPTIMEROBOT_CONFIG_ENTRY_DATA)
mock_entry.add_to_hass(hass)
- with patch(
- "pyuptimerobot.UptimeRobot.async_get_monitors",
- return_value=mock_uptimerobot_api_response(
- data=[MOCK_UPTIMEROBOT_MONITOR_PAUSED]
+ with (
+ patch(
+ "pyuptimerobot.UptimeRobot.async_get_monitors",
+ return_value=mock_uptimerobot_api_response(
+ data=[MOCK_UPTIMEROBOT_MONITOR_PAUSED]
+ ),
+ ),
+ patch(
+ "pyuptimerobot.UptimeRobot.async_edit_monitor",
+ return_value=mock_uptimerobot_api_response(),
),
- ), patch(
- "pyuptimerobot.UptimeRobot.async_edit_monitor",
- return_value=mock_uptimerobot_api_response(),
):
assert await hass.config_entries.async_setup(mock_entry.entry_id)
await hass.async_block_till_done()
@@ -73,12 +76,15 @@ async def test_switch_on(hass: HomeAssistant) -> None:
mock_entry = MockConfigEntry(**MOCK_UPTIMEROBOT_CONFIG_ENTRY_DATA)
mock_entry.add_to_hass(hass)
- with patch(
- "pyuptimerobot.UptimeRobot.async_get_monitors",
- return_value=mock_uptimerobot_api_response(data=[MOCK_UPTIMEROBOT_MONITOR]),
- ), patch(
- "pyuptimerobot.UptimeRobot.async_edit_monitor",
- return_value=mock_uptimerobot_api_response(),
+ with (
+ patch(
+ "pyuptimerobot.UptimeRobot.async_get_monitors",
+ return_value=mock_uptimerobot_api_response(data=[MOCK_UPTIMEROBOT_MONITOR]),
+ ),
+ patch(
+ "pyuptimerobot.UptimeRobot.async_edit_monitor",
+ return_value=mock_uptimerobot_api_response(),
+ ),
):
assert await hass.config_entries.async_setup(mock_entry.entry_id)
await hass.async_block_till_done()
@@ -103,12 +109,15 @@ async def test_authentication_error(
entity = hass.states.get(UPTIMEROBOT_SWITCH_TEST_ENTITY)
assert entity.state == STATE_ON
- with patch(
- "pyuptimerobot.UptimeRobot.async_edit_monitor",
- side_effect=UptimeRobotAuthenticationException,
- ), patch(
- "homeassistant.config_entries.ConfigEntry.async_start_reauth"
- ) as config_entry_reauth:
+ with (
+ patch(
+ "pyuptimerobot.UptimeRobot.async_edit_monitor",
+ side_effect=UptimeRobotAuthenticationException,
+ ),
+ patch(
+ "homeassistant.config_entries.ConfigEntry.async_start_reauth"
+ ) as config_entry_reauth,
+ ):
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
diff --git a/tests/components/usb/test_init.py b/tests/components/usb/test_init.py
index 6d04516a26c..c3f7817527c 100644
--- a/tests/components/usb/test_init.py
+++ b/tests/components/usb/test_init.py
@@ -89,13 +89,14 @@ async def test_observer_discovery(
mock_observer = MagicMock()
return mock_observer
- with patch("pyudev.Context"), patch(
- "pyudev.MonitorObserver", new=_create_mock_monitor_observer
- ), patch("pyudev.Monitor.filter_by"), patch(
- "homeassistant.components.usb.async_get_usb", return_value=new_usb
- ), patch(
- "homeassistant.components.usb.comports", return_value=mock_comports
- ), patch.object(hass.config_entries.flow, "async_init") as mock_config_flow:
+ with (
+ patch("pyudev.Context"),
+ patch("pyudev.MonitorObserver", new=_create_mock_monitor_observer),
+ patch("pyudev.Monitor.filter_by"),
+ patch("homeassistant.components.usb.async_get_usb", return_value=new_usb),
+ patch("homeassistant.components.usb.comports", return_value=mock_comports),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ ):
assert await async_setup_component(hass, "usb", {"usb": {}})
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -140,13 +141,12 @@ async def test_removal_by_observer_before_started(
)
]
- with patch(
- "homeassistant.components.usb.async_get_usb", return_value=new_usb
- ), patch(
- "homeassistant.components.usb.comports", return_value=mock_comports
- ), patch("pyudev.MonitorObserver", new=_create_mock_monitor_observer), patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_config_flow:
+ with (
+ patch("homeassistant.components.usb.async_get_usb", return_value=new_usb),
+ patch("homeassistant.components.usb.comports", return_value=mock_comports),
+ patch("pyudev.MonitorObserver", new=_create_mock_monitor_observer),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ ):
assert await async_setup_component(hass, "usb", {"usb": {}})
await hass.async_block_till_done()
@@ -177,11 +177,12 @@ async def test_discovered_by_websocket_scan(
)
]
- with patch("pyudev.Context", side_effect=ImportError), patch(
- "homeassistant.components.usb.async_get_usb", return_value=new_usb
- ), patch(
- "homeassistant.components.usb.comports", return_value=mock_comports
- ), patch.object(hass.config_entries.flow, "async_init") as mock_config_flow:
+ with (
+ patch("pyudev.Context", side_effect=ImportError),
+ patch("homeassistant.components.usb.async_get_usb", return_value=new_usb),
+ patch("homeassistant.components.usb.comports", return_value=mock_comports),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ ):
assert await async_setup_component(hass, "usb", {"usb": {}})
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -215,11 +216,12 @@ async def test_discovered_by_websocket_scan_limited_by_description_matcher(
)
]
- with patch("pyudev.Context", side_effect=ImportError), patch(
- "homeassistant.components.usb.async_get_usb", return_value=new_usb
- ), patch(
- "homeassistant.components.usb.comports", return_value=mock_comports
- ), patch.object(hass.config_entries.flow, "async_init") as mock_config_flow:
+ with (
+ patch("pyudev.Context", side_effect=ImportError),
+ patch("homeassistant.components.usb.async_get_usb", return_value=new_usb),
+ patch("homeassistant.components.usb.comports", return_value=mock_comports),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ ):
assert await async_setup_component(hass, "usb", {"usb": {}})
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -254,11 +256,12 @@ async def test_most_targeted_matcher_wins(
)
]
- with patch("pyudev.Context", side_effect=ImportError), patch(
- "homeassistant.components.usb.async_get_usb", return_value=new_usb
- ), patch(
- "homeassistant.components.usb.comports", return_value=mock_comports
- ), patch.object(hass.config_entries.flow, "async_init") as mock_config_flow:
+ with (
+ patch("pyudev.Context", side_effect=ImportError),
+ patch("homeassistant.components.usb.async_get_usb", return_value=new_usb),
+ patch("homeassistant.components.usb.comports", return_value=mock_comports),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ ):
assert await async_setup_component(hass, "usb", {"usb": {}})
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -292,11 +295,12 @@ async def test_discovered_by_websocket_scan_rejected_by_description_matcher(
)
]
- with patch("pyudev.Context", side_effect=ImportError), patch(
- "homeassistant.components.usb.async_get_usb", return_value=new_usb
- ), patch(
- "homeassistant.components.usb.comports", return_value=mock_comports
- ), patch.object(hass.config_entries.flow, "async_init") as mock_config_flow:
+ with (
+ patch("pyudev.Context", side_effect=ImportError),
+ patch("homeassistant.components.usb.async_get_usb", return_value=new_usb),
+ patch("homeassistant.components.usb.comports", return_value=mock_comports),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ ):
assert await async_setup_component(hass, "usb", {"usb": {}})
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -334,11 +338,12 @@ async def test_discovered_by_websocket_scan_limited_by_serial_number_matcher(
)
]
- with patch("pyudev.Context", side_effect=ImportError), patch(
- "homeassistant.components.usb.async_get_usb", return_value=new_usb
- ), patch(
- "homeassistant.components.usb.comports", return_value=mock_comports
- ), patch.object(hass.config_entries.flow, "async_init") as mock_config_flow:
+ with (
+ patch("pyudev.Context", side_effect=ImportError),
+ patch("homeassistant.components.usb.async_get_usb", return_value=new_usb),
+ patch("homeassistant.components.usb.comports", return_value=mock_comports),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ ):
assert await async_setup_component(hass, "usb", {"usb": {}})
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -372,11 +377,12 @@ async def test_discovered_by_websocket_scan_rejected_by_serial_number_matcher(
)
]
- with patch("pyudev.Context", side_effect=ImportError), patch(
- "homeassistant.components.usb.async_get_usb", return_value=new_usb
- ), patch(
- "homeassistant.components.usb.comports", return_value=mock_comports
- ), patch.object(hass.config_entries.flow, "async_init") as mock_config_flow:
+ with (
+ patch("pyudev.Context", side_effect=ImportError),
+ patch("homeassistant.components.usb.async_get_usb", return_value=new_usb),
+ patch("homeassistant.components.usb.comports", return_value=mock_comports),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ ):
assert await async_setup_component(hass, "usb", {"usb": {}})
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -414,11 +420,12 @@ async def test_discovered_by_websocket_scan_limited_by_manufacturer_matcher(
)
]
- with patch("pyudev.Context", side_effect=ImportError), patch(
- "homeassistant.components.usb.async_get_usb", return_value=new_usb
- ), patch(
- "homeassistant.components.usb.comports", return_value=mock_comports
- ), patch.object(hass.config_entries.flow, "async_init") as mock_config_flow:
+ with (
+ patch("pyudev.Context", side_effect=ImportError),
+ patch("homeassistant.components.usb.async_get_usb", return_value=new_usb),
+ patch("homeassistant.components.usb.comports", return_value=mock_comports),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ ):
assert await async_setup_component(hass, "usb", {"usb": {}})
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -457,11 +464,12 @@ async def test_discovered_by_websocket_scan_rejected_by_manufacturer_matcher(
)
]
- with patch("pyudev.Context", side_effect=ImportError), patch(
- "homeassistant.components.usb.async_get_usb", return_value=new_usb
- ), patch(
- "homeassistant.components.usb.comports", return_value=mock_comports
- ), patch.object(hass.config_entries.flow, "async_init") as mock_config_flow:
+ with (
+ patch("pyudev.Context", side_effect=ImportError),
+ patch("homeassistant.components.usb.async_get_usb", return_value=new_usb),
+ patch("homeassistant.components.usb.comports", return_value=mock_comports),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ ):
assert await async_setup_component(hass, "usb", {"usb": {}})
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -494,11 +502,12 @@ async def test_discovered_by_websocket_rejected_with_empty_serial_number_only(
)
]
- with patch("pyudev.Context", side_effect=ImportError), patch(
- "homeassistant.components.usb.async_get_usb", return_value=new_usb
- ), patch(
- "homeassistant.components.usb.comports", return_value=mock_comports
- ), patch.object(hass.config_entries.flow, "async_init") as mock_config_flow:
+ with (
+ patch("pyudev.Context", side_effect=ImportError),
+ patch("homeassistant.components.usb.async_get_usb", return_value=new_usb),
+ patch("homeassistant.components.usb.comports", return_value=mock_comports),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ ):
assert await async_setup_component(hass, "usb", {"usb": {}})
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -529,11 +538,12 @@ async def test_discovered_by_websocket_scan_match_vid_only(
)
]
- with patch("pyudev.Context", side_effect=ImportError), patch(
- "homeassistant.components.usb.async_get_usb", return_value=new_usb
- ), patch(
- "homeassistant.components.usb.comports", return_value=mock_comports
- ), patch.object(hass.config_entries.flow, "async_init") as mock_config_flow:
+ with (
+ patch("pyudev.Context", side_effect=ImportError),
+ patch("homeassistant.components.usb.async_get_usb", return_value=new_usb),
+ patch("homeassistant.components.usb.comports", return_value=mock_comports),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ ):
assert await async_setup_component(hass, "usb", {"usb": {}})
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -565,11 +575,12 @@ async def test_discovered_by_websocket_scan_match_vid_wrong_pid(
)
]
- with patch("pyudev.Context", side_effect=ImportError), patch(
- "homeassistant.components.usb.async_get_usb", return_value=new_usb
- ), patch(
- "homeassistant.components.usb.comports", return_value=mock_comports
- ), patch.object(hass.config_entries.flow, "async_init") as mock_config_flow:
+ with (
+ patch("pyudev.Context", side_effect=ImportError),
+ patch("homeassistant.components.usb.async_get_usb", return_value=new_usb),
+ patch("homeassistant.components.usb.comports", return_value=mock_comports),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ ):
assert await async_setup_component(hass, "usb", {"usb": {}})
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -600,11 +611,12 @@ async def test_discovered_by_websocket_no_vid_pid(
)
]
- with patch("pyudev.Context", side_effect=ImportError), patch(
- "homeassistant.components.usb.async_get_usb", return_value=new_usb
- ), patch(
- "homeassistant.components.usb.comports", return_value=mock_comports
- ), patch.object(hass.config_entries.flow, "async_init") as mock_config_flow:
+ with (
+ patch("pyudev.Context", side_effect=ImportError),
+ patch("homeassistant.components.usb.async_get_usb", return_value=new_usb),
+ patch("homeassistant.components.usb.comports", return_value=mock_comports),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ ):
assert await async_setup_component(hass, "usb", {"usb": {}})
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -636,11 +648,12 @@ async def test_non_matching_discovered_by_scanner_after_started(
)
]
- with patch("pyudev.Context", side_effect=exception_type), patch(
- "homeassistant.components.usb.async_get_usb", return_value=new_usb
- ), patch(
- "homeassistant.components.usb.comports", return_value=mock_comports
- ), patch.object(hass.config_entries.flow, "async_init") as mock_config_flow:
+ with (
+ patch("pyudev.Context", side_effect=exception_type),
+ patch("homeassistant.components.usb.async_get_usb", return_value=new_usb),
+ patch("homeassistant.components.usb.comports", return_value=mock_comports),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ ):
assert await async_setup_component(hass, "usb", {"usb": {}})
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -675,11 +688,13 @@ async def test_observer_on_wsl_fallback_without_throwing_exception(
)
]
- with patch("pyudev.Context"), patch(
- "pyudev.Monitor.filter_by", side_effect=ValueError
- ), patch("homeassistant.components.usb.async_get_usb", return_value=new_usb), patch(
- "homeassistant.components.usb.comports", return_value=mock_comports
- ), patch.object(hass.config_entries.flow, "async_init") as mock_config_flow:
+ with (
+ patch("pyudev.Context"),
+ patch("pyudev.Monitor.filter_by", side_effect=ValueError),
+ patch("homeassistant.components.usb.async_get_usb", return_value=new_usb),
+ patch("homeassistant.components.usb.comports", return_value=mock_comports),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ ):
assert await async_setup_component(hass, "usb", {"usb": {}})
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -725,17 +740,18 @@ async def test_not_discovered_by_observer_before_started_on_docker(
)
]
- with patch(
- "homeassistant.components.usb.async_get_usb", return_value=new_usb
- ), patch(
- "homeassistant.components.usb.comports", return_value=mock_comports
- ), patch("pyudev.MonitorObserver", new=_create_mock_monitor_observer):
+ with (
+ patch("homeassistant.components.usb.async_get_usb", return_value=new_usb),
+ patch("homeassistant.components.usb.comports", return_value=mock_comports),
+ patch("pyudev.MonitorObserver", new=_create_mock_monitor_observer),
+ ):
assert await async_setup_component(hass, "usb", {"usb": {}})
await hass.async_block_till_done()
- with patch("homeassistant.components.usb.comports", return_value=[]), patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_config_flow:
+ with (
+ patch("homeassistant.components.usb.comports", return_value=[]),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ ):
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
@@ -843,10 +859,11 @@ async def test_async_is_plugged_in(
"pid": "3039",
}
- with patch("pyudev.Context", side_effect=ImportError), patch(
- "homeassistant.components.usb.async_get_usb", return_value=new_usb
- ), patch("homeassistant.components.usb.comports", return_value=[]), patch.object(
- hass.config_entries.flow, "async_init"
+ with (
+ patch("pyudev.Context", side_effect=ImportError),
+ patch("homeassistant.components.usb.async_get_usb", return_value=new_usb),
+ patch("homeassistant.components.usb.comports", return_value=[]),
+ patch.object(hass.config_entries.flow, "async_init"),
):
assert await async_setup_component(hass, "usb", {"usb": {}})
await hass.async_block_till_done()
@@ -854,9 +871,10 @@ async def test_async_is_plugged_in(
await hass.async_block_till_done()
assert not usb.async_is_plugged_in(hass, matcher)
- with patch(
- "homeassistant.components.usb.comports", return_value=mock_comports
- ), patch.object(hass.config_entries.flow, "async_init"):
+ with (
+ patch("homeassistant.components.usb.comports", return_value=mock_comports),
+ patch.object(hass.config_entries.flow, "async_init"),
+ ):
ws_client = await hass_ws_client(hass)
await ws_client.send_json({"id": 1, "type": "usb/scan"})
response = await ws_client.receive_json()
@@ -882,10 +900,11 @@ async def test_async_is_plugged_in_case_enforcement(
new_usb = [{"domain": "test1", "vid": "ABCD"}]
- with patch("pyudev.Context", side_effect=ImportError), patch(
- "homeassistant.components.usb.async_get_usb", return_value=new_usb
- ), patch("homeassistant.components.usb.comports", return_value=[]), patch.object(
- hass.config_entries.flow, "async_init"
+ with (
+ patch("pyudev.Context", side_effect=ImportError),
+ patch("homeassistant.components.usb.async_get_usb", return_value=new_usb),
+ patch("homeassistant.components.usb.comports", return_value=[]),
+ patch.object(hass.config_entries.flow, "async_init"),
):
assert await async_setup_component(hass, "usb", {"usb": {}})
await hass.async_block_till_done()
@@ -902,10 +921,11 @@ async def test_web_socket_triggers_discovery_request_callbacks(
"""Test the websocket call triggers a discovery request callback."""
mock_callback = Mock()
- with patch("pyudev.Context", side_effect=ImportError), patch(
- "homeassistant.components.usb.async_get_usb", return_value=[]
- ), patch("homeassistant.components.usb.comports", return_value=[]), patch.object(
- hass.config_entries.flow, "async_init"
+ with (
+ patch("pyudev.Context", side_effect=ImportError),
+ patch("homeassistant.components.usb.async_get_usb", return_value=[]),
+ patch("homeassistant.components.usb.comports", return_value=[]),
+ patch.object(hass.config_entries.flow, "async_init"),
):
assert await async_setup_component(hass, "usb", {"usb": {}})
await hass.async_block_till_done()
@@ -937,10 +957,11 @@ async def test_initial_scan_callback(
mock_callback_1 = Mock()
mock_callback_2 = Mock()
- with patch("pyudev.Context", side_effect=ImportError), patch(
- "homeassistant.components.usb.async_get_usb", return_value=[]
- ), patch("homeassistant.components.usb.comports", return_value=[]), patch.object(
- hass.config_entries.flow, "async_init"
+ with (
+ patch("pyudev.Context", side_effect=ImportError),
+ patch("homeassistant.components.usb.async_get_usb", return_value=[]),
+ patch("homeassistant.components.usb.comports", return_value=[]),
+ patch.object(hass.config_entries.flow, "async_init"),
):
assert await async_setup_component(hass, "usb", {"usb": {}})
cancel_1 = usb.async_register_initial_scan_callback(hass, mock_callback_1)
@@ -971,10 +992,11 @@ async def test_cancel_initial_scan_callback(
"""Test it's possible to cancel an initial scan callback."""
mock_callback = Mock()
- with patch("pyudev.Context", side_effect=ImportError), patch(
- "homeassistant.components.usb.async_get_usb", return_value=[]
- ), patch("homeassistant.components.usb.comports", return_value=[]), patch.object(
- hass.config_entries.flow, "async_init"
+ with (
+ patch("pyudev.Context", side_effect=ImportError),
+ patch("homeassistant.components.usb.async_get_usb", return_value=[]),
+ patch("homeassistant.components.usb.comports", return_value=[]),
+ patch.object(hass.config_entries.flow, "async_init"),
):
assert await async_setup_component(hass, "usb", {"usb": {}})
cancel = usb.async_register_initial_scan_callback(hass, mock_callback)
@@ -1007,14 +1029,16 @@ async def test_resolve_serial_by_id(
)
]
- with patch("pyudev.Context", side_effect=ImportError), patch(
- "homeassistant.components.usb.async_get_usb", return_value=new_usb
- ), patch(
- "homeassistant.components.usb.comports", return_value=mock_comports
- ), patch(
- "homeassistant.components.usb.get_serial_by_id",
- return_value="/dev/serial/by-id/bla",
- ), patch.object(hass.config_entries.flow, "async_init") as mock_config_flow:
+ with (
+ patch("pyudev.Context", side_effect=ImportError),
+ patch("homeassistant.components.usb.async_get_usb", return_value=new_usb),
+ patch("homeassistant.components.usb.comports", return_value=mock_comports),
+ patch(
+ "homeassistant.components.usb.get_serial_by_id",
+ return_value="/dev/serial/by-id/bla",
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ ):
assert await async_setup_component(hass, "usb", {"usb": {}})
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
diff --git a/tests/components/usgs_earthquakes_feed/test_geo_location.py b/tests/components/usgs_earthquakes_feed/test_geo_location.py
index effaa119a07..40d19422ced 100644
--- a/tests/components/usgs_earthquakes_feed/test_geo_location.py
+++ b/tests/components/usgs_earthquakes_feed/test_geo_location.py
@@ -116,9 +116,10 @@ async def test_setup(hass: HomeAssistant) -> None:
# Patching 'utcnow' to gain more control over the timed update.
utcnow = dt_util.utcnow()
- with freeze_time(utcnow), patch(
- "aio_geojson_client.feed.GeoJsonFeed.update"
- ) as mock_feed_update:
+ with (
+ freeze_time(utcnow),
+ patch("aio_geojson_client.feed.GeoJsonFeed.update") as mock_feed_update,
+ ):
mock_feed_update.return_value = (
"OK",
[mock_entry_1, mock_entry_2, mock_entry_3],
@@ -219,12 +220,13 @@ async def test_setup_with_custom_location(hass: HomeAssistant) -> None:
# Set up some mock feed entries for this test.
mock_entry_1 = _generate_mock_feed_entry("1234", "Title 1", 20.5, (-31.1, 150.1))
- with patch(
- "aio_geojson_usgs_earthquakes.feed_manager.UsgsEarthquakeHazardsProgramFeed",
- wraps=UsgsEarthquakeHazardsProgramFeed,
- ) as mock_feed, patch(
- "aio_geojson_client.feed.GeoJsonFeed.update"
- ) as mock_feed_update:
+ with (
+ patch(
+ "aio_geojson_usgs_earthquakes.feed_manager.UsgsEarthquakeHazardsProgramFeed",
+ wraps=UsgsEarthquakeHazardsProgramFeed,
+ ) as mock_feed,
+ patch("aio_geojson_client.feed.GeoJsonFeed.update") as mock_feed_update,
+ ):
mock_feed_update.return_value = "OK", [mock_entry_1]
with assert_setup_component(1, geo_location.DOMAIN):
diff --git a/tests/components/uvc/test_camera.py b/tests/components/uvc/test_camera.py
index cbbd27b81df..12203a3e222 100644
--- a/tests/components/uvc/test_camera.py
+++ b/tests/components/uvc/test_camera.py
@@ -382,9 +382,9 @@ async def test_motion_recording_mode_properties(
assert state
assert state.state != STATE_RECORDING
- mock_remote.return_value.get_camera.return_value[
- "recordingIndicator"
- ] = "MOTION_INPROGRESS"
+ mock_remote.return_value.get_camera.return_value["recordingIndicator"] = (
+ "MOTION_INPROGRESS"
+ )
async_fire_time_changed(hass, now + timedelta(seconds=91))
await hass.async_block_till_done()
@@ -394,9 +394,9 @@ async def test_motion_recording_mode_properties(
assert state
assert state.state == STATE_RECORDING
- mock_remote.return_value.get_camera.return_value[
- "recordingIndicator"
- ] = "MOTION_FINISHED"
+ mock_remote.return_value.get_camera.return_value["recordingIndicator"] = (
+ "MOTION_FINISHED"
+ )
async_fire_time_changed(hass, now + timedelta(seconds=121))
await hass.async_block_till_done()
diff --git a/tests/components/vallox/test_config_flow.py b/tests/components/vallox/test_config_flow.py
index 6d053dd4e8a..00c11854fe2 100644
--- a/tests/components/vallox/test_config_flow.py
+++ b/tests/components/vallox/test_config_flow.py
@@ -33,13 +33,16 @@ async def test_form_create_entry(hass: HomeAssistant) -> None:
assert init["type"] == FlowResultType.FORM
assert init["errors"] is None
- with patch(
- "homeassistant.components.vallox.config_flow.Vallox.fetch_metric_data",
- return_value=None,
- ), patch(
- "homeassistant.components.vallox.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.vallox.config_flow.Vallox.fetch_metric_data",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.vallox.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
init["flow_id"],
{"host": "1.2.3.4"},
diff --git a/tests/components/venstar/test_config_flow.py b/tests/components/venstar/test_config_flow.py
index c7a0f0a394f..077f87975f0 100644
--- a/tests/components/venstar/test_config_flow.py
+++ b/tests/components/venstar/test_config_flow.py
@@ -40,13 +40,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.venstar.config_flow.VenstarColorTouch.update_info",
- new=VenstarColorTouchMock.update_info,
- ), patch(
- "homeassistant.components.venstar.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.venstar.config_flow.VenstarColorTouch.update_info",
+ new=VenstarColorTouchMock.update_info,
+ ),
+ patch(
+ "homeassistant.components.venstar.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
TEST_DATA,
@@ -107,12 +110,15 @@ async def test_already_configured(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
- with patch(
- "homeassistant.components.venstar.VenstarColorTouch.update_info",
- new=VenstarColorTouchMock.update_info,
- ), patch(
- "homeassistant.components.venstar.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.venstar.VenstarColorTouch.update_info",
+ new=VenstarColorTouchMock.update_info,
+ ),
+ patch(
+ "homeassistant.components.venstar.async_setup_entry",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/venstar/test_init.py b/tests/components/venstar/test_init.py
index 14064334faf..75250b52f5b 100644
--- a/tests/components/venstar/test_init.py
+++ b/tests/components/venstar/test_init.py
@@ -25,24 +25,31 @@ async def test_setup_entry(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.venstar.VenstarColorTouch._request",
- new=VenstarColorTouchMock._request,
- ), patch(
- "homeassistant.components.venstar.VenstarColorTouch.update_sensors",
- new=VenstarColorTouchMock.update_sensors,
- ), patch(
- "homeassistant.components.venstar.VenstarColorTouch.update_info",
- new=VenstarColorTouchMock.update_info,
- ), patch(
- "homeassistant.components.venstar.VenstarColorTouch.update_alerts",
- new=VenstarColorTouchMock.update_alerts,
- ), patch(
- "homeassistant.components.venstar.VenstarColorTouch.get_runtimes",
- new=VenstarColorTouchMock.get_runtimes,
- ), patch(
- "homeassistant.components.venstar.VENSTAR_SLEEP",
- new=0,
+ with (
+ patch(
+ "homeassistant.components.venstar.VenstarColorTouch._request",
+ new=VenstarColorTouchMock._request,
+ ),
+ patch(
+ "homeassistant.components.venstar.VenstarColorTouch.update_sensors",
+ new=VenstarColorTouchMock.update_sensors,
+ ),
+ patch(
+ "homeassistant.components.venstar.VenstarColorTouch.update_info",
+ new=VenstarColorTouchMock.update_info,
+ ),
+ patch(
+ "homeassistant.components.venstar.VenstarColorTouch.update_alerts",
+ new=VenstarColorTouchMock.update_alerts,
+ ),
+ patch(
+ "homeassistant.components.venstar.VenstarColorTouch.get_runtimes",
+ new=VenstarColorTouchMock.get_runtimes,
+ ),
+ patch(
+ "homeassistant.components.venstar.VENSTAR_SLEEP",
+ new=0,
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -65,21 +72,27 @@ async def test_setup_entry_exception(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.venstar.VenstarColorTouch._request",
- new=VenstarColorTouchMock._request,
- ), patch(
- "homeassistant.components.venstar.VenstarColorTouch.update_sensors",
- new=VenstarColorTouchMock.update_sensors,
- ), patch(
- "homeassistant.components.venstar.VenstarColorTouch.update_info",
- new=VenstarColorTouchMock.broken_update_info,
- ), patch(
- "homeassistant.components.venstar.VenstarColorTouch.update_alerts",
- new=VenstarColorTouchMock.update_alerts,
- ), patch(
- "homeassistant.components.venstar.VenstarColorTouch.get_runtimes",
- new=VenstarColorTouchMock.get_runtimes,
+ with (
+ patch(
+ "homeassistant.components.venstar.VenstarColorTouch._request",
+ new=VenstarColorTouchMock._request,
+ ),
+ patch(
+ "homeassistant.components.venstar.VenstarColorTouch.update_sensors",
+ new=VenstarColorTouchMock.update_sensors,
+ ),
+ patch(
+ "homeassistant.components.venstar.VenstarColorTouch.update_info",
+ new=VenstarColorTouchMock.broken_update_info,
+ ),
+ patch(
+ "homeassistant.components.venstar.VenstarColorTouch.update_alerts",
+ new=VenstarColorTouchMock.update_alerts,
+ ),
+ patch(
+ "homeassistant.components.venstar.VenstarColorTouch.get_runtimes",
+ new=VenstarColorTouchMock.get_runtimes,
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/vesync/test_init.py b/tests/components/vesync/test_init.py
index fedd7f70a93..a089a270c94 100644
--- a/tests/components/vesync/test_init.py
+++ b/tests/components/vesync/test_init.py
@@ -28,11 +28,10 @@ async def test_async_setup_entry__not_login(
"""Test setup does not create config entry when not logged in."""
manager.login = Mock(return_value=False)
- with patch.object(
- hass.config_entries, "async_forward_entry_setups"
- ) as setups_mock, patch(
- "homeassistant.components.vesync.async_process_devices"
- ) as process_mock:
+ with (
+ patch.object(hass.config_entries, "async_forward_entry_setups") as setups_mock,
+ patch("homeassistant.components.vesync.async_process_devices") as process_mock,
+ ):
assert not await async_setup_entry(hass, config_entry)
await hass.async_block_till_done()
assert setups_mock.call_count == 0
diff --git a/tests/components/vilfo/test_config_flow.py b/tests/components/vilfo/test_config_flow.py
index 7077c4f2acc..c1755f95043 100644
--- a/tests/components/vilfo/test_config_flow.py
+++ b/tests/components/vilfo/test_config_flow.py
@@ -22,13 +22,13 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["errors"] == {}
- with patch("vilfo.Client.ping", return_value=None), patch(
- "vilfo.Client.get_board_information", return_value=None
- ), patch(
- "vilfo.Client.resolve_firmware_version", return_value=firmware_version
- ), patch("vilfo.Client.resolve_mac_address", return_value=mock_mac), patch(
- "homeassistant.components.vilfo.async_setup_entry"
- ) as mock_setup_entry:
+ with (
+ patch("vilfo.Client.ping", return_value=None),
+ patch("vilfo.Client.get_board_information", return_value=None),
+ patch("vilfo.Client.resolve_firmware_version", return_value=firmware_version),
+ patch("vilfo.Client.resolve_mac_address", return_value=mock_mac),
+ patch("homeassistant.components.vilfo.async_setup_entry") as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_HOST: "testadmin.vilfo.com", CONF_ACCESS_TOKEN: "test-token"},
@@ -51,11 +51,13 @@ async def test_form_invalid_auth(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch("vilfo.Client.ping", return_value=None), patch(
- "vilfo.Client.resolve_mac_address", return_value=None
- ), patch(
- "vilfo.Client.get_board_information",
- side_effect=vilfo.exceptions.AuthenticationException,
+ with (
+ patch("vilfo.Client.ping", return_value=None),
+ patch("vilfo.Client.resolve_mac_address", return_value=None),
+ patch(
+ "vilfo.Client.get_board_information",
+ side_effect=vilfo.exceptions.AuthenticationException,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -72,8 +74,9 @@ async def test_form_cannot_connect(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch("vilfo.Client.ping", side_effect=vilfo.exceptions.VilfoException), patch(
- "vilfo.Client.resolve_mac_address"
+ with (
+ patch("vilfo.Client.ping", side_effect=vilfo.exceptions.VilfoException),
+ patch("vilfo.Client.resolve_mac_address"),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -83,8 +86,9 @@ async def test_form_cannot_connect(hass: HomeAssistant) -> None:
assert result2["type"] == data_entry_flow.FlowResultType.FORM
assert result2["errors"] == {"base": "cannot_connect"}
- with patch("vilfo.Client.ping", side_effect=vilfo.exceptions.VilfoException), patch(
- "vilfo.Client.resolve_mac_address"
+ with (
+ patch("vilfo.Client.ping", side_effect=vilfo.exceptions.VilfoException),
+ patch("vilfo.Client.resolve_mac_address"),
):
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -112,12 +116,15 @@ async def test_form_already_configured(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
firmware_version = "1.1.0"
- with patch("vilfo.Client.ping", return_value=None), patch(
- "vilfo.Client.get_board_information",
- return_value=None,
- ), patch(
- "vilfo.Client.resolve_firmware_version", return_value=firmware_version
- ), patch("vilfo.Client.resolve_mac_address", return_value=None):
+ with (
+ patch("vilfo.Client.ping", return_value=None),
+ patch(
+ "vilfo.Client.get_board_information",
+ return_value=None,
+ ),
+ patch("vilfo.Client.resolve_firmware_version", return_value=firmware_version),
+ patch("vilfo.Client.resolve_mac_address", return_value=None),
+ ):
first_flow_result2 = await hass.config_entries.flow.async_configure(
first_flow_result1["flow_id"],
{CONF_HOST: "testadmin.vilfo.com", CONF_ACCESS_TOKEN: "test-token"},
@@ -127,12 +134,15 @@ async def test_form_already_configured(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch("vilfo.Client.ping", return_value=None), patch(
- "vilfo.Client.get_board_information",
- return_value=None,
- ), patch(
- "vilfo.Client.resolve_firmware_version", return_value=firmware_version
- ), patch("vilfo.Client.resolve_mac_address", return_value=None):
+ with (
+ patch("vilfo.Client.ping", return_value=None),
+ patch(
+ "vilfo.Client.get_board_information",
+ return_value=None,
+ ),
+ patch("vilfo.Client.resolve_firmware_version", return_value=firmware_version),
+ patch("vilfo.Client.resolve_mac_address", return_value=None),
+ ):
second_flow_result2 = await hass.config_entries.flow.async_configure(
second_flow_result1["flow_id"],
{CONF_HOST: "testadmin.vilfo.com", CONF_ACCESS_TOKEN: "test-token"},
@@ -169,11 +179,12 @@ async def test_validate_input_returns_data(hass: HomeAssistant) -> None:
mock_mac = "FF-00-00-00-00-00"
firmware_version = "1.1.0"
- with patch("vilfo.Client.ping", return_value=None), patch(
- "vilfo.Client.get_board_information", return_value=None
- ), patch(
- "vilfo.Client.resolve_firmware_version", return_value=firmware_version
- ), patch("vilfo.Client.resolve_mac_address", return_value=None):
+ with (
+ patch("vilfo.Client.ping", return_value=None),
+ patch("vilfo.Client.get_board_information", return_value=None),
+ patch("vilfo.Client.resolve_firmware_version", return_value=firmware_version),
+ patch("vilfo.Client.resolve_mac_address", return_value=None),
+ ):
result = await config_flow.validate_input(hass, data=mock_data)
assert result["title"] == mock_data["host"]
@@ -181,11 +192,12 @@ async def test_validate_input_returns_data(hass: HomeAssistant) -> None:
assert result[CONF_MAC] is None
assert result[CONF_ID] == mock_data["host"]
- with patch("vilfo.Client.ping", return_value=None), patch(
- "vilfo.Client.get_board_information", return_value=None
- ), patch(
- "vilfo.Client.resolve_firmware_version", return_value=firmware_version
- ), patch("vilfo.Client.resolve_mac_address", return_value=mock_mac):
+ with (
+ patch("vilfo.Client.ping", return_value=None),
+ patch("vilfo.Client.get_board_information", return_value=None),
+ patch("vilfo.Client.resolve_firmware_version", return_value=firmware_version),
+ patch("vilfo.Client.resolve_mac_address", return_value=mock_mac),
+ ):
result2 = await config_flow.validate_input(hass, data=mock_data)
result3 = await config_flow.validate_input(hass, data=mock_data_with_ip)
result4 = await config_flow.validate_input(hass, data=mock_data_with_ipv6)
diff --git a/tests/components/vizio/conftest.py b/tests/components/vizio/conftest.py
index 08a6e6715be..6ce36b38c8f 100644
--- a/tests/components/vizio/conftest.py
+++ b/tests/components/vizio/conftest.py
@@ -93,12 +93,15 @@ def vizio_connect_fixture():
@pytest.fixture(name="vizio_complete_pairing")
def vizio_complete_pairing_fixture():
"""Mock complete vizio pairing workflow."""
- with patch(
- "homeassistant.components.vizio.config_flow.VizioAsync.start_pair",
- return_value=MockStartPairingResponse(CH_TYPE, RESPONSE_TOKEN),
- ), patch(
- "homeassistant.components.vizio.config_flow.VizioAsync.pair",
- return_value=MockCompletePairingResponse(ACCESS_TOKEN),
+ with (
+ patch(
+ "homeassistant.components.vizio.config_flow.VizioAsync.start_pair",
+ return_value=MockStartPairingResponse(CH_TYPE, RESPONSE_TOKEN),
+ ),
+ patch(
+ "homeassistant.components.vizio.config_flow.VizioAsync.pair",
+ return_value=MockCompletePairingResponse(ACCESS_TOKEN),
+ ),
):
yield
@@ -116,12 +119,15 @@ def vizio_start_pairing_failure_fixture():
@pytest.fixture(name="vizio_invalid_pin_failure")
def vizio_invalid_pin_failure_fixture():
"""Mock vizio failure due to invalid pin."""
- with patch(
- "homeassistant.components.vizio.config_flow.VizioAsync.start_pair",
- return_value=MockStartPairingResponse(CH_TYPE, RESPONSE_TOKEN),
- ), patch(
- "homeassistant.components.vizio.config_flow.VizioAsync.pair",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.components.vizio.config_flow.VizioAsync.start_pair",
+ return_value=MockStartPairingResponse(CH_TYPE, RESPONSE_TOKEN),
+ ),
+ patch(
+ "homeassistant.components.vizio.config_flow.VizioAsync.pair",
+ return_value=None,
+ ),
):
yield
@@ -136,10 +142,13 @@ def vizio_bypass_setup_fixture():
@pytest.fixture(name="vizio_bypass_update")
def vizio_bypass_update_fixture():
"""Mock component update."""
- with patch(
- "homeassistant.components.vizio.media_player.VizioAsync.can_connect_with_auth_check",
- return_value=True,
- ), patch("homeassistant.components.vizio.media_player.VizioDevice.async_update"):
+ with (
+ patch(
+ "homeassistant.components.vizio.media_player.VizioAsync.can_connect_with_auth_check",
+ return_value=True,
+ ),
+ patch("homeassistant.components.vizio.media_player.VizioDevice.async_update"),
+ ):
yield
@@ -156,12 +165,15 @@ def vizio_guess_device_type_fixture():
@pytest.fixture(name="vizio_cant_connect")
def vizio_cant_connect_fixture():
"""Mock vizio device can't connect with valid auth."""
- with patch(
- "homeassistant.components.vizio.config_flow.VizioAsync.validate_ha_config",
- AsyncMock(return_value=False),
- ), patch(
- "homeassistant.components.vizio.media_player.VizioAsync.get_power_state",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.components.vizio.config_flow.VizioAsync.validate_ha_config",
+ AsyncMock(return_value=False),
+ ),
+ patch(
+ "homeassistant.components.vizio.media_player.VizioAsync.get_power_state",
+ return_value=None,
+ ),
):
yield
@@ -169,34 +181,43 @@ def vizio_cant_connect_fixture():
@pytest.fixture(name="vizio_update")
def vizio_update_fixture():
"""Mock valid updates to vizio device."""
- with patch(
- "homeassistant.components.vizio.media_player.VizioAsync.can_connect_with_auth_check",
- return_value=True,
- ), patch(
- "homeassistant.components.vizio.media_player.VizioAsync.get_all_settings",
- return_value={
- "volume": int(MAX_VOLUME[DEVICE_CLASS_SPEAKER] / 2),
- "eq": CURRENT_EQ,
- "mute": "Off",
- },
- ), patch(
- "homeassistant.components.vizio.media_player.VizioAsync.get_setting_options",
- return_value=EQ_LIST,
- ), patch(
- "homeassistant.components.vizio.media_player.VizioAsync.get_current_input",
- return_value=CURRENT_INPUT,
- ), patch(
- "homeassistant.components.vizio.media_player.VizioAsync.get_inputs_list",
- return_value=get_mock_inputs(INPUT_LIST),
- ), patch(
- "homeassistant.components.vizio.media_player.VizioAsync.get_power_state",
- return_value=True,
- ), patch(
- "homeassistant.components.vizio.media_player.VizioAsync.get_model_name",
- return_value=MODEL,
- ), patch(
- "homeassistant.components.vizio.media_player.VizioAsync.get_version",
- return_value=VERSION,
+ with (
+ patch(
+ "homeassistant.components.vizio.media_player.VizioAsync.can_connect_with_auth_check",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.vizio.media_player.VizioAsync.get_all_settings",
+ return_value={
+ "volume": int(MAX_VOLUME[DEVICE_CLASS_SPEAKER] / 2),
+ "eq": CURRENT_EQ,
+ "mute": "Off",
+ },
+ ),
+ patch(
+ "homeassistant.components.vizio.media_player.VizioAsync.get_setting_options",
+ return_value=EQ_LIST,
+ ),
+ patch(
+ "homeassistant.components.vizio.media_player.VizioAsync.get_current_input",
+ return_value=CURRENT_INPUT,
+ ),
+ patch(
+ "homeassistant.components.vizio.media_player.VizioAsync.get_inputs_list",
+ return_value=get_mock_inputs(INPUT_LIST),
+ ),
+ patch(
+ "homeassistant.components.vizio.media_player.VizioAsync.get_power_state",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.vizio.media_player.VizioAsync.get_model_name",
+ return_value=MODEL,
+ ),
+ patch(
+ "homeassistant.components.vizio.media_player.VizioAsync.get_version",
+ return_value=VERSION,
+ ),
):
yield
@@ -204,15 +225,19 @@ def vizio_update_fixture():
@pytest.fixture(name="vizio_update_with_apps")
def vizio_update_with_apps_fixture(vizio_update: pytest.fixture):
"""Mock valid updates to vizio device that supports apps."""
- with patch(
- "homeassistant.components.vizio.media_player.VizioAsync.get_inputs_list",
- return_value=get_mock_inputs(INPUT_LIST_WITH_APPS),
- ), patch(
- "homeassistant.components.vizio.media_player.VizioAsync.get_current_input",
- return_value="CAST",
- ), patch(
- "homeassistant.components.vizio.media_player.VizioAsync.get_current_app_config",
- return_value=AppConfig(**CURRENT_APP_CONFIG),
+ with (
+ patch(
+ "homeassistant.components.vizio.media_player.VizioAsync.get_inputs_list",
+ return_value=get_mock_inputs(INPUT_LIST_WITH_APPS),
+ ),
+ patch(
+ "homeassistant.components.vizio.media_player.VizioAsync.get_current_input",
+ return_value="CAST",
+ ),
+ patch(
+ "homeassistant.components.vizio.media_player.VizioAsync.get_current_app_config",
+ return_value=AppConfig(**CURRENT_APP_CONFIG),
+ ),
):
yield
@@ -220,15 +245,19 @@ def vizio_update_with_apps_fixture(vizio_update: pytest.fixture):
@pytest.fixture(name="vizio_update_with_apps_on_input")
def vizio_update_with_apps_on_input_fixture(vizio_update: pytest.fixture):
"""Mock valid updates to vizio device that supports apps but is on a TV input."""
- with patch(
- "homeassistant.components.vizio.media_player.VizioAsync.get_inputs_list",
- return_value=get_mock_inputs(INPUT_LIST_WITH_APPS),
- ), patch(
- "homeassistant.components.vizio.media_player.VizioAsync.get_current_input",
- return_value=CURRENT_INPUT,
- ), patch(
- "homeassistant.components.vizio.media_player.VizioAsync.get_current_app_config",
- return_value=AppConfig("unknown", 1, "app"),
+ with (
+ patch(
+ "homeassistant.components.vizio.media_player.VizioAsync.get_inputs_list",
+ return_value=get_mock_inputs(INPUT_LIST_WITH_APPS),
+ ),
+ patch(
+ "homeassistant.components.vizio.media_player.VizioAsync.get_current_input",
+ return_value=CURRENT_INPUT,
+ ),
+ patch(
+ "homeassistant.components.vizio.media_player.VizioAsync.get_current_app_config",
+ return_value=AppConfig("unknown", 1, "app"),
+ ),
):
yield
diff --git a/tests/components/vizio/test_media_player.py b/tests/components/vizio/test_media_player.py
index 218c16eb939..d5ce18eb8b9 100644
--- a/tests/components/vizio/test_media_player.py
+++ b/tests/components/vizio/test_media_player.py
@@ -129,15 +129,19 @@ async def _cm_for_test_setup_without_apps(
all_settings: dict[str, Any], vizio_power_state: bool | None
) -> None:
"""Context manager to setup test for Vizio devices without including app specific patches."""
- with patch(
- "homeassistant.components.vizio.media_player.VizioAsync.get_all_settings",
- return_value=all_settings,
- ), patch(
- "homeassistant.components.vizio.media_player.VizioAsync.get_setting_options",
- return_value=EQ_LIST,
- ), patch(
- "homeassistant.components.vizio.media_player.VizioAsync.get_power_state",
- return_value=vizio_power_state,
+ with (
+ patch(
+ "homeassistant.components.vizio.media_player.VizioAsync.get_all_settings",
+ return_value=all_settings,
+ ),
+ patch(
+ "homeassistant.components.vizio.media_player.VizioAsync.get_setting_options",
+ return_value=EQ_LIST,
+ ),
+ patch(
+ "homeassistant.components.vizio.media_player.VizioAsync.get_power_state",
+ return_value=vizio_power_state,
+ ),
):
yield
@@ -484,10 +488,13 @@ async def _test_update_availability_switch(
# Fast forward time to future twice to trigger update and assert vizio log message
for i in range(1, 3):
future = now + (future_interval * i)
- with patch(
- "homeassistant.components.vizio.media_player.VizioAsync.get_power_state",
- return_value=final_power_state,
- ), freeze_time(future):
+ with (
+ patch(
+ "homeassistant.components.vizio.media_player.VizioAsync.get_power_state",
+ return_value=final_power_state,
+ ),
+ freeze_time(future),
+ ):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
if final_power_state is None:
@@ -641,11 +648,14 @@ async def test_setup_with_apps_additional_apps_config(
)
# Test that invalid app does nothing
- with patch(
- "homeassistant.components.vizio.media_player.VizioAsync.launch_app"
- ) as service_call1, patch(
- "homeassistant.components.vizio.media_player.VizioAsync.launch_app_config"
- ) as service_call2:
+ with (
+ patch(
+ "homeassistant.components.vizio.media_player.VizioAsync.launch_app"
+ ) as service_call1,
+ patch(
+ "homeassistant.components.vizio.media_player.VizioAsync.launch_app_config"
+ ) as service_call2,
+ ):
await hass.services.async_call(
MP_DOMAIN,
SERVICE_SELECT_SOURCE,
diff --git a/tests/components/vlc_telnet/test_config_flow.py b/tests/components/vlc_telnet/test_config_flow.py
index 1d75025535a..f5207c52c99 100644
--- a/tests/components/vlc_telnet/test_config_flow.py
+++ b/tests/components/vlc_telnet/test_config_flow.py
@@ -54,14 +54,15 @@ async def test_user_flow(
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with patch("homeassistant.components.vlc_telnet.config_flow.Client.connect"), patch(
- "homeassistant.components.vlc_telnet.config_flow.Client.login"
- ), patch(
- "homeassistant.components.vlc_telnet.config_flow.Client.disconnect"
- ), patch(
- "homeassistant.components.vlc_telnet.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("homeassistant.components.vlc_telnet.config_flow.Client.connect"),
+ patch("homeassistant.components.vlc_telnet.config_flow.Client.login"),
+ patch("homeassistant.components.vlc_telnet.config_flow.Client.disconnect"),
+ patch(
+ "homeassistant.components.vlc_telnet.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
input_data,
@@ -118,14 +119,18 @@ async def test_errors(
DOMAIN, context={"source": source}
)
- with patch(
- "homeassistant.components.vlc_telnet.config_flow.Client.connect",
- side_effect=connect_side_effect,
- ), patch(
- "homeassistant.components.vlc_telnet.config_flow.Client.login",
- side_effect=login_side_effect,
- ), patch(
- "homeassistant.components.vlc_telnet.config_flow.Client.disconnect",
+ with (
+ patch(
+ "homeassistant.components.vlc_telnet.config_flow.Client.connect",
+ side_effect=connect_side_effect,
+ ),
+ patch(
+ "homeassistant.components.vlc_telnet.config_flow.Client.login",
+ side_effect=login_side_effect,
+ ),
+ patch(
+ "homeassistant.components.vlc_telnet.config_flow.Client.disconnect",
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -158,14 +163,15 @@ async def test_reauth_flow(hass: HomeAssistant) -> None:
data=entry_data,
)
- with patch("homeassistant.components.vlc_telnet.config_flow.Client.connect"), patch(
- "homeassistant.components.vlc_telnet.config_flow.Client.login"
- ), patch(
- "homeassistant.components.vlc_telnet.config_flow.Client.disconnect"
- ), patch(
- "homeassistant.components.vlc_telnet.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("homeassistant.components.vlc_telnet.config_flow.Client.connect"),
+ patch("homeassistant.components.vlc_telnet.config_flow.Client.login"),
+ patch("homeassistant.components.vlc_telnet.config_flow.Client.disconnect"),
+ patch(
+ "homeassistant.components.vlc_telnet.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"password": "new-password"},
@@ -213,14 +219,18 @@ async def test_reauth_errors(
data=entry_data,
)
- with patch(
- "homeassistant.components.vlc_telnet.config_flow.Client.connect",
- side_effect=connect_side_effect,
- ), patch(
- "homeassistant.components.vlc_telnet.config_flow.Client.login",
- side_effect=login_side_effect,
- ), patch(
- "homeassistant.components.vlc_telnet.config_flow.Client.disconnect",
+ with (
+ patch(
+ "homeassistant.components.vlc_telnet.config_flow.Client.connect",
+ side_effect=connect_side_effect,
+ ),
+ patch(
+ "homeassistant.components.vlc_telnet.config_flow.Client.login",
+ side_effect=login_side_effect,
+ ),
+ patch(
+ "homeassistant.components.vlc_telnet.config_flow.Client.disconnect",
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -233,14 +243,15 @@ async def test_reauth_errors(
async def test_hassio_flow(hass: HomeAssistant) -> None:
"""Test successful hassio flow."""
- with patch("homeassistant.components.vlc_telnet.config_flow.Client.connect"), patch(
- "homeassistant.components.vlc_telnet.config_flow.Client.login"
- ), patch(
- "homeassistant.components.vlc_telnet.config_flow.Client.disconnect"
- ), patch(
- "homeassistant.components.vlc_telnet.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("homeassistant.components.vlc_telnet.config_flow.Client.connect"),
+ patch("homeassistant.components.vlc_telnet.config_flow.Client.login"),
+ patch("homeassistant.components.vlc_telnet.config_flow.Client.disconnect"),
+ patch(
+ "homeassistant.components.vlc_telnet.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
test_data = HassioServiceInfo(
config={
"password": "test-password",
@@ -310,14 +321,18 @@ async def test_hassio_errors(
login_side_effect: Exception | None,
) -> None:
"""Test we handle hassio errors."""
- with patch(
- "homeassistant.components.vlc_telnet.config_flow.Client.connect",
- side_effect=connect_side_effect,
- ), patch(
- "homeassistant.components.vlc_telnet.config_flow.Client.login",
- side_effect=login_side_effect,
- ), patch(
- "homeassistant.components.vlc_telnet.config_flow.Client.disconnect",
+ with (
+ patch(
+ "homeassistant.components.vlc_telnet.config_flow.Client.connect",
+ side_effect=connect_side_effect,
+ ),
+ patch(
+ "homeassistant.components.vlc_telnet.config_flow.Client.login",
+ side_effect=login_side_effect,
+ ),
+ patch(
+ "homeassistant.components.vlc_telnet.config_flow.Client.disconnect",
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
diff --git a/tests/components/vodafone_station/test_config_flow.py b/tests/components/vodafone_station/test_config_flow.py
index 6334979b742..f2619044861 100644
--- a/tests/components/vodafone_station/test_config_flow.py
+++ b/tests/components/vodafone_station/test_config_flow.py
@@ -20,13 +20,17 @@ from tests.common import MockConfigEntry
async def test_user(hass: HomeAssistant) -> None:
"""Test starting a flow by user."""
- with patch(
- "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.login",
- ), patch(
- "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.logout",
- ), patch(
- "homeassistant.components.vodafone_station.async_setup_entry"
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.login",
+ ),
+ patch(
+ "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.logout",
+ ),
+ patch(
+ "homeassistant.components.vodafone_station.async_setup_entry"
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
@@ -79,18 +83,23 @@ async def test_exception_connection(hass: HomeAssistant, side_effect, error) ->
assert result["errors"]["base"] == error
# Should be recoverable after hits error
- with patch(
- "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.get_devices_data",
- return_value={
- "wifi_user": "on|laptop|device-1|xx:xx:xx:xx:xx:xx|192.168.100.1||2.4G",
- "ethernet": "laptop|device-2|yy:yy:yy:yy:yy:yy|192.168.100.2|;",
- },
- ), patch(
- "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.login",
- ), patch(
- "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.logout",
- ), patch(
- "homeassistant.components.vodafone_station.async_setup_entry",
+ with (
+ patch(
+ "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.get_devices_data",
+ return_value={
+ "wifi_user": "on|laptop|device-1|xx:xx:xx:xx:xx:xx|192.168.100.1||2.4G",
+ "ethernet": "laptop|device-2|yy:yy:yy:yy:yy:yy|192.168.100.2|;",
+ },
+ ),
+ patch(
+ "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.login",
+ ),
+ patch(
+ "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.logout",
+ ),
+ patch(
+ "homeassistant.components.vodafone_station.async_setup_entry",
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -117,12 +126,16 @@ async def test_reauth_successful(hass: HomeAssistant) -> None:
mock_config = MockConfigEntry(domain=DOMAIN, data=MOCK_USER_DATA)
mock_config.add_to_hass(hass)
- with patch(
- "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.login",
- ), patch(
- "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.logout",
- ), patch(
- "homeassistant.components.vodafone_station.async_setup_entry",
+ with (
+ patch(
+ "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.login",
+ ),
+ patch(
+ "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.logout",
+ ),
+ patch(
+ "homeassistant.components.vodafone_station.async_setup_entry",
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -160,13 +173,17 @@ async def test_reauth_not_successful(hass: HomeAssistant, side_effect, error) ->
mock_config = MockConfigEntry(domain=DOMAIN, data=MOCK_USER_DATA)
mock_config.add_to_hass(hass)
- with patch(
- "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.login",
- side_effect=side_effect,
- ), patch(
- "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.logout",
- ), patch(
- "homeassistant.components.vodafone_station.async_setup_entry",
+ with (
+ patch(
+ "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.login",
+ side_effect=side_effect,
+ ),
+ patch(
+ "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.logout",
+ ),
+ patch(
+ "homeassistant.components.vodafone_station.async_setup_entry",
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -190,18 +207,23 @@ async def test_reauth_not_successful(hass: HomeAssistant, side_effect, error) ->
assert result["errors"]["base"] == error
# Should be recoverable after hits error
- with patch(
- "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.get_devices_data",
- return_value={
- "wifi_user": "on|laptop|device-1|xx:xx:xx:xx:xx:xx|192.168.100.1||2.4G",
- "ethernet": "laptop|device-2|yy:yy:yy:yy:yy:yy|192.168.100.2|;",
- },
- ), patch(
- "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.login",
- ), patch(
- "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.logout",
- ), patch(
- "homeassistant.components.vodafone_station.async_setup_entry",
+ with (
+ patch(
+ "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.get_devices_data",
+ return_value={
+ "wifi_user": "on|laptop|device-1|xx:xx:xx:xx:xx:xx|192.168.100.1||2.4G",
+ "ethernet": "laptop|device-2|yy:yy:yy:yy:yy:yy|192.168.100.2|;",
+ },
+ ),
+ patch(
+ "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.login",
+ ),
+ patch(
+ "homeassistant.components.vodafone_station.config_flow.VodafoneStationSercommApi.logout",
+ ),
+ patch(
+ "homeassistant.components.vodafone_station.async_setup_entry",
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/voip/test_sip.py b/tests/components/voip/test_sip.py
index 2e144b87ec0..769be768261 100644
--- a/tests/components/voip/test_sip.py
+++ b/tests/components/voip/test_sip.py
@@ -21,9 +21,10 @@ async def test_create_sip_server(hass: HomeAssistant, socket_enabled) -> None:
entry = result["result"]
await hass.async_block_till_done()
- with pytest.raises(OSError), socket.socket(
- socket.AF_INET, socket.SOCK_DGRAM
- ) as sock:
+ with (
+ pytest.raises(OSError),
+ socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock,
+ ):
# Server should have the port
sock.bind(("127.0.0.1", 5060))
@@ -41,9 +42,10 @@ async def test_create_sip_server(hass: HomeAssistant, socket_enabled) -> None:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.bind(("127.0.0.1", 5060))
- with pytest.raises(OSError), socket.socket(
- socket.AF_INET, socket.SOCK_DGRAM
- ) as sock:
+ with (
+ pytest.raises(OSError),
+ socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock,
+ ):
# Server should now have the new port
sock.bind(("127.0.0.1", 5061))
diff --git a/tests/components/voip/test_voip.py b/tests/components/voip/test_voip.py
index 3d34218e999..f5c5fde2518 100644
--- a/tests/components/voip/test_voip.py
+++ b/tests/components/voip/test_voip.py
@@ -95,15 +95,19 @@ async def test_pipeline(
assert media_source_id == _MEDIA_ID
return ("wav", _empty_wav())
- with patch(
- "homeassistant.components.assist_pipeline.vad.WebRtcVad.is_speech",
- new=is_speech,
- ), patch(
- "homeassistant.components.voip.voip.async_pipeline_from_audio_stream",
- new=async_pipeline_from_audio_stream,
- ), patch(
- "homeassistant.components.voip.voip.tts.async_get_media_source_audio",
- new=async_get_media_source_audio,
+ with (
+ patch(
+ "homeassistant.components.assist_pipeline.vad.WebRtcVad.is_speech",
+ new=is_speech,
+ ),
+ patch(
+ "homeassistant.components.voip.voip.async_pipeline_from_audio_stream",
+ new=async_pipeline_from_audio_stream,
+ ),
+ patch(
+ "homeassistant.components.voip.voip.tts.async_get_media_source_audio",
+ new=async_get_media_source_audio,
+ ),
):
rtp_protocol = voip.voip.PipelineRtpDatagramProtocol(
hass,
@@ -150,12 +154,15 @@ async def test_pipeline_timeout(hass: HomeAssistant, voip_device: VoIPDevice) ->
async def async_pipeline_from_audio_stream(*args, **kwargs):
await asyncio.sleep(10)
- with patch(
- "homeassistant.components.voip.voip.async_pipeline_from_audio_stream",
- new=async_pipeline_from_audio_stream,
- ), patch(
- "homeassistant.components.voip.voip.PipelineRtpDatagramProtocol._wait_for_speech",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.voip.voip.async_pipeline_from_audio_stream",
+ new=async_pipeline_from_audio_stream,
+ ),
+ patch(
+ "homeassistant.components.voip.voip.PipelineRtpDatagramProtocol._wait_for_speech",
+ return_value=True,
+ ),
):
rtp_protocol = voip.voip.PipelineRtpDatagramProtocol(
hass,
@@ -288,15 +295,19 @@ async def test_tts_timeout(
# Should time out immediately
return ("wav", _empty_wav())
- with patch(
- "homeassistant.components.assist_pipeline.vad.WebRtcVad.is_speech",
- new=is_speech,
- ), patch(
- "homeassistant.components.voip.voip.async_pipeline_from_audio_stream",
- new=async_pipeline_from_audio_stream,
- ), patch(
- "homeassistant.components.voip.voip.tts.async_get_media_source_audio",
- new=async_get_media_source_audio,
+ with (
+ patch(
+ "homeassistant.components.assist_pipeline.vad.WebRtcVad.is_speech",
+ new=is_speech,
+ ),
+ patch(
+ "homeassistant.components.voip.voip.async_pipeline_from_audio_stream",
+ new=async_pipeline_from_audio_stream,
+ ),
+ patch(
+ "homeassistant.components.voip.voip.tts.async_get_media_source_audio",
+ new=async_get_media_source_audio,
+ ),
):
rtp_protocol = voip.voip.PipelineRtpDatagramProtocol(
hass,
@@ -389,15 +400,19 @@ async def test_tts_wrong_extension(
# Should fail because it's not "wav"
return ("mp3", b"")
- with patch(
- "homeassistant.components.assist_pipeline.vad.WebRtcVad.is_speech",
- new=is_speech,
- ), patch(
- "homeassistant.components.voip.voip.async_pipeline_from_audio_stream",
- new=async_pipeline_from_audio_stream,
- ), patch(
- "homeassistant.components.voip.voip.tts.async_get_media_source_audio",
- new=async_get_media_source_audio,
+ with (
+ patch(
+ "homeassistant.components.assist_pipeline.vad.WebRtcVad.is_speech",
+ new=is_speech,
+ ),
+ patch(
+ "homeassistant.components.voip.voip.async_pipeline_from_audio_stream",
+ new=async_pipeline_from_audio_stream,
+ ),
+ patch(
+ "homeassistant.components.voip.voip.tts.async_get_media_source_audio",
+ new=async_get_media_source_audio,
+ ),
):
rtp_protocol = voip.voip.PipelineRtpDatagramProtocol(
hass,
@@ -487,15 +502,19 @@ async def test_tts_wrong_wav_format(
return ("wav", wav_io.getvalue())
- with patch(
- "homeassistant.components.assist_pipeline.vad.WebRtcVad.is_speech",
- new=is_speech,
- ), patch(
- "homeassistant.components.voip.voip.async_pipeline_from_audio_stream",
- new=async_pipeline_from_audio_stream,
- ), patch(
- "homeassistant.components.voip.voip.tts.async_get_media_source_audio",
- new=async_get_media_source_audio,
+ with (
+ patch(
+ "homeassistant.components.assist_pipeline.vad.WebRtcVad.is_speech",
+ new=is_speech,
+ ),
+ patch(
+ "homeassistant.components.voip.voip.async_pipeline_from_audio_stream",
+ new=async_pipeline_from_audio_stream,
+ ),
+ patch(
+ "homeassistant.components.voip.voip.tts.async_get_media_source_audio",
+ new=async_get_media_source_audio,
+ ),
):
rtp_protocol = voip.voip.PipelineRtpDatagramProtocol(
hass,
@@ -569,15 +588,19 @@ async def test_empty_tts_output(
)
)
- with patch(
- "homeassistant.components.assist_pipeline.vad.WebRtcVad.is_speech",
- new=is_speech,
- ), patch(
- "homeassistant.components.voip.voip.async_pipeline_from_audio_stream",
- new=async_pipeline_from_audio_stream,
- ), patch(
- "homeassistant.components.voip.voip.PipelineRtpDatagramProtocol._send_tts",
- ) as mock_send_tts:
+ with (
+ patch(
+ "homeassistant.components.assist_pipeline.vad.WebRtcVad.is_speech",
+ new=is_speech,
+ ),
+ patch(
+ "homeassistant.components.voip.voip.async_pipeline_from_audio_stream",
+ new=async_pipeline_from_audio_stream,
+ ),
+ patch(
+ "homeassistant.components.voip.voip.PipelineRtpDatagramProtocol._send_tts",
+ ) as mock_send_tts,
+ ):
rtp_protocol = voip.voip.PipelineRtpDatagramProtocol(
hass,
hass.config.language,
diff --git a/tests/components/volumio/test_config_flow.py b/tests/components/volumio/test_config_flow.py
index 93469a02205..7d185161d0a 100644
--- a/tests/components/volumio/test_config_flow.py
+++ b/tests/components/volumio/test_config_flow.py
@@ -46,13 +46,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.volumio.config_flow.Volumio.get_system_info",
- return_value=TEST_SYSTEM_INFO,
- ), patch(
- "homeassistant.components.volumio.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.volumio.config_flow.Volumio.get_system_info",
+ return_value=TEST_SYSTEM_INFO,
+ ),
+ patch(
+ "homeassistant.components.volumio.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
TEST_CONNECTION,
@@ -84,12 +87,15 @@ async def test_form_updates_unique_id(hass: HomeAssistant) -> None:
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "homeassistant.components.volumio.config_flow.Volumio.get_system_info",
- return_value=TEST_SYSTEM_INFO,
- ), patch(
- "homeassistant.components.volumio.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.volumio.config_flow.Volumio.get_system_info",
+ return_value=TEST_SYSTEM_INFO,
+ ),
+ patch(
+ "homeassistant.components.volumio.async_setup_entry",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -111,13 +117,16 @@ async def test_empty_system_info(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.volumio.config_flow.Volumio.get_system_info",
- return_value={},
- ), patch(
- "homeassistant.components.volumio.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.volumio.config_flow.Volumio.get_system_info",
+ return_value={},
+ ),
+ patch(
+ "homeassistant.components.volumio.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
TEST_CONNECTION,
@@ -181,13 +190,16 @@ async def test_discovery(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_ZEROCONF}, data=TEST_DISCOVERY
)
- with patch(
- "homeassistant.components.volumio.config_flow.Volumio.get_system_info",
- return_value=TEST_SYSTEM_INFO,
- ), patch(
- "homeassistant.components.volumio.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.volumio.config_flow.Volumio.get_system_info",
+ return_value=TEST_SYSTEM_INFO,
+ ),
+ patch(
+ "homeassistant.components.volumio.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={},
diff --git a/tests/components/volvooncall/test_config_flow.py b/tests/components/volvooncall/test_config_flow.py
index e8b9de9a07b..3c866da58ea 100644
--- a/tests/components/volvooncall/test_config_flow.py
+++ b/tests/components/volvooncall/test_config_flow.py
@@ -20,10 +20,13 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert len(result["errors"]) == 0
- with patch("volvooncall.Connection.get"), patch(
- "homeassistant.components.volvooncall.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("volvooncall.Connection.get"),
+ patch(
+ "homeassistant.components.volvooncall.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -86,9 +89,12 @@ async def test_flow_already_configured(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert len(result["errors"]) == 0
- with patch("volvooncall.Connection.get"), patch(
- "homeassistant.components.volvooncall.async_setup_entry",
- return_value=True,
+ with (
+ patch("volvooncall.Connection.get"),
+ patch(
+ "homeassistant.components.volvooncall.async_setup_entry",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/vultr/test_switch.py b/tests/components/vultr/test_switch.py
index 9f98447af41..f75021efa05 100644
--- a/tests/components/vultr/test_switch.py
+++ b/tests/components/vultr/test_switch.py
@@ -99,10 +99,13 @@ def test_switch(hass: HomeAssistant, hass_devices: list[vultr.VultrSwitch]):
@pytest.mark.usefixtures("valid_config")
def test_turn_on(hass: HomeAssistant, hass_devices: list[vultr.VultrSwitch]):
"""Test turning a subscription on."""
- with patch(
- "vultr.Vultr.server_list",
- return_value=json.loads(load_fixture("server_list.json", "vultr")),
- ), patch("vultr.Vultr.server_start") as mock_start:
+ with (
+ patch(
+ "vultr.Vultr.server_list",
+ return_value=json.loads(load_fixture("server_list.json", "vultr")),
+ ),
+ patch("vultr.Vultr.server_start") as mock_start,
+ ):
for device in hass_devices:
if device.name == "Failed Server":
device.update()
@@ -115,10 +118,13 @@ def test_turn_on(hass: HomeAssistant, hass_devices: list[vultr.VultrSwitch]):
@pytest.mark.usefixtures("valid_config")
def test_turn_off(hass: HomeAssistant, hass_devices: list[vultr.VultrSwitch]):
"""Test turning a subscription off."""
- with patch(
- "vultr.Vultr.server_list",
- return_value=json.loads(load_fixture("server_list.json", "vultr")),
- ), patch("vultr.Vultr.server_halt") as mock_halt:
+ with (
+ patch(
+ "vultr.Vultr.server_list",
+ return_value=json.loads(load_fixture("server_list.json", "vultr")),
+ ),
+ patch("vultr.Vultr.server_halt") as mock_halt,
+ ):
for device in hass_devices:
if device.name == "A Server":
device.update()
diff --git a/tests/components/waqi/test_config_flow.py b/tests/components/waqi/test_config_flow.py
index f19d0991f46..712ad8dd39e 100644
--- a/tests/components/waqi/test_config_flow.py
+++ b/tests/components/waqi/test_config_flow.py
@@ -54,12 +54,15 @@ async def test_full_map_flow(
)
assert result["type"] == FlowResultType.FORM
- with patch(
- "aiowaqi.WAQIClient.authenticate",
- ), patch(
- "aiowaqi.WAQIClient.get_by_ip",
- return_value=WAQIAirQuality.from_dict(
- json.loads(load_fixture("waqi/air_quality_sensor.json"))
+ with (
+ patch(
+ "aiowaqi.WAQIClient.authenticate",
+ ),
+ patch(
+ "aiowaqi.WAQIClient.get_by_ip",
+ return_value=WAQIAirQuality.from_dict(
+ json.loads(load_fixture("waqi/air_quality_sensor.json"))
+ ),
),
):
result = await hass.config_entries.flow.async_configure(
@@ -71,17 +74,21 @@ async def test_full_map_flow(
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == method
- with patch(
- "aiowaqi.WAQIClient.authenticate",
- ), patch(
- "aiowaqi.WAQIClient.get_by_coordinates",
- return_value=WAQIAirQuality.from_dict(
- json.loads(load_fixture("waqi/air_quality_sensor.json"))
+ with (
+ patch(
+ "aiowaqi.WAQIClient.authenticate",
),
- ), patch(
- "aiowaqi.WAQIClient.get_by_station_number",
- return_value=WAQIAirQuality.from_dict(
- json.loads(load_fixture("waqi/air_quality_sensor.json"))
+ patch(
+ "aiowaqi.WAQIClient.get_by_coordinates",
+ return_value=WAQIAirQuality.from_dict(
+ json.loads(load_fixture("waqi/air_quality_sensor.json"))
+ ),
+ ),
+ patch(
+ "aiowaqi.WAQIClient.get_by_station_number",
+ return_value=WAQIAirQuality.from_dict(
+ json.loads(load_fixture("waqi/air_quality_sensor.json"))
+ ),
),
):
result = await hass.config_entries.flow.async_configure(
@@ -115,11 +122,14 @@ async def test_flow_errors(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch(
- "aiowaqi.WAQIClient.authenticate",
- ), patch(
- "aiowaqi.WAQIClient.get_by_ip",
- side_effect=exception,
+ with (
+ patch(
+ "aiowaqi.WAQIClient.authenticate",
+ ),
+ patch(
+ "aiowaqi.WAQIClient.get_by_ip",
+ side_effect=exception,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -130,12 +140,15 @@ async def test_flow_errors(
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {"base": error}
- with patch(
- "aiowaqi.WAQIClient.authenticate",
- ), patch(
- "aiowaqi.WAQIClient.get_by_ip",
- return_value=WAQIAirQuality.from_dict(
- json.loads(load_fixture("waqi/air_quality_sensor.json"))
+ with (
+ patch(
+ "aiowaqi.WAQIClient.authenticate",
+ ),
+ patch(
+ "aiowaqi.WAQIClient.get_by_ip",
+ return_value=WAQIAirQuality.from_dict(
+ json.loads(load_fixture("waqi/air_quality_sensor.json"))
+ ),
),
):
result = await hass.config_entries.flow.async_configure(
@@ -147,12 +160,15 @@ async def test_flow_errors(
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "map"
- with patch(
- "aiowaqi.WAQIClient.authenticate",
- ), patch(
- "aiowaqi.WAQIClient.get_by_coordinates",
- return_value=WAQIAirQuality.from_dict(
- json.loads(load_fixture("waqi/air_quality_sensor.json"))
+ with (
+ patch(
+ "aiowaqi.WAQIClient.authenticate",
+ ),
+ patch(
+ "aiowaqi.WAQIClient.get_by_coordinates",
+ return_value=WAQIAirQuality.from_dict(
+ json.loads(load_fixture("waqi/air_quality_sensor.json"))
+ ),
),
):
result = await hass.config_entries.flow.async_configure(
@@ -217,12 +233,15 @@ async def test_error_in_second_step(
)
assert result["type"] == FlowResultType.FORM
- with patch(
- "aiowaqi.WAQIClient.authenticate",
- ), patch(
- "aiowaqi.WAQIClient.get_by_ip",
- return_value=WAQIAirQuality.from_dict(
- json.loads(load_fixture("waqi/air_quality_sensor.json"))
+ with (
+ patch(
+ "aiowaqi.WAQIClient.authenticate",
+ ),
+ patch(
+ "aiowaqi.WAQIClient.get_by_ip",
+ return_value=WAQIAirQuality.from_dict(
+ json.loads(load_fixture("waqi/air_quality_sensor.json"))
+ ),
),
):
result = await hass.config_entries.flow.async_configure(
@@ -234,10 +253,12 @@ async def test_error_in_second_step(
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == method
- with patch(
- "aiowaqi.WAQIClient.authenticate",
- ), patch("aiowaqi.WAQIClient.get_by_coordinates", side_effect=exception), patch(
- "aiowaqi.WAQIClient.get_by_station_number", side_effect=exception
+ with (
+ patch(
+ "aiowaqi.WAQIClient.authenticate",
+ ),
+ patch("aiowaqi.WAQIClient.get_by_coordinates", side_effect=exception),
+ patch("aiowaqi.WAQIClient.get_by_station_number", side_effect=exception),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -248,17 +269,21 @@ async def test_error_in_second_step(
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {"base": error}
- with patch(
- "aiowaqi.WAQIClient.authenticate",
- ), patch(
- "aiowaqi.WAQIClient.get_by_coordinates",
- return_value=WAQIAirQuality.from_dict(
- json.loads(load_fixture("waqi/air_quality_sensor.json"))
+ with (
+ patch(
+ "aiowaqi.WAQIClient.authenticate",
),
- ), patch(
- "aiowaqi.WAQIClient.get_by_station_number",
- return_value=WAQIAirQuality.from_dict(
- json.loads(load_fixture("waqi/air_quality_sensor.json"))
+ patch(
+ "aiowaqi.WAQIClient.get_by_coordinates",
+ return_value=WAQIAirQuality.from_dict(
+ json.loads(load_fixture("waqi/air_quality_sensor.json"))
+ ),
+ ),
+ patch(
+ "aiowaqi.WAQIClient.get_by_station_number",
+ return_value=WAQIAirQuality.from_dict(
+ json.loads(load_fixture("waqi/air_quality_sensor.json"))
+ ),
),
):
result = await hass.config_entries.flow.async_configure(
diff --git a/tests/components/watttime/conftest.py b/tests/components/watttime/conftest.py
index 72bdc2d3419..0b7403d45fc 100644
--- a/tests/components/watttime/conftest.py
+++ b/tests/components/watttime/conftest.py
@@ -102,12 +102,16 @@ def get_grid_region_fixture(data_grid_region):
@pytest.fixture(name="setup_watttime")
async def setup_watttime_fixture(hass, client, config_auth, config_coordinates):
"""Define a fixture to set up WattTime."""
- with patch(
- "homeassistant.components.watttime.Client.async_login", return_value=client
- ), patch(
- "homeassistant.components.watttime.config_flow.Client.async_login",
- return_value=client,
- ), patch("homeassistant.components.watttime.PLATFORMS", []):
+ with (
+ patch(
+ "homeassistant.components.watttime.Client.async_login", return_value=client
+ ),
+ patch(
+ "homeassistant.components.watttime.config_flow.Client.async_login",
+ return_value=client,
+ ),
+ patch("homeassistant.components.watttime.PLATFORMS", []),
+ ):
assert await async_setup_component(
hass, DOMAIN, {**config_auth, **config_coordinates}
)
diff --git a/tests/components/weather/test_intent.py b/tests/components/weather/test_intent.py
index a562838edf3..1fde5882d6e 100644
--- a/tests/components/weather/test_intent.py
+++ b/tests/components/weather/test_intent.py
@@ -103,7 +103,8 @@ async def test_get_weather_no_state(hass: HomeAssistant) -> None:
assert response.response_type == intent.IntentResponseType.QUERY_ANSWER
# Failure without state
- with patch("homeassistant.core.StateMachine.get", return_value=None), pytest.raises(
- intent.IntentHandleError
+ with (
+ patch("homeassistant.core.StateMachine.get", return_value=None),
+ pytest.raises(intent.IntentHandleError),
):
await intent.async_handle(hass, "test", weather_intent.INTENT_GET_WEATHER, {})
diff --git a/tests/components/weatherkit/__init__.py b/tests/components/weatherkit/__init__.py
index 5450205d579..99c856a7e37 100644
--- a/tests/components/weatherkit/__init__.py
+++ b/tests/components/weatherkit/__init__.py
@@ -58,12 +58,15 @@ async def init_integration(
else:
available_data_sets.append(DataSetType.HOURLY_FORECAST)
- with patch(
- "homeassistant.components.weatherkit.WeatherKitApiClient.get_weather_data",
- return_value=weather_response,
- ), patch(
- "homeassistant.components.weatherkit.WeatherKitApiClient.get_availability",
- return_value=available_data_sets,
+ with (
+ patch(
+ "homeassistant.components.weatherkit.WeatherKitApiClient.get_weather_data",
+ return_value=weather_response,
+ ),
+ patch(
+ "homeassistant.components.weatherkit.WeatherKitApiClient.get_availability",
+ return_value=available_data_sets,
+ ),
):
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
diff --git a/tests/components/weatherkit/test_setup.py b/tests/components/weatherkit/test_setup.py
index 479d08be20d..c121f0cc5c1 100644
--- a/tests/components/weatherkit/test_setup.py
+++ b/tests/components/weatherkit/test_setup.py
@@ -25,12 +25,15 @@ async def test_auth_error_handling(hass: HomeAssistant) -> None:
data=EXAMPLE_CONFIG_DATA,
)
- with patch(
- "homeassistant.components.weatherkit.WeatherKitApiClient.get_weather_data",
- side_effect=WeatherKitApiClientAuthenticationError,
- ), patch(
- "homeassistant.components.weatherkit.WeatherKitApiClient.get_availability",
- side_effect=WeatherKitApiClientAuthenticationError,
+ with (
+ patch(
+ "homeassistant.components.weatherkit.WeatherKitApiClient.get_weather_data",
+ side_effect=WeatherKitApiClientAuthenticationError,
+ ),
+ patch(
+ "homeassistant.components.weatherkit.WeatherKitApiClient.get_availability",
+ side_effect=WeatherKitApiClientAuthenticationError,
+ ),
):
entry.add_to_hass(hass)
setup_result = await hass.config_entries.async_setup(entry.entry_id)
@@ -48,12 +51,15 @@ async def test_client_error_handling(hass: HomeAssistant) -> None:
data=EXAMPLE_CONFIG_DATA,
)
- with patch(
- "homeassistant.components.weatherkit.WeatherKitApiClient.get_weather_data",
- side_effect=WeatherKitApiClientError,
- ), patch(
- "homeassistant.components.weatherkit.WeatherKitApiClient.get_availability",
- side_effect=WeatherKitApiClientError,
+ with (
+ patch(
+ "homeassistant.components.weatherkit.WeatherKitApiClient.get_weather_data",
+ side_effect=WeatherKitApiClientError,
+ ),
+ patch(
+ "homeassistant.components.weatherkit.WeatherKitApiClient.get_availability",
+ side_effect=WeatherKitApiClientError,
+ ),
):
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
diff --git a/tests/components/websocket_api/test_http.py b/tests/components/websocket_api/test_http.py
index 6c2646f369e..db186e4811b 100644
--- a/tests/components/websocket_api/test_http.py
+++ b/tests/components/websocket_api/test_http.py
@@ -371,10 +371,13 @@ async def test_prepare_fail(
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test failing to prepare."""
- with patch(
- "homeassistant.components.websocket_api.http.web.WebSocketResponse.prepare",
- side_effect=(TimeoutError, web.WebSocketResponse.prepare),
- ), pytest.raises(ServerDisconnectedError):
+ with (
+ patch(
+ "homeassistant.components.websocket_api.http.web.WebSocketResponse.prepare",
+ side_effect=(TimeoutError, web.WebSocketResponse.prepare),
+ ),
+ pytest.raises(ServerDisconnectedError),
+ ):
await hass_ws_client(hass)
assert "Timeout preparing request" in caplog.text
diff --git a/tests/components/wemo/conftest.py b/tests/components/wemo/conftest.py
index cdf1e7deb68..1316c37b62b 100644
--- a/tests/components/wemo/conftest.py
+++ b/tests/components/wemo/conftest.py
@@ -82,8 +82,9 @@ def create_pywemo_device(pywemo_registry, pywemo_model):
device.switch_state = 0
url = f"http://{MOCK_HOST}:{MOCK_PORT}/setup.xml"
- with patch("pywemo.setup_url_for_address", return_value=url), patch(
- "pywemo.discovery.device_from_description", return_value=device
+ with (
+ patch("pywemo.setup_url_for_address", return_value=url),
+ patch("pywemo.discovery.device_from_description", return_value=device),
):
yield device
diff --git a/tests/components/wemo/test_init.py b/tests/components/wemo/test_init.py
index 5512c2ee989..bf41e703190 100644
--- a/tests/components/wemo/test_init.py
+++ b/tests/components/wemo/test_init.py
@@ -211,13 +211,15 @@ async def test_discovery(hass: HomeAssistant, pywemo_registry) -> None:
pywemo_devices = [create_device(0), create_device(1)]
# Setup the component and start discovery.
- with patch(
- "pywemo.discover_devices", return_value=pywemo_devices
- ) as mock_discovery, patch(
- "homeassistant.components.wemo.WemoDiscovery.discover_statics"
- ) as mock_discover_statics, patch(
- "homeassistant.components.wemo.binary_sensor.async_wemo_dispatcher_connect",
- side_effect=async_connect,
+ with (
+ patch("pywemo.discover_devices", return_value=pywemo_devices) as mock_discovery,
+ patch(
+ "homeassistant.components.wemo.WemoDiscovery.discover_statics"
+ ) as mock_discover_statics,
+ patch(
+ "homeassistant.components.wemo.binary_sensor.async_wemo_dispatcher_connect",
+ side_effect=async_connect,
+ ),
):
assert await async_setup_component(
hass, DOMAIN, {DOMAIN: {CONF_DISCOVERY: True}}
diff --git a/tests/components/whirlpool/test_config_flow.py b/tests/components/whirlpool/test_config_flow.py
index d164bff6a61..273f0e6737d 100644
--- a/tests/components/whirlpool/test_config_flow.py
+++ b/tests/components/whirlpool/test_config_flow.py
@@ -28,20 +28,27 @@ async def test_form(hass: HomeAssistant, region, brand) -> None:
assert result["type"] == "form"
assert result["step_id"] == config_entries.SOURCE_USER
- with patch("homeassistant.components.whirlpool.config_flow.Auth.do_auth"), patch(
- "homeassistant.components.whirlpool.config_flow.Auth.is_access_token_valid",
- return_value=True,
- ), patch(
- "homeassistant.components.whirlpool.config_flow.BackendSelector"
- ) as mock_backend_selector, patch(
- "homeassistant.components.whirlpool.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.whirlpool.config_flow.AppliancesManager.aircons",
- return_value=["test"],
- ), patch(
- "homeassistant.components.whirlpool.config_flow.AppliancesManager.fetch_appliances",
- return_value=True,
+ with (
+ patch("homeassistant.components.whirlpool.config_flow.Auth.do_auth"),
+ patch(
+ "homeassistant.components.whirlpool.config_flow.Auth.is_access_token_valid",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.whirlpool.config_flow.BackendSelector"
+ ) as mock_backend_selector,
+ patch(
+ "homeassistant.components.whirlpool.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.whirlpool.config_flow.AppliancesManager.aircons",
+ return_value=["test"],
+ ),
+ patch(
+ "homeassistant.components.whirlpool.config_flow.AppliancesManager.fetch_appliances",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -66,9 +73,12 @@ async def test_form_invalid_auth(hass: HomeAssistant, region, brand) -> None:
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with patch("homeassistant.components.whirlpool.config_flow.Auth.do_auth"), patch(
- "homeassistant.components.whirlpool.config_flow.Auth.is_access_token_valid",
- return_value=False,
+ with (
+ patch("homeassistant.components.whirlpool.config_flow.Auth.do_auth"),
+ patch(
+ "homeassistant.components.whirlpool.config_flow.Auth.is_access_token_valid",
+ return_value=False,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -157,15 +167,20 @@ async def test_form_already_configured(hass: HomeAssistant, region, brand) -> No
assert result["type"] == "form"
assert result["step_id"] == config_entries.SOURCE_USER
- with patch("homeassistant.components.whirlpool.config_flow.Auth.do_auth"), patch(
- "homeassistant.components.whirlpool.config_flow.Auth.is_access_token_valid",
- return_value=True,
- ), patch(
- "homeassistant.components.whirlpool.config_flow.AppliancesManager.aircons",
- return_value=["test"],
- ), patch(
- "homeassistant.components.whirlpool.config_flow.AppliancesManager.fetch_appliances",
- return_value=True,
+ with (
+ patch("homeassistant.components.whirlpool.config_flow.Auth.do_auth"),
+ patch(
+ "homeassistant.components.whirlpool.config_flow.Auth.is_access_token_valid",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.whirlpool.config_flow.AppliancesManager.aircons",
+ return_value=["test"],
+ ),
+ patch(
+ "homeassistant.components.whirlpool.config_flow.AppliancesManager.fetch_appliances",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -190,12 +205,16 @@ async def test_no_appliances_flow(hass: HomeAssistant, region, brand) -> None:
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == config_entries.SOURCE_USER
- with patch("homeassistant.components.whirlpool.config_flow.Auth.do_auth"), patch(
- "homeassistant.components.whirlpool.config_flow.Auth.is_access_token_valid",
- return_value=True,
- ), patch(
- "homeassistant.components.whirlpool.config_flow.AppliancesManager.fetch_appliances",
- return_value=True,
+ with (
+ patch("homeassistant.components.whirlpool.config_flow.Auth.do_auth"),
+ patch(
+ "homeassistant.components.whirlpool.config_flow.Auth.is_access_token_valid",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.whirlpool.config_flow.AppliancesManager.fetch_appliances",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -230,18 +249,24 @@ async def test_reauth_flow(hass: HomeAssistant, region, brand) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.whirlpool.async_setup_entry",
- return_value=True,
- ), patch("homeassistant.components.whirlpool.config_flow.Auth.do_auth"), patch(
- "homeassistant.components.whirlpool.config_flow.Auth.is_access_token_valid",
- return_value=True,
- ), patch(
- "homeassistant.components.whirlpool.config_flow.AppliancesManager.aircons",
- return_value=["test"],
- ), patch(
- "homeassistant.components.whirlpool.config_flow.AppliancesManager.fetch_appliances",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.whirlpool.async_setup_entry",
+ return_value=True,
+ ),
+ patch("homeassistant.components.whirlpool.config_flow.Auth.do_auth"),
+ patch(
+ "homeassistant.components.whirlpool.config_flow.Auth.is_access_token_valid",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.whirlpool.config_flow.AppliancesManager.aircons",
+ return_value=["test"],
+ ),
+ patch(
+ "homeassistant.components.whirlpool.config_flow.AppliancesManager.fetch_appliances",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -287,12 +312,16 @@ async def test_reauth_flow_auth_error(hass: HomeAssistant, region, brand) -> Non
assert result["step_id"] == "reauth_confirm"
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.whirlpool.async_setup_entry",
- return_value=True,
- ), patch("homeassistant.components.whirlpool.config_flow.Auth.do_auth"), patch(
- "homeassistant.components.whirlpool.config_flow.Auth.is_access_token_valid",
- return_value=False,
+ with (
+ patch(
+ "homeassistant.components.whirlpool.async_setup_entry",
+ return_value=True,
+ ),
+ patch("homeassistant.components.whirlpool.config_flow.Auth.do_auth"),
+ patch(
+ "homeassistant.components.whirlpool.config_flow.Auth.is_access_token_valid",
+ return_value=False,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -330,15 +359,19 @@ async def test_reauth_flow_connnection_error(
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.whirlpool.async_setup_entry",
- return_value=True,
- ), patch(
- "homeassistant.components.whirlpool.config_flow.Auth.do_auth",
- side_effect=ClientConnectionError,
- ), patch(
- "homeassistant.components.whirlpool.config_flow.Auth.is_access_token_valid",
- return_value=False,
+ with (
+ patch(
+ "homeassistant.components.whirlpool.async_setup_entry",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.whirlpool.config_flow.Auth.do_auth",
+ side_effect=ClientConnectionError,
+ ),
+ patch(
+ "homeassistant.components.whirlpool.config_flow.Auth.is_access_token_valid",
+ return_value=False,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
diff --git a/tests/components/whois/conftest.py b/tests/components/whois/conftest.py
index c9d25e24b13..457c06db598 100644
--- a/tests/components/whois/conftest.py
+++ b/tests/components/whois/conftest.py
@@ -41,10 +41,11 @@ def mock_setup_entry() -> Generator[AsyncMock, None, None]:
@pytest.fixture
def mock_whois() -> Generator[MagicMock, None, None]:
"""Return a mocked query."""
- with patch(
- "homeassistant.components.whois.whois_query",
- ) as whois_mock, patch(
- "homeassistant.components.whois.config_flow.whois.query", new=whois_mock
+ with (
+ patch(
+ "homeassistant.components.whois.whois_query",
+ ) as whois_mock,
+ patch("homeassistant.components.whois.config_flow.whois.query", new=whois_mock),
):
domain = whois_mock.return_value
domain.abuse_contact = "abuse@example.com"
diff --git a/tests/components/withings/conftest.py b/tests/components/withings/conftest.py
index 781024c86f7..66dd65efccb 100644
--- a/tests/components/withings/conftest.py
+++ b/tests/components/withings/conftest.py
@@ -174,11 +174,14 @@ def disable_webhook_delay():
"""Disable webhook delay."""
mock = AsyncMock()
- with patch(
- "homeassistant.components.withings.SUBSCRIBE_DELAY",
- timedelta(seconds=0),
- ), patch(
- "homeassistant.components.withings.UNSUBSCRIBE_DELAY",
- timedelta(seconds=0),
+ with (
+ patch(
+ "homeassistant.components.withings.SUBSCRIBE_DELAY",
+ timedelta(seconds=0),
+ ),
+ patch(
+ "homeassistant.components.withings.UNSUBSCRIBE_DELAY",
+ timedelta(seconds=0),
+ ),
):
yield mock
diff --git a/tests/components/withings/test_diagnostics.py b/tests/components/withings/test_diagnostics.py
index 9d8dc03e52d..d607584df7b 100644
--- a/tests/components/withings/test_diagnostics.py
+++ b/tests/components/withings/test_diagnostics.py
@@ -56,21 +56,26 @@ async def test_diagnostics_cloudhook_instance(
freezer: FrozenDateTimeFactory,
) -> None:
"""Test diagnostics."""
- with patch(
- "homeassistant.components.cloud.async_is_logged_in", return_value=True
- ), patch(
- "homeassistant.components.cloud.async_is_connected", return_value=True
- ), patch(
- "homeassistant.components.cloud.async_active_subscription", return_value=True
- ), patch(
- "homeassistant.components.cloud.async_create_cloudhook",
- return_value="https://hooks.nabu.casa/ABCD",
- ), patch(
- "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
- ), patch(
- "homeassistant.components.cloud.async_delete_cloudhook",
- ), patch(
- "homeassistant.components.withings.webhook_generate_url",
+ with (
+ patch("homeassistant.components.cloud.async_is_logged_in", return_value=True),
+ patch("homeassistant.components.cloud.async_is_connected", return_value=True),
+ patch(
+ "homeassistant.components.cloud.async_active_subscription",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.cloud.async_create_cloudhook",
+ return_value="https://hooks.nabu.casa/ABCD",
+ ),
+ patch(
+ "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
+ ),
+ patch(
+ "homeassistant.components.cloud.async_delete_cloudhook",
+ ),
+ patch(
+ "homeassistant.components.withings.webhook_generate_url",
+ ),
):
await setup_integration(hass, webhook_config_entry)
await prepare_webhook_setup(hass, freezer)
diff --git a/tests/components/withings/test_init.py b/tests/components/withings/test_init.py
index c8bebe854eb..eb089f44216 100644
--- a/tests/components/withings/test_init.py
+++ b/tests/components/withings/test_init.py
@@ -295,19 +295,21 @@ async def test_setup_with_cloudhook(
await mock_cloud(hass)
await hass.async_block_till_done()
- with patch(
- "homeassistant.components.cloud.async_is_logged_in", return_value=True
- ), patch(
- "homeassistant.components.cloud.async_is_connected", return_value=True
- ), patch.object(cloud, "async_active_subscription", return_value=True), patch(
- "homeassistant.components.cloud.async_create_cloudhook",
- return_value="https://hooks.nabu.casa/ABCD",
- ) as fake_create_cloudhook, patch(
- "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
- ), patch(
- "homeassistant.components.cloud.async_delete_cloudhook"
- ) as fake_delete_cloudhook, patch(
- "homeassistant.components.withings.webhook_generate_url"
+ with (
+ patch("homeassistant.components.cloud.async_is_logged_in", return_value=True),
+ patch("homeassistant.components.cloud.async_is_connected", return_value=True),
+ patch.object(cloud, "async_active_subscription", return_value=True),
+ patch(
+ "homeassistant.components.cloud.async_create_cloudhook",
+ return_value="https://hooks.nabu.casa/ABCD",
+ ) as fake_create_cloudhook,
+ patch(
+ "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
+ ),
+ patch(
+ "homeassistant.components.cloud.async_delete_cloudhook"
+ ) as fake_delete_cloudhook,
+ patch("homeassistant.components.withings.webhook_generate_url"),
):
await setup_integration(hass, cloudhook_config_entry)
@@ -338,20 +340,24 @@ async def test_removing_entry_with_cloud_unavailable(
await mock_cloud(hass)
await hass.async_block_till_done()
- with patch(
- "homeassistant.components.cloud.async_is_logged_in", return_value=True
- ), patch(
- "homeassistant.components.cloud.async_is_connected", return_value=True
- ), patch.object(cloud, "async_active_subscription", return_value=True), patch(
- "homeassistant.components.cloud.async_create_cloudhook",
- return_value="https://hooks.nabu.casa/ABCD",
- ), patch(
- "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
- ), patch(
- "homeassistant.components.cloud.async_delete_cloudhook",
- side_effect=CloudNotAvailable(),
- ), patch(
- "homeassistant.components.withings.webhook_generate_url",
+ with (
+ patch("homeassistant.components.cloud.async_is_logged_in", return_value=True),
+ patch("homeassistant.components.cloud.async_is_connected", return_value=True),
+ patch.object(cloud, "async_active_subscription", return_value=True),
+ patch(
+ "homeassistant.components.cloud.async_create_cloudhook",
+ return_value="https://hooks.nabu.casa/ABCD",
+ ),
+ patch(
+ "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
+ ),
+ patch(
+ "homeassistant.components.cloud.async_delete_cloudhook",
+ side_effect=CloudNotAvailable(),
+ ),
+ patch(
+ "homeassistant.components.withings.webhook_generate_url",
+ ),
):
await setup_integration(hass, cloudhook_config_entry)
@@ -377,19 +383,21 @@ async def test_setup_with_cloud(
await mock_cloud(hass)
await hass.async_block_till_done()
- with patch(
- "homeassistant.components.cloud.async_is_logged_in", return_value=True
- ), patch.object(cloud, "async_is_connected", return_value=True), patch.object(
- cloud, "async_active_subscription", return_value=True
- ), patch(
- "homeassistant.components.cloud.async_create_cloudhook",
- return_value="https://hooks.nabu.casa/ABCD",
- ) as fake_create_cloudhook, patch(
- "homeassistant.components.withings.async_get_config_entry_implementation",
- ), patch(
- "homeassistant.components.cloud.async_delete_cloudhook"
- ) as fake_delete_cloudhook, patch(
- "homeassistant.components.withings.webhook_generate_url"
+ with (
+ patch("homeassistant.components.cloud.async_is_logged_in", return_value=True),
+ patch.object(cloud, "async_is_connected", return_value=True),
+ patch.object(cloud, "async_active_subscription", return_value=True),
+ patch(
+ "homeassistant.components.cloud.async_create_cloudhook",
+ return_value="https://hooks.nabu.casa/ABCD",
+ ) as fake_create_cloudhook,
+ patch(
+ "homeassistant.components.withings.async_get_config_entry_implementation",
+ ),
+ patch(
+ "homeassistant.components.cloud.async_delete_cloudhook"
+ ) as fake_delete_cloudhook,
+ patch("homeassistant.components.withings.webhook_generate_url"),
):
await setup_integration(hass, webhook_config_entry)
await prepare_webhook_setup(hass, freezer)
@@ -426,14 +434,18 @@ async def test_setup_no_webhook(
) -> None:
"""Test if set up with cloud link and without https."""
hass.config.components.add("cloud")
- with patch(
- "homeassistant.helpers.network.get_url",
- return_value="http://example.nabu.casa",
- ), patch(
- "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
- ), patch(
- "homeassistant.components.withings.webhook_generate_url"
- ) as mock_async_generate_url:
+ with (
+ patch(
+ "homeassistant.helpers.network.get_url",
+ return_value="http://example.nabu.casa",
+ ),
+ patch(
+ "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation",
+ ),
+ patch(
+ "homeassistant.components.withings.webhook_generate_url"
+ ) as mock_async_generate_url,
+ ):
mock_async_generate_url.return_value = url
await setup_integration(hass, webhook_config_entry)
await prepare_webhook_setup(hass, freezer)
@@ -455,19 +467,23 @@ async def test_cloud_disconnect(
await mock_cloud(hass)
await hass.async_block_till_done()
- with patch(
- "homeassistant.components.cloud.async_is_logged_in", return_value=True
- ), patch.object(cloud, "async_is_connected", return_value=True), patch.object(
- cloud, "async_active_subscription", return_value=True
- ), patch(
- "homeassistant.components.cloud.async_create_cloudhook",
- return_value="https://hooks.nabu.casa/ABCD",
- ), patch(
- "homeassistant.components.withings.async_get_config_entry_implementation",
- ), patch(
- "homeassistant.components.cloud.async_delete_cloudhook",
- ), patch(
- "homeassistant.components.withings.webhook_generate_url",
+ with (
+ patch("homeassistant.components.cloud.async_is_logged_in", return_value=True),
+ patch.object(cloud, "async_is_connected", return_value=True),
+ patch.object(cloud, "async_active_subscription", return_value=True),
+ patch(
+ "homeassistant.components.cloud.async_create_cloudhook",
+ return_value="https://hooks.nabu.casa/ABCD",
+ ),
+ patch(
+ "homeassistant.components.withings.async_get_config_entry_implementation",
+ ),
+ patch(
+ "homeassistant.components.cloud.async_delete_cloudhook",
+ ),
+ patch(
+ "homeassistant.components.withings.webhook_generate_url",
+ ),
):
await setup_integration(hass, webhook_config_entry)
await prepare_webhook_setup(hass, freezer)
diff --git a/tests/components/wiz/__init__.py b/tests/components/wiz/__init__.py
index 165e0557fcd..e80a1ed8249 100644
--- a/tests/components/wiz/__init__.py
+++ b/tests/components/wiz/__init__.py
@@ -232,9 +232,12 @@ def _patch_wizlight(device=None, extended_white_range=None, bulb_type=None):
@contextmanager
def _patcher():
bulb = device or _mocked_wizlight(device, extended_white_range, bulb_type)
- with patch("homeassistant.components.wiz.wizlight", return_value=bulb), patch(
- "homeassistant.components.wiz.config_flow.wizlight",
- return_value=bulb,
+ with (
+ patch("homeassistant.components.wiz.wizlight", return_value=bulb),
+ patch(
+ "homeassistant.components.wiz.config_flow.wizlight",
+ return_value=bulb,
+ ),
):
yield
diff --git a/tests/components/wiz/test_config_flow.py b/tests/components/wiz/test_config_flow.py
index 6ee77e83fb6..1b84a048fd2 100644
--- a/tests/components/wiz/test_config_flow.py
+++ b/tests/components/wiz/test_config_flow.py
@@ -52,12 +52,16 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
# Patch functions
- with _patch_wizlight(), patch(
- "homeassistant.components.wiz.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.wiz.async_setup", return_value=True
- ) as mock_setup:
+ with (
+ _patch_wizlight(),
+ patch(
+ "homeassistant.components.wiz.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.wiz.async_setup", return_value=True
+ ) as mock_setup,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
TEST_CONNECTION,
@@ -90,12 +94,16 @@ async def test_user_flow_enters_dns_name(hass: HomeAssistant) -> None:
assert result2["type"] == FlowResultType.FORM
assert result2["errors"] == {"base": "no_ip"}
- with _patch_wizlight(), patch(
- "homeassistant.components.wiz.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.wiz.async_setup", return_value=True
- ) as mock_setup:
+ with (
+ _patch_wizlight(),
+ patch(
+ "homeassistant.components.wiz.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.wiz.async_setup", return_value=True
+ ) as mock_setup,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
TEST_CONNECTION,
@@ -265,14 +273,18 @@ async def test_discovered_by_dhcp_or_integration_discovery(
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "discovery_confirm"
- with _patch_wizlight(
- device=None, extended_white_range=extended_white_range, bulb_type=bulb_type
- ), patch(
- "homeassistant.components.wiz.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.wiz.async_setup", return_value=True
- ) as mock_setup:
+ with (
+ _patch_wizlight(
+ device=None, extended_white_range=extended_white_range, bulb_type=bulb_type
+ ),
+ patch(
+ "homeassistant.components.wiz.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.wiz.async_setup", return_value=True
+ ) as mock_setup,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{},
@@ -380,11 +392,15 @@ async def test_setup_via_discovery(hass: HomeAssistant) -> None:
assert result2["step_id"] == "pick_device"
assert not result2["errors"]
- with _patch_wizlight(), patch(
- "homeassistant.components.wiz.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.wiz.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ _patch_wizlight(),
+ patch(
+ "homeassistant.components.wiz.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.wiz.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_DEVICE: FAKE_MAC},
@@ -433,10 +449,13 @@ async def test_setup_via_discovery_cannot_connect(hass: HomeAssistant) -> None:
assert result2["step_id"] == "pick_device"
assert not result2["errors"]
- with patch(
- "homeassistant.components.wiz.wizlight.getBulbConfig",
- side_effect=WizLightTimeOutError,
- ), _patch_discovery():
+ with (
+ patch(
+ "homeassistant.components.wiz.wizlight.getBulbConfig",
+ side_effect=WizLightTimeOutError,
+ ),
+ _patch_discovery(),
+ ):
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_DEVICE: FAKE_MAC},
@@ -489,15 +508,19 @@ async def test_discovery_with_firmware_update(hass: HomeAssistant) -> None:
# updates and we now can see its really RGBWW not RGBW since the older
# firmwares did not tell us how many white channels exist
- with patch(
- "homeassistant.components.wiz.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.wiz.async_setup", return_value=True
- ) as mock_setup, _patch_wizlight(
- device=None,
- extended_white_range=FAKE_EXTENDED_WHITE_RANGE,
- bulb_type=FAKE_RGBWW_BULB,
+ with (
+ patch(
+ "homeassistant.components.wiz.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.wiz.async_setup", return_value=True
+ ) as mock_setup,
+ _patch_wizlight(
+ device=None,
+ extended_white_range=FAKE_EXTENDED_WHITE_RANGE,
+ bulb_type=FAKE_RGBWW_BULB,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -523,13 +546,18 @@ async def test_discovery_with_firmware_update(hass: HomeAssistant) -> None:
)
async def test_discovered_during_onboarding(hass: HomeAssistant, source, data) -> None:
"""Test dhcp or discovery during onboarding creates the config entry."""
- with _patch_wizlight(), patch(
- "homeassistant.components.wiz.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.wiz.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.onboarding.async_is_onboarded", return_value=False
+ with (
+ _patch_wizlight(),
+ patch(
+ "homeassistant.components.wiz.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.wiz.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.onboarding.async_is_onboarded", return_value=False
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": source}, data=data
diff --git a/tests/components/wiz/test_init.py b/tests/components/wiz/test_init.py
index bd494da95b7..d6813263fcc 100644
--- a/tests/components/wiz/test_init.py
+++ b/tests/components/wiz/test_init.py
@@ -58,9 +58,10 @@ async def test_cleanup_on_failed_first_update(hass: HomeAssistant) -> None:
data={CONF_HOST: FAKE_IP},
)
entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.wiz.discovery.find_wizlights", return_value=[]
- ), _patch_wizlight(device=bulb):
+ with (
+ patch("homeassistant.components.wiz.discovery.find_wizlights", return_value=[]),
+ _patch_wizlight(device=bulb),
+ ):
await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
assert entry.state is config_entries.ConfigEntryState.SETUP_RETRY
diff --git a/tests/components/wled/conftest.py b/tests/components/wled/conftest.py
index ce0c7c28f6a..d2f124a517b 100644
--- a/tests/components/wled/conftest.py
+++ b/tests/components/wled/conftest.py
@@ -53,10 +53,11 @@ def device_fixture() -> str:
@pytest.fixture
def mock_wled(device_fixture: str) -> Generator[MagicMock, None, None]:
"""Return a mocked WLED client."""
- with patch(
- "homeassistant.components.wled.coordinator.WLED", autospec=True
- ) as wled_mock, patch(
- "homeassistant.components.wled.config_flow.WLED", new=wled_mock
+ with (
+ patch(
+ "homeassistant.components.wled.coordinator.WLED", autospec=True
+ ) as wled_mock,
+ patch("homeassistant.components.wled.config_flow.WLED", new=wled_mock),
):
wled = wled_mock.return_value
wled.update.return_value = WLEDDevice(
diff --git a/tests/components/wolflink/test_config_flow.py b/tests/components/wolflink/test_config_flow.py
index 5760a54f5ce..bee646deae8 100644
--- a/tests/components/wolflink/test_config_flow.py
+++ b/tests/components/wolflink/test_config_flow.py
@@ -60,10 +60,13 @@ async def test_device_step_form(hass: HomeAssistant) -> None:
async def test_create_entry(hass: HomeAssistant) -> None:
"""Test entity creation from device step."""
- with patch(
- "homeassistant.components.wolflink.config_flow.WolfClient.fetch_system_list",
- return_value=[DEVICE],
- ), patch("homeassistant.components.wolflink.async_setup_entry", return_value=True):
+ with (
+ patch(
+ "homeassistant.components.wolflink.config_flow.WolfClient.fetch_system_list",
+ return_value=[DEVICE],
+ ),
+ patch("homeassistant.components.wolflink.async_setup_entry", return_value=True),
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}, data=INPUT_CONFIG
)
@@ -122,10 +125,13 @@ async def test_form_unknown_exception(hass: HomeAssistant) -> None:
async def test_already_configured_error(hass: HomeAssistant) -> None:
"""Test already configured while creating entry."""
- with patch(
- "homeassistant.components.wolflink.config_flow.WolfClient.fetch_system_list",
- return_value=[DEVICE],
- ), patch("homeassistant.components.wolflink.async_setup_entry", return_value=True):
+ with (
+ patch(
+ "homeassistant.components.wolflink.config_flow.WolfClient.fetch_system_list",
+ return_value=[DEVICE],
+ ),
+ patch("homeassistant.components.wolflink.async_setup_entry", return_value=True),
+ ):
MockConfigEntry(
domain=DOMAIN, unique_id=CONFIG[DEVICE_ID], data=CONFIG
).add_to_hass(hass)
diff --git a/tests/components/ws66i/test_config_flow.py b/tests/components/ws66i/test_config_flow.py
index aa5e9005394..19a329cb913 100644
--- a/tests/components/ws66i/test_config_flow.py
+++ b/tests/components/ws66i/test_config_flow.py
@@ -32,12 +32,15 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.ws66i.config_flow.get_ws66i",
- ) as mock_ws66i, patch(
- "homeassistant.components.ws66i.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.ws66i.config_flow.get_ws66i",
+ ) as mock_ws66i,
+ patch(
+ "homeassistant.components.ws66i.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
ws66i_instance = mock_ws66i.return_value
result2 = await hass.config_entries.flow.async_configure(
diff --git a/tests/components/wyoming/__init__.py b/tests/components/wyoming/__init__.py
index 45fff55a89c..5bfbbfe87b2 100644
--- a/tests/components/wyoming/__init__.py
+++ b/tests/components/wyoming/__init__.py
@@ -144,12 +144,15 @@ async def reload_satellite(
hass: HomeAssistant, config_entry_id: str
) -> SatelliteDevice:
"""Reload config entry with satellite info and returns new device."""
- with patch(
- "homeassistant.components.wyoming.data.load_wyoming_info",
- return_value=SATELLITE_INFO,
- ), patch(
- "homeassistant.components.wyoming.satellite.WyomingSatellite.run"
- ) as _run_mock:
+ with (
+ patch(
+ "homeassistant.components.wyoming.data.load_wyoming_info",
+ return_value=SATELLITE_INFO,
+ ),
+ patch(
+ "homeassistant.components.wyoming.satellite.WyomingSatellite.run"
+ ) as _run_mock,
+ ):
# _run_mock: satellite task does not actually run
await hass.config_entries.async_reload(config_entry_id)
diff --git a/tests/components/wyoming/conftest.py b/tests/components/wyoming/conftest.py
index b6111eaddd8..4be12312c7a 100644
--- a/tests/components/wyoming/conftest.py
+++ b/tests/components/wyoming/conftest.py
@@ -146,12 +146,15 @@ def satellite_config_entry(hass: HomeAssistant) -> ConfigEntry:
@pytest.fixture
async def init_satellite(hass: HomeAssistant, satellite_config_entry: ConfigEntry):
"""Initialize Wyoming satellite."""
- with patch(
- "homeassistant.components.wyoming.data.load_wyoming_info",
- return_value=SATELLITE_INFO,
- ), patch(
- "homeassistant.components.wyoming.satellite.WyomingSatellite.run"
- ) as _run_mock:
+ with (
+ patch(
+ "homeassistant.components.wyoming.data.load_wyoming_info",
+ return_value=SATELLITE_INFO,
+ ),
+ patch(
+ "homeassistant.components.wyoming.satellite.WyomingSatellite.run"
+ ) as _run_mock,
+ ):
# _run_mock: satellite task does not actually run
await hass.config_entries.async_setup(satellite_config_entry.entry_id)
diff --git a/tests/components/wyoming/test_config_flow.py b/tests/components/wyoming/test_config_flow.py
index f0713448e54..c15eb81a1e2 100644
--- a/tests/components/wyoming/test_config_flow.py
+++ b/tests/components/wyoming/test_config_flow.py
@@ -262,10 +262,13 @@ async def test_zeroconf_discovery_no_port(
snapshot: SnapshotAssertion,
) -> None:
"""Test discovery when the zeroconf service does not have a port."""
- with patch(
- "homeassistant.components.wyoming.data.load_wyoming_info",
- return_value=SATELLITE_INFO,
- ), patch.object(ZEROCONF_DISCOVERY, "port", None):
+ with (
+ patch(
+ "homeassistant.components.wyoming.data.load_wyoming_info",
+ return_value=SATELLITE_INFO,
+ ),
+ patch.object(ZEROCONF_DISCOVERY, "port", None),
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
data=ZEROCONF_DISCOVERY,
diff --git a/tests/components/wyoming/test_satellite.py b/tests/components/wyoming/test_satellite.py
index 76f442ef246..a9d1e73e153 100644
--- a/tests/components/wyoming/test_satellite.py
+++ b/tests/components/wyoming/test_satellite.py
@@ -185,9 +185,9 @@ async def test_satellite_pipeline(hass: HomeAssistant) -> None:
]
pipeline_kwargs: dict[str, Any] = {}
- pipeline_event_callback: Callable[
- [assist_pipeline.PipelineEvent], None
- ] | None = None
+ pipeline_event_callback: Callable[[assist_pipeline.PipelineEvent], None] | None = (
+ None
+ )
run_pipeline_called = asyncio.Event()
audio_chunk_received = asyncio.Event()
@@ -771,9 +771,9 @@ async def test_pipeline_changed(hass: HomeAssistant) -> None:
).event(),
]
- pipeline_event_callback: Callable[
- [assist_pipeline.PipelineEvent], None
- ] | None = None
+ pipeline_event_callback: Callable[[assist_pipeline.PipelineEvent], None] | None = (
+ None
+ )
run_pipeline_called = asyncio.Event()
pipeline_stopped = asyncio.Event()
@@ -845,9 +845,9 @@ async def test_audio_settings_changed(hass: HomeAssistant) -> None:
).event(),
]
- pipeline_event_callback: Callable[
- [assist_pipeline.PipelineEvent], None
- ] | None = None
+ pipeline_event_callback: Callable[[assist_pipeline.PipelineEvent], None] | None = (
+ None
+ )
run_pipeline_called = asyncio.Event()
pipeline_stopped = asyncio.Event()
@@ -981,9 +981,9 @@ async def test_client_stops_pipeline(hass: HomeAssistant) -> None:
).event(),
]
- pipeline_event_callback: Callable[
- [assist_pipeline.PipelineEvent], None
- ] | None = None
+ pipeline_event_callback: Callable[[assist_pipeline.PipelineEvent], None] | None = (
+ None
+ )
run_pipeline_called = asyncio.Event()
pipeline_stopped = asyncio.Event()
diff --git a/tests/components/wyoming/test_stt.py b/tests/components/wyoming/test_stt.py
index 4d1ab6dc4d9..900ee8d544c 100644
--- a/tests/components/wyoming/test_stt.py
+++ b/tests/components/wyoming/test_stt.py
@@ -82,10 +82,13 @@ async def test_streaming_audio_oserror(
mock_client = MockAsyncTcpClient([Transcript(text="Hello world").event()])
- with patch(
- "homeassistant.components.wyoming.stt.AsyncTcpClient",
- mock_client,
- ), patch.object(mock_client, "read_event", side_effect=OSError("Boom!")):
+ with (
+ patch(
+ "homeassistant.components.wyoming.stt.AsyncTcpClient",
+ mock_client,
+ ),
+ patch.object(mock_client, "read_event", side_effect=OSError("Boom!")),
+ ):
result = await entity.async_process_audio_stream(metadata, audio_stream())
assert result.result == stt.SpeechResultState.ERROR
diff --git a/tests/components/wyoming/test_tts.py b/tests/components/wyoming/test_tts.py
index 895774bf92a..4063418e566 100644
--- a/tests/components/wyoming/test_tts.py
+++ b/tests/components/wyoming/test_tts.py
@@ -147,10 +147,13 @@ async def test_get_tts_audio_connection_lost(
hass: HomeAssistant, init_wyoming_tts
) -> None:
"""Test streaming audio and losing connection."""
- with patch(
- "homeassistant.components.wyoming.tts.AsyncTcpClient",
- MockAsyncTcpClient([None]),
- ), pytest.raises(HomeAssistantError):
+ with (
+ patch(
+ "homeassistant.components.wyoming.tts.AsyncTcpClient",
+ MockAsyncTcpClient([None]),
+ ),
+ pytest.raises(HomeAssistantError),
+ ):
await tts.async_get_media_source_audio(
hass,
tts.generate_media_source_id(hass, "Hello world", "tts.test_tts", "en-US"),
@@ -169,13 +172,15 @@ async def test_get_tts_audio_audio_oserror(
mock_client = MockAsyncTcpClient(audio_events)
- with patch(
- "homeassistant.components.wyoming.tts.AsyncTcpClient",
- mock_client,
- ), patch.object(
- mock_client, "read_event", side_effect=OSError("Boom!")
- ), pytest.raises(
- HomeAssistantError,
+ with (
+ patch(
+ "homeassistant.components.wyoming.tts.AsyncTcpClient",
+ mock_client,
+ ),
+ patch.object(mock_client, "read_event", side_effect=OSError("Boom!")),
+ pytest.raises(
+ HomeAssistantError,
+ ),
):
await tts.async_get_media_source_audio(
hass,
diff --git a/tests/components/xiaomi_aqara/test_config_flow.py b/tests/components/xiaomi_aqara/test_config_flow.py
index a2cf62297ef..67991714203 100644
--- a/tests/components/xiaomi_aqara/test_config_flow.py
+++ b/tests/components/xiaomi_aqara/test_config_flow.py
@@ -33,14 +33,18 @@ def xiaomi_aqara_fixture():
"""Mock xiaomi_aqara discovery and entry setup."""
mock_gateway_discovery = get_mock_discovery([TEST_HOST])
- with patch(
- "homeassistant.components.xiaomi_aqara.config_flow.XiaomiGatewayDiscovery",
- return_value=mock_gateway_discovery,
- ), patch(
- "homeassistant.components.xiaomi_aqara.config_flow.XiaomiGateway",
- return_value=mock_gateway_discovery.gateways[TEST_HOST],
- ), patch(
- "homeassistant.components.xiaomi_aqara.async_setup_entry", return_value=True
+ with (
+ patch(
+ "homeassistant.components.xiaomi_aqara.config_flow.XiaomiGatewayDiscovery",
+ return_value=mock_gateway_discovery,
+ ),
+ patch(
+ "homeassistant.components.xiaomi_aqara.config_flow.XiaomiGateway",
+ return_value=mock_gateway_discovery.gateways[TEST_HOST],
+ ),
+ patch(
+ "homeassistant.components.xiaomi_aqara.async_setup_entry", return_value=True
+ ),
):
yield
diff --git a/tests/components/xiaomi_ble/test_binary_sensor.py b/tests/components/xiaomi_ble/test_binary_sensor.py
index b9e0b24a3cf..e446a8fb66e 100644
--- a/tests/components/xiaomi_ble/test_binary_sensor.py
+++ b/tests/components/xiaomi_ble/test_binary_sensor.py
@@ -325,9 +325,12 @@ async def test_unavailable(hass: HomeAssistant) -> None:
# Fastforward time without BLE advertisements
monotonic_now = start_monotonic + FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 1
- with patch_bluetooth_time(
- monotonic_now,
- ), patch_all_discovered_devices([]):
+ with (
+ patch_bluetooth_time(
+ monotonic_now,
+ ),
+ patch_all_discovered_devices([]),
+ ):
async_fire_time_changed(
hass,
dt_util.utcnow()
@@ -377,9 +380,12 @@ async def test_sleepy_device(hass: HomeAssistant) -> None:
# Fastforward time without BLE advertisements
monotonic_now = start_monotonic + FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 1
- with patch_bluetooth_time(
- monotonic_now,
- ), patch_all_discovered_devices([]):
+ with (
+ patch_bluetooth_time(
+ monotonic_now,
+ ),
+ patch_all_discovered_devices([]),
+ ):
async_fire_time_changed(
hass,
dt_util.utcnow()
@@ -429,9 +435,12 @@ async def test_sleepy_device_restore_state(hass: HomeAssistant) -> None:
# Fastforward time without BLE advertisements
monotonic_now = start_monotonic + FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 1
- with patch_bluetooth_time(
- monotonic_now,
- ), patch_all_discovered_devices([]):
+ with (
+ patch_bluetooth_time(
+ monotonic_now,
+ ),
+ patch_all_discovered_devices([]),
+ ):
async_fire_time_changed(
hass,
dt_util.utcnow()
diff --git a/tests/components/xiaomi_ble/test_config_flow.py b/tests/components/xiaomi_ble/test_config_flow.py
index 1ae2a75e66b..8b3ff2ef4ab 100644
--- a/tests/components/xiaomi_ble/test_config_flow.py
+++ b/tests/components/xiaomi_ble/test_config_flow.py
@@ -114,12 +114,15 @@ async def test_async_step_bluetooth_valid_device_but_missing_payload_then_full(
async def test_async_step_bluetooth_during_onboarding(hass: HomeAssistant) -> None:
"""Test discovery via bluetooth during onboarding."""
- with patch(
- "homeassistant.components.xiaomi_ble.async_setup_entry", return_value=True
- ) as mock_setup_entry, patch(
- "homeassistant.components.onboarding.async_is_onboarded",
- return_value=False,
- ) as mock_onboarding:
+ with (
+ patch(
+ "homeassistant.components.xiaomi_ble.async_setup_entry", return_value=True
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.onboarding.async_is_onboarded",
+ return_value=False,
+ ) as mock_onboarding,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_BLUETOOTH},
diff --git a/tests/components/xiaomi_ble/test_sensor.py b/tests/components/xiaomi_ble/test_sensor.py
index 96957bb686f..4d9a29e3111 100644
--- a/tests/components/xiaomi_ble/test_sensor.py
+++ b/tests/components/xiaomi_ble/test_sensor.py
@@ -693,9 +693,12 @@ async def test_unavailable(hass: HomeAssistant) -> None:
# Fastforward time without BLE advertisements
monotonic_now = start_monotonic + FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 1
- with patch_bluetooth_time(
- monotonic_now,
- ), patch_all_discovered_devices([]):
+ with (
+ patch_bluetooth_time(
+ monotonic_now,
+ ),
+ patch_all_discovered_devices([]),
+ ):
async_fire_time_changed(
hass,
dt_util.utcnow()
@@ -739,9 +742,12 @@ async def test_sleepy_device(hass: HomeAssistant) -> None:
# Fastforward time without BLE advertisements
monotonic_now = start_monotonic + FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 1
- with patch_bluetooth_time(
- monotonic_now,
- ), patch_all_discovered_devices([]):
+ with (
+ patch_bluetooth_time(
+ monotonic_now,
+ ),
+ patch_all_discovered_devices([]),
+ ):
async_fire_time_changed(
hass,
dt_util.utcnow()
@@ -787,9 +793,12 @@ async def test_sleepy_device_restore_state(hass: HomeAssistant) -> None:
# Fastforward time without BLE advertisements
monotonic_now = start_monotonic + FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS + 1
- with patch_bluetooth_time(
- monotonic_now,
- ), patch_all_discovered_devices([]):
+ with (
+ patch_bluetooth_time(
+ monotonic_now,
+ ),
+ patch_all_discovered_devices([]),
+ ):
async_fire_time_changed(
hass,
dt_util.utcnow()
diff --git a/tests/components/xiaomi_miio/test_button.py b/tests/components/xiaomi_miio/test_button.py
index 098c08d189a..8159d7c49e5 100644
--- a/tests/components/xiaomi_miio/test_button.py
+++ b/tests/components/xiaomi_miio/test_button.py
@@ -33,12 +33,15 @@ async def setup_test(hass: HomeAssistant):
mock_vacuum = MagicMock()
- with patch(
- "homeassistant.components.xiaomi_miio.get_platforms",
- return_value=[
- Platform.BUTTON,
- ],
- ), patch("homeassistant.components.xiaomi_miio.RoborockVacuum") as mock_vacuum_cls:
+ with (
+ patch(
+ "homeassistant.components.xiaomi_miio.get_platforms",
+ return_value=[
+ Platform.BUTTON,
+ ],
+ ),
+ patch("homeassistant.components.xiaomi_miio.RoborockVacuum") as mock_vacuum_cls,
+ ):
mock_vacuum_cls.return_value = mock_vacuum
yield mock_vacuum
diff --git a/tests/components/xiaomi_miio/test_config_flow.py b/tests/components/xiaomi_miio/test_config_flow.py
index 06c3bf15a1e..7645f67732e 100644
--- a/tests/components/xiaomi_miio/test_config_flow.py
+++ b/tests/components/xiaomi_miio/test_config_flow.py
@@ -73,19 +73,25 @@ def xiaomi_miio_connect_fixture():
"""Mock miio connection and entry setup."""
mock_info = get_mock_info()
- with patch(
- "homeassistant.components.xiaomi_miio.device.Device.info",
- return_value=mock_info,
- ), patch(
- "homeassistant.components.xiaomi_miio.config_flow.MiCloud.login",
- return_value=True,
- ), patch(
- "homeassistant.components.xiaomi_miio.config_flow.MiCloud.get_devices",
- return_value=TEST_CLOUD_DEVICES_1,
- ), patch(
- "homeassistant.components.xiaomi_miio.async_setup_entry", return_value=True
- ), patch(
- "homeassistant.components.xiaomi_miio.async_unload_entry", return_value=True
+ with (
+ patch(
+ "homeassistant.components.xiaomi_miio.device.Device.info",
+ return_value=mock_info,
+ ),
+ patch(
+ "homeassistant.components.xiaomi_miio.config_flow.MiCloud.login",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.xiaomi_miio.config_flow.MiCloud.get_devices",
+ return_value=TEST_CLOUD_DEVICES_1,
+ ),
+ patch(
+ "homeassistant.components.xiaomi_miio.async_setup_entry", return_value=True
+ ),
+ patch(
+ "homeassistant.components.xiaomi_miio.async_unload_entry", return_value=True
+ ),
):
yield
diff --git a/tests/components/xiaomi_miio/test_select.py b/tests/components/xiaomi_miio/test_select.py
index 794fbb090e0..f2f04127d75 100644
--- a/tests/components/xiaomi_miio/test_select.py
+++ b/tests/components/xiaomi_miio/test_select.py
@@ -46,12 +46,17 @@ async def setup_test(hass: HomeAssistant):
mock_airfresh.status().display_orientation = DisplayOrientation.Portrait
mock_airfresh.status().ptc_level = PtcLevel.Low
- with patch(
- "homeassistant.components.xiaomi_miio.get_platforms",
- return_value=[
- Platform.SELECT,
- ],
- ), patch("homeassistant.components.xiaomi_miio.AirFreshT2017") as mock_airfresh_cls:
+ with (
+ patch(
+ "homeassistant.components.xiaomi_miio.get_platforms",
+ return_value=[
+ Platform.SELECT,
+ ],
+ ),
+ patch(
+ "homeassistant.components.xiaomi_miio.AirFreshT2017"
+ ) as mock_airfresh_cls,
+ ):
mock_airfresh_cls.return_value = mock_airfresh
yield mock_airfresh
diff --git a/tests/components/yale_smart_alarm/test_config_flow.py b/tests/components/yale_smart_alarm/test_config_flow.py
index 5a7f3bc3d08..5eed34a2423 100644
--- a/tests/components/yale_smart_alarm/test_config_flow.py
+++ b/tests/components/yale_smart_alarm/test_config_flow.py
@@ -24,12 +24,15 @@ async def test_form(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.yale_smart_alarm.config_flow.YaleSmartAlarmClient",
- ), patch(
- "homeassistant.components.yale_smart_alarm.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.yale_smart_alarm.config_flow.YaleSmartAlarmClient",
+ ),
+ patch(
+ "homeassistant.components.yale_smart_alarm.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -85,11 +88,14 @@ async def test_form_invalid_auth(
assert result2["type"] == FlowResultType.FORM
assert result2["errors"] == {"base": p_error}
- with patch(
- "homeassistant.components.yale_smart_alarm.config_flow.YaleSmartAlarmClient",
- ), patch(
- "homeassistant.components.yale_smart_alarm.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.yale_smart_alarm.config_flow.YaleSmartAlarmClient",
+ ),
+ patch(
+ "homeassistant.components.yale_smart_alarm.async_setup_entry",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -139,12 +145,15 @@ async def test_reauth_flow(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
- with patch(
- "homeassistant.components.yale_smart_alarm.config_flow.YaleSmartAlarmClient",
- ) as mock_yale, patch(
- "homeassistant.components.yale_smart_alarm.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.yale_smart_alarm.config_flow.YaleSmartAlarmClient",
+ ) as mock_yale,
+ patch(
+ "homeassistant.components.yale_smart_alarm.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -220,12 +229,15 @@ async def test_reauth_flow_error(
assert result2["type"] == FlowResultType.FORM
assert result2["errors"] == {"base": p_error}
- with patch(
- "homeassistant.components.yale_smart_alarm.config_flow.YaleSmartAlarmClient",
- return_value="",
- ), patch(
- "homeassistant.components.yale_smart_alarm.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.yale_smart_alarm.config_flow.YaleSmartAlarmClient",
+ return_value="",
+ ),
+ patch(
+ "homeassistant.components.yale_smart_alarm.async_setup_entry",
+ return_value=True,
+ ),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -261,12 +273,15 @@ async def test_options_flow(hass: HomeAssistant) -> None:
)
entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.yale_smart_alarm.config_flow.YaleSmartAlarmClient",
- return_value=True,
- ), patch(
- "homeassistant.components.yale_smart_alarm.async_setup_entry",
- return_value=True,
+ with (
+ patch(
+ "homeassistant.components.yale_smart_alarm.config_flow.YaleSmartAlarmClient",
+ return_value=True,
+ ),
+ patch(
+ "homeassistant.components.yale_smart_alarm.async_setup_entry",
+ return_value=True,
+ ),
):
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/yalexs_ble/test_config_flow.py b/tests/components/yalexs_ble/test_config_flow.py
index 510e2c8be56..34ffc55ac3f 100644
--- a/tests/components/yalexs_ble/test_config_flow.py
+++ b/tests/components/yalexs_ble/test_config_flow.py
@@ -61,12 +61,15 @@ async def test_user_step_success(hass: HomeAssistant, slot: int) -> None:
assert result["step_id"] == "user"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.yalexs_ble.config_flow.PushLock.validate",
- ), patch(
- "homeassistant.components.yalexs_ble.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.yalexs_ble.config_flow.PushLock.validate",
+ ),
+ patch(
+ "homeassistant.components.yalexs_ble.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -175,12 +178,15 @@ async def test_user_step_invalid_keys(hass: HomeAssistant) -> None:
assert result4["step_id"] == "user"
assert result4["errors"] == {CONF_SLOT: "invalid_key_index"}
- with patch(
- "homeassistant.components.yalexs_ble.config_flow.PushLock.validate",
- ), patch(
- "homeassistant.components.yalexs_ble.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.yalexs_ble.config_flow.PushLock.validate",
+ ),
+ patch(
+ "homeassistant.components.yalexs_ble.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result5 = await hass.config_entries.flow.async_configure(
result4["flow_id"],
{
@@ -234,12 +240,15 @@ async def test_user_step_cannot_connect(hass: HomeAssistant) -> None:
assert result2["step_id"] == "user"
assert result2["errors"] == {"base": "cannot_connect"}
- with patch(
- "homeassistant.components.yalexs_ble.config_flow.PushLock.validate",
- ), patch(
- "homeassistant.components.yalexs_ble.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.yalexs_ble.config_flow.PushLock.validate",
+ ),
+ patch(
+ "homeassistant.components.yalexs_ble.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
@@ -293,12 +302,15 @@ async def test_user_step_auth_exception(hass: HomeAssistant) -> None:
assert result2["step_id"] == "user"
assert result2["errors"] == {CONF_KEY: "invalid_auth"}
- with patch(
- "homeassistant.components.yalexs_ble.config_flow.PushLock.validate",
- ), patch(
- "homeassistant.components.yalexs_ble.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.yalexs_ble.config_flow.PushLock.validate",
+ ),
+ patch(
+ "homeassistant.components.yalexs_ble.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
@@ -352,12 +364,15 @@ async def test_user_step_unknown_exception(hass: HomeAssistant) -> None:
assert result2["step_id"] == "user"
assert result2["errors"] == {"base": "unknown"}
- with patch(
- "homeassistant.components.yalexs_ble.config_flow.PushLock.validate",
- ), patch(
- "homeassistant.components.yalexs_ble.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.yalexs_ble.config_flow.PushLock.validate",
+ ),
+ patch(
+ "homeassistant.components.yalexs_ble.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
@@ -391,12 +406,15 @@ async def test_bluetooth_step_success(hass: HomeAssistant) -> None:
assert result["step_id"] == "user"
assert result["errors"] == {}
- with patch(
- "homeassistant.components.yalexs_ble.config_flow.PushLock.validate",
- ), patch(
- "homeassistant.components.yalexs_ble.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.yalexs_ble.config_flow.PushLock.validate",
+ ),
+ patch(
+ "homeassistant.components.yalexs_ble.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -579,13 +597,16 @@ async def test_integration_discovery_updates_key_unique_local_name(
)
entry.add_to_hass(hass)
- with patch(
- "homeassistant.components.yalexs_ble.util.async_discovered_service_info",
- return_value=[LOCK_DISCOVERY_INFO_UUID_ADDRESS],
- ), patch(
- "homeassistant.components.yalexs_ble.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.yalexs_ble.util.async_discovered_service_info",
+ return_value=[LOCK_DISCOVERY_INFO_UUID_ADDRESS],
+ ),
+ patch(
+ "homeassistant.components.yalexs_ble.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY},
@@ -853,13 +874,16 @@ async def test_user_is_setting_up_lock_and_discovery_happens_in_the_middle(
valdidate_started.set()
await user_flow_event.wait()
- with patch(
- "homeassistant.components.yalexs_ble.config_flow.PushLock.validate",
- side_effect=_wait_for_user_flow,
- ), patch(
- "homeassistant.components.yalexs_ble.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.yalexs_ble.config_flow.PushLock.validate",
+ side_effect=_wait_for_user_flow,
+ ),
+ patch(
+ "homeassistant.components.yalexs_ble.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
user_flow_task = asyncio.create_task(
hass.config_entries.flow.async_configure(
result["flow_id"],
@@ -946,15 +970,19 @@ async def test_reauth(hass: HomeAssistant) -> None:
assert result2["step_id"] == "reauth_validate"
assert result2["errors"] == {"base": "no_longer_in_range"}
- with patch(
- "homeassistant.components.yalexs_ble.config_flow.async_ble_device_from_address",
- return_value=YALE_ACCESS_LOCK_DISCOVERY_INFO,
- ), patch(
- "homeassistant.components.yalexs_ble.config_flow.PushLock.validate",
- ), patch(
- "homeassistant.components.yalexs_ble.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.yalexs_ble.config_flow.async_ble_device_from_address",
+ return_value=YALE_ACCESS_LOCK_DISCOVERY_INFO,
+ ),
+ patch(
+ "homeassistant.components.yalexs_ble.config_flow.PushLock.validate",
+ ),
+ patch(
+ "homeassistant.components.yalexs_ble.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
{
diff --git a/tests/components/yamaha_musiccast/test_config_flow.py b/tests/components/yamaha_musiccast/test_config_flow.py
index 356dc78ded1..9740bd70a87 100644
--- a/tests/components/yamaha_musiccast/test_config_flow.py
+++ b/tests/components/yamaha_musiccast/test_config_flow.py
@@ -18,14 +18,16 @@ from tests.common import MockConfigEntry
@pytest.fixture(autouse=True)
async def silent_ssdp_scanner(hass):
"""Start SSDP component and get Scanner, prevent actual SSDP traffic."""
- with patch(
- "homeassistant.components.ssdp.Scanner._async_start_ssdp_listeners"
- ), patch("homeassistant.components.ssdp.Scanner._async_stop_ssdp_listeners"), patch(
- "homeassistant.components.ssdp.Scanner.async_scan"
- ), patch(
- "homeassistant.components.ssdp.Server._async_start_upnp_servers",
- ), patch(
- "homeassistant.components.ssdp.Server._async_stop_upnp_servers",
+ with (
+ patch("homeassistant.components.ssdp.Scanner._async_start_ssdp_listeners"),
+ patch("homeassistant.components.ssdp.Scanner._async_stop_ssdp_listeners"),
+ patch("homeassistant.components.ssdp.Scanner.async_scan"),
+ patch(
+ "homeassistant.components.ssdp.Server._async_start_upnp_servers",
+ ),
+ patch(
+ "homeassistant.components.ssdp.Server._async_stop_upnp_servers",
+ ),
):
yield
diff --git a/tests/components/yeelight/test_config_flow.py b/tests/components/yeelight/test_config_flow.py
index e04dad88da4..41d60c8652a 100644
--- a/tests/components/yeelight/test_config_flow.py
+++ b/tests/components/yeelight/test_config_flow.py
@@ -89,11 +89,12 @@ async def test_discovery(hass: HomeAssistant) -> None:
assert result2["step_id"] == "pick_device"
assert not result2["errors"]
- with _patch_discovery(), _patch_discovery_interval(), patch(
- f"{MODULE}.async_setup", return_value=True
- ) as mock_setup, patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE}.async_setup", return_value=True) as mock_setup,
+ patch(f"{MODULE}.async_setup_entry", return_value=True) as mock_setup_entry,
+ ):
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_DEVICE: ID}
)
@@ -128,8 +129,11 @@ async def test_discovery_with_existing_device_present(hass: HomeAssistant) -> No
alternate_bulb.capabilities["id"] = "0x000000000099999"
alternate_bulb.capabilities["location"] = "yeelight://4.4.4.4"
- with _patch_discovery(), _patch_discovery_timeout(), _patch_discovery_interval(), patch(
- f"{MODULE}.AsyncBulb", return_value=alternate_bulb
+ with (
+ _patch_discovery(),
+ _patch_discovery_timeout(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE}.AsyncBulb", return_value=alternate_bulb),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -166,8 +170,10 @@ async def test_discovery_with_existing_device_present(hass: HomeAssistant) -> No
assert result2["step_id"] == "pick_device"
assert not result2["errors"]
- with _patch_discovery(), _patch_discovery_interval(), patch(
- f"{MODULE}.AsyncBulb", return_value=_mocked_bulb()
+ with (
+ _patch_discovery(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE}.AsyncBulb", return_value=_mocked_bulb()),
):
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_DEVICE: ID}
@@ -202,9 +208,11 @@ async def test_discovery_no_device(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
- with _patch_discovery(
- no_device=True
- ), _patch_discovery_timeout(), _patch_discovery_interval():
+ with (
+ _patch_discovery(no_device=True),
+ _patch_discovery_timeout(),
+ _patch_discovery_interval(),
+ ):
result2 = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result2["type"] == "abort"
@@ -224,10 +232,11 @@ async def test_import(hass: HomeAssistant) -> None:
# Cannot connect
mocked_bulb = _mocked_bulb(cannot_connect=True)
- with _patch_discovery(
- no_device=True
- ), _patch_discovery_timeout(), _patch_discovery_interval(), patch(
- f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(no_device=True),
+ _patch_discovery_timeout(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=config
@@ -237,11 +246,12 @@ async def test_import(hass: HomeAssistant) -> None:
# Success
mocked_bulb = _mocked_bulb()
- with _patch_discovery(), patch(
- f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb
- ), patch(f"{MODULE}.async_setup", return_value=True) as mock_setup, patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_setup_entry:
+ with (
+ _patch_discovery(),
+ patch(f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb),
+ patch(f"{MODULE}.async_setup", return_value=True) as mock_setup,
+ patch(f"{MODULE}.async_setup_entry", return_value=True) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=config
)
@@ -261,8 +271,9 @@ async def test_import(hass: HomeAssistant) -> None:
# Duplicate
mocked_bulb = _mocked_bulb()
- with _patch_discovery(), patch(
- f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(),
+ patch(f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=config
@@ -282,10 +293,11 @@ async def test_manual(hass: HomeAssistant) -> None:
# Cannot connect (timeout)
mocked_bulb = _mocked_bulb(cannot_connect=True)
- with _patch_discovery(
- no_device=True
- ), _patch_discovery_timeout(), _patch_discovery_interval(), patch(
- f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(no_device=True),
+ _patch_discovery_timeout(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: IP_ADDRESS}
@@ -295,10 +307,11 @@ async def test_manual(hass: HomeAssistant) -> None:
assert result2["errors"] == {"base": "cannot_connect"}
# Cannot connect (error)
- with _patch_discovery(
- no_device=True
- ), _patch_discovery_timeout(), _patch_discovery_interval(), patch(
- f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(no_device=True),
+ _patch_discovery_timeout(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb),
):
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: IP_ADDRESS}
@@ -307,10 +320,12 @@ async def test_manual(hass: HomeAssistant) -> None:
# Success
mocked_bulb = _mocked_bulb()
- with _patch_discovery(), _patch_discovery_timeout(), patch(
- f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb
- ), patch(f"{MODULE}.async_setup", return_value=True), patch(
- f"{MODULE}.async_setup_entry", return_value=True
+ with (
+ _patch_discovery(),
+ _patch_discovery_timeout(),
+ patch(f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb),
+ patch(f"{MODULE}.async_setup", return_value=True),
+ patch(f"{MODULE}.async_setup_entry", return_value=True),
):
result4 = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: IP_ADDRESS}
@@ -329,10 +344,11 @@ async def test_manual(hass: HomeAssistant) -> None:
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
mocked_bulb = _mocked_bulb()
- with _patch_discovery(
- no_device=True
- ), _patch_discovery_timeout(), _patch_discovery_interval(), patch(
- f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(no_device=True),
+ _patch_discovery_timeout(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: IP_ADDRESS}
@@ -436,16 +452,19 @@ async def test_manual_no_capabilities(hass: HomeAssistant) -> None:
assert not result["errors"]
mocked_bulb = _mocked_bulb()
- with _patch_discovery(
- no_device=True
- ), _patch_discovery_timeout(), _patch_discovery_interval(), patch(
- f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb
- ), patch(
- f"{MODULE}.async_setup",
- return_value=True,
- ), patch(
- f"{MODULE}.async_setup_entry",
- return_value=True,
+ with (
+ _patch_discovery(no_device=True),
+ _patch_discovery_timeout(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb),
+ patch(
+ f"{MODULE}.async_setup",
+ return_value=True,
+ ),
+ patch(
+ f"{MODULE}.async_setup_entry",
+ return_value=True,
+ ),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: IP_ADDRESS}
@@ -462,8 +481,10 @@ async def test_discovered_by_homekit_and_dhcp(hass: HomeAssistant) -> None:
"""Test we get the form with homekit and abort for dhcp source when we get both."""
mocked_bulb = _mocked_bulb()
- with _patch_discovery(), _patch_discovery_interval(), patch(
- f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -482,8 +503,10 @@ async def test_discovered_by_homekit_and_dhcp(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with _patch_discovery(), _patch_discovery_interval(), patch(
- f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb),
):
result2 = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -496,8 +519,10 @@ async def test_discovered_by_homekit_and_dhcp(hass: HomeAssistant) -> None:
assert result2["type"] == FlowResultType.ABORT
assert result2["reason"] == "already_in_progress"
- with _patch_discovery(), _patch_discovery_interval(), patch(
- f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb),
):
result3 = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -510,10 +535,11 @@ async def test_discovered_by_homekit_and_dhcp(hass: HomeAssistant) -> None:
assert result3["type"] == FlowResultType.ABORT
assert result3["reason"] == "already_in_progress"
- with _patch_discovery(
- no_device=True
- ), _patch_discovery_timeout(), _patch_discovery_interval(), patch(
- f"{MODULE_CONFIG_FLOW}.AsyncBulb", side_effect=CannotConnect
+ with (
+ _patch_discovery(no_device=True),
+ _patch_discovery_timeout(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE_CONFIG_FLOW}.AsyncBulb", side_effect=CannotConnect),
):
result3 = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -554,8 +580,10 @@ async def test_discovered_by_dhcp_or_homekit(hass: HomeAssistant, source, data)
"""Test we can setup when discovered from dhcp or homekit."""
mocked_bulb = _mocked_bulb()
- with _patch_discovery(), _patch_discovery_interval(), patch(
- f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": source}, data=data
@@ -565,11 +593,14 @@ async def test_discovered_by_dhcp_or_homekit(hass: HomeAssistant, source, data)
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with _patch_discovery(), _patch_discovery_interval(), patch(
- f"{MODULE}.async_setup", return_value=True
- ) as mock_async_setup, patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_async_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE}.async_setup", return_value=True) as mock_async_setup,
+ patch(
+ f"{MODULE}.async_setup_entry", return_value=True
+ ) as mock_async_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(result["flow_id"], {})
await hass.async_block_till_done()
@@ -582,10 +613,11 @@ async def test_discovered_by_dhcp_or_homekit(hass: HomeAssistant, source, data)
assert mock_async_setup.called
assert mock_async_setup_entry.called
- with _patch_discovery(
- no_device=True
- ), _patch_discovery_timeout(), _patch_discovery_interval(), patch(
- f"{MODULE_CONFIG_FLOW}.AsyncBulb", side_effect=CannotConnect
+ with (
+ _patch_discovery(no_device=True),
+ _patch_discovery_timeout(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE_CONFIG_FLOW}.AsyncBulb", side_effect=CannotConnect),
):
result3 = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": source}, data=data
@@ -624,10 +656,11 @@ async def test_discovered_by_dhcp_or_homekit_failed_to_get_id(
"""Test we abort if we cannot get the unique id when discovered from dhcp or homekit."""
mocked_bulb = _mocked_bulb()
- with _patch_discovery(
- no_device=True
- ), _patch_discovery_timeout(), _patch_discovery_interval(), patch(
- f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(no_device=True),
+ _patch_discovery_timeout(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": source}, data=data
@@ -640,8 +673,10 @@ async def test_discovered_ssdp(hass: HomeAssistant) -> None:
"""Test we can setup when discovered from ssdp."""
mocked_bulb = _mocked_bulb()
- with _patch_discovery(), _patch_discovery_interval(), patch(
- f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_SSDP}, data=SSDP_INFO
@@ -651,11 +686,14 @@ async def test_discovered_ssdp(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with _patch_discovery(), _patch_discovery_interval(), patch(
- f"{MODULE}.async_setup", return_value=True
- ) as mock_async_setup, patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_async_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE}.async_setup", return_value=True) as mock_async_setup,
+ patch(
+ f"{MODULE}.async_setup_entry", return_value=True
+ ) as mock_async_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(result["flow_id"], {})
await hass.async_block_till_done()
@@ -669,8 +707,10 @@ async def test_discovered_ssdp(hass: HomeAssistant) -> None:
assert mock_async_setup_entry.called
mocked_bulb = _mocked_bulb()
- with _patch_discovery(), _patch_discovery_interval(), patch(
- f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_SSDP}, data=SSDP_INFO
@@ -685,8 +725,10 @@ async def test_discovered_zeroconf(hass: HomeAssistant) -> None:
"""Test we can setup when discovered from zeroconf."""
mocked_bulb = _mocked_bulb()
- with _patch_discovery(), _patch_discovery_interval(), patch(
- f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -698,11 +740,14 @@ async def test_discovered_zeroconf(hass: HomeAssistant) -> None:
assert result["type"] == FlowResultType.FORM
assert result["errors"] is None
- with _patch_discovery(), _patch_discovery_interval(), patch(
- f"{MODULE}.async_setup", return_value=True
- ) as mock_async_setup, patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_async_setup_entry:
+ with (
+ _patch_discovery(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE}.async_setup", return_value=True) as mock_async_setup,
+ patch(
+ f"{MODULE}.async_setup_entry", return_value=True
+ ) as mock_async_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(result["flow_id"], {})
await hass.async_block_till_done()
@@ -716,8 +761,10 @@ async def test_discovered_zeroconf(hass: HomeAssistant) -> None:
assert mock_async_setup_entry.called
mocked_bulb = _mocked_bulb()
- with _patch_discovery(), _patch_discovery_interval(), patch(
- f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -730,8 +777,10 @@ async def test_discovered_zeroconf(hass: HomeAssistant) -> None:
assert result["reason"] == "already_configured"
mocked_bulb = _mocked_bulb()
- with _patch_discovery(), _patch_discovery_interval(), patch(
- f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -752,8 +801,10 @@ async def test_discovery_updates_ip(hass: HomeAssistant) -> None:
config_entry.add_to_hass(hass)
mocked_bulb = _mocked_bulb()
- with _patch_discovery(), _patch_discovery_interval(), patch(
- f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -780,10 +831,11 @@ async def test_discovery_updates_ip_no_reload_setup_in_progress(
config_entry.add_to_hass(hass)
mocked_bulb = _mocked_bulb()
- with patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_setup_entry, _patch_discovery(), _patch_discovery_interval(), patch(
- f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb
+ with (
+ patch(f"{MODULE}.async_setup_entry", return_value=True) as mock_setup_entry,
+ _patch_discovery(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -804,8 +856,10 @@ async def test_discovery_adds_missing_ip_id_only(hass: HomeAssistant) -> None:
config_entry.add_to_hass(hass)
mocked_bulb = _mocked_bulb()
- with _patch_discovery(), _patch_discovery_interval(), patch(
- f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
@@ -845,13 +899,18 @@ async def test_discovery_adds_missing_ip_id_only(hass: HomeAssistant) -> None:
async def test_discovered_during_onboarding(hass: HomeAssistant, source, data) -> None:
"""Test we create a config entry when discovered during onboarding."""
mocked_bulb = _mocked_bulb()
- with _patch_discovery(), _patch_discovery_interval(), patch(
- f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb
- ), patch(f"{MODULE}.async_setup", return_value=True) as mock_async_setup, patch(
- f"{MODULE}.async_setup_entry", return_value=True
- ) as mock_async_setup_entry, patch(
- "homeassistant.components.onboarding.async_is_onboarded", return_value=False
- ) as mock_is_onboarded:
+ with (
+ _patch_discovery(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE_CONFIG_FLOW}.AsyncBulb", return_value=mocked_bulb),
+ patch(f"{MODULE}.async_setup", return_value=True) as mock_async_setup,
+ patch(
+ f"{MODULE}.async_setup_entry", return_value=True
+ ) as mock_async_setup_entry,
+ patch(
+ "homeassistant.components.onboarding.async_is_onboarded", return_value=False
+ ) as mock_is_onboarded,
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": source}, data=data
)
diff --git a/tests/components/yeelight/test_init.py b/tests/components/yeelight/test_init.py
index f9ccc7edb8b..af442d1c8d0 100644
--- a/tests/components/yeelight/test_init.py
+++ b/tests/components/yeelight/test_init.py
@@ -60,9 +60,10 @@ async def test_ip_changes_fallback_discovery(hass: HomeAssistant) -> None:
mocked_fail_bulb = _mocked_bulb(cannot_connect=True)
mocked_fail_bulb.bulb_type = BulbType.WhiteTempMood
- with patch(
- f"{MODULE}.AsyncBulb", return_value=mocked_fail_bulb
- ), _patch_discovery():
+ with (
+ patch(f"{MODULE}.AsyncBulb", return_value=mocked_fail_bulb),
+ _patch_discovery(),
+ ):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -162,11 +163,13 @@ async def test_setup_discovery_with_manually_configured_network_adapter(
config_entry.add_to_hass(hass)
mocked_bulb = _mocked_bulb()
- with _patch_discovery(), patch(
- f"{MODULE}.AsyncBulb", return_value=mocked_bulb
- ), patch(
- "homeassistant.components.zeroconf.network.async_get_adapters",
- return_value=_ADAPTERS_WITH_MANUAL_CONFIG,
+ with (
+ _patch_discovery(),
+ patch(f"{MODULE}.AsyncBulb", return_value=mocked_bulb),
+ patch(
+ "homeassistant.components.zeroconf.network.async_get_adapters",
+ return_value=_ADAPTERS_WITH_MANUAL_CONFIG,
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -218,11 +221,13 @@ async def test_setup_discovery_with_manually_configured_network_adapter_one_fail
config_entry.add_to_hass(hass)
mocked_bulb = _mocked_bulb()
- with _patch_discovery(), patch(
- f"{MODULE}.AsyncBulb", return_value=mocked_bulb
- ), patch(
- "homeassistant.components.zeroconf.network.async_get_adapters",
- return_value=_ADAPTERS_WITH_MANUAL_CONFIG_ONE_FAILING,
+ with (
+ _patch_discovery(),
+ patch(f"{MODULE}.AsyncBulb", return_value=mocked_bulb),
+ patch(
+ "homeassistant.components.zeroconf.network.async_get_adapters",
+ return_value=_ADAPTERS_WITH_MANUAL_CONFIG_ONE_FAILING,
+ ),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -339,17 +344,23 @@ async def test_bulb_off_while_adding_in_ha(hass: HomeAssistant) -> None:
mocked_bulb = _mocked_bulb(cannot_connect=True)
mocked_bulb.bulb_type = BulbType.WhiteTempMood
- with patch(f"{MODULE}.AsyncBulb", return_value=mocked_bulb), _patch_discovery(
- no_device=True
- ), _patch_discovery_timeout(), _patch_discovery_interval():
+ with (
+ patch(f"{MODULE}.AsyncBulb", return_value=mocked_bulb),
+ _patch_discovery(no_device=True),
+ _patch_discovery_timeout(),
+ _patch_discovery_interval(),
+ ):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.SETUP_RETRY
- with patch(f"{MODULE}.AsyncBulb", return_value=_mocked_bulb()), _patch_discovery(
- no_device=True
- ), _patch_discovery_timeout(), _patch_discovery_interval():
+ with (
+ patch(f"{MODULE}.AsyncBulb", return_value=_mocked_bulb()),
+ _patch_discovery(no_device=True),
+ _patch_discovery_timeout(),
+ _patch_discovery_interval(),
+ ):
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=2))
await hass.async_block_till_done()
@@ -422,8 +433,9 @@ async def test_unload_before_discovery(
mocked_bulb = _mocked_bulb(cannot_connect=True)
- with _patch_discovery(no_device=True), patch(
- f"{MODULE}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(no_device=True),
+ patch(f"{MODULE}.AsyncBulb", return_value=mocked_bulb),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -442,10 +454,11 @@ async def test_async_listen_error_has_host_with_id(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with _patch_discovery(
- no_device=True
- ), _patch_discovery_timeout(), _patch_discovery_interval(), patch(
- f"{MODULE}.AsyncBulb", return_value=_mocked_bulb(cannot_connect=True)
+ with (
+ _patch_discovery(no_device=True),
+ _patch_discovery_timeout(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE}.AsyncBulb", return_value=_mocked_bulb(cannot_connect=True)),
):
await hass.config_entries.async_setup(config_entry.entry_id)
@@ -457,10 +470,11 @@ async def test_async_listen_error_has_host_without_id(hass: HomeAssistant) -> No
config_entry = MockConfigEntry(domain=DOMAIN, data={CONF_HOST: "127.0.0.1"})
config_entry.add_to_hass(hass)
- with _patch_discovery(
- no_device=True
- ), _patch_discovery_timeout(), _patch_discovery_interval(), patch(
- f"{MODULE}.AsyncBulb", return_value=_mocked_bulb(cannot_connect=True)
+ with (
+ _patch_discovery(no_device=True),
+ _patch_discovery_timeout(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE}.AsyncBulb", return_value=_mocked_bulb(cannot_connect=True)),
):
await hass.config_entries.async_setup(config_entry.entry_id)
@@ -477,8 +491,11 @@ async def test_async_setup_with_missing_id(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with _patch_discovery(), _patch_discovery_timeout(), _patch_discovery_interval(), patch(
- f"{MODULE}.AsyncBulb", return_value=_mocked_bulb(cannot_connect=True)
+ with (
+ _patch_discovery(),
+ _patch_discovery_timeout(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE}.AsyncBulb", return_value=_mocked_bulb(cannot_connect=True)),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -487,8 +504,11 @@ async def test_async_setup_with_missing_id(hass: HomeAssistant) -> None:
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=2))
await hass.async_block_till_done()
- with _patch_discovery(), _patch_discovery_timeout(), _patch_discovery_interval(), patch(
- f"{MODULE}.AsyncBulb", return_value=_mocked_bulb()
+ with (
+ _patch_discovery(),
+ _patch_discovery_timeout(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE}.AsyncBulb", return_value=_mocked_bulb()),
):
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=4))
await hass.async_block_till_done()
@@ -504,8 +524,11 @@ async def test_async_setup_with_missing_unique_id(hass: HomeAssistant) -> None:
)
config_entry.add_to_hass(hass)
- with _patch_discovery(), _patch_discovery_timeout(), _patch_discovery_interval(), patch(
- f"{MODULE}.AsyncBulb", return_value=_mocked_bulb(cannot_connect=True)
+ with (
+ _patch_discovery(),
+ _patch_discovery_timeout(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE}.AsyncBulb", return_value=_mocked_bulb(cannot_connect=True)),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -514,8 +537,11 @@ async def test_async_setup_with_missing_unique_id(hass: HomeAssistant) -> None:
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=2))
await hass.async_block_till_done()
- with _patch_discovery(), _patch_discovery_timeout(), _patch_discovery_interval(), patch(
- f"{MODULE}.AsyncBulb", return_value=_mocked_bulb()
+ with (
+ _patch_discovery(),
+ _patch_discovery_timeout(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE}.AsyncBulb", return_value=_mocked_bulb()),
):
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=4))
await hass.async_block_till_done()
@@ -533,8 +559,11 @@ async def test_connection_dropped_resyncs_properties(hass: HomeAssistant) -> Non
config_entry.add_to_hass(hass)
mocked_bulb = _mocked_bulb()
- with _patch_discovery(), _patch_discovery_timeout(), _patch_discovery_interval(), patch(
- f"{MODULE}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(),
+ _patch_discovery_timeout(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE}.AsyncBulb", return_value=mocked_bulb),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -566,8 +595,11 @@ async def test_oserror_on_first_update_results_in_unavailable(
mocked_bulb = _mocked_bulb()
mocked_bulb.async_get_properties = AsyncMock(side_effect=OSError)
- with _patch_discovery(), _patch_discovery_timeout(), _patch_discovery_interval(), patch(
- f"{MODULE}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(),
+ _patch_discovery_timeout(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE}.AsyncBulb", return_value=mocked_bulb),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -593,8 +625,11 @@ async def test_non_oserror_exception_on_first_update(
mocked_bulb = _mocked_bulb()
mocked_bulb.async_get_properties = AsyncMock(side_effect=exception)
- with _patch_discovery(), _patch_discovery_timeout(), _patch_discovery_interval(), patch(
- f"{MODULE}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(),
+ _patch_discovery_timeout(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE}.AsyncBulb", return_value=mocked_bulb),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -612,10 +647,11 @@ async def test_async_setup_with_discovery_not_working(hass: HomeAssistant) -> No
)
config_entry.add_to_hass(hass)
- with _patch_discovery(
- no_device=True
- ), _patch_discovery_timeout(), _patch_discovery_interval(), patch(
- f"{MODULE}.AsyncBulb", return_value=_mocked_bulb()
+ with (
+ _patch_discovery(no_device=True),
+ _patch_discovery_timeout(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE}.AsyncBulb", return_value=_mocked_bulb()),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -636,8 +672,11 @@ async def test_async_setup_retries_with_wrong_device(
)
config_entry.add_to_hass(hass)
- with _patch_discovery(), _patch_discovery_timeout(), _patch_discovery_interval(), patch(
- f"{MODULE}.AsyncBulb", return_value=_mocked_bulb()
+ with (
+ _patch_discovery(),
+ _patch_discovery_timeout(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE}.AsyncBulb", return_value=_mocked_bulb()),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/yeelight/test_light.py b/tests/components/yeelight/test_light.py
index 4fed4f602e4..052b6d3223a 100644
--- a/tests/components/yeelight/test_light.py
+++ b/tests/components/yeelight/test_light.py
@@ -153,8 +153,10 @@ async def test_services(hass: HomeAssistant, caplog: pytest.LogCaptureFixture) -
config_entry.add_to_hass(hass)
mocked_bulb = _mocked_bulb()
- with _patch_discovery(), _patch_discovery_interval(), patch(
- f"{MODULE}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE}.AsyncBulb", return_value=mocked_bulb),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -542,8 +544,10 @@ async def test_update_errors(
config_entry.add_to_hass(hass)
mocked_bulb = _mocked_bulb()
- with _patch_discovery(), _patch_discovery_interval(), patch(
- f"{MODULE}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE}.AsyncBulb", return_value=mocked_bulb),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -590,8 +594,10 @@ async def test_state_already_set_avoid_ratelimit(hass: HomeAssistant) -> None:
domain=DOMAIN, data={**CONFIG_ENTRY_DATA, CONF_NIGHTLIGHT_SWITCH: False}
)
config_entry.add_to_hass(hass)
- with _patch_discovery(), _patch_discovery_interval(), patch(
- f"{MODULE}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE}.AsyncBulb", return_value=mocked_bulb),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -1412,8 +1418,10 @@ async def test_effects(hass: HomeAssistant) -> None:
config_entry.add_to_hass(hass)
mocked_bulb = _mocked_bulb()
- with _patch_discovery(), _patch_discovery_interval(), patch(
- f"{MODULE}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE}.AsyncBulb", return_value=mocked_bulb),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -1574,8 +1582,9 @@ async def test_ambilight_with_nightlight_disabled(hass: HomeAssistant) -> None:
options={**CONFIG_ENTRY_DATA, CONF_NIGHTLIGHT_SWITCH: False},
)
config_entry.add_to_hass(hass)
- with _patch_discovery(capabilities=capabilities), patch(
- f"{MODULE}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(capabilities=capabilities),
+ patch(f"{MODULE}.AsyncBulb", return_value=mocked_bulb),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -1601,8 +1610,10 @@ async def test_state_fails_to_update_triggers_update(hass: HomeAssistant) -> Non
domain=DOMAIN, data={**CONFIG_ENTRY_DATA, CONF_NIGHTLIGHT_SWITCH: False}
)
config_entry.add_to_hass(hass)
- with _patch_discovery(), _patch_discovery_interval(), patch(
- f"{MODULE}.AsyncBulb", return_value=mocked_bulb
+ with (
+ _patch_discovery(),
+ _patch_discovery_interval(),
+ patch(f"{MODULE}.AsyncBulb", return_value=mocked_bulb),
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/yolink/test_config_flow.py b/tests/components/yolink/test_config_flow.py
index 60b190025c6..f7abda0bc4b 100644
--- a/tests/components/yolink/test_config_flow.py
+++ b/tests/components/yolink/test_config_flow.py
@@ -87,9 +87,12 @@ async def test_full_flow(
},
)
- with patch("homeassistant.components.yolink.api.ConfigEntryAuth"), patch(
- "homeassistant.components.yolink.async_setup_entry", return_value=True
- ) as mock_setup:
+ 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"])
assert result["data"]["auth_implementation"] == DOMAIN
@@ -202,9 +205,12 @@ async def test_reauthentication(
},
)
- with patch("homeassistant.components.yolink.api.ConfigEntryAuth"), patch(
- "homeassistant.components.yolink.async_setup_entry", return_value=True
- ) as mock_setup:
+ 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"])
token_data = old_entry.data["token"]
assert token_data["access_token"] == "mock-access-token"
diff --git a/tests/components/youtube/test_config_flow.py b/tests/components/youtube/test_config_flow.py
index c735add840b..c8857626384 100644
--- a/tests/components/youtube/test_config_flow.py
+++ b/tests/components/youtube/test_config_flow.py
@@ -55,11 +55,14 @@ async def test_full_flow(
assert resp.status == 200
assert resp.headers["content-type"] == "text/html; charset=utf-8"
- with patch(
- "homeassistant.components.youtube.async_setup_entry", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.youtube.config_flow.YouTube",
- return_value=MockYouTube(),
+ with (
+ patch(
+ "homeassistant.components.youtube.async_setup_entry", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.youtube.config_flow.YouTube",
+ return_value=MockYouTube(),
+ ),
):
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == FlowResultType.FORM
@@ -112,10 +115,11 @@ async def test_flow_abort_without_channel(
assert resp.headers["content-type"] == "text/html; charset=utf-8"
service = MockYouTube(channel_fixture="youtube/get_no_channel.json")
- with patch(
- "homeassistant.components.youtube.async_setup_entry", return_value=True
- ), patch(
- "homeassistant.components.youtube.config_flow.YouTube", return_value=service
+ with (
+ patch("homeassistant.components.youtube.async_setup_entry", return_value=True),
+ patch(
+ "homeassistant.components.youtube.config_flow.YouTube", return_value=service
+ ),
):
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == FlowResultType.ABORT
@@ -152,10 +156,11 @@ async def test_flow_abort_without_subscriptions(
assert resp.headers["content-type"] == "text/html; charset=utf-8"
service = MockYouTube(subscriptions_fixture="youtube/get_no_subscriptions.json")
- with patch(
- "homeassistant.components.youtube.async_setup_entry", return_value=True
- ), patch(
- "homeassistant.components.youtube.config_flow.YouTube", return_value=service
+ with (
+ patch("homeassistant.components.youtube.async_setup_entry", return_value=True),
+ patch(
+ "homeassistant.components.youtube.config_flow.YouTube", return_value=service
+ ),
):
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == FlowResultType.ABORT
@@ -282,11 +287,14 @@ async def test_reauth(
)
youtube = MockYouTube(channel_fixture=f"youtube/{fixture}.json")
- with patch(
- "homeassistant.components.youtube.async_setup_entry", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.youtube.config_flow.YouTube",
- return_value=youtube,
+ with (
+ patch(
+ "homeassistant.components.youtube.async_setup_entry", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.youtube.config_flow.YouTube",
+ return_value=youtube,
+ ),
):
result = await hass.config_entries.flow.async_configure(result["flow_id"])
diff --git a/tests/components/zeroconf/test_init.py b/tests/components/zeroconf/test_init.py
index 0f70d862c4c..6a21212ed6e 100644
--- a/tests/components/zeroconf/test_init.py
+++ b/tests/components/zeroconf/test_init.py
@@ -160,17 +160,20 @@ async def test_setup(hass: HomeAssistant, mock_async_zeroconf: None) -> None:
],
"_Volumio._tcp.local.": [{"domain": "volumio"}],
}
- with patch.dict(
- zc_gen.ZEROCONF,
- mock_zc,
- clear=True,
- ), patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_config_flow, patch.object(
- zeroconf, "AsyncServiceBrowser", side_effect=service_update_mock
- ) as mock_service_browser, patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo",
- side_effect=get_service_info_mock,
+ with (
+ patch.dict(
+ zc_gen.ZEROCONF,
+ mock_zc,
+ clear=True,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ patch.object(
+ zeroconf, "AsyncServiceBrowser", side_effect=service_update_mock
+ ) as mock_service_browser,
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo",
+ side_effect=get_service_info_mock,
+ ),
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -195,32 +198,36 @@ async def test_setup_with_overly_long_url_and_name(
hass: HomeAssistant, mock_async_zeroconf: None, caplog: pytest.LogCaptureFixture
) -> None:
"""Test we still setup with long urls and names."""
- with patch.object(hass.config_entries.flow, "async_init"), patch.object(
- zeroconf, "AsyncServiceBrowser", side_effect=service_update_mock
- ), patch(
- "homeassistant.components.zeroconf.get_url",
- return_value=(
- "https://this.url.is.way.too.long/very/deep/path/that/will/make/us/go/over"
- "/the/maximum/string/length/and/would/cause/zeroconf/to/fail/to/startup"
- "/because/the/key/and/value/can/only/be/255/bytes/and/this/string/is/a"
- "/bit/longer/than/the/maximum/length/that/we/allow/for/a/value"
+ with (
+ patch.object(hass.config_entries.flow, "async_init"),
+ patch.object(zeroconf, "AsyncServiceBrowser", side_effect=service_update_mock),
+ patch(
+ "homeassistant.components.zeroconf.get_url",
+ return_value=(
+ "https://this.url.is.way.too.long/very/deep/path/that/will/make/us/go/over"
+ "/the/maximum/string/length/and/would/cause/zeroconf/to/fail/to/startup"
+ "/because/the/key/and/value/can/only/be/255/bytes/and/this/string/is/a"
+ "/bit/longer/than/the/maximum/length/that/we/allow/for/a/value"
+ ),
),
- ), patch.object(
- hass.config,
- "location_name",
- (
- "\u00dcBER \u00dcber German Umlaut long string long string long string long"
- " string long string long string long string long string long string long"
- " string long string long string long string long string long string long"
- " string long string long string long string long string long string long"
- " string long string long string long string long string long string long"
- " string long string long string long string long string long string long"
- " string long string long string long string long string long string long"
- " string long string long string long string long string long string long"
- " string long string long string long string long string"
+ patch.object(
+ hass.config,
+ "location_name",
+ (
+ "\u00dcBER \u00dcber German Umlaut long string long string long string long"
+ " string long string long string long string long string long string long"
+ " string long string long string long string long string long string long"
+ " string long string long string long string long string long string long"
+ " string long string long string long string long string long string long"
+ " string long string long string long string long string long string long"
+ " string long string long string long string long string long string long"
+ " string long string long string long string long string long string long"
+ " string long string long string long string long string"
+ ),
+ ),
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo.async_request",
),
- ), patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo.async_request",
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
@@ -234,11 +241,13 @@ async def test_setup_with_defaults(
hass: HomeAssistant, mock_zeroconf: None, mock_async_zeroconf: None
) -> None:
"""Test default interface config."""
- with patch.object(hass.config_entries.flow, "async_init"), patch.object(
- zeroconf, "AsyncServiceBrowser", side_effect=service_update_mock
- ), patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo",
- side_effect=get_service_info_mock,
+ with (
+ patch.object(hass.config_entries.flow, "async_init"),
+ patch.object(zeroconf, "AsyncServiceBrowser", side_effect=service_update_mock),
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo",
+ side_effect=get_service_info_mock,
+ ),
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -263,25 +272,28 @@ async def test_zeroconf_match_macaddress(
ServiceStateChange.Added,
)
- with patch.dict(
- zc_gen.ZEROCONF,
- {
- "_http._tcp.local.": [
- {
- "domain": "shelly",
- "name": "shelly*",
- "properties": {"macaddress": "ffaadd*"},
- }
- ]
- },
- clear=True,
- ), patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_config_flow, patch.object(
- zeroconf, "AsyncServiceBrowser", side_effect=http_only_service_update_mock
- ) as mock_service_browser, patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo",
- side_effect=get_zeroconf_info_mock("FFAADDCC11DD"),
+ with (
+ patch.dict(
+ zc_gen.ZEROCONF,
+ {
+ "_http._tcp.local.": [
+ {
+ "domain": "shelly",
+ "name": "shelly*",
+ "properties": {"macaddress": "ffaadd*"},
+ }
+ ]
+ },
+ clear=True,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ patch.object(
+ zeroconf, "AsyncServiceBrowser", side_effect=http_only_service_update_mock
+ ) as mock_service_browser,
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo",
+ side_effect=get_zeroconf_info_mock("FFAADDCC11DD"),
+ ),
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -307,21 +319,24 @@ async def test_zeroconf_match_manufacturer(
ServiceStateChange.Added,
)
- with patch.dict(
- zc_gen.ZEROCONF,
- {
- "_airplay._tcp.local.": [
- {"domain": "samsungtv", "properties": {"manufacturer": "samsung*"}}
- ]
- },
- clear=True,
- ), patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_config_flow, patch.object(
- zeroconf, "AsyncServiceBrowser", side_effect=http_only_service_update_mock
- ) as mock_service_browser, patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo",
- side_effect=get_zeroconf_info_mock_manufacturer("Samsung Electronics"),
+ with (
+ patch.dict(
+ zc_gen.ZEROCONF,
+ {
+ "_airplay._tcp.local.": [
+ {"domain": "samsungtv", "properties": {"manufacturer": "samsung*"}}
+ ]
+ },
+ clear=True,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ patch.object(
+ zeroconf, "AsyncServiceBrowser", side_effect=http_only_service_update_mock
+ ) as mock_service_browser,
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo",
+ side_effect=get_zeroconf_info_mock_manufacturer("Samsung Electronics"),
+ ),
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -346,21 +361,24 @@ async def test_zeroconf_match_model(
ServiceStateChange.Added,
)
- with patch.dict(
- zc_gen.ZEROCONF,
- {
- "_airplay._tcp.local.": [
- {"domain": "appletv", "properties": {"model": "appletv*"}}
- ]
- },
- clear=True,
- ), patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_config_flow, patch.object(
- zeroconf, "AsyncServiceBrowser", side_effect=http_only_service_update_mock
- ) as mock_service_browser, patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo",
- side_effect=get_zeroconf_info_mock_model("appletv"),
+ with (
+ patch.dict(
+ zc_gen.ZEROCONF,
+ {
+ "_airplay._tcp.local.": [
+ {"domain": "appletv", "properties": {"model": "appletv*"}}
+ ]
+ },
+ clear=True,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ patch.object(
+ zeroconf, "AsyncServiceBrowser", side_effect=http_only_service_update_mock
+ ) as mock_service_browser,
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo",
+ side_effect=get_zeroconf_info_mock_model("appletv"),
+ ),
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -385,21 +403,24 @@ async def test_zeroconf_match_manufacturer_not_present(
ServiceStateChange.Added,
)
- with patch.dict(
- zc_gen.ZEROCONF,
- {
- "_airplay._tcp.local.": [
- {"domain": "samsungtv", "properties": {"manufacturer": "samsung*"}}
- ]
- },
- clear=True,
- ), patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_config_flow, patch.object(
- zeroconf, "AsyncServiceBrowser", side_effect=http_only_service_update_mock
- ) as mock_service_browser, patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo",
- side_effect=get_zeroconf_info_mock("aabbccddeeff"),
+ with (
+ patch.dict(
+ zc_gen.ZEROCONF,
+ {
+ "_airplay._tcp.local.": [
+ {"domain": "samsungtv", "properties": {"manufacturer": "samsung*"}}
+ ]
+ },
+ clear=True,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ patch.object(
+ zeroconf, "AsyncServiceBrowser", side_effect=http_only_service_update_mock
+ ) as mock_service_browser,
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo",
+ side_effect=get_zeroconf_info_mock("aabbccddeeff"),
+ ),
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -423,17 +444,20 @@ async def test_zeroconf_no_match(
ServiceStateChange.Added,
)
- with patch.dict(
- zc_gen.ZEROCONF,
- {"_http._tcp.local.": [{"domain": "shelly", "name": "shelly*"}]},
- clear=True,
- ), patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_config_flow, patch.object(
- zeroconf, "AsyncServiceBrowser", side_effect=http_only_service_update_mock
- ) as mock_service_browser, patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo",
- side_effect=get_zeroconf_info_mock("FFAADDCC11DD"),
+ with (
+ patch.dict(
+ zc_gen.ZEROCONF,
+ {"_http._tcp.local.": [{"domain": "shelly", "name": "shelly*"}]},
+ clear=True,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ patch.object(
+ zeroconf, "AsyncServiceBrowser", side_effect=http_only_service_update_mock
+ ) as mock_service_browser,
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo",
+ side_effect=get_zeroconf_info_mock("FFAADDCC11DD"),
+ ),
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -457,21 +481,24 @@ async def test_zeroconf_no_match_manufacturer(
ServiceStateChange.Added,
)
- with patch.dict(
- zc_gen.ZEROCONF,
- {
- "_airplay._tcp.local.": [
- {"domain": "samsungtv", "properties": {"manufacturer": "samsung*"}}
- ]
- },
- clear=True,
- ), patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_config_flow, patch.object(
- zeroconf, "AsyncServiceBrowser", side_effect=http_only_service_update_mock
- ) as mock_service_browser, patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo",
- side_effect=get_zeroconf_info_mock_manufacturer("Not Samsung Electronics"),
+ with (
+ patch.dict(
+ zc_gen.ZEROCONF,
+ {
+ "_airplay._tcp.local.": [
+ {"domain": "samsungtv", "properties": {"manufacturer": "samsung*"}}
+ ]
+ },
+ clear=True,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ patch.object(
+ zeroconf, "AsyncServiceBrowser", side_effect=http_only_service_update_mock
+ ) as mock_service_browser,
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo",
+ side_effect=get_zeroconf_info_mock_manufacturer("Not Samsung Electronics"),
+ ),
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -485,25 +512,29 @@ async def test_homekit_match_partial_space(
hass: HomeAssistant, mock_async_zeroconf: None
) -> None:
"""Test configured options for a device are loaded via config entry."""
- with patch.dict(
- zc_gen.ZEROCONF,
- {"_hap._tcp.local.": [{"domain": "homekit_controller"}]},
- clear=True,
- ), patch.dict(
- zc_gen.HOMEKIT,
- {"LIFX": {"domain": "lifx", "always_discover": True}},
- clear=True,
- ), patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_config_flow, patch.object(
- zeroconf,
- "AsyncServiceBrowser",
- side_effect=lambda *args, **kwargs: service_update_mock(
- *args, **kwargs, limit_service="_hap._tcp.local."
+ with (
+ patch.dict(
+ zc_gen.ZEROCONF,
+ {"_hap._tcp.local.": [{"domain": "homekit_controller"}]},
+ clear=True,
+ ),
+ patch.dict(
+ zc_gen.HOMEKIT,
+ {"LIFX": {"domain": "lifx", "always_discover": True}},
+ clear=True,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ patch.object(
+ zeroconf,
+ "AsyncServiceBrowser",
+ side_effect=lambda *args, **kwargs: service_update_mock(
+ *args, **kwargs, limit_service="_hap._tcp.local."
+ ),
+ ) as mock_service_browser,
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo",
+ side_effect=get_homekit_info_mock("LIFX bulb", HOMEKIT_STATUS_UNPAIRED),
),
- ) as mock_service_browser, patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo",
- side_effect=get_homekit_info_mock("LIFX bulb", HOMEKIT_STATUS_UNPAIRED),
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -523,25 +554,29 @@ async def test_device_with_invalid_name(
hass: HomeAssistant, mock_async_zeroconf: None, caplog: pytest.LogCaptureFixture
) -> None:
"""Test we ignore devices with an invalid name."""
- with patch.dict(
- zc_gen.ZEROCONF,
- {"_hap._tcp.local.": [{"domain": "homekit_controller"}]},
- clear=True,
- ), patch.dict(
- zc_gen.HOMEKIT,
- {"LIFX": {"domain": "lifx", "always_discover": True}},
- clear=True,
- ), patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_config_flow, patch.object(
- zeroconf,
- "AsyncServiceBrowser",
- side_effect=lambda *args, **kwargs: service_update_mock(
- *args, **kwargs, limit_service="_hap._tcp.local."
+ with (
+ patch.dict(
+ zc_gen.ZEROCONF,
+ {"_hap._tcp.local.": [{"domain": "homekit_controller"}]},
+ clear=True,
+ ),
+ patch.dict(
+ zc_gen.HOMEKIT,
+ {"LIFX": {"domain": "lifx", "always_discover": True}},
+ clear=True,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ patch.object(
+ zeroconf,
+ "AsyncServiceBrowser",
+ side_effect=lambda *args, **kwargs: service_update_mock(
+ *args, **kwargs, limit_service="_hap._tcp.local."
+ ),
+ ) as mock_service_browser,
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo",
+ side_effect=BadTypeInNameException,
),
- ) as mock_service_browser, patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo",
- side_effect=BadTypeInNameException,
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -556,25 +591,31 @@ async def test_homekit_match_partial_dash(
hass: HomeAssistant, mock_async_zeroconf: None
) -> None:
"""Test configured options for a device are loaded via config entry."""
- with patch.dict(
- zc_gen.ZEROCONF,
- {"_hap._udp.local.": [{"domain": "homekit_controller"}]},
- clear=True,
- ), patch.dict(
- zc_gen.HOMEKIT,
- {"Smart Bridge": {"domain": "lutron_caseta", "always_discover": False}},
- clear=True,
- ), patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_config_flow, patch.object(
- zeroconf,
- "AsyncServiceBrowser",
- side_effect=lambda *args, **kwargs: service_update_mock(
- *args, **kwargs, limit_service="_hap._udp.local."
+ with (
+ patch.dict(
+ zc_gen.ZEROCONF,
+ {"_hap._udp.local.": [{"domain": "homekit_controller"}]},
+ clear=True,
+ ),
+ patch.dict(
+ zc_gen.HOMEKIT,
+ {"Smart Bridge": {"domain": "lutron_caseta", "always_discover": False}},
+ clear=True,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ patch.object(
+ zeroconf,
+ "AsyncServiceBrowser",
+ side_effect=lambda *args, **kwargs: service_update_mock(
+ *args, **kwargs, limit_service="_hap._udp.local."
+ ),
+ ) as mock_service_browser,
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo",
+ side_effect=get_homekit_info_mock(
+ "Smart Bridge-001", HOMEKIT_STATUS_UNPAIRED
+ ),
),
- ) as mock_service_browser, patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo",
- side_effect=get_homekit_info_mock("Smart Bridge-001", HOMEKIT_STATUS_UNPAIRED),
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -589,25 +630,29 @@ async def test_homekit_match_partial_fnmatch(
hass: HomeAssistant, mock_async_zeroconf: None
) -> None:
"""Test matching homekit devices with fnmatch."""
- with patch.dict(
- zc_gen.ZEROCONF,
- {"_hap._tcp.local.": [{"domain": "homekit_controller"}]},
- clear=True,
- ), patch.dict(
- zc_gen.HOMEKIT,
- {"YLDP*": {"domain": "yeelight", "always_discover": False}},
- clear=True,
- ), patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_config_flow, patch.object(
- zeroconf,
- "AsyncServiceBrowser",
- side_effect=lambda *args, **kwargs: service_update_mock(
- *args, **kwargs, limit_service="_hap._tcp.local."
+ with (
+ patch.dict(
+ zc_gen.ZEROCONF,
+ {"_hap._tcp.local.": [{"domain": "homekit_controller"}]},
+ clear=True,
+ ),
+ patch.dict(
+ zc_gen.HOMEKIT,
+ {"YLDP*": {"domain": "yeelight", "always_discover": False}},
+ clear=True,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ patch.object(
+ zeroconf,
+ "AsyncServiceBrowser",
+ side_effect=lambda *args, **kwargs: service_update_mock(
+ *args, **kwargs, limit_service="_hap._tcp.local."
+ ),
+ ) as mock_service_browser,
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo",
+ side_effect=get_homekit_info_mock("YLDP13YL", HOMEKIT_STATUS_UNPAIRED),
),
- ) as mock_service_browser, patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo",
- side_effect=get_homekit_info_mock("YLDP13YL", HOMEKIT_STATUS_UNPAIRED),
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -622,25 +667,29 @@ async def test_homekit_match_full(
hass: HomeAssistant, mock_async_zeroconf: None
) -> None:
"""Test configured options for a device are loaded via config entry."""
- with patch.dict(
- zc_gen.ZEROCONF,
- {"_hap._udp.local.": [{"domain": "homekit_controller"}]},
- clear=True,
- ), patch.dict(
- zc_gen.HOMEKIT,
- {"BSB002": {"domain": "hue", "always_discover": False}},
- clear=True,
- ), patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_config_flow, patch.object(
- zeroconf,
- "AsyncServiceBrowser",
- side_effect=lambda *args, **kwargs: service_update_mock(
- *args, **kwargs, limit_service="_hap._udp.local."
+ with (
+ patch.dict(
+ zc_gen.ZEROCONF,
+ {"_hap._udp.local.": [{"domain": "homekit_controller"}]},
+ clear=True,
+ ),
+ patch.dict(
+ zc_gen.HOMEKIT,
+ {"BSB002": {"domain": "hue", "always_discover": False}},
+ clear=True,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ patch.object(
+ zeroconf,
+ "AsyncServiceBrowser",
+ side_effect=lambda *args, **kwargs: service_update_mock(
+ *args, **kwargs, limit_service="_hap._udp.local."
+ ),
+ ) as mock_service_browser,
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo",
+ side_effect=get_homekit_info_mock("BSB002", HOMEKIT_STATUS_UNPAIRED),
),
- ) as mock_service_browser, patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo",
- side_effect=get_homekit_info_mock("BSB002", HOMEKIT_STATUS_UNPAIRED),
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -655,28 +704,32 @@ async def test_homekit_already_paired(
hass: HomeAssistant, mock_async_zeroconf: None
) -> None:
"""Test that an already paired device is sent to homekit_controller."""
- with patch.dict(
- zc_gen.ZEROCONF,
- {"_hap._tcp.local.": [{"domain": "homekit_controller"}]},
- clear=True,
- ), patch.dict(
- zc_gen.HOMEKIT,
- {
- "AC02": {"domain": "tado", "always_discover": True},
- "tado": {"domain": "tado", "always_discover": True},
- },
- clear=True,
- ), patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_config_flow, patch.object(
- zeroconf,
- "AsyncServiceBrowser",
- side_effect=lambda *args, **kwargs: service_update_mock(
- *args, **kwargs, limit_service="_hap._tcp.local."
+ with (
+ patch.dict(
+ zc_gen.ZEROCONF,
+ {"_hap._tcp.local.": [{"domain": "homekit_controller"}]},
+ clear=True,
+ ),
+ patch.dict(
+ zc_gen.HOMEKIT,
+ {
+ "AC02": {"domain": "tado", "always_discover": True},
+ "tado": {"domain": "tado", "always_discover": True},
+ },
+ clear=True,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ patch.object(
+ zeroconf,
+ "AsyncServiceBrowser",
+ side_effect=lambda *args, **kwargs: service_update_mock(
+ *args, **kwargs, limit_service="_hap._tcp.local."
+ ),
+ ) as mock_service_browser,
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo",
+ side_effect=get_homekit_info_mock("tado", HOMEKIT_STATUS_PAIRED),
),
- ) as mock_service_browser, patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo",
- side_effect=get_homekit_info_mock("tado", HOMEKIT_STATUS_PAIRED),
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -692,25 +745,29 @@ async def test_homekit_invalid_paring_status(
hass: HomeAssistant, mock_async_zeroconf: None
) -> None:
"""Test that missing paring data is not sent to homekit_controller."""
- with patch.dict(
- zc_gen.ZEROCONF,
- {"_hap._tcp.local.": [{"domain": "homekit_controller"}]},
- clear=True,
- ), patch.dict(
- zc_gen.HOMEKIT,
- {"Smart Bridge": {"domain": "lutron_caseta", "always_discover": False}},
- clear=True,
- ), patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_config_flow, patch.object(
- zeroconf,
- "AsyncServiceBrowser",
- side_effect=lambda *args, **kwargs: service_update_mock(
- *args, **kwargs, limit_service="_hap._tcp.local."
+ with (
+ patch.dict(
+ zc_gen.ZEROCONF,
+ {"_hap._tcp.local.": [{"domain": "homekit_controller"}]},
+ clear=True,
+ ),
+ patch.dict(
+ zc_gen.HOMEKIT,
+ {"Smart Bridge": {"domain": "lutron_caseta", "always_discover": False}},
+ clear=True,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ patch.object(
+ zeroconf,
+ "AsyncServiceBrowser",
+ side_effect=lambda *args, **kwargs: service_update_mock(
+ *args, **kwargs, limit_service="_hap._tcp.local."
+ ),
+ ) as mock_service_browser,
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo",
+ side_effect=get_homekit_info_mock("Smart Bridge", b"invalid"),
),
- ) as mock_service_browser, patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo",
- side_effect=get_homekit_info_mock("Smart Bridge", b"invalid"),
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -725,18 +782,21 @@ async def test_homekit_not_paired(
hass: HomeAssistant, mock_async_zeroconf: None
) -> None:
"""Test that an not paired device is sent to homekit_controller."""
- with patch.dict(
- zc_gen.ZEROCONF,
- {"_hap._tcp.local.": [{"domain": "homekit_controller"}]},
- clear=True,
- ), patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_config_flow, patch.object(
- zeroconf, "AsyncServiceBrowser", side_effect=service_update_mock
- ) as mock_service_browser, patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo",
- side_effect=get_homekit_info_mock(
- "this_will_not_match_any_integration", HOMEKIT_STATUS_UNPAIRED
+ with (
+ patch.dict(
+ zc_gen.ZEROCONF,
+ {"_hap._tcp.local.": [{"domain": "homekit_controller"}]},
+ clear=True,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ patch.object(
+ zeroconf, "AsyncServiceBrowser", side_effect=service_update_mock
+ ) as mock_service_browser,
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo",
+ side_effect=get_homekit_info_mock(
+ "this_will_not_match_any_integration", HOMEKIT_STATUS_UNPAIRED
+ ),
),
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
@@ -758,25 +818,29 @@ async def test_homekit_controller_still_discovered_unpaired_for_cloud(
Since we prefer local control, if the integration that is being discovered
is cloud AND the homekit device is unpaired we still want to discovery it
"""
- with patch.dict(
- zc_gen.ZEROCONF,
- {"_hap._udp.local.": [{"domain": "homekit_controller"}]},
- clear=True,
- ), patch.dict(
- zc_gen.HOMEKIT,
- {"Rachio": {"domain": "rachio", "always_discover": True}},
- clear=True,
- ), patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_config_flow, patch.object(
- zeroconf,
- "AsyncServiceBrowser",
- side_effect=lambda *args, **kwargs: service_update_mock(
- *args, **kwargs, limit_service="_hap._udp.local."
+ with (
+ patch.dict(
+ zc_gen.ZEROCONF,
+ {"_hap._udp.local.": [{"domain": "homekit_controller"}]},
+ clear=True,
+ ),
+ patch.dict(
+ zc_gen.HOMEKIT,
+ {"Rachio": {"domain": "rachio", "always_discover": True}},
+ clear=True,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ patch.object(
+ zeroconf,
+ "AsyncServiceBrowser",
+ side_effect=lambda *args, **kwargs: service_update_mock(
+ *args, **kwargs, limit_service="_hap._udp.local."
+ ),
+ ) as mock_service_browser,
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo",
+ side_effect=get_homekit_info_mock("Rachio-xyz", HOMEKIT_STATUS_UNPAIRED),
),
- ) as mock_service_browser, patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo",
- side_effect=get_homekit_info_mock("Rachio-xyz", HOMEKIT_STATUS_UNPAIRED),
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -798,25 +862,29 @@ async def test_homekit_controller_still_discovered_unpaired_for_polling(
Since we prefer local push, if the integration that is being discovered
is polling AND the homekit device is unpaired we still want to discovery it
"""
- with patch.dict(
- zc_gen.ZEROCONF,
- {"_hap._udp.local.": [{"domain": "homekit_controller"}]},
- clear=True,
- ), patch.dict(
- zc_gen.HOMEKIT,
- {"iSmartGate": {"domain": "gogogate2", "always_discover": True}},
- clear=True,
- ), patch.object(
- hass.config_entries.flow, "async_init"
- ) as mock_config_flow, patch.object(
- zeroconf,
- "AsyncServiceBrowser",
- side_effect=lambda *args, **kwargs: service_update_mock(
- *args, **kwargs, limit_service="_hap._udp.local."
+ with (
+ patch.dict(
+ zc_gen.ZEROCONF,
+ {"_hap._udp.local.": [{"domain": "homekit_controller"}]},
+ clear=True,
+ ),
+ patch.dict(
+ zc_gen.HOMEKIT,
+ {"iSmartGate": {"domain": "gogogate2", "always_discover": True}},
+ clear=True,
+ ),
+ patch.object(hass.config_entries.flow, "async_init") as mock_config_flow,
+ patch.object(
+ zeroconf,
+ "AsyncServiceBrowser",
+ side_effect=lambda *args, **kwargs: service_update_mock(
+ *args, **kwargs, limit_service="_hap._udp.local."
+ ),
+ ) as mock_service_browser,
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo",
+ side_effect=get_homekit_info_mock("iSmartGate", HOMEKIT_STATUS_UNPAIRED),
),
- ) as mock_service_browser, patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo",
- side_effect=get_homekit_info_mock("iSmartGate", HOMEKIT_STATUS_UNPAIRED),
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -964,12 +1032,13 @@ async def test_removed_ignored(hass: HomeAssistant, mock_async_zeroconf: None) -
ServiceStateChange.Removed,
)
- with patch.object(
- zeroconf, "AsyncServiceBrowser", side_effect=service_update_mock
- ), patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo",
- side_effect=get_service_info_mock,
- ) as mock_service_info:
+ with (
+ patch.object(zeroconf, "AsyncServiceBrowser", side_effect=service_update_mock),
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo",
+ side_effect=get_service_info_mock,
+ ) as mock_service_info,
+ ):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
@@ -995,16 +1064,18 @@ async def test_async_detect_interfaces_setting_non_loopback_route(
hass: HomeAssistant, mock_async_zeroconf: None
) -> None:
"""Test without default interface and the route returns a non-loopback address."""
- with patch("homeassistant.components.zeroconf.HaZeroconf") as mock_zc, patch.object(
- hass.config_entries.flow, "async_init"
- ), patch.object(
- zeroconf, "AsyncServiceBrowser", side_effect=service_update_mock
- ), patch(
- "homeassistant.components.zeroconf.network.async_get_adapters",
- return_value=_ADAPTER_WITH_DEFAULT_ENABLED,
- ), patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo",
- side_effect=get_service_info_mock,
+ with (
+ patch("homeassistant.components.zeroconf.HaZeroconf") as mock_zc,
+ patch.object(hass.config_entries.flow, "async_init"),
+ patch.object(zeroconf, "AsyncServiceBrowser", side_effect=service_update_mock),
+ patch(
+ "homeassistant.components.zeroconf.network.async_get_adapters",
+ return_value=_ADAPTER_WITH_DEFAULT_ENABLED,
+ ),
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo",
+ side_effect=get_service_info_mock,
+ ),
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -1079,16 +1150,19 @@ async def test_async_detect_interfaces_setting_empty_route_linux(
hass: HomeAssistant, mock_async_zeroconf: None
) -> None:
"""Test without default interface config and the route returns nothing on linux."""
- with patch("homeassistant.components.zeroconf.sys.platform", "linux"), patch(
- "homeassistant.components.zeroconf.HaZeroconf"
- ) as mock_zc, patch.object(hass.config_entries.flow, "async_init"), patch.object(
- zeroconf, "AsyncServiceBrowser", side_effect=service_update_mock
- ), patch(
- "homeassistant.components.zeroconf.network.async_get_adapters",
- return_value=_ADAPTERS_WITH_MANUAL_CONFIG,
- ), patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo",
- side_effect=get_service_info_mock,
+ with (
+ patch("homeassistant.components.zeroconf.sys.platform", "linux"),
+ patch("homeassistant.components.zeroconf.HaZeroconf") as mock_zc,
+ patch.object(hass.config_entries.flow, "async_init"),
+ patch.object(zeroconf, "AsyncServiceBrowser", side_effect=service_update_mock),
+ patch(
+ "homeassistant.components.zeroconf.network.async_get_adapters",
+ return_value=_ADAPTERS_WITH_MANUAL_CONFIG,
+ ),
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo",
+ side_effect=get_service_info_mock,
+ ),
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -1109,16 +1183,19 @@ async def test_async_detect_interfaces_setting_empty_route_freebsd(
hass: HomeAssistant, mock_async_zeroconf: None
) -> None:
"""Test without default interface and the route returns nothing on freebsd."""
- with patch("homeassistant.components.zeroconf.sys.platform", "freebsd"), patch(
- "homeassistant.components.zeroconf.HaZeroconf"
- ) as mock_zc, patch.object(hass.config_entries.flow, "async_init"), patch.object(
- zeroconf, "AsyncServiceBrowser", side_effect=service_update_mock
- ), patch(
- "homeassistant.components.zeroconf.network.async_get_adapters",
- return_value=_ADAPTERS_WITH_MANUAL_CONFIG,
- ), patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo",
- side_effect=get_service_info_mock,
+ with (
+ patch("homeassistant.components.zeroconf.sys.platform", "freebsd"),
+ patch("homeassistant.components.zeroconf.HaZeroconf") as mock_zc,
+ patch.object(hass.config_entries.flow, "async_init"),
+ patch.object(zeroconf, "AsyncServiceBrowser", side_effect=service_update_mock),
+ patch(
+ "homeassistant.components.zeroconf.network.async_get_adapters",
+ return_value=_ADAPTERS_WITH_MANUAL_CONFIG,
+ ),
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo",
+ side_effect=get_service_info_mock,
+ ),
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -1156,16 +1233,19 @@ async def test_async_detect_interfaces_explicitly_set_ipv6_linux(
hass: HomeAssistant, mock_async_zeroconf: None
) -> None:
"""Test interfaces are explicitly set when IPv6 is present on linux."""
- with patch("homeassistant.components.zeroconf.sys.platform", "linux"), patch(
- "homeassistant.components.zeroconf.HaZeroconf"
- ) as mock_zc, patch.object(hass.config_entries.flow, "async_init"), patch.object(
- zeroconf, "AsyncServiceBrowser", side_effect=service_update_mock
- ), patch(
- "homeassistant.components.zeroconf.network.async_get_adapters",
- return_value=_ADAPTER_WITH_DEFAULT_ENABLED_AND_IPV6,
- ), patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo",
- side_effect=get_service_info_mock,
+ with (
+ patch("homeassistant.components.zeroconf.sys.platform", "linux"),
+ patch("homeassistant.components.zeroconf.HaZeroconf") as mock_zc,
+ patch.object(hass.config_entries.flow, "async_init"),
+ patch.object(zeroconf, "AsyncServiceBrowser", side_effect=service_update_mock),
+ patch(
+ "homeassistant.components.zeroconf.network.async_get_adapters",
+ return_value=_ADAPTER_WITH_DEFAULT_ENABLED_AND_IPV6,
+ ),
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo",
+ side_effect=get_service_info_mock,
+ ),
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -1181,16 +1261,19 @@ async def test_async_detect_interfaces_explicitly_set_ipv6_freebsd(
hass: HomeAssistant, mock_async_zeroconf: None
) -> None:
"""Test interfaces are explicitly set when IPv6 is present on freebsd."""
- with patch("homeassistant.components.zeroconf.sys.platform", "freebsd"), patch(
- "homeassistant.components.zeroconf.HaZeroconf"
- ) as mock_zc, patch.object(hass.config_entries.flow, "async_init"), patch.object(
- zeroconf, "AsyncServiceBrowser", side_effect=service_update_mock
- ), patch(
- "homeassistant.components.zeroconf.network.async_get_adapters",
- return_value=_ADAPTER_WITH_DEFAULT_ENABLED_AND_IPV6,
- ), patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo",
- side_effect=get_service_info_mock,
+ with (
+ patch("homeassistant.components.zeroconf.sys.platform", "freebsd"),
+ patch("homeassistant.components.zeroconf.HaZeroconf") as mock_zc,
+ patch.object(hass.config_entries.flow, "async_init"),
+ patch.object(zeroconf, "AsyncServiceBrowser", side_effect=service_update_mock),
+ patch(
+ "homeassistant.components.zeroconf.network.async_get_adapters",
+ return_value=_ADAPTER_WITH_DEFAULT_ENABLED_AND_IPV6,
+ ),
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo",
+ side_effect=get_service_info_mock,
+ ),
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
@@ -1219,14 +1302,17 @@ async def test_setup_with_disallowed_characters_in_local_name(
hass: HomeAssistant, mock_async_zeroconf: None, caplog: pytest.LogCaptureFixture
) -> None:
"""Test we still setup with disallowed characters in the location name."""
- with patch.object(hass.config_entries.flow, "async_init"), patch.object(
- zeroconf, "AsyncServiceBrowser", side_effect=service_update_mock
- ), patch.object(
- hass.config,
- "location_name",
- "My.House",
- ), patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo.async_request",
+ with (
+ patch.object(hass.config_entries.flow, "async_init"),
+ patch.object(zeroconf, "AsyncServiceBrowser", side_effect=service_update_mock),
+ patch.object(
+ hass.config,
+ "location_name",
+ "My.House",
+ ),
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo.async_request",
+ ),
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
@@ -1260,28 +1346,32 @@ async def test_zeroconf_removed(hass: HomeAssistant, mock_async_zeroconf: None)
ServiceStateChange.Removed,
)
- with patch.dict(
- zc_gen.ZEROCONF,
- {
- "_http._tcp.local.": [
- {
- "domain": "shelly",
- "name": "shelly*",
- }
- ]
- },
- clear=True,
- ), patch.object(
- hass.config_entries.flow,
- "async_progress_by_init_data_type",
- return_value=[{"flow_id": "mock_flow_id"}],
- ) as mock_async_progress_by_init_data_type, patch.object(
- hass.config_entries.flow, "async_abort"
- ) as mock_async_abort, patch.object(
- zeroconf, "AsyncServiceBrowser", side_effect=_device_removed_mock
- ) as mock_service_browser, patch(
- "homeassistant.components.zeroconf.AsyncServiceInfo",
- side_effect=get_zeroconf_info_mock("FFAADDCC11DD"),
+ with (
+ patch.dict(
+ zc_gen.ZEROCONF,
+ {
+ "_http._tcp.local.": [
+ {
+ "domain": "shelly",
+ "name": "shelly*",
+ }
+ ]
+ },
+ clear=True,
+ ),
+ patch.object(
+ hass.config_entries.flow,
+ "async_progress_by_init_data_type",
+ return_value=[{"flow_id": "mock_flow_id"}],
+ ) as mock_async_progress_by_init_data_type,
+ patch.object(hass.config_entries.flow, "async_abort") as mock_async_abort,
+ patch.object(
+ zeroconf, "AsyncServiceBrowser", side_effect=_device_removed_mock
+ ) as mock_service_browser,
+ patch(
+ "homeassistant.components.zeroconf.AsyncServiceInfo",
+ side_effect=get_zeroconf_info_mock("FFAADDCC11DD"),
+ ),
):
assert await async_setup_component(hass, zeroconf.DOMAIN, {zeroconf.DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
diff --git a/tests/components/zeroconf/test_usage.py b/tests/components/zeroconf/test_usage.py
index 9162e3eb5af..9f5b68c2956 100644
--- a/tests/components/zeroconf/test_usage.py
+++ b/tests/components/zeroconf/test_usage.py
@@ -52,29 +52,33 @@ async def test_multiple_zeroconf_instances_gives_shared(
lineno="23",
line="self.light.is_on",
)
- with patch(
- "homeassistant.helpers.frame.linecache.getline", return_value=correct_frame.line
- ), patch(
- "homeassistant.helpers.frame.get_current_frame",
- return_value=extract_stack_to_frame(
- [
- Mock(
- filename="/home/dev/homeassistant/core.py",
- lineno="23",
- line="do_something()",
- ),
- correct_frame,
- Mock(
- filename="/home/dev/homeassistant/components/zeroconf/usage.py",
- lineno="23",
- line="self.light.is_on",
- ),
- Mock(
- filename="/home/dev/mdns/lights.py",
- lineno="2",
- line="something()",
- ),
- ]
+ with (
+ patch(
+ "homeassistant.helpers.frame.linecache.getline",
+ return_value=correct_frame.line,
+ ),
+ patch(
+ "homeassistant.helpers.frame.get_current_frame",
+ return_value=extract_stack_to_frame(
+ [
+ Mock(
+ filename="/home/dev/homeassistant/core.py",
+ lineno="23",
+ line="do_something()",
+ ),
+ correct_frame,
+ Mock(
+ filename="/home/dev/homeassistant/components/zeroconf/usage.py",
+ lineno="23",
+ line="self.light.is_on",
+ ),
+ Mock(
+ filename="/home/dev/mdns/lights.py",
+ lineno="2",
+ line="something()",
+ ),
+ ]
+ ),
),
):
assert zeroconf.Zeroconf() == zeroconf_instance
diff --git a/tests/components/zerproc/test_config_flow.py b/tests/components/zerproc/test_config_flow.py
index 2d933158c54..e512b2a668e 100644
--- a/tests/components/zerproc/test_config_flow.py
+++ b/tests/components/zerproc/test_config_flow.py
@@ -18,13 +18,16 @@ async def test_flow_success(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] is None
- with patch(
- "homeassistant.components.zerproc.config_flow.pyzerproc.discover",
- return_value=["Light1", "Light2"],
- ), patch(
- "homeassistant.components.zerproc.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.zerproc.config_flow.pyzerproc.discover",
+ return_value=["Light1", "Light2"],
+ ),
+ patch(
+ "homeassistant.components.zerproc.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{},
@@ -47,13 +50,16 @@ async def test_flow_no_devices_found(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] is None
- with patch(
- "homeassistant.components.zerproc.config_flow.pyzerproc.discover",
- return_value=[],
- ), patch(
- "homeassistant.components.zerproc.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.zerproc.config_flow.pyzerproc.discover",
+ return_value=[],
+ ),
+ patch(
+ "homeassistant.components.zerproc.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{},
@@ -74,13 +80,16 @@ async def test_flow_exceptions_caught(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["errors"] is None
- with patch(
- "homeassistant.components.zerproc.config_flow.pyzerproc.discover",
- side_effect=pyzerproc.ZerprocException("TEST"),
- ), patch(
- "homeassistant.components.zerproc.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.zerproc.config_flow.pyzerproc.discover",
+ side_effect=pyzerproc.ZerprocException("TEST"),
+ ),
+ patch(
+ "homeassistant.components.zerproc.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{},
diff --git a/tests/components/zerproc/test_light.py b/tests/components/zerproc/test_light.py
index 56a5590e293..c47f960b182 100644
--- a/tests/components/zerproc/test_light.py
+++ b/tests/components/zerproc/test_light.py
@@ -53,11 +53,13 @@ async def mock_light(hass, mock_entry):
mock_state = pyzerproc.LightState(False, (0, 0, 0))
- with patch(
- "homeassistant.components.zerproc.light.pyzerproc.discover",
- return_value=[light],
- ), patch.object(light, "connect"), patch.object(
- light, "get_state", return_value=mock_state
+ with (
+ patch(
+ "homeassistant.components.zerproc.light.pyzerproc.discover",
+ return_value=[light],
+ ),
+ patch.object(light, "connect"),
+ patch.object(light, "get_state", return_value=mock_state),
):
await hass.config_entries.async_setup(mock_entry.entry_id)
await hass.async_block_till_done()
diff --git a/tests/components/zeversolar/test_config_flow.py b/tests/components/zeversolar/test_config_flow.py
index 5e841c9b313..0bfa5ad547d 100644
--- a/tests/components/zeversolar/test_config_flow.py
+++ b/tests/components/zeversolar/test_config_flow.py
@@ -96,9 +96,12 @@ async def test_abort_already_configured(hass: HomeAssistant) -> None:
mock_data = MagicMock()
mock_data.serial_number = "test_serial"
- with patch("zeversolar.ZeverSolarClient.get_data", return_value=mock_data), patch(
- "homeassistant.components.zeversolar.async_setup_entry",
- ) as mock_setup_entry:
+ with (
+ patch("zeversolar.ZeverSolarClient.get_data", return_value=mock_data),
+ patch(
+ "homeassistant.components.zeversolar.async_setup_entry",
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
flow_id=result["flow_id"],
user_input={
@@ -116,10 +119,13 @@ async def _set_up_zeversolar(hass: HomeAssistant, flow_id: str) -> None:
"""Reusable successful setup of Zeversolar sensor."""
mock_data = MagicMock()
mock_data.serial_number = "test_serial"
- with patch("zeversolar.ZeverSolarClient.get_data", return_value=mock_data), patch(
- "homeassistant.components.zeversolar.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch("zeversolar.ZeverSolarClient.get_data", return_value=mock_data),
+ patch(
+ "homeassistant.components.zeversolar.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
flow_id=flow_id,
user_input={
diff --git a/tests/components/zha/conftest.py b/tests/components/zha/conftest.py
index 4c3c4f82a21..b1ac22d544d 100644
--- a/tests/components/zha/conftest.py
+++ b/tests/components/zha/conftest.py
@@ -227,12 +227,15 @@ def mock_zigpy_connect(
zigpy_app_controller: ControllerApplication,
) -> Generator[ControllerApplication, None, None]:
"""Patch the zigpy radio connection with our mock application."""
- with patch(
- "bellows.zigbee.application.ControllerApplication.new",
- return_value=zigpy_app_controller,
- ), patch(
- "bellows.zigbee.application.ControllerApplication",
- return_value=zigpy_app_controller,
+ with (
+ patch(
+ "bellows.zigbee.application.ControllerApplication.new",
+ return_value=zigpy_app_controller,
+ ),
+ patch(
+ "bellows.zigbee.application.ControllerApplication",
+ return_value=zigpy_app_controller,
+ ),
):
yield zigpy_app_controller
diff --git a/tests/components/zha/test_cluster_handlers.py b/tests/components/zha/test_cluster_handlers.py
index c081faab010..60c958f20fe 100644
--- a/tests/components/zha/test_cluster_handlers.py
+++ b/tests/components/zha/test_cluster_handlers.py
@@ -578,9 +578,10 @@ async def test_ep_cluster_handlers_configure(cluster_handler) -> None:
claimed = {ch_1.id: ch_1, ch_2.id: ch_2, ch_3.id: ch_3}
client_handlers = {ch_4.id: ch_4, ch_5.id: ch_5}
- with mock.patch.dict(
- endpoint.claimed_cluster_handlers, claimed, clear=True
- ), mock.patch.dict(endpoint.client_cluster_handlers, client_handlers, clear=True):
+ with (
+ mock.patch.dict(endpoint.claimed_cluster_handlers, claimed, clear=True),
+ mock.patch.dict(endpoint.client_cluster_handlers, client_handlers, clear=True),
+ ):
await endpoint.async_configure()
await endpoint.async_initialize(mock.sentinel.from_cache)
@@ -870,10 +871,13 @@ async def test_invalid_cluster_handler(hass: HomeAssistant, caplog) -> None:
TestZigbeeClusterHandler(cluster, zha_endpoint)
# And one is also logged at runtime
- with patch.dict(
- registries.ZIGBEE_CLUSTER_HANDLER_REGISTRY[cluster.cluster_id],
- {None: TestZigbeeClusterHandler},
- ), caplog.at_level(logging.WARNING):
+ with (
+ patch.dict(
+ registries.ZIGBEE_CLUSTER_HANDLER_REGISTRY[cluster.cluster_id],
+ {None: TestZigbeeClusterHandler},
+ ),
+ caplog.at_level(logging.WARNING),
+ ):
zha_endpoint.add_all_cluster_handlers()
assert "missing_attr" in caplog.text
diff --git a/tests/components/zha/test_config_flow.py b/tests/components/zha/test_config_flow.py
index d1c4c6cb507..bbfca1b1a13 100644
--- a/tests/components/zha/test_config_flow.py
+++ b/tests/components/zha/test_config_flow.py
@@ -55,12 +55,15 @@ def disable_platform_only():
@pytest.fixture(autouse=True)
def mock_multipan_platform():
"""Mock the multipan platform."""
- with patch(
- "homeassistant.components.zha.silabs_multiprotocol.async_get_channel",
- return_value=None,
- ), patch(
- "homeassistant.components.zha.silabs_multiprotocol.async_using_multipan",
- return_value=False,
+ with (
+ patch(
+ "homeassistant.components.zha.silabs_multiprotocol.async_get_channel",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.zha.silabs_multiprotocol.async_using_multipan",
+ return_value=False,
+ ),
):
yield
@@ -1825,9 +1828,10 @@ async def test_config_flow_port_yellow_port_name(hass: HomeAssistant) -> None:
port.manufacturer = None
port.description = None
- with patch(
- "homeassistant.components.zha.config_flow.yellow_hardware.async_info"
- ), patch("serial.tools.list_ports.comports", MagicMock(return_value=[port])):
+ with (
+ patch("homeassistant.components.zha.config_flow.yellow_hardware.async_info"),
+ patch("serial.tools.list_ports.comports", MagicMock(return_value=[port])),
+ ):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={CONF_SOURCE: SOURCE_USER},
@@ -1842,10 +1846,11 @@ async def test_config_flow_port_yellow_port_name(hass: HomeAssistant) -> None:
async def test_config_flow_port_multiprotocol_port_name(hass: HomeAssistant) -> None:
"""Test config flow serial port name for multiprotocol add-on."""
- with patch(
- "homeassistant.components.hassio.addon_manager.AddonManager.async_get_addon_info"
- ) as async_get_addon_info, patch(
- "serial.tools.list_ports.comports", MagicMock(return_value=[])
+ with (
+ patch(
+ "homeassistant.components.hassio.addon_manager.AddonManager.async_get_addon_info"
+ ) as async_get_addon_info,
+ patch("serial.tools.list_ports.comports", MagicMock(return_value=[])),
):
async_get_addon_info.return_value.state = AddonState.RUNNING
async_get_addon_info.return_value.hostname = "core-silabs-multiprotocol"
@@ -1886,11 +1891,14 @@ async def test_probe_wrong_firmware_installed(hass: HomeAssistant) -> None:
async def test_discovery_wrong_firmware_installed(hass: HomeAssistant) -> None:
"""Test auto-probing failing because the wrong firmware is installed."""
- with patch(
- "homeassistant.components.zha.radio_manager.ZhaRadioManager.detect_radio_type",
- return_value=ProbeResult.WRONG_FIRMWARE_INSTALLED,
- ), patch(
- "homeassistant.components.onboarding.async_is_onboarded", return_value=False
+ with (
+ patch(
+ "homeassistant.components.zha.radio_manager.ZhaRadioManager.detect_radio_type",
+ return_value=ProbeResult.WRONG_FIRMWARE_INSTALLED,
+ ),
+ patch(
+ "homeassistant.components.onboarding.async_is_onboarded", return_value=False
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
diff --git a/tests/components/zha/test_discover.py b/tests/components/zha/test_discover.py
index cdf8e137690..debf233de36 100644
--- a/tests/components/zha/test_discover.py
+++ b/tests/components/zha/test_discover.py
@@ -252,10 +252,13 @@ def test_discover_by_device_type_override() -> None:
get_entity_mock = mock.MagicMock(
return_value=(mock.sentinel.entity_cls, mock.sentinel.claimed)
)
- with mock.patch(
- "homeassistant.components.zha.core.registries.ZHA_ENTITIES.get_entity",
- get_entity_mock,
- ), mock.patch.dict(disc.PROBE._device_configs, overrides, clear=True):
+ with (
+ mock.patch(
+ "homeassistant.components.zha.core.registries.ZHA_ENTITIES.get_entity",
+ get_entity_mock,
+ ),
+ mock.patch.dict(disc.PROBE._device_configs, overrides, clear=True),
+ ):
disc.PROBE.discover_by_device_type(endpoint)
assert get_entity_mock.call_count == 1
assert endpoint.claim_cluster_handlers.call_count == 1
diff --git a/tests/components/zha/test_radio_manager.py b/tests/components/zha/test_radio_manager.py
index 5671c9cd465..dbea454ecb0 100644
--- a/tests/components/zha/test_radio_manager.py
+++ b/tests/components/zha/test_radio_manager.py
@@ -436,12 +436,15 @@ def zha_radio_manager(hass: HomeAssistant) -> ZhaRadioManager:
async def test_detect_radio_type_success(radio_manager: ZhaRadioManager) -> None:
"""Test radio type detection, success."""
- with patch(
- "bellows.zigbee.application.ControllerApplication.probe", return_value=False
- ), patch(
- # Intentionally probe only the second radio type
- "zigpy_znp.zigbee.application.ControllerApplication.probe",
- return_value=True,
+ with (
+ patch(
+ "bellows.zigbee.application.ControllerApplication.probe", return_value=False
+ ),
+ patch(
+ # Intentionally probe only the second radio type
+ "zigpy_znp.zigbee.application.ControllerApplication.probe",
+ return_value=True,
+ ),
):
assert (
await radio_manager.detect_radio_type() == ProbeResult.RADIO_TYPE_DETECTED
@@ -453,11 +456,12 @@ async def test_detect_radio_type_failure_wrong_firmware(
radio_manager: ZhaRadioManager,
) -> None:
"""Test radio type detection, wrong firmware."""
- with patch(
- "homeassistant.components.zha.radio_manager.AUTOPROBE_RADIOS", ()
- ), patch(
- "homeassistant.components.zha.radio_manager.repairs.wrong_silabs_firmware.warn_on_wrong_silabs_firmware",
- return_value=True,
+ with (
+ patch("homeassistant.components.zha.radio_manager.AUTOPROBE_RADIOS", ()),
+ patch(
+ "homeassistant.components.zha.radio_manager.repairs.wrong_silabs_firmware.warn_on_wrong_silabs_firmware",
+ return_value=True,
+ ),
):
assert (
await radio_manager.detect_radio_type()
@@ -470,11 +474,12 @@ async def test_detect_radio_type_failure_no_detect(
radio_manager: ZhaRadioManager,
) -> None:
"""Test radio type detection, no firmware detected."""
- with patch(
- "homeassistant.components.zha.radio_manager.AUTOPROBE_RADIOS", ()
- ), patch(
- "homeassistant.components.zha.radio_manager.repairs.wrong_silabs_firmware.warn_on_wrong_silabs_firmware",
- return_value=False,
+ with (
+ patch("homeassistant.components.zha.radio_manager.AUTOPROBE_RADIOS", ()),
+ patch(
+ "homeassistant.components.zha.radio_manager.repairs.wrong_silabs_firmware.warn_on_wrong_silabs_firmware",
+ return_value=False,
+ ),
):
assert await radio_manager.detect_radio_type() == ProbeResult.PROBING_FAILED
assert radio_manager.radio_type is None
diff --git a/tests/components/zha/test_repairs.py b/tests/components/zha/test_repairs.py
index 5d5dbe8d147..c164abf9b2d 100644
--- a/tests/components/zha/test_repairs.py
+++ b/tests/components/zha/test_repairs.py
@@ -86,12 +86,15 @@ def test_detect_radio_hardware(hass: HomeAssistant) -> None:
def test_detect_radio_hardware_failure(hass: HomeAssistant) -> None:
"""Test radio hardware detection failure."""
- with patch(
- "homeassistant.components.homeassistant_yellow.hardware.async_info",
- side_effect=HomeAssistantError(),
- ), patch(
- "homeassistant.components.homeassistant_sky_connect.hardware.async_info",
- side_effect=HomeAssistantError(),
+ with (
+ patch(
+ "homeassistant.components.homeassistant_yellow.hardware.async_info",
+ side_effect=HomeAssistantError(),
+ ),
+ patch(
+ "homeassistant.components.homeassistant_sky_connect.hardware.async_info",
+ side_effect=HomeAssistantError(),
+ ),
):
assert _detect_radio_hardware(hass, SKYCONNECT_DEVICE) == HardwareType.OTHER
@@ -116,16 +119,20 @@ async def test_multipan_firmware_repair(
config_entry.add_to_hass(hass)
# ZHA fails to set up
- with patch(
- "homeassistant.components.zha.repairs.wrong_silabs_firmware.Flasher.probe_app_type",
- side_effect=set_flasher_app_type(ApplicationType.CPC),
- autospec=True,
- ), patch(
- "homeassistant.components.zha.core.gateway.ZHAGateway.async_initialize",
- side_effect=RuntimeError(),
- ), patch(
- "homeassistant.components.zha.repairs.wrong_silabs_firmware._detect_radio_hardware",
- return_value=detected_hardware,
+ with (
+ patch(
+ "homeassistant.components.zha.repairs.wrong_silabs_firmware.Flasher.probe_app_type",
+ side_effect=set_flasher_app_type(ApplicationType.CPC),
+ autospec=True,
+ ),
+ patch(
+ "homeassistant.components.zha.core.gateway.ZHAGateway.async_initialize",
+ side_effect=RuntimeError(),
+ ),
+ patch(
+ "homeassistant.components.zha.repairs.wrong_silabs_firmware._detect_radio_hardware",
+ return_value=detected_hardware,
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -165,13 +172,16 @@ async def test_multipan_firmware_no_repair_on_probe_failure(
config_entry.add_to_hass(hass)
# ZHA fails to set up
- with patch(
- "homeassistant.components.zha.repairs.wrong_silabs_firmware.Flasher.probe_app_type",
- side_effect=set_flasher_app_type(None),
- autospec=True,
- ), patch(
- "homeassistant.components.zha.core.gateway.ZHAGateway.async_initialize",
- side_effect=RuntimeError(),
+ with (
+ patch(
+ "homeassistant.components.zha.repairs.wrong_silabs_firmware.Flasher.probe_app_type",
+ side_effect=set_flasher_app_type(None),
+ autospec=True,
+ ),
+ patch(
+ "homeassistant.components.zha.core.gateway.ZHAGateway.async_initialize",
+ side_effect=RuntimeError(),
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -199,13 +209,16 @@ async def test_multipan_firmware_retry_on_probe_ezsp(
config_entry.add_to_hass(hass)
# ZHA fails to set up
- with patch(
- "homeassistant.components.zha.repairs.wrong_silabs_firmware.Flasher.probe_app_type",
- side_effect=set_flasher_app_type(ApplicationType.EZSP),
- autospec=True,
- ), patch(
- "homeassistant.components.zha.core.gateway.ZHAGateway.async_initialize",
- side_effect=RuntimeError(),
+ with (
+ patch(
+ "homeassistant.components.zha.repairs.wrong_silabs_firmware.Flasher.probe_app_type",
+ side_effect=set_flasher_app_type(ApplicationType.EZSP),
+ autospec=True,
+ ),
+ patch(
+ "homeassistant.components.zha.core.gateway.ZHAGateway.async_initialize",
+ side_effect=RuntimeError(),
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -237,10 +250,13 @@ async def test_no_warn_on_socket(hass: HomeAssistant) -> None:
async def test_probe_failure_exception_handling(caplog) -> None:
"""Test that probe failures are handled gracefully."""
- with patch(
- "homeassistant.components.zha.repairs.wrong_silabs_firmware.Flasher.probe_app_type",
- side_effect=RuntimeError(),
- ), caplog.at_level(logging.DEBUG):
+ with (
+ patch(
+ "homeassistant.components.zha.repairs.wrong_silabs_firmware.Flasher.probe_app_type",
+ side_effect=RuntimeError(),
+ ),
+ caplog.at_level(logging.DEBUG),
+ ):
await probe_silabs_firmware_type("/dev/ttyZigbee")
assert "Failed to probe application type" in caplog.text
diff --git a/tests/components/zha/test_sensor.py b/tests/components/zha/test_sensor.py
index f656ddea71c..a6c4cfbf4ec 100644
--- a/tests/components/zha/test_sensor.py
+++ b/tests/components/zha/test_sensor.py
@@ -1096,9 +1096,9 @@ async def test_elec_measurement_sensor_polling(
entity_id = ENTITY_ID_PREFIX.format("power")
zigpy_dev = elec_measurement_zigpy_dev
- zigpy_dev.endpoints[1].electrical_measurement.PLUGGED_ATTR_READS[
- "active_power"
- ] = 20
+ zigpy_dev.endpoints[1].electrical_measurement.PLUGGED_ATTR_READS["active_power"] = (
+ 20
+ )
await zha_device_joined_restored(zigpy_dev)
@@ -1107,9 +1107,9 @@ async def test_elec_measurement_sensor_polling(
assert state.state == "2.0"
# update the value for the power reading
- zigpy_dev.endpoints[1].electrical_measurement.PLUGGED_ATTR_READS[
- "active_power"
- ] = 60
+ zigpy_dev.endpoints[1].electrical_measurement.PLUGGED_ATTR_READS["active_power"] = (
+ 60
+ )
# ensure the state is still 2.0
state = hass.states.get(entity_id)
diff --git a/tests/components/zha/test_siren.py b/tests/components/zha/test_siren.py
index dae04c45fef..f5486d91c0f 100644
--- a/tests/components/zha/test_siren.py
+++ b/tests/components/zha/test_siren.py
@@ -86,13 +86,16 @@ async def test_siren(hass: HomeAssistant, siren) -> None:
assert hass.states.get(entity_id).state == STATE_OFF
# turn on from HA
- with patch(
- "zigpy.device.Device.request",
- return_value=[0x00, zcl_f.Status.SUCCESS],
- ), patch(
- "zigpy.zcl.Cluster.request",
- side_effect=zigpy.zcl.Cluster.request,
- autospec=True,
+ with (
+ patch(
+ "zigpy.device.Device.request",
+ return_value=[0x00, zcl_f.Status.SUCCESS],
+ ),
+ patch(
+ "zigpy.zcl.Cluster.request",
+ side_effect=zigpy.zcl.Cluster.request,
+ autospec=True,
+ ),
):
# turn on via UI
await hass.services.async_call(
@@ -118,13 +121,16 @@ async def test_siren(hass: HomeAssistant, siren) -> None:
assert hass.states.get(entity_id).state == STATE_ON
# turn off from HA
- with patch(
- "zigpy.device.Device.request",
- return_value=[0x01, zcl_f.Status.SUCCESS],
- ), patch(
- "zigpy.zcl.Cluster.request",
- side_effect=zigpy.zcl.Cluster.request,
- autospec=True,
+ with (
+ patch(
+ "zigpy.device.Device.request",
+ return_value=[0x01, zcl_f.Status.SUCCESS],
+ ),
+ patch(
+ "zigpy.zcl.Cluster.request",
+ side_effect=zigpy.zcl.Cluster.request,
+ autospec=True,
+ ),
):
# turn off via UI
await hass.services.async_call(
@@ -150,13 +156,16 @@ async def test_siren(hass: HomeAssistant, siren) -> None:
assert hass.states.get(entity_id).state == STATE_OFF
# turn on from HA
- with patch(
- "zigpy.device.Device.request",
- return_value=[0x00, zcl_f.Status.SUCCESS],
- ), patch(
- "zigpy.zcl.Cluster.request",
- side_effect=zigpy.zcl.Cluster.request,
- autospec=True,
+ with (
+ patch(
+ "zigpy.device.Device.request",
+ return_value=[0x00, zcl_f.Status.SUCCESS],
+ ),
+ patch(
+ "zigpy.zcl.Cluster.request",
+ side_effect=zigpy.zcl.Cluster.request,
+ autospec=True,
+ ),
):
# turn on via UI
await hass.services.async_call(
diff --git a/tests/components/zha/test_update.py b/tests/components/zha/test_update.py
index 31c28e31646..854c08985ac 100644
--- a/tests/components/zha/test_update.py
+++ b/tests/components/zha/test_update.py
@@ -516,10 +516,13 @@ async def test_firmware_update_raises(
blocking=True,
)
- with patch(
- "zigpy.device.Device.update_firmware",
- AsyncMock(side_effect=DeliveryError("failed to deliver")),
- ), pytest.raises(HomeAssistantError):
+ with (
+ patch(
+ "zigpy.device.Device.update_firmware",
+ AsyncMock(side_effect=DeliveryError("failed to deliver")),
+ ),
+ pytest.raises(HomeAssistantError),
+ ):
await hass.services.async_call(
UPDATE_DOMAIN,
SERVICE_INSTALL,
diff --git a/tests/components/zwave_js/scripts/test_convert_device_diagnostics_to_fixture.py b/tests/components/zwave_js/scripts/test_convert_device_diagnostics_to_fixture.py
index 545c56d6f9d..a5c5e4475ce 100644
--- a/tests/components/zwave_js/scripts/test_convert_device_diagnostics_to_fixture.py
+++ b/tests/components/zwave_js/scripts/test_convert_device_diagnostics_to_fixture.py
@@ -75,9 +75,12 @@ def test_main(capfd: pytest.CaptureFixture[str]) -> None:
# Check file dump
args.append("--file")
- with patch.object(sys, "argv", args), patch(
- "homeassistant.components.zwave_js.scripts.convert_device_diagnostics_to_fixture.Path.write_text"
- ) as write_text_mock:
+ with (
+ patch.object(sys, "argv", args),
+ patch(
+ "homeassistant.components.zwave_js.scripts.convert_device_diagnostics_to_fixture.Path.write_text"
+ ) as write_text_mock,
+ ):
main()
assert len(write_text_mock.call_args_list) == 1
diff --git a/tests/components/zwave_js/test_api.py b/tests/components/zwave_js/test_api.py
index ed84d155e1d..6295dbed8f1 100644
--- a/tests/components/zwave_js/test_api.py
+++ b/tests/components/zwave_js/test_api.py
@@ -3070,13 +3070,17 @@ async def test_firmware_upload_view(
"""Test the HTTP firmware upload view."""
client = await hass_client()
device = get_device(hass, multisensor_6)
- with patch(
- "homeassistant.components.zwave_js.api.update_firmware",
- ) as mock_node_cmd, patch(
- "homeassistant.components.zwave_js.api.controller_firmware_update_otw",
- ) as mock_controller_cmd, patch.dict(
- "homeassistant.components.zwave_js.api.USER_AGENT",
- {"HomeAssistant": "0.0.0"},
+ with (
+ patch(
+ "homeassistant.components.zwave_js.api.update_firmware",
+ ) as mock_node_cmd,
+ patch(
+ "homeassistant.components.zwave_js.api.controller_firmware_update_otw",
+ ) as mock_controller_cmd,
+ patch.dict(
+ "homeassistant.components.zwave_js.api.USER_AGENT",
+ {"HomeAssistant": "0.0.0"},
+ ),
):
data = {"file": firmware_file}
data.update(firmware_data)
@@ -3107,13 +3111,17 @@ async def test_firmware_upload_view_controller(
"""Test the HTTP firmware upload view for a controller."""
hass_client = await hass_client()
device = get_device(hass, client.driver.controller.nodes[1])
- with patch(
- "homeassistant.components.zwave_js.api.update_firmware",
- ) as mock_node_cmd, patch(
- "homeassistant.components.zwave_js.api.controller_firmware_update_otw",
- ) as mock_controller_cmd, patch.dict(
- "homeassistant.components.zwave_js.api.USER_AGENT",
- {"HomeAssistant": "0.0.0"},
+ with (
+ patch(
+ "homeassistant.components.zwave_js.api.update_firmware",
+ ) as mock_node_cmd,
+ patch(
+ "homeassistant.components.zwave_js.api.controller_firmware_update_otw",
+ ) as mock_controller_cmd,
+ patch.dict(
+ "homeassistant.components.zwave_js.api.USER_AGENT",
+ {"HomeAssistant": "0.0.0"},
+ ),
):
resp = await hass_client.post(
f"/api/zwave_js/firmware/upload/{device.id}",
diff --git a/tests/components/zwave_js/test_config_flow.py b/tests/components/zwave_js/test_config_flow.py
index ad066dec992..511fb8d7570 100644
--- a/tests/components/zwave_js/test_config_flow.py
+++ b/tests/components/zwave_js/test_config_flow.py
@@ -114,13 +114,16 @@ def mock_get_server_version(server_version_side_effect, server_version_timeout):
min_schema_version=0,
max_schema_version=1,
)
- with patch(
- "homeassistant.components.zwave_js.config_flow.get_server_version",
- side_effect=server_version_side_effect,
- return_value=version_info,
- ) as mock_version, patch(
- "homeassistant.components.zwave_js.config_flow.SERVER_VERSION_TIMEOUT",
- new=server_version_timeout,
+ with (
+ patch(
+ "homeassistant.components.zwave_js.config_flow.get_server_version",
+ side_effect=server_version_side_effect,
+ return_value=version_info,
+ ) as mock_version,
+ patch(
+ "homeassistant.components.zwave_js.config_flow.SERVER_VERSION_TIMEOUT",
+ new=server_version_timeout,
+ ),
):
yield mock_version
@@ -192,12 +195,15 @@ async def test_manual(hass: HomeAssistant) -> None:
)
assert result["type"] == "form"
- with patch(
- "homeassistant.components.zwave_js.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.zwave_js.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.zwave_js.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.zwave_js.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -348,12 +354,15 @@ async def test_supervisor_discovery(
),
)
- with patch(
- "homeassistant.components.zwave_js.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.zwave_js.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.zwave_js.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.zwave_js.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
await hass.async_block_till_done()
@@ -440,12 +449,15 @@ async def test_clean_discovery_on_user_create(
assert result["type"] == "form"
assert result["step_id"] == "manual"
- with patch(
- "homeassistant.components.zwave_js.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.zwave_js.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.zwave_js.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.zwave_js.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -613,12 +625,15 @@ async def test_usb_discovery(
assert result["type"] == "progress"
assert result["step_id"] == "start_addon"
- with patch(
- "homeassistant.components.zwave_js.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.zwave_js.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.zwave_js.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.zwave_js.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
await hass.async_block_till_done()
result = await hass.config_entries.flow.async_configure(result["flow_id"])
await hass.async_block_till_done()
@@ -703,12 +718,15 @@ async def test_usb_discovery_addon_not_running(
assert result["type"] == "progress"
assert result["step_id"] == "start_addon"
- with patch(
- "homeassistant.components.zwave_js.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.zwave_js.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.zwave_js.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.zwave_js.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
await hass.async_block_till_done()
result = await hass.config_entries.flow.async_configure(result["flow_id"])
await hass.async_block_till_done()
@@ -789,12 +807,15 @@ async def test_discovery_addon_not_running(
assert result["type"] == "progress"
assert result["step_id"] == "start_addon"
- with patch(
- "homeassistant.components.zwave_js.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.zwave_js.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.zwave_js.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.zwave_js.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
await hass.async_block_till_done()
result = await hass.config_entries.flow.async_configure(result["flow_id"])
await hass.async_block_till_done()
@@ -883,12 +904,15 @@ async def test_discovery_addon_not_installed(
assert result["type"] == "progress"
assert result["step_id"] == "start_addon"
- with patch(
- "homeassistant.components.zwave_js.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.zwave_js.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.zwave_js.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.zwave_js.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
await hass.async_block_till_done()
result = await hass.config_entries.flow.async_configure(result["flow_id"])
await hass.async_block_till_done()
@@ -1017,12 +1041,15 @@ async def test_not_addon(hass: HomeAssistant, supervisor) -> None:
assert result["type"] == "form"
assert result["step_id"] == "manual"
- with patch(
- "homeassistant.components.zwave_js.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.zwave_js.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.zwave_js.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.zwave_js.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
@@ -1069,12 +1096,15 @@ async def test_addon_running(
assert result["type"] == "form"
assert result["step_id"] == "on_supervisor"
- with patch(
- "homeassistant.components.zwave_js.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.zwave_js.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.zwave_js.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.zwave_js.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"use_addon": True}
)
@@ -1268,12 +1298,15 @@ async def test_addon_installed(
assert result["type"] == "progress"
assert result["step_id"] == "start_addon"
- with patch(
- "homeassistant.components.zwave_js.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.zwave_js.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.zwave_js.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.zwave_js.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
await hass.async_block_till_done()
result = await hass.config_entries.flow.async_configure(result["flow_id"])
await hass.async_block_till_done()
@@ -1645,12 +1678,15 @@ async def test_addon_not_installed(
assert result["type"] == "progress"
assert result["step_id"] == "start_addon"
- with patch(
- "homeassistant.components.zwave_js.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.zwave_js.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.zwave_js.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.zwave_js.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
await hass.async_block_till_done()
result = await hass.config_entries.flow.async_configure(result["flow_id"])
await hass.async_block_till_done()
@@ -2633,12 +2669,15 @@ async def test_import_addon_installed(
assert result["type"] == "progress"
assert result["step_id"] == "start_addon"
- with patch(
- "homeassistant.components.zwave_js.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.zwave_js.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.zwave_js.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.zwave_js.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
await hass.async_block_till_done()
result = await hass.config_entries.flow.async_configure(result["flow_id"])
await hass.async_block_till_done()
@@ -2681,12 +2720,15 @@ async def test_zeroconf(hass: HomeAssistant) -> None:
assert result["type"] == "form"
assert result["step_id"] == "zeroconf_confirm"
- with patch(
- "homeassistant.components.zwave_js.async_setup", return_value=True
- ) as mock_setup, patch(
- "homeassistant.components.zwave_js.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry:
+ with (
+ patch(
+ "homeassistant.components.zwave_js.async_setup", return_value=True
+ ) as mock_setup,
+ patch(
+ "homeassistant.components.zwave_js.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ ):
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
await hass.async_block_till_done()
diff --git a/tests/components/zwave_js/test_device_condition.py b/tests/components/zwave_js/test_device_condition.py
index 4c3cfd5d8a0..24f756c5042 100644
--- a/tests/components/zwave_js/test_device_condition.py
+++ b/tests/components/zwave_js/test_device_condition.py
@@ -627,12 +627,15 @@ async def test_failure_scenarios(
hass, {"type": "failed.test", "device_id": device.id}
)
- with patch(
- "homeassistant.components.zwave_js.device_condition.async_get_node_from_device_id",
- return_value=None,
- ), patch(
- "homeassistant.components.zwave_js.device_condition.get_zwave_value_from_config",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.components.zwave_js.device_condition.async_get_node_from_device_id",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.zwave_js.device_condition.get_zwave_value_from_config",
+ return_value=None,
+ ),
):
assert (
await device_condition.async_get_condition_capabilities(
diff --git a/tests/components/zwave_js/test_device_trigger.py b/tests/components/zwave_js/test_device_trigger.py
index 93402219b6c..6818b2d73af 100644
--- a/tests/components/zwave_js/test_device_trigger.py
+++ b/tests/components/zwave_js/test_device_trigger.py
@@ -1571,12 +1571,15 @@ async def test_failure_scenarios(
{},
)
- with patch(
- "homeassistant.components.zwave_js.device_trigger.async_get_node_from_device_id",
- return_value=None,
- ), patch(
- "homeassistant.components.zwave_js.helpers.get_zwave_value_from_config",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.components.zwave_js.device_trigger.async_get_node_from_device_id",
+ return_value=None,
+ ),
+ patch(
+ "homeassistant.components.zwave_js.helpers.get_zwave_value_from_config",
+ return_value=None,
+ ),
):
assert (
await device_trigger.async_get_trigger_capabilities(
diff --git a/tests/components/zwave_js/test_init.py b/tests/components/zwave_js/test_init.py
index ee0e9d61707..822302a9940 100644
--- a/tests/components/zwave_js/test_init.py
+++ b/tests/components/zwave_js/test_init.py
@@ -111,11 +111,14 @@ async def test_noop_statistics(hass: HomeAssistant, client) -> None:
entry = MockConfigEntry(domain="zwave_js", data={"url": "ws://test.org"})
entry.add_to_hass(hass)
- with patch(
- "zwave_js_server.model.driver.Driver.async_enable_statistics"
- ) as mock_cmd1, patch(
- "zwave_js_server.model.driver.Driver.async_disable_statistics"
- ) as mock_cmd2:
+ with (
+ patch(
+ "zwave_js_server.model.driver.Driver.async_enable_statistics"
+ ) as mock_cmd1,
+ patch(
+ "zwave_js_server.model.driver.Driver.async_disable_statistics"
+ ) as mock_cmd2,
+ ):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert not mock_cmd1.called
diff --git a/tests/components/zwave_js/test_services.py b/tests/components/zwave_js/test_services.py
index 633a4dbf7de..5462bcf9946 100644
--- a/tests/components/zwave_js/test_services.py
+++ b/tests/components/zwave_js/test_services.py
@@ -1521,9 +1521,12 @@ async def test_multicast_set_value(
diff_network_node = MagicMock()
diff_network_node.client.driver.controller.home_id.return_value = "diff_home_id"
- with pytest.raises(vol.MultipleInvalid), patch(
- "homeassistant.components.zwave_js.helpers.async_get_node_from_device_id",
- side_effect=(climate_danfoss_lc_13, diff_network_node),
+ with (
+ pytest.raises(vol.MultipleInvalid),
+ patch(
+ "homeassistant.components.zwave_js.helpers.async_get_node_from_device_id",
+ side_effect=(climate_danfoss_lc_13, diff_network_node),
+ ),
):
await hass.services.async_call(
DOMAIN,
diff --git a/tests/components/zwave_me/test_config_flow.py b/tests/components/zwave_me/test_config_flow.py
index f84b74b2f0e..52d5e8fce6f 100644
--- a/tests/components/zwave_me/test_config_flow.py
+++ b/tests/components/zwave_me/test_config_flow.py
@@ -29,12 +29,15 @@ MOCK_ZEROCONF_DATA = zeroconf.ZeroconfServiceInfo(
async def test_form(hass: HomeAssistant) -> None:
"""Test we get the form."""
- with patch(
- "homeassistant.components.zwave_me.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.zwave_me.helpers.get_uuid",
- return_value="test_uuid",
+ with (
+ patch(
+ "homeassistant.components.zwave_me.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.zwave_me.helpers.get_uuid",
+ return_value="test_uuid",
+ ),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@@ -61,12 +64,15 @@ async def test_form(hass: HomeAssistant) -> None:
async def test_zeroconf(hass: HomeAssistant) -> None:
"""Test starting a flow from zeroconf."""
- with patch(
- "homeassistant.components.zwave_me.async_setup_entry",
- return_value=True,
- ) as mock_setup_entry, patch(
- "homeassistant.components.zwave_me.helpers.get_uuid",
- return_value="test_uuid",
+ with (
+ patch(
+ "homeassistant.components.zwave_me.async_setup_entry",
+ return_value=True,
+ ) as mock_setup_entry,
+ patch(
+ "homeassistant.components.zwave_me.helpers.get_uuid",
+ return_value="test_uuid",
+ ),
):
result: FlowResult = await hass.config_entries.flow.async_init(
DOMAIN,
diff --git a/tests/components/zwave_me/test_remove_stale_devices.py b/tests/components/zwave_me/test_remove_stale_devices.py
index 8117237ba15..0a4ae24e0f0 100644
--- a/tests/components/zwave_me/test_remove_stale_devices.py
+++ b/tests/components/zwave_me/test_remove_stale_devices.py
@@ -51,11 +51,14 @@ async def test_remove_stale_devices(
connections={("mac", "12:34:56:AB:CD:EF")},
identifiers={("zwave_me", f"{config_entry.unique_id}-{identifier}")},
)
- with patch(
- "homeassistant.components.zwave_me.ZWaveMe.get_connection",
- mock_connection,
- ), patch(
- "homeassistant.components.zwave_me.async_setup_platforms",
+ with (
+ patch(
+ "homeassistant.components.zwave_me.ZWaveMe.get_connection",
+ mock_connection,
+ ),
+ patch(
+ "homeassistant.components.zwave_me.async_setup_platforms",
+ ),
):
await hass.config_entries.async_setup(config_entry.entry_id)
assert (
diff --git a/tests/conftest.py b/tests/conftest.py
index 4eacb8991c0..157e0f2ba59 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -161,9 +161,9 @@ def pytest_runtest_setup() -> None:
except ImportError:
pass
else:
- MySQLdb_converters.conversions[
- HAFakeDatetime
- ] = MySQLdb_converters.DateTime2literal
+ MySQLdb_converters.conversions[HAFakeDatetime] = (
+ MySQLdb_converters.DateTime2literal
+ )
def ha_datetime_to_fakedatetime(datetime) -> freezegun.api.FakeDatetime: # type: ignore[name-defined]
@@ -622,15 +622,18 @@ def mock_device_tracker_conf() -> Generator[list[Device], None, None]:
async def mock_update_config(path: str, dev_id: str, entity: Device) -> None:
devices.append(entity)
- with patch(
- (
- "homeassistant.components.device_tracker.legacy"
- ".DeviceTracker.async_update_config"
+ with (
+ patch(
+ (
+ "homeassistant.components.device_tracker.legacy"
+ ".DeviceTracker.async_update_config"
+ ),
+ side_effect=mock_update_config,
+ ),
+ patch(
+ "homeassistant.components.device_tracker.legacy.async_load_config",
+ side_effect=lambda *args: devices,
),
- side_effect=mock_update_config,
- ), patch(
- "homeassistant.components.device_tracker.legacy.async_load_config",
- side_effect=lambda *args: devices,
):
yield devices
@@ -1124,10 +1127,9 @@ def mock_zeroconf() -> Generator[None, None, None]:
"""Mock zeroconf."""
from zeroconf import DNSCache # pylint: disable=import-outside-toplevel
- with patch(
- "homeassistant.components.zeroconf.HaZeroconf", autospec=True
- ) as mock_zc, patch(
- "homeassistant.components.zeroconf.AsyncServiceBrowser", autospec=True
+ with (
+ patch("homeassistant.components.zeroconf.HaZeroconf", autospec=True) as mock_zc,
+ patch("homeassistant.components.zeroconf.AsyncServiceBrowser", autospec=True),
):
zc = mock_zc.return_value
# DNSCache has strong Cython type checks, and MagicMock does not work
@@ -1338,38 +1340,47 @@ def hass_recorder(
migrate_entity_ids = (
recorder.Recorder._migrate_entity_ids if enable_migrate_entity_ids else None
)
- with patch(
- "homeassistant.components.recorder.Recorder.async_nightly_tasks",
- side_effect=nightly,
- autospec=True,
- ), patch(
- "homeassistant.components.recorder.Recorder.async_periodic_statistics",
- side_effect=stats,
- autospec=True,
- ), patch(
- "homeassistant.components.recorder.migration._find_schema_errors",
- side_effect=schema_validate,
- autospec=True,
- ), patch(
- "homeassistant.components.recorder.Recorder._migrate_events_context_ids",
- side_effect=migrate_events_context_ids,
- autospec=True,
- ), patch(
- "homeassistant.components.recorder.Recorder._migrate_states_context_ids",
- side_effect=migrate_states_context_ids,
- autospec=True,
- ), patch(
- "homeassistant.components.recorder.Recorder._migrate_event_type_ids",
- side_effect=migrate_event_type_ids,
- autospec=True,
- ), patch(
- "homeassistant.components.recorder.Recorder._migrate_entity_ids",
- side_effect=migrate_entity_ids,
- autospec=True,
- ), patch(
- "homeassistant.components.recorder.Recorder._schedule_compile_missing_statistics",
- side_effect=compile_missing,
- autospec=True,
+ with (
+ patch(
+ "homeassistant.components.recorder.Recorder.async_nightly_tasks",
+ side_effect=nightly,
+ autospec=True,
+ ),
+ patch(
+ "homeassistant.components.recorder.Recorder.async_periodic_statistics",
+ side_effect=stats,
+ autospec=True,
+ ),
+ patch(
+ "homeassistant.components.recorder.migration._find_schema_errors",
+ side_effect=schema_validate,
+ autospec=True,
+ ),
+ patch(
+ "homeassistant.components.recorder.Recorder._migrate_events_context_ids",
+ side_effect=migrate_events_context_ids,
+ autospec=True,
+ ),
+ patch(
+ "homeassistant.components.recorder.Recorder._migrate_states_context_ids",
+ side_effect=migrate_states_context_ids,
+ autospec=True,
+ ),
+ patch(
+ "homeassistant.components.recorder.Recorder._migrate_event_type_ids",
+ side_effect=migrate_event_type_ids,
+ autospec=True,
+ ),
+ patch(
+ "homeassistant.components.recorder.Recorder._migrate_entity_ids",
+ side_effect=migrate_entity_ids,
+ autospec=True,
+ ),
+ patch(
+ "homeassistant.components.recorder.Recorder._schedule_compile_missing_statistics",
+ side_effect=compile_missing,
+ autospec=True,
+ ),
):
def setup_recorder(config: dict[str, Any] | None = None) -> HomeAssistant:
@@ -1462,38 +1473,47 @@ async def async_setup_recorder_instance(
migrate_entity_ids = (
recorder.Recorder._migrate_entity_ids if enable_migrate_entity_ids else None
)
- with patch(
- "homeassistant.components.recorder.Recorder.async_nightly_tasks",
- side_effect=nightly,
- autospec=True,
- ), patch(
- "homeassistant.components.recorder.Recorder.async_periodic_statistics",
- side_effect=stats,
- autospec=True,
- ), patch(
- "homeassistant.components.recorder.migration._find_schema_errors",
- side_effect=schema_validate,
- autospec=True,
- ), patch(
- "homeassistant.components.recorder.Recorder._migrate_events_context_ids",
- side_effect=migrate_events_context_ids,
- autospec=True,
- ), patch(
- "homeassistant.components.recorder.Recorder._migrate_states_context_ids",
- side_effect=migrate_states_context_ids,
- autospec=True,
- ), patch(
- "homeassistant.components.recorder.Recorder._migrate_event_type_ids",
- side_effect=migrate_event_type_ids,
- autospec=True,
- ), patch(
- "homeassistant.components.recorder.Recorder._migrate_entity_ids",
- side_effect=migrate_entity_ids,
- autospec=True,
- ), patch(
- "homeassistant.components.recorder.Recorder._schedule_compile_missing_statistics",
- side_effect=compile_missing,
- autospec=True,
+ with (
+ patch(
+ "homeassistant.components.recorder.Recorder.async_nightly_tasks",
+ side_effect=nightly,
+ autospec=True,
+ ),
+ patch(
+ "homeassistant.components.recorder.Recorder.async_periodic_statistics",
+ side_effect=stats,
+ autospec=True,
+ ),
+ patch(
+ "homeassistant.components.recorder.migration._find_schema_errors",
+ side_effect=schema_validate,
+ autospec=True,
+ ),
+ patch(
+ "homeassistant.components.recorder.Recorder._migrate_events_context_ids",
+ side_effect=migrate_events_context_ids,
+ autospec=True,
+ ),
+ patch(
+ "homeassistant.components.recorder.Recorder._migrate_states_context_ids",
+ side_effect=migrate_states_context_ids,
+ autospec=True,
+ ),
+ patch(
+ "homeassistant.components.recorder.Recorder._migrate_event_type_ids",
+ side_effect=migrate_event_type_ids,
+ autospec=True,
+ ),
+ patch(
+ "homeassistant.components.recorder.Recorder._migrate_entity_ids",
+ side_effect=migrate_entity_ids,
+ autospec=True,
+ ),
+ patch(
+ "homeassistant.components.recorder.Recorder._schedule_compile_missing_statistics",
+ side_effect=compile_missing,
+ autospec=True,
+ ),
):
async def async_setup_recorder(
@@ -1540,22 +1560,25 @@ async def mock_enable_bluetooth(
@pytest.fixture(scope="session")
def mock_bluetooth_adapters() -> Generator[None, None, None]:
"""Fixture to mock bluetooth adapters."""
- with patch("bluetooth_auto_recovery.recover_adapter"), patch(
- "bluetooth_adapters.systems.platform.system", return_value="Linux"
- ), patch("bluetooth_adapters.systems.linux.LinuxAdapters.refresh"), patch(
- "bluetooth_adapters.systems.linux.LinuxAdapters.adapters",
- {
- "hci0": {
- "address": "00:00:00:00:00:01",
- "hw_version": "usb:v1D6Bp0246d053F",
- "passive_scan": False,
- "sw_version": "homeassistant",
- "manufacturer": "ACME",
- "product": "Bluetooth Adapter 5.0",
- "product_id": "aa01",
- "vendor_id": "cc01",
+ with (
+ patch("bluetooth_auto_recovery.recover_adapter"),
+ patch("bluetooth_adapters.systems.platform.system", return_value="Linux"),
+ patch("bluetooth_adapters.systems.linux.LinuxAdapters.refresh"),
+ patch(
+ "bluetooth_adapters.systems.linux.LinuxAdapters.adapters",
+ {
+ "hci0": {
+ "address": "00:00:00:00:00:01",
+ "hw_version": "usb:v1D6Bp0246d053F",
+ "passive_scan": False,
+ "sw_version": "homeassistant",
+ "manufacturer": "ACME",
+ "product": "Bluetooth Adapter 5.0",
+ "product_id": "aa01",
+ "vendor_id": "cc01",
+ },
},
- },
+ ),
):
yield
@@ -1573,10 +1596,13 @@ def mock_bleak_scanner_start() -> Generator[MagicMock, None, None]:
# out start and this fixture will expire before the stop method is called
# when EVENT_HOMEASSISTANT_STOP is fired.
bluetooth_scanner.OriginalBleakScanner.stop = AsyncMock() # type: ignore[assignment]
- with patch.object(
- bluetooth_scanner.OriginalBleakScanner,
- "start",
- ) as mock_bleak_scanner_start, patch.object(bluetooth_scanner, "HaScanner"):
+ with (
+ patch.object(
+ bluetooth_scanner.OriginalBleakScanner,
+ "start",
+ ) as mock_bleak_scanner_start,
+ patch.object(bluetooth_scanner, "HaScanner"),
+ ):
yield mock_bleak_scanner_start
@@ -1588,24 +1614,28 @@ def mock_integration_frame() -> Generator[Mock, None, None]:
lineno="23",
line="self.light.is_on",
)
- with patch(
- "homeassistant.helpers.frame.linecache.getline", return_value=correct_frame.line
- ), patch(
- "homeassistant.helpers.frame.get_current_frame",
- return_value=extract_stack_to_frame(
- [
- Mock(
- filename="/home/paulus/homeassistant/core.py",
- lineno="23",
- line="do_something()",
- ),
- correct_frame,
- Mock(
- filename="/home/paulus/aiohue/lights.py",
- lineno="2",
- line="something()",
- ),
- ]
+ with (
+ patch(
+ "homeassistant.helpers.frame.linecache.getline",
+ return_value=correct_frame.line,
+ ),
+ patch(
+ "homeassistant.helpers.frame.get_current_frame",
+ return_value=extract_stack_to_frame(
+ [
+ Mock(
+ filename="/home/paulus/homeassistant/core.py",
+ lineno="23",
+ line="do_something()",
+ ),
+ correct_frame,
+ Mock(
+ filename="/home/paulus/aiohue/lights.py",
+ lineno="2",
+ line="something()",
+ ),
+ ]
+ ),
),
):
yield correct_frame
diff --git a/tests/helpers/test_aiohttp_client.py b/tests/helpers/test_aiohttp_client.py
index 73339e9fe3c..69015c80305 100644
--- a/tests/helpers/test_aiohttp_client.py
+++ b/tests/helpers/test_aiohttp_client.py
@@ -171,29 +171,32 @@ async def test_warning_close_session_integration(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test log warning message when closing the session from integration context."""
- with patch(
- "homeassistant.helpers.frame.linecache.getline",
- return_value="await session.close()",
- ), patch(
- "homeassistant.helpers.frame.get_current_frame",
- return_value=extract_stack_to_frame(
- [
- Mock(
- filename="/home/paulus/homeassistant/core.py",
- lineno="23",
- line="do_something()",
- ),
- Mock(
- filename="/home/paulus/homeassistant/components/hue/light.py",
- lineno="23",
- line="await session.close()",
- ),
- Mock(
- filename="/home/paulus/aiohue/lights.py",
- lineno="2",
- line="something()",
- ),
- ]
+ with (
+ patch(
+ "homeassistant.helpers.frame.linecache.getline",
+ return_value="await session.close()",
+ ),
+ patch(
+ "homeassistant.helpers.frame.get_current_frame",
+ return_value=extract_stack_to_frame(
+ [
+ Mock(
+ filename="/home/paulus/homeassistant/core.py",
+ lineno="23",
+ line="do_something()",
+ ),
+ Mock(
+ filename="/home/paulus/homeassistant/components/hue/light.py",
+ lineno="23",
+ line="await session.close()",
+ ),
+ Mock(
+ filename="/home/paulus/aiohue/lights.py",
+ lineno="2",
+ line="something()",
+ ),
+ ]
+ ),
),
):
session = client.async_get_clientsession(hass)
@@ -212,29 +215,32 @@ async def test_warning_close_session_custom(
) -> None:
"""Test log warning message when closing the session from custom context."""
mock_integration(hass, MockModule("hue"), built_in=False)
- with patch(
- "homeassistant.helpers.frame.linecache.getline",
- return_value="await session.close()",
- ), patch(
- "homeassistant.helpers.frame.get_current_frame",
- return_value=extract_stack_to_frame(
- [
- Mock(
- filename="/home/paulus/homeassistant/core.py",
- lineno="23",
- line="do_something()",
- ),
- Mock(
- filename="/home/paulus/config/custom_components/hue/light.py",
- lineno="23",
- line="await session.close()",
- ),
- Mock(
- filename="/home/paulus/aiohue/lights.py",
- lineno="2",
- line="something()",
- ),
- ]
+ with (
+ patch(
+ "homeassistant.helpers.frame.linecache.getline",
+ return_value="await session.close()",
+ ),
+ patch(
+ "homeassistant.helpers.frame.get_current_frame",
+ return_value=extract_stack_to_frame(
+ [
+ Mock(
+ filename="/home/paulus/homeassistant/core.py",
+ lineno="23",
+ line="do_something()",
+ ),
+ Mock(
+ filename="/home/paulus/config/custom_components/hue/light.py",
+ lineno="23",
+ line="await session.close()",
+ ),
+ Mock(
+ filename="/home/paulus/aiohue/lights.py",
+ lineno="2",
+ line="something()",
+ ),
+ ]
+ ),
),
):
session = client.async_get_clientsession(hass)
diff --git a/tests/helpers/test_check_config.py b/tests/helpers/test_check_config.py
index bba9c3f27c4..fd94c453e51 100644
--- a/tests/helpers/test_check_config.py
+++ b/tests/helpers/test_check_config.py
@@ -121,10 +121,14 @@ async def test_integrationt_requirement_not_found(hass: HomeAssistant) -> None:
"""Test errors if integration with a requirement not found not found."""
# Make sure they don't exist
files = {YAML_CONFIG_FILE: BASE_CONFIG + "test_custom_component:"}
- with patch(
- "homeassistant.helpers.check_config.async_get_integration_with_requirements",
- side_effect=RequirementsNotFound("test_custom_component", ["any"]),
- ), patch("os.path.isfile", return_value=True), patch_yaml_files(files):
+ with (
+ patch(
+ "homeassistant.helpers.check_config.async_get_integration_with_requirements",
+ side_effect=RequirementsNotFound("test_custom_component", ["any"]),
+ ),
+ patch("os.path.isfile", return_value=True),
+ patch_yaml_files(files),
+ ):
res = await async_check_ha_config_file(hass)
log_ha_config(res)
@@ -170,10 +174,14 @@ async def test_integration_import_error(hass: HomeAssistant) -> None:
"""Test errors if integration with a requirement not found not found."""
# Make sure they don't exist
files = {YAML_CONFIG_FILE: BASE_CONFIG + "light:"}
- with patch(
- "homeassistant.loader.Integration.async_get_component",
- side_effect=ImportError("blablabla"),
- ), patch("os.path.isfile", return_value=True), patch_yaml_files(files):
+ with (
+ patch(
+ "homeassistant.loader.Integration.async_get_component",
+ side_effect=ImportError("blablabla"),
+ ),
+ patch("os.path.isfile", return_value=True),
+ patch_yaml_files(files),
+ ):
res = await async_check_ha_config_file(hass)
log_ha_config(res)
@@ -336,10 +344,14 @@ async def test_config_platform_import_error(hass: HomeAssistant) -> None:
"""Test errors if config platform fails to import."""
# Make sure they don't exist
files = {YAML_CONFIG_FILE: BASE_CONFIG + "light:\n platform: beer"}
- with patch(
- "homeassistant.loader.Integration.async_get_platform",
- side_effect=ImportError("blablabla"),
- ), patch("os.path.isfile", return_value=True), patch_yaml_files(files):
+ with (
+ patch(
+ "homeassistant.loader.Integration.async_get_platform",
+ side_effect=ImportError("blablabla"),
+ ),
+ patch("os.path.isfile", return_value=True),
+ patch_yaml_files(files),
+ ):
res = await async_check_ha_config_file(hass)
log_ha_config(res)
@@ -356,10 +368,14 @@ async def test_platform_import_error(hass: HomeAssistant) -> None:
"""Test errors if platform not found."""
# Make sure they don't exist
files = {YAML_CONFIG_FILE: BASE_CONFIG + "light:\n platform: demo"}
- with patch(
- "homeassistant.loader.Integration.async_get_platform",
- side_effect=[None, ImportError("blablabla")],
- ), patch("os.path.isfile", return_value=True), patch_yaml_files(files):
+ with (
+ patch(
+ "homeassistant.loader.Integration.async_get_platform",
+ side_effect=[None, ImportError("blablabla")],
+ ),
+ patch("os.path.isfile", return_value=True),
+ patch_yaml_files(files),
+ ):
res = await async_check_ha_config_file(hass)
log_ha_config(res)
diff --git a/tests/helpers/test_config_entry_flow.py b/tests/helpers/test_config_entry_flow.py
index 0735c0a1a80..e99cfbb2f58 100644
--- a/tests/helpers/test_config_entry_flow.py
+++ b/tests/helpers/test_config_entry_flow.py
@@ -376,18 +376,23 @@ async def test_webhook_create_cloudhook(
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
- with patch(
- "hass_nabucasa.cloudhooks.Cloudhooks.async_create",
- return_value={"cloudhook_url": "https://example.com"},
- ) as mock_create, patch(
- "hass_nabucasa.Cloud.subscription_expired",
- new_callable=PropertyMock(return_value=False),
- ), patch(
- "hass_nabucasa.Cloud.is_logged_in",
- new_callable=PropertyMock(return_value=True),
- ), patch(
- "hass_nabucasa.iot_base.BaseIoT.connected",
- new_callable=PropertyMock(return_value=True),
+ with (
+ patch(
+ "hass_nabucasa.cloudhooks.Cloudhooks.async_create",
+ return_value={"cloudhook_url": "https://example.com"},
+ ) as mock_create,
+ patch(
+ "hass_nabucasa.Cloud.subscription_expired",
+ new_callable=PropertyMock(return_value=False),
+ ),
+ patch(
+ "hass_nabucasa.Cloud.is_logged_in",
+ new_callable=PropertyMock(return_value=True),
+ ),
+ patch(
+ "hass_nabucasa.iot_base.BaseIoT.connected",
+ new_callable=PropertyMock(return_value=True),
+ ),
):
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
@@ -432,18 +437,23 @@ async def test_webhook_create_cloudhook_aborts_not_connected(
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
- with patch(
- "hass_nabucasa.cloudhooks.Cloudhooks.async_create",
- return_value={"cloudhook_url": "https://example.com"},
- ), patch(
- "hass_nabucasa.Cloud.subscription_expired",
- new_callable=PropertyMock(return_value=False),
- ), patch(
- "hass_nabucasa.Cloud.is_logged_in",
- new_callable=PropertyMock(return_value=True),
- ), patch(
- "hass_nabucasa.iot_base.BaseIoT.connected",
- new_callable=PropertyMock(return_value=False),
+ with (
+ patch(
+ "hass_nabucasa.cloudhooks.Cloudhooks.async_create",
+ return_value={"cloudhook_url": "https://example.com"},
+ ),
+ patch(
+ "hass_nabucasa.Cloud.subscription_expired",
+ new_callable=PropertyMock(return_value=False),
+ ),
+ patch(
+ "hass_nabucasa.Cloud.is_logged_in",
+ new_callable=PropertyMock(return_value=True),
+ ),
+ patch(
+ "hass_nabucasa.iot_base.BaseIoT.connected",
+ new_callable=PropertyMock(return_value=False),
+ ),
):
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
diff --git a/tests/helpers/test_config_entry_oauth2_flow.py b/tests/helpers/test_config_entry_oauth2_flow.py
index 6ad8af5d698..a9e69f542f3 100644
--- a/tests/helpers/test_config_entry_oauth2_flow.py
+++ b/tests/helpers/test_config_entry_oauth2_flow.py
@@ -104,9 +104,10 @@ def test_inherit_enforces_domain_set() -> None:
"""Return logger."""
return logging.getLogger(__name__)
- with patch.dict(
- config_entries.HANDLERS, {TEST_DOMAIN: TestFlowHandler}
- ), pytest.raises(TypeError):
+ with (
+ patch.dict(config_entries.HANDLERS, {TEST_DOMAIN: TestFlowHandler}),
+ pytest.raises(TypeError),
+ ):
TestFlowHandler()
diff --git a/tests/helpers/test_config_validation.py b/tests/helpers/test_config_validation.py
index c10e82627eb..133e5e80442 100644
--- a/tests/helpers/test_config_validation.py
+++ b/tests/helpers/test_config_validation.py
@@ -97,8 +97,9 @@ def test_isfile() -> None:
# patching methods that allow us to fake a file existing
# with write access
- with patch("os.path.isfile", Mock(return_value=True)), patch(
- "os.access", Mock(return_value=True)
+ with (
+ patch("os.path.isfile", Mock(return_value=True)),
+ patch("os.access", Mock(return_value=True)),
):
schema("test.txt")
diff --git a/tests/helpers/test_deprecation.py b/tests/helpers/test_deprecation.py
index 4cca4174e9c..b53a6d5ec1d 100644
--- a/tests/helpers/test_deprecation.py
+++ b/tests/helpers/test_deprecation.py
@@ -178,29 +178,32 @@ def test_deprecated_function_called_from_built_in_integration(
def mock_deprecated_function():
pass
- with patch(
- "homeassistant.helpers.frame.linecache.getline",
- return_value="await session.close()",
- ), patch(
- "homeassistant.helpers.frame.get_current_frame",
- return_value=extract_stack_to_frame(
- [
- Mock(
- filename="/home/paulus/homeassistant/core.py",
- lineno="23",
- line="do_something()",
- ),
- Mock(
- filename="/home/paulus/homeassistant/components/hue/light.py",
- lineno="23",
- line="await session.close()",
- ),
- Mock(
- filename="/home/paulus/aiohue/lights.py",
- lineno="2",
- line="something()",
- ),
- ]
+ with (
+ patch(
+ "homeassistant.helpers.frame.linecache.getline",
+ return_value="await session.close()",
+ ),
+ patch(
+ "homeassistant.helpers.frame.get_current_frame",
+ return_value=extract_stack_to_frame(
+ [
+ Mock(
+ filename="/home/paulus/homeassistant/core.py",
+ lineno="23",
+ line="do_something()",
+ ),
+ Mock(
+ filename="/home/paulus/homeassistant/components/hue/light.py",
+ lineno="23",
+ line="await session.close()",
+ ),
+ Mock(
+ filename="/home/paulus/aiohue/lights.py",
+ lineno="2",
+ line="something()",
+ ),
+ ]
+ ),
),
):
mock_deprecated_function()
@@ -235,29 +238,32 @@ def test_deprecated_function_called_from_custom_integration(
def mock_deprecated_function():
pass
- with patch(
- "homeassistant.helpers.frame.linecache.getline",
- return_value="await session.close()",
- ), patch(
- "homeassistant.helpers.frame.get_current_frame",
- return_value=extract_stack_to_frame(
- [
- Mock(
- filename="/home/paulus/homeassistant/core.py",
- lineno="23",
- line="do_something()",
- ),
- Mock(
- filename="/home/paulus/config/custom_components/hue/light.py",
- lineno="23",
- line="await session.close()",
- ),
- Mock(
- filename="/home/paulus/aiohue/lights.py",
- lineno="2",
- line="something()",
- ),
- ]
+ with (
+ patch(
+ "homeassistant.helpers.frame.linecache.getline",
+ return_value="await session.close()",
+ ),
+ patch(
+ "homeassistant.helpers.frame.get_current_frame",
+ return_value=extract_stack_to_frame(
+ [
+ Mock(
+ filename="/home/paulus/homeassistant/core.py",
+ lineno="23",
+ line="do_something()",
+ ),
+ Mock(
+ filename="/home/paulus/config/custom_components/hue/light.py",
+ lineno="23",
+ line="await session.close()",
+ ),
+ Mock(
+ filename="/home/paulus/aiohue/lights.py",
+ lineno="2",
+ line="something()",
+ ),
+ ]
+ ),
),
):
mock_deprecated_function()
@@ -337,29 +343,33 @@ def test_check_if_deprecated_constant(
filename = f"/home/paulus/{module_name.replace('.', '/')}.py"
# mock sys.modules for homeassistant/helpers/frame.py#get_integration_frame
- with patch.dict(sys.modules, {module_name: Mock(__file__=filename)}), patch(
- "homeassistant.helpers.frame.linecache.getline",
- return_value="await session.close()",
- ), patch(
- "homeassistant.helpers.frame.get_current_frame",
- return_value=extract_stack_to_frame(
- [
- Mock(
- filename="/home/paulus/homeassistant/core.py",
- lineno="23",
- line="do_something()",
- ),
- Mock(
- filename=filename,
- lineno="23",
- line="await session.close()",
- ),
- Mock(
- filename="/home/paulus/aiohue/lights.py",
- lineno="2",
- line="something()",
- ),
- ]
+ with (
+ patch.dict(sys.modules, {module_name: Mock(__file__=filename)}),
+ patch(
+ "homeassistant.helpers.frame.linecache.getline",
+ return_value="await session.close()",
+ ),
+ patch(
+ "homeassistant.helpers.frame.get_current_frame",
+ return_value=extract_stack_to_frame(
+ [
+ Mock(
+ filename="/home/paulus/homeassistant/core.py",
+ lineno="23",
+ line="do_something()",
+ ),
+ Mock(
+ filename=filename,
+ lineno="23",
+ line="await session.close()",
+ ),
+ Mock(
+ filename="/home/paulus/aiohue/lights.py",
+ lineno="2",
+ line="something()",
+ ),
+ ]
+ ),
),
):
value = check_if_deprecated_constant("TEST_CONSTANT", module_globals)
diff --git a/tests/helpers/test_device_registry.py b/tests/helpers/test_device_registry.py
index 4438ba93861..bed3dea4dc1 100644
--- a/tests/helpers/test_device_registry.py
+++ b/tests/helpers/test_device_registry.py
@@ -2453,13 +2453,17 @@ async def test_device_name_translation_placeholders_errors(
config_entry_1 = MockConfigEntry()
config_entry_1.add_to_hass(hass)
- with patch(
- "homeassistant.helpers.device_registry.translation.async_get_cached_translations",
- side_effect=async_get_cached_translations,
- ), patch(
- "homeassistant.helpers.device_registry.get_release_channel",
- return_value=release_channel,
- ), expectation:
+ with (
+ patch(
+ "homeassistant.helpers.device_registry.translation.async_get_cached_translations",
+ side_effect=async_get_cached_translations,
+ ),
+ patch(
+ "homeassistant.helpers.device_registry.get_release_channel",
+ return_value=release_channel,
+ ),
+ expectation,
+ ):
device_registry.async_get_or_create(
config_entry_id=config_entry_1.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
diff --git a/tests/helpers/test_entity.py b/tests/helpers/test_entity.py
index dab986a7284..dac03f0be67 100644
--- a/tests/helpers/test_entity.py
+++ b/tests/helpers/test_entity.py
@@ -741,12 +741,13 @@ async def test_disabled_in_entity_registry(hass: HomeAssistant) -> None:
async def test_capability_attrs(hass: HomeAssistant) -> None:
"""Test we still include capabilities even when unavailable."""
- with patch.object(
- entity.Entity, "available", PropertyMock(return_value=False)
- ), patch.object(
- entity.Entity,
- "capability_attributes",
- PropertyMock(return_value={"always": "there"}),
+ with (
+ patch.object(entity.Entity, "available", PropertyMock(return_value=False)),
+ patch.object(
+ entity.Entity,
+ "capability_attributes",
+ PropertyMock(return_value={"always": "there"}),
+ ),
):
ent = entity.Entity()
ent.hass = hass
@@ -1328,11 +1329,15 @@ async def test_entity_name_translation_placeholder_errors(
caplog.clear()
- with patch(
- "homeassistant.helpers.entity_platform.translation.async_get_translations",
- side_effect=async_get_translations,
- ), patch(
- "homeassistant.helpers.entity.get_release_channel", return_value=release_channel
+ with (
+ patch(
+ "homeassistant.helpers.entity_platform.translation.async_get_translations",
+ side_effect=async_get_translations,
+ ),
+ patch(
+ "homeassistant.helpers.entity.get_release_channel",
+ return_value=release_channel,
+ ),
):
await entity_platform.async_setup_entry(config_entry)
diff --git a/tests/helpers/test_entity_platform.py b/tests/helpers/test_entity_platform.py
index efea66c8d77..17b5d634018 100644
--- a/tests/helpers/test_entity_platform.py
+++ b/tests/helpers/test_entity_platform.py
@@ -1761,8 +1761,9 @@ async def test_setup_entry_with_entities_that_block_forever(
hass, platform_name=config_entry.domain, platform=platform
)
- with patch.object(entity_platform, "SLOW_ADD_ENTITY_MAX_WAIT", 0.01), patch.object(
- entity_platform, "SLOW_ADD_MIN_TIMEOUT", 0.01
+ with (
+ patch.object(entity_platform, "SLOW_ADD_ENTITY_MAX_WAIT", 0.01),
+ patch.object(entity_platform, "SLOW_ADD_MIN_TIMEOUT", 0.01),
):
assert await platform.async_setup_entry(config_entry)
await hass.async_block_till_done()
diff --git a/tests/helpers/test_entity_registry.py b/tests/helpers/test_entity_registry.py
index 0974d3bc9de..a9177fc8c83 100644
--- a/tests/helpers/test_entity_registry.py
+++ b/tests/helpers/test_entity_registry.py
@@ -704,9 +704,10 @@ async def test_update_entity_unique_id_conflict(
entry2 = entity_registry.async_get_or_create(
"light", "hue", "1234", config_entry=mock_config
)
- with patch.object(
- entity_registry, "async_schedule_save"
- ) as mock_schedule_save, pytest.raises(ValueError):
+ with (
+ patch.object(entity_registry, "async_schedule_save") as mock_schedule_save,
+ pytest.raises(ValueError),
+ ):
entity_registry.async_update_entity(
entry.entity_id, new_unique_id=entry2.unique_id
)
@@ -752,9 +753,10 @@ async def test_update_entity_entity_id_entity_id(
assert entry2.entity_id != state_entity_id
# Try updating to a registered entity_id
- with patch.object(
- entity_registry, "async_schedule_save"
- ) as mock_schedule_save, pytest.raises(ValueError):
+ with (
+ patch.object(entity_registry, "async_schedule_save") as mock_schedule_save,
+ pytest.raises(ValueError),
+ ):
entity_registry.async_update_entity(
entry.entity_id, new_entity_id=entry2.entity_id
)
@@ -769,9 +771,10 @@ async def test_update_entity_entity_id_entity_id(
assert entity_registry.async_get(entry2.entity_id) is entry2
# Try updating to an entity_id which is in the state machine
- with patch.object(
- entity_registry, "async_schedule_save"
- ) as mock_schedule_save, pytest.raises(ValueError):
+ with (
+ patch.object(entity_registry, "async_schedule_save") as mock_schedule_save,
+ pytest.raises(ValueError),
+ ):
entity_registry.async_update_entity(
entry.entity_id, new_entity_id=state_entity_id
)
diff --git a/tests/helpers/test_frame.py b/tests/helpers/test_frame.py
index 7881c845a77..fe215264f59 100644
--- a/tests/helpers/test_frame.py
+++ b/tests/helpers/test_frame.py
@@ -107,23 +107,26 @@ async def test_extract_frame_integration_with_excluded_integration(
async def test_extract_frame_no_integration(caplog: pytest.LogCaptureFixture) -> None:
"""Test extracting the current frame without integration context."""
- with patch(
- "homeassistant.helpers.frame.get_current_frame",
- return_value=extract_stack_to_frame(
- [
- Mock(
- filename="/home/paulus/homeassistant/core.py",
- lineno="23",
- line="do_something()",
- ),
- Mock(
- filename="/home/paulus/aiohue/lights.py",
- lineno="2",
- line="something()",
- ),
- ]
+ with (
+ patch(
+ "homeassistant.helpers.frame.get_current_frame",
+ return_value=extract_stack_to_frame(
+ [
+ Mock(
+ filename="/home/paulus/homeassistant/core.py",
+ lineno="23",
+ line="do_something()",
+ ),
+ Mock(
+ filename="/home/paulus/aiohue/lights.py",
+ lineno="2",
+ line="something()",
+ ),
+ ]
+ ),
),
- ), pytest.raises(frame.MissingIntegrationFrame):
+ pytest.raises(frame.MissingIntegrationFrame),
+ ):
frame.get_integration_frame()
diff --git a/tests/helpers/test_httpx_client.py b/tests/helpers/test_httpx_client.py
index 2d1baf88b16..60bdbe607e3 100644
--- a/tests/helpers/test_httpx_client.py
+++ b/tests/helpers/test_httpx_client.py
@@ -104,29 +104,32 @@ async def test_warning_close_session_integration(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test log warning message when closing the session from integration context."""
- with patch(
- "homeassistant.helpers.frame.linecache.getline",
- return_value="await session.aclose()",
- ), patch(
- "homeassistant.helpers.frame.get_current_frame",
- return_value=extract_stack_to_frame(
- [
- Mock(
- filename="/home/paulus/homeassistant/core.py",
- lineno="23",
- line="do_something()",
- ),
- Mock(
- filename="/home/paulus/homeassistant/components/hue/light.py",
- lineno="23",
- line="await session.aclose()",
- ),
- Mock(
- filename="/home/paulus/aiohue/lights.py",
- lineno="2",
- line="something()",
- ),
- ]
+ with (
+ patch(
+ "homeassistant.helpers.frame.linecache.getline",
+ return_value="await session.aclose()",
+ ),
+ patch(
+ "homeassistant.helpers.frame.get_current_frame",
+ return_value=extract_stack_to_frame(
+ [
+ Mock(
+ filename="/home/paulus/homeassistant/core.py",
+ lineno="23",
+ line="do_something()",
+ ),
+ Mock(
+ filename="/home/paulus/homeassistant/components/hue/light.py",
+ lineno="23",
+ line="await session.aclose()",
+ ),
+ Mock(
+ filename="/home/paulus/aiohue/lights.py",
+ lineno="2",
+ line="something()",
+ ),
+ ]
+ ),
),
):
httpx_session = client.get_async_client(hass)
@@ -146,29 +149,32 @@ async def test_warning_close_session_custom(
) -> None:
"""Test log warning message when closing the session from custom context."""
mock_integration(hass, MockModule("hue"), built_in=False)
- with patch(
- "homeassistant.helpers.frame.linecache.getline",
- return_value="await session.aclose()",
- ), patch(
- "homeassistant.helpers.frame.get_current_frame",
- return_value=extract_stack_to_frame(
- [
- Mock(
- filename="/home/paulus/homeassistant/core.py",
- lineno="23",
- line="do_something()",
- ),
- Mock(
- filename="/home/paulus/config/custom_components/hue/light.py",
- lineno="23",
- line="await session.aclose()",
- ),
- Mock(
- filename="/home/paulus/aiohue/lights.py",
- lineno="2",
- line="something()",
- ),
- ]
+ with (
+ patch(
+ "homeassistant.helpers.frame.linecache.getline",
+ return_value="await session.aclose()",
+ ),
+ patch(
+ "homeassistant.helpers.frame.get_current_frame",
+ return_value=extract_stack_to_frame(
+ [
+ Mock(
+ filename="/home/paulus/homeassistant/core.py",
+ lineno="23",
+ line="do_something()",
+ ),
+ Mock(
+ filename="/home/paulus/config/custom_components/hue/light.py",
+ lineno="23",
+ line="await session.aclose()",
+ ),
+ Mock(
+ filename="/home/paulus/aiohue/lights.py",
+ lineno="2",
+ line="something()",
+ ),
+ ]
+ ),
),
):
httpx_session = client.get_async_client(hass)
diff --git a/tests/helpers/test_icon.py b/tests/helpers/test_icon.py
index cf329100d75..e986a07d7d5 100644
--- a/tests/helpers/test_icon.py
+++ b/tests/helpers/test_icon.py
@@ -161,15 +161,19 @@ async def test_get_icons_while_loading_components(hass: HomeAssistant) -> None:
load_count += 1
return {"component1": {"entity": {"climate": {"test": {"icon": "mdi:home"}}}}}
- with patch(
- "homeassistant.helpers.icon._component_icons_path",
- return_value="choochoo.json",
- ), patch(
- "homeassistant.helpers.icon._load_icons_files",
- mock_load_icons_files,
- ), patch(
- "homeassistant.helpers.icon.async_get_integrations",
- return_value={"component1": integration},
+ with (
+ patch(
+ "homeassistant.helpers.icon._component_icons_path",
+ return_value="choochoo.json",
+ ),
+ patch(
+ "homeassistant.helpers.icon._load_icons_files",
+ mock_load_icons_files,
+ ),
+ patch(
+ "homeassistant.helpers.icon.async_get_integrations",
+ return_value={"component1": integration},
+ ),
):
times = 5
all_icons = [await icon.async_get_icons(hass, "entity") for _ in range(times)]
diff --git a/tests/helpers/test_importlib.py b/tests/helpers/test_importlib.py
index 7f89018ded2..5683dd5cf94 100644
--- a/tests/helpers/test_importlib.py
+++ b/tests/helpers/test_importlib.py
@@ -38,17 +38,23 @@ async def test_async_import_module_on_helper(hass: HomeAssistant) -> None:
async def test_async_import_module_failures(hass: HomeAssistant) -> None:
"""Test importing a module fails."""
- with patch(
- "homeassistant.helpers.importlib.importlib.import_module",
- side_effect=ImportError,
- ), pytest.raises(ImportError):
+ with (
+ patch(
+ "homeassistant.helpers.importlib.importlib.import_module",
+ side_effect=ImportError,
+ ),
+ pytest.raises(ImportError),
+ ):
await importlib.async_import_module(hass, "test.module")
mock_module = MockModule()
# The failure should be cached
- with pytest.raises(ImportError), patch(
- "homeassistant.helpers.importlib.importlib.import_module",
- return_value=mock_module,
+ with (
+ pytest.raises(ImportError),
+ patch(
+ "homeassistant.helpers.importlib.importlib.import_module",
+ return_value=mock_module,
+ ),
):
await importlib.async_import_module(hass, "test.module")
diff --git a/tests/helpers/test_instance_id.py b/tests/helpers/test_instance_id.py
index 3f1326bcd2e..ad2e4626af5 100644
--- a/tests/helpers/test_instance_id.py
+++ b/tests/helpers/test_instance_id.py
@@ -41,9 +41,11 @@ async def test_get_id_migrate(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Migrate existing file."""
- with patch(
- "homeassistant.util.json.load_json", return_value={"uuid": "1234"}
- ), patch("os.path.isfile", return_value=True), patch("os.remove") as mock_remove:
+ with (
+ patch("homeassistant.util.json.load_json", return_value={"uuid": "1234"}),
+ patch("os.path.isfile", return_value=True),
+ patch("os.remove") as mock_remove,
+ ):
uuid = await instance_id.async_get(hass)
assert uuid == "1234"
@@ -59,10 +61,14 @@ async def test_get_id_migrate_fail(
hass: HomeAssistant, hass_storage: dict[str, Any], caplog: pytest.LogCaptureFixture
) -> None:
"""Migrate existing file with error."""
- with patch(
- "homeassistant.util.json.load_json",
- side_effect=JSONDecodeError("test_error", "test", 1),
- ), patch("os.path.isfile", return_value=True), patch("os.remove") as mock_remove:
+ with (
+ patch(
+ "homeassistant.util.json.load_json",
+ side_effect=JSONDecodeError("test_error", "test", 1),
+ ),
+ patch("os.path.isfile", return_value=True),
+ patch("os.remove") as mock_remove,
+ ):
uuid = await instance_id.async_get(hass)
assert uuid is not None
diff --git a/tests/helpers/test_integration_platform.py b/tests/helpers/test_integration_platform.py
index 2eeae2ff3e0..81eb1f2fd38 100644
--- a/tests/helpers/test_integration_platform.py
+++ b/tests/helpers/test_integration_platform.py
@@ -163,9 +163,10 @@ async def test_process_integration_platforms_import_fails_after_registered(
assert processed[0][1] == loaded_platform
event_integration = await loader.async_get_integration(hass, "event")
- with patch.object(
- event_integration, "async_get_platforms", side_effect=ImportError
- ), patch.object(event_integration, "get_platform_cached", return_value=None):
+ with (
+ patch.object(event_integration, "async_get_platforms", side_effect=ImportError),
+ patch.object(event_integration, "get_platform_cached", return_value=None),
+ ):
hass.bus.async_fire(EVENT_COMPONENT_LOADED, {ATTR_COMPONENT: "event"})
await hass.async_block_till_done()
diff --git a/tests/helpers/test_network.py b/tests/helpers/test_network.py
index 3c0793290d0..caffebf094e 100644
--- a/tests/helpers/test_network.py
+++ b/tests/helpers/test_network.py
@@ -75,10 +75,13 @@ async def test_get_url_internal(hass: HomeAssistant) -> None:
with pytest.raises(NoURLAvailableError):
_get_internal_url(hass, require_current_request=True, require_ssl=True)
- with patch(
- "homeassistant.helpers.network._get_request_host",
- return_value="no_match.example.local",
- ), pytest.raises(NoURLAvailableError):
+ with (
+ patch(
+ "homeassistant.helpers.network._get_request_host",
+ return_value="no_match.example.local",
+ ),
+ pytest.raises(NoURLAvailableError),
+ ):
_get_internal_url(hass, require_current_request=True)
# Test with internal URL: https://example.local:8123
@@ -275,10 +278,13 @@ async def test_get_url_external(hass: HomeAssistant) -> None:
with pytest.raises(NoURLAvailableError):
_get_external_url(hass, require_current_request=True, require_ssl=True)
- with patch(
- "homeassistant.helpers.network._get_request_host",
- return_value="no_match.example.com",
- ), pytest.raises(NoURLAvailableError):
+ with (
+ patch(
+ "homeassistant.helpers.network._get_request_host",
+ return_value="no_match.example.com",
+ ),
+ pytest.raises(NoURLAvailableError),
+ ):
_get_external_url(hass, require_current_request=True)
# Test with external URL: http://example.com:80/
@@ -380,16 +386,22 @@ async def test_get_cloud_url(hass: HomeAssistant) -> None:
== "https://example.nabu.casa"
)
- with patch(
- "homeassistant.helpers.network._get_request_host",
- return_value="no_match.nabu.casa",
- ), pytest.raises(NoURLAvailableError):
+ with (
+ patch(
+ "homeassistant.helpers.network._get_request_host",
+ return_value="no_match.nabu.casa",
+ ),
+ pytest.raises(NoURLAvailableError),
+ ):
_get_cloud_url(hass, require_current_request=True)
- with patch(
- "homeassistant.components.cloud.async_remote_ui_url",
- side_effect=cloud.CloudNotAvailable,
- ), pytest.raises(NoURLAvailableError):
+ with (
+ patch(
+ "homeassistant.components.cloud.async_remote_ui_url",
+ side_effect=cloud.CloudNotAvailable,
+ ),
+ pytest.raises(NoURLAvailableError),
+ ):
_get_cloud_url(hass)
@@ -506,9 +518,13 @@ async def test_get_url(hass: HomeAssistant) -> None:
with pytest.raises(NoURLAvailableError):
get_url(hass, require_current_request=True)
- with patch(
- "homeassistant.helpers.network._get_request_host", return_value="example.com"
- ), patch("homeassistant.components.http.current_request"):
+ with (
+ patch(
+ "homeassistant.helpers.network._get_request_host",
+ return_value="example.com",
+ ),
+ patch("homeassistant.components.http.current_request"),
+ ):
assert get_url(hass, require_current_request=True) == "https://example.com"
assert (
get_url(hass, require_current_request=True, require_ssl=True)
@@ -518,9 +534,13 @@ async def test_get_url(hass: HomeAssistant) -> None:
with pytest.raises(NoURLAvailableError):
get_url(hass, require_current_request=True, allow_external=False)
- with patch(
- "homeassistant.helpers.network._get_request_host", return_value="example.local"
- ), patch("homeassistant.components.http.current_request"):
+ with (
+ patch(
+ "homeassistant.helpers.network._get_request_host",
+ return_value="example.local",
+ ),
+ patch("homeassistant.components.http.current_request"),
+ ):
assert get_url(hass, require_current_request=True) == "http://example.local"
with pytest.raises(NoURLAvailableError):
@@ -529,10 +549,13 @@ async def test_get_url(hass: HomeAssistant) -> None:
with pytest.raises(NoURLAvailableError):
get_url(hass, require_current_request=True, require_ssl=True)
- with patch(
- "homeassistant.helpers.network._get_request_host",
- return_value="no_match.example.com",
- ), pytest.raises(NoURLAvailableError):
+ with (
+ patch(
+ "homeassistant.helpers.network._get_request_host",
+ return_value="no_match.example.com",
+ ),
+ pytest.raises(NoURLAvailableError),
+ ):
_get_internal_url(hass, require_current_request=True)
# Test allow_ip defaults when SSL specified
@@ -615,9 +638,13 @@ async def test_get_current_request_url_with_known_host(
get_url(hass, require_current_request=True) == "http://homeassistant:8123"
)
- with patch(
- "homeassistant.helpers.network._get_request_host", return_value="unknown.local"
- ), pytest.raises(NoURLAvailableError):
+ with (
+ patch(
+ "homeassistant.helpers.network._get_request_host",
+ return_value="unknown.local",
+ ),
+ pytest.raises(NoURLAvailableError),
+ ):
get_url(hass, require_current_request=True)
diff --git a/tests/helpers/test_reload.py b/tests/helpers/test_reload.py
index 4f7a2053a87..66d4efe9a55 100644
--- a/tests/helpers/test_reload.py
+++ b/tests/helpers/test_reload.py
@@ -141,10 +141,13 @@ async def test_setup_reload_service_when_async_process_component_config_fails(
await async_setup_reload_service(hass, PLATFORM, [DOMAIN])
yaml_path = get_fixture_path("helpers/reload_configuration.yaml")
- with patch.object(config, "YAML_CONFIG_FILE", yaml_path), patch.object(
- config,
- "async_process_component_config",
- return_value=config.IntegrationConfigInfo(None, []),
+ with (
+ patch.object(config, "YAML_CONFIG_FILE", yaml_path),
+ patch.object(
+ config,
+ "async_process_component_config",
+ return_value=config.IntegrationConfigInfo(None, []),
+ ),
):
await hass.services.async_call(
PLATFORM,
@@ -250,10 +253,14 @@ async def test_async_integration_failing_on_reload(hass: HomeAssistant) -> None:
mock_integration(hass, MockModule(DOMAIN))
yaml_path = get_fixture_path(f"helpers/{DOMAIN}_configuration.yaml")
- with patch.object(config, "YAML_CONFIG_FILE", yaml_path), patch(
- "homeassistant.config.async_process_component_config",
- side_effect=HomeAssistantError(),
- ), pytest.raises(HomeAssistantError):
+ with (
+ patch.object(config, "YAML_CONFIG_FILE", yaml_path),
+ patch(
+ "homeassistant.config.async_process_component_config",
+ side_effect=HomeAssistantError(),
+ ),
+ pytest.raises(HomeAssistantError),
+ ):
# Test fetching yaml config does raise when the raise_on_failure option is set
await async_integration_yaml_config(hass, DOMAIN, raise_on_failure=True)
@@ -263,7 +270,8 @@ async def test_async_integration_missing_yaml_config(hass: HomeAssistant) -> Non
mock_integration(hass, MockModule(DOMAIN))
yaml_path = get_fixture_path("helpers/does_not_exist_configuration.yaml")
- with pytest.raises(FileNotFoundError), patch.object(
- config, "YAML_CONFIG_FILE", yaml_path
+ with (
+ pytest.raises(FileNotFoundError),
+ patch.object(config, "YAML_CONFIG_FILE", yaml_path),
):
await async_integration_yaml_config(hass, DOMAIN)
diff --git a/tests/helpers/test_script.py b/tests/helpers/test_script.py
index 95bb3f813e4..c1462ccfc2f 100644
--- a/tests/helpers/test_script.py
+++ b/tests/helpers/test_script.py
@@ -4929,10 +4929,13 @@ async def test_validate_action_config(
assert key in expected_templates or key in script.STATIC_VALIDATION_ACTION_TYPES
# Verify we raise if we don't know the action type
- with patch(
- "homeassistant.helpers.config_validation.determine_script_action",
- return_value="non-existing",
- ), pytest.raises(ValueError):
+ with (
+ patch(
+ "homeassistant.helpers.config_validation.determine_script_action",
+ return_value="non-existing",
+ ),
+ pytest.raises(ValueError),
+ ):
await script.async_validate_action_config(hass, {})
# Verify each action can validate
diff --git a/tests/helpers/test_service.py b/tests/helpers/test_service.py
index cf099b3bc23..74b8a86ce7c 100644
--- a/tests/helpers/test_service.py
+++ b/tests/helpers/test_service.py
@@ -927,12 +927,15 @@ async def test_async_get_all_descriptions_failing_integration(
logger_config = {DOMAIN_LOGGER: {}}
await async_setup_component(hass, DOMAIN_LOGGER, logger_config)
- with patch(
- "homeassistant.helpers.service.async_get_integrations",
- return_value={"logger": ImportError},
- ), patch(
- "homeassistant.helpers.service.translation.async_get_translations",
- return_value={},
+ with (
+ patch(
+ "homeassistant.helpers.service.async_get_integrations",
+ return_value={"logger": ImportError},
+ ),
+ patch(
+ "homeassistant.helpers.service.translation.async_get_translations",
+ return_value={},
+ ),
):
descriptions = await service.async_get_all_descriptions(hass)
@@ -1294,9 +1297,12 @@ async def test_call_context_target_specific_no_auth(
hass: HomeAssistant, mock_handle_entity_call, mock_entities
) -> None:
"""Check targeting specific entities without auth."""
- with pytest.raises(exceptions.Unauthorized) as err, patch(
- "homeassistant.auth.AuthManager.async_get_user",
- return_value=Mock(permissions=PolicyPermissions({}, None), is_admin=False),
+ with (
+ pytest.raises(exceptions.Unauthorized) as err,
+ patch(
+ "homeassistant.auth.AuthManager.async_get_user",
+ return_value=Mock(permissions=PolicyPermissions({}, None), is_admin=False),
+ ),
):
await service.entity_service_call(
hass,
diff --git a/tests/helpers/test_significant_change.py b/tests/helpers/test_significant_change.py
index 8dda63bb72b..e930ff30feb 100644
--- a/tests/helpers/test_significant_change.py
+++ b/tests/helpers/test_significant_change.py
@@ -18,9 +18,9 @@ async def checker_fixture(hass):
):
return abs(float(old_state) - float(new_state)) > 4
- hass.data[significant_change.DATA_FUNCTIONS][
- "test_domain"
- ] = async_check_significant_change
+ hass.data[significant_change.DATA_FUNCTIONS]["test_domain"] = (
+ async_check_significant_change
+ )
return checker
diff --git a/tests/helpers/test_storage.py b/tests/helpers/test_storage.py
index 0918a9551f4..d04f7902297 100644
--- a/tests/helpers/test_storage.py
+++ b/tests/helpers/test_storage.py
@@ -410,8 +410,9 @@ async def test_migrator_no_existing_config(
hass: HomeAssistant, store, hass_storage: dict[str, Any]
) -> None:
"""Test migrator with no existing config."""
- with patch("os.path.isfile", return_value=False), patch.object(
- store, "async_load", return_value={"cur": "config"}
+ with (
+ patch("os.path.isfile", return_value=False),
+ patch.object(store, "async_load", return_value={"cur": "config"}),
):
data = await storage.async_migrator(hass, "old-path", store)
@@ -791,14 +792,20 @@ async def test_os_error_is_fatal(tmpdir: py.path.local) -> None:
)
await store.async_save({"hello": "world"})
- with pytest.raises(OSError), patch(
- "homeassistant.helpers.storage.json_util.load_json", side_effect=OSError
+ with (
+ pytest.raises(OSError),
+ patch(
+ "homeassistant.helpers.storage.json_util.load_json", side_effect=OSError
+ ),
):
await store.async_load()
# Verify second load is also failing
- with pytest.raises(OSError), patch(
- "homeassistant.helpers.storage.json_util.load_json", side_effect=OSError
+ with (
+ pytest.raises(OSError),
+ patch(
+ "homeassistant.helpers.storage.json_util.load_json", side_effect=OSError
+ ),
):
await store.async_load()
@@ -820,9 +827,12 @@ async def test_json_load_failure(tmpdir: py.path.local) -> None:
home_assistant_error = HomeAssistantError()
home_assistant_error.__cause__ = base_os_error
- with pytest.raises(HomeAssistantError), patch(
- "homeassistant.helpers.storage.json_util.load_json",
- side_effect=home_assistant_error,
+ with (
+ pytest.raises(HomeAssistantError),
+ patch(
+ "homeassistant.helpers.storage.json_util.load_json",
+ side_effect=home_assistant_error,
+ ),
):
await store.async_load()
diff --git a/tests/helpers/test_system_info.py b/tests/helpers/test_system_info.py
index a7f77bd5cfb..16b5b8b652b 100644
--- a/tests/helpers/test_system_info.py
+++ b/tests/helpers/test_system_info.py
@@ -36,13 +36,14 @@ async def test_get_system_info_supervisor_not_available(
) -> None:
"""Test the get system info when supervisor is not available."""
hass.config.components.add("hassio")
- with patch("platform.system", return_value="Linux"), patch(
- "homeassistant.helpers.system_info.is_docker_env", return_value=True
- ), patch(
- "homeassistant.helpers.system_info.is_official_image", return_value=True
- ), patch.object(hassio, "is_hassio", return_value=True), patch.object(
- hassio, "get_info", return_value=None
- ), patch("homeassistant.helpers.system_info.cached_get_user", return_value="root"):
+ with (
+ patch("platform.system", return_value="Linux"),
+ patch("homeassistant.helpers.system_info.is_docker_env", return_value=True),
+ patch("homeassistant.helpers.system_info.is_official_image", return_value=True),
+ patch.object(hassio, "is_hassio", return_value=True),
+ patch.object(hassio, "get_info", return_value=None),
+ patch("homeassistant.helpers.system_info.cached_get_user", return_value="root"),
+ ):
info = await async_get_system_info(hass)
assert isinstance(info, dict)
assert info["version"] == current_version
@@ -54,12 +55,12 @@ async def test_get_system_info_supervisor_not_available(
async def test_get_system_info_supervisor_not_loaded(hass: HomeAssistant) -> None:
"""Test the get system info when supervisor is not loaded."""
- with patch("platform.system", return_value="Linux"), patch(
- "homeassistant.helpers.system_info.is_docker_env", return_value=True
- ), patch(
- "homeassistant.helpers.system_info.is_official_image", return_value=True
- ), patch.object(hassio, "get_info", return_value=None), patch.dict(
- os.environ, {"SUPERVISOR": "127.0.0.1"}
+ with (
+ patch("platform.system", return_value="Linux"),
+ patch("homeassistant.helpers.system_info.is_docker_env", return_value=True),
+ patch("homeassistant.helpers.system_info.is_official_image", return_value=True),
+ patch.object(hassio, "get_info", return_value=None),
+ patch.dict(os.environ, {"SUPERVISOR": "127.0.0.1"}),
):
info = await async_get_system_info(hass)
assert isinstance(info, dict)
@@ -71,19 +72,23 @@ async def test_get_system_info_supervisor_not_loaded(hass: HomeAssistant) -> Non
async def test_container_installationtype(hass: HomeAssistant) -> None:
"""Test container installation type."""
- with patch("platform.system", return_value="Linux"), patch(
- "homeassistant.helpers.system_info.is_docker_env", return_value=True
- ), patch(
- "homeassistant.helpers.system_info.is_official_image", return_value=True
- ), patch("homeassistant.helpers.system_info.cached_get_user", return_value="root"):
+ with (
+ patch("platform.system", return_value="Linux"),
+ patch("homeassistant.helpers.system_info.is_docker_env", return_value=True),
+ patch("homeassistant.helpers.system_info.is_official_image", return_value=True),
+ patch("homeassistant.helpers.system_info.cached_get_user", return_value="root"),
+ ):
info = await async_get_system_info(hass)
assert info["installation_type"] == "Home Assistant Container"
- with patch("platform.system", return_value="Linux"), patch(
- "homeassistant.helpers.system_info.is_docker_env", return_value=True
- ), patch(
- "homeassistant.helpers.system_info.is_official_image", return_value=False
- ), patch("homeassistant.helpers.system_info.cached_get_user", return_value="user"):
+ with (
+ patch("platform.system", return_value="Linux"),
+ patch("homeassistant.helpers.system_info.is_docker_env", return_value=True),
+ patch(
+ "homeassistant.helpers.system_info.is_official_image", return_value=False
+ ),
+ patch("homeassistant.helpers.system_info.cached_get_user", return_value="user"),
+ ):
info = await async_get_system_info(hass)
assert info["installation_type"] == "Unsupported Third Party Container"
diff --git a/tests/helpers/test_translation.py b/tests/helpers/test_translation.py
index 669fb4bed24..1bba23c51a1 100644
--- a/tests/helpers/test_translation.py
+++ b/tests/helpers/test_translation.py
@@ -222,15 +222,19 @@ async def test_get_translations_loads_config_flows(
integration = Mock(file_path=pathlib.Path(__file__))
integration.name = "Component 1"
- with patch(
- "homeassistant.helpers.translation.component_translation_path",
- return_value="bla.json",
- ), patch(
- "homeassistant.helpers.translation._load_translations_files_by_language",
- return_value={"en": {"component1": {"title": "world"}}},
- ), patch(
- "homeassistant.helpers.translation.async_get_integrations",
- return_value={"component1": integration},
+ with (
+ patch(
+ "homeassistant.helpers.translation.component_translation_path",
+ return_value="bla.json",
+ ),
+ patch(
+ "homeassistant.helpers.translation._load_translations_files_by_language",
+ return_value={"en": {"component1": {"title": "world"}}},
+ ),
+ patch(
+ "homeassistant.helpers.translation.async_get_integrations",
+ return_value={"component1": integration},
+ ),
):
translations = await translation.async_get_translations(
hass, "en", "title", config_flow=True
@@ -251,15 +255,19 @@ async def test_get_translations_loads_config_flows(
integration = Mock(file_path=pathlib.Path(__file__))
integration.name = "Component 2"
- with patch(
- "homeassistant.helpers.translation.component_translation_path",
- return_value="bla.json",
- ), patch(
- "homeassistant.helpers.translation._load_translations_files_by_language",
- return_value={"en": {"component2": {"title": "world"}}},
- ), patch(
- "homeassistant.helpers.translation.async_get_integrations",
- return_value={"component2": integration},
+ with (
+ patch(
+ "homeassistant.helpers.translation.component_translation_path",
+ return_value="bla.json",
+ ),
+ patch(
+ "homeassistant.helpers.translation._load_translations_files_by_language",
+ return_value={"en": {"component2": {"title": "world"}}},
+ ),
+ patch(
+ "homeassistant.helpers.translation.async_get_integrations",
+ return_value={"component2": integration},
+ ),
):
translations = await translation.async_get_translations(
hass, "en", "title", config_flow=True
@@ -301,15 +309,19 @@ async def test_get_translations_while_loading_components(hass: HomeAssistant) ->
return {language: {"component1": {"title": "world"}} for language in files}
- with patch(
- "homeassistant.helpers.translation.component_translation_path",
- return_value="bla.json",
- ), patch(
- "homeassistant.helpers.translation._load_translations_files_by_language",
- mock_load_translation_files,
- ), patch(
- "homeassistant.helpers.translation.async_get_integrations",
- return_value={"component1": integration},
+ with (
+ patch(
+ "homeassistant.helpers.translation.component_translation_path",
+ return_value="bla.json",
+ ),
+ patch(
+ "homeassistant.helpers.translation._load_translations_files_by_language",
+ mock_load_translation_files,
+ ),
+ patch(
+ "homeassistant.helpers.translation.async_get_integrations",
+ return_value={"component1": integration},
+ ),
):
tasks = [
translation.async_get_translations(hass, "en", "title") for _ in range(5)
@@ -842,15 +854,19 @@ async def test_get_translations_still_has_title_without_translations_files(
integration = Mock(file_path=pathlib.Path(__file__))
integration.name = "Component 1"
- with patch(
- "homeassistant.helpers.translation.component_translation_path",
- return_value="bla.json",
- ), patch(
- "homeassistant.helpers.translation._load_translations_files_by_language",
- return_value={},
- ), patch(
- "homeassistant.helpers.translation.async_get_integrations",
- return_value={"component1": integration},
+ with (
+ patch(
+ "homeassistant.helpers.translation.component_translation_path",
+ return_value="bla.json",
+ ),
+ patch(
+ "homeassistant.helpers.translation._load_translations_files_by_language",
+ return_value={},
+ ),
+ patch(
+ "homeassistant.helpers.translation.async_get_integrations",
+ return_value={"component1": integration},
+ ),
):
translations = await translation.async_get_translations(
hass, "en", "title", config_flow=True
diff --git a/tests/pylint/test_enforce_super_call.py b/tests/pylint/test_enforce_super_call.py
index 39a70369e0c..84d4086fc5c 100644
--- a/tests/pylint/test_enforce_super_call.py
+++ b/tests/pylint/test_enforce_super_call.py
@@ -124,9 +124,14 @@ def test_enforce_super_call(
walker = ASTWalker(linter)
walker.add_checker(super_call_checker)
- with patch.object(
- hass_enforce_super_call, "METHODS", new={"added_to_hass", "async_added_to_hass"}
- ), assert_no_messages(linter):
+ with (
+ patch.object(
+ hass_enforce_super_call,
+ "METHODS",
+ new={"added_to_hass", "async_added_to_hass"},
+ ),
+ assert_no_messages(linter),
+ ):
walker.walk(root_node)
@@ -204,19 +209,24 @@ def test_enforce_super_call_bad(
walker.add_checker(super_call_checker)
node = root_node.body[node_idx].body[0]
- with patch.object(
- hass_enforce_super_call, "METHODS", new={"added_to_hass", "async_added_to_hass"}
- ), assert_adds_messages(
- linter,
- MessageTest(
- msg_id="hass-missing-super-call",
- node=node,
- line=node.lineno,
- args=(node.name,),
- col_offset=node.col_offset,
- end_line=node.position.end_lineno,
- end_col_offset=node.position.end_col_offset,
- confidence=INFERENCE,
+ with (
+ patch.object(
+ hass_enforce_super_call,
+ "METHODS",
+ new={"added_to_hass", "async_added_to_hass"},
+ ),
+ assert_adds_messages(
+ linter,
+ MessageTest(
+ msg_id="hass-missing-super-call",
+ node=node,
+ line=node.lineno,
+ args=(node.name,),
+ col_offset=node.col_offset,
+ end_line=node.position.end_lineno,
+ end_col_offset=node.position.end_col_offset,
+ confidence=INFERENCE,
+ ),
),
):
walker.walk(root_node)
diff --git a/tests/test_bootstrap.py b/tests/test_bootstrap.py
index 90e9017a5c1..de82aba9911 100644
--- a/tests/test_bootstrap.py
+++ b/tests/test_bootstrap.py
@@ -1,4 +1,5 @@
"""Test the bootstrapping."""
+
import asyncio
from collections.abc import Generator, Iterable
import glob
@@ -46,9 +47,10 @@ async def apply_stop_hass(stop_hass: None) -> None:
@pytest.fixture(scope="session", autouse=True)
def mock_http_start_stop() -> Generator[None, None, None]:
"""Mock HTTP start and stop."""
- with patch(
- "homeassistant.components.http.start_http_server_and_save_config"
- ), patch("homeassistant.components.http.HomeAssistantHTTP.stop"):
+ with (
+ patch("homeassistant.components.http.start_http_server_and_save_config"),
+ patch("homeassistant.components.http.HomeAssistantHTTP.stop"),
+ ):
yield
@@ -66,11 +68,15 @@ async def test_async_enable_logging(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test to ensure logging is migrated to the queue handlers."""
- with patch("logging.getLogger"), patch(
- "homeassistant.bootstrap.async_activate_log_queue_handler"
- ) as mock_async_activate_log_queue_handler, patch(
- "homeassistant.bootstrap.logging.handlers.RotatingFileHandler.doRollover",
- side_effect=OSError,
+ with (
+ patch("logging.getLogger"),
+ patch(
+ "homeassistant.bootstrap.async_activate_log_queue_handler"
+ ) as mock_async_activate_log_queue_handler,
+ patch(
+ "homeassistant.bootstrap.logging.handlers.RotatingFileHandler.doRollover",
+ side_effect=OSError,
+ ),
):
bootstrap.async_enable_logging(hass)
mock_async_activate_log_queue_handler.assert_called_once()
@@ -636,11 +642,13 @@ async def test_setup_hass_takes_longer_than_log_slow_startup(
await asyncio.sleep(0.6)
return True
- with patch.object(bootstrap, "LOG_SLOW_STARTUP_INTERVAL", 0.3), patch.object(
- bootstrap, "SLOW_STARTUP_CHECK_INTERVAL", 0.05
- ), patch(
- "homeassistant.components.frontend.async_setup",
- side_effect=_async_setup_that_blocks_startup,
+ with (
+ patch.object(bootstrap, "LOG_SLOW_STARTUP_INTERVAL", 0.3),
+ patch.object(bootstrap, "SLOW_STARTUP_CHECK_INTERVAL", 0.05),
+ patch(
+ "homeassistant.components.frontend.async_setup",
+ side_effect=_async_setup_that_blocks_startup,
+ ),
):
await bootstrap.async_setup_hass(
runner.RuntimeConfig(
@@ -718,9 +726,12 @@ async def test_setup_hass_recovery_mode(
mock_process_ha_config_upgrade: Mock,
) -> None:
"""Test it works."""
- with patch("homeassistant.components.browser.setup") as browser_setup, patch(
- "homeassistant.config_entries.ConfigEntries.async_domains",
- return_value=["browser"],
+ with (
+ patch("homeassistant.components.browser.setup") as browser_setup,
+ patch(
+ "homeassistant.config_entries.ConfigEntries.async_domains",
+ return_value=["browser"],
+ ),
):
hass = await bootstrap.async_setup_hass(
runner.RuntimeConfig(
@@ -752,9 +763,12 @@ async def test_setup_hass_safe_mode(
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test it works."""
- with patch("homeassistant.components.browser.setup"), patch(
- "homeassistant.config_entries.ConfigEntries.async_domains",
- return_value=["browser"],
+ with (
+ patch("homeassistant.components.browser.setup"),
+ patch(
+ "homeassistant.config_entries.ConfigEntries.async_domains",
+ return_value=["browser"],
+ ),
):
hass = await bootstrap.async_setup_hass(
runner.RuntimeConfig(
@@ -784,9 +798,12 @@ async def test_setup_hass_recovery_mode_and_safe_mode(
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test it works."""
- with patch("homeassistant.components.browser.setup"), patch(
- "homeassistant.config_entries.ConfigEntries.async_domains",
- return_value=["browser"],
+ with (
+ patch("homeassistant.components.browser.setup"),
+ patch(
+ "homeassistant.config_entries.ConfigEntries.async_domains",
+ return_value=["browser"],
+ ),
):
hass = await bootstrap.async_setup_hass(
runner.RuntimeConfig(
@@ -1004,10 +1021,12 @@ async def test_tasks_logged_that_block_stage_1(
)
original_stage_1 = bootstrap.STAGE_1_INTEGRATIONS
- with patch.object(bootstrap, "STAGE_1_TIMEOUT", 0), patch.object(
- bootstrap, "COOLDOWN_TIME", 0
- ), patch.object(
- bootstrap, "STAGE_1_INTEGRATIONS", [*original_stage_1, "normal_integration"]
+ with (
+ patch.object(bootstrap, "STAGE_1_TIMEOUT", 0),
+ patch.object(bootstrap, "COOLDOWN_TIME", 0),
+ patch.object(
+ bootstrap, "STAGE_1_INTEGRATIONS", [*original_stage_1, "normal_integration"]
+ ),
):
await bootstrap._async_set_up_integrations(hass, {"normal_integration": {}})
await hass.async_block_till_done()
@@ -1043,8 +1062,9 @@ async def test_tasks_logged_that_block_stage_2(
),
)
- with patch.object(bootstrap, "STAGE_2_TIMEOUT", 0), patch.object(
- bootstrap, "COOLDOWN_TIME", 0
+ with (
+ patch.object(bootstrap, "STAGE_2_TIMEOUT", 0),
+ patch.object(bootstrap, "COOLDOWN_TIME", 0),
):
await bootstrap._async_set_up_integrations(hass, {"normal_integration": {}})
await hass.async_block_till_done()
@@ -1191,12 +1211,15 @@ async def test_bootstrap_dependencies(
"""Mock integrations."""
return {domain: integrations[domain]["integration"] for domain in domains}
- with patch(
- "homeassistant.setup.loader.async_get_integrations",
- side_effect=mock_async_get_integrations,
- ), patch(
- "homeassistant.config.async_process_component_config",
- return_value=config_util.IntegrationConfigInfo({}, []),
+ with (
+ patch(
+ "homeassistant.setup.loader.async_get_integrations",
+ side_effect=mock_async_get_integrations,
+ ),
+ patch(
+ "homeassistant.config.async_process_component_config",
+ return_value=config_util.IntegrationConfigInfo({}, []),
+ ),
):
bootstrap.async_set_domains_to_be_loaded(hass, {integration})
await bootstrap.async_setup_multi_components(hass, {integration}, {})
diff --git a/tests/test_config.py b/tests/test_config.py
index c2e134b1cfd..c20e2822592 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -466,8 +466,9 @@ def test_load_yaml_config_raises_error_if_unsafe_yaml() -> None:
with open(YAML_PATH, "w") as fp:
fp.write("- !!python/object/apply:os.system []")
- with patch.object(os, "system") as system_mock, contextlib.suppress(
- HomeAssistantError
+ with (
+ patch.object(os, "system") as system_mock,
+ contextlib.suppress(HomeAssistantError),
):
config_util.load_yaml_config_file(YAML_PATH)
@@ -652,8 +653,9 @@ def test_process_config_upgrade(hass: HomeAssistant) -> None:
ha_version = "0.92.0"
mock_open = mock.mock_open()
- with patch("homeassistant.config.open", mock_open, create=True), patch.object(
- config_util, "__version__", "0.91.0"
+ with (
+ patch("homeassistant.config.open", mock_open, create=True),
+ patch.object(config_util, "__version__", "0.91.0"),
):
opened_file = mock_open.return_value
opened_file.readline.return_value = ha_version
@@ -1909,10 +1911,13 @@ async def test_component_config_error_processing(
)
),
)
- with patch(
- "homeassistant.config.async_process_component_config",
- return_value=config_util.IntegrationConfigInfo(None, exception_info_list),
- ), pytest.raises(ConfigValidationError) as ex:
+ with (
+ patch(
+ "homeassistant.config.async_process_component_config",
+ return_value=config_util.IntegrationConfigInfo(None, exception_info_list),
+ ),
+ pytest.raises(ConfigValidationError) as ex,
+ ):
await config_util.async_process_component_and_handle_errors(
hass, {}, test_integration, raise_on_failure=True
)
diff --git a/tests/test_config_entries.py b/tests/test_config_entries.py
index da100d8cfb0..7d564f1cf12 100644
--- a/tests/test_config_entries.py
+++ b/tests/test_config_entries.py
@@ -1791,9 +1791,12 @@ async def test_init_custom_integration(hass: HomeAssistant) -> None:
None,
{"name": "Hue", "dependencies": [], "requirements": [], "domain": "hue"},
)
- with pytest.raises(data_entry_flow.UnknownHandler), patch(
- "homeassistant.loader.async_get_integration",
- return_value=integration,
+ with (
+ pytest.raises(data_entry_flow.UnknownHandler),
+ patch(
+ "homeassistant.loader.async_get_integration",
+ return_value=integration,
+ ),
):
await hass.config_entries.flow.async_init("bla", context={"source": "user"})
@@ -1813,9 +1816,12 @@ async def test_init_custom_integration_with_missing_handler(
MockModule("hue"),
)
mock_platform(hass, "hue.config_flow", None)
- with pytest.raises(data_entry_flow.UnknownHandler), patch(
- "homeassistant.loader.async_get_integration",
- return_value=integration,
+ with (
+ pytest.raises(data_entry_flow.UnknownHandler),
+ patch(
+ "homeassistant.loader.async_get_integration",
+ return_value=integration,
+ ),
):
await hass.config_entries.flow.async_init("bla", context={"source": "user"})
@@ -2013,11 +2019,13 @@ async def test_entry_id_existing_entry(
"""Test user step."""
return self.async_create_entry(title="mock-title", data={"via": "flow"})
- with pytest.raises(HomeAssistantError), patch.dict(
- config_entries.HANDLERS, {"comp": TestFlow}
- ), patch(
- "homeassistant.config_entries.uuid_util.random_uuid_hex",
- return_value=collide_entry_id,
+ with (
+ pytest.raises(HomeAssistantError),
+ patch.dict(config_entries.HANDLERS, {"comp": TestFlow}),
+ patch(
+ "homeassistant.config_entries.uuid_util.random_uuid_hex",
+ return_value=collide_entry_id,
+ ),
):
await manager.flow.async_init(
"comp", context={"source": config_entries.SOURCE_USER}
@@ -2055,9 +2063,12 @@ async def test_unique_id_update_existing_entry_without_reload(
updates={"host": "1.1.1.1"}, reload_on_update=False
)
- with patch.dict(config_entries.HANDLERS, {"comp": TestFlow}), patch(
- "homeassistant.config_entries.ConfigEntries.async_reload"
- ) as async_reload:
+ with (
+ patch.dict(config_entries.HANDLERS, {"comp": TestFlow}),
+ patch(
+ "homeassistant.config_entries.ConfigEntries.async_reload"
+ ) as async_reload,
+ ):
result = await manager.flow.async_init(
"comp", context={"source": config_entries.SOURCE_USER}
)
@@ -2102,9 +2113,12 @@ async def test_unique_id_update_existing_entry_with_reload(
updates=updates, reload_on_update=True
)
- with patch.dict(config_entries.HANDLERS, {"comp": TestFlow}), patch(
- "homeassistant.config_entries.ConfigEntries.async_reload"
- ) as async_reload:
+ with (
+ patch.dict(config_entries.HANDLERS, {"comp": TestFlow}),
+ patch(
+ "homeassistant.config_entries.ConfigEntries.async_reload"
+ ) as async_reload,
+ ):
result = await manager.flow.async_init(
"comp", context={"source": config_entries.SOURCE_USER}
)
@@ -2119,9 +2133,12 @@ async def test_unique_id_update_existing_entry_with_reload(
# Test we don't reload if entry not started
updates["host"] = "2.2.2.2"
entry._async_set_state(hass, config_entries.ConfigEntryState.NOT_LOADED, None)
- with patch.dict(config_entries.HANDLERS, {"comp": TestFlow}), patch(
- "homeassistant.config_entries.ConfigEntries.async_reload"
- ) as async_reload:
+ with (
+ patch.dict(config_entries.HANDLERS, {"comp": TestFlow}),
+ patch(
+ "homeassistant.config_entries.ConfigEntries.async_reload"
+ ) as async_reload,
+ ):
result = await manager.flow.async_init(
"comp", context={"source": config_entries.SOURCE_USER}
)
@@ -2173,9 +2190,12 @@ async def test_unique_id_from_discovery_in_setup_retry(
self._abort_if_unique_id_configured()
# Verify we do not reload from a user source
- with patch.dict(config_entries.HANDLERS, {"comp": TestFlow}), patch(
- "homeassistant.config_entries.ConfigEntries.async_reload"
- ) as async_reload:
+ with (
+ patch.dict(config_entries.HANDLERS, {"comp": TestFlow}),
+ patch(
+ "homeassistant.config_entries.ConfigEntries.async_reload"
+ ) as async_reload,
+ ):
result = await manager.flow.async_init(
"comp", context={"source": config_entries.SOURCE_USER}
)
@@ -2186,9 +2206,12 @@ async def test_unique_id_from_discovery_in_setup_retry(
assert len(async_reload.mock_calls) == 0
# Verify do reload from a discovery source
- with patch.dict(config_entries.HANDLERS, {"comp": TestFlow}), patch(
- "homeassistant.config_entries.ConfigEntries.async_reload"
- ) as async_reload:
+ with (
+ patch.dict(config_entries.HANDLERS, {"comp": TestFlow}),
+ patch(
+ "homeassistant.config_entries.ConfigEntries.async_reload"
+ ) as async_reload,
+ ):
discovery_result = await manager.flow.async_init(
"comp",
context={"source": config_entries.SOURCE_DHCP},
@@ -2235,9 +2258,12 @@ async def test_unique_id_not_update_existing_entry(
updates={"host": "0.0.0.0"}, reload_on_update=True
)
- with patch.dict(config_entries.HANDLERS, {"comp": TestFlow}), patch(
- "homeassistant.config_entries.ConfigEntries.async_reload"
- ) as async_reload:
+ with (
+ patch.dict(config_entries.HANDLERS, {"comp": TestFlow}),
+ patch(
+ "homeassistant.config_entries.ConfigEntries.async_reload"
+ ) as async_reload,
+ ):
result = await manager.flow.async_init(
"comp", context={"source": config_entries.SOURCE_USER}
)
@@ -2405,9 +2431,12 @@ async def test_manual_add_overrides_ignored_entry(
async def async_step_step2(self, user_input=None):
raise NotImplementedError
- with patch.dict(config_entries.HANDLERS, {"comp": TestFlow}), patch(
- "homeassistant.config_entries.ConfigEntries.async_reload"
- ) as async_reload:
+ with (
+ patch.dict(config_entries.HANDLERS, {"comp": TestFlow}),
+ patch(
+ "homeassistant.config_entries.ConfigEntries.async_reload"
+ ) as async_reload,
+ ):
result = await manager.flow.async_init(
"comp", context={"source": config_entries.SOURCE_USER}
)
@@ -3973,9 +4002,12 @@ async def test_unique_id_update_while_setup_in_progress(
updates=updates, reload_on_update=True
)
- with patch.dict(config_entries.HANDLERS, {"comp": TestFlow}), patch(
- "homeassistant.config_entries.ConfigEntries.async_reload"
- ) as async_reload:
+ with (
+ patch.dict(config_entries.HANDLERS, {"comp": TestFlow}),
+ patch(
+ "homeassistant.config_entries.ConfigEntries.async_reload"
+ ) as async_reload,
+ ):
result = await manager.flow.async_init(
"comp", context={"source": config_entries.SOURCE_USER}
)
@@ -4726,10 +4758,13 @@ async def test_avoid_adding_second_config_entry_on_single_config_entry(
mock_integration(hass, MockModule("comp"))
mock_platform(hass, "comp.config_flow", None)
- with patch(
- "homeassistant.loader.async_get_integration",
- return_value=integration,
- ), patch.dict(config_entries.HANDLERS, {"comp": TestFlow}):
+ with (
+ patch(
+ "homeassistant.loader.async_get_integration",
+ return_value=integration,
+ ),
+ patch.dict(config_entries.HANDLERS, {"comp": TestFlow}),
+ ):
# Start a flow
result = await manager.flow.async_init(
"comp", context={"source": config_entries.SOURCE_USER}
@@ -4786,9 +4821,12 @@ async def test_in_progress_get_canceled_when_entry_is_created(
return self.async_show_form(step_id="user")
- with patch.dict(config_entries.HANDLERS, {"comp": TestFlow}), patch(
- "homeassistant.loader.async_get_integration",
- return_value=integration,
+ with (
+ patch.dict(config_entries.HANDLERS, {"comp": TestFlow}),
+ patch(
+ "homeassistant.loader.async_get_integration",
+ return_value=integration,
+ ),
):
# Create one to be in progress
result = await manager.flow.async_init(
diff --git a/tests/test_core.py b/tests/test_core.py
index ab6f0b11270..efeb185a3d6 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -705,9 +705,12 @@ async def test_shutdown_calls_block_till_done_after_shutdown_run_callback_thread
nonlocal stop_calls
stop_calls.append(("shutdown_run_callback_threadsafe", loop))
- with patch.object(hass, "async_block_till_done", _record_block_till_done), patch(
- "homeassistant.core.shutdown_run_callback_threadsafe",
- _record_shutdown_run_callback_threadsafe,
+ with (
+ patch.object(hass, "async_block_till_done", _record_block_till_done),
+ patch(
+ "homeassistant.core.shutdown_run_callback_threadsafe",
+ _record_shutdown_run_callback_threadsafe,
+ ),
):
await hass.async_stop()
diff --git a/tests/test_data_entry_flow.py b/tests/test_data_entry_flow.py
index c18eae4dd19..5c3ad2a3b39 100644
--- a/tests/test_data_entry_flow.py
+++ b/tests/test_data_entry_flow.py
@@ -760,8 +760,9 @@ async def test_abort_flow_exception(manager) -> None:
async def test_init_unknown_flow(manager) -> None:
"""Test that UnknownFlow is raised when async_create_flow returns None."""
- with pytest.raises(data_entry_flow.UnknownFlow), patch.object(
- manager, "async_create_flow", return_value=None
+ with (
+ pytest.raises(data_entry_flow.UnknownFlow),
+ patch.object(manager, "async_create_flow", return_value=None),
):
await manager.async_init("test")
diff --git a/tests/test_loader.py b/tests/test_loader.py
index c8a8905cdef..9e191ee9e00 100644
--- a/tests/test_loader.py
+++ b/tests/test_loader.py
@@ -252,13 +252,21 @@ async def test_get_integration_exceptions(hass: HomeAssistant) -> None:
"""Test resolving integration."""
integration = await loader.async_get_integration(hass, "hue")
- with pytest.raises(ImportError), patch(
- "homeassistant.loader.importlib.import_module", side_effect=ValueError("Boom")
+ with (
+ pytest.raises(ImportError),
+ patch(
+ "homeassistant.loader.importlib.import_module",
+ side_effect=ValueError("Boom"),
+ ),
):
assert hue == integration.get_component()
- with pytest.raises(ImportError), patch(
- "homeassistant.loader.importlib.import_module", side_effect=ValueError("Boom")
+ with (
+ pytest.raises(ImportError),
+ patch(
+ "homeassistant.loader.importlib.import_module",
+ side_effect=ValueError("Boom"),
+ ),
):
assert hue_light == integration.get_platform("light")
@@ -269,27 +277,43 @@ async def test_get_platform_caches_failures_when_component_loaded(
"""Test get_platform cache failures only when the component is loaded."""
integration = await loader.async_get_integration(hass, "hue")
- with pytest.raises(ImportError), patch(
- "homeassistant.loader.importlib.import_module", side_effect=ImportError("Boom")
+ with (
+ pytest.raises(ImportError),
+ patch(
+ "homeassistant.loader.importlib.import_module",
+ side_effect=ImportError("Boom"),
+ ),
):
assert integration.get_component() == hue
- with pytest.raises(ImportError), patch(
- "homeassistant.loader.importlib.import_module", side_effect=ImportError("Boom")
+ with (
+ pytest.raises(ImportError),
+ patch(
+ "homeassistant.loader.importlib.import_module",
+ side_effect=ImportError("Boom"),
+ ),
):
assert integration.get_platform("light") == hue_light
# Hue is not loaded so we should still hit the import_module path
- with pytest.raises(ImportError), patch(
- "homeassistant.loader.importlib.import_module", side_effect=ImportError("Boom")
+ with (
+ pytest.raises(ImportError),
+ patch(
+ "homeassistant.loader.importlib.import_module",
+ side_effect=ImportError("Boom"),
+ ),
):
assert integration.get_platform("light") == hue_light
assert integration.get_component() == hue
# Hue is loaded so we should cache the import_module failure now
- with pytest.raises(ImportError), patch(
- "homeassistant.loader.importlib.import_module", side_effect=ImportError("Boom")
+ with (
+ pytest.raises(ImportError),
+ patch(
+ "homeassistant.loader.importlib.import_module",
+ side_effect=ImportError("Boom"),
+ ),
):
assert integration.get_platform("light") == hue_light
@@ -304,27 +328,43 @@ async def test_async_get_platform_caches_failures_when_component_loaded(
"""Test async_get_platform cache failures only when the component is loaded."""
integration = await loader.async_get_integration(hass, "hue")
- with pytest.raises(ImportError), patch(
- "homeassistant.loader.importlib.import_module", side_effect=ImportError("Boom")
+ with (
+ pytest.raises(ImportError),
+ patch(
+ "homeassistant.loader.importlib.import_module",
+ side_effect=ImportError("Boom"),
+ ),
):
assert integration.get_component() == hue
- with pytest.raises(ImportError), patch(
- "homeassistant.loader.importlib.import_module", side_effect=ImportError("Boom")
+ with (
+ pytest.raises(ImportError),
+ patch(
+ "homeassistant.loader.importlib.import_module",
+ side_effect=ImportError("Boom"),
+ ),
):
assert await integration.async_get_platform("light") == hue_light
# Hue is not loaded so we should still hit the import_module path
- with pytest.raises(ImportError), patch(
- "homeassistant.loader.importlib.import_module", side_effect=ImportError("Boom")
+ with (
+ pytest.raises(ImportError),
+ patch(
+ "homeassistant.loader.importlib.import_module",
+ side_effect=ImportError("Boom"),
+ ),
):
assert await integration.async_get_platform("light") == hue_light
assert integration.get_component() == hue
# Hue is loaded so we should cache the import_module failure now
- with pytest.raises(ImportError), patch(
- "homeassistant.loader.importlib.import_module", side_effect=ImportError("Boom")
+ with (
+ pytest.raises(ImportError),
+ patch(
+ "homeassistant.loader.importlib.import_module",
+ side_effect=ImportError("Boom"),
+ ),
):
assert await integration.async_get_platform("light") == hue_light
@@ -342,27 +382,43 @@ async def test_async_get_platforms_caches_failures_when_component_loaded(
"""Test async_get_platforms cache failures only when the component is loaded."""
integration = await loader.async_get_integration(hass, "hue")
- with pytest.raises(ImportError), patch(
- "homeassistant.loader.importlib.import_module", side_effect=ImportError("Boom")
+ with (
+ pytest.raises(ImportError),
+ patch(
+ "homeassistant.loader.importlib.import_module",
+ side_effect=ImportError("Boom"),
+ ),
):
assert integration.get_component() == hue
- with pytest.raises(ImportError), patch(
- "homeassistant.loader.importlib.import_module", side_effect=ImportError("Boom")
+ with (
+ pytest.raises(ImportError),
+ patch(
+ "homeassistant.loader.importlib.import_module",
+ side_effect=ImportError("Boom"),
+ ),
):
assert await integration.async_get_platforms(["light"]) == {"light": hue_light}
# Hue is not loaded so we should still hit the import_module path
- with pytest.raises(ImportError), patch(
- "homeassistant.loader.importlib.import_module", side_effect=ImportError("Boom")
+ with (
+ pytest.raises(ImportError),
+ patch(
+ "homeassistant.loader.importlib.import_module",
+ side_effect=ImportError("Boom"),
+ ),
):
assert await integration.async_get_platforms(["light"]) == {"light": hue_light}
assert integration.get_component() == hue
# Hue is loaded so we should cache the import_module failure now
- with pytest.raises(ImportError), patch(
- "homeassistant.loader.importlib.import_module", side_effect=ImportError("Boom")
+ with (
+ pytest.raises(ImportError),
+ patch(
+ "homeassistant.loader.importlib.import_module",
+ side_effect=ImportError("Boom"),
+ ),
):
assert await integration.async_get_platforms(["light"]) == {"light": hue_light}
@@ -1129,12 +1185,15 @@ async def test_hass_components_use_reported(
relative_filename="custom_components/test_integration_frame/__init__.py",
)
- with patch(
- "homeassistant.helpers.frame.get_integration_frame",
- return_value=integration_frame,
- ), patch(
- "homeassistant.components.http.start_http_server_and_save_config",
- return_value=None,
+ with (
+ patch(
+ "homeassistant.helpers.frame.get_integration_frame",
+ return_value=integration_frame,
+ ),
+ patch(
+ "homeassistant.components.http.start_http_server_and_save_config",
+ return_value=None,
+ ),
):
await hass.components.http.start_http_server_and_save_config(hass, [], None)
@@ -1162,10 +1221,11 @@ async def test_async_get_component_preloads_config_and_config_flow(
platform_exists_calls.append(platforms)
return platforms
- with patch(
- "homeassistant.loader.importlib.import_module"
- ) as mock_import, patch.object(
- executor_import_integration, "platforms_exists", mock_platforms_exists
+ with (
+ patch("homeassistant.loader.importlib.import_module") as mock_import,
+ patch.object(
+ executor_import_integration, "platforms_exists", mock_platforms_exists
+ ),
):
await executor_import_integration.async_get_component()
@@ -1218,11 +1278,14 @@ async def test_async_get_component_loads_loop_if_already_in_sys_modules(
modules_without_config_flow = {
k: v for k, v in sys.modules.items() if k != config_flow_module_name
}
- with patch.dict(
- "sys.modules",
- {**modules_without_config_flow, integration.pkg_path: module_mock},
- clear=True,
- ), patch("homeassistant.loader.importlib.import_module", import_module):
+ with (
+ patch.dict(
+ "sys.modules",
+ {**modules_without_config_flow, integration.pkg_path: module_mock},
+ clear=True,
+ ),
+ patch("homeassistant.loader.importlib.import_module", import_module),
+ ):
module = await integration.async_get_component()
# The config flow is missing so we should load
@@ -1232,13 +1295,16 @@ async def test_async_get_component_loads_loop_if_already_in_sys_modules(
assert module is module_mock
caplog.clear()
- with patch.dict(
- "sys.modules",
- {
- integration.pkg_path: module_mock,
- config_flow_module_name: config_flow_module_mock,
- },
- ), patch("homeassistant.loader.importlib.import_module", import_module):
+ with (
+ patch.dict(
+ "sys.modules",
+ {
+ integration.pkg_path: module_mock,
+ config_flow_module_name: config_flow_module_mock,
+ },
+ ),
+ patch("homeassistant.loader.importlib.import_module", import_module),
+ ):
module = await integration.async_get_component()
# Everything is already in the integration cache
@@ -1285,11 +1351,14 @@ async def test_async_get_component_concurrent_loads(
for k, v in sys.modules.items()
if k != config_flow_module_name and k != integration.pkg_path
}
- with patch.dict(
- "sys.modules",
- {**modules_without_integration},
- clear=True,
- ), patch("homeassistant.loader.importlib.import_module", import_module):
+ with (
+ patch.dict(
+ "sys.modules",
+ {**modules_without_integration},
+ clear=True,
+ ),
+ patch("homeassistant.loader.importlib.import_module", import_module),
+ ):
load_task1 = asyncio.create_task(integration.async_get_component())
load_task2 = asyncio.create_task(integration.async_get_component())
await import_event.wait() # make sure the import is started
@@ -1371,9 +1440,10 @@ async def test_async_get_component_raises_after_import_failure(
assert "homeassistant.components.executor_import" not in sys.modules
assert "custom_components.executor_import" not in sys.modules
- with patch(
- "homeassistant.loader.importlib.import_module", mock_import
- ), pytest.raises(ImportError):
+ with (
+ patch("homeassistant.loader.importlib.import_module", mock_import),
+ pytest.raises(ImportError),
+ ):
await executor_import_integration.async_get_component()
assert (
@@ -1454,9 +1524,10 @@ async def test_async_get_platform_raises_after_import_failure(
assert "homeassistant.components.executor_import" not in sys.modules
assert "custom_components.executor_import" not in sys.modules
- with patch(
- "homeassistant.loader.importlib.import_module", mock_import
- ), pytest.raises(ImportError):
+ with (
+ patch("homeassistant.loader.importlib.import_module", mock_import),
+ pytest.raises(ImportError),
+ ):
await executor_import_integration.async_get_platform("config_flow")
assert (
@@ -1563,11 +1634,14 @@ async def test_async_get_platforms_loads_loop_if_already_in_sys_modules(
modules_without_button = {
k: v for k, v in sys.modules.items() if k != button_module_name
}
- with patch.dict(
- "sys.modules",
- modules_without_button,
- clear=True,
- ), patch("homeassistant.loader.importlib.import_module", import_module):
+ with (
+ patch.dict(
+ "sys.modules",
+ modules_without_button,
+ clear=True,
+ ),
+ patch("homeassistant.loader.importlib.import_module", import_module),
+ ):
module = (await integration.async_get_platforms(["button"]))["button"]
# The button module is missing so we should load
@@ -1577,13 +1651,16 @@ async def test_async_get_platforms_loads_loop_if_already_in_sys_modules(
assert module is button_module_mock
caplog.clear()
- with patch.dict(
- "sys.modules",
- {
- **modules_without_button,
- button_module_name: button_module_mock,
- },
- ), patch("homeassistant.loader.importlib.import_module", import_module):
+ with (
+ patch.dict(
+ "sys.modules",
+ {
+ **modules_without_button,
+ button_module_name: button_module_mock,
+ },
+ ),
+ patch("homeassistant.loader.importlib.import_module", import_module),
+ ):
module = (await integration.async_get_platforms(["button"]))["button"]
# Everything is cached so there should be no logging
@@ -1595,11 +1672,14 @@ async def test_async_get_platforms_loads_loop_if_already_in_sys_modules(
modules_without_switch = {
k: v for k, v in sys.modules.items() if k not in switch_module_name
}
- with patch.dict(
- "sys.modules",
- {**modules_without_switch, light_module_name: light_module_mock},
- clear=True,
- ), patch("homeassistant.loader.importlib.import_module", import_module):
+ with (
+ patch.dict(
+ "sys.modules",
+ {**modules_without_switch, light_module_name: light_module_mock},
+ clear=True,
+ ),
+ patch("homeassistant.loader.importlib.import_module", import_module),
+ ):
modules = await integration.async_get_platforms(["button", "switch", "light"])
# The button module is already in the cache so nothing happens
@@ -1659,11 +1739,14 @@ async def test_async_get_platforms_concurrent_loads(
for k, v in sys.modules.items()
if k != button_module_name and k != integration.pkg_path
}
- with patch.dict(
- "sys.modules",
- modules_without_button,
- clear=True,
- ), patch("homeassistant.loader.importlib.import_module", import_module):
+ with (
+ patch.dict(
+ "sys.modules",
+ modules_without_button,
+ clear=True,
+ ),
+ patch("homeassistant.loader.importlib.import_module", import_module),
+ ):
load_task1 = asyncio.create_task(integration.async_get_platforms(["button"]))
load_task2 = asyncio.create_task(integration.async_get_platforms(["button"]))
await import_event.wait() # make sure the import is started
diff --git a/tests/test_requirements.py b/tests/test_requirements.py
index 87d055e2122..ed04ef8649b 100644
--- a/tests/test_requirements.py
+++ b/tests/test_requirements.py
@@ -31,11 +31,15 @@ def env_without_wheel_links():
async def test_requirement_installed_in_venv(hass: HomeAssistant) -> None:
"""Test requirement installed in virtual environment."""
- with patch("os.path.dirname", return_value="ha_package_path"), patch(
- "homeassistant.util.package.is_virtual_env", return_value=True
- ), patch("homeassistant.util.package.is_docker_env", return_value=False), patch(
- "homeassistant.util.package.install_package", return_value=True
- ) as mock_install, patch.dict(os.environ, env_without_wheel_links(), clear=True):
+ with (
+ patch("os.path.dirname", return_value="ha_package_path"),
+ patch("homeassistant.util.package.is_virtual_env", return_value=True),
+ patch("homeassistant.util.package.is_docker_env", return_value=False),
+ patch(
+ "homeassistant.util.package.install_package", return_value=True
+ ) as mock_install,
+ patch.dict(os.environ, env_without_wheel_links(), clear=True),
+ ):
hass.config.skip_pip = False
mock_integration(hass, MockModule("comp", requirements=["package==0.0.1"]))
assert await setup.async_setup_component(hass, "comp", {})
@@ -49,11 +53,15 @@ async def test_requirement_installed_in_venv(hass: HomeAssistant) -> None:
async def test_requirement_installed_in_deps(hass: HomeAssistant) -> None:
"""Test requirement installed in deps directory."""
- with patch("os.path.dirname", return_value="ha_package_path"), patch(
- "homeassistant.util.package.is_virtual_env", return_value=False
- ), patch("homeassistant.util.package.is_docker_env", return_value=False), patch(
- "homeassistant.util.package.install_package", return_value=True
- ) as mock_install, patch.dict(os.environ, env_without_wheel_links(), clear=True):
+ with (
+ patch("os.path.dirname", return_value="ha_package_path"),
+ patch("homeassistant.util.package.is_virtual_env", return_value=False),
+ patch("homeassistant.util.package.is_docker_env", return_value=False),
+ patch(
+ "homeassistant.util.package.install_package", return_value=True
+ ) as mock_install,
+ patch.dict(os.environ, env_without_wheel_links(), clear=True),
+ ):
hass.config.skip_pip = False
mock_integration(hass, MockModule("comp", requirements=["package==0.0.1"]))
assert await setup.async_setup_component(hass, "comp", {})
@@ -75,9 +83,10 @@ async def test_install_existing_package(hass: HomeAssistant) -> None:
assert len(mock_inst.mock_calls) == 1
- with patch("homeassistant.util.package.is_installed", return_value=True), patch(
- "homeassistant.util.package.install_package"
- ) as mock_inst:
+ with (
+ patch("homeassistant.util.package.is_installed", return_value=True),
+ patch("homeassistant.util.package.install_package") as mock_inst,
+ ):
await async_process_requirements(hass, "test_component", ["hello==1.0.0"])
assert len(mock_inst.mock_calls) == 0
@@ -85,9 +94,12 @@ async def test_install_existing_package(hass: HomeAssistant) -> None:
async def test_install_missing_package(hass: HomeAssistant) -> None:
"""Test an install attempt on an existing package."""
- with patch(
- "homeassistant.util.package.install_package", return_value=False
- ) as mock_inst, pytest.raises(RequirementsNotFound):
+ with (
+ patch(
+ "homeassistant.util.package.install_package", return_value=False
+ ) as mock_inst,
+ pytest.raises(RequirementsNotFound),
+ ):
await async_process_requirements(hass, "test_component", ["hello==1.0.0"])
assert len(mock_inst.mock_calls) == 3
@@ -134,11 +146,14 @@ async def test_get_integration_with_requirements(hass: HomeAssistant) -> None:
),
)
- with patch(
- "homeassistant.util.package.is_installed", return_value=False
- ) as mock_is_installed, patch(
- "homeassistant.util.package.install_package", return_value=True
- ) as mock_inst:
+ with (
+ patch(
+ "homeassistant.util.package.is_installed", return_value=False
+ ) as mock_is_installed,
+ patch(
+ "homeassistant.util.package.install_package", return_value=True
+ ) as mock_inst,
+ ):
integration = await async_get_integration_with_requirements(
hass, "test_component"
)
@@ -195,13 +210,18 @@ async def test_get_integration_with_requirements_cache(hass: HomeAssistant) -> N
),
)
- with patch(
- "homeassistant.util.package.is_installed", return_value=False
- ) as mock_is_installed, patch(
- "homeassistant.util.package.install_package", return_value=True
- ) as mock_inst, patch(
- "homeassistant.requirements.async_get_integration", wraps=async_get_integration
- ) as mock_async_get_integration:
+ with (
+ patch(
+ "homeassistant.util.package.is_installed", return_value=False
+ ) as mock_is_installed,
+ patch(
+ "homeassistant.util.package.install_package", return_value=True
+ ) as mock_inst,
+ patch(
+ "homeassistant.requirements.async_get_integration",
+ wraps=async_get_integration,
+ ) as mock_async_get_integration,
+ ):
integration = await async_get_integration_with_requirements(
hass, "test_component"
)
@@ -323,11 +343,16 @@ async def test_get_integration_with_requirements_pip_install_fails_two_passes(
return False
# 1st pass
- with pytest.raises(RequirementsNotFound), patch(
- "homeassistant.util.package.is_installed", return_value=False
- ) as mock_is_installed, patch(
- "homeassistant.util.package.install_package", side_effect=_mock_install_package
- ) as mock_inst:
+ with (
+ pytest.raises(RequirementsNotFound),
+ patch(
+ "homeassistant.util.package.is_installed", return_value=False
+ ) as mock_is_installed,
+ patch(
+ "homeassistant.util.package.install_package",
+ side_effect=_mock_install_package,
+ ) as mock_inst,
+ ):
integration = await async_get_integration_with_requirements(
hass, "test_component"
)
@@ -353,11 +378,16 @@ async def test_get_integration_with_requirements_pip_install_fails_two_passes(
]
# 2nd pass
- with pytest.raises(RequirementsNotFound), patch(
- "homeassistant.util.package.is_installed", return_value=False
- ) as mock_is_installed, patch(
- "homeassistant.util.package.install_package", side_effect=_mock_install_package
- ) as mock_inst:
+ with (
+ pytest.raises(RequirementsNotFound),
+ patch(
+ "homeassistant.util.package.is_installed", return_value=False
+ ) as mock_is_installed,
+ patch(
+ "homeassistant.util.package.install_package",
+ side_effect=_mock_install_package,
+ ) as mock_inst,
+ ):
integration = await async_get_integration_with_requirements(
hass, "test_component"
)
@@ -371,11 +401,16 @@ async def test_get_integration_with_requirements_pip_install_fails_two_passes(
# Now clear the history and so we try again
async_clear_install_history(hass)
- with pytest.raises(RequirementsNotFound), patch(
- "homeassistant.util.package.is_installed", return_value=False
- ) as mock_is_installed, patch(
- "homeassistant.util.package.install_package", side_effect=_mock_install_package
- ) as mock_inst:
+ with (
+ pytest.raises(RequirementsNotFound),
+ patch(
+ "homeassistant.util.package.is_installed", return_value=False
+ ) as mock_is_installed,
+ patch(
+ "homeassistant.util.package.install_package",
+ side_effect=_mock_install_package,
+ ) as mock_inst,
+ ):
integration = await async_get_integration_with_requirements(
hass, "test_component"
)
@@ -401,11 +436,14 @@ async def test_get_integration_with_requirements_pip_install_fails_two_passes(
# Now clear the history and mock success
async_clear_install_history(hass)
- with patch(
- "homeassistant.util.package.is_installed", return_value=False
- ) as mock_is_installed, patch(
- "homeassistant.util.package.install_package", return_value=True
- ) as mock_inst:
+ with (
+ patch(
+ "homeassistant.util.package.is_installed", return_value=False
+ ) as mock_is_installed,
+ patch(
+ "homeassistant.util.package.install_package", return_value=True
+ ) as mock_inst,
+ ):
integration = await async_get_integration_with_requirements(
hass, "test_component"
)
@@ -497,13 +535,15 @@ async def test_install_with_wheels_index(hass: HomeAssistant) -> None:
hass.config.skip_pip = False
mock_integration(hass, MockModule("comp", requirements=["hello==1.0.0"]))
- with patch("homeassistant.util.package.is_installed", return_value=False), patch(
- "homeassistant.util.package.is_docker_env", return_value=True
- ), patch("homeassistant.util.package.install_package") as mock_inst, patch.dict(
- os.environ, {"WHEELS_LINKS": "https://wheels.hass.io/test"}
- ), patch(
- "os.path.dirname",
- ) as mock_dir:
+ with (
+ patch("homeassistant.util.package.is_installed", return_value=False),
+ patch("homeassistant.util.package.is_docker_env", return_value=True),
+ patch("homeassistant.util.package.install_package") as mock_inst,
+ patch.dict(os.environ, {"WHEELS_LINKS": "https://wheels.hass.io/test"}),
+ patch(
+ "os.path.dirname",
+ ) as mock_dir,
+ ):
mock_dir.return_value = "ha_package_path"
assert await setup.async_setup_component(hass, "comp", {})
assert "comp" in hass.config.components
@@ -520,11 +560,13 @@ async def test_install_on_docker(hass: HomeAssistant) -> None:
hass.config.skip_pip = False
mock_integration(hass, MockModule("comp", requirements=["hello==1.0.0"]))
- with patch("homeassistant.util.package.is_installed", return_value=False), patch(
- "homeassistant.util.package.is_docker_env", return_value=True
- ), patch("homeassistant.util.package.install_package") as mock_inst, patch(
- "os.path.dirname"
- ) as mock_dir, patch.dict(os.environ, env_without_wheel_links(), clear=True):
+ with (
+ patch("homeassistant.util.package.is_installed", return_value=False),
+ patch("homeassistant.util.package.is_docker_env", return_value=True),
+ patch("homeassistant.util.package.install_package") as mock_inst,
+ patch("os.path.dirname") as mock_dir,
+ patch.dict(os.environ, env_without_wheel_links(), clear=True),
+ ):
mock_dir.return_value = "ha_package_path"
assert await setup.async_setup_component(hass, "comp", {})
assert "comp" in hass.config.components
diff --git a/tests/test_runner.py b/tests/test_runner.py
index c49093bd4d6..ab9b0e31e0d 100644
--- a/tests/test_runner.py
+++ b/tests/test_runner.py
@@ -38,9 +38,11 @@ async def test_setup_and_run_hass(hass: HomeAssistant, tmpdir: py.path.local) ->
test_dir = tmpdir.mkdir("config")
default_config = runner.RuntimeConfig(test_dir)
- with patch("homeassistant.bootstrap.async_setup_hass", return_value=hass), patch(
- "threading._shutdown"
- ), patch("homeassistant.core.HomeAssistant.async_run") as mock_run:
+ with (
+ patch("homeassistant.bootstrap.async_setup_hass", return_value=hass),
+ patch("threading._shutdown"),
+ patch("homeassistant.core.HomeAssistant.async_run") as mock_run,
+ ):
await runner.setup_and_run_hass(default_config)
assert threading._shutdown == thread.deadlock_safe_shutdown
@@ -52,11 +54,12 @@ def test_run(hass: HomeAssistant, tmpdir: py.path.local) -> None:
test_dir = tmpdir.mkdir("config")
default_config = runner.RuntimeConfig(test_dir)
- with patch.object(runner, "TASK_CANCELATION_TIMEOUT", 1), patch(
- "homeassistant.bootstrap.async_setup_hass", return_value=hass
- ), patch("threading._shutdown"), patch(
- "homeassistant.core.HomeAssistant.async_run"
- ) as mock_run:
+ with (
+ patch.object(runner, "TASK_CANCELATION_TIMEOUT", 1),
+ patch("homeassistant.bootstrap.async_setup_hass", return_value=hass),
+ patch("threading._shutdown"),
+ patch("homeassistant.core.HomeAssistant.async_run") as mock_run,
+ ):
runner.run(default_config)
assert mock_run.called
@@ -69,16 +72,19 @@ def test_run_executor_shutdown_throws(
test_dir = tmpdir.mkdir("config")
default_config = runner.RuntimeConfig(test_dir)
- with patch.object(runner, "TASK_CANCELATION_TIMEOUT", 1), pytest.raises(
- RuntimeError
- ), patch("homeassistant.bootstrap.async_setup_hass", return_value=hass), patch(
- "threading._shutdown"
- ), patch(
- "homeassistant.runner.InterruptibleThreadPoolExecutor.shutdown",
- side_effect=RuntimeError,
- ) as mock_shutdown, patch(
- "homeassistant.core.HomeAssistant.async_run",
- ) as mock_run:
+ with (
+ patch.object(runner, "TASK_CANCELATION_TIMEOUT", 1),
+ pytest.raises(RuntimeError),
+ patch("homeassistant.bootstrap.async_setup_hass", return_value=hass),
+ patch("threading._shutdown"),
+ patch(
+ "homeassistant.runner.InterruptibleThreadPoolExecutor.shutdown",
+ side_effect=RuntimeError,
+ ) as mock_shutdown,
+ patch(
+ "homeassistant.core.HomeAssistant.async_run",
+ ) as mock_run,
+ ):
runner.run(default_config)
assert mock_shutdown.called
@@ -112,10 +118,11 @@ def test_run_does_not_block_forever_with_shielded_task(
await asyncio.sleep(0.1)
return 0
- with patch.object(runner, "TASK_CANCELATION_TIMEOUT", 1), patch(
- "homeassistant.bootstrap.async_setup_hass", return_value=hass
- ), patch("threading._shutdown"), patch(
- "homeassistant.core.HomeAssistant.async_run", _async_create_tasks
+ with (
+ patch.object(runner, "TASK_CANCELATION_TIMEOUT", 1),
+ patch("homeassistant.bootstrap.async_setup_hass", return_value=hass),
+ patch("threading._shutdown"),
+ patch("homeassistant.core.HomeAssistant.async_run", _async_create_tasks),
):
runner.run(default_config)
@@ -159,14 +166,22 @@ def test__enable_posix_spawn() -> None:
def _mock_sys_tags_musl() -> Iterator[packaging.tags.Tag]:
yield from packaging.tags.parse_tag("cp311-cp311-musllinux_1_1_x86_64")
- with patch.object(runner.subprocess, "_USE_POSIX_SPAWN", False), patch(
- "homeassistant.runner.packaging.tags.sys_tags", side_effect=_mock_sys_tags_musl
+ with (
+ patch.object(runner.subprocess, "_USE_POSIX_SPAWN", False),
+ patch(
+ "homeassistant.runner.packaging.tags.sys_tags",
+ side_effect=_mock_sys_tags_musl,
+ ),
):
runner._enable_posix_spawn()
assert runner.subprocess._USE_POSIX_SPAWN is True
- with patch.object(runner.subprocess, "_USE_POSIX_SPAWN", False), patch(
- "homeassistant.runner.packaging.tags.sys_tags", side_effect=_mock_sys_tags_any
+ with (
+ patch.object(runner.subprocess, "_USE_POSIX_SPAWN", False),
+ patch(
+ "homeassistant.runner.packaging.tags.sys_tags",
+ side_effect=_mock_sys_tags_any,
+ ),
):
runner._enable_posix_spawn()
assert runner.subprocess._USE_POSIX_SPAWN is False
diff --git a/tests/test_setup.py b/tests/test_setup.py
index 387ac19c5d0..e3d9a322862 100644
--- a/tests/test_setup.py
+++ b/tests/test_setup.py
@@ -394,9 +394,10 @@ async def test_platform_specific_config_validation(hass: HomeAssistant) -> None:
MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup),
)
- with assert_setup_component(0, "switch"), patch(
- "homeassistant.setup.async_notify_setup_error"
- ) as mock_notify:
+ with (
+ assert_setup_component(0, "switch"),
+ patch("homeassistant.setup.async_notify_setup_error") as mock_notify,
+ ):
assert await setup.async_setup_component(
hass,
"switch",
@@ -409,9 +410,10 @@ async def test_platform_specific_config_validation(hass: HomeAssistant) -> None:
hass.data.pop(setup.DATA_SETUP)
hass.config.components.remove("switch")
- with assert_setup_component(0), patch(
- "homeassistant.setup.async_notify_setup_error"
- ) as mock_notify:
+ with (
+ assert_setup_component(0),
+ patch("homeassistant.setup.async_notify_setup_error") as mock_notify,
+ ):
assert await setup.async_setup_component(
hass,
"switch",
@@ -430,9 +432,10 @@ async def test_platform_specific_config_validation(hass: HomeAssistant) -> None:
hass.data.pop(setup.DATA_SETUP)
hass.config.components.remove("switch")
- with assert_setup_component(1, "switch"), patch(
- "homeassistant.setup.async_notify_setup_error"
- ) as mock_notify:
+ with (
+ assert_setup_component(1, "switch"),
+ patch("homeassistant.setup.async_notify_setup_error") as mock_notify,
+ ):
assert await setup.async_setup_component(
hass,
"switch",
diff --git a/tests/testing_config/custom_components/test/number.py b/tests/testing_config/custom_components/test/number.py
index aa4d6fdcd8f..4de3dce233a 100644
--- a/tests/testing_config/custom_components/test/number.py
+++ b/tests/testing_config/custom_components/test/number.py
@@ -56,9 +56,9 @@ class MockRestoreNumber(MockNumberEntity, RestoreNumber):
self._values["native_max_value"] = last_number_data.native_max_value
self._values["native_min_value"] = last_number_data.native_min_value
self._values["native_step"] = last_number_data.native_step
- self._values[
- "native_unit_of_measurement"
- ] = last_number_data.native_unit_of_measurement
+ self._values["native_unit_of_measurement"] = (
+ last_number_data.native_unit_of_measurement
+ )
self._values["native_value"] = last_number_data.native_value
diff --git a/tests/testing_config/custom_components/test/sensor.py b/tests/testing_config/custom_components/test/sensor.py
index b6040227574..9ebf16b9dcd 100644
--- a/tests/testing_config/custom_components/test/sensor.py
+++ b/tests/testing_config/custom_components/test/sensor.py
@@ -138,6 +138,6 @@ class MockRestoreSensor(MockSensor, RestoreSensor):
if (last_sensor_data := await self.async_get_last_sensor_data()) is None:
return
self._values["native_value"] = last_sensor_data.native_value
- self._values[
- "native_unit_of_measurement"
- ] = last_sensor_data.native_unit_of_measurement
+ self._values["native_unit_of_measurement"] = (
+ last_sensor_data.native_unit_of_measurement
+ )
diff --git a/tests/util/test_async.py b/tests/util/test_async.py
index fc0032204d7..1029d670703 100644
--- a/tests/util/test_async.py
+++ b/tests/util/test_async.py
@@ -51,28 +51,33 @@ async def test_check_loop_async() -> None:
async def test_check_loop_async_integration(caplog: pytest.LogCaptureFixture) -> None:
"""Test check_loop detects and raises when called from event loop from integration context."""
- with pytest.raises(RuntimeError), patch(
- "homeassistant.helpers.frame.linecache.getline", return_value="self.light.is_on"
- ), patch(
- "homeassistant.helpers.frame.get_current_frame",
- return_value=extract_stack_to_frame(
- [
- Mock(
- filename="/home/paulus/homeassistant/core.py",
- lineno="23",
- line="do_something()",
- ),
- Mock(
- filename="/home/paulus/homeassistant/components/hue/light.py",
- lineno="23",
- line="self.light.is_on",
- ),
- Mock(
- filename="/home/paulus/aiohue/lights.py",
- lineno="2",
- line="something()",
- ),
- ]
+ with (
+ pytest.raises(RuntimeError),
+ patch(
+ "homeassistant.helpers.frame.linecache.getline",
+ return_value="self.light.is_on",
+ ),
+ patch(
+ "homeassistant.helpers.frame.get_current_frame",
+ return_value=extract_stack_to_frame(
+ [
+ Mock(
+ filename="/home/paulus/homeassistant/core.py",
+ lineno="23",
+ line="do_something()",
+ ),
+ Mock(
+ filename="/home/paulus/homeassistant/components/hue/light.py",
+ lineno="23",
+ line="self.light.is_on",
+ ),
+ Mock(
+ filename="/home/paulus/aiohue/lights.py",
+ lineno="2",
+ line="something()",
+ ),
+ ]
+ ),
),
):
hasync.check_loop(banned_function)
@@ -88,28 +93,32 @@ async def test_check_loop_async_integration_non_strict(
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test check_loop detects when called from event loop from integration context."""
- with patch(
- "homeassistant.helpers.frame.linecache.getline", return_value="self.light.is_on"
- ), patch(
- "homeassistant.helpers.frame.get_current_frame",
- return_value=extract_stack_to_frame(
- [
- Mock(
- filename="/home/paulus/homeassistant/core.py",
- lineno="23",
- line="do_something()",
- ),
- Mock(
- filename="/home/paulus/homeassistant/components/hue/light.py",
- lineno="23",
- line="self.light.is_on",
- ),
- Mock(
- filename="/home/paulus/aiohue/lights.py",
- lineno="2",
- line="something()",
- ),
- ]
+ with (
+ patch(
+ "homeassistant.helpers.frame.linecache.getline",
+ return_value="self.light.is_on",
+ ),
+ patch(
+ "homeassistant.helpers.frame.get_current_frame",
+ return_value=extract_stack_to_frame(
+ [
+ Mock(
+ filename="/home/paulus/homeassistant/core.py",
+ lineno="23",
+ line="do_something()",
+ ),
+ Mock(
+ filename="/home/paulus/homeassistant/components/hue/light.py",
+ lineno="23",
+ line="self.light.is_on",
+ ),
+ Mock(
+ filename="/home/paulus/aiohue/lights.py",
+ lineno="2",
+ line="something()",
+ ),
+ ]
+ ),
),
):
hasync.check_loop(banned_function, strict=False)
@@ -123,28 +132,33 @@ async def test_check_loop_async_integration_non_strict(
async def test_check_loop_async_custom(caplog: pytest.LogCaptureFixture) -> None:
"""Test check_loop detects when called from event loop with custom component context."""
- with pytest.raises(RuntimeError), patch(
- "homeassistant.helpers.frame.linecache.getline", return_value="self.light.is_on"
- ), patch(
- "homeassistant.helpers.frame.get_current_frame",
- return_value=extract_stack_to_frame(
- [
- Mock(
- filename="/home/paulus/homeassistant/core.py",
- lineno="23",
- line="do_something()",
- ),
- Mock(
- filename="/home/paulus/config/custom_components/hue/light.py",
- lineno="23",
- line="self.light.is_on",
- ),
- Mock(
- filename="/home/paulus/aiohue/lights.py",
- lineno="2",
- line="something()",
- ),
- ]
+ with (
+ pytest.raises(RuntimeError),
+ patch(
+ "homeassistant.helpers.frame.linecache.getline",
+ return_value="self.light.is_on",
+ ),
+ patch(
+ "homeassistant.helpers.frame.get_current_frame",
+ return_value=extract_stack_to_frame(
+ [
+ Mock(
+ filename="/home/paulus/homeassistant/core.py",
+ lineno="23",
+ line="do_something()",
+ ),
+ Mock(
+ filename="/home/paulus/config/custom_components/hue/light.py",
+ lineno="23",
+ line="self.light.is_on",
+ ),
+ Mock(
+ filename="/home/paulus/aiohue/lights.py",
+ lineno="2",
+ line="something()",
+ ),
+ ]
+ ),
),
):
hasync.check_loop(banned_function)
@@ -248,9 +262,10 @@ async def test_callback_is_always_scheduled(hass: HomeAssistant) -> None:
callback = MagicMock()
hasync.shutdown_run_callback_threadsafe(hass.loop)
- with patch.object(
- hass.loop, "call_soon_threadsafe"
- ) as mock_call_soon_threadsafe, 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()
diff --git a/tests/util/test_file.py b/tests/util/test_file.py
index 64c74b73dc3..2371998b1b9 100644
--- a/tests/util/test_file.py
+++ b/tests/util/test_file.py
@@ -37,8 +37,11 @@ def test_write_utf8_file_fails_at_creation(tmpdir: py.path.local) -> None:
test_dir = tmpdir.mkdir("files")
test_file = Path(test_dir / "test.json")
- with pytest.raises(WriteError), patch(
- "homeassistant.util.file.tempfile.NamedTemporaryFile", side_effect=OSError
+ with (
+ pytest.raises(WriteError),
+ patch(
+ "homeassistant.util.file.tempfile.NamedTemporaryFile", side_effect=OSError
+ ),
):
write_utf8_file(test_file, '{"some":"data"}', False)
@@ -52,8 +55,9 @@ def test_write_utf8_file_fails_at_rename(
test_dir = tmpdir.mkdir("files")
test_file = Path(test_dir / "test.json")
- with pytest.raises(WriteError), patch(
- "homeassistant.util.file.os.replace", side_effect=OSError
+ with (
+ pytest.raises(WriteError),
+ patch("homeassistant.util.file.os.replace", side_effect=OSError),
):
write_utf8_file(test_file, '{"some":"data"}', False)
@@ -69,9 +73,11 @@ def test_write_utf8_file_fails_at_rename_and_remove(
test_dir = tmpdir.mkdir("files")
test_file = Path(test_dir / "test.json")
- with pytest.raises(WriteError), patch(
- "homeassistant.util.file.os.remove", side_effect=OSError
- ), patch("homeassistant.util.file.os.replace", side_effect=OSError):
+ with (
+ pytest.raises(WriteError),
+ patch("homeassistant.util.file.os.remove", side_effect=OSError),
+ patch("homeassistant.util.file.os.replace", side_effect=OSError),
+ ):
write_utf8_file(test_file, '{"some":"data"}', False)
assert "File replacement cleanup failed" in caplog.text
@@ -82,8 +88,9 @@ def test_write_utf8_file_atomic_fails(tmpdir: py.path.local) -> None:
test_dir = tmpdir.mkdir("files")
test_file = Path(test_dir / "test.json")
- with pytest.raises(WriteError), patch(
- "homeassistant.util.file.AtomicWriter.open", side_effect=OSError
+ with (
+ pytest.raises(WriteError),
+ patch("homeassistant.util.file.AtomicWriter.open", side_effect=OSError),
):
write_utf8_file_atomic(test_file, '{"some":"data"}', False)
diff --git a/tests/util/test_logging.py b/tests/util/test_logging.py
index 2473485e103..53342e8d1bd 100644
--- a/tests/util/test_logging.py
+++ b/tests/util/test_logging.py
@@ -27,8 +27,9 @@ async def test_logging_with_queue_handler() -> None:
handler.emit(log_record)
- with pytest.raises(asyncio.CancelledError), patch.object(
- handler, "enqueue", side_effect=asyncio.CancelledError
+ with (
+ pytest.raises(asyncio.CancelledError),
+ patch.object(handler, "enqueue", side_effect=asyncio.CancelledError),
):
handler.emit(log_record)
@@ -36,16 +37,18 @@ async def test_logging_with_queue_handler() -> None:
handler.handle(log_record)
emit_mock.assert_called_once()
- with patch.object(handler, "filter") as filter_mock, patch.object(
- handler, "emit"
- ) as emit_mock:
+ with (
+ patch.object(handler, "filter") as filter_mock,
+ patch.object(handler, "emit") as emit_mock,
+ ):
filter_mock.return_value = False
handler.handle(log_record)
emit_mock.assert_not_called()
- with patch.object(handler, "enqueue", side_effect=OSError), patch.object(
- handler, "handleError"
- ) as mock_handle_error:
+ with (
+ patch.object(handler, "enqueue", side_effect=OSError),
+ patch.object(handler, "handleError") as mock_handle_error,
+ ):
handler.emit(log_record)
mock_handle_error.assert_called_once()
diff --git a/tests/util/test_timeout.py b/tests/util/test_timeout.py
index 02a06632ff6..d49008d608b 100644
--- a/tests/util/test_timeout.py
+++ b/tests/util/test_timeout.py
@@ -46,8 +46,9 @@ async def test_simple_zone_timeout_freeze_inside_executor_job(
with timeout.freeze("recorder"):
time.sleep(0.3)
- async with timeout.async_timeout(1.0), timeout.async_timeout(
- 0.2, zone_name="recorder"
+ async with (
+ timeout.async_timeout(1.0),
+ timeout.async_timeout(0.2, zone_name="recorder"),
):
await hass.async_add_executor_job(_some_sync_work)
@@ -76,8 +77,9 @@ async def test_mix_global_timeout_freeze_and_zone_freeze_inside_executor_job(
with timeout.freeze("recorder"):
time.sleep(0.3)
- async with timeout.async_timeout(0.1), timeout.async_timeout(
- 0.2, zone_name="recorder"
+ async with (
+ timeout.async_timeout(0.1),
+ timeout.async_timeout(0.2, zone_name="recorder"),
):
await hass.async_add_executor_job(_some_sync_work)
@@ -110,9 +112,10 @@ async def test_mix_global_timeout_freeze_and_zone_freeze_other_zone_inside_execu
with pytest.raises(TimeoutError):
async with timeout.async_timeout(0.1):
- async with timeout.async_timeout(
- 0.2, zone_name="recorder"
- ), timeout.async_timeout(0.2, zone_name="not_recorder"):
+ async with (
+ timeout.async_timeout(0.2, zone_name="recorder"),
+ timeout.async_timeout(0.2, zone_name="not_recorder"),
+ ):
await hass.async_add_executor_job(_some_sync_work)
@@ -214,9 +217,11 @@ async def test_mix_zone_timeout_freeze_and_global_freeze() -> None:
"""Test a mix zone timeout freeze and global freeze."""
timeout = TimeoutManager()
- async with timeout.async_timeout(0.2, "test"), timeout.async_freeze(
- "test"
- ), timeout.async_freeze():
+ async with (
+ timeout.async_timeout(0.2, "test"),
+ timeout.async_freeze("test"),
+ timeout.async_freeze(),
+ ):
await asyncio.sleep(0.3)
@@ -224,9 +229,11 @@ async def test_mix_global_and_zone_timeout_freeze_() -> None:
"""Test a mix zone timeout freeze and global freeze."""
timeout = TimeoutManager()
- async with timeout.async_timeout(
- 0.2, "test"
- ), timeout.async_freeze(), timeout.async_freeze("test"):
+ async with (
+ timeout.async_timeout(0.2, "test"),
+ timeout.async_freeze(),
+ timeout.async_freeze("test"),
+ ):
await asyncio.sleep(0.3)
diff --git a/tests/util/yaml/test_init.py b/tests/util/yaml/test_init.py
index 185c4cdb22c..dba8e9b8017 100644
--- a/tests/util/yaml/test_init.py
+++ b/tests/util/yaml/test_init.py
@@ -517,9 +517,9 @@ class TestSecrets(unittest.TestCase):
def test_secrets_are_not_dict(self):
"""Did secrets handle non-dict file."""
- FILES[
- self._secret_path
- ] = "- http_pw: pwhttp\n comp1_un: un1\n comp1_pw: pw1\n"
+ FILES[self._secret_path] = (
+ "- http_pw: pwhttp\n comp1_un: un1\n comp1_pw: pw1\n"
+ )
with pytest.raises(HomeAssistantError):
load_yaml(
self._yaml_path,
@@ -611,24 +611,28 @@ def mock_integration_frame() -> Generator[Mock, None, None]:
lineno="23",
line="self.light.is_on",
)
- with patch(
- "homeassistant.helpers.frame.linecache.getline", return_value=correct_frame.line
- ), patch(
- "homeassistant.helpers.frame.get_current_frame",
- return_value=extract_stack_to_frame(
- [
- Mock(
- filename="/home/paulus/homeassistant/core.py",
- lineno="23",
- line="do_something()",
- ),
- correct_frame,
- Mock(
- filename="/home/paulus/aiohue/lights.py",
- lineno="2",
- line="something()",
- ),
- ]
+ with (
+ patch(
+ "homeassistant.helpers.frame.linecache.getline",
+ return_value=correct_frame.line,
+ ),
+ patch(
+ "homeassistant.helpers.frame.get_current_frame",
+ return_value=extract_stack_to_frame(
+ [
+ Mock(
+ filename="/home/paulus/homeassistant/core.py",
+ lineno="23",
+ line="do_something()",
+ ),
+ correct_frame,
+ Mock(
+ filename="/home/paulus/aiohue/lights.py",
+ lineno="2",
+ line="something()",
+ ),
+ ]
+ ),
),
):
yield correct_frame
@@ -652,8 +656,9 @@ async def test_deprecated_loaders(
message: str,
) -> None:
"""Test instantiating the deprecated yaml loaders logs a warning."""
- with pytest.raises(TypeError), patch(
- "homeassistant.helpers.frame._REPORTED_INTEGRATIONS", set()
+ with (
+ pytest.raises(TypeError),
+ patch("homeassistant.helpers.frame._REPORTED_INTEGRATIONS", set()),
):
loader_class()
assert (f"Detected that integration 'hue' uses deprecated {message}") in caplog.text