ronantakizawa/codereview-bench huggingface dataset:
Repository: home-assistant/core
File: homeassistant/components/waterfurnace/sensor.py (Python)

Code before:
        self.entity_id = ENTITY_ID_FORMAT.format(
            f"wf_{slugify(coordinator.unit)}_{slugify(description.key)}"
        )
        self._attr_unique_id = f"{coordinator.unit}_{description.key}"

        device_info = DeviceInfo(
            identifiers={(DOMAIN, self.coordinator.unit)},
            manufacturer="WaterFurnace",
            name="WaterFurnace System",
        )

        if self.coordinator.device_metadata:
            if self.coordinator.device_metadata.description:
                # Eg. Series 7
                device_info["model"] = self.coordinator.device_metadata.description
            if self.coordinator.device_metadata.awlabctypedesc:
                # Eg. Series 7, 5 Ton
                device_info["name"] = self.coordinator.device_metadata.awlabctypedesc

        self._attr_device_info = device_info

    @property
    def native_value(self):
        """Return the native value of the sensor."""
        if self.coordinator.data is None:
            return None
        return getattr(self.coordinator.data, self.entity_description.key, None)


Review comment (suggestion):
when you did config entry first refresh this wouldn't be needed, as when data is `None`, the entity would be unavailable and native_value wouldn't be queried

Code after:
    ),
    SensorEntityDescription(
        key="waterflowrate",
        translation_key="water_flow_rate",
        native_unit_of_measurement=UnitOfVolumeFlowRate.GALLONS_PER_MINUTE,
        device_class=SensorDeviceClass.VOLUME_FLOW_RATE,
        state_class=SensorStateClass.MEASUREMENT,
    ),
]


async def async_setup_entry(
    hass: HomeAssistant,
    config_entry: WaterFurnaceConfigEntry,
    async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
    """Set up Waterfurnace sensors from a config entry."""
    coordinator = config_entry.runtime_data

    async_add_entities(
        WaterFurnaceSensor(coordinator, description) for description in SENSORS
    )


class WaterFurnaceSensor(CoordinatorEntity[WaterFurnaceCoordinator], SensorEntity):
    """Implementing the Waterfurnace sensor."""

    entity_description: SensorEntityDescription
    _attr_should_poll = False
    _attr_has_entity_name = True

    def __init__(
        self, coordinator: WaterFurnaceCoordinator, description: SensorEntityDescription
    ) -> None:
        """Initialize the sensor."""
        super().__init__(coordinator)
        self.entity_description = description

        # This ensures that the sensors are isolated per waterfurnace unit
        self.entity_id = ENTITY_ID_FORMAT.format(
            f"wf_{slugify(coordinator.unit)}_{slugify(description.key)}"
        )
        self._attr_unique_id = f"{coordinator.unit}_{description.key}"

        device_info = DeviceInfo(
            identifiers={(DOMAIN, coordinator.unit)},
            manufacturer="WaterFurnace",
            name="WaterFurnace System",
        )

        if coordinator.device_metadata:
Repository: home-assistant/core
File: homeassistant/components/waterfurnace/sensor.py (Python)

Code before:

    entity_description: SensorEntityDescription
    _attr_should_poll = False
    _attr_has_entity_name = True

    def __init__(
        self, coordinator: WaterFurnaceCoordinator, description: SensorEntityDescription
    ) -> None:
        """Initialize the sensor."""
        super().__init__(coordinator)
        self.entity_description = description

        # This ensures that the sensors are isolated per waterfurnace unit
        self.entity_id = ENTITY_ID_FORMAT.format(
            f"wf_{slugify(coordinator.unit)}_{slugify(description.key)}"
        )
        self._attr_unique_id = f"{coordinator.unit}_{description.key}"

        device_info = DeviceInfo(
            identifiers={(DOMAIN, self.coordinator.unit)},
            manufacturer="WaterFurnace",
            name="WaterFurnace System",
        )

        if self.coordinator.device_metadata:
            if self.coordinator.device_metadata.description:
                # Eg. Series 7
                device_info["model"] = self.coordinator.device_metadata.description
            if self.coordinator.device_metadata.awlabctypedesc:
                # Eg. Series 7, 5 Ton
                device_info["name"] = self.coordinator.device_metadata.awlabctypedesc

        self._attr_device_info = device_info

    @property
    def native_value(self):
        """Return the native value of the sensor."""
        return getattr(self.coordinator.data, self.entity_description.key, None)


Review comment (suggestion):
```suggestion
        if coordinator.device_metadata:
            if coordinator.device_metadata.description:
```

Code after:

    entity_description: SensorEntityDescription
    _attr_should_poll = False
    _attr_has_entity_name = True

    def __init__(
        self, coordinator: WaterFurnaceCoordinator, description: SensorEntityDescription
    ) -> None:
        """Initialize the sensor."""
        super().__init__(coordinator)
        self.entity_description = description

        # This ensures that the sensors are isolated per waterfurnace unit
        self.entity_id = ENTITY_ID_FORMAT.format(
            f"wf_{slugify(coordinator.unit)}_{slugify(description.key)}"
        )
        self._attr_unique_id = f"{coordinator.unit}_{description.key}"

        device_info = DeviceInfo(
            identifiers={(DOMAIN, coordinator.unit)},
            manufacturer="WaterFurnace",
            name="WaterFurnace System",
        )

        if coordinator.device_metadata:
            if coordinator.device_metadata.description:
                # Eg. Series 7
                device_info["model"] = coordinator.device_metadata.description
            if coordinator.device_metadata.awlabctypedesc:
                # Eg. Series 7, 5 Ton
                device_info["name"] = coordinator.device_metadata.awlabctypedesc

        self._attr_device_info = device_info

    @property
    def native_value(self):
        """Return the native value of the sensor."""
        return getattr(self.coordinator.data, self.entity_description.key, None)
Repository: home-assistant/core
File: homeassistant/components/waterfurnace/sensor.py (Python)

Code before:
        self, coordinator: WaterFurnaceCoordinator, description: SensorEntityDescription
    ) -> None:
        """Initialize the sensor."""
        super().__init__(coordinator)
        self.entity_description = description

        # This ensures that the sensors are isolated per waterfurnace unit
        self.entity_id = ENTITY_ID_FORMAT.format(
            f"wf_{slugify(coordinator.unit)}_{slugify(description.key)}"
        )
        self._attr_unique_id = f"{coordinator.unit}_{description.key}"

        device_info = DeviceInfo(
            identifiers={(DOMAIN, self.coordinator.unit)},
            manufacturer="WaterFurnace",
            name="WaterFurnace System",
        )

        if self.coordinator.device_metadata:
            if self.coordinator.device_metadata.description:
                # Eg. Series 7
                device_info["model"] = self.coordinator.device_metadata.description
            if self.coordinator.device_metadata.awlabctypedesc:
                # Eg. Series 7, 5 Ton
                device_info["name"] = self.coordinator.device_metadata.awlabctypedesc

        self._attr_device_info = device_info

    @property
    def native_value(self):
        """Return the native value of the sensor."""
        return getattr(self.coordinator.data, self.entity_description.key, None)


