From 5843e63878cb64a4c83202ffd2242fba5726efe3 Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Sun, 20 Apr 2025 02:13:01 +0200 Subject: [PATCH] Add contextmanager to reset logger after set_level call in tests (#143295) --- tests/common.py | 23 ++++ tests/components/bluetooth/test_manager.py | 84 ++++++------ tests/components/bluetooth/test_scanner.py | 125 +++++++++--------- tests/components/esphome/test_manager.py | 134 +++++++++---------- tests/components/http/test_init.py | 36 +++--- tests/components/logger/test_init.py | 43 +++---- tests/components/websocket_api/test_http.py | 42 +++--- tests/components/zwave_js/test_init.py | 135 ++++++++++---------- 8 files changed, 304 insertions(+), 318 deletions(-) diff --git a/tests/common.py b/tests/common.py index f426d2aebd2..8f06aa54383 100644 --- a/tests/common.py +++ b/tests/common.py @@ -46,6 +46,7 @@ from homeassistant.components import device_automation, persistent_notification from homeassistant.components.device_automation import ( # noqa: F401 _async_get_device_automation_capabilities as async_get_device_automation_capabilities, ) +from homeassistant.components.logger import DOMAIN as LOGGER_DOMAIN, SERVICE_SET_LEVEL from homeassistant.config import IntegrationConfigInfo, async_process_component_config from homeassistant.config_entries import ConfigEntry, ConfigFlow, ConfigFlowResult from homeassistant.const import ( @@ -1688,6 +1689,28 @@ def async_mock_cloud_connection_status(hass: HomeAssistant, connected: bool) -> async_dispatcher_send(hass, SIGNAL_CLOUD_CONNECTION_STATE, state) +@asynccontextmanager +async def async_call_logger_set_level( + logger: str, + level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "FATAL", "CRITICAL"], + *, + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, +) -> AsyncGenerator[None]: + """Context manager to reset loggers after logger.set_level call.""" + assert LOGGER_DOMAIN in hass.data, "'logger' integration not setup" + with caplog.at_level(logging.NOTSET, logger): + await hass.services.async_call( + LOGGER_DOMAIN, + SERVICE_SET_LEVEL, + {logger: level}, + blocking=True, + ) + await hass.async_block_till_done() + yield + hass.data[LOGGER_DOMAIN].overrides.clear() + + def import_and_test_deprecated_constant_enum( caplog: pytest.LogCaptureFixture, module: ModuleType, diff --git a/tests/components/bluetooth/test_manager.py b/tests/components/bluetooth/test_manager.py index 48d1a38375d..bf773b69a99 100644 --- a/tests/components/bluetooth/test_manager.py +++ b/tests/components/bluetooth/test_manager.py @@ -61,6 +61,7 @@ from . import ( from tests.common import ( MockConfigEntry, MockModule, + async_call_logger_set_level, async_fire_time_changed, load_fixture, mock_integration, @@ -1144,54 +1145,45 @@ async def test_debug_logging( ) -> None: """Test debug logging.""" assert await async_setup_component(hass, "logger", {"logger": {}}) - await hass.services.async_call( - "logger", - "set_level", - {"homeassistant.components.bluetooth": "DEBUG"}, - blocking=True, - ) - await hass.async_block_till_done() + async with async_call_logger_set_level( + "homeassistant.components.bluetooth", "DEBUG", hass=hass, caplog=caplog + ): + address = "44:44:33:11:23:41" + start_time_monotonic = 50.0 - address = "44:44:33:11:23:41" - start_time_monotonic = 50.0 + switchbot_device_poor_signal_hci0 = generate_ble_device( + address, "wohand_poor_signal_hci0" + ) + switchbot_adv_poor_signal_hci0 = generate_advertisement_data( + local_name="wohand_poor_signal_hci0", service_uuids=[], rssi=-100 + ) + inject_advertisement_with_time_and_source( + hass, + switchbot_device_poor_signal_hci0, + switchbot_adv_poor_signal_hci0, + start_time_monotonic, + "hci0", + ) + assert "wohand_poor_signal_hci0" in caplog.text + caplog.clear() - switchbot_device_poor_signal_hci0 = generate_ble_device( - address, "wohand_poor_signal_hci0" - ) - switchbot_adv_poor_signal_hci0 = generate_advertisement_data( - local_name="wohand_poor_signal_hci0", service_uuids=[], rssi=-100 - ) - inject_advertisement_with_time_and_source( - hass, - switchbot_device_poor_signal_hci0, - switchbot_adv_poor_signal_hci0, - start_time_monotonic, - "hci0", - ) - assert "wohand_poor_signal_hci0" in caplog.text - caplog.clear() - - await hass.services.async_call( - "logger", - "set_level", - {"homeassistant.components.bluetooth": "WARNING"}, - blocking=True, - ) - - switchbot_device_good_signal_hci0 = generate_ble_device( - address, "wohand_good_signal_hci0" - ) - switchbot_adv_good_signal_hci0 = generate_advertisement_data( - local_name="wohand_good_signal_hci0", service_uuids=[], rssi=-33 - ) - inject_advertisement_with_time_and_source( - hass, - switchbot_device_good_signal_hci0, - switchbot_adv_good_signal_hci0, - start_time_monotonic, - "hci0", - ) - assert "wohand_good_signal_hci0" not in caplog.text + async with async_call_logger_set_level( + "homeassistant.components.bluetooth", "WARNING", hass=hass, caplog=caplog + ): + switchbot_device_good_signal_hci0 = generate_ble_device( + address, "wohand_good_signal_hci0" + ) + switchbot_adv_good_signal_hci0 = generate_advertisement_data( + local_name="wohand_good_signal_hci0", service_uuids=[], rssi=-33 + ) + inject_advertisement_with_time_and_source( + hass, + switchbot_device_good_signal_hci0, + switchbot_adv_good_signal_hci0, + start_time_monotonic, + "hci0", + ) + assert "wohand_good_signal_hci0" not in caplog.text @pytest.mark.usefixtures("enable_bluetooth", "macos_adapter") diff --git a/tests/components/bluetooth/test_scanner.py b/tests/components/bluetooth/test_scanner.py index 6acb86476e7..142438fbb95 100644 --- a/tests/components/bluetooth/test_scanner.py +++ b/tests/components/bluetooth/test_scanner.py @@ -29,7 +29,11 @@ from . import ( patch_bluetooth_time, ) -from tests.common import MockConfigEntry, async_fire_time_changed +from tests.common import ( + MockConfigEntry, + async_call_logger_set_level, + async_fire_time_changed, +) # If the adapter is in a stuck state the following errors are raised: NEED_RESET_ERRORS = [ @@ -482,70 +486,67 @@ async def test_adapter_fails_to_start_and_takes_a_bit_to_init( ) -> None: """Test we can recover the adapter at startup and we wait for Dbus to init.""" assert await async_setup_component(hass, "logger", {}) - await hass.services.async_call( - "logger", - "set_level", - {"homeassistant.components.bluetooth": "DEBUG"}, - blocking=True, - ) - called_start = 0 - called_stop = 0 - _callback = None - mock_discovered = [] - - class MockBleakScanner: - async def start(self, *args, **kwargs): - """Mock Start.""" - nonlocal called_start - called_start += 1 - if called_start == 1: - raise BleakError("org.freedesktop.DBus.Error.UnknownObject") - if called_start == 2: - raise BleakError("org.bluez.Error.InProgress") - if called_start == 3: - raise BleakError("org.bluez.Error.InProgress") - - async def stop(self, *args, **kwargs): - """Mock Start.""" - nonlocal called_stop - called_stop += 1 - - @property - def discovered_devices(self): - """Mock discovered_devices.""" - nonlocal mock_discovered - return mock_discovered - - def register_detection_callback(self, callback: AdvertisementDataCallback): - """Mock Register Detection Callback.""" - nonlocal _callback - _callback = callback - - scanner = MockBleakScanner() - start_time_monotonic = time.monotonic() - - with ( - patch( - "habluetooth.scanner.ADAPTER_INIT_TIME", - 0, - ), - patch_bluetooth_time( - start_time_monotonic, - ), - patch( - "habluetooth.scanner.OriginalBleakScanner", - return_value=scanner, - ), - patch( - "habluetooth.util.recover_adapter", return_value=True - ) as mock_recover_adapter, + async with async_call_logger_set_level( + "homeassistant.components.bluetooth", "DEBUG", hass=hass, caplog=caplog ): - await async_setup_with_one_adapter(hass) + called_start = 0 + called_stop = 0 + _callback = None + mock_discovered = [] - assert called_start == 4 + class MockBleakScanner: + async def start(self, *args, **kwargs): + """Mock Start.""" + nonlocal called_start + called_start += 1 + if called_start == 1: + raise BleakError("org.freedesktop.DBus.Error.UnknownObject") + if called_start == 2: + raise BleakError("org.bluez.Error.InProgress") + if called_start == 3: + raise BleakError("org.bluez.Error.InProgress") - assert len(mock_recover_adapter.mock_calls) == 1 - assert "Waiting for adapter to initialize" in caplog.text + async def stop(self, *args, **kwargs): + """Mock Start.""" + nonlocal called_stop + called_stop += 1 + + @property + def discovered_devices(self): + """Mock discovered_devices.""" + nonlocal mock_discovered + return mock_discovered + + def register_detection_callback(self, callback: AdvertisementDataCallback): + """Mock Register Detection Callback.""" + nonlocal _callback + _callback = callback + + scanner = MockBleakScanner() + start_time_monotonic = time.monotonic() + + with ( + patch( + "habluetooth.scanner.ADAPTER_INIT_TIME", + 0, + ), + patch_bluetooth_time( + start_time_monotonic, + ), + patch( + "habluetooth.scanner.OriginalBleakScanner", + return_value=scanner, + ), + patch( + "habluetooth.util.recover_adapter", return_value=True + ) as mock_recover_adapter, + ): + await async_setup_with_one_adapter(hass) + + assert called_start == 4 + + assert len(mock_recover_adapter.mock_calls) == 1 + assert "Waiting for adapter to initialize" in caplog.text @pytest.mark.usefixtures("one_adapter") diff --git a/tests/components/esphome/test_manager.py b/tests/components/esphome/test_manager.py index 9e7810cde8f..12ae58a8240 100644 --- a/tests/components/esphome/test_manager.py +++ b/tests/components/esphome/test_manager.py @@ -49,7 +49,12 @@ from homeassistant.setup import async_setup_component from .conftest import MockESPHomeDevice -from tests.common import MockConfigEntry, async_capture_events, async_mock_service +from tests.common import ( + MockConfigEntry, + async_call_logger_set_level, + async_capture_events, + async_mock_service, +) async def test_esphome_device_subscribe_logs( @@ -83,62 +88,50 @@ async def test_esphome_device_subscribe_logs( ) await hass.async_block_till_done() - await hass.services.async_call( - "logger", - "set_level", - {"homeassistant.components.esphome": "DEBUG"}, - blocking=True, - ) - assert device.current_log_level == LogLevel.LOG_LEVEL_VERY_VERBOSE + async with async_call_logger_set_level( + "homeassistant.components.esphome", "DEBUG", hass=hass, caplog=caplog + ): + assert device.current_log_level == LogLevel.LOG_LEVEL_VERY_VERBOSE - caplog.set_level(logging.DEBUG) - device.mock_on_log_message( - Mock(level=LogLevel.LOG_LEVEL_INFO, message=b"test_log_message") - ) - await hass.async_block_till_done() - assert "test_log_message" in caplog.text + caplog.set_level(logging.DEBUG) + device.mock_on_log_message( + Mock(level=LogLevel.LOG_LEVEL_INFO, message=b"test_log_message") + ) + await hass.async_block_till_done() + assert "test_log_message" in caplog.text - device.mock_on_log_message( - Mock(level=LogLevel.LOG_LEVEL_ERROR, message=b"test_error_log_message") - ) - await hass.async_block_till_done() - assert "test_error_log_message" in caplog.text + device.mock_on_log_message( + Mock(level=LogLevel.LOG_LEVEL_ERROR, message=b"test_error_log_message") + ) + await hass.async_block_till_done() + assert "test_error_log_message" in caplog.text - caplog.set_level(logging.ERROR) - device.mock_on_log_message( - Mock(level=LogLevel.LOG_LEVEL_DEBUG, message=b"test_debug_log_message") - ) - await hass.async_block_till_done() - assert "test_debug_log_message" not in caplog.text + caplog.set_level(logging.ERROR) + device.mock_on_log_message( + Mock(level=LogLevel.LOG_LEVEL_DEBUG, message=b"test_debug_log_message") + ) + await hass.async_block_till_done() + assert "test_debug_log_message" not in caplog.text - caplog.set_level(logging.DEBUG) - device.mock_on_log_message( - Mock(level=LogLevel.LOG_LEVEL_DEBUG, message=b"test_debug_log_message") - ) - await hass.async_block_till_done() - assert "test_debug_log_message" in caplog.text + caplog.set_level(logging.DEBUG) + device.mock_on_log_message( + Mock(level=LogLevel.LOG_LEVEL_DEBUG, message=b"test_debug_log_message") + ) + await hass.async_block_till_done() + assert "test_debug_log_message" in caplog.text - await hass.services.async_call( - "logger", - "set_level", - {"homeassistant.components.esphome": "WARNING"}, - blocking=True, - ) - assert device.current_log_level == LogLevel.LOG_LEVEL_WARN - await hass.services.async_call( - "logger", - "set_level", - {"homeassistant.components.esphome": "ERROR"}, - blocking=True, - ) - assert device.current_log_level == LogLevel.LOG_LEVEL_ERROR - await hass.services.async_call( - "logger", - "set_level", - {"homeassistant.components.esphome": "INFO"}, - blocking=True, - ) - assert device.current_log_level == LogLevel.LOG_LEVEL_CONFIG + async with async_call_logger_set_level( + "homeassistant.components.esphome", "WARNING", hass=hass, caplog=caplog + ): + assert device.current_log_level == LogLevel.LOG_LEVEL_WARN + async with async_call_logger_set_level( + "homeassistant.components.esphome", "ERROR", hass=hass, caplog=caplog + ): + assert device.current_log_level == LogLevel.LOG_LEVEL_ERROR + async with async_call_logger_set_level( + "homeassistant.components.esphome", "INFO", hass=hass, caplog=caplog + ): + assert device.current_log_level == LogLevel.LOG_LEVEL_CONFIG async def test_esphome_device_service_calls_not_allowed( @@ -961,31 +954,22 @@ async def test_debug_logging( caplog: pytest.LogCaptureFixture, ) -> None: """Test enabling and disabling debug logging.""" - with caplog.at_level(logging.NOTSET, "homeassistant.components.esphome"): - assert await async_setup_component(hass, "logger", {"logger": {}}) - await mock_generic_device_entry( - mock_client=mock_client, - entity_info=[], - user_service=[], - states=[], - ) - await hass.services.async_call( - "logger", - "set_level", - {"homeassistant.components.esphome": "DEBUG"}, - blocking=True, - ) - await hass.async_block_till_done() + assert await async_setup_component(hass, "logger", {"logger": {}}) + await mock_generic_device_entry( + mock_client=mock_client, + entity_info=[], + user_service=[], + states=[], + ) + async with async_call_logger_set_level( + "homeassistant.components.esphome", "DEBUG", hass=hass, caplog=caplog + ): mock_client.set_debug.assert_has_calls([call(True)]) - mock_client.reset_mock() - await hass.services.async_call( - "logger", - "set_level", - {"homeassistant.components.esphome": "WARNING"}, - blocking=True, - ) - await hass.async_block_till_done() + + async with async_call_logger_set_level( + "homeassistant.components.esphome", "WARNING", hass=hass, caplog=caplog + ): mock_client.set_debug.assert_has_calls([call(False)]) diff --git a/tests/components/http/test_init.py b/tests/components/http/test_init.py index 4d96f2267fa..2937e673946 100644 --- a/tests/components/http/test_init.py +++ b/tests/components/http/test_init.py @@ -22,7 +22,7 @@ from homeassistant.setup import async_setup_component from homeassistant.util import dt as dt_util from homeassistant.util.ssl import server_context_intermediate, server_context_modern -from tests.common import async_fire_time_changed +from tests.common import async_call_logger_set_level, async_fire_time_changed from tests.typing import ClientSessionGenerator @@ -505,27 +505,21 @@ async def test_logging( ) ) hass.states.async_set("logging.entity", "hello") - await hass.services.async_call( - "logger", - "set_level", - {"aiohttp.access": "info"}, - blocking=True, - ) - client = await hass_client() - response = await client.get("/api/states/logging.entity") - assert response.status == HTTPStatus.OK + async with async_call_logger_set_level( + "aiohttp.access", "INFO", hass=hass, caplog=caplog + ): + client = await hass_client() + response = await client.get("/api/states/logging.entity") + assert response.status == HTTPStatus.OK - assert "GET /api/states/logging.entity" in caplog.text - caplog.clear() - await hass.services.async_call( - "logger", - "set_level", - {"aiohttp.access": "warning"}, - blocking=True, - ) - response = await client.get("/api/states/logging.entity") - assert response.status == HTTPStatus.OK - assert "GET /api/states/logging.entity" not in caplog.text + assert "GET /api/states/logging.entity" in caplog.text + caplog.clear() + async with async_call_logger_set_level( + "aiohttp.access", "WARNING", hass=hass, caplog=caplog + ): + response = await client.get("/api/states/logging.entity") + assert response.status == HTTPStatus.OK + assert "GET /api/states/logging.entity" not in caplog.text async def test_register_static_paths( diff --git a/tests/components/logger/test_init.py b/tests/components/logger/test_init.py index 24e58a77226..53b8b72b385 100644 --- a/tests/components/logger/test_init.py +++ b/tests/components/logger/test_init.py @@ -15,7 +15,7 @@ from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from homeassistant.util import dt as dt_util -from tests.common import async_fire_time_changed +from tests.common import async_call_logger_set_level, async_fire_time_changed HASS_NS = "unused.homeassistant" COMPONENTS_NS = f"{HASS_NS}.components" @@ -73,28 +73,27 @@ async def test_log_filtering( msg_test(filter_logger, True, "format string shouldfilter%s", "not") # Filtering should work even if log level is modified - await hass.services.async_call( - "logger", - "set_level", - {"test.filter": "warning"}, - blocking=True, - ) - assert filter_logger.getEffectiveLevel() == logging.WARNING - msg_test( - filter_logger, - False, - "this line containing shouldfilterall should still be filtered", - ) + async with async_call_logger_set_level( + "test.filter", "WARNING", hass=hass, caplog=caplog + ): + assert filter_logger.getEffectiveLevel() == logging.WARNING + msg_test( + filter_logger, + False, + "this line containing shouldfilterall should still be filtered", + ) - # Filtering should be scoped to a service - msg_test( - filter_logger, True, "this line containing otherfilterer should not be filtered" - ) - msg_test( - logging.getLogger("test.other_filter"), - False, - "this line containing otherfilterer SHOULD be filtered", - ) + # Filtering should be scoped to a service + msg_test( + filter_logger, + True, + "this line containing otherfilterer should not be filtered", + ) + msg_test( + logging.getLogger("test.other_filter"), + False, + "this line containing otherfilterer SHOULD be filtered", + ) async def test_setting_level(hass: HomeAssistant) -> None: diff --git a/tests/components/websocket_api/test_http.py b/tests/components/websocket_api/test_http.py index 075f5fa9c0a..b4b11d9cf02 100644 --- a/tests/components/websocket_api/test_http.py +++ b/tests/components/websocket_api/test_http.py @@ -19,7 +19,7 @@ from homeassistant.core import HomeAssistant, callback from homeassistant.setup import async_setup_component from homeassistant.util.dt import utcnow -from tests.common import async_fire_time_changed +from tests.common import async_call_logger_set_level, async_fire_time_changed from tests.typing import MockHAClientWebSocket, WebSocketGenerator @@ -533,27 +533,19 @@ async def test_enable_disable_debug_logging( ) -> None: """Test enabling and disabling debug logging.""" assert await async_setup_component(hass, "logger", {"logger": {}}) - await hass.services.async_call( - "logger", - "set_level", - {"homeassistant.components.websocket_api": "DEBUG"}, - blocking=True, - ) - await hass.async_block_till_done() - await websocket_client.send_json({"id": 1, "type": "ping"}) - msg = await websocket_client.receive_json() - assert msg["id"] == 1 - assert msg["type"] == "pong" - assert 'Sending b\'{"id":1,"type":"pong"}\'' in caplog.text - await hass.services.async_call( - "logger", - "set_level", - {"homeassistant.components.websocket_api": "WARNING"}, - blocking=True, - ) - await hass.async_block_till_done() - await websocket_client.send_json({"id": 2, "type": "ping"}) - msg = await websocket_client.receive_json() - assert msg["id"] == 2 - assert msg["type"] == "pong" - assert 'Sending b\'{"id":2,"type":"pong"}\'' not in caplog.text + async with async_call_logger_set_level( + "homeassistant.components.websocket_api", "DEBUG", hass=hass, caplog=caplog + ): + await websocket_client.send_json({"id": 1, "type": "ping"}) + msg = await websocket_client.receive_json() + assert msg["id"] == 1 + assert msg["type"] == "pong" + assert 'Sending b\'{"id":1,"type":"pong"}\'' in caplog.text + async with async_call_logger_set_level( + "homeassistant.components.websocket_api", "WARNING", hass=hass, caplog=caplog + ): + await websocket_client.send_json({"id": 2, "type": "ping"}) + msg = await websocket_client.receive_json() + assert msg["id"] == 2 + assert msg["type"] == "pong" + assert 'Sending b\'{"id":2,"type":"pong"}\'' not in caplog.text diff --git a/tests/components/zwave_js/test_init.py b/tests/components/zwave_js/test_init.py index 4abda90b5cf..a0423efdf52 100644 --- a/tests/components/zwave_js/test_init.py +++ b/tests/components/zwave_js/test_init.py @@ -23,7 +23,6 @@ from zwave_js_server.model.node import Node, NodeDataType from zwave_js_server.model.version import VersionInfo from homeassistant.components.hassio import HassioAPIError -from homeassistant.components.logger import DOMAIN as LOGGER_DOMAIN, SERVICE_SET_LEVEL from homeassistant.components.persistent_notification import async_dismiss from homeassistant.components.zwave_js import DOMAIN from homeassistant.components.zwave_js.helpers import get_device_id, get_device_id_ext @@ -42,6 +41,7 @@ from .common import AIR_TEMPERATURE_SENSOR, EATON_RF9640_ENTITY from tests.common import ( MockConfigEntry, + async_call_logger_set_level, async_fire_time_changed, async_get_persistent_notifications, ) @@ -2018,7 +2018,9 @@ async def test_identify_event( assert "network with the home ID `3245146787`" in notifications[msg_id]["message"] -async def test_server_logging(hass: HomeAssistant, client: MagicMock) -> None: +async def test_server_logging( + hass: HomeAssistant, client: MagicMock, caplog: pytest.LogCaptureFixture +) -> None: """Test automatic server logging functionality.""" def _reset_mocks(): @@ -2037,83 +2039,82 @@ async def test_server_logging(hass: HomeAssistant, client: MagicMock) -> None: # Setup logger and set log level to debug to trigger event listener assert await async_setup_component(hass, "logger", {"logger": {}}) - assert logging.getLogger("zwave_js_server").getEffectiveLevel() == logging.INFO - client.async_send_command.reset_mock() - await hass.services.async_call( - LOGGER_DOMAIN, SERVICE_SET_LEVEL, {"zwave_js_server": "debug"}, blocking=True - ) - await hass.async_block_till_done() assert logging.getLogger("zwave_js_server").getEffectiveLevel() == logging.DEBUG + client.async_send_command.reset_mock() + async with async_call_logger_set_level( + "zwave_js_server", "DEBUG", hass=hass, caplog=caplog + ): + assert logging.getLogger("zwave_js_server").getEffectiveLevel() == logging.DEBUG - # Validate that the server logging was enabled - assert len(client.async_send_command.call_args_list) == 1 - assert client.async_send_command.call_args[0][0] == { - "command": "driver.update_log_config", - "config": {"level": "debug"}, - } - assert client.enable_server_logging.called - assert not client.disable_server_logging.called + # Validate that the server logging was enabled + assert len(client.async_send_command.call_args_list) == 1 + assert client.async_send_command.call_args[0][0] == { + "command": "driver.update_log_config", + "config": {"level": "debug"}, + } + assert client.enable_server_logging.called + assert not client.disable_server_logging.called - _reset_mocks() + _reset_mocks() - # Emulate server by setting log level to debug - event = Event( - type="log config updated", - data={ - "source": "driver", - "event": "log config updated", - "config": { - "enabled": False, - "level": "debug", - "logToFile": True, - "filename": "test", - "forceConsole": True, + # Emulate server by setting log level to debug + event = Event( + type="log config updated", + data={ + "source": "driver", + "event": "log config updated", + "config": { + "enabled": False, + "level": "debug", + "logToFile": True, + "filename": "test", + "forceConsole": True, + }, }, - }, - ) - client.driver.receive_event(event) + ) + client.driver.receive_event(event) - # "Enable" server logging and unload the entry - client.server_logging_enabled = True - await hass.config_entries.async_unload(entry.entry_id) + # "Enable" server logging and unload the entry + client.server_logging_enabled = True + await hass.config_entries.async_unload(entry.entry_id) - # Validate that the server logging was disabled - assert len(client.async_send_command.call_args_list) == 1 - assert client.async_send_command.call_args[0][0] == { - "command": "driver.update_log_config", - "config": {"level": "info"}, - } - assert not client.enable_server_logging.called - assert client.disable_server_logging.called + # Validate that the server logging was disabled + assert len(client.async_send_command.call_args_list) == 1 + assert client.async_send_command.call_args[0][0] == { + "command": "driver.update_log_config", + "config": {"level": "info"}, + } + assert not client.enable_server_logging.called + assert client.disable_server_logging.called - _reset_mocks() + _reset_mocks() - # Validate that the server logging doesn't get enabled because HA thinks it already - # is enabled - await hass.config_entries.async_setup(entry.entry_id) - await hass.async_block_till_done() - assert len(client.async_send_command.call_args_list) == 2 - assert client.async_send_command.call_args_list[0][0][0] == { - "command": "controller.get_provisioning_entries", - } - assert client.async_send_command.call_args_list[1][0][0] == { - "command": "controller.get_provisioning_entry", - "dskOrNodeId": 1, - } - assert not client.enable_server_logging.called - assert not client.disable_server_logging.called + # Validate that the server logging doesn't get enabled because HA thinks it already + # is enabled + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + assert len(client.async_send_command.call_args_list) == 2 + assert client.async_send_command.call_args_list[0][0][0] == { + "command": "controller.get_provisioning_entries", + } + assert client.async_send_command.call_args_list[1][0][0] == { + "command": "controller.get_provisioning_entry", + "dskOrNodeId": 1, + } + assert not client.enable_server_logging.called + assert not client.disable_server_logging.called - _reset_mocks() + _reset_mocks() - # "Disable" server logging and unload the entry - client.server_logging_enabled = False - await hass.config_entries.async_unload(entry.entry_id) + # "Disable" server logging and unload the entry + client.server_logging_enabled = False + await hass.config_entries.async_unload(entry.entry_id) - # Validate that the server logging was not disabled because HA thinks it is already - # is disabled - assert len(client.async_send_command.call_args_list) == 0 - assert not client.enable_server_logging.called - assert not client.disable_server_logging.called + # Validate that the server logging was not disabled because HA thinks it is already + # is disabled + assert len(client.async_send_command.call_args_list) == 0 + assert not client.enable_server_logging.called + assert not client.disable_server_logging.called async def test_factory_reset_node(