Skip to content

Home Information - Your home, your data, organized.

Python

Established view testing framework with initial view tests.

Tony Cassandra3331a56152de
diff --git a/docs/dev/Testing.md b/docs/dev/Testing.md
index e092e075..7a622720 100644
--- a/docs/dev/Testing.md
+++ b/docs/dev/Testing.md
@@ -405,6 +405,327 @@ event_clauses = await sync_to_async(list)(
entity = await sync_to_async(Entity.objects.create)(name='Test')
```
+## Django View Testing
+
+Django views in this application come in five distinct patterns that require different testing approaches:
+
+1. **Synchronous HTML Views** - Traditional Django page views returning HTML responses
+2. **Synchronous JSON Views** - API endpoints returning JSON responses
+3. **Asynchronous HTML Views** - AJAX views returning HTML snippets for DOM insertion
+4. **Asynchronous JSON Views** - AJAX views returning JSON data for JavaScript processing
+5. **Dual-Mode Views** - Views (HiModalView/HiGridView) that handle both sync and async requests
+
+### View Testing Base Classes
+
+The framework uses a mixin-based architecture to provide clean separation of concerns:
+
+- `ViewTestBase` - Common utilities and core assertions
+- `SyncTestMixin` - Synchronous testing capabilities (regular `client.get()`, `client.post()`)
+- `AsyncTestMixin` - Asynchronous testing capabilities (`async_get()`, `async_post()` with AJAX headers)
+
+These are composed into test case classes:
+
+Use these base classes from `hi.tests.view_test_base` for consistent view testing:
+
+```python
+from django.urls import reverse
+from hi.tests.view_test_base import SyncViewTestCase, AsyncViewTestCase, DualModeViewTestCase
+
+class TestMySyncViews(SyncViewTestCase):
+ def test_synchronous_html_view(self):
+ url = reverse('my_view_name')
+ response = self.client.get(url) # Regular Django test client
+ self.assertSuccessResponse(response)
+ self.assertHtmlResponse(response)
+ self.assertTemplateRendered(response, 'my_app/template.html')
+
+class TestMyAsyncViews(AsyncViewTestCase):
+ def test_asynchronous_html_view(self):
+ url = reverse('my_async_view_name')
+ response = self.async_get(url) # Automatically includes AJAX headers
+ self.assertSuccessResponse(response)
+ self.assertJsonResponse(response)
+
+class TestMyDualModeViews(DualModeViewTestCase):
+ def test_view_synchronous_mode(self):
+ url = reverse('my_dual_view_name')
+ response = self.client.get(url) # Regular request
+ self.assertSuccessResponse(response)
+ self.assertHtmlResponse(response)
+
+ def test_view_asynchronous_mode(self):
+ url = reverse('my_dual_view_name')
+ response = self.async_get(url) # AJAX request
+ self.assertSuccessResponse(response)
+ self.assertJsonResponse(response)
+```
+
+### Helper Methods
+
+The base test classes provide these assertion and utility methods:
+
+**Status Code Assertions:**
+- `assertResponseStatusCode(response, expected_code)` - Verifies specific status code
+- `assertSuccessResponse(response)` - Verifies 2xx status code
+- `assertErrorResponse(response)` - Verifies 4xx status code
+- `assertServerErrorResponse(response)` - Verifies 5xx status code
+
+**Response Type Assertions:**
+- `assertHtmlResponse(response)` - Verifies HTML content type (status code independent)
+- `assertJsonResponse(response)` - Verifies JSON content type (status code independent)
+
+**Template Assertions:**
+- `assertTemplateRendered(response, template_name)` - Verifies specific template was used
+
+**Session Assertions:**
+- `assertSessionValue(response, key, expected_value)` - Verifies session contains specific key-value pair
+- `assertSessionContains(response, key)` - Verifies session contains specific key
+
+**Session Management:**
+- `setSessionViewType(view_type)` - Set ViewType in session for subsequent requests
+- `setSessionViewMode(view_mode)` - Set ViewMode in session for subsequent requests
+- `setSessionLocationView(location_view)` - Set location_view_id in session for subsequent requests
+- `setSessionCollection(collection)` - Set collection_id in session for subsequent requests
+- `setSessionViewParameters(view_type=None, view_mode=None, location_view=None, collection=None)` - Set multiple view parameters at once
+
+**Redirect Testing:**
+- `assertRedirectsToTemplates(initial_url, expected_templates)` - Follow redirects and verify final templates rendered
+
+**AJAX Request Methods:**
+- `async_get(url, data=None)` - GET request with AJAX headers
+- `async_post(url, data=None)` - POST request with AJAX headers
+- `async_put(url, data=None)` - PUT request with AJAX headers
+- `async_delete(url, data=None)` - DELETE request with AJAX headers
+
+### Testing Patterns by View Type
+
+#### Synchronous HTML Views
+- Test status code, response type, and template rendering separately
+- Verify error handling and edge cases
+- Validate form processing and context data
+
+```python
+def test_location_view_renders_correctly(self):
+ location = Location.objects.create(name='Test Location')
+ url = reverse('location_detail', kwargs={'location_id': location.id})
+ response = self.client.get(url)
+
+ self.assertSuccessResponse(response)
+ self.assertHtmlResponse(response)
+ self.assertTemplateRendered(response, 'location/detail.html')
+ self.assertEqual(response.context['location'], location)
+
+def test_location_view_not_found(self):
+ url = reverse('location_detail', kwargs={'location_id': 999})
+ response = self.client.get(url)
+
+ self.assertResponseStatusCode(response, 404)
+ self.assertHtmlResponse(response)
+```
+
+#### Synchronous JSON Views
+- Test status codes and JSON response structure separately
+- Verify API endpoint error responses
+
+```python
+def test_api_status_returns_json(self):
+ url = reverse('api_status')
+ response = self.client.get(url)
+
+ self.assertSuccessResponse(response)
+ self.assertJsonResponse(response)
+ data = response.json()
+ self.assertIn('timestamp', data)
+ self.assertIn('alertData', data)
+
+def test_api_invalid_request(self):
+ url = reverse('api_update')
+ response = self.client.post(url, {'invalid': 'data'})
+
+ self.assertErrorResponse(response)
+ self.assertJsonResponse(response)
+```
+
+#### Asynchronous HTML Views
+- Test AJAX request detection and proper status codes
+- Verify HTML snippet responses for DOM insertion
+- Test response when called incorrectly (sync instead of async)
+
+```python
+def test_async_html_view_with_ajax_header(self):
+ url = reverse('console_sensor_view', kwargs={'sensor_id': 1})
+ response = self.async_get(url) # Includes HTTP_X_REQUESTED_WITH header
+
+ self.assertSuccessResponse(response)
+ self.assertJsonResponse(response)
+ # Test that async view returns content for DOM insertion
+ data = response.json()
+ self.assertIn('insert_map', data)
+
+def test_async_view_called_synchronously_redirects(self):
+ url = reverse('console_sensor_view', kwargs={'sensor_id': 1})
+ response = self.client.get(url) # Regular GET without AJAX headers
+
+ expected_redirect = reverse('console_home')
+ self.assertRedirects(response, expected_redirect)
+
+def test_async_view_error_handling(self):
+ url = reverse('console_sensor_view', kwargs={'sensor_id': 999})
+ response = self.async_get(url)
+
+ self.assertErrorResponse(response)
+ self.assertJsonResponse(response) # Error responses may be JSON
+```
+
+#### Asynchronous JSON Views
+- Test AJAX JSON responses with correct status codes
+- Verify JavaScript-consumable data formats
+- Test error handling in async context
+
+```python
+def test_async_json_view_returns_update_data(self):
+ url = reverse('api_update')
+ response = self.async_post(url, {'entity_id': 1}) # Includes AJAX headers
+
+ self.assertSuccessResponse(response)
+ self.assertJsonResponse(response)
+ data = response.json()
+ self.assertIn('timestamp', data)
+ self.assertIn('alertData', data)
+
+def test_async_json_view_validation_error(self):
+ url = reverse('api_update')
+ response = self.async_post(url, {}) # Missing required data
+
+ self.assertErrorResponse(response)
+ self.assertJsonResponse(response)
+```
+
+#### Dual-Mode Views (HiModalView/HiGridView)
+- Test both synchronous and asynchronous call patterns
+- Verify correct response type based on request context
+- Test modal rendering vs. full page rendering
+
+```python
+def test_modal_view_sync_request(self):
+ url = reverse('weather_current_conditions_details')
+ response = self.client.get(url) # Regular request without AJAX headers
+
+ self.assertSuccessResponse(response)
+ self.assertHtmlResponse(response)
+ # Should render both the base page and the modal template
+ self.assertTemplateRendered(response, 'pages/main_default.html')
+ self.assertTemplateRendered(response, 'weather/modals/conditions_details.html')
+
+def test_modal_view_async_request(self):
+ url = reverse('weather_current_conditions_details')
+ response = self.async_get(url) # Request with AJAX headers
+
+ self.assertSuccessResponse(response)
+ self.assertJsonResponse(response)
+ self.assertTemplateRendered(response, 'weather/modals/conditions_details.html')
+ # Verify modal response structure for AJAX
+ data = response.json()
+ self.assertIn('modal', data)
+```
+
+### View Testing Guidelines
+
+**DO:**
+- Use `reverse()` with URL names instead of hardcoded URL strings
+- Use `async_get()`, `async_post()` etc. for AJAX requests to ensure proper headers
+- Test status codes, response types, and template rendering as separate concerns
+- Use `assertTemplateRendered()` to verify template usage independently
+- Use real database operations and test data setup
+- Test actual request/response flows through real code paths
+- Mock only at system boundaries (HTTP calls, external services)
+- Test conditional logic that affects response content or status codes
+- Test error handling and edge cases with appropriate status code assertions
+- Verify context data correctness
+- **Test each view's specific decisions, not downstream redirect effects** (use `fetch_redirect_response=False` for immediate redirects)
+
+**DON'T:**
+- Use hardcoded URL strings - always use `reverse()` with URL names
+- Use regular `client.get()` for AJAX requests - use `async_get()` helper methods
+- Mix status code, response type, and template assertions in single method calls
+- Test template content text that may change - use template name verification instead
+- Use magic strings instead of defined enums/constants (e.g., `'EDIT'` vs `ViewMode.EDIT`)
+- Mock internal Django components or ORM operations
+- Test implementation details instead of interface contracts
+- Create tests that depend on log message assertions
+- Over-mock internal application components
+
+### Database Setup for View Tests
+
+View tests should create real test data to verify complete request/response flows:
+
+```python
+def setUp(self):
+ super().setUp()
+ self.location = Location.objects.create(name='Test Location')
+ self.entity = Entity.objects.create(
+ integration_id='test.entity',
+ integration_name='test_integration',
+ location=self.location
+ )
+
+def test_location_view_with_entities(self):
+ url = reverse('location_detail', kwargs={'location_id': self.location.id})
+ response = self.client.get(url)
+
+ self.assertSuccessResponse(response)
+ self.assertHtmlResponse(response)
+ self.assertTemplateRendered(response, 'location/detail.html')
+ self.assertEqual(response.context['location'], self.location)
+ # Test that entity is in context or response data
+ self.assertIn(self.entity, response.context['entities'])
+```
+
+### Authentication and Permission Testing
+
+For views requiring authentication:
+
+```python
+def test_protected_view_requires_authentication(self):
+ url = reverse('protected_view')
+ response = self.client.get(url)
+ login_url = reverse('login')
+ self.assertRedirects(response, f'{login_url}?next={url}')
+
+def test_protected_view_with_authenticated_user(self):
+ self.client.force_login(self.user)
+ url = reverse('protected_view')
+ response = self.client.get(url)
+
+ self.assertSuccessResponse(response)
+ self.assertHtmlResponse(response)
+```
+
+### Form Validation Testing
+
+For views that process forms:
+
+```python
+def test_form_validation_success(self):
+ form_data = {'name': 'Test Entity', 'location': self.location.id}
+ url = reverse('entity_create')
+ response = self.client.post(url, form_data)
+
+ success_url = reverse('entity_list')
+ self.assertRedirects(response, success_url)
+ self.assertTrue(Entity.objects.filter(name='Test Entity').exists())
+
+def test_form_validation_errors(self):
+ form_data = {'name': ''} # Missing required field
+ url = reverse('entity_create')
+ response = self.client.post(url, form_data)
+
+ self.assertSuccessResponse(response) # Form errors return 200, not 4xx
+ self.assertHtmlResponse(response)
+ self.assertTemplateRendered(response, 'entity/create.html')
+ self.assertFormError(response, 'form', 'name', 'This field is required.')
+```
+
## Integration Tests
_TBD_
diff --git a/src/hi/apps/api/tests/test_views.py b/src/hi/apps/api/tests/test_views.py
new file mode 100644
index 00000000..f80dc0dc
--- /dev/null
+++ b/src/hi/apps/api/tests/test_views.py
@@ -0,0 +1,105 @@
+import logging
+from datetime import datetime, timezone
+
+from django.urls import reverse
+
+from hi.tests.view_test_base import AsyncViewTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestStatusView(AsyncViewTestCase):
+ """
+ Tests for StatusView - demonstrates asynchronous JSON view testing.
+ This critical view is called every 3 seconds from clients and provides
+ the main payload that drives client-side view updates.
+ """
+
+ def test_status_view_returns_json_with_ajax(self):
+ """Test that StatusView returns valid JSON when called with AJAX headers."""
+ url = reverse('api_status')
+ response = self.async_get(url)
+
+ self.assertSuccessResponse(response)
+ self.assertJsonResponse(response)
+
+ data = response.json()
+ # Verify required fields in the status response
+ self.assertIn('timestamp', data)
+ self.assertIn('startTimestamp', data)
+ self.assertIn('alertData', data)
+ self.assertIn('cssClassUpdateMap', data)
+ self.assertIn('idReplaceUpdateMap', data)
+ self.assertIn('idReplaceHashMap', data)
+
+ def test_status_view_timestamp_format(self):
+ """Test that timestamps in status response are properly formatted."""
+ url = reverse('api_status')
+ response = self.async_get(url)
+
+ self.assertSuccessResponse(response)
+ data = response.json()
+
+ # Verify timestamps are valid ISO format
+ timestamp = data['timestamp']
+ start_timestamp = data['startTimestamp']
+
+ # Should be able to parse as datetime
+ parsed_timestamp = datetime.fromisoformat(timestamp.replace('Z', '+00:00'))
+ parsed_start_timestamp = datetime.fromisoformat(start_timestamp.replace('Z', '+00:00'))
+
+ self.assertIsInstance(parsed_timestamp, datetime)
+ self.assertIsInstance(parsed_start_timestamp, datetime)
+
+ def test_status_view_with_last_timestamp_parameter(self):
+ """Test status view handles lastTimestamp query parameter correctly."""
+ last_timestamp = datetime.now(timezone.utc).isoformat()
+ url = reverse('api_status')
+ response = self.async_get(url, {'lastTimestamp': last_timestamp})
+
+ self.assertSuccessResponse(response)
+ self.assertJsonResponse(response)
+
+ data = response.json()
+ self.assertIn('timestamp', data)
+ # The response should still contain all required fields
+ self.assertIn('alertData', data)
+
+ def test_status_view_with_invalid_timestamp_parameter(self):
+ """Test status view handles invalid lastTimestamp parameter with error response."""
+ url = reverse('api_status')
+ response = self.async_get(url, {'lastTimestamp': 'invalid-date'})
+
+ # Should return error response for invalid timestamp
+ self.assertErrorResponse(response)
+
+ def test_status_view_hash_map_structure(self):
+ """Test that idReplaceHashMap contains valid MD5 hashes."""
+ url = reverse('api_status')
+ response = self.async_get(url)
+
+ self.assertSuccessResponse(response)
+ data = response.json()
+
+ id_replace_map = data['idReplaceUpdateMap']
+ id_replace_hash_map = data['idReplaceHashMap']
+
+ # Hash map should have entries for each id_replace_map entry
+ for element_id in id_replace_map.keys():
+ self.assertIn(element_id, id_replace_hash_map)
+ # MD5 hashes should be 32 character hex strings
+ hash_value = id_replace_hash_map[element_id]
+ self.assertEqual(len(hash_value), 32)
+ self.assertTrue(all(c in '0123456789abcdef' for c in hash_value.lower()))
+
+ def test_status_view_alert_data_structure(self):
+ """Test that alertData has expected structure."""
+ url = reverse('api_status')
+ response = self.async_get(url)
+
+ self.assertSuccessResponse(response)
+ data = response.json()
+
+ alert_data = data['alertData']
+ self.assertIsInstance(alert_data, dict)
+ # AlertData should be a dict (specific structure depends on AlertStatusData.to_dict())
diff --git a/src/hi/apps/weather/tests/test_views.py b/src/hi/apps/weather/tests/test_views.py
new file mode 100644
index 00000000..17b1b849
--- /dev/null
+++ b/src/hi/apps/weather/tests/test_views.py
@@ -0,0 +1,54 @@
+import logging
+
+from django.urls import reverse
+
+from hi.tests.view_test_base import DualModeViewTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestCurrentConditionsDetailsView(DualModeViewTestCase):
+ """
+ Tests for CurrentConditionsDetailsView - demonstrates dual-mode view testing.
+ HiModalView handles both sync and async requests:
+ - Async: Returns JSON with modal HTML content
+ - Sync: Returns full page with modal auto-displayed
+ """
+
+ def test_modal_view_async_request(self):
+ """Test that modal view returns JSON with modal content when called with AJAX."""
+ url = reverse('weather_current_conditions_details')
+ response = self.async_get(url)
+
+ self.assertSuccessResponse(response)
+ self.assertJsonResponse(response)
+ self.assertTemplateRendered(response, 'weather/modals/conditions_details.html')
+
+ # Should contain modal HTML content in JSON response
+ data = response.json()
+ self.assertIn('modal', data)
+
+ def test_modal_view_sync_request(self):
+ """Test that modal view returns full page with modal setup when called synchronously."""
+ url = reverse('weather_current_conditions_details')
+ response = self.client.get(url) # Regular request without AJAX headers
+
+ self.assertSuccessResponse(response)
+ self.assertHtmlResponse(response)
+
+ # Should render both the base page and the modal template
+ self.assertTemplateRendered(response, 'pages/main_default.html')
+ self.assertTemplateRendered(response, 'weather/modals/conditions_details.html')
+
+ def test_modal_view_json_structure(self):
+ """Test that modal view returns properly structured JSON for async requests."""
+ url = reverse('weather_current_conditions_details')
+ response = self.async_get(url)
+
+ self.assertSuccessResponse(response)
+ data = response.json()
+
+ # Should have the expected JSON structure for modal responses
+ self.assertIn('modal', data)
+ self.assertIsInstance(data['modal'], str)
+ self.assertTrue(len(data['modal']) > 0) # Should contain rendered content
diff --git a/src/hi/tests/test_views.py b/src/hi/tests/test_views.py
new file mode 100644
index 00000000..f155846f
--- /dev/null
+++ b/src/hi/tests/test_views.py
@@ -0,0 +1,182 @@
+import logging
+
+from django.urls import reverse
+
+from hi.apps.location.models import Location, LocationView
+from hi.enums import ViewMode, ViewType
+from hi.tests.view_test_base import SyncViewTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestStartView(SyncViewTestCase):
+ """
+ Tests for StartView - demonstrates synchronous HTML view testing.
+ This view renders a template for first-time users when no locations exist.
+ """
+
+ def test_start_view_renders_template_when_no_locations(self):
+ """Test that StartView renders start.html template when no locations exist."""
+ # Ensure no locations exist
+ Location.objects.all().delete()
+
+ url = reverse('start')
+ response = self.client.get(url)
+
+ self.assertSuccessResponse(response)
+ self.assertHtmlResponse(response)
+ self.assertTemplateRendered(response, 'pages/start.html')
+
+ def test_start_view_redirects_when_locations_exist(self):
+ """Test that StartView redirects to home when locations already exist."""
+ # Create a location with required fields
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+ # Create a LocationView for the location
+ LocationView.objects.create(
+ location=location,
+ name='Test View',
+ location_view_type_str='MAIN',
+ svg_view_box_str='0 0 100 100',
+ svg_rotate=0.0,
+ svg_style_name_str='DEFAULT'
+ )
+
+ url = reverse('start')
+ response = self.client.get(url)
+
+ # Should redirect to home (test only StartView's decision, not HomeView's logic)
+ home_url = reverse('home')
+ self.assertRedirects(response, home_url, fetch_redirect_response=False)
+
+ def test_start_view_sets_edit_mode_in_session(self):
+ """Test that StartView sets edit mode in the session."""
+ # Ensure no locations exist
+ Location.objects.all().delete()
+
+ url = reverse('start')
+ response = self.client.get(url)
+
+ self.assertSuccessResponse(response)
+ self.assertSessionValue(response, 'view_mode', str(ViewMode.EDIT))
+
+
+class TestHomeView(SyncViewTestCase):
+ """
+ Tests for HomeView - demonstrates redirect logic testing.
+ This view redirects based on existing data and view parameters.
+ """
+
+ def test_home_view_redirects_to_start_when_no_locations(self):
+ """Test that HomeView redirects to start page when no locations exist."""
+ # Ensure no locations exist
+ Location.objects.all().delete()
+
+ url = reverse('home')
+ response = self.client.get(url)
+
+ start_url = reverse('start')
+ self.assertRedirects(response, start_url)
+
+ def test_home_view_redirects_to_location_view_when_locations_exist(self):
+ """Test that HomeView redirects and renders location view template."""
+ # Create a location with required fields
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+ # Create a LocationView for the location
+ LocationView.objects.create(
+ location=location,
+ name='Test View',
+ location_view_type_str='MAIN',
+ svg_view_box_str='0 0 100 100',
+ svg_rotate=0.0,
+ svg_style_name_str='DEFAULT'
+ )
+
+ url = reverse('home')
+ # Use assertRedirectsToTemplates to follow redirects and verify final template
+ self.assertRedirectsToTemplates(url, ['location/panes/location_view.html'])
+
+ def test_home_view_handles_inconsistent_database_state(self):
+ """Test that HomeView redirects to start when Location exists but no LocationView exists.
+
+ This test covers the edge case where a Location object exists but no associated
+ LocationView exists. This shouldn't happen in normal operation since Location
+ creation atomically creates a default LocationView, but we test the fallback
+ behavior for safety.
+ """
+ # Create an orphaned Location without a LocationView
+ # (This shouldn't happen in normal operation but we test the fallback)
+ Location.objects.create(
+ name='Orphaned Location',
+ svg_fragment_filename='orphaned.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+ # Ensure no LocationView objects exist
+ LocationView.objects.all().delete()
+
+ url = reverse('home')
+ response = self.client.get(url)
+
+ start_url = reverse('start')
+ self.assertRedirects(response, start_url, fetch_redirect_response=False)
+
+ def test_home_view_redirects_to_collection_view_when_collection_type(self):
+ """Test that HomeView redirects to collection_view_default when view_type is collection."""
+ # Create a location with required fields
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+ # Create a LocationView for the location
+ LocationView.objects.create(
+ location=location,
+ name='Test View',
+ location_view_type_str='MAIN',
+ svg_view_box_str='0 0 100 100',
+ svg_rotate=0.0,
+ svg_style_name_str='DEFAULT'
+ )
+
+ # Set session to have collection view type
+ self.setSessionViewType(ViewType.COLLECTION)
+
+ url = reverse('home')
+ response = self.client.get(url)
+
+ collection_url = reverse('collection_view_default')
+ self.assertRedirects(response, collection_url, fetch_redirect_response=False)
+
+ def test_home_view_redirects_to_location_view_when_location_type(self):
+ """Test that HomeView redirects to location_view_default when view_type is location."""
+ # Create a location with required fields
+ location = Location.objects.create(
+ name='Test Location',
+ svg_fragment_filename='test.svg',
+ svg_view_box_str='0 0 100 100'
+ )
+ # Create a LocationView for the location
+ LocationView.objects.create(
+ location=location,
+ name='Test View',
+ location_view_type_str='MAIN',
+ svg_view_box_str='0 0 100 100',
+ svg_rotate=0.0,
+ svg_style_name_str='DEFAULT'
+ )
+
+ # Set session to have location view type (or leave default)
+ self.setSessionViewType(ViewType.LOCATION_VIEW)
+
+ url = reverse('home')
+ response = self.client.get(url)
+
+ location_view_url = reverse('location_view_default')
+ self.assertRedirects(response, location_view_url, fetch_redirect_response=False)
diff --git a/src/hi/tests/view_test_base.py b/src/hi/tests/view_test_base.py
new file mode 100644
index 00000000..ad37b822
--- /dev/null
+++ b/src/hi/tests/view_test_base.py
@@ -0,0 +1,230 @@
+from typing import Dict, Any, Optional
+import json
+
+from django.contrib.auth import get_user_model
+from django.http import HttpResponse
+
+from hi.tests.base_test_case import BaseTestCase
+from hi.enums import ViewType, ViewMode
+from hi.apps.location.models import LocationView
+from hi.apps.collection.models import Collection
+
+
+class ViewTestBase(BaseTestCase):
+ """
+ Base class for all Django view tests, providing common utilities and assertions.
+ """
+
+ def setUp(self):
+ super().setUp()
+ User = get_user_model()
+ self.user = User.objects.create_user(
+ password='testpass123'
+ )
+
+ def assertResponseStatusCode(self, response: HttpResponse, expected_code: int):
+ """Assert that response has the expected status code."""
+ self.assertEqual(
+ response.status_code,
+ expected_code,
+ f"Expected status code {expected_code}, got {response.status_code}"
+ )
+
+ def assertSuccessResponse(self, response: HttpResponse):
+ """Assert that response has a 2xx status code."""
+ self.assertTrue(
+ 200 <= response.status_code < 300,
+ f"Expected 2xx status code, got {response.status_code}"
+ )
+
+ def assertErrorResponse(self, response: HttpResponse):
+ """Assert that response has a 4xx status code."""
+ self.assertTrue(
+ 400 <= response.status_code < 500,
+ f"Expected 4xx status code, got {response.status_code}"
+ )
+
+ def assertServerErrorResponse(self, response: HttpResponse):
+ """Assert that response has a 5xx status code."""
+ self.assertTrue(
+ 500 <= response.status_code < 600,
+ f"Expected 5xx status code, got {response.status_code}"
+ )
+
+ def assertHtmlResponse(self, response: HttpResponse):
+ """Assert that response is HTML content type (status code independent)."""
+ content_type = response.get('Content-Type', '').lower()
+ self.assertTrue(
+ 'text/html' in content_type,
+ f"Expected HTML content type, got '{content_type}'"
+ )
+
+ def assertJsonResponse(self, response: HttpResponse):
+ """Assert that response is JSON content type (status code independent)."""
+ content_type = response.get('Content-Type', '').lower()
+ self.assertTrue(
+ 'application/json' in content_type,
+ f"Expected JSON content type, got '{content_type}'"
+ )
+
+ def assertTemplateRendered(self, response: HttpResponse, template_name: str):
+ """Assert that the specified template was used to render the response."""
+ template_names = [t.name for t in response.templates]
+ self.assertIn(
+ template_name,
+ template_names,
+ f"Template '{template_name}' not found in rendered templates: {template_names}"
+ )
+
+ def assertSessionValue(self, response: HttpResponse, key: str, expected_value):
+ """Assert that a session value matches the expected value."""
+ session = response.wsgi_request.session
+ actual_value = session.get(key)
+ self.assertEqual(
+ actual_value,
+ expected_value,
+ f"Session key '{key}': expected '{expected_value}', got '{actual_value}'"
+ )
+
+ def assertSessionContains(self, response: HttpResponse, key: str):
+ """Assert that a session contains the specified key."""
+ session = response.wsgi_request.session
+ self.assertIn(
+ key,
+ session,
+ f"Session key '{key}' not found in session keys: {list(session.keys())}"
+ )
+
+ def assertRedirectsToTemplates(self, initial_url: str, expected_templates: list):
+ """Assert that URL redirects and final response renders all expected templates."""
+ response = self.client.get(initial_url, follow=True)
+
+ self.assertTrue(
+ len(response.redirect_chain) > 0,
+ f"Expected redirect from {initial_url}, but got direct response"
+ )
+
+ self.assertSuccessResponse(response)
+ for template in expected_templates:
+ self.assertTemplateRendered(response, template)
+ return response
+
+ # Session Management Convenience Methods
+
+ def setSessionViewType(self, view_type: ViewType):
+ """Set the view_type in the session for subsequent requests."""
+ session = self.client.session
+ session['view_type'] = str(view_type)
+ session.save()
+
+ def setSessionViewMode(self, view_mode: ViewMode):
+ """Set the view_mode in the session for subsequent requests."""
+ session = self.client.session
+ session['view_mode'] = str(view_mode)
+ session.save()
+
+ def setSessionLocationView(self, location_view: Optional[LocationView]):
+ """Set the location_view_id in the session for subsequent requests."""
+ session = self.client.session
+ session['location_view_id'] = location_view.id if location_view else None
+ session.save()
+
+ def setSessionCollection(self, collection: Optional[Collection]):
+ """Set the collection_id in the session for subsequent requests."""
+ session = self.client.session
+ session['collection_id'] = collection.id if collection else None
+ session.save()
+
+ def setSessionViewParameters(self,
+ view_type: Optional[ViewType] = None,
+ view_mode: Optional[ViewMode] = None,
+ location_view: Optional[LocationView] = None,
+ collection: Optional[Collection] = None):
+ """Convenience method to set multiple view parameters at once."""
+ session = self.client.session
+ if view_type is not None:
+ session['view_type'] = str(view_type)
+ if view_mode is not None:
+ session['view_mode'] = str(view_mode)
+ if location_view is not None:
+ session['location_view_id'] = location_view.id
+ if collection is not None:
+ session['collection_id'] = collection.id
+ session.save()
+
+
+class SyncTestMixin:
+ """
+ Mixin providing synchronous testing capabilities.
+ No special methods needed beyond base - regular client.get(), client.post() etc.
+ """
+ pass
+
+
+class AsyncTestMixin:
+ """
+ Mixin providing asynchronous (AJAX) testing capabilities.
+ Includes helper methods that automatically add AJAX headers.
+ """
+
+ def async_get(self, url: str, data: Dict[str, Any] = None) -> HttpResponse:
+ """Make a GET request with AJAX headers."""
+ return self.client.get(
+ url,
+ data=data or {},
+ **self.async_http_headers
+ )
+
+ def async_post(self, url: str, data: Dict[str, Any] = None) -> HttpResponse:
+ """Make a POST request with AJAX headers."""
+ return self.client.post(
+ url,
+ data=data or {},
+ **self.async_http_headers
+ )
+
+ def async_put(self, url: str, data: Dict[str, Any] = None) -> HttpResponse:
+ """Make a PUT request with AJAX headers."""
+ return self.client.put(
+ url,
+ data=json.dumps(data or {}),
+ content_type='application/json',
+ **self.async_http_headers
+ )
+
+ def async_delete(self, url: str, data: Dict[str, Any] = None) -> HttpResponse:
+ """Make a DELETE request with AJAX headers."""
+ return self.client.delete(
+ url,
+ data=json.dumps(data or {}),
+ content_type='application/json',
+ **self.async_http_headers
+ )
+
+
+class SyncViewTestCase(ViewTestBase, SyncTestMixin):
+ """
+ Test case for synchronous views (traditional Django page views and API endpoints).
+ Uses regular client.get(), client.post() methods for testing.
+ """
+ pass
+
+
+class AsyncViewTestCase(ViewTestBase, AsyncTestMixin):
+ """
+ Test case for asynchronous views (AJAX endpoints).
+ Provides async_get(), async_post() methods that include AJAX headers.
+ """
+ pass
+
+
+class DualModeViewTestCase(ViewTestBase, SyncTestMixin, AsyncTestMixin):
+ """
+ Test case for dual-mode views (HiModalView/HiGridView) that handle both
+ synchronous and asynchronous requests.
+
+ Provides both regular client methods (sync) and async_* methods (AJAX)
+ to test the same view in both contexts.
+ """
+ pass
diff --git a/src/hi/views.py b/src/hi/views.py
index b0f46bf6..a0ea4913 100644
--- a/src/hi/views.py
+++ b/src/hi/views.py
@@ -15,7 +15,7 @@ from django.views.generic import View
import hi.apps.common.antinode as antinode
from hi.apps.common.healthcheck import do_healthcheck
from hi.apps.common.utils import is_ajax
-from hi.apps.location.models import Location
+from hi.apps.location.models import Location, LocationView
from hi.enums import ViewMode
@@ -169,7 +169,7 @@ class HomeView( View ):
def get(self, request, *args, **kwargs):
- if not Location.objects.all().exists():
+ if not LocationView.objects.all().exists():
redirect_url = reverse( 'start' )
return HttpResponseRedirect( redirect_url )
@@ -184,8 +184,8 @@ class StartView( View ):
def get(self, request, *args, **kwargs):
- # This view only for first time users (when no Locations exist)
- if Location.objects.all().exists():
+ # This view only for first time users (when no LocationViews exist)
+ if LocationView.objects.all().exists():
redirect_url = reverse( 'home' )
return HttpResponseRedirect( redirect_url )