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

Code before:
"""Config flow for OpenEVSE integration."""

import openevsewifi
import voluptuous as vol

from homeassistant import config_entries
from homeassistant.const import CONF_HOST

from .const import DOMAIN


class OpenEVSEConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
    """OpenEVSE config flow."""

    VERSION = 1
    MINOR_VERSION = 1

    async def check_status(self, host: str) -> bool:
        """Check if we can connect to the OpenEVSE charger."""

        try:
            charger = openevsewifi.Charger(host)
            result = await self.hass.async_add_executor_job(charger.getStatus)
        except AttributeError:
            return False
        else:
            return result is not None

    async def async_step_user(self, user_input=None) -> config_entries.ConfigFlowResult:
        """Handle the initial step."""

        if user_input is not None:
            await self.async_set_unique_id(user_input[CONF_HOST])
            self._abort_if_unique_id_configured()

            if not await self.check_status(user_input[CONF_HOST]):
                return self.async_show_form(
                    step_id="user",
                    data_schema=vol.Schema({vol.Required(CONF_HOST): str}),
                    errors={CONF_HOST: "cannot_connect"},
                )

            return self.async_create_entry(
                title=f"OpenEVSE {user_input[CONF_HOST]}",
                data={
                    CONF_HOST: user_input[CONF_HOST],
                },
            )
        return self.async_show_form(
            step_id="user", data_schema=vol.Schema({vol.Required(CONF_HOST): str})
        )

    async def async_step_import(self, data) -> config_entries.ConfigFlowResult:
        """Handle the initial step."""

        return self.async_create_entry(
            title=f"OpenEVSE {data[CONF_HOST]}",
            data={
                CONF_HOST: data[CONF_HOST],
            },
        )


Review comment (suggestion):
We should also try to validate the connection during import, because if the config doesn't work (maybe the user doesn't have this device anymore), we should not just import it.

Code after:

            if await self.check_status(user_input[CONF_HOST]):
                return self.async_create_entry(
                    title=f"OpenEVSE {user_input[CONF_HOST]}",
                    data=user_input,
                )
            errors = {CONF_HOST: "cannot_connect"}

        return self.async_show_form(
            step_id="user",
            data_schema=vol.Schema({vol.Required(CONF_HOST): str}),
            errors=errors,
        )

    async def async_step_import(self, data: dict[str, str]) -> ConfigFlowResult:
        """Handle the initial step."""

        self._async_abort_entries_match({CONF_HOST: data[CONF_HOST]})

        if not await self.check_status(data[CONF_HOST]):
            return self.async_abort(reason="unavailable_host")

        return self.async_create_entry(
            title=f"OpenEVSE {data[CONF_HOST]}",
            data=data,
        )
Repository: home-assistant/core
File: tests/components/openevse/conftest.py (Python)

Code before:
"""Test Fixtures for the OpenEVSE tests."""

from collections.abc import Generator
from unittest.mock import AsyncMock, MagicMock, patch

import pytest

from homeassistant.const import CONF_HOST

from tests.common import MockConfigEntry


@pytest.fixture
def mock_charger():
    """Create a mock OpenEVSE charger."""
    with patch(
        "homeassistant.components.openevse.config_flow.openevsewifi.Charger"
    ) as mock:
        charger = MagicMock()
        charger.getStatus.return_value = "Charging"
        charger.getChargeTimeElapsed.return_value = 3600  # 60 minutes in seconds
        charger.getAmbientTemperature.return_value = 25.5
        charger.getIRTemperature.return_value = 30.2
        charger.getRTCTemperature.return_value = 28.7
        charger.getUsageSession.return_value = 15000  # 15 kWh in Wh
        charger.getUsageTotal.return_value = 500000  # 500 kWh in Wh
        charger.charging_current = 32.0
        mock.return_value = charger
        yield charger


@pytest.fixture
def mock_bad_charger():
    """Create a mock OpenEVSE charger."""
    with patch(
        "homeassistant.components.openevse.config_flow.openevsewifi.Charger"
    ) as mock:
        charger = MagicMock()
        charger.getStatus.side_effect = AttributeError

Review comment (suggestion):
```suggestion
def mock_charger() -> Generator[AsyncMock]:
```

Code after:
"""Test Fixtures for the OpenEVSE tests."""

from collections.abc import Generator
from unittest.mock import AsyncMock, MagicMock, patch

import pytest

from homeassistant.components.openevse.const import DOMAIN
from homeassistant.const import CONF_HOST

