Add contextmanager to reset logger after set_level call in tests (#143295)

This commit is contained in:
Marc Mueller 2025-04-20 02:13:01 +02:00 committed by GitHub
parent 961f8afe53
commit 5843e63878
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 304 additions and 318 deletions

View File

@ -46,6 +46,7 @@ from homeassistant.components import device_automation, persistent_notification
from homeassistant.components.device_automation import ( # noqa: F401 from homeassistant.components.device_automation import ( # noqa: F401
_async_get_device_automation_capabilities as async_get_device_automation_capabilities, _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 import IntegrationConfigInfo, async_process_component_config
from homeassistant.config_entries import ConfigEntry, ConfigFlow, ConfigFlowResult from homeassistant.config_entries import ConfigEntry, ConfigFlow, ConfigFlowResult
from homeassistant.const import ( 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) 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( def import_and_test_deprecated_constant_enum(
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
module: ModuleType, module: ModuleType,

View File

@ -61,6 +61,7 @@ from . import (
from tests.common import ( from tests.common import (
MockConfigEntry, MockConfigEntry,
MockModule, MockModule,
async_call_logger_set_level,
async_fire_time_changed, async_fire_time_changed,
load_fixture, load_fixture,
mock_integration, mock_integration,
@ -1144,54 +1145,45 @@ async def test_debug_logging(
) -> None: ) -> None:
"""Test debug logging.""" """Test debug logging."""
assert await async_setup_component(hass, "logger", {"logger": {}}) assert await async_setup_component(hass, "logger", {"logger": {}})
await hass.services.async_call( async with async_call_logger_set_level(
"logger", "homeassistant.components.bluetooth", "DEBUG", hass=hass, caplog=caplog
"set_level", ):
{"homeassistant.components.bluetooth": "DEBUG"}, address = "44:44:33:11:23:41"
blocking=True, start_time_monotonic = 50.0
)
await hass.async_block_till_done()
address = "44:44:33:11:23:41" switchbot_device_poor_signal_hci0 = generate_ble_device(
start_time_monotonic = 50.0 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( async with async_call_logger_set_level(
address, "wohand_poor_signal_hci0" "homeassistant.components.bluetooth", "WARNING", hass=hass, caplog=caplog
) ):
switchbot_adv_poor_signal_hci0 = generate_advertisement_data( switchbot_device_good_signal_hci0 = generate_ble_device(
local_name="wohand_poor_signal_hci0", service_uuids=[], rssi=-100 address, "wohand_good_signal_hci0"
) )
inject_advertisement_with_time_and_source( switchbot_adv_good_signal_hci0 = generate_advertisement_data(
hass, local_name="wohand_good_signal_hci0", service_uuids=[], rssi=-33
switchbot_device_poor_signal_hci0, )
switchbot_adv_poor_signal_hci0, inject_advertisement_with_time_and_source(
start_time_monotonic, hass,
"hci0", switchbot_device_good_signal_hci0,
) switchbot_adv_good_signal_hci0,
assert "wohand_poor_signal_hci0" in caplog.text start_time_monotonic,
caplog.clear() "hci0",
)
await hass.services.async_call( assert "wohand_good_signal_hci0" not in caplog.text
"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
@pytest.mark.usefixtures("enable_bluetooth", "macos_adapter") @pytest.mark.usefixtures("enable_bluetooth", "macos_adapter")

View File

@ -29,7 +29,11 @@ from . import (
patch_bluetooth_time, 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: # If the adapter is in a stuck state the following errors are raised:
NEED_RESET_ERRORS = [ NEED_RESET_ERRORS = [
@ -482,70 +486,67 @@ async def test_adapter_fails_to_start_and_takes_a_bit_to_init(
) -> None: ) -> None:
"""Test we can recover the adapter at startup and we wait for Dbus to init.""" """Test we can recover the adapter at startup and we wait for Dbus to init."""
assert await async_setup_component(hass, "logger", {}) assert await async_setup_component(hass, "logger", {})
await hass.services.async_call( async with async_call_logger_set_level(
"logger", "homeassistant.components.bluetooth", "DEBUG", hass=hass, caplog=caplog
"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,
): ):
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 async def stop(self, *args, **kwargs):
assert "Waiting for adapter to initialize" in caplog.text """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") @pytest.mark.usefixtures("one_adapter")

View File

@ -49,7 +49,12 @@ from homeassistant.setup import async_setup_component
from .conftest import MockESPHomeDevice 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( 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.async_block_till_done()
await hass.services.async_call( async with async_call_logger_set_level(
"logger", "homeassistant.components.esphome", "DEBUG", hass=hass, caplog=caplog
"set_level", ):
{"homeassistant.components.esphome": "DEBUG"}, assert device.current_log_level == LogLevel.LOG_LEVEL_VERY_VERBOSE
blocking=True,
)
assert device.current_log_level == LogLevel.LOG_LEVEL_VERY_VERBOSE
caplog.set_level(logging.DEBUG) caplog.set_level(logging.DEBUG)
device.mock_on_log_message( device.mock_on_log_message(
Mock(level=LogLevel.LOG_LEVEL_INFO, message=b"test_log_message") Mock(level=LogLevel.LOG_LEVEL_INFO, message=b"test_log_message")
) )
await hass.async_block_till_done() await hass.async_block_till_done()
assert "test_log_message" in caplog.text assert "test_log_message" in caplog.text
device.mock_on_log_message( device.mock_on_log_message(
Mock(level=LogLevel.LOG_LEVEL_ERROR, message=b"test_error_log_message") Mock(level=LogLevel.LOG_LEVEL_ERROR, message=b"test_error_log_message")
) )
await hass.async_block_till_done() await hass.async_block_till_done()
assert "test_error_log_message" in caplog.text assert "test_error_log_message" in caplog.text
caplog.set_level(logging.ERROR) caplog.set_level(logging.ERROR)
device.mock_on_log_message( device.mock_on_log_message(
Mock(level=LogLevel.LOG_LEVEL_DEBUG, message=b"test_debug_log_message") Mock(level=LogLevel.LOG_LEVEL_DEBUG, message=b"test_debug_log_message")
) )
await hass.async_block_till_done() await hass.async_block_till_done()
assert "test_debug_log_message" not in caplog.text assert "test_debug_log_message" not in caplog.text
caplog.set_level(logging.DEBUG) caplog.set_level(logging.DEBUG)
device.mock_on_log_message( device.mock_on_log_message(
Mock(level=LogLevel.LOG_LEVEL_DEBUG, message=b"test_debug_log_message") Mock(level=LogLevel.LOG_LEVEL_DEBUG, message=b"test_debug_log_message")
) )
await hass.async_block_till_done() await hass.async_block_till_done()
assert "test_debug_log_message" in caplog.text assert "test_debug_log_message" in caplog.text
await hass.services.async_call( async with async_call_logger_set_level(
"logger", "homeassistant.components.esphome", "WARNING", hass=hass, caplog=caplog
"set_level", ):
{"homeassistant.components.esphome": "WARNING"}, assert device.current_log_level == LogLevel.LOG_LEVEL_WARN
blocking=True, async with async_call_logger_set_level(
) "homeassistant.components.esphome", "ERROR", hass=hass, caplog=caplog
assert device.current_log_level == LogLevel.LOG_LEVEL_WARN ):
await hass.services.async_call( assert device.current_log_level == LogLevel.LOG_LEVEL_ERROR
"logger", async with async_call_logger_set_level(
"set_level", "homeassistant.components.esphome", "INFO", hass=hass, caplog=caplog
{"homeassistant.components.esphome": "ERROR"}, ):
blocking=True, assert device.current_log_level == LogLevel.LOG_LEVEL_CONFIG
)
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 def test_esphome_device_service_calls_not_allowed( async def test_esphome_device_service_calls_not_allowed(
@ -961,31 +954,22 @@ async def test_debug_logging(
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
) -> None: ) -> None:
"""Test enabling and disabling debug logging.""" """Test enabling and disabling debug logging."""
with caplog.at_level(logging.NOTSET, "homeassistant.components.esphome"): assert await async_setup_component(hass, "logger", {"logger": {}})
assert await async_setup_component(hass, "logger", {"logger": {}}) await mock_generic_device_entry(
await mock_generic_device_entry( mock_client=mock_client,
mock_client=mock_client, entity_info=[],
entity_info=[], user_service=[],
user_service=[], states=[],
states=[], )
) async with async_call_logger_set_level(
await hass.services.async_call( "homeassistant.components.esphome", "DEBUG", hass=hass, caplog=caplog
"logger", ):
"set_level",
{"homeassistant.components.esphome": "DEBUG"},
blocking=True,
)
await hass.async_block_till_done()
mock_client.set_debug.assert_has_calls([call(True)]) mock_client.set_debug.assert_has_calls([call(True)])
mock_client.reset_mock() mock_client.reset_mock()
await hass.services.async_call(
"logger", async with async_call_logger_set_level(
"set_level", "homeassistant.components.esphome", "WARNING", hass=hass, caplog=caplog
{"homeassistant.components.esphome": "WARNING"}, ):
blocking=True,
)
await hass.async_block_till_done()
mock_client.set_debug.assert_has_calls([call(False)]) mock_client.set_debug.assert_has_calls([call(False)])

View File

@ -22,7 +22,7 @@ from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util from homeassistant.util import dt as dt_util
from homeassistant.util.ssl import server_context_intermediate, server_context_modern 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 from tests.typing import ClientSessionGenerator
@ -505,27 +505,21 @@ async def test_logging(
) )
) )
hass.states.async_set("logging.entity", "hello") hass.states.async_set("logging.entity", "hello")
await hass.services.async_call( async with async_call_logger_set_level(
"logger", "aiohttp.access", "INFO", hass=hass, caplog=caplog
"set_level", ):
{"aiohttp.access": "info"}, client = await hass_client()
blocking=True, response = await client.get("/api/states/logging.entity")
) assert response.status == HTTPStatus.OK
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 assert "GET /api/states/logging.entity" in caplog.text
caplog.clear() caplog.clear()
await hass.services.async_call( async with async_call_logger_set_level(
"logger", "aiohttp.access", "WARNING", hass=hass, caplog=caplog
"set_level", ):
{"aiohttp.access": "warning"}, response = await client.get("/api/states/logging.entity")
blocking=True, assert response.status == HTTPStatus.OK
) assert "GET /api/states/logging.entity" not in caplog.text
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( async def test_register_static_paths(

View File

@ -15,7 +15,7 @@ from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util 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" HASS_NS = "unused.homeassistant"
COMPONENTS_NS = f"{HASS_NS}.components" 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") msg_test(filter_logger, True, "format string shouldfilter%s", "not")
# Filtering should work even if log level is modified # Filtering should work even if log level is modified
await hass.services.async_call( async with async_call_logger_set_level(
"logger", "test.filter", "WARNING", hass=hass, caplog=caplog
"set_level", ):
{"test.filter": "warning"}, assert filter_logger.getEffectiveLevel() == logging.WARNING
blocking=True, msg_test(
) filter_logger,
assert filter_logger.getEffectiveLevel() == logging.WARNING False,
msg_test( "this line containing shouldfilterall should still be filtered",
filter_logger, )
False,
"this line containing shouldfilterall should still be filtered",
)
# Filtering should be scoped to a service # Filtering should be scoped to a service
msg_test( msg_test(
filter_logger, True, "this line containing otherfilterer should not be filtered" filter_logger,
) True,
msg_test( "this line containing otherfilterer should not be filtered",
logging.getLogger("test.other_filter"), )
False, msg_test(
"this line containing otherfilterer SHOULD be filtered", logging.getLogger("test.other_filter"),
) False,
"this line containing otherfilterer SHOULD be filtered",
)
async def test_setting_level(hass: HomeAssistant) -> None: async def test_setting_level(hass: HomeAssistant) -> None:

View File

@ -19,7 +19,7 @@ from homeassistant.core import HomeAssistant, callback
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from homeassistant.util.dt import utcnow 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 from tests.typing import MockHAClientWebSocket, WebSocketGenerator
@ -533,27 +533,19 @@ async def test_enable_disable_debug_logging(
) -> None: ) -> None:
"""Test enabling and disabling debug logging.""" """Test enabling and disabling debug logging."""
assert await async_setup_component(hass, "logger", {"logger": {}}) assert await async_setup_component(hass, "logger", {"logger": {}})
await hass.services.async_call( async with async_call_logger_set_level(
"logger", "homeassistant.components.websocket_api", "DEBUG", hass=hass, caplog=caplog
"set_level", ):
{"homeassistant.components.websocket_api": "DEBUG"}, await websocket_client.send_json({"id": 1, "type": "ping"})
blocking=True, msg = await websocket_client.receive_json()
) assert msg["id"] == 1
await hass.async_block_till_done() assert msg["type"] == "pong"
await websocket_client.send_json({"id": 1, "type": "ping"}) assert 'Sending b\'{"id":1,"type":"pong"}\'' in caplog.text
msg = await websocket_client.receive_json() async with async_call_logger_set_level(
assert msg["id"] == 1 "homeassistant.components.websocket_api", "WARNING", hass=hass, caplog=caplog
assert msg["type"] == "pong" ):
assert 'Sending b\'{"id":1,"type":"pong"}\'' in caplog.text await websocket_client.send_json({"id": 2, "type": "ping"})
await hass.services.async_call( msg = await websocket_client.receive_json()
"logger", assert msg["id"] == 2
"set_level", assert msg["type"] == "pong"
{"homeassistant.components.websocket_api": "WARNING"}, assert 'Sending b\'{"id":2,"type":"pong"}\'' not in caplog.text
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

View File

@ -23,7 +23,6 @@ from zwave_js_server.model.node import Node, NodeDataType
from zwave_js_server.model.version import VersionInfo from zwave_js_server.model.version import VersionInfo
from homeassistant.components.hassio import HassioAPIError 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.persistent_notification import async_dismiss
from homeassistant.components.zwave_js import DOMAIN from homeassistant.components.zwave_js import DOMAIN
from homeassistant.components.zwave_js.helpers import get_device_id, get_device_id_ext 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 ( from tests.common import (
MockConfigEntry, MockConfigEntry,
async_call_logger_set_level,
async_fire_time_changed, async_fire_time_changed,
async_get_persistent_notifications, 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"] 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.""" """Test automatic server logging functionality."""
def _reset_mocks(): 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 # Setup logger and set log level to debug to trigger event listener
assert await async_setup_component(hass, "logger", {"logger": {}}) 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 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 # Validate that the server logging was enabled
assert len(client.async_send_command.call_args_list) == 1 assert len(client.async_send_command.call_args_list) == 1
assert client.async_send_command.call_args[0][0] == { assert client.async_send_command.call_args[0][0] == {
"command": "driver.update_log_config", "command": "driver.update_log_config",
"config": {"level": "debug"}, "config": {"level": "debug"},
} }
assert client.enable_server_logging.called assert client.enable_server_logging.called
assert not client.disable_server_logging.called assert not client.disable_server_logging.called
_reset_mocks() _reset_mocks()
# Emulate server by setting log level to debug # Emulate server by setting log level to debug
event = Event( event = Event(
type="log config updated", type="log config updated",
data={ data={
"source": "driver", "source": "driver",
"event": "log config updated", "event": "log config updated",
"config": { "config": {
"enabled": False, "enabled": False,
"level": "debug", "level": "debug",
"logToFile": True, "logToFile": True,
"filename": "test", "filename": "test",
"forceConsole": True, "forceConsole": True,
},
}, },
}, )
) client.driver.receive_event(event)
client.driver.receive_event(event)
# "Enable" server logging and unload the entry # "Enable" server logging and unload the entry
client.server_logging_enabled = True client.server_logging_enabled = True
await hass.config_entries.async_unload(entry.entry_id) await hass.config_entries.async_unload(entry.entry_id)
# Validate that the server logging was disabled # Validate that the server logging was disabled
assert len(client.async_send_command.call_args_list) == 1 assert len(client.async_send_command.call_args_list) == 1
assert client.async_send_command.call_args[0][0] == { assert client.async_send_command.call_args[0][0] == {
"command": "driver.update_log_config", "command": "driver.update_log_config",
"config": {"level": "info"}, "config": {"level": "info"},
} }
assert not client.enable_server_logging.called assert not client.enable_server_logging.called
assert client.disable_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 # Validate that the server logging doesn't get enabled because HA thinks it already
# is enabled # is enabled
await hass.config_entries.async_setup(entry.entry_id) await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
assert len(client.async_send_command.call_args_list) == 2 assert len(client.async_send_command.call_args_list) == 2
assert client.async_send_command.call_args_list[0][0][0] == { assert client.async_send_command.call_args_list[0][0][0] == {
"command": "controller.get_provisioning_entries", "command": "controller.get_provisioning_entries",
} }
assert client.async_send_command.call_args_list[1][0][0] == { assert client.async_send_command.call_args_list[1][0][0] == {
"command": "controller.get_provisioning_entry", "command": "controller.get_provisioning_entry",
"dskOrNodeId": 1, "dskOrNodeId": 1,
} }
assert not client.enable_server_logging.called assert not client.enable_server_logging.called
assert not client.disable_server_logging.called assert not client.disable_server_logging.called
_reset_mocks() _reset_mocks()
# "Disable" server logging and unload the entry # "Disable" server logging and unload the entry
client.server_logging_enabled = False client.server_logging_enabled = False
await hass.config_entries.async_unload(entry.entry_id) await hass.config_entries.async_unload(entry.entry_id)
# Validate that the server logging was not disabled because HA thinks it is already # Validate that the server logging was not disabled because HA thinks it is already
# is disabled # is disabled
assert len(client.async_send_command.call_args_list) == 0 assert len(client.async_send_command.call_args_list) == 0
assert not client.enable_server_logging.called assert not client.enable_server_logging.called
assert not client.disable_server_logging.called assert not client.disable_server_logging.called
async def test_factory_reset_node( async def test_factory_reset_node(