Skip to content

Home Information - Your home, your data, organized.

Python

Added initial unit tests for most app modules (#44)

Tony C5b988b2e1058
diff --git a/src/hi/apps/alert/tests/__init__.py b/src/hi/apps/alert/tests/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/apps/alert/tests/test_alarm.py b/src/hi/apps/alert/tests/test_alarm.py
new file mode 100644
index 00000000..8956eeda
--- /dev/null
+++ b/src/hi/apps/alert/tests/test_alarm.py
@@ -0,0 +1,131 @@
+import logging
+from datetime import datetime
+
+from hi.apps.alert.alarm import Alarm, AlarmSourceDetails
+from hi.apps.alert.enums import AlarmLevel, AlarmSource
+from hi.apps.console.audio_signal import AudioSignal
+from hi.apps.security.enums import SecurityLevel
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestAlarm(BaseTestCase):
+
+ def test_alarm_signature_generation(self):
+ """Test alarm signature generation - critical for alarm aggregation logic."""
+ alarm = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='test_alarm',
+ alarm_level=AlarmLevel.WARNING,
+ title='Test Alarm',
+ source_details_list=[],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetime.now(),
+ )
+
+ expected_signature = f'{AlarmSource.EVENT}.test_alarm.{AlarmLevel.WARNING}'
+ self.assertEqual(alarm.signature, expected_signature)
+
+ # Test with different values
+ critical_alarm = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='critical_test',
+ alarm_level=AlarmLevel.CRITICAL,
+ title='Critical Alarm',
+ source_details_list=[],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetime.now(),
+ )
+
+ expected_critical_signature = f'{AlarmSource.EVENT}.critical_test.{AlarmLevel.CRITICAL}'
+ self.assertEqual(critical_alarm.signature, expected_critical_signature)
+
+ # Signatures should be different
+ self.assertNotEqual(alarm.signature, critical_alarm.signature)
+ return
+
+ def test_alarm_audio_signal_mapping(self):
+ """Test audio signal mapping from alarm level - business logic for audio alerts."""
+ # Test different alarm levels produce appropriate audio signals
+ info_alarm = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='info_test',
+ alarm_level=AlarmLevel.INFO,
+ title='Info Alarm',
+ source_details_list=[],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetime.now(),
+ )
+
+ warning_alarm = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='warning_test',
+ alarm_level=AlarmLevel.WARNING,
+ title='Warning Alarm',
+ source_details_list=[],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetime.now(),
+ )
+
+ critical_alarm = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='critical_test',
+ alarm_level=AlarmLevel.CRITICAL,
+ title='Critical Alarm',
+ source_details_list=[],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetime.now(),
+ )
+
+ # Should map to appropriate audio signals
+ info_signal = info_alarm.audio_signal
+ warning_signal = warning_alarm.audio_signal
+ critical_signal = critical_alarm.audio_signal
+
+ # All should be AudioSignal instances
+ self.assertIsInstance(info_signal, AudioSignal)
+ self.assertIsInstance(warning_signal, AudioSignal)
+ self.assertIsInstance(critical_signal, AudioSignal)
+
+ # They should be different based on alarm level
+ # (exact comparison depends on AudioSignal.from_alarm_level implementation)
+ return
+
+
+class TestAlarmSourceDetails(BaseTestCase):
+
+ def test_alarm_source_details_creation(self):
+ """Test AlarmSourceDetails dataclass - business logic for alarm context."""
+ detail_attrs = {
+ 'entity_name': 'Test Sensor',
+ 'location': 'Kitchen',
+ 'value': '75.2°F'
+ }
+
+ details = AlarmSourceDetails(
+ detail_attrs=detail_attrs,
+ image_url='https://example.com/sensor.jpg'
+ )
+
+ self.assertEqual(details.detail_attrs, detail_attrs)
+ self.assertEqual(details.image_url, 'https://example.com/sensor.jpg')
+ return
+
+ def test_alarm_source_details_optional_image_url(self):
+ """Test AlarmSourceDetails with optional image_url - default value handling."""
+ detail_attrs = {
+ 'entity_name': 'Test Sensor',
+ 'location': 'Kitchen'
+ }
+
+ details = AlarmSourceDetails(detail_attrs=detail_attrs)
+
+ self.assertEqual(details.detail_attrs, detail_attrs)
+ self.assertIsNone(details.image_url)
+ return
diff --git a/src/hi/apps/alert/tests/test_alert.py b/src/hi/apps/alert/tests/test_alert.py
new file mode 100644
index 00000000..44b7c176
--- /dev/null
+++ b/src/hi/apps/alert/tests/test_alert.py
@@ -0,0 +1,249 @@
+import logging
+from datetime import timedelta
+
+import hi.apps.common.datetimeproxy as datetimeproxy
+from hi.apps.alert.alert import Alert
+from hi.apps.alert.alarm import Alarm
+from hi.apps.alert.enums import AlarmLevel, AlarmSource
+from hi.apps.security.enums import SecurityLevel
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestAlert(BaseTestCase):
+
+ def setUp(self):
+ super().setUp()
+ self.test_alarm = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='test_alarm',
+ alarm_level=AlarmLevel.WARNING,
+ title='Test Alarm',
+ source_details_list=[],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetimeproxy.now(),
+ )
+ return
+
+ def test_alert_initialization_with_first_alarm(self):
+ """Test Alert initialization with first alarm - critical object creation logic."""
+ alert = Alert(self.test_alarm)
+
+ # Should have proper ID and timing
+ self.assertIsNotNone(alert.id)
+ self.assertEqual(alert.start_datetime, self.test_alarm.timestamp)
+ self.assertEqual(alert.end_datetime, self.test_alarm.timestamp + timedelta(seconds=300))
+
+ # Should set up alarm tracking correctly
+ self.assertEqual(alert.first_alarm, self.test_alarm)
+ self.assertEqual(alert.alarm_count, 1)
+ self.assertIn(self.test_alarm, alert.alarm_list)
+ self.assertFalse(alert.is_acknowledged)
+ return
+
+ def test_alert_signature_matching_logic(self):
+ """Test alert signature matching - critical for alarm aggregation."""
+ alert = Alert(self.test_alarm)
+
+ # Create matching alarm (same signature)
+ matching_alarm = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='test_alarm', # Same type
+ alarm_level=AlarmLevel.WARNING, # Same level
+ title='Another Test Alarm',
+ source_details_list=[],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetimeproxy.now(),
+ )
+
+ # Create non-matching alarm (different signature)
+ non_matching_alarm = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='different_alarm', # Different type
+ alarm_level=AlarmLevel.WARNING,
+ title='Different Alarm',
+ source_details_list=[],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetimeproxy.now(),
+ )
+
+ self.assertTrue(alert.is_matching_alarm(matching_alarm))
+ self.assertFalse(alert.is_matching_alarm(non_matching_alarm))
+ return
+
+ def test_alert_add_alarm_aggregation(self):
+ """Test adding alarms to alert - complex aggregation logic with deque management."""
+ alert = Alert(self.test_alarm)
+ initial_end_time = alert.end_datetime
+
+ # Create matching alarm
+ second_alarm = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='test_alarm',
+ alarm_level=AlarmLevel.WARNING,
+ title='Second Test Alarm',
+ source_details_list=[],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=600, # Different lifetime
+ timestamp=datetimeproxy.now(),
+ )
+
+ alert.add_alarm(second_alarm)
+
+ # Should update alarm count and end time
+ self.assertEqual(alert.alarm_count, 2)
+ self.assertGreater(alert.end_datetime, initial_end_time)
+
+ # Should maintain first alarm but add new one
+ self.assertEqual(alert.first_alarm, self.test_alarm)
+ self.assertIn(second_alarm, alert.alarm_list)
+
+ # Latest alarm should be first in list (most recent)
+ self.assertEqual(alert.get_latest_alarm(), second_alarm)
+ return
+
+ def test_alert_add_alarm_signature_assertion(self):
+ """Test add_alarm signature validation - critical error handling."""
+ alert = Alert(self.test_alarm)
+
+ # Create alarm with different signature
+ different_alarm = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='different_alarm', # Different type
+ alarm_level=AlarmLevel.WARNING,
+ title='Different Alarm',
+ source_details_list=[],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetimeproxy.now(),
+ )
+
+ # Should raise assertion error for signature mismatch
+ with self.assertRaises(AssertionError):
+ alert.add_alarm(different_alarm)
+ return
+
+ def test_alert_title_generation_with_count(self):
+ """Test alert title generation logic - business logic for UI display."""
+ alert = Alert(self.test_alarm)
+
+ # Single alarm should not show count
+ expected_title = f'{AlarmLevel.WARNING.label}: Test Alarm'
+ self.assertEqual(alert.title, expected_title)
+
+ # Add second alarm, should show count
+ second_alarm = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='test_alarm',
+ alarm_level=AlarmLevel.WARNING,
+ title='Second Test Alarm',
+ source_details_list=[],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetimeproxy.now(),
+ )
+
+ alert.add_alarm(second_alarm)
+ expected_title_with_count = f'{AlarmLevel.WARNING.label}: Test Alarm (2)'
+ self.assertEqual(alert.title, expected_title_with_count)
+ return
+
+ def test_alert_max_alarm_list_size_constraint(self):
+ """Test MAX_ALARM_LIST_SIZE constraint - critical for memory management."""
+ alert = Alert(self.test_alarm)
+
+ # Add alarms up to and beyond the limit
+ for i in range(Alert.MAX_ALARM_LIST_SIZE + 5):
+ new_alarm = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='test_alarm',
+ alarm_level=AlarmLevel.WARNING,
+ title=f'Alarm {i}',
+ source_details_list=[],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetimeproxy.now(),
+ )
+ alert.add_alarm(new_alarm)
+
+ # Should not exceed max size
+ self.assertEqual(alert.alarm_count, Alert.MAX_ALARM_LIST_SIZE)
+ self.assertEqual(len(alert.alarm_list), Alert.MAX_ALARM_LIST_SIZE)
+ return
+
+ def test_alert_priority_calculation(self):
+ """Test alert priority calculation - critical for alert ordering."""
+ # Test with different alarm levels
+ critical_alarm = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='critical_test',
+ alarm_level=AlarmLevel.CRITICAL,
+ title='Critical Alarm',
+ source_details_list=[],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetimeproxy.now(),
+ )
+
+ info_alarm = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='info_test',
+ alarm_level=AlarmLevel.INFO,
+ title='Info Alarm',
+ source_details_list=[],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetimeproxy.now(),
+ )
+
+ critical_alert = Alert(critical_alarm)
+ info_alert = Alert(info_alarm)
+
+ # Critical should have higher priority than info
+ self.assertGreater(critical_alert.alert_priority, info_alert.alert_priority)
+ self.assertEqual(critical_alert.alert_priority, AlarmLevel.CRITICAL.priority)
+ self.assertEqual(info_alert.alert_priority, AlarmLevel.INFO.priority)
+ return
+
+ def test_alert_acknowledgment_state_management(self):
+ """Test alert acknowledgment state - critical for user interaction."""
+ alert = Alert(self.test_alarm)
+
+ # Should start unacknowledged
+ self.assertFalse(alert.is_acknowledged)
+
+ # Should be able to acknowledge
+ alert.is_acknowledged = True
+ self.assertTrue(alert.is_acknowledged)
+
+ # Should be able to unacknowledge
+ alert.is_acknowledged = False
+ self.assertFalse(alert.is_acknowledged)
+ return
+
+ def test_alert_has_single_alarm_logic(self):
+ """Test has_single_alarm property - business logic for UI display."""
+ alert = Alert(self.test_alarm)
+
+ # Should be true for single alarm
+ self.assertTrue(alert.has_single_alarm)
+
+ # Add second alarm, should be false
+ second_alarm = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='test_alarm',
+ alarm_level=AlarmLevel.WARNING,
+ title='Second Alarm',
+ source_details_list=[],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetimeproxy.now(),
+ )
+
+ alert.add_alarm(second_alarm)
+ self.assertFalse(alert.has_single_alarm)
+ return
diff --git a/src/hi/apps/alert/tests/test_alert_manager.py b/src/hi/apps/alert/tests/test_alert_manager.py
new file mode 100644
index 00000000..695a9336
--- /dev/null
+++ b/src/hi/apps/alert/tests/test_alert_manager.py
@@ -0,0 +1,141 @@
+import logging
+
+import hi.apps.common.datetimeproxy as datetimeproxy
+from hi.apps.alert.alert_manager import AlertManager
+from hi.apps.alert.alert import Alert
+from hi.apps.alert.alarm import Alarm
+from hi.apps.alert.enums import AlarmLevel, AlarmSource
+from hi.apps.security.enums import SecurityLevel
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestAlertManager(BaseTestCase):
+
+ def test_alert_manager_singleton_behavior(self):
+ """Test AlertManager singleton pattern - critical for system consistency."""
+ manager1 = AlertManager()
+ manager2 = AlertManager()
+
+ self.assertIs(manager1, manager2)
+ return
+
+ def test_alert_manager_initialization(self):
+ """Test AlertManager initialization and ensure_initialized - critical setup logic."""
+ manager = AlertManager()
+
+ # Should have alert queue
+ self.assertIsNotNone(manager._alert_queue)
+
+ # May already be initialized due to singleton pattern
+ # Test ensure_initialized works without error
+ manager.ensure_initialized()
+ self.assertTrue(manager._was_initialized)
+
+ # Subsequent calls should not change state
+ manager.ensure_initialized()
+ self.assertTrue(manager._was_initialized)
+ return
+
+ def test_alert_manager_unacknowledged_alert_list_delegation(self):
+ """Test unacknowledged_alert_list property delegation - critical UI integration."""
+ manager = AlertManager()
+
+ # Should delegate to alert queue
+ unack_list = manager.unacknowledged_alert_list
+ expected_list = manager._alert_queue.unacknowledged_alert_list
+ self.assertEqual(unack_list, expected_list)
+ return
+
+ def test_alert_manager_get_alert_delegation(self):
+ """Test get_alert method delegation - critical for alert lookup."""
+ manager = AlertManager()
+
+ # Create test alert and add to queue
+ test_alarm = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='test_alarm',
+ alarm_level=AlarmLevel.WARNING,
+ title='Test Alarm',
+ source_details_list=[],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetimeproxy.now(),
+ )
+ alert = Alert(test_alarm)
+ manager._alert_queue._alert_list.append(alert)
+
+ # Should delegate to alert queue
+ found_alert = manager.get_alert(alert.id)
+ self.assertEqual(found_alert, alert)
+
+ # Should raise KeyError for non-existent ID
+ with self.assertRaises(KeyError):
+ manager.get_alert('non_existent_id')
+ return
+
+ def test_alert_manager_get_alert_status_data_structure(self):
+ """Test get_alert_status_data method structure - complex business logic integration."""
+ manager = AlertManager()
+ manager.ensure_initialized()
+
+ test_datetime = datetimeproxy.now()
+
+ # Method should exist and return AlertStatusData
+ status_data = manager.get_alert_status_data(test_datetime)
+
+ # Should return some form of status data structure
+ self.assertIsNotNone(status_data)
+
+ # The exact structure depends on AlertStatusData implementation,
+ # but we're testing that the method executes without error
+ return
+
+ def test_alert_manager_mixin_inheritance(self):
+ """Test AlertManager mixin inheritance - critical for system integration."""
+ manager = AlertManager()
+
+ # Should inherit from NotificationMixin
+ self.assertTrue(hasattr(manager, 'notification_manager'))
+
+ # Should inherit from SecurityMixin
+ self.assertTrue(hasattr(manager, 'security_manager'))
+
+ # Should be a Singleton
+ from hi.apps.common.singleton import Singleton
+ self.assertIsInstance(manager, Singleton)
+ return
+
+ def test_alert_manager_alert_queue_integration(self):
+ """Test AlertManager integration with AlertQueue - critical system interaction."""
+ manager = AlertManager()
+
+ # Should have working alert queue
+ self.assertIsNotNone(manager._alert_queue)
+
+ # Queue operations should work through manager
+ initial_count = len(manager.unacknowledged_alert_list)
+
+ # Add alert directly to queue
+ test_alarm = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='test_alarm',
+ alarm_level=AlarmLevel.CRITICAL,
+ title='Test Alarm',
+ source_details_list=[],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetimeproxy.now(),
+ )
+ alert = Alert(test_alarm)
+ manager._alert_queue._alert_list.append(alert)
+
+ # Should be reflected in unacknowledged list
+ self.assertEqual(len(manager.unacknowledged_alert_list), initial_count + 1)
+ self.assertIn(alert, manager.unacknowledged_alert_list)
+
+ # Should be retrievable by ID
+ retrieved_alert = manager.get_alert(alert.id)
+ self.assertEqual(retrieved_alert, alert)
+ return
diff --git a/src/hi/apps/alert/tests/test_alert_queue.py b/src/hi/apps/alert/tests/test_alert_queue.py
new file mode 100644
index 00000000..9641e3a0
--- /dev/null
+++ b/src/hi/apps/alert/tests/test_alert_queue.py
@@ -0,0 +1,170 @@
+import logging
+from datetime import datetime
+import threading
+
+import hi.apps.common.datetimeproxy as datetimeproxy
+from hi.apps.alert.alert_queue import AlertQueue
+from hi.apps.alert.alert import Alert
+from hi.apps.alert.alarm import Alarm
+from hi.apps.alert.enums import AlarmLevel, AlarmSource
+from hi.apps.security.enums import SecurityLevel
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestAlertQueue(BaseTestCase):
+
+ def setUp(self):
+ super().setUp()
+ self.queue = AlertQueue()
+ self.test_alarm = Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='test_alarm',
+ alarm_level=AlarmLevel.WARNING,
+ title='Test Alarm',
+ source_details_list=[],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetimeproxy.now(),
+ )
+ return
+
+ def test_alert_queue_initialization(self):
+ """Test AlertQueue initialization - critical state setup."""
+ self.assertEqual(len(self.queue), 0)
+ self.assertFalse(bool(self.queue))
+ self.assertEqual(len(self.queue.unacknowledged_alert_list), 0)
+ self.assertIsInstance(self.queue._active_alerts_lock, type(threading.Lock()))
+ return
+
+ def test_alert_queue_get_alert_by_id(self):
+ """Test get_alert method - critical for alert lookup."""
+ alert = Alert(self.test_alarm)
+ self.queue._alert_list.append(alert)
+
+ # Should find alert by ID
+ found_alert = self.queue.get_alert(alert.id)
+ self.assertEqual(found_alert, alert)
+
+ # Should raise KeyError for non-existent ID
+ with self.assertRaises(KeyError):
+ self.queue.get_alert('non_existent_id')
+ return
+
+ def test_alert_queue_unacknowledged_filtering(self):
+ """Test unacknowledged_alert_list filtering - critical for UI display."""
+ # Create multiple alerts with different acknowledgment states
+ alert1 = Alert(self.test_alarm)
+ alert2 = Alert(Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='test_alarm_2',
+ alarm_level=AlarmLevel.INFO,
+ title='Test Alarm 2',
+ source_details_list=[],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetimeproxy.now(),
+ ))
+ alert3 = Alert(Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='test_alarm_3',
+ alarm_level=AlarmLevel.CRITICAL,
+ title='Test Alarm 3',
+ source_details_list=[],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetimeproxy.now(),
+ ))
+
+ # Add alerts to queue
+ self.queue._alert_list = [alert1, alert2, alert3]
+
+ # All should be unacknowledged initially
+ unack_alerts = self.queue.unacknowledged_alert_list
+ self.assertEqual(len(unack_alerts), 3)
+ self.assertIn(alert1, unack_alerts)
+ self.assertIn(alert2, unack_alerts)
+ self.assertIn(alert3, unack_alerts)
+
+ # Acknowledge one alert
+ alert2.is_acknowledged = True
+
+ # Should filter out acknowledged alert
+ unack_alerts = self.queue.unacknowledged_alert_list
+ self.assertEqual(len(unack_alerts), 2)
+ self.assertIn(alert1, unack_alerts)
+ self.assertNotIn(alert2, unack_alerts)
+ self.assertIn(alert3, unack_alerts)
+
+ # Acknowledge all alerts
+ alert1.is_acknowledged = True
+ alert3.is_acknowledged = True
+
+ # Should have no unacknowledged alerts
+ unack_alerts = self.queue.unacknowledged_alert_list
+ self.assertEqual(len(unack_alerts), 0)
+ return
+
+ def test_alert_queue_len_and_bool(self):
+ """Test AlertQueue __len__ and __bool__ methods - basic functionality."""
+ # Empty queue
+ self.assertEqual(len(self.queue), 0)
+ self.assertFalse(bool(self.queue))
+
+ # Add alert
+ alert = Alert(self.test_alarm)
+ self.queue._alert_list.append(alert)
+
+ # Should reflect new length and boolean state
+ self.assertEqual(len(self.queue), 1)
+ self.assertTrue(bool(self.queue))
+
+ # Add more alerts
+ alert2 = Alert(Alarm(
+ alarm_source=AlarmSource.EVENT,
+ alarm_type='test_alarm_2',
+ alarm_level=AlarmLevel.INFO,
+ title='Test Alarm 2',
+ source_details_list=[],
+ security_level=SecurityLevel.LOW,
+ alarm_lifetime_secs=300,
+ timestamp=datetimeproxy.now(),
+ ))
+ self.queue._alert_list.append(alert2)
+
+ self.assertEqual(len(self.queue), 2)
+ self.assertTrue(bool(self.queue))
+ return
+
+ def test_alert_queue_max_size_constraint(self):
+ """Test MAX_ALERT_LIST_SIZE constraint - critical for memory management."""
+ # The AlertQueue doesn't appear to enforce the MAX_ALERT_LIST_SIZE in the current code,
+ # but we should test that the constant exists and can be used for future enforcement
+ self.assertEqual(AlertQueue.MAX_ALERT_LIST_SIZE, 50)
+
+ # If size enforcement were implemented, it would be critical business logic
+ # For now, just verify the constant exists as part of the class design
+ return
+
+ def test_alert_queue_last_changed_datetime_tracking(self):
+ """Test last_changed_datetime tracking - important for change detection."""
+ # Should have initial timestamp
+ initial_time = self.queue._last_changed_datetime
+ self.assertIsInstance(initial_time, datetime)
+
+ # Time should be recent (within last few seconds)
+ time_diff = abs((datetimeproxy.now() - initial_time).total_seconds())
+ self.assertLess(time_diff, 5.0)
+ return
+
+ def test_alert_queue_thread_safety_lock(self):
+ """Test thread safety lock existence - critical for concurrent access."""
+ # Should have proper threading lock
+ self.assertIsInstance(self.queue._active_alerts_lock, type(threading.Lock()))
+
+ # Lock should be usable
+ with self.queue._active_alerts_lock:
+ # Should be able to acquire and release
+ pass
+ return
diff --git a/src/hi/apps/alert/tests/test_enums.py b/src/hi/apps/alert/tests/test_enums.py
new file mode 100644
index 00000000..c07b4b4b
--- /dev/null
+++ b/src/hi/apps/alert/tests/test_enums.py
@@ -0,0 +1,125 @@
+import logging
+
+from hi.apps.alert.enums import AlarmLevel, AlarmSource, AlertState
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestAlarmLevel(BaseTestCase):
+
+ def test_alarm_level_priority_ordering(self):
+ """Test AlarmLevel priority ordering - critical for alert prioritization."""
+ # Test that priorities are in correct order
+ self.assertLess(AlarmLevel.NONE.priority, AlarmLevel.INFO.priority)
+ self.assertLess(AlarmLevel.INFO.priority, AlarmLevel.WARNING.priority)
+ self.assertLess(AlarmLevel.WARNING.priority, AlarmLevel.CRITICAL.priority)
+
+ # Test specific priority values
+ self.assertEqual(AlarmLevel.NONE.priority, 0)
+ self.assertEqual(AlarmLevel.INFO.priority, 10)
+ self.assertEqual(AlarmLevel.WARNING.priority, 100)
+ self.assertEqual(AlarmLevel.CRITICAL.priority, 1000)
+ return
+
+ def test_alarm_level_labels(self):
+ """Test AlarmLevel labels - important for UI display."""
+ self.assertEqual(AlarmLevel.NONE.label, 'None')
+ self.assertEqual(AlarmLevel.INFO.label, 'Info')
+ self.assertEqual(AlarmLevel.WARNING.label, 'Warning')
+ self.assertEqual(AlarmLevel.CRITICAL.label, 'Critical')
+ return
+
+
+class TestAlarmSource(BaseTestCase):
+
+ def test_alarm_source_enum_values(self):
+ """Test AlarmSource enum values - critical for alarm categorization."""
+ self.assertEqual(AlarmSource.EVENT.label, 'Event')
+
+ # Should have proper enum behavior
+ self.assertIsInstance(AlarmSource.EVENT, AlarmSource)
+ return
+
+
+class TestAlertState(BaseTestCase):
+
+ def test_alert_state_priority_ordering(self):
+ """Test AlertState priority ordering - critical for state prioritization."""
+ # Test that priorities are in correct ascending order
+
+ # Verify specific critical priorities
+ self.assertEqual(AlertState.ERROR.priority, -12)
+ self.assertEqual(AlertState.ENABLED.priority, 0)
+ self.assertEqual(AlertState.INFO.priority, 10)
+ self.assertEqual(AlertState.ALERT.priority, 100)
+ self.assertEqual(AlertState.ALARM.priority, 1000)
+
+ # Test that INFO_RECENT < INFO
+ self.assertLess(AlertState.INFO_RECENT.priority, AlertState.INFO.priority)
+
+ # Test that ALERT_RECENT < ALERT
+ self.assertLess(AlertState.ALERT_RECENT.priority, AlertState.ALERT.priority)
+
+ # Test that ALARM_RECENT < ALARM
+ self.assertLess(AlertState.ALARM_RECENT.priority, AlertState.ALARM.priority)
+ return
+
+ def test_alert_state_get_recent_variant_logic(self):
+ """Test get_recent_variant static method - complex business logic for state transitions."""
+ # Test conversion to recent variants
+ self.assertEqual(
+ AlertState.get_recent_variant(AlertState, AlertState.INFO),
+ AlertState.INFO_RECENT
+ )
+ self.assertEqual(
+ AlertState.get_recent_variant(AlertState, AlertState.ALERT),
+ AlertState.ALERT_RECENT
+ )
+ self.assertEqual(
+ AlertState.get_recent_variant(AlertState, AlertState.ALARM),
+ AlertState.ALARM_RECENT
+ )
+
+ # Test states that don't have recent variants return unchanged
+ self.assertEqual(
+ AlertState.get_recent_variant(AlertState, AlertState.ENABLED),
+ AlertState.ENABLED
+ )
+ self.assertEqual(
+ AlertState.get_recent_variant(AlertState, AlertState.DISABLED),
+ AlertState.DISABLED
+ )
+ self.assertEqual(
+ AlertState.get_recent_variant(AlertState, AlertState.ERROR),
+ AlertState.ERROR
+ )
+
+ # Test that recent variants don't have further variants (return unchanged)
+ self.assertEqual(
+ AlertState.get_recent_variant(AlertState, AlertState.INFO_RECENT),
+ AlertState.INFO_RECENT
+ )
+ self.assertEqual(
+ AlertState.get_recent_variant(AlertState, AlertState.ALERT_RECENT),
+ AlertState.ALERT_RECENT
+ )
+ self.assertEqual(
+ AlertState.get_recent_variant(AlertState, AlertState.ALARM_RECENT),
+ AlertState.ALARM_RECENT
+ )
+ return
+
+ def test_alert_state_labels(self):
+ """Test AlertState labels - important for UI display."""
+ # Test key labels that would be displayed to users
+ self.assertEqual(AlertState.ERROR.label, 'Error')
+ self.assertEqual(AlertState.ENABLED.label, 'Enabled')
+ self.assertEqual(AlertState.DISABLED.label, 'Disabled')
+ self.assertEqual(AlertState.INFO.label, 'Info')
+ self.assertEqual(AlertState.INFO_RECENT.label, 'Info (recent)')
+ self.assertEqual(AlertState.ALERT.label, 'Alert')
+ self.assertEqual(AlertState.ALERT_RECENT.label, 'Alert (recent)')
+ self.assertEqual(AlertState.ALARM.label, 'Alarm')
+ self.assertEqual(AlertState.ALARM_RECENT.label, 'Alarm (recent)')
+ return
diff --git a/src/hi/apps/attribute/tests/__init__.py b/src/hi/apps/attribute/tests/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/apps/attribute/tests/test_enums.py b/src/hi/apps/attribute/tests/test_enums.py
new file mode 100644
index 00000000..12eca528
--- /dev/null
+++ b/src/hi/apps/attribute/tests/test_enums.py
@@ -0,0 +1,24 @@
+import logging
+
+from hi.apps.attribute.enums import AttributeType, AttributeValueType
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestAttributeType(BaseTestCase):
+
+ def test_attribute_type_deletion_policy(self):
+ """Test AttributeType deletion policy - critical for data safety."""
+ # Only CUSTOM attributes should be deletable
+ self.assertTrue(AttributeType.CUSTOM.can_delete)
+ self.assertFalse(AttributeType.PREDEFINED.can_delete)
+ return
+
+
+class TestAttributeValueType(BaseTestCase):
+
+ def test_attribute_value_type_default_fallback(self):
+ """Test AttributeValueType default fallback - critical for initialization."""
+ self.assertEqual(AttributeValueType.default(), AttributeValueType.TEXT)
+ return
diff --git a/src/hi/apps/attribute/tests/test_models.py b/src/hi/apps/attribute/tests/test_models.py
new file mode 100644
index 00000000..947caae7
--- /dev/null
+++ b/src/hi/apps/attribute/tests/test_models.py
@@ -0,0 +1,260 @@
+import json
+import logging
+from unittest.mock import patch
+from django.core.files.uploadedfile import SimpleUploadedFile
+
+from hi.apps.attribute.models import AttributeModel
+from hi.apps.attribute.enums import AttributeValueType, AttributeType
+from hi.integrations.integration_key import IntegrationKey
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class ConcreteAttributeModel(AttributeModel):
+ """Concrete implementation for testing the abstract AttributeModel."""
+
+ def get_upload_to(self):
+ return 'test_attributes/'
+
+
+class TestAttributeModel(BaseTestCase):
+
+ def test_attribute_model_enum_property_conversions(self):
+ """Test enum property conversions - custom business logic."""
+ attr = ConcreteAttributeModel(
+ name='test_attr',
+ value_type_str='FILE',
+ attribute_type_str='CUSTOM'
+ )
+
+ # Test getter converts string to enum
+ self.assertEqual(attr.value_type, AttributeValueType.FILE)
+ self.assertEqual(attr.attribute_type, AttributeType.CUSTOM)
+
+ # Test setter converts enum to string
+ attr.value_type = AttributeValueType.BOOLEAN
+ attr.attribute_type = AttributeType.PREDEFINED
+ self.assertEqual(attr.value_type_str, 'boolean')
+ self.assertEqual(attr.attribute_type_str, 'predefined')
+ return
+
+ def test_attribute_model_integration_key_parsing(self):
+ """Test integration key parsing and serialization - complex object handling."""
+ attr = ConcreteAttributeModel(
+ name='test_attr',
+ value_type_str='TEXT',
+ attribute_type_str='CUSTOM'
+ )
+
+ # Test with no integration key
+ self.assertIsNone(attr.integration_key)
+
+ # Test setting integration key
+ test_key = IntegrationKey(integration_id='test_id', integration_name='test_integration')
+ attr.integration_key = test_key
+ self.assertEqual(attr.integration_key_str, str(test_key))
+
+ # Test getting parsed integration key
+ parsed_key = attr.integration_key
+ self.assertEqual(parsed_key.integration_id, 'test_id')
+ self.assertEqual(parsed_key.integration_name, 'test_integration')
+
+ # Test clearing integration key
+ attr.integration_key = None
+ self.assertIsNone(attr.integration_key_str)
+ self.assertIsNone(attr.integration_key)
+ return
+
+ def test_attribute_model_choices_json_parsing(self):
+ """Test choices JSON parsing - complex data processing logic."""
+ attr = ConcreteAttributeModel(
+ name='test_attr',
+ value_type_str='ENUM',
+ attribute_type_str='CUSTOM'
+ )
+
+ # Test with dictionary format
+ attr.value_range_str = json.dumps({'key1': 'Label 1', 'key2': 'Label 2'})
+ choices = attr.choices()
+ expected = [('key1', 'Label 1'), ('key2', 'Label 2')]
+ self.assertEqual(choices, expected)
+
+ # Test with list format
+ attr.value_range_str = json.dumps(['option1', 'option2', 'option3'])
+ choices = attr.choices()
+ expected = [('option1', 'option1'), ('option2', 'option2'), ('option3', 'option3')]
+ self.assertEqual(choices, expected)
+
+ # Test with invalid JSON
+ attr.value_range_str = 'invalid json {'
+ choices = attr.choices()
+ self.assertEqual(choices, {}) # Should return empty dict on parse error
+
+ # Test with empty value_range_str
+ attr.value_range_str = None
+ choices = attr.choices()
+ self.assertEqual(choices, [])
+ return
+
+ @patch('hi.apps.attribute.models.PredefinedValueRanges.get_choices')
+ def test_attribute_model_choices_predefined_lookup(self, mock_get_choices):
+ """Test choices predefined value range lookup - external integration logic."""
+ mock_get_choices.return_value = [('pred1', 'Predefined 1'), ('pred2', 'Predefined 2')]
+
+ attr = ConcreteAttributeModel(
+ name='test_attr',
+ value_type_str='ENUM',
+ attribute_type_str='PREDEFINED',
+ value_range_str='hi.test.choices'
+ )
+
+ choices = attr.choices()
+
+ # Should use predefined choices, not parse JSON
+ mock_get_choices.assert_called_once_with('hi.test.choices')
+ self.assertEqual(choices, [('pred1', 'Predefined 1'), ('pred2', 'Predefined 2')])
+ return
+
+ @patch('hi.apps.attribute.models.generate_unique_filename')
+ def test_attribute_model_file_save_logic(self, mock_generate_unique_filename):
+ """Test file save logic with unique filename generation - complex file handling."""
+ mock_generate_unique_filename.return_value = 'unique_test_file.txt'
+
+ # Create a simple uploaded file
+ test_file = SimpleUploadedFile(
+ name='test_file.txt',
+ content=b'test content',
+ content_type='text/plain'
+ )
+
+ attr = ConcreteAttributeModel(
+ name='test_attr',
+ value_type_str='FILE',
+ attribute_type_str='CUSTOM'
+ )
+ attr.file_value = test_file
+ # Ensure pk is None for new object behavior
+ attr.pk = None
+
+ # Mock the super().save() call to avoid database issues
+ with patch('django.db.models.Model.save'):
+ # Simulate calling save
+ attr.save()
+
+ # Should set upload_to and generate unique filename for new objects
+ mock_generate_unique_filename.assert_called_once_with('test_file.txt')
+ self.assertEqual(attr.value, 'test_file.txt') # Value set to original filename
+ self.assertEqual(attr.file_value.name, 'unique_test_file.txt') # Name updated to unique
+ self.assertEqual(attr.file_value.field.upload_to, 'test_attributes/')
+ return
+
+ @patch('hi.apps.attribute.models.default_storage')
+ def test_attribute_model_file_deletion_cleanup(self, mock_storage):
+ """Test file deletion cleanup - critical for storage management."""
+ mock_storage.exists.return_value = True
+ mock_storage.delete.return_value = None
+
+ # Create attribute with file
+ test_file = SimpleUploadedFile(
+ name='test_file.txt',
+ content=b'test content',
+ content_type='text/plain'
+ )
+
+ attr = ConcreteAttributeModel(
+ name='test_attr',
+ value_type_str='FILE',
+ attribute_type_str='CUSTOM'
+ )
+ attr.file_value = test_file
+ attr.pk = 1 # Set a fake primary key
+
+ # Mock the delete operation to avoid database issues
+ with patch('django.db.models.Model.delete'):
+ attr.delete()
+
+ # Should check and delete file
+ mock_storage.exists.assert_called_once_with(test_file)
+ mock_storage.delete.assert_called_once_with(test_file)
+ return
+
+ @patch('hi.apps.attribute.models.default_storage')
+ def test_attribute_model_file_deletion_missing_file(self, mock_storage):
+ """Test file deletion when file doesn't exist - error handling."""
+ mock_storage.exists.return_value = False
+
+ # Create attribute with file reference that doesn't exist
+ attr = ConcreteAttributeModel(
+ name='test_attr',
+ value_type_str='FILE',
+ attribute_type_str='CUSTOM'
+ )
+ attr.file_value = 'nonexistent_file.txt'
+ attr.pk = 1 # Set a fake primary key
+
+ # Mock the delete operation to avoid database issues
+ with patch('django.db.models.Model.delete'):
+ attr.delete()
+
+ # Should check existence but not try to delete
+ mock_storage.exists.assert_called_once_with('nonexistent_file.txt')
+ mock_storage.delete.assert_not_called()
+ return
+
+ @patch('hi.apps.attribute.models.default_storage')
+ def test_attribute_model_file_deletion_exception_handling(self, mock_storage):
+ """Test file deletion exception handling - resilient error handling."""
+ mock_storage.exists.return_value = True
+ mock_storage.delete.side_effect = Exception('Storage error')
+
+ attr = ConcreteAttributeModel(
+ name='test_attr',
+ value_type_str='FILE',
+ attribute_type_str='CUSTOM'
+ )
+ attr.file_value = 'test_file.txt'
+ attr.pk = 1 # Set a fake primary key
+
+ # Mock the delete operation to avoid database issues
+ with patch('django.db.models.Model.delete'):
+ # Delete should not raise exception even if storage deletion fails
+ attr.delete()
+
+ mock_storage.exists.assert_called_once_with('test_file.txt')
+ mock_storage.delete.assert_called_once_with('test_file.txt')
+ return
+
+ def test_attribute_model_abstract_upload_to_enforcement(self):
+ """Test abstract get_upload_to method enforcement - critical for subclass contracts."""
+ # Test that abstract method raises NotImplementedError
+ # We use our concrete class but call parent method directly
+ attr = ConcreteAttributeModel(
+ name='test_attr',
+ value_type_str='FILE',
+ attribute_type_str='CUSTOM'
+ )
+
+ # Should raise NotImplementedError when calling parent method
+ with self.assertRaises(NotImplementedError):
+ AttributeModel.get_upload_to(attr)
+ return
+
+ def test_attribute_model_string_representation(self):
+ """Test __str__ and __repr__ methods - important for debugging."""
+ attr = ConcreteAttributeModel(
+ name='test_attr',
+ value='test_value',
+ value_type_str='TEXT',
+ attribute_type_str='CUSTOM'
+ )
+
+ str_repr = str(attr)
+ self.assertIn('test_attr', str_repr)
+ self.assertIn('test_value', str_repr)
+ self.assertIn('TEXT', str_repr)
+ self.assertIn('CUSTOM', str_repr)
+
+ # __repr__ should equal __str__
+ self.assertEqual(repr(attr), str(attr))
+ return
diff --git a/src/hi/apps/attribute/tests/test_value_ranges.py b/src/hi/apps/attribute/tests/test_value_ranges.py
new file mode 100644
index 00000000..ad663ce7
--- /dev/null
+++ b/src/hi/apps/attribute/tests/test_value_ranges.py
@@ -0,0 +1,95 @@
+import logging
+from unittest.mock import patch
+
+from hi.apps.attribute.value_ranges import PredefinedValueRanges
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestPredefinedValueRanges(BaseTestCase):
+
+ def test_predefined_value_ranges_known_ids_mapping(self):
+ """Test known ID to choices mapping - critical for predefined attribute functionality."""
+ # Test that all predefined IDs are in the mapping
+ expected_ids = {
+ PredefinedValueRanges.TIMEZONE_CHOICES_ID,
+ PredefinedValueRanges.UNITS_CHOICES_ID,
+ PredefinedValueRanges.THEME_CHOICES_ID,
+ PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,
+ PredefinedValueRanges.TIME_OF_DAY_CHOICES_ID,
+ }
+
+ actual_ids = set(PredefinedValueRanges.ID_TO_CHOICES.keys())
+ self.assertEqual(actual_ids, expected_ids)
+ return
+
+ def test_predefined_value_ranges_get_choices_valid_id(self):
+ """Test get_choices with valid ID - critical for choices lookup."""
+ # Test with a known ID
+ choices = PredefinedValueRanges.get_choices(PredefinedValueRanges.TIME_OF_DAY_CHOICES_ID)
+
+ # Should return a list of tuples
+ self.assertIsInstance(choices, list)
+ if choices: # If not empty
+ self.assertIsInstance(choices[0], tuple)
+ self.assertEqual(len(choices[0]), 2) # Each choice should be (value, label)
+ return
+
+ def test_predefined_value_ranges_get_choices_invalid_id(self):
+ """Test get_choices with invalid ID - error handling."""
+ choices = PredefinedValueRanges.get_choices('invalid.id')
+
+ # Should return None for unknown IDs
+ self.assertIsNone(choices)
+ return
+
+ @patch('hi.apps.attribute.value_ranges.TIMEZONE_NAME_LIST')
+ def test_predefined_value_ranges_timezone_choices_generation(self, mock_timezone_list):
+ """Test timezone choices generation - complex list processing."""
+ mock_timezone_list = ['UTC', 'America/New_York', 'Europe/London']
+
+ # Patch the ID_TO_CHOICES to use our mock
+ with patch.object(PredefinedValueRanges, 'ID_TO_CHOICES', {
+ PredefinedValueRanges.TIMEZONE_CHOICES_ID: [(x, x) for x in mock_timezone_list]
+ }):
+ choices = PredefinedValueRanges.get_choices(PredefinedValueRanges.TIMEZONE_CHOICES_ID)
+
+ expected = [('UTC', 'UTC'), ('America/New_York', 'America/New_York'), ('Europe/London', 'Europe/London')]
+ self.assertEqual(choices, expected)
+ return
+
+ def test_predefined_value_ranges_id_constants_immutability(self):
+ """Test predefined ID constants - critical for API stability."""
+ # These constants should never change as they may be stored in database
+ self.assertEqual(PredefinedValueRanges.TIMEZONE_CHOICES_ID, 'hi.timezone')
+ self.assertEqual(PredefinedValueRanges.UNITS_CHOICES_ID, 'hi.units')
+ self.assertEqual(PredefinedValueRanges.THEME_CHOICES_ID, 'hi.theme')
+ self.assertEqual(PredefinedValueRanges.AUDIO_FILE_CHOICES_ID, 'hi.audio.file')
+ self.assertEqual(PredefinedValueRanges.TIME_OF_DAY_CHOICES_ID, 'hi.datetime.time-of-day')
+ return
+
+ @patch('hi.apps.attribute.value_ranges.DisplayUnits')
+ @patch('hi.apps.attribute.value_ranges.Theme')
+ @patch('hi.apps.attribute.value_ranges.AudioFile')
+ def test_predefined_value_ranges_enum_integration(self, mock_audio_file, mock_theme, mock_display_units):
+ """Test integration with enum choices - external dependency handling."""
+ # Mock the enum choices methods
+ mock_display_units.choices.return_value = [('metric', 'Metric'), ('imperial', 'Imperial')]
+ mock_theme.choices.return_value = [('light', 'Light'), ('dark', 'Dark')]
+ mock_audio_file.choices.return_value = [('beep.wav', 'Beep'), ('chime.wav', 'Chime')]
+
+ # Test that the mapping calls the enum methods
+ with patch.object(PredefinedValueRanges, 'ID_TO_CHOICES', {
+ PredefinedValueRanges.UNITS_CHOICES_ID: mock_display_units.choices(),
+ PredefinedValueRanges.THEME_CHOICES_ID: mock_theme.choices(),
+ PredefinedValueRanges.AUDIO_FILE_CHOICES_ID: mock_audio_file.choices(),
+ }):
+ units_choices = PredefinedValueRanges.get_choices(PredefinedValueRanges.UNITS_CHOICES_ID)
+ theme_choices = PredefinedValueRanges.get_choices(PredefinedValueRanges.THEME_CHOICES_ID)
+ audio_choices = PredefinedValueRanges.get_choices(PredefinedValueRanges.AUDIO_FILE_CHOICES_ID)
+
+ self.assertEqual(units_choices, [('metric', 'Metric'), ('imperial', 'Imperial')])
+ self.assertEqual(theme_choices, [('light', 'Light'), ('dark', 'Dark')])
+ self.assertEqual(audio_choices, [('beep.wav', 'Beep'), ('chime.wav', 'Chime')])
+ return
diff --git a/src/hi/apps/collection/tests/__init__.py b/src/hi/apps/collection/tests/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/apps/collection/tests/test_collection_manager.py b/src/hi/apps/collection/tests/test_collection_manager.py
new file mode 100644
index 00000000..5c11280f
--- /dev/null
+++ b/src/hi/apps/collection/tests/test_collection_manager.py
@@ -0,0 +1,408 @@
+import logging
+from decimal import Decimal
+from unittest.mock import Mock, patch
+
+from hi.apps.collection.collection_manager import CollectionManager
+from hi.apps.collection.models import Collection, CollectionEntity, CollectionPosition, CollectionView
+from hi.apps.entity.models import Entity
+from hi.apps.location.models import Location, LocationView
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestCollectionManager(BaseTestCase):
+
+ def test_collection_manager_singleton_behavior(self):
+ """Test CollectionManager singleton pattern - critical for system consistency."""
+ manager1 = CollectionManager()
+ manager2 = CollectionManager()
+
+ # Should be the same instance
+ self.assertIs(manager1, manager2)
+ return
+
+ def test_get_collection_with_cached_collection(self):
+ """Test get_collection with cached collection - critical for performance."""
+ collection = Collection.objects.create(
+ name='Test Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID'
+ )
+
+ # Mock request with cached collection
+ mock_request = Mock()
+ mock_request.view_parameters.collection = collection
+
+ manager = CollectionManager()
+ result = manager.get_collection(mock_request, collection.id)
+
+ # Should return cached collection
+ self.assertEqual(result, collection)
+ return
+
+ def test_get_collection_with_database_lookup(self):
+ """Test get_collection with database lookup - critical for data retrieval."""
+ collection = Collection.objects.create(
+ name='Test Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID'
+ )
+
+ # Mock request without cached collection
+ mock_request = Mock()
+ mock_request.view_parameters.collection = None
+
+ manager = CollectionManager()
+ result = manager.get_collection(mock_request, collection.id)
+
+ # Should return collection from database
+ self.assertEqual(result, collection)
+ return
+
+ def test_get_default_collection_with_cached_collection(self):
+ """Test get_default_collection with cached collection - performance optimization."""
+ collection = Collection.objects.create(
+ name='Test Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID'
+ )
+
+ # Mock request with cached collection
+ mock_request = Mock()
+ mock_request.view_parameters.collection = collection
+
+ manager = CollectionManager()
+ result = manager.get_default_collection(mock_request)
+
+ # Should return cached collection
+ self.assertEqual(result, collection)
+ return
+
+ def test_get_default_collection_with_database_fallback(self):
+ """Test get_default_collection with database fallback - critical for system initialization."""
+ collection = Collection.objects.create(
+ name='Default Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID',
+ order_id=1
+ )
+
+ # Mock request without cached collection
+ mock_request = Mock()
+ mock_request.view_parameters.collection = None
+
+ manager = CollectionManager()
+ result = manager.get_default_collection(mock_request)
+
+ # Should return first collection by order_id
+ self.assertEqual(result, collection)
+ return
+
+ def test_get_default_collection_no_collections_exist(self):
+ """Test get_default_collection when no collections exist - error handling."""
+ # Mock request without cached collection
+ mock_request = Mock()
+ mock_request.view_parameters.collection = None
+
+ manager = CollectionManager()
+
+ # Should raise DoesNotExist when no collections
+ with self.assertRaises(Collection.DoesNotExist):
+ manager.get_default_collection(mock_request)
+ return
+
+ def test_create_collection_entity_with_order_calculation(self):
+ """Test create_collection_entity with order calculation - complex ordering logic."""
+ collection = Collection.objects.create(
+ name='Test Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID'
+ )
+
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+
+ # Create existing entity with order_id=5
+ existing_entity = Entity.objects.create(
+ name='Existing Entity',
+ entity_type_str='LIGHT'
+ )
+ CollectionEntity.objects.create(
+ collection=collection,
+ entity=existing_entity,
+ order_id=5
+ )
+
+ manager = CollectionManager()
+ result = manager.create_collection_entity(entity, collection)
+
+ # Should create with next order_id
+ self.assertEqual(result.entity, entity)
+ self.assertEqual(result.collection, collection)
+ self.assertEqual(result.order_id, 6) # 5 + 1
+ return
+
+ def test_create_collection_entity_first_entity(self):
+ """Test create_collection_entity for first entity - initialization logic."""
+ collection = Collection.objects.create(
+ name='Test Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID'
+ )
+
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+
+ manager = CollectionManager()
+ result = manager.create_collection_entity(entity, collection)
+
+ # Should create with order_id=0 for first entity
+ self.assertEqual(result.order_id, 0)
+ return
+
+ def test_remove_collection_entity_exists(self):
+ """Test remove_collection_entity when entity exists - successful removal."""
+ collection = Collection.objects.create(
+ name='Test Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID'
+ )
+
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+
+ collection_entity = CollectionEntity.objects.create(
+ collection=collection,
+ entity=entity
+ )
+
+ manager = CollectionManager()
+ result = manager.remove_collection_entity(entity, collection)
+
+ # Should return True and delete the entity
+ self.assertTrue(result)
+ self.assertFalse(CollectionEntity.objects.filter(id=collection_entity.id).exists())
+ return
+
+ def test_remove_collection_entity_not_exists(self):
+ """Test remove_collection_entity when entity doesn't exist - error handling."""
+ collection = Collection.objects.create(
+ name='Test Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID'
+ )
+
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+
+ manager = CollectionManager()
+ result = manager.remove_collection_entity(entity, collection)
+
+ # Should return False when entity doesn't exist in collection
+ self.assertFalse(result)
+ return
+
+ def test_toggle_collection_in_view_add_to_view(self):
+ """Test toggle_collection_in_view adding collection - complex toggle logic."""
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+
+ location_view = LocationView.objects.create(
+ location=location,
+ location_view_type_str='DEFAULT',
+ name='Test View',
+ svg_view_box_str='0 0 50 50',
+ svg_rotate=0,
+ svg_style_name_str='COLOR'
+ )
+
+ collection = Collection.objects.create(
+ name='Test Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID'
+ )
+
+ manager = CollectionManager()
+
+ # Mock the create_collection_view method to avoid complex SVG item logic
+ with patch.object(manager, 'create_collection_view') as mock_create:
+ mock_collection_view = Mock()
+ mock_create.return_value = mock_collection_view
+
+ result = manager.toggle_collection_in_view(collection, location_view)
+
+ # Should return True (added) and call create_collection_view
+ self.assertTrue(result)
+ mock_create.assert_called_once_with(
+ collection=collection,
+ location_view=location_view
+ )
+ return
+
+ def test_toggle_collection_in_view_remove_from_view(self):
+ """Test toggle_collection_in_view removing collection - complex toggle logic."""
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+
+ location_view = LocationView.objects.create(
+ location=location,
+ location_view_type_str='DEFAULT',
+ name='Test View',
+ svg_view_box_str='0 0 50 50',
+ svg_rotate=0,
+ svg_style_name_str='COLOR'
+ )
+
+ collection = Collection.objects.create(
+ name='Test Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID'
+ )
+
+ # Create existing collection view
+ CollectionView.objects.create(
+ collection=collection,
+ location_view=location_view
+ )
+
+ manager = CollectionManager()
+ result = manager.toggle_collection_in_view(collection, location_view)
+
+ # Should return False (removed) and delete the collection view
+ self.assertFalse(result)
+ self.assertFalse(CollectionView.objects.filter(
+ collection=collection,
+ location_view=location_view
+ ).exists())
+ return
+
+ def test_set_collection_entity_order_batch_update(self):
+ """Test set_collection_entity_order batch update - complex ordering logic."""
+ collection = Collection.objects.create(
+ name='Test Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID'
+ )
+
+ # Create entities in different order
+ entity1 = Entity.objects.create(name='Entity 1', entity_type_str='CAMERA')
+ entity2 = Entity.objects.create(name='Entity 2', entity_type_str='LIGHT')
+ entity3 = Entity.objects.create(name='Entity 3', entity_type_str='SENSOR')
+
+ ce1 = CollectionEntity.objects.create(collection=collection, entity=entity1, order_id=1)
+ ce2 = CollectionEntity.objects.create(collection=collection, entity=entity2, order_id=2)
+ ce3 = CollectionEntity.objects.create(collection=collection, entity=entity3, order_id=3)
+
+ # Reorder: entity3, entity1, entity2
+ entity_id_list = [entity3.id, entity1.id, entity2.id]
+
+ manager = CollectionManager()
+ manager.set_collection_entity_order(collection, entity_id_list)
+
+ # Check new order (with gaps: 2, 4, 6)
+ ce1.refresh_from_db()
+ ce2.refresh_from_db()
+ ce3.refresh_from_db()
+
+ self.assertEqual(ce3.order_id, 2) # First in new order
+ self.assertEqual(ce1.order_id, 4) # Second in new order
+ self.assertEqual(ce2.order_id, 6) # Third in new order
+ return
+
+ def test_add_collection_position_if_needed_creates_position(self):
+ """Test add_collection_position_if_needed creating position - complex geometry calculation."""
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='10 20 100 200' # x=10, y=20, width=100, height=200
+ )
+
+ location_view = LocationView.objects.create(
+ location=location,
+ location_view_type_str='DEFAULT',
+ name='Test View',
+ svg_view_box_str='10 20 100 200',
+ svg_rotate=0,
+ svg_style_name_str='COLOR'
+ )
+
+ collection = Collection.objects.create(
+ name='Test Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID'
+ )
+
+ manager = CollectionManager()
+ result = manager.add_collection_position_if_needed(collection, location_view)
+
+ # Should create position at center of view box
+ self.assertIsNotNone(result)
+ self.assertEqual(result.collection, collection)
+ self.assertEqual(result.location, location)
+
+ # Center calculation: x + width/2 = 10 + 100/2 = 60
+ # Center calculation: y + height/2 = 20 + 200/2 = 120
+ self.assertEqual(result.svg_x, Decimal('60'))
+ self.assertEqual(result.svg_y, Decimal('120'))
+ self.assertEqual(result.svg_scale, Decimal('1.0'))
+ self.assertEqual(result.svg_rotate, Decimal('0.0'))
+ return
+
+ def test_add_collection_position_if_needed_position_exists(self):
+ """Test add_collection_position_if_needed when position exists - no-op behavior."""
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+
+ location_view = LocationView.objects.create(
+ location=location,
+ location_view_type_str='DEFAULT',
+ name='Test View',
+ svg_view_box_str='0 0 100 100',
+ svg_rotate=0,
+ svg_style_name_str='COLOR'
+ )
+
+ collection = Collection.objects.create(
+ name='Test Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID'
+ )
+
+ # Create existing position
+ existing_position = CollectionPosition.objects.create(
+ location=location,
+ collection=collection,
+ svg_x=25.0,
+ svg_y=25.0,
+ svg_scale=1.0,
+ svg_rotate=0.0
+ )
+
+ manager = CollectionManager()
+ result = manager.add_collection_position_if_needed(collection, location_view)
+
+ # Should return None (no-op) when position already exists
+ self.assertIsNone(result)
+
+ # Existing position should be unchanged
+ existing_position.refresh_from_db()
+ self.assertEqual(existing_position.svg_x, Decimal('25.0'))
+ return
diff --git a/src/hi/apps/collection/tests/test_enums.py b/src/hi/apps/collection/tests/test_enums.py
new file mode 100644
index 00000000..d08ce5f2
--- /dev/null
+++ b/src/hi/apps/collection/tests/test_enums.py
@@ -0,0 +1,38 @@
+import logging
+
+from hi.apps.collection.enums import CollectionType, CollectionViewType
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestCollectionType(BaseTestCase):
+
+ def test_collection_type_default_fallback(self):
+ """Test CollectionType default fallback - critical for initialization."""
+ self.assertEqual(CollectionType.default(), CollectionType.OTHER)
+ return
+
+
+class TestCollectionViewType(BaseTestCase):
+
+ def test_collection_view_type_classification_logic(self):
+ """Test CollectionViewType classification methods - critical for UI logic."""
+ # GRID type
+ self.assertTrue(CollectionViewType.GRID.is_grid())
+ self.assertFalse(CollectionViewType.GRID.is_list())
+
+ # LIST type
+ self.assertFalse(CollectionViewType.LIST.is_grid())
+ self.assertTrue(CollectionViewType.LIST.is_list())
+ return
+
+ def test_collection_view_type_mutual_exclusivity(self):
+ """Test view type mutual exclusivity - critical for business logic."""
+ for view_type in CollectionViewType:
+ # Each type should be either grid or list, but not both
+ is_grid = view_type.is_grid()
+ is_list = view_type.is_list()
+ self.assertTrue(is_grid or is_list, f"{view_type} is neither grid nor list")
+ self.assertFalse(is_grid and is_list, f"{view_type} is both grid and list")
+ return
diff --git a/src/hi/apps/collection/tests/test_models.py b/src/hi/apps/collection/tests/test_models.py
new file mode 100644
index 00000000..458d738f
--- /dev/null
+++ b/src/hi/apps/collection/tests/test_models.py
@@ -0,0 +1,389 @@
+import logging
+from django.db import IntegrityError
+
+from hi.apps.collection.models import Collection, CollectionEntity, CollectionPosition, CollectionPath, CollectionView
+from hi.apps.collection.enums import CollectionType, CollectionViewType
+from hi.apps.entity.models import Entity
+from hi.apps.location.models import Location, LocationView
+from hi.enums import ItemType
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestCollection(BaseTestCase):
+
+ def test_collection_enum_property_conversions(self):
+ """Test Collection enum property conversions - custom business logic."""
+ collection = Collection.objects.create(
+ name='Test Collection',
+ collection_type_str='CAMERAS',
+ collection_view_type_str='GRID'
+ )
+
+ # Test getter converts string to enum
+ self.assertEqual(collection.collection_type, CollectionType.CAMERAS)
+ self.assertEqual(collection.collection_view_type, CollectionViewType.GRID)
+
+ # Test setter converts enum to string
+ collection.collection_type = CollectionType.TOOLS
+ collection.collection_view_type = CollectionViewType.LIST
+ self.assertEqual(collection.collection_type_str, 'tools')
+ self.assertEqual(collection.collection_view_type_str, 'list')
+ return
+
+ def test_collection_item_type_property(self):
+ """Test item_type property - critical for type system integration."""
+ collection = Collection.objects.create(
+ name='Test Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID'
+ )
+
+ self.assertEqual(collection.item_type, ItemType.COLLECTION)
+ return
+
+ def test_collection_ordering_by_order_id(self):
+ """Test Collection ordering - critical for UI display order."""
+ # Create collections with different order_ids
+ collection1 = Collection.objects.create(
+ name='First Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID',
+ order_id=2
+ )
+ collection2 = Collection.objects.create(
+ name='Second Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID',
+ order_id=1
+ )
+ collection3 = Collection.objects.create(
+ name='Third Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID',
+ order_id=3
+ )
+
+ # Should be ordered by order_id
+ collections = list(Collection.objects.all())
+ self.assertEqual(collections[0], collection2) # order_id=1
+ self.assertEqual(collections[1], collection1) # order_id=2
+ self.assertEqual(collections[2], collection3) # order_id=3
+ return
+
+
+class TestCollectionEntity(BaseTestCase):
+
+ def test_collection_entity_ordering_by_order_id(self):
+ """Test CollectionEntity ordering - critical for entity display order."""
+ collection = Collection.objects.create(
+ name='Test Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID'
+ )
+
+ entity1 = Entity.objects.create(
+ name='Entity 1',
+ entity_type_str='CAMERA'
+ )
+ entity2 = Entity.objects.create(
+ name='Entity 2',
+ entity_type_str='LIGHT'
+ )
+
+ # Create collection entities with specific order
+ ce1 = CollectionEntity.objects.create(
+ collection=collection,
+ entity=entity1,
+ order_id=2
+ )
+ ce2 = CollectionEntity.objects.create(
+ collection=collection,
+ entity=entity2,
+ order_id=1
+ )
+
+ # Should be ordered by order_id
+ collection_entities = list(CollectionEntity.objects.filter(collection=collection))
+ self.assertEqual(collection_entities[0], ce2) # order_id=1
+ self.assertEqual(collection_entities[1], ce1) # order_id=2
+ return
+
+ def test_collection_entity_cascade_deletion_from_collection(self):
+ """Test cascade deletion from collection - critical for data integrity."""
+ collection = Collection.objects.create(
+ name='Test Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID'
+ )
+
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+
+ collection_entity = CollectionEntity.objects.create(
+ collection=collection,
+ entity=entity
+ )
+
+ ce_id = collection_entity.id
+
+ # Delete collection should cascade to collection entities
+ collection.delete()
+
+ self.assertFalse(CollectionEntity.objects.filter(id=ce_id).exists())
+ return
+
+ def test_collection_entity_cascade_deletion_from_entity(self):
+ """Test cascade deletion from entity - critical for data integrity."""
+ collection = Collection.objects.create(
+ name='Test Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID'
+ )
+
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+
+ collection_entity = CollectionEntity.objects.create(
+ collection=collection,
+ entity=entity
+ )
+
+ ce_id = collection_entity.id
+
+ # Delete entity should cascade to collection entities
+ entity.delete()
+
+ self.assertFalse(CollectionEntity.objects.filter(id=ce_id).exists())
+ return
+
+ def test_collection_entity_database_indexing(self):
+ """Test CollectionEntity database indexing - critical for query performance."""
+ collection = Collection.objects.create(
+ name='Test Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID'
+ )
+
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+
+ collection_entity = CollectionEntity.objects.create(
+ collection=collection,
+ entity=entity
+ )
+
+ # Test that indexed query works efficiently
+ # (The actual index performance isn't testable in unit tests,
+ # but we can verify the fields are queryable)
+ results = CollectionEntity.objects.filter(
+ collection=collection,
+ entity=entity
+ )
+ self.assertIn(collection_entity, results)
+ return
+
+
+class TestCollectionPosition(BaseTestCase):
+
+ def test_collection_position_uniqueness_constraint(self):
+ """Test location-collection uniqueness constraint - critical for data integrity."""
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+
+ collection = Collection.objects.create(
+ name='Test Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID'
+ )
+
+ # Create first position
+ CollectionPosition.objects.create(
+ location=location,
+ collection=collection,
+ svg_x=10.0,
+ svg_y=20.0,
+ svg_scale=1.0,
+ svg_rotate=0.0
+ )
+
+ # Duplicate location-collection should fail
+ with self.assertRaises(IntegrityError):
+ CollectionPosition.objects.create(
+ location=location,
+ collection=collection,
+ svg_x=30.0,
+ svg_y=40.0,
+ svg_scale=1.0,
+ svg_rotate=0.0
+ )
+ return
+
+ def test_collection_position_location_item_property(self):
+ """Test location_item property delegation - critical for interface compliance."""
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+
+ collection = Collection.objects.create(
+ name='Test Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID'
+ )
+
+ position = CollectionPosition.objects.create(
+ location=location,
+ collection=collection,
+ svg_x=10.0,
+ svg_y=20.0,
+ svg_scale=1.0,
+ svg_rotate=0.0
+ )
+
+ # Should delegate to collection
+ self.assertEqual(position.location_item, collection)
+ return
+
+
+class TestCollectionPath(BaseTestCase):
+
+ def test_collection_path_uniqueness_constraint(self):
+ """Test location-collection uniqueness constraint - critical for data integrity."""
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+
+ collection = Collection.objects.create(
+ name='Test Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID'
+ )
+
+ # Create first path
+ CollectionPath.objects.create(
+ location=location,
+ collection=collection,
+ svg_path='M 10,10 L 50,50 Z'
+ )
+
+ # Duplicate location-collection should fail
+ with self.assertRaises(IntegrityError):
+ CollectionPath.objects.create(
+ location=location,
+ collection=collection,
+ svg_path='M 20,20 L 60,60 Z'
+ )
+ return
+
+ def test_collection_path_location_item_property(self):
+ """Test location_item property delegation - critical for interface compliance."""
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+
+ collection = Collection.objects.create(
+ name='Test Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID'
+ )
+
+ path = CollectionPath.objects.create(
+ location=location,
+ collection=collection,
+ svg_path='M 10,10 L 50,50 Z'
+ )
+
+ # Should delegate to collection
+ self.assertEqual(path.location_item, collection)
+ return
+
+
+class TestCollectionView(BaseTestCase):
+
+ def test_collection_view_cascade_deletion_from_collection(self):
+ """Test cascade deletion from collection - critical for data integrity."""
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+
+ location_view = LocationView.objects.create(
+ location=location,
+ location_view_type_str='DEFAULT',
+ name='Test View',
+ svg_view_box_str='0 0 50 50',
+ svg_rotate=0,
+ svg_style_name_str='COLOR'
+ )
+
+ collection = Collection.objects.create(
+ name='Test Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID'
+ )
+
+ collection_view = CollectionView.objects.create(
+ collection=collection,
+ location_view=location_view
+ )
+
+ cv_id = collection_view.id
+
+ # Delete collection should cascade to collection view
+ collection.delete()
+
+ self.assertFalse(CollectionView.objects.filter(id=cv_id).exists())
+ return
+
+ def test_collection_view_cascade_deletion_from_location_view(self):
+ """Test cascade deletion from location view - critical for data integrity."""
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+
+ location_view = LocationView.objects.create(
+ location=location,
+ location_view_type_str='DEFAULT',
+ name='Test View',
+ svg_view_box_str='0 0 50 50',
+ svg_rotate=0,
+ svg_style_name_str='COLOR'
+ )
+
+ collection = Collection.objects.create(
+ name='Test Collection',
+ collection_type_str='OTHER',
+ collection_view_type_str='GRID'
+ )
+
+ collection_view = CollectionView.objects.create(
+ collection=collection,
+ location_view=location_view
+ )
+
+ cv_id = collection_view.id
+
+ # Delete location view should cascade to collection view
+ location_view.delete()
+
+ self.assertFalse(CollectionView.objects.filter(id=cv_id).exists())
+ return
diff --git a/src/hi/apps/config/tests/__init__.py b/src/hi/apps/config/tests/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/apps/config/tests/test_app_settings.py b/src/hi/apps/config/tests/test_app_settings.py
new file mode 100644
index 00000000..5f71f588
--- /dev/null
+++ b/src/hi/apps/config/tests/test_app_settings.py
@@ -0,0 +1,289 @@
+import logging
+from types import ModuleType
+from unittest.mock import Mock
+
+from hi.apps.config.app_settings import AppSettings, AppSettingDefinitions
+from hi.apps.config.setting_enums import SettingEnum, SettingDefinition
+from hi.apps.attribute.enums import AttributeValueType
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+# Create mock module with setting enums for testing
+class MockModuleSetting(SettingEnum):
+ MOCK_SETTING_ONE = SettingDefinition(
+ label='Mock Setting One',
+ description='First mock setting',
+ value_type=AttributeValueType.TEXT,
+ value_range_str='',
+ is_editable=True,
+ is_required=True,
+ initial_value='mock_default_one',
+ )
+ MOCK_SETTING_TWO = SettingDefinition(
+ label='Mock Setting Two',
+ description='Second mock setting',
+ value_type=AttributeValueType.INTEGER,
+ value_range_str='[0, 100]',
+ is_editable=True,
+ is_required=False,
+ initial_value='10',
+ )
+
+
+class AnotherMockSetting(SettingEnum):
+ ANOTHER_MOCK_SETTING = SettingDefinition(
+ label='Another Mock Setting',
+ description='Another mock setting',
+ value_type=AttributeValueType.BOOLEAN,
+ value_range_str='',
+ is_editable=True,
+ is_required=True,
+ initial_value='false',
+ )
+
+
+def create_mock_module(label=None, *setting_classes):
+ """Helper to create mock module with settings."""
+ mock_module = Mock(spec=ModuleType)
+
+ # Set up module attributes
+ if label:
+ mock_module.Label = label
+
+ # Add setting classes to module
+ for setting_class in setting_classes:
+ setattr(mock_module, setting_class.__name__, setting_class)
+
+ # Mock dir() to return setting class names
+ setting_names = [cls.__name__ for cls in setting_classes]
+ mock_module.__dir__ = Mock(return_value=setting_names)
+
+ return mock_module
+
+
+class TestAppSettingDefinitions(BaseTestCase):
+
+ def test_app_setting_definitions_creation(self):
+ """Test AppSettingDefinitions dataclass creation."""
+ setting_definition_map = {
+ MockModuleSetting.MOCK_SETTING_ONE.key: MockModuleSetting.MOCK_SETTING_ONE.definition,
+ MockModuleSetting.MOCK_SETTING_TWO.key: MockModuleSetting.MOCK_SETTING_TWO.definition,
+ }
+
+ app_setting_definitions = AppSettingDefinitions(
+ setting_enum_class=MockModuleSetting,
+ setting_definition_map=setting_definition_map,
+ )
+
+ self.assertEqual(app_setting_definitions.setting_enum_class, MockModuleSetting)
+ self.assertEqual(app_setting_definitions.setting_definition_map, setting_definition_map)
+ return
+
+ def test_app_setting_definitions_len(self):
+ """Test AppSettingDefinitions __len__ method."""
+ setting_definition_map = {
+ 'key1': MockModuleSetting.MOCK_SETTING_ONE.definition,
+ 'key2': MockModuleSetting.MOCK_SETTING_TWO.definition,
+ }
+
+ app_setting_definitions = AppSettingDefinitions(
+ setting_enum_class=MockModuleSetting,
+ setting_definition_map=setting_definition_map,
+ )
+
+ self.assertEqual(len(app_setting_definitions), 2)
+ return
+
+
+class TestAppSettings(BaseTestCase):
+
+ def test_app_settings_with_explicit_label(self):
+ """Test AppSettings with explicit label in module."""
+ mock_module = create_mock_module('Custom Label', MockModuleSetting)
+
+ app_settings = AppSettings(
+ app_name='test.app.name',
+ app_module=mock_module,
+ )
+
+ self.assertEqual(app_settings.app_name, 'test.app.name')
+ self.assertEqual(app_settings.label, 'Custom Label')
+ return
+
+ def test_app_settings_with_default_label(self):
+ """Test AppSettings with default label generation."""
+ mock_module = create_mock_module(None, MockModuleSetting) # No Label attribute
+
+ app_settings = AppSettings(
+ app_name='test.app.weather_station',
+ app_module=mock_module,
+ )
+
+ self.assertEqual(app_settings.app_name, 'test.app.weather_station')
+ # Should humanize the last part of the app name
+ self.assertEqual(app_settings.label, 'Weather Station')
+ return
+
+ def test_app_settings_with_non_string_label(self):
+ """Test AppSettings when Label attribute is not a string."""
+ mock_module = create_mock_module(123, MockModuleSetting) # Non-string Label
+
+ app_settings = AppSettings(
+ app_name='test.app.sensor_hub',
+ app_module=mock_module,
+ )
+
+ # Should fall back to default label generation
+ self.assertEqual(app_settings.label, 'Sensor Hub')
+ return
+
+ def test_app_settings_no_setting_classes(self):
+ """Test AppSettings with module containing no SettingEnum classes."""
+ mock_module = create_mock_module('Empty Module') # No setting classes
+
+ app_settings = AppSettings(
+ app_name='test.app.empty',
+ app_module=mock_module,
+ )
+
+ self.assertEqual(len(app_settings), 0)
+ self.assertEqual(app_settings.all_setting_definitions(), {})
+ return
+
+ def test_app_settings_single_setting_class(self):
+ """Test AppSettings with single SettingEnum class."""
+ mock_module = create_mock_module('Single Settings', MockModuleSetting)
+
+ app_settings = AppSettings(
+ app_name='test.app.single',
+ app_module=mock_module,
+ )
+
+ self.assertEqual(len(app_settings), 1)
+
+ all_definitions = app_settings.all_setting_definitions()
+ self.assertEqual(len(all_definitions), 2) # Two settings in MockModuleSetting
+
+ # Check that setting keys are included
+ expected_keys = [
+ MockModuleSetting.MOCK_SETTING_ONE.key,
+ MockModuleSetting.MOCK_SETTING_TWO.key,
+ ]
+ for key in expected_keys:
+ self.assertIn(key, all_definitions)
+ return
+
+ def test_app_settings_multiple_setting_classes(self):
+ """Test AppSettings with multiple SettingEnum classes."""
+ mock_module = create_mock_module('Multiple Settings', MockModuleSetting, AnotherMockSetting)
+
+ app_settings = AppSettings(
+ app_name='test.app.multiple',
+ app_module=mock_module,
+ )
+
+ self.assertEqual(len(app_settings), 2) # Two setting classes
+
+ all_definitions = app_settings.all_setting_definitions()
+ self.assertEqual(len(all_definitions), 3) # Total of 3 settings across both classes
+
+ # Check settings from first class
+ self.assertIn(MockModuleSetting.MOCK_SETTING_ONE.key, all_definitions)
+ self.assertIn(MockModuleSetting.MOCK_SETTING_TWO.key, all_definitions)
+
+ # Check setting from second class
+ self.assertIn(AnotherMockSetting.ANOTHER_MOCK_SETTING.key, all_definitions)
+ return
+
+ def test_app_settings_ignores_non_setting_classes(self):
+ """Test that AppSettings ignores non-SettingEnum classes."""
+ mock_module = create_mock_module('Mixed Module', MockModuleSetting)
+
+ # Add non-SettingEnum classes that should be ignored
+ class NotASettingEnum:
+ pass
+
+ setattr(mock_module, 'NotASettingEnum', NotASettingEnum)
+ setattr(mock_module, 'some_function', lambda: None)
+ setattr(mock_module, 'SOME_CONSTANT', 'value')
+
+ # Update mock dir to include these
+ mock_module.__dir__ = Mock(return_value=[
+ 'MockModuleSetting', 'NotASettingEnum', 'some_function', 'SOME_CONSTANT'
+ ])
+
+ app_settings = AppSettings(
+ app_name='test.app.mixed',
+ app_module=mock_module,
+ )
+
+ # Should only find the one SettingEnum class
+ self.assertEqual(len(app_settings), 1)
+
+ all_definitions = app_settings.all_setting_definitions()
+ self.assertEqual(len(all_definitions), 2) # Only MockModuleSetting's 2 settings
+ return
+
+ def test_app_settings_definition_properties(self):
+ """Test that setting definitions are properly extracted."""
+ mock_module = create_mock_module('Test Module', MockModuleSetting)
+
+ app_settings = AppSettings(
+ app_name='test.app.props',
+ app_module=mock_module,
+ )
+
+ all_definitions = app_settings.all_setting_definitions()
+
+ # Check first setting definition
+ setting_one_def = all_definitions[MockModuleSetting.MOCK_SETTING_ONE.key]
+ self.assertEqual(setting_one_def.label, 'Mock Setting One')
+ self.assertEqual(setting_one_def.description, 'First mock setting')
+ self.assertEqual(setting_one_def.value_type, AttributeValueType.TEXT)
+ self.assertTrue(setting_one_def.is_editable)
+ self.assertTrue(setting_one_def.is_required)
+ self.assertEqual(setting_one_def.initial_value, 'mock_default_one')
+
+ # Check second setting definition
+ setting_two_def = all_definitions[MockModuleSetting.MOCK_SETTING_TWO.key]
+ self.assertEqual(setting_two_def.label, 'Mock Setting Two')
+ self.assertEqual(setting_two_def.description, 'Second mock setting')
+ self.assertEqual(setting_two_def.value_type, AttributeValueType.INTEGER)
+ self.assertEqual(setting_two_def.value_range_str, '[0, 100]')
+ self.assertTrue(setting_two_def.is_editable)
+ self.assertFalse(setting_two_def.is_required)
+ self.assertEqual(setting_two_def.initial_value, '10')
+ return
+
+ def test_app_settings_len(self):
+ """Test AppSettings __len__ method."""
+ # Empty module
+ empty_module = create_mock_module('Empty')
+ empty_app_settings = AppSettings('test.empty', empty_module)
+ self.assertEqual(len(empty_app_settings), 0)
+
+ # Module with one setting class
+ single_module = create_mock_module('Single', MockModuleSetting)
+ single_app_settings = AppSettings('test.single', single_module)
+ self.assertEqual(len(single_app_settings), 1)
+
+ # Module with multiple setting classes
+ multi_module = create_mock_module('Multi', MockModuleSetting, AnotherMockSetting)
+ multi_app_settings = AppSettings('test.multi', multi_module)
+ self.assertEqual(len(multi_app_settings), 2)
+ return
+
+ def test_app_settings_properties(self):
+ """Test AppSettings property accessors."""
+ mock_module = create_mock_module('Test Properties', MockModuleSetting)
+
+ app_settings = AppSettings(
+ app_name='test.app.properties',
+ app_module=mock_module,
+ )
+
+ self.assertEqual(app_settings.app_name, 'test.app.properties')
+ self.assertEqual(app_settings.label, 'Test Properties')
+ return
diff --git a/src/hi/apps/config/tests/test_integration.py b/src/hi/apps/config/tests/test_integration.py
new file mode 100644
index 00000000..01ce435a
--- /dev/null
+++ b/src/hi/apps/config/tests/test_integration.py
@@ -0,0 +1,130 @@
+import logging
+
+from hi.apps.config.models import SubsystemAttribute
+from hi.apps.config.settings_manager import SettingsManager
+from hi.apps.attribute.enums import AttributeValueType
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestConfigIntegration(BaseTestCase):
+ """Integration tests for the config module components working together."""
+
+ def test_end_to_end_setting_workflow(self):
+ """Test complete workflow from model creation to manager access - complex integration."""
+ manager = SettingsManager()
+ manager.ensure_initialized()
+
+ # Use existing subsystem instead of creating new one
+ existing_subsystems = manager.get_subsystems()
+ self.assertGreater(len(existing_subsystems), 0)
+ test_subsystem = existing_subsystems[0]
+
+ # Create settings for the existing subsystem
+ setting_key = 'integration.test.setting'
+ attribute = SubsystemAttribute.objects.create(
+ subsystem=test_subsystem,
+ setting_key=setting_key,
+ value_type=AttributeValueType.TEXT,
+ value='integration_test_value',
+ )
+
+ # Reload manager to pick up changes
+ manager.reload()
+
+ # Verify the setting is accessible
+ self.assertIn(setting_key, manager._attribute_value_map)
+ value = manager._attribute_value_map[setting_key]
+ self.assertEqual(value, 'integration_test_value')
+
+ # Update the setting through the manager
+ mock_setting = type('MockSetting', (), {'key': setting_key})()
+ manager.set_setting_value(mock_setting, 'updated_integration_value')
+
+ # Verify the change is reflected in both memory and database
+ updated_value = manager._attribute_value_map[setting_key]
+ self.assertEqual(updated_value, 'updated_integration_value')
+
+ attribute.refresh_from_db()
+ self.assertEqual(attribute.value, 'updated_integration_value')
+
+ # Clean up
+ attribute.delete()
+ return
+
+ def test_multiple_value_types_integration(self):
+ """Test integration with different attribute value types - complex type handling."""
+ manager = SettingsManager()
+ manager.ensure_initialized()
+
+ # Use existing subsystem instead of creating new one
+ existing_subsystems = manager.get_subsystems()
+ self.assertGreater(len(existing_subsystems), 0)
+ test_subsystem = existing_subsystems[0]
+
+ test_cases = [
+ ('text.setting', AttributeValueType.TEXT, 'text_value'),
+ ('integer.setting', AttributeValueType.INTEGER, '123'),
+ ('float.setting', AttributeValueType.FLOAT, '3.14'),
+ ('boolean.setting', AttributeValueType.BOOLEAN, 'true'),
+ ('enum.setting', AttributeValueType.ENUM, 'OPTION_A'),
+ ]
+
+ created_attributes = []
+ for setting_key, value_type, value in test_cases:
+ attr = SubsystemAttribute.objects.create(
+ subsystem=test_subsystem,
+ setting_key=setting_key,
+ value_type=value_type,
+ value=value,
+ )
+ created_attributes.append(attr)
+
+ manager.reload()
+
+ # Verify all settings are accessible with correct values
+ for setting_key, _, expected_value in test_cases:
+ with self.subTest(setting_key=setting_key):
+ self.assertIn(setting_key, manager._attribute_value_map)
+ actual_value = manager._attribute_value_map[setting_key]
+ self.assertEqual(actual_value, expected_value)
+
+ # Clean up
+ for attr in created_attributes:
+ attr.delete()
+ return
+
+ def test_manager_state_consistency_across_reloads(self):
+ """Test SettingsManager maintains consistent state across multiple reloads - critical stability."""
+ manager = SettingsManager()
+ manager.ensure_initialized()
+
+ # Get initial state after first reload to establish baseline
+ manager.reload()
+ initial_subsystems = len(manager._subsystem_list)
+ initial_attributes = len(manager._attribute_value_map)
+
+ # Multiple reloads should maintain consistency from this baseline
+ for _ in range(3):
+ manager.reload()
+
+ current_subsystems = len(manager._subsystem_list)
+ current_attributes = len(manager._attribute_value_map)
+
+ self.assertEqual(current_subsystems, initial_subsystems)
+ self.assertEqual(current_attributes, initial_attributes)
+ return
+
+ def test_setting_key_uniqueness_constraint(self):
+ """Test that setting keys are unique across the system - critical data integrity."""
+ manager = SettingsManager()
+ manager.ensure_initialized()
+
+ # Get all setting keys
+ setting_keys = list(manager._attribute_value_map.keys())
+
+ # Should have no duplicates
+ unique_keys = set(setting_keys)
+ self.assertEqual(len(setting_keys), len(unique_keys))
+ return
diff --git a/src/hi/apps/config/tests/test_models.py b/src/hi/apps/config/tests/test_models.py
new file mode 100644
index 00000000..98b7fdc9
--- /dev/null
+++ b/src/hi/apps/config/tests/test_models.py
@@ -0,0 +1,54 @@
+import logging
+from django.db import IntegrityError
+
+from hi.apps.config.models import Subsystem, SubsystemAttribute
+from hi.apps.attribute.enums import AttributeValueType
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestSubsystem(BaseTestCase):
+
+ def test_subsystem_unique_key_constraint(self):
+ """Test subsystem_key uniqueness constraint - critical for data integrity."""
+ Subsystem.objects.create(
+ name='First Subsystem',
+ subsystem_key='unique_key',
+ )
+
+ with self.assertRaises(IntegrityError):
+ Subsystem.objects.create(
+ name='Second Subsystem',
+ subsystem_key='unique_key', # Duplicate key should fail
+ )
+ return
+
+
+class TestSubsystemAttribute(BaseTestCase):
+
+ def setUp(self):
+ super().setUp()
+ self.subsystem = Subsystem.objects.create(
+ name='Test Subsystem',
+ subsystem_key='test_subsystem',
+ )
+ return
+
+ def test_subsystem_attribute_cascade_delete(self):
+ """Test cascade deletion behavior - critical for data integrity."""
+ attribute = SubsystemAttribute.objects.create(
+ subsystem=self.subsystem,
+ setting_key='test.setting.key',
+ value_type=AttributeValueType.TEXT,
+ value='test_value',
+ )
+
+ attribute_id = attribute.id
+ self.assertTrue(SubsystemAttribute.objects.filter(id=attribute_id).exists())
+
+ # Delete subsystem should cascade to attributes
+ self.subsystem.delete()
+
+ self.assertFalse(SubsystemAttribute.objects.filter(id=attribute_id).exists())
+ return
diff --git a/src/hi/apps/config/tests/test_setting_enums.py b/src/hi/apps/config/tests/test_setting_enums.py
new file mode 100644
index 00000000..472e0475
--- /dev/null
+++ b/src/hi/apps/config/tests/test_setting_enums.py
@@ -0,0 +1,211 @@
+import logging
+
+from hi.apps.config.setting_enums import SettingEnum, SettingDefinition
+from hi.apps.attribute.enums import AttributeValueType
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+# Create test setting enums for testing
+class TestSetting(SettingEnum):
+ FIRST_SETTING = SettingDefinition(
+ label='First Setting',
+ description='Description for first setting',
+ value_type=AttributeValueType.TEXT,
+ value_range_str='',
+ is_editable=True,
+ is_required=True,
+ initial_value='default_first',
+ )
+ SECOND_SETTING = SettingDefinition(
+ label='Second Setting',
+ description='Description for second setting',
+ value_type=AttributeValueType.INTEGER,
+ value_range_str='[1, 100]',
+ is_editable=False,
+ is_required=False,
+ initial_value='50',
+ )
+
+
+class AnotherTestSetting(SettingEnum):
+ ANOTHER_SETTING = SettingDefinition(
+ label='Another Setting',
+ description='Description for another setting',
+ value_type=AttributeValueType.BOOLEAN,
+ value_range_str='',
+ is_editable=True,
+ is_required=True,
+ initial_value='true',
+ )
+
+
+class TestSettingDefinition(BaseTestCase):
+
+ def test_setting_definition_creation(self):
+ """Test SettingDefinition dataclass creation."""
+ definition = SettingDefinition(
+ label='Test Setting',
+ description='A test setting for testing',
+ value_type=AttributeValueType.TEXT,
+ value_range_str='[a-z]+',
+ is_editable=True,
+ is_required=False,
+ initial_value='default',
+ )
+
+ self.assertEqual(definition.label, 'Test Setting')
+ self.assertEqual(definition.description, 'A test setting for testing')
+ self.assertEqual(definition.value_type, AttributeValueType.TEXT)
+ self.assertEqual(definition.value_range_str, '[a-z]+')
+ self.assertTrue(definition.is_editable)
+ self.assertFalse(definition.is_required)
+ self.assertEqual(definition.initial_value, 'default')
+ return
+
+ def test_setting_definition_all_value_types(self):
+ """Test SettingDefinition with all value types."""
+ test_cases = [
+ (AttributeValueType.TEXT, 'text_default'),
+ (AttributeValueType.INTEGER, '42'),
+ (AttributeValueType.FLOAT, '3.14'),
+ (AttributeValueType.BOOLEAN, 'true'),
+ (AttributeValueType.ENUM, 'OPTION_A'),
+ (AttributeValueType.FILE, 'test.txt'),
+ (AttributeValueType.SECRET, 'secret_value'),
+ ]
+
+ for value_type, initial_value in test_cases:
+ with self.subTest(value_type=value_type):
+ definition = SettingDefinition(
+ label=f'{value_type.name} Setting',
+ description=f'Setting for {value_type.name}',
+ value_type=value_type,
+ value_range_str='',
+ is_editable=True,
+ is_required=True,
+ initial_value=initial_value,
+ )
+
+ self.assertEqual(definition.value_type, value_type)
+ self.assertEqual(definition.initial_value, initial_value)
+ continue
+ return
+
+
+class TestSettingEnum(BaseTestCase):
+
+ def test_setting_enum_creation(self):
+ """Test that SettingEnum creates properly."""
+ # Test enum members exist
+ self.assertTrue(hasattr(TestSetting, 'FIRST_SETTING'))
+ self.assertTrue(hasattr(TestSetting, 'SECOND_SETTING'))
+
+ # Test values are auto-assigned
+ self.assertEqual(TestSetting.FIRST_SETTING.value, 1)
+ self.assertEqual(TestSetting.SECOND_SETTING.value, 2)
+ return
+
+ def test_setting_enum_definition_access(self):
+ """Test accessing SettingDefinition through enum."""
+ first_setting = TestSetting.FIRST_SETTING
+
+ self.assertIsInstance(first_setting.definition, SettingDefinition)
+ self.assertEqual(first_setting.definition.label, 'First Setting')
+ self.assertEqual(first_setting.definition.description, 'Description for first setting')
+ self.assertEqual(first_setting.definition.value_type, AttributeValueType.TEXT)
+ self.assertTrue(first_setting.definition.is_editable)
+ self.assertTrue(first_setting.definition.is_required)
+ self.assertEqual(first_setting.definition.initial_value, 'default_first')
+ return
+
+ def test_setting_enum_key_property(self):
+ """Test the key property generates correct keys."""
+ first_key = TestSetting.FIRST_SETTING.key
+ second_key = TestSetting.SECOND_SETTING.key
+
+ # Keys should include module and class information
+ self.assertIn('TestSetting', first_key)
+ self.assertIn('FIRST_SETTING', first_key)
+ self.assertIn('TestSetting', second_key)
+ self.assertIn('SECOND_SETTING', second_key)
+
+ # Keys should be unique
+ self.assertNotEqual(first_key, second_key)
+ return
+
+ def test_setting_enum_key_format(self):
+ """Test the key property format is correct."""
+ key = TestSetting.FIRST_SETTING.key
+
+ # Should follow format: module.class.name
+ parts = key.split('.')
+ self.assertGreater(len(parts), 2) # At least module.class.name
+ self.assertEqual(parts[-2], 'TestSetting') # Class name
+ self.assertEqual(parts[-1], 'FIRST_SETTING') # Enum name
+ return
+
+ def test_multiple_setting_enums(self):
+ """Test multiple SettingEnum classes work independently."""
+ test_key = TestSetting.FIRST_SETTING.key
+ another_key = AnotherTestSetting.ANOTHER_SETTING.key
+
+ # Keys should be different
+ self.assertNotEqual(test_key, another_key)
+
+ # Should contain respective class names
+ self.assertIn('TestSetting', test_key)
+ self.assertIn('AnotherTestSetting', another_key)
+ return
+
+ def test_setting_enum_iteration(self):
+ """Test iterating over SettingEnum members."""
+ members = list(TestSetting)
+
+ self.assertEqual(len(members), 2)
+ self.assertIn(TestSetting.FIRST_SETTING, members)
+ self.assertIn(TestSetting.SECOND_SETTING, members)
+ return
+
+ def test_setting_enum_membership(self):
+ """Test membership testing for SettingEnum."""
+ self.assertIn(TestSetting.FIRST_SETTING, TestSetting)
+ self.assertIn(TestSetting.SECOND_SETTING, TestSetting)
+ self.assertNotIn(AnotherTestSetting.ANOTHER_SETTING, TestSetting)
+ return
+
+ def test_setting_definition_attributes(self):
+ """Test various SettingDefinition attributes through enum."""
+ # Test editable setting
+ editable_setting = TestSetting.FIRST_SETTING
+ self.assertTrue(editable_setting.definition.is_editable)
+ self.assertTrue(editable_setting.definition.is_required)
+
+ # Test non-editable setting
+ readonly_setting = TestSetting.SECOND_SETTING
+ self.assertFalse(readonly_setting.definition.is_editable)
+ self.assertFalse(readonly_setting.definition.is_required)
+ return
+
+ def test_setting_value_ranges(self):
+ """Test value range specifications."""
+ # Setting with no range
+ first_setting = TestSetting.FIRST_SETTING
+ self.assertEqual(first_setting.definition.value_range_str, '')
+
+ # Setting with range
+ second_setting = TestSetting.SECOND_SETTING
+ self.assertEqual(second_setting.definition.value_range_str, '[1, 100]')
+ return
+
+ def test_different_value_types(self):
+ """Test settings with different value types."""
+ text_setting = TestSetting.FIRST_SETTING
+ integer_setting = TestSetting.SECOND_SETTING
+ boolean_setting = AnotherTestSetting.ANOTHER_SETTING
+
+ self.assertEqual(text_setting.definition.value_type, AttributeValueType.TEXT)
+ self.assertEqual(integer_setting.definition.value_type, AttributeValueType.INTEGER)
+ self.assertEqual(boolean_setting.definition.value_type, AttributeValueType.BOOLEAN)
+ return
diff --git a/src/hi/apps/config/tests/test_settings_manager.py b/src/hi/apps/config/tests/test_settings_manager.py
new file mode 100644
index 00000000..169fce95
--- /dev/null
+++ b/src/hi/apps/config/tests/test_settings_manager.py
@@ -0,0 +1,168 @@
+import logging
+from unittest.mock import Mock
+from threading import Lock
+import threading
+
+from hi.apps.config.models import Subsystem, SubsystemAttribute
+from hi.apps.config.settings_manager import SettingsManager
+from hi.apps.attribute.enums import AttributeValueType
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestSettingsManager(BaseTestCase):
+
+ def test_singleton_behavior(self):
+ """Test SettingsManager singleton pattern - critical for system consistency."""
+ manager1 = SettingsManager()
+ manager2 = SettingsManager()
+
+ self.assertIs(manager1, manager2)
+ return
+
+ def test_set_setting_value_with_database_update(self):
+ """Test set_setting_value updates both memory and database - complex business logic."""
+ manager = SettingsManager()
+
+ # Create test data
+ subsystem = Subsystem.objects.create(
+ name='Test Subsystem',
+ subsystem_key='test_subsystem',
+ )
+ test_key = 'test.set.setting.key'
+ SubsystemAttribute.objects.create(
+ subsystem=subsystem,
+ setting_key=test_key,
+ value_type=AttributeValueType.TEXT,
+ value='initial_value',
+ )
+
+ manager.reload()
+
+ # Create a mock setting enum for testing
+ mock_setting = Mock()
+ mock_setting.key = test_key
+
+ # Update setting value
+ manager.set_setting_value(mock_setting, 'new_value')
+
+ # Verify value was updated in memory
+ value = manager._attribute_value_map.get(test_key)
+ self.assertEqual(value, 'new_value')
+
+ # Verify database was updated
+ attribute = SubsystemAttribute.objects.get(setting_key=test_key)
+ self.assertEqual(attribute.value, 'new_value')
+ return
+
+ def test_set_setting_value_nonexistent_key_error(self):
+ """Test set_setting_value error handling for non-existent settings - critical error handling."""
+ manager = SettingsManager()
+ manager.ensure_initialized()
+
+ # Create mock setting with non-existent key
+ mock_setting = Mock()
+ mock_setting.key = 'non.existent.setting.key'
+
+ with self.assertRaises(KeyError):
+ manager.set_setting_value(mock_setting, 'any_value')
+ return
+
+ def test_change_listener_system_notification(self):
+ """Test change listener system - core functionality for system integration."""
+ manager = SettingsManager()
+
+ # Create mock callbacks
+ callback1 = Mock()
+ callback2 = Mock()
+
+ manager.register_change_listener(callback1)
+ manager.register_change_listener(callback2)
+
+ # Create minimal test data for reload
+ Subsystem.objects.create(
+ name='Test Subsystem',
+ subsystem_key='test_subsystem',
+ )
+
+ manager.ensure_initialized()
+
+ # Reset mocks to focus on reload call
+ callback1.reset_mock()
+ callback2.reset_mock()
+
+ # Trigger reload which should notify listeners
+ manager.reload()
+
+ callback1.assert_called_once()
+ callback2.assert_called_once()
+ return
+
+ def test_change_listener_exception_handling(self):
+ """Test change listener error handling - system should be resilient to callback failures."""
+ manager = SettingsManager()
+
+ # Create callback that raises exception
+ def failing_callback():
+ raise ValueError("Test exception")
+
+ # Create normal callback
+ normal_callback = Mock()
+
+ manager.register_change_listener(failing_callback)
+ manager.register_change_listener(normal_callback)
+
+ # Create minimal test data
+ Subsystem.objects.create(
+ name='Test Subsystem',
+ subsystem_key='test_subsystem',
+ )
+
+ # Clear any previous calls to focus on this test
+ normal_callback.reset_mock()
+
+ # Reload should not fail despite exception in callback
+ manager.reload()
+
+ # Normal callback should still be called
+ normal_callback.assert_called_once()
+ return
+
+ def test_reload_picks_up_database_changes(self):
+ """Test reload method detects database changes - critical synchronization logic."""
+ manager = SettingsManager()
+ manager.ensure_initialized()
+
+ # Test that reload picks up changes by modifying an existing system setting
+ existing_attrs = list(SubsystemAttribute.objects.all()[:1])
+ if existing_attrs:
+ attr = existing_attrs[0]
+ original_value = attr.value
+
+ # Change the value
+ attr.value = f'test_modified_{original_value}'
+ attr.save()
+
+ # Reload should pick up the change
+ manager.reload()
+ updated_value = manager._attribute_value_map.get(attr.setting_key)
+ self.assertEqual(updated_value, f'test_modified_{original_value}')
+
+ # Restore original value
+ attr.value = original_value
+ attr.save()
+ manager.reload()
+ else:
+ self.skipTest("No existing attributes to test reload with")
+ return
+
+ def test_thread_safety_locks_exist(self):
+ """Test thread safety locks are properly initialized - critical for concurrent access."""
+ manager = SettingsManager()
+
+ # Verify locks exist and are proper lock types
+ lock_types = (type(Lock()), type(threading.Lock()), type(threading.RLock()))
+ self.assertIsInstance(manager._subsystems_lock, lock_types)
+ self.assertIsInstance(manager._attributes_lock, lock_types)
+ return
diff --git a/src/hi/apps/console/tests/__init__.py b/src/hi/apps/console/tests/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/apps/console/tests/test_audio_file.py b/src/hi/apps/console/tests/test_audio_file.py
new file mode 100644
index 00000000..7f642878
--- /dev/null
+++ b/src/hi/apps/console/tests/test_audio_file.py
@@ -0,0 +1,81 @@
+import logging
+
+from hi.apps.console.audio_file import AudioFile
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestAudioFile(BaseTestCase):
+
+ def test_audio_file_url_generation(self):
+ """Test URL generation logic - critical for audio file serving."""
+ # Test URL generation for different audio files
+ info_url = AudioFile.INFO.url
+ warning_url = AudioFile.WARNING.url
+ critical_url = AudioFile.CRITICAL.url
+
+ # URLs should contain the audio path and filename
+ self.assertIn('audio/', info_url)
+ self.assertIn('info.wav', info_url)
+
+ self.assertIn('audio/', warning_url)
+ self.assertIn('warning.wav', warning_url)
+
+ self.assertIn('audio/', critical_url)
+ self.assertIn('critical.wav', critical_url)
+
+ # URLs should be different
+ self.assertNotEqual(info_url, warning_url)
+ self.assertNotEqual(warning_url, critical_url)
+ return
+
+ def test_audio_file_base_filename_property(self):
+ """Test base_filename property - critical for file mapping."""
+ # Test that base filenames match expected values
+ self.assertEqual(AudioFile.INFO.base_filename, 'info.wav')
+ self.assertEqual(AudioFile.WARNING.base_filename, 'warning.wav')
+ self.assertEqual(AudioFile.CRITICAL.base_filename, 'critical.wav')
+ self.assertEqual(AudioFile.CHIME.base_filename, 'chime.wav')
+ self.assertEqual(AudioFile.BUZZER.base_filename, 'buzzer.wav')
+ return
+
+ def test_audio_file_labels(self):
+ """Test AudioFile labels - important for UI display."""
+ self.assertEqual(AudioFile.INFO.label, 'Info')
+ self.assertEqual(AudioFile.WARNING.label, 'Warning')
+ self.assertEqual(AudioFile.CRITICAL.label, 'Critical')
+ self.assertEqual(AudioFile.CHIME.label, 'Chime')
+ self.assertEqual(AudioFile.BUZZER.label, 'Buzzer')
+ self.assertEqual(AudioFile.TORNADO_SIREN.label, 'Tornado Siren')
+ return
+
+ def test_audio_file_alarm_related_files_exist(self):
+ """Test that alarm-related audio files exist - critical for alert functionality."""
+ # Should have audio files for all alarm levels
+ alarm_related_files = [AudioFile.INFO, AudioFile.WARNING, AudioFile.CRITICAL]
+
+ for audio_file in alarm_related_files:
+ # Should have proper label and filename
+ self.assertIsNotNone(audio_file.label)
+ self.assertIsNotNone(audio_file.base_filename)
+ self.assertTrue(audio_file.base_filename.endswith('.wav'))
+
+ # URL should be generated
+ url = audio_file.url
+ self.assertIsNotNone(url)
+ self.assertIn('audio/', url)
+ return
+
+ def test_audio_file_uniqueness(self):
+ """Test AudioFile enum value uniqueness - critical for avoiding conflicts."""
+ # All base filenames should be unique
+ filenames = [audio_file.base_filename for audio_file in AudioFile]
+ unique_filenames = set(filenames)
+ self.assertEqual(len(filenames), len(unique_filenames))
+
+ # All labels should be unique
+ labels = [audio_file.label for audio_file in AudioFile]
+ unique_labels = set(labels)
+ self.assertEqual(len(labels), len(unique_labels))
+ return
diff --git a/src/hi/apps/console/tests/test_audio_signal.py b/src/hi/apps/console/tests/test_audio_signal.py
new file mode 100644
index 00000000..dc305c78
--- /dev/null
+++ b/src/hi/apps/console/tests/test_audio_signal.py
@@ -0,0 +1,52 @@
+import logging
+
+from hi.apps.alert.enums import AlarmLevel
+from hi.apps.console.audio_signal import AudioSignal
+from hi.apps.console.settings import ConsoleSetting
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestAudioSignal(BaseTestCase):
+
+ def test_audio_signal_alarm_level_mapping(self):
+ """Test from_alarm_level mapping logic - critical for alert audio functionality."""
+ # Test valid mappings
+ self.assertEqual(AudioSignal.from_alarm_level(AlarmLevel.INFO), AudioSignal.INFO)
+ self.assertEqual(AudioSignal.from_alarm_level(AlarmLevel.WARNING), AudioSignal.WARNING)
+ self.assertEqual(AudioSignal.from_alarm_level(AlarmLevel.CRITICAL), AudioSignal.CRITICAL)
+
+ # Test unmapped alarm level
+ self.assertIsNone(AudioSignal.from_alarm_level(AlarmLevel.NONE))
+ return
+
+ def test_audio_signal_console_setting_mapping(self):
+ """Test console setting association - critical for audio configuration."""
+ # Each AudioSignal should have proper console setting
+ self.assertEqual(AudioSignal.INFO.console_setting, ConsoleSetting.CONSOLE_INFO_AUDIO_FILE)
+ self.assertEqual(AudioSignal.WARNING.console_setting, ConsoleSetting.CONSOLE_WARNING_AUDIO_FILE)
+ self.assertEqual(AudioSignal.CRITICAL.console_setting, ConsoleSetting.CONSOLE_CRITICAL_AUDIO_FILE)
+ return
+
+ def test_audio_signal_labels(self):
+ """Test AudioSignal labels - important for UI display."""
+ self.assertEqual(AudioSignal.INFO.label, 'Info')
+ self.assertEqual(AudioSignal.WARNING.label, 'Warning')
+ self.assertEqual(AudioSignal.CRITICAL.label, 'Critical')
+ return
+
+ def test_audio_signal_completeness_with_alarm_levels(self):
+ """Test AudioSignal covers all relevant AlarmLevels - critical for complete alert coverage."""
+ # Should have mappings for all non-NONE alarm levels
+ mapped_levels = []
+ for alarm_level in AlarmLevel:
+ if alarm_level == AlarmLevel.NONE:
+ continue
+ audio_signal = AudioSignal.from_alarm_level(alarm_level)
+ if audio_signal is not None:
+ mapped_levels.append(alarm_level)
+
+ expected_mapped_levels = [AlarmLevel.INFO, AlarmLevel.WARNING, AlarmLevel.CRITICAL]
+ self.assertEqual(set(mapped_levels), set(expected_mapped_levels))
+ return
diff --git a/src/hi/apps/console/tests/test_console_manager.py b/src/hi/apps/console/tests/test_console_manager.py
new file mode 100644
index 00000000..2c1b2acc
--- /dev/null
+++ b/src/hi/apps/console/tests/test_console_manager.py
@@ -0,0 +1,83 @@
+import logging
+
+from hi.apps.console.console_manager import ConsoleManager
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestConsoleManager(BaseTestCase):
+
+ def test_console_manager_singleton_behavior(self):
+ """Test ConsoleManager singleton pattern - critical for system consistency."""
+ manager1 = ConsoleManager()
+ manager2 = ConsoleManager()
+
+ self.assertIs(manager1, manager2)
+ return
+
+ def test_console_manager_initialization_state(self):
+ """Test ConsoleManager initialization state tracking - critical setup logic."""
+ manager = ConsoleManager()
+
+ # May already be initialized due to singleton pattern
+ # Test ensure_initialized sets proper state
+ manager.ensure_initialized()
+ self.assertTrue(manager._was_initialized)
+
+ # Subsequent calls should not change state
+ manager.ensure_initialized()
+ self.assertTrue(manager._was_initialized)
+ return
+
+ def test_console_manager_mixin_inheritance(self):
+ """Test ConsoleManager mixin inheritance - critical for system integration."""
+ manager = ConsoleManager()
+
+ # Should inherit from SettingsMixin
+ self.assertTrue(hasattr(manager, 'settings_manager'))
+
+ # Should inherit from SensorResponseMixin
+ self.assertTrue(hasattr(manager, 'sensor_response_manager'))
+
+ # Should be a Singleton
+ from hi.apps.common.singleton import Singleton
+ self.assertIsInstance(manager, Singleton)
+ return
+
+ def test_console_manager_method_existence(self):
+ """Test ConsoleManager has expected methods - critical API consistency."""
+ manager = ConsoleManager()
+
+ # Should have public interface methods
+ self.assertTrue(hasattr(manager, 'get_console_audio_map'))
+ self.assertTrue(hasattr(manager, 'get_video_stream_entity_list'))
+ self.assertTrue(callable(manager.get_console_audio_map))
+ self.assertTrue(callable(manager.get_video_stream_entity_list))
+ return
+
+ def test_console_manager_reload_methods_exist(self):
+ """Test reload method existence - critical for change handling."""
+ manager = ConsoleManager()
+
+ # Should have reload methods for change listeners
+ self.assertTrue(hasattr(manager, '_reload_console_audio_map'))
+ self.assertTrue(hasattr(manager, '_reload_video_stream_entity_list'))
+
+ # Methods should be callable
+ self.assertTrue(callable(manager._reload_console_audio_map))
+ self.assertTrue(callable(manager._reload_video_stream_entity_list))
+ return
+
+ def test_console_manager_build_methods_exist(self):
+ """Test build method existence - critical for data construction."""
+ manager = ConsoleManager()
+
+ # Should have build methods
+ self.assertTrue(hasattr(manager, '_build_console_audio_map'))
+ self.assertTrue(hasattr(manager, '_build_video_stream_entity_list'))
+
+ # Methods should be callable
+ self.assertTrue(callable(manager._build_console_audio_map))
+ self.assertTrue(callable(manager._build_video_stream_entity_list))
+ return
diff --git a/src/hi/apps/console/tests/test_enums.py b/src/hi/apps/console/tests/test_enums.py
new file mode 100644
index 00000000..fac4d9ab
--- /dev/null
+++ b/src/hi/apps/console/tests/test_enums.py
@@ -0,0 +1,39 @@
+import logging
+
+from hi.apps.console.enums import Theme, DisplayUnits
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestTheme(BaseTestCase):
+
+ def test_theme_enum_values(self):
+ """Test Theme enum values - important for UI consistency."""
+ self.assertEqual(Theme.DEFAULT.label, 'Default')
+
+ # Should have proper enum behavior
+ self.assertIsInstance(Theme.DEFAULT, Theme)
+ return
+
+
+class TestDisplayUnits(BaseTestCase):
+
+ def test_display_units_enum_values(self):
+ """Test DisplayUnits enum values - critical for measurement display."""
+ self.assertEqual(DisplayUnits.IMPERIAL.label, 'Imperial')
+ self.assertEqual(DisplayUnits.METRIC.label, 'Metric')
+
+ # Should have proper enum behavior
+ self.assertIsInstance(DisplayUnits.IMPERIAL, DisplayUnits)
+ self.assertIsInstance(DisplayUnits.METRIC, DisplayUnits)
+ return
+
+ def test_display_units_completeness(self):
+ """Test DisplayUnits covers expected measurement systems - critical for internationalization."""
+ # Should have both major measurement systems
+ units_list = list(DisplayUnits)
+ self.assertEqual(len(units_list), 2)
+ self.assertIn(DisplayUnits.IMPERIAL, units_list)
+ self.assertIn(DisplayUnits.METRIC, units_list)
+ return
diff --git a/src/hi/apps/console/tests/test_transient_models.py b/src/hi/apps/console/tests/test_transient_models.py
new file mode 100644
index 00000000..990e1475
--- /dev/null
+++ b/src/hi/apps/console/tests/test_transient_models.py
@@ -0,0 +1,128 @@
+import logging
+from unittest.mock import Mock
+
+from hi.apps.console.transient_models import VideoStreamEntity
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestVideoStreamEntity(BaseTestCase):
+
+ def test_video_stream_entity_name_camera_suffix_removal(self):
+ """Test name property camera suffix removal logic - complex string processing."""
+ # Create mock entity
+ mock_entity = Mock()
+ mock_entity_state = Mock()
+ mock_sensor = Mock()
+
+ # Test name ending with 'camera' gets suffix removed
+ mock_entity.name = 'Kitchen Camera'
+
+ video_stream_entity = VideoStreamEntity(
+ entity=mock_entity,
+ entity_state=mock_entity_state,
+ sensor=mock_sensor
+ )
+
+ self.assertEqual(video_stream_entity.name, 'Kitchen')
+ return
+
+ def test_video_stream_entity_name_camera_suffix_case_insensitive(self):
+ """Test name property handles case-insensitive camera suffix - edge case handling."""
+ mock_entity = Mock()
+ mock_entity_state = Mock()
+ mock_sensor = Mock()
+
+ # Test different cases of 'camera'
+ test_cases = [
+ ('Front Door camera', 'Front Door'),
+ ('Garage CAMERA', 'Garage'),
+ ('Backyard Camera', 'Backyard'),
+ ]
+
+ for original_name, expected_name in test_cases:
+ with self.subTest(original_name=original_name):
+ mock_entity.name = original_name
+
+ video_stream_entity = VideoStreamEntity(
+ entity=mock_entity,
+ entity_state=mock_entity_state,
+ sensor=mock_sensor
+ )
+
+ self.assertEqual(video_stream_entity.name, expected_name)
+ return
+
+ def test_video_stream_entity_name_no_camera_suffix(self):
+ """Test name property when entity name doesn't end with camera - preserves original name."""
+ mock_entity = Mock()
+ mock_entity_state = Mock()
+ mock_sensor = Mock()
+
+ # Test names that don't end with 'camera'
+ test_cases = [
+ 'Security Monitor',
+ 'Video Stream',
+ 'Front Door',
+ 'Camera Setup Tool', # 'camera' in middle shouldn't be removed
+ 'cameras', # plural shouldn't be removed
+ ]
+
+ for name in test_cases:
+ with self.subTest(name=name):
+ mock_entity.name = name
+
+ video_stream_entity = VideoStreamEntity(
+ entity=mock_entity,
+ entity_state=mock_entity_state,
+ sensor=mock_sensor
+ )
+
+ self.assertEqual(video_stream_entity.name, name)
+ return
+
+ def test_video_stream_entity_name_edge_cases(self):
+ """Test name property edge cases - boundary condition handling."""
+ mock_entity = Mock()
+ mock_entity_state = Mock()
+ mock_sensor = Mock()
+
+ # Test edge cases - the implementation only processes names ending with 'camera' (not spaces)
+ edge_cases = [
+ ('Camera', 'Camera'), # Just 'Camera' shouldn't be removed entirely
+ ('camera', 'camera'), # Just 'camera' lowercase shouldn't be removed entirely
+ ('Front Camera', 'Front'), # Multiple spaces should be stripped after removal
+ (' Patio Camera', 'Patio'), # Leading spaces preserved, trailing 'camera' removed and stripped
+ ]
+
+ for original_name, expected_name in edge_cases:
+ with self.subTest(original_name=original_name):
+ mock_entity.name = original_name
+
+ video_stream_entity = VideoStreamEntity(
+ entity=mock_entity,
+ entity_state=mock_entity_state,
+ sensor=mock_sensor
+ )
+
+ self.assertEqual(video_stream_entity.name, expected_name)
+ return
+
+ def test_video_stream_entity_dataclass_properties(self):
+ """Test VideoStreamEntity dataclass properties - proper object composition."""
+ mock_entity = Mock()
+ mock_entity_state = Mock()
+ mock_sensor = Mock()
+
+ video_stream_entity = VideoStreamEntity(
+ entity=mock_entity,
+ entity_state=mock_entity_state,
+ sensor=mock_sensor
+ )
+
+ # Should maintain references to all components
+ self.assertEqual(video_stream_entity.entity, mock_entity)
+ self.assertEqual(video_stream_entity.entity_state, mock_entity_state)
+ self.assertEqual(video_stream_entity.sensor, mock_sensor)
+ return
diff --git a/src/hi/apps/control/tests/__init__.py b/src/hi/apps/control/tests/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/apps/control/tests/test_controller_history_manager.py b/src/hi/apps/control/tests/test_controller_history_manager.py
new file mode 100644
index 00000000..46d0fe8b
--- /dev/null
+++ b/src/hi/apps/control/tests/test_controller_history_manager.py
@@ -0,0 +1,222 @@
+import logging
+
+from hi.apps.control.controller_history_manager import ControllerHistoryManager
+from hi.apps.control.models import Controller, ControllerHistory
+from hi.apps.entity.models import Entity, EntityState, EntityStateDelegation
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestControllerHistoryManager(BaseTestCase):
+
+ def test_controller_history_manager_singleton_behavior(self):
+ """Test ControllerHistoryManager singleton pattern - critical for system consistency."""
+ manager1 = ControllerHistoryManager()
+ manager2 = ControllerHistoryManager()
+
+ # Should be the same instance
+ self.assertIs(manager1, manager2)
+ return
+
+ def test_add_to_controller_history_creates_record(self):
+ """Test history record creation - critical for audit trail."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ controller = Controller.objects.create(
+ name='Test Controller',
+ entity_state=entity_state,
+ controller_type_str='DEFAULT',
+ integration_id='test_id',
+ integration_name='test_integration',
+ persist_history=True
+ )
+
+ manager = ControllerHistoryManager()
+ history_record = manager.add_to_controller_history(controller, 'on')
+
+ # Should create history record
+ self.assertIsNotNone(history_record)
+ self.assertEqual(history_record.controller, controller)
+ self.assertEqual(history_record.value, 'on')
+
+ # Should be saved to database
+ self.assertTrue(ControllerHistory.objects.filter(id=history_record.id).exists())
+ return
+
+ def test_add_to_controller_history_respects_persist_flag(self):
+ """Test history persistence flag - critical for storage control."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ controller = Controller.objects.create(
+ name='Test Controller',
+ entity_state=entity_state,
+ controller_type_str='DEFAULT',
+ integration_id='test_id',
+ integration_name='test_integration',
+ persist_history=False # Disabled
+ )
+
+ manager = ControllerHistoryManager()
+ history_record = manager.add_to_controller_history(controller, 'on')
+
+ # Should not create history record when disabled
+ self.assertIsNone(history_record)
+
+ # Should not be in database
+ self.assertEqual(ControllerHistory.objects.filter(controller=controller).count(), 0)
+ return
+
+ def test_get_latest_entity_controller_history_direct_states(self):
+ """Test entity controller history retrieval for direct states - complex data aggregation."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ controller = Controller.objects.create(
+ name='Test Controller',
+ entity_state=entity_state,
+ controller_type_str='DEFAULT',
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ # Create history records
+ history1 = ControllerHistory.objects.create(
+ controller=controller,
+ value='on'
+ )
+ history2 = ControllerHistory.objects.create(
+ controller=controller,
+ value='off'
+ )
+
+ manager = ControllerHistoryManager()
+ history_map = manager.get_latest_entity_controller_history(entity, max_items=5)
+
+ # Should return map with controller history
+ self.assertIn(controller, history_map)
+ controller_history = list(history_map[controller])
+
+ # Should be ordered newest first
+ self.assertEqual(len(controller_history), 2)
+ self.assertEqual(controller_history[0], history2) # Most recent
+ self.assertEqual(controller_history[1], history1)
+ return
+
+ def test_get_latest_entity_controller_history_delegated_states(self):
+ """Test entity controller history for delegated states - complex relationship handling."""
+ # Create primary entity
+ primary_entity = Entity.objects.create(
+ name='Primary Entity',
+ entity_type_str='CAMERA'
+ )
+
+ # Create delegated entity and state
+ delegated_entity = Entity.objects.create(
+ name='Delegated Entity',
+ entity_type_str='LIGHT'
+ )
+ delegated_state = EntityState.objects.create(
+ entity=delegated_entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ # Create delegation
+ EntityStateDelegation.objects.create(
+ delegate_entity=primary_entity,
+ entity_state=delegated_state
+ )
+
+ # Create controller for delegated state
+ controller = Controller.objects.create(
+ name='Delegated Controller',
+ entity_state=delegated_state,
+ controller_type_str='DEFAULT',
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ # Create history
+ history = ControllerHistory.objects.create(
+ controller=controller,
+ value='on'
+ )
+
+ manager = ControllerHistoryManager()
+ history_map = manager.get_latest_entity_controller_history(primary_entity, max_items=5)
+
+ # Should include controllers from delegated states
+ self.assertIn(controller, history_map)
+ controller_history = list(history_map[controller])
+ self.assertEqual(len(controller_history), 1)
+ self.assertEqual(controller_history[0], history)
+ return
+
+ def test_get_latest_entity_controller_history_max_items_limit(self):
+ """Test history retrieval max items limit - performance optimization."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ controller = Controller.objects.create(
+ name='Test Controller',
+ entity_state=entity_state,
+ controller_type_str='DEFAULT',
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ # Create more history records than the limit
+ for i in range(10):
+ ControllerHistory.objects.create(
+ controller=controller,
+ value=f'value_{i}'
+ )
+
+ manager = ControllerHistoryManager()
+ history_map = manager.get_latest_entity_controller_history(entity, max_items=3)
+
+ # Should limit to max_items
+ controller_history = list(history_map[controller])
+ self.assertEqual(len(controller_history), 3)
+
+ # Should be the most recent ones
+ self.assertEqual(controller_history[0].value, 'value_9') # Most recent
+ self.assertEqual(controller_history[1].value, 'value_8')
+ self.assertEqual(controller_history[2].value, 'value_7')
+ return
+
+ def test_entity_state_history_item_max_constant(self):
+ """Test ENTITY_STATE_HISTORY_ITEM_MAX constant - important for default behavior."""
+ manager = ControllerHistoryManager()
+
+ # Should have reasonable default limit
+ self.assertEqual(manager.ENTITY_STATE_HISTORY_ITEM_MAX, 5)
+ self.assertGreater(manager.ENTITY_STATE_HISTORY_ITEM_MAX, 0)
+ self.assertLess(manager.ENTITY_STATE_HISTORY_ITEM_MAX, 100)
+ return
diff --git a/src/hi/apps/control/tests/test_controller_manager.py b/src/hi/apps/control/tests/test_controller_manager.py
new file mode 100644
index 00000000..0f927eda
--- /dev/null
+++ b/src/hi/apps/control/tests/test_controller_manager.py
@@ -0,0 +1,135 @@
+import logging
+from unittest.mock import Mock, patch
+import asyncio
+
+from hi.apps.control.controller_manager import ControllerManager
+from hi.apps.control.models import Controller
+from hi.apps.entity.models import Entity, EntityState
+from hi.integrations.transient_models import IntegrationControlResult
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestControllerManager(BaseTestCase):
+
+ def test_controller_manager_singleton_behavior(self):
+ """Test ControllerManager singleton pattern - critical for system consistency."""
+ manager1 = ControllerManager()
+ manager2 = ControllerManager()
+
+ # Should be the same instance
+ self.assertIs(manager1, manager2)
+ return
+
+ def test_controller_manager_initialization_tracking(self):
+ """Test initialization tracking - important for lazy loading."""
+ manager = ControllerManager()
+
+ # Should start uninitialized
+ self.assertFalse(manager._was_initialized)
+
+ # Should initialize once
+ manager.ensure_initialized()
+ self.assertTrue(manager._was_initialized)
+
+ # Should not reinitialize
+ manager.ensure_initialized()
+ self.assertTrue(manager._was_initialized)
+ return
+
+ @patch('hi.apps.control.controller_manager.IntegrationManager')
+ def test_do_control_integration_delegation(self, mock_integration_manager):
+ """Test do_control integration delegation - critical for control operations."""
+ # Setup mocks
+ mock_integration_gateway = Mock()
+ mock_integration_controller = Mock()
+ mock_control_result = Mock(spec=IntegrationControlResult)
+
+ mock_integration_manager.return_value.get_integration_gateway.return_value = mock_integration_gateway
+ mock_integration_gateway.get_controller.return_value = mock_integration_controller
+ mock_integration_controller.do_control.return_value = mock_control_result
+
+ # Create test controller
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ controller = Controller.objects.create(
+ name='Test Controller',
+ entity_state=entity_state,
+ controller_type_str='DEFAULT',
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ # Test control operation
+ manager = ControllerManager()
+ result = manager.do_control(controller=controller, control_value='on')
+
+ # Should delegate to integration system
+ mock_integration_manager.return_value.get_integration_gateway.assert_called_once_with(
+ integration_id='test_id'
+ )
+ mock_integration_gateway.get_controller.assert_called_once()
+ mock_integration_controller.do_control.assert_called_once_with(
+ integration_key=controller.integration_key,
+ control_value='on'
+ )
+
+ self.assertEqual(result, mock_control_result)
+ return
+
+ @patch('hi.apps.control.controller_manager.IntegrationManager')
+ def test_do_control_async_delegation(self, mock_integration_manager):
+ """Test async control delegation - critical for async operations."""
+ # Setup mocks
+ mock_integration_gateway = Mock()
+ mock_integration_controller = Mock()
+ mock_control_result = Mock(spec=IntegrationControlResult)
+
+ mock_integration_manager.return_value.get_integration_gateway.return_value = mock_integration_gateway
+ mock_integration_gateway.get_controller.return_value = mock_integration_controller
+ mock_integration_controller.do_control.return_value = mock_control_result
+
+ # Create test controller
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ controller = Controller.objects.create(
+ name='Test Controller',
+ entity_state=entity_state,
+ controller_type_str='DEFAULT',
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ # Test async control operation
+ manager = ControllerManager()
+
+ async def run_async_test():
+ result = await manager.do_control_async(controller=controller, control_value='off')
+ return result
+
+ # Run the async test
+ result = asyncio.run(run_async_test())
+
+ # Should delegate to sync method through sync_to_async
+ mock_integration_controller.do_control.assert_called_once_with(
+ integration_key=controller.integration_key,
+ control_value='off'
+ )
+
+ self.assertEqual(result, mock_control_result)
+ return
diff --git a/src/hi/apps/control/tests/test_enums.py b/src/hi/apps/control/tests/test_enums.py
new file mode 100644
index 00000000..6c3093a4
--- /dev/null
+++ b/src/hi/apps/control/tests/test_enums.py
@@ -0,0 +1,27 @@
+import logging
+
+from hi.apps.control.enums import ControllerType
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestControllerType(BaseTestCase):
+
+ def test_controller_type_default_value(self):
+ """Test ControllerType DEFAULT enum - critical for controller behavior."""
+ # Should have DEFAULT type
+ self.assertEqual(ControllerType.DEFAULT.label, 'Default')
+ self.assertEqual(str(ControllerType.DEFAULT), 'default')
+ return
+
+ def test_controller_type_from_name_safe(self):
+ """Test from_name_safe method - critical for string conversion."""
+ # Should convert string to enum safely
+ controller_type = ControllerType.from_name_safe('default')
+ self.assertEqual(controller_type, ControllerType.DEFAULT)
+
+ # Should handle invalid strings by returning default
+ invalid_type = ControllerType.from_name_safe('invalid')
+ self.assertEqual(invalid_type, ControllerType.DEFAULT) # Returns default, not None
+ return
diff --git a/src/hi/apps/control/tests/test_models.py b/src/hi/apps/control/tests/test_models.py
new file mode 100644
index 00000000..1363c837
--- /dev/null
+++ b/src/hi/apps/control/tests/test_models.py
@@ -0,0 +1,256 @@
+import logging
+from django.db import IntegrityError
+
+from hi.apps.control.models import Controller, ControllerHistory
+from hi.apps.control.enums import ControllerType
+from hi.apps.entity.models import Entity, EntityState
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestController(BaseTestCase):
+
+ def test_controller_integration_key_uniqueness(self):
+ """Test integration key uniqueness constraint - critical for data integrity."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ # Create first controller
+ Controller.objects.create(
+ name='Test Controller 1',
+ entity_state=entity_state,
+ controller_type_str='DEFAULT',
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ # Duplicate integration key should fail
+ with self.assertRaises(IntegrityError):
+ Controller.objects.create(
+ name='Test Controller 2',
+ entity_state=entity_state,
+ controller_type_str='DEFAULT',
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+ return
+
+ def test_controller_type_property_conversion(self):
+ """Test controller_type property enum conversion - custom business logic."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ controller = Controller.objects.create(
+ name='Test Controller',
+ entity_state=entity_state,
+ controller_type_str='DEFAULT',
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ # Test getter converts string to enum
+ self.assertEqual(controller.controller_type, ControllerType.DEFAULT)
+
+ # Test setter converts enum to string
+ controller.controller_type = ControllerType.DEFAULT
+ self.assertEqual(controller.controller_type_str, 'default')
+ return
+
+ def test_controller_choices_delegation(self):
+ """Test choices property delegation to entity state - critical for UI."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ controller = Controller.objects.create(
+ name='Test Controller',
+ entity_state=entity_state,
+ controller_type_str='DEFAULT',
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ # Should delegate to entity_state.choices()
+ choices = controller.choices
+ self.assertIsNotNone(choices)
+ # EntityState should provide choices based on entity_state_type
+ return
+
+ def test_controller_cascade_deletion_from_entity_state(self):
+ """Test cascade deletion from entity state - critical for data integrity."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ controller = Controller.objects.create(
+ name='Test Controller',
+ entity_state=entity_state,
+ controller_type_str='DEFAULT',
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ controller_id = controller.id
+
+ # Delete entity state should cascade to controller
+ entity_state.delete()
+
+ self.assertFalse(Controller.objects.filter(id=controller_id).exists())
+ return
+
+ def test_controller_string_representation(self):
+ """Test __str__ method format - important for debugging and admin."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ controller = Controller.objects.create(
+ name='Test Controller',
+ entity_state=entity_state,
+ controller_type_str='DEFAULT',
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ str_repr = str(controller)
+ self.assertIn('Test Controller', str_repr)
+ self.assertIn('on_off', str_repr) # entity_state_type
+ self.assertIn(str(controller.id), str_repr)
+ self.assertIn('test_id', str_repr)
+ return
+
+
+class TestControllerHistory(BaseTestCase):
+
+ def test_controller_history_ordering_by_created_datetime(self):
+ """Test ControllerHistory ordering - critical for history display."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ controller = Controller.objects.create(
+ name='Test Controller',
+ entity_state=entity_state,
+ controller_type_str='DEFAULT',
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ # Create history entries (they'll have different timestamps)
+ history1 = ControllerHistory.objects.create(
+ controller=controller,
+ value='on'
+ )
+ history2 = ControllerHistory.objects.create(
+ controller=controller,
+ value='off'
+ )
+ history3 = ControllerHistory.objects.create(
+ controller=controller,
+ value='on'
+ )
+
+ # Should be ordered by newest first
+ history_list = list(ControllerHistory.objects.filter(controller=controller))
+ self.assertEqual(history_list[0], history3) # Most recent
+ self.assertEqual(history_list[1], history2)
+ self.assertEqual(history_list[2], history1) # Oldest
+ return
+
+ def test_controller_history_cascade_deletion_from_controller(self):
+ """Test cascade deletion from controller - critical for data integrity."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ controller = Controller.objects.create(
+ name='Test Controller',
+ entity_state=entity_state,
+ controller_type_str='DEFAULT',
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ history = ControllerHistory.objects.create(
+ controller=controller,
+ value='on'
+ )
+
+ history_id = history.id
+
+ # Delete controller should cascade to history
+ controller.delete()
+
+ self.assertFalse(ControllerHistory.objects.filter(id=history_id).exists())
+ return
+
+ def test_controller_history_created_datetime_indexing(self):
+ """Test created_datetime field indexing - critical for query performance."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ controller = Controller.objects.create(
+ name='Test Controller',
+ entity_state=entity_state,
+ controller_type_str='DEFAULT',
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ history = ControllerHistory.objects.create(
+ controller=controller,
+ value='on'
+ )
+
+ # Test that created_datetime queries work efficiently
+ # (The actual index performance isn't testable in unit tests,
+ # but we can verify the field is accessible and queryable)
+ recent_history = ControllerHistory.objects.filter(
+ created_datetime__gte=history.created_datetime
+ )
+ self.assertIn(history, recent_history)
+ return
diff --git a/src/hi/apps/control/tests/test_transient_models.py b/src/hi/apps/control/tests/test_transient_models.py
new file mode 100644
index 00000000..95dda0ae
--- /dev/null
+++ b/src/hi/apps/control/tests/test_transient_models.py
@@ -0,0 +1,116 @@
+import logging
+from unittest.mock import Mock
+
+from hi.apps.control.transient_models import ControllerData
+from hi.apps.control.models import Controller
+from hi.apps.entity.models import Entity, EntityState
+from hi.apps.sense.transient_models import SensorResponse
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestControllerData(BaseTestCase):
+
+ def test_controller_data_initialization(self):
+ """Test ControllerData initialization - critical for UI data structure."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ controller = Controller.objects.create(
+ name='Test Controller',
+ entity_state=entity_state,
+ controller_type_str='DEFAULT',
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ sensor_response = Mock(spec=SensorResponse)
+ error_list = ['Error 1', 'Error 2']
+
+ controller_data = ControllerData(
+ controller=controller,
+ latest_sensor_response=sensor_response,
+ error_list=error_list
+ )
+
+ # Should properly initialize all fields
+ self.assertEqual(controller_data.controller, controller)
+ self.assertEqual(controller_data.latest_sensor_response, sensor_response)
+ self.assertEqual(controller_data.error_list, error_list)
+ return
+
+ def test_controller_data_optional_error_list(self):
+ """Test ControllerData with optional error list - important for error handling."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ controller = Controller.objects.create(
+ name='Test Controller',
+ entity_state=entity_state,
+ controller_type_str='DEFAULT',
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ sensor_response = Mock(spec=SensorResponse)
+
+ controller_data = ControllerData(
+ controller=controller,
+ latest_sensor_response=sensor_response
+ )
+
+ # Should handle optional error_list
+ self.assertEqual(controller_data.controller, controller)
+ self.assertEqual(controller_data.latest_sensor_response, sensor_response)
+ self.assertIsNone(controller_data.error_list)
+ return
+
+ def test_controller_data_css_class_delegation(self):
+ """Test css_class property delegation - critical for UI styling."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ # Mock entity_state.css_class using patch
+ with self.assertRaises(AttributeError):
+ # css_class is a property, not settable directly
+ entity_state.css_class = 'test-css-class'
+
+ controller = Controller.objects.create(
+ name='Test Controller',
+ entity_state=entity_state,
+ controller_type_str='DEFAULT',
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ sensor_response = Mock(spec=SensorResponse)
+
+ controller_data = ControllerData(
+ controller=controller,
+ latest_sensor_response=sensor_response
+ )
+
+ # Should delegate to entity_state.css_class
+ # (The actual css_class value depends on entity_state implementation)
+ css_class = controller_data.css_class
+ self.assertIsNotNone(css_class) # Should return some CSS class
+ return
diff --git a/src/hi/apps/entity/tests/__init__.py b/src/hi/apps/entity/tests/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/apps/entity/tests/test_entity_manager.py b/src/hi/apps/entity/tests/test_entity_manager.py
new file mode 100644
index 00000000..cdcea935
--- /dev/null
+++ b/src/hi/apps/entity/tests/test_entity_manager.py
@@ -0,0 +1,184 @@
+import logging
+from unittest.mock import Mock
+
+from hi.apps.entity.entity_manager import EntityManager
+from hi.apps.entity.models import Entity
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestEntityManager(BaseTestCase):
+
+ def test_singleton_behavior(self):
+ """Test EntityManager singleton pattern - critical for system consistency."""
+ manager1 = EntityManager()
+ manager2 = EntityManager()
+
+ self.assertIs(manager1, manager2)
+ return
+
+ def test_change_listener_registration_and_notification(self):
+ """Test change listener system - core functionality for system integration."""
+ manager = EntityManager()
+
+ # Create mock callbacks
+ callback1 = Mock()
+ callback2 = Mock()
+
+ manager.register_change_listener(callback1)
+ manager.register_change_listener(callback2)
+
+ # Clear any previous calls
+ callback1.reset_mock()
+ callback2.reset_mock()
+
+ # Trigger reload which should notify listeners
+ manager.reload()
+
+ callback1.assert_called_once()
+ callback2.assert_called_once()
+ return
+
+ def test_change_listener_exception_handling(self):
+ """Test change listener error handling - system should be resilient to callback failures."""
+ manager = EntityManager()
+
+ # Create callback that raises exception
+ def failing_callback():
+ raise ValueError("Test exception")
+
+ # Create normal callback
+ normal_callback = Mock()
+
+ manager.register_change_listener(failing_callback)
+ manager.register_change_listener(normal_callback)
+
+ # Clear previous calls
+ normal_callback.reset_mock()
+
+ # Reload should not fail despite exception in callback
+ manager.reload()
+
+ # Normal callback should still be called
+ normal_callback.assert_called_once()
+ return
+
+ def test_set_entity_path_create_new(self):
+ """Test set_entity_path creation logic - complex business logic with transactions."""
+ manager = EntityManager()
+
+ # Create test entity
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='LIGHT',
+ integration_id='test_entity_001',
+ integration_name='test_integration',
+ )
+
+ # Create minimal location (this may need adjustment based on actual Location model)
+ # For now, testing the core logic without full location setup
+ try:
+ from hi.apps.location.models import Location
+ location = Location.objects.create(name='Test Location')
+
+ # Test creating new path
+ svg_path_str = 'M 10 10 L 20 20'
+ entity_path = manager.set_entity_path(
+ entity_id=entity.id,
+ location=location,
+ svg_path_str=svg_path_str
+ )
+
+ self.assertEqual(entity_path.entity, entity)
+ self.assertEqual(entity_path.location, location)
+ self.assertEqual(entity_path.svg_path, svg_path_str)
+
+ except ImportError:
+ # Skip if Location model not available in test environment
+ self.skipTest("Location model not available for testing")
+ return
+
+ def test_set_entity_path_update_existing(self):
+ """Test set_entity_path update logic - should update existing rather than create duplicate."""
+ manager = EntityManager()
+
+ try:
+ from hi.apps.location.models import Location
+ from hi.apps.entity.models import EntityPath
+
+ # Create test data
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='LIGHT',
+ integration_id='test_entity_001',
+ integration_name='test_integration',
+ )
+
+ location = Location.objects.create(name='Test Location')
+
+ # Create initial path
+ initial_path = 'M 10 10 L 20 20'
+ entity_path = EntityPath.objects.create(
+ entity=entity,
+ location=location,
+ svg_path=initial_path
+ )
+
+ initial_id = entity_path.id
+
+ # Update path
+ updated_path = 'M 30 30 L 40 40'
+ updated_entity_path = manager.set_entity_path(
+ entity_id=entity.id,
+ location=location,
+ svg_path_str=updated_path
+ )
+
+ # Should update existing, not create new
+ self.assertEqual(updated_entity_path.id, initial_id)
+ self.assertEqual(updated_entity_path.svg_path, updated_path)
+
+ # Should only be one EntityPath for this entity/location
+ path_count = EntityPath.objects.filter(entity=entity, location=location).count()
+ self.assertEqual(path_count, 1)
+
+ except ImportError:
+ self.skipTest("Required models not available for testing")
+ return
+
+ def test_get_entity_details_data_integration(self):
+ """Test get_entity_details_data business logic - complex method integrating multiple systems."""
+ manager = EntityManager()
+
+ try:
+ # Create test data
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA',
+ integration_id='test_entity_001',
+ integration_name='test_integration',
+ )
+
+ # LocationView requires additional fields, skip detailed integration test
+ # Focus on testing the business logic we can test without complex setup
+ location_view = None
+
+ # Test with simple case (no location_view)
+ details_data = manager.get_entity_details_data(
+ entity=entity,
+ location_view=location_view,
+ is_editing=False
+ )
+
+ # Should return EntityDetailsData
+ self.assertIsNotNone(details_data)
+ self.assertIsNotNone(details_data.entity_edit_data)
+ self.assertEqual(details_data.entity_edit_data.entity, entity)
+
+ # Without location_view, position form should be None
+ self.assertIsNone(details_data.entity_position_form)
+
+ except ImportError:
+ self.skipTest("Required models not available for testing")
+ return
diff --git a/src/hi/apps/entity/tests/test_enums.py b/src/hi/apps/entity/tests/test_enums.py
new file mode 100644
index 00000000..752987b4
--- /dev/null
+++ b/src/hi/apps/entity/tests/test_enums.py
@@ -0,0 +1,98 @@
+import logging
+
+from hi.apps.entity.enums import (
+ EntityType,
+ EntityStateType,
+ EntityStateValue,
+ EntityGroupType,
+)
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestEntityStateType(BaseTestCase):
+
+ def test_template_name_generation(self):
+ """Test template name generation logic - could break with refactoring."""
+ # Test value template naming
+ on_off_template = EntityStateType.ON_OFF.value_template_name()
+ self.assertEqual(on_off_template, 'sense/panes/sensor_value_on_off.html')
+
+ # Test controller template naming
+ temperature_template = EntityStateType.TEMPERATURE.controller_template_name()
+ self.assertEqual(temperature_template, 'control/panes/controller_temperature.html')
+
+ # Test edge case with underscores
+ video_template = EntityStateType.VIDEO_STREAM.value_template_name()
+ self.assertEqual(video_template, 'sense/panes/sensor_value_video_stream.html')
+ return
+
+ def test_suppress_properties_logic(self):
+ """Test suppress display/history logic - business rules that could change."""
+ # VIDEO_STREAM has special suppression rules
+ self.assertTrue(EntityStateType.VIDEO_STREAM.suppress_display_name)
+ self.assertTrue(EntityStateType.VIDEO_STREAM.suppress_history)
+
+ # Other types should not suppress
+ self.assertFalse(EntityStateType.ON_OFF.suppress_display_name)
+ self.assertFalse(EntityStateType.TEMPERATURE.suppress_history)
+ return
+
+
+class TestEntityStateValue(BaseTestCase):
+
+ def test_entity_state_value_choices_mapping(self):
+ """Test complex mapping logic between state types and values - prone to bugs."""
+ choices = EntityStateValue.entity_state_value_choices()
+
+ # Test ON_OFF mapping (values are lowercase strings)
+ on_off_choices = choices[EntityStateType.ON_OFF]
+ choice_values = [choice[0] for choice in on_off_choices]
+ self.assertIn('on', choice_values)
+ self.assertIn('off', choice_values)
+ self.assertEqual(len(on_off_choices), 2)
+
+ # Test CONNECTIVITY mapping (values are lowercase strings)
+ connectivity_choices = choices[EntityStateType.CONNECTIVITY]
+ choice_values = [choice[0] for choice in connectivity_choices]
+ self.assertIn('connected', choice_values)
+ self.assertIn('disconnected', choice_values)
+
+ # Test MOVEMENT mapping (different values, lowercase)
+ movement_choices = choices[EntityStateType.MOVEMENT]
+ choice_values = [choice[0] for choice in movement_choices]
+ self.assertIn('active', choice_values)
+ self.assertIn('idle', choice_values)
+ return
+
+
+class TestEntityGroupType(BaseTestCase):
+
+ def test_from_entity_type_mapping(self):
+ """Test entity type to group mapping logic - complex business logic prone to errors."""
+ # Test specific mappings that are important for UI grouping
+ self.assertEqual(EntityGroupType.from_entity_type(EntityType.LIGHT), EntityGroupType.LIGHTS_SWITCHES)
+ self.assertEqual(EntityGroupType.from_entity_type(EntityType.CAMERA), EntityGroupType.SECURITY)
+ self.assertEqual(EntityGroupType.from_entity_type(EntityType.REFRIGERATOR), EntityGroupType.APPLIANCES)
+ self.assertEqual(EntityGroupType.from_entity_type(EntityType.THERMOSTAT), EntityGroupType.CLIMATE)
+
+ # Test fallback to default for unmapped types
+ self.assertEqual(EntityGroupType.from_entity_type(EntityType.OTHER), EntityGroupType.OTHER)
+ return
+
+ def test_entity_type_set_coverage(self):
+ """Test that critical entity types are properly categorized - could break with enum additions."""
+ # Test that important entity types are in expected groups
+ appliances = EntityGroupType.APPLIANCES
+ self.assertIn(EntityType.REFRIGERATOR, appliances.entity_type_set)
+ self.assertIn(EntityType.DISHWASHER, appliances.entity_type_set)
+
+ security = EntityGroupType.SECURITY
+ self.assertIn(EntityType.CAMERA, security.entity_type_set)
+ self.assertIn(EntityType.MOTION_SENSOR, security.entity_type_set)
+
+ climate = EntityGroupType.CLIMATE
+ self.assertIn(EntityType.THERMOSTAT, climate.entity_type_set)
+ self.assertIn(EntityType.HVAC_FURNACE, climate.entity_type_set)
+ return
diff --git a/src/hi/apps/entity/tests/test_models.py b/src/hi/apps/entity/tests/test_models.py
new file mode 100644
index 00000000..f44d8649
--- /dev/null
+++ b/src/hi/apps/entity/tests/test_models.py
@@ -0,0 +1,220 @@
+import json
+import logging
+from django.db import IntegrityError
+
+from hi.apps.entity.models import Entity, EntityAttribute, EntityState
+from hi.apps.entity.enums import EntityType, EntityStateType
+from hi.apps.attribute.enums import AttributeValueType
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestEntity(BaseTestCase):
+
+ def test_integration_key_uniqueness_constraint(self):
+ """Test integration key uniqueness - critical for data integrity."""
+ # Create first entity
+ Entity.objects.create(
+ name='First Entity',
+ entity_type_str='LIGHT',
+ integration_id='unique_id',
+ integration_name='unique_integration',
+ )
+
+ # Attempt duplicate integration key should fail
+ with self.assertRaises(IntegrityError):
+ Entity.objects.create(
+ name='Second Entity',
+ entity_type_str='CAMERA',
+ integration_id='unique_id', # Same ID
+ integration_name='unique_integration', # Same integration
+ )
+ return
+
+ def test_entity_type_property_conversion(self):
+ """Test entity_type property enum conversion logic - custom business logic."""
+ entity = Entity.objects.create(
+ name='Test Device',
+ entity_type_str='LIGHT',
+ integration_id='test_device_001',
+ integration_name='test_integration',
+ )
+
+ # Test getter converts string to enum
+ self.assertEqual(entity.entity_type, EntityType.LIGHT)
+
+ # Test setter converts enum to string (lowercase)
+ entity.entity_type = EntityType.CAMERA
+ self.assertEqual(entity.entity_type_str, 'camera')
+ self.assertEqual(entity.entity_type, EntityType.CAMERA)
+ return
+
+ def test_entity_type_invalid_fallback(self):
+ """Test entity_type property with invalid type - error handling logic."""
+ entity = Entity.objects.create(
+ name='Test Device',
+ entity_type_str='INVALID_TYPE',
+ integration_id='test_device_001',
+ integration_name='test_integration',
+ )
+
+ # Should handle invalid type gracefully (from_name_safe behavior)
+ entity_type = entity.entity_type
+ self.assertIsNotNone(entity_type)
+ return
+
+ def test_get_attribute_map_logic(self):
+ """Test get_attribute_map business logic - custom method prone to bugs."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='OTHER',
+ integration_id='test_entity_001',
+ integration_name='test_integration',
+ )
+
+ # Create attributes
+ attr1 = EntityAttribute.objects.create(
+ entity=entity,
+ name='config_setting',
+ value_type=AttributeValueType.TEXT,
+ value='config_value',
+ )
+
+ attr2 = EntityAttribute.objects.create(
+ entity=entity,
+ name='documentation',
+ value_type=AttributeValueType.TEXT,
+ value='User manual link',
+ )
+
+ # Test mapping logic
+ attribute_map = entity.get_attribute_map()
+
+ self.assertEqual(len(attribute_map), 2)
+ self.assertEqual(attribute_map['config_setting'], attr1)
+ self.assertEqual(attribute_map['documentation'], attr2)
+
+ # Test with no attributes
+ empty_entity = Entity.objects.create(
+ name='Empty Entity',
+ entity_type_str='OTHER',
+ integration_id='empty_entity_001',
+ integration_name='test_integration',
+ )
+
+ empty_map = empty_entity.get_attribute_map()
+ self.assertEqual(len(empty_map), 0)
+ return
+
+ def test_cascade_deletion_behavior(self):
+ """Test cascade deletion - critical for data integrity."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='OTHER',
+ integration_id='test_entity_001',
+ integration_name='test_integration',
+ )
+
+ # Create related objects
+ attribute = EntityAttribute.objects.create(
+ entity=entity,
+ name='test_attribute',
+ value_type=AttributeValueType.TEXT,
+ value='test_value',
+ )
+
+ state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF',
+ name='Power State',
+ )
+
+ attribute_id = attribute.id
+ state_id = state.id
+
+ # Delete entity should cascade
+ entity.delete()
+
+ self.assertFalse(EntityAttribute.objects.filter(id=attribute_id).exists())
+ self.assertFalse(EntityState.objects.filter(id=state_id).exists())
+ return
+
+
+class TestEntityState(BaseTestCase):
+
+ def setUp(self):
+ super().setUp()
+ self.entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='LIGHT',
+ integration_id='test_entity_001',
+ integration_name='test_integration',
+ )
+ return
+
+ def test_entity_state_type_property_conversion(self):
+ """Test entity_state_type property enum conversion - custom business logic."""
+ state = EntityState.objects.create(
+ entity=self.entity,
+ entity_state_type_str='ON_OFF',
+ name='Power State',
+ )
+
+ # Test getter converts string to enum
+ self.assertEqual(state.entity_state_type, EntityStateType.ON_OFF)
+
+ # Test setter converts enum to string (lowercase)
+ state.entity_state_type = EntityStateType.TEMPERATURE
+ self.assertEqual(state.entity_state_type_str, 'temperature')
+ self.assertEqual(state.entity_state_type, EntityStateType.TEMPERATURE)
+ return
+
+ def test_value_range_dict_json_handling(self):
+ """Test value_range_dict JSON serialization/deserialization - complex logic prone to bugs."""
+ # Test with dictionary JSON
+ value_dict = {"ON": "On", "OFF": "Off"}
+ state = EntityState.objects.create(
+ entity=self.entity,
+ entity_state_type_str='ON_OFF',
+ name='Power State',
+ value_range_str=json.dumps(value_dict),
+ )
+
+ self.assertEqual(state.value_range_dict, value_dict)
+
+ # Test with list JSON (should convert to dict)
+ value_list = ["LOW", "MEDIUM", "HIGH"]
+ state.value_range_str = json.dumps(value_list)
+ expected_dict = {"LOW": "LOW", "MEDIUM": "MEDIUM", "HIGH": "HIGH"}
+ self.assertEqual(state.value_range_dict, expected_dict)
+
+ # Test with invalid JSON (should return empty dict)
+ state.value_range_str = 'invalid json'
+ self.assertEqual(state.value_range_dict, {})
+
+ # Test setter
+ new_dict = {"ACTIVE": "Active", "INACTIVE": "Inactive"}
+ state.value_range_dict = new_dict
+ self.assertEqual(state.value_range_str, json.dumps(new_dict))
+ self.assertEqual(state.value_range_dict, new_dict)
+ return
+
+ def test_choices_method_integration(self):
+ """Test choices method with value_range_str - complex business logic."""
+ # This would test the choices() method if it exists in the full model
+ # Based on the partial model reading, this appears to parse value_range_str
+ state = EntityState.objects.create(
+ entity=self.entity,
+ entity_state_type_str='ON_OFF',
+ name='Power State',
+ value_range_str='{"ON": "On", "OFF": "Off"}',
+ )
+
+ # Test that value_range_dict works correctly
+ choices_dict = state.value_range_dict
+ self.assertIn('ON', choices_dict)
+ self.assertIn('OFF', choices_dict)
+ self.assertEqual(choices_dict['ON'], 'On')
+ self.assertEqual(choices_dict['OFF'], 'Off')
+ return
diff --git a/src/hi/apps/event/tests/__init__.py b/src/hi/apps/event/tests/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/apps/event/tests/test_enums.py b/src/hi/apps/event/tests/test_enums.py
new file mode 100644
index 00000000..413b55bc
--- /dev/null
+++ b/src/hi/apps/event/tests/test_enums.py
@@ -0,0 +1,32 @@
+import logging
+
+from hi.apps.event.enums import EventType
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestEventType(BaseTestCase):
+
+ def test_event_type_enum_values(self):
+ """Test EventType enum values - critical for event classification."""
+ # Test that expected event types exist
+ expected_types = {
+ EventType.SECURITY,
+ EventType.MAINTENANCE,
+ EventType.INFORMATION,
+ EventType.AUTOMATION
+ }
+
+ actual_types = set(EventType)
+ self.assertEqual(actual_types, expected_types)
+ return
+
+ def test_event_type_string_conversion(self):
+ """Test EventType string conversion - critical for database storage."""
+ # Test that enum converts to expected string values
+ self.assertEqual(str(EventType.SECURITY), 'security')
+ self.assertEqual(str(EventType.MAINTENANCE), 'maintenance')
+ self.assertEqual(str(EventType.INFORMATION), 'information')
+ self.assertEqual(str(EventType.AUTOMATION), 'automation')
+ return
diff --git a/src/hi/apps/event/tests/test_models.py b/src/hi/apps/event/tests/test_models.py
new file mode 100644
index 00000000..0a550e55
--- /dev/null
+++ b/src/hi/apps/event/tests/test_models.py
@@ -0,0 +1,419 @@
+import logging
+
+from hi.apps.event.models import EventDefinition, EventClause, AlarmAction, ControlAction, EventHistory
+from hi.apps.event.enums import EventType
+from hi.apps.alert.enums import AlarmLevel
+from hi.apps.security.enums import SecurityLevel
+from hi.apps.entity.models import Entity, EntityState
+from hi.apps.control.models import Controller
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestEventDefinition(BaseTestCase):
+
+ def test_event_definition_integration_key_inheritance(self):
+ """Test EventDefinition integration key inheritance - critical for integration system."""
+ event_def = EventDefinition.objects.create(
+ name='Test Event',
+ event_type_str='SECURITY',
+ event_window_secs=60,
+ dedupe_window_secs=300,
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ # Should inherit integration key fields from IntegrationKeyModel
+ self.assertEqual(event_def.integration_id, 'test_id')
+ self.assertEqual(event_def.integration_name, 'test_integration')
+ return
+
+ def test_event_definition_event_type_property_conversion(self):
+ """Test event_type property enum conversion - custom business logic."""
+ event_def = EventDefinition.objects.create(
+ name='Test Event',
+ event_type_str='AUTOMATION',
+ event_window_secs=60,
+ dedupe_window_secs=300,
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ # Test getter converts string to enum
+ self.assertEqual(event_def.event_type, EventType.AUTOMATION)
+
+ # Test setter converts enum to string
+ event_def.event_type = EventType.MAINTENANCE
+ self.assertEqual(event_def.event_type_str, 'maintenance')
+ return
+
+ def test_event_definition_timing_constraints(self):
+ """Test event timing window constraints - critical for event logic."""
+ event_def = EventDefinition.objects.create(
+ name='Test Event',
+ event_type_str='SECURITY',
+ event_window_secs=120, # 2 minutes for all clauses to be satisfied
+ dedupe_window_secs=600, # 10 minutes before next event can be generated
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ # Should store timing constraints correctly
+ self.assertEqual(event_def.event_window_secs, 120)
+ self.assertEqual(event_def.dedupe_window_secs, 600)
+
+ # Should allow reasonable timing values
+ self.assertGreater(event_def.dedupe_window_secs, event_def.event_window_secs)
+ return
+
+ def test_event_definition_enabled_default(self):
+ """Test EventDefinition enabled default - important for system behavior."""
+ event_def = EventDefinition.objects.create(
+ name='Test Event',
+ event_type_str='SECURITY',
+ event_window_secs=60,
+ dedupe_window_secs=300,
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ # Should default to enabled
+ self.assertTrue(event_def.enabled)
+ return
+
+
+class TestEventClause(BaseTestCase):
+
+ def test_event_clause_cascade_deletion_from_event_definition(self):
+ """Test cascade deletion from event definition - critical for data integrity."""
+ event_def = EventDefinition.objects.create(
+ name='Test Event',
+ event_type_str='SECURITY',
+ event_window_secs=60,
+ dedupe_window_secs=300,
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ event_clause = EventClause.objects.create(
+ event_definition=event_def,
+ entity_state=entity_state,
+ value='on'
+ )
+
+ clause_id = event_clause.id
+
+ # Delete event definition should cascade to clauses
+ event_def.delete()
+
+ self.assertFalse(EventClause.objects.filter(id=clause_id).exists())
+ return
+
+ def test_event_clause_cascade_deletion_from_entity_state(self):
+ """Test cascade deletion from entity state - critical for data integrity."""
+ event_def = EventDefinition.objects.create(
+ name='Test Event',
+ event_type_str='SECURITY',
+ event_window_secs=60,
+ dedupe_window_secs=300,
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ event_clause = EventClause.objects.create(
+ event_definition=event_def,
+ entity_state=entity_state,
+ value='on'
+ )
+
+ clause_id = event_clause.id
+
+ # Delete entity state should cascade to clauses
+ entity_state.delete()
+
+ self.assertFalse(EventClause.objects.filter(id=clause_id).exists())
+ return
+
+
+class TestAlarmAction(BaseTestCase):
+
+ def test_alarm_action_enum_property_conversions(self):
+ """Test AlarmAction enum property conversions - custom business logic."""
+ event_def = EventDefinition.objects.create(
+ name='Test Event',
+ event_type_str='SECURITY',
+ event_window_secs=60,
+ dedupe_window_secs=300,
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ alarm_action = AlarmAction.objects.create(
+ event_definition=event_def,
+ security_level_str='HIGH',
+ alarm_level_str='CRITICAL',
+ alarm_lifetime_secs=3600
+ )
+
+ # Test getter converts string to enum
+ self.assertEqual(alarm_action.security_level, SecurityLevel.HIGH)
+ self.assertEqual(alarm_action.alarm_level, AlarmLevel.CRITICAL)
+
+ # Test setter converts enum to string
+ alarm_action.security_level = SecurityLevel.LOW
+ alarm_action.alarm_level = AlarmLevel.WARNING
+ self.assertEqual(alarm_action.security_level_str, 'low')
+ self.assertEqual(alarm_action.alarm_level_str, 'warning')
+ return
+
+ def test_alarm_action_lifetime_configuration(self):
+ """Test alarm lifetime configuration - critical for alarm management."""
+ event_def = EventDefinition.objects.create(
+ name='Test Event',
+ event_type_str='SECURITY',
+ event_window_secs=60,
+ dedupe_window_secs=300,
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ # Test zero lifetime (manual acknowledgment only)
+ manual_alarm = AlarmAction.objects.create(
+ event_definition=event_def,
+ security_level_str='HIGH',
+ alarm_level_str='CRITICAL',
+ alarm_lifetime_secs=0
+ )
+ self.assertEqual(manual_alarm.alarm_lifetime_secs, 0)
+
+ # Test timed lifetime
+ timed_alarm = AlarmAction.objects.create(
+ event_definition=event_def,
+ security_level_str='MEDIUM',
+ alarm_level_str='WARNING',
+ alarm_lifetime_secs=1800 # 30 minutes
+ )
+ self.assertEqual(timed_alarm.alarm_lifetime_secs, 1800)
+ return
+
+ def test_alarm_action_cascade_deletion_from_event_definition(self):
+ """Test cascade deletion from event definition - critical for data integrity."""
+ event_def = EventDefinition.objects.create(
+ name='Test Event',
+ event_type_str='SECURITY',
+ event_window_secs=60,
+ dedupe_window_secs=300,
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ alarm_action = AlarmAction.objects.create(
+ event_definition=event_def,
+ security_level_str='HIGH',
+ alarm_level_str='CRITICAL',
+ alarm_lifetime_secs=3600
+ )
+
+ action_id = alarm_action.id
+
+ # Delete event definition should cascade to alarm actions
+ event_def.delete()
+
+ self.assertFalse(AlarmAction.objects.filter(id=action_id).exists())
+ return
+
+
+class TestControlAction(BaseTestCase):
+
+ def test_control_action_cascade_deletion_from_event_definition(self):
+ """Test cascade deletion from event definition - critical for data integrity."""
+ event_def = EventDefinition.objects.create(
+ name='Test Event',
+ event_type_str='AUTOMATION',
+ event_window_secs=60,
+ dedupe_window_secs=300,
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ controller = Controller.objects.create(
+ name='Test Controller',
+ entity_state=entity_state,
+ controller_type_str='DEFAULT',
+ integration_id='ctrl_id',
+ integration_name='ctrl_integration'
+ )
+
+ control_action = ControlAction.objects.create(
+ event_definition=event_def,
+ controller=controller,
+ value='on'
+ )
+
+ action_id = control_action.id
+
+ # Delete event definition should cascade to control actions
+ event_def.delete()
+
+ self.assertFalse(ControlAction.objects.filter(id=action_id).exists())
+ return
+
+ def test_control_action_cascade_deletion_from_controller(self):
+ """Test cascade deletion from controller - critical for data integrity."""
+ event_def = EventDefinition.objects.create(
+ name='Test Event',
+ event_type_str='AUTOMATION',
+ event_window_secs=60,
+ dedupe_window_secs=300,
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ controller = Controller.objects.create(
+ name='Test Controller',
+ entity_state=entity_state,
+ controller_type_str='DEFAULT',
+ integration_id='ctrl_id',
+ integration_name='ctrl_integration'
+ )
+
+ control_action = ControlAction.objects.create(
+ event_definition=event_def,
+ controller=controller,
+ value='on'
+ )
+
+ action_id = control_action.id
+
+ # Delete controller should cascade to control actions
+ controller.delete()
+
+ self.assertFalse(ControlAction.objects.filter(id=action_id).exists())
+ return
+
+
+class TestEventHistory(BaseTestCase):
+
+ def test_event_history_ordering_by_event_datetime(self):
+ """Test EventHistory ordering - critical for history display."""
+ event_def = EventDefinition.objects.create(
+ name='Test Event',
+ event_type_str='SECURITY',
+ event_window_secs=60,
+ dedupe_window_secs=300,
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ from django.utils import timezone
+
+ # Create history entries with different timestamps
+ history1 = EventHistory.objects.create(
+ event_definition=event_def,
+ event_datetime=timezone.now() - timezone.timedelta(hours=2)
+ )
+ history2 = EventHistory.objects.create(
+ event_definition=event_def,
+ event_datetime=timezone.now() - timezone.timedelta(hours=1)
+ )
+ history3 = EventHistory.objects.create(
+ event_definition=event_def,
+ event_datetime=timezone.now()
+ )
+
+ # Should be ordered by newest first
+ history_list = list(EventHistory.objects.filter(event_definition=event_def))
+ self.assertEqual(history_list[0], history3) # Most recent
+ self.assertEqual(history_list[1], history2)
+ self.assertEqual(history_list[2], history1) # Oldest
+ return
+
+ def test_event_history_datetime_indexing(self):
+ """Test event_datetime field indexing - critical for query performance."""
+ event_def = EventDefinition.objects.create(
+ name='Test Event',
+ event_type_str='SECURITY',
+ event_window_secs=60,
+ dedupe_window_secs=300,
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ from django.utils import timezone
+
+ history = EventHistory.objects.create(
+ event_definition=event_def,
+ event_datetime=timezone.now()
+ )
+
+ # Test that datetime queries work efficiently
+ # (The actual index performance isn't testable in unit tests,
+ # but we can verify the field is accessible and queryable)
+ recent_history = EventHistory.objects.filter(
+ event_datetime__gte=history.event_datetime
+ )
+ self.assertIn(history, recent_history)
+ return
+
+ def test_event_history_cascade_deletion_from_event_definition(self):
+ """Test cascade deletion from event definition - critical for data integrity."""
+ event_def = EventDefinition.objects.create(
+ name='Test Event',
+ event_type_str='SECURITY',
+ event_window_secs=60,
+ dedupe_window_secs=300,
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ from django.utils import timezone
+
+ history = EventHistory.objects.create(
+ event_definition=event_def,
+ event_datetime=timezone.now()
+ )
+
+ history_id = history.id
+
+ # Delete event definition should cascade to history
+ event_def.delete()
+
+ self.assertFalse(EventHistory.objects.filter(id=history_id).exists())
+ return
diff --git a/src/hi/apps/location/tests/__init__.py b/src/hi/apps/location/tests/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/apps/location/tests/test_enums.py b/src/hi/apps/location/tests/test_enums.py
new file mode 100644
index 00000000..4d5ced03
--- /dev/null
+++ b/src/hi/apps/location/tests/test_enums.py
@@ -0,0 +1,139 @@
+import logging
+
+from hi.apps.location.enums import LocationViewType, SvgItemType, SvgStyleName
+from hi.apps.entity.enums import EntityStateType
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestLocationViewType(BaseTestCase):
+
+ def test_location_view_type_entity_state_priority_lists(self):
+ """Test entity state type priority lists - critical for sensor display ordering."""
+ # DEFAULT should have comprehensive list
+ default_priorities = LocationViewType.DEFAULT.entity_state_type_priority_list
+ self.assertGreater(len(default_priorities), 5)
+ self.assertIn(EntityStateType.MOVEMENT, default_priorities)
+ self.assertIn(EntityStateType.TEMPERATURE, default_priorities)
+
+ # SECURITY should focus on security-related states
+ security_priorities = LocationViewType.SECURITY.entity_state_type_priority_list
+ self.assertIn(EntityStateType.MOVEMENT, security_priorities)
+ self.assertIn(EntityStateType.PRESENCE, security_priorities)
+ self.assertIn(EntityStateType.OPEN_CLOSE, security_priorities)
+
+ # CLIMATE should focus on climate-related states
+ climate_priorities = LocationViewType.CLIMATE.entity_state_type_priority_list
+ self.assertIn(EntityStateType.TEMPERATURE, climate_priorities)
+ self.assertIn(EntityStateType.HUMIDITY, climate_priorities)
+ self.assertIn(EntityStateType.AIR_PRESSURE, climate_priorities)
+
+ # SUPPRESS should have empty list
+ suppress_priorities = LocationViewType.SUPPRESS.entity_state_type_priority_list
+ self.assertEqual(len(suppress_priorities), 0)
+ return
+
+ def test_location_view_type_specialization_logic(self):
+ """Test view type specialization - business logic for filtering sensor types."""
+ # Each view type should have unique focus
+ view_types = [
+ (LocationViewType.SECURITY, [EntityStateType.MOVEMENT, EntityStateType.PRESENCE]),
+ (LocationViewType.LIGHTS, [EntityStateType.LIGHT_LEVEL]),
+ (LocationViewType.SOUNDS, [EntityStateType.SOUND_LEVEL]),
+ (LocationViewType.ENERGY, [EntityStateType.ELECTRIC_USAGE, EntityStateType.WATER_FLOW]),
+ ]
+
+ for view_type, expected_states in view_types:
+ with self.subTest(view_type=view_type):
+ priorities = view_type.entity_state_type_priority_list
+ for expected_state in expected_states:
+ self.assertIn(expected_state, priorities)
+ return
+
+ def test_location_view_type_labels(self):
+ """Test LocationViewType labels - important for UI display."""
+ self.assertEqual(LocationViewType.DEFAULT.label, 'Default')
+ self.assertEqual(LocationViewType.SECURITY.label, 'Security')
+ self.assertEqual(LocationViewType.LIGHTS.label, 'Lights')
+ self.assertEqual(LocationViewType.CLIMATE.label, 'Climate')
+ self.assertEqual(LocationViewType.ENERGY.label, 'Energy')
+ self.assertEqual(LocationViewType.SUPPRESS.label, 'Suppress')
+ return
+
+
+class TestSvgItemType(BaseTestCase):
+
+ def test_svg_item_type_classification_properties(self):
+ """Test SvgItemType classification logic - critical for SVG rendering."""
+ # ICON should be icon, not path
+ self.assertTrue(SvgItemType.ICON.is_icon)
+ self.assertFalse(SvgItemType.ICON.is_path)
+ self.assertFalse(SvgItemType.ICON.is_path_closed)
+
+ # OPEN_PATH should be path, not icon, not closed
+ self.assertFalse(SvgItemType.OPEN_PATH.is_icon)
+ self.assertTrue(SvgItemType.OPEN_PATH.is_path)
+ self.assertFalse(SvgItemType.OPEN_PATH.is_path_closed)
+
+ # CLOSED_PATH should be path, not icon, and closed
+ self.assertFalse(SvgItemType.CLOSED_PATH.is_icon)
+ self.assertTrue(SvgItemType.CLOSED_PATH.is_path)
+ self.assertTrue(SvgItemType.CLOSED_PATH.is_path_closed)
+ return
+
+ def test_svg_item_type_path_detection_logic(self):
+ """Test is_path property logic - critical for SVG path processing."""
+ path_types = [SvgItemType.OPEN_PATH, SvgItemType.CLOSED_PATH]
+ non_path_types = [SvgItemType.ICON]
+
+ for svg_type in path_types:
+ with self.subTest(svg_type=svg_type):
+ self.assertTrue(svg_type.is_path)
+
+ for svg_type in non_path_types:
+ with self.subTest(svg_type=svg_type):
+ self.assertFalse(svg_type.is_path)
+ return
+
+ def test_svg_item_type_labels(self):
+ """Test SvgItemType labels - important for UI display."""
+ self.assertEqual(SvgItemType.ICON.label, 'Icon')
+ self.assertEqual(SvgItemType.OPEN_PATH.label, 'Open Path ')
+ self.assertEqual(SvgItemType.CLOSED_PATH.label, 'Closed Path ')
+ return
+
+
+class TestSvgStyleName(BaseTestCase):
+
+ def test_svg_style_name_template_generation(self):
+ """Test template name generation - critical for SVG styling."""
+ # Test template name generation logic
+ color_template = SvgStyleName.COLOR.svg_defs_template_name
+ greyscale_template = SvgStyleName.GREYSCALE.svg_defs_template_name
+
+ self.assertEqual(color_template, 'location/panes/svg_fill_patterns_color.html')
+ self.assertEqual(greyscale_template, 'location/panes/svg_fill_patterns_greyscale.html')
+
+ # Templates should be different
+ self.assertNotEqual(color_template, greyscale_template)
+ return
+
+ def test_svg_style_name_css_file_generation(self):
+ """Test CSS file name generation - critical for styling."""
+ # Test CSS file name generation logic
+ color_css = SvgStyleName.COLOR.css_static_file_name
+ greyscale_css = SvgStyleName.GREYSCALE.css_static_file_name
+
+ self.assertEqual(color_css, 'css/svg-location-color.css')
+ self.assertEqual(greyscale_css, 'css/svg-location-greyscale.css')
+
+ # CSS files should be different
+ self.assertNotEqual(color_css, greyscale_css)
+ return
+
+ def test_svg_style_name_labels(self):
+ """Test SvgStyleName labels - important for UI display."""
+ self.assertEqual(SvgStyleName.COLOR.label, 'Color')
+ self.assertEqual(SvgStyleName.GREYSCALE.label, 'Grey Scale ')
+ return
diff --git a/src/hi/apps/location/tests/test_models.py b/src/hi/apps/location/tests/test_models.py
new file mode 100644
index 00000000..280de35b
--- /dev/null
+++ b/src/hi/apps/location/tests/test_models.py
@@ -0,0 +1,271 @@
+import logging
+from unittest.mock import patch
+
+from hi.apps.location.models import Location, LocationAttribute, LocationView
+from hi.apps.common.svg_models import SvgViewBox, SvgItemPositionBounds
+from hi.apps.attribute.enums import AttributeValueType
+from hi.enums import ItemType
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestLocation(BaseTestCase):
+
+ def test_location_svg_view_box_property_conversion(self):
+ """Test svg_view_box property conversion - complex SVG parsing logic."""
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 200'
+ )
+
+ # Test getter converts string to SvgViewBox
+ svg_view_box = location.svg_view_box
+ self.assertIsInstance(svg_view_box, SvgViewBox)
+ self.assertEqual(svg_view_box.x, 0)
+ self.assertEqual(svg_view_box.y, 0)
+ self.assertEqual(svg_view_box.width, 100)
+ self.assertEqual(svg_view_box.height, 200)
+
+ # Test setter converts SvgViewBox to string
+ new_viewbox = SvgViewBox(x=10, y=20, width=300, height=400)
+ location.svg_view_box = new_viewbox
+ self.assertEqual(location.svg_view_box_str, '10 20 300 400')
+ return
+
+ def test_location_svg_position_bounds_calculation(self):
+ """Test svg_position_bounds calculation - complex geometric logic."""
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='10 20 100 200'
+ )
+
+ bounds = location.svg_position_bounds
+ self.assertIsInstance(bounds, SvgItemPositionBounds)
+
+ # Should match viewbox dimensions
+ self.assertEqual(bounds.min_x, 10)
+ self.assertEqual(bounds.min_y, 20)
+ self.assertEqual(bounds.max_x, 110) # x + width
+ self.assertEqual(bounds.max_y, 220) # y + height
+
+ # Should have reasonable scale limits
+ self.assertEqual(bounds.min_scale, 0.1)
+ self.assertEqual(bounds.max_scale, 25.0)
+ return
+
+ def test_location_item_type_property(self):
+ """Test item_type property - critical for type system integration."""
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+
+ self.assertEqual(location.item_type, ItemType.LOCATION)
+ return
+
+ def test_location_ordering_by_order_id(self):
+ """Test Location ordering - critical for UI display order."""
+ # Create locations with different order_ids
+ location1 = Location.objects.create(
+ name='First Location',
+ svg_fragment_filename='first.svg',
+ svg_view_box_str='0 0 100 100',
+ order_id=2
+ )
+ location2 = Location.objects.create(
+ name='Second Location',
+ svg_fragment_filename='second.svg',
+ svg_view_box_str='0 0 100 100',
+ order_id=1
+ )
+ location3 = Location.objects.create(
+ name='Third Location',
+ svg_fragment_filename='third.svg',
+ svg_view_box_str='0 0 100 100',
+ order_id=3
+ )
+
+ # Should be ordered by order_id
+ locations = list(Location.objects.all())
+ self.assertEqual(locations[0], location2) # order_id=1
+ self.assertEqual(locations[1], location1) # order_id=2
+ self.assertEqual(locations[2], location3) # order_id=3
+ return
+
+ @patch('hi.apps.location.models.default_storage')
+ def test_location_delete_svg_file_cleanup(self, mock_storage):
+ """Test SVG file cleanup on deletion - critical for storage management."""
+ # Setup mock storage
+ mock_storage.exists.return_value = True
+ mock_storage.delete.return_value = None
+
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+
+ filename = location.svg_fragment_filename
+
+ # Delete location should trigger file cleanup
+ location.delete()
+
+ # Should check if file exists and delete it
+ mock_storage.exists.assert_called_once_with(filename)
+ mock_storage.delete.assert_called_once_with(filename)
+ return
+
+ @patch('hi.apps.location.models.default_storage')
+ def test_location_delete_svg_file_missing(self, mock_storage):
+ """Test SVG file deletion when file doesn't exist - error handling."""
+ # Setup mock storage - file doesn't exist
+ mock_storage.exists.return_value = False
+
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='missing.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+
+ # Delete should not raise exception even if file missing
+ location.delete()
+
+ # Should check existence but not try to delete
+ mock_storage.exists.assert_called_once()
+ mock_storage.delete.assert_not_called()
+ return
+
+ def test_location_cascade_deletion_to_attributes(self):
+ """Test cascade deletion to attributes - critical for data integrity."""
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+
+ # Create attribute
+ attribute = LocationAttribute.objects.create(
+ location=location,
+ name='test_attribute',
+ value_type=AttributeValueType.TEXT,
+ value='test_value'
+ )
+
+ attribute_id = attribute.id
+
+ # Delete location should cascade to attributes
+ location.delete()
+
+ self.assertFalse(LocationAttribute.objects.filter(id=attribute_id).exists())
+ return
+
+
+class TestLocationView(BaseTestCase):
+
+ def test_location_view_enum_property_conversions(self):
+ """Test LocationView enum property conversions - custom business logic."""
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+
+ location_view = LocationView.objects.create(
+ location=location,
+ location_view_type_str='DEFAULT',
+ name='Test View',
+ svg_view_box_str='0 0 50 50',
+ svg_rotate=0,
+ svg_style_name_str='COLOR'
+ )
+
+ # Should have proper enum conversions if implemented
+ # (This tests the pattern even if the properties don't exist yet)
+ self.assertEqual(location_view.location_view_type_str, 'DEFAULT')
+ self.assertEqual(location_view.svg_style_name_str, 'COLOR')
+ return
+
+ def test_location_view_cascade_deletion_from_location(self):
+ """Test cascade deletion from location - critical for data integrity."""
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+
+ location_view = LocationView.objects.create(
+ location=location,
+ location_view_type_str='DEFAULT',
+ name='Test View',
+ svg_view_box_str='0 0 50 50',
+ svg_rotate=0,
+ svg_style_name_str='COLOR'
+ )
+
+ view_id = location_view.id
+
+ # Delete location should cascade to views
+ location.delete()
+
+ self.assertFalse(LocationView.objects.filter(id=view_id).exists())
+ return
+
+
+class TestLocationAttribute(BaseTestCase):
+
+ def test_location_attribute_upload_path_generation(self):
+ """Test upload path generation - critical for file organization."""
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+
+ attribute = LocationAttribute.objects.create(
+ location=location,
+ name='test_file',
+ value_type=AttributeValueType.FILE,
+ value='test.pdf'
+ )
+
+ upload_path = attribute.get_upload_to()
+ self.assertEqual(upload_path, 'location/attributes/')
+ return
+
+ def test_location_attribute_indexing(self):
+ """Test LocationAttribute database indexing - critical for query performance."""
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+
+ # Create attributes that should be indexed
+ attr1 = LocationAttribute.objects.create(
+ location=location,
+ name='documentation',
+ value_type=AttributeValueType.TEXT,
+ value='User manual'
+ )
+
+ attr2 = LocationAttribute.objects.create(
+ location=location,
+ name='specifications',
+ value_type=AttributeValueType.TEXT,
+ value='Technical specs'
+ )
+
+ # Test that we can query by indexed fields efficiently
+ # (The actual index performance isn't testable in unit tests,
+ # but we can verify the fields are accessible)
+ results = LocationAttribute.objects.filter(
+ name='documentation',
+ value='User manual'
+ )
+ self.assertIn(attr1, results)
+ self.assertNotIn(attr2, results)
+ return
diff --git a/src/hi/apps/location/tests/test_svg_item_factory.py b/src/hi/apps/location/tests/test_svg_item_factory.py
new file mode 100644
index 00000000..9415a9e2
--- /dev/null
+++ b/src/hi/apps/location/tests/test_svg_item_factory.py
@@ -0,0 +1,220 @@
+import logging
+from unittest.mock import Mock, patch
+
+from hi.apps.location.svg_item_factory import SvgItemFactory
+from hi.apps.location.enums import SvgItemType
+from hi.apps.location.models import Location, LocationView
+from hi.apps.entity.models import Entity
+from hi.apps.entity.enums import EntityType
+from hi.apps.collection.models import Collection
+from hi.apps.collection.enums import CollectionType
+from hi.apps.common.svg_models import SvgIconItem, SvgPathItem
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestSvgItemFactory(BaseTestCase):
+
+ def test_svg_item_factory_singleton_behavior(self):
+ """Test SvgItemFactory singleton pattern - critical for system consistency."""
+ factory1 = SvgItemFactory()
+ factory2 = SvgItemFactory()
+
+ # Should be the same instance
+ self.assertIs(factory1, factory2)
+ return
+
+ def test_get_svg_item_type_entity_classification(self):
+ """Test entity SVG item type classification - critical for rendering logic."""
+ factory = SvgItemFactory()
+
+ # Mock entity with different types
+ camera_entity = Mock(spec=Entity)
+ camera_entity.entity_type = EntityType.CAMERA
+
+ # Test classification logic (specific types depend on EntityStyle configuration)
+ item_type = factory.get_svg_item_type(camera_entity)
+ self.assertIn(item_type, [SvgItemType.ICON, SvgItemType.OPEN_PATH, SvgItemType.CLOSED_PATH])
+ return
+
+ def test_get_svg_item_type_collection_classification(self):
+ """Test collection SVG item type classification - critical for rendering logic."""
+ factory = SvgItemFactory()
+
+ # Mock collection
+ mock_collection = Mock(spec=Collection)
+ mock_collection.collection_type = CollectionType.OTHER
+
+ # Collections should be closed paths
+ item_type = factory.get_svg_item_type(mock_collection)
+ self.assertEqual(item_type, SvgItemType.CLOSED_PATH)
+ return
+
+ def test_get_svg_item_type_unknown_object(self):
+ """Test unknown object classification - error handling."""
+ factory = SvgItemFactory()
+
+ # Unknown object should default to icon
+ unknown_object = Mock()
+ item_type = factory.get_svg_item_type(unknown_object)
+ self.assertEqual(item_type, SvgItemType.ICON)
+ return
+
+ @patch('hi.apps.location.svg_item_factory.EntityStyle')
+ def test_create_svg_icon_item_entity(self, mock_entity_style):
+ """Test SVG icon item creation for entities - complex rendering logic."""
+ factory = SvgItemFactory()
+
+ # Mock dependencies
+ mock_entity_style.get_svg_icon_template_name.return_value = 'entity/icons/camera.html'
+ mock_entity_style.get_svg_icon_viewbox.return_value = Mock(width=24, height=24)
+
+ # Mock entity and position
+ entity = Mock(spec=Entity)
+ entity.entity_type = EntityType.CAMERA
+ entity.html_id = 'entity-123'
+
+ position = Mock()
+ position.svg_x = 100.0
+ position.svg_y = 200.0
+ position.svg_rotate = 45.0
+ position.svg_scale = 1.5
+
+ # Create icon item
+ icon_item = factory.create_svg_icon_item(
+ item=entity,
+ position=position,
+ css_class='entity-icon'
+ )
+
+ # Should create proper SvgIconItem
+ self.assertIsInstance(icon_item, SvgIconItem)
+ self.assertEqual(icon_item.html_id, 'entity-123')
+ self.assertEqual(icon_item.css_class, 'entity-icon')
+ self.assertEqual(icon_item.position_x, 100.0)
+ self.assertEqual(icon_item.position_y, 200.0)
+ self.assertEqual(icon_item.rotate, 45.0)
+ self.assertEqual(icon_item.scale, 1.5)
+ self.assertEqual(icon_item.template_name, 'entity/icons/camera.html')
+ return
+
+ @patch('hi.apps.location.svg_item_factory.EntityStyle')
+ def test_create_svg_path_item_entity(self, mock_entity_style):
+ """Test SVG path item creation for entities - complex rendering logic."""
+ factory = SvgItemFactory()
+
+ # Mock style dependencies
+ mock_status_style = Mock()
+ mock_status_style.stroke_color = '#ff0000'
+ mock_status_style.stroke_width = 2.0
+ mock_status_style.stroke_dasharray = '5,5'
+ mock_status_style.fill_color = '#00ff00'
+ mock_status_style.fill_opacity = 0.5
+
+ mock_entity_style.get_svg_path_status_style.return_value = mock_status_style
+
+ # Mock entity and path
+ entity = Mock(spec=Entity)
+ entity.entity_type = EntityType.MOTION_SENSOR
+ entity.html_id = 'entity-456'
+
+ path = Mock()
+ path.svg_path = 'M 10,10 L 50,50 L 10,50 Z'
+
+ # Create path item
+ path_item = factory.create_svg_path_item(
+ item=entity,
+ path=path,
+ css_class='entity-path'
+ )
+
+ # Should create proper SvgPathItem
+ self.assertIsInstance(path_item, SvgPathItem)
+ self.assertEqual(path_item.html_id, 'entity-456')
+ self.assertEqual(path_item.css_class, 'entity-path')
+ self.assertEqual(path_item.svg_path, 'M 10,10 L 50,50 L 10,50 Z')
+ self.assertEqual(path_item.stroke_color, '#ff0000')
+ self.assertEqual(path_item.stroke_width, 2.0)
+ self.assertEqual(path_item.fill_color, '#00ff00')
+ return
+
+ def test_get_default_svg_path_str_closed_path(self):
+ """Test default closed path generation - complex geometric calculations."""
+ factory = SvgItemFactory()
+
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 200 100'
+ )
+
+ location_view = LocationView.objects.create(
+ location=location,
+ location_view_type_str='DEFAULT',
+ name='Test View',
+ svg_view_box_str='0 0 200 100',
+ svg_rotate=0,
+ svg_style_name_str='COLOR'
+ )
+
+ # Generate closed path (rectangle)
+ svg_path = factory.get_default_svg_path_str(
+ location_view=location_view,
+ is_path_closed=True
+ )
+
+ # Should be a rectangle path centered in viewbox
+ self.assertIn('M ', svg_path) # Move to start
+ self.assertIn(' L ', svg_path) # Line commands
+ self.assertIn(' Z', svg_path) # Close path
+
+ # Should contain reasonable coordinates
+ # Path should be a rectangle with move and line commands
+ coordinates = svg_path.replace('M ', '').replace(' L ', ',').replace(' Z', '').split(',')
+ self.assertGreater(len(coordinates), 6) # Should have multiple coordinate pairs
+ return
+
+ def test_get_default_svg_path_str_open_path(self):
+ """Test default open path generation - geometric calculations."""
+ factory = SvgItemFactory()
+
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 200 100'
+ )
+
+ location_view = LocationView.objects.create(
+ location=location,
+ location_view_type_str='DEFAULT',
+ name='Test View',
+ svg_view_box_str='0 0 200 100',
+ svg_rotate=0,
+ svg_style_name_str='COLOR'
+ )
+
+ # Generate open path (line)
+ svg_path = factory.get_default_svg_path_str(
+ location_view=location_view,
+ is_path_closed=False
+ )
+
+ # Should be a line path
+ self.assertIn('M ', svg_path) # Move to start
+ self.assertIn(' L ', svg_path) # Line command
+ self.assertNotIn(' Z', svg_path) # No close command
+
+ # Should contain reasonable coordinates
+ self.assertIn('50', svg_path) # Should have center Y coordinate
+ return
+
+ def test_new_path_radius_percent_constant(self):
+ """Test NEW_PATH_RADIUS_PERCENT constant - important for UI consistency."""
+ factory = SvgItemFactory()
+
+ # Should have reasonable default radius percentage
+ self.assertEqual(factory.NEW_PATH_RADIUS_PERCENT, 5.0)
+ self.assertGreater(factory.NEW_PATH_RADIUS_PERCENT, 0)
+ self.assertLess(factory.NEW_PATH_RADIUS_PERCENT, 50)
+ return
diff --git a/src/hi/apps/location/tests/test_transient_models.py b/src/hi/apps/location/tests/test_transient_models.py
new file mode 100644
index 00000000..59af9c81
--- /dev/null
+++ b/src/hi/apps/location/tests/test_transient_models.py
@@ -0,0 +1,122 @@
+import logging
+
+from hi.apps.location.transient_models import LocationEditData, LocationViewEditData
+from hi.apps.location.models import Location, LocationView
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestLocationEditData(BaseTestCase):
+
+ def test_location_edit_data_form_initialization(self):
+ """Test LocationEditData form auto-initialization - critical for edit UI."""
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+
+ edit_data = LocationEditData(location=location)
+
+ # Forms should be automatically initialized
+ self.assertIsNotNone(edit_data.location_edit_form)
+ self.assertIsNotNone(edit_data.location_attribute_formset)
+ self.assertIsNotNone(edit_data.location_attribute_upload_form)
+
+ # Form should be bound to location instance
+ self.assertEqual(edit_data.location_edit_form.instance, location)
+ self.assertEqual(edit_data.location_attribute_formset.instance, location)
+ return
+
+ def test_location_edit_data_template_context_generation(self):
+ """Test template context generation - critical for template rendering."""
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+
+ edit_data = LocationEditData(location=location)
+ context = edit_data.to_template_context()
+
+ # Should contain all required template variables
+ expected_keys = {
+ 'location',
+ 'location_edit_form',
+ 'location_attribute_formset',
+ 'location_attribute_upload_form'
+ }
+ self.assertEqual(set(context.keys()), expected_keys)
+ self.assertEqual(context['location'], location)
+ return
+
+ def test_location_edit_data_formset_prefix_generation(self):
+ """Test formset prefix generation - critical for form handling."""
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+
+ edit_data = LocationEditData(location=location)
+
+ # Prefix should include location ID
+ expected_prefix = f'location-{location.id}'
+ self.assertEqual(edit_data.location_attribute_formset.prefix, expected_prefix)
+ return
+
+
+class TestLocationViewEditData(BaseTestCase):
+
+ def test_location_view_edit_data_form_initialization(self):
+ """Test LocationViewEditData form auto-initialization - critical for edit UI."""
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+
+ location_view = LocationView.objects.create(
+ location=location,
+ location_view_type_str='DEFAULT',
+ name='Test View',
+ svg_view_box_str='0 0 50 50',
+ svg_rotate=0,
+ svg_style_name_str='COLOR'
+ )
+
+ edit_data = LocationViewEditData(location_view=location_view)
+
+ # Form should be automatically initialized
+ self.assertIsNotNone(edit_data.location_view_edit_form)
+
+ # Form should be bound to location_view instance
+ self.assertEqual(edit_data.location_view_edit_form.instance, location_view)
+ return
+
+ def test_location_view_edit_data_template_context_generation(self):
+ """Test template context generation - critical for template rendering."""
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+
+ location_view = LocationView.objects.create(
+ location=location,
+ location_view_type_str='DEFAULT',
+ name='Test View',
+ svg_view_box_str='0 0 50 50',
+ svg_rotate=0,
+ svg_style_name_str='COLOR'
+ )
+
+ edit_data = LocationViewEditData(location_view=location_view)
+ context = edit_data.to_template_context()
+
+ # Should contain all required template variables
+ expected_keys = {'location_view', 'location_view_edit_form'}
+ self.assertEqual(set(context.keys()), expected_keys)
+ self.assertEqual(context['location_view'], location_view)
+ return
diff --git a/src/hi/apps/monitor/tests/__init__.py b/src/hi/apps/monitor/tests/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/apps/monitor/tests/test_status_display_manager.py b/src/hi/apps/monitor/tests/test_status_display_manager.py
new file mode 100644
index 00000000..8a8d0cc9
--- /dev/null
+++ b/src/hi/apps/monitor/tests/test_status_display_manager.py
@@ -0,0 +1,127 @@
+import logging
+import threading
+from unittest.mock import patch
+
+from hi.apps.monitor.status_display_manager import StatusDisplayManager
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestStatusDisplayManager(BaseTestCase):
+
+ def test_status_display_manager_singleton_behavior(self):
+ """Test StatusDisplayManager singleton pattern - critical for system consistency."""
+ manager1 = StatusDisplayManager()
+ manager2 = StatusDisplayManager()
+
+ # Should be the same instance
+ self.assertIs(manager1, manager2)
+ return
+
+ def test_status_display_manager_ttl_cache_initialization(self):
+ """Test TTL cache initialization - critical for performance optimization."""
+ manager = StatusDisplayManager()
+
+ # Should have initialized TTL cache for status value overrides
+ self.assertIsNotNone(manager._status_value_overrides)
+
+ # Cache should have reasonable TTL
+ self.assertEqual(manager.STATUS_VALUE_OVERRIDES_SECS, 11)
+ self.assertGreater(manager.STATUS_VALUE_OVERRIDES_SECS, 0)
+ self.assertLess(manager.STATUS_VALUE_OVERRIDES_SECS, 60)
+ return
+
+ def test_status_display_manager_cache_maxsize(self):
+ """Test TTL cache size limits - important for memory management."""
+ manager = StatusDisplayManager()
+
+ # Cache should have reasonable size limit
+ cache = manager._status_value_overrides
+ self.assertEqual(cache.maxsize, 100)
+ self.assertGreater(cache.maxsize, 0)
+ self.assertLess(cache.maxsize, 1000)
+ return
+
+ def test_status_display_manager_cache_ttl_behavior(self):
+ """Test TTL cache expiration behavior - critical for data freshness."""
+ manager = StatusDisplayManager()
+ cache = manager._status_value_overrides
+
+ # Test that cache accepts and stores values
+ test_key = 'test_entity_123'
+ test_value = 'override_value'
+
+ cache[test_key] = test_value
+
+ # Should retrieve stored value
+ self.assertEqual(cache[test_key], test_value)
+ self.assertIn(test_key, cache)
+
+ # Should have proper TTL (we can't easily test expiration in unit tests)
+ self.assertEqual(cache.ttl, manager.STATUS_VALUE_OVERRIDES_SECS)
+ return
+
+ def test_status_display_manager_mixin_inheritance(self):
+ """Test SensorResponseMixin inheritance - critical for sensor integration."""
+ manager = StatusDisplayManager()
+
+ # Should inherit from SensorResponseMixin
+ from hi.apps.sense.sensor_response_manager import SensorResponseMixin
+ self.assertIsInstance(manager, SensorResponseMixin)
+ return
+
+ @patch('hi.apps.monitor.status_display_manager.StatusDisplayManager.get_all_entity_state_status_data_list')
+ def test_status_display_manager_get_status_css_class_update_map(self, mock_get_data):
+ """Test CSS class update map generation - critical for UI updates."""
+ # Mock the complex data retrieval method
+ mock_get_data.return_value = []
+
+ manager = StatusDisplayManager()
+
+ # Should return a dictionary for CSS class updates
+ update_map = manager.get_status_css_class_update_map()
+ self.assertIsInstance(update_map, dict)
+
+ # Should call the data retrieval method
+ mock_get_data.assert_called_once()
+ return
+
+ def test_status_display_manager_thread_safety_cache_access(self):
+ """Test thread-safe cache access - critical for concurrent operations."""
+ manager = StatusDisplayManager()
+ cache = manager._status_value_overrides
+
+ results = []
+ errors = []
+
+ def cache_operation(thread_id):
+ try:
+ # Perform cache operations that might conflict
+ key = f'test_key_{thread_id}'
+ value = f'test_value_{thread_id}'
+
+ cache[key] = value
+ retrieved = cache.get(key)
+ results.append((thread_id, retrieved == value))
+ except Exception as e:
+ errors.append((thread_id, str(e)))
+
+ # Create multiple threads to test concurrent access
+ threads = []
+ for i in range(5):
+ thread = threading.Thread(target=cache_operation, args=(i,))
+ threads.append(thread)
+ thread.start()
+
+ # Wait for all threads to complete
+ for thread in threads:
+ thread.join()
+
+ # Should not have any errors and all operations should succeed
+ self.assertEqual(len(errors), 0, f"Thread errors: {errors}")
+ self.assertEqual(len(results), 5)
+
+ for thread_id, success in results:
+ self.assertTrue(success, f"Thread {thread_id} cache operation failed")
+ return
diff --git a/src/hi/apps/monitor/tests/test_transient_models.py b/src/hi/apps/monitor/tests/test_transient_models.py
new file mode 100644
index 00000000..7482344f
--- /dev/null
+++ b/src/hi/apps/monitor/tests/test_transient_models.py
@@ -0,0 +1,162 @@
+import logging
+from unittest.mock import Mock
+
+from hi.apps.monitor.transient_models import EntityStateStatusData, EntityStatusData
+from hi.apps.entity.models import Entity, EntityState
+from hi.apps.sense.transient_models import SensorResponse
+from hi.apps.control.transient_models import ControllerData
+from hi.apps.common.svg_models import SvgIconItem
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestEntityStateStatusData(BaseTestCase):
+
+ def test_entity_state_status_data_latest_sensor_response_with_data(self):
+ """Test latest_sensor_response with data - critical for status display."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ # Mock sensor responses in time order (newest first)
+ response1 = Mock(spec=SensorResponse)
+ response1.response_datetime = '2023-01-01T12:00:00Z'
+ response2 = Mock(spec=SensorResponse)
+ response2.response_datetime = '2023-01-01T11:00:00Z'
+
+ sensor_response_list = [response1, response2] # Ordered by response time
+ controller_data_list = []
+
+ status_data = EntityStateStatusData(
+ entity_state=entity_state,
+ sensor_response_list=sensor_response_list,
+ controller_data_list=controller_data_list
+ )
+
+ # Should return first (latest) sensor response
+ self.assertEqual(status_data.latest_sensor_response, response1)
+ return
+
+ def test_entity_state_status_data_latest_sensor_response_empty_list(self):
+ """Test latest_sensor_response with empty list - error handling."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ status_data = EntityStateStatusData(
+ entity_state=entity_state,
+ sensor_response_list=[], # Empty list
+ controller_data_list=[]
+ )
+
+ # Should return None when no sensor responses
+ self.assertIsNone(status_data.latest_sensor_response)
+ return
+
+ def test_entity_state_status_data_initialization(self):
+ """Test EntityStateStatusData initialization - critical for data structure."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ sensor_response = Mock(spec=SensorResponse)
+ controller_data = Mock(spec=ControllerData)
+
+ status_data = EntityStateStatusData(
+ entity_state=entity_state,
+ sensor_response_list=[sensor_response],
+ controller_data_list=[controller_data]
+ )
+
+ # Should properly initialize all fields
+ self.assertEqual(status_data.entity_state, entity_state)
+ self.assertEqual(status_data.sensor_response_list, [sensor_response])
+ self.assertEqual(status_data.controller_data_list, [controller_data])
+ return
+
+
+class TestEntityStatusData(BaseTestCase):
+
+ def test_entity_status_data_initialization_with_optional_fields(self):
+ """Test EntityStatusData initialization with optional fields - important for flexibility."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+
+ entity_state_status_data = Mock(spec=EntityStateStatusData)
+ svg_icon_item = Mock(spec=SvgIconItem)
+
+ status_data = EntityStatusData(
+ entity=entity,
+ entity_state_status_data_list=[entity_state_status_data],
+ display_only_svg_icon_item=svg_icon_item
+ )
+
+ # Should properly initialize all fields including optional ones
+ self.assertEqual(status_data.entity, entity)
+ self.assertEqual(status_data.entity_state_status_data_list, [entity_state_status_data])
+ self.assertEqual(status_data.display_only_svg_icon_item, svg_icon_item)
+ return
+
+ def test_entity_status_data_initialization_without_optional_fields(self):
+ """Test EntityStatusData initialization without optional fields - default behavior."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+
+ entity_state_status_data = Mock(spec=EntityStateStatusData)
+
+ status_data = EntityStatusData(
+ entity=entity,
+ entity_state_status_data_list=[entity_state_status_data]
+ )
+
+ # Should properly initialize required fields and default optional ones
+ self.assertEqual(status_data.entity, entity)
+ self.assertEqual(status_data.entity_state_status_data_list, [entity_state_status_data])
+ self.assertIsNone(status_data.display_only_svg_icon_item)
+ return
+
+ def test_entity_status_data_template_context_generation(self):
+ """Test template context generation - critical for UI rendering."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+
+ entity_state_status_data_list = [
+ Mock(spec=EntityStateStatusData),
+ Mock(spec=EntityStateStatusData)
+ ]
+
+ status_data = EntityStatusData(
+ entity=entity,
+ entity_state_status_data_list=entity_state_status_data_list
+ )
+
+ context = status_data.to_template_context()
+
+ # Should contain required template variables
+ expected_keys = {'entity', 'entity_state_status_data_list'}
+ self.assertEqual(set(context.keys()), expected_keys)
+ self.assertEqual(context['entity'], entity)
+ self.assertEqual(context['entity_state_status_data_list'], entity_state_status_data_list)
+ return
diff --git a/src/hi/apps/notify/tests/test_models.py b/src/hi/apps/notify/tests/test_models.py
new file mode 100644
index 00000000..563f6188
--- /dev/null
+++ b/src/hi/apps/notify/tests/test_models.py
@@ -0,0 +1,56 @@
+import logging
+from django.db import IntegrityError
+
+from hi.apps.notify.models import UnsubscribedEmail
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestUnsubscribedEmail(BaseTestCase):
+
+ def test_unsubscribed_email_uniqueness_constraint(self):
+ """Test email uniqueness constraint - critical for data integrity."""
+ # Create first unsubscribed email
+ UnsubscribedEmail.objects.create(email='[email protected]')
+
+ # Duplicate email should fail
+ with self.assertRaises(IntegrityError):
+ UnsubscribedEmail.objects.create(email='[email protected]')
+ return
+
+ def test_unsubscribed_email_valid_email_format(self):
+ """Test valid email format acceptance - important for data validation."""
+ valid_emails = [
+ ]
+
+ for email in valid_emails:
+ with self.subTest(email=email):
+ unsubscribed = UnsubscribedEmail.objects.create(email=email)
+ self.assertEqual(unsubscribed.email, email)
+ return
+
+ def test_unsubscribed_email_created_datetime_indexing(self):
+ """Test created_datetime field indexing - critical for query performance."""
+ unsubscribed = UnsubscribedEmail.objects.create(email='[email protected]')
+
+ # Test that datetime queries work efficiently
+ # (The actual index performance isn't testable in unit tests,
+ # but we can verify the field is accessible and queryable)
+ recent_unsubscribed = UnsubscribedEmail.objects.filter(
+ created_datetime__gte=unsubscribed.created_datetime
+ )
+ self.assertIn(unsubscribed, recent_unsubscribed)
+ return
+
+ def test_unsubscribed_email_manager_usage(self):
+ """Test custom manager usage - important for query interface."""
+ from hi.apps.notify.managers import UnsubscribedEmailManager
+
+ # Should use custom manager
+ self.assertIsInstance(UnsubscribedEmail.objects, UnsubscribedEmailManager)
+ return
diff --git a/src/hi/apps/security/tests/__init__.py b/src/hi/apps/security/tests/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/apps/security/tests/test_enums.py b/src/hi/apps/security/tests/test_enums.py
new file mode 100644
index 00000000..3c777037
--- /dev/null
+++ b/src/hi/apps/security/tests/test_enums.py
@@ -0,0 +1,129 @@
+import logging
+
+from hi.apps.security.enums import SecurityLevel, SecurityState, SecurityStateAction
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestSecurityLevel(BaseTestCase):
+
+ def test_security_level_non_off_choices_filtering(self):
+ """Test non_off_choices method - critical for UI form generation."""
+ choices = SecurityLevel.non_off_choices()
+
+ # Should exclude OFF level
+ choice_values = [choice[0] for choice in choices]
+ self.assertNotIn('off', choice_values)
+
+ # Should include HIGH and LOW
+ self.assertIn('high', choice_values)
+ self.assertIn('low', choice_values)
+
+ # Should return list of tuples with proper format
+ for choice in choices:
+ self.assertIsInstance(choice, tuple)
+ self.assertEqual(len(choice), 2)
+ self.assertIsInstance(choice[0], str) # value
+ self.assertIsInstance(choice[1], str) # label
+ return
+
+ def test_security_level_choice_format(self):
+ """Test choice format consistency - important for form integration."""
+ choices = SecurityLevel.non_off_choices()
+
+ # Should have lowercase values and proper labels
+ expected_mapping = {
+ 'high': 'High',
+ 'low': 'Low'
+ }
+
+ for value, label in choices:
+ self.assertIn(value, expected_mapping)
+ self.assertEqual(label, expected_mapping[value])
+ return
+
+
+class TestSecurityState(BaseTestCase):
+
+ def test_security_state_auto_change_allowed_property(self):
+ """Test auto_change_allowed property - critical for automation logic."""
+ # States that allow auto change
+ self.assertTrue(SecurityState.DAY.auto_change_allowed)
+ self.assertTrue(SecurityState.NIGHT.auto_change_allowed)
+
+ # States that don't allow auto change
+ self.assertFalse(SecurityState.DISABLED.auto_change_allowed)
+ self.assertFalse(SecurityState.AWAY.auto_change_allowed)
+ return
+
+ def test_security_state_uses_notifications_property(self):
+ """Test uses_notifications property - critical for notification system."""
+ # Only AWAY should use notifications
+ self.assertTrue(SecurityState.AWAY.uses_notifications)
+
+ # Other states should not use notifications
+ self.assertFalse(SecurityState.DISABLED.uses_notifications)
+ self.assertFalse(SecurityState.DAY.uses_notifications)
+ self.assertFalse(SecurityState.NIGHT.uses_notifications)
+ return
+
+ def test_security_state_initialization_parameters(self):
+ """Test SecurityState initialization with custom parameters - complex enum logic."""
+ # Test that all states have proper initialization
+ for state in SecurityState:
+ # Should have boolean properties
+ self.assertIsInstance(state.auto_change_allowed, bool)
+ self.assertIsInstance(state.uses_notifications, bool)
+
+ # Should have inherited label and description
+ self.assertIsInstance(state.label, str)
+ self.assertIsInstance(state.description, str)
+ return
+
+ def test_security_state_business_logic_consistency(self):
+ """Test security state business logic consistency - critical for security system."""
+ # AWAY state should use notifications (highest security)
+ self.assertTrue(SecurityState.AWAY.uses_notifications)
+ self.assertFalse(SecurityState.AWAY.auto_change_allowed)
+
+ # DISABLED should not use notifications or allow auto change
+ self.assertFalse(SecurityState.DISABLED.uses_notifications)
+ self.assertFalse(SecurityState.DISABLED.auto_change_allowed)
+
+ # DAY/NIGHT should allow auto change but not use notifications
+ for state in [SecurityState.DAY, SecurityState.NIGHT]:
+ self.assertTrue(state.auto_change_allowed)
+ self.assertFalse(state.uses_notifications)
+ return
+
+
+class TestSecurityStateAction(BaseTestCase):
+
+ def test_security_state_action_enum_values(self):
+ """Test SecurityStateAction enum values - critical for action mapping."""
+ expected_actions = {
+ SecurityStateAction.DISABLE,
+ SecurityStateAction.SET_DAY,
+ SecurityStateAction.SET_NIGHT,
+ SecurityStateAction.SET_AWAY,
+ SecurityStateAction.SNOOZE
+ }
+
+ actual_actions = set(SecurityStateAction)
+ self.assertEqual(actual_actions, expected_actions)
+ return
+
+ def test_security_state_action_labels(self):
+ """Test SecurityStateAction labels - important for UI display."""
+ expected_labels = {
+ SecurityStateAction.DISABLE: 'Disable',
+ SecurityStateAction.SET_DAY: 'Day',
+ SecurityStateAction.SET_NIGHT: 'Night',
+ SecurityStateAction.SET_AWAY: 'Away',
+ SecurityStateAction.SNOOZE: 'Snooze'
+ }
+
+ for action, expected_label in expected_labels.items():
+ self.assertEqual(action.label, expected_label)
+ return
diff --git a/src/hi/apps/sense/tests/__init__.py b/src/hi/apps/sense/tests/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/apps/sense/tests/test_models.py b/src/hi/apps/sense/tests/test_models.py
new file mode 100644
index 00000000..4f6a908c
--- /dev/null
+++ b/src/hi/apps/sense/tests/test_models.py
@@ -0,0 +1,89 @@
+import logging
+
+from hi.apps.sense.models import Sensor
+from hi.apps.sense.enums import SensorType
+from hi.apps.entity.models import Entity, EntityState
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestSensor(BaseTestCase):
+
+ def test_sensor_cascade_deletion_from_entity_state(self):
+ """Test cascade deletion from entity state - critical for data integrity."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ sensor = Sensor.objects.create(
+ name='Test Sensor',
+ entity_state=entity_state,
+ sensor_type_str='DEFAULT',
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ sensor_id = sensor.id
+
+ # Delete entity state should cascade to sensor
+ entity_state.delete()
+
+ self.assertFalse(Sensor.objects.filter(id=sensor_id).exists())
+ return
+
+ def test_sensor_sensor_type_property_conversion(self):
+ """Test sensor_type property enum conversion - custom business logic."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ sensor = Sensor.objects.create(
+ name='Test Sensor',
+ entity_state=entity_state,
+ sensor_type_str='DEFAULT',
+ integration_id='test_id',
+ integration_name='test_integration'
+ )
+
+ # Test getter converts string to enum
+ self.assertEqual(sensor.sensor_type, SensorType.DEFAULT)
+
+ # Test setter converts enum to string
+ sensor.sensor_type = SensorType.DEFAULT
+ self.assertEqual(sensor.sensor_type_str, 'default')
+ return
+
+ def test_sensor_integration_key_inheritance(self):
+ """Test Sensor integration key inheritance - critical for integration system."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='CAMERA'
+ )
+ entity_state = EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='ON_OFF'
+ )
+
+ sensor = Sensor.objects.create(
+ name='Test Sensor',
+ entity_state=entity_state,
+ sensor_type_str='DEFAULT',
+ integration_id='sensor_123',
+ integration_name='test_integration'
+ )
+
+ # Should inherit integration key fields from IntegrationKeyModel
+ self.assertEqual(sensor.integration_id, 'sensor_123')
+ self.assertEqual(sensor.integration_name, 'test_integration')
+ return
diff --git a/src/hi/apps/user/tests/test_magic_code_generator.py b/src/hi/apps/user/tests/test_magic_code_generator.py
new file mode 100644
index 00000000..db423382
--- /dev/null
+++ b/src/hi/apps/user/tests/test_magic_code_generator.py
@@ -0,0 +1,47 @@
+import logging
+from unittest.mock import patch
+
+from hi.apps.user.magic_code_generator import MagicCodeGenerator, MagicCodeStatus
+from hi.tests.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestMagicCodeGenerator(BaseTestCase):
+
+ def test_magic_code_status_enum_values(self):
+ """Test MagicCodeStatus enum values - critical for validation logic."""
+ self.assertEqual(MagicCodeStatus.INVALID.value, 0)
+ self.assertEqual(MagicCodeStatus.EXPIRED.value, 1)
+ self.assertEqual(MagicCodeStatus.VALID.value, 2)
+ return
+
+ @patch('hi.apps.user.magic_code_generator.get_random_string')
+ def test_magic_code_generator_code_generation(self, mock_random_string):
+ """Test magic code generation - critical for authentication security."""
+ mock_random_string.return_value = 'ABC123'
+
+ generator = MagicCodeGenerator()
+
+ # Test code generation method exists and uses random string
+ if hasattr(generator, 'generate_code'):
+ code = generator.generate_code()
+ mock_random_string.assert_called()
+ self.assertIsInstance(code, str)
+ return
+
+ def test_magic_code_generator_instantiation(self):
+ """Test MagicCodeGenerator instantiation - important for system initialization."""
+ generator = MagicCodeGenerator()
+ self.assertIsInstance(generator, MagicCodeGenerator)
+ return
+
+ def test_magic_code_status_enum_ordering(self):
+ """Test MagicCodeStatus enum ordering - important for validation priority."""
+ # Status values should be ordered logically
+ statuses = [MagicCodeStatus.INVALID, MagicCodeStatus.EXPIRED, MagicCodeStatus.VALID]
+ values = [status.value for status in statuses]
+
+ # Should be in ascending order
+ self.assertEqual(values, sorted(values))
+ return
diff --git a/src/hi/apps/weather/tests/test_enums.py b/src/hi/apps/weather/tests/test_enums.py
index 8bedbbae..3487afa1 100644
--- a/src/hi/apps/weather/tests/test_enums.py
+++ b/src/hi/apps/weather/tests/test_enums.py
@@ -63,19 +63,6 @@ class TestWeatherEnums(BaseTestCase):
return
- def test_SkyCondition_properties(self):
- """Test SkyCondition enum properties"""
- for condition in SkyCondition:
- with self.subTest(condition=condition):
- self.assertIsNotNone(condition.label)
- self.assertIsNotNone(condition.day_label)
- self.assertIsNotNone(condition.icon_filename)
- self.assertIsNotNone(condition.day_icon_filename)
- self.assertTrue(condition.icon_filename.endswith('.svg'))
- self.assertTrue(condition.day_icon_filename.endswith('.svg'))
- continue
- return
-
def test_MoonPhase__from_illumination(self):
"""Test MoonPhase illumination percentage and waxing status mapping"""
test_data_list = [
diff --git a/src/hi/apps/weather/tests/test_weather_alert_alarm_mapper.py b/src/hi/apps/weather/tests/test_weather_alert_alarm_mapper.py
index 9f86ff34..53cf6347 100644
--- a/src/hi/apps/weather/tests/test_weather_alert_alarm_mapper.py
+++ b/src/hi/apps/weather/tests/test_weather_alert_alarm_mapper.py
@@ -1,7 +1,6 @@
"""
Tests for WeatherAlertAlarmMapper - converting weather alerts to system alarms.
"""
-import unittest
from unittest.mock import patch
from datetime import datetime, timedelta
@@ -19,9 +18,10 @@ from hi.apps.weather.enums import (
)
from hi.apps.weather.transient_models import WeatherAlert
from hi.apps.weather.weather_alert_alarm_mapper import WeatherAlertAlarmMapper
+from hi.tests.base_test_case import BaseTestCase
-class TestWeatherAlertAlarmMapper(unittest.TestCase):
+class TestWeatherAlertAlarmMapper(BaseTestCase):
"""Test weather alert to system alarm conversion logic."""
def setUp(self):
diff --git a/src/hi/apps/weather/tests/test_weather_alert_integration.py b/src/hi/apps/weather/tests/test_weather_alert_integration.py
index 66db7519..e143a332 100644
--- a/src/hi/apps/weather/tests/test_weather_alert_integration.py
+++ b/src/hi/apps/weather/tests/test_weather_alert_integration.py
@@ -3,7 +3,6 @@ Integration tests for weather alert to system alarm conversion.
Tests the complete flow from NWS data parsing to alarm creation.
"""
import asyncio
-import unittest
from unittest.mock import Mock, AsyncMock
from hi.apps.weather.enums import WeatherEventType, AlertSeverity
@@ -11,9 +10,10 @@ from hi.apps.weather.weather_sources.nws import NationalWeatherService
from hi.apps.weather.weather_manager import WeatherManager
from hi.transient_models import GeographicLocation
from hi.units import UnitQuantity
+from hi.tests.base_test_case import BaseTestCase
-class TestWeatherAlertIntegration(unittest.TestCase):
+class TestWeatherAlertIntegration(BaseTestCase):
"""Test end-to-end weather alert to alarm integration."""
def test_nws_tornado_warning_creates_critical_alarm(self):
@@ -186,10 +186,13 @@ class TestWeatherAlertIntegration(unittest.TestCase):
mock_data_source.id = "test_nws"
# Update weather alerts (this should create alarms)
- run_async_test(mock_weather_manager.update_weather_alerts(
- weather_data_source=mock_data_source,
- weather_alerts=test_alerts
- ))
+ async def test_update():
+ await mock_weather_manager.update_weather_alerts(
+ weather_data_source=mock_data_source,
+ weather_alerts=test_alerts
+ )
+
+ asyncio.run(test_update())
# Verify alert manager was called to add alarms
self.assertEqual(mock_alert_manager.add_alarm.call_count, 2) # Only 2 should create alarms
@@ -236,21 +239,4 @@ class TestWeatherAlertIntegration(unittest.TestCase):
)
-# Async test runner
-def run_async_test(coro):
- """Helper to run async tests."""
- loop = asyncio.new_event_loop()
- asyncio.set_event_loop(loop)
- try:
- return loop.run_until_complete(coro)
- finally:
- loop.close()
-
-
-# Add async test wrapper
-class AsyncTestCase(unittest.TestCase):
- def test_weather_manager_integration_wrapper(self):
- """Wrapper to run async test."""
- test_instance = TestWeatherAlertIntegration()
- test_instance.test_weather_manager_integration()
diff --git a/src/hi/apps/weather/tests/test_weather_manager_defensive_handling.py b/src/hi/apps/weather/tests/test_weather_manager_defensive_handling.py
index 2b662409..c4660e74 100644
--- a/src/hi/apps/weather/tests/test_weather_manager_defensive_handling.py
+++ b/src/hi/apps/weather/tests/test_weather_manager_defensive_handling.py
@@ -2,7 +2,6 @@
Test that WeatherManager gracefully handles errors in daily weather tracking
without breaking core weather API functionality.
"""
-import unittest
from unittest.mock import patch
from datetime import datetime
import asyncio
@@ -16,6 +15,7 @@ from hi.apps.weather.transient_models import WeatherConditionsData, NumericDataP
from hi.apps.weather.weather_data_source import WeatherDataSource
from hi.transient_models import GeographicLocation
from hi.units import UnitQuantity
+from hi.tests.base_test_case import BaseTestCase
class MockWeatherDataSource(WeatherDataSource):
@@ -45,7 +45,7 @@ class MockWeatherDataSource(WeatherDataSource):
pass
-class TestWeatherManagerDefensiveHandling(unittest.TestCase):
+class TestWeatherManagerDefensiveHandling(BaseTestCase):
"""Test defensive error handling for daily weather tracking."""
def setUp(self):