Home Information - Your home, your data, organized.
Python
Integration/Services unit tests adds and improvements (#59)
Tony Cf37d283a181a
diff --git a/CLAUDE_CONTEXT_ISSUE_52.md b/CLAUDE_CONTEXT_ISSUE_52.mdnew file mode 100644index 00000000..38766567--- /dev/null+++ b/CLAUDE_CONTEXT_ISSUE_52.md@@ -0,0 +1,86 @@+# Claude Context - Issue #52 Test Implementation Progress++## Current Status: Working on HassController Tests (536 lines)++### Overall Progress Summary+- **Phase 1 (ZoneMinder)**: 100% Complete ✅+- **Phase 2 (HASS)**: 66% Complete ✅+- **Phase 3 (Integration)**: 0% Remaining ⏳++### Completed Work (Major Achievements)+1. **ZoneMinder Complete Test Suite** - All modules now have comprehensive tests:+ - `test_zm_manager.py` - Singleton, TTL caching (300s), timezone validation, thread safety+ - `test_zm_controller.py` - Integration key parsing, regex validation, PyZM API calls+ - `test_zm_sync.py` - Database operations, state sync, entity lifecycle + real ZM API data+ - Real data: `/src/hi/services/zoneminder/tests/data/zm_*.json`++2. **HASS Partial Test Suite** - Major gaps filled:+ - `test_hass_manager.py` - Singleton, database constraint validation (was ZERO tests)+ - `test_hass_client.py` - HTTP API, error handling + real HASS data (was ZERO tests)+ - Real data: `/src/hi/services/hass/tests/data/hass-states.json` (already existed)++### Current Task: HassController Tests+**File to create**: `/src/hi/services/hass/tests/test_hass_controller.py`++**Key Module Info** (`hass_controller.py` - 536 lines):+- **Main class**: `HassController(IntegrationController, HassMixin)`+- **Primary method**: `do_control(integration_details, control_value) -> IntegrationControlResult`+- **Key internal methods**:+ - `_do_control_with_services()` - Main service routing logic+ - `_do_control_with_set_state()` - Legacy state setting method+ - `_control_device_with_payload()` - Payload-based device control+ - `_control_numeric_parameter_device()` - Multi-domain numeric control++**Critical Testing Areas** (High-Value):+1. **Service routing with domain/service mapping** - Complex CONTROL_SERVICE_MAPPING logic+2. **Payload-based device control** - `integration_details.payload` processing+3. **Multi-domain numeric control** - brightness (0-100%), volume (0.0-1.0), temperature+4. **Error scenarios and exception handling** - HTTP failures, invalid payloads+5. **Integration key parsing** - entity_id extraction and validation++### Testing Approach Patterns Established+**From ZoneMinder/HASS patterns**:+- Use real API data when available (improve robustness)+- Mock external dependencies (PyZM, HTTP requests)+- Focus on business logic over trivial getters/setters+- Test error scenarios and edge cases+- Avoid log message assertions (per testing guidelines)+- Test database operations with transactions+- Test singleton patterns and thread safety++### Real Data Available for End-to-End Testing+- **ZoneMinder**: `data/testing/api/zm*.json` (states, monitors, events)+- **Home Assistant**: `data/testing/api/hass-states.json` (entities, complex attributes)++### Remaining Tasks After HassController+1. **HassSynchronizer tests** (142 lines) - Database operations, entity lifecycle+2. **End-to-end integration tests** - Using real API data from both services+3. **Run full test suite** - `./manage.py test`+4. **flake8 linting** - `flake8 --config=.flake8-ci src/`++### Project Testing Guidelines (Critical)+**High-Value Tests**: Database constraints, complex business logic, external API boundaries, integration key parsing, caching, singleton patterns, thread safety+**Avoid**: Simple getters/setters, Django ORM internals, log message assertions++### Development Commands+```bash+# Setup+. ./init-env-dev.sh++# Test specific modules+cd src && ./manage.py test hi.services.hass.tests.test_hass_controller+cd src && ./manage.py test hi.services.zoneminder.tests++# Linting+flake8 --config=.flake8-ci src/++# Git workflow (when ready)+git push github branch-name+```++### Next Immediate Action+Create comprehensive `test_hass_controller.py` focusing on:+- Service routing and payload processing+- Multi-domain numeric parameter validation+- Error handling for HTTP failures and invalid data+- Integration with real HASS entity patterns from existing data\ No newline at end of filediff --git a/docs/CLAUDE.md b/docs/CLAUDE.mdindex 5f889555..c2240193 100644--- a/docs/CLAUDE.md+++ b/docs/CLAUDE.md@@ -52,7 +52,7 @@ For detailed setup and daily commands, see [Development Setup](dev/Setup.md).# Common commandscd src && ./manage.py test-flake8 --config=.flake8-ci src/+cd src && flake8 --config=.flake8-ci src/./manage.py runserver # http://127.0.0.1:8411```@@ -76,7 +76,7 @@ All generated code must comply with the `.flake8-ci` configuration rules. Common4. **Line Continuation**: Proper indentation for multi-line statements following PEP 85. **Line Length**: Respect maximum line length limits defined in `.flake8-ci`-Before submitting code, always run: `flake8 --config=.flake8-ci src/` to verify compliance.+Before submitting code, always run: `cd src && flake8 --config=.flake8-ci src/` to verify compliance.## Commit Message Guidelines (Claude-Specific)diff --git a/docs/dev/Guidelines.md b/docs/dev/Guidelines.mdindex e2895825..f6b12c6d 100644--- a/docs/dev/Guidelines.md+++ b/docs/dev/Guidelines.md@@ -86,7 +86,7 @@ ignore = E129,D203,E201,E202,E203,E221,E231,E251,W293,W291,W391,W503#### CI Configuration (`.flake8-ci`)**Hard requirement** for pull request approval. GitHub uses this configuration to enforce code quality standards and will block PR merging if linting fails.-**Before submitting any PR**, you must run: `flake8 --config=.flake8-ci src/` and ensure it passes with no violations.+**Before submitting any PR**, you must run: `flake8 --config=src/.flake8-ci src/` and ensure it passes with no violations.### Generated Code Standardsdiff --git a/docs/dev/ReleaseProcesses.md b/docs/dev/ReleaseProcesses.mdindex d7aa0f94..1248e9b1 100644--- a/docs/dev/ReleaseProcesses.md+++ b/docs/dev/ReleaseProcesses.md@@ -6,13 +6,13 @@- Get your local `staging` branch fuly in sync with remote/upstream.- Bump the version number in the file `HI_VERSION` as appropriate: major, minor or suffix.- Commit the version number change directly to the upstream `staging` branch with "Bump version number to vX.X.X".-- Chnage to local `master` branch.+- Change to local `master` branch.- Get your `master` branch fully in sync with remote/upstream.- Merge from `staging` into `master`- Push `master` to remote/upstream.- Create GitHub release.- Add/create tag with next version number in the form `vX.X.X`.- Set Target = `master`-- Use "Generate relewase notes" button anmd edit as needed.+- Use "Generate release notes" button anmd edit as needed.- Use "Set as the latest release" (usually)- "Publish Release" button.diff --git a/docs/dev/Setup.md b/docs/dev/Setup.mdindex 862f16e5..33b8429c 100644--- a/docs/dev/Setup.md+++ b/docs/dev/Setup.md@@ -89,8 +89,7 @@ pip install -r src/hi/requirements/development.txtInitialize the database and add the admin users and groups.``` shell-cd $PROJ_DIR-cd src+cd $PROJ_DIR/src./manage.py check./manage.py migrate./manage.py hi_createsuperuser@@ -99,6 +98,7 @@ cd srcIt is a good idea to run the unit tests to validate that you can and that the installation seem fine.``` shell+cd $PROJ_DIR/src./manage.py test```@@ -107,6 +107,7 @@ It is a good idea to run the unit tests to validate that you can and that the inEnsure that the Redis server is running (see the Dependencies page for installation instructions), then:``` shell+cd $PROJ_DIR/src./manage.py runserver```@@ -124,7 +125,7 @@ Once your environment is set up, these are the common commands for daily develop### Django Management```bash-cd src+cd $PROJ_DIR/src# Database operations./manage.py migrate@@ -147,7 +148,7 @@ cd src```bash# Linting and formatting (from development.txt requirements)black src/ # Format code-flake8 --config=.flake8-ci src/ # Lint code with CI configuration+flake8 --config=src/.flake8-ci src/ # Lint code with CI configurationautopep8 --in-place --recursive src/ # Auto-format```diff --git a/docs/dev/Testing.md b/docs/dev/Testing.mdindex 560be469..e40cf78e 100644--- a/docs/dev/Testing.md+++ b/docs/dev/Testing.md@@ -5,6 +5,7 @@## Unit Tests``` shell+cd $PROJ_DIR/src./manage.py test```@@ -54,6 +55,224 @@ with patch.object(manager, 'fallback_handler', mock_fallback):self.assertIsNone(result) # Verify expected failure behavior```+### Additional Testing Anti-Patterns (Avoid These)++**Mock-Centric Testing Instead of Behavior Testing**++**Problem**: Tests focus on verifying mock calls rather than testing actual behavior and return values.++**Bad Example**:+```python+# BAD - Testing mock calls instead of behavior+@patch('module.external_service')+def test_process_data(self, mock_service):+ mock_service.return_value = {'status': 'success'}++ result = processor.process_data(input_data)++ # Only testing that the mock was called correctly+ mock_service.assert_called_once_with(expected_params)+ # Missing: What did process_data actually return?+```++**Good Example**:+```python+# GOOD - Testing actual behavior and return values+@patch('module.external_service')+def test_process_data_returns_transformed_result(self, mock_service):+ mock_service.return_value = {'status': 'success', 'data': 'raw_value'}++ result = processor.process_data(input_data)++ # Test the actual behavior and return value+ self.assertEqual(result['transformed_data'], 'processed_raw_value')+ self.assertEqual(result['status'], 'completed')+ self.assertIn('timestamp', result)+```++**Over-Mocking Internal Components**++**Problem**: Mocking too many internal components breaks the integration between parts of the system.++**Bad Example**:+```python+# BAD - Mocking both HTTP layer AND internal converter+@patch('module.http_client.get')+@patch('module.DataConverter.parse')+def test_fetch_and_parse(self, mock_parse, mock_get):+ mock_get.return_value = mock_response+ mock_parse.return_value = mock_parsed_data++ result = service.fetch_and_parse()+ # This tests nothing about actual data flow+```++**Good Example**:+```python+# GOOD - Mock only at system boundaries+@patch('module.http_client.get')+def test_fetch_and_parse_integration(self, mock_get):+ mock_get.return_value = Mock(text='{"real": "json", "data": "here"}')++ result = service.fetch_and_parse()++ # Test that real data flows through real converter+ self.assertIsInstance(result, ExpectedDataType)+ self.assertEqual(result.parsed_field, "expected_value")+```++**Testing Implementation Details Instead of Interface Contracts**++**Problem**: Tests verify internal implementation details rather than public interface behavior.++**Bad Example**:+```python+# BAD - Testing exact HTTP parameters instead of behavior+def test_api_call_constructs_correct_url(self):+ client.make_request('entity_123')++ expected_url = 'https://api.service.com/v1/entities/entity_123'+ expected_headers = {'Authorization': 'Bearer token', 'Content-Type': 'application/json'}+ mock_post.assert_called_once_with(expected_url, headers=expected_headers)+ # Missing: What happens with the response?+```++**Good Example**:+```python+# GOOD - Testing the interface contract+def test_api_call_returns_entity_data(self):+ mock_response_data = {'id': 'entity_123', 'name': 'Test Entity'}+ mock_post.return_value = Mock(json=lambda: mock_response_data)++ result = client.make_request('entity_123')++ # Test the contract: what the method promises to return+ self.assertEqual(result['id'], 'entity_123')+ self.assertEqual(result['name'], 'Test Entity')+```++**Superficial Edge Case Testing**++**Problem**: Creating edge case tests that don't test meaningful business logic scenarios.++**Bad Example**:+```python+# BAD - Testing trivial edge cases without business impact+def test_handles_various_url_formats(self):+ test_cases = [+ ('http://localhost', 'http://localhost'),+ ('http://localhost/', 'http://localhost'),+ ('https://example.com/', 'https://example.com')+ ]+ for input_url, expected in test_cases:+ client = ApiClient(input_url)+ self.assertEqual(client.base_url, expected)+```++**Good Example**:+```python+# GOOD - Testing edge cases that affect actual functionality+def test_url_normalization_prevents_api_call_failures(self):+ client_with_slash = ApiClient('https://api.example.com/')+ client_without_slash = ApiClient('https://api.example.com')++ # Test that both work correctly for actual API calls+ with patch('requests.get') as mock_get:+ mock_get.return_value = Mock(json=lambda: {'data': 'test'})++ result1 = client_with_slash.fetch_data()+ result2 = client_without_slash.fetch_data()++ # Both should work and return same data+ self.assertEqual(result1, result2)+ # Verify no double slashes in URL+ for call in mock_get.call_args_list:+ url = call[0][0]+ self.assertNotIn('//api', url)+```++**Complex Multi-Purpose Tests**++**Problem**: Single tests that verify too many different behaviors, making failures hard to diagnose.++**Bad Example**:+```python+# BAD - Testing multiple services and scenarios in one test+def test_service_various_operations(self):+ test_cases = [+ ('light', 'turn_on', 'light.bedroom'),+ ('switch', 'turn_off', 'switch.outlet'),+ ('climate', 'set_temperature', 'climate.thermostat'),+ ('media_player', 'play_media', 'media_player.living_room'),+ ]+ for domain, service, entity in test_cases:+ with self.subTest(domain=domain):+ result = client.call_service(domain, service, entity)+ # Generic assertions that don't test domain-specific logic+ self.assertIsNotNone(result)+```++**Good Example**:+```python+# GOOD - Focused tests for specific behaviors+def test_light_service_calls_return_response_objects(self):+ mock_response = Mock(status_code=200, json=lambda: {'context': 'light_context'})++ result = client.call_service('light', 'turn_on', 'light.bedroom')++ self.assertEqual(result.status_code, 200)+ self.assertIn('context', result.json())++def test_climate_service_handles_temperature_data(self):+ service_data = {'temperature': 72, 'hvac_mode': 'heat'}++ result = client.call_service('climate', 'set_temperature', 'climate.thermostat', service_data)++ # Test climate-specific behavior+ call_data = mock_post.call_args[1]['json']+ self.assertEqual(call_data['temperature'], 72)+ self.assertEqual(call_data['hvac_mode'], 'heat')+```++**Inadequate Error Context Testing**++**Problem**: Testing that errors occur without verifying error messages provide useful debugging information.++**Bad Example**:+```python+# BAD - Only testing that an error occurs+def test_invalid_entity_raises_error(self):+ with self.assertRaises(ValueError):+ client.set_state('invalid.entity', 'on')+```++**Good Example**:+```python+# GOOD - Testing error context and messages+def test_invalid_entity_provides_descriptive_error(self):+ mock_response = Mock(status_code=404, text='Entity invalid.entity not found')++ with self.assertRaises(ValueError) as context:+ client.set_state('invalid.entity', 'on')++ error_message = str(context.exception)+ self.assertIn('invalid.entity', error_message)+ self.assertIn('404', error_message)+ self.assertIn('not found', error_message)+ # Verify error provides actionable information+```++### Testing Best Practices Summary++1. **Mock at system boundaries only** (HTTP calls, database, external services)+2. **Test return values and state changes**, not mock call parameters+3. **Use real data through real code paths** when possible+4. **Test error messages provide useful context** for debugging+5. **Focus on interface contracts**, not implementation details+6. **Create focused tests** that test one behavior well+7. **Test meaningful edge cases** that affect business logic+8. **Verify data transformations** work correctly end-to-end+### Django-Specific Testing Patterns```pythondiff --git a/src/hi/apps/config/settings_manager.py b/src/hi/apps/config/settings_manager.pyindex b9fb3f3b..41853f5f 100644--- a/src/hi/apps/config/settings_manager.py+++ b/src/hi/apps/config/settings_manager.py@@ -43,11 +43,16 @@ class SettingsManager( Singleton ):with self._attributes_lock:self._attribute_value_map = dict()for subsystem in self._subsystem_list:- subsystem.refresh_from_db()- for subsystem_attribute in subsystem.attributes.all():- attr_type = subsystem_attribute.setting_key- self._attribute_value_map[attr_type] = subsystem_attribute.value- continue+ try:+ subsystem.refresh_from_db()+ for subsystem_attribute in subsystem.attributes.all():+ attr_type = subsystem_attribute.setting_key+ self._attribute_value_map[attr_type] = subsystem_attribute.value+ continue+ except Subsystem.DoesNotExist:+ # Log error - this should not normally happen outside of test teardown+ logger.error(f'Subsystem {subsystem} no longer exists in database during reload. '+ 'This may indicate a configuration issue or test teardown problem.')continueself._notify_change_listeners()diff --git a/src/hi/integrations/managers.py b/src/hi/integrations/managers.pyindex e56d1074..5dd6b95f 100644--- a/src/hi/integrations/managers.py+++ b/src/hi/integrations/managers.py@@ -13,6 +13,9 @@ class IntegrationDetailsManager(models.Manager):integration_name = integration_key.integration_name )def filter_by_integration_keys( self, integration_keys : Sequence[ IntegrationKey ] ):+ if not integration_keys:+ return self.none()+query = Q()for integration_key in integration_keys:query |= Q( integration_id = integration_key.integration_id,diff --git a/src/hi/integrations/tests/test_integration_manager.py b/src/hi/integrations/tests/test_integration_manager.pynew file mode 100644index 00000000..8e9abe73--- /dev/null+++ b/src/hi/integrations/tests/test_integration_manager.py@@ -0,0 +1,748 @@+"""+Unit tests for IntegrationManager.+"""++import asyncio+import threading+from unittest.mock import Mock, AsyncMock, patch+from django.test import TestCase++from hi.apps.attribute.enums import AttributeType, AttributeValueType++from hi.integrations.integration_manager import IntegrationManager+from hi.integrations.integration_data import IntegrationData+from hi.integrations.integration_gateway import IntegrationGateway+from hi.integrations.models import Integration, IntegrationAttribute+from hi.integrations.transient_models import IntegrationMetaData, IntegrationKey+from hi.integrations.enums import IntegrationAttributeType+++class MockIntegrationAttributeType(IntegrationAttributeType):+ """Mock integration attribute type for testing."""++ TEST_ATTR = ('Test Attribute', 'Test description', AttributeValueType.TEXT, {}, True, True, 'default')+++class MockIntegrationGateway(IntegrationGateway):+ """Mock integration gateway for testing."""++ def __init__(self, integration_id='test_integration', label='Test Integration'):+ self.integration_id = integration_id+ self.label = label++ def get_metadata(self):+ return IntegrationMetaData(+ integration_id=self.integration_id,+ label=self.label,+ attribute_type=MockIntegrationAttributeType,+ allow_entity_deletion=True+ )++ def get_manage_view_pane(self):+ return Mock()++ def get_monitor(self):+ return Mock()++ def get_controller(self):+ return Mock()+++class IntegrationManagerTestCase(TestCase):+ """Test cases for IntegrationManager singleton behavior and core functionality."""++ def setUp(self):+ """Set up test data."""+ # Clear any existing singleton instance for clean tests+ IntegrationManager._instances = {}+ IntegrationManager._initialized_instance = None++ def test_singleton_pattern_behavior(self):+ """Test that IntegrationManager implements singleton pattern correctly."""+ manager1 = IntegrationManager()+ manager2 = IntegrationManager()++ # Verify same instance returned+ self.assertIs(manager1, manager2)++ # Verify singleton state is shared+ manager1._test_attribute = 'test_value'+ self.assertEqual(manager2._test_attribute, 'test_value')++ # Verify initialization state (should be False for new instances in test)+ # Note: _initialized may be True if singleton was used elsewhere+ # The key test is that both managers are the same instance+ self.assertEqual(manager1._initialized, manager2._initialized)++ def test_singleton_thread_safety(self):+ """Test that singleton creation is thread-safe."""+ managers = []+ results = []++ def create_manager():+ try:+ manager = IntegrationManager()+ managers.append(manager)+ results.append('success')+ except Exception as e:+ results.append(f'error: {e}')++ # Create multiple threads that create manager instances+ threads = [threading.Thread(target=create_manager) for _ in range(10)]++ for thread in threads:+ thread.start()++ for thread in threads:+ thread.join()++ # Verify all threads succeeded+ self.assertEqual(len(results), 10)+ self.assertTrue(all(result == 'success' for result in results))++ # Verify all managers are the same instance+ self.assertEqual(len(set(id(manager) for manager in managers)), 1)+ self.assertTrue(all(manager is managers[0] for manager in managers))++ def test_integration_data_list_sorting_and_filtering(self):+ """Test get_integration_data_list with sorting and enabled filtering."""+ manager = IntegrationManager()++ # Create mock integration data with different labels and enabled states+ integration1 = Integration.objects.create(+ integration_id='zebra_integration',+ is_enabled=True+ )+ integration2 = Integration.objects.create(+ integration_id='alpha_integration',+ is_enabled=False+ )+ integration3 = Integration.objects.create(+ integration_id='beta_integration',+ is_enabled=True+ )++ data1 = IntegrationData(+ integration_gateway=MockIntegrationGateway('zebra_integration', 'Zebra Service'),+ integration=integration1+ )+ data2 = IntegrationData(+ integration_gateway=MockIntegrationGateway('alpha_integration', 'Alpha Service'),+ integration=integration2+ )+ data3 = IntegrationData(+ integration_gateway=MockIntegrationGateway('beta_integration', 'Beta Service'),+ integration=integration3+ )++ manager._integration_data_map = {+ 'zebra_integration': data1,+ 'alpha_integration': data2,+ 'beta_integration': data3+ }++ # Test all integrations - should be sorted by label+ all_integrations = manager.get_integration_data_list(enabled_only=False)+ self.assertEqual(len(all_integrations), 3)+ self.assertEqual([data.integration_id for data in all_integrations],+ ['alpha_integration', 'beta_integration', 'zebra_integration'])++ # Test enabled only - should only include enabled, sorted by label+ enabled_integrations = manager.get_integration_data_list(enabled_only=True)+ self.assertEqual(len(enabled_integrations), 2)+ self.assertEqual([data.integration_id for data in enabled_integrations],+ ['beta_integration', 'zebra_integration'])++ def test_get_default_integration_data(self):+ """Test default integration selection logic."""+ manager = IntegrationManager()++ # Test with no integrations+ result = manager.get_default_integration_data()+ self.assertIsNone(result)++ # Test with disabled integrations only+ disabled_integration = Integration.objects.create(+ integration_id='disabled_integration',+ is_enabled=False+ )+ disabled_data = IntegrationData(+ integration_gateway=MockIntegrationGateway('disabled_integration', 'Disabled'),+ integration=disabled_integration+ )+ manager._integration_data_map = {'disabled_integration': disabled_data}++ result = manager.get_default_integration_data()+ self.assertIsNone(result)++ # Test with enabled integrations - should return first alphabetically+ enabled_integration1 = Integration.objects.create(+ integration_id='zebra_integration',+ is_enabled=True+ )+ enabled_integration2 = Integration.objects.create(+ integration_id='alpha_integration',+ is_enabled=True+ )++ enabled_data1 = IntegrationData(+ integration_gateway=MockIntegrationGateway('zebra_integration', 'Zebra'),+ integration=enabled_integration1+ )+ enabled_data2 = IntegrationData(+ integration_gateway=MockIntegrationGateway('alpha_integration', 'Alpha'),+ integration=enabled_integration2+ )++ manager._integration_data_map.update({+ 'zebra_integration': enabled_data1,+ 'alpha_integration': enabled_data2+ })++ result = manager.get_default_integration_data()+ self.assertEqual(result.integration_id, 'alpha_integration')++ def test_get_integration_data_success_and_error(self):+ """Test integration data retrieval by ID."""+ manager = IntegrationManager()++ integration = Integration.objects.create(+ integration_id='test_integration',+ is_enabled=True+ )+ data = IntegrationData(+ integration_gateway=MockIntegrationGateway('test_integration'),+ integration=integration+ )+ manager._integration_data_map = {'test_integration': data}++ # Test successful retrieval+ result = manager.get_integration_data('test_integration')+ self.assertEqual(result, data)+ self.assertEqual(result.integration_id, 'test_integration')++ # Test error for unknown integration+ with self.assertRaises(KeyError) as context:+ manager.get_integration_data('unknown_integration')++ error_message = str(context.exception)+ self.assertIn('Unknown integration id "unknown_integration"', error_message)++ def test_get_integration_gateway_success_and_error(self):+ """Test integration gateway retrieval by ID."""+ manager = IntegrationManager()++ gateway = MockIntegrationGateway('test_integration')+ integration = Integration.objects.create(+ integration_id='test_integration',+ is_enabled=True+ )+ data = IntegrationData(+ integration_gateway=gateway,+ integration=integration+ )+ manager._integration_data_map = {'test_integration': data}++ # Test successful retrieval+ result = manager.get_integration_gateway('test_integration')+ self.assertEqual(result, gateway)++ # Test error for unknown integration+ with self.assertRaises(KeyError) as context:+ manager.get_integration_gateway('unknown_integration')++ error_message = str(context.exception)+ self.assertIn('Unknown integration id "unknown_integration"', error_message)++ def test_refresh_integrations_from_db(self):+ """Test database refresh for all integration models."""+ manager = IntegrationManager()++ # Create integrations and modify them outside the data objects+ integration1 = Integration.objects.create(+ integration_id='test_integration_1',+ is_enabled=False+ )+ integration2 = Integration.objects.create(+ integration_id='test_integration_2',+ is_enabled=False+ )++ data1 = IntegrationData(+ integration_gateway=MockIntegrationGateway('test_integration_1'),+ integration=integration1+ )+ data2 = IntegrationData(+ integration_gateway=MockIntegrationGateway('test_integration_2'),+ integration=integration2+ )++ manager._integration_data_map = {+ 'test_integration_1': data1,+ 'test_integration_2': data2+ }++ # Modify database directly (simulating external change)+ Integration.objects.filter(integration_id='test_integration_1').update(is_enabled=True)+ Integration.objects.filter(integration_id='test_integration_2').update(is_enabled=True)++ # Verify objects in memory still show old values+ self.assertFalse(data1.integration.is_enabled)+ self.assertFalse(data2.integration.is_enabled)++ # Call refresh and verify updates+ manager.refresh_integrations_from_db()++ self.assertTrue(data1.integration.is_enabled)+ self.assertTrue(data2.integration.is_enabled)++ @patch('hi.integrations.integration_manager.apps.get_app_configs')+ @patch('hi.integrations.integration_manager.import_module_safe')+ def test_discover_defined_integrations(self, mock_import, mock_get_apps):+ """Test auto-discovery of integration gateways in services modules."""+ manager = IntegrationManager()++ # Mock app configs+ mock_app1 = Mock()+ mock_app1.name = 'hi.services.test_service'+ mock_app2 = Mock()+ mock_app2.name = 'hi.other.module' # Should be skipped+ mock_app3 = Mock()+ mock_app3.name = 'hi.services.another_service'++ mock_get_apps.return_value = [mock_app1, mock_app2, mock_app3]++ # Mock integration modules+ mock_gateway_class1 = type('TestGateway1', (IntegrationGateway,), {+ 'get_metadata': lambda self: IntegrationMetaData(+ integration_id='test_service',+ label='Test Service',+ attribute_type=MockIntegrationAttributeType,+ allow_entity_deletion=True+ )+ })++ mock_gateway_class2 = type('TestGateway2', (IntegrationGateway,), {+ 'get_metadata': lambda self: IntegrationMetaData(+ integration_id='another_service',+ label='Another Service',+ attribute_type=MockIntegrationAttributeType,+ allow_entity_deletion=True+ )+ })++ mock_module1 = Mock()+ mock_module1.__dir__ = lambda self: ['TestGateway1', 'other_class', 'IntegrationGateway']+ mock_module1.TestGateway1 = mock_gateway_class1+ mock_module1.other_class = str # Should be ignored+ mock_module1.IntegrationGateway = IntegrationGateway # Should be ignored (base class)++ mock_module2 = Mock()+ mock_module2.__dir__ = lambda self: ['TestGateway2']+ mock_module2.TestGateway2 = mock_gateway_class2++ def mock_import_side_effect(module_name):+ if module_name == 'hi.services.test_service.integration':+ return mock_module1+ elif module_name == 'hi.services.another_service.integration':+ return mock_module2+ return None++ mock_import.side_effect = mock_import_side_effect++ # Execute discovery+ result = manager._discover_defined_integrations()++ # Verify correct modules were imported+ expected_module_names = [+ 'hi.services.test_service.integration',+ 'hi.services.another_service.integration'+ ]+ # Extract module names from call_args_list+ # The function is called with keyword argument 'module_name'+ actual_calls = [call.kwargs['module_name'] for call in mock_import.call_args_list]++ self.assertEqual(set(actual_calls), set(expected_module_names))++ # Verify correct gateways were discovered+ self.assertEqual(len(result), 2)+ self.assertIn('test_service', result)+ self.assertIn('another_service', result)++ # Verify gateway instances were created correctly+ self.assertIsInstance(result['test_service'], mock_gateway_class1)+ self.assertIsInstance(result['another_service'], mock_gateway_class2)++ def test_load_existing_integrations(self):+ """Test loading existing integrations from database."""+ manager = IntegrationManager()++ # Create test integrations+ integration1 = Integration.objects.create(+ integration_id='existing_integration_1',+ is_enabled=True+ )+ integration2 = Integration.objects.create(+ integration_id='existing_integration_2',+ is_enabled=False+ )++ result = manager._load_existing_integrations()++ # Verify correct mapping+ self.assertEqual(len(result), 2)+ self.assertEqual(result['existing_integration_1'], integration1)+ self.assertEqual(result['existing_integration_2'], integration2)++ # Verify return type is dict with integration_id as key+ self.assertIsInstance(result, dict)+ self.assertEqual(set(result.keys()), {'existing_integration_1', 'existing_integration_2'})++ def test_thread_safety_with_data_lock(self):+ """Test that data operations are thread-safe using _data_lock."""+ manager = IntegrationManager()++ # Clear any existing data to start clean+ manager._integration_data_map.clear()++ results = []+ errors = []++ def concurrent_operation():+ try:+ # Simulate operations that would use _data_lock+ with manager._data_lock:+ # Simulate some data modification+ current_count = len(manager._integration_data_map)+ # Add artificial delay to increase chance of race condition+ import time+ time.sleep(0.001)+ manager._integration_data_map[f'test_{current_count}'] = f'data_{current_count}'+ results.append(len(manager._integration_data_map))+ except Exception as e:+ errors.append(str(e))++ # Run multiple concurrent operations+ threads = [threading.Thread(target=concurrent_operation) for _ in range(10)]++ for thread in threads:+ thread.start()++ for thread in threads:+ thread.join()++ # Verify no errors occurred+ self.assertEqual(len(errors), 0, f"Errors occurred: {errors}")++ # Verify all operations completed+ self.assertEqual(len(results), 10)++ # Verify final state is consistent (10 items added)+ self.assertEqual(len(manager._integration_data_map), 10)++ def test_initialization_flag_prevents_double_initialization(self):+ """Test that _initialized flag prevents multiple initialization."""+ manager = IntegrationManager()++ # Verify initial state+ self.assertFalse(manager._initialized)+ self.assertIsNone(manager._monitor_event_loop)++ # Mock event loop+ mock_event_loop = Mock()++ # Set up patches for async methods called during initialization+ with patch.object(manager, '_load_integration_data', new=AsyncMock()) as mock_load, \+ patch.object(manager, '_start_all_integration_monitors', new=AsyncMock()) as mock_start_monitors:++ async def test_initialization():+ # First initialization+ await manager.initialize(mock_event_loop)++ # Verify initialization happened+ self.assertTrue(manager._initialized)+ self.assertEqual(manager._monitor_event_loop, mock_event_loop)++ # Reset mocks+ mock_load.reset_mock()+ mock_start_monitors.reset_mock()++ # Second initialization attempt+ await manager.initialize(mock_event_loop)++ # Verify methods were not called again+ mock_load.assert_not_called()+ mock_start_monitors.assert_not_called()++ # Run the test+ asyncio.run(test_initialization())++ def test_ensure_all_attributes_exist_new_attributes(self):+ """Test creation of new integration attributes when they don't exist."""+ manager = IntegrationManager()++ # Create integration+ integration = Integration.objects.create(+ integration_id='test_integration',+ is_enabled=True+ )++ # Create metadata with attribute types+ metadata = IntegrationMetaData(+ integration_id='test_integration',+ label='Test Integration',+ attribute_type=MockIntegrationAttributeType,+ allow_entity_deletion=True+ )++ # Verify no attributes exist initially+ self.assertEqual(integration.attributes.count(), 0)++ # Call method to ensure attributes exist+ manager._ensure_all_attributes_exist(metadata, integration)++ # Verify attribute was created+ self.assertEqual(integration.attributes.count(), 1)++ created_attr = integration.attributes.first()+ self.assertEqual(created_attr.name, 'Test Attribute')+ self.assertEqual(created_attr.value, 'default')+ self.assertEqual(created_attr.value_type_str, str(AttributeValueType.TEXT))+ self.assertTrue(created_attr.is_editable)+ self.assertTrue(created_attr.is_required)++ # Verify integration key format+ expected_key = f'test_integration.{str(MockIntegrationAttributeType.TEST_ATTR).lower()}'+ self.assertEqual(created_attr.integration_key_str, expected_key)++ def test_ensure_all_attributes_exist_no_duplicates(self):+ """Test that existing attributes are not duplicated."""+ manager = IntegrationManager()++ integration = Integration.objects.create(+ integration_id='test_integration',+ is_enabled=True+ )++ # Create existing attribute+ existing_key = IntegrationKey(+ integration_id='test_integration',+ integration_name=str(MockIntegrationAttributeType.TEST_ATTR)+ )+ IntegrationAttribute.objects.create(+ integration=integration,+ name='Existing Attribute',+ value='existing_value',+ value_type_str=str(AttributeValueType.TEXT),+ integration_key_str=str(existing_key),+ attribute_type_str=AttributeType.PREDEFINED+ )++ # Verify one attribute exists+ self.assertEqual(integration.attributes.count(), 1)++ # Create metadata+ metadata = IntegrationMetaData(+ integration_id='test_integration',+ label='Test Integration',+ attribute_type=MockIntegrationAttributeType,+ allow_entity_deletion=True+ )++ # Call method+ manager._ensure_all_attributes_exist(metadata, integration)++ # Verify no new attributes were created+ self.assertEqual(integration.attributes.count(), 1)++ # Verify existing attribute was not modified+ attr = integration.attributes.first()+ self.assertEqual(attr.name, 'Existing Attribute')+ self.assertEqual(attr.value, 'existing_value')++ def test_create_integration_attribute(self):+ """Test creation of individual integration attribute."""+ manager = IntegrationManager()++ integration = Integration.objects.create(+ integration_id='test_integration',+ is_enabled=True+ )++ # Call method+ manager._create_integration_attribute(+ integration=integration,+ attribute_type=MockIntegrationAttributeType.TEST_ATTR+ )++ # Verify attribute was created correctly+ self.assertEqual(integration.attributes.count(), 1)++ attr = integration.attributes.first()+ self.assertEqual(attr.integration, integration)+ self.assertEqual(attr.name, 'Test Attribute')+ self.assertEqual(attr.value, 'default')+ self.assertEqual(attr.value_type_str, str(AttributeValueType.TEXT))+ self.assertEqual(attr.attribute_type_str, str(AttributeType.PREDEFINED))+ self.assertTrue(attr.is_editable)+ self.assertTrue(attr.is_required)++ # Verify integration key format+ expected_key = f'test_integration.{str(MockIntegrationAttributeType.TEST_ATTR).lower()}'+ self.assertEqual(attr.integration_key_str, expected_key)++ # Verify value_range_str is JSON+ import json+ self.assertEqual(json.loads(attr.value_range_str), {})++ def test_enable_integration_database_transaction(self):+ """Test enable integration with database transaction and monitor launch."""+ manager = IntegrationManager()++ integration = Integration.objects.create(+ integration_id='test_integration',+ is_enabled=False+ )++ gateway = MockIntegrationGateway('test_integration')+ data = IntegrationData(+ integration_gateway=gateway,+ integration=integration+ )++ # Mock formset+ mock_formset = Mock()++ with patch.object(manager, '_launch_integration_monitor_task') as mock_launch:+ # Call enable+ manager.enable_integration(data, mock_formset)++ # Verify database changes+ integration.refresh_from_db()+ self.assertTrue(integration.is_enabled)++ # Verify formset was saved+ mock_formset.save.assert_called_once()++ # Verify monitor was launched+ mock_launch.assert_called_once_with(integration_data=data)++ def test_disable_integration_database_transaction(self):+ """Test disable integration with database transaction and monitor stop."""+ manager = IntegrationManager()++ integration = Integration.objects.create(+ integration_id='test_integration',+ is_enabled=True+ )++ gateway = MockIntegrationGateway('test_integration')+ data = IntegrationData(+ integration_gateway=gateway,+ integration=integration+ )++ with patch.object(manager, '_stop_integration_monitor') as mock_stop:+ # Call disable+ manager.disable_integration(data)++ # Verify database changes+ integration.refresh_from_db()+ self.assertFalse(integration.is_enabled)++ # Verify monitor was stopped+ mock_stop.assert_called_once_with(integration_data=data)++ def test_data_lock_thread_safety_during_attribute_creation(self):+ """Test thread safety of attribute creation operations."""+ # Note: This test verifies the presence of thread safety mechanisms+ # Full concurrency testing is difficult with SQLite's table locking+ manager = IntegrationManager()++ integration = Integration.objects.create(+ integration_id='test_integration',+ is_enabled=True+ )++ metadata = IntegrationMetaData(+ integration_id='test_integration',+ label='Test Integration',+ attribute_type=MockIntegrationAttributeType,+ allow_entity_deletion=True+ )++ # Verify the method uses the data lock+ with patch.object(manager, '_data_lock') as mock_lock:+ manager._ensure_all_attributes_exist(metadata, integration)++ # Verify the lock was used as a context manager+ mock_lock.__enter__.assert_called_once()+ mock_lock.__exit__.assert_called_once()++ # Verify attribute was created+ self.assertEqual(integration.attributes.count(), 1)++ @patch('hi.integrations.integration_manager.logger')+ def test_discover_defined_integrations_error_handling(self, mock_logger):+ """Test error handling during integration discovery."""+ manager = IntegrationManager()++ # Mock app configs+ mock_app = Mock()+ mock_app.name = 'hi.services.failing_service'++ with patch('hi.integrations.integration_manager.apps.get_app_configs', return_value=[mock_app]), \+ patch('hi.integrations.integration_manager.import_module_safe', side_effect=Exception("Import failed")):++ # Execute discovery+ result = manager._discover_defined_integrations()++ # Verify empty result when import fails+ self.assertEqual(result, {})++ # Verify error was logged+ mock_logger.exception.assert_called_once()+ call_args = mock_logger.exception.call_args[0]+ self.assertIn('Problem getting integration gateway', call_args[0])+ self.assertIn('hi.services.failing_service.integration', call_args[0])++ def test_monitor_management_methods(self):+ """Test monitor start/stop management methods."""+ manager = IntegrationManager()++ integration = Integration.objects.create(+ integration_id='test_integration',+ is_enabled=True+ )++ gateway = MockIntegrationGateway('test_integration')+ data = IntegrationData(+ integration_gateway=gateway,+ integration=integration+ )++ # Test stopping non-existent monitor+ manager._stop_integration_monitor(data) # Should not raise error++ # Test with monitor in map+ mock_monitor = Mock()+ mock_monitor.is_running = True+ manager._monitor_map['test_integration'] = mock_monitor++ # Test stopping existing monitor+ manager._stop_integration_monitor(data)++ # Verify monitor was stopped and removed+ mock_monitor.stop.assert_called_once()+ self.assertNotIn('test_integration', manager._monitor_map)++ # Test stopping already stopped monitor+ mock_monitor2 = Mock()+ mock_monitor2.is_running = False+ manager._monitor_map['test_integration'] = mock_monitor2++ manager._stop_integration_monitor(data)++ # Verify stop was not called on already stopped monitor+ mock_monitor2.stop.assert_not_called()+ self.assertNotIn('test_integration', manager._monitor_map)diff --git a/src/hi/integrations/tests/test_managers.py b/src/hi/integrations/tests/test_managers.pynew file mode 100644index 00000000..dff40351--- /dev/null+++ b/src/hi/integrations/tests/test_managers.py@@ -0,0 +1,354 @@+"""+Unit tests for IntegrationDetailsManager.+"""++from django.test import TransactionTestCase+from django.db import models, connection++from hi.integrations.managers import IntegrationDetailsManager+from hi.integrations.models import IntegrationDetailsModel+from hi.integrations.transient_models import IntegrationKey+++class ManagerTestModel(IntegrationDetailsModel):+ """Concrete test model for testing IntegrationDetailsManager."""++ name = models.CharField(max_length=64, default='test')++ class Meta:+ app_label = 'integrations'+++class IntegrationDetailsManagerTestCase(TransactionTestCase):+ """Test cases for IntegrationDetailsManager functionality."""++ def setUp(self):+ """Set up test data by creating table and test instances."""+ # Create table manually for test model+ with connection.schema_editor() as schema_editor:+ schema_editor.create_model(ManagerTestModel)++ # Create test instances with different integration keys+ self.model1 = ManagerTestModel.objects.create(+ name='Test Model 1',+ integration_id='home_assistant',+ integration_name='light_bedroom'+ )++ self.model2 = ManagerTestModel.objects.create(+ name='Test Model 2',+ integration_id='home_assistant',+ integration_name='switch_kitchen'+ )++ self.model3 = ManagerTestModel.objects.create(+ name='Test Model 3',+ integration_id='zoneminder',+ integration_name='camera_front_door'+ )++ self.model4 = ManagerTestModel.objects.create(+ name='Test Model 4',+ integration_id='zoneminder',+ integration_name='camera_back_yard'+ )++ # Create model without integration (user-created)+ self.model_no_integration = ManagerTestModel.objects.create(+ name='User Created Model',+ integration_id=None,+ integration_name=None+ )++ def tearDown(self):+ """Clean up test table."""+ with connection.schema_editor() as schema_editor:+ schema_editor.delete_model(ManagerTestModel)++ def test_filter_by_integration_key_exact_match(self):+ """Test filter_by_integration_key with exact key matches."""+ # Test home_assistant light+ ha_light_key = IntegrationKey('home_assistant', 'light_bedroom')+ result = ManagerTestModel.objects.filter_by_integration_key(ha_light_key)++ self.assertEqual(result.count(), 1)+ self.assertEqual(result.first(), self.model1)+ self.assertEqual(result.first().name, 'Test Model 1')++ # Test zoneminder camera+ zm_camera_key = IntegrationKey('zoneminder', 'camera_front_door')+ result = ManagerTestModel.objects.filter_by_integration_key(zm_camera_key)++ self.assertEqual(result.count(), 1)+ self.assertEqual(result.first(), self.model3)+ self.assertEqual(result.first().name, 'Test Model 3')++ def test_filter_by_integration_key_no_matches(self):+ """Test filter_by_integration_key with no matching results."""+ # Test non-existent integration+ nonexistent_key = IntegrationKey('nonexistent_integration', 'device_name')+ result = ManagerTestModel.objects.filter_by_integration_key(nonexistent_key)++ self.assertEqual(result.count(), 0)++ # Test existing integration with non-existent device+ partial_key = IntegrationKey('home_assistant', 'nonexistent_device')+ result = ManagerTestModel.objects.filter_by_integration_key(partial_key)++ self.assertEqual(result.count(), 0)++ def test_filter_by_integration_key_case_sensitivity(self):+ """Test filter_by_integration_key case sensitivity behavior."""+ # Create key with different case+ # Note: IntegrationKey lowercases values in __post_init__, so this tests the database query+ different_case_key = IntegrationKey('HOME_ASSISTANT', 'LIGHT_BEDROOM')++ # Should match because IntegrationKey normalizes to lowercase+ result = ManagerTestModel.objects.filter_by_integration_key(different_case_key)++ self.assertEqual(result.count(), 1)+ self.assertEqual(result.first(), self.model1)++ def test_filter_entities_without_integration(self):+ """Test filtering entities that have no integration data."""+ # Query directly for entities without integration data+ result = ManagerTestModel.objects.filter(+ integration_id=None,+ integration_name=None+ )++ # Should match the model without integration+ self.assertEqual(result.count(), 1)+ self.assertEqual(result.first(), self.model_no_integration)++ def test_filter_by_integration_keys_multiple_keys(self):+ """Test filter_by_integration_keys with multiple keys."""+ # Create multiple keys+ key1 = IntegrationKey('home_assistant', 'light_bedroom')+ key2 = IntegrationKey('zoneminder', 'camera_front_door')+ key3 = IntegrationKey('nonexistent', 'device') # This won't match anything++ keys = [key1, key2, key3]+ result = ManagerTestModel.objects.filter_by_integration_keys(keys)++ # Should match model1 and model3+ self.assertEqual(result.count(), 2)+ result_names = {model.name for model in result}+ self.assertEqual(result_names, {'Test Model 1', 'Test Model 3'})++ def test_filter_by_integration_keys_empty_list(self):+ """Test filter_by_integration_keys with empty key list."""+ result = ManagerTestModel.objects.filter_by_integration_keys([])++ # Empty list should return no results+ self.assertEqual(result.count(), 0)++ def test_filter_by_integration_keys_single_key(self):+ """Test filter_by_integration_keys with single key (equivalent to filter_by_integration_key)."""+ key = IntegrationKey('home_assistant', 'switch_kitchen')+ result = ManagerTestModel.objects.filter_by_integration_keys([key])++ # Should match model2+ self.assertEqual(result.count(), 1)+ self.assertEqual(result.first(), self.model2)+ self.assertEqual(result.first().name, 'Test Model 2')++ def test_filter_by_integration_keys_duplicate_keys(self):+ """Test filter_by_integration_keys with duplicate keys."""+ key = IntegrationKey('home_assistant', 'light_bedroom')+ duplicate_keys = [key, key, key] # Same key multiple times++ result = ManagerTestModel.objects.filter_by_integration_keys(duplicate_keys)++ # Should still return only one result (no duplicates)+ self.assertEqual(result.count(), 1)+ self.assertEqual(result.first(), self.model1)++ def test_filter_by_integration_keys_all_same_integration(self):+ """Test filter_by_integration_keys with multiple devices from same integration."""+ key1 = IntegrationKey('home_assistant', 'light_bedroom')+ key2 = IntegrationKey('home_assistant', 'switch_kitchen')++ result = ManagerTestModel.objects.filter_by_integration_keys([key1, key2])++ # Should match both home_assistant models+ self.assertEqual(result.count(), 2)+ result_names = {model.name for model in result}+ self.assertEqual(result_names, {'Test Model 1', 'Test Model 2'})++ def test_filter_by_integration_keys_mixed_integrations(self):+ """Test filter_by_integration_keys with keys from different integrations."""+ ha_key = IntegrationKey('home_assistant', 'light_bedroom')+ zm_key1 = IntegrationKey('zoneminder', 'camera_front_door')+ zm_key2 = IntegrationKey('zoneminder', 'camera_back_yard')++ result = ManagerTestModel.objects.filter_by_integration_keys([ha_key, zm_key1, zm_key2])++ # Should match model1, model3, and model4+ self.assertEqual(result.count(), 3)+ result_names = {model.name for model in result}+ self.assertEqual(result_names, {'Test Model 1', 'Test Model 3', 'Test Model 4'})++ def test_manager_query_chaining(self):+ """Test that manager methods can be chained with other queryset operations."""+ # Test chaining with additional filters+ key = IntegrationKey('home_assistant', 'light_bedroom')+ result = ManagerTestModel.objects.filter_by_integration_key(key).filter(name__contains='Model 1')++ self.assertEqual(result.count(), 1)+ self.assertEqual(result.first(), self.model1)++ # Test chaining with exclude+ keys = [+ IntegrationKey('home_assistant', 'light_bedroom'),+ IntegrationKey('home_assistant', 'switch_kitchen')+ ]+ result = ManagerTestModel.objects.filter_by_integration_keys(keys).exclude(name__contains='Test Model 1')++ self.assertEqual(result.count(), 1)+ self.assertEqual(result.first(), self.model2)++ def test_manager_query_ordering(self):+ """Test that manager methods work with ordering."""+ keys = [+ IntegrationKey('zoneminder', 'camera_front_door'),+ IntegrationKey('zoneminder', 'camera_back_yard')+ ]++ # Test ordering by name+ result_asc = ManagerTestModel.objects.filter_by_integration_keys(keys).order_by('name')+ result_desc = ManagerTestModel.objects.filter_by_integration_keys(keys).order_by('-name')++ self.assertEqual(result_asc.count(), 2)+ self.assertEqual(result_desc.count(), 2)++ # Verify ordering+ asc_names = [model.name for model in result_asc]+ desc_names = [model.name for model in result_desc]++ self.assertEqual(asc_names, ['Test Model 3', 'Test Model 4'])+ self.assertEqual(desc_names, ['Test Model 4', 'Test Model 3'])++ def test_manager_integration_key_query_performance(self):+ """Test that manager methods generate efficient queries."""+ # This test verifies that the manager methods use proper query structure++ key = IntegrationKey('home_assistant', 'light_bedroom')+ queryset = ManagerTestModel.objects.filter_by_integration_key(key)++ # Verify the queryset generates correct SQL (basic check)+ sql = str(queryset.query)++ # Should use AND to combine integration_id and integration_name filters+ self.assertIn('integration_id', sql)+ self.assertIn('integration_name', sql)+ self.assertIn('AND', sql.upper())++ def test_manager_multiple_keys_query_structure(self):+ """Test that filter_by_integration_keys generates correct OR query structure."""+ keys = [+ IntegrationKey('home_assistant', 'light_bedroom'),+ IntegrationKey('zoneminder', 'camera_front_door')+ ]++ queryset = ManagerTestModel.objects.filter_by_integration_keys(keys)+ sql = str(queryset.query)++ # Should use OR to combine different integration key filters+ self.assertIn('OR', sql.upper())+ self.assertIn('integration_id', sql)+ self.assertIn('integration_name', sql)++ def test_manager_with_values_and_annotations(self):+ """Test that manager methods work with values() and annotations."""+ keys = [+ IntegrationKey('home_assistant', 'light_bedroom'),+ IntegrationKey('home_assistant', 'switch_kitchen')+ ]++ # Test with values()+ result = ManagerTestModel.objects.filter_by_integration_keys(keys).values('name', 'integration_id')++ self.assertEqual(len(result), 2)+ names = {item['name'] for item in result}+ self.assertEqual(names, {'Test Model 1', 'Test Model 2'})++ # Verify all have same integration_id+ integration_ids = {item['integration_id'] for item in result}+ self.assertEqual(integration_ids, {'home_assistant'})++ def test_manager_with_complex_filter_combinations(self):+ """Test manager methods with complex filter combinations."""+ # Create additional test data+ ManagerTestModel.objects.create(+ name='Extra Model',+ integration_id='home_assistant',+ integration_name='light_bedroom' # Same key as model1+ )++ key = IntegrationKey('home_assistant', 'light_bedroom')++ # Test that multiple objects with same integration key are returned+ result = ManagerTestModel.objects.filter_by_integration_key(key)++ self.assertEqual(result.count(), 2) # model1 and extra_model+ result_names = {model.name for model in result}+ self.assertEqual(result_names, {'Test Model 1', 'Extra Model'})++ # Test filtering further+ filtered_result = ManagerTestModel.objects.filter_by_integration_key(key).filter(name__contains='Extra')++ self.assertEqual(filtered_result.count(), 1)+ self.assertEqual(filtered_result.first().name, 'Extra Model')++ def test_manager_inheritance_and_usage(self):+ """Test that IntegrationDetailsManager is properly inherited and used."""+ # Verify that ManagerTestModel uses IntegrationDetailsManager+ self.assertIsInstance(ManagerTestModel.objects, IntegrationDetailsManager)++ # Verify that manager methods exist and are callable+ self.assertTrue(hasattr(ManagerTestModel.objects, 'filter_by_integration_key'))+ self.assertTrue(hasattr(ManagerTestModel.objects, 'filter_by_integration_keys'))++ # Verify methods are callable+ self.assertTrue(callable(ManagerTestModel.objects.filter_by_integration_key))+ self.assertTrue(callable(ManagerTestModel.objects.filter_by_integration_keys))++ def test_manager_with_special_characters_in_keys(self):+ """Test manager methods with special characters in integration keys."""+ # Create model with special characters+ special_model = ManagerTestModel.objects.create(+ name='Special Model',+ integration_id='integration-with-dashes',+ integration_name='device_with_underscores-and-dashes'+ )++ # Test filtering with special character key+ special_key = IntegrationKey('integration-with-dashes', 'device_with_underscores-and-dashes')+ result = ManagerTestModel.objects.filter_by_integration_key(special_key)++ self.assertEqual(result.count(), 1)+ self.assertEqual(result.first(), special_model)+ self.assertEqual(result.first().name, 'Special Model')++ def test_manager_queryset_methods_return_types(self):+ """Test that manager methods return correct QuerySet types."""+ key = IntegrationKey('home_assistant', 'light_bedroom')+ keys = [key]++ # Test return types+ single_result = ManagerTestModel.objects.filter_by_integration_key(key)+ multiple_result = ManagerTestModel.objects.filter_by_integration_keys(keys)++ # Both should return QuerySet instances+ self.assertEqual(type(single_result).__name__, 'QuerySet')+ self.assertEqual(type(multiple_result).__name__, 'QuerySet')++ # Should be able to evaluate to lists+ single_list = list(single_result)+ multiple_list = list(multiple_result)++ self.assertIsInstance(single_list, list)+ self.assertIsInstance(multiple_list, list)+ self.assertEqual(len(single_list), 1)+ self.assertEqual(len(multiple_list), 1)diff --git a/src/hi/integrations/tests/test_models.py b/src/hi/integrations/tests/test_models.pynew file mode 100644index 00000000..8887d076--- /dev/null+++ b/src/hi/integrations/tests/test_models.py@@ -0,0 +1,618 @@+"""+Unit tests for Integration models.+"""++from django.test import TestCase, TransactionTestCase+from django.db import IntegrityError, transaction, models++from hi.apps.attribute.enums import AttributeType, AttributeValueType++from hi.integrations.models import Integration, IntegrationAttribute, IntegrationDetailsModel+from hi.integrations.transient_models import IntegrationKey, IntegrationDetails+++class ConcreteIntegrationDetailsModel(IntegrationDetailsModel):+ """Concrete test class for testing abstract IntegrationDetailsModel."""++ # Add a simple field to make it a valid concrete model+ name = models.CharField(max_length=64, default='test')++ class Meta:+ # Use this model only for testing+ app_label = 'integrations'+++class IntegrationModelTestCase(TestCase):+ """Test cases for Integration model functionality."""++ def test_integration_model_fields_and_constraints(self):+ """Test Integration model field definitions and constraints."""+ # Create integration+ integration = Integration.objects.create(+ integration_id='test_integration',+ is_enabled=True+ )++ # Verify field values+ self.assertEqual(integration.integration_id, 'test_integration')+ self.assertTrue(integration.is_enabled)+ self.assertIsNotNone(integration.created_datetime)+ self.assertIsNotNone(integration.updated_datetime)++ # Verify string representation+ self.assertEqual(str(integration), 'test_integration')++ # Verify model meta+ self.assertEqual(integration._meta.verbose_name, 'Integration')+ self.assertEqual(integration._meta.verbose_name_plural, 'Integrations')++ def test_integration_id_unique_constraint(self):+ """Test that integration_id must be unique."""+ # Create first integration+ Integration.objects.create(+ integration_id='unique_integration',+ is_enabled=True+ )++ # Attempt to create duplicate+ with self.assertRaises(IntegrityError):+ Integration.objects.create(+ integration_id='unique_integration', # Same ID+ is_enabled=False+ )++ def test_integration_id_required_constraint(self):+ """Test that integration_id is required (not null, not blank)."""+ # Test empty string (should work - blank=False prevents form validation, not DB)+ integration = Integration.objects.create(+ integration_id='',+ is_enabled=True+ )+ self.assertEqual(integration.integration_id, '')++ def test_is_enabled_default_value(self):+ """Test that is_enabled defaults to False."""+ integration = Integration.objects.create(+ integration_id='default_test'+ )++ # Should default to False+ self.assertFalse(integration.is_enabled)++ def test_datetime_field_auto_behavior(self):+ """Test auto_now_add and auto_now behavior of datetime fields."""+ import time++ # Create integration+ integration = Integration.objects.create(+ integration_id='datetime_test',+ is_enabled=False+ )++ created_time = integration.created_datetime+ updated_time = integration.updated_datetime++ # Initially, created and updated should be very close+ time_diff = abs((updated_time - created_time).total_seconds())+ self.assertLess(time_diff, 1.0) # Within 1 second++ # Wait a small amount and update+ time.sleep(0.1)+ integration.is_enabled = True+ integration.save()++ # Reload from database+ integration.refresh_from_db()++ # Created time should not have changed+ self.assertEqual(integration.created_datetime, created_time)++ # Updated time should have changed+ self.assertGreater(integration.updated_datetime, updated_time)++ def test_attributes_by_name_property(self):+ """Test attributes_by_name property returns correct mapping."""+ integration = Integration.objects.create(+ integration_id='attr_test_integration',+ is_enabled=True+ )++ # Test with no attributes+ result = integration.attributes_by_name+ self.assertEqual(result, {})+ self.assertIsInstance(result, dict)++ # Create attributes+ attr1 = IntegrationAttribute.objects.create(+ integration=integration,+ name='First Attribute',+ value='value1',+ value_type_str=str(AttributeValueType.TEXT),+ attribute_type_str=str(AttributeType.PREDEFINED)+ )++ attr2 = IntegrationAttribute.objects.create(+ integration=integration,+ name='Second Attribute',+ value='value2',+ value_type_str=str(AttributeValueType.TEXT),+ attribute_type_str=str(AttributeType.PREDEFINED)+ )++ # Test property returns correct mapping+ result = integration.attributes_by_name++ self.assertEqual(len(result), 2)+ self.assertEqual(result['First Attribute'], attr1)+ self.assertEqual(result['Second Attribute'], attr2)+ self.assertIsInstance(result, dict)++ # Verify keys are attribute names+ self.assertEqual(set(result.keys()), {'First Attribute', 'Second Attribute'})++ def test_attributes_by_integration_key_property(self):+ """Test attributes_by_integration_key property returns correct mapping."""+ integration = Integration.objects.create(+ integration_id='key_test_integration',+ is_enabled=True+ )++ # Test with no attributes+ result = integration.attributes_by_integration_key+ self.assertEqual(result, {})+ self.assertIsInstance(result, dict)++ # Create attributes with integration keys+ key1 = IntegrationKey(+ integration_id='test_integration',+ integration_name='attr1'+ )+ key2 = IntegrationKey(+ integration_id='test_integration',+ integration_name='attr2'+ )++ attr1 = IntegrationAttribute.objects.create(+ integration=integration,+ name='First Attribute',+ value='value1',+ value_type_str=str(AttributeValueType.TEXT),+ attribute_type_str=str(AttributeType.PREDEFINED),+ integration_key_str=str(key1)+ )++ attr2 = IntegrationAttribute.objects.create(+ integration=integration,+ name='Second Attribute',+ value='value2',+ value_type_str=str(AttributeValueType.TEXT),+ attribute_type_str=str(AttributeType.PREDEFINED),+ integration_key_str=str(key2)+ )++ # Test property returns correct mapping+ result = integration.attributes_by_integration_key++ self.assertEqual(len(result), 2)+ self.assertEqual(result[key1], attr1)+ self.assertEqual(result[key2], attr2)+ self.assertIsInstance(result, dict)++ # Verify keys are IntegrationKey objects+ result_keys = list(result.keys())+ self.assertTrue(all(isinstance(key, IntegrationKey) for key in result_keys))++ def test_attributes_by_integration_key_property_without_keys(self):+ """Test attributes_by_integration_key with attributes that have no integration key."""+ integration = Integration.objects.create(+ integration_id='no_key_test',+ is_enabled=True+ )++ # Create attribute without integration key+ attr = IntegrationAttribute.objects.create(+ integration=integration,+ name='No Key Attribute',+ value='value',+ value_type_str=str(AttributeValueType.TEXT),+ attribute_type_str=str(AttributeType.CUSTOM)+ # No integration_key_str+ )++ # Property should handle attributes without integration keys+ result = integration.attributes_by_integration_key++ # Should have one entry with None key+ self.assertEqual(len(result), 1)++ # The key should be None since no integration_key_str was set+ self.assertIn(None, result)+ self.assertEqual(result[None], attr)+++class IntegrationAttributeModelTestCase(TestCase):+ """Test cases for IntegrationAttribute model functionality."""++ def setUp(self):+ """Set up test data."""+ self.integration = Integration.objects.create(+ integration_id='test_integration',+ is_enabled=True+ )++ def test_integration_attribute_foreign_key_relationship(self):+ """Test foreign key relationship between IntegrationAttribute and Integration."""+ # Create attribute+ attr = IntegrationAttribute.objects.create(+ integration=self.integration,+ name='Test Attribute',+ value='test_value',+ value_type_str=str(AttributeValueType.TEXT),+ attribute_type_str=str(AttributeType.PREDEFINED)+ )++ # Verify relationship from attribute to integration+ self.assertEqual(attr.integration, self.integration)+ self.assertEqual(attr.integration.integration_id, 'test_integration')++ # Verify reverse relationship from integration to attributes+ integration_attrs = self.integration.attributes.all()+ self.assertEqual(integration_attrs.count(), 1)+ self.assertEqual(integration_attrs.first(), attr)++ def test_integration_attribute_cascade_deletion(self):+ """Test that attributes are deleted when integration is deleted (CASCADE)."""+ # Create attributes+ attr1 = IntegrationAttribute.objects.create(+ integration=self.integration,+ name='Attribute 1',+ value='value1',+ value_type_str=str(AttributeValueType.TEXT),+ attribute_type_str=str(AttributeType.PREDEFINED)+ )++ attr2 = IntegrationAttribute.objects.create(+ integration=self.integration,+ name='Attribute 2',+ value='value2',+ value_type_str=str(AttributeValueType.TEXT),+ attribute_type_str=str(AttributeType.PREDEFINED)+ )++ attr1_id = attr1.id+ attr2_id = attr2.id++ # Verify attributes exist+ self.assertEqual(IntegrationAttribute.objects.filter(integration=self.integration).count(), 2)++ # Delete integration+ self.integration.delete()++ # Verify attributes were cascade deleted+ self.assertFalse(IntegrationAttribute.objects.filter(id=attr1_id).exists())+ self.assertFalse(IntegrationAttribute.objects.filter(id=attr2_id).exists())+ self.assertEqual(IntegrationAttribute.objects.filter(integration_id=self.integration.id).count(), 0)++ def test_integration_attribute_get_upload_to(self):+ """Test get_upload_to method returns correct path."""+ attr = IntegrationAttribute.objects.create(+ integration=self.integration,+ name='Test Attribute',+ value='test_value',+ value_type_str=str(AttributeValueType.TEXT),+ attribute_type_str=str(AttributeType.PREDEFINED)+ )++ upload_path = attr.get_upload_to()+ self.assertEqual(upload_path, 'integration/attributes/')++ def test_integration_attribute_meta_properties(self):+ """Test IntegrationAttribute model meta properties."""+ attr = IntegrationAttribute.objects.create(+ integration=self.integration,+ name='Meta Test',+ value='test',+ value_type_str=str(AttributeValueType.TEXT),+ attribute_type_str=str(AttributeType.PREDEFINED)+ )++ # Test meta properties+ self.assertEqual(attr._meta.verbose_name, 'Attribute')+ self.assertEqual(attr._meta.verbose_name_plural, 'Attributes')+++class IntegrationDetailsModelTestCase(TestCase):+ """Test cases for IntegrationDetailsModel abstract model functionality."""++ def test_integration_key_property_getter(self):+ """Test integration_key property returns correct IntegrationKey."""+ # We can't instantiate abstract model directly, but can test the property logic+ # Create a mock object with the required fields+ class MockIntegrationDetails:+ def __init__(self, integration_id, integration_name):+ self.integration_id = integration_id+ self.integration_name = integration_name++ @property+ def integration_key(self):+ if self.integration_id is None or self.integration_name is None:+ return None+ return IntegrationKey(+ integration_id=self.integration_id,+ integration_name=self.integration_name,+ )++ # Test with both values present+ mock_obj = MockIntegrationDetails('test_integration', 'device_1')+ key = mock_obj.integration_key++ self.assertIsInstance(key, IntegrationKey)+ self.assertEqual(key.integration_id, 'test_integration')+ self.assertEqual(key.integration_name, 'device_1')++ # Test with None values - should return None instead of IntegrationKey+ mock_obj_none = MockIntegrationDetails(None, None)+ key_none = mock_obj_none.integration_key++ self.assertIsNone(key_none)++ def test_integration_key_property_setter(self):+ """Test integration_key property setter updates fields correctly."""+ class MockIntegrationDetails:+ def __init__(self):+ self.integration_id = None+ self.integration_name = None++ @property+ def integration_key(self):+ if self.integration_id is None or self.integration_name is None:+ return None+ return IntegrationKey(+ integration_id=self.integration_id,+ integration_name=self.integration_name,+ )++ @integration_key.setter+ def integration_key(self, integration_key):+ if not integration_key:+ self.integration_id = None+ self.integration_name = None+ return+ self.integration_id = integration_key.integration_id+ self.integration_name = integration_key.integration_name++ mock_obj = MockIntegrationDetails()++ # Test setting with IntegrationKey+ key = IntegrationKey('test_integration', 'device_1')+ mock_obj.integration_key = key++ self.assertEqual(mock_obj.integration_id, 'test_integration')+ self.assertEqual(mock_obj.integration_name, 'device_1')++ # Test setting with None+ mock_obj.integration_key = None++ self.assertIsNone(mock_obj.integration_id)+ self.assertIsNone(mock_obj.integration_name)++ # Test setting with falsy value+ mock_obj.integration_key = ''++ self.assertIsNone(mock_obj.integration_id)+ self.assertIsNone(mock_obj.integration_name)++ def test_get_integration_details_method(self):+ """Test get_integration_details method returns correct IntegrationDetails."""+ class MockIntegrationDetails:+ def __init__(self, integration_id, integration_name, payload):+ self.integration_id = integration_id+ self.integration_name = integration_name+ self.integration_payload = payload++ @property+ def integration_key(self):+ return IntegrationKey(+ integration_id=self.integration_id,+ integration_name=self.integration_name,+ )++ def get_integration_details(self):+ return IntegrationDetails(+ key=self.integration_key,+ payload=self.integration_payload,+ )++ # Test with payload+ payload = {'device_type': 'light', 'capabilities': ['brightness']}+ mock_obj = MockIntegrationDetails('test_integration', 'device_1', payload)++ details = mock_obj.get_integration_details()++ self.assertIsInstance(details, IntegrationDetails)+ self.assertEqual(details.key.integration_id, 'test_integration')+ self.assertEqual(details.key.integration_name, 'device_1')+ self.assertEqual(details.payload, payload)++ # Test with empty payload+ mock_obj_empty = MockIntegrationDetails('test_integration', 'device_2', {})+ details_empty = mock_obj_empty.get_integration_details()++ self.assertEqual(details_empty.payload, {})++ def test_update_integration_payload_method(self):+ """Test update_integration_payload method behavior and change detection."""+ class MockIntegrationDetails:+ def __init__(self, initial_payload=None):+ self.integration_payload = initial_payload or {}+ self.save_called = False++ def save(self):+ self.save_called = True++ def update_integration_payload(self, new_payload):+ old_payload = self.integration_payload or {}+ changed_fields = []++ # Check for changes to existing fields only+ for key, new_value in new_payload.items():+ if key in old_payload and old_payload[key] != new_value:+ changed_fields.append(f'{key}: {old_payload[key]} -> {new_value}')++ # Always update payload (even if no existing fields changed)+ self.integration_payload = new_payload+ self.save()++ return changed_fields++ # Test with empty initial payload+ mock_obj = MockIntegrationDetails()++ new_payload = {'device_type': 'light', 'brightness': 80}+ changes = mock_obj.update_integration_payload(new_payload)++ # No existing fields to change+ self.assertEqual(changes, [])+ self.assertEqual(mock_obj.integration_payload, new_payload)+ self.assertTrue(mock_obj.save_called)++ # Test with existing payload and changes+ mock_obj2 = MockIntegrationDetails({'device_type': 'switch', 'brightness': 50})+ mock_obj2.save_called = False++ updated_payload = {'device_type': 'light', 'brightness': 80, 'color': 'red'}+ changes = mock_obj2.update_integration_payload(updated_payload)++ # Should detect changes to existing fields+ expected_changes = [+ 'device_type: switch -> light',+ 'brightness: 50 -> 80'+ ]+ self.assertEqual(set(changes), set(expected_changes))+ self.assertEqual(mock_obj2.integration_payload, updated_payload)+ self.assertTrue(mock_obj2.save_called)++ # Test with no changes to existing fields+ mock_obj3 = MockIntegrationDetails({'device_type': 'light'})+ mock_obj3.save_called = False++ same_payload = {'device_type': 'light', 'new_field': 'new_value'}+ changes = mock_obj3.update_integration_payload(same_payload)++ # No changes to existing fields (new fields are ignored for change detection)+ self.assertEqual(changes, [])+ self.assertEqual(mock_obj3.integration_payload, same_payload)+ self.assertTrue(mock_obj3.save_called)++ def test_integration_details_model_manager(self):+ """Test that IntegrationDetailsModel uses IntegrationDetailsManager."""+ # Test using the concrete test model+ self.assertEqual(ConcreteIntegrationDetailsModel.objects.__class__.__name__, 'IntegrationDetailsManager')++ def test_integration_details_model_fields(self):+ """Test IntegrationDetailsModel field definitions."""+ # Test field properties on the abstract model+ integration_id_field = IntegrationDetailsModel._meta.get_field('integration_id')+ integration_name_field = IntegrationDetailsModel._meta.get_field('integration_name')+ integration_payload_field = IntegrationDetailsModel._meta.get_field('integration_payload')++ # Test integration_id field+ self.assertEqual(integration_id_field.max_length, 32)+ self.assertTrue(integration_id_field.null)+ self.assertTrue(integration_id_field.blank)+ self.assertEqual(integration_id_field.verbose_name, 'Integration Id')++ # Test integration_name field+ self.assertEqual(integration_name_field.max_length, 128)+ self.assertTrue(integration_name_field.null)+ self.assertTrue(integration_name_field.blank)+ self.assertEqual(integration_name_field.verbose_name, 'Integration Name')++ # Test integration_payload field+ self.assertEqual(integration_payload_field.default, dict)+ self.assertTrue(integration_payload_field.blank)+ self.assertEqual(integration_payload_field.verbose_name, 'Integration Payload')+ self.assertIn('Integration-specific data', integration_payload_field.help_text)+++class IntegrationModelTransactionTestCase(TransactionTestCase):+ """Transaction-specific tests for Integration models."""++ def test_integration_id_null_constraint(self):+ """Test that integration_id cannot be null."""+ with self.assertRaises(IntegrityError):+ Integration.objects.create(+ integration_id=None,+ is_enabled=True+ )++ def test_integration_unique_constraint_transaction_behavior(self):+ """Test unique constraint behavior in transaction context."""+ integration_id = 'transaction_test_integration'++ # Test that transaction rollback works correctly with unique constraint+ try:+ with transaction.atomic():+ # Create first integration+ Integration.objects.create(+ integration_id=integration_id,+ is_enabled=True+ )++ # Attempt to create duplicate in same transaction+ Integration.objects.create(+ integration_id=integration_id, # Duplicate+ is_enabled=False+ )++ except IntegrityError:+ # Expected - transaction should roll back+ pass++ # Verify no integrations were created due to rollback+ self.assertFalse(Integration.objects.filter(integration_id=integration_id).exists())++ # Verify we can create integration after failed transaction+ integration = Integration.objects.create(+ integration_id=integration_id,+ is_enabled=True+ )+ self.assertTrue(Integration.objects.filter(integration_id=integration_id).exists())+ self.assertEqual(integration.integration_id, integration_id)++ def test_integration_attribute_cascade_deletion_transaction_consistency(self):+ """Test cascade deletion maintains transaction consistency."""+ # Create integration with attributes+ integration = Integration.objects.create(+ integration_id='cascade_test',+ is_enabled=True+ )++ # Create multiple attributes+ attributes = []+ for i in range(3):+ attr = IntegrationAttribute.objects.create(+ integration=integration,+ name=f'Attribute {i}',+ value=f'value{i}',+ value_type_str=str(AttributeValueType.TEXT),+ attribute_type_str=str(AttributeType.PREDEFINED)+ )+ attributes.append(attr)++ attribute_ids = [attr.id for attr in attributes]++ # Verify all attributes exist+ self.assertEqual(IntegrationAttribute.objects.filter(id__in=attribute_ids).count(), 3)++ # Delete integration in transaction+ with transaction.atomic():+ integration.delete()++ # Verify complete cleanup+ self.assertEqual(IntegrationAttribute.objects.filter(id__in=attribute_ids).count(), 0)+ self.assertFalse(Integration.objects.filter(id=integration.id).exists())++ # Verify database consistency - no orphaned attributes+ orphaned_attrs = IntegrationAttribute.objects.filter(integration_id=integration.id)+ self.assertEqual(orphaned_attrs.count(), 0)diff --git a/src/hi/integrations/tests/test_sync_mixins.py b/src/hi/integrations/tests/test_sync_mixins.pyindex 97901c08..42fffe6e 100644--- a/src/hi/integrations/tests/test_sync_mixins.py+++ b/src/hi/integrations/tests/test_sync_mixins.py@@ -2,7 +2,7 @@Unit tests for IntegrationSyncMixin."""-from django.test import TestCase+from django.test import TestCase, TransactionTestCasefrom hi.apps.entity.models import Entity, EntityAttribute, EntityStatefrom hi.apps.sense.models import Sensor@@ -70,9 +70,16 @@ class IntegrationSyncMixinTestCase(TestCase):# Entity should be completely deletedself.assertFalse(Entity.objects.filter(id=entity_id).exists())- # Check result message+ # Check result message content and qualityself.assertEqual(len(self.result.message_list), 1)- self.assertIn('Removed stale TestIntegration entity', self.result.message_list[0])+ message = self.result.message_list[0]+ self.assertIn('Removed stale TestIntegration entity', message)+ self.assertIn('Test Entity', message) # Should include entity name for debugging++ # Verify complete cleanup - no orphaned attributes or states+ self.assertEqual(EntityAttribute.objects.filter(entity_id=entity_id).count(), 0)+ self.assertEqual(EntityState.objects.filter(entity_id=entity_id).count(), 0)+ self.assertEqual(Sensor.objects.filter(entity_state__entity_id=entity_id).count(), 0)def test_remove_entity_intelligently_with_user_data(self):"""Test preservation when entity has user data."""@@ -149,10 +156,29 @@ class IntegrationSyncMixinTestCase(TestCase):# Entity state should be deleted (orphaned)self.assertFalse(EntityState.objects.filter(id=state_id).exists())- # Check result message+ # Check result message content and completenessself.assertEqual(len(self.result.message_list), 1)- self.assertIn('Preserved TestIntegration entity', self.result.message_list[0])- self.assertIn('disconnected from integration', self.result.message_list[0])+ message = self.result.message_list[0]+ self.assertIn('Preserved TestIntegration entity', message)+ self.assertIn('disconnected from integration', message)+ self.assertIn(original_name, message) # Should reference original name+ self.assertIn('[Disconnected]', message) # Should show new name++ # Verify integration payload is cleared+ self.entity.refresh_from_db()+ self.assertEqual(self.entity.integration_payload, {})++ # Verify entity maintains referential integrity+ remaining_attributes = EntityAttribute.objects.filter(entity=self.entity)+ self.assertEqual(remaining_attributes.count(), 1)+ self.assertEqual(remaining_attributes.first().name, 'User Note')++ # Verify no orphaned integration data remains+ orphaned_attrs = EntityAttribute.objects.filter(+ entity=self.entity,+ integration_key_str__isnull=False+ )+ self.assertEqual(orphaned_attrs.count(), 0)def test_preserve_entity_state_with_remaining_user_components(self):"""Test that entity states are preserved when user components remain."""@@ -287,3 +313,745 @@ class IntegrationSyncMixinTestCase(TestCase):# User sensor should be preservedself.assertTrue(Sensor.objects.filter(id=user_sensor2.id).exists())++ def test_remove_entity_with_no_states(self):+ """Test deletion of entity with no entity states."""+ # Remove the default entity state+ self.entity_state.delete()++ # Create only entity attributes+ EntityAttribute.objects.create(+ entity=self.entity,+ name='Integration Data',+ value='Some data',+ value_type_str='TEXT',+ attribute_type_str='CONFIGURATION',+ integration_key_str='test_integration:test_device_1'+ )++ entity_id = self.entity.id++ # Call the method+ self.synchronizer._remove_entity_intelligently(+ self.entity, self.result, 'TestIntegration'+ )++ # Entity should be completely deleted+ self.assertFalse(Entity.objects.filter(id=entity_id).exists())++ # Verify message indicates successful deletion+ self.assertEqual(len(self.result.message_list), 1)+ self.assertIn('Removed stale TestIntegration entity', self.result.message_list[0])++ def test_entity_with_integration_payload_preservation(self):+ """Test that integration_payload is preserved during entity preservation."""+ # Set up entity with integration payload+ original_payload = {+ 'device_type': 'light',+ 'capabilities': ['brightness', 'color'],+ 'last_seen': '2024-01-01T00:00:00Z'+ }+ self.entity.integration_payload = original_payload+ self.entity.save()++ # Create user data to trigger preservation+ EntityAttribute.objects.create(+ entity=self.entity,+ name='User Note',+ value='Important note',+ value_type_str='TEXT',+ attribute_type_str='DOCUMENTATION'+ )++ # Call the method+ self.synchronizer._remove_entity_intelligently(+ self.entity, self.result, 'TestIntegration'+ )++ # Verify entity is preserved and integration fields are cleared+ self.entity.refresh_from_db()+ self.assertIsNone(self.entity.integration_id)+ self.assertIsNone(self.entity.integration_name)+ # Integration payload should be preserved for historical value+ self.assertEqual(self.entity.integration_payload, original_payload)++ def test_entity_with_multiple_integration_attributes(self):+ """Test removal of multiple integration attributes while preserving user data."""+ # Create multiple integration attributes+ integration_attrs = []+ for i in range(3):+ attr = EntityAttribute.objects.create(+ entity=self.entity,+ name=f'Integration Config {i}',+ value=f'Config value {i}',+ value_type_str='TEXT',+ attribute_type_str='CONFIGURATION',+ integration_key_str=f'test_integration:config_{i}'+ )+ integration_attrs.append(attr)++ # Create user attribute+ user_attr = EntityAttribute.objects.create(+ entity=self.entity,+ name='User Documentation',+ value='User-created note',+ value_type_str='TEXT',+ attribute_type_str='DOCUMENTATION'+ )++ # Call the method+ self.synchronizer._remove_entity_intelligently(+ self.entity, self.result, 'TestIntegration'+ )++ # All integration attributes should be deleted+ for attr in integration_attrs:+ self.assertFalse(EntityAttribute.objects.filter(id=attr.id).exists())++ # User attribute should be preserved+ self.assertTrue(EntityAttribute.objects.filter(id=user_attr.id).exists())++ # Verify only user attributes remain+ remaining_attrs = EntityAttribute.objects.filter(entity=self.entity)+ self.assertEqual(remaining_attrs.count(), 1)+ self.assertEqual(remaining_attrs.first().name, 'User Documentation')++ def test_complex_entity_state_relationships(self):+ """Test handling of entity with complex sensor/controller relationships."""+ # Create multiple entity states+ state2 = EntityState.objects.create(+ entity=self.entity,+ entity_state_type_str='CONTINUOUS',+ name='Temperature State'+ )++ state3 = EntityState.objects.create(+ entity=self.entity,+ entity_state_type_str='DISCRETE',+ name='Motion State'+ )++ # Create mixed sensors and controllers across states+ # State 1: integration sensor + user controller+ integration_sensor1 = Sensor.objects.create(+ name='Integration Sensor 1',+ entity_state=self.entity_state,+ sensor_type_str='DISCRETE',+ integration_id='test_integration',+ integration_name='sensor_1'+ )++ user_controller1 = Controller.objects.create(+ name='User Controller 1',+ entity_state=self.entity_state,+ controller_type_str='DISCRETE'+ )++ # State 2: user sensor + integration controller+ user_sensor2 = Sensor.objects.create(+ name='User Sensor 2',+ entity_state=state2,+ sensor_type_str='CONTINUOUS'+ )++ integration_controller2 = Controller.objects.create(+ name='Integration Controller 2',+ entity_state=state2,+ controller_type_str='CONTINUOUS',+ integration_id='test_integration',+ integration_name='controller_2'+ )++ # State 3: only integration components (will be orphaned)+ integration_sensor3 = Sensor.objects.create(+ name='Integration Sensor 3',+ entity_state=state3,+ sensor_type_str='DISCRETE',+ integration_id='test_integration',+ integration_name='sensor_3'+ )++ # Create user attribute to trigger preservation+ user_attr = EntityAttribute.objects.create(+ entity=self.entity,+ name='User Note',+ value='User note',+ value_type_str='TEXT',+ attribute_type_str='DOCUMENTATION'+ )++ # Call the method+ self.synchronizer._remove_entity_intelligently(+ self.entity, self.result, 'TestIntegration'+ )++ # Verify entity is preserved+ self.assertTrue(Entity.objects.filter(id=self.entity.id).exists())++ # State 1 should be preserved (has user controller)+ self.assertTrue(EntityState.objects.filter(id=self.entity_state.id).exists())++ # State 2 should be preserved (has user sensor)+ self.assertTrue(EntityState.objects.filter(id=state2.id).exists())++ # State 3 should be deleted (orphaned)+ self.assertFalse(EntityState.objects.filter(id=state3.id).exists())++ # Integration components should be deleted+ self.assertFalse(Sensor.objects.filter(id=integration_sensor1.id).exists())+ self.assertFalse(Controller.objects.filter(id=integration_controller2.id).exists())+ self.assertFalse(Sensor.objects.filter(id=integration_sensor3.id).exists())++ # User components should be preserved+ self.assertTrue(Controller.objects.filter(id=user_controller1.id).exists())+ self.assertTrue(Sensor.objects.filter(id=user_sensor2.id).exists())++ # User attribute should be preserved+ self.assertTrue(EntityAttribute.objects.filter(id=user_attr.id).exists())++ def test_database_cascade_deletion_integrity(self):+ """Test that complete deletion properly cascades and maintains database integrity."""+ # Create complex entity structure with multiple relationships+ state2 = EntityState.objects.create(+ entity=self.entity,+ entity_state_type_str='CONTINUOUS',+ name='Second State'+ )++ # Create multiple integration components+ sensor1 = Sensor.objects.create(+ name='Integration Sensor 1',+ entity_state=self.entity_state,+ sensor_type_str='DISCRETE',+ integration_id='test_integration',+ integration_name='sensor_1'+ )++ sensor2 = Sensor.objects.create(+ name='Integration Sensor 2',+ entity_state=state2,+ sensor_type_str='CONTINUOUS',+ integration_id='test_integration',+ integration_name='sensor_2'+ )++ controller = Controller.objects.create(+ name='Integration Controller',+ entity_state=self.entity_state,+ controller_type_str='DISCRETE',+ integration_id='test_integration',+ integration_name='controller_1'+ )++ # Create multiple integration attributes+ attr1 = EntityAttribute.objects.create(+ entity=self.entity,+ name='Config 1',+ value='Value 1',+ value_type_str='TEXT',+ attribute_type_str='CONFIGURATION',+ integration_key_str='test_integration:config_1'+ )++ attr2 = EntityAttribute.objects.create(+ entity=self.entity,+ name='Config 2',+ value='Value 2',+ value_type_str='TEXT',+ attribute_type_str='CONFIGURATION',+ integration_key_str='test_integration:config_2'+ )++ # Store IDs for verification+ entity_id = self.entity.id+ state1_id = self.entity_state.id+ state2_id = state2.id+ component_ids = [sensor1.id, sensor2.id, controller.id]+ attribute_ids = [attr1.id, attr2.id]++ # Call deletion (no user data, should delete completely)+ self.synchronizer._remove_entity_intelligently(+ self.entity, self.result, 'TestIntegration'+ )++ # Verify complete cascade deletion+ self.assertFalse(Entity.objects.filter(id=entity_id).exists())+ self.assertFalse(EntityState.objects.filter(id__in=[state1_id, state2_id]).exists())+ self.assertFalse(Sensor.objects.filter(id__in=component_ids).exists())+ self.assertFalse(Controller.objects.filter(id__in=component_ids).exists())+ self.assertFalse(EntityAttribute.objects.filter(id__in=attribute_ids).exists())++ # Verify message indicates successful deletion+ self.assertEqual(len(self.result.message_list), 1)+ message = self.result.message_list[0]+ self.assertIn('Removed stale TestIntegration entity', message)+ self.assertIn('Test Entity', message)++ def test_result_message_accumulation(self):+ """Test that ProcessingResult properly accumulates messages from multiple operations."""+ # Add some initial messages to result+ self.result.message_list.append('Initial message')+ self.result.message_list.append('Another message')++ # Create user data to trigger preservation+ EntityAttribute.objects.create(+ entity=self.entity,+ name='User Note',+ value='User note',+ value_type_str='TEXT',+ attribute_type_str='DOCUMENTATION'+ )++ # Call the method+ self.synchronizer._remove_entity_intelligently(+ self.entity, self.result, 'TestIntegration'+ )++ # Should have 3 messages total (2 existing + 1 new)+ self.assertEqual(len(self.result.message_list), 3)++ # New message should be last+ self.assertIn('Preserved TestIntegration entity', self.result.message_list[2])++ # Original messages should be preserved+ self.assertEqual(self.result.message_list[0], 'Initial message')+ self.assertEqual(self.result.message_list[1], 'Another message')+++class IntegrationSyncMixinTransactionTestCase(TransactionTestCase):+ """Transaction-specific tests for IntegrationSyncMixin."""++ def setUp(self):+ """Set up test data."""+ # Ensure subsystem data is populated after database flush+ from hi.apps.config.signals import SettingsInitializer+ initializer = SettingsInitializer()+ initializer.run(sender=None)++ self.synchronizer = TestSynchronizer()+ self.result = ProcessingResult(title='Test Sync Result')++ # Create a test entity+ self.entity = Entity.objects.create(+ name='Test Entity',+ entity_type_str='LIGHT',+ integration_id='test_integration',+ integration_name='test_device_1'+ )++ # Create entity state+ self.entity_state = EntityState.objects.create(+ entity=self.entity,+ entity_state_type_str='DISCRETE',+ name='Test State'+ )++ def test_data_consistency_during_preservation_operation(self):+ """Test that preservation maintains referential integrity throughout the operation."""+ # Create user attribute to trigger preservation path+ user_attr = EntityAttribute.objects.create(+ entity=self.entity,+ name='User Note',+ value='Critical user note',+ value_type_str='TEXT',+ attribute_type_str='DOCUMENTATION'+ )++ # Create complex state structure+ state2 = EntityState.objects.create(+ entity=self.entity,+ entity_state_type_str='CONTINUOUS',+ name='Temperature State'+ )++ # Create mixed integration and user components+ integration_sensor = Sensor.objects.create(+ name='Integration Sensor',+ entity_state=self.entity_state,+ sensor_type_str='DISCRETE',+ integration_id='test_integration',+ integration_name='sensor_1'+ )++ user_sensor = Sensor.objects.create(+ name='User Sensor',+ entity_state=state2,+ sensor_type_str='CONTINUOUS'+ # No integration_id - user created+ )++ integration_controller = Controller.objects.create(+ name='Integration Controller',+ entity_state=self.entity_state,+ controller_type_str='DISCRETE',+ integration_id='test_integration',+ integration_name='controller_1'+ )++ integration_attr = EntityAttribute.objects.create(+ entity=self.entity,+ name='Integration Config',+ value='Config data',+ value_type_str='TEXT',+ attribute_type_str='CONFIGURATION',+ integration_key_str='test_integration:config_1'+ )++ # Store initial counts for verification+ initial_entity_count = Entity.objects.count()++ # Execute preservation operation+ self.synchronizer._remove_entity_intelligently(+ self.entity, self.result, 'TestIntegration'+ )++ # Verify entity preservation and disconnection+ self.entity.refresh_from_db()+ self.assertTrue(self.entity.name.startswith('[Disconnected]'))+ self.assertIsNone(self.entity.integration_id)+ self.assertIsNone(self.entity.integration_name)++ # Verify database consistency - no orphaned or invalid foreign keys+ self.assertEqual(Entity.objects.count(), initial_entity_count)++ # Verify selective component removal+ self.assertFalse(Sensor.objects.filter(id=integration_sensor.id).exists())+ self.assertTrue(Sensor.objects.filter(id=user_sensor.id).exists())+ self.assertFalse(Controller.objects.filter(id=integration_controller.id).exists())++ # Verify attribute handling+ self.assertTrue(EntityAttribute.objects.filter(id=user_attr.id).exists())+ self.assertFalse(EntityAttribute.objects.filter(id=integration_attr.id).exists())++ # Verify state preservation logic+ # State 1 should be deleted (orphaned - only had integration components)+ self.assertFalse(EntityState.objects.filter(id=self.entity_state.id).exists())+ # State 2 should be preserved (has user sensor)+ self.assertTrue(EntityState.objects.filter(id=state2.id).exists())++ # Verify remaining components have valid foreign key relationships+ remaining_sensors = Sensor.objects.filter(entity_state__entity=self.entity)+ self.assertEqual(remaining_sensors.count(), 1)+ self.assertEqual(remaining_sensors.first().name, 'User Sensor')++ remaining_attributes = EntityAttribute.objects.filter(entity=self.entity)+ self.assertEqual(remaining_attributes.count(), 1)+ self.assertEqual(remaining_attributes.first().name, 'User Note')++ # Verify operation was logged+ self.assertEqual(len(self.result.message_list), 1)+ message = self.result.message_list[0]+ self.assertIn('Preserved TestIntegration entity', message)+ self.assertIn('disconnected from integration', message)++ def test_preservation_with_database_constraint_validation(self):+ """Test that preservation operations respect database constraints and maintain referential integrity."""+ # Create user attribute to trigger preservation+ user_attr = EntityAttribute.objects.create(+ entity=self.entity,+ name='User Note',+ value='User note',+ value_type_str='TEXT',+ attribute_type_str='DOCUMENTATION'+ )++ # Create integration sensor that will be orphaned (state will be deleted)+ integration_sensor = Sensor.objects.create(+ name='Integration Sensor',+ entity_state=self.entity_state,+ sensor_type_str='DISCRETE',+ integration_id='test_integration',+ integration_name='sensor_1'+ )++ # Create a second entity state with mixed components+ second_state = EntityState.objects.create(+ entity=self.entity,+ entity_state_type_str='CONTINUOUS',+ name='Mixed State'+ )++ # Integration controller on second state+ integration_controller = Controller.objects.create(+ name='Integration Controller',+ entity_state=second_state,+ controller_type_str='CONTINUOUS',+ integration_id='test_integration',+ integration_name='controller_1'+ )++ # User sensor on second state (should preserve the state)+ user_sensor = Sensor.objects.create(+ name='User Sensor',+ entity_state=second_state,+ sensor_type_str='CONTINUOUS'+ # No integration_id - user created+ )++ # Store IDs for verification+ first_state_id = self.entity_state.id+ second_state_id = second_state.id++ # Execute preservation+ self.synchronizer._remove_entity_intelligently(+ self.entity, self.result, 'TestIntegration'+ )++ # Verify our entity was preserved and disconnected+ self.entity.refresh_from_db()+ self.assertTrue(self.entity.name.startswith('[Disconnected]'))+ self.assertIsNone(self.entity.integration_id)+ self.assertIsNone(self.entity.integration_name)++ # Integration components should be deleted+ self.assertFalse(Sensor.objects.filter(id=integration_sensor.id).exists())+ self.assertFalse(Controller.objects.filter(id=integration_controller.id).exists())++ # First state should be deleted (orphaned - only had integration sensor)+ self.assertFalse(EntityState.objects.filter(id=first_state_id).exists())++ # Second state should be preserved (has user sensor)+ self.assertTrue(EntityState.objects.filter(id=second_state_id).exists())++ # User components should still exist+ self.assertTrue(Sensor.objects.filter(id=user_sensor.id).exists())+ self.assertTrue(EntityAttribute.objects.filter(id=user_attr.id).exists())++ # Verify message was added+ self.assertEqual(len(self.result.message_list), 1)+ self.assertIn('Preserved TestIntegration entity', self.result.message_list[0])++ # Verify database integrity: remaining state has valid relationships+ remaining_state = EntityState.objects.get(id=second_state_id)+ remaining_sensors = remaining_state.sensors.all()+ self.assertEqual(remaining_sensors.count(), 1)+ self.assertEqual(remaining_sensors.first().name, 'User Sensor')++ # Verify entity still has correct relationships+ self.assertEqual(self.entity.states.count(), 1)+ self.assertEqual(self.entity.states.first().id, second_state_id)++ def test_user_data_detection_boundary_conditions(self):+ """Test edge cases in user data detection that determine preservation vs deletion."""+ # Test 1: Entity with only integration attributes (should be deleted)+ integration_only_entity = Entity.objects.create(+ name='Integration Only Entity',+ entity_type_str='LIGHT',+ integration_id='test_integration',+ integration_name='device_2'+ )++ EntityAttribute.objects.create(+ entity=integration_only_entity,+ name='Integration Config',+ value='Config value',+ value_type_str='TEXT',+ attribute_type_str='CONFIGURATION',+ integration_key_str='test_integration:device_2'+ )++ entity_id = integration_only_entity.id++ self.synchronizer._remove_entity_intelligently(+ integration_only_entity, self.result, 'TestIntegration'+ )++ # Should be completely deleted+ self.assertFalse(Entity.objects.filter(id=entity_id).exists())++ # Test 2: Entity with mixed attributes (should be preserved)+ mixed_entity = Entity.objects.create(+ name='Mixed Entity',+ entity_type_str='LIGHT',+ integration_id='test_integration',+ integration_name='device_3'+ )++ # Add integration attribute+ EntityAttribute.objects.create(+ entity=mixed_entity,+ name='Integration Config',+ value='Config value',+ value_type_str='TEXT',+ attribute_type_str='CONFIGURATION',+ integration_key_str='test_integration:device_3'+ )++ # Add user attribute (should trigger preservation)+ EntityAttribute.objects.create(+ entity=mixed_entity,+ name='User Comment',+ value='User added this',+ value_type_str='TEXT',+ attribute_type_str='DOCUMENTATION'+ # No integration_key_str - user created+ )++ self.synchronizer._remove_entity_intelligently(+ mixed_entity, self.result, 'TestIntegration'+ )++ # Should be preserved and disconnected+ mixed_entity.refresh_from_db()+ self.assertTrue(mixed_entity.name.startswith('[Disconnected]'))+ self.assertIsNone(mixed_entity.integration_id)+ self.assertIsNone(mixed_entity.integration_name)++ # Integration attribute should be deleted, user attribute preserved+ integration_attrs = EntityAttribute.objects.filter(+ entity=mixed_entity,+ integration_key_str__isnull=False+ )+ self.assertEqual(integration_attrs.count(), 0)++ user_attrs = EntityAttribute.objects.filter(+ entity=mixed_entity,+ integration_key_str__isnull=True+ )+ self.assertEqual(user_attrs.count(), 1)+ self.assertEqual(user_attrs.first().name, 'User Comment')++ def test_entity_state_orphan_detection_with_mixed_components(self):+ """Test that entity state cleanup correctly identifies orphaned vs preserved states."""+ # Create second entity state for this entity+ second_state = EntityState.objects.create(+ entity=self.entity,+ entity_state_type_str='CONTINUOUS',+ name='Temperature State'+ )++ # First state: only integration sensor (will be orphaned)+ integration_sensor1 = Sensor.objects.create(+ name='Integration Sensor 1',+ entity_state=self.entity_state,+ sensor_type_str='DISCRETE',+ integration_id='test_integration',+ integration_name='sensor_1'+ )++ # Second state: integration controller + user sensor (will be preserved)+ integration_controller = Controller.objects.create(+ name='Integration Controller',+ entity_state=second_state,+ controller_type_str='CONTINUOUS',+ integration_id='test_integration',+ integration_name='controller_1'+ )++ user_sensor = Sensor.objects.create(+ name='User Sensor',+ entity_state=second_state,+ sensor_type_str='CONTINUOUS'+ # No integration_id - user created+ )++ # Add user data to trigger preservation+ user_attr = EntityAttribute.objects.create(+ entity=self.entity,+ name='User Note',+ value='Important user data',+ value_type_str='TEXT',+ attribute_type_str='DOCUMENTATION'+ )++ # Store IDs for verification+ first_state_id = self.entity_state.id+ second_state_id = second_state.id++ # Execute preservation+ self.synchronizer._remove_entity_intelligently(+ self.entity, self.result, 'TestIntegration'+ )++ # Our entity should be preserved and disconnected+ self.entity.refresh_from_db()+ self.assertTrue(self.entity.name.startswith('[Disconnected]'))+ self.assertIsNone(self.entity.integration_id)++ # Integration components should be deleted+ self.assertFalse(Sensor.objects.filter(id=integration_sensor1.id).exists())+ self.assertFalse(Controller.objects.filter(id=integration_controller.id).exists())++ # First state should be deleted (orphaned)+ self.assertFalse(EntityState.objects.filter(id=first_state_id).exists())++ # Second state should be preserved (has user sensor)+ self.assertTrue(EntityState.objects.filter(id=second_state_id).exists())++ # User components should remain+ self.assertTrue(Sensor.objects.filter(id=user_sensor.id).exists())+ self.assertTrue(EntityAttribute.objects.filter(id=user_attr.id).exists())++ # Verify entity now has only one state+ self.assertEqual(self.entity.states.count(), 1)+ remaining_state = self.entity.states.first()+ self.assertEqual(remaining_state.id, second_state_id)++ # Verify remaining state has only user components+ self.assertEqual(remaining_state.sensors.count(), 1)+ self.assertEqual(remaining_state.controllers.count(), 0)+ self.assertEqual(remaining_state.sensors.first().name, 'User Sensor')++ def test_complex_disconnection_name_handling(self):+ """Test various edge cases in disconnection name handling."""+ test_cases = [+ {+ 'name': 'Simple Entity Name',+ 'expected': '[Disconnected] Simple Entity Name'+ },+ {+ 'name': '[Already Disconnected] Entity',+ 'expected': '[Disconnected] [Already Disconnected] Entity' # Should not duplicate if different format+ },+ {+ 'name': '[Disconnected] Already Prefixed',+ 'expected': '[Disconnected] Already Prefixed' # Should not duplicate exact match+ },+ {+ 'name': ' Whitespace Padded ',+ 'expected': '[Disconnected] Whitespace Padded ' # Should preserve exact spacing+ },+ {+ 'name': '',+ 'expected': '[Disconnected] ' # Should handle empty name+ }+ ]++ for i, test_case in enumerate(test_cases):+ with self.subTest(test_case=test_case):+ # Create entity for this test+ entity = Entity.objects.create(+ name=test_case['name'],+ entity_type_str='LIGHT',+ integration_id='test_integration',+ integration_name=f'device_{i}'+ )++ # Add user data to trigger preservation+ EntityAttribute.objects.create(+ entity=entity,+ name='User Data',+ value='User value',+ value_type_str='TEXT',+ attribute_type_str='DOCUMENTATION'+ )++ # Create fresh result for each test+ test_result = ProcessingResult(title='Test Result')++ # Execute preservation+ self.synchronizer._remove_entity_intelligently(+ entity, test_result, 'TestIntegration'+ )++ # Verify name transformation+ entity.refresh_from_db()+ self.assertEqual(entity.name, test_case['expected'])++ # Verify disconnection+ self.assertIsNone(entity.integration_id)+ self.assertIsNone(entity.integration_name)++ # Verify result message was added+ self.assertEqual(len(test_result.message_list), 1)+ self.assertIn('Preserved TestIntegration entity', test_result.message_list[0])diff --git a/src/hi/integrations/tests/test_transient_models.py b/src/hi/integrations/tests/test_transient_models.pynew file mode 100644index 00000000..8aac9ccb--- /dev/null+++ b/src/hi/integrations/tests/test_transient_models.py@@ -0,0 +1,493 @@+"""+Unit tests for transient models (dataclasses and key parsing logic).+"""++from django.test import TestCase++from hi.apps.attribute.enums import AttributeValueType++from hi.integrations.transient_models import (+ IntegrationKey,+ IntegrationDetails,+ IntegrationControlResult,+ IntegrationMetaData+)+from hi.integrations.enums import IntegrationAttributeType+++class MockIntegrationAttributeType(IntegrationAttributeType):+ """Mock integration attribute type for testing."""++ TEST_ATTR = ('Test Attribute', 'Test description', AttributeValueType.TEXT, {}, True, True, 'default')+++class IntegrationKeyTestCase(TestCase):+ """Test cases for IntegrationKey dataclass functionality."""++ def test_integration_key_initialization(self):+ """Test IntegrationKey initialization and basic properties."""+ key = IntegrationKey(+ integration_id='TestIntegration',+ integration_name='DeviceName'+ )++ # Test that values are lowercased during initialization+ self.assertEqual(key.integration_id, 'testintegration')+ self.assertEqual(key.integration_name, 'devicename')++ def test_integration_key_post_init_lowercasing(self):+ """Test that __post_init__ properly lowercases values."""+ # Test with mixed case+ key = IntegrationKey('MixedCase_Integration', 'Mixed_Device_NAME')++ self.assertEqual(key.integration_id, 'mixedcase_integration')+ self.assertEqual(key.integration_name, 'mixed_device_name')++ # Test with already lowercase+ key2 = IntegrationKey('lowercase', 'device')+ self.assertEqual(key2.integration_id, 'lowercase')+ self.assertEqual(key2.integration_name, 'device')++ # Test with uppercase+ key3 = IntegrationKey('UPPERCASE', 'DEVICE')+ self.assertEqual(key3.integration_id, 'uppercase')+ self.assertEqual(key3.integration_name, 'device')++ def test_integration_key_str_representation(self):+ """Test __str__ method returns integration_key_str."""+ key = IntegrationKey('test_integration', 'device_1')++ expected_str = 'test_integration.device_1'+ self.assertEqual(str(key), expected_str)+ self.assertEqual(str(key), key.integration_key_str)++ def test_integration_key_str_property(self):+ """Test integration_key_str property format."""+ key = IntegrationKey('home_assistant', 'light_bedroom')++ expected = 'home_assistant.light_bedroom'+ self.assertEqual(key.integration_key_str, expected)++ # Test with special characters (should be preserved after lowercasing)+ key2 = IntegrationKey('integration_with_underscores', 'device-with-dashes')+ expected2 = 'integration_with_underscores.device-with-dashes'+ self.assertEqual(key2.integration_key_str, expected2)++ def test_integration_key_equality(self):+ """Test __eq__ method for IntegrationKey comparison."""+ key1 = IntegrationKey('test_integration', 'device_1')+ key2 = IntegrationKey('test_integration', 'device_1')+ key3 = IntegrationKey('test_integration', 'device_2')+ key4 = IntegrationKey('other_integration', 'device_1')++ # Test equality+ self.assertEqual(key1, key2)+ self.assertTrue(key1 == key2)++ # Test inequality - different device name+ self.assertNotEqual(key1, key3)+ self.assertFalse(key1 == key3)++ # Test inequality - different integration id+ self.assertNotEqual(key1, key4)+ self.assertFalse(key1 == key4)++ # Test equality with different case (should be equal due to lowercasing)+ key_upper = IntegrationKey('TEST_INTEGRATION', 'DEVICE_1')+ self.assertEqual(key1, key_upper)++ def test_integration_key_equality_with_non_integration_key(self):+ """Test __eq__ method with non-IntegrationKey objects."""+ key = IntegrationKey('test_integration', 'device_1')++ # Test comparison with string+ self.assertNotEqual(key, 'test_integration.device_1')+ self.assertFalse(key == 'test_integration.device_1')++ # Test comparison with None+ self.assertNotEqual(key, None)+ self.assertFalse(key is None)++ # Test comparison with other object types+ self.assertNotEqual(key, 123)+ self.assertNotEqual(key, {'integration_id': 'test', 'integration_name': 'device'})++ def test_integration_key_hash(self):+ """Test __hash__ method for use in sets and dictionaries."""+ key1 = IntegrationKey('test_integration', 'device_1')+ key2 = IntegrationKey('test_integration', 'device_1')+ key3 = IntegrationKey('test_integration', 'device_2')++ # Equal objects should have equal hashes+ self.assertEqual(hash(key1), hash(key2))++ # Different objects should typically have different hashes+ self.assertNotEqual(hash(key1), hash(key3))++ # Test that keys can be used in sets+ key_set = {key1, key2, key3}+ self.assertEqual(len(key_set), 2) # key1 and key2 are equal++ # Test that keys can be used as dictionary keys+ key_dict = {key1: 'value1', key3: 'value3'}+ self.assertEqual(len(key_dict), 2)+ self.assertEqual(key_dict[key2], 'value1') # key2 equals key1++ def test_integration_key_hash_consistency_with_equality(self):+ """Test that hash is consistent with equality across case variations."""+ key_lower = IntegrationKey('test_integration', 'device_1')+ key_upper = IntegrationKey('TEST_INTEGRATION', 'DEVICE_1')+ key_mixed = IntegrationKey('Test_Integration', 'Device_1')++ # All should be equal due to lowercasing+ self.assertEqual(key_lower, key_upper)+ self.assertEqual(key_lower, key_mixed)+ self.assertEqual(key_upper, key_mixed)++ # All should have the same hash+ self.assertEqual(hash(key_lower), hash(key_upper))+ self.assertEqual(hash(key_lower), hash(key_mixed))+ self.assertEqual(hash(key_upper), hash(key_mixed))++ def test_integration_key_from_string_method(self):+ """Test from_string class method for parsing string representations."""+ # Test basic parsing+ key_str = 'home_assistant.light_bedroom'+ key = IntegrationKey.from_string(key_str)++ self.assertEqual(key.integration_id, 'home_assistant')+ self.assertEqual(key.integration_name, 'light_bedroom')++ # Test with complex names containing dots+ complex_str = 'complex_integration.device.with.multiple.dots'+ complex_key = IntegrationKey.from_string(complex_str)++ self.assertEqual(complex_key.integration_id, 'complex_integration')+ self.assertEqual(complex_key.integration_name, 'device.with.multiple.dots')++ # Test round-trip consistency+ original_key = IntegrationKey('test_integration', 'device_name')+ parsed_key = IntegrationKey.from_string(str(original_key))++ self.assertEqual(original_key, parsed_key)++ def test_integration_key_from_string_edge_cases(self):+ """Test from_string method with edge cases."""+ # Test with minimal dot case+ minimal_str = 'a.b'+ minimal_key = IntegrationKey.from_string(minimal_str)++ self.assertEqual(minimal_key.integration_id, 'a')+ self.assertEqual(minimal_key.integration_name, 'b')++ # Test with empty parts+ empty_integration = '.device_name'+ empty_key = IntegrationKey.from_string(empty_integration)++ self.assertEqual(empty_key.integration_id, '')+ self.assertEqual(empty_key.integration_name, 'device_name')++ # Test with special characters after split+ special_str = 'integration_id.device-name_with_special_chars'+ special_key = IntegrationKey.from_string(special_str)++ self.assertEqual(special_key.integration_id, 'integration_id')+ self.assertEqual(special_key.integration_name, 'device-name_with_special_chars')++ def test_integration_key_from_string_invalid_format(self):+ """Test from_string method error handling with invalid formats."""+ # Test string without dot+ with self.assertRaises(ValueError):+ IntegrationKey.from_string('no_dot_in_string')++ # Test empty string+ with self.assertRaises(ValueError):+ IntegrationKey.from_string('')++ # Test None input+ with self.assertRaises(AttributeError):+ IntegrationKey.from_string(None)+++class IntegrationDetailsTestCase(TestCase):+ """Test cases for IntegrationDetails dataclass functionality."""++ def test_integration_details_initialization(self):+ """Test IntegrationDetails initialization with key and payload."""+ key = IntegrationKey('test_integration', 'device_1')+ payload = {'device_type': 'light', 'capabilities': ['brightness', 'color']}++ details = IntegrationDetails(key=key, payload=payload)++ self.assertEqual(details.key, key)+ self.assertEqual(details.payload, payload)++ def test_integration_details_with_none_payload(self):+ """Test IntegrationDetails with None payload (default)."""+ key = IntegrationKey('test_integration', 'device_1')++ # Test default None payload+ details = IntegrationDetails(key=key)++ self.assertEqual(details.key, key)+ self.assertIsNone(details.payload)++ # Test explicit None payload+ details_explicit = IntegrationDetails(key=key, payload=None)++ self.assertEqual(details_explicit.key, key)+ self.assertIsNone(details_explicit.payload)++ def test_integration_details_with_empty_payload(self):+ """Test IntegrationDetails with empty dictionary payload."""+ key = IntegrationKey('test_integration', 'device_1')+ empty_payload = {}++ details = IntegrationDetails(key=key, payload=empty_payload)++ self.assertEqual(details.key, key)+ self.assertEqual(details.payload, {})+ self.assertIsInstance(details.payload, dict)++ def test_integration_details_with_complex_payload(self):+ """Test IntegrationDetails with complex nested payload."""+ key = IntegrationKey('home_assistant', 'climate_thermostat')+ complex_payload = {+ 'device_info': {+ 'manufacturer': 'Nest',+ 'model': 'Learning Thermostat',+ 'sw_version': '5.9.3'+ },+ 'capabilities': {+ 'temperature': {'min': 50, 'max': 90, 'step': 1},+ 'humidity': {'readable': True, 'writable': False}+ },+ 'state': {+ 'current_temperature': 72,+ 'target_temperature': 68,+ 'hvac_mode': 'heat'+ }+ }++ details = IntegrationDetails(key=key, payload=complex_payload)++ self.assertEqual(details.key, key)+ self.assertEqual(details.payload, complex_payload)++ # Test that payload is properly preserved+ self.assertEqual(details.payload['device_info']['manufacturer'], 'Nest')+ self.assertEqual(details.payload['capabilities']['temperature']['max'], 90)++ def test_integration_details_dataclass_behavior(self):+ """Test that IntegrationDetails behaves as expected dataclass."""+ key1 = IntegrationKey('test_integration', 'device_1')+ key2 = IntegrationKey('test_integration', 'device_1')+ payload = {'test': 'value'}++ details1 = IntegrationDetails(key=key1, payload=payload)+ details2 = IntegrationDetails(key=key2, payload=payload)++ # Test equality (should be equal with same content)+ self.assertEqual(details1, details2)++ # Test with different payloads+ details3 = IntegrationDetails(key=key1, payload={'different': 'value'})+ self.assertNotEqual(details1, details3)++ # Test with different keys+ key3 = IntegrationKey('other_integration', 'device_1')+ details4 = IntegrationDetails(key=key3, payload=payload)+ self.assertNotEqual(details1, details4)+++class IntegrationControlResultTestCase(TestCase):+ """Test cases for IntegrationControlResult dataclass functionality."""++ def test_integration_control_result_initialization(self):+ """Test IntegrationControlResult initialization."""+ result = IntegrationControlResult(+ new_value='on',+ error_list=['Connection failed', 'Invalid state']+ )++ self.assertEqual(result.new_value, 'on')+ self.assertEqual(result.error_list, ['Connection failed', 'Invalid state'])++ def test_integration_control_result_has_errors_property(self):+ """Test has_errors property logic."""+ # Test with errors+ result_with_errors = IntegrationControlResult(+ new_value='off',+ error_list=['Network timeout', 'Device not found']+ )++ self.assertTrue(result_with_errors.has_errors)++ # Test with empty error list+ result_no_errors = IntegrationControlResult(+ new_value='on',+ error_list=[]+ )++ self.assertFalse(result_no_errors.has_errors)++ # Test with None error list (if that's possible)+ try:+ result_none_errors = IntegrationControlResult(+ new_value='on',+ error_list=None+ )+ # This would fail the bool() conversion, testing robustness+ _ = result_none_errors.has_errors+ except TypeError:+ # Expected if bool(None) is called+ pass++ def test_integration_control_result_has_errors_edge_cases(self):+ """Test has_errors property with edge cases."""+ # Test with single error+ result_single = IntegrationControlResult(+ new_value='dimmed',+ error_list=['Brightness out of range']+ )++ self.assertTrue(result_single.has_errors)++ # Test with empty strings in error list (should still count as having errors)+ result_empty_strings = IntegrationControlResult(+ new_value='unknown',+ error_list=['', ' ', 'Real error']+ )++ self.assertTrue(result_empty_strings.has_errors)++ # Test with falsy but non-empty error list+ result_falsy = IntegrationControlResult(+ new_value='state',+ error_list=[None, False, 0] # Falsy values but list is not empty+ )++ self.assertTrue(result_falsy.has_errors) # List is not empty, so has_errors = True++ def test_integration_control_result_with_complex_values(self):+ """Test IntegrationControlResult with complex new_value and detailed errors."""+ # Test with JSON-like new value+ complex_value = '{"brightness": 75, "color": {"r": 255, "g": 0, "b": 0}}'+ detailed_errors = [+ 'Color temperature not supported by device',+ 'Brightness adjustment failed: hardware limitation',+ 'State change timeout after 30 seconds'+ ]++ result = IntegrationControlResult(+ new_value=complex_value,+ error_list=detailed_errors+ )++ self.assertEqual(result.new_value, complex_value)+ self.assertEqual(len(result.error_list), 3)+ self.assertTrue(result.has_errors)+ self.assertIn('hardware limitation', result.error_list[1])+++class IntegrationMetaDataTestCase(TestCase):+ """Test cases for IntegrationMetaData dataclass functionality."""++ def test_integration_metadata_initialization(self):+ """Test IntegrationMetaData initialization with all required fields."""+ metadata = IntegrationMetaData(+ integration_id='test_integration',+ label='Test Integration Service',+ attribute_type=MockIntegrationAttributeType,+ allow_entity_deletion=True+ )++ self.assertEqual(metadata.integration_id, 'test_integration')+ self.assertEqual(metadata.label, 'Test Integration Service')+ self.assertEqual(metadata.attribute_type, MockIntegrationAttributeType)+ self.assertTrue(metadata.allow_entity_deletion)++ def test_integration_metadata_with_deletion_disabled(self):+ """Test IntegrationMetaData with entity deletion disabled."""+ metadata = IntegrationMetaData(+ integration_id='readonly_integration',+ label='Read-Only Integration',+ attribute_type=MockIntegrationAttributeType,+ allow_entity_deletion=False+ )++ self.assertFalse(metadata.allow_entity_deletion)+ self.assertEqual(metadata.integration_id, 'readonly_integration')++ def test_integration_metadata_dataclass_behavior(self):+ """Test IntegrationMetaData dataclass equality and representation."""+ metadata1 = IntegrationMetaData(+ integration_id='test_id',+ label='Test Label',+ attribute_type=MockIntegrationAttributeType,+ allow_entity_deletion=True+ )++ metadata2 = IntegrationMetaData(+ integration_id='test_id',+ label='Test Label',+ attribute_type=MockIntegrationAttributeType,+ allow_entity_deletion=True+ )++ # Test equality+ self.assertEqual(metadata1, metadata2)++ # Test inequality with different values+ metadata3 = IntegrationMetaData(+ integration_id='different_id',+ label='Test Label',+ attribute_type=MockIntegrationAttributeType,+ allow_entity_deletion=True+ )++ self.assertNotEqual(metadata1, metadata3)++ def test_integration_metadata_with_different_attribute_types(self):+ """Test IntegrationMetaData with different attribute type enums."""+ # This tests that the attribute_type field can hold different enum classes++ class AlternativeAttributeType(IntegrationAttributeType):+ ALT_ATTR = ('Alternative', 'Alt description', AttributeValueType.BOOLEAN, {}, False, False, 'false')++ metadata1 = IntegrationMetaData(+ integration_id='test_1',+ label='Test 1',+ attribute_type=MockIntegrationAttributeType,+ allow_entity_deletion=True+ )++ metadata2 = IntegrationMetaData(+ integration_id='test_2',+ label='Test 2',+ attribute_type=AlternativeAttributeType,+ allow_entity_deletion=True+ )++ # Test that different attribute types work+ self.assertEqual(metadata1.attribute_type, MockIntegrationAttributeType)+ self.assertEqual(metadata2.attribute_type, AlternativeAttributeType)+ self.assertNotEqual(metadata1.attribute_type, metadata2.attribute_type)++ def test_integration_metadata_field_types(self):+ """Test that IntegrationMetaData enforces expected field types."""+ metadata = IntegrationMetaData(+ integration_id='type_test',+ label='Type Test Integration',+ attribute_type=MockIntegrationAttributeType,+ allow_entity_deletion=True+ )++ # Test field types+ self.assertIsInstance(metadata.integration_id, str)+ self.assertIsInstance(metadata.label, str)+ self.assertIsInstance(metadata.allow_entity_deletion, bool)++ # Test that attribute_type is a class (IntegrationAttributeType subclass)+ self.assertTrue(hasattr(metadata.attribute_type, '__bases__'))+ self.assertIn(IntegrationAttributeType, metadata.attribute_type.__bases__)diff --git a/src/hi/integrations/tests/test_user_data_detector.py b/src/hi/integrations/tests/test_user_data_detector.pyindex cbacee6f..83392355 100644--- a/src/hi/integrations/tests/test_user_data_detector.py+++ b/src/hi/integrations/tests/test_user_data_detector.py@@ -9,6 +9,7 @@ from hi.apps.sense.models import Sensorfrom hi.apps.control.models import Controllerfrom hi.integrations.user_data_detector import EntityUserDataDetector+from django.db import IntegrityErrorclass EntityUserDataDetectorTestCase(TestCase):@@ -33,8 +34,12 @@ class EntityUserDataDetectorTestCase(TestCase):def test_has_user_created_attributes_with_user_data(self):"""Test detection of user-created attributes."""+ # Verify initial state - no user attributes+ result_before = EntityUserDataDetector.has_user_created_attributes(self.entity)+ self.assertFalse(result_before)+# Create a user-created attribute (no integration_key_str)- EntityAttribute.objects.create(+ user_attr = EntityAttribute.objects.create(entity=self.entity,name='User Note',value='This is a user note',@@ -43,13 +48,24 @@ class EntityUserDataDetectorTestCase(TestCase):# integration_key_str is None (user-created))+ # Verify detection of user-created attributeresult = EntityUserDataDetector.has_user_created_attributes(self.entity)self.assertTrue(result)++ # Verify database state remains unchanged (read-only operation)+ user_attr.refresh_from_db()+ self.assertEqual(user_attr.name, 'User Note')+ self.assertEqual(user_attr.value, 'This is a user note')+ self.assertIsNone(user_attr.integration_key_str)++ # Verify entity state unchanged+ self.entity.refresh_from_db()+ self.assertEqual(self.entity.attributes.count(), 1)def test_has_user_created_attributes_with_integration_data_only(self):"""Test that integration-created attributes don't trigger preservation."""# Create an integration-created attribute- EntityAttribute.objects.create(+ integration_attr = EntityAttribute.objects.create(entity=self.entity,name='Integration Data',value='Integration-specific data',@@ -60,16 +76,32 @@ class EntityUserDataDetectorTestCase(TestCase):result = EntityUserDataDetector.has_user_created_attributes(self.entity)self.assertFalse(result)++ # Verify database state remains unchanged+ integration_attr.refresh_from_db()+ self.assertEqual(integration_attr.integration_key_str, 'test_integration:test_device_1')+ self.assertEqual(self.entity.attributes.count(), 1)++ # Verify specifically that only integration attributes exist+ user_attrs = self.entity.attributes.filter(integration_key_str__isnull=True)+ self.assertEqual(user_attrs.count(), 0)def test_has_user_created_attributes_no_attributes(self):"""Test entity with no attributes."""+ # Verify entity has no attributes initially+ self.assertEqual(self.entity.attributes.count(), 0)+result = EntityUserDataDetector.has_user_created_attributes(self.entity)self.assertFalse(result)++ # Verify database state unchanged+ self.entity.refresh_from_db()+ self.assertEqual(self.entity.attributes.count(), 0)def test_has_user_created_attributes_mixed_attributes(self):"""Test entity with both user and integration attributes."""# Create both types- EntityAttribute.objects.create(+ user_attr = EntityAttribute.objects.create(entity=self.entity,name='User Note',value='User data',@@ -77,7 +109,7 @@ class EntityUserDataDetectorTestCase(TestCase):attribute_type_str='DOCUMENTATION'# integration_key_str is None (user-created))- EntityAttribute.objects.create(+ integration_attr = EntityAttribute.objects.create(entity=self.entity,name='Integration Data',value='Integration data',@@ -88,9 +120,23 @@ class EntityUserDataDetectorTestCase(TestCase):result = EntityUserDataDetector.has_user_created_attributes(self.entity)self.assertTrue(result) # Should preserve due to user attribute++ # Verify both attributes exist with correct types+ self.assertEqual(self.entity.attributes.count(), 2)+ user_attrs = self.entity.attributes.filter(integration_key_str__isnull=True)+ integration_attrs = self.entity.attributes.filter(integration_key_str__isnull=False)++ self.assertEqual(user_attrs.count(), 1)+ self.assertEqual(integration_attrs.count(), 1)+ self.assertEqual(user_attrs.first(), user_attr)+ self.assertEqual(integration_attrs.first(), integration_attr)def test_get_integration_related_sensors(self):"""Test identification of integration-related sensors."""+ # Verify initial state - no sensors+ initial_sensor_ids = EntityUserDataDetector.get_integration_related_sensors(self.entity)+ self.assertEqual(len(initial_sensor_ids), 0)+# Create integration sensorintegration_sensor = Sensor.objects.create(name='Integration Sensor',@@ -110,12 +156,28 @@ class EntityUserDataDetectorTestCase(TestCase):sensor_ids = EntityUserDataDetector.get_integration_related_sensors(self.entity)+ # Verify exact result setself.assertEqual(len(sensor_ids), 1)self.assertIn(integration_sensor.id, sensor_ids)self.assertNotIn(user_sensor.id, sensor_ids)+ self.assertEqual(sensor_ids, {integration_sensor.id})++ # Verify database state unchanged (read-only operation)+ integration_sensor.refresh_from_db()+ user_sensor.refresh_from_db()+ self.assertEqual(integration_sensor.integration_id, 'test_integration')+ self.assertIsNone(user_sensor.integration_id)++ # Verify all sensors still exist+ total_sensors = self.entity_state.sensors.count()+ self.assertEqual(total_sensors, 2)def test_get_integration_related_controllers(self):"""Test identification of integration-related controllers."""+ # Verify initial state - no controllers+ initial_controller_ids = EntityUserDataDetector.get_integration_related_controllers(self.entity)+ self.assertEqual(len(initial_controller_ids), 0)+# Create integration controllerintegration_controller = Controller.objects.create(name='Integration Controller',@@ -135,9 +197,21 @@ class EntityUserDataDetectorTestCase(TestCase):controller_ids = EntityUserDataDetector.get_integration_related_controllers(self.entity)+ # Verify exact result setself.assertEqual(len(controller_ids), 1)self.assertIn(integration_controller.id, controller_ids)self.assertNotIn(user_controller.id, controller_ids)+ self.assertEqual(controller_ids, {integration_controller.id})++ # Verify database state unchanged (read-only operation)+ integration_controller.refresh_from_db()+ user_controller.refresh_from_db()+ self.assertEqual(integration_controller.integration_id, 'test_integration')+ self.assertIsNone(user_controller.integration_id)++ # Verify all controllers still exist+ total_controllers = self.entity_state.controllers.count()+ self.assertEqual(total_controllers, 2)def test_get_orphaned_entity_states_all_integration(self):"""Test detection of entity states that become orphaned when all sensors/controllers are integration-related."""@@ -166,8 +240,19 @@ class EntityUserDataDetectorTestCase(TestCase):self.entity, sensor_ids, controller_ids)+ # Verify exact result setself.assertEqual(len(orphaned_ids), 1)self.assertIn(self.entity_state.id, orphaned_ids)+ self.assertEqual(orphaned_ids, {self.entity_state.id})++ # Verify database state unchanged (read-only operation)+ integration_sensor.refresh_from_db()+ integration_controller.refresh_from_db()+ self.entity_state.refresh_from_db()++ # Verify the state still has its components+ self.assertEqual(self.entity_state.sensors.count(), 1)+ self.assertEqual(self.entity_state.controllers.count(), 1)def test_get_orphaned_entity_states_with_remaining_user_components(self):"""Test that entity states with remaining user sensors/controllers are not orphaned."""@@ -181,7 +266,7 @@ class EntityUserDataDetectorTestCase(TestCase):)# Create user sensor (should keep the state)- Sensor.objects.create(+ user_sensor = Sensor.objects.create(name='User Sensor',entity_state=self.entity_state,sensor_type_str='DISCRETE'@@ -196,7 +281,22 @@ class EntityUserDataDetectorTestCase(TestCase):self.entity, sensor_ids, controller_ids)- self.assertEqual(len(orphaned_ids), 0) # State should not be orphaned+ # Verify exact result - no orphaned states+ self.assertEqual(len(orphaned_ids), 0)+ self.assertEqual(orphaned_ids, set())++ # Verify database state unchanged+ integration_sensor.refresh_from_db()+ user_sensor.refresh_from_db()+ self.entity_state.refresh_from_db()++ # Verify the state has both sensors+ self.assertEqual(self.entity_state.sensors.count(), 2)+ remaining_sensors_after_removal = self.entity_state.sensors.exclude(+ id__in=sensor_ids+ )+ self.assertEqual(remaining_sensors_after_removal.count(), 1)+ self.assertEqual(remaining_sensors_after_removal.first(), user_sensor)def test_multiple_entity_states(self):"""Test handling multiple entity states with different orphan status."""@@ -225,7 +325,7 @@ class EntityUserDataDetectorTestCase(TestCase):integration_name='sensor_2')- Sensor.objects.create(+ user_sensor2 = Sensor.objects.create(name='User Sensor 2',entity_state=entity_state2,sensor_type_str='CONTINUOUS'@@ -239,6 +339,213 @@ class EntityUserDataDetectorTestCase(TestCase):self.entity, sensor_ids, controller_ids)+ # Verify exact result setself.assertEqual(len(orphaned_ids), 1)self.assertIn(self.entity_state.id, orphaned_ids)self.assertNotIn(entity_state2.id, orphaned_ids)+ self.assertEqual(orphaned_ids, {self.entity_state.id})++ # Verify database state unchanged+ self.entity_state.refresh_from_db()+ entity_state2.refresh_from_db()++ # Verify entity has both states+ self.assertEqual(self.entity.states.count(), 2)++ # Verify state 2 would retain user sensor+ remaining_sensors_state2 = entity_state2.sensors.exclude(id__in=sensor_ids)+ self.assertEqual(remaining_sensors_state2.count(), 1)+ self.assertEqual(remaining_sensors_state2.first(), user_sensor2)++ # Additional comprehensive test cases++ def test_has_user_created_attributes_with_null_entity(self):+ """Test error handling with null entity parameter."""+ with self.assertRaises(AttributeError):+ EntityUserDataDetector.has_user_created_attributes(None)++ def test_has_user_created_attributes_with_multiple_user_attributes(self):+ """Test detection when multiple user attributes exist."""+ # Create multiple user attributes+ attr1 = EntityAttribute.objects.create(+ entity=self.entity,+ name='User Note 1',+ value='First note',+ value_type_str='TEXT',+ attribute_type_str='DOCUMENTATION'+ )+ attr2 = EntityAttribute.objects.create(+ entity=self.entity,+ name='User Note 2',+ value='Second note',+ value_type_str='TEXT',+ attribute_type_str='CONFIGURATION'+ )++ result = EntityUserDataDetector.has_user_created_attributes(self.entity)+ self.assertTrue(result)++ # Verify both attributes exist and are user-created+ user_attrs = self.entity.attributes.filter(integration_key_str__isnull=True)+ self.assertEqual(user_attrs.count(), 2)+ self.assertIn(attr1, user_attrs)+ self.assertIn(attr2, user_attrs)++ def test_get_integration_related_sensors_entity_with_no_states(self):+ """Test sensor detection for entity with no states."""+ # Create entity with no states+ empty_entity = Entity.objects.create(+ name='Empty Entity',+ entity_type_str='GENERIC',+ integration_id='test_integration',+ integration_name='empty_device'+ )++ sensor_ids = EntityUserDataDetector.get_integration_related_sensors(empty_entity)+ self.assertEqual(len(sensor_ids), 0)+ self.assertEqual(sensor_ids, set())++ def test_get_integration_related_controllers_entity_with_no_states(self):+ """Test controller detection for entity with no states."""+ # Create entity with no states+ empty_entity = Entity.objects.create(+ name='Empty Entity',+ entity_type_str='GENERIC',+ integration_id='test_integration',+ integration_name='empty_device'+ )++ controller_ids = EntityUserDataDetector.get_integration_related_controllers(empty_entity)+ self.assertEqual(len(controller_ids), 0)+ self.assertEqual(controller_ids, set())++ def test_get_integration_related_sensors_multiple_integrations(self):+ """Test sensor detection across multiple integrations."""+ # Create sensors from different integrations+ sensor1 = Sensor.objects.create(+ name='Integration 1 Sensor',+ entity_state=self.entity_state,+ sensor_type_str='DISCRETE',+ integration_id='integration_1',+ integration_name='sensor_1'+ )+ sensor2 = Sensor.objects.create(+ name='Integration 2 Sensor',+ entity_state=self.entity_state,+ sensor_type_str='DISCRETE',+ integration_id='integration_2',+ integration_name='sensor_2'+ )+ user_sensor = Sensor.objects.create(+ name='User Sensor',+ entity_state=self.entity_state,+ sensor_type_str='DISCRETE'+ )++ sensor_ids = EntityUserDataDetector.get_integration_related_sensors(self.entity)++ # Verify all integration sensors are detected, user sensor is not+ self.assertEqual(len(sensor_ids), 2)+ self.assertIn(sensor1.id, sensor_ids)+ self.assertIn(sensor2.id, sensor_ids)+ self.assertNotIn(user_sensor.id, sensor_ids)+ self.assertEqual(sensor_ids, {sensor1.id, sensor2.id})++ def test_get_orphaned_entity_states_empty_removal_sets(self):+ """Test orphan detection with empty removal sets."""+ # Create sensors and controllers+ Sensor.objects.create(+ name='Test Sensor',+ entity_state=self.entity_state,+ sensor_type_str='DISCRETE',+ integration_id='test_integration',+ integration_name='sensor_1'+ )+ Controller.objects.create(+ name='Test Controller',+ entity_state=self.entity_state,+ controller_type_str='DISCRETE',+ integration_id='test_integration',+ integration_name='controller_1'+ )++ # Test with empty removal sets - no states should be orphaned+ orphaned_ids = EntityUserDataDetector.get_orphaned_entity_states(+ self.entity, set(), set()+ )++ self.assertEqual(len(orphaned_ids), 0)+ self.assertEqual(orphaned_ids, set())++ def test_get_orphaned_entity_states_no_components(self):+ """Test orphan detection for state with no sensors or controllers."""+ # EntityState exists but has no sensors or controllers+ orphaned_ids = EntityUserDataDetector.get_orphaned_entity_states(+ self.entity, set(), set()+ )++ # State with no components should be orphaned+ self.assertEqual(len(orphaned_ids), 1)+ self.assertIn(self.entity_state.id, orphaned_ids)++ def test_integration_key_str_consistency(self):+ """Test that integration_key_str format is handled consistently."""+ # Test various integration key formats+ test_keys = [+ 'simple_key',+ 'integration:device',+ 'complex.integration:device_name_with_underscores',+ 'integration:device:sub_component'+ ]++ for key in test_keys:+ with self.subTest(integration_key=key):+ # Create attribute with specific integration key+ attr = EntityAttribute.objects.create(+ entity=self.entity,+ name=f'Test Attr {key}',+ value='test value',+ value_type_str='TEXT',+ attribute_type_str='CONFIGURATION',+ integration_key_str=key+ )++ # Should not be detected as user-created+ result = EntityUserDataDetector.has_user_created_attributes(self.entity)+ self.assertFalse(result)++ # Clean up for next iteration+ attr.delete()++ def test_database_constraint_behavior(self):+ """Test database constraints for integration keys."""+ from django.db import transaction++ # Test unique constraint on Entity integration key+ with transaction.atomic():+ with self.assertRaises(IntegrityError):+ Entity.objects.create(+ name='Duplicate Entity',+ entity_type_str='LIGHT',+ integration_id='test_integration', # Same as setUp entity+ integration_name='test_device_1' # Same as setUp entity+ )++ # Test unique constraint on Sensor integration key+ Sensor.objects.create(+ name='Sensor 1',+ entity_state=self.entity_state,+ sensor_type_str='DISCRETE',+ integration_id='test_sensor_integration',+ integration_name='sensor_device_1'+ )++ with transaction.atomic():+ with self.assertRaises(IntegrityError):+ Sensor.objects.create(+ name='Duplicate Sensor',+ entity_state=self.entity_state,+ sensor_type_str='DISCRETE',+ integration_id='test_sensor_integration', # Same as sensor1+ integration_name='sensor_device_1' # Same as sensor1+ )diff --git a/src/hi/integrations/transient_models.py b/src/hi/integrations/transient_models.pyindex 873f49ad..e46629e3 100644--- a/src/hi/integrations/transient_models.py+++ b/src/hi/integrations/transient_models.py@@ -32,7 +32,7 @@ class IntegrationKey:integration_name : str # Name or identifier that is used by the external source.def __post_init__(self):- # Want to make matching more robust, so only+ # Want to make matching more robust, so convert to lowercaseself.integration_id = self.integration_id.lower()self.integration_name = self.integration_name.lower()returndiff --git a/src/hi/services/hass/hass_manager.py b/src/hi/services/hass/hass_manager.pyindex 05adec7b..00054864 100644--- a/src/hi/services/hass/hass_manager.py+++ b/src/hi/services/hass/hass_manager.py@@ -45,8 +45,8 @@ class HassManager( Singleton ):for callback in self._change_listeners:try:callback()- except Exception as e:- logger.exception( 'Problem calling setting change callback.', e )+ except Exception:+ logger.exception( 'Problem calling setting change callback.' )continuereturndiff --git a/src/hi/services/hass/tests/test_hass_client.py b/src/hi/services/hass/tests/test_hass_client.pynew file mode 100644index 00000000..2e55a46f--- /dev/null+++ b/src/hi/services/hass/tests/test_hass_client.py@@ -0,0 +1,906 @@+import json+import os+from unittest.mock import Mock, patch+from django.test import TestCase+from requests.exceptions import ConnectionError++from hi.services.hass.hass_client import HassClient+from hi.services.hass.hass_models import HassState+++class TestHassClientInitialization(TestCase):+ """Test HassClient initialization and configuration"""++ def test_init_with_valid_options(self):+ """Test HassClient initialization with valid API options"""+ api_options = {+ 'api_base_url': 'https://test.homeassistant.io:8123',+ 'api_token': 'test_token_123456'+ }++ client = HassClient(api_options)++ self.assertEqual(client._api_base_url, 'https://test.homeassistant.io:8123')+ self.assertEqual(client._headers['Authorization'], 'Bearer test_token_123456')+ self.assertEqual(client._headers['content-type'], 'application/json')++ def test_init_strips_trailing_slash_from_url(self):+ """Test URL trailing slash is stripped during initialization"""+ api_options = {+ 'api_base_url': 'https://test.homeassistant.io:8123/', # With trailing slash+ 'api_token': 'test_token_123456'+ }++ client = HassClient(api_options)++ self.assertEqual(client._api_base_url, 'https://test.homeassistant.io:8123')++ def test_init_missing_base_url_raises_assertion(self):+ """Test initialization fails with missing API base URL"""+ api_options = {+ 'api_token': 'test_token_123456'+ # Missing api_base_url+ }++ with self.assertRaises(AssertionError):+ HassClient(api_options)++ def test_init_missing_token_raises_assertion(self):+ """Test initialization fails with missing API token"""+ api_options = {+ 'api_base_url': 'https://test.homeassistant.io:8123'+ # Missing api_token+ }++ with self.assertRaises(AssertionError):+ HassClient(api_options)++ def test_init_none_values_raise_assertion(self):+ """Test initialization fails with None values"""+ api_options_with_none_url = {+ 'api_base_url': None,+ 'api_token': 'test_token_123456'+ }++ with self.assertRaises(AssertionError):+ HassClient(api_options_with_none_url)++ api_options_with_none_token = {+ 'api_base_url': 'https://test.homeassistant.io:8123',+ 'api_token': None+ }++ with self.assertRaises(AssertionError):+ HassClient(api_options_with_none_token)+++class TestHassClientStatesMethod(TestCase):+ """Test states() method with focus on real behavior and error handling"""++ def setUp(self):+ self.api_options = {+ 'api_base_url': 'https://test.homeassistant.io:8123',+ 'api_token': 'test_token_123456'+ }+ self.client = HassClient(self.api_options)++ def test_states_returns_empty_list_for_empty_response(self):+ """Test states() returns empty list when HASS returns no entities"""+ with patch('hi.services.hass.hass_client.get') as mock_get:+ mock_response = Mock()+ mock_response.text = '[]'+ mock_get.return_value = mock_response++ result = self.client.states()++ self.assertEqual(result, [])+ self.assertIsInstance(result, list)++ def test_states_processes_real_hass_data_correctly(self):+ """Test states() correctly transforms real HASS JSON into HassState objects"""+ # Use real HASS data structure from our test files+ test_data_dir = os.path.join(os.path.dirname(__file__), 'data')+ with open(os.path.join(test_data_dir, 'hass-states.json'), 'r') as f:+ real_hass_data = json.load(f)++ with patch('hi.services.hass.hass_client.get') as mock_get:+ mock_response = Mock()+ mock_response.text = json.dumps(real_hass_data)+ mock_get.return_value = mock_response++ result = self.client.states()++ # Verify data transformation quality+ self.assertEqual(len(result), len(real_hass_data))+ self.assertIsInstance(result, list)++ # Test that HassConverter properly processes each entity+ for i, state in enumerate(result):+ original_data = real_hass_data[i]+ self.assertIsInstance(state, HassState)+ self.assertEqual(state.entity_id, original_data['entity_id'])+ self.assertEqual(state.state_value, original_data['state'])+ self.assertIn('.', state.entity_id) # Proper domain.name format+ # Verify domain extraction works+ expected_domain = original_data['entity_id'].split('.')[0]+ self.assertEqual(state.domain, expected_domain)++ def test_states_network_error_handling(self):+ """Test states() handles network connection errors properly"""+ with patch('hi.services.hass.hass_client.get') as mock_get:+ mock_get.side_effect = ConnectionError("Connection refused")++ with self.assertRaises(ConnectionError):+ self.client.states()++ def test_states_propagates_json_decode_errors(self):+ """Test states() properly propagates JSON parsing errors with context"""+ with patch('hi.services.hass.hass_client.get') as mock_get:+ mock_response = Mock()+ mock_response.text = 'invalid json {"incomplete"'+ mock_get.return_value = mock_response++ with self.assertRaises(json.JSONDecodeError) as context:+ self.client.states()++ # Verify the error provides useful information for debugging+ self.assertIn('Expecting', str(context.exception))++ def test_states_handles_single_entity_response(self):+ """Test states() correctly processes single entity response"""+ single_entity = {+ 'entity_id': 'sensor.temperature',+ 'state': '22.5',+ 'attributes': {+ 'unit_of_measurement': '°C',+ 'device_class': 'temperature'+ }+ }++ with patch('hi.services.hass.hass_client.get') as mock_get:+ mock_response = Mock()+ mock_response.text = json.dumps([single_entity])+ mock_get.return_value = mock_response++ result = self.client.states()++ self.assertEqual(len(result), 1)+ state = result[0]+ self.assertEqual(state.entity_id, 'sensor.temperature')+ self.assertEqual(state.state_value, '22.5')+ self.assertEqual(state.domain, 'sensor')+ self.assertEqual(state.unit_of_measurement, '°C')+ self.assertEqual(state.device_class, 'temperature')++ def test_states_preserves_entity_attributes_and_metadata(self):+ """Test states() preserves important entity attributes from HASS response"""+ sample_entity = {+ 'entity_id': 'light.kitchen_light',+ 'state': 'on',+ 'attributes': {+ 'friendly_name': 'Kitchen Light',+ 'brightness': 200,+ 'device_class': 'light'+ },+ 'context': {'id': 'test-context'},+ 'last_changed': '2023-01-01T12:00:00Z',+ 'last_updated': '2023-01-01T12:00:00Z'+ }++ with patch('hi.services.hass.hass_client.get') as mock_get:+ mock_response = Mock()+ mock_response.text = json.dumps([sample_entity])+ mock_get.return_value = mock_response++ result = self.client.states()++ self.assertEqual(len(result), 1)+ hass_state = result[0]++ # Verify attribute preservation+ self.assertEqual(hass_state.friendly_name, 'Kitchen Light')+ self.assertEqual(hass_state.attributes['brightness'], 200)+ self.assertEqual(hass_state.device_class, 'light')+ self.assertEqual(hass_state.domain, 'light')+ self.assertEqual(hass_state.entity_name_sans_prefix, 'kitchen_light')+++class TestHassClientSetStateMethod(TestCase):+ """Test set_state() method HTTP calls and error handling"""++ def setUp(self):+ self.api_options = {+ 'api_base_url': 'https://test.homeassistant.io:8123',+ 'api_token': 'test_token_123456'+ }+ self.client = HassClient(self.api_options)++ @patch('hi.services.hass.hass_client.post')+ def test_set_state_returns_response_data_without_attributes(self, mock_post):+ """Test set_state returns parsed JSON response for successful calls without attributes"""+ expected_response_data = {+ 'entity_id': 'light.living_room',+ 'state': 'on',+ 'last_changed': '2023-01-01T12:00:00Z',+ 'context': {'id': 'test-context'}+ }++ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = expected_response_data+ mock_post.return_value = mock_response++ result = self.client.set_state('light.living_room', 'on')++ # Test the actual return value, not the mock call+ self.assertEqual(result, expected_response_data)+ self.assertIn('entity_id', result)+ self.assertIn('state', result)+ self.assertIn('last_changed', result)+ self.assertEqual(result['entity_id'], 'light.living_room')+ self.assertEqual(result['state'], 'on')++ @patch('hi.services.hass.hass_client.post')+ def test_set_state_includes_attributes_in_response(self, mock_post):+ """Test set_state properly handles attributes and returns updated entity state"""+ input_attributes = {'brightness': 255, 'color_temp': 300}+ expected_response = {+ 'entity_id': 'light.living_room',+ 'state': 'on',+ 'attributes': {+ 'brightness': 255,+ 'color_temp': 300,+ 'friendly_name': 'Living Room Light'+ }+ }++ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = expected_response+ mock_post.return_value = mock_response++ result = self.client.set_state('light.living_room', 'on', input_attributes)++ # Test that attributes are preserved in the response+ self.assertEqual(result, expected_response)+ self.assertEqual(result['attributes']['brightness'], 255)+ self.assertEqual(result['attributes']['color_temp'], 300)+ self.assertIn('friendly_name', result['attributes']) # HASS may add additional attributes++ @patch('hi.services.hass.hass_client.post')+ def test_set_state_raises_descriptive_error_for_bad_requests(self, mock_post):+ """Test set_state raises ValueError with descriptive message for HTTP 400 errors"""+ mock_response = Mock()+ mock_response.status_code = 400+ mock_response.text = 'Invalid entity ID format'+ mock_post.return_value = mock_response++ with self.assertRaises(ValueError) as context:+ self.client.set_state('invalid.entity.format', 'on')++ error_message = str(context.exception)+ self.assertIn('Failed to set state', error_message)+ self.assertIn('400', error_message)+ self.assertIn('Invalid entity ID format', error_message)++ @patch('hi.services.hass.hass_client.post')+ def test_set_state_distinguishes_between_error_types(self, mock_post):+ """Test set_state provides different error messages for different HTTP error types"""+ # Test 404 error+ mock_response = Mock()+ mock_response.status_code = 404+ mock_response.text = 'Entity not found'+ mock_post.return_value = mock_response++ with self.assertRaises(ValueError) as context:+ self.client.set_state('light.nonexistent', 'on')++ error_404 = str(context.exception)+ self.assertIn('404', error_404)+ self.assertIn('Entity not found', error_404)++ # Test 403 error+ mock_response.status_code = 403+ mock_response.text = 'Forbidden - read-only entity'++ with self.assertRaises(ValueError) as context:+ self.client.set_state('sensor.readonly', 'value')++ error_403 = str(context.exception)+ self.assertIn('403', error_403)+ self.assertIn('Forbidden', error_403)++ # Verify error messages are different+ self.assertNotEqual(error_404, error_403)++ @patch('hi.services.hass.hass_client.post')+ def test_set_state_json_response_parsing_error(self, mock_post):+ """Test set_state handles JSON response parsing errors"""+ # Mock response with invalid JSON+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.side_effect = json.JSONDecodeError("Invalid JSON", "", 0)+ mock_post.return_value = mock_response++ with self.assertRaises(json.JSONDecodeError):+ self.client.set_state('light.living_room', 'on')+++class TestHassClientCallServiceMethod(TestCase):+ """Test call_service() method HTTP calls and error handling"""++ def setUp(self):+ self.api_options = {+ 'api_base_url': 'https://test.homeassistant.io:8123',+ 'api_token': 'test_token_123456'+ }+ self.client = HassClient(self.api_options)++ @patch('hi.services.hass.hass_client.post')+ def test_call_service_returns_response_object(self, mock_post):+ """Test call_service returns the actual response object for successful calls"""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.headers = {'content-type': 'application/json'}+ mock_response.json.return_value = [{'context': {'id': 'service-call-context'}}]+ mock_post.return_value = mock_response++ result = self.client.call_service('light', 'turn_on', 'light.living_room')++ # Test that we get the actual response object back+ self.assertEqual(result, mock_response)+ self.assertEqual(result.status_code, 200)+ self.assertIn('content-type', result.headers)+ # Verify the response can be used for further processing+ response_data = result.json()+ self.assertIsInstance(response_data, list)++ @patch('hi.services.hass.hass_client.post')+ def test_call_service_merges_service_data_correctly(self, mock_post):+ """Test call_service properly merges entity_id with additional service data"""+ mock_response = Mock()+ mock_response.status_code = 201 # Test that 201 is also accepted+ mock_post.return_value = mock_response++ service_data = {'brightness': 255, 'color_temp': 300}+ result = self.client.call_service('light', 'turn_on', 'light.living_room', service_data)++ # Verify the response is returned (testing behavior, not mock calls)+ self.assertEqual(result, mock_response)+ self.assertEqual(result.status_code, 201)++ # Verify data merging by checking the call was made with merged data+ mock_post.assert_called_once()+ call_data = mock_post.call_args[1]['json']+ self.assertEqual(call_data['entity_id'], 'light.living_room')+ self.assertEqual(call_data['brightness'], 255)+ self.assertEqual(call_data['color_temp'], 300)+ self.assertEqual(len(call_data), 3) # Should have exactly 3 keys++ @patch('hi.services.hass.hass_client.post')+ def test_call_service_raises_descriptive_errors_for_invalid_requests(self, mock_post):+ """Test call_service provides meaningful error messages for invalid service calls"""+ mock_response = Mock()+ mock_response.status_code = 400+ mock_response.text = 'Service light.invalid_service not found'+ mock_post.return_value = mock_response++ with self.assertRaises(ValueError) as context:+ self.client.call_service('light', 'invalid_service', 'light.living_room')++ error_message = str(context.exception)+ self.assertIn('Failed to call service', error_message)+ self.assertIn('400', error_message)+ self.assertIn('Service light.invalid_service not found', error_message)++ @patch('hi.services.hass.hass_client.post')+ def test_call_service_rejects_unacceptable_status_codes(self, mock_post):+ """Test call_service raises errors for status codes other than 200 and 201"""+ # Test various error status codes+ error_scenarios = [+ (404, 'Domain unknown_domain not found'),+ (403, 'Access denied for this service'),+ (500, 'Internal server error'),+ (422, 'Unprocessable entity data')+ ]++ for status_code, error_text in error_scenarios:+ with self.subTest(status_code=status_code):+ mock_response = Mock()+ mock_response.status_code = status_code+ mock_response.text = error_text+ mock_post.return_value = mock_response++ with self.assertRaises(ValueError) as context:+ self.client.call_service('test_domain', 'test_service', 'test.entity')++ error_message = str(context.exception)+ self.assertIn('Failed to call service', error_message)+ self.assertIn(str(status_code), error_message)+ self.assertIn(error_text, error_message)++ @patch('hi.services.hass.hass_client.post')+ def test_call_service_accepts_multiple_success_status_codes(self, mock_post):+ """Test call_service treats both 200 and 201 as successful responses"""+ # Test 200 response+ mock_response_200 = Mock()+ mock_response_200.status_code = 200+ mock_post.return_value = mock_response_200++ result1 = self.client.call_service('light', 'turn_on', 'light.living_room')+ self.assertEqual(result1, mock_response_200)+ self.assertEqual(result1.status_code, 200)++ # Test 201 response+ mock_response_201 = Mock()+ mock_response_201.status_code = 201+ mock_post.return_value = mock_response_201++ result2 = self.client.call_service('light', 'turn_off', 'light.living_room')+ self.assertEqual(result2, mock_response_201)+ self.assertEqual(result2.status_code, 201)++ # Both should return successfully without raising exceptions+ self.assertIsNotNone(result1)+ self.assertIsNotNone(result2)++ @patch('hi.services.hass.hass_client.post')+ def test_call_service_handles_empty_service_data_correctly(self, mock_post):+ """Test call_service works correctly when service_data is None or empty"""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_post.return_value = mock_response++ # Test with None service_data+ result1 = self.client.call_service('switch', 'turn_off', 'switch.kitchen', None)+ self.assertEqual(result1, mock_response)++ # Test with empty dict service_data+ result2 = self.client.call_service('switch', 'turn_on', 'switch.kitchen', {})+ self.assertEqual(result2, mock_response)++ # Verify both calls were made correctly+ self.assertEqual(mock_post.call_count, 2)++ # Check that entity_id is present in both calls+ for call in mock_post.call_args_list:+ call_data = call[1]['json']+ self.assertIn('entity_id', call_data)+ self.assertEqual(call_data['entity_id'], 'switch.kitchen')++ @patch('hi.services.hass.hass_client.post')+ def test_call_service_constructs_correct_service_urls(self, mock_post):+ """Test call_service builds correct URLs for different domain/service combinations"""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_post.return_value = mock_response++ # Test URL construction for different service types+ result1 = self.client.call_service('light', 'turn_on', 'light.bedroom')+ result2 = self.client.call_service('climate', 'set_temperature', 'climate.thermostat')++ # Verify both calls succeeded+ self.assertEqual(result1, mock_response)+ self.assertEqual(result2, mock_response)++ # Verify correct URLs were constructed+ call_args_list = mock_post.call_args_list+ self.assertEqual(len(call_args_list), 2)++ # Check first call URL+ first_url = call_args_list[0][0][0]+ self.assertEqual(first_url, 'https://test.homeassistant.io:8123/api/services/light/turn_on')++ # Check second call URL+ second_url = call_args_list[1][0][0]+ self.assertEqual(second_url, 'https://test.homeassistant.io:8123/api/services/climate/set_temperature')++ # Verify entity_id is included in request data+ first_data = call_args_list[0][1]['json']+ second_data = call_args_list[1][1]['json']+ self.assertEqual(first_data['entity_id'], 'light.bedroom')+ self.assertEqual(second_data['entity_id'], 'climate.thermostat')+++class TestHassClientConstants(TestCase):+ """Test HassClient constants and class attributes"""++ def test_api_constants(self):+ """Test API constant values"""+ self.assertEqual(HassClient.API_BASE_URL, 'api_base_url')+ self.assertEqual(HassClient.API_TOKEN, 'api_token')++ def test_trace_constant_default(self):+ """Test TRACE constant default value"""+ self.assertFalse(HassClient.TRACE)++ def test_trace_constant_modifiable(self):+ """Test TRACE constant can be modified for debugging"""+ original_value = HassClient.TRACE++ try:+ HassClient.TRACE = True+ self.assertTrue(HassClient.TRACE)++ HassClient.TRACE = False+ self.assertFalse(HassClient.TRACE)+ finally:+ # Reset to original value+ HassClient.TRACE = original_value+++class TestHassClientEdgeCases(TestCase):+ """Test edge cases and error scenarios"""++ def setUp(self):+ self.api_options = {+ 'api_base_url': 'https://test.homeassistant.io:8123',+ 'api_token': 'test_token_123456'+ }+ self.client = HassClient(self.api_options)++ def test_trailing_slash_normalization_affects_api_calls(self):+ """Test that trailing slash normalization produces correct API endpoints"""+ # Test with trailing slash+ api_options_with_slash = {+ 'api_base_url': 'https://ha.example.com/',+ 'api_token': 'test_token'+ }+ client_with_slash = HassClient(api_options_with_slash)++ # Test without trailing slash+ api_options_without_slash = {+ 'api_base_url': 'https://ha.example.com',+ 'api_token': 'test_token'+ }+ client_without_slash = HassClient(api_options_without_slash)++ # Both should normalize to the same base URL+ self.assertEqual(client_with_slash._api_base_url, client_without_slash._api_base_url)+ self.assertEqual(client_with_slash._api_base_url, 'https://ha.example.com')++ # Mock an API call to verify the URL construction works correctly+ with patch('hi.services.hass.hass_client.get') as mock_get:+ mock_response = Mock()+ mock_response.text = '[]'+ mock_get.return_value = mock_response++ client_with_slash.states()++ # Verify the URL doesn't have double slashes+ called_url = mock_get.call_args[0][0]+ self.assertEqual(called_url, 'https://ha.example.com/api/states')+ self.assertNotIn('//', called_url.replace('https://', ''))++ @patch('hi.services.hass.hass_client.get')+ def test_states_empty_response(self, mock_get):+ """Test states method with empty response"""+ mock_response = Mock()+ mock_response.text = '[]'+ mock_get.return_value = mock_response++ result = self.client.states()++ self.assertEqual(result, [])++ @patch('hi.services.hass.hass_client.post')+ def test_set_state_empty_attributes(self, mock_post):+ """Test set_state with empty attributes dictionary"""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = {}+ mock_post.return_value = mock_response++ # Empty dict should not add attributes to payload+ self.client.set_state('light.test', 'on', {})++ expected_data = {'state': 'on'}+ mock_post.assert_called_once()+ call_args = mock_post.call_args+ self.assertEqual(call_args[1]['json'], expected_data)++ @patch('hi.services.hass.hass_client.post')+ def test_call_service_empty_service_data(self, mock_post):+ """Test call_service with empty service data dictionary"""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_post.return_value = mock_response++ # Empty dict should not add extra data to payload+ self.client.call_service('light', 'turn_on', 'light.test', {})++ expected_data = {'entity_id': 'light.test'}+ mock_post.assert_called_once()+ call_args = mock_post.call_args+ self.assertEqual(call_args[1]['json'], expected_data)+++class TestHassClientWithRealData(TestCase):+ """Test HassClient with real Home Assistant API response data"""++ @classmethod+ def setUpClass(cls):+ super().setUpClass()+ # Load real HASS API response data+ test_data_dir = os.path.join(os.path.dirname(__file__), 'data')+ with open(os.path.join(test_data_dir, 'hass-states.json'), 'r') as f:+ cls.real_hass_states_data = json.load(f)++ def setUp(self):+ self.api_options = {+ 'api_base_url': 'https://test.homeassistant.io:8123',+ 'api_token': 'test_token_123456'+ }+ self.client = HassClient(self.api_options)++ @patch('hi.services.hass.hass_client.get')+ def test_states_integrates_with_real_hass_data_end_to_end(self, mock_get):+ """Test states() method processes real HASS data through entire pipeline"""+ # Use real HASS data without mocking the converter+ mock_response = Mock()+ mock_response.text = json.dumps(self.real_hass_states_data)+ mock_get.return_value = mock_response++ result = self.client.states()++ # Test end-to-end behavior: real data -> real converter -> real HassState objects+ self.assertEqual(len(result), len(self.real_hass_states_data))++ # Verify each HassState was created correctly from real data+ for i, hass_state in enumerate(result):+ original_entity = self.real_hass_states_data[i]++ # Test the actual HassState object properties+ self.assertIsInstance(hass_state, HassState)+ self.assertEqual(hass_state.entity_id, original_entity['entity_id'])+ self.assertEqual(hass_state.state_value, original_entity['state'])++ # Test domain parsing worked correctly+ expected_domain = original_entity['entity_id'].split('.')[0]+ self.assertEqual(hass_state.domain, expected_domain)++ # Test attribute access works+ if 'attributes' in original_entity and original_entity['attributes']:+ original_attrs = original_entity['attributes']+ if 'friendly_name' in original_attrs:+ self.assertEqual(hass_state.friendly_name, original_attrs['friendly_name'])+ if 'device_class' in original_attrs:+ self.assertEqual(hass_state.device_class, original_attrs['device_class'])++ def test_real_hass_data_diversity_validation(self):+ """Test that our real HASS data covers diverse entity types and configurations"""+ entity_ids = [entity['entity_id'] for entity in self.real_hass_states_data]++ # Extract domains from entity IDs+ domains = set()+ for entity_id in entity_ids:+ if '.' in entity_id:+ domain = entity_id.split('.', 1)[0]+ domains.add(domain)++ # Verify we have diverse entity types+ expected_domains = ['person', 'zone', 'script', 'camera', 'sensor']+ for expected_domain in expected_domains:+ self.assertIn(expected_domain, domains,+ f"Should have {expected_domain} entities in test data")++ # Verify we have a good number of entities for testing+ self.assertGreaterEqual(len(entity_ids), 10, "Should have substantial test data")++ # Verify entity ID format consistency+ for entity_id in entity_ids:+ self.assertIn('.', entity_id, f"Entity ID should contain domain: {entity_id}")+ self.assertGreater(len(entity_id.split('.', 1)[1]), 0,+ f"Entity name should not be empty: {entity_id}")++ def test_real_hass_data_structure_validation(self):+ """Test that real HASS data has expected structure for API responses"""+ for i, entity_data in enumerate(self.real_hass_states_data[:5]): # Test first 5 entities+ with self.subTest(entity_index=i):+ # Verify required top-level fields+ required_fields = ['entity_id', 'state', 'attributes', 'context',+ 'last_changed', 'last_reported', 'last_updated']+ for field in required_fields:+ self.assertIn(field, entity_data,+ f"Entity {i} missing required field: {field}")++ # Verify entity_id format+ entity_id = entity_data['entity_id']+ self.assertIsInstance(entity_id, str)+ self.assertIn('.', entity_id)++ # Verify state field+ self.assertIn('state', entity_data)+ # State can be various types (string, number, etc.)++ # Verify attributes is a dictionary+ self.assertIsInstance(entity_data['attributes'], dict)++ # Verify context structure+ context = entity_data['context']+ self.assertIsInstance(context, dict)+ self.assertIn('id', context)++ @patch('hi.services.hass.hass_client.post')+ def test_set_state_with_real_entity_ids(self, mock_post):+ """Test set_state() with real entity IDs from our HASS setup"""+ # Mock successful response+ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = {'state': 'on'}+ mock_post.return_value = mock_response++ # Test with various real entity types+ real_entity_samples = [+ ('camera.frontcamera', 'idle'),+ ('sensor.frontcamera_status', 'Connected'),+ ('script.play_door_chime', 'off'),+ ('zone.home', '1'),+ ]++ for entity_id, state_value in real_entity_samples:+ with self.subTest(entity_id=entity_id):+ mock_post.reset_mock()+ mock_response.json.reset_mock()+ mock_response.json.return_value = {'entity_id': entity_id, 'state': state_value}++ result = self.client.set_state(entity_id, state_value)++ # Verify correct URL construction+ expected_url = f'https://test.homeassistant.io:8123/api/states/{entity_id}'+ mock_post.assert_called_once()+ self.assertEqual(mock_post.call_args[0][0], expected_url)++ # Verify result+ self.assertEqual(result['entity_id'], entity_id)+ self.assertEqual(result['state'], state_value)++ @patch('hi.services.hass.hass_client.post')+ def test_call_service_with_real_domain_service_combinations(self, mock_post):+ """Test call_service() with realistic domain/service combinations from our setup"""+ # Mock successful response+ mock_response = Mock()+ mock_response.status_code = 200+ mock_post.return_value = mock_response++ # Test realistic service calls based on our entity types+ real_service_calls = [+ ('script', 'turn_on', 'script.play_door_chime'),+ ('script', 'turn_off', 'script.play_door_chime'),+ ('camera', 'enable_motion_detection', 'camera.frontcamera'),+ ('camera', 'disable_motion_detection', 'camera.patiocamera'),+ ('person', 'set_location', 'person.cassandra'),+ ]++ for domain, service, entity_id in real_service_calls:+ with self.subTest(domain=domain, service=service, entity_id=entity_id):+ mock_post.reset_mock()++ self.client.call_service(domain, service, entity_id)++ # Verify correct URL construction+ expected_url = f'https://test.homeassistant.io:8123/api/services/{domain}/{service}'+ mock_post.assert_called_once()+ self.assertEqual(mock_post.call_args[0][0], expected_url)++ # Verify entity_id in request data+ call_data = mock_post.call_args[1]['json']+ self.assertEqual(call_data['entity_id'], entity_id)++ @patch('hi.services.hass.hass_client.post')+ def test_call_service_with_real_camera_service_data(self, mock_post):+ """Test call_service() with realistic service data for camera entities"""+ mock_response = Mock()+ mock_response.status_code = 200+ mock_post.return_value = mock_response++ # Test camera-specific service calls with additional data+ camera_service_data = {+ 'motion_detection': True,+ 'infrared_mode': 'auto',+ 'sensitivity': 85+ }++ self.client.call_service(+ 'camera',+ 'set_motion_detection',+ 'camera.frontcamera',+ camera_service_data+ )++ # Verify service data is merged correctly+ expected_data = {+ 'entity_id': 'camera.frontcamera',+ 'motion_detection': True,+ 'infrared_mode': 'auto',+ 'sensitivity': 85+ }++ mock_post.assert_called_once()+ call_data = mock_post.call_args[1]['json']+ self.assertEqual(call_data, expected_data)++ def test_real_entity_id_domain_extraction(self):+ """Test entity ID domain extraction works with real entity patterns"""+ real_entities_by_domain = {}++ # Group real entities by domain+ for entity_data in self.real_hass_states_data:+ entity_id = entity_data['entity_id']+ domain = entity_id.split('.', 1)[0]++ if domain not in real_entities_by_domain:+ real_entities_by_domain[domain] = []+ real_entities_by_domain[domain].append(entity_id)++ # Verify we have expected domains with multiple entities+ self.assertIn('camera', real_entities_by_domain)+ self.assertIn('sensor', real_entities_by_domain)++ # Verify camera entities follow expected pattern+ camera_entities = real_entities_by_domain.get('camera', [])+ self.assertGreater(len(camera_entities), 3, "Should have multiple camera entities")++ # Verify sensor entities follow expected pattern+ sensor_entities = real_entities_by_domain.get('sensor', [])+ self.assertGreater(len(sensor_entities), 5, "Should have multiple sensor entities")++ # Verify entity naming patterns match our camera setup+ camera_names = [entity.split('.', 1)[1] for entity in camera_entities]+ expected_cameras = ['frontcamera', 'patiocamera', 'sidecamera']+ for expected_camera in expected_cameras:+ self.assertIn(expected_camera, camera_names,+ f"Should have {expected_camera} in our test data")++ @patch('hi.services.hass.hass_client.get')+ def test_states_json_parsing_with_real_complex_attributes(self, mock_get):+ """Test JSON parsing handles complex real attributes from HASS entities"""+ # Use subset of real data with complex attributes+ complex_entities = []+ for entity_data in self.real_hass_states_data[:3]:+ # Real entities have complex nested attributes+ if entity_data['attributes']:+ complex_entities.append(entity_data)++ self.assertGreater(len(complex_entities), 0, "Should have entities with complex attributes")++ mock_response = Mock()+ mock_response.text = json.dumps(complex_entities)+ mock_get.return_value = mock_response++ # Should not raise JSON parsing errors+ with patch('hi.services.hass.hass_client.HassConverter.create_hass_state') as mock_create:+ mock_create.return_value = Mock(spec=HassState)++ try:+ result = self.client.states()+ # If we get here, JSON parsing succeeded+ self.assertEqual(len(result), len(complex_entities))+ except json.JSONDecodeError:+ self.fail("Should handle complex real HASS JSON data without parsing errors")++ @patch('hi.services.hass.hass_client.post')+ def test_set_state_error_scenarios_with_real_entities(self, mock_post):+ """Test error handling with realistic entity IDs that might cause issues"""+ # Mock error responses for realistic scenarios+ error_scenarios = [+ (404, 'Entity camera.nonexistent not found'),+ (400, 'Invalid state value for sensor entity'),+ (401, 'Authentication failed'),+ (403, 'Access denied for person entity')+ ]++ real_entity_id = 'camera.frontcamera' # Use real entity from our data++ for status_code, error_message in error_scenarios:+ with self.subTest(status_code=status_code):+ mock_response = Mock()+ mock_response.status_code = status_code+ mock_response.text = error_message+ mock_post.return_value = mock_response++ with self.assertRaises(ValueError) as context:+ self.client.set_state(real_entity_id, 'test_state')++ self.assertIn(f'Failed to set state: {status_code}', str(context.exception))+ self.assertIn(error_message, str(context.exception))diff --git a/src/hi/services/hass/tests/test_hass_controller.py b/src/hi/services/hass/tests/test_hass_controller.pynew file mode 100644index 00000000..313e347a--- /dev/null+++ b/src/hi/services/hass/tests/test_hass_controller.py@@ -0,0 +1,924 @@+from unittest.mock import Mock, patch+from django.test import TestCase++from hi.integrations.transient_models import IntegrationDetails, IntegrationKey, IntegrationControlResult++from hi.services.hass.hass_controller import HassController+++class TestHassControllerBehaviorVerification(TestCase):+ """Test HassController focusing on behavior verification rather than mock validation"""++ def setUp(self):+ self.controller = HassController()++ # Mock only at system boundary - the HTTP client+ self.mock_client = Mock()++ # Mock hass_manager but let it provide real client reference+ self.mock_manager = Mock()+ self.mock_manager.hass_client = self.mock_client++ # Inject the manager (singleton pattern allows this)+ self.controller._hass_manager = self.mock_manager++ def test_do_control_light_on_returns_correct_result(self):+ """Test that light control returns the expected IntegrationControlResult with proper state"""+ # Setup - Light entity with on/off control and is_controllable flag+ integration_key = IntegrationKey(integration_id='hass', integration_name='light.living_room')+ integration_details = IntegrationDetails(+ key=integration_key,+ payload={+ 'domain': 'light',+ 'is_controllable': True,+ 'on_service': 'turn_on',+ 'off_service': 'turn_off'+ }+ )++ # Mock successful HTTP response+ self.mock_client.call_service.return_value = {'context': {'id': 'abc123'}}++ # Execute the actual control flow+ result = self.controller.do_control(integration_details, 'on')++ # Verify behavior: check the actual result object content+ self.assertIsInstance(result, IntegrationControlResult)+ self.assertEqual(result.new_value, 'on')+ self.assertEqual(result.error_list, [])++ # Verify the service call was made correctly (system boundary)+ self.mock_client.call_service.assert_called_once_with(+ domain='light', service='turn_on', hass_state_id='light.living_room'+ )++ def test_do_control_brightness_numeric_conversion_and_service_call(self):+ """Test brightness control handles numeric conversion and calls appropriate service"""+ integration_key = IntegrationKey(integration_id='hass', integration_name='light.dining_room')+ integration_details = IntegrationDetails(+ key=integration_key,+ payload={+ 'domain': 'light',+ 'is_controllable': True,+ 'supports_brightness': True,+ 'on_service': 'turn_on',+ 'off_service': 'turn_off'+ }+ )++ self.mock_client.call_service.return_value = {'context': {'id': 'brightness123'}}++ # Test brightness = 75 (should call turn_on with brightness_pct)+ result = self.controller.do_control(integration_details, '75')++ # Verify numeric conversion and result+ self.assertEqual(result.new_value, '75')+ self.assertEqual(result.error_list, [])++ # Verify correct service call with brightness parameter+ self.mock_client.call_service.assert_called_once_with(+ domain='light',+ service='turn_on',+ hass_state_id='light.dining_room',+ service_data={'brightness_pct': 75}+ )++ def test_do_control_brightness_zero_turns_off_light(self):+ """Test that brightness = 0 correctly calls turn_off service instead of turn_on"""+ integration_key = IntegrationKey(integration_id='hass', integration_name='light.bedroom')+ integration_details = IntegrationDetails(+ key=integration_key,+ payload={+ 'domain': 'light',+ 'is_controllable': True,+ 'supports_brightness': True,+ 'on_service': 'turn_on',+ 'off_service': 'turn_off'+ }+ )++ self.mock_client.call_service.return_value = {'context': {'id': 'off123'}}++ result = self.controller.do_control(integration_details, '0')++ # Verify 0 brightness correctly maps to 'off' behavior+ self.assertEqual(result.new_value, '0')+ self.assertEqual(result.error_list, [])++ # Verify turn_off was called, not turn_on+ self.mock_client.call_service.assert_called_once_with(+ domain='light',+ service='turn_off',+ hass_state_id='light.bedroom',+ service_data=None+ )++ def test_do_control_volume_validation_and_service_call(self):+ """Test volume control validates range and makes correct service call"""+ integration_key = IntegrationKey(integration_id='hass', integration_name='media_player.living_room')+ integration_details = IntegrationDetails(+ key=integration_key,+ payload={+ 'domain': 'media_player',+ 'is_controllable': True,+ 'parameters': {'volume_level': True},+ 'set_service': 'volume_set'+ }+ )++ self.mock_client.call_service.return_value = {'context': {'id': 'vol123'}}++ # Test valid volume (0.7)+ result = self.controller.do_control(integration_details, '0.7')++ self.assertEqual(result.new_value, '0.7')+ self.assertEqual(result.error_list, [])++ self.mock_client.call_service.assert_called_once_with(+ domain='media_player',+ service='volume_set',+ hass_state_id='media_player.living_room',+ service_data={'volume_level': 0.7}+ )++ def test_do_control_invalid_volume_returns_error(self):+ """Test that invalid volume values return appropriate errors without service calls"""+ integration_key = IntegrationKey(integration_id='hass', integration_name='media_player.bedroom')+ integration_details = IntegrationDetails(+ key=integration_key,+ payload={+ 'domain': 'media_player',+ 'is_controllable': True,+ 'parameters': {'volume_level': True},+ 'set_service': 'volume_set'+ }+ )++ # Test invalid volume (1.5 > 1.0)+ result = self.controller.do_control(integration_details, '1.5')++ # Should return error without making service call+ self.assertIsNone(result.new_value)+ self.assertTrue(len(result.error_list) > 0)+ self.assertIn('Invalid volume value', result.error_list[0])++ # Verify no service call was made+ self.mock_client.call_service.assert_not_called()+++class TestHassControllerErrorHandlingBehavior(TestCase):+ """Test comprehensive error handling behavior and recovery"""++ def setUp(self):+ self.controller = HassController()+ self.mock_client = Mock()+ self.mock_manager = Mock()+ self.mock_manager.hass_client = self.mock_client+ self.controller._hass_manager = self.mock_manager++ def test_exception_during_conversion_returns_error_result(self):+ """Test that conversion exceptions are caught and returned as error results"""+ integration_key = IntegrationKey(integration_id='hass', integration_name='light.invalid')+ integration_details = IntegrationDetails(key=integration_key)++ # Patch the converter to raise an exception+ with patch('hi.services.hass.hass_controller.HassConverter.hass_entity_id_to_state_value_str') as mock_converter:+ mock_converter.side_effect = ValueError("Invalid entity format")++ result = self.controller.do_control(integration_details, 'on')++ # Verify exception is caught and returned as error+ self.assertIsNone(result.new_value)+ self.assertEqual(len(result.error_list), 1)+ self.assertIn('Invalid entity format', result.error_list[0])++ # Verify no service call was attempted+ self.mock_client.call_service.assert_not_called()++ def test_malformed_integration_details_handled_gracefully(self):+ """Test handling of malformed integration details returns proper error"""+ # Integration details with None key+ integration_details = IntegrationDetails(key=None)++ result = self.controller.do_control(integration_details, 'on')++ # Should handle gracefully and return error+ self.assertIsNone(result.new_value)+ self.assertTrue(len(result.error_list) > 0)+ self.assertIn("'NoneType' object has no attribute 'integration_name'", result.error_list[0])++ # No service calls should be made+ self.mock_client.call_service.assert_not_called()+++class TestHassControllerDomainRoutingBehavior(TestCase):+ """Test domain routing and payload vs best-effort decisions"""++ def setUp(self):+ self.controller = HassController()+ self.mock_client = Mock()+ self.mock_manager = Mock()+ self.mock_manager.hass_client = self.mock_client+ self.controller._hass_manager = self.mock_manager++ def test_payload_based_routing_with_explicit_services(self):+ """Test that payload with explicit services uses payload-based control path"""+ integration_key = IntegrationKey(integration_id='hass', integration_name='cover.garage_door')+ integration_details = IntegrationDetails(+ key=integration_key,+ payload={+ 'domain': 'cover',+ 'is_controllable': True,+ 'open_service': 'open_cover',+ 'close_service': 'close_cover'+ }+ )++ self.mock_client.call_service.return_value = {'context': {'id': 'cover123'}}++ # Test 'open' command uses payload service definition+ result = self.controller.do_control(integration_details, 'open')++ self.assertEqual(result.new_value, 'open')+ self.assertEqual(result.error_list, [])++ # Should use the explicit service from payload+ self.mock_client.call_service.assert_called_once_with(+ domain='cover',+ service='open_cover',+ hass_state_id='cover.garage_door'+ )++ def test_best_effort_routing_without_payload(self):+ """Test that missing payload triggers best-effort control with domain parsing"""+ integration_key = IntegrationKey(integration_id='hass', integration_name='switch.outlet')+ integration_details = IntegrationDetails(key=integration_key) # No payload++ self.mock_client.call_service.return_value = {'context': {'id': 'switch123'}}++ result = self.controller.do_control(integration_details, 'off')++ # Should succeed using best-effort patterns+ self.assertEqual(result.new_value, 'off')+ self.assertEqual(result.error_list, [])++ # Should use standard turn_off service for switch domain+ self.mock_client.call_service.assert_called_once_with(+ domain='switch',+ service='turn_off',+ hass_state_id='switch.outlet'+ )++ def test_payload_domain_overrides_entity_id_domain(self):+ """Test that explicit domain in payload overrides domain parsed from entity_id"""+ integration_key = IntegrationKey(integration_id='hass', integration_name='light.misleading_name')+ integration_details = IntegrationDetails(+ key=integration_key,+ payload={+ 'domain': 'switch', # Override: this is actually a switch, not a light+ 'is_controllable': True,+ 'on_service': 'turn_on',+ 'off_service': 'turn_off'+ }+ )++ self.mock_client.call_service.return_value = {'context': {'id': 'switch123'}}++ result = self.controller.do_control(integration_details, 'on')++ self.assertEqual(result.new_value, 'on')+ self.assertEqual(result.error_list, [])++ # Should use 'switch' domain from payload, not 'light' from entity_id+ self.mock_client.call_service.assert_called_once_with(+ domain='switch', # From payload, not entity_id+ service='turn_on',+ hass_state_id='light.misleading_name'+ )++ def test_climate_temperature_control_with_best_effort(self):+ """Test climate domain numeric temperature control via best-effort routing"""+ integration_key = IntegrationKey(integration_id='hass', integration_name='climate.thermostat')+ integration_details = IntegrationDetails(key=integration_key) # No payload - triggers best-effort++ self.mock_client.call_service.return_value = {'context': {'id': 'climate123'}}++ result = self.controller.do_control(integration_details, '72.5')++ # Should parse domain and handle numeric temperature+ self.assertEqual(result.new_value, '72.5')+ self.assertEqual(result.error_list, [])++ # Should use climate-specific service+ self.mock_client.call_service.assert_called_once_with(+ domain='climate',+ service='set_temperature',+ hass_state_id='climate.thermostat',+ service_data={'temperature': 72.5}+ )++ def test_invalid_entity_id_format_returns_error(self):+ """Test that malformed entity_id returns error without attempting service calls"""+ integration_key = IntegrationKey(integration_id='hass', integration_name='invalid_entity_id_no_dot')+ integration_details = IntegrationDetails(key=integration_key) # No payload++ result = self.controller.do_control(integration_details, 'on')++ # Should return error for malformed entity_id+ self.assertIsNone(result.new_value)+ self.assertTrue(len(result.error_list) > 0)+ self.assertIn('Invalid entity_id format', result.error_list[0])++ # No service calls should be attempted+ self.mock_client.call_service.assert_not_called()+++class TestHassControllerValueTransformationBehavior(TestCase):+ """Test value transformation and service mapping behavior"""++ def setUp(self):+ self.controller = HassController()+ self.mock_client = Mock()+ self.mock_manager = Mock()+ self.mock_manager.hass_client = self.mock_client+ self.controller._hass_manager = self.mock_manager++ def test_on_value_variations_all_map_to_turn_on(self):+ """Test that various 'on' representations all result in turn_on service call"""+ integration_key = IntegrationKey(integration_id='hass', integration_name='light.test')++ # Note: '1' is treated as numeric brightness, not boolean 'on'+ on_values = ['on', 'ON', 'true', 'TRUE']++ for control_value in on_values:+ with self.subTest(control_value=control_value):+ self.mock_client.reset_mock()++ integration_details = IntegrationDetails(key=integration_key)+ self.mock_client.call_service.return_value = {'context': {'id': f'test_{control_value}'}}++ result = self.controller.do_control(integration_details, control_value)++ # Verify behavior: all variations should result in 'turn_on' service+ self.assertEqual(result.new_value, control_value)+ self.assertEqual(result.error_list, [])++ self.mock_client.call_service.assert_called_once_with(+ domain='light', service='turn_on', hass_state_id='light.test'+ )++ def test_numeric_one_treated_as_brightness_not_boolean(self):+ """Test that '1' is treated as brightness=1%, not boolean on"""+ integration_key = IntegrationKey(integration_id='hass', integration_name='light.test')+ integration_details = IntegrationDetails(key=integration_key)++ self.mock_client.call_service.return_value = {'context': {'id': 'test_1'}}++ result = self.controller.do_control(integration_details, '1')++ # '1' should be treated as brightness 1% (best-effort numeric control)+ self.assertEqual(result.new_value, '1')+ self.assertEqual(result.error_list, [])++ # Should call turn_on with brightness_pct=1+ self.mock_client.call_service.assert_called_once_with(+ domain='light',+ service='turn_on',+ hass_state_id='light.test',+ service_data={'brightness_pct': 1}+ )++ def test_off_value_variations_all_map_to_turn_off(self):+ """Test that various 'off' representations all result in turn_off service call"""+ integration_key = IntegrationKey(integration_id='hass', integration_name='switch.test')++ # Note: '0' is treated differently for switches (no brightness support)+ off_values = ['off', 'OFF', 'false', 'FALSE']++ for control_value in off_values:+ with self.subTest(control_value=control_value):+ self.mock_client.reset_mock()++ integration_details = IntegrationDetails(key=integration_key)+ self.mock_client.call_service.return_value = {'context': {'id': f'test_{control_value}'}}++ result = self.controller.do_control(integration_details, control_value)++ # Verify behavior: all variations should result in 'turn_off' service+ self.assertEqual(result.new_value, control_value)+ self.assertEqual(result.error_list, [])++ self.mock_client.call_service.assert_called_once_with(+ domain='switch', service='turn_off', hass_state_id='switch.test'+ )++ def test_numeric_zero_on_switch_returns_error(self):+ """Test that '0' on a switch (no brightness) returns error"""+ integration_key = IntegrationKey(integration_id='hass', integration_name='switch.test')+ integration_details = IntegrationDetails(key=integration_key)++ result = self.controller.do_control(integration_details, '0')++ # '0' is numeric, switches don't support numeric control in best-effort mode+ self.assertIsNone(result.new_value)+ self.assertTrue(len(result.error_list) > 0)+ self.assertIn('No numeric control pattern', result.error_list[0])++ def test_unknown_control_value_returns_error_without_service_call(self):+ """Test that unrecognized control values return errors without attempting service calls"""+ integration_key = IntegrationKey(integration_id='hass', integration_name='light.test')+ integration_details = IntegrationDetails(key=integration_key)++ result = self.controller.do_control(integration_details, 'maybe')++ # Should return error without making any service calls+ self.assertIsNone(result.new_value)+ self.assertTrue(len(result.error_list) > 0)+ self.assertIn('Unknown control value: maybe', result.error_list[0])++ self.mock_client.call_service.assert_not_called()++ def test_cover_domain_uses_specific_services_for_open_close(self):+ """Test that cover domain maps open/close to cover-specific services"""+ integration_key = IntegrationKey(integration_id='hass', integration_name='cover.garage')+ integration_details = IntegrationDetails(key=integration_key)++ self.mock_client.call_service.return_value = {'context': {'id': 'cover123'}}++ # Test 'open' maps to open_cover+ result_open = self.controller.do_control(integration_details, 'open')++ self.assertEqual(result_open.new_value, 'open')+ self.assertEqual(result_open.error_list, [])++ self.mock_client.call_service.assert_called_with(+ domain='cover', service='open_cover', hass_state_id='cover.garage'+ )++ # Reset and test 'close' maps to close_cover+ self.mock_client.reset_mock()+ result_close = self.controller.do_control(integration_details, 'close')++ self.assertEqual(result_close.new_value, 'close')+ self.assertEqual(result_close.error_list, [])++ self.mock_client.call_service.assert_called_with(+ domain='cover', service='close_cover', hass_state_id='cover.garage'+ )+++class TestHassControllerHttpExceptionHandling(TestCase):+ """Test HTTP exception handling and propagation behavior"""++ def setUp(self):+ self.controller = HassController()+ self.mock_client = Mock()+ self.mock_manager = Mock()+ self.mock_manager.hass_client = self.mock_client+ self.controller._hass_manager = self.mock_manager++ def test_http_service_call_exception_not_caught_in_best_effort(self):+ """Test that HTTP exceptions in best-effort control are caught and returned as errors"""+ integration_key = IntegrationKey(integration_id='hass', integration_name='light.test')+ integration_details = IntegrationDetails(key=integration_key) # No payload - triggers best-effort++ # Simulate HTTP failure+ self.mock_client.call_service.side_effect = Exception("HTTP 503 Service Unavailable")++ # In best-effort mode, exceptions are caught and returned as errors+ result = self.controller.do_control(integration_details, 'on')++ # Should return error result, not propagate exception+ self.assertIsNone(result.new_value)+ self.assertTrue(len(result.error_list) > 0)+ self.assertIn('Best-effort control failed', result.error_list[0])+ self.assertIn('HTTP 503 Service Unavailable', result.error_list[0])++ def test_set_state_http_exception_propagates(self):+ """Test that set_state HTTP exceptions propagate correctly"""+ self.mock_client.set_state.side_effect = Exception("HTTP 404 Not Found")++ with self.assertRaises(Exception) as context:+ self.controller._do_control_with_set_state('light.nonexistent', 'on', 'on')++ self.assertEqual(str(context.exception), "HTTP 404 Not Found")+++class TestHassControllerNumericValidationBehavior(TestCase):+ """Test numeric parameter validation and boundary behavior"""++ def setUp(self):+ self.controller = HassController()+ self.mock_client = Mock()+ self.mock_manager = Mock()+ self.mock_manager.hass_client = self.mock_client+ self.controller._hass_manager = self.mock_manager++ def test_brightness_boundary_values_handled_correctly(self):+ """Test brightness boundary values (0, 100) are handled correctly"""+ integration_key = IntegrationKey(integration_id='hass', integration_name='light.dimmer')++ # Test brightness = 0 (should turn off)+ integration_details = IntegrationDetails(+ key=integration_key,+ payload={+ 'domain': 'light',+ 'is_controllable': True,+ 'supports_brightness': True,+ 'on_service': 'turn_on',+ 'off_service': 'turn_off'+ }+ )++ self.mock_client.call_service.return_value = {'context': {'id': 'bright0'}}++ result = self.controller.do_control(integration_details, '0')++ # Brightness 0 should call turn_off, not turn_on+ self.assertEqual(result.new_value, '0')+ self.assertEqual(result.error_list, [])++ self.mock_client.call_service.assert_called_once_with(+ domain='light',+ service='turn_off',+ hass_state_id='light.dimmer',+ service_data=None+ )++ # Test brightness = 100 (should turn on with full brightness)+ self.mock_client.reset_mock()++ result = self.controller.do_control(integration_details, '100')++ self.assertEqual(result.new_value, '100')+ self.assertEqual(result.error_list, [])++ self.mock_client.call_service.assert_called_once_with(+ domain='light',+ service='turn_on',+ hass_state_id='light.dimmer',+ service_data={'brightness_pct': 100}+ )++ def test_brightness_invalid_values_return_errors(self):+ """Test that invalid brightness values return errors without service calls"""+ integration_key = IntegrationKey(integration_id='hass', integration_name='light.dimmer')+ integration_details = IntegrationDetails(+ key=integration_key,+ payload={+ 'domain': 'light',+ 'is_controllable': True,+ 'supports_brightness': True,+ 'on_service': 'turn_on',+ 'off_service': 'turn_off'+ }+ )++ invalid_brightness_values = ['-10', '150', 'abc']++ for brightness in invalid_brightness_values:+ with self.subTest(brightness=brightness):+ self.mock_client.reset_mock()++ result = self.controller.do_control(integration_details, brightness)++ # Should return error without service call+ if brightness == 'abc':+ # Non-numeric values should be caught early+ self.assertIsNone(result.new_value)+ self.assertTrue(len(result.error_list) > 0)+ else:+ # Numeric but out-of-range values+ self.assertIsNone(result.new_value)+ self.assertTrue(len(result.error_list) > 0)+ self.assertIn('Invalid brightness value', result.error_list[0])++ # No service calls should be made for invalid values+ self.mock_client.call_service.assert_not_called()++ def test_volume_boundary_validation_enforced(self):+ """Test that volume boundary validation (0.0-1.0) is properly enforced"""+ integration_key = IntegrationKey(integration_id='hass', integration_name='media_player.speaker')+ integration_details = IntegrationDetails(+ key=integration_key,+ payload={+ 'domain': 'media_player',+ 'is_controllable': True,+ 'parameters': {'volume_level': True},+ 'set_service': 'volume_set'+ }+ )++ self.mock_client.call_service.return_value = {'context': {'id': 'vol123'}}++ # Test valid boundary values+ valid_volumes = ['0.0', '0.5', '1.0']++ for volume in valid_volumes:+ with self.subTest(volume=volume):+ self.mock_client.reset_mock()++ result = self.controller.do_control(integration_details, volume)++ self.assertEqual(result.new_value, volume)+ self.assertEqual(result.error_list, [])++ self.mock_client.call_service.assert_called_once_with(+ domain='media_player',+ service='volume_set',+ hass_state_id='media_player.speaker',+ service_data={'volume_level': float(volume)}+ )++ # Test invalid values (outside 0.0-1.0 range)+ invalid_volumes = ['-0.1', '1.1', '2.0']++ for volume in invalid_volumes:+ with self.subTest(volume=volume):+ self.mock_client.reset_mock()++ result = self.controller.do_control(integration_details, volume)++ # Should return error+ self.assertIsNone(result.new_value)+ self.assertTrue(len(result.error_list) > 0)+ self.assertIn('Invalid volume value', result.error_list[0])++ # No service call should be made+ self.mock_client.call_service.assert_not_called()+++class TestHassControllerCoverPositionBehavior(TestCase):+ """Test cover position control behavior and validation"""++ def setUp(self):+ self.controller = HassController()+ self.mock_client = Mock()+ self.mock_manager = Mock()+ self.mock_manager.hass_client = self.mock_client+ self.controller._hass_manager = self.mock_manager++ def test_cover_position_percentage_control(self):+ """Test cover position control with percentage values"""+ integration_key = IntegrationKey(integration_id='hass', integration_name='cover.blinds')+ integration_details = IntegrationDetails(+ key=integration_key,+ payload={+ 'domain': 'cover',+ 'is_controllable': True,+ 'parameters': {'position': True},+ 'set_service': 'set_cover_position'+ }+ )++ self.mock_client.call_service.return_value = {'context': {'id': 'pos123'}}++ # Test 50% position+ result = self.controller.do_control(integration_details, '50')++ self.assertEqual(result.new_value, '50')+ self.assertEqual(result.error_list, [])++ self.mock_client.call_service.assert_called_once_with(+ domain='cover',+ service='set_cover_position',+ hass_state_id='cover.blinds',+ service_data={'position': 50}+ )+++class TestHassControllerRealWorldEntityBehavior(TestCase):+ """Test behavior with real-world entity patterns from Home Assistant"""++ def setUp(self):+ self.controller = HassController()+ self.mock_client = Mock()+ self.mock_manager = Mock()+ self.mock_manager.hass_client = self.mock_client+ self.controller._hass_manager = self.mock_manager++ def test_camera_entities_handle_non_controllable_gracefully(self):+ """Test that camera entities (typically non-controllable) are handled appropriately"""+ real_camera_entities = [+ 'camera.frontcamera',+ 'camera.patiocamera',+ 'camera.sidecamera',+ 'camera.drivecamera'+ ]++ for entity_id in real_camera_entities:+ with self.subTest(entity_id=entity_id):+ self.mock_client.reset_mock()++ integration_key = IntegrationKey(integration_id='hass', integration_name=entity_id)+ # Camera without is_controllable flag should fallback to best-effort+ integration_details = IntegrationDetails(+ key=integration_key,+ payload={'domain': 'camera'} # No is_controllable or services defined+ )++ result = self.controller.do_control(integration_details, 'idle')++ # Should attempt best-effort control or return error+ # Since 'idle' is not a standard on/off value, should return error+ self.assertIsNone(result.new_value)+ self.assertTrue(len(result.error_list) > 0)+ self.assertIn('Unknown control value', result.error_list[0])++ def test_script_entities_execute_with_turn_on_service(self):+ """Test that script entities execute using turn_on service"""+ script_entity = 'script.play_door_chime'++ integration_key = IntegrationKey(integration_id='hass', integration_name=script_entity)+ integration_details = IntegrationDetails(+ key=integration_key,+ payload={'domain': 'script'} # Scripts use turn_on to execute+ )++ self.mock_client.call_service.return_value = {'context': {'id': 'script123'}}++ result = self.controller.do_control(integration_details, 'on')++ # Scripts should execute with turn_on service+ self.assertEqual(result.new_value, 'on')+ self.assertEqual(result.error_list, [])++ self.mock_client.call_service.assert_called_once_with(+ domain='script',+ service='turn_on',+ hass_state_id=script_entity+ )++ def test_sensor_entities_return_error_for_control_attempts(self):+ """Test that sensor entities (read-only) return appropriate errors"""+ sensor_entities = [+ 'sensor.frontcamera_status',+ 'sensor.frontcamera_events_last_hour'+ ]++ for entity_id in sensor_entities:+ with self.subTest(entity_id=entity_id):+ self.mock_client.reset_mock()++ integration_key = IntegrationKey(integration_id='hass', integration_name=entity_id)+ integration_details = IntegrationDetails(key=integration_key) # No payload++ result = self.controller.do_control(integration_details, 'test_value')++ # Sensors are not controllable - should return error+ self.assertIsNone(result.new_value)+ self.assertTrue(len(result.error_list) > 0)++ # Should not attempt any service calls for sensors+ self.mock_client.call_service.assert_not_called()+++class TestHassControllerLegacySetStateBehavior(TestCase):+ """Test legacy set_state method behavior and error handling"""++ def setUp(self):+ self.controller = HassController()+ self.mock_client = Mock()+ self.mock_manager = Mock()+ self.mock_manager.hass_client = self.mock_client+ self.controller._hass_manager = self.mock_manager++ def test_set_state_returns_control_value_on_success(self):+ """Test that set_state returns the control value (not HA response) on success"""+ # Mock successful HTTP response from HA+ self.mock_client.set_state.return_value = {+ 'entity_id': 'light.bedroom',+ 'state': 'on',+ 'attributes': {'brightness': 255}+ }++ result = self.controller._do_control_with_set_state('light.bedroom', 'bright', 'on')++ # Should return the original control value, not the HA state+ self.assertEqual(result.new_value, 'bright') # Not 'on' from HA response+ self.assertEqual(result.error_list, [])++ # Verify correct HA API call+ self.mock_client.set_state.assert_called_once_with(+ entity_id='light.bedroom',+ state='on' # Converted HA state value+ )++ def test_set_state_propagates_http_exceptions(self):+ """Test that set_state propagates HTTP exceptions without catching them"""+ self.mock_client.set_state.side_effect = Exception("HTTP 401 Unauthorized")++ with self.assertRaises(Exception) as context:+ self.controller._do_control_with_set_state('light.test', 'on', 'on')++ self.assertEqual(str(context.exception), "HTTP 401 Unauthorized")+++class TestHassControllerIntegrationBehavior(TestCase):+ """Test integration behavior between components"""++ def setUp(self):+ self.controller = HassController()+ self.mock_client = Mock()+ self.mock_manager = Mock()+ self.mock_manager.hass_client = self.mock_client+ self.controller._hass_manager = self.mock_manager++ def test_multiple_sequential_controls_maintain_state(self):+ """Test that multiple sequential control operations work correctly"""+ integration_key = IntegrationKey(integration_id='hass', integration_name='light.living_room')+ integration_details = IntegrationDetails(+ key=integration_key,+ payload={+ 'domain': 'light',+ 'is_controllable': True,+ 'supports_brightness': True,+ 'on_service': 'turn_on',+ 'off_service': 'turn_off'+ }+ )++ self.mock_client.call_service.return_value = {'context': {'id': 'seq123'}}++ # Sequence: off -> on -> brightness 50 -> off+ control_sequence = [+ ('off', 'turn_off', None),+ ('on', 'turn_on', None),+ ('50', 'turn_on', {'brightness_pct': 50}),+ ('off', 'turn_off', None)+ ]++ for control_value, expected_service, expected_data in control_sequence:+ with self.subTest(control_value=control_value):+ self.mock_client.reset_mock()++ result = self.controller.do_control(integration_details, control_value)++ self.assertEqual(result.new_value, control_value)+ self.assertEqual(result.error_list, [])++ # Verify the correct service was called+ self.mock_client.call_service.assert_called_once_with(+ domain='light',+ service=expected_service,+ hass_state_id='light.living_room',+ **(dict(service_data=expected_data) if expected_data else {})+ )++ def test_lock_domain_uses_lock_unlock_services(self):+ """Test that lock domain correctly maps open/close to unlock/lock"""+ integration_key = IntegrationKey(integration_id='hass', integration_name='lock.front_door')+ integration_details = IntegrationDetails(key=integration_key) # No payload - best effort++ self.mock_client.call_service.return_value = {'context': {'id': 'lock123'}}++ # Test 'open' maps to 'unlock' for locks+ result = self.controller.do_control(integration_details, 'open')++ self.assertEqual(result.new_value, 'open')+ self.assertEqual(result.error_list, [])++ self.mock_client.call_service.assert_called_once_with(+ domain='lock',+ service='unlock', # 'open' -> 'unlock' for locks+ hass_state_id='lock.front_door'+ )++ # Test 'close' maps to 'lock' for locks+ self.mock_client.reset_mock()++ result = self.controller.do_control(integration_details, 'close')++ self.assertEqual(result.new_value, 'close')+ self.assertEqual(result.error_list, [])++ self.mock_client.call_service.assert_called_once_with(+ domain='lock',+ service='lock', # 'close' -> 'lock' for locks+ hass_state_id='lock.front_door'+ )++ @patch('hi.services.hass.hass_mixins.HassManager')+ def test_hass_manager_singleton_behavior(self, mock_manager_class):+ """Test that HassManager maintains singleton behavior through mixin"""+ mock_manager_instance = Mock()+ mock_manager_class.return_value = mock_manager_instance++ # Clear any existing manager+ if hasattr(self.controller, '_hass_manager'):+ delattr(self.controller, '_hass_manager')++ # First access+ manager1 = self.controller.hass_manager()++ # Second access should return cached instance+ manager2 = self.controller.hass_manager()++ # Should be same instance (singleton)+ self.assertIs(manager1, manager2)++ # Manager class should only be instantiated once+ mock_manager_class.assert_called_once()++ # ensure_initialized called only on first access (singleton already initialized)+ mock_manager_instance.ensure_initialized.assert_called_once()diff --git a/src/hi/services/hass/tests/test_hass_converter_mapping.py b/src/hi/services/hass/tests/test_hass_converter_mapping.pyindex fe76616c..d9cf5f95 100644--- a/src/hi/services/hass/tests/test_hass_converter_mapping.py+++ b/src/hi/services/hass/tests/test_hass_converter_mapping.py@@ -1,18 +1,21 @@import jsonimport osfrom django.test import TestCase-from unittest.mock import patch, MagicMock+from unittest.mock import Mock-from hi.apps.entity.enums import EntityStateType-from hi.apps.entity.models import Entity+from hi.apps.entity.enums import EntityStateType, EntityType+from hi.apps.entity.models import Entity, EntityState+from hi.apps.control.models import Controller+from hi.apps.sense.models import Sensorfrom hi.integrations.transient_models import IntegrationKeyfrom hi.services.hass.hass_converter import HassConverter-from hi.services.hass.hass_models import HassApi+from hi.services.hass.hass_models import HassApi, HassDeviceclass TestHassConverterMapping(TestCase):"""- Test the new mapping-based converter methods using real HA API data+ Test the mapping-based converter methods using real HA API data.+ Focus on testing actual behavior rather than mocking internals."""@classmethod@@ -24,12 +27,14 @@ class TestHassConverterMapping(TestCase):cls.real_ha_states_data = json.load(f)def setUp(self):- # Create a mock entity for testing- self.mock_entity = MagicMock(spec=Entity)- self.mock_entity.name = "Test Entity"+ # Create a real entity for testing instead of a mock+ self.test_entity = Entity.objects.create(+ name="Test Entity",+ entity_type=EntityType.OTHER+ )def test_determine_entity_state_type_from_mapping_light_dimmer(self):- """Test that dimmer lights are correctly identified"""+ """Test that dimmer lights are correctly identified with comprehensive checks"""# Find a real dimmer light from the test datadimmer_data = None@@ -44,15 +49,31 @@ class TestHassConverterMapping(TestCase):# Create HassState from real datahass_state = HassConverter.create_hass_state(dimmer_data)+ # Verify HassState properties are correctly parsed+ self.assertEqual(hass_state.domain, HassApi.LIGHT_DOMAIN)+ self.assertIsNotNone(hass_state.entity_id)+ self.assertIn('light.', hass_state.entity_id)+# Test the mappingentity_state_type = HassConverter._determine_entity_state_type_from_mapping(hass_state)+ # Check brightness capability detection+ has_brightness = HassConverter._has_brightness_capability(hass_state)+# Should be LIGHT_DIMMER if it has brightness capability- if 'brightness' in dimmer_data.get('attributes', {}):+ if has_brightness:self.assertEqual(entity_state_type, EntityStateType.LIGHT_DIMMER)+ self.assertTrue( 'brightness' in dimmer_data.get('attributes', {})+ or 'brightness_pct' in dimmer_data.get('attributes', {}) )else:# Fallback to ON_OFF if no brightness detectedself.assertEqual(entity_state_type, EntityStateType.ON_OFF)++ # Verify this is controllable+ is_controllable = HassConverter._is_controllable_domain_and_type(+ hass_state.domain, entity_state_type+ )+ self.assertTrue(is_controllable, "Dimmer lights should be controllable")def test_determine_entity_state_type_from_mapping_light_onoff(self):"""Test that regular (non-dimmer) lights are correctly identified"""@@ -98,144 +119,243 @@ class TestHassConverterMapping(TestCase):self.assertEqual(entity_state_type, EntityStateType.ON_OFF)def test_determine_entity_state_type_from_mapping_binary_sensor(self):- """Test that binary sensors are correctly identified"""+ """Test that binary sensors are correctly identified with all device classes"""- # Find a binary sensor from the test data- binary_sensor_data = None- for state_data in self.real_ha_states_data:- if state_data.get('entity_id', '').startswith('binary_sensor.'):- binary_sensor_data = state_data- break-- self.assertIsNotNone(binary_sensor_data, "Should find a binary sensor in test data")-- # Create HassState from real data- hass_state = HassConverter.create_hass_state(binary_sensor_data)+ # Test multiple binary sensor types for comprehensive coverage+ tested_device_classes = set()- # Test the mapping- entity_state_type = HassConverter._determine_entity_state_type_from_mapping(hass_state)+ for state_data in self.real_ha_states_data:+ if not state_data.get('entity_id', '').startswith('binary_sensor.'):+ continue++ # Create HassState from real data+ hass_state = HassConverter.create_hass_state(state_data)++ # Verify basic properties+ self.assertEqual(hass_state.domain, HassApi.BINARY_SENSOR_DOMAIN)++ # Test the mapping+ entity_state_type = HassConverter._determine_entity_state_type_from_mapping(hass_state)++ # Verify we get a valid EntityStateType+ self.assertIsInstance(entity_state_type, EntityStateType)++ # Track device classes we've tested+ device_class = hass_state.device_class+ if device_class:+ tested_device_classes.add(device_class)++ # Verify mapping correctness based on device class+ expected_mappings = {+ HassApi.MOTION_DEVICE_CLASS: EntityStateType.MOVEMENT,+ HassApi.CONNECTIVITY_DEVICE_CLASS: EntityStateType.CONNECTIVITY,+ HassApi.BATTERY_DEVICE_CLASS: EntityStateType.HIGH_LOW,+ HassApi.DOOR_DEVICE_CLASS: EntityStateType.OPEN_CLOSE,+ HassApi.GARAGE_DOOR_DEVICE_CLASS: EntityStateType.OPEN_CLOSE,+ HassApi.WINDOW_DEVICE_CLASS: EntityStateType.OPEN_CLOSE,+ }++ if device_class in expected_mappings:+ self.assertEqual(+ entity_state_type,+ expected_mappings[device_class],+ f"Device class {device_class} should map to {expected_mappings[device_class]}"+ )+ else:+ # Default for unknown device classes+ self.assertEqual(+ entity_state_type,+ EntityStateType.ON_OFF,+ f"Unknown device class {device_class} should default to ON_OFF"+ )++ # Binary sensors should not be controllable+ is_controllable = HassConverter._is_controllable_domain_and_type(+ hass_state.domain, entity_state_type+ )+ self.assertFalse(is_controllable, "Binary sensors should not be controllable")- # Should be appropriate sensor type based on device class- device_class = hass_state.device_class- if device_class == HassApi.MOTION_DEVICE_CLASS:- self.assertEqual(entity_state_type, EntityStateType.MOVEMENT)- elif device_class == HassApi.CONNECTIVITY_DEVICE_CLASS:- self.assertEqual(entity_state_type, EntityStateType.CONNECTIVITY)- else:- # Default for binary sensors- self.assertEqual(entity_state_type, EntityStateType.ON_OFF)+ # Ensure we tested at least one binary sensor+ self.assertGreater(len(tested_device_classes), 0, "Should test at least one binary sensor")def test_has_brightness_capability(self):- """Test brightness detection for lights"""+ """Test brightness detection for lights with edge cases"""- # Test with a known dimmer light- dimmer_data = None- for state_data in self.real_ha_states_data:- if ( state_data.get('entity_id', '').startswith('light.')- and 'brightness' in state_data.get('attributes', {}) ):- dimmer_data = state_data- break-- if dimmer_data:- hass_state = HassConverter.create_hass_state(dimmer_data)- has_brightness = HassConverter._has_brightness_capability(hass_state)- self.assertTrue(has_brightness, "Should detect brightness capability")+ # Track what we've tested+ tested_dimmer = False+ tested_relay = False- # Test with a regular light- relay_data = Nonefor state_data in self.real_ha_states_data:- if ( state_data.get('entity_id', '').startswith('light.')- and state_data.get('attributes', {}).get('color_mode') == 'onoff' ):- relay_data = state_data- break+ if not state_data.get('entity_id', '').startswith('light.'):+ continue++ hass_state = HassConverter.create_hass_state(state_data)+ has_brightness = HassConverter._has_brightness_capability(hass_state)++ attributes = state_data.get('attributes', {})++ # Test dimmer lights (with brightness attribute)+ if 'brightness' in attributes:+ tested_dimmer = True+ self.assertTrue(+ has_brightness,+ f"Light {hass_state.entity_id} has brightness attribute but capability not detected"+ )++ # Verify the entity state type mapping+ entity_state_type = HassConverter._determine_entity_state_type_from_mapping(hass_state)+ self.assertEqual(+ entity_state_type, EntityStateType.LIGHT_DIMMER,+ f"Light with brightness should be LIGHT_DIMMER, got {entity_state_type}"+ )++ # Test lights with brightness_pct+ elif 'brightness_pct' in attributes:+ self.assertTrue(+ has_brightness,+ f"Light {hass_state.entity_id} has brightness_pct but capability not detected"+ )++ # Test relay lights (color_mode = 'onoff')+ elif attributes.get('color_mode') == 'onoff':+ tested_relay = True+ self.assertFalse(+ has_brightness,+ f"Relay light {hass_state.entity_id} should not have brightness capability"+ )++ # Verify the entity state type mapping+ entity_state_type = HassConverter._determine_entity_state_type_from_mapping(hass_state)+ self.assertEqual(+ entity_state_type, EntityStateType.ON_OFF,+ f"Relay light should be ON_OFF, got {entity_state_type}"+ )- if relay_data:- hass_state = HassConverter.create_hass_state(relay_data)+ # Test non-light domains should always return False+ for state_data in self.real_ha_states_data[:5]:+ if state_data.get('entity_id', '').startswith('light.'):+ continue++ hass_state = HassConverter.create_hass_state(state_data)has_brightness = HassConverter._has_brightness_capability(hass_state)- self.assertFalse(has_brightness, "Should not detect brightness capability for relay lights")+ self.assertFalse(+ has_brightness,+ f"Non-light domain {hass_state.domain} should not have brightness capability"+ )++ # Verify we tested the main scenarios+ if not tested_dimmer:+ self.skipTest("No dimmer lights found in test data")+ if not tested_relay:+ self.skipTest("No relay lights found in test data")def test_is_controllable_domain_and_type(self):- """Test controllability detection"""-- # Test controllable combinations- self.assertTrue(- HassConverter._is_controllable_domain_and_type( HassApi.LIGHT_DOMAIN,- EntityStateType.ON_OFF )- )- self.assertTrue(- HassConverter._is_controllable_domain_and_type( HassApi.LIGHT_DOMAIN,- EntityStateType.LIGHT_DIMMER )- )- self.assertTrue(- HassConverter._is_controllable_domain_and_type( HassApi.SWITCH_DOMAIN,- EntityStateType.ON_OFF )- )+ """Test controllability detection with comprehensive coverage"""++ # Test all controllable combinations from CONTROL_SERVICE_MAPPING+ for (domain, entity_type) in HassConverter.CONTROL_SERVICE_MAPPING.keys():+ is_controllable = HassConverter._is_controllable_domain_and_type(domain, entity_type)+ self.assertTrue(+ is_controllable,+ f"Mapping exists for {domain}/{entity_type}, should be controllable"+ )- # Test non-controllable combinations- self.assertFalse(- HassConverter._is_controllable_domain_and_type( HassApi.SENSOR_DOMAIN,- EntityStateType.TEMPERATURE )- )- self.assertFalse(- HassConverter._is_controllable_domain_and_type( HassApi.BINARY_SENSOR_DOMAIN,- EntityStateType.MOVEMENT )- )+ # Test known non-controllable combinations+ non_controllable_cases = [+ (HassApi.SENSOR_DOMAIN, EntityStateType.TEMPERATURE),+ (HassApi.SENSOR_DOMAIN, EntityStateType.HUMIDITY),+ (HassApi.SENSOR_DOMAIN, EntityStateType.BLOB),+ (HassApi.BINARY_SENSOR_DOMAIN, EntityStateType.MOVEMENT),+ (HassApi.BINARY_SENSOR_DOMAIN, EntityStateType.CONNECTIVITY),+ (HassApi.BINARY_SENSOR_DOMAIN, EntityStateType.ON_OFF),+ (HassApi.CAMERA_DOMAIN, EntityStateType.VIDEO_STREAM),+ (HassApi.SUN_DOMAIN, EntityStateType.MULTVALUED),+ (HassApi.WEATHER_DOMAIN, EntityStateType.MULTVALUED),+ ]++ for domain, entity_type in non_controllable_cases:+ is_controllable = HassConverter._is_controllable_domain_and_type(domain, entity_type)+ self.assertFalse(is_controllable,+ f"{domain}/{entity_type} should not be controllable")++ # Test that sensor-only domains are never controllable+ for domain in HassConverter.SENSOR_ONLY_DOMAINS:+ # Test with various entity types+ for entity_type in [EntityStateType.ON_OFF, EntityStateType.TEMPERATURE,+ EntityStateType.BLOB, EntityStateType.MOVEMENT]:+ is_controllable = HassConverter._is_controllable_domain_and_type(domain, entity_type)+ self.assertFalse(is_controllable,+ f"Sensor-only domain {domain} should never be controllable")- @patch('hi.apps.model_helper.HiModelHelper.create_on_off_controller')- @patch('hi.apps.model_helper.HiModelHelper.create_light_dimmer_controller')- @patch('hi.apps.model_helper.HiModelHelper.create_blob_sensor')- def test_create_hass_state_with_mapping_integration( self,- mock_blob_sensor,- mock_light_dimmer_controller,- mock_on_off_controller ):- """Test the complete integration of the new mapping method"""-- # Mock the return values- mock_controller = MagicMock()- mock_controller.integration_metadata = {}- mock_controller.entity_state = MagicMock()- mock_on_off_controller.return_value = mock_controller- mock_light_dimmer_controller.return_value = mock_controller-- mock_sensor = MagicMock()- mock_sensor.integration_metadata = {}- mock_sensor.entity_state = MagicMock()- mock_blob_sensor.return_value = mock_sensor-- # Test with a controllable light+ def test_create_hass_state_with_mapping_integration(self):+ """Test the complete integration of the mapping method with real models"""++ # Test controllable lightlight_data = Nonefor state_data in self.real_ha_states_data:if state_data.get('entity_id', '').startswith('light.'):light_data = state_databreak- if light_data:- hass_state = HassConverter.create_hass_state(light_data)- integration_key = IntegrationKey(- integration_id='hass',- integration_name=hass_state.entity_id- )-- # Call the new method- entity_state = HassConverter._create_hass_state_with_mapping(- hass_device=MagicMock(),- hass_state=hass_state,- entity=self.mock_entity,- integration_key=integration_key,- add_alarm_events=False- )+ self.assertIsNotNone(light_data, "Should find a light in test data")++ hass_state = HassConverter.create_hass_state(light_data)+ integration_key = IntegrationKey(+ integration_id='hass',+ integration_name=hass_state.entity_id+ )++ # Create a mock HassDevice+ hass_device = Mock(spec=HassDevice)+ hass_device.device_id = 'test_device_id'++ # Call the mapping method+ entity_state = HassConverter._create_hass_state_with_mapping(+ hass_device=hass_device,+ hass_state=hass_state,+ entity=self.test_entity,+ integration_key=integration_key,+ add_alarm_events=False+ )++ # Verify EntityState was created+ self.assertIsNotNone(entity_state)+ self.assertIsInstance(entity_state, EntityState)+ self.assertEqual(entity_state.entity, self.test_entity)++ # Check if controller was created for controllable domain+ controller = Controller.objects.filter(entity_state=entity_state).first()+ sensor = Sensor.objects.filter(entity_state=entity_state).first()++ # Light should have a controller+ if hass_state.domain in HassConverter.ALL_CONTROLLABLE_DOMAINS:+ self.assertIsNotNone(controller,+ f"Controllable domain {hass_state.domain} should have controller")- # Should have created a controller and stored metadata- self.assertIsNotNone(entity_state)+ # Verify integration payload was stored+ self.assertIsNotNone(controller.integration_payload)+ self.assertIn('domain', controller.integration_payload)+ self.assertEqual(controller.integration_payload['domain'], hass_state.domain)+ self.assertIn('has_brightness', controller.integration_payload)- # Check that metadata was stored (either controller or sensor should have been called)- metadata_stored = (mock_controller.integration_metadata or mock_sensor.integration_metadata)- self.assertIsNotNone(metadata_stored)+ # Verify service mapping exists+ entity_state_type = HassConverter._determine_entity_state_type_from_mapping(hass_state)+ service_key = (hass_state.domain, entity_state_type)+ if service_key in HassConverter.CONTROL_SERVICE_MAPPING:+ service_info = HassConverter.CONTROL_SERVICE_MAPPING[service_key]+ # The service info should be available for the controller to use+ self.assertIn('on_service', service_info)+ self.assertIn('off_service', service_info)+ else:+ # Non-controllable should only have sensor+ self.assertIsNone(controller,+ f"Non-controllable domain {hass_state.domain} should not have controller")+ self.assertIsNotNone(sensor,+ f"Non-controllable domain {hass_state.domain} should have sensor")- # Metadata should contain domain info- if mock_controller.integration_metadata:- self.assertIn('domain', mock_controller.integration_metadata)- self.assertEqual(mock_controller.integration_metadata['domain'], HassApi.LIGHT_DOMAIN)+ # Verify integration payload was stored on sensor+ self.assertIsNotNone(sensor.integration_payload)+ self.assertIn('domain', sensor.integration_payload)def test_domain_parsing_consistency(self):"""Test that domain parsing is consistent across all real entities"""@@ -256,15 +376,225 @@ class TestHassConverterMapping(TestCase):self.assertIsNotNone(entity_state_type,f"Should have EntityStateType mapping for domain {expected_domain}")+ def test_unmapped_domain_falls_back_to_blob(self):+ """Test that unmapped domains fall back to BLOB EntityStateType"""++ # Create a state with an unmapped domain+ unmapped_data = {+ 'entity_id': 'unknown_domain.test_entity',+ 'state': 'active',+ 'attributes': {+ 'friendly_name': 'Test Unknown Entity'+ }+ }++ hass_state = HassConverter.create_hass_state(unmapped_data)++ # Should parse domain correctly+ self.assertEqual(hass_state.domain, 'unknown_domain')++ # Should fall back to BLOB type+ entity_state_type = HassConverter._determine_entity_state_type_from_mapping(hass_state)+ self.assertEqual(entity_state_type, EntityStateType.BLOB,+ "Unmapped domains should fall back to BLOB")++ # Should not be controllable+ is_controllable = HassConverter._is_controllable_domain_and_type(+ hass_state.domain, entity_state_type+ )+ self.assertFalse(is_controllable, "Unmapped domains should not be controllable")++ def test_service_payload_creation(self):+ """Test that service payloads are created correctly for different domains"""++ test_cases = [+ # (entity_id_prefix, expected_has_brightness, expected_services)+ ('light.test_dimmer', True, ['on_service', 'off_service', 'set_service']),+ ('switch.test_switch', False, ['on_service', 'off_service']),+ ('cover.test_blind', False, ['on_service', 'off_service']),+ ('climate.test_thermostat', False, ['set_service']),+ ]++ for entity_id_prefix, should_have_brightness, expected_services in test_cases:+ # Find or create test data+ test_data = None+ for state_data in self.real_ha_states_data:+ if state_data.get('entity_id', '').startswith(entity_id_prefix.split('.')[0] + '.'):+ test_data = state_data+ break++ if not test_data:+ # Create synthetic test data if not found+ test_data = {+ 'entity_id': entity_id_prefix,+ 'state': 'on',+ 'attributes': {+ 'friendly_name': 'Test Device'+ }+ }+ if should_have_brightness:+ test_data['attributes']['brightness'] = 128++ hass_state = HassConverter.create_hass_state(test_data)+ entity_state_type = HassConverter._determine_entity_state_type_from_mapping(hass_state)++ # Check service mapping exists+ service_key = (hass_state.domain, entity_state_type)+ if service_key in HassConverter.CONTROL_SERVICE_MAPPING:+ service_info = HassConverter.CONTROL_SERVICE_MAPPING[service_key]++ # Verify expected services based on actual entity state type+ if entity_state_type == EntityStateType.LIGHT_DIMMER:+ # Dimmer lights should have set_service+ self.assertIn('set_service', service_info,+ "LIGHT_DIMMER should have set_service")+ self.assertIn('on_service', service_info)+ self.assertIn('off_service', service_info)+ elif entity_state_type == EntityStateType.ON_OFF and hass_state.domain == 'light':+ # Regular lights should not have set_service+ self.assertNotIn('set_service', service_info,+ "ON_OFF light should not have set_service")+ self.assertIn('on_service', service_info)+ self.assertIn('off_service', service_info)+ elif entity_state_type == EntityStateType.TEMPERATURE:+ # Climate controls should have set_service but not on/off+ self.assertIn('set_service', service_info)+ self.assertNotIn('on_service', service_info,+ "Climate should not have on_service")+ else:+ # Check that basic on/off services exist for other controllable types+ if hass_state.domain in ['switch', 'cover', 'fan', 'lock', 'media_player']:+ self.assertIn('on_service', service_info)+ self.assertIn('off_service', service_info)+def test_service_mapping_completeness(self):- """Test that all controllable domains have service mappings"""+ """Test that all controllable domains have complete and valid service mappings"""controllable_domains = HassConverter.ALL_CONTROLLABLE_DOMAINSfor domain in controllable_domains:# Each controllable domain should have at least one service mapping- has_mapping = any(- key[0] == domain- for key in HassConverter.CONTROL_SERVICE_MAPPING.keys()- )- self.assertTrue(has_mapping, f"Domain {domain} should have service mappings")+ domain_mappings = [+ (key, value) for key, value in HassConverter.CONTROL_SERVICE_MAPPING.items()+ if key[0] == domain+ ]++ self.assertGreater(len(domain_mappings), 0,+ f"Domain {domain} should have at least one service mapping")++ # Verify each mapping has required fields+ for (mapping_domain, entity_type), service_info in domain_mappings:+ self.assertIsInstance(service_info, dict,+ f"Service info for {mapping_domain}/{entity_type} should be a dict")++ # Check required service fields based on domain+ if mapping_domain in HassConverter.ON_OFF_CONTROLLABLE_DOMAINS:+ self.assertIn('on_service', service_info,+ f"{mapping_domain} should have on_service")+ self.assertIn('off_service', service_info,+ f"{mapping_domain} should have off_service")++ # Verify service names are valid+ self.assertIsNotNone(service_info.get('on_service'))+ self.assertIsNotNone(service_info.get('off_service'))++ # Check for parameters field+ self.assertIn('parameters', service_info,+ f"{mapping_domain}/{entity_type} should have parameters field")+ self.assertIsInstance(service_info['parameters'], dict,+ f"Parameters should be a dict for {mapping_domain}/{entity_type}")++ # Special checks for specific domains+ if mapping_domain == HassApi.LIGHT_DOMAIN and entity_type == EntityStateType.LIGHT_DIMMER:+ self.assertIn('set_service', service_info,+ "Dimmer lights should have set_service for brightness")+ self.assertIn('brightness_pct', service_info['parameters'],+ "Dimmer lights should have brightness_pct parameter")++ if mapping_domain == HassApi.CLIMATE_DOMAIN:+ self.assertIn('set_service', service_info,+ "Climate should have set_service for temperature")+ self.assertIn('temperature', service_info['parameters'],+ "Climate should have temperature parameter")++ def test_sensor_creation_for_non_controllable_domains(self):+ """Test that sensors are created correctly for non-controllable domains"""++ # Find a binary sensor (non-controllable)+ sensor_data = None+ for state_data in self.real_ha_states_data:+ if state_data.get('entity_id', '').startswith('binary_sensor.'):+ sensor_data = state_data+ break++ self.assertIsNotNone(sensor_data, "Should find a binary sensor in test data")++ hass_state = HassConverter.create_hass_state(sensor_data)+ integration_key = IntegrationKey(+ integration_id='hass',+ integration_name=hass_state.entity_id+ )++ # Create mock HassDevice+ hass_device = Mock(spec=HassDevice)+ hass_device.device_id = 'test_sensor_device'++ # Call the mapping method+ entity_state = HassConverter._create_hass_state_with_mapping(+ hass_device=hass_device,+ hass_state=hass_state,+ entity=self.test_entity,+ integration_key=integration_key,+ add_alarm_events=False+ )++ # Verify EntityState was created+ self.assertIsNotNone(entity_state)+ self.assertIsInstance(entity_state, EntityState)++ # Should have sensor but no controller+ controller = Controller.objects.filter(entity_state=entity_state).first()+ sensor = Sensor.objects.filter(entity_state=entity_state).first()++ self.assertIsNone(controller, "Binary sensors should not have controllers")+ self.assertIsNotNone(sensor, "Binary sensors should have sensors")++ # Verify sensor has correct integration payload+ self.assertIsNotNone(sensor.integration_payload)+ self.assertEqual(sensor.integration_payload['domain'], HassApi.BINARY_SENSOR_DOMAIN)+ self.assertIn('device_class', sensor.integration_payload)++ # Verify sensor properties+ self.assertEqual(sensor.entity_state, entity_state)+ self.assertEqual(sensor.integration_id, integration_key.integration_id)+ self.assertEqual(sensor.integration_name, integration_key.integration_name)++ def test_edge_cases_in_entity_id_parsing(self):+ """Test edge cases in entity_id parsing"""++ edge_cases = [+ # (entity_id, expected_domain, expected_full_name)+ ('light.living_room', 'light', 'living_room'),+ ('switch.outlet_1', 'switch', 'outlet_1'),+ ('sensor.temperature_sensor', 'sensor', 'temperature_sensor'),+ ('malformed_entity', 'malformed_entity', 'malformed_entity'), # No dot+ ('', '', ''), # Empty string+ # These edge cases test regex behavior: r'^([^\.]+)\.(.+)$'+ ('domain.', 'domain.', 'domain.'), # Domain with empty name - no match, fallback+ ('.name', '.name', '.name'), # Empty domain - no match, fallback+ ]++ for entity_id, expected_domain, expected_full_name in edge_cases:+ test_data = {+ 'entity_id': entity_id,+ 'state': 'unknown',+ 'attributes': {}+ }++ hass_state = HassConverter.create_hass_state(test_data)++ self.assertEqual(hass_state.entity_id, entity_id)+ self.assertEqual(hass_state.domain, expected_domain,+ f"Domain parsing failed for entity_id: {entity_id}")+ self.assertEqual(hass_state.entity_name_sans_prefix, expected_full_name,+ f"Name parsing failed for entity_id: {entity_id}")diff --git a/src/hi/services/hass/tests/test_hass_manager.py b/src/hi/services/hass/tests/test_hass_manager.pynew file mode 100644index 00000000..feb66527--- /dev/null+++ b/src/hi/services/hass/tests/test_hass_manager.py@@ -0,0 +1,930 @@+import threading+from unittest.mock import Mock, patch+from django.test import TestCase++from hi.integrations.exceptions import IntegrationAttributeError, IntegrationError+from hi.integrations.transient_models import IntegrationKey+from hi.integrations.models import Integration++from hi.services.hass.enums import HassAttributeType+from hi.services.hass.hass_client import HassClient+from hi.services.hass.hass_manager import HassManager+from hi.services.hass.hass_metadata import HassMetaData+++class TestHassManagerSingleton(TestCase):+ """Test singleton behavior and thread safety"""++ def setUp(self):+ # Reset singleton instance for each test+ HassManager._instance = None+ HassManager._lock = threading.Lock()++ def test_singleton_behavior(self):+ """Test that HassManager follows singleton pattern"""+ manager1 = HassManager()+ manager2 = HassManager()+ self.assertIs(manager1, manager2)++ def test_singleton_thread_safety(self):+ """Test singleton creation is thread-safe"""+ results = []++ def create_manager():+ results.append(HassManager())++ threads = [threading.Thread(target=create_manager) for _ in range(10)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()++ # All instances should be the same object+ first_instance = results[0]+ for instance in results[1:]:+ self.assertIs(instance, first_instance)++ # Verify singleton maintains consistent state across threads+ test_value = 'test_thread_safety'+ first_instance._test_attribute = test_value+ for instance in results:+ self.assertEqual(getattr(instance, '_test_attribute', None), test_value)++ def test_singleton_initialization_state_consistency(self):+ """Test that singleton maintains consistent initialization state"""+ manager1 = HassManager()++ # Verify initial state+ self.assertEqual(manager1._hass_attr_type_to_attribute, {})+ self.assertIsNone(manager1._hass_client)+ self.assertFalse(manager1._was_initialized)++ # Modify state+ manager1._was_initialized = True+ manager1._hass_attr_type_to_attribute = {'test': 'value'}++ # Get another instance and verify state persistence+ manager2 = HassManager()+ self.assertTrue(manager2._was_initialized)+ self.assertEqual(manager2._hass_attr_type_to_attribute, {'test': 'value'})+++class TestHassManagerInitialization(TestCase):+ """Test initialization and attribute loading"""++ def setUp(self):+ HassManager._instance = None+ HassManager._lock = threading.Lock()+ self.manager = HassManager()++ def test_init_singleton_sets_defaults(self):+ """Test singleton initialization sets correct defaults"""+ self.assertEqual(self.manager._hass_attr_type_to_attribute, {})+ self.assertIsNone(self.manager._hass_client)+ self.assertEqual(self.manager._change_listeners, [])+ self.assertFalse(self.manager._was_initialized)+ self.assertIsNotNone(self.manager._data_lock)++ @patch('hi.services.hass.hass_manager.HassManager.reload')+ def test_ensure_initialized_calls_reload_once(self, mock_reload):+ """Test ensure_initialized only calls reload once and sets state correctly"""+ # Verify initial state+ self.assertFalse(self.manager._was_initialized)++ self.manager.ensure_initialized()+ mock_reload.assert_called_once()+ self.assertTrue(self.manager._was_initialized)++ # Second call should not trigger reload but state should remain+ self.manager.ensure_initialized()+ mock_reload.assert_called_once() # Still only one call+ self.assertTrue(self.manager._was_initialized)++ def test_ensure_initialized_idempotent_behavior(self):+ """Test ensure_initialized can be called multiple times safely"""+ with patch.object(self.manager, 'reload') as mock_reload:+ # Call multiple times+ for _ in range(5):+ self.manager.ensure_initialized()++ # Should only be called once+ mock_reload.assert_called_once()+ self.assertTrue(self.manager._was_initialized)++ @patch.object(Integration.objects, 'get')+ def test_load_attributes_integration_not_found(self, mock_get):+ """Test _load_attributes raises IntegrationError when integration not found"""+ mock_get.side_effect = Integration.DoesNotExist++ with self.assertRaises(IntegrationError) as context:+ self.manager._load_attributes()++ self.assertEqual(str(context.exception), 'Home Assistant integration is not implemented.')++ @patch.object(Integration.objects, 'get')+ def test_load_attributes_integration_disabled(self, mock_get):+ """Test _load_attributes raises IntegrationError when integration disabled"""+ mock_integration = Mock()+ mock_integration.is_enabled = False+ mock_get.return_value = mock_integration++ with self.assertRaises(IntegrationError) as context:+ self.manager._load_attributes()++ self.assertEqual(str(context.exception), 'Home Assistant integration is not enabled.')++ @patch.object(Integration.objects, 'get')+ def test_load_attributes_missing_required_attribute(self, mock_get):+ """Test _load_attributes raises IntegrationAttributeError for missing required attributes"""+ mock_integration = Mock()+ mock_integration.is_enabled = True+ mock_integration.integration_id = HassMetaData.integration_id+ mock_integration.attributes_by_integration_key = {}+ mock_get.return_value = mock_integration++ with self.assertRaises(IntegrationAttributeError) as context:+ self.manager._load_attributes()++ # Should fail on first required attribute (API_BASE_URL)+ self.assertIn('Missing HAss attribute', str(context.exception))+ self.assertIn('api_base_url', str(context.exception))++ @patch.object(Integration.objects, 'get')+ def test_load_attributes_empty_required_value(self, mock_get):+ """Test _load_attributes raises IntegrationAttributeError for empty required values"""+ mock_integration = Mock()+ mock_integration.is_enabled = True+ mock_integration.integration_id = HassMetaData.integration_id++ # Create mock attribute with empty value+ mock_attr = Mock()+ mock_attr.is_required = True+ mock_attr.value = ' ' # Empty/whitespace only++ integration_key = IntegrationKey(+ integration_id=HassMetaData.integration_id,+ integration_name=str(HassAttributeType.API_BASE_URL)+ )+ mock_integration.attributes_by_integration_key = {integration_key: mock_attr}+ mock_get.return_value = mock_integration++ with self.assertRaises(IntegrationAttributeError) as context:+ self.manager._load_attributes()++ self.assertIn('Missing HAss attribute value for', str(context.exception))++ @patch.object(Integration.objects, 'get')+ def test_load_attributes_success_with_all_required(self, mock_get):+ """Test _load_attributes successfully loads all required attributes"""+ mock_integration = Mock()+ mock_integration.is_enabled = True+ mock_integration.integration_id = HassMetaData.integration_id++ # Create mock attributes for all required types+ attributes = {}+ expected_values = {}+ for attr_type in HassAttributeType:+ if attr_type.is_required:+ mock_attr = Mock()+ mock_attr.is_required = True+ test_value = f'test_value_{attr_type.name}'+ mock_attr.value = test_value+ expected_values[attr_type] = test_value+ integration_key = IntegrationKey(+ integration_id=HassMetaData.integration_id,+ integration_name=str(attr_type)+ )+ attributes[integration_key] = mock_attr++ mock_integration.attributes_by_integration_key = attributes+ mock_get.return_value = mock_integration++ result = self.manager._load_attributes()++ # Should return dictionary with all required attribute types+ required_types = [attr_type for attr_type in HassAttributeType if attr_type.is_required]+ self.assertEqual(len(result), len(required_types))++ # Verify actual attribute values and objects are returned correctly+ for attr_type in required_types:+ self.assertIn(attr_type, result)+ self.assertEqual(result[attr_type].value, expected_values[attr_type])+ self.assertTrue(result[attr_type].is_required)++ @patch.object(Integration.objects, 'get')+ def test_load_attributes_handles_optional_attributes(self, mock_get):+ """Test _load_attributes correctly handles optional attributes"""+ mock_integration = Mock()+ mock_integration.is_enabled = True+ mock_integration.integration_id = HassMetaData.integration_id++ # Only include required attributes, omit optional ones+ attributes = {}+ for attr_type in HassAttributeType:+ if attr_type.is_required:+ mock_attr = Mock()+ mock_attr.is_required = True+ mock_attr.value = f'test_value_{attr_type.name}'+ integration_key = IntegrationKey(+ integration_id=HassMetaData.integration_id,+ integration_name=str(attr_type)+ )+ attributes[integration_key] = mock_attr++ mock_integration.attributes_by_integration_key = attributes+ mock_get.return_value = mock_integration++ result = self.manager._load_attributes()++ # Should succeed with only required attributes+ required_count = len([attr for attr in HassAttributeType if attr.is_required])+ self.assertEqual(len(result), required_count)++ # Optional attributes should not be in result+ for attr_type in HassAttributeType:+ if not attr_type.is_required:+ self.assertNotIn(attr_type, result)+++class TestHassManagerClientCreation(TestCase):+ """Test HASS client creation and API option validation"""++ def setUp(self):+ HassManager._instance = None+ HassManager._lock = threading.Lock()+ self.manager = HassManager()++ def create_mock_attributes(self):+ """Helper to create mock attributes for client creation"""+ attributes = {}+ attr_values = {+ HassAttributeType.API_BASE_URL: 'https://test.homeassistant.io:8123',+ HassAttributeType.API_TOKEN: 'test_token_123456'+ }++ for attr_type, value in attr_values.items():+ mock_attr = Mock()+ mock_attr.value = value+ mock_attr.integration_key = IntegrationKey(+ integration_id=HassMetaData.integration_id,+ integration_name=str(attr_type)+ )+ attributes[attr_type] = mock_attr++ return attributes++ def test_create_hass_client_missing_api_attribute(self):+ """Test create_hass_client raises error for missing API attributes"""+ incomplete_attributes = {+ HassAttributeType.API_BASE_URL: Mock(value='https://test.homeassistant.io:8123')+ # Missing API_TOKEN+ }++ with self.assertRaises(IntegrationAttributeError) as context:+ self.manager.create_hass_client(incomplete_attributes)++ self.assertIn('Missing HAss API attribute', str(context.exception))++ def test_create_hass_client_empty_api_attribute_value(self):+ """Test create_hass_client raises error for empty API attribute values"""+ attributes = self.create_mock_attributes()+ attributes[HassAttributeType.API_BASE_URL].value = ' ' # Empty value++ with self.assertRaises(IntegrationAttributeError) as context:+ self.manager.create_hass_client(attributes)++ self.assertIn('Missing HAss API attribute value for', str(context.exception))++ @patch('hi.services.hass.hass_manager.HassClient')+ def test_create_hass_client_success(self, mock_hass_client):+ """Test create_hass_client successfully creates HassClient with correct options"""+ # Store the real constants before mocking+ real_api_base_url = HassClient.API_BASE_URL+ real_api_token = HassClient.API_TOKEN++ attributes = self.create_mock_attributes()+ mock_client = Mock()+ mock_hass_client.return_value = mock_client+ # Set the constants on the mock to match the real values+ mock_hass_client.API_BASE_URL = real_api_base_url+ mock_hass_client.API_TOKEN = real_api_token++ result = self.manager.create_hass_client(attributes)++ # Verify HassClient was called with correct options+ expected_options = {+ 'api_base_url': 'https://test.homeassistant.io:8123',+ 'api_token': 'test_token_123456'+ }+ mock_hass_client.assert_called_once_with(api_options=expected_options)+ self.assertEqual(result, mock_client)++ # Verify the returned client is stored in manager instance+ self.manager._hass_client = result+ self.assertIs(self.manager.hass_client, mock_client)++ def test_create_hass_client_validates_attribute_structure(self):+ """Test create_hass_client validates integration key structure correctly"""+ # Create attributes with different integration keys to test validation+ attributes = {}++ # Add API_BASE_URL with correct integration key+ mock_attr = Mock()+ mock_attr.value = 'https://test.homeassistant.io:8123'+ mock_attr.integration_key = IntegrationKey(+ integration_id=HassMetaData.integration_id,+ integration_name=str(HassAttributeType.API_BASE_URL)+ )+ attributes[HassAttributeType.API_BASE_URL] = mock_attr++ # Add API_TOKEN with correct integration key+ mock_attr2 = Mock()+ mock_attr2.value = 'test_token'+ mock_attr2.integration_key = IntegrationKey(+ integration_id=HassMetaData.integration_id,+ integration_name=str(HassAttributeType.API_TOKEN)+ )+ attributes[HassAttributeType.API_TOKEN] = mock_attr2++ with patch('hi.services.hass.hass_manager.HassClient') as mock_client:+ mock_client.API_BASE_URL = 'api_base_url'+ mock_client.API_TOKEN = 'api_token'+ mock_client.return_value = Mock()++ result = self.manager.create_hass_client(attributes)++ # Should succeed and create client+ self.assertIsNotNone(result)+ mock_client.assert_called_once()+++class TestHassManagerChangeListeners(TestCase):+ """Test change listener callback system and thread safety"""++ def setUp(self):+ HassManager._instance = None+ HassManager._lock = threading.Lock()+ self.manager = HassManager()++ def test_register_change_listener(self):+ """Test registering change listeners adds them to internal list"""+ callback1 = Mock()+ callback2 = Mock()++ # Verify initial empty state+ self.assertEqual(len(self.manager._change_listeners), 0)++ self.manager.register_change_listener(callback1)+ self.assertEqual(len(self.manager._change_listeners), 1)+ self.assertIn(callback1, self.manager._change_listeners)++ self.manager.register_change_listener(callback2)+ self.assertEqual(len(self.manager._change_listeners), 2)+ self.assertIn(callback1, self.manager._change_listeners)+ self.assertIn(callback2, self.manager._change_listeners)++ # Verify order is preserved+ self.assertEqual(self.manager._change_listeners[0], callback1)+ self.assertEqual(self.manager._change_listeners[1], callback2)++ @patch.object(HassManager, 'reload')+ def test_notify_settings_changed_calls_reload_and_listeners(self, mock_reload):+ """Test notify_settings_changed calls reload and all listeners in correct order"""+ call_order = []++ def track_reload():+ call_order.append('reload')++ def track_callback1():+ call_order.append('callback1')++ def track_callback2():+ call_order.append('callback2')++ mock_reload.side_effect = track_reload+ callback1 = Mock(side_effect=track_callback1)+ callback2 = Mock(side_effect=track_callback2)++ self.manager.register_change_listener(callback1)+ self.manager.register_change_listener(callback2)++ self.manager.notify_settings_changed()++ # Verify reload is called first, then callbacks+ self.assertEqual(call_order, ['reload', 'callback1', 'callback2'])+ mock_reload.assert_called_once()+ callback1.assert_called_once()+ callback2.assert_called_once()++ @patch.object(HassManager, 'reload')+ def test_notify_settings_changed_handles_callback_exceptions(self, mock_reload):+ """Test notify_settings_changed continues if callback raises exception"""+ callback1 = Mock()+ callback2 = Mock(side_effect=Exception("Test exception"))+ callback3 = Mock()++ self.manager.register_change_listener(callback1)+ self.manager.register_change_listener(callback2)+ self.manager.register_change_listener(callback3)++ # Should not raise exception despite callback2 failing+ self.manager.notify_settings_changed()++ # Verify reload was called despite callback exception+ mock_reload.assert_called_once()++ # All callbacks should be attempted+ callback1.assert_called_once()+ callback2.assert_called_once()+ callback3.assert_called_once()++ # Verify manager state remains consistent after exception+ self.assertEqual(len(self.manager._change_listeners), 3)+++class TestHassManagerReloadAndDataLock(TestCase):+ """Test reload method with data lock coordination"""++ def setUp(self):+ HassManager._instance = None+ HassManager._lock = threading.Lock()+ self.manager = HassManager()++ @patch.object(HassManager, '_load_attributes')+ @patch.object(HassManager, 'create_hass_client')+ @patch.object(HassManager, 'clear_caches')+ def test_reload_calls_methods_in_correct_order(self, mock_clear_caches, mock_create_client, mock_load_attributes):+ """Test reload calls methods in correct order within data lock"""+ call_order = []++ def track_load_attributes():+ call_order.append('load_attributes')+ return {'test': 'attributes'}++ def track_create_client(attrs):+ call_order.append('create_client')+ return Mock()++ def track_clear_caches():+ call_order.append('clear_caches')++ mock_load_attributes.side_effect = track_load_attributes+ mock_create_client.side_effect = track_create_client+ mock_clear_caches.side_effect = track_clear_caches++ # Store initial state+ initial_attributes = self.manager._hass_attr_type_to_attribute+ initial_client = self.manager._hass_client++ self.manager.reload()++ # Verify methods called in correct order+ self.assertEqual(call_order, ['load_attributes', 'create_client', 'clear_caches'])++ # Verify state updated correctly+ self.assertEqual(self.manager._hass_attr_type_to_attribute, {'test': 'attributes'})+ self.assertIsNotNone(self.manager._hass_client)++ # Verify state changed from initial values+ self.assertNotEqual(self.manager._hass_attr_type_to_attribute, initial_attributes)+ self.assertNotEqual(self.manager._hass_client, initial_client)++ @patch.object(HassManager, 'create_hass_client')+ @patch.object(HassManager, '_load_attributes')+ def test_reload_thread_safety_with_data_lock(self, mock_load_attributes, mock_create_client):+ """Test reload method uses data lock for thread safety"""+ # Mock a long-running operation+ import time++ execution_order = []+ lock_acquisition_times = []++ def slow_load():+ execution_order.append(f'load_start_{threading.current_thread().ident}')+ time.sleep(0.1) # Simulate slow operation+ execution_order.append(f'load_end_{threading.current_thread().ident}')+ return {}++ def slow_create_client(attrs):+ execution_order.append(f'create_start_{threading.current_thread().ident}')+ time.sleep(0.05) # Simulate client creation+ execution_order.append(f'create_end_{threading.current_thread().ident}')+ return Mock()++ mock_load_attributes.side_effect = slow_load+ mock_create_client.side_effect = slow_create_client++ results = []+ exceptions = []++ def run_reload():+ try:+ start_time = time.time()+ self.manager.reload()+ end_time = time.time()+ lock_acquisition_times.append((start_time, end_time))+ results.append("success")+ except Exception as e:+ exceptions.append(e)++ # Run multiple reload operations concurrently+ threads = [threading.Thread(target=run_reload) for _ in range(3)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()++ # All should complete successfully+ self.assertEqual(len(results), 3)+ self.assertEqual(len(exceptions), 0)++ # Verify operations were serialized (no overlapping execution)+ thread_executions = {}+ for event in execution_order:+ parts = event.split('_')+ thread_id = parts[2]+ event_type = f'{parts[0]}_{parts[1]}'++ if thread_id not in thread_executions:+ thread_executions[thread_id] = []+ thread_executions[thread_id].append(event_type)++ # Each thread should complete all its operations before another starts+ for thread_id, events in thread_executions.items():+ self.assertEqual(events, ['load_start', 'load_end', 'create_start', 'create_end'])+++class TestHassManagerBooleanConversion(TestCase):+ """Test enum property conversion with custom logic"""++ def setUp(self):+ HassManager._instance = None+ HassManager._lock = threading.Lock()+ self.manager = HassManager()++ @patch('hi.services.hass.hass_manager.str_to_bool')+ def test_should_add_alarm_events_true(self, mock_str_to_bool):+ """Test should_add_alarm_events returns True when attribute is true"""+ mock_attribute = Mock()+ mock_attribute.value = 'true'+ self.manager._hass_attr_type_to_attribute = {+ HassAttributeType.ADD_ALARM_EVENTS: mock_attribute+ }++ mock_str_to_bool.return_value = True++ result = self.manager.should_add_alarm_events++ self.assertTrue(result)+ mock_str_to_bool.assert_called_once_with('true')++ def test_should_add_alarm_events_false_when_no_attribute(self):+ """Test should_add_alarm_events returns False when no attribute"""+ self.manager._hass_attr_type_to_attribute = {}++ result = self.manager.should_add_alarm_events++ self.assertFalse(result)+++class TestHassManagerApiDataFetching(TestCase):+ """Test external API data fetching"""++ def setUp(self):+ HassManager._instance = None+ HassManager._lock = threading.Lock()+ self.manager = HassManager()++ # Mock the hass_client+ self.mock_client = Mock()+ self.manager._hass_client = self.mock_client++ def test_fetch_hass_states_from_api_success(self):+ """Test fetch_hass_states_from_api returns state dictionary"""+ # Mock HASS states+ mock_state1 = Mock()+ mock_state1.entity_id = 'light.living_room'+ mock_state2 = Mock()+ mock_state2.entity_id = 'switch.kitchen'++ self.mock_client.states.return_value = [mock_state1, mock_state2]++ result = self.manager.fetch_hass_states_from_api()++ self.mock_client.states.assert_called_once()+ self.assertEqual(len(result), 2)+ self.assertIn('light.living_room', result)+ self.assertIn('switch.kitchen', result)+ self.assertEqual(result['light.living_room'], mock_state1)+ self.assertEqual(result['switch.kitchen'], mock_state2)++ def test_fetch_hass_states_from_api_with_duplicate_entity_ids(self):+ """Test fetch_hass_states_from_api handles duplicate entity IDs correctly"""+ # Mock HASS states with same entity ID (should use last one)+ mock_state1 = Mock()+ mock_state1.entity_id = 'light.living_room'+ mock_state1.state = 'on'++ mock_state2 = Mock()+ mock_state2.entity_id = 'light.living_room' # Same entity ID+ mock_state2.state = 'off'++ self.mock_client.states.return_value = [mock_state1, mock_state2]++ result = self.manager.fetch_hass_states_from_api()++ # Should contain only one entry for the entity ID (the last one)+ self.assertEqual(len(result), 1)+ self.assertIn('light.living_room', result)+ self.assertEqual(result['light.living_room'], mock_state2)+ self.assertEqual(result['light.living_room'].state, 'off')++ def test_fetch_hass_states_from_api_empty_response(self):+ """Test fetch_hass_states_from_api handles empty state list"""+ self.mock_client.states.return_value = []++ result = self.manager.fetch_hass_states_from_api()++ self.assertEqual(len(result), 0)+ self.assertEqual(result, {})+ self.mock_client.states.assert_called_once()++ def test_fetch_hass_states_from_api_verbose_parameter_affects_behavior(self):+ """Test fetch_hass_states_from_api verbose parameter affects execution but not results"""+ mock_states = [+ Mock(entity_id='light.test1'),+ Mock(entity_id='switch.test2')+ ]+ self.mock_client.states.return_value = mock_states++ # Test both verbose settings return same data+ result_verbose = self.manager.fetch_hass_states_from_api(verbose=True)+ result_quiet = self.manager.fetch_hass_states_from_api(verbose=False)++ # Results should be identical regardless of verbose setting+ self.assertEqual(result_verbose, result_quiet)+ self.assertEqual(len(result_verbose), 2)+ self.assertIn('light.test1', result_verbose)+ self.assertIn('switch.test2', result_verbose)++ def test_fetch_hass_states_from_api_handles_client_exceptions(self):+ """Test fetch_hass_states_from_api propagates client exceptions"""+ self.mock_client.states.side_effect = Exception("Connection error")++ with self.assertRaises(Exception) as context:+ self.manager.fetch_hass_states_from_api()++ self.assertEqual(str(context.exception), "Connection error")++ # Verify client.states was called+ self.mock_client.states.assert_called_once()++ def test_fetch_hass_states_from_api_data_transformation(self):+ """Test fetch_hass_states_from_api correctly transforms state list to dictionary"""+ # Create states with various entity types+ states_data = [+ ('light.bedroom', 'on'),+ ('switch.kitchen', 'off'),+ ('sensor.temperature', '22.5'),+ ('binary_sensor.door', 'open')+ ]++ mock_states = []+ for entity_id, state_value in states_data:+ mock_state = Mock()+ mock_state.entity_id = entity_id+ mock_state.state = state_value+ mock_states.append(mock_state)++ self.mock_client.states.return_value = mock_states++ result = self.manager.fetch_hass_states_from_api()++ # Verify dictionary structure and data integrity+ self.assertEqual(len(result), len(states_data))+ for entity_id, expected_state in states_data:+ self.assertIn(entity_id, result)+ self.assertEqual(result[entity_id].entity_id, entity_id)+ self.assertEqual(result[entity_id].state, expected_state)++ # Verify keys are entity IDs+ expected_entity_ids = {data[0] for data in states_data}+ actual_entity_ids = set(result.keys())+ self.assertEqual(actual_entity_ids, expected_entity_ids)+++class TestHassManagerProperties(TestCase):+ """Test property access and getters"""++ def setUp(self):+ HassManager._instance = None+ HassManager._lock = threading.Lock()+ self.manager = HassManager()++ def test_hass_client_property_returns_client(self):+ """Test hass_client property returns the stored client"""+ mock_client = Mock()+ self.manager._hass_client = mock_client++ result = self.manager.hass_client++ self.assertEqual(result, mock_client)++ def test_hass_client_property_returns_none_when_no_client(self):+ """Test hass_client property returns None when no client set"""+ self.manager._hass_client = None++ result = self.manager.hass_client++ self.assertIsNone(result)++ def test_clear_caches_method_exists(self):+ """Test clear_caches method exists and is callable"""+ # Should not raise exception+ self.manager.clear_caches()++ # Method should be callable+ self.assertTrue(callable(self.manager.clear_caches))+++class TestHassManagerIntegrationBoundaries(TestCase):+ """Test integration boundary behavior and error handling"""++ def setUp(self):+ HassManager._instance = None+ HassManager._lock = threading.Lock()+ self.manager = HassManager()++ @patch.object(Integration.objects, 'get')+ def test_load_attributes_validates_integration_id_match(self, mock_get):+ """Test _load_attributes validates integration IDs match expected metadata"""+ mock_integration = Mock()+ mock_integration.is_enabled = True+ # Wrong integration ID+ mock_integration.integration_id = 'wrong_integration_id'+ mock_get.return_value = mock_integration++ # Should still work as long as query matches HassMetaData.integration_id+ # The test verifies that get() is called with correct ID+ try:+ self.manager._load_attributes()+ except (IntegrationAttributeError, IntegrationError):+ pass # Expected due to missing attributes++ mock_get.assert_called_once_with(integration_id=HassMetaData.integration_id)++ def test_create_hass_client_integration_key_consistency(self):+ """Test create_hass_client validates integration key consistency"""+ # Create attributes with mismatched integration keys+ mock_attr = Mock()+ mock_attr.value = 'https://test.homeassistant.io:8123'+ mock_attr.integration_key = IntegrationKey(+ integration_id='wrong_id', # Wrong integration ID+ integration_name=str(HassAttributeType.API_BASE_URL)+ )++ attributes = {HassAttributeType.API_BASE_URL: mock_attr}++ with self.assertRaises(IntegrationAttributeError) as context:+ self.manager.create_hass_client(attributes)++ self.assertIn('Missing HAss API attribute', str(context.exception))++ @patch.object(Integration.objects, 'get')+ def test_load_attributes_required_vs_optional_validation(self, mock_get):+ """Test _load_attributes correctly differentiates required vs optional attributes"""+ mock_integration = Mock()+ mock_integration.is_enabled = True+ mock_integration.integration_id = HassMetaData.integration_id++ # Create attributes only for required types+ attributes = {}+ required_attrs = [attr for attr in HassAttributeType if attr.is_required]+ optional_attrs = [attr for attr in HassAttributeType if not attr.is_required]++ # Add only required attributes+ for attr_type in required_attrs:+ mock_attr = Mock()+ mock_attr.is_required = True+ mock_attr.value = f'test_value_{attr_type.name}'+ integration_key = IntegrationKey(+ integration_id=HassMetaData.integration_id,+ integration_name=str(attr_type)+ )+ attributes[integration_key] = mock_attr++ mock_integration.attributes_by_integration_key = attributes+ mock_get.return_value = mock_integration++ result = self.manager._load_attributes()++ # Should succeed with only required attributes+ self.assertEqual(len(result), len(required_attrs))++ # Optional attributes should not be required+ for attr_type in optional_attrs:+ self.assertNotIn(attr_type, result)++ def test_manager_state_isolation_between_instances(self):+ """Test that manager state is properly isolated in singleton"""+ # This tests the singleton pattern maintains state correctly+ manager1 = HassManager()+ manager1._test_state = 'test_value_1'++ manager2 = HassManager()+ self.assertIs(manager1, manager2)+ self.assertEqual(getattr(manager2, '_test_state', None), 'test_value_1')++ # Modify state through manager2+ manager2._test_state = 'test_value_2'++ # manager1 should see the change+ self.assertEqual(manager1._test_state, 'test_value_2')+++class TestHassManagerComplexBusinessLogic(TestCase):+ """Test complex business logic scenarios and edge cases"""++ def setUp(self):+ HassManager._instance = None+ HassManager._lock = threading.Lock()+ self.manager = HassManager()++ @patch.object(Integration.objects, 'get')+ def test_attribute_value_whitespace_handling(self, mock_get):+ """Test attribute value validation handles whitespace correctly"""+ mock_integration = Mock()+ mock_integration.is_enabled = True+ mock_integration.integration_id = HassMetaData.integration_id++ # Test various whitespace scenarios+ whitespace_values = [+ ' ', # Only spaces+ '\t\t', # Only tabs+ '\n\n', # Only newlines+ ' \t\n ', # Mixed whitespace+ '', # Empty string+ ]++ for whitespace_value in whitespace_values:+ with self.subTest(value=repr(whitespace_value)):+ mock_attr = Mock()+ mock_attr.is_required = True+ mock_attr.value = whitespace_value++ integration_key = IntegrationKey(+ integration_id=HassMetaData.integration_id,+ integration_name=str(HassAttributeType.API_BASE_URL)+ )+ mock_integration.attributes_by_integration_key = {integration_key: mock_attr}+ mock_get.return_value = mock_integration++ with self.assertRaises(IntegrationAttributeError) as context:+ self.manager._load_attributes()++ self.assertIn('Missing HAss attribute value for', str(context.exception))++ def test_concurrent_initialization_and_reload(self):+ """Test concurrent initialization and reload operations"""+ import time+ results = []+ exceptions = []++ def initialize_manager():+ try:+ with patch.object(self.manager, 'reload') as mock_reload:+ mock_reload.side_effect = lambda: time.sleep(0.05) # Slow reload++ self.manager.ensure_initialized()+ results.append('initialized')+ except Exception as e:+ exceptions.append(e)++ def reload_manager():+ try:+ with patch.object(self.manager, '_load_attributes') as mock_load:+ with patch.object(self.manager, 'create_hass_client') as mock_create:+ mock_load.return_value = {}+ mock_create.return_value = Mock()+ time.sleep(0.05) # Slow operation++ self.manager.reload()+ results.append('reloaded')+ except Exception as e:+ exceptions.append(e)++ # Run concurrent operations+ threads = [+ threading.Thread(target=initialize_manager),+ threading.Thread(target=reload_manager),+ threading.Thread(target=initialize_manager),+ ]++ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()++ # All operations should complete successfully+ self.assertEqual(len(exceptions), 0)+ self.assertGreater(len(results), 0)diff --git a/src/hi/services/hass/tests/test_hass_sync.py b/src/hi/services/hass/tests/test_hass_sync.pynew file mode 100644index 00000000..59eadc29--- /dev/null+++ b/src/hi/services/hass/tests/test_hass_sync.py@@ -0,0 +1,455 @@+import json+import os+from unittest.mock import Mock, patch+from django.test import TestCase++from hi.apps.common.processing_result import ProcessingResult+from hi.apps.entity.models import Entity+from hi.integrations.transient_models import IntegrationKey++from hi.services.hass.hass_sync import HassSynchronizer+from hi.services.hass.hass_models import HassDevice, HassState+++class TestHassSynchronizerInitialization(TestCase):+ """Test HassSynchronizer initialization and basic setup"""++ def test_init_creates_instance_successfully(self):+ """Test HassSynchronizer initialization"""+ synchronizer = HassSynchronizer()+ self.assertIsInstance(synchronizer, HassSynchronizer)++ def test_synchronization_lock_name_constant(self):+ """Test SYNCHRONIZATION_LOCK_NAME constant is properly defined"""+ self.assertEqual(HassSynchronizer.SYNCHRONIZATION_LOCK_NAME, 'hass_integration_sync')++ def test_inherits_from_mixins(self):+ """Test that HassSynchronizer inherits from required mixins"""+ synchronizer = HassSynchronizer()++ # Should inherit from HassMixin+ self.assertTrue(hasattr(synchronizer, 'hass_manager'))++ # Should inherit from IntegrationSyncMixin+ self.assertTrue(hasattr(synchronizer, '_remove_entity_intelligently'))+++class TestHassSynchronizerSyncMethod(TestCase):+ """Test main sync() method with database transactions"""++ def setUp(self):+ self.synchronizer = HassSynchronizer()++ @patch('hi.services.hass.hass_sync.ExclusionLockContext')+ @patch.object(HassSynchronizer, '_sync_helper')+ def test_sync_success_with_lock(self, mock_sync_helper, mock_lock_context):+ """Test successful sync operation with proper locking"""+ # Mock successful sync result+ expected_result = ProcessingResult(title='HAss Sync Result')+ expected_result.message_list.append('Sync completed successfully')+ mock_sync_helper.return_value = expected_result++ # Mock lock context manager+ mock_lock_context.return_value.__enter__ = Mock()+ mock_lock_context.return_value.__exit__ = Mock()++ result = self.synchronizer.sync()++ # Verify lock was used with correct name+ mock_lock_context.assert_called_once_with(name='hass_integration_sync')++ # Verify helper was called+ mock_sync_helper.assert_called_once()++ # Verify result+ self.assertEqual(result, expected_result)+ self.assertIn('Sync completed successfully', result.message_list)++ @patch('hi.services.hass.hass_sync.ExclusionLockContext')+ @patch.object(HassSynchronizer, '_sync_helper')+ def test_sync_handles_runtime_error(self, mock_sync_helper, mock_lock_context):+ """Test sync method handles RuntimeError exceptions"""+ # Mock RuntimeError in sync helper+ mock_sync_helper.side_effect = RuntimeError("Database connection failed")++ # Mock lock context manager properly+ mock_context = Mock()+ mock_context.__enter__ = Mock()+ mock_context.__exit__ = Mock(return_value=False)+ mock_lock_context.return_value = mock_context++ result = self.synchronizer.sync()++ # Verify error handling+ self.assertEqual(result.title, 'HAss Sync Result')+ self.assertIn('Database connection failed', result.error_list[0])++ @patch('hi.services.hass.hass_sync.ExclusionLockContext')+ @patch.object(HassSynchronizer, '_sync_helper')+ def test_sync_returns_error_result_on_exception(self, mock_sync_helper, mock_lock_context):+ """Test sync method returns proper error result when _sync_helper raises exception"""+ # Mock RuntimeError in sync helper+ mock_sync_helper.side_effect = RuntimeError("Database connection failed")++ # Mock lock context manager properly+ mock_context = Mock()+ mock_context.__enter__ = Mock()+ mock_context.__exit__ = Mock(return_value=False)+ mock_lock_context.return_value = mock_context++ result = self.synchronizer.sync()++ # Verify actual error result structure and content+ self.assertEqual(result.title, 'HAss Sync Result')+ self.assertEqual(len(result.error_list), 1)+ self.assertIn('Database connection failed', result.error_list[0])+ self.assertEqual(len(result.message_list), 0) # No success messages on error+++class TestHassSynchronizerSyncHelper(TestCase):+ """Test _sync_helper method logic"""++ def setUp(self):+ self.synchronizer = HassSynchronizer()++ # Mock hass_manager and dependencies+ self.mock_manager = Mock()+ self.mock_client = Mock()+ self.mock_manager.hass_client = self.mock_client++ @patch.object(HassSynchronizer, 'hass_manager')+ def test_sync_helper_client_not_available(self, mock_hass_manager):+ """Test sync helper handles missing HASS client"""+ # Mock manager without client+ self.mock_manager.hass_client = None+ mock_hass_manager.return_value = self.mock_manager++ result = self.synchronizer._sync_helper()++ self.assertEqual(result.title, 'HAss Sync Result')+ self.assertIn('Sync problem. HAss integration disabled?', result.error_list)++ @patch('hi.services.hass.hass_sync.HassConverter.hass_states_to_hass_devices')+ @patch('hi.services.hass.hass_sync.HassConverter.hass_device_to_integration_key')+ @patch.object(HassSynchronizer, '_get_existing_hass_entities')+ @patch.object(HassSynchronizer, 'hass_manager')+ @patch('hi.services.hass.hass_sync.transaction')+ def test_sync_helper_successful_flow(self, mock_transaction, mock_hass_manager,+ mock_get_entities, mock_device_to_key,+ mock_states_to_devices):+ """Test successful sync helper flow with data processing"""+ # Setup mocks+ mock_hass_manager.return_value = self.mock_manager++ # Mock API data+ mock_hass_states = {+ 'light.living_room': Mock(spec=HassState),+ 'switch.kitchen': Mock(spec=HassState)+ }+ self.mock_manager.fetch_hass_states_from_api.return_value = mock_hass_states++ # Mock existing entities+ mock_entities = {}+ mock_get_entities.return_value = mock_entities++ # Mock device conversion+ mock_device = Mock(spec=HassDevice)+ mock_devices = {'device_1': mock_device}+ mock_states_to_devices.return_value = mock_devices++ # Mock integration key conversion+ mock_key = IntegrationKey(integration_id='hass', integration_name='light.living_room')+ mock_device_to_key.return_value = mock_key++ # Mock transaction context+ mock_transaction.atomic.return_value.__enter__ = Mock()+ mock_transaction.atomic.return_value.__exit__ = Mock()++ with patch.object(self.synchronizer, '_create_entity') as mock_create:+ result = self.synchronizer._sync_helper()++ # Verify API was called+ self.mock_manager.fetch_hass_states_from_api.assert_called_once()++ # Verify data processing calls+ mock_get_entities.assert_called_once()+ mock_states_to_devices.assert_called_once_with(hass_entity_id_to_state=mock_hass_states)++ # Verify entity creation was called+ mock_create.assert_called_once()++ # Verify result messages+ self.assertIn('Found 2 current HAss states.', result.message_list)+ self.assertIn('Found 0 existing HAss entities.', result.message_list)+ self.assertIn('Found 1 current HAss devices.', result.message_list)+++class TestHassSynchronizerStateConversion(TestCase):+ """Test HassSynchronizer with real HASS API data"""++ @classmethod+ def setUpClass(cls):+ super().setUpClass()+ # Load real HASS API response data+ test_data_dir = os.path.join(os.path.dirname(__file__), 'data')+ try:+ with open(os.path.join(test_data_dir, 'hass-states.json'), 'r') as f:+ cls.real_hass_states_data = json.load(f)+ except FileNotFoundError:+ cls.real_hass_states_data = []++ def setUp(self):+ self.synchronizer = HassSynchronizer()++ @patch('hi.services.hass.hass_sync.HassConverter.hass_states_to_hass_devices')+ @patch('hi.services.hass.hass_sync.HassConverter.create_hass_state')+ @patch.object(HassSynchronizer, '_get_existing_hass_entities')+ @patch.object(HassSynchronizer, 'hass_manager')+ def test_sync_helper_with_real_hass_data_structure(self, mock_hass_manager,+ mock_get_entities, mock_create_state,+ mock_states_to_devices):+ """Test sync helper processes real HASS API data structure correctly"""+ if not self.real_hass_states_data:+ self.skipTest("No real HASS data available for testing")++ # Setup mocks with real data+ mock_manager = Mock()+ mock_manager.hass_client = Mock()++ # Convert real data to HassState mocks+ mock_hass_states = {}+ for entity_data in self.real_hass_states_data[:5]: # Use first 5 entities+ entity_id = entity_data['entity_id']+ mock_state = Mock(spec=HassState)+ mock_state.entity_id = entity_id+ mock_create_state.return_value = mock_state+ mock_hass_states[entity_id] = mock_state++ mock_manager.fetch_hass_states_from_api.return_value = mock_hass_states+ mock_hass_manager.return_value = mock_manager++ mock_get_entities.return_value = {}+ mock_states_to_devices.return_value = {}++ with patch('hi.services.hass.hass_sync.transaction.atomic') as mock_atomic:+ mock_atomic.return_value.__enter__ = Mock()+ mock_atomic.return_value.__exit__ = Mock()++ result = self.synchronizer._sync_helper()++ # Verify real data was processed+ expected_count = len(mock_hass_states)+ self.assertIn(f'Found {expected_count} current HAss states.', result.message_list)++ # Verify API fetch was called+ mock_manager.fetch_hass_states_from_api.assert_called_once()++ def test_real_data_entity_id_diversity(self):+ """Test that real HASS data contains diverse entity types for comprehensive testing"""+ if not self.real_hass_states_data:+ self.skipTest("No real HASS data available for testing")++ entity_ids = [entity['entity_id'] for entity in self.real_hass_states_data]++ # Extract domains+ domains = set()+ for entity_id in entity_ids:+ if '.' in entity_id:+ domain = entity_id.split('.', 1)[0]+ domains.add(domain)++ # Verify diverse entity types for sync testing+ expected_domains = ['camera', 'sensor', 'script']+ for expected_domain in expected_domains:+ self.assertIn(expected_domain, domains,+ f"Should have {expected_domain} entities for sync testing")++ # Verify substantial data for comprehensive sync testing+ self.assertGreaterEqual(len(entity_ids), 10, "Should have substantial entities for sync testing")+++class TestHassSynchronizerTransactionBehavior(TestCase):+ """Test transaction handling and atomicity in sync operations"""++ def setUp(self):+ self.synchronizer = HassSynchronizer()++ def test_sync_helper_executes_entity_operations_atomically(self):+ """Test that all entity operations in sync_helper execute within single transaction"""+ with patch.object(self.synchronizer, 'hass_manager') as mock_hass_manager, \+ patch.object(self.synchronizer, '_get_existing_hass_entities') as mock_get_entities, \+ patch.object(self.synchronizer, '_create_entity') as mock_create, \+ patch.object(self.synchronizer, '_remove_entity') as mock_remove:++ # Setup manager+ mock_manager = Mock()+ mock_manager.hass_client = Mock()+ mock_hass_manager.return_value = mock_manager++ # Setup scenario: one new device, one entity to remove+ api_states = {'light.new': self._create_mock_hass_state('light.new', 'light', 'on')}+ mock_manager.fetch_hass_states_from_api.return_value = api_states++ old_entity = Mock(spec=Entity)+ old_key = IntegrationKey(integration_id='hass', integration_name='old_device')+ mock_get_entities.return_value = {old_key: old_entity}++ # Track transaction usage+ with patch('hi.services.hass.hass_sync.transaction.atomic') as mock_atomic:+ mock_atomic.return_value.__enter__ = Mock()+ mock_atomic.return_value.__exit__ = Mock()++ result = self.synchronizer._sync_helper()++ # Verify atomic transaction was used exactly once+ mock_atomic.assert_called_once()++ # Verify both operations occurred (would be within same transaction)+ mock_create.assert_called_once()+ mock_remove.assert_called_once()++ # Verify successful result+ self.assertEqual(len(result.error_list), 0)++ def test_sync_helper_rollback_behavior_on_entity_operation_failure(self):+ """Test that transaction rollback works when entity operations fail"""+ with patch.object(self.synchronizer, 'hass_manager') as mock_hass_manager, \+ patch.object(self.synchronizer, '_get_existing_hass_entities') as mock_get_entities:++ # Setup manager+ mock_manager = Mock()+ mock_manager.hass_client = Mock()+ mock_hass_manager.return_value = mock_manager++ # Setup API data+ api_states = {'light.test': self._create_mock_hass_state('light.test', 'light', 'on')}+ mock_manager.fetch_hass_states_from_api.return_value = api_states+ mock_get_entities.return_value = {}++ # Mock entity creation failure within transaction+ with patch.object(self.synchronizer, '_create_entity') as mock_create:+ mock_create.side_effect = Exception("Entity creation failed")++ # Transaction should propagate the exception (allowing rollback)+ with self.assertRaises(Exception) as context:+ self.synchronizer._sync_helper()++ self.assertEqual(str(context.exception), "Entity creation failed")++ def _create_mock_hass_state(self, entity_id, domain, state):+ """Helper to create mock HASS state for testing"""+ hass_state = Mock(spec=HassState)+ hass_state.entity_id = entity_id+ hass_state.domain = domain+ hass_state.state_value = state+ hass_state.entity_name_sans_prefix = entity_id.split('.', 1)[1]+ hass_state.entity_name_sans_suffix = hass_state.entity_name_sans_prefix+ hass_state.device_group_id = None+ hass_state.attributes = {}+ hass_state.device_class = None+ hass_state.friendly_name = None+ return hass_state+++class TestHassSynchronizerErrorScenarios(TestCase):+ """Test comprehensive error handling scenarios"""++ def setUp(self):+ self.synchronizer = HassSynchronizer()++ @patch('hi.services.hass.hass_sync.ExclusionLockContext')+ def test_sync_handles_exclusion_lock_timeout(self, mock_lock_context):+ """Test sync handles exclusion lock timeout gracefully"""+ # Mock lock timeout+ mock_lock_context.side_effect = RuntimeError("Lock acquisition timeout")++ result = self.synchronizer.sync()++ # Verify error handling+ self.assertEqual(result.title, 'HAss Sync Result')+ self.assertIn('Lock acquisition timeout', result.error_list[0])++ @patch.object(HassSynchronizer, 'hass_manager')+ def test_sync_helper_handles_api_fetch_failure(self, mock_hass_manager):+ """Test sync helper handles API fetch failures"""+ # Mock manager with client that fails API fetch+ mock_manager = Mock()+ mock_manager.hass_client = Mock()+ mock_manager.fetch_hass_states_from_api.side_effect = Exception("API connection failed")+ mock_hass_manager.return_value = mock_manager++ with self.assertRaises(Exception) as context:+ self.synchronizer._sync_helper()++ self.assertEqual(str(context.exception), "API connection failed")++ @patch('hi.services.hass.hass_sync.HassConverter.hass_states_to_hass_devices')+ @patch.object(HassSynchronizer, '_get_existing_hass_entities')+ @patch.object(HassSynchronizer, 'hass_manager')+ def test_sync_helper_handles_converter_failure(+ self, mock_hass_manager,+ mock_get_entities, mock_states_to_devices ):+ """Test sync helper handles converter failures"""+ # Setup mocks+ mock_manager = Mock()+ mock_manager.hass_client = Mock()+ mock_manager.fetch_hass_states_from_api.return_value = {'test': Mock()}+ mock_hass_manager.return_value = mock_manager++ mock_get_entities.return_value = {}++ # Mock converter failure+ mock_states_to_devices.side_effect = ValueError("Invalid state data format")++ with self.assertRaises(ValueError) as context:+ self.synchronizer._sync_helper()++ self.assertEqual(str(context.exception), "Invalid state data format")++ @patch('hi.services.hass.hass_sync.Entity.objects')+ def test_get_existing_entities_handles_database_error(self, mock_entity_objects):+ """Test _get_existing_hass_entities handles database errors"""+ # Mock database query failure+ mock_entity_objects.filter.side_effect = Exception("Database connection lost")++ result = ProcessingResult(title='Test')++ with self.assertRaises(Exception) as context:+ self.synchronizer._get_existing_hass_entities(result)++ self.assertEqual(str(context.exception), "Database connection lost")+++class TestHassSynchronizerMixinIntegration(TestCase):+ """Test integration with HassMixin and IntegrationSyncMixin"""++ def setUp(self):+ self.synchronizer = HassSynchronizer()++ @patch('hi.services.hass.hass_mixins.HassManager')+ def test_hass_mixin_integration(self, mock_manager_class):+ """Test HassMixin integration provides hass_manager access"""+ mock_manager_instance = Mock()+ mock_manager_class.return_value = mock_manager_instance++ # Should be able to access hass_manager through mixin+ result = self.synchronizer.hass_manager()++ self.assertEqual(result, mock_manager_instance)++ def test_integration_sync_mixin_methods_available(self):+ """Test IntegrationSyncMixin methods are available"""+ # Should have _remove_entity_intelligently method from mixin+ self.assertTrue(hasattr(self.synchronizer, '_remove_entity_intelligently'))+ self.assertTrue(callable(getattr(self.synchronizer, '_remove_entity_intelligently')))++ @patch.object(HassSynchronizer, '_remove_entity_intelligently')+ def test_remove_entity_uses_mixin_method(self, mock_remove_intelligently):+ """Test _remove_entity properly delegates to mixin method"""+ mock_entity = Mock(spec=Entity)+ result = ProcessingResult(title='Test')++ self.synchronizer._remove_entity(mock_entity, result)++ # Verify mixin method was called with correct parameters+ mock_remove_intelligently.assert_called_once_with(mock_entity, result, 'HASS')diff --git a/src/hi/services/zoneminder/tests/__init__.py b/src/hi/services/zoneminder/tests/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/services/zoneminder/tests/data/zm.monitors.json b/src/hi/services/zoneminder/tests/data/zm.monitors.jsonnew file mode 100644index 00000000..4e6e8ccf--- /dev/null+++ b/src/hi/services/zoneminder/tests/data/zm.monitors.json@@ -0,0 +1 @@+{"monitors": [{"Monitor": {"Id": "1", "Name": "HighCamera", "Notes": "", "ServerId": "0", "StorageId": "0", "Type": "Remote", "Function": "Modect", "Enabled": "1", "LinkedMonitors": null, "Triggers": "", "Device": "", "Channel": "0", "Format": "0", "V4LMultiBuffer": null, "V4LCapturesPerFrame": "1", "Protocol": "rtsp", "Method": "rtpRtsp", "Host": "192.168.100.204", "Port": "554", "SubPath": "", "Path": "live3.sdp", "Options": null, "User": null, "Pass": null, "Width": "1280", "Height": "800", "Colours": "3", "Palette": "0", "Orientation": "ROTATE_270", "Deinterlacing": "0", "DecoderHWAccelName": null, "DecoderHWAccelDevice": null, "SaveJPEGs": "3", "VideoWriter": "0", "OutputCodec": null, "OutputContainer": null, "EncoderParameters": "# Lines beginning with # are a comment \r\n# For changing quality, use the crf option\r\n# 1 is best, 51 is worst quality\r\n#crf=23", "RecordAudio": "0", "RTSPDescribe": false, "Brightness": "-1", "Contrast": "-1", "Hue": "-1", "Colour": "-1", "EventPrefix": "Event-", "LabelFormat": "%N - %d/%m/%y %H:%M:%S", "LabelX": "0", "LabelY": "0", "LabelSize": "1", "ImageBufferCount": "20", "WarmupCount": "0", "PreEventCount": "5", "PostEventCount": "15", "StreamReplayBuffer": "0", "AlarmFrameCount": "3", "SectionLength": "600", "MinSectionLength": "10", "FrameSkip": "0", "MotionFrameSkip": "0", "AnalysisFPSLimit": "5.00", "AnalysisUpdateDelay": "0", "MaxFPS": null, "AlarmMaxFPS": null, "FPSReportInterval": "100", "RefBlendPerc": "6", "AlarmRefBlendPerc": "6", "Controllable": "0", "ControlId": null, "ControlDevice": null, "ControlAddress": null, "AutoStopTimeout": null, "TrackMotion": "0", "TrackDelay": null, "ReturnLocation": "-1", "ReturnDelay": null, "DefaultRate": "100", "DefaultScale": "100", "DefaultCodec": "auto", "SignalCheckPoints": "0", "SignalCheckColour": "#0000BE", "WebColour": "#ec3688", "Exif": false, "Sequence": "1", "TotalEvents": "61", "TotalEventDiskSpace": "628452202", "HourEvents": "0", "HourEventDiskSpace": "0", "DayEvents": "1", "DayEventDiskSpace": "10711988", "WeekEvents": "9", "WeekEventDiskSpace": "99347346", "MonthEvents": "61", "MonthEventDiskSpace": "628452202", "ArchivedEvents": "0", "ArchivedEventDiskSpace": null, "ZoneCount": "5", "Refresh": null}, "Monitor_Status": {"MonitorId": "1", "Status": "Connected", "CaptureFPS": "5.00", "AnalysisFPS": "5.00", "CaptureBandwidth": "159047"}}, {"Monitor": {"Id": "2", "Name": "BackCamera", "Notes": "", "ServerId": "0", "StorageId": "0", "Type": "Remote", "Function": "Modect", "Enabled": "1", "LinkedMonitors": null, "Triggers": "", "Device": "", "Channel": "0", "Format": "0", "V4LMultiBuffer": null, "V4LCapturesPerFrame": "1", "Protocol": "rtsp", "Method": "rtpRtsp", "Host": "192.168.100.206", "Port": "554", "SubPath": "", "Path": "live3.sdp", "Options": null, "User": null, "Pass": null, "Width": "1280", "Height": "800", "Colours": "3", "Palette": "0", "Orientation": "ROTATE_0", "Deinterlacing": "0", "DecoderHWAccelName": null, "DecoderHWAccelDevice": null, "SaveJPEGs": "3", "VideoWriter": "0", "OutputCodec": null, "OutputContainer": null, "EncoderParameters": "# Lines beginning with # are a comment \r\n# For changing quality, use the crf option\r\n# 1 is best, 51 is worst quality\r\n#crf=23", "RecordAudio": "0", "RTSPDescribe": false, "Brightness": "-1", "Contrast": "-1", "Hue": "-1", "Colour": "-1", "EventPrefix": "Event-", "LabelFormat": "%N - %d/%m/%y %H:%M:%S", "LabelX": "0", "LabelY": "0", "LabelSize": "1", "ImageBufferCount": "20", "WarmupCount": "0", "PreEventCount": "5", "PostEventCount": "15", "StreamReplayBuffer": "0", "AlarmFrameCount": "3", "SectionLength": "600", "MinSectionLength": "10", "FrameSkip": "0", "MotionFrameSkip": "0", "AnalysisFPSLimit": "5.00", "AnalysisUpdateDelay": "0", "MaxFPS": null, "AlarmMaxFPS": null, "FPSReportInterval": "100", "RefBlendPerc": "6", "AlarmRefBlendPerc": "6", "Controllable": "0", "ControlId": null, "ControlDevice": null, "ControlAddress": null, "AutoStopTimeout": null, "TrackMotion": "0", "TrackDelay": null, "ReturnLocation": "-1", "ReturnDelay": null, "DefaultRate": "100", "DefaultScale": "100", "DefaultCodec": "auto", "SignalCheckPoints": "0", "SignalCheckColour": "#0000BE", "WebColour": "#d94abf", "Exif": false, "Sequence": "8", "TotalEvents": "11", "TotalEventDiskSpace": "121117494", "HourEvents": "0", "HourEventDiskSpace": "0", "DayEvents": "0", "DayEventDiskSpace": "0", "WeekEvents": "7", "WeekEventDiskSpace": "79850593", "MonthEvents": "8", "MonthEventDiskSpace": "89992068", "ArchivedEvents": "0", "ArchivedEventDiskSpace": null, "ZoneCount": "4", "Refresh": null}, "Monitor_Status": {"MonitorId": "2", "Status": "Connected", "CaptureFPS": "5.00", "AnalysisFPS": "5.00", "CaptureBandwidth": "204360"}}, {"Monitor": {"Id": "3", "Name": "FrontCamera", "Notes": "", "ServerId": "0", "StorageId": "0", "Type": "Remote", "Function": "Modect", "Enabled": "1", "LinkedMonitors": null, "Triggers": "", "Device": "", "Channel": "0", "Format": "0", "V4LMultiBuffer": null, "V4LCapturesPerFrame": "1", "Protocol": "rtsp", "Method": "rtpRtsp", "Host": "192.168.99.211", "Port": "554", "SubPath": "", "Path": "Streaming/channels/101", "Options": null, "User": null, "Pass": null, "Width": "1920", "Height": "1080", "Colours": "3", "Palette": "0", "Orientation": "ROTATE_0", "Deinterlacing": "0", "DecoderHWAccelName": null, "DecoderHWAccelDevice": null, "SaveJPEGs": "3", "VideoWriter": "0", "OutputCodec": null, "OutputContainer": null, "EncoderParameters": "# Lines beginning with # are a comment \r\n# For changing quality, use the crf option\r\n# 1 is best, 51 is worst quality\r\n#crf=23", "RecordAudio": "0", "RTSPDescribe": false, "Brightness": "-1", "Contrast": "-1", "Hue": "-1", "Colour": "-1", "EventPrefix": "Event-", "LabelFormat": "%N - %d/%m/%y %H:%M:%S", "LabelX": "0", "LabelY": "0", "LabelSize": "1", "ImageBufferCount": "20", "WarmupCount": "0", "PreEventCount": "5", "PostEventCount": "15", "StreamReplayBuffer": "0", "AlarmFrameCount": "3", "SectionLength": "600", "MinSectionLength": "10", "FrameSkip": "0", "MotionFrameSkip": "0", "AnalysisFPSLimit": "5.00", "AnalysisUpdateDelay": "0", "MaxFPS": null, "AlarmMaxFPS": null, "FPSReportInterval": "100", "RefBlendPerc": "6", "AlarmRefBlendPerc": "6", "Controllable": "0", "ControlId": null, "ControlDevice": null, "ControlAddress": null, "AutoStopTimeout": null, "TrackMotion": "0", "TrackDelay": null, "ReturnLocation": "-1", "ReturnDelay": null, "DefaultRate": "100", "DefaultScale": "100", "DefaultCodec": "auto", "SignalCheckPoints": "0", "SignalCheckColour": "#0000BE", "WebColour": "#0b8b7c", "Exif": false, "Sequence": "0", "TotalEvents": "295", "TotalEventDiskSpace": "7194580670", "HourEvents": "0", "HourEventDiskSpace": "0", "DayEvents": "1", "DayEventDiskSpace": "40725193", "WeekEvents": "113", "WeekEventDiskSpace": "2180379773", "MonthEvents": "246", "MonthEventDiskSpace": "5949548403", "ArchivedEvents": "0", "ArchivedEventDiskSpace": null, "ZoneCount": "4", "Refresh": null}, "Monitor_Status": {"MonitorId": "3", "Status": "Connected", "CaptureFPS": "8.33", "AnalysisFPS": "6.67", "CaptureBandwidth": "64662"}}, {"Monitor": {"Id": "4", "Name": "PatioCamera", "Notes": "", "ServerId": "0", "StorageId": "0", "Type": "Remote", "Function": "Modect", "Enabled": "1", "LinkedMonitors": null, "Triggers": "", "Device": "", "Channel": "0", "Format": "0", "V4LMultiBuffer": null, "V4LCapturesPerFrame": "1", "Protocol": "rtsp", "Method": "rtpRtsp", "Host": "192.168.99.212", "Port": "554", "SubPath": "", "Path": "Streaming/Channels/101", "Options": null, "User": null, "Pass": null, "Width": "1920", "Height": "1080", "Colours": "3", "Palette": "0", "Orientation": "ROTATE_0", "Deinterlacing": "0", "DecoderHWAccelName": null, "DecoderHWAccelDevice": null, "SaveJPEGs": "3", "VideoWriter": "0", "OutputCodec": null, "OutputContainer": null, "EncoderParameters": "# Lines beginning with # are a comment \r\n# For changing quality, use the crf option\r\n# 1 is best, 51 is worst quality\r\n#crf=23", "RecordAudio": "0", "RTSPDescribe": true, "Brightness": "-1", "Contrast": "-1", "Hue": "-1", "Colour": "-1", "EventPrefix": "Event-", "LabelFormat": "%N - %d/%m/%y %H:%M:%S", "LabelX": "0", "LabelY": "0", "LabelSize": "1", "ImageBufferCount": "20", "WarmupCount": "0", "PreEventCount": "5", "PostEventCount": "15", "StreamReplayBuffer": "0", "AlarmFrameCount": "3", "SectionLength": "600", "MinSectionLength": "10", "FrameSkip": "0", "MotionFrameSkip": "0", "AnalysisFPSLimit": "5.00", "AnalysisUpdateDelay": "0", "MaxFPS": null, "AlarmMaxFPS": null, "FPSReportInterval": "100", "RefBlendPerc": "6", "AlarmRefBlendPerc": "6", "Controllable": "0", "ControlId": null, "ControlDevice": null, "ControlAddress": null, "AutoStopTimeout": null, "TrackMotion": "0", "TrackDelay": null, "ReturnLocation": "-1", "ReturnDelay": null, "DefaultRate": "100", "DefaultScale": "100", "DefaultCodec": "auto", "SignalCheckPoints": "0", "SignalCheckColour": "#0000BE", "WebColour": "#382531", "Exif": false, "Sequence": "6", "TotalEvents": "129", "TotalEventDiskSpace": "3923441540", "HourEvents": "0", "HourEventDiskSpace": "0", "DayEvents": "24", "DayEventDiskSpace": "743287869", "WeekEvents": "61", "WeekEventDiskSpace": "1969585781", "MonthEvents": "129", "MonthEventDiskSpace": "3923441540", "ArchivedEvents": "0", "ArchivedEventDiskSpace": null, "ZoneCount": "7", "Refresh": null}, "Monitor_Status": {"MonitorId": "4", "Status": "Connected", "CaptureFPS": "7.69", "AnalysisFPS": "7.69", "CaptureBandwidth": "121490"}}, {"Monitor": {"Id": "5", "Name": "SideCamera", "Notes": "", "ServerId": "0", "StorageId": "0", "Type": "Remote", "Function": "Modect", "Enabled": "1", "LinkedMonitors": null, "Triggers": "", "Device": "", "Channel": "0", "Format": "0", "V4LMultiBuffer": null, "V4LCapturesPerFrame": "1", "Protocol": "rtsp", "Method": "rtpRtsp", "Host": "192.168.100.205", "Port": "554", "SubPath": "", "Path": "live3.sdp", "Options": null, "User": null, "Pass": null, "Width": "1280", "Height": "800", "Colours": "3", "Palette": "0", "Orientation": "ROTATE_0", "Deinterlacing": "0", "DecoderHWAccelName": null, "DecoderHWAccelDevice": null, "SaveJPEGs": "3", "VideoWriter": "0", "OutputCodec": null, "OutputContainer": null, "EncoderParameters": "# Lines beginning with # are a comment \r\n# For changing quality, use the crf option\r\n# 1 is best, 51 is worst quality\r\n#crf=23", "RecordAudio": "0", "RTSPDescribe": false, "Brightness": "-1", "Contrast": "-1", "Hue": "-1", "Colour": "-1", "EventPrefix": "Event-", "LabelFormat": "%N - %d/%m/%y %H:%M:%S", "LabelX": "0", "LabelY": "0", "LabelSize": "1", "ImageBufferCount": "20", "WarmupCount": "0", "PreEventCount": "5", "PostEventCount": "15", "StreamReplayBuffer": "0", "AlarmFrameCount": "3", "SectionLength": "600", "MinSectionLength": "10", "FrameSkip": "0", "MotionFrameSkip": "0", "AnalysisFPSLimit": "5.00", "AnalysisUpdateDelay": "0", "MaxFPS": null, "AlarmMaxFPS": null, "FPSReportInterval": "100", "RefBlendPerc": "6", "AlarmRefBlendPerc": "6", "Controllable": "0", "ControlId": null, "ControlDevice": null, "ControlAddress": null, "AutoStopTimeout": null, "TrackMotion": "0", "TrackDelay": null, "ReturnLocation": "-1", "ReturnDelay": null, "DefaultRate": "100", "DefaultScale": "100", "DefaultCodec": "auto", "SignalCheckPoints": "0", "SignalCheckColour": "#0000BE", "WebColour": "#90c924", "Exif": false, "Sequence": "5", "TotalEvents": "372", "TotalEventDiskSpace": "3584550628", "HourEvents": "0", "HourEventDiskSpace": "0", "DayEvents": "23", "DayEventDiskSpace": "215813104", "WeekEvents": "209", "WeekEventDiskSpace": "2130593556", "MonthEvents": "351", "MonthEventDiskSpace": "3402009872", "ArchivedEvents": "0", "ArchivedEventDiskSpace": null, "ZoneCount": "6", "Refresh": null}, "Monitor_Status": {"MonitorId": "5", "Status": "Connected", "CaptureFPS": "5.00", "AnalysisFPS": "5.00", "CaptureBandwidth": "245464"}}, {"Monitor": {"Id": "6", "Name": "DriveCamera", "Notes": "", "ServerId": "0", "StorageId": "0", "Type": "Remote", "Function": "Modect", "Enabled": "1", "LinkedMonitors": null, "Triggers": "", "Device": "", "Channel": "0", "Format": "0", "V4LMultiBuffer": null, "V4LCapturesPerFrame": "1", "Protocol": "rtsp", "Method": "rtpRtsp", "Host": "192.168.100.202", "Port": "554", "SubPath": "", "Path": "live2.sdp", "Options": null, "User": null, "Pass": null, "Width": "640", "Height": "480", "Colours": "3", "Palette": "0", "Orientation": "ROTATE_0", "Deinterlacing": "0", "DecoderHWAccelName": null, "DecoderHWAccelDevice": null, "SaveJPEGs": "3", "VideoWriter": "0", "OutputCodec": null, "OutputContainer": null, "EncoderParameters": "# Lines beginning with # are a comment \r\n# For changing quality, use the crf option\r\n# 1 is best, 51 is worst quality\r\n#crf=23", "RecordAudio": "0", "RTSPDescribe": false, "Brightness": "-1", "Contrast": "-1", "Hue": "-1", "Colour": "-1", "EventPrefix": "Event-", "LabelFormat": "%N - %d/%m/%y %H:%M:%S", "LabelX": "0", "LabelY": "0", "LabelSize": "1", "ImageBufferCount": "20", "WarmupCount": "0", "PreEventCount": "5", "PostEventCount": "15", "StreamReplayBuffer": "0", "AlarmFrameCount": "3", "SectionLength": "600", "MinSectionLength": "10", "FrameSkip": "0", "MotionFrameSkip": "0", "AnalysisFPSLimit": "5.00", "AnalysisUpdateDelay": "0", "MaxFPS": null, "AlarmMaxFPS": null, "FPSReportInterval": "100", "RefBlendPerc": "6", "AlarmRefBlendPerc": "6", "Controllable": "0", "ControlId": null, "ControlDevice": null, "ControlAddress": null, "AutoStopTimeout": null, "TrackMotion": "0", "TrackDelay": null, "ReturnLocation": "-1", "ReturnDelay": null, "DefaultRate": "100", "DefaultScale": "100", "DefaultCodec": "auto", "SignalCheckPoints": "0", "SignalCheckColour": "#0000BE", "WebColour": "#1ab997", "Exif": false, "Sequence": "2", "TotalEvents": "697", "TotalEventDiskSpace": "2882364721", "HourEvents": "0", "HourEventDiskSpace": "0", "DayEvents": "23", "DayEventDiskSpace": "102722285", "WeekEvents": "353", "WeekEventDiskSpace": "1471604409", "MonthEvents": "696", "MonthEventDiskSpace": "2881005888", "ArchivedEvents": "3", "ArchivedEventDiskSpace": "4763431", "ZoneCount": "9", "Refresh": null}, "Monitor_Status": {"MonitorId": "6", "Status": "Connected", "CaptureFPS": "10.00", "AnalysisFPS": "6.67", "CaptureBandwidth": "152861"}}, {"Monitor": {"Id": "7", "Name": "PoolCamera", "Notes": "", "ServerId": "0", "StorageId": "0", "Type": "Remote", "Function": "Modect", "Enabled": "1", "LinkedMonitors": null, "Triggers": "", "Device": "", "Channel": "0", "Format": "0", "V4LMultiBuffer": null, "V4LCapturesPerFrame": "1", "Protocol": "rtsp", "Method": "rtpRtsp", "Host": "192.168.100.201", "Port": "554", "SubPath": "", "Path": "live3.sdp", "Options": null, "User": null, "Pass": null, "Width": "1280", "Height": "800", "Colours": "3", "Palette": "0", "Orientation": "ROTATE_0", "Deinterlacing": "0", "DecoderHWAccelName": null, "DecoderHWAccelDevice": null, "SaveJPEGs": "3", "VideoWriter": "0", "OutputCodec": null, "OutputContainer": null, "EncoderParameters": "# Lines beginning with # are a comment \r\n# For changing quality, use the crf option\r\n# 1 is best, 51 is worst quality\r\n#crf=23", "RecordAudio": "0", "RTSPDescribe": false, "Brightness": "-1", "Contrast": "-1", "Hue": "-1", "Colour": "-1", "EventPrefix": "Event-", "LabelFormat": "%N - %d/%m/%y %H:%M:%S", "LabelX": "0", "LabelY": "0", "LabelSize": "1", "ImageBufferCount": "20", "WarmupCount": "0", "PreEventCount": "5", "PostEventCount": "15", "StreamReplayBuffer": "0", "AlarmFrameCount": "3", "SectionLength": "600", "MinSectionLength": "10", "FrameSkip": "0", "MotionFrameSkip": "0", "AnalysisFPSLimit": "5.00", "AnalysisUpdateDelay": "0", "MaxFPS": null, "AlarmMaxFPS": null, "FPSReportInterval": "100", "RefBlendPerc": "6", "AlarmRefBlendPerc": "6", "Controllable": "0", "ControlId": null, "ControlDevice": null, "ControlAddress": null, "AutoStopTimeout": null, "TrackMotion": "0", "TrackDelay": null, "ReturnLocation": "-1", "ReturnDelay": null, "DefaultRate": "100", "DefaultScale": "100", "DefaultCodec": "auto", "SignalCheckPoints": "0", "SignalCheckColour": "#0000BE", "WebColour": "#e43167", "Exif": false, "Sequence": "7", "TotalEvents": "31", "TotalEventDiskSpace": "357054370", "HourEvents": "0", "HourEventDiskSpace": "0", "DayEvents": "8", "DayEventDiskSpace": "80643857", "WeekEvents": "14", "WeekEventDiskSpace": "129602970", "MonthEvents": "31", "MonthEventDiskSpace": "357054370", "ArchivedEvents": "0", "ArchivedEventDiskSpace": null, "ZoneCount": "7", "Refresh": null}, "Monitor_Status": {"MonitorId": "7", "Status": "Connected", "CaptureFPS": "5.00", "AnalysisFPS": "5.00", "CaptureBandwidth": "150084"}}, {"Monitor": {"Id": "8", "Name": "CarCamera", "Notes": "", "ServerId": "0", "StorageId": "0", "Type": "Remote", "Function": "Modect", "Enabled": "1", "LinkedMonitors": null, "Triggers": "", "Device": "", "Channel": "0", "Format": "0", "V4LMultiBuffer": null, "V4LCapturesPerFrame": "1", "Protocol": "rtsp", "Method": "rtpRtsp", "Host": "192.168.99.213", "Port": "554", "SubPath": "", "Path": "Streaming/Channels/101", "Options": null, "User": null, "Pass": null, "Width": "1920", "Height": "1080", "Colours": "3", "Palette": "0", "Orientation": "ROTATE_0", "Deinterlacing": "0", "DecoderHWAccelName": null, "DecoderHWAccelDevice": null, "SaveJPEGs": "3", "VideoWriter": "0", "OutputCodec": null, "OutputContainer": null, "EncoderParameters": "# Lines beginning with # are a comment \r\n# For changing quality, use the crf option\r\n# 1 is best, 51 is worst quality\r\n#crf=23", "RecordAudio": "0", "RTSPDescribe": true, "Brightness": "-1", "Contrast": "-1", "Hue": "-1", "Colour": "-1", "EventPrefix": "Event-", "LabelFormat": "%N - %d/%m/%y %H:%M:%S", "LabelX": "0", "LabelY": "0", "LabelSize": "1", "ImageBufferCount": "20", "WarmupCount": "0", "PreEventCount": "5", "PostEventCount": "5", "StreamReplayBuffer": "0", "AlarmFrameCount": "1", "SectionLength": "600", "MinSectionLength": "10", "FrameSkip": "0", "MotionFrameSkip": "0", "AnalysisFPSLimit": "5.00", "AnalysisUpdateDelay": "0", "MaxFPS": null, "AlarmMaxFPS": null, "FPSReportInterval": "100", "RefBlendPerc": "6", "AlarmRefBlendPerc": "6", "Controllable": "0", "ControlId": null, "ControlDevice": null, "ControlAddress": null, "AutoStopTimeout": null, "TrackMotion": "0", "TrackDelay": null, "ReturnLocation": "-1", "ReturnDelay": null, "DefaultRate": "100", "DefaultScale": "100", "DefaultCodec": "auto", "SignalCheckPoints": "0", "SignalCheckColour": "#0000be", "WebColour": "#994f18", "Exif": false, "Sequence": "3", "TotalEvents": "750", "TotalEventDiskSpace": "18250676715", "HourEvents": "0", "HourEventDiskSpace": "0", "DayEvents": "132", "DayEventDiskSpace": "3754812741", "WeekEvents": "308", "WeekEventDiskSpace": "8440263128", "MonthEvents": "750", "MonthEventDiskSpace": "18250676715", "ArchivedEvents": "3", "ArchivedEventDiskSpace": "47116016", "ZoneCount": "5", "Refresh": null}, "Monitor_Status": {"MonitorId": "8", "Status": "Connected", "CaptureFPS": "7.69", "AnalysisFPS": "7.69", "CaptureBandwidth": "132454"}}, {"Monitor": {"Id": "9", "Name": "GarageCamera", "Notes": "", "ServerId": "0", "StorageId": "0", "Type": "Remote", "Function": "Modect", "Enabled": "1", "LinkedMonitors": null, "Triggers": "", "Device": "", "Channel": "0", "Format": "0", "V4LMultiBuffer": null, "V4LCapturesPerFrame": "1", "Protocol": "rtsp", "Method": "rtpRtsp", "Host": "192.168.100.203", "Port": "554", "SubPath": "", "Path": "live2.sdp", "Options": null, "User": null, "Pass": null, "Width": "640", "Height": "480", "Colours": "3", "Palette": "0", "Orientation": "ROTATE_0", "Deinterlacing": "0", "DecoderHWAccelName": null, "DecoderHWAccelDevice": null, "SaveJPEGs": "3", "VideoWriter": "0", "OutputCodec": null, "OutputContainer": null, "EncoderParameters": "# Lines beginning with # are a comment \r\n# For changing quality, use the crf option\r\n# 1 is best, 51 is worst quality\r\n#crf=23", "RecordAudio": "0", "RTSPDescribe": false, "Brightness": "-1", "Contrast": "-1", "Hue": "-1", "Colour": "-1", "EventPrefix": "Event-", "LabelFormat": "%N - %d/%m/%y %H:%M:%S", "LabelX": "0", "LabelY": "0", "LabelSize": "1", "ImageBufferCount": "20", "WarmupCount": "0", "PreEventCount": "5", "PostEventCount": "5", "StreamReplayBuffer": "0", "AlarmFrameCount": "1", "SectionLength": "600", "MinSectionLength": "10", "FrameSkip": "0", "MotionFrameSkip": "0", "AnalysisFPSLimit": "5.00", "AnalysisUpdateDelay": "0", "MaxFPS": null, "AlarmMaxFPS": null, "FPSReportInterval": "100", "RefBlendPerc": "6", "AlarmRefBlendPerc": "6", "Controllable": "0", "ControlId": null, "ControlDevice": null, "ControlAddress": null, "AutoStopTimeout": null, "TrackMotion": "0", "TrackDelay": null, "ReturnLocation": "-1", "ReturnDelay": null, "DefaultRate": "100", "DefaultScale": "100", "DefaultCodec": "auto", "SignalCheckPoints": "0", "SignalCheckColour": "#0000BE", "WebColour": "#1b5370", "Exif": false, "Sequence": "4", "TotalEvents": "113", "TotalEventDiskSpace": "235951814", "HourEvents": "0", "HourEventDiskSpace": "0", "DayEvents": "0", "DayEventDiskSpace": "0", "WeekEvents": "19", "WeekEventDiskSpace": "44264572", "MonthEvents": "113", "MonthEventDiskSpace": "235951814", "ArchivedEvents": "0", "ArchivedEventDiskSpace": null, "ZoneCount": "3", "Refresh": null}, "Monitor_Status": {"MonitorId": "9", "Status": "Connected", "CaptureFPS": "7.69", "AnalysisFPS": "8.33", "CaptureBandwidth": "18401"}}]}\ No newline at end of filediff --git a/src/hi/services/zoneminder/tests/data/zm.states.json b/src/hi/services/zoneminder/tests/data/zm.states.jsonnew file mode 100644index 00000000..9e6d4fcf--- /dev/null+++ b/src/hi/services/zoneminder/tests/data/zm.states.json@@ -0,0 +1 @@+{"states": [{"State": {"Id": "1", "Name": "default", "Definition": "", "IsActive": "0"}}, {"State": {"Id": "2", "Name": "Away", "Definition": "1:Modect:1,2:Modect:1,3:Modect:1,4:Modect:1,5:Modect:1,6:Modect:1,7:Modect:1", "IsActive": "1"}}, {"State": {"Id": "3", "Name": "HomeDay", "Definition": "1:Modect:1,2:Monitor:1,3:Modect:1,4:Monitor:1,5:Monitor:1,6:Modect:1,7:Monitor:1", "IsActive": "0"}}, {"State": {"Id": "4", "Name": "Disabled", "Definition": "1:Monitor:1,2:Monitor:1,3:Monitor:1,4:Monitor:1,5:Monitor:1,6:Monitor:1,7:Monitor:1", "IsActive": "0"}}]}\ No newline at end of filediff --git a/src/hi/services/zoneminder/tests/data/zm_monitors.json b/src/hi/services/zoneminder/tests/data/zm_monitors.jsonnew file mode 100644index 00000000..955ae102--- /dev/null+++ b/src/hi/services/zoneminder/tests/data/zm_monitors.json@@ -0,0 +1,42 @@+{"monitors": [+ {+ "Monitor": {+ "Id": "1", "Name": "HighCamera", "Function": "Modect", "Enabled": "1",+ "Width": "1280", "Height": "800", "Orientation": "ROTATE_270",+ "TotalEvents": "61", "ZoneCount": "5", "Sequence": "1"+ },+ "Monitor_Status": {+ "MonitorId": "1", "Status": "Connected", "CaptureFPS": "5.00", "AnalysisFPS": "5.00"+ }+ },+ {+ "Monitor": {+ "Id": "3", "Name": "FrontCamera", "Function": "Modect", "Enabled": "1",+ "Width": "1920", "Height": "1080", "Orientation": "ROTATE_0",+ "TotalEvents": "295", "ZoneCount": "4", "Sequence": "0"+ },+ "Monitor_Status": {+ "MonitorId": "3", "Status": "Connected", "CaptureFPS": "8.33", "AnalysisFPS": "6.67"+ }+ },+ {+ "Monitor": {+ "Id": "6", "Name": "DriveCamera", "Function": "Modect", "Enabled": "1",+ "Width": "640", "Height": "480", "Orientation": "ROTATE_0",+ "TotalEvents": "697", "ArchivedEvents": "3", "ZoneCount": "9", "Sequence": "2"+ },+ "Monitor_Status": {+ "MonitorId": "6", "Status": "Connected", "CaptureFPS": "10.00", "AnalysisFPS": "6.67"+ }+ },+ {+ "Monitor": {+ "Id": "9", "Name": "GarageCamera", "Function": "Modect", "Enabled": "1",+ "Width": "640", "Height": "480", "Orientation": "ROTATE_0",+ "TotalEvents": "113", "ZoneCount": "3", "Sequence": "4"+ },+ "Monitor_Status": {+ "MonitorId": "9", "Status": "Connected", "CaptureFPS": "7.69", "AnalysisFPS": "8.33"+ }+ }+]}\ No newline at end of filediff --git a/src/hi/services/zoneminder/tests/data/zm_states.json b/src/hi/services/zoneminder/tests/data/zm_states.jsonnew file mode 100644index 00000000..9e6d4fcf--- /dev/null+++ b/src/hi/services/zoneminder/tests/data/zm_states.json@@ -0,0 +1 @@+{"states": [{"State": {"Id": "1", "Name": "default", "Definition": "", "IsActive": "0"}}, {"State": {"Id": "2", "Name": "Away", "Definition": "1:Modect:1,2:Modect:1,3:Modect:1,4:Modect:1,5:Modect:1,6:Modect:1,7:Modect:1", "IsActive": "1"}}, {"State": {"Id": "3", "Name": "HomeDay", "Definition": "1:Modect:1,2:Monitor:1,3:Modect:1,4:Monitor:1,5:Monitor:1,6:Modect:1,7:Monitor:1", "IsActive": "0"}}, {"State": {"Id": "4", "Name": "Disabled", "Definition": "1:Monitor:1,2:Monitor:1,3:Monitor:1,4:Monitor:1,5:Monitor:1,6:Monitor:1,7:Monitor:1", "IsActive": "0"}}]}\ No newline at end of filediff --git a/src/hi/services/zoneminder/tests/test_zm_controller.py b/src/hi/services/zoneminder/tests/test_zm_controller.pynew file mode 100644index 00000000..314448ad--- /dev/null+++ b/src/hi/services/zoneminder/tests/test_zm_controller.py@@ -0,0 +1,728 @@+from unittest.mock import Mock, patch+from django.test import TestCase++from hi.integrations.transient_models import IntegrationDetails, IntegrationKey++from hi.services.zoneminder.zm_controller import ZoneMinderController+from hi.services.zoneminder.zm_manager import ZoneMinderManager+from hi.services.zoneminder.zm_metadata import ZmMetaData+++class TestZoneMinderControllerIntegrationKeyParsing(TestCase):+ """Test integration key parsing and end-to-end behavior with real manager"""++ def setUp(self):+ self.controller = ZoneMinderController()++ # Create real monitor objects that behave like pyzm Monitor objects+ self.mock_monitor_123 = Mock()+ self.mock_monitor_123.id.return_value = 123+ self.mock_monitor_123.set_parameter.return_value = {'message': 'success'}++ self.mock_monitor_4567 = Mock()+ self.mock_monitor_4567.id.return_value = 4567+ self.mock_monitor_4567.set_parameter.return_value = {'message': 'success'}++ # Mock ZMApi components+ self.mock_zm_api = Mock()+ self.mock_zm_api.set_state.return_value = {'status': 'success'}++ # Mock monitors response - this is what get_zm_monitors() calls+ self.mock_monitors_collection = Mock()+ self.mock_monitors_collection.list.return_value = [self.mock_monitor_123, self.mock_monitor_4567]+ self.mock_zm_api.monitors.return_value = self.mock_monitors_collection++ # Patch ZMApi creation to return our mock+ self.zm_api_patcher = patch('hi.services.zoneminder.zm_manager.ZMApi')+ self.mock_zm_api_class = self.zm_api_patcher.start()+ self.mock_zm_api_class.return_value = self.mock_zm_api++ # Mock the integration loading to avoid database dependency+ from hi.services.zoneminder.enums import ZmAttributeType+ from hi.integrations.transient_models import IntegrationKey++ self.integration_patcher = patch('hi.services.zoneminder.zm_manager.Integration.objects.get')+ self.mock_integration_get = self.integration_patcher.start()++ # Create mock integration attributes for required fields+ mock_attributes = {}+ for attr_type in ZmAttributeType:+ if attr_type.is_required:+ integration_key = IntegrationKey(+ integration_id=ZmMetaData.integration_id,+ integration_name=str(attr_type)+ )+ mock_attr = Mock()+ mock_attr.integration_key = integration_key+ mock_attr.is_required = attr_type.is_required+ mock_attr.value = f'test_{attr_type.name.lower()}'+ mock_attributes[integration_key] = mock_attr++ mock_integration = Mock()+ mock_integration.is_enabled = True+ mock_integration.integration_id = ZmMetaData.integration_id+ mock_integration.attributes_by_integration_key = mock_attributes+ self.mock_integration_get.return_value = mock_integration++ def tearDown(self):+ self.zm_api_patcher.stop()+ self.integration_patcher.stop()+ # Clear any cached manager instance from controller+ if hasattr(self.controller, '_zm_manager'):+ delattr(self.controller, '_zm_manager')+ # Reset singleton instance to ensure clean state between tests+ ZoneMinderManager._instance = None++ def test_run_state_control_exact_match(self):+ """Test run state control end-to-end with real manager"""+ integration_key = IntegrationKey(+ integration_id=ZmMetaData.integration_id,+ integration_name='run.state'+ )+ integration_details = IntegrationDetails(key=integration_key)++ self.mock_zm_api.set_state.return_value = {'status': 'success'}++ # Test actual behavior - manager should be created and used+ result = self.controller.do_control(integration_details, 'start')++ # Verify HTTP API call was made correctly+ self.mock_zm_api.set_state.assert_called_once_with('start')++ # Verify actual controller behavior+ self.assertEqual(result.new_value, 'start')+ self.assertEqual(result.error_list, [])++ # Verify manager singleton behavior+ manager1 = self.controller.zm_manager()+ manager2 = self.controller.zm_manager()+ self.assertIs(manager1, manager2, "Manager should be singleton")++ # Verify cache state was actually cleared+ self.assertEqual(manager1._zm_state_list, [])+ self.assertEqual(manager1._zm_monitor_list, [])++ def test_monitor_function_regex_parsing_valid_id(self):+ """Test monitor function control end-to-end with real integration key parsing"""+ integration_key = IntegrationKey(+ integration_id=ZmMetaData.integration_id,+ integration_name='monitor.function.123'+ )+ integration_details = IntegrationDetails(key=integration_key)++ # Test end-to-end: controller should parse integration name,+ # create real manager, get monitors, and call correct monitor+ result = self.controller.do_control(integration_details, 'Modect')++ # Verify correct monitor (ID 123) was called with correct parameters+ self.mock_monitor_123.set_parameter.assert_called_once_with({'function': 'Modect'})+ self.mock_monitor_4567.set_parameter.assert_not_called()++ # Verify controller return value+ self.assertEqual(result.new_value, 'Modect')+ self.assertEqual(result.error_list, [])++ # Verify real manager was used to get monitors+ self.mock_zm_api.monitors.assert_called_once_with({'force_reload': True})++ # Verify cache was actually cleared by checking manager state+ manager = self.controller.zm_manager()+ self.assertEqual(manager._zm_monitor_list, [])++ def test_monitor_function_regex_parsing_multi_digit_id(self):+ """Test monitor function control handles multi-digit monitor IDs correctly"""+ integration_key = IntegrationKey(+ integration_id=ZmMetaData.integration_id,+ integration_name='monitor.function.4567'+ )+ integration_details = IntegrationDetails(key=integration_key)++ result = self.controller.do_control(integration_details, 'Record')++ # Verify correct monitor (ID 4567) was identified and called+ self.mock_monitor_4567.set_parameter.assert_called_once_with({'function': 'Record'})+ self.mock_monitor_123.set_parameter.assert_not_called()+ self.assertEqual(result.new_value, 'Record')++ # Verify manager processed monitor ID matching correctly+ # (string '4567' should match integer 4567)+ self.mock_monitor_4567.id.assert_called()++ def test_monitor_function_regex_no_match_invalid_format(self):+ """Test error handling when integration name has invalid format"""+ integration_key = IntegrationKey(+ integration_id=ZmMetaData.integration_id,+ integration_name='monitor.function.abc' # No numeric ID+ )+ integration_details = IntegrationDetails(key=integration_key)++ result = self.controller.do_control(integration_details, 'Modect')++ # Should fall through to unknown action error+ self.assertIsNone(result.new_value)+ self.assertIn('Unknown ZM control action.', result.error_list[0])++ # Verify manager cache was still cleared even on error+ manager = self.controller.zm_manager()+ self.assertEqual(manager._zm_state_list, [])+ self.assertEqual(manager._zm_monitor_list, [])++ def test_unknown_integration_name_error(self):+ """Test error handling for unknown integration names with real manager"""+ integration_key = IntegrationKey(+ integration_id=ZmMetaData.integration_id,+ integration_name='unknown.action'+ )+ integration_details = IntegrationDetails(key=integration_key)++ result = self.controller.do_control(integration_details, 'test')++ self.assertIsNone(result.new_value)+ self.assertIn('Unknown ZM control action.', result.error_list[0])++ # Verify real manager was created and cache cleared+ manager = self.controller.zm_manager()+ self.assertIsInstance(manager, ZoneMinderManager)+ self.assertEqual(manager._zm_state_list, [])+ self.assertEqual(manager._zm_monitor_list, [])+++class TestZoneMinderControllerRunStateControl(TestCase):+ """Test run state control with real manager and broader assertions"""++ def setUp(self):+ self.controller = ZoneMinderController()++ # Mock ZMApi at HTTP boundary+ self.mock_zm_api = Mock()+ self.mock_zm_api.set_state.return_value = {'status': 'success'}++ # Patch ZMApi creation+ self.zm_api_patcher = patch('hi.services.zoneminder.zm_manager.ZMApi')+ self.mock_zm_api_class = self.zm_api_patcher.start()+ self.mock_zm_api_class.return_value = self.mock_zm_api++ # Mock integration loading+ from hi.services.zoneminder.enums import ZmAttributeType+ self.integration_patcher = patch('hi.services.zoneminder.zm_manager.Integration.objects.get')+ self.mock_integration_get = self.integration_patcher.start()++ # Create mock integration attributes+ mock_attributes = {}+ for attr_type in ZmAttributeType:+ if attr_type.is_required:+ integration_key = IntegrationKey(+ integration_id=ZmMetaData.integration_id,+ integration_name=str(attr_type)+ )+ mock_attr = Mock()+ mock_attr.integration_key = integration_key+ mock_attr.is_required = attr_type.is_required+ mock_attr.value = f'test_{attr_type.name.lower()}'+ mock_attributes[integration_key] = mock_attr++ mock_integration = Mock()+ mock_integration.is_enabled = True+ mock_integration.integration_id = ZmMetaData.integration_id+ mock_integration.attributes_by_integration_key = mock_attributes+ self.mock_integration_get.return_value = mock_integration++ def tearDown(self):+ self.zm_api_patcher.stop()+ self.integration_patcher.stop()+ if hasattr(self.controller, '_zm_manager'):+ delattr(self.controller, '_zm_manager')+ ZoneMinderManager._instance = None++ def test_set_run_state_success(self):+ """Test successful run state setting with real manager integration"""+ result = self.controller.set_run_state('start')++ # Verify HTTP API was called correctly+ self.mock_zm_api.set_state.assert_called_once_with('start')++ # Verify controller behavior+ self.assertEqual(result.new_value, 'start')+ self.assertEqual(result.error_list, [])++ # Verify real manager was created and used+ manager = self.controller.zm_manager()+ self.assertIsInstance(manager, ZoneMinderManager)++ # Verify manager caching - same instance returned+ manager2 = self.controller.zm_manager()+ self.assertIs(manager, manager2)++ def test_set_run_state_different_values(self):+ """Test run state setting with different values and behavior verification"""+ test_values = ['start', 'stop', 'restart', 'pause']++ for value in test_values:+ with self.subTest(value=value):+ self.mock_zm_api.reset_mock()+ self.mock_zm_api.set_state.return_value = {'status': 'success'}++ result = self.controller.set_run_state(value)++ # Verify HTTP call+ self.mock_zm_api.set_state.assert_called_once_with(value)++ # Verify behavior+ self.assertEqual(result.new_value, value)+ self.assertEqual(result.error_list, [])++ # Verify manager state consistency across multiple calls+ manager = self.controller.zm_manager()+ self.assertIsInstance(manager, ZoneMinderManager)+ # Manager should maintain the same client+ self.assertIs(manager._zm_client, self.mock_zm_api)++ def test_set_run_state_with_api_exception(self):+ """Test run state setting handles API exceptions with real error propagation"""+ self.mock_zm_api.set_state.side_effect = Exception("API connection failed")++ # Test that exception is properly caught and handled by calling code+ with self.assertRaises(Exception) as context:+ self.controller.set_run_state('start')++ self.assertEqual(str(context.exception), "API connection failed")++ # Verify API was called despite exception+ self.mock_zm_api.set_state.assert_called_once_with('start')++ # Verify manager was still created and maintains state+ manager = self.controller.zm_manager()+ self.assertIsInstance(manager, ZoneMinderManager)+++class TestZoneMinderControllerMonitorFunctionControl(TestCase):+ """Test monitor function control with real manager and end-to-end data flow"""++ def setUp(self):+ self.controller = ZoneMinderController()++ # Create monitor mocks with realistic behavior+ self.mock_monitor_111 = Mock()+ self.mock_monitor_111.id.return_value = 111+ self.mock_monitor_111.set_parameter.return_value = {'message': 'Monitor saved'}++ self.mock_monitor_222 = Mock()+ self.mock_monitor_222.id.return_value = 222+ self.mock_monitor_222.set_parameter.return_value = {'message': 'Success'}++ self.mock_monitor_333 = Mock()+ self.mock_monitor_333.id.return_value = 333+ self.mock_monitor_333.set_parameter.return_value = {'message': 'Updated'}++ # Mock ZMApi at HTTP boundary+ self.mock_zm_api = Mock()+ self.mock_monitors_collection = Mock()+ self.mock_monitors_collection.list.return_value = [+ self.mock_monitor_111, self.mock_monitor_222, self.mock_monitor_333+ ]+ self.mock_zm_api.monitors.return_value = self.mock_monitors_collection++ # Patch ZMApi creation+ self.zm_api_patcher = patch('hi.services.zoneminder.zm_manager.ZMApi')+ self.mock_zm_api_class = self.zm_api_patcher.start()+ self.mock_zm_api_class.return_value = self.mock_zm_api++ # Mock integration loading+ from hi.services.zoneminder.enums import ZmAttributeType+ self.integration_patcher = patch('hi.services.zoneminder.zm_manager.Integration.objects.get')+ self.mock_integration_get = self.integration_patcher.start()++ mock_attributes = {}+ for attr_type in ZmAttributeType:+ if attr_type.is_required:+ integration_key = IntegrationKey(+ integration_id=ZmMetaData.integration_id,+ integration_name=str(attr_type)+ )+ mock_attr = Mock()+ mock_attr.integration_key = integration_key+ mock_attr.is_required = attr_type.is_required+ mock_attr.value = f'test_{attr_type.name.lower()}'+ mock_attributes[integration_key] = mock_attr++ mock_integration = Mock()+ mock_integration.is_enabled = True+ mock_integration.integration_id = ZmMetaData.integration_id+ mock_integration.attributes_by_integration_key = mock_attributes+ self.mock_integration_get.return_value = mock_integration++ def tearDown(self):+ self.zm_api_patcher.stop()+ self.integration_patcher.stop()+ if hasattr(self.controller, '_zm_manager'):+ delattr(self.controller, '_zm_manager')+ ZoneMinderManager._instance = None++ def test_set_monitor_function_success(self):+ """Test successful monitor function setting with real manager integration"""+ result = self.controller.set_monitor_function('222', 'Modect')++ # Verify correct monitor was called+ self.mock_monitor_222.set_parameter.assert_called_once_with({'function': 'Modect'})+ self.mock_monitor_111.set_parameter.assert_not_called()+ self.mock_monitor_333.set_parameter.assert_not_called()++ # Verify controller behavior+ self.assertEqual(result.new_value, 'Modect')+ self.assertEqual(result.error_list, [])++ # Verify real manager was used to fetch monitors+ self.mock_zm_api.monitors.assert_called_once_with({'force_reload': True})++ # Verify manager state and behavior+ manager = self.controller.zm_manager()+ self.assertIsInstance(manager, ZoneMinderManager)++ # Test that caching works - subsequent calls use cached data+ cached_monitors = manager.get_zm_monitors()+ self.assertEqual(len(cached_monitors), 3)+ self.assertIn(self.mock_monitor_222, cached_monitors)++ def test_set_monitor_function_multiple_monitors_correct_match(self):+ """Test monitor function correctly identifies target monitor among multiple"""+ result = self.controller.set_monitor_function('111', 'Record')++ # Only the correct monitor should have set_parameter called+ self.mock_monitor_111.set_parameter.assert_called_once_with({'function': 'Record'})+ self.mock_monitor_222.set_parameter.assert_not_called()+ self.mock_monitor_333.set_parameter.assert_not_called()++ self.assertEqual(result.new_value, 'Record')++ # Verify correct monitor was found (others may or may not be checked depending on order)+ self.mock_monitor_111.id.assert_called()++ # Verify real data flow through manager+ manager = self.controller.zm_manager()+ monitors = manager.get_zm_monitors()+ self.assertEqual(len(monitors), 3)++ def test_set_monitor_function_string_id_comparison(self):+ """Test monitor function handles string/int ID comparison correctly in real manager"""+ # Pass string ID (as comes from regex parsing) that should match integer 222+ result = self.controller.set_monitor_function('222', 'Motion')++ # Verify string '222' matched integer 222+ self.mock_monitor_222.set_parameter.assert_called_once_with({'function': 'Motion'})+ self.assertEqual(result.new_value, 'Motion')++ # Verify the comparison logic worked correctly+ self.mock_monitor_111.set_parameter.assert_not_called()+ self.mock_monitor_333.set_parameter.assert_not_called()++ # Test edge case: leading zeros should not match+ self.mock_monitor_333.set_parameter.reset_mock()++ # This should not match because '0333' != '333' as strings+ # Testing real behavior - string comparison is exact+ with self.assertRaises(ValueError) as context:+ self.controller.set_monitor_function('0333', 'Nodect')+ self.assertEqual(str(context.exception), 'Unknown ZM entity.')++ def test_set_monitor_function_monitor_not_found(self):+ """Test monitor function raises error when monitor ID not found with real manager"""+ with self.assertRaises(ValueError) as context:+ self.controller.set_monitor_function('999', 'Modect')++ self.assertEqual(str(context.exception), 'Unknown ZM entity.')++ # Verify all monitors were checked but none matched+ self.mock_monitor_111.set_parameter.assert_not_called()+ self.mock_monitor_222.set_parameter.assert_not_called()+ self.mock_monitor_333.set_parameter.assert_not_called()++ # Verify real manager was used to fetch monitors+ self.mock_zm_api.monitors.assert_called_once_with({'force_reload': True})++ def test_set_monitor_function_api_error_response(self):+ """Test monitor function handles API error responses with real error propagation"""+ # Configure monitor to return error response+ self.mock_monitor_222.set_parameter.return_value = {'message': 'Error: Invalid function'}++ with self.assertRaises(ValueError) as context:+ self.controller.set_monitor_function('222', 'InvalidFunction')++ self.assertEqual(str(context.exception), 'Problen setting ZM monitor function.')++ # Verify the monitor was called and error was detected+ self.mock_monitor_222.set_parameter.assert_called_once_with({'function': 'InvalidFunction'})++ # Verify error detection logic works with real response checking+ response = self.mock_monitor_222.set_parameter.return_value+ self.assertIn('error', response['message'].lower())++ def test_set_monitor_function_various_function_values(self):+ """Test monitor function setting with various valid function values and real manager"""+ function_values = ['None', 'Monitor', 'Modect', 'Record', 'Mocord', 'Nodect']++ for function_value in function_values:+ with self.subTest(function_value=function_value):+ # Reset mock to track this specific call+ self.mock_monitor_111.set_parameter.reset_mock()+ self.mock_monitor_111.set_parameter.return_value = {'message': 'Success'}++ result = self.controller.set_monitor_function('111', function_value)++ # Verify correct function value was set+ self.mock_monitor_111.set_parameter.assert_called_with({'function': function_value})+ self.assertEqual(result.new_value, function_value)+ self.assertEqual(result.error_list, [])++ # Verify manager consistency across multiple function changes+ manager = self.controller.zm_manager()+ self.assertIsInstance(manager, ZoneMinderManager)+++class TestZoneMinderControllerExceptionHandling(TestCase):+ """Test exception handling with real manager and error recovery scenarios"""++ def setUp(self):+ self.controller = ZoneMinderController()++ # Mock ZMApi at HTTP boundary+ self.mock_zm_api = Mock()++ # Patch ZMApi creation+ self.zm_api_patcher = patch('hi.services.zoneminder.zm_manager.ZMApi')+ self.mock_zm_api_class = self.zm_api_patcher.start()+ self.mock_zm_api_class.return_value = self.mock_zm_api++ # Mock integration loading+ from hi.services.zoneminder.enums import ZmAttributeType+ self.integration_patcher = patch('hi.services.zoneminder.zm_manager.Integration.objects.get')+ self.mock_integration_get = self.integration_patcher.start()++ mock_attributes = {}+ for attr_type in ZmAttributeType:+ if attr_type.is_required:+ integration_key = IntegrationKey(+ integration_id=ZmMetaData.integration_id,+ integration_name=str(attr_type)+ )+ mock_attr = Mock()+ mock_attr.integration_key = integration_key+ mock_attr.is_required = attr_type.is_required+ mock_attr.value = f'test_{attr_type.name.lower()}'+ mock_attributes[integration_key] = mock_attr++ mock_integration = Mock()+ mock_integration.is_enabled = True+ mock_integration.integration_id = ZmMetaData.integration_id+ mock_integration.attributes_by_integration_key = mock_attributes+ self.mock_integration_get.return_value = mock_integration++ def tearDown(self):+ self.zm_api_patcher.stop()+ self.integration_patcher.stop()+ if hasattr(self.controller, '_zm_manager'):+ delattr(self.controller, '_zm_manager')+ ZoneMinderManager._instance = None++ def test_do_control_handles_set_run_state_exception(self):+ """Test do_control handles HTTP API exceptions with real error recovery"""+ integration_key = IntegrationKey(+ integration_id=ZmMetaData.integration_id,+ integration_name='run.state'+ )+ integration_details = IntegrationDetails(key=integration_key)++ # Configure API to raise exception+ self.mock_zm_api.set_state.side_effect = Exception("ZM API connection failed")++ result = self.controller.do_control(integration_details, 'start')++ # Verify error handling+ self.assertIsNone(result.new_value)+ self.assertIn('ZM API connection failed', result.error_list[0])++ # Verify real manager was created and cache cleared despite error+ manager = self.controller.zm_manager()+ self.assertIsInstance(manager, ZoneMinderManager)+ self.assertEqual(manager._zm_state_list, [])+ self.assertEqual(manager._zm_monitor_list, [])++ # Verify API was actually called before failing+ self.mock_zm_api.set_state.assert_called_once_with('start')++ def test_do_control_handles_set_monitor_function_exception(self):+ """Test do_control handles monitor fetch exceptions from real manager"""+ integration_key = IntegrationKey(+ integration_id=ZmMetaData.integration_id,+ integration_name='monitor.function.123'+ )+ integration_details = IntegrationDetails(key=integration_key)++ # Configure monitors API to raise exception+ self.mock_zm_api.monitors.side_effect = Exception("Failed to fetch monitors")++ result = self.controller.do_control(integration_details, 'Modect')++ # Verify error handling+ self.assertIsNone(result.new_value)+ self.assertIn('Failed to fetch monitors', result.error_list[0])++ # Verify real manager was created and attempted to fetch monitors+ manager = self.controller.zm_manager()+ self.assertIsInstance(manager, ZoneMinderManager)++ # Verify cache was cleared despite error+ self.assertEqual(manager._zm_monitor_list, [])++ # Verify API was called before failing+ self.mock_zm_api.monitors.assert_called_once_with({'force_reload': True})++ def test_do_control_always_clears_caches_on_success(self):+ """Test do_control clears real manager caches on successful operations"""+ integration_key = IntegrationKey(+ integration_id=ZmMetaData.integration_id,+ integration_name='run.state'+ )+ integration_details = IntegrationDetails(key=integration_key)++ self.mock_zm_api.set_state.return_value = {'status': 'success'}++ # Pre-populate cache to test clearing+ manager = self.controller.zm_manager()+ manager._zm_state_list = ['cached_state']+ manager._zm_monitor_list = ['cached_monitor']++ result = self.controller.do_control(integration_details, 'start')++ self.assertEqual(result.new_value, 'start')++ # Verify cache was actually cleared+ self.assertEqual(manager._zm_state_list, [])+ self.assertEqual(manager._zm_monitor_list, [])++ # Verify same manager instance was used throughout+ manager2 = self.controller.zm_manager()+ self.assertIs(manager, manager2)++ def test_do_control_always_clears_caches_on_exception(self):+ """Test do_control clears real manager caches even when exceptions occur"""+ integration_key = IntegrationKey(+ integration_id=ZmMetaData.integration_id,+ integration_name='run.state'+ )+ integration_details = IntegrationDetails(key=integration_key)++ self.mock_zm_api.set_state.side_effect = Exception("Test exception")++ # Pre-populate cache to test clearing on error+ manager = self.controller.zm_manager()+ manager._zm_state_list = ['cached_state']+ manager._zm_monitor_list = ['cached_monitor']++ result = self.controller.do_control(integration_details, 'start')++ self.assertIsNone(result.new_value)++ # Verify cache was cleared despite exception+ self.assertEqual(manager._zm_state_list, [])+ self.assertEqual(manager._zm_monitor_list, [])++ # Verify manager consistency even after error+ manager2 = self.controller.zm_manager()+ self.assertIs(manager, manager2)+++class TestZoneMinderControllerMixin(TestCase):+ """Test ZoneMinderMixin functionality"""++ def setUp(self):+ self.controller = ZoneMinderController()++ @patch('hi.services.zoneminder.zm_mixins.ZoneMinderManager')+ def test_zm_manager_creates_and_initializes_manager(self, mock_manager_class):+ """Test zm_manager method creates and initializes manager instance"""+ mock_manager_instance = Mock()+ mock_manager_class.return_value = mock_manager_instance++ # Clear any existing manager+ if hasattr(self.controller, '_zm_manager'):+ delattr(self.controller, '_zm_manager')++ result = self.controller.zm_manager()++ mock_manager_class.assert_called_once()+ mock_manager_instance.ensure_initialized.assert_called_once()+ self.assertEqual(result, mock_manager_instance)++ @patch('hi.services.zoneminder.zm_mixins.ZoneMinderManager')+ def test_zm_manager_reuses_existing_instance(self, mock_manager_class):+ """Test zm_manager method reuses existing manager instance"""+ mock_manager_instance = Mock()+ mock_manager_class.return_value = mock_manager_instance++ # First call+ result1 = self.controller.zm_manager()++ # Second call+ result2 = self.controller.zm_manager()++ # Should only create once+ mock_manager_class.assert_called_once()+ mock_manager_instance.ensure_initialized.assert_called_once()+ self.assertIs(result1, result2)++ def test_zm_manager_real_singleton_behavior(self):+ """Test real ZoneMinderManager singleton behavior"""+ # Mock ZMApi for initialization+ with patch('hi.services.zoneminder.zm_manager.ZMApi') as mock_api_class:+ mock_api = Mock()+ mock_api_class.return_value = mock_api++ # Mock integration loading with required attributes+ with patch('hi.services.zoneminder.zm_manager.Integration.objects.get') as mock_int:+ from hi.services.zoneminder.enums import ZmAttributeType++ mock_attributes = {}+ for attr_type in ZmAttributeType:+ if attr_type.is_required:+ integration_key = IntegrationKey(+ integration_id=ZmMetaData.integration_id,+ integration_name=str(attr_type)+ )+ mock_attr = Mock()+ mock_attr.integration_key = integration_key+ mock_attr.is_required = attr_type.is_required+ mock_attr.value = f'test_{attr_type.name.lower()}'+ mock_attributes[integration_key] = mock_attr++ mock_integration = Mock()+ mock_integration.is_enabled = True+ mock_integration.integration_id = ZmMetaData.integration_id+ mock_integration.attributes_by_integration_key = mock_attributes+ mock_int.return_value = mock_integration++ # Ensure clean singleton state+ ZoneMinderManager._instance = None++ try:+ # Test across multiple controllers+ controller1 = ZoneMinderController()+ controller2 = ZoneMinderController()++ manager1 = controller1.zm_manager()+ manager2 = controller2.zm_manager()++ # Should be same singleton instance+ self.assertIs(manager1, manager2)+ self.assertIsInstance(manager1, ZoneMinderManager)++ # Test state persistence across controller instances+ manager1._test_value = 'shared_state'+ self.assertEqual(manager2._test_value, 'shared_state')++ finally:+ # Clean up+ ZoneMinderManager._instance = None+ if hasattr(controller1, '_zm_manager'):+ delattr(controller1, '_zm_manager')+ if hasattr(controller2, '_zm_manager'):+ delattr(controller2, '_zm_manager')diff --git a/src/hi/services/zoneminder/tests/test_zm_manager.py b/src/hi/services/zoneminder/tests/test_zm_manager.pynew file mode 100644index 00000000..2e7cde58--- /dev/null+++ b/src/hi/services/zoneminder/tests/test_zm_manager.py@@ -0,0 +1,618 @@+import threading+from datetime import timedelta+from unittest.mock import Mock, patch+from django.test import TestCase+import pytz++import hi.apps.common.datetimeproxy as datetimeproxy+from hi.integrations.exceptions import IntegrationAttributeError, IntegrationError+from hi.integrations.transient_models import IntegrationKey+from hi.integrations.models import Integration, IntegrationAttribute++from hi.services.zoneminder.enums import ZmAttributeType+from hi.services.zoneminder.zm_manager import ZoneMinderManager+from hi.services.zoneminder.zm_metadata import ZmMetaData+++class TestZoneMinderManagerSingleton(TestCase):+ """Test singleton behavior and thread safety"""++ def setUp(self):+ # Reset singleton instance for each test+ ZoneMinderManager._instance = None+ ZoneMinderManager._lock = threading.Lock()++ def test_singleton_behavior(self):+ """Test that ZoneMinderManager follows singleton pattern"""+ manager1 = ZoneMinderManager()+ manager2 = ZoneMinderManager()+ self.assertIs(manager1, manager2)++ def test_singleton_thread_safety(self):+ """Test singleton creation is thread-safe"""+ results = []++ def create_manager():+ results.append(ZoneMinderManager())++ threads = [threading.Thread(target=create_manager) for _ in range(5)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()++ # All instances should be the same object+ first_instance = results[0]+ for instance in results[1:]:+ self.assertIs(instance, first_instance)+++class TestZoneMinderManagerInitialization(TestCase):+ """Test initialization and attribute loading"""++ def setUp(self):+ ZoneMinderManager._instance = None+ ZoneMinderManager._lock = threading.Lock()+ self.manager = ZoneMinderManager()++ def test_init_singleton_sets_defaults(self):+ """Test singleton initialization sets correct defaults"""+ self.assertEqual(self.manager._zm_attr_type_to_attribute, {})+ self.assertIsNone(self.manager._zm_client)+ self.assertEqual(self.manager._zm_state_list, [])+ self.assertEqual(self.manager._zm_monitor_list, [])+ self.assertEqual(self.manager._change_listeners, [])+ self.assertFalse(self.manager._was_initialized)+ self.assertIsNotNone(self.manager._data_lock)++ @patch('hi.services.zoneminder.zm_manager.ZoneMinderManager.reload')+ def test_ensure_initialized_calls_reload_once(self, mock_reload):+ """Test ensure_initialized only calls reload once"""+ self.manager.ensure_initialized()+ mock_reload.assert_called_once()++ # Second call should not trigger reload+ self.manager.ensure_initialized()+ mock_reload.assert_called_once() # Still only one call++ self.assertTrue(self.manager._was_initialized)++ @patch.object(Integration.objects, 'get')+ def test_load_attributes_integration_not_found(self, mock_get):+ """Test _load_attributes raises IntegrationError when integration not found"""+ mock_get.side_effect = Integration.DoesNotExist()++ with self.assertRaises(IntegrationError) as context:+ self.manager._load_attributes()++ self.assertEqual(str(context.exception), 'ZoneMinder integration is not implemented.')++ @patch.object(Integration.objects, 'get')+ def test_load_attributes_integration_disabled(self, mock_get):+ """Test _load_attributes raises IntegrationError when integration disabled"""+ mock_integration = Mock()+ mock_integration.is_enabled = False+ mock_get.return_value = mock_integration++ with self.assertRaises(IntegrationError) as context:+ self.manager._load_attributes()++ self.assertEqual(str(context.exception), 'ZoneMinder integration is not enabled.')++ @patch.object(Integration.objects, 'get')+ def test_load_attributes_missing_required_attribute(self, mock_get):+ """Test _load_attributes raises IntegrationAttributeError for missing required attributes"""+ mock_integration = Mock()+ mock_integration.is_enabled = True+ mock_integration.integration_id = ZmMetaData.integration_id+ mock_integration.attributes_by_integration_key = {}+ mock_get.return_value = mock_integration++ with self.assertRaises(IntegrationAttributeError) as context:+ self.manager._load_attributes()++ # Should fail on first required attribute (API_URL)+ self.assertIn('Missing ZM attribute', str(context.exception))+ self.assertIn('api_url', str(context.exception))++ @patch.object(Integration.objects, 'get')+ def test_load_attributes_empty_required_value(self, mock_get):+ """Test _load_attributes raises IntegrationAttributeError for empty required values"""+ mock_integration = Mock()+ mock_integration.is_enabled = True+ mock_integration.integration_id = ZmMetaData.integration_id++ # Create mock attribute with empty value+ mock_attr = Mock()+ mock_attr.is_required = True+ mock_attr.value = ' ' # Empty/whitespace only++ integration_key = IntegrationKey(+ integration_id=ZmMetaData.integration_id,+ integration_name=str(ZmAttributeType.API_URL)+ )+ mock_integration.attributes_by_integration_key = {integration_key: mock_attr}+ mock_get.return_value = mock_integration++ with self.assertRaises(IntegrationAttributeError) as context:+ self.manager._load_attributes()++ self.assertIn('Missing ZM attribute value for', str(context.exception))++ @patch.object(Integration.objects, 'get')+ def test_load_attributes_success_with_all_required(self, mock_get):+ """Test _load_attributes successfully loads all required attributes"""+ mock_integration = Mock()+ mock_integration.is_enabled = True+ mock_integration.integration_id = ZmMetaData.integration_id++ # Create mock attributes for all required types+ attributes = {}+ for attr_type in ZmAttributeType:+ if attr_type.is_required:+ mock_attr = Mock()+ mock_attr.is_required = True+ mock_attr.value = f'test_value_{attr_type.name}'+ integration_key = IntegrationKey(+ integration_id=ZmMetaData.integration_id,+ integration_name=str(attr_type)+ )+ attributes[integration_key] = mock_attr++ mock_integration.attributes_by_integration_key = attributes+ mock_get.return_value = mock_integration++ result = self.manager._load_attributes()++ # Should return dictionary with all required attribute types+ required_types = [attr_type for attr_type in ZmAttributeType if attr_type.is_required]+ self.assertEqual(len(result), len(required_types))+ for attr_type in required_types:+ self.assertIn(attr_type, result)+++class TestZoneMinderManagerClientCreation(TestCase):+ """Test ZM client creation and API option validation"""++ def setUp(self):+ ZoneMinderManager._instance = None+ ZoneMinderManager._lock = threading.Lock()+ self.manager = ZoneMinderManager()++ def create_mock_attributes(self):+ """Helper to create mock attributes for client creation"""+ attributes = {}+ attr_values = {+ ZmAttributeType.API_URL: 'https://test.com/zm/api',+ ZmAttributeType.PORTAL_URL: 'https://test.com/zm',+ ZmAttributeType.API_USER: 'testuser',+ ZmAttributeType.API_PASSWORD: 'testpass'+ }++ for attr_type, value in attr_values.items():+ mock_attr = Mock()+ mock_attr.value = value+ mock_attr.integration_key = IntegrationKey(+ integration_id=ZmMetaData.integration_id,+ integration_name=str(attr_type)+ )+ attributes[attr_type] = mock_attr++ return attributes++ def test_create_zm_client_missing_api_attribute(self):+ """Test create_zm_client raises error for missing API attributes"""+ incomplete_attributes = {+ ZmAttributeType.API_URL: Mock(value='https://test.com/api')+ # Missing other required API attributes+ }++ with self.assertRaises(IntegrationAttributeError) as context:+ self.manager.create_zm_client(incomplete_attributes)++ self.assertIn('Missing ZM API attribute', str(context.exception))++ def test_create_zm_client_empty_api_attribute_value(self):+ """Test create_zm_client raises error for empty API attribute values"""+ attributes = self.create_mock_attributes()+ attributes[ZmAttributeType.API_URL].value = ' ' # Empty value++ with self.assertRaises(IntegrationAttributeError) as context:+ self.manager.create_zm_client(attributes)++ self.assertIn('Missing ZM API attribute value for', str(context.exception))++ @patch('hi.services.zoneminder.zm_manager.ZMApi')+ def test_create_zm_client_success(self, mock_zmapi):+ """Test create_zm_client successfully creates ZMApi with correct options and returns functional client"""+ attributes = self.create_mock_attributes()++ # Create a mock client with realistic behavior+ mock_client = Mock()+ mock_client.portal_url = 'https://test.com/zm'+ mock_client.api_url = 'https://test.com/zm/api'+ mock_zmapi.return_value = mock_client++ result = self.manager.create_zm_client(attributes)++ # Verify behavior: returns a client that has expected properties+ self.assertIsNotNone(result)+ self.assertEqual(result.portal_url, 'https://test.com/zm')+ self.assertEqual(result.api_url, 'https://test.com/zm/api')++ # Verify client can be used for typical operations+ self.assertTrue(hasattr(result, 'states'))+ self.assertTrue(hasattr(result, 'monitors'))++ # Verify ZMApi was called with correct configuration options+ expected_options = {+ 'apiurl': 'https://test.com/zm/api',+ 'portalurl': 'https://test.com/zm',+ 'user': 'testuser',+ 'password': 'testpass'+ }+ mock_zmapi.assert_called_once_with(options=expected_options)+++class TestZoneMinderManagerCaching(TestCase):+ """Test TTL caching logic for states and monitors"""++ def setUp(self):+ ZoneMinderManager._instance = None+ ZoneMinderManager._lock = threading.Lock()+ self.manager = ZoneMinderManager()++ # Mock the zm_client+ self.mock_client = Mock()+ self.manager._zm_client = self.mock_client++ @patch('hi.apps.common.datetimeproxy.now')+ def test_get_zm_states_cache_miss_empty_list(self, mock_now):+ """Test get_zm_states fetches from API when list is empty and updates cache"""+ test_time = datetimeproxy.datetime.datetime(2023, 1, 1, 12, 0, 0, tzinfo=pytz.UTC)+ mock_now.return_value = test_time++ # Create mock states with some identifiable data+ mock_state1 = Mock()+ mock_state1.get.return_value = {'State': {'Name': 'state1'}}+ mock_state2 = Mock()+ mock_state2.get.return_value = {'State': {'Name': 'state2'}}+ mock_states = [mock_state1, mock_state2]+ self.mock_client.states.return_value.list.return_value = mock_states++ # Verify initial cache state is empty+ self.assertEqual(self.manager._zm_state_list, [])+ self.assertEqual(self.manager._zm_state_timestamp, datetimeproxy.min())++ result = self.manager.get_zm_states()++ # Verify behavior: returns the correct states+ self.assertEqual(result, mock_states)+ self.assertEqual(len(result), 2)++ # Verify state changes: cache is populated and timestamp updated+ self.assertEqual(self.manager._zm_state_list, mock_states)+ self.assertEqual(self.manager._zm_state_timestamp, test_time)++ # Verify API was called (secondary to behavior verification)+ self.mock_client.states.assert_called_once()+ self.mock_client.states.return_value.list.assert_called_once()++ @patch('hi.apps.common.datetimeproxy.now')+ def test_get_zm_states_cache_hit_within_ttl(self, mock_now):+ """Test get_zm_states returns cached data within TTL without API call"""+ start_time = datetimeproxy.datetime.datetime(2023, 1, 1, 12, 0, 0, tzinfo=pytz.UTC)+ mock_now.return_value = start_time++ # Set up cached data with identifiable content+ cached_state1 = Mock()+ cached_state1.get.return_value = {'State': {'Name': 'cached_state1'}}+ cached_state2 = Mock()+ cached_state2.get.return_value = {'State': {'Name': 'cached_state2'}}+ cached_states = [cached_state1, cached_state2]+ self.manager._zm_state_list = cached_states+ self.manager._zm_state_timestamp = start_time++ # Advance time by less than TTL (300 seconds)+ mock_now.return_value = start_time + timedelta(seconds=200)++ result = self.manager.get_zm_states()++ # Verify behavior: returns exact cached data+ self.assertIs(result, cached_states)+ self.assertEqual(len(result), 2)++ # Verify state unchanged: cache timestamp and content remain the same+ self.assertEqual(self.manager._zm_state_timestamp, start_time)+ self.assertIs(self.manager._zm_state_list, cached_states)++ # Verify no API call was made (important for caching behavior)+ self.mock_client.states.assert_not_called()++ @patch('hi.apps.common.datetimeproxy.now')+ def test_get_zm_states_cache_miss_expired_ttl(self, mock_now):+ """Test get_zm_states fetches from API when TTL expired"""+ start_time = datetimeproxy.datetime.datetime(2023, 1, 1, 12, 0, 0, tzinfo=pytz.UTC)++ # Set up cached data+ cached_states = [Mock(), Mock()]+ self.manager._zm_state_list = cached_states+ self.manager._zm_state_timestamp = start_time++ # Advance time beyond TTL (300 seconds)+ mock_now.return_value = start_time + timedelta(seconds=400)++ new_states = [Mock(), Mock(), Mock()]+ self.mock_client.states.return_value.list.return_value = new_states++ result = self.manager.get_zm_states()++ self.mock_client.states.assert_called_once()+ self.assertEqual(result, new_states)+ self.assertEqual(self.manager._zm_state_list, new_states)++ def test_get_zm_states_force_load_bypasses_cache(self):+ """Test get_zm_states with force_load=True bypasses cache"""+ # Set up cached data+ cached_states = [Mock(), Mock()]+ self.manager._zm_state_list = cached_states+ self.manager._zm_state_timestamp = datetimeproxy.now()++ new_states = [Mock(), Mock(), Mock()]+ self.mock_client.states.return_value.list.return_value = new_states++ result = self.manager.get_zm_states(force_load=True)++ self.mock_client.states.assert_called_once()+ self.assertEqual(result, new_states)++ @patch('hi.apps.common.datetimeproxy.now')+ def test_get_zm_monitors_cache_behavior(self, mock_now):+ """Test get_zm_monitors follows same caching pattern as states"""+ test_time = datetimeproxy.datetime.datetime(2023, 1, 1, 12, 0, 0, tzinfo=pytz.UTC)+ mock_now.return_value = test_time++ mock_monitors = [Mock(), Mock()]+ self.mock_client.monitors.return_value.list.return_value = mock_monitors++ result = self.manager.get_zm_monitors()++ # Verify force_reload option is passed to pyzm+ expected_options = {'force_reload': True}+ self.mock_client.monitors.assert_called_once_with(expected_options)+ self.assertEqual(result, mock_monitors)++ def test_clear_caches_resets_cached_data(self):+ """Test clear_caches resets both state and monitor caches"""+ # Set up cached data+ self.manager._zm_state_list = [Mock(), Mock()]+ self.manager._zm_monitor_list = [Mock(), Mock(), Mock()]++ self.manager.clear_caches()++ self.assertEqual(self.manager._zm_state_list, [])+ self.assertEqual(self.manager._zm_monitor_list, [])+++class TestZoneMinderManagerTimezoneValidation(TestCase):+ """Test complex timezone validation business logic"""++ def setUp(self):+ ZoneMinderManager._instance = None+ ZoneMinderManager._lock = threading.Lock()+ self.manager = ZoneMinderManager()++ @patch.object(Integration.objects, 'get')+ @patch.object(IntegrationAttribute.objects, 'filter')+ @patch('hi.apps.common.datetimeproxy.is_valid_timezone_name')+ def test_get_zm_tzname_valid_timezone(self, mock_is_valid, mock_filter, mock_get):+ """Test get_zm_tzname returns valid timezone"""+ mock_integration = Mock()+ mock_get.return_value = mock_integration++ mock_attr = Mock()+ mock_attr.value = 'America/Chicago'+ mock_filter.return_value.first.return_value = mock_attr++ mock_is_valid.return_value = True++ result = self.manager.get_zm_tzname()++ self.assertEqual(result, 'America/Chicago')+ mock_is_valid.assert_called_once_with(tz_name='America/Chicago')++ @patch.object(Integration.objects, 'get')+ @patch.object(IntegrationAttribute.objects, 'filter')+ @patch('hi.apps.common.datetimeproxy.is_valid_timezone_name')+ def test_get_zm_tzname_invalid_timezone_fallback(self, mock_is_valid, mock_filter, mock_get):+ """Test get_zm_tzname falls back to UTC for invalid timezone"""+ mock_integration = Mock()+ mock_get.return_value = mock_integration++ mock_attr = Mock()+ mock_attr.value = 'Invalid/Timezone'+ mock_filter.return_value.first.return_value = mock_attr++ mock_is_valid.return_value = False++ result = self.manager.get_zm_tzname()++ self.assertEqual(result, 'UTC')++ @patch.object(Integration.objects, 'get')+ @patch.object(IntegrationAttribute.objects, 'filter')+ def test_get_zm_tzname_no_attribute_fallback(self, mock_filter, mock_get):+ """Test get_zm_tzname falls back to UTC when no attribute found"""+ mock_integration = Mock()+ mock_get.return_value = mock_integration++ mock_filter.return_value.first.return_value = None++ result = self.manager.get_zm_tzname()++ self.assertEqual(result, 'UTC')++ @patch.object(Integration.objects, 'get')+ def test_get_zm_tzname_integration_not_found_fallback(self, mock_get):+ """Test get_zm_tzname falls back to UTC when integration not found"""+ mock_get.side_effect = Integration.DoesNotExist++ result = self.manager.get_zm_tzname()++ self.assertEqual(result, 'UTC')++ @patch.object(Integration.objects, 'get')+ @patch.object(IntegrationAttribute.objects, 'filter')+ def test_get_zm_tzname_integration_attribute_not_found_fallback(self, mock_filter, mock_get):+ """Test get_zm_tzname falls back to UTC when integration attribute not found"""+ mock_integration = Mock()+ mock_get.return_value = mock_integration++ # Simulate IntegrationAttribute.DoesNotExist by making filter().first() raise it+ mock_filter.return_value.first.side_effect = IntegrationAttribute.DoesNotExist++ result = self.manager.get_zm_tzname()++ self.assertEqual(result, 'UTC')+++class TestZoneMinderManagerChangeListeners(TestCase):+ """Test change listener callback system and thread safety"""++ def setUp(self):+ ZoneMinderManager._instance = None+ ZoneMinderManager._lock = threading.Lock()+ self.manager = ZoneMinderManager()++ def test_register_change_listener(self):+ """Test registering change listeners"""+ callback1 = Mock()+ callback2 = Mock()++ self.manager.register_change_listener(callback1)+ self.manager.register_change_listener(callback2)++ self.assertEqual(len(self.manager._change_listeners), 2)+ self.assertIn(callback1, self.manager._change_listeners)+ self.assertIn(callback2, self.manager._change_listeners)++ @patch.object(ZoneMinderManager, 'reload')+ def test_notify_settings_changed_calls_reload_and_listeners(self, mock_reload):+ """Test notify_settings_changed triggers reload and notifies all registered listeners"""+ # Create trackable callback functions+ callback1_called = []+ callback2_called = []++ def callback1():+ callback1_called.append(True)++ def callback2():+ callback2_called.append(True)++ # Verify initial state: no listeners registered+ self.assertEqual(len(self.manager._change_listeners), 0)++ # Register listeners and verify they are stored+ self.manager.register_change_listener(callback1)+ self.manager.register_change_listener(callback2)+ self.assertEqual(len(self.manager._change_listeners), 2)++ # Verify initial callback state+ self.assertEqual(len(callback1_called), 0)+ self.assertEqual(len(callback2_called), 0)++ self.manager.notify_settings_changed()++ # Verify behavior: reload was triggered+ mock_reload.assert_called_once()++ # Verify behavior: all callbacks were executed+ self.assertEqual(len(callback1_called), 1)+ self.assertEqual(len(callback2_called), 1)++ # Verify state: listeners remain registered for future notifications+ self.assertEqual(len(self.manager._change_listeners), 2)++ @patch.object(ZoneMinderManager, 'reload')+ def test_notify_settings_changed_handles_callback_exceptions(self, mock_reload):+ """Test notify_settings_changed continues if callback raises exception"""+ callback1 = Mock()+ callback2 = Mock(side_effect=Exception("Test exception"))+ callback3 = Mock()++ self.manager.register_change_listener(callback1)+ self.manager.register_change_listener(callback2)+ self.manager.register_change_listener(callback3)++ # Should not raise exception despite callback2 failing+ self.manager.notify_settings_changed()++ # All callbacks should be attempted+ callback1.assert_called_once()+ callback2.assert_called_once()+ callback3.assert_called_once()+++class TestZoneMinderManagerUrlGeneration(TestCase):+ """Test URL generation for video streams"""++ def setUp(self):+ ZoneMinderManager._instance = None+ ZoneMinderManager._lock = threading.Lock()+ self.manager = ZoneMinderManager()++ # Mock client with portal URL+ self.mock_client = Mock()+ self.mock_client.portal_url = 'https://test.com/zm'+ self.manager._zm_client = self.mock_client++ def test_get_video_stream_url(self):+ """Test video stream URL generation"""+ monitor_id = 123+ expected_url = 'https://test.com/zm/cgi-bin/nph-zms?mode=jpeg&scale=100&rate=5&maxfps=5&monitor=123'++ result = self.manager.get_video_stream_url(monitor_id)++ self.assertEqual(result, expected_url)++ def test_get_event_video_stream_url(self):+ """Test event video stream URL generation"""+ event_id = 456+ expected_url = 'https://test.com/zm/cgi-bin/nph-zms?mode=jpeg&scale=100&rate=5&maxfps=5&replay=single&source=event&event=456'++ result = self.manager.get_event_video_stream_url(event_id)++ self.assertEqual(result, expected_url)+++class TestZoneMinderManagerBooleanConversion(TestCase):+ """Test enum property conversion with custom logic"""++ def setUp(self):+ ZoneMinderManager._instance = None+ ZoneMinderManager._lock = threading.Lock()+ self.manager = ZoneMinderManager()++ @patch('hi.services.zoneminder.zm_manager.str_to_bool')+ def test_should_add_alarm_events_true(self, mock_str_to_bool):+ """Test should_add_alarm_events returns True when attribute is true"""+ mock_attribute = Mock()+ mock_attribute.value = 'true'+ self.manager._zm_attr_type_to_attribute = {+ ZmAttributeType.ADD_ALARM_EVENTS: mock_attribute+ }++ mock_str_to_bool.return_value = True++ result = self.manager.should_add_alarm_events++ self.assertTrue(result)+ mock_str_to_bool.assert_called_once_with('true')++ def test_should_add_alarm_events_false_when_no_attribute(self):+ """Test should_add_alarm_events returns False when no attribute"""+ self.manager._zm_attr_type_to_attribute = {}++ result = self.manager.should_add_alarm_events++ self.assertFalse(result)diff --git a/src/hi/services/zoneminder/tests/test_zm_sync.py b/src/hi/services/zoneminder/tests/test_zm_sync.pynew file mode 100644index 00000000..3cb0c2af--- /dev/null+++ b/src/hi/services/zoneminder/tests/test_zm_sync.py@@ -0,0 +1,1032 @@+import json+import os+from unittest.mock import Mock, patch, call+from django.test import TestCase++from hi.apps.common.processing_result import ProcessingResult+from hi.apps.entity.models import Entity+from hi.apps.sense.models import Sensor++from hi.integrations.transient_models import IntegrationKey++from hi.services.zoneminder.zm_sync import ZoneMinderSynchronizer+from hi.services.zoneminder.zm_metadata import ZmMetaData+++class TestZoneMinderSynchronizerLockBehavior(TestCase):+ """Test database lock coordination with exception handling"""++ def setUp(self):+ self.synchronizer = ZoneMinderSynchronizer()++ @patch('hi.services.zoneminder.zm_sync.ExclusionLockContext')+ def test_sync_uses_exclusion_lock(self, mock_lock_context):+ """Test sync method uses exclusion lock and returns sync results"""+ # Mock a successful lock context+ mock_lock_context.return_value.__enter__ = Mock()+ mock_lock_context.return_value.__exit__ = Mock(return_value=False)++ # Mock zm_manager to simulate disabled client+ mock_manager = Mock()+ mock_manager.zm_client = None+ self.synchronizer._zm_manager = mock_manager++ result = self.synchronizer.sync()++ # Test lock usage+ mock_lock_context.assert_called_once_with(name='zm_integration_sync')++ # Test actual behavior: should return result with error when client disabled+ self.assertEqual(result.title, 'ZM Sync Result')+ self.assertGreater(len(result.error_list), 0)+ self.assertIn('Sync problem. ZM integration disabled?', result.error_list[0])++ @patch('hi.services.zoneminder.zm_sync.ExclusionLockContext')+ def test_sync_handles_lock_runtime_error(self, mock_lock_context):+ """Test sync method handles RuntimeError from lock context and returns proper error result"""+ lock_error_msg = "Lock acquisition failed"+ mock_lock_context.side_effect = RuntimeError(lock_error_msg)++ result = self.synchronizer.sync()++ # Test error handling behavior+ self.assertEqual(result.title, 'ZM Sync Result')+ self.assertEqual(len(result.error_list), 1)+ self.assertIn(lock_error_msg, result.error_list[0])++ # Test that no sync operations were attempted+ self.assertEqual(len(result.message_list), 0)++ # Test that result is properly formed for error condition+ self.assertIsNotNone(result.title)+ self.assertIsInstance(result.error_list, list)+++class TestZoneMinderSynchronizerSyncHelper(TestCase):+ """Test main sync helper logic and flow control"""++ def setUp(self):+ self.synchronizer = ZoneMinderSynchronizer()++ # Mock the zm_manager+ self.mock_manager = Mock()+ self.synchronizer._zm_manager = self.mock_manager++ def test_sync_helper_client_not_available(self):+ """Test sync helper handles missing ZM client gracefully"""+ self.mock_manager.zm_client = None++ result = self.synchronizer._sync_helper()++ self.assertEqual(result.title, 'ZM Sync Result')+ self.assertIn('Sync problem. ZM integration disabled?', result.error_list[0])++ def test_sync_helper_calls_both_sync_methods(self):+ """Test sync helper coordinates state and monitor sync and aggregates their results"""+ self.mock_manager.zm_client = Mock() # Client available++ # Mock the sync methods to simulate successful operations+ def mock_sync_states(result):+ result.message_list.append('States synced successfully')+ return result++ def mock_sync_monitors(result):+ result.message_list.append('Monitors synced successfully')+ return result++ # Patch the methods to track their execution and simulate behavior+ with patch.object(self.synchronizer, '_sync_states', side_effect=mock_sync_states) as mock_sync_states, \+ patch.object(self.synchronizer, '_sync_monitors', side_effect=mock_sync_monitors) as mock_sync_monitors:++ result = self.synchronizer._sync_helper()++ # Test coordination: both methods called with same result+ mock_sync_states.assert_called_once()+ mock_sync_monitors.assert_called_once()++ # Test result aggregation: messages from both operations+ self.assertEqual(result.title, 'ZM Sync Result')+ self.assertIn('States synced successfully', result.message_list)+ self.assertIn('Monitors synced successfully', result.message_list)++ # Test that sync_states was called before sync_monitors+ self.assertEqual(mock_sync_states.call_args[1]['result'], result)+ self.assertEqual(mock_sync_monitors.call_args[1]['result'], result)+++class TestZoneMinderSynchronizerStateSync(TestCase):+ """Test state synchronization and value range updates"""++ def setUp(self):+ self.synchronizer = ZoneMinderSynchronizer()++ # Mock the zm_manager+ self.mock_manager = Mock()+ self.mock_manager._zm_integration_key.return_value = IntegrationKey(+ integration_id=ZmMetaData.integration_id,+ integration_name='system'+ )+ self.mock_manager._zm_run_state_integration_key.return_value = IntegrationKey(+ integration_id=ZmMetaData.integration_id,+ integration_name='run.state'+ )+ self.synchronizer._zm_manager = self.mock_manager++ @patch.object(Entity.objects, 'filter_by_integration_key')+ @patch.object(Sensor.objects, 'filter_by_integration_key')+ @patch.object(ZoneMinderSynchronizer, '_create_zm_entity')+ def test_sync_states_creates_zm_entity_when_missing(self, mock_create_entity, mock_sensor_filter, mock_entity_filter):+ """Test _sync_states creates ZM entity when it doesn't exist and verifies entity creation parameters"""+ # Mock ZM states+ mock_state1 = Mock()+ mock_state1.name.return_value = 'start'+ mock_state2 = Mock()+ mock_state2.name.return_value = 'stop'+ self.mock_manager.get_zm_states.return_value = [mock_state1, mock_state2]++ # No existing entity+ mock_entity_filter.return_value.first.return_value = None++ # Mock created entity to test return behavior+ mock_created_entity = Mock()+ mock_created_entity.name = 'ZoneMinder'+ mock_created_entity.id = 123++ # Simulate the actual behavior of _create_zm_entity+ def mock_create_behavior(run_state_name_label_dict, result):+ result.message_list.append(f'Created ZM entity: {mock_created_entity}')+ return mock_created_entity++ mock_create_entity.side_effect = mock_create_behavior++ # Mock sensor exists+ mock_sensor = Mock()+ mock_entity_state = Mock()+ mock_entity_state.value_range_dict = {'start': 'start', 'stop': 'stop'}+ mock_sensor.entity_state = mock_entity_state+ mock_sensor_filter.return_value.select_related.return_value.first.return_value = mock_sensor++ result = ProcessingResult(title='Test')+ self.synchronizer._sync_states(result)++ # Verify entity creation was called with correct parameters+ expected_dict = {'start': 'start', 'stop': 'stop'}+ mock_create_entity.assert_called_once()+ call_args = mock_create_entity.call_args+ self.assertEqual(call_args[1]['run_state_name_label_dict'], expected_dict)++ # Verify result contains creation information+ self.assertGreater(len(result.message_list), 0)+ # Test behavior: should not have errors when successful+ self.assertEqual(len(result.error_list), 0)++ @patch.object(Entity.objects, 'filter_by_integration_key')+ @patch.object(Sensor.objects, 'filter_by_integration_key')+ def test_sync_states_missing_sensor_error(self, mock_sensor_filter, mock_entity_filter):+ """Test _sync_states handles missing run state sensor and stops processing gracefully"""+ # Mock states+ mock_state = Mock()+ mock_state.name.return_value = 'start'+ self.mock_manager.get_zm_states.return_value = [mock_state]++ # Entity exists+ mock_entity = Mock()+ mock_entity.name = 'ZoneMinder'+ mock_entity_filter.return_value.first.return_value = mock_entity++ # No sensor found+ mock_sensor_filter.return_value.select_related.return_value.first.return_value = None++ result = ProcessingResult(title='Test')+ returned_result = self.synchronizer._sync_states(result)++ # Test behavior: function should handle error gracefully+ self.assertEqual(len(result.error_list), 1)+ self.assertIn('Missing ZoneMinder sensor for ZM state.', result.error_list[0])+ # Should return early without processing further+ self.assertIsNone(returned_result)+ # Should not have created any entities since sensor missing+ self.assertEqual(len(result.message_list), 0)++ @patch.object(Entity.objects, 'filter_by_integration_key')+ @patch.object(Sensor.objects, 'filter_by_integration_key')+ def test_sync_states_updates_value_range_when_changed(self, mock_sensor_filter, mock_entity_filter):+ """Test _sync_states updates value range when states change and persists changes"""+ # Mock new states+ mock_state1 = Mock()+ mock_state1.name.return_value = 'start'+ mock_state2 = Mock()+ mock_state2.name.return_value = 'pause' # New state+ self.mock_manager.get_zm_states.return_value = [mock_state1, mock_state2]++ # Entity exists+ mock_entity = Mock()+ mock_entity.name = 'ZoneMinder'+ mock_entity_filter.return_value.first.return_value = mock_entity++ # Mock sensor with existing state+ mock_sensor = Mock()+ mock_entity_state = Mock()+ mock_entity_state.value_range_dict = {'start': 'start', 'stop': 'stop'} # Old states+ mock_entity_state.save = Mock()+ mock_sensor.entity_state = mock_entity_state+ mock_sensor.name = 'ZM Run State'+ mock_sensor_filter.return_value.select_related.return_value.first.return_value = mock_sensor++ result = ProcessingResult(title='Test')+ self.synchronizer._sync_states(result)++ # Test actual state transformation+ expected_new_dict = {'start': 'start', 'pause': 'pause'}+ self.assertEqual(mock_entity_state.value_range_dict, expected_new_dict)++ # Test persistence behavior+ mock_entity_state.save.assert_called_once()++ # Test that old values are completely replaced, not merged+ self.assertNotIn('stop', mock_entity_state.value_range_dict)++ # Test successful processing behavior+ self.assertEqual(len(result.error_list), 0)+ self.assertGreater(len(result.message_list), 0)+ # Verify the state dict is included in the message for debugging+ message = result.message_list[0]+ self.assertIn('Updated ZM state values to:', message)+ self.assertIn('start', message)+ self.assertIn('pause', message)++ @patch.object(Entity.objects, 'filter_by_integration_key')+ @patch.object(Sensor.objects, 'filter_by_integration_key')+ def test_sync_states_no_update_when_unchanged(self, mock_sensor_filter, mock_entity_filter):+ """Test _sync_states doesn't update when state values unchanged and preserves existing state"""+ # Mock states - identical to existing+ mock_state1 = Mock()+ mock_state1.name.return_value = 'start'+ mock_state2 = Mock()+ mock_state2.name.return_value = 'stop'+ self.mock_manager.get_zm_states.return_value = [mock_state1, mock_state2]++ # Entity exists+ mock_entity = Mock()+ mock_entity.name = 'ZoneMinder'+ mock_entity_filter.return_value.first.return_value = mock_entity++ # Mock sensor with same existing states+ mock_sensor = Mock()+ mock_entity_state = Mock()+ original_state_dict = {'start': 'start', 'stop': 'stop'}+ mock_entity_state.value_range_dict = original_state_dict.copy() # Same states+ mock_entity_state.save = Mock()+ mock_sensor.entity_state = mock_entity_state+ mock_sensor.name = 'ZM Run State'+ mock_sensor_filter.return_value.select_related.return_value.first.return_value = mock_sensor++ result = ProcessingResult(title='Test')+ self.synchronizer._sync_states(result)++ # Test no persistence when no changes+ mock_entity_state.save.assert_not_called()++ # Test state preservation - should be exactly the same+ self.assertEqual(mock_entity_state.value_range_dict, original_state_dict)++ # Test no error conditions+ self.assertEqual(len(result.error_list), 0)++ # Test no update messages generated+ update_messages = [msg for msg in result.message_list if 'Updated ZM state values' in msg]+ self.assertEqual(len(update_messages), 0)+++class TestZoneMinderSynchronizerMonitorSync(TestCase):+ """Test monitor synchronization and entity lifecycle management"""++ def setUp(self):+ self.synchronizer = ZoneMinderSynchronizer()++ # Mock the zm_manager+ self.mock_manager = Mock()+ self.mock_manager.ZM_MONITOR_INTEGRATION_NAME_PREFIX = 'monitor'+ self.mock_manager._to_integration_key = Mock()+ self.synchronizer._zm_manager = self.mock_manager++ def test_sync_monitors_creates_new_entities(self):+ """Test _sync_monitors creates entities for new monitors and tracks sync results"""+ # Mock monitors from ZM+ mock_monitor = Mock()+ mock_monitor.id.return_value = 123+ mock_monitor.name.return_value = 'Test Camera'+ integration_key = IntegrationKey(integration_id='zm', integration_name='monitor.123')++ # Mock the individual sync methods to test coordination+ def mock_fetch_monitors(result):+ result.message_list.append('Fetched 1 monitor from ZM')+ return {integration_key: mock_monitor}++ def mock_get_existing(result):+ result.message_list.append('Found 0 existing entities')+ return {}++ def mock_create_entity(zm_monitor, result):+ result.message_list.append(f'Created entity for monitor {zm_monitor.name.return_value}')+ return Mock()++ with patch.object(self.synchronizer, '_fetch_zm_monitors', side_effect=mock_fetch_monitors), \+ patch.object(self.synchronizer, '_get_existing_zm_monitor_entities', side_effect=mock_get_existing), \+ patch.object(self.synchronizer, '_create_monitor_entity', side_effect=mock_create_entity) as mock_create, \+ patch.object(self.synchronizer, '_update_entity') as mock_update, \+ patch.object(self.synchronizer, '_remove_entity') as mock_remove:++ result = ProcessingResult(title='Test')+ self.synchronizer._sync_monitors(result)++ # Test creation path was taken+ mock_create.assert_called_once_with(zm_monitor=mock_monitor, result=result)+ mock_update.assert_not_called()+ mock_remove.assert_not_called()++ # Test result aggregation from all sync phases+ self.assertIn('Fetched 1 monitor from ZM', result.message_list)+ self.assertIn('Found 0 existing entities', result.message_list)+ self.assertIn('Created entity for monitor Test Camera', result.message_list)++ # Test no errors in successful creation scenario+ self.assertEqual(len(result.error_list), 0)++ @patch.object(ZoneMinderSynchronizer, '_fetch_zm_monitors')+ @patch.object(ZoneMinderSynchronizer, '_get_existing_zm_monitor_entities')+ @patch.object(ZoneMinderSynchronizer, '_create_monitor_entity')+ @patch.object(ZoneMinderSynchronizer, '_update_entity')+ @patch.object(ZoneMinderSynchronizer, '_remove_entity')+ def test_sync_monitors_updates_existing_entities(self, mock_remove, mock_update, mock_create, mock_get_existing, mock_fetch):+ """Test _sync_monitors updates existing entities"""+ # Mock monitors and entities with same key+ mock_monitor = Mock()+ mock_entity = Mock()+ integration_key = IntegrationKey(integration_id='zm', integration_name='monitor.123')+ mock_fetch.return_value = {integration_key: mock_monitor}+ mock_get_existing.return_value = {integration_key: mock_entity}++ result = ProcessingResult(title='Test')+ self.synchronizer._sync_monitors(result)++ mock_update.assert_called_once_with(entity=mock_entity, zm_monitor=mock_monitor, result=result)+ mock_create.assert_not_called()+ mock_remove.assert_not_called()++ def test_sync_monitors_removes_stale_entities(self):+ """Test _sync_monitors removes entities for deleted monitors and handles cleanup properly"""+ # Existing entity that should be removed+ mock_entity = Mock()+ mock_entity.name = 'Deleted Camera'+ mock_entity.id = 456+ integration_key = IntegrationKey(integration_id='zm', integration_name='monitor.123')++ # Mock the individual sync methods to test coordination+ def mock_fetch_monitors(result):+ result.message_list.append('Fetched 0 monitors from ZM')+ return {} # No current monitors++ def mock_get_existing(result):+ result.message_list.append('Found 1 existing entity')+ return {integration_key: mock_entity}++ def mock_remove_entity(entity, result):+ result.message_list.append(f'Removed stale entity {entity.name}')++ with patch.object(self.synchronizer, '_fetch_zm_monitors', side_effect=mock_fetch_monitors), \+ patch.object(self.synchronizer, '_get_existing_zm_monitor_entities', side_effect=mock_get_existing), \+ patch.object(self.synchronizer, '_create_monitor_entity') as mock_create, \+ patch.object(self.synchronizer, '_update_entity') as mock_update, \+ patch.object(self.synchronizer, '_remove_entity', side_effect=mock_remove_entity) as mock_remove:++ result = ProcessingResult(title='Test')+ self.synchronizer._sync_monitors(result)++ # Test removal path was taken+ mock_remove.assert_called_once_with(entity=mock_entity, result=result)+ mock_create.assert_not_called()+ mock_update.assert_not_called()++ # Test result tracking for cleanup scenario+ self.assertIn('Fetched 0 monitors from ZM', result.message_list)+ self.assertIn('Found 1 existing entity', result.message_list)+ self.assertIn('Removed stale entity Deleted Camera', result.message_list)++ # Test no errors in successful removal scenario+ self.assertEqual(len(result.error_list), 0)+++class TestZoneMinderSynchronizerFetchMonitors(TestCase):+ """Test ZM monitor fetching and integration key generation"""++ def setUp(self):+ self.synchronizer = ZoneMinderSynchronizer()++ # Mock the zm_manager+ self.mock_manager = Mock()+ self.mock_manager.ZM_MONITOR_INTEGRATION_NAME_PREFIX = 'monitor'+ self.synchronizer._zm_manager = self.mock_manager++ def test_fetch_zm_monitors_creates_integration_keys(self):+ """Test _fetch_zm_monitors creates correct integration keys for each monitor"""+ # Mock monitors+ mock_monitor1 = Mock()+ mock_monitor1.id.return_value = 123+ mock_monitor2 = Mock()+ mock_monitor2.id.return_value = 456++ self.mock_manager.get_zm_monitors.return_value = [mock_monitor1, mock_monitor2]++ # Mock integration key generation+ key1 = IntegrationKey(integration_id='zm', integration_name='monitor.123')+ key2 = IntegrationKey(integration_id='zm', integration_name='monitor.456')+ self.mock_manager._to_integration_key.side_effect = [key1, key2]++ result = ProcessingResult(title='Test')+ result_dict = self.synchronizer._fetch_zm_monitors(result)++ # Should call integration key generation for each monitor+ expected_calls = [+ call(prefix='monitor', zm_monitor_id=123),+ call(prefix='monitor', zm_monitor_id=456)+ ]+ self.mock_manager._to_integration_key.assert_has_calls(expected_calls)++ # Should return dictionary mapping keys to monitors+ self.assertEqual(len(result_dict), 2)+ self.assertEqual(result_dict[key1], mock_monitor1)+ self.assertEqual(result_dict[key2], mock_monitor2)++ def test_fetch_zm_monitors_forces_reload(self):+ """Test _fetch_zm_monitors forces reload of monitor data"""+ self.mock_manager.get_zm_monitors.return_value = []++ result = ProcessingResult(title='Test')+ self.synchronizer._fetch_zm_monitors(result)++ self.mock_manager.get_zm_monitors.assert_called_once_with(force_load=True)+++class TestZoneMinderSynchronizerExistingEntities(TestCase):+ """Test existing entity retrieval and error handling"""++ def setUp(self):+ self.synchronizer = ZoneMinderSynchronizer()++ # Mock the zm_manager+ self.mock_manager = Mock()+ self.mock_manager.ZM_MONITOR_INTEGRATION_NAME_PREFIX = 'monitor'+ self.synchronizer._zm_manager = self.mock_manager++ @patch.object(Entity.objects, 'filter')+ def test_get_existing_zm_monitor_entities_filters_by_integration_id(self, mock_filter):+ """Test _get_existing_zm_monitor_entities filters by correct integration ID"""+ mock_filter.return_value = []++ result = ProcessingResult(title='Test')+ self.synchronizer._get_existing_zm_monitor_entities(result)++ mock_filter.assert_called_once_with(integration_id=ZmMetaData.integration_id)++ @patch.object(Entity.objects, 'filter')+ def test_get_existing_zm_monitor_entities_handles_missing_integration_key(self, mock_filter):+ """Test entity retrieval handles entities without integration keys"""+ # Mock entity without integration key+ mock_entity = Mock()+ mock_entity.id = 999+ mock_entity.integration_key = None+ mock_filter.return_value = [mock_entity]++ result = ProcessingResult(title='Test')+ result_dict = self.synchronizer._get_existing_zm_monitor_entities(result)++ # Should add error message+ self.assertIn('ZM entity found without integration name', result.error_list[0])++ # Should NOT include entity in result (mock key doesn't start with 'monitor' prefix)+ self.assertEqual(len(result_dict), 0)++ @patch.object(Entity.objects, 'filter')+ def test_get_existing_zm_monitor_entities_filters_monitor_entities(self, mock_filter):+ """Test entity retrieval only includes monitor entities"""+ # Mock entities - one monitor, one non-monitor+ mock_monitor_entity = Mock()+ monitor_key = IntegrationKey(integration_id='zm', integration_name='monitor.123')+ mock_monitor_entity.integration_key = monitor_key++ mock_other_entity = Mock()+ other_key = IntegrationKey(integration_id='zm', integration_name='system.state')+ mock_other_entity.integration_key = other_key++ mock_filter.return_value = [mock_monitor_entity, mock_other_entity]++ result = ProcessingResult(title='Test')+ result_dict = self.synchronizer._get_existing_zm_monitor_entities(result)++ # Should only include monitor entity+ self.assertEqual(len(result_dict), 1)+ self.assertIn(monitor_key, result_dict)+ self.assertNotIn(other_key, result_dict)+++class TestZoneMinderSynchronizerEntityCreation(TestCase):+ """Test entity creation with database transactions"""++ def setUp(self):+ self.synchronizer = ZoneMinderSynchronizer()++ # Mock the zm_manager+ self.mock_manager = Mock()+ self.mock_manager.ZM_ENTITY_NAME = 'ZoneMinder'+ self.mock_manager.ZM_MONITOR_INTEGRATION_NAME_PREFIX = 'monitor'+ self.mock_manager.VIDEO_STREAM_SENSOR_PREFIX = 'monitor.video_stream'+ self.mock_manager.MOVEMENT_SENSOR_PREFIX = 'monitor.motion'+ self.mock_manager.MONITOR_FUNCTION_SENSOR_PREFIX = 'monitor.function'+ self.mock_manager.MOVEMENT_EVENT_PREFIX = 'monitor.motion'+ self.mock_manager.should_add_alarm_events = True+ self.synchronizer._zm_manager = self.mock_manager++ @patch('hi.services.zoneminder.zm_sync.transaction.atomic')+ @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_discrete_controller')+ @patch.object(Entity, 'save')+ def test_create_zm_entity_uses_transaction(self, mock_save, mock_create_controller, mock_atomic):+ """Test _create_zm_entity uses database transaction"""+ run_state_dict = {'start': 'start', 'stop': 'stop'}++ mock_integration_key = IntegrationKey(integration_id='zm', integration_name='system')+ self.mock_manager._zm_integration_key.return_value = mock_integration_key+ self.mock_manager._zm_run_state_integration_key.return_value = IntegrationKey(+ integration_id='zm', integration_name='run.state'+ )++ result = ProcessingResult(title='Test')+ self.synchronizer._create_zm_entity(run_state_dict, result)++ mock_atomic.assert_called_once()+ mock_save.assert_called_once()+ mock_create_controller.assert_called_once()++ @patch('hi.services.zoneminder.zm_sync.transaction.atomic')+ @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_video_stream_sensor')+ @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_movement_sensor')+ @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_discrete_controller')+ @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_movement_event_definition')+ @patch.object(Entity, 'save')+ def test_create_monitor_entity_creates_all_components(self, mock_save, mock_create_event,+ mock_create_controller, mock_create_movement,+ mock_create_video, mock_atomic):+ """Test _create_monitor_entity creates all required sensors and controllers"""+ # Mock monitor+ mock_monitor = Mock()+ mock_monitor.id.return_value = 123+ mock_monitor.name.return_value = 'Front Door'++ # Mock integration key generation+ entity_key = IntegrationKey(integration_id='zm', integration_name='monitor.123')+ video_key = IntegrationKey(integration_id='zm', integration_name='monitor.video_stream.123')+ movement_key = IntegrationKey(integration_id='zm', integration_name='monitor.motion.123')+ function_key = IntegrationKey(integration_id='zm', integration_name='monitor.function.123')+ event_key = IntegrationKey(integration_id='zm', integration_name='monitor.motion.123')++ self.mock_manager._to_integration_key.side_effect = [+ entity_key, video_key, movement_key, function_key, event_key+ ]++ # Mock movement sensor for event creation+ mock_movement_sensor = Mock()+ mock_movement_sensor.name = 'Front Door Motion'+ mock_movement_sensor.entity_state = Mock()+ mock_create_movement.return_value = mock_movement_sensor++ result = ProcessingResult(title='Test')+ self.synchronizer._create_monitor_entity(mock_monitor, result)++ # Should create all components+ mock_create_video.assert_called_once()+ mock_create_movement.assert_called_once()+ mock_create_controller.assert_called_once()+ mock_create_event.assert_called_once()++ # Should use transaction+ mock_atomic.assert_called_once()+ mock_save.assert_called_once()++ @patch('hi.services.zoneminder.zm_sync.transaction.atomic')+ @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_video_stream_sensor')+ @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_movement_sensor')+ @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_discrete_controller')+ @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_movement_event_definition')+ @patch.object(Entity, 'save')+ def test_create_monitor_entity_skips_events_when_disabled(self, mock_save, mock_create_event,+ mock_create_controller, mock_create_movement,+ mock_create_video, mock_atomic):+ """Test _create_monitor_entity skips event creation when alarm events disabled"""+ self.mock_manager.should_add_alarm_events = False++ mock_monitor = Mock()+ mock_monitor.id.return_value = 123+ mock_monitor.name.return_value = 'Front Door'++ # Mock integration key generation+ self.mock_manager._to_integration_key.side_effect = [+ Mock(), Mock(), Mock(), Mock() # entity, video, movement, function keys+ ]++ mock_movement_sensor = Mock()+ mock_create_movement.return_value = mock_movement_sensor++ result = ProcessingResult(title='Test')+ self.synchronizer._create_monitor_entity(mock_monitor, result)++ # Should not create event+ mock_create_event.assert_not_called()++ # Should still create other components+ mock_create_video.assert_called_once()+ mock_create_movement.assert_called_once()+ mock_create_controller.assert_called_once()+++class TestZoneMinderSynchronizerEntityUpdate(TestCase):+ """Test entity update logic"""++ def setUp(self):+ self.synchronizer = ZoneMinderSynchronizer()++ def test_update_entity_changes_name_when_different(self):+ """Test _update_entity updates name when monitor name changed and preserves other attributes"""+ mock_entity = Mock()+ mock_entity.name = 'Old Name'+ mock_entity.id = 123+ mock_entity.entity_type_str = 'CAMERA'+ mock_entity.can_user_delete = True+ original_integration_key = Mock()+ mock_entity.integration_key = original_integration_key+ mock_entity.save = Mock()++ mock_monitor = Mock()+ mock_monitor.name.return_value = 'New Name'+ mock_monitor.id.return_value = 456++ result = ProcessingResult(title='Test')+ self.synchronizer._update_entity(mock_entity, mock_monitor, result)++ # Test name update behavior+ self.assertEqual(mock_entity.name, 'New Name')+ mock_entity.save.assert_called_once()++ # Test preservation of other critical attributes+ self.assertEqual(mock_entity.id, 123) # Entity ID unchanged+ self.assertEqual(mock_entity.entity_type_str, 'CAMERA') # Type unchanged+ self.assertEqual(mock_entity.can_user_delete, True) # User delete flag unchanged+ self.assertEqual(mock_entity.integration_key, original_integration_key) # Integration key unchanged++ # Test result tracking+ self.assertEqual(len(result.error_list), 0)+ self.assertGreater(len(result.message_list), 0)+ update_message = result.message_list[0]+ self.assertIn('Name changed for', update_message)+ self.assertIn('New Name', update_message)++ def test_update_entity_no_change_when_name_same(self):+ """Test _update_entity doesn't save when name unchanged and preserves all entity state"""+ mock_entity = Mock()+ mock_entity.name = 'Same Name'+ mock_entity.id = 789+ mock_entity.entity_type_str = 'CAMERA'+ mock_entity.save = Mock()++ mock_monitor = Mock()+ mock_monitor.name.return_value = 'Same Name'+ mock_monitor.id.return_value = 999++ result = ProcessingResult(title='Test')+ self.synchronizer._update_entity(mock_entity, mock_monitor, result)++ # Test no persistence when no changes+ mock_entity.save.assert_not_called()++ # Test complete state preservation+ self.assertEqual(mock_entity.name, 'Same Name') # Name unchanged+ self.assertEqual(mock_entity.id, 789) # ID unchanged+ self.assertEqual(mock_entity.entity_type_str, 'CAMERA') # Type unchanged++ # Test result tracking for no-change scenario+ self.assertEqual(len(result.error_list), 0)+ self.assertGreater(len(result.message_list), 0)+ no_change_message = result.message_list[0]+ self.assertIn('No changes found for', no_change_message)++ # Test that the entity object itself is referenced in the message+ self.assertIn(str(mock_entity), no_change_message)+++class TestZoneMinderSynchronizerEntityRemoval(TestCase):+ """Test intelligent entity deletion"""++ def setUp(self):+ self.synchronizer = ZoneMinderSynchronizer()++ @patch.object(ZoneMinderSynchronizer, '_remove_entity_intelligently')+ def test_remove_entity_calls_intelligent_deletion(self, mock_intelligent_removal):+ """Test _remove_entity calls intelligent deletion with correct parameters"""+ mock_entity = Mock()+ result = ProcessingResult(title='Test')++ self.synchronizer._remove_entity(mock_entity, result)++ mock_intelligent_removal.assert_called_once_with(mock_entity, result, 'ZoneMinder')+++class TestZoneMinderSynchronizerFunctionConstants(TestCase):+ """Test monitor function name constants"""++ def test_monitor_function_name_label_dict_completeness(self):+ """Test MONITOR_FUNCTION_NAME_LABEL_DICT contains expected ZM functions"""+ expected_functions = ['None', 'Monitor', 'Modect', 'Record', 'Mocord', 'Nodect']++ for function in expected_functions:+ self.assertIn(function, ZoneMinderSynchronizer.MONITOR_FUNCTION_NAME_LABEL_DICT)+ # Labels should match function names+ self.assertEqual(+ ZoneMinderSynchronizer.MONITOR_FUNCTION_NAME_LABEL_DICT[function],+ function+ )+++class TestZoneMinderSynchronizerWithRealData(TestCase):+ """Test synchronizer with real ZoneMinder API response data"""++ @classmethod+ def setUpClass(cls):+ super().setUpClass()+ # Load real ZM API response data+ test_data_dir = os.path.join(os.path.dirname(__file__), 'data')++ with open(os.path.join(test_data_dir, 'zm_states.json'), 'r') as f:+ cls.real_states_data = json.load(f)++ with open(os.path.join(test_data_dir, 'zm_monitors.json'), 'r') as f:+ cls.real_monitors_data = json.load(f)++ def setUp(self):+ self.synchronizer = ZoneMinderSynchronizer()++ # Mock the zm_manager+ self.mock_manager = Mock()+ self.mock_manager.ZM_MONITOR_INTEGRATION_NAME_PREFIX = 'monitor'+ self.mock_manager._to_integration_key = Mock()+ self.synchronizer._zm_manager = self.mock_manager++ def create_mock_states_from_real_data(self):+ """Create mock PyZM State objects from real API data"""+ mock_states = []+ for state_data in self.real_states_data['states']:+ state_info = state_data['State']+ mock_state = Mock()+ mock_state.name.return_value = state_info['Name']+ mock_state.id.return_value = int(state_info['Id'])+ mock_state.is_active.return_value = state_info['IsActive'] == '1'+ mock_states.append(mock_state)+ return mock_states++ def create_mock_monitors_from_real_data(self):+ """Create mock PyZM Monitor objects from real API data"""+ mock_monitors = []+ for monitor_data in self.real_monitors_data['monitors']:+ monitor_info = monitor_data['Monitor']+ mock_monitor = Mock()+ mock_monitor.id.return_value = int(monitor_info['Id'])+ mock_monitor.name.return_value = monitor_info['Name']+ mock_monitor.function.return_value = monitor_info['Function']+ mock_monitor.enabled.return_value = monitor_info['Enabled'] == '1'+ mock_monitors.append(mock_monitor)+ return mock_monitors++ @patch.object(Entity.objects, 'filter_by_integration_key')+ @patch.object(Sensor.objects, 'filter_by_integration_key')+ def test_sync_states_with_real_zm_state_names(self, mock_sensor_filter, mock_entity_filter):+ """Test state sync handles real ZM state names: default, Away, HomeDay, Disabled"""+ # Use real state data+ mock_states = self.create_mock_states_from_real_data()+ self.mock_manager.get_zm_states.return_value = mock_states++ # Mock existing entity and sensor+ mock_entity_filter.return_value.first.return_value = Mock()++ mock_sensor = Mock()+ mock_entity_state = Mock()+ mock_entity_state.value_range_dict = {'old_state': 'old_state'} # Different from real data+ mock_entity_state.save = Mock()+ mock_sensor.entity_state = mock_entity_state+ mock_sensor_filter.return_value.select_related.return_value.first.return_value = mock_sensor++ # Mock integration keys+ self.mock_manager._zm_integration_key.return_value = IntegrationKey(+ integration_id='zm', integration_name='system'+ )+ self.mock_manager._zm_run_state_integration_key.return_value = IntegrationKey(+ integration_id='zm', integration_name='run.state'+ )++ result = ProcessingResult(title='Test')+ self.synchronizer._sync_states(result)++ # Should update to real state names+ expected_states = {'default': 'default', 'Away': 'Away', 'HomeDay': 'HomeDay', 'Disabled': 'Disabled'}+ self.assertEqual(mock_entity_state.value_range_dict, expected_states)+ mock_entity_state.save.assert_called_once()+ self.assertIn('Updated ZM state values to:', result.message_list[0])++ @patch.object(ZoneMinderSynchronizer, '_fetch_zm_monitors')+ @patch.object(ZoneMinderSynchronizer, '_get_existing_zm_monitor_entities')+ @patch.object(ZoneMinderSynchronizer, '_create_monitor_entity')+ def test_sync_monitors_with_real_monitor_configurations(self, mock_create, mock_get_existing, mock_fetch):+ """Test monitor sync with real monitor configurations and diverse setups"""+ # Use real monitor data to create integration keys and monitors+ mock_monitors = self.create_mock_monitors_from_real_data()++ integration_key_to_monitor = {}+ for i, mock_monitor in enumerate(mock_monitors):+ # Use real monitor IDs from the data+ monitor_id = [1, 3, 6, 9][i] # IDs from our test data+ integration_key = IntegrationKey(+ integration_id='zm',+ integration_name=f'monitor.{monitor_id}'+ )+ integration_key_to_monitor[integration_key] = mock_monitor++ mock_fetch.return_value = integration_key_to_monitor+ mock_get_existing.return_value = {} # No existing entities++ result = ProcessingResult(title='Test')+ self.synchronizer._sync_monitors(result)++ # Should create entities for all real monitors+ self.assertEqual(mock_create.call_count, 4)++ # Verify created with real monitor names+ created_monitors = [call.kwargs['zm_monitor'] for call in mock_create.call_args_list]+ created_names = [monitor.name.return_value for monitor in created_monitors]+ expected_names = ['HighCamera', 'FrontCamera', 'DriveCamera', 'GarageCamera']+ self.assertEqual(created_names, expected_names)++ def test_real_monitor_data_diversity_validation(self):+ """Test that our real monitor data covers diverse configurations"""+ monitors = self.real_monitors_data['monitors']++ # Test we have monitors with different resolutions+ resolutions = set()+ orientations = set()+ zone_counts = set()++ for monitor_data in monitors:+ monitor = monitor_data['Monitor']+ resolution = f"{monitor['Width']}x{monitor['Height']}"+ resolutions.add(resolution)+ orientations.add(monitor['Orientation'])+ zone_counts.add(int(monitor['ZoneCount']))++ # Verify diversity in our test data+ self.assertGreaterEqual(len(resolutions), 2, "Should have multiple resolutions")+ self.assertGreaterEqual(len(orientations), 2, "Should have multiple orientations")+ self.assertGreaterEqual(len(zone_counts), 3, "Should have varying zone counts")++ # Verify we have the expected variety+ self.assertIn('640x480', resolutions)+ self.assertIn('1920x1080', resolutions)+ self.assertIn('ROTATE_0', orientations)+ self.assertIn('ROTATE_270', orientations)++ def test_update_entity_with_real_monitor_name_changes(self):+ """Test entity updates with realistic monitor name scenarios"""+ # Create scenario where monitor name changed from generic to real name+ mock_entity = Mock()+ mock_entity.name = 'Camera_001' # Generic name++ # Use real monitor data+ real_monitor = self.create_mock_monitors_from_real_data()[0] # HighCamera++ result = ProcessingResult(title='Test')+ self.synchronizer._update_entity(mock_entity, real_monitor, result)++ # Should update to real name from ZM API+ self.assertEqual(mock_entity.name, 'HighCamera')+ mock_entity.save.assert_called_once()+ self.assertIn('Name changed for', result.message_list[0])++ @patch.object(Entity.objects, 'filter')+ def test_get_existing_entities_with_real_monitor_id_patterns(self, mock_filter):+ """Test existing entity retrieval with realistic monitor ID patterns"""+ # Create mock entities with integration keys matching real monitor IDs+ mock_entities = []+ real_monitor_ids = ['1', '3', '6', '9'] # From our real data++ for monitor_id in real_monitor_ids:+ mock_entity = Mock()+ mock_entity.id = int(monitor_id) + 100 # Offset for entity IDs+ mock_entity.integration_key = IntegrationKey(+ integration_id='zm',+ integration_name=f'monitor.{monitor_id}'+ )+ mock_entities.append(mock_entity)++ # Add one entity with missing integration key to test error handling+ mock_broken_entity = Mock()+ mock_broken_entity.id = 999+ mock_broken_entity.integration_key = None+ mock_entities.append(mock_broken_entity)++ mock_filter.return_value = mock_entities++ result = ProcessingResult(title='Test')+ result_dict = self.synchronizer._get_existing_zm_monitor_entities(result)++ # Should find 4 valid monitor entities (broken entity is filtered out)+ self.assertEqual(len(result_dict), 4)++ # Should have error message for broken entity+ self.assertIn('ZM entity found without integration name', result.error_list[0])++ # Should include all real monitor integration keys+ integration_names = [key.integration_name for key in result_dict.keys()]+ for monitor_id in real_monitor_ids:+ self.assertIn(f'monitor.{monitor_id}', integration_names)++ def test_real_state_data_validation(self):+ """Test that our real state data contains expected ZM states"""+ states = self.real_states_data['states']++ # Extract state names+ state_names = [state['State']['Name'] for state in states]++ # Verify we have typical ZM states+ expected_states = ['default', 'Away', 'HomeDay', 'Disabled']+ for expected_state in expected_states:+ self.assertIn(expected_state, state_names)++ # Verify state structure+ for state_data in states:+ state = state_data['State']+ self.assertIn('Id', state)+ self.assertIn('Name', state)+ self.assertIn('Definition', state)+ self.assertIn('IsActive', state)++ # Verify IsActive is boolean-like string+ self.assertIn(state['IsActive'], ['0', '1'])++ @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_video_stream_sensor')+ @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_movement_sensor')+ @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_discrete_controller')+ @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_movement_event_definition')+ @patch('hi.services.zoneminder.zm_sync.transaction.atomic')+ @patch.object(Entity, 'save')+ def test_create_monitor_entity_with_real_monitor_variations(self, mock_save, mock_atomic,+ mock_create_event, mock_create_controller,+ mock_create_movement, mock_create_video):+ """Test monitor entity creation with real monitor data variations"""+ # Test each real monitor configuration+ real_monitors = self.create_mock_monitors_from_real_data()++ # Mock integration key generation for each component+ def mock_integration_key_side_effect(prefix, zm_monitor_id):+ return IntegrationKey(+ integration_id='zm',+ integration_name=f'{prefix}.{zm_monitor_id}'+ )++ self.mock_manager._to_integration_key.side_effect = mock_integration_key_side_effect+ self.mock_manager.should_add_alarm_events = True++ # Mock movement sensor for event creation+ mock_movement_sensor = Mock()+ mock_movement_sensor.entity_state = Mock()+ mock_create_movement.return_value = mock_movement_sensor++ for monitor in real_monitors:+ with self.subTest(monitor_name=monitor.name.return_value):+ mock_save.reset_mock()+ mock_create_video.reset_mock()+ mock_create_movement.reset_mock()+ mock_create_controller.reset_mock()+ mock_create_event.reset_mock()++ result = ProcessingResult(title='Test')+ self.synchronizer._create_monitor_entity(monitor, result)++ # Should create all components for each monitor+ mock_create_video.assert_called_once()+ mock_create_movement.assert_called_once()+ mock_create_controller.assert_called_once()+ mock_create_event.assert_called_once()++ # Should save entity+ mock_save.assert_called_once()++ # Should use transaction+ mock_atomic.assert_called()++ # Should log creation+ self.assertIn('Create new camera entity:', result.message_list[0])diff --git a/src/hi/services/zoneminder/zm_manager.py b/src/hi/services/zoneminder/zm_manager.pyindex f19d1d66..f4673d39 100644--- a/src/hi/services/zoneminder/zm_manager.py+++ b/src/hi/services/zoneminder/zm_manager.py@@ -75,8 +75,8 @@ class ZoneMinderManager( Singleton ):for callback in self._change_listeners:try:callback()- except Exception as e:- logger.exception( 'Problem calling setting change callback.', e )+ except Exception:+ logger.exception( 'Problem calling setting change callback.' )continuereturn@@ -241,7 +241,7 @@ class ZoneMinderManager( Singleton ):logger.error( 'ZoneMinder timezone name is not available.' )- except IntegrationAttribute.DoesNotExist:+ except (Integration.DoesNotExist, IntegrationAttribute.DoesNotExist):logger.error( 'ZoneMinder timezone not found.' )return 'UTC'