Home Information - Your home, your data, organized.
Python
Added better health status messages (#221)
Tony C87109a3a5790
diff --git a/src/hi/apps/alert/alert_manager.py b/src/hi/apps/alert/alert_manager.pyindex 0747d60e..d9ef46ec 100644--- a/src/hi/apps/alert/alert_manager.py+++ b/src/hi/apps/alert/alert_manager.py@@ -10,6 +10,7 @@ from .alert import Alertfrom .alert_queue import AlertQueuefrom .alarm import Alarmfrom .alert_status import AlertStatusData+from .transient_models import AlertMaintenanceResultlogger = logging.getLogger(__name__)@@ -99,10 +100,25 @@ class AlertManager( Singleton, NotificationMixin, SecurityMixin ):logger.exception( 'Problem adding alarm to alert queue.', e )return- async def do_periodic_maintenance(self):+ async def do_periodic_maintenance(self) -> AlertMaintenanceResult:+ """Perform alert queue cleanup and return execution results."""+ result = AlertMaintenanceResult()+try:- self._alert_queue.remove_expired_or_acknowledged_alerts()+ # Capture state before cleanup+ result.alerts_before_cleanup = len(self._alert_queue)++ # Perform cleanup and get detailed results+ cleanup_result = self._alert_queue.remove_expired_or_acknowledged_alerts()+ result.expired_alerts_removed = cleanup_result.expired_removed+ result.acknowledged_alerts_removed = cleanup_result.acknowledged_removed++ # Capture state after cleanup+ result.alerts_after_cleanup = len(self._alert_queue)+except Exception as e:logger.exception( 'Problem doing periodic alert maintenance.', e )- return+ result.error_message = str(e)[:100] # Truncate long error messages++ return resultdiff --git a/src/hi/apps/alert/alert_queue.py b/src/hi/apps/alert/alert_queue.pyindex 756ff221..bd956704 100644--- a/src/hi/apps/alert/alert_queue.py+++ b/src/hi/apps/alert/alert_queue.py@@ -7,6 +7,7 @@ import hi.apps.common.datetimeproxy as datetimeproxyfrom .alarm import Alarmfrom .alert import Alertfrom .enums import AlarmLevel+from .transient_models import AlertQueueCleanupResultlogger = logging.getLogger(__name__)@@ -135,27 +136,39 @@ class AlertQueue:raise KeyError( f'Alert not found for {alert_id}' )def remove_expired_or_acknowledged_alerts(self):+ """Remove expired and acknowledged alerts and return detailed results."""+ expired_removed = 0+ acknowledged_removed = 0+with self._active_alerts_lock:if self.TRACE:logger.debug( f'Alert Check: List size = {len(self._alert_list)}')if len( self._alert_list ) < 1:- return-+ return AlertQueueCleanupResult()+now_datetime = datetimeproxy.now()new_list = list()for alert in self._alert_list:if alert.end_datetime <= now_datetime:+ expired_removed += 1continueif alert.is_acknowledged:+ acknowledged_removed += 1continuenew_list.append( alert )-- removed_count = len(self._alert_list) - len(new_list)- logger.debug( f'Removed "{removed_count}" alerts.' )- if removed_count > 0:+ continue++ total_removed = expired_removed + acknowledged_removed+ logger.debug( f'Removed "{total_removed}" alerts: {expired_removed}'+ f' expired, {acknowledged_removed} acknowledged.' )+ if total_removed > 0:self._alert_list = new_listself._last_changed_datetime = datetimeproxy.now()- return+ return AlertQueueCleanupResult(+ expired_removed = expired_removed,+ acknowledged_removed = acknowledged_removed,+ total_removed = total_removed+ )diff --git a/src/hi/apps/alert/monitors.py b/src/hi/apps/alert/monitors.pyindex d1b7a65c..1abb188c 100644--- a/src/hi/apps/alert/monitors.py+++ b/src/hi/apps/alert/monitors.py@@ -36,7 +36,24 @@ class AlertMonitor( PeriodicMonitor, AlertMixin ):logger.debug( 'Checking for alert maintenance work.' )alert_manager = await self.alert_manager_async()if not alert_manager:+ self.record_error( 'Alert manager not available' )return-- await alert_manager.do_periodic_maintenance()++ try:+ result = await alert_manager.do_periodic_maintenance()+ summary_message = result.get_summary_message()++ if result.error_message:+ self.record_error( summary_message )+ else:+ self.record_healthy( summary_message )++ if self.TRACE:+ logger.debug( f'Alert maintenance completed: {summary_message}' )++ except Exception as e:+ error_msg = f"Alert maintenance failed: {str(e)[:50]}"+ logger.exception( error_msg )+ self.record_error( error_msg )+returndiff --git a/src/hi/apps/alert/tests/test_alert_manager.py b/src/hi/apps/alert/tests/test_alert_manager.pyindex aaed5436..15e47321 100644--- a/src/hi/apps/alert/tests/test_alert_manager.py+++ b/src/hi/apps/alert/tests/test_alert_manager.py@@ -1,10 +1,12 @@import logging+from unittest.mock import patchimport hi.apps.common.datetimeproxy as datetimeproxy-from hi.apps.alert.alert_manager import AlertManager+from hi.apps.alert.alert_manager import AlertManager, AlertMaintenanceResultfrom hi.apps.alert.alarm import Alarmfrom hi.apps.alert.enums import AlarmLevel, AlarmSourcefrom hi.apps.security.enums import SecurityLevel+from hi.testing.async_task_utils import AsyncTaskTestCasefrom hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)@@ -138,3 +140,134 @@ class TestAlertManager(BaseTestCase):retrieved_alert = manager.get_alert(created_alert.id)self.assertEqual(retrieved_alert, created_alert)return++++class TestAlertMaintenanceResult(BaseTestCase):+ """Test the AlertMaintenanceResult data class and summary message generation."""++ def test_summary_message_no_alerts_in_queue(self):+ """Test summary message when no alerts in queue."""+ result = AlertMaintenanceResult(alerts_before_cleanup=0)+ self.assertEqual(result.get_summary_message(), "No alerts in queue")++ def test_summary_message_no_cleanup_needed(self):+ """Test summary message when no cleanup needed."""+ result = AlertMaintenanceResult(+ alerts_before_cleanup=3,+ alerts_after_cleanup=3,+ expired_alerts_removed=0,+ acknowledged_alerts_removed=0+ )+ self.assertEqual(result.get_summary_message(), "No cleanup needed (3 active alerts)")++ def test_summary_message_no_cleanup_needed_single_alert(self):+ """Test summary message when no cleanup needed with single alert."""+ result = AlertMaintenanceResult(+ alerts_before_cleanup=1,+ alerts_after_cleanup=1,+ expired_alerts_removed=0,+ acknowledged_alerts_removed=0+ )+ self.assertEqual(result.get_summary_message(), "No cleanup needed (1 active alert)")++ def test_summary_message_expired_alerts_removed(self):+ """Test summary message when expired alerts removed."""+ result = AlertMaintenanceResult(+ alerts_before_cleanup=5,+ alerts_after_cleanup=3,+ expired_alerts_removed=2,+ acknowledged_alerts_removed=0+ )+ self.assertEqual(result.get_summary_message(), "Removed 2 expired, 3 active")++ def test_summary_message_acknowledged_alerts_removed(self):+ """Test summary message when acknowledged alerts removed."""+ result = AlertMaintenanceResult(+ alerts_before_cleanup=4,+ alerts_after_cleanup=2,+ expired_alerts_removed=0,+ acknowledged_alerts_removed=2+ )+ self.assertEqual(result.get_summary_message(), "Removed 2 acknowledged, 2 active")++ def test_summary_message_mixed_removal(self):+ """Test summary message when both expired and acknowledged alerts removed."""+ result = AlertMaintenanceResult(+ alerts_before_cleanup=7,+ alerts_after_cleanup=3,+ expired_alerts_removed=2,+ acknowledged_alerts_removed=2+ )+ self.assertEqual(result.get_summary_message(), "Removed 2 expired, 2 acknowledged, 3 active")++ def test_summary_message_all_alerts_removed(self):+ """Test summary message when all alerts removed."""+ result = AlertMaintenanceResult(+ alerts_before_cleanup=3,+ alerts_after_cleanup=0,+ expired_alerts_removed=2,+ acknowledged_alerts_removed=1+ )+ self.assertEqual(result.get_summary_message(), "Removed 2 expired, 1 acknowledged, none active")++ def test_summary_message_with_error(self):+ """Test summary message when error occurred."""+ result = AlertMaintenanceResult(error_message="Database connection failed")+ self.assertEqual(result.get_summary_message(), "Alert maintenance failed: Database connection failed")++ def test_total_alerts_removed_property(self):+ """Test total_alerts_removed property calculation."""+ result = AlertMaintenanceResult(+ expired_alerts_removed=3,+ acknowledged_alerts_removed=2+ )+ self.assertEqual(result.total_alerts_removed, 5)+++class TestAlertManagerMaintenance(AsyncTaskTestCase):+ """Test AlertManager periodic maintenance with new result tracking."""++ def setUp(self):+ super().setUp()+ # Reset singleton state for each test+ AlertManager._instance = None+ self.manager = AlertManager()++ def test_periodic_maintenance_returns_result(self):+ """Test periodic maintenance returns AlertMaintenanceResult."""+ async def async_test_logic():+ # Use the real AlertQueue - no mocking needed+ result = await self.manager.do_periodic_maintenance()++ # Verify result is correct type+ self.assertIsInstance(result, AlertMaintenanceResult)++ # For an empty queue, should have specific values+ self.assertEqual(result.alerts_before_cleanup, 0)+ self.assertEqual(result.alerts_after_cleanup, 0)+ self.assertEqual(result.expired_alerts_removed, 0)+ self.assertEqual(result.acknowledged_alerts_removed, 0)+ self.assertIsNone(result.error_message)++ # Should report "No alerts in queue"+ self.assertEqual(result.get_summary_message(), "No alerts in queue")++ self.run_async(async_test_logic())++ def test_periodic_maintenance_handles_exceptions(self):+ """Test periodic maintenance handles exceptions gracefully."""+ async def async_test_logic():+ # Mock the alert queue to raise an exception+ with patch.object(self.manager._alert_queue, 'remove_expired_or_acknowledged_alerts') as mock_cleanup:+ mock_cleanup.side_effect = Exception("Test exception")++ result = await self.manager.do_periodic_maintenance()++ # Verify result contains error information+ self.assertIsInstance(result, AlertMaintenanceResult)+ self.assertEqual(result.alerts_before_cleanup, 0) # Empty queue before exception+ self.assertIn("Test exception", result.error_message)++ self.run_async(async_test_logic())+diff --git a/src/hi/apps/alert/transient_models.py b/src/hi/apps/alert/transient_models.pynew file mode 100644index 00000000..f76fe40c--- /dev/null+++ b/src/hi/apps/alert/transient_models.py@@ -0,0 +1,48 @@+from dataclasses import dataclass+++@dataclass+class AlertQueueCleanupResult:++ expired_removed : int = 0+ acknowledged_removed : int = 0+ total_removed : int = 0+++@dataclass+class AlertMaintenanceResult:++ alerts_before_cleanup: int = 0+ alerts_after_cleanup: int = 0+ expired_alerts_removed: int = 0+ acknowledged_alerts_removed: int = 0+ error_message: str = None++ @property+ def total_alerts_removed(self) -> int:+ return self.expired_alerts_removed + self.acknowledged_alerts_removed++ def get_summary_message(self) -> str:+ if self.error_message:+ return f"Alert maintenance failed: {self.error_message}"++ if self.alerts_before_cleanup == 0:+ return "No alerts in queue"++ if self.total_alerts_removed == 0:+ return f"No cleanup needed ({self.alerts_after_cleanup} active alert{'s' if self.alerts_after_cleanup != 1 else ''})"++ # Build removal details+ removal_parts = []+ if self.expired_alerts_removed > 0:+ removal_parts.append(f"{self.expired_alerts_removed} expired")+ if self.acknowledged_alerts_removed > 0:+ removal_parts.append(f"{self.acknowledged_alerts_removed} acknowledged")++ removal_text = ", ".join(removal_parts)+ active_text = f"{self.alerts_after_cleanup} active" if self.alerts_after_cleanup > 0 else "none active"++ return f"Removed {removal_text}, {active_text}"+++diff --git a/src/hi/apps/notify/monitors.py b/src/hi/apps/notify/monitors.pyindex b329de32..d00e74b5 100644--- a/src/hi/apps/notify/monitors.py+++ b/src/hi/apps/notify/monitors.py@@ -28,11 +28,35 @@ class NotificationMonitor( PeriodicMonitor, NotificationMixin ):description = 'Notification processing and delivery',expected_heartbeat_interval_secs = cls.NOTIFICATION_POLLING_INTERVAL_SECS,)-+async def do_work(self):logger.debug( 'Checking for notification maintenance work.' )notification_manager = await self.notification_manager_async()if not notification_manager:+ self.record_error( 'Notification manager not available' )return- await notification_manager.do_periodic_maintenance()++ try:+ result = await notification_manager.do_periodic_maintenance()++ # Update health status based on results+ summary_message = result.get_summary_message()++ if result.error_messages:+ if result.notifications_failed > 0 and result.notifications_sent == 0:+ # All notifications failed - this is an error+ self.record_error( summary_message )+ else:+ # Some succeeded, some failed - this is a warning+ self.record_warning( summary_message )+ else:+ self.record_healthy( summary_message )++ logger.debug( f'Notification maintenance completed: {summary_message}' )++ except Exception as e:+ error_msg = f"Notification maintenance failed: {str(e)[:50]}"+ logger.exception( error_msg )+ self.record_error( error_msg )+returndiff --git a/src/hi/apps/notify/notification_manager.py b/src/hi/apps/notify/notification_manager.pyindex 5f4ee987..90133d3e 100644--- a/src/hi/apps/notify/notification_manager.py+++ b/src/hi/apps/notify/notification_manager.py@@ -1,4 +1,5 @@import logging+from typing import Listfrom hi.apps.common.email_utils import parse_emails_from_textfrom hi.apps.common.singleton import Singleton@@ -9,6 +10,7 @@ from hi.apps.notify.notification_queue import NotificationQueuefrom .email_sender import EmailData, EmailSenderfrom .transient_models import Notification, NotificationItemfrom .settings import NotifySetting+from .transient_models import NotificationMaintenanceResultlogger = logging.getLogger(__name__)@@ -26,21 +28,73 @@ class NotificationManager( Singleton, SettingsMixin ):# Any future heavyweight initializations go here (e.g., any DB operations).self._was_initialized = Truereturn-+def add_notification_item( self, notification_item : NotificationItem ):self._notification_queue.add_item( notification_item = notification_item )return-- async def do_periodic_maintenance(self):++ async def do_periodic_maintenance(self) -> NotificationMaintenanceResult:+ """Process pending notifications and return execution results."""+ result = NotificationMaintenanceResult()+try:+ settings_manager = await self.settings_manager_async()+ if not settings_manager:+ result.error_messages.append("Settings manager not available")+ return result++ notifications_enabled_str = settings_manager.get_setting_value(+ NotifySetting.NOTIFICATIONS_ENABLED,+ )+ notifications_enabled = str_to_bool( notifications_enabled_str )++ if not notifications_enabled:+ result.notifications_disabled = True+ logger.debug( 'Notifications are disabled, skipping maintenance.' )+ return result++ email_addresses_str = settings_manager.get_setting_value(+ NotifySetting.NOTIFICATIONS_EMAIL_ADDRESSES,+ )+ email_address_list = parse_emails_from_text( text = email_addresses_str )++ if not email_address_list:+ result.no_email_addresses = True++ # Get pending notificationsnotification_list = self._notification_queue.check_for_notifications()- logger.debug( f'Notifications found: {len(notification_list)}.' )+ result.notifications_found = len(notification_list)+ logger.debug( f'Notifications found: {result.notifications_found}.' )++ # Process each notificationfor notification in notification_list:- await self.send_notifications( notification )+ try:+ if not email_address_list:+ logger.info( f'No valid notification emails defined. Skipping: {notification}.' )+ result.notifications_skipped += 1+ continue++ success = await self._send_email_notification_internal(+ notification=notification,+ email_address_list=email_address_list+ )+ if success:+ result.notifications_sent += 1+ else:+ result.notifications_failed += 1+ except Exception as e:+ logger.exception( f"Failed to send notification: {e}" )+ result.notifications_failed += 1+ error_msg = str(e)[:100] # Truncate long error messages+ if error_msg not in result.error_messages:+ result.error_messages.append(error_msg)continue+except Exception as e:- logger.exception( "Problem sending notifications", e )- return+ logger.exception( "Problem checking notifications queue", e )+ result.error_messages.append(f"Queue check failed: {str(e)[:100]}")++ return resultasync def send_notifications( self, notification : Notification ) -> bool:settings_manager = await self.settings_manager_async()@@ -55,7 +109,7 @@ class NotificationManager( Singleton, SettingsMixin ):return Falsereturn await self.send_email_notification_if_needed_async( notification = notification )-+async def send_email_notification_if_needed_async( self, notification : Notification ) -> bool:settings_manager = await self.settings_manager_async()if not settings_manager:@@ -68,16 +122,32 @@ class NotificationManager( Singleton, SettingsMixin ):logger.info( f'No valid notification emails defined. Ignoring: {notification}.' )return False+ return await self._send_email_notification_internal(+ notification=notification,+ email_address_list=email_address_list+ )++ async def _send_email_notification_internal(+ self,+ notification: Notification,+ email_address_list: List[str]+ ) -> bool:+ """Internal method to send email notification with known email list."""logger.debug( f'Sending notification email to "{email_address_list}": {notification}.' )email_data = EmailData(request = None,- to_email_address = email_address_list,+ to_email_address = email_address_list,subject_template_name = 'notify/emails/notification_subject.txt',message_text_template_name = 'notify/emails/notification_message.txt',message_html_template_name = 'notify/emails/notification_message.html',template_context = { 'notification': notification },)- email_sender = EmailSender( data = email_data )- await email_sender.send_async()- return True++ try:+ email_sender = EmailSender( data = email_data )+ await email_sender.send_async()+ return True+ except Exception as e:+ logger.exception( f"Failed to send email notification: {e}" )+ raisediff --git a/src/hi/apps/notify/tests/test_notification_manager.py b/src/hi/apps/notify/tests/test_notification_manager.pyindex 2ff42f37..fabcc84b 100644--- a/src/hi/apps/notify/tests/test_notification_manager.py+++ b/src/hi/apps/notify/tests/test_notification_manager.py@@ -6,6 +6,8 @@ from hi.apps.notify.notification_manager import NotificationManagerfrom hi.apps.notify.settings import NotifySettingfrom hi.apps.notify.transient_models import Notification, NotificationItem+from hi.apps.notify.transient_models import NotificationMaintenanceResult as MaintenanceResult+logging.disable(logging.CRITICAL)@@ -81,38 +83,71 @@ class TestNotificationManager(AsyncManagerTestCase):item_list=[NotificationItem(signature='sig2', title='Test 2')])mock_notifications = [notification1, notification2]-- # Mock queue check and notification sending++ # Mock settings manager to enable notifications and provide email addresses+ mock_settings_manager = Mock()+ mock_settings_manager.get_setting_value.side_effect = lambda setting: {+ NotifySetting.NOTIFICATIONS_ENABLED: 'true',+ NotifySetting.NOTIFICATIONS_EMAIL_ADDRESSES: '[email protected]'+ }.get(setting, '')++ # Mock queue check and email sendingwith patch.object(self.manager._notification_queue, 'check_for_notifications') as mock_check:- with patch.object(self.manager, 'send_notifications') as mock_send:- mock_check.return_value = mock_notifications- mock_send.return_value = True-- await self.manager.do_periodic_maintenance()-- # Verify queue was checked- mock_check.assert_called_once()-- # Verify each notification was processed- self.assertEqual(mock_send.call_count, 2)- mock_send.assert_any_call(notification1)- mock_send.assert_any_call(notification2)-+ with patch.object(self.manager, 'settings_manager_async') as mock_settings:+ with patch.object(self.manager, '_send_email_notification_internal') as mock_send:+ mock_check.return_value = mock_notifications+ mock_settings.return_value = mock_settings_manager+ mock_send.return_value = True++ result = await self.manager.do_periodic_maintenance()++ # Verify queue was checked+ mock_check.assert_called_once()++ # Verify each notification was processed+ self.assertEqual(mock_send.call_count, 2)+ mock_send.assert_any_call(+ notification=notification1,+ email_address_list=['[email protected]']+ )+ mock_send.assert_any_call(+ notification=notification2,+ email_address_list=['[email protected]']+ )++ # Verify result+ self.assertEqual(result.notifications_found, 2)+ self.assertEqual(result.notifications_sent, 2)+ self.assertEqual(result.notifications_failed, 0)+ self.assertFalse(result.notifications_disabled)+self.run_async(async_test_logic())def test_periodic_maintenance_handles_exceptions_gracefully(self):"""Test periodic maintenance gracefully handles exceptions without crashing."""async def async_test_logic():+ # Mock settings manager to enable notifications+ mock_settings_manager = Mock()+ mock_settings_manager.get_setting_value.side_effect = lambda setting: {+ NotifySetting.NOTIFICATIONS_ENABLED: 'true',+ NotifySetting.NOTIFICATIONS_EMAIL_ADDRESSES: '[email protected]'+ }.get(setting, '')+# Mock queue to raise an exceptionwith patch.object(self.manager._notification_queue, 'check_for_notifications') as mock_check:- mock_check.side_effect = Exception("Test exception")-- # Should not raise an exception- await self.manager.do_periodic_maintenance()-- # Verify exception was caught and logged- mock_check.assert_called_once()-+ with patch.object(self.manager, 'settings_manager_async') as mock_settings:+ mock_check.side_effect = Exception("Test exception")+ mock_settings.return_value = mock_settings_manager++ # Should not raise an exception+ result = await self.manager.do_periodic_maintenance()++ # Verify exception was caught and logged+ mock_check.assert_called_once()++ # Verify error is recorded in result+ self.assertIn('Queue check failed', result.error_messages[0])+self.run_async(async_test_logic())def test_send_notifications_disabled_by_setting(self):@@ -306,3 +341,98 @@ class TestNotificationManager(AsyncManagerTestCase):self.assertFalse(result)self.run_async(async_test_logic())++++class TestMaintenanceResult(AsyncManagerTestCase):+ """Test the MaintenanceResult data class and summary message generation."""++ def test_summary_message_notifications_disabled(self):+ """Test summary message when notifications are disabled."""+ result = MaintenanceResult(notifications_disabled=True)+ self.assertEqual(result.get_summary_message(), "Notifications disabled")++ def test_summary_message_no_notifications_found(self):+ """Test summary message when no notifications found."""+ result = MaintenanceResult(notifications_found=0)+ self.assertEqual(result.get_summary_message(), "No notifications found")++ def test_summary_message_no_email_addresses(self):+ """Test summary message when no email addresses configured."""+ result = MaintenanceResult(+ notifications_found=3,+ no_email_addresses=True+ )+ self.assertEqual(+ result.get_summary_message(),+ "No email addresses configured (3 notifications pending)"+ )++ def test_summary_message_single_notification_no_addresses(self):+ """Test summary message with single notification and no addresses."""+ result = MaintenanceResult(+ notifications_found=1,+ no_email_addresses=True+ )+ self.assertEqual(+ result.get_summary_message(),+ "No email addresses configured (1 notification pending)"+ )++ def test_summary_message_notifications_sent_successfully(self):+ """Test summary message when notifications sent successfully."""+ result = MaintenanceResult(+ notifications_found=5,+ notifications_sent=5+ )+ self.assertEqual(result.get_summary_message(), "Sent 5 notifications")++ def test_summary_message_single_notification_sent(self):+ """Test summary message when single notification sent."""+ result = MaintenanceResult(+ notifications_found=1,+ notifications_sent=1+ )+ self.assertEqual(result.get_summary_message(), "Sent 1 notification")++ def test_summary_message_mixed_results(self):+ """Test summary message with mixed success and failures."""+ result = MaintenanceResult(+ notifications_found=5,+ notifications_sent=3,+ notifications_failed=2+ )+ self.assertEqual(+ result.get_summary_message(),+ "Sent 3 notifications, 2 failed"+ )++ def test_summary_message_with_skipped_notifications(self):+ """Test summary message with skipped notifications."""+ result = MaintenanceResult(+ notifications_found=5,+ notifications_sent=2,+ notifications_skipped=2,+ notifications_failed=1+ )+ self.assertEqual(+ result.get_summary_message(),+ "Sent 2 notifications, 2 skipped (no addresses), 1 failed"+ )++ def test_summary_message_all_failed(self):+ """Test summary message when all notifications failed."""+ result = MaintenanceResult(+ notifications_found=3,+ notifications_failed=3+ )+ self.assertEqual(result.get_summary_message(), "3 failed")++ def test_summary_message_all_skipped(self):+ """Test summary message when all notifications skipped."""+ result = MaintenanceResult(+ notifications_found=3,+ notifications_skipped=3+ )+ self.assertEqual(result.get_summary_message(), "3 skipped (no addresses)")+diff --git a/src/hi/apps/notify/transient_models.py b/src/hi/apps/notify/transient_models.pyindex caee2b26..69ccce23 100644--- a/src/hi/apps/notify/transient_models.py+++ b/src/hi/apps/notify/transient_models.py@@ -13,3 +13,51 @@ class NotificationItem:class Notification:title : stritem_list : List[ NotificationItem ]+++@dataclass+class NotificationMaintenanceResult:+ """Result of a periodic maintenance execution."""+ notifications_found: int = 0+ notifications_sent: int = 0+ notifications_skipped: int = 0 # Skipped due to no email addresses+ notifications_failed: int = 0+ notifications_disabled: bool = False+ no_email_addresses: bool = False+ error_messages: List[str] = None++ def __post_init__(self):+ if self.error_messages is None:+ self.error_messages = []++ def get_summary_message(self) -> str:+ """Generate a human-readable summary message for health status."""+ if self.notifications_disabled:+ return "Notifications disabled"++ if self.notifications_found == 0:+ return "No notifications found"++ if self.no_email_addresses:+ return f"No email addresses configured ({self.notifications_found} notification{'s' if self.notifications_found != 1 else ''} pending)"++ # Build the message parts+ parts = []++ if self.notifications_sent > 0:+ parts.append(+ f"Sent {self.notifications_sent} notification{'s' if self.notifications_sent != 1 else ''}")++ if self.notifications_skipped > 0:+ parts.append(f"{self.notifications_skipped} skipped (no addresses)")++ if self.notifications_failed > 0:+ parts.append(f"{self.notifications_failed} failed")++ if not parts:+ return "No notifications sent"++ return ", ".join(parts)+++diff --git a/src/hi/apps/security/monitors.py b/src/hi/apps/security/monitors.pyindex ddf33e9a..f64a79a7 100644--- a/src/hi/apps/security/monitors.py+++ b/src/hi/apps/security/monitors.py@@ -36,25 +36,34 @@ class SecurityMonitor( PeriodicMonitor, SettingsMixin, SecurityMixin ):)async def do_work(self):- await self._check_security_state()+ try:+ message = await self._check_security_state()+ self.record_healthy(message)+ except Exception as e:+ error_msg = f"Security state check failed: {str(e)[:50]}"+ logger.exception(error_msg)+ self.record_error(error_msg)return- async def _check_security_state( self ):+ async def _check_security_state( self ) -> str:+ """Check security state and return status message."""logger.debug( 'Security monitor: Checking security state.' )settings_manager = await self.settings_manager_async()if not settings_manager:- return+ return "Settings manager not available"security_manager = await self.security_manager_async()if not security_manager:- return-+ return "Security manager not available"+current_datetime = datetimeproxy.now()tz_name = ConsoleSettingsHelper().get_tz_name()+ current_state = security_manager.security_state+try:# Some states do not allow automated changes- if not security_manager.security_state.auto_change_allowed:- logger.debug( f'Security state "{security_manager.security_state}". Auto-change not allowed.' )- return+ if not current_state.auto_change_allowed:+ logger.debug( f'Security state "{current_state}". Auto-change not allowed.' )+ return f"Auto-change blocked ({current_state.label} mode)"day_start_time_of_day = settings_manager.get_setting_value(SecuritySetting.SECURITY_DAY_START,@@ -68,7 +77,7 @@ class SecurityMonitor( PeriodicMonitor, SettingsMixin, SecurityMixin ):security_manager.update_security_state_auto(new_security_state = SecurityState.DAY,)- return+ return f"Transitioned {current_state.label} → Day"night_start_time_of_day = settings_manager.get_setting_value(SecuritySetting.SECURITY_NIGHT_START,@@ -82,9 +91,9 @@ class SecurityMonitor( PeriodicMonitor, SettingsMixin, SecurityMixin ):security_manager.update_security_state_auto(new_security_state = SecurityState.NIGHT,)- return+ return f"Transitioned {current_state.label} → Night"logger.debug( 'Security monitor: No change needed.' )+ return f"No change needed ({current_state.label} mode)"finally:self._last_security_state_check_datetime = current_datetime- returndiff --git a/src/hi/apps/security/tests/test_security_monitor.py b/src/hi/apps/security/tests/test_security_monitor.pyindex 11928919..d0e74989 100644--- a/src/hi/apps/security/tests/test_security_monitor.py+++ b/src/hi/apps/security/tests/test_security_monitor.py@@ -6,6 +6,7 @@ from hi.testing.async_task_utils import AsyncTaskTestCaseimport hi.apps.common.datetimeproxy as datetimeproxyfrom hi.apps.security.enums import SecurityStatefrom hi.apps.security.monitors import SecurityMonitor+from hi.apps.security.settings import SecuritySettinglogging.disable(logging.CRITICAL)@@ -310,3 +311,160 @@ class TestSecurityMonitor(AsyncTaskTestCase):self.assertTrue(hasattr(monitor, 'security_manager_async'))self.assertTrue(hasattr(monitor, 'settings_manager'))self.assertTrue(hasattr(monitor, 'settings_manager_async'))+++ async def test_do_work_reports_health_status_success(self):+ """Test do_work reports healthy status when security state check succeeds."""+ monitor = SecurityMonitor()++ with patch.object(monitor, "_check_security_state", new_callable=AsyncMock) as mock_check:+ with patch.object(monitor, "record_healthy") as mock_healthy:+ mock_check.return_value = "No change needed (Day mode)"++ await monitor.do_work()++ mock_check.assert_called_once()+ mock_healthy.assert_called_once_with("No change needed (Day mode)")++ async def test_do_work_reports_health_status_error(self):+ """Test do_work reports error status when security state check fails."""+ monitor = SecurityMonitor()++ with patch.object(monitor, "_check_security_state", new_callable=AsyncMock) as mock_check:+ with patch.object(monitor, "record_error") as mock_error:+ mock_check.side_effect = Exception("Test exception")++ await monitor.do_work()++ mock_check.assert_called_once()+ mock_error.assert_called_once()+ # Check that error message contains the exception+ error_call_args = mock_error.call_args[0][0]+ self.assertIn("Security state check failed", error_call_args)+ self.assertIn("Test exception", error_call_args)++ async def test_check_security_state_returns_appropriate_messages(self):+ """Test _check_security_state returns appropriate status messages."""+ monitor = SecurityMonitor()++ # Test settings manager not available+ with patch.object(monitor, "settings_manager_async", new_callable=AsyncMock) as mock_settings:+ mock_settings.return_value = None++ result = await monitor._check_security_state()++ self.assertEqual(result, "Settings manager not available")++ async def test_check_security_state_security_manager_not_available(self):+ """Test _check_security_state handles missing security manager."""+ monitor = SecurityMonitor()++ mock_settings_manager = Mock()++ with patch.object(monitor, "settings_manager_async", new_callable=AsyncMock) as mock_settings:+ with patch.object(monitor, "security_manager_async", new_callable=AsyncMock) as mock_security:+ mock_settings.return_value = mock_settings_manager+ mock_security.return_value = None++ result = await monitor._check_security_state()++ self.assertEqual(result, "Security manager not available")++ async def test_check_security_state_auto_change_blocked(self):+ """Test _check_security_state reports when auto-change is blocked."""+ monitor = SecurityMonitor()++ mock_settings_manager = Mock()+ mock_security_manager = Mock()+ mock_security_manager.security_state = SecurityState.AWAY # auto_change_allowed = False++ with patch.object(monitor, "settings_manager_async", new_callable=AsyncMock) as mock_settings:+ with patch.object(monitor, "security_manager_async", new_callable=AsyncMock) as mock_security:+ with patch("hi.apps.security.monitors.ConsoleSettingsHelper") as mock_console:+ mock_settings.return_value = mock_settings_manager+ mock_security.return_value = mock_security_manager+ mock_console.return_value.get_tz_name.return_value = "UTC"++ result = await monitor._check_security_state()++ self.assertEqual(result, "Auto-change blocked (Away mode)")++ async def test_check_security_state_no_change_needed(self):+ """Test _check_security_state reports when no change is needed."""+ monitor = SecurityMonitor()++ mock_settings_manager = Mock()+ mock_settings_manager.get_setting_value.return_value = "06:00" # Day/night start times++ mock_security_manager = Mock()+ mock_security_manager.security_state = SecurityState.DAY # auto_change_allowed = True++ with patch.object(monitor, "settings_manager_async", new_callable=AsyncMock) as mock_settings:+ with patch.object(monitor, "security_manager_async", new_callable=AsyncMock) as mock_security:+ with patch("hi.apps.security.monitors.datetimeproxy.is_time_of_day_in_interval") as mock_interval:+ with patch("hi.apps.security.monitors.ConsoleSettingsHelper") as mock_console:+ mock_settings.return_value = mock_settings_manager+ mock_security.return_value = mock_security_manager+ mock_console.return_value.get_tz_name.return_value = "UTC"+ mock_interval.return_value = False # No time interval match++ result = await monitor._check_security_state()++ self.assertEqual(result, "No change needed (Day mode)")++ async def test_check_security_state_day_transition(self):+ """Test _check_security_state reports day transition."""+ monitor = SecurityMonitor()++ mock_settings_manager = Mock()+ mock_settings_manager.get_setting_value.side_effect = lambda setting: {+ SecuritySetting.SECURITY_DAY_START: "06:00"+ }.get(setting, "18:00")++ mock_security_manager = Mock()+ mock_security_manager.security_state = SecurityState.NIGHT # auto_change_allowed = True++ with patch.object(monitor, "settings_manager_async", new_callable=AsyncMock) as mock_settings:+ with patch.object(monitor, "security_manager_async", new_callable=AsyncMock) as mock_security:+ with patch("hi.apps.security.monitors.datetimeproxy.is_time_of_day_in_interval") as mock_interval:+ with patch("hi.apps.security.monitors.ConsoleSettingsHelper") as mock_console:+ mock_settings.return_value = mock_settings_manager+ mock_security.return_value = mock_security_manager+ mock_console.return_value.get_tz_name.return_value = "UTC"+ mock_interval.side_effect = [True, False] # Day start time matches, night does not++ result = await monitor._check_security_state()++ self.assertEqual(result, "Transitioned Night → Day")+ mock_security_manager.update_security_state_auto.assert_called_once_with(+ new_security_state=SecurityState.DAY+ )++ async def test_check_security_state_night_transition(self):+ """Test _check_security_state reports night transition."""+ monitor = SecurityMonitor()++ mock_settings_manager = Mock()+ mock_settings_manager.get_setting_value.side_effect = lambda setting: {+ SecuritySetting.SECURITY_NIGHT_START: "18:00"+ }.get(setting, "06:00")++ mock_security_manager = Mock()+ mock_security_manager.security_state = SecurityState.DAY # auto_change_allowed = True++ with patch.object(monitor, "settings_manager_async", new_callable=AsyncMock) as mock_settings:+ with patch.object(monitor, "security_manager_async", new_callable=AsyncMock) as mock_security:+ with patch("hi.apps.security.monitors.datetimeproxy.is_time_of_day_in_interval") as mock_interval:+ with patch("hi.apps.security.monitors.ConsoleSettingsHelper") as mock_console:+ mock_settings.return_value = mock_settings_manager+ mock_security.return_value = mock_security_manager+ mock_console.return_value.get_tz_name.return_value = "UTC"+ mock_interval.side_effect = [False, True] # Day start doesnt match, night does++ result = await monitor._check_security_state()++ self.assertEqual(result, "Transitioned Day → Night")+ mock_security_manager.update_security_state_auto.assert_called_once_with(+ new_security_state=SecurityState.NIGHT+ )+diff --git a/src/hi/apps/weather/monitors.py b/src/hi/apps/weather/monitors.pyindex 456638e4..4b07b388 100644--- a/src/hi/apps/weather/monitors.py+++ b/src/hi/apps/weather/monitors.py@@ -67,10 +67,17 @@ class WeatherMonitor( PeriodicMonitor, AlertMixin, SettingsMixin ):# issuing weather queries until server stays up a minimum amount of# time.#++ weather_source_manager = WeatherSourceManager()uptime = datetimeproxy.now() - self._started_datetimeif uptime.total_seconds() < self.STARTUP_SAFETY_SECS:- logger.debug( 'Startup safety period. Skipping weather data fetch.' )+ message = 'Startup safety period. Waiting to fetch.'+ logger.debug( message )+ self.record_warning( message )+ weather_source_manager.record_warning( message )return++ disabled_count = 0task_list = list()for weather_data_source in self._weather_data_source_instance_list:@@ -82,12 +89,19 @@ class WeatherMonitor( PeriodicMonitor, AlertMixin, SettingsMixin ):task_list.append( task )else:weather_data_source.record_disabled()+ disabled_count += 1logger.debug( f'Weather source {weather_data_source.id} is disabled, skipping' )continueif task_list:await asyncio.gather( *task_list )+ message = f'Ran {len(task_list)} integrations, {disabled_count} disabled.'+ self.record_healthy( message )+ weather_source_manager.record_healthy( message )else:- logger.debug( 'No enabled weather sources found' )+ message = 'No enabled weather sources found'+ logger.debug( message )+ self.record_warning( message )+ weather_source_manager.record_warning( message )returndiff --git a/src/hi/services/hass/monitors.py b/src/hi/services/hass/monitors.pyindex 2909c63b..2e27dc01 100644--- a/src/hi/services/hass/monitors.py+++ b/src/hi/services/hass/monitors.py@@ -67,10 +67,12 @@ class HassMonitor( PeriodicMonitor, HassMixin, SensorResponseMixin ):if not self._was_initialized:# Timing issues when first enabling could fail initialization.logger.warning( 'HAss monitor failed to initialize. Skipping work cycle.' )+ self.record_warning( 'Was not initialized.' )returnhass_manager = await self.hass_manager_async()if not hass_manager:+ self.record_error( 'No manager found.' )returnid_to_hass_state_map = await hass_manager.fetch_hass_states_from_api_async( verbose = False )@@ -95,5 +97,9 @@ class HassMonitor( PeriodicMonitor, HassMixin, SensorResponseMixin ):await self.sensor_response_manager().update_with_latest_sensor_responses(sensor_response_map = sensor_response_latest_map,)++ message = f'Processed {len(id_to_hass_state_map)} Home Assistant states.'+ self.record_healthy( message )+ hass_manager.record_healthy( message )returndiff --git a/src/hi/services/zoneminder/monitors.py b/src/hi/services/zoneminder/monitors.pyindex a6be0e25..02b0f77e 100644--- a/src/hi/services/zoneminder/monitors.py+++ b/src/hi/services/zoneminder/monitors.py@@ -49,10 +49,11 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )return self.ZONEMINDER_API_TIMEOUT_SECSasync def _initialize(self):- zm_manager = await self.zm_manager_async()+ zm_manager = await self.zm_manager_async() # Allows sync use elsewhere in moduleif not zm_manager:return- _ = await self.sensor_response_manager_async() # Allows async use of self.sensor_response_manager()+ _ = await self.sensor_response_manager_async() # Allows sync use elsewhere in module+self._zm_tzname = await zm_manager.get_zm_tzname_async()self._poll_from_datetime = datetimeproxy.now()zm_manager.register_change_listener( self.refresh )@@ -69,16 +70,16 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin ))def refresh( self ):- """+ """Called when integration settings are changed (via listener callback).-+Note: ZoneMinderManager.reload() is already called BEFORE this callback is triggered,so we should NOT call manager.reload() here to avoid redundant reloads.The monitor should just reset its own state to pick up fresh manager state."""# Reset monitor state so next cycle reinitializes with updated managerself._was_initialized = False- self._zm_tzname = None # Clear cached timezone+ self._zm_tzname = Nonelogger.debug( 'ZoneMinderMonitor refreshed - will reinitialize with new settings on next cycle' )return@@ -89,6 +90,7 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )if not self._was_initialized:# Timing issues when first enabling could fail initialization.logger.warning( 'ZoneMinder monitor failed to initialize. Skipping work cycle.' )+ self.record_warning( 'Was not initialized.' )returnsensor_response_map = dict()@@ -106,6 +108,10 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )await self.sensor_response_manager().update_with_latest_sensor_responses(sensor_response_map = sensor_response_map,)+ message = f'Processed {len(sensor_response_map)} ZoneMinder states.'+ self.record_healthy( message )+ if self.zm_manager():+ self.zm_manager().record_healthy( message )returnasync def _process_events(self):diff --git a/src/hi/settings/base.py b/src/hi/settings/base.pyindex f01cf08e..aea2bff3 100644--- a/src/hi/settings/base.py+++ b/src/hi/settings/base.py@@ -351,7 +351,7 @@ EMAIL_USE_SSL = ENV.EMAIL_USE_SSL# Needed when sending emails in background tasks since HttpRequest not# available. Override this for development/testing/staging.#-BASE_URL_FOR_EMAIL_LINKS = 'http://{SITE_DOMAIN}'+BASE_URL_FOR_EMAIL_LINKS = f'http://{SITE_DOMAIN}'# ====================diff --git a/src/hi/settings/production.py b/src/hi/settings/production.pyindex 7e11d5b7..2f304a39 100644--- a/src/hi/settings/production.py+++ b/src/hi/settings/production.py@@ -42,4 +42,4 @@ LOGGING = {},}-BASE_URL_FOR_EMAIL_LINKS = 'https://{SITE_DOMAIN}'+BASE_URL_FOR_EMAIL_LINKS = f'https://{SITE_DOMAIN}'diff --git a/src/hi/static/css/attribute.css b/src/hi/static/css/attribute.cssindex 72034b09..c93bb43f 100644--- a/src/hi/static/css/attribute.css+++ b/src/hi/static/css/attribute.css@@ -413,6 +413,9 @@display: flex;align-items: center;gap: 0.5rem;+ flex: 1 1 auto; /* Allow to grow and shrink as needed */+ max-width: 70%; /* But don't take more than 70% to leave room for actions */+ min-width: 200px; /* Ensure minimum usable width */}.attr-v2-attribute-actions {