init home-assistant

This commit is contained in:
2026-11-19 15:15:32 -05:00
parent 2e81d9d300
commit feec6ef9fb
19230 changed files with 3335526 additions and 0 deletions

View File

@@ -0,0 +1,12 @@
"""Tests for the emoncms component."""
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
async def setup_integration(hass: HomeAssistant, entry: MockConfigEntry) -> None:
"""Set up the integration."""
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()

View File

@@ -0,0 +1,162 @@
"""Fixtures for emoncms integration tests."""
from collections.abc import AsyncGenerator, Generator
import copy
from unittest.mock import AsyncMock, patch
import pytest
from homeassistant.components.emoncms.const import CONF_ONLY_INCLUDE_FEEDID, DOMAIN
from homeassistant.const import (
CONF_API_KEY,
CONF_ID,
CONF_PLATFORM,
CONF_URL,
CONF_VALUE_TEMPLATE,
)
from homeassistant.helpers.typing import ConfigType
from tests.common import MockConfigEntry
UNITS = ["kWh", "Wh", "W", "V", "A", "VA", "°C", "°F", "K", "Hz", "hPa", ""]
def get_feed(
number: int, unit: str = "W", value: int = 18.04, timestamp: int = 1665509570
):
"""Generate feed details."""
return {
"id": str(number),
"userid": "1",
"name": f"parameter {number}",
"tag": "tag",
"size": "35809224",
"unit": unit,
"time": timestamp,
"value": value,
}
FEEDS = [get_feed(i + 1, unit=unit) for i, unit in enumerate(UNITS)]
EMONCMS_FAILURE = {"success": False, "message": "failure"}
FLOW_RESULT = {
CONF_API_KEY: "my_api_key",
CONF_ONLY_INCLUDE_FEEDID: [str(i + 1) for i in range(len(UNITS))],
CONF_URL: "http://1.1.1.1",
}
SENSOR_NAME = "emoncms@1.1.1.1"
YAML_BASE = {
CONF_PLATFORM: "emoncms",
CONF_API_KEY: "my_api_key",
CONF_ID: 1,
CONF_URL: "http://1.1.1.1",
}
YAML = {
**YAML_BASE,
CONF_ONLY_INCLUDE_FEEDID: [1],
}
@pytest.fixture
def emoncms_yaml_config() -> ConfigType:
"""Mock emoncms yaml configuration."""
return {"sensor": YAML}
@pytest.fixture
def emoncms_yaml_config_with_template() -> ConfigType:
"""Mock emoncms yaml conf with template parameter."""
return {"sensor": {**YAML, CONF_VALUE_TEMPLATE: "{{ value | float + 1500 }}"}}
@pytest.fixture
def emoncms_yaml_config_no_include_only_feed_id() -> ConfigType:
"""Mock emoncms yaml configuration without include_only_feed_id parameter."""
return {"sensor": YAML_BASE}
@pytest.fixture
def config_entry() -> MockConfigEntry:
"""Mock emoncms config entry."""
return MockConfigEntry(
domain=DOMAIN,
title=SENSOR_NAME,
data=FLOW_RESULT,
)
FLOW_RESULT_SECOND_URL = copy.deepcopy(FLOW_RESULT)
FLOW_RESULT_SECOND_URL[CONF_URL] = "http://1.1.1.2"
@pytest.fixture
def config_entry_unique_id() -> MockConfigEntry:
"""Mock emoncms config entry."""
return MockConfigEntry(
domain=DOMAIN,
title=SENSOR_NAME,
data=FLOW_RESULT_SECOND_URL,
unique_id="123-53535292",
)
FLOW_RESULT_NO_FEED = copy.deepcopy(FLOW_RESULT)
FLOW_RESULT_NO_FEED[CONF_ONLY_INCLUDE_FEEDID] = None
@pytest.fixture
def config_no_feed() -> MockConfigEntry:
"""Mock emoncms config entry with no feed selected."""
return MockConfigEntry(
domain=DOMAIN,
title=SENSOR_NAME,
data=FLOW_RESULT_NO_FEED,
)
FLOW_RESULT_SINGLE_FEED = copy.deepcopy(FLOW_RESULT)
FLOW_RESULT_SINGLE_FEED[CONF_ONLY_INCLUDE_FEEDID] = ["1"]
@pytest.fixture
def config_single_feed() -> MockConfigEntry:
"""Mock emoncms config entry with a single feed exposed."""
return MockConfigEntry(
domain=DOMAIN,
title=SENSOR_NAME,
data=FLOW_RESULT_SINGLE_FEED,
entry_id="XXXXXXXX",
)
@pytest.fixture
def mock_setup_entry() -> Generator[AsyncMock]:
"""Override async_setup_entry."""
with patch(
"homeassistant.components.emoncms.async_setup_entry", return_value=True
) as mock_setup_entry:
yield mock_setup_entry
@pytest.fixture
async def emoncms_client() -> AsyncGenerator[AsyncMock]:
"""Mock pyemoncms success response."""
with (
patch(
"homeassistant.components.emoncms.EmoncmsClient", autospec=True
) as mock_client,
patch(
"homeassistant.components.emoncms.config_flow.EmoncmsClient",
new=mock_client,
),
):
client = mock_client.return_value
client.async_request.return_value = {"success": True, "message": FEEDS}
client.async_get_uuid.return_value = "123-53535292"
yield client