Review comment (suggestion):
```suggestion
                device_info["model"] = coordinator.device_metadata.description
            if coordinator.device_metadata.awlabctypedesc:
                # Eg. Series 7, 5 Ton
                device_info["name"] = coordinator.device_metadata.awlabctypedesc

```

Code after:
        self, coordinator: WaterFurnaceCoordinator, description: SensorEntityDescription
    ) -> None:
        """Initialize the sensor."""
        super().__init__(coordinator)
        self.entity_description = description

        # This ensures that the sensors are isolated per waterfurnace unit
        self.entity_id = ENTITY_ID_FORMAT.format(
            f"wf_{slugify(coordinator.unit)}_{slugify(description.key)}"
        )
        self._attr_unique_id = f"{coordinator.unit}_{description.key}"

        device_info = DeviceInfo(
            identifiers={(DOMAIN, coordinator.unit)},
            manufacturer="WaterFurnace",
            name="WaterFurnace System",
        )

        if coordinator.device_metadata:
            if coordinator.device_metadata.description:
                # Eg. Series 7
                device_info["model"] = coordinator.device_metadata.description
            if coordinator.device_metadata.awlabctypedesc:
                # Eg. Series 7, 5 Ton
                device_info["name"] = coordinator.device_metadata.awlabctypedesc

        self._attr_device_info = device_info

    @property
    def native_value(self):
        """Return the native value of the sensor."""
        return getattr(self.coordinator.data, self.entity_description.key, None)
Repository: home-assistant/core
File: homeassistant/components/waterfurnace/sensor.py (Python)

