mirror of
https://github.com/home-assistant/core.git
synced 2026-12-04 12:50:45 -04:00
Restore ZHA log levels only when the last permit session ends (#185604)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: zigpy-review-bot <286747149+zigpy-review-bot@users.noreply.github.com> Co-authored-by: TheJulianJES <TheJulianJES@users.noreply.github.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
zigpy-review-bot
TheJulianJES
parent
f936e779e0
commit
cbbd58b4ca
@@ -827,7 +827,10 @@ class ZHAGatewayProxy(EventBase):
|
||||
@callback
|
||||
def async_enable_debug_mode(self, filterer: _LogFilterType | None = None) -> None:
|
||||
"""Enable debug mode for ZHA."""
|
||||
self._log_levels[DEBUG_LEVEL_ORIGINAL] = async_capture_log_levels()
|
||||
# Only the first of overlapping sessions captures the levels to restore,
|
||||
# later ones would capture the debug levels set by the first
|
||||
if self._log_queue_handler_count == 0:
|
||||
self._log_levels[DEBUG_LEVEL_ORIGINAL] = async_capture_log_levels()
|
||||
async_set_logger_levels(DEBUG_LEVELS)
|
||||
self._log_levels[DEBUG_LEVEL_CURRENT] = async_capture_log_levels()
|
||||
|
||||
@@ -848,20 +851,23 @@ class ZHAGatewayProxy(EventBase):
|
||||
@callback
|
||||
def async_disable_debug_mode(self, filterer: _LogFilterType | None = None) -> None:
|
||||
"""Disable debug mode for ZHA."""
|
||||
if filterer:
|
||||
self._log_queue_handler.removeFilter(filterer)
|
||||
|
||||
# Only restore the original levels and stop relaying logs once nothing
|
||||
# else is using debug mode
|
||||
self._log_queue_handler_count -= 1
|
||||
if self._log_queue_handler_count > 0:
|
||||
return
|
||||
|
||||
async_set_logger_levels(self._log_levels[DEBUG_LEVEL_ORIGINAL])
|
||||
self._log_levels[DEBUG_LEVEL_CURRENT] = async_capture_log_levels()
|
||||
for logger_name in DEBUG_RELAY_LOGGERS:
|
||||
logging.getLogger(logger_name).removeHandler(self._log_queue_handler)
|
||||
|
||||
# Only stop the log queue handler if nothing else is using it
|
||||
self._log_queue_handler_count -= 1
|
||||
|
||||
if self._log_queue_handler.listener and self._log_queue_handler_count == 0:
|
||||
if self._log_queue_handler.listener:
|
||||
self._log_queue_handler.listener.stop()
|
||||
|
||||
if filterer:
|
||||
self._log_queue_handler.removeFilter(filterer)
|
||||
|
||||
self.debug_enabled = False
|
||||
|
||||
async def shutdown(self) -> None:
|
||||
|
||||
@@ -1,25 +1,32 @@
|
||||
"""Tests for ZHA helpers."""
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Callable, Coroutine
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from probatio import to_field_list
|
||||
import pytest
|
||||
from pytest_homeassistant.common import MockConfigEntry
|
||||
from zha.application.const import ATTR_TYPE, ZHA_GW_MSG
|
||||
from zigpy.application import ControllerApplication
|
||||
from zigpy.types.basic import uint16_t
|
||||
from zigpy.zcl.clusters import lighting
|
||||
|
||||
from homeassistant.components.zha import const as zha_const
|
||||
from homeassistant.components.zha.helpers import (
|
||||
ZHA_GW_MSG_LOG_ENTRY,
|
||||
ZHA_GW_MSG_LOG_OUTPUT,
|
||||
cluster_command_schema_to_vol_schema,
|
||||
convert_to_zcl_values,
|
||||
create_zha_config,
|
||||
exclude_none_values,
|
||||
get_zha_data,
|
||||
get_zha_gateway_proxy,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.helpers import config_validation as cv
|
||||
from homeassistant.helpers.dispatcher import async_dispatcher_connect
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
@@ -217,3 +224,60 @@ async def test_create_zha_config_remove_unused(
|
||||
|
||||
# Does not error out
|
||||
create_zha_config(hass, ha_zha_data)
|
||||
|
||||
|
||||
async def test_debug_mode_log_filter(
|
||||
hass: HomeAssistant, setup_zha: Callable[..., Coroutine[None]]
|
||||
) -> None:
|
||||
"""Test a debug mode session filters relayed logs only until it ends."""
|
||||
await setup_zha()
|
||||
gateway_proxy = get_zha_gateway_proxy(hass)
|
||||
|
||||
relayed: list[str] = []
|
||||
marker_relayed = asyncio.Event()
|
||||
|
||||
@callback
|
||||
def collect(data: dict[str, Any]) -> None:
|
||||
if data[ATTR_TYPE] != ZHA_GW_MSG_LOG_OUTPUT:
|
||||
return
|
||||
message = data[ZHA_GW_MSG_LOG_ENTRY]["message"][0]
|
||||
if message.startswith("test "):
|
||||
relayed.append(message)
|
||||
if message == "test marker":
|
||||
marker_relayed.set()
|
||||
|
||||
unsub = async_dispatcher_connect(hass, ZHA_GW_MSG, collect)
|
||||
|
||||
async def log_and_wait(*messages: str) -> None:
|
||||
# The relay is a queue, so the marker arrives after everything before it
|
||||
marker_relayed.clear()
|
||||
for message in (*messages, "test marker"):
|
||||
logging.getLogger("zha").debug(message)
|
||||
async with asyncio.timeout(5):
|
||||
await marker_relayed.wait()
|
||||
|
||||
def drop_filtered(record: logging.LogRecord) -> bool:
|
||||
return record.getMessage() != "test filtered"
|
||||
|
||||
gateway_proxy.async_enable_debug_mode(drop_filtered)
|
||||
await log_and_wait("test filtered", "test kept")
|
||||
gateway_proxy.async_disable_debug_mode(drop_filtered)
|
||||
assert relayed == ["test kept", "test marker"]
|
||||
|
||||
# A later session without the filter relays everything again
|
||||
relayed.clear()
|
||||
gateway_proxy.async_enable_debug_mode()
|
||||
await log_and_wait("test filtered")
|
||||
gateway_proxy.async_disable_debug_mode()
|
||||
assert relayed == ["test filtered", "test marker"]
|
||||
|
||||
# Ending the filtered session removes its filter while another one is open
|
||||
relayed.clear()
|
||||
gateway_proxy.async_enable_debug_mode(drop_filtered)
|
||||
gateway_proxy.async_enable_debug_mode()
|
||||
gateway_proxy.async_disable_debug_mode(drop_filtered)
|
||||
await log_and_wait("test filtered")
|
||||
gateway_proxy.async_disable_debug_mode()
|
||||
assert relayed == ["test filtered", "test marker"]
|
||||
|
||||
unsub()
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
"""Test ZHA WebSocket API."""
|
||||
|
||||
import asyncio
|
||||
from binascii import unhexlify
|
||||
from collections.abc import Callable, Coroutine
|
||||
from copy import deepcopy
|
||||
from typing import TYPE_CHECKING
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from unittest.mock import ANY, AsyncMock, MagicMock, call, patch
|
||||
|
||||
import probatio
|
||||
@@ -52,6 +54,7 @@ from homeassistant.components.zha.const import (
|
||||
EZSP_OVERWRITE_EUI64,
|
||||
)
|
||||
from homeassistant.components.zha.helpers import (
|
||||
DEBUG_LEVELS,
|
||||
ZHADeviceProxy,
|
||||
ZHAGatewayProxy,
|
||||
get_zha_gateway,
|
||||
@@ -954,6 +957,48 @@ async def test_ws_permit_ha12(
|
||||
assert app_controller.permit_with_link_key.call_count == 0
|
||||
|
||||
|
||||
async def test_ws_permit_overlapping_restores_log_levels(
|
||||
zha_client: MockHAClientWebSocket, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""Test overlapping permit subscriptions restore the original log levels."""
|
||||
|
||||
async def send_and_wait_result(payload: dict[str, Any]) -> None:
|
||||
await zha_client.send_json(payload)
|
||||
msg = await zha_client.receive_json()
|
||||
# Skip the log events relayed to the open permit subscriptions
|
||||
while msg["type"] != TYPE_RESULT:
|
||||
msg = await zha_client.receive_json()
|
||||
assert msg["id"] == payload[ID]
|
||||
assert msg["success"]
|
||||
|
||||
def log_levels() -> dict[str, int]:
|
||||
return {name: logging.getLogger(name).level for name in DEBUG_LEVELS}
|
||||
|
||||
for name in DEBUG_LEVELS:
|
||||
caplog.set_level(logging.INFO, logger=name)
|
||||
|
||||
await send_and_wait_result({ID: 20, TYPE: f"{DOMAIN}/devices/{SERVICE_PERMIT}"})
|
||||
await send_and_wait_result({ID: 21, TYPE: f"{DOMAIN}/devices/{SERVICE_PERMIT}"})
|
||||
assert log_levels() == DEBUG_LEVELS
|
||||
|
||||
# Ending the first session must leave the second one in debug mode
|
||||
await send_and_wait_result({ID: 22, TYPE: "unsubscribe_events", "subscription": 20})
|
||||
assert log_levels() == DEBUG_LEVELS
|
||||
|
||||
# and still relaying logs to it
|
||||
logging.getLogger("zha").debug("still relayed")
|
||||
async with asyncio.timeout(5):
|
||||
while True:
|
||||
msg = await zha_client.receive_json()
|
||||
log_entry = msg.get("event", {}).get("log_entry", {})
|
||||
if msg["id"] == 21 and log_entry.get("message") == ["still relayed"]:
|
||||
break
|
||||
|
||||
# Ending the last session restores the levels from before the first one
|
||||
await send_and_wait_result({ID: 23, TYPE: "unsubscribe_events", "subscription": 21})
|
||||
assert log_levels() == dict.fromkeys(DEBUG_LEVELS, logging.INFO)
|
||||
|
||||
|
||||
async def test_get_network_settings(
|
||||
app_controller: ControllerApplication, zha_client
|
||||
) -> None:
|
||||
|
||||
Reference in New Issue
Block a user