id
stringlengths 30
32
| content
stringlengths 139
2.8k
|
|---|---|
codereview_new_python_data_9629
|
def send_error(self, msg_id: int, code: str, message: str) -> None:
def async_handle(self, msg: dict[str, Any]) -> None:
"""Handle a single incoming message."""
if (
not (cur_id := msg.get("id"))
or not isinstance(cur_id, int)
or not (type_ := msg.get("type"))
we should also validate that it's a dict.
```suggestion
# Not using isinstance as we don't care about children
type(msg) is dict and
not (cur_id := msg.get("id"))
```
def send_error(self, msg_id: int, code: str, message: str) -> None:
def async_handle(self, msg: dict[str, Any]) -> None:
"""Handle a single incoming message."""
if (
+ # Not using isinstance as we don't care about children
+ type(msg) is dict and
not (cur_id := msg.get("id"))
or not isinstance(cur_id, int)
or not (type_ := msg.get("type"))
|
codereview_new_python_data_9630
|
def list_statistic_ids(
}
if not statistic_ids_set or statistic_ids_set.difference(result):
- # If we all statistic_ids, or some are missing, we need to query
# the integrations for the missing ones.
#
# Query all integrations with a registered recorder platform
```suggestion
# If we want all statistic_ids, or some are missing, we need to query
```
def list_statistic_ids(
}
if not statistic_ids_set or statistic_ids_set.difference(result):
+ # If we want all statistic_ids, or some are missing, we need to query
# the integrations for the missing ones.
#
# Query all integrations with a registered recorder platform
|
codereview_new_python_data_9631
|
def __init__(self, hass: HomeAssistant) -> None:
self.latitude: float = 0
self.longitude: float = 0
- # Elevation (always in meters regardless of the unit system)
self.elevation: int = 0
self.location_name: str = "Home"
self.time_zone: str = "UTC"
self.units: UnitSystem = METRIC_SYSTEM
Can/Should this be a docstring?
def __init__(self, hass: HomeAssistant) -> None:
self.latitude: float = 0
self.longitude: float = 0
+
self.elevation: int = 0
+ """Elevation (always in meters regardless of the unit system)."""
+
self.location_name: str = "Home"
self.time_zone: str = "UTC"
self.units: UnitSystem = METRIC_SYSTEM
|
codereview_new_python_data_9632
|
import pytest
-@pytest.fixture(autouse=True)
def mock_setup_entry() -> Generator[AsyncMock, None, None]:
"""Override async_setup_entry."""
with patch(
We can't auto use this here
import pytest
+@pytest.fixture
def mock_setup_entry() -> Generator[AsyncMock, None, None]:
"""Override async_setup_entry."""
with patch(
|
codereview_new_python_data_9633
|
import pytest
-@pytest.fixture(autouse=True)
def mock_setup_entry() -> Generator[AsyncMock, None, None]:
"""Override async_setup_entry."""
with patch(
We can't auto use this here
import pytest
+@pytest.fixture
def mock_setup_entry() -> Generator[AsyncMock, None, None]:
"""Override async_setup_entry."""
with patch(
|
codereview_new_python_data_9634
|
async def async_setup(self) -> bool:
func = getattr(self._client, entry.func_name)
self._pb_call[entry.call_type] = RunEntry(entry.attr, func)
- self.hass.async_create_task(self.async_pymodbus_connect())
# Start counting down to allow modbus requests.
if self._config_delay:
All tasks created with `async_create_task` are still awaited to finish the startup phase. To create a task that is not awaited, use:
```suggestion
self.hass.async_create_background_task(
self.async_pymodbus_connect(), “modbus-connect”
)
```
async def async_setup(self) -> bool:
func = getattr(self._client, entry.func_name)
self._pb_call[entry.call_type] = RunEntry(entry.attr, func)
+ self.hass.async_create_background_task(
+ self.async_pymodbus_connect(), "modbus-connect"
+ )
# Start counting down to allow modbus requests.
if self._config_delay:
|
codereview_new_python_data_9635
|
def __init__(
self._attr_unique_id = f"{config_entry.entry_id}_{index}"
self._attr_extra_state_attributes = {ATTR_NUMBER: self._index}
self._attr_device_info = DeviceInfo(
- identifiers={(DOMAIN, f"{config_entry.entry_id}_light_{index}")}, name=name
)
async def async_added_to_hass(self) -> None:
```suggestion
identifiers={(DOMAIN, f"{config_entry.entry_id}_light_{index}")}, name=name
via_device=(DOMAIN, f"{entry_id}_mcp")
```
def __init__(
self._attr_unique_id = f"{config_entry.entry_id}_{index}"
self._attr_extra_state_attributes = {ATTR_NUMBER: self._index}
self._attr_device_info = DeviceInfo(
+ identifiers={(DOMAIN, f"{config_entry.entry_id}_light_{index}")},
+ name=name,
+ via_device=(DOMAIN, f"{config_entry.entry_id}_mcp"),
)
async def async_added_to_hass(self) -> None:
|
codereview_new_python_data_9636
|
-"""The tests for camera recorder."""
from __future__ import annotations
from datetime import datetime, timedelta
```suggestion
"""The tests for unifiprotect recorder."""
```
+"""The tests for unifiprotect recorder."""
from __future__ import annotations
from datetime import datetime, timedelta
|
codereview_new_python_data_9637
|
async def _async_update_trend():
# This can take longer than 60s and we already know
# sense is online since get_discovered_device_data was
# successful so we do it later.
- entry.async_on_unload(
- hass.async_create_background_task(
- trends_coordinator.async_request_refresh(),
- "sense.trends-coordinator-refresh",
- ).cancel
)
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {
MyPy doesn't agree here because I feel like we have too strictly typed `entry.async_on_unload`. We are now forcing all callbacks to return `None`, however, the truth is that we do not care about the return value.
In TypeScript there is an `unknown` type. But I think that in this case we could also consider `Any`.
Because working around it means that we cannot even use a lambda – as `cancel` will still return a boolean. And PyLint will correctly complain about useless lambda.
The workaround for silly typing is to write it all out.
```python
task = hass.async_create_background_task(...)
def cancel_task()
task.cancel()
entry.async_on_unload(cancel_task)
```
async def _async_update_trend():
# This can take longer than 60s and we already know
# sense is online since get_discovered_device_data was
# successful so we do it later.
+ entry.async_create_background_task(
+ hass,
+ trends_coordinator.async_request_refresh(),
+ "sense.trends-coordinator-refresh",
)
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {
|
codereview_new_python_data_9638
|
def on_conn_made(_: BaseAsyncGateway) -> None:
finally:
if connect_task is not None and not connect_task.done():
connect_task.cancel()
- hass.async_create_background_task(gateway.stop(), "mysensors.gateway-stop")
except OSError as err:
_LOGGER.info("Try gateway connect failed with exception", exc_info=err)
return False
```suggestion
await gateway.stop()
```
def on_conn_made(_: BaseAsyncGateway) -> None:
finally:
if connect_task is not None and not connect_task.done():
connect_task.cancel()
+ await gateway.stop()
except OSError as err:
_LOGGER.info("Try gateway connect failed with exception", exc_info=err)
return False
|
codereview_new_python_data_9639
|
async def _async_discovery(*_: Any) -> None:
hass, await async_discover_devices(hass, DISCOVER_SCAN_TIMEOUT)
)
- hass.async_create_task(_async_discovery())
async_track_time_interval(hass, _async_discovery, DISCOVERY_INTERVAL)
if DOMAIN not in hass_config:
```suggestion
hass.async_create_background_task(_async_discovery(), "elkm1 setup discovery")
```
This one will always run for 10s waiting for responses which could be longer than stage 2 for everything else on a fast system. Its only needed to update the IP in the rare event it changes so it can run in the background.
async def _async_discovery(*_: Any) -> None:
hass, await async_discover_devices(hass, DISCOVER_SCAN_TIMEOUT)
)
+ hass.async_create_background_task(_async_discovery(), "elkm1 setup discovery")
async_track_time_interval(hass, _async_discovery, DISCOVERY_INTERVAL)
if DOMAIN not in hass_config:
|
codereview_new_python_data_9640
|
def no_more_acks() -> bool:
def async_restore_tracked_subscriptions(
self, subscriptions: list[Subscription]
) -> None:
- """Restore tracked subscriptions after reconnect."""
for subscription in subscriptions:
self._async_track_subscription(subscription)
self._matching_subscriptions.cache_clear()
```suggestion
"""Restore tracked subscriptions after reload."""
```
def no_more_acks() -> bool:
def async_restore_tracked_subscriptions(
self, subscriptions: list[Subscription]
) -> None:
+ """Restore tracked subscriptions after reload."""
for subscription in subscriptions:
self._async_track_subscription(subscription)
self._matching_subscriptions.cache_clear()
|
codereview_new_python_data_9641
|
async def async_stop_mqtt(_event: Event) -> None:
@property
def subscriptions(self) -> list[Subscription]:
- """Return the subscriptions."""
return [
*chain.from_iterable(self._simple_subscriptions.values()),
*self._wildcard_subscriptions,
```suggestion
"""Return the tracked subscriptions."""
```
async def async_stop_mqtt(_event: Event) -> None:
@property
def subscriptions(self) -> list[Subscription]:
+ """Return the tracked subscriptions."""
return [
*chain.from_iterable(self._simple_subscriptions.values()),
*self._wildcard_subscriptions,
|
codereview_new_python_data_9642
|
class ReolinkSirenEntityDescription(
supported: Callable[[Host, int], bool] = lambda api, ch: True
SIREN_ENTITIES = (
ReolinkSirenEntityDescription(
key="siren",
name="Siren",
icon="mdi:alarm-light",
supported=lambda api, ch: api.supported(ch, "siren"),
- method=lambda api, ch, on_off, duration: api.set_siren(
- ch, on_off, int(duration)
- ),
volume=lambda api, ch, volume: api.set_volume(ch, int(volume)),
),
)
lambdas shouldn't be multiline I've been told before. You can provide a method instead
class ReolinkSirenEntityDescription(
supported: Callable[[Host, int], bool] = lambda api, ch: True
+async def async_set_siren(api, ch, on_off, duration):
+ return await api.set_siren(ch, on_off, int(duration)
+
SIREN_ENTITIES = (
ReolinkSirenEntityDescription(
key="siren",
name="Siren",
icon="mdi:alarm-light",
supported=lambda api, ch: api.supported(ch, "siren"),
+ method=async_set_siren,
volume=lambda api, ch, volume: api.set_volume(ch, int(volume)),
),
)
|
codereview_new_python_data_9643
|
def __init__(
self.entity_description = entity_description
self._attr_unique_id = (
- f"{self._host.unique_id}_{self._channel}_{entity_description.key}"
)
async def async_turn_on(self, **kwargs: Any) -> None:
```suggestion
f"{self._host.unique_id}_{channel}_{entity_description.key}"
```
def __init__(
self.entity_description = entity_description
self._attr_unique_id = (
+ f"{self._host.unique_id}_{channel}_{entity_description.key}"
)
async def async_turn_on(self, **kwargs: Any) -> None:
|
codereview_new_python_data_9644
|
def init_client(self) -> None:
def _is_active_subscription(self, topic: str) -> bool:
"""Check if a topic has an active subscription."""
- if topic in self._simple_subscriptions:
- return True
- return any(other.topic == topic for other in self._wildcard_subscriptions)
async def async_publish(
self, topic: str, payload: PublishPayloadType, qos: int, retain: bool
```suggestion
return topic in self._simple_subscriptions or any(other.topic == topic for other in self._wildcard_subscriptions)
```
You could write it this way.
black will complain about this suggestion.
def init_client(self) -> None:
def _is_active_subscription(self, topic: str) -> bool:
"""Check if a topic has an active subscription."""
+ return topic in self._simple_subscriptions or any(
+ other.topic == topic for other in self._wildcard_subscriptions
+ )
async def async_publish(
self, topic: str, payload: PublishPayloadType, qos: int, retain: bool
|
codereview_new_python_data_9645
|
JSON_ENCODE_EXCEPTIONS = (TypeError, ValueError)
JSON_DECODE_EXCEPTIONS = (orjson.JSONDecodeError,)
json_loads: Callable[[bytes | bytearray | memoryview | str], JsonValueType]
json_loads = orjson.loads
"""Parse JSON data."""
Maybe we should keep `SerializationError` declared inside util to avoid breaking change
JSON_ENCODE_EXCEPTIONS = (TypeError, ValueError)
JSON_DECODE_EXCEPTIONS = (orjson.JSONDecodeError,)
+
+class SerializationError(HomeAssistantError):
+ """Error serializing the data to JSON."""
+
+
+class WriteError(HomeAssistantError):
+ """Error writing the data."""
+
+
json_loads: Callable[[bytes | bytearray | memoryview | str], JsonValueType]
json_loads = orjson.loads
"""Parse JSON data."""
|
codereview_new_python_data_9646
|
async def ws_delete_dataset(
connection.send_error(msg["id"], websocket_api.const.ERR_NOT_FOUND, str(exc))
return
except dataset_store.DatasetPreferredError as exc:
- connection.send_error(
- msg["id"], websocket_api.const.ERR_NOT_SUPPORTED, str(exc)
- )
return
connection.send_result(msg["id"])
Should this be "not allowed"? Or maybe just a unique error code
async def ws_delete_dataset(
connection.send_error(msg["id"], websocket_api.const.ERR_NOT_FOUND, str(exc))
return
except dataset_store.DatasetPreferredError as exc:
+ connection.send_error(msg["id"], websocket_api.const.ERR_NOT_ALLOWED, str(exc))
return
connection.send_result(msg["id"])
|
codereview_new_python_data_9647
|
async def test_washer_sensor_values(
assert entry
assert entry.disabled
assert entry.disabled_by is entity_registry.RegistryEntryDisabler.INTEGRATION
- update_entry = registry.async_update_entity(
- entry.entity_id, **{"disabled_by": None}
- )
await hass.async_block_till_done()
assert update_entry != entry
assert update_entry.disabled is False
state = hass.states.get(state_id)
assert state is None
# Test the washer cycle states
mock_instance.get_machine_state.return_value = MachineState.RunningMainCycle
mock_instance.get_cycle_status_filling.return_value = True
How was this 50 before but now is None? Don't see anything else that would change this value
async def test_washer_sensor_values(
assert entry
assert entry.disabled
assert entry.disabled_by is entity_registry.RegistryEntryDisabler.INTEGRATION
+
+ update_entry = registry.async_update_entity(entry.entity_id, disabled_by=None)
await hass.async_block_till_done()
+
assert update_entry != entry
assert update_entry.disabled is False
state = hass.states.get(state_id)
assert state is None
+ await hass.config_entries.async_reload(entry.config_entry_id)
+ state = hass.states.get(state_id)
+ assert state is not None
+ assert state.state == "50"
+
# Test the washer cycle states
mock_instance.get_machine_state.return_value = MachineState.RunningMainCycle
mock_instance.get_cycle_status_filling.return_value = True
|
codereview_new_python_data_9648
|
class WhirlpoolSensorEntityDescription(
device_class=SensorDeviceClass.ENUM,
options=list(TANK_FILL.values()),
value_fn=lambda WasherDryer: TANK_FILL.get(
- WasherDryer.get_attribute("WashCavity_OpStatusBulkDispense1Level"), None
),
),
)
by the way, in the future I think we should really avoid using get_attribute here, and have proper getters on the library's classes. HA should not have to know about WashCavity_OpStatusBulkDispense1Level
class WhirlpoolSensorEntityDescription(
device_class=SensorDeviceClass.ENUM,
options=list(TANK_FILL.values()),
value_fn=lambda WasherDryer: TANK_FILL.get(
+ WasherDryer.get_attribute("WashCavity_OpStatusBulkDispense1Level")
),
),
)
|
codereview_new_python_data_9649
|
class WhirlpoolSensorEntityDescription(
device_class=SensorDeviceClass.ENUM,
options=list(TANK_FILL.values()),
value_fn=lambda WasherDryer: TANK_FILL.get(
- WasherDryer.get_attribute("WashCavity_OpStatusBulkDispense1Level"), None
),
),
)
```suggestion
WasherDryer.get_attribute("WashCavity_OpStatusBulkDispense1Level")
```
class WhirlpoolSensorEntityDescription(
device_class=SensorDeviceClass.ENUM,
options=list(TANK_FILL.values()),
value_fn=lambda WasherDryer: TANK_FILL.get(
+ WasherDryer.get_attribute("WashCavity_OpStatusBulkDispense1Level")
),
),
)
|
codereview_new_python_data_9650
|
async def test_hidden_entities_skipped(
assert len(calls) == 0
assert result.response.response_type == intent.IntentResponseType.ERROR
assert result.response.error_code == intent.IntentResponseErrorCode.NO_INTENT_MATCH
-
-
-async def test_cant_turn_on_sun(hass: HomeAssistant, init_components) -> None:
- """Test we can't turn on entities that don't support it."""
-
- assert await async_setup_component(hass, "sun", {})
- result = await conversation.async_converse(
- hass, "turn on sun", None, Context(), None
- )
-
- assert result.response.response_type == intent.IntentResponseType.ERROR
- assert result.response.error_code == intent.IntentResponseErrorCode.FAILED_TO_HANDLE
This is a test for intent internals. In that case, use `helpers/test_intent.py`.
async def test_hidden_entities_skipped(
assert len(calls) == 0
assert result.response.response_type == intent.IntentResponseType.ERROR
assert result.response.error_code == intent.IntentResponseErrorCode.NO_INTENT_MATCH
|
codereview_new_python_data_9651
|
def router_removed(key: str) -> None:
@callback
def stop_discovery() -> None:
"""Stop discovery."""
- hass.async_create_task(thread_disovery.async_stop())
# Start Thread router discovery
- thread_disovery = discovery.ThreadRouterDiscovery(
hass, router_discovered, router_removed
)
- await thread_disovery.async_start()
connection.subscriptions[msg["id"]] = stop_discovery
connection.send_message(websocket_api.result_message(msg["id"]))
```suggestion
thread_discovery = discovery.ThreadRouterDiscovery(
```
def router_removed(key: str) -> None:
@callback
def stop_discovery() -> None:
"""Stop discovery."""
+ hass.async_create_task(thread_discovery.async_stop())
# Start Thread router discovery
+ thread_discovery = discovery.ThreadRouterDiscovery(
hass, router_discovered, router_removed
)
+ await thread_discovery.async_start()
connection.subscriptions[msg["id"]] = stop_discovery
connection.send_message(websocket_api.result_message(msg["id"]))
|
codereview_new_python_data_9652
|
async def async_press(self) -> None:
icon="mdi:ev-station",
name="Start charge",
requires_electricity=True,
- ),RenaultButtonEntityDescription(
async_press=lambda x: x.vehicle.set_charge_stop(),
key="stop_charge",
icon="mdi:ev-station",
This will fail black formatting, it will need a carriage return:
```suggestion
),
RenaultButtonEntityDescription(
```
async def async_press(self) -> None:
icon="mdi:ev-station",
name="Start charge",
requires_electricity=True,
+ ),
+ RenaultButtonEntityDescription(
async_press=lambda x: x.vehicle.set_charge_stop(),
key="stop_charge",
icon="mdi:ev-station",
|
codereview_new_python_data_9653
|
async def guard_func(*args: _P.args, **kwargs: _P.kwargs) -> _R:
# Guard a few functions that would make network connections
location.async_detect_location_info = check_real(location.async_detect_location_info)
-util.get_local_ip = lambda: "127.0.0.1" # type: ignore[attr-defined]
@pytest.fixture(name="caplog")
This I purposefully left out. I think it is fully unused and can be completely removed from `conftest.py`
I think it is patching a function that has been removed...
async def guard_func(*args: _P.args, **kwargs: _P.kwargs) -> _R:
# Guard a few functions that would make network connections
location.async_detect_location_info = check_real(location.async_detect_location_info)
+util.get_local_ip = lambda: "127.0.0.1"
@pytest.fixture(name="caplog")
|
codereview_new_python_data_9654
|
class ClassTypeHintMatch:
"hass_read_only_access_token": "str",
"hass_read_only_user": "MockUser",
"hass_recorder": "Callable[..., HomeAssistant]",
- "hass_storage": "Generator[dict[str, Any], None, None]",
"hass_supervisor_access_token": "str",
"hass_supervisor_user": "MockUser",
"hass_ws_client": "WebSocketGenerator",
This needs to be the type as used by the tests.
```suggestion
"hass_storage": "dict[str, Any]",
```
class ClassTypeHintMatch:
"hass_read_only_access_token": "str",
"hass_read_only_user": "MockUser",
"hass_recorder": "Callable[..., HomeAssistant]",
+ "hass_storage": "dict[str, Any]",
"hass_supervisor_access_token": "str",
"hass_supervisor_user": "MockUser",
"hass_ws_client": "WebSocketGenerator",
|
codereview_new_python_data_9655
|
async def test_check_ha_config_file_wrong(mock_check, hass):
],
)
async def test_async_hass_config_yaml_merge(
- merge_log_err, hass: HomeAssistant, mock_yaml_config: None
) -> None:
"""Test merge during async config reload."""
conf = await config_util.async_hass_config_yaml(hass)
I wonder if there are more places where `mock_yaml_config` could be used already.
Maybe `test_bootstrap.py`
Or maybe we should be patching "homeassistant.config.async_hass_config_yaml" instead?
async def test_check_ha_config_file_wrong(mock_check, hass):
],
)
async def test_async_hass_config_yaml_merge(
+ merge_log_err, hass: HomeAssistant, mock_yaml_configuration: None
) -> None:
"""Test merge during async config reload."""
conf = await config_util.async_hass_config_yaml(hass)
|
codereview_new_python_data_9656
|
def yaml_configuration_files(yaml_configuration: str | None) -> dict[str, str] |
@pytest.fixture
-def mock_yaml_config(
hass: HomeAssistant, yaml_configuration_files: dict[str, str] | None
) -> Generator[None, None, None]:
- """Fixture to mock the configuration.yaml file content.
- Parameterize configuration.yaml using the `yaml_config`,
`yaml_configuration` and `yaml_configuration_files` fixtures.
"""
with patch_yaml_files(yaml_configuration_files):
I think to keep in line we should use `configuration` here.
```suggestion
def mock_yaml_configuration(
hass: HomeAssistant, yaml_configuration_files: dict[str, str] | None
) -> Generator[None, None, None]:
"""Fixture to mock the content of the yaml configuration files.
Parameterize configuration files using the `yaml_config`,
`yaml_configuration` and `yaml_configuration_files` fixtures.
```
def yaml_configuration_files(yaml_configuration: str | None) -> dict[str, str] |
@pytest.fixture
+def mock_yaml_configuration(
hass: HomeAssistant, yaml_configuration_files: dict[str, str] | None
) -> Generator[None, None, None]:
+ """Fixture to mock the content of the yaml configuration files.
+ Parameterize configuration files using the `yaml_config`,
`yaml_configuration` and `yaml_configuration_files` fixtures.
"""
with patch_yaml_files(yaml_configuration_files):
|
codereview_new_python_data_9657
|
def test_config_platform_valid(
@pytest.mark.parametrize(
- "yaml_configuration,platforms,error",
[
(
BASE_CONFIG + "beer:",
This also needs adjusting for #88165
def test_config_platform_valid(
@pytest.mark.parametrize(
+ ("yaml_configuration", "platforms", "error"),
[
(
BASE_CONFIG + "beer:",
|
codereview_new_python_data_9658
|
def mock_hass_config(
@pytest.fixture
def hass_config_yaml() -> str | None:
- """Fixture to parameterize the content of a single yaml configuration file.
To set yaml content, tests can be marked with:
@pytest.mark.parametrize("hass_config_yaml", ["..."])
```suggestion
"""Fixture to parameterize the content of configuration.yaml file.
To set yaml content, tests can be marked with:
@pytest.mark.parametrize("hass_config_yaml", ["..."])
Add the `mock_hass_config_yaml: None` fixture to the test.
"""
```
def mock_hass_config(
@pytest.fixture
def hass_config_yaml() -> str | None:
+ """Fixture to parameterize the content of configuration.yaml file.
To set yaml content, tests can be marked with:
@pytest.mark.parametrize("hass_config_yaml", ["..."])
|
codereview_new_python_data_9659
|
def create_mock_mqtt(*args, **kwargs) -> MqttMockHAClient:
@pytest.fixture
def hass_config() -> ConfigType | None:
- """Fixture to parameterize the content of main configuration using mock_hass_config.
To set a configuration, tests can be marked with:
@pytest.mark.parametrize("hass_config", [{integration: {...}}])
```suggestion
"""Fixture to parametrize the content of main configuration using mock_hass_config.
```
def create_mock_mqtt(*args, **kwargs) -> MqttMockHAClient:
@pytest.fixture
def hass_config() -> ConfigType | None:
+ """Fixture to parametrize the content of main configuration using mock_hass_config.
To set a configuration, tests can be marked with:
@pytest.mark.parametrize("hass_config", [{integration: {...}}])
|
codereview_new_python_data_9660
|
async def async_setup_entry(
"""Set up the lock platform for Dormakaba dKey."""
data: DormakabaDkeyData = hass.data[DOMAIN][entry.entry_id]
async_add_entities(
- [
- DormakabaDkeySensor(data.coordinator, data.lock, description)
- for description in BINARY_SENSOR_DESCRIPTIONS
- ]
)
`async_add_entities` can accept a generator.
```suggestion
DormakabaDkeySensor(data.coordinator, data.lock, description)
for description in BINARY_SENSOR_DESCRIPTIONS
```
async def async_setup_entry(
"""Set up the lock platform for Dormakaba dKey."""
data: DormakabaDkeyData = hass.data[DOMAIN][entry.entry_id]
async_add_entities(
+ DormakabaDkeySensor(data.coordinator, data.lock, description)
+ for description in BINARY_SENSOR_DESCRIPTIONS
)
|
codereview_new_python_data_9661
|
async def async_block_till_done(self) -> None:
"""Block until all pending work is done."""
# To flush out any call_soon_threadsafe
await asyncio.sleep(0)
- await asyncio.sleep(0)
start_time: float | None = None
current_task = asyncio.current_task()
We used to do this by always entering the while loop, because we only checked if there were done tasks to be cleared afterwards.
async def async_block_till_done(self) -> None:
"""Block until all pending work is done."""
# To flush out any call_soon_threadsafe
await asyncio.sleep(0)
start_time: float | None = None
current_task = asyncio.current_task()
|
codereview_new_python_data_9662
|
class ReolinkSwitchEntityDescription(
value=lambda api, ch: api.ir_enabled(ch),
method=lambda api, ch, value: api.set_ir_lights(ch, value),
),
)
Same as above?
class ReolinkSwitchEntityDescription(
value=lambda api, ch: api.ir_enabled(ch),
method=lambda api, ch, value: api.set_ir_lights(ch, value),
),
+ ReolinkSwitchEntityDescription(
+ key="record_audio",
+ name="Record audio",
+ icon="mdi:microphone",
+ supported=lambda api, ch: api.supported(ch, "audio"),
+ value=lambda api, ch: api.audio_record(ch),
+ method=lambda api, ch, value: api.set_audio(ch, value),
+ ),
+ ReolinkSwitchEntityDescription(
+ key="siren_on_event",
+ name="Siren on event",
+ icon="mdi:alarm-light",
+ supported=lambda api, ch: api.supported(ch, "siren"),
+ value=lambda api, ch: api.audio_alarm_enabled(ch),
+ method=lambda api, ch, value: api.set_audio_alarm(ch, value),
+ ),
)
|
codereview_new_python_data_9663
|
class ReolinkNumberEntityDescription(
key="floodlight_brightness",
name="Floodlight brightness",
icon="mdi:spotlight-beam",
- mode=NumberMode.SLIDER,
native_step=1,
get_min_value=lambda api, ch: 1,
get_max_value=lambda api, ch: 100,
The slider is automatically set in general, was it needed to override it in this case?
../Frenck
class ReolinkNumberEntityDescription(
key="floodlight_brightness",
name="Floodlight brightness",
icon="mdi:spotlight-beam",
native_step=1,
get_min_value=lambda api, ch: 1,
get_max_value=lambda api, ch: 100,
|
codereview_new_python_data_9664
|
async def async_check_firmware_update():
)
# Fetch initial data so we have data when entities subscribe
try:
- await device_coordinator.async_config_entry_first_refresh()
- await firmware_coordinator.async_config_entry_first_refresh()
except ConfigEntryNotReady:
await host.stop()
raise
We can use `asyncio.gather` here to do this in parallel.
async def async_check_firmware_update():
)
# Fetch initial data so we have data when entities subscribe
try:
+ await asyncio.gather(
+ device_coordinator.async_config_entry_first_refresh()
+ firmware_coordinator.async_config_entry_first_refresh()
+ )
except ConfigEntryNotReady:
await host.stop()
raise
|
codereview_new_python_data_9665
|
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle the initial step."""
- errors = {}
if user_input is not None:
try:
info = await validate_input(self.hass, user_input)
```suggestion
errors: dict[str, str] = {}
```
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle the initial step."""
+ errors: dict[str, str] = {}
if user_input is not None:
try:
info = await validate_input(self.hass, user_input)
|
codereview_new_python_data_9666
|
async def test_sensors(
},
}
- ## Check if the entity is well registered in the device registry
assert entry.device_id
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
```suggestion
# Check if the entity is well registered in the device registry
```
async def test_sensors(
},
}
+ # Check if the entity is well registered in the device registry
assert entry.device_id
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
|
codereview_new_python_data_9667
|
async def test_list_entities_for_display(
"di": "device123",
"ei": "test_domain.renamed",
},
- {
- "ei": "test_domain.boring",
- },
{
"ei": "test_domain.hidden",
"hb": True,
Maybe a silly question but… do we still need this entry since it has no useful information?
async def test_list_entities_for_display(
"di": "device123",
"ei": "test_domain.renamed",
},
{
"ei": "test_domain.hidden",
"hb": True,
|
codereview_new_python_data_9668
|
async def test_shutdown_before_startup_finishes(
tmp_path,
):
"""Test shutdown before recorder starts is clean."""
if recorder_db_url == "sqlite://":
# On-disk database because this test does not play nice with the
# MutexPool
```suggestion
if recorder_db_url == "sqlite://":
```
async def test_shutdown_before_startup_finishes(
tmp_path,
):
"""Test shutdown before recorder starts is clean."""
+
if recorder_db_url == "sqlite://":
# On-disk database because this test does not play nice with the
# MutexPool
|
codereview_new_python_data_9669
|
async def test_database_lock_timeout(recorder_mock, hass, recorder_db_url):
return
hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
instance = get_instance(hass)
class BlockQueue(recorder.tasks.RecorderTask):
```suggestion
hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
```
async def test_database_lock_timeout(recorder_mock, hass, recorder_db_url):
return
hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
+
instance = get_instance(hass)
class BlockQueue(recorder.tasks.RecorderTask):
|
codereview_new_python_data_9670
|
def as_local(dattim: dt.datetime) -> dt.datetime:
return dattim.astimezone(DEFAULT_TIME_ZONE)
-def utc_from_timestamp(timestamp: float) -> dt.datetime:
- """Return a UTC time from a timestamp."""
- return dt.datetime.fromtimestamp(timestamp, UTC)
def utc_to_timestamp(utc_dt: dt.datetime) -> float:
Might be faster as a partial
def as_local(dattim: dt.datetime) -> dt.datetime:
return dattim.astimezone(DEFAULT_TIME_ZONE)
+# We use a partial here to improve performance by avoiding the global lookup
+# of UTC and the function call overhead.
+utc_from_timestamp = partial(dt.datetime.fromtimestamp, tz=UTC)
+"""Return a UTC time from a timestamp."""
def utc_to_timestamp(utc_dt: dt.datetime) -> float:
|
codereview_new_python_data_9671
|
def media_content_type(self) -> str | None:
if not self._currently_playing:
return None
item = self._currently_playing.get("item") or {}
- return (
- MediaType.PODCAST
- if item.get("type") == MediaType.EPISODE
- else MediaType.MUSIC
- )
@property
def media_duration(self) -> int | None:
Please don't use multi-line ternary statements
def media_content_type(self) -> str | None:
if not self._currently_playing:
return None
item = self._currently_playing.get("item") or {}
+ return MediaType.PODCAST if item.get("type") == MediaType.EPISODE else MediaType.MUSIC
@property
def media_duration(self) -> int | None:
|
codereview_new_python_data_9672
|
def async_update_state(self, new_state):
@TYPES.register("VolatileOrganicCompoundsSensor")
class VolatileOrganicCompoundsSensor(AirQualitySensor):
- """Generate a VolatileOrganicCompoundsSensor accessory as VOCs sensor."""
def create_services(self):
- """Override the init function for PM 2.5 Sensor."""
serv_air_quality: Service = self.add_preload_service(
SERV_AIR_QUALITY_SENSOR, [CHAR_VOC_DENSITY]
)
This docstring needs to be fixed as these should only be in micrograms/m3
def async_update_state(self, new_state):
@TYPES.register("VolatileOrganicCompoundsSensor")
class VolatileOrganicCompoundsSensor(AirQualitySensor):
+ """Generate a VolatileOrganicCompoundsSensor accessory as VOCs sensor.
+
+ Sensor entity must return VOC in µg/m3.
+ """
def create_services(self):
+ """Override the init function for VOC Sensor."""
serv_air_quality: Service = self.add_preload_service(
SERV_AIR_QUALITY_SENSOR, [CHAR_VOC_DENSITY]
)
|
codereview_new_python_data_9673
|
def density_to_air_quality_nitrogen_dioxide(density: float) -> int:
def density_to_air_quality_voc(density: float) -> int:
- """Map VOCs µg/m3 to HomeKit AirQuality level."""
- if density <= 250:
return 1
- if density <= 500:
return 2
- if density <= 1000:
return 3
- if density <= 3000:
return 4
- return 5
def get_persist_filename_for_entry_id(entry_id: str) -> str:
My main grind with this PR is: We are breaking it again; and to be honest, that is a bit unacceptable to break twice in such a short time.
I'm not using this myself, so have no personal opinion on it, but I really do want an extensive reasoning and definitive decision documented in the code comments here, that will block/prevent any breaking change to this again in the future.
def density_to_air_quality_nitrogen_dioxide(density: float) -> int:
def density_to_air_quality_voc(density: float) -> int:
+ """Map VOCs µg/m3 to HomeKit AirQuality level.
+
+ The VOC mappings use the IAQ guidelines for Europe released by the WHO (World Health Organization).
+ Referenced from Sensirion_Gas_Sensors_SGP3x_TVOC_Concept.pdf
+ https://github.com/paulvha/svm30/blob/master/extras/Sensirion_Gas_Sensors_SGP3x_TVOC_Concept.pdf
+ """
+ if density <= 250: # WHO IAQ 1 (HomeKit: Excellent)
return 1
+ if density <= 500: # WHO IAQ 2 (HomeKit: Good)
return 2
+ if density <= 1000: # WHO IAQ 3 (HomeKit: Fair)
return 3
+ if density <= 3000: # WHO IAQ 4 (HomeKit: Inferior)
return 4
+ return 5 # WHOA IAQ 5 (HomeKit: Poor)
def get_persist_filename_for_entry_id(entry_id: str) -> str:
|
codereview_new_python_data_9674
|
async def async_setup_entry(
config_entry: ConfigEntry,
) -> bool:
"""Set up EDL21 integration from a config entry."""
- hass.data.setdefault(DOMAIN, {})
-
# Forward the setup to the sensor platform.
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(config_entry, Platform.SENSOR)
I think this is wrong
```suggestion
```
async def async_setup_entry(
config_entry: ConfigEntry,
) -> bool:
"""Set up EDL21 integration from a config entry."""
# Forward the setup to the sensor platform.
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(config_entry, Platform.SENSOR)
|
codereview_new_python_data_9675
|
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
-async def async_setup_entry(
- hass: HomeAssistant,
- config_entry: ConfigEntry,
-) -> bool:
- """Set up EDL21 integration from a config entry."""
- # Forward the setup to the sensor platform.
- hass.async_create_task(
- hass.config_entries.async_forward_entry_setup(config_entry, Platform.SENSOR)
- )
return True
I suggest that you follow the usual pattern, with a PLATFORMS constant:
```suggestion
PLATFORMS = [Platform.SENSOR]
async def async_setup_entry(
```
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
+PLATFORMS = [Platform.SENSOR]
+async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
+ """Set up EDL21 integration from a config entry."""
+ await hass.config_entries.async_forward_entry_setups(config_entry, PLATFORMS)
return True
+
+
+async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
+ """Unload a config entry."""
+ return await hass.config_entries.async_unload_platforms(config_entry, PLATFORMS)
|
codereview_new_python_data_9676
|
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
-async def async_setup_entry(
- hass: HomeAssistant,
- config_entry: ConfigEntry,
-) -> bool:
- """Set up EDL21 integration from a config entry."""
- # Forward the setup to the sensor platform.
- hass.async_create_task(
- hass.config_entries.async_forward_entry_setup(config_entry, Platform.SENSOR)
- )
return True
```suggestion
return hass.config_entries.async_forward_entry_setup(config_entry, PLATFORMS)
async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
"""Unload a config entry."""
return await hass.config_entries.async_unload_platforms(config_entry, PLATFORMS)
```
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
+PLATFORMS = [Platform.SENSOR]
+async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
+ """Set up EDL21 integration from a config entry."""
+ await hass.config_entries.async_forward_entry_setups(config_entry, PLATFORMS)
return True
+
+
+async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
+ """Unload a config entry."""
+ return await hass.config_entries.async_unload_platforms(config_entry, PLATFORMS)
|
codereview_new_python_data_9677
|
def mock_setup_entry() -> Generator[AsyncMock, None, None]:
"""Override async_setup_entry."""
with patch(
- "homeassistant.components.openuv.async_setup_entry", return_value=True
) as mock_setup_entry:
yield mock_setup_entry
I think you used the wrong domain here.
```suggestion
"homeassistant.components.edl21.async_setup_entry", return_value=True
```
def mock_setup_entry() -> Generator[AsyncMock, None, None]:
"""Override async_setup_entry."""
with patch(
+ "homeassistant.components.edl21.async_setup_entry", return_value=True
) as mock_setup_entry:
yield mock_setup_entry
|
codereview_new_python_data_9678
|
def is_on(self) -> bool | None:
@property
def available(self) -> bool:
"""Return True if entity is available."""
- if self.device_info:
- if self.device_info[ATTR_MODEL] in SLEEPY_DEVICE_MODELS:
- # These devices sleep for an indeterminate amount of time
- # so there is no way to track their availability.
- return True
return super().available
```suggestion
if self.device_info and self.device_info[ATTR_MODEL] in SLEEPY_DEVICE_MODELS:
# These devices sleep for an indeterminate amount of time
# so there is no way to track their availability.
return True
```
def is_on(self) -> bool | None:
@property
def available(self) -> bool:
"""Return True if entity is available."""
+ if self.device_info and self.device_info[ATTR_MODEL] in SLEEPY_DEVICE_MODELS:
+ # These devices sleep for an indeterminate amount of time
+ # so there is no way to track their availability.
+ return True
return super().available
|
codereview_new_python_data_9679
|
def native_value(self) -> int | float | None:
@property
def available(self) -> bool:
"""Return True if entity is available."""
- if self.device_info:
- if self.device_info[ATTR_MODEL] in SLEEPY_DEVICE_MODELS:
- # These devices sleep for an indeterminate amount of time
- # so there is no way to track their availability.
- return True
return super().available
```suggestion
if self.device_info and self.device_info[ATTR_MODEL] in SLEEPY_DEVICE_MODELS:
# These devices sleep for an indeterminate amount of time
# so there is no way to track their availability.
return True
```
def native_value(self) -> int | float | None:
@property
def available(self) -> bool:
"""Return True if entity is available."""
+ if self.device_info and self.device_info[ATTR_MODEL] in SLEEPY_DEVICE_MODELS:
+ # These devices sleep for an indeterminate amount of time
+ # so there is no way to track their availability.
+ return True
return super().available
|
codereview_new_python_data_9680
|
def serialize(self) -> dict[str, dict[str, _T]]:
# Integration that provided the entity
vol.Optional("integration"): str,
# Domain the entity belongs to
- vol.Optional("device_class"): vol.All(cv.ensure_list, [str]),
# Device class of the entity
vol.Optional("device_class"): vol.All(cv.ensure_list, [str]),
}
You're removing `domain` here, but it's still part of `EntityFilterSelectorConfig` class
def serialize(self) -> dict[str, dict[str, _T]]:
# Integration that provided the entity
vol.Optional("integration"): str,
# Domain the entity belongs to
+ vol.Optional("domain"): vol.All(cv.ensure_list, [str]),
# Device class of the entity
vol.Optional("device_class"): vol.All(cv.ensure_list, [str]),
}
|
codereview_new_python_data_9681
|
def serialize(self) -> dict[str, dict[str, _T]]:
# Integration that provided the entity
vol.Optional("integration"): str,
# Domain the entity belongs to
- vol.Optional("device_class"): vol.All(cv.ensure_list, [str]),
# Device class of the entity
vol.Optional("device_class"): vol.All(cv.ensure_list, [str]),
}
And device class is twice.
def serialize(self) -> dict[str, dict[str, _T]]:
# Integration that provided the entity
vol.Optional("integration"): str,
# Domain the entity belongs to
+ vol.Optional("domain"): vol.All(cv.ensure_list, [str]),
# Device class of the entity
vol.Optional("device_class"): vol.All(cv.ensure_list, [str]),
}
|
codereview_new_python_data_9682
|
from aiohttp.test_utils import TestClient
ClientSessionGenerator = Callable[..., Coroutine[Any, Any, TestClient]]
-MqttMockType = Callable[..., Coroutine[Any, Any, MagicMock]]
WebSocketGenerator = Callable[..., Coroutine[Any, Any, ClientWebSocketResponse]]
I think we should be more explicit. Unless I am mistaken it's a generator that returns a mock.
```suggestion
MqttMockGenerator = Callable[..., Coroutine[Any, Any, MagicMock]]
```
from aiohttp.test_utils import TestClient
ClientSessionGenerator = Callable[..., Coroutine[Any, Any, TestClient]]
+MqttMockGenerator = Callable[..., Coroutine[Any, Any, MagicMock]]
WebSocketGenerator = Callable[..., Coroutine[Any, Any, ClientWebSocketResponse]]
|
codereview_new_python_data_9683
|
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
self._check_function(node, match, annotations)
# Check method matchers.
- if node.is_method():
- for match in _METHOD_MATCH["__any_class__"]:
- if not match.need_to_check_function(node):
- continue
- self._check_function(node, match, annotations)
visit_asyncfunctiondef = visit_functiondef
Class matcher using string as a key isn't flexible enough. I'd expect that someone may want to add checks for classes which inherit some specific base class which sounds be more useful than checking methods of specific class (which is also not implemented yet).
It's probably fine too keep is this way for now but this makes it harder for others who may want to add more such checks.
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
self._check_function(node, match, annotations)
# Check method matchers.
+ for match in _METHOD_MATCH["__any_class__"]:
+ if not match.need_to_check_function(node) or not node.is_method():
+ continue
+ self._check_function(node, match, annotations)
visit_asyncfunctiondef = visit_functiondef
|
codereview_new_python_data_9684
|
async def async_setup_entry(
) -> None:
"""Set up the lock platform for Dormakaba dKey."""
data: DormakabaDkeyData = hass.data[DOMAIN][entry.entry_id]
- async_add_entities([DormakabaDkeyLock(data.coordinator, data.lock, entry.title)])
-class DormakabaDkeyLock(CoordinatorEntity, LockEntity):
"""Representation of Dormakaba dKey lock."""
_attr_has_entity_name = True
def __init__(
- self, coordinator: DataUpdateCoordinator, lock: DKEYLock, name: str
) -> None:
"""Initialize a Dormakaba dKey lock."""
super().__init__(coordinator)
```suggestion
class DormakabaDkeyLock(CoordinatorEntity[DataUpdateCoordinator[None]], LockEntity):
```
async def async_setup_entry(
) -> None:
"""Set up the lock platform for Dormakaba dKey."""
data: DormakabaDkeyData = hass.data[DOMAIN][entry.entry_id]
+ async_add_entities([DormakabaDkeyLock(data.coordinator, data.lock)])
+class DormakabaDkeyLock(CoordinatorEntity[DataUpdateCoordinator[None]], LockEntity):
"""Representation of Dormakaba dKey lock."""
_attr_has_entity_name = True
def __init__(
+ self, coordinator: DataUpdateCoordinator[None], lock: DKEYLock
) -> None:
"""Initialize a Dormakaba dKey lock."""
super().__init__(coordinator)
|
codereview_new_python_data_9685
|
DEVICE_TIMEOUT = 30
UPDATE_SECONDS = 120
-ASSOCIATION_DATA = "association_data"
Prefix with `CONF_` in constants for config keys.
```suggestion
CONF_ASSOCIATION_DATA = "association_data"
```
DEVICE_TIMEOUT = 30
UPDATE_SECONDS = 120
+CONF_ASSOCIATION_DATA = "association_data"
|
codereview_new_python_data_9686
|
key="gas_consumed_interval",
name="Gas consumed interval",
icon="mdi:meter-gas",
- native_unit_of_measurement="m³/h",
state_class=SensorStateClass.TOTAL,
),
SensorEntityDescription(
```suggestion
native_unit_of_measurement=f"UnitOfVolume.CUBIC_METERS/UnitOfTime.HOURS",
```
key="gas_consumed_interval",
name="Gas consumed interval",
icon="mdi:meter-gas",
+ native_unit_of_measurement=f"UnitOfVolume.CUBIC_METERS/UnitOfTime.HOURS",
state_class=SensorStateClass.TOTAL,
),
SensorEntityDescription(
|
codereview_new_python_data_9687
|
key="gas_consumed_interval",
name="Gas consumed interval",
icon="mdi:meter-gas",
- native_unit_of_measurement="m³/h",
state_class=SensorStateClass.TOTAL,
),
SensorEntityDescription(
As the sensor becomes a rate, it can't be a total.
key="gas_consumed_interval",
name="Gas consumed interval",
icon="mdi:meter-gas",
+ native_unit_of_measurement=f"UnitOfVolume.CUBIC_METERS/UnitOfTime.HOURS",
state_class=SensorStateClass.TOTAL,
),
SensorEntityDescription(
|
codereview_new_python_data_9688
|
async def _update_no_ip(
body = await resp.text()
if body.startswith("good") or body.startswith("nochg"):
- _LOGGER.info(
"Updating NO-IP success: %s", domain
return True
Max debug level please.
```suggestion
_LOGGER.debug(
```
async def _update_no_ip(
body = await resp.text()
if body.startswith("good") or body.startswith("nochg"):
+ _LOGGER.debug(
"Updating NO-IP success: %s", domain
return True
|
codereview_new_python_data_9689
|
async def async_setup_entry(
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up entry."""
- entities = list[ScreenLogicSensorEntity]()
coordinator = hass.data[DOMAIN][config_entry.entry_id]
equipment_flags = coordinator.gateway.get_data()[SL_DATA.KEY_CONFIG][
"equipment_flags"
```suggestion
entities: list[ScreenLogicSensorEntity] = []
```
async def async_setup_entry(
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up entry."""
+ entities: list[ScreenLogicSensorEntity] = []
coordinator = hass.data[DOMAIN][config_entry.entry_id]
equipment_flags = coordinator.gateway.get_data()[SL_DATA.KEY_CONFIG][
"equipment_flags"
|
codereview_new_python_data_9690
|
async def async_get_connect_info(hass: HomeAssistant, entry: ConfigEntry):
class ScreenlogicDataUpdateCoordinator(DataUpdateCoordinator):
"""Class to manage the data update for the Screenlogic component."""
- def __init__(self, hass, *, config_entry, gateway):
"""Initialize the Screenlogic Data Update Coordinator."""
- self.config_entry: ConfigEntry = config_entry
- self.gateway: ScreenLogicGateway = gateway
interval = timedelta(
seconds=config_entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL)
```suggestion
def __init__(self, hass: HomeAssistant, *: Any, config_entry: ConfigEntry, gateway: ScreenLogicGateway) -> None:
```
Than you can drop the typing on `self.config_entry` and `self.gateway` below since it will already be known
async def async_get_connect_info(hass: HomeAssistant, entry: ConfigEntry):
class ScreenlogicDataUpdateCoordinator(DataUpdateCoordinator):
"""Class to manage the data update for the Screenlogic component."""
+ def __init__(
+ self,
+ hass: HomeAssistant,
+ *,
+ config_entry: ConfigEntry,
+ gateway: ScreenLogicGateway,
+ ) -> None:
"""Initialize the Screenlogic Data Update Coordinator."""
+ self.config_entry = config_entry
+ self.gateway = gateway
interval = timedelta(
seconds=config_entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL)
|
codereview_new_python_data_9691
|
def set_cover_position(self, **kwargs: Any) -> None:
self.device.id, f"exact?level={str(min(value, 99))}"
)
- def stop_cover(self, **kwargs):
"""Stop cover."""
self.controller.zwave_api.send_command(self.device.id, "stop")
```suggestion
def stop_cover(self, **kwargs: Any) -> None:
```
def set_cover_position(self, **kwargs: Any) -> None:
self.device.id, f"exact?level={str(min(value, 99))}"
)
+ def stop_cover(self, **kwargs: Any) -> None:
"""Stop cover."""
self.controller.zwave_api.send_command(self.device.id, "stop")
|
codereview_new_python_data_9692
|
async def async_setup_trigger(
config = TRIGGER_DISCOVERY_SCHEMA(config)
device_id = update_device(hass, config_entry, config)
mqtt_device_trigger = MqttDeviceTrigger(
- hass, config, str(device_id), discovery_data, config_entry
)
await mqtt_device_trigger.async_setup()
send_discovery_done(hass, discovery_data)
Since the schema already validates the data, update device will always return a device_id
async def async_setup_trigger(
config = TRIGGER_DISCOVERY_SCHEMA(config)
device_id = update_device(hass, config_entry, config)
+ assert isinstance(device_id, str)
mqtt_device_trigger = MqttDeviceTrigger(
+ hass, config, device_id, discovery_data, config_entry
)
await mqtt_device_trigger.async_setup()
send_discovery_done(hass, discovery_data)
|
codereview_new_python_data_9693
|
async def register_webhook(self) -> None:
self._hass,
DOMAIN,
"https_webhook",
- breaks_in_ha_version="2023.2.0",
is_fixable=False,
severity=ir.IssueSeverity.WARNING,
translation_key="https_webhook",
I don't think there should be a `breaks_in_ha_version` item. This is a problem already and for the future, right?
async def register_webhook(self) -> None:
self._hass,
DOMAIN,
"https_webhook",
is_fixable=False,
severity=ir.IssueSeverity.WARNING,
translation_key="https_webhook",
|
codereview_new_python_data_9694
|
def __init__(
) -> None:
"""Initialize the Yale Lock Device."""
super().__init__(coordinator, data)
- self._attr_code_format = f"^\\d{{{code_format}}}$"
self.lock_name: str = data["name"]
async def async_unlock(self, **kwargs: Any) -> None:
Why is the extra backslash there btw?
Shouldn't it be:
`^\d{{{code_format}}}$`?
def __init__(
) -> None:
"""Initialize the Yale Lock Device."""
super().__init__(coordinator, data)
+ self._attr_code_format = rf"^\d{{{code_format}}}$"
self.lock_name: str = data["name"]
async def async_unlock(self, **kwargs: Any) -> None:
|
codereview_new_python_data_9695
|
class Base(DeclarativeBase):
TABLE_STATISTICS_RUNS = "statistics_runs"
TABLE_STATISTICS_SHORT_TERM = "statistics_short_term"
-# Order is important here, as we expect statistics to have
-# more rows than statistics_short_term
STATISTICS_TABLES = ("statistics", "statistics_short_term")
MAX_STATE_ATTRS_BYTES = 16384
Please improve the comment, it does not explain why the order is important
class Base(DeclarativeBase):
TABLE_STATISTICS_RUNS = "statistics_runs"
TABLE_STATISTICS_SHORT_TERM = "statistics_short_term"
STATISTICS_TABLES = ("statistics", "statistics_short_term")
MAX_STATE_ATTRS_BYTES = 16384
|
codereview_new_python_data_9696
|
async def _async_update_data(self) -> None:
async def async_update_volume(self) -> None:
"""Update volume information."""
volume_info = await self.client.get_volume_info()
- volume_level = volume_info.get("volume")
- if volume_level is not None:
self.volume_level = volume_level / 100
self.volume_muted = volume_info.get("mute", False)
self.volume_target = volume_info.get("target")
```suggestion
if (volume_level := volume_info.get("volume")) is not None:
```
async def _async_update_data(self) -> None:
async def async_update_volume(self) -> None:
"""Update volume information."""
volume_info = await self.client.get_volume_info()
+ if (volume_level := volume_info.get("volume")) is not None:
self.volume_level = volume_level / 100
self.volume_muted = volume_info.get("mute", False)
self.volume_target = volume_info.get("target")
|
codereview_new_python_data_9697
|
def node_status(node: Node) -> dict[str, Any]:
"highest_security_class": node.highest_security_class,
"is_controller_node": node.is_controller_node,
"has_firmware_update_cc": any(
- CommandClass.FIRMWARE_UPDATE_MD.value == cc.id
for cc in node.command_classes
),
}
I'd put the constant known value to the right in the comparison.
def node_status(node: Node) -> dict[str, Any]:
"highest_security_class": node.highest_security_class,
"is_controller_node": node.is_controller_node,
"has_firmware_update_cc": any(
+ cc.id == CommandClass.FIRMWARE_UPDATE_MD.value
for cc in node.command_classes
),
}
|
codereview_new_python_data_9698
|
class PrusaLinkSensorEntityDescription(
PrusaLinkSensorEntityDescription[PrinterInfo](
key="printer.telemetry.temp-nozzle",
name="Nozzle Temperature",
- icon="mdi:printer-3d-nozzle-heat",
native_unit_of_measurement=UnitOfTemperature.CELSIUS,
device_class=SensorDeviceClass.TEMPERATURE,
state_class=SensorStateClass.MEASUREMENT,
We do not allow icons for entities with a device class.
class PrusaLinkSensorEntityDescription(
PrusaLinkSensorEntityDescription[PrinterInfo](
key="printer.telemetry.temp-nozzle",
name="Nozzle Temperature",
native_unit_of_measurement=UnitOfTemperature.CELSIUS,
device_class=SensorDeviceClass.TEMPERATURE,
state_class=SensorStateClass.MEASUREMENT,
|
codereview_new_python_data_9699
|
async def async_setup_entry(
"""Set up a Reolink number entities."""
reolink_data: ReolinkData = hass.data[DOMAIN][config_entry.entry_id]
- entities: list[ReolinkNumberEntity] = []
- for channel in reolink_data.host.api.channels:
- entities.extend(
- [
- ReolinkNumberEntity(reolink_data, channel, entity_description)
- for entity_description in NUMBER_ENTITIES
- if entity_description.supported(reolink_data.host.api, channel)
- ]
- )
-
- async_add_entities(entities)
class ReolinkNumberEntity(ReolinkCoordinatorEntity, NumberEntity):
```suggestion
async_add_entities(
ReolinkNumberEntity(reolink_data, channel, entity_description)
for entity_description in NUMBER_ENTITIES
for channel in reolink_data.host.api.channels
if entity_description.supported(reolink_data.host.api, channel)
)
```
async def async_setup_entry(
"""Set up a Reolink number entities."""
reolink_data: ReolinkData = hass.data[DOMAIN][config_entry.entry_id]
+ async_add_entities(
+ ReolinkNumberEntity(reolink_data, channel, entity_description)
+ for entity_description in NUMBER_ENTITIES
+ for channel in reolink_data.host.api.channels
+ if entity_description.supported(reolink_data.host.api, channel)
+ )
class ReolinkNumberEntity(ReolinkCoordinatorEntity, NumberEntity):
|
codereview_new_python_data_9700
|
from homeassistant.helpers.typing import ConfigType
from .const import DOMAIN
-from .dataset_store import (
- DatasetEntry,
- async_add_dataset,
- async_delete_dataset,
- async_get_dataset,
- async_list_datasets,
-)
__all__ = [
"DOMAIN",
"DatasetEntry",
"async_add_dataset",
- "async_delete_dataset",
- "async_get_dataset",
- "async_list_datasets",
]
These APIs are not used and should not be exposed.
from homeassistant.helpers.typing import ConfigType
from .const import DOMAIN
+from .dataset_store import DatasetEntry, async_add_dataset
__all__ = [
"DOMAIN",
"DatasetEntry",
"async_add_dataset",
]
|
codereview_new_python_data_9701
|
async def register_webhook(self) -> None:
self.webhook_id = f"{DOMAIN}_{self.unique_id.replace(':', '')}_ONVIF"
event_id = self.webhook_id
- try:
- webhook.async_register(
- self._hass, DOMAIN, event_id, event_id, self.handle_webhook
- )
- except ValueError:
- webhook.async_unregister(self._hass, event_id)
- webhook.async_register(
- self._hass, DOMAIN, event_id, event_id, self.handle_webhook
- )
try:
base_url = get_url(self._hass, prefer_external=False)
I think the problem is that we don't unregister the webhook before trying to set up the integration again via raising `ConfigEntryNotReady`.
async def register_webhook(self) -> None:
self.webhook_id = f"{DOMAIN}_{self.unique_id.replace(':', '')}_ONVIF"
event_id = self.webhook_id
+ webhook.async_register(
+ self._hass, DOMAIN, event_id, event_id, self.handle_webhook
+ )
try:
base_url = get_url(self._hass, prefer_external=False)
|
codereview_new_python_data_9702
|
"stat_val_tpl": "state_value_template",
"step": "step",
"stype": "subtype",
- "sug_dsp_precision": "suggested_display_precision",
"sup_dur": "support_duration",
"sup_vol": "support_volume_set",
"sup_feat": "supported_features",
Maybe `sug_dsp_prc`? https://www.allacronyms.com/precision/abbreviated
"stat_val_tpl": "state_value_template",
"step": "step",
"stype": "subtype",
+ "sug_dsp_prc": "suggested_display_precision",
"sup_dur": "support_duration",
"sup_vol": "support_volume_set",
"sup_feat": "supported_features",
|
codereview_new_python_data_9703
|
async def test_async_call_later_timedelta(hass):
scheduleutctime = dt_util.utcnow()
def action(__utcnow: datetime):
- _currentdelay = __utcnow.timestamp() - scheduleutctime.timestamp()
- future.set_result(delay < _currentdelay < (delay + delay_tolerance))
remove = async_call_later(hass, timedelta(seconds=delay), action)
```suggestion
schedule_utctime = dt_util.utcnow()
```
async def test_async_call_later_timedelta(hass):
scheduleutctime = dt_util.utcnow()
def action(__utcnow: datetime):
+ _current_delay = __utcnow.timestamp() - schedule_utctime.timestamp()
+ future.set_result(delay < _current_delay < (delay + delay_tolerance))
remove = async_call_later(hass, timedelta(seconds=delay), action)
|
codereview_new_python_data_9704
|
async def test_async_call_later_timedelta(hass):
scheduleutctime = dt_util.utcnow()
def action(__utcnow: datetime):
- _currentdelay = __utcnow.timestamp() - scheduleutctime.timestamp()
- future.set_result(delay < _currentdelay < (delay + delay_tolerance))
remove = async_call_later(hass, timedelta(seconds=delay), action)
```suggestion
_current_delay = __utcnow.timestamp() - schedule_utctime.timestamp()
future.set_result(delay < _current_delay < (delay + delay_tolerance))
```
async def test_async_call_later_timedelta(hass):
scheduleutctime = dt_util.utcnow()
def action(__utcnow: datetime):
+ _current_delay = __utcnow.timestamp() - schedule_utctime.timestamp()
+ future.set_result(delay < _current_delay < (delay + delay_tolerance))
remove = async_call_later(hass, timedelta(seconds=delay), action)
|
codereview_new_python_data_9705
|
def _numeric_state_expected(self) -> bool:
return True
# Sensors with custom device classes are not considered numeric
device_class = try_parse_enum(SensorDeviceClass, self.device_class)
- return (
- device_class is not None and device_class not in NON_NUMERIC_DEVICE_CLASSES
- )
@property
def options(self) -> list[str] | None:
```suggestion
return device_class not in {None, *NON_NUMERIC_DEVICE_CLASSES}
```
Alternative suggestion, thnx to @epenet ?
def _numeric_state_expected(self) -> bool:
return True
# Sensors with custom device classes are not considered numeric
device_class = try_parse_enum(SensorDeviceClass, self.device_class)
+ return device_class not in {None, *NON_NUMERIC_DEVICE_CLASSES}
@property
def options(self) -> list[str] | None:
|
codereview_new_python_data_9706
|
def shared_attrs_bytes_from_event(
_LOGGER.warning(
"State attributes for %s exceed maximum size of %s bytes. "
"This can cause database performance issues; Attributes "
- "will not be stored: %s",
state.entity_id,
MAX_STATE_ATTRS_BYTES,
- state.attributes,
)
return b"{}"
return bytes_result
we should not print the attributes, they are very big 🙈
def shared_attrs_bytes_from_event(
_LOGGER.warning(
"State attributes for %s exceed maximum size of %s bytes. "
"This can cause database performance issues; Attributes "
+ "will not be stored",
state.entity_id,
MAX_STATE_ATTRS_BYTES,
)
return b"{}"
return bytes_result
|
codereview_new_python_data_9707
|
def _encode_jwt(hass: HomeAssistant, data: dict) -> str:
@callback
def _decode_jwt(hass: HomeAssistant, encoded: str) -> dict | None:
"""JWT encode data."""
- secret = cast(str | None, hass.data.get(DATA_JWT_SECRET))
if secret is None:
return None
```suggestion
secret: str | None = hass.data.get(DATA_JWT_SECRET)
```
def _encode_jwt(hass: HomeAssistant, data: dict) -> str:
@callback
def _decode_jwt(hass: HomeAssistant, encoded: str) -> dict | None:
"""JWT encode data."""
+ secret: str | None = hass.data.get(DATA_JWT_SECRET)
if secret is None:
return None
|
codereview_new_python_data_9708
|
async def async_scan_devices(self, now: datetime | None = None) -> None:
self.fritz_hosts.get_mesh_topology
)
):
- raise HomeAssistantError("Mesh supported but empty topology reported")
except FritzActionError:
self.mesh_role = MeshRoles.SLAVE
# Avoid duplicating device trackers
Code owner should explain what this means and what can be done about it.
async def async_scan_devices(self, now: datetime | None = None) -> None:
self.fritz_hosts.get_mesh_topology
)
):
+ # pylint: disable=broad-exception-raised
+ raise Exception("Mesh supported but empty topology reported")
except FritzActionError:
self.mesh_role = MeshRoles.SLAVE
# Avoid duplicating device trackers
|
codereview_new_python_data_9709
|
def supports_update(self) -> bool:
esphome_version: str = next(iter(self.data.values()))["current_version"]
- return AwesomeVersion(esphome_version) >= AwesomeVersion("2023.2.0-dev")
async def _async_update_data(self) -> dict:
"""Fetch device data."""
I dont think the `-dev` is needed here
```suggestion
return AwesomeVersion(esphome_version) >= AwesomeVersion("2023.2.0")
```
def supports_update(self) -> bool:
esphome_version: str = next(iter(self.data.values()))["current_version"]
+ # There is no January release
+ return AwesomeVersion(esphome_version) > AwesomeVersion("2023.1.0")
async def _async_update_data(self) -> dict:
"""Fetch device data."""
|
codereview_new_python_data_9710
|
def is_numeric(self) -> bool:
or self.native_precision is not None
):
return True
- if self.device_class and self.device_class not in _NON_NUMERIC_DEVICE_CLASSES:
return True
return False
```suggestion
with suppress(ValueError):
# Custom device classes are not considered as numeric
device_class = SensorDeviceClass(str(self.device_class))
if device_class and device_class not in _NON_NUMERIC_DEVICE_CLASSES:
```
def is_numeric(self) -> bool:
or self.native_precision is not None
):
return True
+ with suppress(ValueError):
+ # Custom device classes are not considered as numeric
+ device_class = SensorDeviceClass(str(self.device_class))
+ if device_class and device_class not in _NON_NUMERIC_DEVICE_CLASSES:
return True
return False
|
codereview_new_python_data_9711
|
def is_numeric(self) -> bool:
or self.native_precision is not None
):
return True
- with suppress(ValueError):
- # Custom device classes are not considered as numeric
- device_class = SensorDeviceClass(str(self.device_class))
- if device_class and device_class not in _NON_NUMERIC_DEVICE_CLASSES:
return True
return False
It looks like device_class can be unbound now... sorry about that.
```suggestion
device_class: SensorDeviceClass | None = None
with suppress(ValueError):
```
def is_numeric(self) -> bool:
or self.native_precision is not None
):
return True
+ if self.device_class and self.device_class not in _NON_NUMERIC_DEVICE_CLASSES:
return True
return False
|
codereview_new_python_data_9712
|
def numeric_state_expected(self) -> bool:
with suppress(ValueError):
# Custom device classes are not considered numeric
device_class = SensorDeviceClass(str(self.device_class))
- if device_class and device_class not in _NON_NUMERIC_DEVICE_CLASSES:
- return True
- return False
@property
def options(self) -> list[str] | None:
```suggestion
return device_class is None and device_class not in _NON_NUMERIC_DEVICE_CLASSES
```
def numeric_state_expected(self) -> bool:
with suppress(ValueError):
# Custom device classes are not considered numeric
device_class = SensorDeviceClass(str(self.device_class))
+ return device_class is None and device_class not in _NON_NUMERIC_DEVICE_CLASSES
@property
def options(self) -> list[str] | None:
|
codereview_new_python_data_9713
|
def numeric_state_expected(self) -> bool:
with suppress(ValueError):
# Custom device classes are not considered numeric
device_class = SensorDeviceClass(str(self.device_class))
- if device_class and device_class not in NON_NUMERIC_DEVICE_CLASSES:
- return True
- return False
@property
def options(self) -> list[str] | None:
Reverted this change as it is not the same logic.
def numeric_state_expected(self) -> bool:
with suppress(ValueError):
# Custom device classes are not considered numeric
device_class = SensorDeviceClass(str(self.device_class))
+ return bool(device_class and device_class not in NON_NUMERIC_DEVICE_CLASSES)
@property
def options(self) -> list[str] | None:
|
codereview_new_python_data_9714
|
def numeric_state_expected(self) -> bool:
with suppress(ValueError):
# Custom device classes are not considered numeric
device_class = SensorDeviceClass(str(self.device_class))
- return bool(device_class and device_class not in NON_NUMERIC_DEVICE_CLASSES)
@property
def options(self) -> list[str] | None:
The use of `bool()` really isn't needed here
def numeric_state_expected(self) -> bool:
with suppress(ValueError):
# Custom device classes are not considered numeric
device_class = SensorDeviceClass(str(self.device_class))
+ return not (device_class is None or device_class in NON_NUMERIC_DEVICE_CLASSES)
@property
def options(self) -> list[str] | None:
|
codereview_new_python_data_9715
|
def _numeric_state_expected(self) -> bool:
or self.native_precision is not None
):
return True
- device_class: SensorDeviceClass | None = None
- with suppress(ValueError):
- # Sensors with custom device classes are not considered numeric
- device_class = SensorDeviceClass(str(self.device_class))
return not (device_class is None or device_class in NON_NUMERIC_DEVICE_CLASSES)
@property
This could be simplified if #87082 is accepted.
def _numeric_state_expected(self) -> bool:
or self.native_precision is not None
):
return True
+ # Sensors with custom device classes are not considered numeric
+ device_class: SensorDeviceClass | None = try_parse_enum(
+ SensorDeviceClass, self.device_class
+ )
return not (device_class is None or device_class in NON_NUMERIC_DEVICE_CLASSES)
@property
|
codereview_new_python_data_9716
|
def _numeric_state_expected(self) -> bool:
or self.native_precision is not None
):
return True
- device_class: SensorDeviceClass | None = None
- with suppress(ValueError):
- # Sensors with custom device classes are not considered numeric
- device_class = SensorDeviceClass(str(self.device_class))
return not (device_class is None or device_class in NON_NUMERIC_DEVICE_CLASSES)
@property
#87082 has been approved
```suggestion
# Sensors with custom device classes are not considered numeric
device_class = try_parse_enum(SensorDeviceClass, self.device_class)
return not (device_class is None or device_class in NON_NUMERIC_DEVICE_CLASSES)
```
def _numeric_state_expected(self) -> bool:
or self.native_precision is not None
):
return True
+ # Sensors with custom device classes are not considered numeric
+ device_class: SensorDeviceClass | None = try_parse_enum(
+ SensorDeviceClass, self.device_class
+ )
return not (device_class is None or device_class in NON_NUMERIC_DEVICE_CLASSES)
@property
|
codereview_new_python_data_9717
|
def _has_name(
# Check name/aliases
if entity is not None:
- if (entity.name is not None) and (name == entity.name.casefold()):
- return True
-
if entity.aliases:
for alias in entity.aliases:
if name == alias.casefold():
This is code from the other PR that we weren't pursueing right now? Let's remove it as it's not correctly handling entity registry names.
def _has_name(
# Check name/aliases
if entity is not None:
if entity.aliases:
for alias in entity.aliases:
if name == alias.casefold():
|
codereview_new_python_data_9718
|
"""Typing helpers for Home Assistant tests."""
from __future__ import annotations
-from typing import TYPE_CHECKING, TypeAlias
-if TYPE_CHECKING:
- from collections.abc import Callable, Coroutine
- from typing import Any
- from aiohttp import ClientWebSocketResponse
- from aiohttp.test_utils import TestClient
-
-TestClientGenerator: TypeAlias = "Callable[..., Coroutine[Any, Any, TestClient]]"
-TestWebSocketGenerator: TypeAlias = (
- "Callable[..., Coroutine[Any, Any, ClientWebSocketResponse]]"
-)
The type hints are quite happily accepted in conftest, but when I tried to make use of them for real they generated a `TypeError`
Declaring them instead as `TypeAlias` strings makes it happy
cc @MartinHjelmare
(and @cdce8p in case has better idea to resolve the issue)
"""Typing helpers for Home Assistant tests."""
from __future__ import annotations
+from collections.abc import Callable, Coroutine
+from typing import Any
+from aiohttp import ClientWebSocketResponse
+from aiohttp.test_utils import TestClient
+ClientSessionGenerator = Callable[..., Coroutine[Any, Any, TestClient]]
+WebSocketGenerator = Callable[..., Coroutine[Any, Any, ClientWebSocketResponse]]
|
codereview_new_python_data_9719
|
async def test_thermostat_missing_temperature_trait(
assert ATTR_FAN_MODE not in thermostat.attributes
assert ATTR_FAN_MODES not in thermostat.attributes
- with pytest.raises(KeyError):
await common.async_set_temperature(hass, temperature=24.0)
await hass.async_block_till_done()
assert thermostat.attributes[ATTR_TEMPERATURE] is None
We should fail with a friendlier error message, for example look at how the preset mode check is handled when a mode is not supported.
async def test_thermostat_missing_temperature_trait(
assert ATTR_FAN_MODE not in thermostat.attributes
assert ATTR_FAN_MODES not in thermostat.attributes
+ with pytest.raises(HomeAssistantError) as e_info:
await common.async_set_temperature(hass, temperature=24.0)
await hass.async_block_till_done()
+ assert "temperature" in str(e_info)
+ assert "climate.my_thermostat" in str(e_info)
+ assert "24.0" in str(e_info)
+ assert "ThermostatHvac" in str(e_info)
+ assert "ThermostatMode" in str(e_info)
assert thermostat.attributes[ATTR_TEMPERATURE] is None
|
codereview_new_python_data_9720
|
def __init__(
async def stream_source(self) -> str:
"""Return the stream source."""
url = URL(self._mjpeg_url)
- if self._username and self._password:
url = url.with_user(self._username)
url = url.with_password(self._password)
return str(url)
```suggestion
if self._username:
url = url.with_user(self._username)
if self._password:
url = url.with_password(self._password)
```
def __init__(
async def stream_source(self) -> str:
"""Return the stream source."""
url = URL(self._mjpeg_url)
+ if self._username:
url = url.with_user(self._username)
+ if self._password:
url = url.with_password(self._password)
return str(url)
|
codereview_new_python_data_9721
|
async def test_setup_success(
await hass.config_entries.async_unload(entries[0].entry_id)
await hass.async_block_till_done()
- assert not hass.services.async_services().get(DOMAIN, {})
@pytest.mark.parametrize("expires_at", [time.time() - 3600], ids=["expired"])
I think this is equivalent:
```suggestion
assert not hass.services.async_services().get(DOMAIN)
```
async def test_setup_success(
await hass.config_entries.async_unload(entries[0].entry_id)
await hass.async_block_till_done()
+ assert not hass.services.async_services().get(DOMAIN)
@pytest.mark.parametrize("expires_at", [time.time() - 3600], ids=["expired"])
|
codereview_new_python_data_9722
|
async def test_reauth(
calls: int,
access_token: str,
) -> None:
- """Test the reauthentication case updates the correct config entry. Make sure we abort if the user selects the wrong account on the consent screen."""
config_entry.add_to_hass(hass)
config_entry.async_start_reauth(hass)
The first line of the docstring is the header. It should have a single sentence. Further sentences can follow in the body. The header and body should be separated with a blank line. Maximum length of docstring lines are 72 characters according to PEP8.
async def test_reauth(
calls: int,
access_token: str,
) -> None:
+ """Test the re-authentication case updates the correct config entry.
+
+ Make sure we abort if the user selects the
+ wrong account on the consent screen.
+ """
config_entry.add_to_hass(hass)
config_entry.async_start_reauth(hass)
|
codereview_new_python_data_9723
|
def outlet() -> dict[str, Any]:
@pytest.fixture
-def socket(outlet) -> Socket:
"""Return socket."""
device = Device(outlet)
socket_control = device.socket_control
For the sake of consistency with the other functions in this file:
```suggestion
def socket(outlet: dict[str, Any]) -> Socket:
```
def outlet() -> dict[str, Any]:
@pytest.fixture
+def socket(outlet: dict[str, Any]) -> Socket:
"""Return socket."""
device = Device(outlet)
socket_control = device.socket_control
|
codereview_new_python_data_9724
|
async def async_setup_platform(
[
GeniusClimateZone(broker, z)
for z in broker.client.zone_objs
- if 'type' in z.data and z.data["type"] in GH_ZONES
]
)
This will fail CI. Does this work?
```suggestion
if z.data.get("type") in GH_ZONES
```
async def async_setup_platform(
[
GeniusClimateZone(broker, z)
for z in broker.client.zone_objs
+ if z.data.get("type") in GH_ZONES
]
)
|
codereview_new_python_data_9725
|
async def async_setup_platform(
[
GeniusWaterHeater(broker, z)
for z in broker.client.zone_objs
- if 'type' in z.data and z.data["type"] in GH_HEATERS
]
)
```suggestion
if z.data.get("type") in GH_HEATERS
```
async def async_setup_platform(
[
GeniusWaterHeater(broker, z)
for z in broker.client.zone_objs
+ if z.data.get("type") in GH_HEATERS
]
)
|
codereview_new_python_data_9726
|
async def test_init_ignores_tolerance(hass, setup_comp_3):
await hass.async_block_till_done()
assert len(calls) == 1
call = calls[0]
- assert HASS_DOMAIN == call.domain
- assert SERVICE_TURN_OFF == call.service
- assert ENT_SWITCH == call.data["entity_id"]
async def test_humidity_change_dry_off_within_tolerance(hass, setup_comp_3):
Does it not work on constants?
```suggestion
assert call.domain == HASS_DOMAIN
assert call.service == SERVICE_TURN_OFF
```
async def test_init_ignores_tolerance(hass, setup_comp_3):
await hass.async_block_till_done()
assert len(calls) == 1
call = calls[0]
+ assert call.domain == HASS_DOMAIN
+ assert call.service == SERVICE_TURN_OFF
+ assert call.data["entity_id"] == ENT_SWITCH
async def test_humidity_change_dry_off_within_tolerance(hass, setup_comp_3):
|
codereview_new_python_data_9727
|
async def test_form(hass: HomeAssistant) -> None:
assert len(mock_setup_entry.mock_calls) == 1
-async def test_options(hass: HomeAssistant, mock_config_entry) -> None:
"""Test the options form."""
options_flow = await hass.config_entries.options.async_init(
mock_config_entry.entry_id
Please set up the config entry before starting the options flow to ensure that the config flow module is loaded.
async def test_form(hass: HomeAssistant) -> None:
assert len(mock_setup_entry.mock_calls) == 1
+async def test_options(
+ hass: HomeAssistant, mock_config_entry, mock_init_component
+) -> None:
"""Test the options form."""
options_flow = await hass.config_entries.options.async_init(
mock_config_entry.entry_id
|
codereview_new_python_data_9728
|
async def test_switch_handles_requesterror(
async def test_switch_handles_disablederror(
hass, mock_config_entry_data, mock_config_entry
):
- """Test entity pytest.raises HomeAssistantError when Disabled was raised."""
api = get_mock_device(product_type="HWE-SKT", firmware_version="3.02")
api.state = AsyncMock(
There are some more of these.
```suggestion
"""Test entity raises HomeAssistantError when Disabled was raised."""
```
async def test_switch_handles_requesterror(
async def test_switch_handles_disablederror(
hass, mock_config_entry_data, mock_config_entry
):
+ """Test entity raises HomeAssistantError when Disabled was raised."""
api = get_mock_device(product_type="HWE-SKT", firmware_version="3.02")
api.state = AsyncMock(
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.