Code before:
    _attr_has_entity_name = True

    def __init__(
        self, coordinator: WaterFurnaceCoordinator, description: SensorEntityDescription
    ) -> None:
        """Initialize the sensor."""
        super().__init__(coordinator)
        self.entity_description = description

        # This ensures that the sensors are isolated per waterfurnace unit
        self.entity_id = ENTITY_ID_FORMAT.format(
            f"wf_{slugify(coordinator.unit)}_{slugify(description.key)}"
        )
        self._attr_unique_id = f"{coordinator.unit}_{description.key}"

        device_info = DeviceInfo(
            identifiers={(DOMAIN, coordinator.unit)},
            manufacturer="WaterFurnace",
            name="WaterFurnace System",
        )

        if coordinator.device_metadata:
            if coordinator.device_metadata.description:
                # Eg. Series 7
                device_info["model"] = self.coordinator.device_metadata.description
            if self.coordinator.device_metadata.awlabctypedesc:
                # Eg. Series 7, 5 Ton
                device_info["name"] = self.coordinator.device_metadata.awlabctypedesc

        self._attr_device_info = device_info

    @property
    def native_value(self):
        """Return the native value of the sensor."""
        return getattr(self.coordinator.data, self.entity_description.key, None)


Review comment (suggestion):
```suggestion
                device_info["model"] = coordinator.device_metadata.description
            if coordinator.device_metadata.awlabctypedesc:
```

Code after:
    _attr_has_entity_name = True

    def __init__(
        self, coordinator: WaterFurnaceCoordinator, description: SensorEntityDescription
    ) -> None:
        """Initialize the sensor."""
        super().__init__(coordinator)
        self.entity_description = description

        # This ensures that the sensors are isolated per waterfurnace unit
        self.entity_id = ENTITY_ID_FORMAT.format(
            f"wf_{slugify(coordinator.unit)}_{slugify(description.key)}"
        )
        self._attr_unique_id = f"{coordinator.unit}_{description.key}"

        device_info = DeviceInfo(
            identifiers={(DOMAIN, coordinator.unit)},
            manufacturer="WaterFurnace",
            name="WaterFurnace System",
        )

        if coordinator.device_metadata:
            if coordinator.device_metadata.description:
                # Eg. Series 7
                device_info["model"] = coordinator.device_metadata.description
            if coordinator.device_metadata.awlabctypedesc:
                # Eg. Series 7, 5 Ton
                device_info["name"] = coordinator.device_metadata.awlabctypedesc

        self._attr_device_info = device_info

    @property
    def native_value(self):
        """Return the native value of the sensor."""
        return getattr(self.coordinator.data, self.entity_description.key, None)
Repository: home-assistant/core
File: homeassistant/components/waterfurnace/sensor.py (Python)

Code before:
    def __init__(
        self, coordinator: WaterFurnaceCoordinator, description: SensorEntityDescription
    ) -> None:
        """Initialize the sensor."""
        super().__init__(coordinator)
        self.entity_description = description

        # This ensures that the sensors are isolated per waterfurnace unit
        self.entity_id = ENTITY_ID_FORMAT.format(
            f"wf_{slugify(coordinator.unit)}_{slugify(description.key)}"
        )
        self._attr_unique_id = f"{coordinator.unit}_{description.key}"

        device_info = DeviceInfo(
            identifiers={(DOMAIN, coordinator.unit)},
            manufacturer="WaterFurnace",
            name="WaterFurnace System",
        )

        if coordinator.device_metadata:
            if coordinator.device_metadata.description:
                # Eg. Series 7
                device_info["model"] = self.coordinator.device_metadata.description
            if self.coordinator.device_metadata.awlabctypedesc:
                # Eg. Series 7, 5 Ton
                device_info["name"] = self.coordinator.device_metadata.awlabctypedesc

        self._attr_device_info = device_info

    @property
    def native_value(self):
        """Return the native value of the sensor."""
        return getattr(self.coordinator.data, self.entity_description.key, None)


Review comment (suggestion):
```suggestion
                device_info["name"] = coordinator.device_metadata.awlabctypedesc
```

Code after:
    def __init__(
        self, coordinator: WaterFurnaceCoordinator, description: SensorEntityDescription
    ) -> None:
        """Initialize the sensor."""
        super().__init__(coordinator)
        self.entity_description = description

        # This ensures that the sensors are isolated per waterfurnace unit
        self.entity_id = ENTITY_ID_FORMAT.format(
            f"wf_{slugify(coordinator.unit)}_{slugify(description.key)}"
        )
        self._attr_unique_id = f"{coordinator.unit}_{description.key}"

        device_info = DeviceInfo(
            identifiers={(DOMAIN, coordinator.unit)},
            manufacturer="WaterFurnace",
            name="WaterFurnace System",
        )

        if coordinator.device_metadata:
            if coordinator.device_metadata.description:
                # Eg. Series 7
                device_info["model"] = coordinator.device_metadata.description
            if coordinator.device_metadata.awlabctypedesc:
                # Eg. Series 7, 5 Ton
                device_info["name"] = coordinator.device_metadata.awlabctypedesc

        self._attr_device_info = device_info

    @property
    def native_value(self):
        """Return the native value of the sensor."""
        return getattr(self.coordinator.data, self.entity_description.key, None)
