# Step 08: Context and Core Tests

## Status Reference
- **Current Status**: Pending
- **Dependencies**: Steps 01-07 should be complete
- **Target Modules**:
  - `storm_logger/context_detector.py` (31.34% coverage)
  - `storm_logger/core/base.py` (31.86% coverage)
  - `storm_logger/core/logger.py` (25.42% coverage)
  - `storm_logger/professional_logger.py` (19.88% coverage)
- **Target Coverage**: 100% for all modules

## Objectives
1. Test context detection mechanisms
2. Verify base logger abstractions
3. Test core logger implementation
4. Ensure professional logger features work
5. Test framework detection
6. Verify logging configuration

## Coverage Gap Analysis

### context_detector.py - Missing Coverage
Missing lines: 162, 166, 178-188, 199, 211-261, 265-281, 285-297, 303-325, 329-343, 348-377, 381, 390-393, 397-411, 420, 425

Key areas:
- Stack inspection
- Framework-specific detection
- Module and class detection
- Method context extraction
- Async context detection

### base.py - Missing Coverage
Missing lines: 34-37, 41-56, 70, 74, 78, 82, 86, 90, 94, 98, 102, 106-109, 113, 117, 121, 125, 129, 134-138, 143-162, 171-182, 199-292, 297

Key areas:
- Abstract method implementations
- Configuration loading
- Handler management
- Formatter setup
- Framework detection

### logger.py - Missing Coverage
Missing lines: 37-48, 53, 58-66, 70-71, 75-76, 80-81, 85-86, 90-91, 96-105, 110-119, 124-138, 144-153, 158-167, 172-184, 190-195, 201-213, 218-227, 233-237, 242, 246, 250-251, 255, 259, 280-294, 304-312, 322-323, 336

Key areas:
- Business event tracking
- Performance measurement
- Context management
- Metric collection
- Log enrichment

### professional_logger.py - Missing Coverage
Missing lines: 31-37, 41-72, 80-91, 95-111, 115-131, 135-149, 153-155, 159-168, 172-186, 190-191, 196-203, 208-217, 230-232, 245-247

Key areas:
- Professional formatting
- Business event logging
- Django operations
- Test result formatting
- Success celebrations

## Test Suite Design

### Test File: `test_context_detector_comprehensive.py`

#### 1. Basic Context Detection Tests
```python
class TestBasicContextDetection:
    - test_get_current_context
    - test_module_detection
    - test_function_detection
    - test_class_detection
    - test_method_detection
    - test_line_number_detection
```

#### 2. Framework Detection Tests
```python
class TestFrameworkDetection:
    - test_django_context_detection
    - test_flask_context_detection
    - test_fastapi_context_detection
    - test_pytest_context_detection
    - test_unittest_context_detection
    - test_no_framework_detection
```

#### 3. Stack Analysis Tests
```python
class TestStackAnalysis:
    - test_stack_depth_analysis
    - test_caller_identification
    - test_call_chain_construction
    - test_recursive_call_detection
    - test_async_stack_analysis
```

#### 4. Special Context Tests
```python
class TestSpecialContexts:
    - test_decorator_context
    - test_lambda_context
    - test_comprehension_context
    - test_generator_context
    - test_coroutine_context
```

### Test File: `test_base_logger_comprehensive.py`

#### 1. Abstract Base Tests
```python
class TestBaseLoggerAbstract:
    - test_cannot_instantiate_abstract
    - test_required_methods
    - test_abstract_properties
    - test_inheritance_requirements
```

#### 2. Configuration Tests
```python
class TestBaseLoggerConfig:
    - test_default_configuration
    - test_custom_configuration
    - test_config_validation
    - test_config_merge
    - test_environment_overrides
```

#### 3. Handler Management Tests
```python
class TestHandlerManagement:
    - test_add_handler
    - test_remove_handler
    - test_handler_levels
    - test_handler_formatters
    - test_handler_filters
```

#### 4. Framework Integration Tests
```python
class TestFrameworkIntegration:
    - test_django_detection
    - test_flask_detection
    - test_framework_specific_config
    - test_framework_handlers
```

### Test File: `test_core_logger_comprehensive.py`

