Skip to content

Commit

Permalink
Add sensor tests to co2signal (home-assistant#104464)
Browse files Browse the repository at this point in the history
  • Loading branch information
jpbede authored Nov 24, 2023
1 parent 9962301 commit 94995f5
Show file tree
Hide file tree
Showing 3 changed files with 185 additions and 1 deletion.
1 change: 0 additions & 1 deletion .coveragerc
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,6 @@ omit =
homeassistant/components/control4/director_utils.py
homeassistant/components/control4/light.py
homeassistant/components/coolmaster/coordinator.py
homeassistant/components/co2signal/coordinator.py
homeassistant/components/cppm_tracker/device_tracker.py
homeassistant/components/crownstone/__init__.py
homeassistant/components/crownstone/devices.py
Expand Down
101 changes: 101 additions & 0 deletions tests/components/co2signal/snapshots/test_sensor.ambr
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# serializer version: 1
# name: test_sensor[sensor.electricity_maps_co2_intensity]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': dict({
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
}),
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'sensor',
'entity_category': None,
'entity_id': 'sensor.electricity_maps_co2_intensity',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'name': None,
'options': dict({
}),
'original_device_class': None,
'original_icon': 'mdi:molecule-co2',
'original_name': 'CO2 intensity',
'platform': 'co2signal',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': 'carbon_intensity',
'unique_id': '904a74160aa6f335526706bee85dfb83_co2intensity',
'unit_of_measurement': 'gCO2eq/kWh',
})
# ---
# name: test_sensor[sensor.electricity_maps_co2_intensity].1
StateSnapshot({
'attributes': ReadOnlyDict({
'attribution': 'Data provided by Electricity Maps',
'country_code': 'FR',
'friendly_name': 'Electricity Maps CO2 intensity',
'icon': 'mdi:molecule-co2',
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
'unit_of_measurement': 'gCO2eq/kWh',
}),
'context': <ANY>,
'entity_id': 'sensor.electricity_maps_co2_intensity',
'last_changed': <ANY>,
'last_updated': <ANY>,
'state': '45.9862319009581',
})
# ---
# name: test_sensor[sensor.electricity_maps_grid_fossil_fuel_percentage]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': dict({
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
}),
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'sensor',
'entity_category': None,
'entity_id': 'sensor.electricity_maps_grid_fossil_fuel_percentage',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'name': None,
'options': dict({
}),
'original_device_class': None,
'original_icon': 'mdi:molecule-co2',
'original_name': 'Grid fossil fuel percentage',
'platform': 'co2signal',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': 'fossil_fuel_percentage',
'unique_id': '904a74160aa6f335526706bee85dfb83_fossilFuelPercentage',
'unit_of_measurement': '%',
})
# ---
# name: test_sensor[sensor.electricity_maps_grid_fossil_fuel_percentage].1
StateSnapshot({
'attributes': ReadOnlyDict({
'attribution': 'Data provided by Electricity Maps',
'country_code': 'FR',
'friendly_name': 'Electricity Maps Grid fossil fuel percentage',
'icon': 'mdi:molecule-co2',
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
'unit_of_measurement': '%',
}),
'context': <ANY>,
'entity_id': 'sensor.electricity_maps_grid_fossil_fuel_percentage',
'last_changed': <ANY>,
'last_updated': <ANY>,
'state': '5.4611827419371',
})
# ---
84 changes: 84 additions & 0 deletions tests/components/co2signal/test_sensor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
"""Tests Electricity Maps sensor platform."""
from datetime import timedelta
from unittest.mock import AsyncMock

from aioelectricitymaps.exceptions import (
ElectricityMapsDecodeError,
ElectricityMapsError,
InvalidToken,
)
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy import SnapshotAssertion

from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er

from tests.common import async_fire_time_changed


@pytest.mark.parametrize(
"entity_name",
[
"sensor.electricity_maps_co2_intensity",
"sensor.electricity_maps_grid_fossil_fuel_percentage",
],
)
@pytest.mark.usefixtures("setup_integration")
async def test_sensor(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
entity_name: str,
snapshot: SnapshotAssertion,
) -> None:
"""Test sensor setup and update."""
assert (entry := entity_registry.async_get(entity_name))
assert entry == snapshot

assert (state := hass.states.get(entity_name))
assert state == snapshot


@pytest.mark.parametrize(
"error",
[
InvalidToken,
ElectricityMapsDecodeError,
ElectricityMapsError,
Exception,
],
)
@pytest.mark.usefixtures("setup_integration")
async def test_sensor_update_fail(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
electricity_maps: AsyncMock,
error: Exception,
) -> None:
"""Test sensor error handling."""
assert (state := hass.states.get("sensor.electricity_maps_co2_intensity"))
assert state.state == "45.9862319009581"
assert len(electricity_maps.mock_calls) == 1

electricity_maps.latest_carbon_intensity_by_coordinates.side_effect = error
electricity_maps.latest_carbon_intensity_by_country_code.side_effect = error

freezer.tick(timedelta(minutes=20))
async_fire_time_changed(hass)
await hass.async_block_till_done()

assert (state := hass.states.get("sensor.electricity_maps_co2_intensity"))
assert state.state == "unavailable"
assert len(electricity_maps.mock_calls) == 2

# reset mock and test if entity is available again
electricity_maps.latest_carbon_intensity_by_coordinates.side_effect = None
electricity_maps.latest_carbon_intensity_by_country_code.side_effect = None

freezer.tick(timedelta(minutes=20))
async_fire_time_changed(hass)
await hass.async_block_till_done()

assert (state := hass.states.get("sensor.electricity_maps_co2_intensity"))
assert state.state == "45.9862319009581"
assert len(electricity_maps.mock_calls) == 3

0 comments on commit 94995f5

Please sign in to comment.