Repository: home-assistant/core
File: homeassistant/components/dexcom/coordinator.py (Python)

Code before:
"""Coordinator for the Dexcom integration."""

from datetime import timedelta
import logging

from pydexcom import Dexcom, GlucoseReading

from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator

from .const import DOMAIN

_LOGGER = logging.getLogger(__name__)

_SCAN_INTERVAL = timedelta(seconds=180)

type DexcomConfigEntry = ConfigEntry[DexcomCoordinator]


class DexcomCoordinator(DataUpdateCoordinator[GlucoseReading]):
    """Dexcom Coordinator."""

    def __init__(
        self,
        hass: HomeAssistant,
        entry: DexcomConfigEntry,
        dexcom: Dexcom,
    ) -> None:
        """Initialize the coordinator."""
        super().__init__(
            hass,
            _LOGGER,
            config_entry=entry,
            name=DOMAIN,
            update_interval=_SCAN_INTERVAL,
        )
        self.dexcom = dexcom

    async def _async_update_data(self) -> GlucoseReading:
        """Fetch data from API endpoint."""
        return await self.hass.async_add_executor_job(
            self.dexcom.get_current_glucose_reading
        )


Review comment (bug):
why `| None`? If it returns None, did it actually fetch data or should we trigger UpdateFailed to indicate that there was no new data

Code after:
"""Coordinator for the Dexcom integration."""

from datetime import timedelta
import logging

from pydexcom import Dexcom, GlucoseReading

from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator

from .const import DOMAIN

_LOGGER = logging.getLogger(__name__)

_SCAN_INTERVAL = timedelta(seconds=180)

type DexcomConfigEntry = ConfigEntry[DexcomCoordinator]


class DexcomCoordinator(DataUpdateCoordinator[GlucoseReading | None]):
    """Dexcom Coordinator."""

    def __init__(
        self,
        hass: HomeAssistant,
        entry: DexcomConfigEntry,
        dexcom: Dexcom,
    ) -> None:
        """Initialize the coordinator."""
        super().__init__(
            hass,
            _LOGGER,
            config_entry=entry,
            name=DOMAIN,
            update_interval=_SCAN_INTERVAL,
        )
        self.dexcom = dexcom

    async def _async_update_data(self) -> GlucoseReading | None:
        """Fetch data from API endpoint."""
        return await self.hass.async_add_executor_job(
            self.dexcom.get_current_glucose_reading
        )
Repository: home-assistant/core
File: homeassistant/components/mastodon/services.py (Python)

Code before:
    ATTR_LANGUAGE,
    ATTR_MEDIA,
    ATTR_MEDIA_DESCRIPTION,
    ATTR_MEDIA_WARNING,
    ATTR_STATUS,
    ATTR_VISIBILITY,
    DOMAIN,
)
from .coordinator import MastodonConfigEntry
from .utils import get_media_type


class StatusVisibility(StrEnum):
    """StatusVisibility model."""

    PUBLIC = "public"
    UNLISTED = "unlisted"
    PRIVATE = "private"
    DIRECT = "direct"


SERVICE_GET_ACCOUNT = "get_account"
SERVICE_GET_ACCOUNT_SCHEMA = vol.Schema(
    {
        vol.Required(ATTR_CONFIG_ENTRY_ID): str,
        vol.Required("account_name"): str,
    }
)
SERVICE_POST = "post"
SERVICE_POST_SCHEMA = vol.Schema(
    {
        vol.Required(ATTR_CONFIG_ENTRY_ID): str,
        vol.Required(ATTR_STATUS): str,
        vol.Optional(ATTR_VISIBILITY): vol.In([x.lower() for x in StatusVisibility]),
        vol.Optional(ATTR_IDEMPOTENCY_KEY): str,
        vol.Optional(ATTR_CONTENT_WARNING): str,
        vol.Optional(ATTR_LANGUAGE): str,
        vol.Optional(ATTR_MEDIA): str,
        vol.Optional(ATTR_MEDIA_DESCRIPTION): str,
        vol.Optional(ATTR_MEDIA_WARNING): bool,
    }
)