View File

@@ -0,0 +1,59 @@
# serializer version: 1
# name: test_coordinator_update[sensor.temperature_tag_parameter_1-entry]
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.temperature_tag_parameter_1',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <SensorDeviceClass.TEMPERATURE: 'temperature'>,
'original_icon': None,
'original_name': 'Temperature tag parameter 1',
'platform': 'emoncms',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': 'temperature',
'unique_id': '123-53535292-1',
'unit_of_measurement': <UnitOfTemperature.CELSIUS: '°C'>,
})
# ---
# name: test_coordinator_update[sensor.temperature_tag_parameter_1-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'FeedId': '1',
'FeedName': 'parameter 1',
'LastUpdated': 1665509570,
'LastUpdatedStr': '2022-10-11T10:32:50-07:00',
'Size': '35809224',
'Tag': 'tag',
'UserId': '1',
'device_class': 'temperature',
'friendly_name': 'Temperature tag parameter 1',
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
'unit_of_measurement': <UnitOfTemperature.CELSIUS: '°C'>,
}),
'context': <ANY>,
'entity_id': 'sensor.temperature_tag_parameter_1',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': '18.04',
})
# ---

View File

@@ -0,0 +1,161 @@
"""Test emoncms config flow."""
from unittest.mock import AsyncMock
from homeassistant.components.emoncms.const import CONF_ONLY_INCLUDE_FEEDID, DOMAIN
from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER
from homeassistant.const import CONF_API_KEY, CONF_URL
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from . import setup_integration
from .conftest import EMONCMS_FAILURE, FLOW_RESULT_SINGLE_FEED, SENSOR_NAME, YAML
from tests.common import MockConfigEntry
async def test_flow_import_include_feeds(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
emoncms_client: AsyncMock,
) -> None:
"""YAML import with included feed - success test."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data=YAML,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == SENSOR_NAME
assert result["data"] == FLOW_RESULT_SINGLE_FEED
async def test_flow_import_failure(
hass: HomeAssistant,
emoncms_client: AsyncMock,
) -> None:
"""YAML import - failure test."""
emoncms_client.async_request.return_value = EMONCMS_FAILURE
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data=YAML,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "api_error"
async def test_flow_import_already_configured(
hass: HomeAssistant,
config_entry: MockConfigEntry,
emoncms_client: AsyncMock,
) -> None:
"""Test we abort import data set when entry is already configured."""
config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data=YAML,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
USER_INPUT = {
CONF_URL: "http://1.1.1.1",
CONF_API_KEY: "my_api_key",
}
async def test_user_flow(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
emoncms_client: AsyncMock,
) -> None:
"""Test we get the user form."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
USER_INPUT,
)
assert result["type"] is FlowResultType.FORM
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_ONLY_INCLUDE_FEEDID: ["1"]},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == SENSOR_NAME
assert result["data"] == {**USER_INPUT, CONF_ONLY_INCLUDE_FEEDID: ["1"]}
assert len(mock_setup_entry.mock_calls) == 1
CONFIG_ENTRY = {
CONF_API_KEY: "my_api_key",
CONF_ONLY_INCLUDE_FEEDID: ["1"],
CONF_URL: "http://1.1.1.1",
}
async def test_options_flow(
hass: HomeAssistant,
emoncms_client: AsyncMock,
config_entry: MockConfigEntry,
) -> None:
"""Options flow - success test."""
await setup_integration(hass, config_entry)
assert config_entry.options == {}
result = await hass.config_entries.options.async_init(config_entry.entry_id)
await hass.async_block_till_done()
result = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input={
CONF_ONLY_INCLUDE_FEEDID: ["1"],
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert config_entry.options == {
CONF_ONLY_INCLUDE_FEEDID: ["1"],
}
async def test_options_flow_failure(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
emoncms_client: AsyncMock,
config_entry: MockConfigEntry,
) -> None:
"""Options flow - test failure."""
emoncms_client.async_request.return_value = EMONCMS_FAILURE
await setup_integration(hass, config_entry)
result = await hass.config_entries.options.async_init(config_entry.entry_id)
await hass.async_block_till_done()
assert result["errors"]["base"] == "api_error"
assert result["description_placeholders"]["details"] == "failure"
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "init"
async def test_unique_id_exists(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
emoncms_client: AsyncMock,
config_entry_unique_id: MockConfigEntry,
) -> None:
"""Test when entry with same unique id already exists."""
config_entry_unique_id.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], USER_INPUT
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"

