Replace enphase_envoy fixture collection by library function (#189335)

This commit is contained in:
Arie Catsman
2026-11-02 10:18:42 +00:00
committed by GitHub
parent c236dd4fa8
commit 2cb29765fa
5 changed files with 184 additions and 219 deletions
@@ -4,9 +4,9 @@ import copy
from datetime import datetime
from typing import TYPE_CHECKING, Any
from aiohttp import ClientError, ClientResponse
from aiohttp import ClientError
from pyenphase.envoy import Envoy
from pyenphase.exceptions import EnvoyError
from pyenphase.exceptions import EnvoyClientClosedError, EnvoyError
from homeassistant.components.diagnostics import (
async_redact_data,
@@ -42,63 +42,24 @@ TO_REDACT = {
}
async def _get_fixture_collection(envoy: Envoy, serial: str) -> dict[str, Any]:
"""Collect Envoy endpoints to use for test fixture set."""
fixture_data: dict[str, Any] = {}
end_points = [
"/info",
"/api/v1/production",
"/api/v1/production/inverters",
"/production.json",
"/production.json?details=1",
"/production",
"/ivp/ensemble/power",
"/ivp/ensemble/inventory",
"/ivp/ensemble/dry_contacts",
"/ivp/ensemble/status",
"/ivp/ensemble/secctrl",
"/ivp/ss/dry_contact_settings",
"/admin/lib/tariff",
"/ivp/ss/gen_config",
"/ivp/ss/gen_schedule",
"/ivp/sc/pvlimit",
"/ivp/ss/pel_settings",
"/ivp/ensemble/generator",
"/ivp/meters",
"/ivp/meters/readings",
"/ivp/pdm/device_data",
"/home",
"/inventory.json?deleted=1",
"/admin/lib/acb_config",
"/ivp/sc/sched",
"/admin/lib/network_display",
"/admin/lib/wireless_display",
"/ivp/ensemble/relay",
"/ivp/livedata/status",
"/ivp/pdm/energy",
]
for end_point in end_points:
try:
response: ClientResponse = await envoy.request(end_point)
fixture_data[end_point] = (
(await response.text(errors="replace"))
.replace("\n", "")
.replace(serial, CLEAN_TEXT)
)
fixture_data[f"{end_point}_log"] = json_dumps(
{
"headers": dict(response.headers.items()),
"code": response.status,
}
)
except ClientError as err:
fixture_data[f"{end_point}_log"] = {
"Error": f"Aiohttp Client error {type(err).__name__ if not hasattr(err, 'status') else err.status}"
async def _get_fixture_collection(
envoy: Envoy, mask: bool, strict: bool
) -> dict[str, Any]:
try:
fixtures: dict[str, Any] = await envoy.fixture_collection(
mask_serials=mask, strict_masking=strict
)
except (EnvoyError, EnvoyClientClosedError, ClientError) as err:
status = getattr(err, "status", None)
if isinstance(status, int) and 100 <= status <= 599:
return {"collection_aborted_log": f"Error: {type(err).__name__}: {status}"}
status_code = getattr(err, "status_code", 0)
if isinstance(status_code, int) and status_code > 0:
return {
"collection_aborted_log": f"Error: {type(err).__name__}: {status_code}"
}
except EnvoyError as err:
fixture_data[f"{end_point}_log"] = {"Error": repr(err)}
return fixture_data
return {"collection_aborted_log": f"Error: {type(err).__name__}"}
return fixtures
async def async_get_config_entry_diagnostics(
@@ -183,6 +144,7 @@ async def async_get_config_entry_diagnostics(
"part_number": envoy.part_number,
"envoy_model": envoy.envoy_model,
"active interface": active_interface,
"token_lifetime": coordinator.token_lifetime,
"supported_features": [feature.name for feature in envoy.supported_features],
"phase_mode": envoy.phase_mode,
"phase_count": envoy.phase_count,
@@ -196,7 +158,10 @@ async def async_get_config_entry_diagnostics(
fixture_data: dict[str, Any] = {}
if entry.options.get(OPTION_DIAGNOSTICS_INCLUDE_FIXTURES, False):
fixture_data = await _get_fixture_collection(envoy=envoy, serial=old_serial)
# use strict masking until option_flow let user select mode that should be used
fixture_data = await _get_fixture_collection(
envoy=envoy, mask=True, strict=True
)
diagnostic_data: dict[str, Any] = {
"config_entry": async_redact_data(entry.as_dict(), TO_REDACT),
@@ -191,6 +191,11 @@ def load_envoy_fixture(mock_envoy: AsyncMock, fixture_name: str) -> None:
else:
mock_envoy.interface_settings.return_value = None
if item := json_fixture.get("fixture_collection"):
mock_envoy.fixture_collection.return_value = item
else:
mock_envoy.fixture_collection.return_value = None
def _load_json_2_production_data(
mocked_data: EnvoyData, json_fixture: dict[str, Any]
@@ -61,5 +61,44 @@
"dhcp": true,
"software_build_epoch": 1719503966,
"timezone": "Europe/Amsterdam"
},
"fixture_collection": {
"/info": "Lorem ipsum dolor sit amet, consectetur adipiscing elit,",
"/info_log": {
"code": 200,
"mask_state": "unchanged",
"line": "1, first half"
},
"/api/v1/production/inverters": "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
"/api/v1/production/inverters_log": {
"code": 200,
"mask_state": "masked",
"line": "1, second half"
},
"/ivp/pdm/device_data": "Ut enim ad minim veniam,",
"/ivp/pdm/device_data_log": {
"code": 200,
"mask_state": "removed",
"line": "2, first half"
},
"/ivp/meters/readings": "quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
"/ivp/meters/readings_log": {
"code": 200,
"mask_state": "failed",
"line": "2, second half"
},
"/ivp/ensemble/power": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.",
"/ivp/ensemble/power_log": {
"code": 200,
"mask_state": "unchanged",
"line": "3"
},
"/admin/lib/tariff": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
"/admin/lib/tariff_log": {
"error": "ClientResponseError",
"code": 200,
"mask_state": "unchanged",
"line": "4"
}
}
}
@@ -890,6 +890,7 @@
'INVERTERS',
'PRODUCTION',
]),
'token_lifetime': 200,
}),
'fixtures': dict({
}),
@@ -1790,68 +1791,46 @@
'INVERTERS',
'PRODUCTION',
]),
'token_lifetime': 200,
}),
'fixtures': dict({
'/admin/lib/acb_config': 'Testing request replies.',
'/admin/lib/acb_config_log': '{"headers":{"Hello":"World"},"code":200}',
'/admin/lib/network_display': 'Testing request replies.',
'/admin/lib/network_display_log': '{"headers":{"Hello":"World"},"code":200}',
'/admin/lib/tariff': 'Testing request replies.',
'/admin/lib/tariff_log': '{"headers":{"Hello":"World"},"code":200}',
'/admin/lib/wireless_display': 'Testing request replies.',
'/admin/lib/wireless_display_log': '{"headers":{"Hello":"World"},"code":200}',
'/api/v1/production': 'Testing request replies.',
'/api/v1/production/inverters': 'Testing request replies.',
'/api/v1/production/inverters_log': '{"headers":{"Hello":"World"},"code":200}',
'/api/v1/production_log': '{"headers":{"Hello":"World"},"code":200}',
'/home': 'Testing request replies.',
'/home_log': '{"headers":{"Hello":"World"},"code":200}',
'/info': 'Testing request replies.',
'/info_log': '{"headers":{"Hello":"World"},"code":200}',
'/inventory.json?deleted=1': 'Testing request replies.',
'/inventory.json?deleted=1_log': '{"headers":{"Hello":"World"},"code":200}',
'/ivp/ensemble/dry_contacts': 'Testing request replies.',
'/ivp/ensemble/dry_contacts_log': '{"headers":{"Hello":"World"},"code":200}',
'/ivp/ensemble/generator': 'Testing request replies.',
'/ivp/ensemble/generator_log': '{"headers":{"Hello":"World"},"code":200}',
'/ivp/ensemble/inventory': 'Testing request replies.',
'/ivp/ensemble/inventory_log': '{"headers":{"Hello":"World"},"code":200}',
'/ivp/ensemble/power': 'Testing request replies.',
'/ivp/ensemble/power_log': '{"headers":{"Hello":"World"},"code":200}',
'/ivp/ensemble/relay': 'Testing request replies.',
'/ivp/ensemble/relay_log': '{"headers":{"Hello":"World"},"code":200}',
'/ivp/ensemble/secctrl': 'Testing request replies.',
'/ivp/ensemble/secctrl_log': '{"headers":{"Hello":"World"},"code":200}',
'/ivp/ensemble/status': 'Testing request replies.',
'/ivp/ensemble/status_log': '{"headers":{"Hello":"World"},"code":200}',
'/ivp/livedata/status': 'Testing request replies.',
'/ivp/livedata/status_log': '{"headers":{"Hello":"World"},"code":200}',
'/ivp/meters': 'Testing request replies.',
'/ivp/meters/readings': 'Testing request replies.',
'/ivp/meters/readings_log': '{"headers":{"Hello":"World"},"code":200}',
'/ivp/meters_log': '{"headers":{"Hello":"World"},"code":200}',
'/ivp/pdm/device_data': 'Testing request replies.',
'/ivp/pdm/device_data_log': '{"headers":{"Hello":"World"},"code":200}',
'/ivp/pdm/energy': 'Testing request replies.',
'/ivp/pdm/energy_log': '{"headers":{"Hello":"World"},"code":200}',
'/ivp/sc/pvlimit': 'Testing request replies.',
'/ivp/sc/pvlimit_log': '{"headers":{"Hello":"World"},"code":200}',
'/ivp/sc/sched': 'Testing request replies.',
'/ivp/sc/sched_log': '{"headers":{"Hello":"World"},"code":200}',
'/ivp/ss/dry_contact_settings': 'Testing request replies.',
'/ivp/ss/dry_contact_settings_log': '{"headers":{"Hello":"World"},"code":200}',
'/ivp/ss/gen_config': 'Testing request replies.',
'/ivp/ss/gen_config_log': '{"headers":{"Hello":"World"},"code":200}',
'/ivp/ss/gen_schedule': 'Testing request replies.',
'/ivp/ss/gen_schedule_log': '{"headers":{"Hello":"World"},"code":200}',
'/ivp/ss/pel_settings': 'Testing request replies.',
'/ivp/ss/pel_settings_log': '{"headers":{"Hello":"World"},"code":200}',
'/production': 'Testing request replies.',
'/production.json': 'Testing request replies.',
'/production.json?details=1': 'Testing request replies.',
'/production.json?details=1_log': '{"headers":{"Hello":"World"},"code":200}',
'/production.json_log': '{"headers":{"Hello":"World"},"code":200}',
'/production_log': '{"headers":{"Hello":"World"},"code":200}',
'/admin/lib/tariff': 'Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
'/admin/lib/tariff_log': dict({
'code': 200,
'error': 'ClientResponseError',
'line': '4',
'mask_state': 'unchanged',
}),
'/api/v1/production/inverters': 'sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
'/api/v1/production/inverters_log': dict({
'code': 200,
'line': '1, second half',
'mask_state': 'masked',
}),
'/info': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit,',
'/info_log': dict({
'code': 200,
'line': '1, first half',
'mask_state': 'unchanged',
}),
'/ivp/ensemble/power': 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.',
'/ivp/ensemble/power_log': dict({
'code': 200,
'line': '3',
'mask_state': 'unchanged',
}),
'/ivp/meters/readings': 'quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.',
'/ivp/meters/readings_log': dict({
'code': 200,
'line': '2, second half',
'mask_state': 'failed',
}),
'/ivp/pdm/device_data': 'Ut enim ad minim veniam,',
'/ivp/pdm/device_data_log': dict({
'code': 200,
'line': '2, first half',
'mask_state': 'removed',
}),
}),
'raw_data': dict({
'varies_by': 'firmware_version',
@@ -2750,98 +2729,10 @@
'INVERTERS',
'PRODUCTION',
]),
'token_lifetime': 200,
}),
'fixtures': dict({
'/admin/lib/acb_config_log': dict({
'Error': "EnvoyError('Test')",
}),
'/admin/lib/network_display_log': dict({
'Error': "EnvoyError('Test')",
}),
'/admin/lib/tariff_log': dict({
'Error': "EnvoyError('Test')",
}),
'/admin/lib/wireless_display_log': dict({
'Error': "EnvoyError('Test')",
}),
'/api/v1/production/inverters_log': dict({
'Error': "EnvoyError('Test')",
}),
'/api/v1/production_log': dict({
'Error': "EnvoyError('Test')",
}),
'/home_log': dict({
'Error': "EnvoyError('Test')",
}),
'/info_log': dict({
'Error': "EnvoyError('Test')",
}),
'/inventory.json?deleted=1_log': dict({
'Error': "EnvoyError('Test')",
}),
'/ivp/ensemble/dry_contacts_log': dict({
'Error': "EnvoyError('Test')",
}),
'/ivp/ensemble/generator_log': dict({
'Error': "EnvoyError('Test')",
}),
'/ivp/ensemble/inventory_log': dict({
'Error': "EnvoyError('Test')",
}),
'/ivp/ensemble/power_log': dict({
'Error': "EnvoyError('Test')",
}),
'/ivp/ensemble/relay_log': dict({
'Error': "EnvoyError('Test')",
}),
'/ivp/ensemble/secctrl_log': dict({
'Error': "EnvoyError('Test')",
}),
'/ivp/ensemble/status_log': dict({
'Error': "EnvoyError('Test')",
}),
'/ivp/livedata/status_log': dict({
'Error': "EnvoyError('Test')",
}),
'/ivp/meters/readings_log': dict({
'Error': "EnvoyError('Test')",
}),
'/ivp/meters_log': dict({
'Error': "EnvoyError('Test')",
}),
'/ivp/pdm/device_data_log': dict({
'Error': "EnvoyError('Test')",
}),
'/ivp/pdm/energy_log': dict({
'Error': "EnvoyError('Test')",
}),
'/ivp/sc/pvlimit_log': dict({
'Error': "EnvoyError('Test')",
}),
'/ivp/sc/sched_log': dict({
'Error': "EnvoyError('Test')",
}),
'/ivp/ss/dry_contact_settings_log': dict({
'Error': "EnvoyError('Test')",
}),
'/ivp/ss/gen_config_log': dict({
'Error': "EnvoyError('Test')",
}),
'/ivp/ss/gen_schedule_log': dict({
'Error': "EnvoyError('Test')",
}),
'/ivp/ss/pel_settings_log': dict({
'Error': "EnvoyError('Test')",
}),
'/production.json?details=1_log': dict({
'Error': "EnvoyError('Test')",
}),
'/production.json_log': dict({
'Error': "EnvoyError('Test')",
}),
'/production_log': dict({
'Error': "EnvoyError('Test')",
}),
'collection_aborted_log': 'Error: EnvoyError',
}),
'raw_data': dict({
'varies_by': 'firmware_version',
@@ -3749,6 +3640,7 @@
'INVERTERS',
'PRODUCTION',
]),
'token_lifetime': 200,
}),
'fixtures': dict({
}),
@@ -20090,6 +19982,7 @@
'THREEPHASE',
'CTMETERS',
]),
'token_lifetime': 200,
}),
'fixtures': dict({
}),
@@ -5,7 +5,8 @@ from unittest.mock import AsyncMock
from aiohttp import ClientConnectionError, ClientResponseError
from aiohttp.client import RequestInfo
from freezegun.api import FrozenDateTimeFactory
from pyenphase.exceptions import EnvoyError
import orjson
from pyenphase.exceptions import EnvoyAuthenticationRequired, EnvoyError
from pyenphase.models.meters import CtType
import pytest
from pytest_homeassistant.common import MockConfigEntry, async_fire_time_changed
@@ -90,7 +91,7 @@ async def test_entry_diagnostics_with_fixtures_with_error(
) -> None:
"""Test config entry diagnostics."""
await setup_integration(hass, config_entry_options)
mock_envoy.request.side_effect = EnvoyError("Test")
mock_envoy.fixture_collection.side_effect = EnvoyError("Test")
assert await get_diagnostics_for_config_entry(
hass, hass_client, config_entry_options
) == snapshot(exclude=limit_diagnostic_attrs)
@@ -105,7 +106,29 @@ async def test_entry_diagnostics_with_fixtures_with_clientresponse_error(
) -> None:
"""Test diagnostics test fixtures with client errors."""
await setup_integration(hass, config_entry_options)
mock_envoy.request.side_effect = ClientResponseError(
mock_envoy.fixture_collection.side_effect = ClientResponseError(
RequestInfo(
url="http://example.com",
method="GET",
headers={
"Host": "www.example.com",
"Connection": "keep-alive",
"secret": "very secret secret",
},
real_url="http://example.com",
),
None,
status=125,
)
diagnostics = await get_diagnostics_for_config_entry(
hass, hass_client, config_entry_options
)
assert (
diagnostics["fixtures"]["collection_aborted_log"]
== "Error: ClientResponseError: 125"
)
mock_envoy.fixture_collection.side_effect = ClientResponseError(
RequestInfo(
url="http://example.com",
method="GET",
@@ -122,21 +145,61 @@ async def test_entry_diagnostics_with_fixtures_with_clientresponse_error(
diagnostics = await get_diagnostics_for_config_entry(
hass, hass_client, config_entry_options
)
assert diagnostics["fixtures"]["/info_log"] == {"Error": "Aiohttp Client error 0"}
assert (
diagnostics["fixtures"]["collection_aborted_log"]
== "Error: ClientResponseError"
)
mock_envoy.request.side_effect = EnvoyError("Test")
mock_envoy.fixture_collection.side_effect = ClientResponseError(
RequestInfo(
url="http://example.com",
method="GET",
headers={
"Host": "www.example.com",
"Connection": "keep-alive",
"secret": "very secret secret",
},
real_url="http://example.com",
),
None,
status=600,
)
diagnostics = await get_diagnostics_for_config_entry(
hass, hass_client, config_entry_options
)
assert diagnostics["fixtures"]["/info_log"] == {"Error": "EnvoyError('Test')"}
assert (
diagnostics["fixtures"]["collection_aborted_log"]
== "Error: ClientResponseError"
)
diagnostics_text = orjson.dumps(diagnostics).decode()
assert "ClientResponseError" in diagnostics_text
assert "example.com" not in diagnostics_text
mock_envoy.request.side_effect = ClientConnectionError
mock_envoy.fixture_collection.side_effect = EnvoyAuthenticationRequired(
"this is a test", 403
)
diagnostics = await get_diagnostics_for_config_entry(
hass, hass_client, config_entry_options
)
assert diagnostics["fixtures"]["/info_log"] == {
"Error": "Aiohttp Client error ClientConnectionError"
}
assert (
diagnostics["fixtures"]["collection_aborted_log"]
== "Error: EnvoyAuthenticationRequired: 403"
)
mock_envoy.fixture_collection.side_effect = EnvoyError("Test")
diagnostics = await get_diagnostics_for_config_entry(
hass, hass_client, config_entry_options
)
assert diagnostics["fixtures"]["collection_aborted_log"] == "Error: EnvoyError"
mock_envoy.fixture_collection.side_effect = ClientConnectionError
diagnostics = await get_diagnostics_for_config_entry(
hass, hass_client, config_entry_options
)
assert (
diagnostics["fixtures"]["collection_aborted_log"]
== "Error: ClientConnectionError"
)
@pytest.mark.parametrize(