Improve lists in integrations [V-W] (#113252)

This commit is contained in:
Joost Lekkerkerker 2024-03-13 19:38:04 +01:00 committed by GitHub
parent 41215aa954
commit 49fc59548a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
23 changed files with 126 additions and 163 deletions

View file

@ -65,10 +65,8 @@ def setup_platform(
) -> None: ) -> None:
"""Set up the departure sensor.""" """Set up the departure sensor."""
planner = vasttrafik.JournyPlanner(config.get(CONF_KEY), config.get(CONF_SECRET)) planner = vasttrafik.JournyPlanner(config.get(CONF_KEY), config.get(CONF_SECRET))
sensors = [] add_entities(
(
for departure in config[CONF_DEPARTURES]:
sensors.append(
VasttrafikDepartureSensor( VasttrafikDepartureSensor(
planner, planner,
departure.get(CONF_NAME), departure.get(CONF_NAME),
@ -77,8 +75,10 @@ def setup_platform(
departure.get(CONF_LINES), departure.get(CONF_LINES),
departure.get(CONF_DELAY), departure.get(CONF_DELAY),
) )
) for departure in config[CONF_DEPARTURES]
add_entities(sensors, True) ),
True,
)
class VasttrafikDepartureSensor(SensorEntity): class VasttrafikDepartureSensor(SensorEntity):

View file

@ -38,11 +38,10 @@ async def async_setup_entry(
"""Set up Velbus switch based on config_entry.""" """Set up Velbus switch based on config_entry."""
await hass.data[DOMAIN][entry.entry_id]["tsk"] await hass.data[DOMAIN][entry.entry_id]["tsk"]
cntrl = hass.data[DOMAIN][entry.entry_id]["cntrl"] cntrl = hass.data[DOMAIN][entry.entry_id]["cntrl"]
entities: list[Entity] = [] entities: list[Entity] = [
for channel in cntrl.get_all("light"): VelbusLight(channel) for channel in cntrl.get_all("light")
entities.append(VelbusLight(channel)) ]
for channel in cntrl.get_all("led"): entities.extend(VelbusButtonLight(channel) for channel in cntrl.get_all("led"))
entities.append(VelbusButtonLight(channel))
async_add_entities(entities) async_add_entities(entities)

View file

@ -21,10 +21,7 @@ async def async_setup_entry(
"""Set up Velbus switch based on config_entry.""" """Set up Velbus switch based on config_entry."""
await hass.data[DOMAIN][entry.entry_id]["tsk"] await hass.data[DOMAIN][entry.entry_id]["tsk"]
cntrl = hass.data[DOMAIN][entry.entry_id]["cntrl"] cntrl = hass.data[DOMAIN][entry.entry_id]["cntrl"]
entities = [] async_add_entities(VelbusSwitch(channel) for channel in cntrl.get_all("switch"))
for channel in cntrl.get_all("switch"):
entities.append(VelbusSwitch(channel))
async_add_entities(entities)
class VelbusSwitch(VelbusEntity, SwitchEntity): class VelbusSwitch(VelbusEntity, SwitchEntity):

View file

@ -27,12 +27,12 @@ async def async_setup_entry(
hass: HomeAssistant, config: ConfigEntry, async_add_entities: AddEntitiesCallback hass: HomeAssistant, config: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None: ) -> None:
"""Set up cover(s) for Velux platform.""" """Set up cover(s) for Velux platform."""
entities = []
module = hass.data[DOMAIN][config.entry_id] module = hass.data[DOMAIN][config.entry_id]
for node in module.pyvlx.nodes: async_add_entities(
if isinstance(node, OpeningDevice): VeluxCover(node)
entities.append(VeluxCover(node)) for node in module.pyvlx.nodes
async_add_entities(entities) if isinstance(node, OpeningDevice)
)
class VeluxCover(VeluxEntity, CoverEntity): class VeluxCover(VeluxEntity, CoverEntity):

View file

@ -96,13 +96,11 @@ async def async_setup_entry(
) )
runtimes = coordinator.runtimes[-1] runtimes = coordinator.runtimes[-1]
for sensor_name in runtimes: entities.extend(
if sensor_name in RUNTIME_DEVICES: VenstarSensor(coordinator, config_entry, RUNTIME_ENTITY, sensor_name)
entities.append( for sensor_name in runtimes
VenstarSensor( if sensor_name in RUNTIME_DEVICES
coordinator, config_entry, RUNTIME_ENTITY, sensor_name )
)
)
for description in INFO_ENTITIES: for description in INFO_ENTITIES:
try: try:

View file

@ -129,14 +129,10 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
if device_type is not None: if device_type is not None:
vera_devices[device_type].append(device) vera_devices[device_type].append(device)
vera_scenes = []
for scene in all_scenes:
vera_scenes.append(scene)
controller_data = ControllerData( controller_data = ControllerData(
controller=controller, controller=controller,
devices=vera_devices, devices=vera_devices,
scenes=vera_scenes, scenes=all_scenes,
config_entry=entry, config_entry=entry,
) )

View file

@ -27,9 +27,7 @@ class ControllerData(NamedTuple):
def get_configured_platforms(controller_data: ControllerData) -> set[Platform]: def get_configured_platforms(controller_data: ControllerData) -> set[Platform]:
"""Get configured platforms for a controller.""" """Get configured platforms for a controller."""
platforms: list[Platform] = [] platforms: list[Platform] = list(controller_data.devices)
for platform in controller_data.devices:
platforms.append(platform)
if controller_data.scenes: if controller_data.scenes:
platforms.append(Platform.SCENE) platforms.append(Platform.SCENE)

View file

@ -194,12 +194,15 @@ async def async_setup_entry(
@callback @callback
def _setup_entities(devices, async_add_entities): def _setup_entities(devices, async_add_entities):
"""Check if device is online and add entity.""" """Check if device is online and add entity."""
entities = [] async_add_entities(
for dev in devices: (
for description in SENSORS: VeSyncSensorEntity(dev, description)
if description.exists_fn(dev): for dev in devices
entities.append(VeSyncSensorEntity(dev, description)) for description in SENSORS
async_add_entities(entities, update_before_add=True) if description.exists_fn(dev)
),
update_before_add=True,
)
class VeSyncSensorEntity(VeSyncBaseEntity, SensorEntity): class VeSyncSensorEntity(VeSyncBaseEntity, SensorEntity):

View file

@ -19,12 +19,15 @@ async def async_get_config_entry_diagnostics(
hass: HomeAssistant, entry: ConfigEntry hass: HomeAssistant, entry: ConfigEntry
) -> dict[str, Any]: ) -> dict[str, Any]:
"""Return diagnostics for a config entry.""" """Return diagnostics for a config entry."""
data = []
for device in hass.data[DOMAIN][entry.entry_id][DEVICE_LIST]: def dump_devices() -> list[dict[str, Any]]:
data.append( """Dump devices."""
json.loads(await hass.async_add_executor_job(device.config.dump_secure)) return [
) json.loads(device.config.dump_secure())
for device in hass.data[DOMAIN][entry.entry_id][DEVICE_LIST]
]
return { return {
"entry": async_redact_data(entry.as_dict(), TO_REDACT), "entry": async_redact_data(entry.as_dict(), TO_REDACT),
"data": data, "data": await hass.async_add_executor_job(dump_devices),
} }

View file

@ -32,21 +32,17 @@ async def async_setup_entry(
@callback @callback
def async_discover_device(instruments: list[Instrument]) -> None: def async_discover_device(instruments: list[Instrument]) -> None:
"""Discover and add a discovered Volvo On Call binary sensor.""" """Discover and add a discovered Volvo On Call binary sensor."""
entities: list[VolvoSensor] = [] async_add_entities(
VolvoSensor(
for instrument in instruments: coordinator,
if instrument.component == "binary_sensor": instrument.vehicle.vin,
entities.append( instrument.component,
VolvoSensor( instrument.attr,
coordinator, instrument.slug_attr,
instrument.vehicle.vin, )
instrument.component, for instrument in instruments
instrument.attr, if instrument.component == "binary_sensor"
instrument.slug_attr, )
)
)
async_add_entities(entities)
async_discover_device([*volvo_data.instruments]) async_discover_device([*volvo_data.instruments])

View file

@ -26,21 +26,17 @@ async def async_setup_entry(
@callback @callback
def async_discover_device(instruments: list[Instrument]) -> None: def async_discover_device(instruments: list[Instrument]) -> None:
"""Discover and add a discovered Volvo On Call device tracker.""" """Discover and add a discovered Volvo On Call device tracker."""
entities: list[VolvoTrackerEntity] = [] async_add_entities(
VolvoTrackerEntity(
for instrument in instruments: instrument.vehicle.vin,
if instrument.component == "device_tracker": instrument.component,
entities.append( instrument.attr,
VolvoTrackerEntity( instrument.slug_attr,
instrument.vehicle.vin, coordinator,
instrument.component, )
instrument.attr, for instrument in instruments
instrument.slug_attr, if instrument.component == "device_tracker"
coordinator, )
)
)
async_add_entities(entities)
async_discover_device([*volvo_data.instruments]) async_discover_device([*volvo_data.instruments])

View file

@ -28,21 +28,17 @@ async def async_setup_entry(
@callback @callback
def async_discover_device(instruments: list[Instrument]) -> None: def async_discover_device(instruments: list[Instrument]) -> None:
"""Discover and add a discovered Volvo On Call lock.""" """Discover and add a discovered Volvo On Call lock."""
entities: list[VolvoLock] = [] async_add_entities(
VolvoLock(
for instrument in instruments: coordinator,
if instrument.component == "lock": instrument.vehicle.vin,
entities.append( instrument.component,
VolvoLock( instrument.attr,
coordinator, instrument.slug_attr,
instrument.vehicle.vin, )
instrument.component, for instrument in instruments
instrument.attr, if instrument.component == "lock"
instrument.slug_attr, )
)
)
async_add_entities(entities)
async_discover_device([*volvo_data.instruments]) async_discover_device([*volvo_data.instruments])

View file

@ -26,21 +26,17 @@ async def async_setup_entry(
@callback @callback
def async_discover_device(instruments: list[Instrument]) -> None: def async_discover_device(instruments: list[Instrument]) -> None:
"""Discover and add a discovered Volvo On Call sensor.""" """Discover and add a discovered Volvo On Call sensor."""
entities: list[VolvoSensor] = [] async_add_entities(
VolvoSensor(
for instrument in instruments: coordinator,
if instrument.component == "sensor": instrument.vehicle.vin,
entities.append( instrument.component,
VolvoSensor( instrument.attr,
coordinator, instrument.slug_attr,
instrument.vehicle.vin, )
instrument.component, for instrument in instruments
instrument.attr, if instrument.component == "sensor"
instrument.slug_attr, )
)
)
async_add_entities(entities)
async_discover_device([*volvo_data.instruments]) async_discover_device([*volvo_data.instruments])

View file

@ -28,21 +28,17 @@ async def async_setup_entry(
@callback @callback
def async_discover_device(instruments: list[Instrument]) -> None: def async_discover_device(instruments: list[Instrument]) -> None:
"""Discover and add a discovered Volvo On Call switch.""" """Discover and add a discovered Volvo On Call switch."""
entities: list[VolvoSwitch] = [] async_add_entities(
VolvoSwitch(
for instrument in instruments: coordinator,
if instrument.component == "switch": instrument.vehicle.vin,
entities.append( instrument.component,
VolvoSwitch( instrument.attr,
coordinator, instrument.slug_attr,
instrument.vehicle.vin, )
instrument.component, for instrument in instruments
instrument.attr, if instrument.component == "switch"
instrument.slug_attr, )
)
)
async_add_entities(entities)
async_discover_device([*volvo_data.instruments]) async_discover_device([*volvo_data.instruments])

View file

@ -190,9 +190,7 @@ class VulcanFlowHandler(ConfigFlow, domain=DOMAIN):
async def async_step_add_next_config_entry(self, user_input=None): async def async_step_add_next_config_entry(self, user_input=None):
"""Flow initialized when user is adding next entry of that integration.""" """Flow initialized when user is adding next entry of that integration."""
existing_entries = [] existing_entries = self.hass.config_entries.async_entries(DOMAIN)
for entry in self.hass.config_entries.async_entries(DOMAIN):
existing_entries.append(entry)
errors = {} errors = {}
@ -205,13 +203,14 @@ class VulcanFlowHandler(ConfigFlow, domain=DOMAIN):
account = Account.load(existing_entries[0].data["account"]) account = Account.load(existing_entries[0].data["account"])
client = Vulcan(keystore, account, async_get_clientsession(self.hass)) client = Vulcan(keystore, account, async_get_clientsession(self.hass))
students = await client.get_students() students = await client.get_students()
new_students = [] existing_entry_ids = [
existing_entry_ids = [] entry.data["student_id"] for entry in existing_entries
for entry in self.hass.config_entries.async_entries(DOMAIN): ]
existing_entry_ids.append(entry.data["student_id"]) new_students = [
for student in students: student
if str(student.pupil.id) not in existing_entry_ids: for student in students
new_students.append(student) if str(student.pupil.id) not in existing_entry_ids
]
if not new_students: if not new_students:
return self.async_abort(reason="all_student_already_configured") return self.async_abort(reason="all_student_already_configured")
if len(new_students) == 1: if len(new_students) == 1:
@ -277,9 +276,7 @@ class VulcanFlowHandler(ConfigFlow, domain=DOMAIN):
keystore = credentials["keystore"] keystore = credentials["keystore"]
client = Vulcan(keystore, account, async_get_clientsession(self.hass)) client = Vulcan(keystore, account, async_get_clientsession(self.hass))
students = await client.get_students() students = await client.get_students()
existing_entries = [] existing_entries = self.hass.config_entries.async_entries(DOMAIN)
for entry in self.hass.config_entries.async_entries(DOMAIN):
existing_entries.append(entry)
matching_entries = False matching_entries = False
for student in students: for student in students:
for entry in existing_entries: for entry in existing_entries:

View file

@ -104,12 +104,9 @@ def setup_platform(
if discovery_info is None: if discovery_info is None:
return return
sensors = []
client = hass.data[WF_DOMAIN] client = hass.data[WF_DOMAIN]
for description in SENSORS:
sensors.append(WaterFurnaceSensor(client, description))
add_entities(sensors) add_entities(WaterFurnaceSensor(client, description) for description in SENSORS)
class WaterFurnaceSensor(SensorEntity): class WaterFurnaceSensor(SensorEntity):

View file

@ -140,7 +140,8 @@ def async_update_segments(
# Process new segments, add them to Home Assistant # Process new segments, add them to Home Assistant
for segment_id in segment_ids - current_ids: for segment_id in segment_ids - current_ids:
current_ids.add(segment_id) current_ids.add(segment_id)
for desc in NUMBERS: new_entities.extend(
new_entities.append(WLEDNumber(coordinator, segment_id, desc)) WLEDNumber(coordinator, segment_id, desc) for desc in NUMBERS
)
async_add_entities(new_entities) async_add_entities(new_entities)

View file

@ -66,9 +66,7 @@ def add_province_and_language_to_schema(
_country = country_holidays(country=country) _country = country_holidays(country=country)
if country_default_language := (_country.default_language): if country_default_language := (_country.default_language):
selectable_languages = _country.supported_languages selectable_languages = _country.supported_languages
new_selectable_languages = [] new_selectable_languages = [lang[:2] for lang in selectable_languages]
for lang in selectable_languages:
new_selectable_languages.append(lang[:2])
language_schema = { language_schema = {
vol.Optional( vol.Optional(
CONF_LANGUAGE, default=country_default_language CONF_LANGUAGE, default=country_default_language

View file

@ -47,14 +47,13 @@ async def async_init_integration(
skip_setup: bool = False, skip_setup: bool = False,
): ):
"""Set up the venstar integration in Home Assistant.""" """Set up the venstar integration in Home Assistant."""
platform_config = [] platform_config = [
for model in TEST_MODELS: {
platform_config.append( CONF_PLATFORM: "venstar",
{ CONF_HOST: f"venstar-{model}.localdomain",
CONF_PLATFORM: "venstar", }
CONF_HOST: f"venstar-{model}.localdomain", for model in TEST_MODELS
} ]
)
config = {DOMAIN: platform_config} config = {DOMAIN: platform_config}
await async_setup_component(hass, DOMAIN, config) await async_setup_component(hass, DOMAIN, config)

View file

@ -49,10 +49,11 @@ def mock_devices_response(
requests_mock: requests_mock.Mocker, device_name: str requests_mock: requests_mock.Mocker, device_name: str
) -> None: ) -> None:
"""Build a response for the Helpers.call_api method.""" """Build a response for the Helpers.call_api method."""
device_list = [] device_list = [
for device in ALL_DEVICES["result"]["list"]: device
if device["deviceName"] == device_name: for device in ALL_DEVICES["result"]["list"]
device_list.append(device) if device["deviceName"] == device_name
]
requests_mock.post( requests_mock.post(
"https://smartapi.vesync.com/cloud/v1/deviceManaged/devices", "https://smartapi.vesync.com/cloud/v1/deviceManaged/devices",

View file

@ -141,8 +141,7 @@ def test_invalid_switches(hass: HomeAssistant) -> None:
def add_entities(devices, action): def add_entities(devices, action):
"""Mock add devices.""" """Mock add devices."""
for device in devices: hass_devices.extend(devices)
hass_devices.append(device)
bad_conf = {} # No subscription bad_conf = {} # No subscription

View file

@ -684,9 +684,7 @@ async def test_get_states(
assert msg["type"] == const.TYPE_RESULT assert msg["type"] == const.TYPE_RESULT
assert msg["success"] assert msg["success"]
states = [] states = [state.as_dict() for state in hass.states.async_all()]
for state in hass.states.async_all():
states.append(state.as_dict())
assert msg["result"] == states assert msg["result"] == states

View file

@ -46,8 +46,7 @@ async def test_setup(hass: HomeAssistant, requests_mock: requests_mock.Mocker) -
for entity in new_entities: for entity in new_entities:
entity.update() entity.update()
for entity in new_entities: entities.extend(new_entities)
entities.append(entity)
uri = re.compile(RESOURCE + "*") uri = re.compile(RESOURCE + "*")
requests_mock.get(uri, text=load_fixture("wsdot/wsdot.json")) requests_mock.get(uri, text=load_fixture("wsdot/wsdot.json"))