Skip to content

Home Information - Your home, your data, organized.

Python

Test-suite performance pass (#335)

Tony C72f9aaf08737
diff --git a/src/hi/apps/alert/tests/test_alert_manager.py b/src/hi/apps/alert/tests/test_alert_manager.py
index 15e47321..ea4059cd 100644
--- a/src/hi/apps/alert/tests/test_alert_manager.py
+++ b/src/hi/apps/alert/tests/test_alert_manager.py
@@ -6,7 +6,7 @@ from hi.apps.alert.alert_manager import AlertManager, AlertMaintenanceResult
from hi.apps.alert.alarm import Alarm
from hi.apps.alert.enums import AlarmLevel, AlarmSource
from hi.apps.security.enums import SecurityLevel
-from hi.testing.async_task_utils import AsyncTaskTestCase
+from hi.testing.async_task_utils import AsyncTaskFastTestCase
from hi.testing.base_test_case import BaseTestCase
logging.disable(logging.CRITICAL)
@@ -225,7 +225,7 @@ class TestAlertMaintenanceResult(BaseTestCase):
self.assertEqual(result.total_alerts_removed, 5)
-class TestAlertManagerMaintenance(AsyncTaskTestCase):
+class TestAlertManagerMaintenance(AsyncTaskFastTestCase):
"""Test AlertManager periodic maintenance with new result tracking."""
def setUp(self):
diff --git a/src/hi/apps/attribute/tests/test_models.py b/src/hi/apps/attribute/tests/test_models.py
index 435bf004..1cb5bca9 100644
--- a/src/hi/apps/attribute/tests/test_models.py
+++ b/src/hi/apps/attribute/tests/test_models.py
@@ -1,13 +1,11 @@
import json
import logging
import uuid
-from io import BytesIO
from unittest.mock import patch, call
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
-from PIL import Image
from hi.apps.attribute.models import AttributeModel
from hi.apps.attribute.enums import AttributeValueType, AttributeType
@@ -29,22 +27,6 @@ class ConcreteAttributeModel(AttributeModel):
class TestAttributeModel(BaseTestCase):
- @staticmethod
- def _create_valid_png_image_bytes(size=(128, 96)):
- image = Image.new('RGB', size=size, color=(24, 120, 220))
- image_bytes = BytesIO()
- image.save(image_bytes, format='PNG')
- return image_bytes.getvalue()
-
- @staticmethod
- def _create_valid_pdf_bytes():
- try:
- image = Image.new('RGB', size=(360, 220), color=(255, 255, 255))
- pdf_bytes = BytesIO()
- image.save(pdf_bytes, format='PDF')
- return pdf_bytes.getvalue()
- except Exception:
- return None
def test_attribute_model_enum_property_conversions(self):
"""Test enum property conversions - custom business logic."""
@@ -227,7 +209,7 @@ class TestAttributeModel(BaseTestCase):
source_path = 'test_attributes/camera_snapshot.png'
default_storage.save(
source_path,
- ContentFile(self._create_valid_png_image_bytes(size=(900, 600)))
+ ContentFile(self.create_test_png_bytes())
)
attr = ConcreteAttributeModel(
@@ -270,13 +252,9 @@ class TestAttributeModel(BaseTestCase):
def test_generate_thumbnail_best_effort_pdf_success(self):
"""Test thumbnail generation from first page of a PDF file."""
- pdf_bytes = self._create_valid_pdf_bytes()
- if not pdf_bytes:
- self.skipTest('Unable to generate test PDF bytes in this environment')
-
with self.isolated_media_root():
source_path = 'test_attributes/manual.pdf'
- default_storage.save(source_path, ContentFile(pdf_bytes))
+ default_storage.save(source_path, ContentFile(self.create_test_pdf_bytes()))
attr = ConcreteAttributeModel(
name='manual',
@@ -301,7 +279,7 @@ class TestAttributeModel(BaseTestCase):
source_path = 'test_attributes/lazy_view.png'
default_storage.save(
source_path,
- ContentFile(self._create_valid_png_image_bytes()),
+ ContentFile(self.create_test_png_bytes()),
)
attr = ConcreteAttributeModel(
@@ -329,7 +307,7 @@ class TestAttributeModel(BaseTestCase):
source_path = 'test_attributes/already_done.png'
default_storage.save(
source_path,
- ContentFile(self._create_valid_png_image_bytes()),
+ ContentFile(self.create_test_png_bytes()),
)
attr = ConcreteAttributeModel(
diff --git a/src/hi/apps/attribute/tests/test_thumbnail_command.py b/src/hi/apps/attribute/tests/test_thumbnail_command.py
index cdb33c1f..1bca6a2e 100644
--- a/src/hi/apps/attribute/tests/test_thumbnail_command.py
+++ b/src/hi/apps/attribute/tests/test_thumbnail_command.py
@@ -1,11 +1,9 @@
-from io import BytesIO, StringIO
+from io import StringIO
from django.core.files.base import ContentFile
from django.core.management import call_command
from django.core.files.storage import default_storage
-from PIL import Image
-
from hi.apps.entity.enums import EntityType
from hi.testing.base_test_case import BaseTestCase
from hi.apps.entity.models import Entity, EntityAttribute
@@ -14,13 +12,6 @@ from hi.apps.attribute.enums import AttributeType, AttributeValueType
class TestBackfillAttributeThumbnailsCommand(BaseTestCase):
- @staticmethod
- def _create_valid_png_image_bytes(size=(320, 240)):
- image = Image.new('RGB', size=size, color=(80, 120, 200))
- image_bytes = BytesIO()
- image.save(image_bytes, format='PNG')
- return image_bytes.getvalue()
-
def _create_entity(self):
return Entity.objects.create(
name='Thumbnail Command Test Entity',
@@ -42,7 +33,7 @@ class TestBackfillAttributeThumbnailsCommand(BaseTestCase):
name='retroactive_image',
value='Retroactive image',
file_value=ContentFile(
- self._create_valid_png_image_bytes(),
+ self.create_test_png_bytes(),
name='retroactive-image.png',
),
file_mime_type='image/png',
@@ -66,7 +57,7 @@ class TestBackfillAttributeThumbnailsCommand(BaseTestCase):
name='retroactive_image_dry_run',
value='Retroactive image dry-run',
file_value=ContentFile(
- self._create_valid_png_image_bytes(),
+ self.create_test_png_bytes(),
name='retroactive-image-dry-run.png',
),
file_mime_type='image/png',
diff --git a/src/hi/apps/config/tests/test_settings_manager.py b/src/hi/apps/config/tests/test_settings_manager.py
index 7a394587..a4f40549 100644
--- a/src/hi/apps/config/tests/test_settings_manager.py
+++ b/src/hi/apps/config/tests/test_settings_manager.py
@@ -4,7 +4,7 @@ import threading
import time
from hi.apps.config.models import Subsystem, SubsystemAttribute
-from hi.apps.config.settings_manager import SettingsManager, _settings_processor
+from hi.apps.config.settings_manager import SettingsManager
from hi.apps.config.setting_enums import SettingEnum, SettingDefinition
from hi.apps.attribute.enums import AttributeValueType
from hi.testing.base_test_case import BaseTestCase
@@ -267,12 +267,15 @@ class TestSettingsManager(BaseTestCase):
self.assertTrue(True) # Lock acquisition succeeded
def test_no_deadlock_on_setting_save(self):
- """Test that setting a value doesn't cause deadlock from signal-triggered reload."""
-
+ """Test that setting a value doesn't cause deadlock from signal-triggered reload.
+
+ The background reload via ``_settings_processor`` is scheduled
+ from ``transaction.on_commit``, which doesn't fire under
+ ``TestCase`` (the wrapping transaction rolls back), so this
+ test only asserts the synchronous no-deadlock contract."""
manager = SettingsManager()
manager.ensure_initialized()
-
- # Create test subsystem and attribute first
+
subsystem = Subsystem.objects.create(
name='Deadlock Test Subsystem',
subsystem_key='deadlock_test',
@@ -284,46 +287,17 @@ class TestSettingsManager(BaseTestCase):
value_type=AttributeValueType.TEXT,
value='deadlock_initial_value',
)
-
- # Reload to pick up the new setting
manager.reload()
-
- # Track if the background reload completes
- reload_completed = threading.Event()
- original_callback = _settings_processor.callback_func
-
- def tracking_callback():
- try:
- original_callback()
- finally:
- reload_completed.set()
-
- # Patch the processor callback to track completion
- _settings_processor.callback_func = tracking_callback
-
- try:
- # This operation previously caused deadlock
- # The signal handler would try to reload while the lock was held
- start_time = time.time()
- manager.set_setting_value(TestSetting.TEST_SETTING, 'deadlock_test_value')
-
- # Verify the operation completed quickly (no deadlock)
- elapsed = time.time() - start_time
- self.assertLess(elapsed, 1.0, "set_setting_value took too long, possible deadlock")
-
- # Verify the delayed reload was scheduled and completes
- # Give a bit more time for the Timer to execute
- reload_completed.wait(timeout=3.0)
- # The main test is that set_setting_value completed without deadlock
- # Background reload completion is secondary (timing-dependent in tests)
- if not reload_completed.is_set():
- # This is just a warning - the important thing is no deadlock occurred
- pass
-
- # Verify the setting was actually saved
- self.assertEqual(manager.get_setting_value(TestSetting.TEST_SETTING), 'deadlock_test_value')
-
- finally:
- # Restore original callback
- _settings_processor.callback_func = original_callback
+
+ # This operation previously caused deadlock: the signal handler
+ # tried to reload while the manager's lock was held.
+ start_time = time.time()
+ manager.set_setting_value(TestSetting.TEST_SETTING, 'deadlock_test_value')
+ elapsed = time.time() - start_time
+ self.assertLess(elapsed, 1.0, "set_setting_value took too long, possible deadlock")
+
+ # The in-memory map is updated synchronously by set_setting_value,
+ # so it reflects the new value regardless of whether the
+ # background reload eventually runs.
+ self.assertEqual(manager.get_setting_value(TestSetting.TEST_SETTING), 'deadlock_test_value')
return
diff --git a/src/hi/apps/entity/tests/test_attribute_view_integration.py b/src/hi/apps/entity/tests/test_attribute_view_integration.py
index 7d27a261..5f7cecd9 100644
--- a/src/hi/apps/entity/tests/test_attribute_view_integration.py
+++ b/src/hi/apps/entity/tests/test_attribute_view_integration.py
@@ -6,10 +6,7 @@ including handler/renderer integration, session dependencies, and
antinode response patterns.
"""
import logging
-import tempfile
-import shutil
from django.urls import reverse
-from django.test import override_settings
from hi.apps.entity.tests.synthetic_data import EntityAttributeSyntheticData
from hi.apps.entity.models import EntityAttribute
@@ -25,10 +22,7 @@ class TestEntityAttributeViewIntegration(DualModeViewTestCase):
def setUp(self):
super().setUp()
- # Set up isolated MEDIA_ROOT for file upload tests
- self._temp_media_dir = tempfile.mkdtemp()
- self._settings_patcher = override_settings(MEDIA_ROOT=self._temp_media_dir)
- self._settings_patcher.enable()
+ self.enterContext(self.in_memory_media_storage())
# Create entity with attributes for testing
self.entity = EntityAttributeSyntheticData.create_test_entity(
@@ -57,14 +51,6 @@ class TestEntityAttributeViewIntegration(DualModeViewTestCase):
# Set required session state for views
self.setSessionViewMode(ViewMode.EDIT)
- def tearDown(self):
- # Clean up the temporary media directory and settings
- if hasattr(self, '_settings_patcher'):
- self._settings_patcher.disable()
- if hasattr(self, '_temp_media_dir'):
- shutil.rmtree(self._temp_media_dir, ignore_errors=True)
- super().tearDown()
-
def test_entity_edit_view_get_request_success(self):
"""Test GET request to entity edit view returns correct template and context - initial rendering."""
url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})
diff --git a/src/hi/apps/entity/tests/test_entity_attribute_framework.py b/src/hi/apps/entity/tests/test_entity_attribute_framework.py
index 5d7aa6fd..48354cef 100644
--- a/src/hi/apps/entity/tests/test_entity_attribute_framework.py
+++ b/src/hi/apps/entity/tests/test_entity_attribute_framework.py
@@ -12,11 +12,8 @@ Following project testing guidelines:
- Test meaningful Entity-specific edge cases and workflows
"""
import logging
-import tempfile
-import shutil
from django.core.files.uploadedfile import SimpleUploadedFile
-from django.test import override_settings
from hi.apps.attribute.tests.attribute_framework_test_base import (
AttributeEditFormHandlerTestMixin,
@@ -40,18 +37,8 @@ class EntityAttributeEditFormHandlerTest(AttributeEditFormHandlerTestMixin, Base
def setUp(self):
super().setUp()
- # Set up isolated MEDIA_ROOT for file upload tests
- self._temp_media_dir = tempfile.mkdtemp()
- self._settings_patcher = override_settings(MEDIA_ROOT=self._temp_media_dir)
- self._settings_patcher.enable()
+ self.enterContext(self.in_memory_media_storage())
- def tearDown(self):
- # Clean up the temporary media directory and settings
- if hasattr(self, '_settings_patcher'):
- self._settings_patcher.disable()
- if hasattr(self, '_temp_media_dir'):
- shutil.rmtree(self._temp_media_dir, ignore_errors=True)
- super().tearDown()
def create_owner_instance(self, **kwargs):
"""Create Entity instance for testing."""
@@ -381,18 +368,8 @@ class EntityAttributeViewMixinTest(AttributeViewMixinTestMixin, BaseTestCase):
def setUp(self):
super().setUp()
- # Set up isolated MEDIA_ROOT for file upload tests
- self._temp_media_dir = tempfile.mkdtemp()
- self._settings_patcher = override_settings(MEDIA_ROOT=self._temp_media_dir)
- self._settings_patcher.enable()
+ self.enterContext(self.in_memory_media_storage())
- def tearDown(self):
- # Clean up the temporary media directory and settings
- if hasattr(self, '_settings_patcher'):
- self._settings_patcher.disable()
- if hasattr(self, '_temp_media_dir'):
- shutil.rmtree(self._temp_media_dir, ignore_errors=True)
- super().tearDown()
def create_owner_instance(self, **kwargs):
"""Create Entity instance for testing."""
diff --git a/src/hi/apps/entity/tests/test_file_upload_integration.py b/src/hi/apps/entity/tests/test_file_upload_integration.py
index 11021ce0..55ff7b51 100644
--- a/src/hi/apps/entity/tests/test_file_upload_integration.py
+++ b/src/hi/apps/entity/tests/test_file_upload_integration.py
@@ -5,9 +5,7 @@ Tests file storage patterns, upload path generation, file cleanup operations,
and cross-owner file handling consistency using AttributeItemEditContext pattern.
"""
import logging
-import tempfile
from django.core.files.uploadedfile import SimpleUploadedFile
-from django.test import override_settings
from hi.apps.entity.tests.synthetic_data import EntityAttributeSyntheticData
from hi.apps.entity.models import EntityAttribute
@@ -19,26 +17,14 @@ logging.disable(logging.CRITICAL)
class TestFileUploadContextIntegration(BaseTestCase):
"""Test file upload operations with AttributeItemEditContext integration."""
-
+
def setUp(self):
super().setUp()
- # Create temporary media root for this test class
- self._temp_media_dir = tempfile.mkdtemp()
- self._settings_patcher = override_settings(MEDIA_ROOT=self._temp_media_dir)
- self._settings_patcher.enable()
-
+ self.enterContext(self.in_memory_media_storage())
+
self.entity = EntityAttributeSyntheticData.create_test_entity(
name="File Upload Test Entity"
)
-
- def tearDown(self):
- # Clean up the temporary media directory and settings
- if hasattr(self, '_settings_patcher'):
- self._settings_patcher.disable()
- if hasattr(self, '_temp_media_dir'):
- import shutil
- shutil.rmtree(self._temp_media_dir, ignore_errors=True)
- super().tearDown()
def test_file_attribute_creation_with_context(self):
"""Test file attribute creation provides correct context - file lifecycle integration."""
diff --git a/src/hi/apps/entity/tests/test_views.py b/src/hi/apps/entity/tests/test_views.py
index 1f64be05..cf691c8e 100644
--- a/src/hi/apps/entity/tests/test_views.py
+++ b/src/hi/apps/entity/tests/test_views.py
@@ -1,11 +1,8 @@
import logging
-import tempfile
-import shutil
from unittest.mock import patch
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db import transaction
-from django.test import override_settings
from django.urls import reverse
from hi.apps.attribute.enums import AttributeValueType
@@ -33,10 +30,7 @@ class TestEntityEditView(DualModeViewTestCase):
def setUp(self):
super().setUp()
- # Set up isolated MEDIA_ROOT for file upload tests
- self._temp_media_dir = tempfile.mkdtemp()
- self._settings_patcher = override_settings(MEDIA_ROOT=self._temp_media_dir)
- self._settings_patcher.enable()
+ self.enterContext(self.in_memory_media_storage())
# Create test data using synthetic data helper
self.entity = EntityAttributeSyntheticData.create_test_entity(
@@ -53,13 +47,6 @@ class TestEntityEditView(DualModeViewTestCase):
name='manual'
)
- def tearDown(self):
- # Clean up the temporary media directory and settings
- if hasattr(self, '_settings_patcher'):
- self._settings_patcher.disable()
- if hasattr(self, '_temp_media_dir'):
- shutil.rmtree(self._temp_media_dir, ignore_errors=True)
- super().tearDown()
def test_get_modal_displays_entity_edit_form(self):
"""Test that GET request displays entity edit modal with forms."""
@@ -527,10 +514,7 @@ class TestEntityAttributeUploadView(SyncViewTestCase):
def setUp(self):
super().setUp()
- # Set up isolated MEDIA_ROOT for file upload tests
- self._temp_media_dir = tempfile.mkdtemp()
- self._settings_patcher = override_settings(MEDIA_ROOT=self._temp_media_dir)
- self._settings_patcher.enable()
+ self.enterContext(self.in_memory_media_storage())
# Create test entity
self.entity = Entity.objects.create(
@@ -540,13 +524,6 @@ class TestEntityAttributeUploadView(SyncViewTestCase):
entity_type_str=str(EntityType.CAMERA)
)
- def tearDown(self):
- # Clean up the temporary media directory and settings
- if hasattr(self, '_settings_patcher'):
- self._settings_patcher.disable()
- if hasattr(self, '_temp_media_dir'):
- shutil.rmtree(self._temp_media_dir, ignore_errors=True)
- super().tearDown()
def test_post_valid_file_upload(self):
"""Test successful file upload using real form."""
@@ -854,23 +831,13 @@ class TestEntityEditViewFileUploadIntegration(DualModeViewTestCase):
def setUp(self):
super().setUp()
- # Set up isolated MEDIA_ROOT for file upload tests
- self._temp_media_dir = tempfile.mkdtemp()
- self._settings_patcher = override_settings(MEDIA_ROOT=self._temp_media_dir)
- self._settings_patcher.enable()
+ self.enterContext(self.in_memory_media_storage())
self.entity = EntityAttributeSyntheticData.create_test_entity(
name='File Upload Test Entity',
entity_type_str=str(EntityType.CAMERA)
)
- def tearDown(self):
- # Clean up the temporary media directory and settings
- if hasattr(self, '_settings_patcher'):
- self._settings_patcher.disable()
- if hasattr(self, '_temp_media_dir'):
- shutil.rmtree(self._temp_media_dir, ignore_errors=True)
- super().tearDown()
def test_file_upload_creates_attribute_and_updates_dom(self):
"""Test complete file upload flow from upload to DOM update."""
diff --git a/src/hi/apps/location/edit/tests/test_views.py b/src/hi/apps/location/edit/tests/test_views.py
index ccf81bd6..d5058533 100644
--- a/src/hi/apps/location/edit/tests/test_views.py
+++ b/src/hi/apps/location/edit/tests/test_views.py
@@ -1,9 +1,6 @@
import logging
-import tempfile
-import shutil
from django.core.files.uploadedfile import SimpleUploadedFile
-from django.test import override_settings
from django.urls import reverse
from hi.apps.collection.collection_manager import CollectionManager
@@ -29,20 +26,10 @@ class TestLocationAddView(DualModeViewTestCase):
# Set edit mode (required by decorator)
self.setSessionViewMode(ViewMode.EDIT)
- # Set up isolated MEDIA_ROOT for file upload tests
- self._temp_media_dir = tempfile.mkdtemp()
- self._settings_patcher = override_settings(MEDIA_ROOT=self._temp_media_dir)
- self._settings_patcher.enable()
+ self.enterContext(self.in_memory_media_storage())
def tearDown(self):
"""Clean up singletons when using real objects instead of mocks."""
- # Clean up the temporary media directory and settings
- if hasattr(self, '_settings_patcher'):
- self._settings_patcher.disable()
- if hasattr(self, '_temp_media_dir'):
- shutil.rmtree(self._temp_media_dir, ignore_errors=True)
-
- # Reset singleton managers to ensure clean state between tests
try:
LocationManager._instance = None
except ImportError:
@@ -174,15 +161,9 @@ class TestLocationAddFirstView(DualModeViewTestCase):
def setUp(self):
super().setUp()
self.setSessionViewMode(ViewMode.EDIT)
- self._temp_media_dir = tempfile.mkdtemp()
- self._settings_patcher = override_settings(MEDIA_ROOT=self._temp_media_dir)
- self._settings_patcher.enable()
+ self.enterContext(self.in_memory_media_storage())
def tearDown(self):
- if hasattr(self, '_settings_patcher'):
- self._settings_patcher.disable()
- if hasattr(self, '_temp_media_dir'):
- shutil.rmtree(self._temp_media_dir, ignore_errors=True)
LocationManager._instance = None
CollectionManager._instance = None
EntityManager._instance = None
@@ -223,9 +204,7 @@ class TestLocationSvgReplaceView(DualModeViewTestCase):
self.setSessionViewMode(ViewMode.EDIT)
# Create temporary media root for this test class
- self._temp_media_dir = tempfile.mkdtemp()
- self._settings_patcher = override_settings(MEDIA_ROOT=self._temp_media_dir)
- self._settings_patcher.enable()
+ self.enterContext(self.in_memory_media_storage())
# Create test location
self.location = Location.objects.create(
@@ -234,14 +213,6 @@ class TestLocationSvgReplaceView(DualModeViewTestCase):
svg_view_box_str='0 0 100 100'
)
- def tearDown(self):
- # Clean up the temporary media directory and settings
- if hasattr(self, '_settings_patcher'):
- self._settings_patcher.disable()
- if hasattr(self, '_temp_media_dir'):
- import shutil
- shutil.rmtree(self._temp_media_dir, ignore_errors=True)
- super().tearDown()
def test_get_svg_replace_form(self):
"""Test getting SVG replace form."""
diff --git a/src/hi/apps/location/tests/test_location_attribute_framework.py b/src/hi/apps/location/tests/test_location_attribute_framework.py
index e723e27e..137e01ab 100644
--- a/src/hi/apps/location/tests/test_location_attribute_framework.py
+++ b/src/hi/apps/location/tests/test_location_attribute_framework.py
@@ -12,11 +12,8 @@ Following project testing guidelines:
- Test meaningful Location-specific edge cases and workflows
"""
import logging
-import tempfile
-import shutil
from django.core.files.uploadedfile import SimpleUploadedFile
-from django.test import override_settings
from hi.apps.attribute.tests.attribute_framework_test_base import (
AttributeEditFormHandlerTestMixin,
@@ -40,18 +37,8 @@ class LocationAttributeEditFormHandlerTest(AttributeEditFormHandlerTestMixin, Ba
def setUp(self):
super().setUp()
- # Set up isolated MEDIA_ROOT for file upload tests
- self._temp_media_dir = tempfile.mkdtemp()
- self._settings_patcher = override_settings(MEDIA_ROOT=self._temp_media_dir)
- self._settings_patcher.enable()
+ self.enterContext(self.in_memory_media_storage())
- def tearDown(self):
- # Clean up the temporary media directory and settings
- if hasattr(self, '_settings_patcher'):
- self._settings_patcher.disable()
- if hasattr(self, '_temp_media_dir'):
- shutil.rmtree(self._temp_media_dir, ignore_errors=True)
- super().tearDown()
def create_owner_instance(self, **kwargs):
"""Create Location instance for testing."""
@@ -465,18 +452,8 @@ class LocationAttributeViewMixinTest(AttributeViewMixinTestMixin, BaseTestCase):
def setUp(self):
super().setUp()
- # Set up isolated MEDIA_ROOT for file upload tests
- self._temp_media_dir = tempfile.mkdtemp()
- self._settings_patcher = override_settings(MEDIA_ROOT=self._temp_media_dir)
- self._settings_patcher.enable()
+ self.enterContext(self.in_memory_media_storage())
- def tearDown(self):
- # Clean up the temporary media directory and settings
- if hasattr(self, '_settings_patcher'):
- self._settings_patcher.disable()
- if hasattr(self, '_temp_media_dir'):
- shutil.rmtree(self._temp_media_dir, ignore_errors=True)
- super().tearDown()
def create_owner_instance(self, **kwargs):
"""Create Location instance for testing."""
diff --git a/src/hi/apps/monitor/tests/test_monitor_manager.py b/src/hi/apps/monitor/tests/test_monitor_manager.py
index 63ada8de..271cecbc 100644
--- a/src/hi/apps/monitor/tests/test_monitor_manager.py
+++ b/src/hi/apps/monitor/tests/test_monitor_manager.py
@@ -4,7 +4,7 @@ import threading
from unittest.mock import Mock, patch, MagicMock
from django.test import override_settings
-from hi.testing.async_task_utils import AsyncTaskTestCase
+from hi.testing.async_task_utils import AsyncTaskFastTestCase
from hi.apps.monitor.monitor_manager import AppMonitorManager
from hi.apps.monitor.periodic_monitor import PeriodicMonitor
@@ -30,7 +30,7 @@ class TestMonitor2(PeriodicMonitor):
pass
-class TestAppMonitorManager(AsyncTaskTestCase):
+class TestAppMonitorManager(AsyncTaskFastTestCase):
"""Test AppMonitorManager singleton and async behavior.
Uses AsyncTaskTestCase for async compatibility.
diff --git a/src/hi/apps/monitor/tests/test_periodic_monitor.py b/src/hi/apps/monitor/tests/test_periodic_monitor.py
index 2ed912fe..3fbd835f 100644
--- a/src/hi/apps/monitor/tests/test_periodic_monitor.py
+++ b/src/hi/apps/monitor/tests/test_periodic_monitor.py
@@ -1,7 +1,7 @@
import asyncio
import logging
-from hi.testing.async_task_utils import AsyncTaskTestCase
+from hi.testing.async_task_utils import AsyncTaskFastTestCase
from hi.apps.monitor.periodic_monitor import PeriodicMonitor
from hi.apps.system.provider_info import ProviderInfo
@@ -40,7 +40,7 @@ class ConcreteTestMonitor(PeriodicMonitor):
await super().cleanup()
-class TestPeriodicMonitor(AsyncTaskTestCase):
+class TestPeriodicMonitor(AsyncTaskFastTestCase):
"""Test PeriodicMonitor async lifecycle and behavior.
Uses AsyncTaskTestCase to avoid database locking issues with async code.
diff --git a/src/hi/apps/notify/tests/test_notification_manager.py b/src/hi/apps/notify/tests/test_notification_manager.py
index fabcc84b..53d8b758 100644
--- a/src/hi/apps/notify/tests/test_notification_manager.py
+++ b/src/hi/apps/notify/tests/test_notification_manager.py
@@ -1,6 +1,6 @@
import logging
from unittest.mock import AsyncMock, Mock, patch
-from hi.testing.async_task_utils import AsyncTaskTestCase
+from hi.testing.async_task_utils import AsyncTaskFastTestCase
from hi.apps.notify.notification_manager import NotificationManager
from hi.apps.notify.settings import NotifySetting
@@ -11,7 +11,7 @@ from hi.apps.notify.transient_models import NotificationMaintenanceResult as Mai
logging.disable(logging.CRITICAL)
-class AsyncManagerTestCase(AsyncTaskTestCase):
+class AsyncManagerTestCase(AsyncTaskFastTestCase):
"""Base class for async manager tests with proper infrastructure."""
diff --git a/src/hi/apps/profiles/tests/test_profile_manager.py b/src/hi/apps/profiles/tests/test_profile_manager.py
index 04632bd0..507b1f23 100644
--- a/src/hi/apps/profiles/tests/test_profile_manager.py
+++ b/src/hi/apps/profiles/tests/test_profile_manager.py
@@ -1,5 +1,4 @@
import logging
-import tempfile
from pathlib import Path
from hi.apps.profiles.profile_manager import ProfileManager
@@ -157,21 +156,18 @@ class TestProfileManager(BaseTestCase):
def test_single_story_profile_loading(self):
"""Test loading SINGLE_STORY profile from actual JSON data."""
- with tempfile.TemporaryDirectory() as temp_media_root:
- with self.settings(MEDIA_ROOT=temp_media_root):
- self._test_profile_loading(ProfileType.SINGLE_STORY)
+ with self.in_memory_media_storage():
+ self._test_profile_loading(ProfileType.SINGLE_STORY)
def test_two_story_profile_loading(self):
"""Test loading TWO_STORY profile from actual JSON data."""
- with tempfile.TemporaryDirectory() as temp_media_root:
- with self.settings(MEDIA_ROOT=temp_media_root):
- self._test_profile_loading(ProfileType.TWO_STORY)
+ with self.in_memory_media_storage():
+ self._test_profile_loading(ProfileType.TWO_STORY)
def test_apartment_profile_loading(self):
"""Test loading APARTMENT profile from actual JSON data."""
- with tempfile.TemporaryDirectory() as temp_media_root:
- with self.settings(MEDIA_ROOT=temp_media_root):
- self._test_profile_loading(ProfileType.APARTMENT)
+ with self.in_memory_media_storage():
+ self._test_profile_loading(ProfileType.APARTMENT)
def test_profile_requires_empty_database(self):
"""Test that profile loading fails when database is not empty."""
@@ -218,29 +214,26 @@ class TestProfileManager(BaseTestCase):
def test_svg_template_rendering_to_media(self):
"""Test that profile loading renders SVG templates to MEDIA_ROOT files."""
- import os
+ from django.core.files.storage import default_storage
- with tempfile.TemporaryDirectory() as temp_media_root:
- with self.settings(MEDIA_ROOT=temp_media_root):
- stats = self.profile_manager.load_profile(ProfileType.SINGLE_STORY)
- self.assertTrue(stats.meets_minimum_requirements())
+ with self.in_memory_media_storage():
+ stats = self.profile_manager.load_profile(ProfileType.SINGLE_STORY)
+ self.assertTrue(stats.meets_minimum_requirements())
- locations = Location.objects.all()
- self.assertGreater(locations.count(), 0, "Should create locations")
+ locations = Location.objects.all()
+ self.assertGreater(locations.count(), 0, "Should create locations")
- for location in locations:
- self.assertIsNotNone(
- location.svg_fragment_filename,
- "Location should have SVG fragment filename")
- full_path = os.path.join(temp_media_root, location.svg_fragment_filename)
- self.assertTrue(
- os.path.exists(full_path),
- f"Rendered SVG should exist in MEDIA_ROOT: {full_path}")
- # Verify file has content
- with open(full_path, 'r') as f:
- content = f.read()
- self.assertGreater(len(content), 0,
- f"SVG file should not be empty: {full_path}")
+ for location in locations:
+ self.assertIsNotNone(
+ location.svg_fragment_filename,
+ "Location should have SVG fragment filename")
+ self.assertTrue(
+ default_storage.exists(location.svg_fragment_filename),
+ f"Rendered SVG should exist: {location.svg_fragment_filename}")
+ with default_storage.open(location.svg_fragment_filename, 'r') as f:
+ content = f.read()
+ self.assertGreater(len(content), 0,
+ f"SVG file should not be empty: {location.svg_fragment_filename}")
def test_real_profile_templates_exist(self):
"""Test that the real profile JSON files reference existing SVG templates."""
@@ -262,12 +255,10 @@ class TestProfileManager(BaseTestCase):
def test_profile_svg_template_error_handling(self):
"""Test error handling when SVG template references are invalid."""
- with tempfile.TemporaryDirectory() as temp_media_root:
- with self.settings(MEDIA_ROOT=temp_media_root):
- # Load real profile data and corrupt the template reference
- json_path = self.profile_manager._get_profile_json_path(ProfileType.SINGLE_STORY)
- profile_data = self.profile_manager._load_json_file(json_path)
- profile_data['locations'][0]['svg_template_name'] = 'profiles/svg/backgrounds/nonexistent.svg'
+ with self.in_memory_media_storage():
+ json_path = self.profile_manager._get_profile_json_path(ProfileType.SINGLE_STORY)
+ profile_data = self.profile_manager._load_json_file(json_path)
+ profile_data['locations'][0]['svg_template_name'] = 'profiles/svg/backgrounds/nonexistent.svg'
- with self.assertRaises(Exception):
- self.profile_manager._render_svg_templates(profile_data)
+ with self.assertRaises(Exception):
+ self.profile_manager._render_svg_templates(profile_data)
diff --git a/src/hi/apps/profiles/tests/test_profile_manager_error_handling.py b/src/hi/apps/profiles/tests/test_profile_manager_error_handling.py
index 369ee416..aba3684c 100644
--- a/src/hi/apps/profiles/tests/test_profile_manager_error_handling.py
+++ b/src/hi/apps/profiles/tests/test_profile_manager_error_handling.py
@@ -1,5 +1,4 @@
import logging
-import tempfile
from hi.apps.profiles.profile_manager import ProfileManager, ProfileLoadingStats
from hi.apps.entity.models import Entity, EntityPosition
@@ -23,10 +22,9 @@ class TestProfileManagerErrorHandling(BaseTestCase):
"""Test that a non-existent SVG template causes an error during rendering."""
malformed_data = self.data_generator.create_missing_svg_file_data()
- with tempfile.TemporaryDirectory() as temp_media_root:
- with self.settings(MEDIA_ROOT=temp_media_root):
- with self.assertRaises(Exception):
- self.profile_manager._render_svg_templates(malformed_data)
+ with self.in_memory_media_storage():
+ with self.assertRaises(Exception):
+ self.profile_manager._render_svg_templates(malformed_data)
def test_invalid_entity_types_individual_failure(self):
"""Test that invalid entity types cause individual entity creation failures."""
diff --git a/src/hi/apps/security/tests/test_security_monitor.py b/src/hi/apps/security/tests/test_security_monitor.py
index d0e74989..0962fda8 100644
--- a/src/hi/apps/security/tests/test_security_monitor.py
+++ b/src/hi/apps/security/tests/test_security_monitor.py
@@ -1,7 +1,7 @@
import logging
from unittest.mock import Mock, patch, AsyncMock
-from hi.testing.async_task_utils import AsyncTaskTestCase
+from hi.testing.async_task_utils import AsyncTaskFastTestCase
import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.security.enums import SecurityState
@@ -11,7 +11,7 @@ from hi.apps.security.settings import SecuritySetting
logging.disable(logging.CRITICAL)
-class TestSecurityMonitor(AsyncTaskTestCase):
+class TestSecurityMonitor(AsyncTaskFastTestCase):
"""Test SecurityMonitor async behavior and time-based transitions.
Uses AsyncTaskTestCase to avoid database locking issues with async code.
diff --git a/src/hi/apps/sense/tests/test_models.py b/src/hi/apps/sense/tests/test_models.py
index d814a6dc..486621b4 100644
--- a/src/hi/apps/sense/tests/test_models.py
+++ b/src/hi/apps/sense/tests/test_models.py
@@ -3,7 +3,6 @@ import logging
from datetime import datetime
from django.db import IntegrityError
-from django.test import TransactionTestCase
from django.utils import timezone
from hi.apps.sense.models import Sensor, SensorHistory
@@ -142,8 +141,9 @@ class TestSensor(BaseTestCase):
self.assertEqual(sensor.css_class, expected_css_class)
-class TestSensorHistory(TransactionTestCase):
- """Test SensorHistory model with database transactions."""
+class TestSensorHistory(BaseTestCase):
+ """SensorHistory model: default ordering, JSON details parsing,
+ index-backed query correctness, and related-name access."""
def setUp(self):
self.entity = Entity.objects.create(
diff --git a/src/hi/apps/sense/tests/test_sensor_history_manager.py b/src/hi/apps/sense/tests/test_sensor_history_manager.py
index d8ba39b9..5b47993e 100644
--- a/src/hi/apps/sense/tests/test_sensor_history_manager.py
+++ b/src/hi/apps/sense/tests/test_sensor_history_manager.py
@@ -5,7 +5,7 @@ from unittest.mock import patch
from asgiref.sync import sync_to_async
from django.utils import timezone
-from hi.testing.async_task_utils import AsyncTaskTestCase
+from hi.testing.async_task_utils import AsyncTaskFastTestCase, AsyncTaskTestCase
from hi.apps.entity.models import Entity, EntityState
from hi.apps.sense.models import Sensor, SensorHistory
@@ -16,7 +16,7 @@ from hi.integrations.transient_models import IntegrationKey
logging.disable(logging.CRITICAL)
-class AsyncSensorHistoryManagerTestCase(AsyncTaskTestCase):
+class AsyncSensorHistoryManagerTestCase(AsyncTaskFastTestCase):
"""Test SensorHistoryManager with proper async infrastructure."""
def setUp(self):
@@ -160,6 +160,38 @@ class AsyncSensorHistoryManagerTestCase(AsyncTaskTestCase):
self.assertEqual(history.source_image_url, response.source_image_url)
self.assertIn('key', history.detail_attrs)
+
+class AsyncSensorHistoryManagerCrossConnectionTestCase(AsyncTaskTestCase):
+ """Tests that exercise add_to_sensor_history end-to-end (real DB
+ writes via sync_to_async). Needs TransactionTestCase semantics
+ so worker threads see the setUp Sensor row."""
+
+ def setUp(self):
+ super().setUp()
+ SensorHistoryManager._instances = {}
+ self.manager = SensorHistoryManager()
+
+ self.entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='LIGHT',
+ )
+ self.entity_state = EntityState.objects.create(
+ entity=self.entity,
+ entity_state_type_str='ON_OFF',
+ )
+ self.sensor = Sensor.objects.create(
+ name='Test Sensor',
+ entity_state=self.entity_state,
+ sensor_type_str='DEFAULT',
+ integration_id='test_sensor_123',
+ integration_name='test_integration',
+ persist_history=True,
+ )
+ self.integration_key = IntegrationKey(
+ integration_id='test_sensor_123',
+ integration_name='test_integration',
+ )
+
def test_add_sensor_history_populates_sensor_history_id(self):
"""Test that add_to_sensor_history populates sensor_history_id in SensorResponse objects."""
# Create sensor with history disabled
@@ -224,7 +256,7 @@ class AsyncSensorHistoryManagerTestCase(AsyncTaskTestCase):
def test_concurrent_history_addition_thread_safety(self):
"""Test manager handles concurrent access safely."""
import threading
-
+
from django.utils import timezone
responses = [
SensorResponse(
@@ -234,9 +266,9 @@ class AsyncSensorHistoryManagerTestCase(AsyncTaskTestCase):
sensor=self.sensor
) for i in range(5)
]
-
+
results = []
-
+
def worker(response_list):
async def async_worker():
await self.manager.add_to_sensor_history(response_list)
@@ -245,7 +277,7 @@ class AsyncSensorHistoryManagerTestCase(AsyncTaskTestCase):
sensor=self.sensor
).count)()
results.append(count)
-
+
# Run in separate event loop for each thread
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
@@ -253,15 +285,16 @@ class AsyncSensorHistoryManagerTestCase(AsyncTaskTestCase):
loop.run_until_complete(async_worker())
finally:
loop.close()
-
+
threads = [threading.Thread(target=worker, args=([resp],)) for resp in responses]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
-
+
# All operations should succeed
self.assertEqual(len(results), 5)
# Total records should equal number of operations
final_count = SensorHistory.objects.filter(sensor=self.sensor).count()
self.assertEqual(final_count, 5)
+
diff --git a/src/hi/apps/sense/tests/test_sensor_response_manager.py b/src/hi/apps/sense/tests/test_sensor_response_manager.py
index 44aa17b1..3056cb4e 100644
--- a/src/hi/apps/sense/tests/test_sensor_response_manager.py
+++ b/src/hi/apps/sense/tests/test_sensor_response_manager.py
@@ -2,7 +2,7 @@ import logging
from datetime import datetime
from unittest.mock import Mock, patch
from django.utils import timezone
-from hi.testing.async_task_utils import AsyncTaskTestCase
+from hi.testing.async_task_utils import AsyncTaskFastTestCase, AsyncTaskTestCase
from hi.apps.entity.models import Entity, EntityState
from hi.apps.sense.models import Sensor, SensorHistory
@@ -13,7 +13,7 @@ from hi.integrations.transient_models import IntegrationKey
logging.disable(logging.CRITICAL)
-class AsyncSensorResponseManagerTestCase(AsyncTaskTestCase):
+class AsyncSensorResponseManagerTestCase(AsyncTaskFastTestCase):
"""Test SensorResponseManager with proper async infrastructure."""
def setUp(self):
@@ -140,49 +140,6 @@ class AsyncSensorResponseManagerTestCase(AsyncTaskTestCase):
deserialized = SensorResponse.from_string(serialized)
self.assertEqual(new_response.value, deserialized.value)
- def test_dirty_flag_set_only_after_redis_pipeline_executes(self):
- """Regression for the cache-poisoning race: setting the
- dirty flag before the Redis write let a concurrent reader
- rebuild the in-memory map from pre-update Redis state and
- clear the flag, leaving the map permanently stuck on the
- stale value. Assert the flag is still False at the moment
- ``pipeline.execute()`` runs and True after."""
- observed_dirty_at_execute = []
-
- async def run():
- sensor_response = SensorResponse(
- integration_key=self.integration_key,
- value='on',
- timestamp=timezone.now(),
- )
-
- mock_pipeline = Mock()
-
- def capture_dirty_state():
- observed_dirty_at_execute.append(
- self.manager._latest_sensor_data_dirty,
- )
- return []
-
- mock_pipeline.execute.side_effect = capture_dirty_state
-
- with patch.object( self.manager, '_redis_client' ) as mock_redis:
- mock_redis.pipeline.return_value = mock_pipeline
- self.manager._latest_sensor_data_dirty = False
- await self.manager._add_latest_sensor_responses( [ sensor_response ] )
-
- import asyncio
- asyncio.get_event_loop().run_until_complete( run() )
-
- self.assertEqual(
- observed_dirty_at_execute, [ False ],
- 'Dirty flag was set before the Redis pipeline executed',
- )
- self.assertTrue(
- self.manager._latest_sensor_data_dirty,
- 'Dirty flag must be True after the Redis pipeline executes',
- )
-
def test_redis_caching_operations_use_correct_commands(self):
"""Test Redis cache key generation follows expected pattern."""
@@ -363,3 +320,80 @@ class AsyncSensorResponseManagerTestCase(AsyncTaskTestCase):
response_list = result[self.sensor]
self.assertEqual(len(response_list), 1)
self.assertEqual(response_list[0].sensor, self.sensor)
+
+
+class AsyncSensorResponseManagerCrossConnectionTestCase(AsyncTaskTestCase):
+ """Tests that exercise ``_add_latest_sensor_responses`` end-to-end.
+ The method fans out through ``sync_to_async`` to multiple DB
+ reads/writes; under TestCase the worker thread can't see setUp's
+ uncommitted Sensor row, so SQLite returns ``database table is
+ locked``. TransactionTestCase commits between methods, which is
+ the visibility this fan-out needs."""
+
+ def setUp(self):
+ super().setUp()
+ SensorResponseManager._instances = {}
+ self.manager = SensorResponseManager()
+
+ self.entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str='LIGHT',
+ )
+ self.entity_state = EntityState.objects.create(
+ entity=self.entity,
+ entity_state_type_str='ON_OFF',
+ )
+ self.sensor = Sensor.objects.create(
+ name='Test Sensor',
+ entity_state=self.entity_state,
+ sensor_type_str='DEFAULT',
+ integration_id='test_sensor_123',
+ integration_name='test_integration',
+ )
+ self.integration_key = IntegrationKey(
+ integration_id='test_sensor_123',
+ integration_name='test_integration',
+ )
+
+ def test_dirty_flag_set_only_after_redis_pipeline_executes(self):
+ """Regression for the cache-poisoning race: setting the
+ dirty flag before the Redis write let a concurrent reader
+ rebuild the in-memory map from pre-update Redis state and
+ clear the flag, leaving the map permanently stuck on the
+ stale value. Assert the flag is still False at the moment
+ ``pipeline.execute()`` runs and True after."""
+ observed_dirty_at_execute = []
+
+ async def run():
+ sensor_response = SensorResponse(
+ integration_key=self.integration_key,
+ value='on',
+ timestamp=timezone.now(),
+ )
+
+ mock_pipeline = Mock()
+
+ def capture_dirty_state():
+ observed_dirty_at_execute.append(
+ self.manager._latest_sensor_data_dirty,
+ )
+ return []
+
+ mock_pipeline.execute.side_effect = capture_dirty_state
+
+ with patch.object( self.manager, '_redis_client' ) as mock_redis:
+ mock_redis.pipeline.return_value = mock_pipeline
+ self.manager._latest_sensor_data_dirty = False
+ await self.manager._add_latest_sensor_responses( [ sensor_response ] )
+
+ import asyncio
+ asyncio.get_event_loop().run_until_complete( run() )
+
+ self.assertEqual(
+ observed_dirty_at_execute, [ False ],
+ 'Dirty flag was set before the Redis pipeline executed',
+ )
+ self.assertTrue(
+ self.manager._latest_sensor_data_dirty,
+ 'Dirty flag must be True after the Redis pipeline executes',
+ )
diff --git a/src/hi/apps/weather/tests/test_weather_alert_integration.py b/src/hi/apps/weather/tests/test_weather_alert_integration.py
index c4686977..5e7ff792 100644
--- a/src/hi/apps/weather/tests/test_weather_alert_integration.py
+++ b/src/hi/apps/weather/tests/test_weather_alert_integration.py
@@ -10,12 +10,12 @@ from hi.apps.weather.weather_sources.nws import NationalWeatherService
from hi.apps.weather.weather_manager import WeatherManager
from hi.transient_models import GeographicLocation
from hi.units import UnitQuantity
-from hi.testing.async_task_utils import AsyncTaskTestCase
+from hi.testing.async_task_utils import AsyncTaskFastTestCase
logging.disable(logging.CRITICAL)
-class TestWeatherAlertIntegration(AsyncTaskTestCase):
+class TestWeatherAlertIntegration(AsyncTaskFastTestCase):
"""Test end-to-end weather alert to alarm integration."""
def test_nws_tornado_warning_creates_critical_alarm(self):
diff --git a/src/hi/apps/weather/tests/test_weather_manager.py b/src/hi/apps/weather/tests/test_weather_manager.py
index f9a2b575..67401b44 100644
--- a/src/hi/apps/weather/tests/test_weather_manager.py
+++ b/src/hi/apps/weather/tests/test_weather_manager.py
@@ -27,13 +27,13 @@ from hi.apps.weather.enums import (
)
from hi.units import UnitQuantity
-from hi.testing.async_task_utils import AsyncTaskTestCase
+from hi.testing.async_task_utils import AsyncTaskFastTestCase
from hi.apps.weather.tests.synthetic_data import WeatherSyntheticData
logging.disable(logging.CRITICAL)
-class TestWeatherManager( AsyncTaskTestCase ):
+class TestWeatherManager( AsyncTaskFastTestCase ):
def _create_test_weather_data(self, priority, time_offset_secs, temperature_value, is_null=False):
"""Helper to create test weather data with specified parameters."""
diff --git a/src/hi/apps/weather/tests/test_weather_manager_daily_tracker_integration.py b/src/hi/apps/weather/tests/test_weather_manager_daily_tracker_integration.py
index 4c7be228..f60b20de 100644
--- a/src/hi/apps/weather/tests/test_weather_manager_daily_tracker_integration.py
+++ b/src/hi/apps/weather/tests/test_weather_manager_daily_tracker_integration.py
@@ -15,7 +15,7 @@ from hi.apps.weather.transient_models import WeatherConditionsData, NumericDataP
from hi.apps.weather.weather_data_source import WeatherDataSource
from hi.transient_models import GeographicLocation
from hi.units import UnitQuantity
-from hi.testing.async_task_utils import AsyncTaskTestCase
+from hi.testing.async_task_utils import AsyncTaskFastTestCase
logging.disable(logging.CRITICAL)
@@ -52,7 +52,7 @@ class MockWeatherDataSource(WeatherDataSource):
pass # Not used in these tests
-class TestWeatherManagerDailyTrackerIntegration(AsyncTaskTestCase):
+class TestWeatherManagerDailyTrackerIntegration(AsyncTaskFastTestCase):
"""Test integration between WeatherManager and DailyWeatherTracker."""
def setUp(self):
diff --git a/src/hi/apps/weather/tests/test_weather_manager_defensive_handling.py b/src/hi/apps/weather/tests/test_weather_manager_defensive_handling.py
index 15f18c55..b49f0916 100644
--- a/src/hi/apps/weather/tests/test_weather_manager_defensive_handling.py
+++ b/src/hi/apps/weather/tests/test_weather_manager_defensive_handling.py
@@ -15,7 +15,7 @@ from hi.apps.weather.transient_models import WeatherConditionsData, NumericDataP
from hi.apps.weather.weather_data_source import WeatherDataSource
from hi.transient_models import GeographicLocation
from hi.units import UnitQuantity
-from hi.testing.async_task_utils import AsyncTaskTestCase
+from hi.testing.async_task_utils import AsyncTaskFastTestCase
logging.disable(logging.CRITICAL)
@@ -56,7 +56,7 @@ class MockWeatherDataSource(WeatherDataSource):
pass
-class TestWeatherManagerDefensiveHandling(AsyncTaskTestCase):
+class TestWeatherManagerDefensiveHandling(AsyncTaskFastTestCase):
"""Test defensive error handling for daily weather tracking."""
def setUp(self):
diff --git a/src/hi/integrations/tests/test_integration_converter_helper.py b/src/hi/integrations/tests/test_integration_converter_helper.py
index b000484b..a0081aa0 100644
--- a/src/hi/integrations/tests/test_integration_converter_helper.py
+++ b/src/hi/integrations/tests/test_integration_converter_helper.py
@@ -5,7 +5,7 @@ from django.test import TestCase
from hi.integrations.integration_converter_helper import IntegrationConverterHelper
from hi.integrations.integration_metadata_cache import IntegrationMetadataCache
from hi.integrations.transient_models import IntegrationKey
-from hi.testing.async_task_utils import AsyncTaskTestCase
+from hi.testing.async_task_utils import AsyncTaskFastTestCase
logging.disable(logging.CRITICAL)
@@ -148,7 +148,7 @@ class TestFromEntityStateValue(TestCase):
self.assertAlmostEqual( external, 75.0, places = 6 )
-class TestAsyncConverterHelpers(AsyncTaskTestCase):
+class TestAsyncConverterHelpers(AsyncTaskFastTestCase):
"""Async variants delegate to the cache's async API, which uses
sync_to_async for DB safety. AsyncTaskTestCase manages the
event-loop lifecycle so these don't deadlock on DB locks."""
diff --git a/src/hi/integrations/tests/test_integration_synchronizer.py b/src/hi/integrations/tests/test_integration_synchronizer.py
index a9f9a860..307d0018 100644
--- a/src/hi/integrations/tests/test_integration_synchronizer.py
+++ b/src/hi/integrations/tests/test_integration_synchronizer.py
@@ -20,7 +20,7 @@ contracts live in each ``services/<integration>/tests/`` directory.
import logging
-from django.test import TestCase, TransactionTestCase
+from django.test import TestCase
from hi.apps.attribute.enums import AttributeType
from hi.apps.entity.models import Entity, EntityAttribute, EntityState
@@ -29,6 +29,7 @@ from hi.apps.sense.models import Sensor
from hi.apps.control.models import Controller
from hi.integrations.integration_synchronizer import IntegrationSynchronizer
from hi.integrations.sync_result import IntegrationSyncResult
+from hi.testing.base_test_case import BaseTestCase
logging.disable(logging.CRITICAL)
@@ -696,16 +697,15 @@ class IntegrationSynchronizerRemovalTestCase(TestCase):
self.assertEqual(self.result.removed_list, [])
-class IntegrationSynchronizerRemovalTransactionTestCase(TransactionTestCase):
- """Transaction-specific tests for _remove_entity_intelligently."""
-
+class IntegrationSynchronizerPreservationIntegrationTests(BaseTestCase):
+ """End-to-end ``_remove_entity_intelligently`` exercises with
+ mixed integration/user components: data consistency under
+ preservation, foreign-key integrity, user-data detection at
+ the entity-attribute boundary, and orphan vs preserved
+ entity-state classification."""
+
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)
-
+ super().setUp()
self.synchronizer = TestSynchronizer()
self.result = IntegrationSyncResult(title='Test Import Result')
diff --git a/src/hi/integrations/tests/test_models.py b/src/hi/integrations/tests/test_models.py
index 0fba1716..07b57c97 100644
--- a/src/hi/integrations/tests/test_models.py
+++ b/src/hi/integrations/tests/test_models.py
@@ -4,12 +4,13 @@ Unit tests for Integration models.
import logging
-from django.test import TestCase, TransactionTestCase
+from django.test import TestCase
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
+from hi.testing.base_test_case import BaseTestCase
logging.disable(logging.CRITICAL)
@@ -600,8 +601,9 @@ class IntegrationDetailsModelTestCase(TestCase):
self.assertIn('Integration-specific data', integration_payload_field.help_text)
-class IntegrationModelTransactionTestCase(TransactionTestCase):
- """Transaction-specific tests for Integration models."""
+class IntegrationModelConstraintsTestCase(BaseTestCase):
+ """Database-constraint behavior on the Integration / IntegrationAttribute
+ models: null guards, unique-constraint rollback, cascade deletion."""
def test_integration_id_null_constraint(self):
"""Test that integration_id cannot be null."""
diff --git a/src/hi/settings/base.py b/src/hi/settings/base.py
index b368256d..0f009b18 100644
--- a/src/hi/settings/base.py
+++ b/src/hi/settings/base.py
@@ -12,6 +12,7 @@ https://docs.djangoproject.com/en/4.2/ref/settings/
from pathlib import Path
import os
+import sys
from hi.environment.server import EnvironmentSettings
@@ -200,6 +201,16 @@ AUTH_PASSWORD_VALIDATORS = [
},
]
+# Default PBKDF2 hashing is hundreds of ms per call by design; for tests
+# (where many setUps create a user) it dominates wall time. Swap to a
+# fast hasher only when the process is invoked as ``manage.py test``.
+# WSGI / gunicorn / runserver / migrate / shell do not match, so
+# production processes are unaffected.
+if sys.argv[1:2] == ['test']:
+ PASSWORD_HASHERS = [
+ 'django.contrib.auth.hashers.MD5PasswordHasher',
+ ]
+
# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/
diff --git a/src/hi/testing/async_task_utils.py b/src/hi/testing/async_task_utils.py
index f1de9e24..b6ce8446 100644
--- a/src/hi/testing/async_task_utils.py
+++ b/src/hi/testing/async_task_utils.py
@@ -11,7 +11,7 @@ This module focuses on asyncio event loops and background tasks.
import asyncio
import weakref
import logging
-from django.test import TransactionTestCase
+from django.test import TestCase, TransactionTestCase
logger = logging.getLogger(__name__)
@@ -97,57 +97,52 @@ def get_background_thread_count():
return active_threads
-class AsyncTaskTestCase(TransactionTestCase):
- """
- Base class for Django tests that use asyncio event loops and async tasks.
-
- Provides proper setup and cleanup of event loops to prevent test hangs.
- Use this instead of TransactionTestCase for tests with async functionality.
-
- This is separate from AJAX testing - use ViewTestBase for HTTP async requests.
-
- Usage:
- class MyAsyncTest(AsyncTaskTestCase):
- def test_async_operation(self):
- result = self.run_async(my_async_function())
- self.assertEqual(result, expected)
- """
-
+class _AsyncLoopMixin:
+ """Shared event-loop setUpClass/tearDownClass + run_async helper.
+ Both AsyncTaskTestCase (TransactionTestCase-based) and
+ AsyncTaskFastTestCase (TestCase-based) inherit it."""
+
@classmethod
def setUpClass(cls):
super().setUpClass()
- # Create a single shared event loop for all tests in this class
cls._test_loop = asyncio.new_event_loop()
asyncio.set_event_loop(cls._test_loop)
track_background_loop(cls._test_loop)
-
+
@classmethod
def tearDownClass(cls):
- # Clean up the shared event loop
if hasattr(cls, '_test_loop'):
try:
- # Stop the loop if it's still running
if cls._test_loop.is_running():
cls._test_loop.call_soon_threadsafe(cls._test_loop.stop)
- # Close the loop
if not cls._test_loop.is_closed():
cls._test_loop.close()
except Exception as e:
logger.debug(f"Error closing test loop: {e}")
-
- # Stop any remaining background loops created during tests
stop_all_background_loops()
super().tearDownClass()
-
+
def run_async(self, coro):
- """Helper method to run async coroutines using the shared event loop."""
if hasattr(self, '_test_loop'):
return self._test_loop.run_until_complete(coro)
else:
- # Fallback if no test loop is available
return asyncio.run(coro)
+class AsyncTaskTestCase(_AsyncLoopMixin, TransactionTestCase):
+ """Async event-loop helper with TransactionTestCase semantics.
+ Required when async code under test wraps DB queries via
+ ``sync_to_async`` and the worker thread needs to see test
+ setUp's writes (cross-connection visibility)."""
+
+
+class AsyncTaskFastTestCase(_AsyncLoopMixin, TestCase):
+ """Async event-loop helper with TestCase semantics. Faster
+ (transaction rollback instead of per-test DB flush) but does
+ NOT support cross-connection visibility — use only when the
+ async code under test doesn't call DB via sync_to_async."""
+
+
def cleanup_all_async_resources():
"""
Global cleanup function to be called at the end of test runs.
diff --git a/src/hi/testing/base_test_case.py b/src/hi/testing/base_test_case.py
index b2f7a0a8..3a64e01d 100644
--- a/src/hi/testing/base_test_case.py
+++ b/src/hi/testing/base_test_case.py
@@ -98,20 +98,52 @@ class BaseTestCase(TestCase):
def isolated_media_root(self):
"""
Context manager for isolated MEDIA_ROOT testing.
-
+
Creates a temporary directory for MEDIA_ROOT to ensure tests don't
pollute the production media directory with test files.
-
+
Usage:
with self.isolated_media_root() as temp_media:
# Test file operations here
# Files will be written to temp_media, not production MEDIA_ROOT
pass
# Temporary directory is automatically cleaned up
+
+ Prefer ``in_memory_media_storage()`` for tests that only need
+ Django's ``default_storage`` abstraction.
"""
with tempfile.TemporaryDirectory() as temp_media_root:
with self.settings(MEDIA_ROOT=temp_media_root):
yield temp_media_root
+
+ @contextmanager
+ def in_memory_media_storage(self):
+ """Swap the default file storage for ``InMemoryStorage`` so
+ tests using ``default_storage`` skip filesystem I/O entirely.
+ Drop-in for ``isolated_media_root`` when the test never
+ touches real paths (``os.path.exists`` / raw ``open()``);
+ for those cases assert via ``default_storage`` instead.
+
+ Usage (context manager):
+ with self.in_memory_media_storage():
+ ...
+
+ Usage (setUp, Python 3.11+):
+ def setUp(self):
+ super().setUp()
+ self.enterContext(self.in_memory_media_storage())
+ """
+ with self.settings(
+ STORAGES = {
+ 'default': {
+ 'BACKEND': 'django.core.files.storage.InMemoryStorage',
+ },
+ 'staticfiles': {
+ 'BACKEND': 'django.contrib.staticfiles.storage.StaticFilesStorage',
+ },
+ },
+ ):
+ yield
def create_test_text_file(self, filename='test_file.txt', content='test content'):
"""
@@ -130,13 +162,74 @@ class BaseTestCase(TestCase):
content_type='text/plain'
)
+ @staticmethod
+ def create_test_png_bytes():
+ """Minimal valid PNG (4x4, RGB) that PIL/Pillow can decode.
+
+ Prefer this over generating PNGs at test time via
+ ``PIL.Image.new(...).save(...)``; doing so per test adds
+ encoder cost and pulls PIL into otherwise pure logic tests.
+ For tests that don't exercise image decoding at all, use any
+ arbitrary bytes (``ContentFile(b'whatever')``)."""
+ return (
+ b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'
+ b'\x00\x00\x00\x04\x00\x00\x00\x04\x08\x02\x00\x00\x00&\x93\t'
+ b')\x00\x00\x00\x14IDATx\xdac4J9\xc1'
+ b'\x00\x03L\x0cH\x007\x07\x00D\xca\x01f\xa1\xfbT'
+ b'\x08\x00\x00\x00\x00IEND\xaeB`\x82'
+ )
+
+ @staticmethod
+ def create_test_pdf_bytes():
+ """Minimal valid PDF (1 page, blank) that ``pdf2image`` /
+ poppler can render. Same byte sequence as
+ ``create_test_pdf_file`` but returned as raw bytes for
+ ``ContentFile`` usage."""
+ return (
+ b'%PDF-1.4\n'
+ b'1 0 obj\n'
+ b'<<\n'
+ b'/Type /Catalog\n'
+ b'/Pages 2 0 R\n'
+ b'>>\n'
+ b'endobj\n'
+ b'2 0 obj\n'
+ b'<<\n'
+ b'/Type /Pages\n'
+ b'/Kids [3 0 R]\n'
+ b'/Count 1\n'
+ b'>>\n'
+ b'endobj\n'
+ b'3 0 obj\n'
+ b'<<\n'
+ b'/Type /Page\n'
+ b'/Parent 2 0 R\n'
+ b'/MediaBox [0 0 612 792]\n'
+ b'>>\n'
+ b'endobj\n'
+ b'xref\n'
+ b'0 4\n'
+ b'0000000000 65535 f \n'
+ b'0000000010 00000 n \n'
+ b'0000000053 00000 n \n'
+ b'0000000125 00000 n \n'
+ b'trailer\n'
+ b'<<\n'
+ b'/Size 4\n'
+ b'/Root 1 0 R\n'
+ b'>>\n'
+ b'startxref\n'
+ b'205\n'
+ b'%%EOF\n'
+ )
+
def create_test_image_file(self, filename='test_image.jpg'):
"""
Create a test image file for file upload testing.
-
+
Args:
filename: Name of the image file (default: 'test_image.jpg')
-
+
Returns:
SimpleUploadedFile instance with minimal JPEG data
"""