# Step 06: Business Metrics Tests

## Status Reference
- **Current Status**: Pending
- **Dependencies**: Steps 01-05 should be complete
- **Target Module**: `storm_logger/utils/business_metrics.py` (21.40% coverage)
- **Target Coverage**: 100%

## Objectives
1. Test singleton pattern implementation
2. Verify metric collection and aggregation
3. Test performance tracking capabilities
4. Validate business event tracking
5. Test report generation and export features
6. Ensure thread safety for concurrent metrics

## Coverage Gap Analysis

### Missing Coverage
Missing lines: 39-50, 54, 75-77, 82-98, 109-122, 133, 155-166, 171-201, 205-206, 222-233, 237, 241, 245, 249-266, 270-288, 292-303, 307-346, 350-377, 381-382, 386-412, 422-424

Key areas:
- Singleton instance management
- Metric recording methods
- Aggregation algorithms
- Report generation
- Export functionality
- Trend analysis
- Performance optimizations

## Test Suite Design

### Test File: `test_business_metrics_comprehensive.py`

#### 1. Singleton Pattern Tests
```python
class TestBusinessMetricsSingleton:
    - test_singleton_instance_creation
    - test_singleton_same_instance
    - test_singleton_thread_safety
    - test_singleton_reset_capability
    - test_singleton_with_config
```

#### 2. Metric Collection Tests
```python
class TestMetricCollection:
    - test_record_performance_metric
    - test_record_business_event
    - test_record_error_metric
    - test_record_custom_metric
    - test_metric_with_metadata
    - test_metric_timestamps
    - test_metric_categorization
```

#### 3. Aggregation Tests
```python
class TestMetricAggregation:
    - test_calculate_average
    - test_calculate_percentiles
    - test_calculate_min_max
    - test_calculate_sum
    - test_calculate_rate
    - test_time_window_aggregation
    - test_grouped_aggregation
```

#### 4. Business Event Tests
```python
class TestBusinessEvents:
    - test_track_revenue_event
    - test_track_conversion_event
    - test_track_user_action
    - test_track_system_event
    - test_event_correlation
    - test_event_timeline
```

#### 5. Report Generation Tests
```python
class TestReportGeneration:
    - test_generate_summary_report
    - test_generate_detailed_report
    - test_generate_trend_report
    - test_generate_comparison_report
    - test_custom_report_template
    - test_report_formatting
```

#### 6. Export Tests
```python
class TestMetricExport:
    - test_export_to_json
    - test_export_to_csv
    - test_export_to_dict
    - test_export_with_filters
    - test_export_time_range
    - test_export_compression
```

#### 7. Performance Tests
```python
class TestMetricsPerformance:
    - test_high_volume_metrics
    - test_concurrent_recording
    - test_memory_efficiency
    - test_metric_rotation
    - test_cleanup_old_metrics
```

## Implementation Details

### Phase 1: Core Functionality (45 minutes)
1. Test singleton pattern thoroughly
2. Implement basic metric recording
3. Test all metric types
4. Verify data structures

### Phase 2: Aggregation and Analysis (30 minutes)
1. Test statistical calculations
2. Verify time-based aggregations
3. Test grouping and filtering
4. Check trend analysis

### Phase 3: Reporting and Export (15 minutes)
1. Test report generation
2. Verify export formats
3. Test filtering and customization
4. Check output quality

## Test Scenarios

### Business Scenarios
```python
# Revenue tracking scenario
def test_revenue_tracking_scenario():
    collector = BusinessMetricsCollector.get_instance()
    
    # Record sales
    collector.record_event("sale", {"amount": 99.99, "product": "Pro"})
    collector.record_event("sale", {"amount": 49.99, "product": "Basic"})
    
    # Generate report
    report = collector.generate_report("revenue")
    assert report["total_revenue"] == 149.98
    assert report["transactions"] == 2
```

### Performance Tracking
```python
# API performance scenario
def test_api_performance_tracking():
    collector = BusinessMetricsCollector.get_instance()
    
    # Record API calls
    for i in range(100):
        collector.record_performance("api_call", 
                                   random.uniform(0.1, 0.5))
    
    # Check aggregations
    stats = collector.get_performance_stats("api_call")
    assert stats["p95"] < 0.5
    assert stats["avg"] < 0.3
```

### Trend Analysis
```python
# Usage trend scenario
def test_usage_trends():
    collector = BusinessMetricsCollector.get_instance()
    
    # Simulate daily usage
    for day in range(30):
        users = 1000 + (day * 10)  # Growing usage
        collector.record_event("daily_active_users", 
                             {"count": users, "day": day})
    
    # Analyze trend
    trend = collector.analyze_trend("daily_active_users")
    assert trend["direction"] == "increasing"
    assert trend["growth_rate"] > 0
```

## Mock Requirements

### Time Mocking
```python
@freeze_time("2024-01-01 12:00:00")
def test_with_fixed_time():
    # Test time-based metrics
    pass
```

### Thread Testing
```python
def test_concurrent_metric_recording():
    collector = BusinessMetricsCollector.get_instance()
    
    def record_metrics(thread_id):
        for i in range(1000):
            collector.record_metric(f"thread_{thread_id}", i)
    
    threads = [Thread(target=record_metrics, args=(i,)) 
               for i in range(10)]
    # Verify thread safety
```

## Test Data

### Sample Metrics
```python
SAMPLE_METRICS = {
    "performance": {
        "response_times": [0.1, 0.2, 0.15, 0.3, 0.12],
        "memory_usage": [100, 120, 115, 130, 125],
        "cpu_usage": [20, 25, 30, 22, 28]
    },
    "business": {
        "revenue": [1000, 1200, 1100, 1300, 1250],
        "users": [100, 110, 120, 125, 130],
        "conversions": [10, 12, 11, 13, 14]
    }
}
```

## Success Criteria
- 100% coverage for business_metrics.py
- All metric types tested
- Aggregation algorithms verified
- Report generation working
- Export formats tested
- Thread safety confirmed
- Performance benchmarks met

## Next Steps
1. Create comprehensive test file
2. Implement singleton tests first
3. Add metric recording tests
4. Test aggregation and analysis
5. Verify reporting features
6. Update status.json
7. Move to Step 07

## Automation Notes
- Use fixtures for collector instance
- Mock time for consistent tests
- Use parameterized tests for metric types
- Test edge cases (empty data, None values)
- Ensure cleanup between tests