from tests.common import MockConfigEntry


@pytest.fixture
def mock_charger() -> Generator[MagicMock]:
    """Create a mock OpenEVSE charger."""
    with (
        patch(
            "homeassistant.components.openevse.openevsewifi.Charger",
            autospec=True,
        ) as mock,
        patch(
            "homeassistant.components.openevse.config_flow.openevsewifi.Charger",
            new=mock,
        ),
    ):
        charger = mock.return_value
        charger.getStatus.return_value = "Charging"
        charger.getChargeTimeElapsed.return_value = 3600  # 60 minutes in seconds
        charger.getAmbientTemperature.return_value = 25.5
        charger.getIRTemperature.return_value = 30.2
        charger.getRTCTemperature.return_value = 28.7
        charger.getUsageSession.return_value = 15000  # 15 kWh in Wh
        charger.getUsageTotal.return_value = 500000  # 500 kWh in Wh
        charger.charging_current = 32.0
        yield charger


@pytest.fixture
Repository: home-assistant/core
File: tests/components/openevse/conftest.py (Python)

Code before:
"""Test Fixtures for the OpenEVSE tests."""

from collections.abc import Generator
from unittest.mock import AsyncMock, MagicMock, patch

import pytest

from homeassistant.const import CONF_HOST

from tests.common import MockConfigEntry


@pytest.fixture
def mock_charger():
    """Create a mock OpenEVSE charger."""
    with patch(
        "homeassistant.components.openevse.config_flow.openevsewifi.Charger"
    ) as mock:
        charger = MagicMock()
        charger.getStatus.return_value = "Charging"
        charger.getChargeTimeElapsed.return_value = 3600  # 60 minutes in seconds
        charger.getAmbientTemperature.return_value = 25.5
        charger.getIRTemperature.return_value = 30.2
        charger.getRTCTemperature.return_value = 28.7
        charger.getUsageSession.return_value = 15000  # 15 kWh in Wh
        charger.getUsageTotal.return_value = 500000  # 500 kWh in Wh
        charger.charging_current = 32.0
        mock.return_value = charger
        yield charger


@pytest.fixture
def mock_bad_charger():
    """Create a mock OpenEVSE charger."""
    with patch(
        "homeassistant.components.openevse.config_flow.openevsewifi.Charger"
    ) as mock:
        charger = MagicMock()
        charger.getStatus.side_effect = AttributeError
        mock.return_value = charger
        yield charger


@pytest.fixture

Review comment (suggestion):
```suggestion
    with patch(
        "homeassistant.components.openevse.config_flow.openevsewifi.Charger", autospec=True
    ) as mock:
        charger = mock.return_value
```

Code after:
"""Test Fixtures for the OpenEVSE tests."""

from collections.abc import Generator
from unittest.mock import AsyncMock, MagicMock, patch

import pytest

from homeassistant.components.openevse.const import DOMAIN
from homeassistant.const import CONF_HOST

from tests.common import MockConfigEntry


@pytest.fixture
def mock_charger() -> Generator[MagicMock]:
    """Create a mock OpenEVSE charger."""
    with (
        patch(
            "homeassistant.components.openevse.openevsewifi.Charger",
            autospec=True,
        ) as mock,
        patch(
            "homeassistant.components.openevse.config_flow.openevsewifi.Charger",
            new=mock,
        ),
    ):
        charger = mock.return_value
        charger.getStatus.return_value = "Charging"
        charger.getChargeTimeElapsed.return_value = 3600  # 60 minutes in seconds
        charger.getAmbientTemperature.return_value = 25.5
        charger.getIRTemperature.return_value = 30.2
        charger.getRTCTemperature.return_value = 28.7
        charger.getUsageSession.return_value = 15000  # 15 kWh in Wh
        charger.getUsageTotal.return_value = 500000  # 500 kWh in Wh
        charger.charging_current = 32.0
        yield charger


@pytest.fixture
def mock_setup_entry() -> Generator[AsyncMock]:
    """Mock setting up a config entry."""
    with patch(
        "homeassistant.components.openevse.async_setup_entry", return_value=True
    ) as mock_setup_entry:
Repository: home-assistant/core
File: tests/components/openevse/conftest.py (Python)

Code before:
        mock.return_value = charger
        yield charger


@pytest.fixture
def mock_bad_charger():
    """Create a mock OpenEVSE charger."""
    with patch(
        "homeassistant.components.openevse.config_flow.openevsewifi.Charger"
    ) as mock:
        charger = MagicMock()
        charger.getStatus.side_effect = AttributeError
        mock.return_value = charger
        yield charger


