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...
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 ```su...
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.uni...
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_s...
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_s...
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._con...
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 asy...
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(), - ...
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 g...
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...
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._m...
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 "...
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"), - metho...
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}_...
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) a...
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 chang...
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 ...
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() as...
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...
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 ...
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: -...
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_re...
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 for...
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...
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", "has...
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 the...
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 conf...
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"), ...
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 parameteriz...
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", [{integr...
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...
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 t...
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: ...
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 automatica...
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.st...
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:...
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 ```...
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...
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://": ...
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 ...
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: ...
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 - ) ...
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 Senso...
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 d...
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, Pl...
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_creat...
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_creat...
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 ...
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 - ...
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 tim...
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_...
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_...
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...
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): - ...
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): """R...
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/UnitO...
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_int...
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....
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_flag...
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 Upd...
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...
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_disc...
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...
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 ther...
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 = 16...
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 = vol...
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 ...
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, devic...
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( - [ - ReolinkNumber...
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", - "a...
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 V...
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/precisio...
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...
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...
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_CL...
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_STAT...
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...
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 = Mes...
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 nee...
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): #...
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 ...
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 - ...
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 - ...
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 ...
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_c...
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_c...
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 ...
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...
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() asser...
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) ```sugge...
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: ```sug...
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 f...
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: ```...
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 ``` ...
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(...
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_dr...
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 Pleas...
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.sta...