def async_get_entry(hass: HomeAssistant, config_entry_id: str) -> MastodonConfigEntry:
    """Get the Mastodon config entry."""
    if not (entry := hass.config_entries.async_get_entry(config_entry_id)):
        raise ServiceValidationError(
            translation_domain=DOMAIN,
            translation_key="integration_not_found",
            translation_placeholders={"target": DOMAIN},

Review comment (suggestion):
```suggestion
        vol.Required(ATTR_ACCOUNT_NAME): str,
```
use a const for that

Code after:
    ATTR_IDEMPOTENCY_KEY,
    ATTR_LANGUAGE,
    ATTR_MEDIA,
    ATTR_MEDIA_DESCRIPTION,
    ATTR_MEDIA_WARNING,
    ATTR_STATUS,
    ATTR_VISIBILITY,
    DOMAIN,
)
from .coordinator import MastodonConfigEntry
from .utils import get_media_type


class StatusVisibility(StrEnum):
    """StatusVisibility model."""

    PUBLIC = "public"
    UNLISTED = "unlisted"
    PRIVATE = "private"
    DIRECT = "direct"


SERVICE_GET_ACCOUNT = "get_account"
SERVICE_GET_ACCOUNT_SCHEMA = vol.Schema(
    {
        vol.Required(ATTR_CONFIG_ENTRY_ID): str,
        vol.Required(ATTR_ACCOUNT_NAME): str,
    }
)
SERVICE_POST = "post"
SERVICE_POST_SCHEMA = vol.Schema(
    {
        vol.Required(ATTR_CONFIG_ENTRY_ID): str,
        vol.Required(ATTR_STATUS): str,
        vol.Optional(ATTR_VISIBILITY): vol.In([x.lower() for x in StatusVisibility]),
        vol.Optional(ATTR_IDEMPOTENCY_KEY): str,
        vol.Optional(ATTR_CONTENT_WARNING): str,
        vol.Optional(ATTR_LANGUAGE): str,
        vol.Optional(ATTR_MEDIA): str,
        vol.Optional(ATTR_MEDIA_DESCRIPTION): str,
        vol.Optional(ATTR_MEDIA_WARNING): bool,
    }
)


@callback
def async_setup_services(hass: HomeAssistant) -> None:
    """Set up the services for the Mastodon integration."""
    hass.services.async_register(
        DOMAIN,
        SERVICE_GET_ACCOUNT,
Repository: home-assistant/core
File: tests/components/teslemetry/conftest.py (Python)

Code before:
"""Test fixtures for Teslemetry component.

Test naming conventions:
- `test_*`: Standard tests using default VEHICLE_DATA and METADATA fixtures
- `test_*_alt`: Tests using VEHICLE_DATA_ALT fixture data to verify entity
  behavior with alternative vehicle state values (different charge levels,
  door states, climate settings, etc.)
- `test_*_noscope`: Tests using METADATA_NOSCOPE fixture data to verify
  behavior with limited API scopes (only openid, offline_access, and
  vehicle_device_data scopes available). This tests graceful handling when
  the user hasn't granted full API permissions.
- `test_*_streaming`: Tests that verify real-time streaming updates from
  the Teslemetry websocket connection and state restoration after reload.
"""

from __future__ import annotations

from collections.abc import Generator
from copy import deepcopy
from typing import Any
from unittest.mock import AsyncMock, patch

import pytest
from teslemetry_stream.stream import recursive_match

from homeassistant.components.teslemetry.const import TOKEN_URL

from .const import (
    COMMAND_OK,
    ENERGY_HISTORY,
    LIVE_STATUS,
    METADATA,
    METADATA_LEGACY,
    PRODUCTS,
    SITE_INFO,
    VEHICLE_DATA,
    WAKE_UP_ONLINE,
)


Review comment (suggestion):
```suggestion
"""Test fixtures for Teslemetry component."""
```

Code after:
"""Test fixtures for Teslemetry component."""

from __future__ import annotations

from collections.abc import Generator
from copy import deepcopy
from typing import Any
from unittest.mock import AsyncMock, patch

import pytest
from teslemetry_stream.stream import recursive_match

from homeassistant.components.teslemetry.const import TOKEN_URL

from .const import (
    COMMAND_OK,
    ENERGY_HISTORY,
    LIVE_STATUS,
    METADATA,
    METADATA_LEGACY,
    PRODUCTS,
    SITE_INFO,
    VEHICLE_DATA,
    WAKE_UP_ONLINE,
)

from tests.test_util.aiohttp import AiohttpClientMocker


@pytest.fixture
def mock_setup_entry():
    """Mock Teslemetry async_setup_entry method."""
    with patch(
        "homeassistant.components.teslemetry.async_setup_entry", return_value=True
    ) as mock_async_setup_entry:
        yield mock_async_setup_entry


@pytest.fixture