import hashlib import json from unittest.mock import MagicMock, patch from django.contrib.auth import get_user_model from django.test import TestCase, override_settings from django.urls import reverse from groceries.models import GroceryItem from planner.models import Task from .client import ConnectionError, _get_json, _request_json, decrypt_token, encrypt_token, get_items, normalize_url from .models import HomeAssistantConnection, HomeAssistantItemMap, HomeAssistantSyncRun from .sync import _schedule_after_failure, build_plan, confirm_and_sync, preview, run_due_syncs from .task_sync import confirm_task_sync, preview_tasks def dns_for(address): return [(2, 1, 6, '', (address, 8123))] @override_settings(SECURE_SSL_REDIRECT=False) class ConnectionTests(TestCase): def setUp(self): self.user = get_user_model().objects.create_user(username='ha-user', password='example-password') self.other = get_user_model().objects.create_user(username='other-user', password='example-password') self.client.force_login(self.user) self.url = reverse('home_assistant:settings') @patch('home_assistant.client.socket.getaddrinfo', return_value=dns_for('192.168.1.10')) def test_token_is_encrypted_and_never_rendered(self, _dns): response = self.client.post(self.url, {'action': 'save', 'base_url': 'http://ha.local:8123/', 'token': 'private-token'}) self.assertEqual(response.status_code, 302) connection = HomeAssistantConnection.objects.get(user=self.user) self.assertEqual(connection.base_url, 'http://ha.local:8123') self.assertNotIn('private-token', connection.encrypted_token) self.assertEqual(decrypt_token(connection.encrypted_token), 'private-token') self.assertNotContains(self.client.get(self.url), 'private-token') @patch('home_assistant.client.socket.getaddrinfo', return_value=dns_for('192.168.1.10')) def test_blank_token_keeps_previous_value_and_owner_isolation(self, _dns): HomeAssistantConnection.objects.create(user=self.user, base_url='http://ha.local:8123', encrypted_token=encrypt_token('old')) HomeAssistantConnection.objects.create(user=self.other, base_url='https://other.example', encrypted_token=encrypt_token('other')) self.client.post(self.url, {'action': 'save', 'base_url': 'http://ha.local:8123', 'token': ''}) self.assertEqual(decrypt_token(HomeAssistantConnection.objects.get(user=self.user).encrypted_token), 'old') self.assertEqual(decrypt_token(HomeAssistantConnection.objects.get(user=self.other).encrypted_token), 'other') @patch('home_assistant.client.socket.getaddrinfo', return_value=dns_for('192.168.1.10')) @patch('home_assistant.views.test_connection', return_value='2026.10.0') @patch('home_assistant.views.discover_entities', return_value=[{'id': 'todo.shopping', 'name': 'Shopping'}]) def test_discover_and_select_only_known_entity(self, _discover, _test, _dns): HomeAssistantConnection.objects.create(user=self.user, base_url='http://ha.local:8123', encrypted_token=encrypt_token('secret')) self.client.post(self.url, {'action': 'discover'}) connection = HomeAssistantConnection.objects.get(user=self.user) self.assertEqual(connection.version, '2026.10.0') self.assertEqual(connection.entities[0]['id'], 'todo.shopping') self.client.post(self.url, {'action': 'select', 'grocery_entity_id': 'todo.foreign'}) connection.refresh_from_db() self.assertEqual(connection.grocery_entity_id, '') self.client.post(self.url, {'action': 'select', 'grocery_entity_id': 'todo.shopping'}) connection.refresh_from_db() self.assertEqual(connection.grocery_entity_id, 'todo.shopping') def test_optional_task_entity_requires_discovery_and_can_be_disconnected(self): connection = HomeAssistantConnection.objects.create(user=self.user, base_url='https://ha.example', encrypted_token=encrypt_token('secret'), grocery_entity_id='todo.shopping', entities=[ {'id': 'todo.shopping', 'name': 'Shopping'}, {'id': 'todo.tasks', 'name': 'Tasks'}, ]) self.client.post(self.url, {'action': 'select-task', 'task_entity_id': 'todo.unknown'}) connection.refresh_from_db() self.assertEqual(connection.task_entity_id, '') self.client.post(self.url, {'action': 'select-task', 'task_entity_id': 'todo.tasks'}) connection.refresh_from_db() self.assertEqual(connection.task_entity_id, 'todo.tasks') self.client.post(self.url, {'action': 'select-task', 'task_entity_id': ''}) connection.refresh_from_db() self.assertEqual(connection.task_entity_id, '') self.assertEqual(connection.grocery_entity_id, 'todo.shopping') @patch('home_assistant.client.socket.getaddrinfo', return_value=dns_for('8.8.8.8')) def test_public_http_rejected(self, _dns): with self.assertRaises(ConnectionError): normalize_url('http://example.com:8123') def test_url_credentials_and_paths_rejected(self): for value in ('https://user:secret@example.com', 'https://example.com/api', 'file:///etc/passwd'): with self.subTest(value=value), self.assertRaises(ConnectionError): normalize_url(value) @patch('home_assistant.client.socket.getaddrinfo', return_value=dns_for('192.168.1.10')) def test_changing_host_requires_new_token(self, _dns): HomeAssistantConnection.objects.create(user=self.user, base_url='http://old.local:8123', encrypted_token=encrypt_token('old')) self.client.post(self.url, {'action': 'save', 'base_url': 'http://new.local:8123', 'token': ''}) connection = HomeAssistantConnection.objects.get(user=self.user) self.assertEqual(connection.base_url, 'http://old.local:8123') @patch('home_assistant.views.test_connection', side_effect=ConnectionError('Token rejected (401).')) def test_test_failure_is_sanitized_and_saved(self, _test): HomeAssistantConnection.objects.create(user=self.user, base_url='https://ha.example', encrypted_token=encrypt_token('secret')) self.client.post(self.url, {'action': 'test'}) connection = HomeAssistantConnection.objects.get(user=self.user) self.assertEqual(connection.last_error, 'Token rejected (401).') self.assertNotIn('secret', connection.last_error) self.assertIsNone(connection.last_tested_at) @patch('home_assistant.client.socket.getaddrinfo', return_value=dns_for('192.168.1.10')) @patch('home_assistant.client.http.client.HTTPConnection') def test_api_rejects_redirect_and_unauthorized(self, connection_class, _dns): connection = connection_class.return_value response = MagicMock() connection.getresponse.return_value = response for status, expected in ((302, 'redirected'), (401, 'Token rejected')): response.status = status with self.subTest(status=status), self.assertRaisesRegex(ConnectionError, expected): _get_json('http://ha.local:8123', 'secret', '/api/config') self.assertEqual(connection.request.call_count, 2) self.assertEqual(connection.request.call_args.args[:2], ('GET', '/api/config')) @patch('home_assistant.client.socket.getaddrinfo', return_value=dns_for('192.168.1.10')) @patch('home_assistant.client.http.client.HTTPConnection') def test_unavailable_entity_error_is_actionable(self, connection_class, _dns): response = connection_class.return_value.getresponse.return_value response.status = 500 response.read.return_value = b'{"message":"Service call requested response data but did not match any entities"}' with self.assertRaisesRegex(ConnectionError, 'selected Home Assistant to-do list is unavailable'): _request_json('http://ha.local:8123', 'secret', '/api/services/todo/get_items?return_response', {}) @patch('home_assistant.client._get_json', return_value=[ {'entity_id': 'todo.active', 'state': '0', 'attributes': {'friendly_name': 'Active'}}, {'entity_id': 'todo.offline', 'state': 'unavailable', 'attributes': {'friendly_name': 'Offline'}}, ]) def test_discovery_marks_unavailable_entities(self, _get): from .client import discover_entities found = discover_entities('https://ha.example', 'token') self.assertTrue(next(entity for entity in found if entity['id'] == 'todo.active')['available']) self.assertFalse(next(entity for entity in found if entity['id'] == 'todo.offline')['available']) @patch('home_assistant.client._request_json') def test_get_items_parses_service_response_and_rejects_duplicate_uids(self, request): request.return_value = {'changed_states': [], 'service_response': {'todo.shopping': {'items': [ {'uid': 'one', 'summary': 'Milk', 'status': 'needs_action'}, {'uid': 'two', 'summary': 'Bread', 'status': 'completed'}, ]}}} result = get_items('https://ha.example', 'token', 'todo.shopping') self.assertEqual(set(result), {'one', 'two'}) self.assertEqual(request.call_args.args[2], '/api/services/todo/get_items?return_response') request.return_value['service_response']['todo.shopping']['items'][1]['uid'] = 'one' with self.assertRaises(ConnectionError): get_items('https://ha.example', 'token', 'todo.shopping') class FakeHomeAssistant: def __init__(self, items=None): self.items = {item['uid']: item.copy() for item in (items or [])} self.calls = [] self.next_id = 1 def get(self, *_args): return {uid: item.copy() for uid, item in self.items.items()} def add(self, _url, _token, _entity, name): self.calls.append(('add', name)) uid = f'new-{self.next_id}' self.next_id += 1 self.items[uid] = {'uid': uid, 'name': name, 'status': 'needs_action'} def update(self, _url, _token, _entity, uid, *, name=None, status=None): self.calls.append(('update', uid, name, status)) if name is not None: self.items[uid]['name'] = name if status is not None: self.items[uid]['status'] = status class FakeTaskHomeAssistant: def __init__(self, items=None): self.items = {item['uid']: item.copy() for item in (items or [])} self.next_id = 1 def get(self, *_args): return {uid: item.copy() for uid, item in self.items.items()} def add(self, _url, _token, _entity, name, *, due_date=None, description=None): uid = f'task-{self.next_id}' self.next_id += 1 self.items[uid] = {'uid': uid, 'name': name, 'status': 'needs_action', 'due': due_date, 'description': description or ''} def update(self, _url, _token, _entity, uid, *, name=None, status=None, due_date=None, description=None): item = self.items[uid] if name is not None: item['name'] = name if status is not None: item['status'] = status if due_date is not None: item['due'] = due_date if description is not None: item['description'] = description @override_settings(SECURE_SSL_REDIRECT=False) class GrocerySyncTests(TestCase): def setUp(self): self.user = get_user_model().objects.create_user(username='sync-user') self.other = get_user_model().objects.create_user(username='sync-other') self.connection = HomeAssistantConnection.objects.create( user=self.user, base_url='https://ha.example', encrypted_token=encrypt_token('secret'), grocery_entity_id='todo.shopping', entities=[{'id': 'todo.shopping', 'name': 'Shopping', 'features': 5}]) def local(self, name, status='needed', user=None): return GroceryItem.objects.create(user=user or self.user, name=name, quantity=1, unit='pieces', status=status) def run_with(self, fake): with patch('home_assistant.sync.get_items', side_effect=fake.get), \ patch('home_assistant.sync.add_item', side_effect=fake.add), \ patch('home_assistant.sync.update_item', side_effect=fake.update): plan = preview(self.connection) result = confirm_and_sync(self.connection, plan['digest']) return plan, result def test_first_sync_import_export_and_repeat_is_duplicate_free(self): local = self.local('Milk', 'purchased') self.local('Private', user=self.other) fake = FakeHomeAssistant([{'uid': 'ha-1', 'name': 'Bread', 'status': 'completed'}]) plan, (done, _) = self.run_with(fake) self.assertEqual({action['kind'] for action in plan['operations']}, {'import', 'export'}) self.assertEqual(done, 2) self.assertEqual(fake.items['new-1']['status'], 'completed') self.assertEqual(HomeAssistantItemMap.objects.filter(connection=self.connection).count(), 2) self.assertEqual(GroceryItem.objects.get(user=self.user, name='Bread').status, 'purchased') self.assertEqual(GroceryItem.objects.get(pk=local.pk).name, 'Milk') second, (done_again, _) = self.run_with(fake) self.assertEqual(second['operations'], []) self.assertEqual(done_again, 0) self.assertEqual(fake.calls.count(('add', 'Milk')), 1) self.assertFalse(GroceryItem.objects.filter(user=self.user, name='Private').exists()) def test_ambiguous_same_title_is_not_merged_or_duplicated(self): self.local('Eggs') fake = FakeHomeAssistant([{'uid': 'ha-1', 'name': 'Eggs', 'status': 'needs_action'}]) plan, (done, _) = self.run_with(fake) self.assertEqual(done, 0) self.assertEqual(plan['operations'], []) self.assertTrue(plan['issues']) self.assertEqual(fake.calls, []) def test_remote_edit_and_completion_pull_into_local(self): item = self.local('Tea') fake = FakeHomeAssistant([{'uid': 'ha-1', 'name': 'Tea', 'status': 'needs_action'}]) self.run_with(fake) # Initial same-title items are deliberately not matched; create a known mapping. HomeAssistantItemMap.objects.create(connection=self.connection, entity_id='todo.shopping', grocery=item, ha_uid='ha-1', last_local_hash='x', last_remote_hash='x') fake.items['ha-1'].update(name='Green tea', status='completed') with patch('home_assistant.sync.get_items', side_effect=fake.get): plan = preview(self.connection) self.assertEqual(plan['operations'][0]['kind'], 'pull') with patch('home_assistant.sync.get_items', side_effect=fake.get): confirm_and_sync(self.connection, plan['digest']) item.refresh_from_db() self.assertEqual((item.name, item.status), ('Green tea', 'purchased')) def test_missing_remote_does_not_delete_local(self): item = self.local('Rice') HomeAssistantItemMap.objects.create(connection=self.connection, entity_id='todo.shopping', grocery=item, ha_uid='gone', last_local_hash='x', last_remote_hash='x') fake = FakeHomeAssistant() plan, (done, _) = self.run_with(fake) self.assertEqual(done, 0) self.assertTrue(plan['issues']) self.assertTrue(GroceryItem.objects.filter(pk=item.pk).exists()) def test_outbound_failure_stays_pending_and_does_not_retry_blindly(self): self.local('Oats') fake = FakeHomeAssistant() with patch('home_assistant.sync.get_items', side_effect=fake.get), \ patch('home_assistant.sync.add_item', side_effect=ConnectionError('Connection timed out.')): plan = preview(self.connection) with self.assertRaises(ConnectionError): confirm_and_sync(self.connection, plan['digest']) mapping = HomeAssistantItemMap.objects.get(connection=self.connection) self.assertTrue(mapping.pending_create) with patch('home_assistant.sync.get_items', side_effect=fake.get): next_plan = preview(self.connection) self.assertFalse(next_plan['operations']) self.assertTrue(next_plan['issues']) def test_two_sided_conflict_defaults_to_home_assistant(self): item = self.local('Original') fake = FakeHomeAssistant([{'uid': 'ha-1', 'name': 'Home edit', 'status': 'completed'}]) baseline = hashlib.sha256(json.dumps(['Original', 'needs_action'], ensure_ascii=False).encode()).hexdigest() HomeAssistantItemMap.objects.create(connection=self.connection, entity_id='todo.shopping', grocery=item, ha_uid='ha-1', last_local_hash=baseline, last_remote_hash=baseline) item.name = 'TasksNest edit' item.save() plan, (done, _) = self.run_with(fake) self.assertEqual(plan['operations'][0]['kind'], 'pull') self.assertEqual(done, 1) item.refresh_from_db() self.assertEqual((item.name, item.status), ('Home edit', 'purchased')) def test_two_sided_conflict_can_choose_tasksnest(self): item = self.local('Local edit') fake = FakeHomeAssistant([{'uid': 'ha-1', 'name': 'Home edit', 'status': 'completed'}]) HomeAssistantItemMap.objects.create(connection=self.connection, entity_id='todo.shopping', grocery=item, ha_uid='ha-1', last_local_hash='old', last_remote_hash='old') self.connection.conflict_winner = 'tasksnest' self.connection.save() plan, (done, _) = self.run_with(fake) self.assertEqual(plan['operations'][0]['kind'], 'push') self.assertEqual(done, 1) self.assertEqual(fake.items['ha-1']['name'], 'Local edit') self.assertEqual(fake.items['ha-1']['status'], 'needs_action') def test_direction_to_ha_pushes_and_unsupported_update_is_blocked(self): item = self.local('Original') fake = FakeHomeAssistant([{'uid': 'ha-1', 'name': 'Home edit', 'status': 'needs_action'}]) HomeAssistantItemMap.objects.create(connection=self.connection, entity_id='todo.shopping', grocery=item, ha_uid='ha-1', last_local_hash='previous', last_remote_hash='previous') self.connection.direction = 'to_ha' self.connection.save() plan, (done, _) = self.run_with(fake) self.assertEqual(plan['operations'][0]['kind'], 'push') self.assertEqual(done, 1) self.assertEqual(fake.items['ha-1']['name'], 'Original') self.connection.entities = [{'id': 'todo.shopping', 'features': 1}] self.connection.save() item.name = 'Another edit' item.save() with patch('home_assistant.sync.get_items', side_effect=fake.get): blocked = preview(self.connection) self.assertFalse(blocked['operations']) self.assertTrue(blocked['issues']) def test_stale_preview_cannot_write(self): item = self.local('Apples') fake = FakeHomeAssistant() with patch('home_assistant.sync.get_items', side_effect=fake.get), \ patch('home_assistant.sync.add_item', side_effect=fake.add): digest = preview(self.connection)['digest'] item.name = 'Oranges' item.save() with self.assertRaisesRegex(ConnectionError, 'changed after the preview'): confirm_and_sync(self.connection, digest) self.assertEqual(fake.calls, []) def test_preview_page_requires_signed_confirmation(self): self.client.force_login(self.user) self.local('Bananas') fake = FakeHomeAssistant() with patch('home_assistant.sync.get_items', side_effect=fake.get): response = self.client.get(reverse('home_assistant:preview')) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Bananas') bad = self.client.post(reverse('home_assistant:preview'), {'preview_token': 'invalid'}) self.assertEqual(bad.status_code, 302) self.assertEqual(fake.calls, []) def test_pending_addition_can_only_be_reset_after_checked_absent(self): item = self.local('Oats') mapping = HomeAssistantItemMap.objects.create(connection=self.connection, entity_id='todo.shopping', grocery=item, pending_create=True) self.client.force_login(self.user) with patch('home_assistant.sync.get_items', return_value={}): response = self.client.get(reverse('home_assistant:preview')) token = response.context['preview_token'] refused = self.client.post(reverse('home_assistant:preview'), { 'action': 'reset-pending', 'mapping_id': mapping.pk, 'preview_token': token, }) self.assertEqual(refused.status_code, 302) self.assertTrue(HomeAssistantItemMap.objects.filter(pk=mapping.pk).exists()) reset = self.client.post(reverse('home_assistant:preview'), { 'action': 'reset-pending', 'mapping_id': mapping.pk, 'checked_absent': 'yes', 'preview_token': token, }) self.assertEqual(reset.status_code, 302) self.assertFalse(HomeAssistantItemMap.objects.filter(pk=mapping.pk).exists()) def test_auto_sync_preferences_and_due_run_are_recorded(self): self.client.force_login(self.user) self.connection.initial_sync_confirmed = True self.connection.save(update_fields=['initial_sync_confirmed', 'updated_at']) self.client.post(reverse('home_assistant:settings'), { 'action': 'sync-options', 'direction': 'both', 'conflict_winner': 'ha', 'sync_interval_minutes': '5', 'auto_sync_enabled': 'on', }) self.connection.refresh_from_db() self.assertTrue(self.connection.auto_sync_enabled) self.assertEqual(self.connection.sync_interval_minutes, '5') self.connection.task_entity_id = 'todo.tasks' self.connection.task_initial_sync_confirmed = True self.connection.entities.append({'id': 'todo.tasks', 'features': 85}) self.connection.save(update_fields=['task_entity_id', 'task_initial_sync_confirmed', 'entities', 'updated_at']) fake = FakeHomeAssistant() with patch('home_assistant.sync.get_items', side_effect=fake.get), \ patch('home_assistant.task_sync.get_items', side_effect=fake.get): result = run_due_syncs() self.assertEqual(result, {'attempted': 2, 'succeeded': 2, 'failed': 0}) runs = HomeAssistantSyncRun.objects.filter(connection=self.connection) self.assertEqual(runs.count(), 2) self.assertTrue(all(run.succeeded and run.automatic for run in runs)) self.connection.refresh_from_db() self.assertIsNotNone(self.connection.next_sync_at) self.assertEqual(self.connection.consecutive_sync_failures, 0) def test_automatic_retries_stop_after_five_consecutive_failures(self): self.connection.auto_sync_enabled = True self.connection.sync_interval_minutes = '5' self.connection.consecutive_sync_failures = 4 self.connection.save() _schedule_after_failure(self.connection, ConnectionError('Home Assistant is unreachable.'), True) self.connection.refresh_from_db() self.assertFalse(self.connection.auto_sync_enabled) self.assertIsNone(self.connection.next_sync_at) self.assertEqual(self.connection.consecutive_sync_failures, 5) run = self.connection.sync_runs.first() self.assertIn('disabled after five', run.summary) def test_task_sync_maps_due_description_and_completion_without_losing_planner_fields(self): local = Task.objects.create(owner=self.user, title='Read a book', description='Chapter 4', scheduled_for='2026-11-02', priority=Task.Priority.HIGH, is_completed=True, is_outdoor=True, weather_profile=Task.WeatherProfile.SUNNY) self.connection.task_entity_id = 'todo.tasks' self.connection.entities.append({'id': 'todo.tasks', 'features': 85}) self.connection.save() remote = FakeTaskHomeAssistant([{'uid': 'remote-1', 'name': 'Pay a bill', 'status': 'completed', 'due': '2026-11-03', 'description': 'Online'}]) with patch('home_assistant.task_sync.get_items', side_effect=remote.get), \ patch('home_assistant.task_sync.add_item', side_effect=remote.add), \ patch('home_assistant.task_sync.update_item', side_effect=remote.update): plan = preview_tasks(self.connection) self.assertEqual({item['kind'] for item in plan['operations']}, {'task_export', 'task_import'}) done, _ = confirm_task_sync(self.connection, plan['digest']) self.assertEqual(done, 2) next_plan = preview_tasks(self.connection) self.assertFalse(next_plan['operations']) local.refresh_from_db() self.assertEqual((local.title, local.description, local.priority, local.is_outdoor, local.weather_profile, local.is_completed), ('Read a book', 'Chapter 4', Task.Priority.HIGH, True, Task.WeatherProfile.SUNNY, True)) imported = Task.objects.get(owner=self.user, title='Pay a bill') self.assertEqual((imported.description, imported.scheduled_for.isoformat(), imported.is_completed), ('Online', '2026-11-03', True)) self.assertEqual(remote.items['task-1']['status'], 'completed') def test_task_sync_skips_recurring_and_remote_tasks_without_due_dates(self): Task.objects.create(owner=self.user, title='Daily journal', scheduled_for='2026-10-22', is_recurring=True) self.connection.task_entity_id = 'todo.tasks' self.connection.entities.append({'id': 'todo.tasks', 'features': 85}) self.connection.save() remote = FakeTaskHomeAssistant([{'uid': 'remote-1', 'name': 'Unscheduled', 'status': 'needs_action', 'due': None, 'description': ''}]) with patch('home_assistant.task_sync.get_items', side_effect=remote.get): plan = preview_tasks(self.connection) self.assertFalse(plan['operations']) self.assertTrue(any('recurs' in issue for issue in plan['issues'])) self.assertTrue(any('requires a scheduled date' in issue for issue in plan['issues'])) def test_reopening_and_local_completion_both_propagate(self): fake = FakeHomeAssistant([{'uid': 'ha-1', 'name': 'Coffee', 'status': 'completed'}]) self.run_with(fake) item = GroceryItem.objects.get(user=self.user, name='Coffee') self.assertEqual(item.status, 'purchased') fake.items['ha-1']['status'] = 'needs_action' plan, _ = self.run_with(fake) self.assertEqual(plan['operations'][0]['kind'], 'pull') item.refresh_from_db() self.assertEqual(item.status, 'needed') item.status = 'purchased' item.save() plan, _ = self.run_with(fake) self.assertEqual(plan['operations'][0]['kind'], 'push') self.assertEqual(fake.items['ha-1']['status'], 'completed') def test_uncertain_addition_reconciles_uid_without_duplicate(self): item = self.local('Yoghurt') HomeAssistantItemMap.objects.create(connection=self.connection, entity_id='todo.shopping', grocery=item, pending_create=True) fake = FakeHomeAssistant([{'uid': 'ha-created', 'name': 'Yoghurt', 'status': 'needs_action'}]) plan, (done, _) = self.run_with(fake) self.assertEqual([action['kind'] for action in plan['operations']], ['reconcile']) self.assertEqual(done, 1) mapping = HomeAssistantItemMap.objects.get(connection=self.connection) self.assertEqual(mapping.ha_uid, 'ha-created') self.assertEqual(fake.calls, [])