#### 1. Logger Initialization Tests
```python
class TestLoggerInitialization:
    - test_default_initialization
    - test_named_logger
    - test_config_initialization
    - test_singleton_behavior
    - test_child_loggers
```

#### 2. Business Intelligence Tests
```python
class TestBusinessIntelligence:
    - test_track_business_event
    - test_measure_performance
    - test_business_metrics_collection
    - test_revenue_tracking
    - test_conversion_tracking
```

#### 3. Context Management Tests
```python
class TestContextManagement:
    - test_context_manager
    - test_nested_contexts
    - test_context_propagation
    - test_thread_local_context
    - test_async_context
```

#### 4. Log Enrichment Tests
```python
class TestLogEnrichment:
    - test_automatic_enrichment
    - test_custom_enrichment
    - test_metadata_injection
    - test_correlation_ids
    - test_user_context
```

### Test File: `test_professional_logger_comprehensive.py`

#### 1. Professional Features Tests
```python
class TestProfessionalFeatures:
    - test_professional_formatting
    - test_business_language
    - test_success_celebrations
    - test_error_guidance
    - test_recommendation_system
```

#### 2. Django Integration Tests
```python
class TestDjangoOperations:
    - test_log_django_request
    - test_log_django_response
    - test_log_model_operations
    - test_log_admin_actions
    - test_log_migrations
```

#### 3. Test Result Formatting Tests
```python
class TestResultFormatting:
    - test_format_test_results
    - test_format_coverage_report
    - test_format_performance_results
    - test_format_benchmark_results
```

#### 4. Console Integration Tests
```python
class TestConsoleIntegration:
    - test_rich_console_output
    - test_table_generation
    - test_progress_indicators
    - test_styled_output
```

## Implementation Strategy

### Phase 1: Context Detection (60 minutes)
1. Test basic context extraction
2. Verify framework detection
3. Test stack analysis
4. Check special contexts

### Phase 2: Base Logger (45 minutes)
1. Test abstract base class
2. Verify configuration system
3. Test handler management
4. Check framework integration

### Phase 3: Core Logger (45 minutes)
1. Test initialization
2. Verify business features
3. Test context management
4. Check enrichment

### Phase 4: Professional Logger (30 minutes)
1. Test professional features
2. Verify Django integration
3. Test formatting
4. Check console output

## Mock Strategies

### Mock Stack Frames
```python
def create_mock_frame(filename, function, lineno):
    frame = Mock()
    frame.f_code.co_filename = filename
    frame.f_code.co_name = function
    frame.f_lineno = lineno
    return frame

@patch('inspect.stack')
def test_with_mock_stack(mock_stack):
    mock_stack.return_value = [
        create_mock_frame("/app/module.py", "function", 42)
    ]
```

### Mock Django Environment
```python
@patch.dict('sys.modules', {'django': Mock()})
def test_django_detection():
    # Test Django-specific behavior
```

### Mock Logger Hierarchy
```python
def test_logger_hierarchy():
    parent = StormLogger("parent")
    child = StormLogger("parent.child")
    
    # Test propagation
    assert child.parent == parent
```

## Test Data

### Context Scenarios
```python
CONTEXT_SCENARIOS = [
    {
        "description": "Django view context",
        "stack": [
            ("views.py", "user_list_view", 25),
            ("django/core/handlers.py", "get_response", 115),
        ],
        "expected": {
            "framework": "django",
            "view": "user_list_view",
            "module": "views"
        }
    },
    {
        "description": "Pytest context",
        "stack": [
            ("test_models.py", "test_user_creation", 10),
            ("pytest/main.py", "runtest", 200),
        ],
        "expected": {
            "framework": "pytest",
            "test": "test_user_creation",
            "module": "test_models"
        }
    }
]
```

## Success Criteria
- 100% coverage for all core modules
- Context detection working reliably
- Base logger properly tested
- Core logger features verified
- Professional features complete
- Framework detection accurate

## Next Steps
1. Create comprehensive test files
2. Mock complex dependencies
3. Test each module systematically
4. Verify integration points
5. Update status.json
6. Move to Step 09

## Automation Notes
- Mock inspect module carefully
- Test with real stack traces
- Use fixtures for logger instances
- Test thread safety
- Verify memory management