View File

@@ -0,0 +1,89 @@
"""Test Emoncms component setup process."""
from __future__ import annotations
from unittest.mock import AsyncMock
from homeassistant.components.emoncms.const import DOMAIN, FEED_ID, FEED_NAME
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er, issue_registry as ir
from . import setup_integration
from .conftest import EMONCMS_FAILURE, FEEDS
from tests.common import MockConfigEntry
async def test_load_unload_entry(
hass: HomeAssistant,
config_entry: MockConfigEntry,
emoncms_client: AsyncMock,
) -> None:
"""Test load and unload entry."""
await setup_integration(hass, config_entry)
assert config_entry.state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.NOT_LOADED
async def test_failure(
hass: HomeAssistant,
config_entry: MockConfigEntry,
emoncms_client: AsyncMock,
) -> None:
"""Test load failure."""
emoncms_client.async_request.return_value = EMONCMS_FAILURE
config_entry.add_to_hass(hass)
assert not await hass.config_entries.async_setup(config_entry.entry_id)
async def test_migrate_uuid(
hass: HomeAssistant,
config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
emoncms_client: AsyncMock,
) -> None:
"""Test migration from home assistant uuid to emoncms uuid."""
config_entry.add_to_hass(hass)
assert config_entry.unique_id is None
for _, feed in enumerate(FEEDS):
entity_registry.async_get_or_create(
Platform.SENSOR,
DOMAIN,
f"{config_entry.entry_id}-{feed[FEED_ID]}",
config_entry=config_entry,
suggested_object_id=f"{DOMAIN}_{feed[FEED_NAME]}",
)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
emoncms_uuid = emoncms_client.async_get_uuid.return_value
assert config_entry.unique_id == emoncms_uuid
entity_entries = er.async_entries_for_config_entry(
entity_registry, config_entry.entry_id
)
for nb, feed in enumerate(FEEDS):
assert entity_entries[nb].unique_id == f"{emoncms_uuid}-{feed[FEED_ID]}"
assert (
entity_entries[nb].previous_unique_id
== f"{config_entry.entry_id}-{feed[FEED_ID]}"
)
async def test_no_uuid(
hass: HomeAssistant,
config_entry: MockConfigEntry,
issue_registry: ir.IssueRegistry,
emoncms_client: AsyncMock,
) -> None:
"""Test an issue is created when the emoncms server does not ship an uuid."""
emoncms_client.async_get_uuid.return_value = None
await setup_integration(hass, config_entry)
assert issue_registry.async_get_issue(domain=DOMAIN, issue_id="migrate database")

View File