@pytest.fixture
def mock_flaky_charger():
    """Create a mock OpenEVSE charger."""
    with patch(
        "homeassistant.components.openevse.config_flow.openevsewifi.Charger"
    ) as mock:
        charger = MagicMock()
        charger.getStatus.side_effect = [AttributeError, "Charging"]
        mock.return_value = charger
        yield charger


@pytest.fixture
def mock_setup_entry() -> Generator[AsyncMock]:
    """Mock setting up a config entry."""
    with patch(
        "homeassistant.components.openevse.async_setup_entry", return_value=True
    ) as mock_setup_entry:
        yield mock_setup_entry


@pytest.fixture
def mock_config_entry():
    """Create a mock config entry."""
    return MockConfigEntry(
        domain="openevse",
        data={CONF_HOST: "192.168.1.100"},
        unique_id="192.168.1.100",
    )


Review comment (suggestion):
As during testing we sometimes need to repatch, I generally just opt to add side_effects inline as that is more flexible.

It'd just be a 

```py
mock_charger.getStatus.side_effect = AttributeError
```

Code after:
        charger.getStatus.return_value = "Charging"
        charger.getChargeTimeElapsed.return_value = 3600  # 60 minutes in seconds
        charger.getAmbientTemperature.return_value = 25.5
        charger.getIRTemperature.return_value = 30.2
        charger.getRTCTemperature.return_value = 28.7
        charger.getUsageSession.return_value = 15000  # 15 kWh in Wh
        charger.getUsageTotal.return_value = 500000  # 500 kWh in Wh
        charger.charging_current = 32.0
        yield charger


@pytest.fixture
def mock_setup_entry() -> Generator[AsyncMock]:
    """Mock setting up a config entry."""
    with patch(
        "homeassistant.components.openevse.async_setup_entry", return_value=True
    ) as mock_setup_entry:
        yield mock_setup_entry


@pytest.fixture
def mock_config_entry() -> MockConfigEntry:
    """Create a mock config entry."""
    return MockConfigEntry(
        domain=DOMAIN, data={CONF_HOST: "192.168.1.100"}, entry_id="FAKE"
    )
Repository: home-assistant/core
File: homeassistant/components/esphome/water_heater.py (Python)

Code before:
"""Support for ESPHome water heaters."""

from __future__ import annotations

from typing import Any, cast

from aioesphomeapi import WaterHeaterInfo, WaterHeaterMode, WaterHeaterState

from homeassistant.components.water_heater import (
    WaterHeaterEntity,
    WaterHeaterEntityFeature,
)
from homeassistant.const import ATTR_TEMPERATURE, PRECISION_TENTHS, UnitOfTemperature
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback

from .entity import (
    EsphomeEntity,
    EsphomeEnumMapper,
    convert_api_error_ha_error,
    esphome_float_state_property,
    esphome_state_property,
    platform_async_setup_entry,
)
from .entry_data import ESPHomeConfigEntry, RuntimeEntryData

PARALLEL_UPDATES = 0


