# Step 04: Django Integration Tests

## Status Reference
- **Current Status**: Pending
- **Dependencies**: Steps 01-03 should be complete
- **Target Modules**:
  - `storm_logger/integrations/django.py` (12.70% coverage)
  - `storm_logger/integrations/django_config.py` (18.18% coverage)
- **Target Coverage**: 100% for both modules

## Objectives
1. Create comprehensive Django integration tests
2. Test middleware, signals, and admin integration
3. Verify Django-specific configuration
4. Test database handlers and model tracking
5. Ensure compatibility with Django 4.x and 5.x

## Coverage Gap Analysis

### django.py - Missing Coverage
Missing lines: 29-33, 37-40, 51-187, 200-216, 232-241, 254-267, 301-315

Key areas:
- DjangoStormLogger class implementation
- Middleware integration
- Signal handlers
- Admin interface customization
- Database log handler

### django_config.py - Missing Coverage
Missing lines: 18-19, 74-103, 115, 119-128, 132-147, 160-179, 192-258, 270-274, 283-284, 293, 298-309, 314-325, 330-339, 353-355, 360-392, 396-397, 401-415, 419, 423, 427-439, 443, 451-484, 500-504, 517-528, 542-548, 559-563

Key areas:
- Django settings generation
- Middleware configuration
- Handler setup
- Filter configuration
- Integration with Django's logging

## Test Suite Design

### Test File: `test_django_integration_comprehensive.py`

#### 1. Django Logger Tests
```python
@pytest.mark.django_db
class TestDjangoStormLogger:
    - test_logger_initialization
    - test_django_specific_formatting
    - test_request_context_injection
    - test_user_tracking
    - test_session_management
    - test_database_queries_logging
```

#### 2. Middleware Tests
```python
@pytest.mark.django_db
class TestStormLoggerMiddleware:
    - test_request_logging
    - test_response_logging
    - test_error_handling
    - test_performance_tracking
    - test_user_agent_parsing
    - test_ip_extraction
```

#### 3. Signal Handler Tests
```python
@pytest.mark.django_db
class TestDjangoSignals:
    - test_model_save_logging
    - test_model_delete_logging
    - test_m2m_change_logging
    - test_request_started_logging
    - test_request_finished_logging
    - test_custom_signal_logging
```

#### 4. Admin Integration Tests
```python
@pytest.mark.django_db
class TestAdminIntegration:
    - test_admin_action_logging
    - test_admin_view_logging
    - test_admin_change_logging
    - test_admin_permission_logging
    - test_admin_search_logging
```

### Test File: `test_django_config_comprehensive.py`

#### 1. Configuration Generation Tests
```python
class TestDjangoConfigGeneration:
    - test_default_config_generation
    - test_custom_config_merge
    - test_environment_variable_override
    - test_handler_configuration
    - test_formatter_configuration
    - test_filter_configuration
```

#### 2. Settings Integration Tests
```python
class TestDjangoSettings:
    - test_settings_auto_discovery
    - test_logging_config_merge
    - test_middleware_insertion
    - test_installed_apps_check
    - test_database_handler_config
```

#### 3. Handler Configuration Tests
```python
class TestHandlerConfiguration:
    - test_console_handler_setup
    - test_file_handler_setup
    - test_database_handler_setup
    - test_email_handler_setup
    - test_custom_handler_registration
```

#### 4. Django Version Compatibility Tests
```python
class TestDjangoCompatibility:
    - test_django_4_compatibility
    - test_django_5_compatibility
    - test_deprecated_features
    - test_future_warnings
    - test_migration_path
```

## Implementation Strategy

### Phase 1: Basic Django Integration (1.5 hours)
1. Set up Django test environment
2. Create test Django app
3. Implement basic logger tests
4. Test middleware functionality

### Phase 2: Advanced Features (1 hour)
1. Test signal handlers
2. Implement admin integration tests
3. Test model tracking
4. Verify database handler

### Phase 3: Configuration Tests (45 minutes)
1. Test configuration generation
2. Verify settings integration
3. Test handler setup
4. Check compatibility

## Django Test Setup

### Test Settings
```python
# tests/django_test_settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'storm_logger.integrations.django',
    'tests.django_test_app',
]

MIDDLEWARE = [
    'storm_logger.integrations.django.middleware.StormLoggerMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
]

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': ':memory:',
    }
}
```

### Test Models
```python
# tests/django_test_app/models.py
class TestModel(models.Model):
    name = models.CharField(max_length=100)
    value = models.IntegerField()
    
    class Meta:
        app_label = 'django_test_app'
```

## Mock Requirements

### Request/Response Mocks
```python
def create_mock_request():
    request = Mock()
    request.method = 'GET'
    request.path = '/test/'
    request.user = Mock(username='testuser')
    request.session = {'session_key': 'test123'}
    return request
```

### Django Settings Mock
```python
@patch('django.conf.settings')
def test_with_settings(mock_settings):
    mock_settings.DEBUG = True
    mock_settings.LOGGING = {}
    # Test implementation
```

## Success Criteria
- 100% coverage for both Django integration modules
- All Django-specific features tested
- Middleware fully tested with edge cases
- Signal handlers verified
- Configuration generation complete
- Django 4.x and 5.x compatibility confirmed

## Next Steps
1. Set up Django test environment
2. Create test app and models
3. Implement test classes systematically
4. Run with Django test runner
5. Update status.json with progress
6. Move to Step 05 after 100% coverage

## Automation Notes
- Use Django's TestCase for database tests
- Mock Django settings where needed
- Test with multiple Django versions
- Use fixtures for test data
- Ensure tests run in isolation