@@ -0,0 +1,151 @@
"""Test emoncms sensor."""
from unittest.mock import AsyncMock
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.emoncms.const import DOMAIN
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant
from homeassistant.helpers import entity_registry as er, issue_registry as ir
from homeassistant.helpers.typing import ConfigType
from homeassistant.setup import async_setup_component
from . import setup_integration
from .conftest import EMONCMS_FAILURE, get_feed
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
async def test_deprecated_yaml(
hass: HomeAssistant,
issue_registry: ir.IssueRegistry,
emoncms_yaml_config: ConfigType,
emoncms_client: AsyncMock,
) -> None:
"""Test an issue is created when we import from yaml config."""
await async_setup_component(hass, SENSOR_DOMAIN, emoncms_yaml_config)
await hass.async_block_till_done()
assert issue_registry.async_get_issue(
domain=HOMEASSISTANT_DOMAIN, issue_id=f"deprecated_yaml_{DOMAIN}"
)
async def test_yaml_with_template(
hass: HomeAssistant,
issue_registry: ir.IssueRegistry,
emoncms_yaml_config_with_template: ConfigType,
emoncms_client: AsyncMock,
) -> None:
"""Test an issue is created when we import a yaml config with a value_template parameter."""
await async_setup_component(hass, SENSOR_DOMAIN, emoncms_yaml_config_with_template)
await hass.async_block_till_done()
assert issue_registry.async_get_issue(
domain=DOMAIN, issue_id=f"remove_value_template_{DOMAIN}"
)
async def test_yaml_no_include_only_feed_id(
hass: HomeAssistant,
issue_registry: ir.IssueRegistry,
emoncms_yaml_config_no_include_only_feed_id: ConfigType,
emoncms_client: AsyncMock,
) -> None:
"""Test an issue is created when we import a yaml config without a include_only_feed_id parameter."""
await async_setup_component(
hass, SENSOR_DOMAIN, emoncms_yaml_config_no_include_only_feed_id
)
await hass.async_block_till_done()
assert issue_registry.async_get_issue(
domain=DOMAIN, issue_id=f"missing_include_only_feed_id_{DOMAIN}"
)
async def test_no_feed_selected(
hass: HomeAssistant,
config_no_feed: MockConfigEntry,
entity_registry: er.EntityRegistry,
emoncms_client: AsyncMock,
) -> None:
"""Test with no feed selected."""
await setup_integration(hass, config_no_feed)
assert config_no_feed.state is ConfigEntryState.LOADED
entity_entries = er.async_entries_for_config_entry(
entity_registry, config_no_feed.entry_id
)
assert entity_entries == []
async def test_no_feed_broadcast(
hass: HomeAssistant,
config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
emoncms_client: AsyncMock,
) -> None:
"""Test with no feed broadcasted."""
emoncms_client.async_request.return_value = {"success": True, "message": []}
await setup_integration(hass, config_entry)
assert config_entry.state is ConfigEntryState.LOADED
entity_entries = er.async_entries_for_config_entry(
entity_registry, config_entry.entry_id
)
assert entity_entries == []
async def test_coordinator_update(
hass: HomeAssistant,
config_single_feed: MockConfigEntry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
emoncms_client: AsyncMock,
caplog: pytest.LogCaptureFixture,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test coordinator update."""
emoncms_client.async_request.return_value = {
"success": True,
"message": [get_feed(1, unit="°C")],
}
await setup_integration(hass, config_single_feed)
await snapshot_platform(
hass, entity_registry, snapshot, config_single_feed.entry_id
)
async def skip_time() -> None:
freezer.tick(60)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
emoncms_client.async_request.return_value = {
"success": True,
"message": [get_feed(1, unit="°C", value=24.04, timestamp=1665509670)],
}
await skip_time()
entity_entries = er.async_entries_for_config_entry(
entity_registry, config_single_feed.entry_id
)
for entity_entry in entity_entries:
state = hass.states.get(entity_entry.entity_id)
assert state.attributes["LastUpdated"] == 1665509670
assert state.state == "24.04"
emoncms_client.async_request.return_value = EMONCMS_FAILURE
await skip_time()
assert f"Error fetching {DOMAIN}_coordinator data" in caplog.text