async def async_setup_entry(
    hass: HomeAssistant,
    entry: ESPHomeConfigEntry,
    async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
    """Set up ESPHome water heaters based on a config entry."""
    await platform_async_setup_entry(
        hass,
        entry,
        async_add_entities,
        info_type=WaterHeaterInfo,
        entity_type=EsphomeWaterHeater,
        state_type=WaterHeaterState,
    )


Review comment (suggestion):
import from
```
from .enum_mapper import EsphomeEnumMapper 
```

Code after:
"""Support for ESPHome water heaters."""

from __future__ import annotations

from functools import partial
from typing import Any

from aioesphomeapi import EntityInfo, WaterHeaterInfo, WaterHeaterMode, WaterHeaterState

from homeassistant.components.water_heater import (
    WaterHeaterEntity,
    WaterHeaterEntityFeature,
)
from homeassistant.const import ATTR_TEMPERATURE, PRECISION_TENTHS, UnitOfTemperature
from homeassistant.core import callback

from .entity import (
    EsphomeEntity,
    convert_api_error_ha_error,
    esphome_float_state_property,
    esphome_state_property,
    platform_async_setup_entry,
)
from .enum_mapper import EsphomeEnumMapper

PARALLEL_UPDATES = 0


_WATER_HEATER_MODES: EsphomeEnumMapper[WaterHeaterMode, str] = EsphomeEnumMapper(
    {
        WaterHeaterMode.OFF: "off",
        WaterHeaterMode.ECO: "eco",
        WaterHeaterMode.ELECTRIC: "electric",
        WaterHeaterMode.PERFORMANCE: "performance",
        WaterHeaterMode.HIGH_DEMAND: "high_demand",
        WaterHeaterMode.HEAT_PUMP: "heat_pump",
        WaterHeaterMode.GAS: "gas",
    }
)


class EsphomeWaterHeater(
    EsphomeEntity[WaterHeaterInfo, WaterHeaterState], WaterHeaterEntity
):
Repository: home-assistant/core
File: homeassistant/components/sensor/const.py (Python)

Code before:
    IRRADIANCE = "irradiance"
    """Irradiance.

    Unit of measurement:
    - SI / metric: `W/m²`
    - USCS / imperial: `BTU/(h⋅ft²)`
    """

    MOISTURE = "moisture"
    """Moisture.

    Unit of measurement: `%`
    """

    MONETARY = "monetary"
    """Amount of money.

    Unit of measurement: ISO4217 currency code

    See https://en.wikipedia.org/wiki/ISO_4217#Active_codes for active codes
    """

    NITROGEN_DIOXIDE = "nitrogen_dioxide"
    """Amount of NO2.

    Unit of measurement: `ppb` (parts per billion),`μg/m³`
    """

    NITROGEN_MONOXIDE = "nitrogen_monoxide"
    """Amount of NO.

    Unit of measurement: `μg/m³`
    """

    NITROUS_OXIDE = "nitrous_oxide"
    """Amount of N2O.

    Unit of measurement: `μg/m³`
    """

    OZONE = "ozone"
    """Amount of O3.

    Unit of measurement: `μg/m³`
    """

    PH = "ph"
    """Potential hydrogen (acidity/alkalinity).

    Unit of measurement: Unitless
    """

Review comment (suggestion):
```suggestion
    Unit of measurement: `ppb` (parts per billion), `μg/m³`
```

Code after:

    IRRADIANCE = "irradiance"
    """Irradiance.

    Unit of measurement:
    - SI / metric: `W/m²`
    - USCS / imperial: `BTU/(h⋅ft²)`
    """

    MOISTURE = "moisture"
    """Moisture.

    Unit of measurement: `%`
    """

    MONETARY = "monetary"
    """Amount of money.

    Unit of measurement: ISO4217 currency code

    See https://en.wikipedia.org/wiki/ISO_4217#Active_codes for active codes
    """

    NITROGEN_DIOXIDE = "nitrogen_dioxide"
    """Amount of NO2.

    Unit of measurement: `ppb` (parts per billion), `μg/m³`
    """

    NITROGEN_MONOXIDE = "nitrogen_monoxide"
    """Amount of NO.

    Unit of measurement: `μg/m³`
    """

    NITROUS_OXIDE = "nitrous_oxide"
    """Amount of N2O.

    Unit of measurement: `μg/m³`
    """

    OZONE = "ozone"
    """Amount of O3.

    Unit of measurement: `μg/m³`
    """

    PH = "ph"
    """Potential hydrogen (acidity/alkalinity).

    Unit of measurement: Unitless
Repository: home-assistant/core
File: homeassistant/components/scrape/coordinator.py (Python)

Code before:
"""Coordinator for the scrape component."""

from __future__ import annotations

from datetime import timedelta
import logging
from typing import Any

from bs4 import BeautifulSoup

from homeassistant.components.rest import CONF_PAYLOAD_TEMPLATE, RestData
from homeassistant.components.rest.const import XML_MIME_TYPES
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_RESOURCE_TEMPLATE
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed

_LOGGER = logging.getLogger(__name__)


class ScrapeCoordinator(DataUpdateCoordinator[BeautifulSoup]):
    """Scrape Coordinator."""

    def __init__(
        self,
        hass: HomeAssistant,
        config_entry: ConfigEntry | None,
        rest: RestData,
        rest_config: dict[str, Any],
        update_interval: timedelta,
    ) -> None:
        """Initialize Scrape coordinator."""
        super().__init__(
            hass,
            _LOGGER,
            config_entry=config_entry,
            name="Scrape Coordinator",

Review comment (suggestion):
@joostlek Looks like a new linter rule has been added but the code wasn't updated in the repo (see other unchanged lines)? This is just going to lead to inconsistent import formats.


```suggestion
from .rest.const import XML_MIME_TYPES
```

Code after:
"""Coordinator for the scrape component."""

from __future__ import annotations

from datetime import timedelta
import logging
from typing import Any

from bs4 import BeautifulSoup

from homeassistant.components.rest import CONF_PAYLOAD_TEMPLATE, RestData
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_RESOURCE_TEMPLATE
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed

_LOGGER = logging.getLogger(__name__)

XML_MIME_TYPES = (
    "application/rss+xml",
    "application/xhtml+xml",
    "application/xml",
    "text/xml",
)


class ScrapeCoordinator(DataUpdateCoordinator[BeautifulSoup]):
    """Scrape Coordinator."""

    def __init__(
        self,
        hass: HomeAssistant,
        config_entry: ConfigEntry | None,
        rest: RestData,
        rest_config: dict[str, Any],
        update_interval: timedelta,
    ) -> None:
Repository: home-assistant/core
File: tests/hassfest/test_translations.py (Python)

Code before:
"""Tests for hassfest translations."""

import pytest
from syrupy.assertion import SnapshotAssertion
import voluptuous as vol

from script.hassfest import translations

from . import get_integration


def test_string_with_no_placeholders_in_single_quotes() -> None:
    """Test string with no placeholders in single quotes."""
    schema = vol.Schema(translations.string_no_single_quoted_placeholders)

    with pytest.raises(vol.Invalid):
        schema("This has '{placeholder}' in single quotes")

    for value in (
        'This has "{placeholder}" in double quotes',
        "Simple {placeholder}",
        "No placeholder",
    ):
        schema(value)


SAMPLE_STRINGS = {
    "title": "Test Integration",
    "config": {
        "flow_title": "Configure {name}",
        "step": {

Review comment (suggestion):
```suggestion
from script.hassfest import translations
from script.hassfest.model import Config
```

Code after:
"""Tests for hassfest translations."""

import pytest
import voluptuous as vol

from script.hassfest import translations
from script.hassfest.model import Config

from . import get_integration


def test_string_with_no_placeholders_in_single_quotes() -> None:
    """Test string with no placeholders in single quotes."""
    schema = vol.Schema(translations.string_no_single_quoted_placeholders)

    with pytest.raises(vol.Invalid):
        schema("This has '{placeholder}' in single quotes")

    for value in (
        'This has "{placeholder}" in double quotes',
        "Simple {placeholder}",
        "No placeholder",
    ):
        schema(value)


SAMPLE_STRINGS = {
    "title": "Test Integration",
    "config": {
        "flow_title": "Configure {name}",
        "step": {
Repository: home-assistant/core
File: tests/hassfest/test_translations.py (Python)

Code before:
            },
        },
    },
    "triggers": {
        "turned_on": {
            "name": "Turned on",
            "description": "When the device turns on",
            "fields": {
                "entity_id": {
                    "name": "Entity",
                    "description": "The entity to monitor",
                    "example": "light.living_room",
                },
            },
        },
    },
    "conversation": {
        "agent": {
            "done": "Done",
        },
    },
    "common": {
        "on": "On",
        "off": "Off",
        "unknown": "Unknown",
    },
}


def test_gen_strings_schema(
    config: Config,
    snapshot: SnapshotAssertion,
) -> None:
    """Test gen_strings_schema validates all string types."""
    integration = get_integration("test_integration", config)
    schema = translations.gen_strings_schema(config, integration)

    # Validate the sample strings - should not raise
    validated = schema(SAMPLE_STRINGS)

    assert validated == snapshot


Review comment (suggestion):
We could consider moving this to a fixture.

Also, I would suggest to sort this to make it more similar to the snapshot (which is alphabetically sorted)

Code after:
        },
    },
    "triggers": {
        "turned_on": {
            "name": "Turned on",
            "description": "When the device turns on",
            "fields": {
                "entity_id": {
                    "name": "Entity",
                    "description": "The entity to monitor",
                    "example": "light.living_room",
                },
            },
        },
    },
    "conversation": {
        "agent": {
            "done": "Done",
        },
    },
    "common": {
        "on": "On",
        "off": "Off",
        "unknown": "Unknown",
    },
}


def test_gen_strings_schema(
    config: Config,
) -> None:
    """Test gen_strings_schema validates all string types."""
    integration = get_integration("test_integration", config)
    schema = translations.gen_strings_schema(config, integration)

    # Validate the sample strings - should not raise
    validated = schema(SAMPLE_STRINGS)

    assert validated == SAMPLE_STRINGS