# Functional Tests - Storm Logger

## Quick Overview for Gemini

Functional tests validate Storm Logger from a user's perspective, focusing on real-world usage scenarios and quickstart examples. These tests ensure the library works as documented and provides a great developer experience.

## Test Focus

```
functional/
├── test_quickstart.py  # Tests based on quickstart guide
└── (future tests)      # End-to-end user scenarios
```

## Functional Testing Philosophy

### What We Validate
1. **Documentation Examples**: All code in docs works
2. **User Workflows**: Common usage patterns
3. **API Contracts**: Public API stability
4. **Error Messages**: Helpful user feedback
5. **Developer Experience**: Ease of use

### Testing Approach
- Black-box testing (use public API only)
- Scenario-based validation
- User story implementation
- Documentation-driven testing

## Key Functional Scenarios

### 1. Quickstart Validation
```python
def test_quickstart_example_works():
    """Ensure quickstart code runs without modification."""
    # Exactly as shown in documentation
    from storm_logger import get_storm_logger
    
    logger = get_storm_logger("quickstart")
    logger.info("Hello from Storm Logger!")
    
    # Should work out of the box
    assert True  # No exceptions raised
```

### 2. Common User Workflows

#### New User Setup
```python
def test_first_time_user_experience():
    """Test the experience of a new user."""
    # Step 1: Import (should work after pip install)
    from storm_logger import ProfessionalStormLogger
    
    # Step 2: Get instance (should auto-configure)
    logger = ProfessionalStormLogger.get_instance()
    
    # Step 3: Use immediately
    logger.info("My first log!")
    logger.log_business_success("Setup complete!")
    
    # No configuration needed for basic use
```

#### Django Developer
```python
def test_django_developer_workflow():
    """Test Django integration workflow."""
    # In settings.py
    from storm_logger import StormLoggerConfig
    
    STORM_LOGGER_CONFIG = StormLoggerConfig.generate_django_config()
    LOGGING = STORM_LOGGER_CONFIG
    
    # In views.py
    from storm_logger import get_storm_logger
    
    logger = get_storm_logger(__name__)
    
    def my_view(request):
        logger.log_django_operation("page_view", "success")
        return JsonResponse({"status": "ok"})
```

#### Script Developer
```python
def test_script_developer_workflow():
    """Test standalone script usage."""
    from storm_logger import ProfessionalStormLogger
    
    def main():
        logger = ProfessionalStormLogger.get_instance()
        
        with logger.progress("Processing files") as progress:
            for i in range(100):
                logger.info(f"Processing file {i}")
                progress.update(1)
        
        logger.print_summary()
    
    # Should provide nice CLI output
    main()
```

### 3. Business Intelligence Features

```python
def test_business_metrics_workflow():
    """Test business intelligence features."""
    logger = get_storm_logger("business")
    
    # Track business events
    logger.track_business_event("user_signup", {
        "plan": "premium",
        "value": 99.99,
        "source": "organic"
    })
    
    # Measure performance
    @logger.measure_performance("api_call")
    def slow_operation():
        time.sleep(0.1)
        return "result"
    
    result = slow_operation()
    
    # Generate report
    report = logger.generate_business_report()
    
    # Verify report contains metrics
    assert "user_signup" in report
    assert "api_call" in report
    assert report["api_call"]["avg_duration"] > 0.1
```

## User Story Tests

### Story 1: DevOps Engineer
```python
def test_devops_monitoring_setup():
    """As a DevOps engineer, I want centralized logging."""
    # Configure for production
    config = StormLoggerConfig(
        level="INFO",
        handlers={
            "file": {
                "class": "RotatingFileHandler",
                "filename": "/var/log/app.log",
                "maxBytes": 10485760,  # 10MB
                "backupCount": 5
            },
            "syslog": {
                "class": "SysLogHandler",
                "address": ("syslog.internal", 514)
            }
        },
        formatters={
            "json": {
                "class": "JsonFormatter"
            }
        }
    )
    
    logger = StormLogger(config)
    logger.info("Application started", version="1.0.0")
    
    # Logs should go to both file and syslog
```

### Story 2: Data Scientist
```python
def test_data_scientist_notebook():
    """As a data scientist, I want clean notebook output."""
    from storm_logger import get_storm_logger
    
    logger = get_storm_logger("analysis")
    
    # Configure for Jupyter
    logger.configure_notebook_output()
    
    # Log experiment details
    logger.info("Starting experiment", {
        "model": "RandomForest",
        "parameters": {"n_estimators": 100}
    })
    
    # Track metrics
    logger.track_business_event("model_accuracy", {
        "accuracy": 0.95,
        "precision": 0.93,
        "recall": 0.97
    })
    
    # Display nice summary
    logger.display_metrics_table()
```

### Story 3: Security Engineer
```python
def test_security_compliance():
    """As a security engineer, I need PII protection."""
    from storm_logger import get_storm_logger, SanitizationConfig
    
    # Configure with high security
    logger = get_storm_logger(
        "secure_app",
        sanitization_config=SanitizationConfig(
            level="high",
            compliance_mode="GDPR",
            custom_patterns=[
                r"\b\d{3}-\d{2}-\d{4}\b",  # SSN
                r"\b[A-Z]{2}\d{6}\b"        # ID numbers
            ]
        )
    )
    
    # Log with PII (should be sanitized)
    logger.info("User login", {
        "email": "user@example.com",
        "ssn": "123-45-6789",
        "ip": "192.168.1.1"
    })
    
    # Verify sanitization in output
    log_content = read_latest_log()
    assert "123-45-6789" not in log_content
    assert "[REDACTED]" in log_content
```

## Error Scenario Testing

### 1. Helpful Error Messages
```python
def test_configuration_error_messages():
    """Test that errors guide users to solutions."""
    with pytest.raises(ValueError) as exc_info:
        StormLoggerConfig(level="INVALID")
    
    error_message = str(exc_info.value)
    assert "INVALID" in error_message
    assert "Valid levels are:" in error_message
    assert "DEBUG, INFO, WARNING" in error_message
```

### 2. Graceful Degradation
```python
def test_missing_optional_dependencies():
    """Test behavior without optional dependencies."""
    # Simulate missing colorlog
    with patch.dict('sys.modules', {'colorlog': None}):
        logger = get_storm_logger("test")
        logger.info("Should work without colorlog")
        
        # Should fall back to standard formatter
        assert logger.handlers[0].formatter.__class__.__name__ != "ColoredFormatter"
```

## API Stability Tests

### 1. Backwards Compatibility
```python
def test_api_v1_compatibility():
    """Ensure v1 API still works in v2."""
    # Old v1 style
    from storm_logger import StormLogger
    
    logger = StormLogger()  # v1 allowed no args
    logger.log("INFO", "Message")  # v1 method
    
    # Should still work with deprecation warning
    with pytest.warns(DeprecationWarning):
        logger.log("INFO", "Message")
```

### 2. Public API Contract
```python
def test_public_api_contract():
    """Test all documented public APIs exist."""
    from storm_logger import (
        get_storm_logger,
        StormLogger,
        ProfessionalStormLogger,
        StormLoggerConfig,
        ConsoleConfig,
        SanitizationConfig,
        BusinessMetricsCollector
    )
    
    # All imports should succeed
    assert all([
        get_storm_logger,
        StormLogger,
        ProfessionalStormLogger,
        StormLoggerConfig
    ])
```

## Performance Expectations

### 1. Reasonable Defaults
```python
def test_default_performance():
    """Test performance with default settings."""
    logger = get_storm_logger("perf_test")
    
    start = time.time()
    for i in range(1000):
        logger.info(f"Message {i}")
    duration = time.time() - start
    
    # Should handle 1000 messages in < 1 second
    assert duration < 1.0
```

### 2. No Blocking Operations
```python
def test_non_blocking_logging():
    """Ensure logging doesn't block main thread."""
    logger = get_storm_logger("async_test")
    
    # Configure with async handler
    logger.add_handler(AsyncFileHandler("async.log"))
    
    # Log should return immediately
    start = time.time()
    logger.info("Large message" * 10000)
    duration = time.time() - start
    
    assert duration < 0.01  # Should be near instant
```

## Documentation Validation

### 1. README Examples
```python
def test_all_readme_examples():
    """Test every code example in README."""
    # Extract code blocks from README
    readme_examples = extract_code_from_readme()
    
    for i, example in enumerate(readme_examples):
        # Execute each example
        exec(example, {"__name__": f"readme_example_{i}"})
```

### 2. Docstring Examples
```python
def test_docstring_examples():
    """Test code examples in docstrings."""
    import doctest
    import storm_logger
    
    # Run all docstring examples
    results = doctest.testmod(storm_logger)
    assert results.failed == 0
```

## Running Functional Tests

```bash
# Run all functional tests
pytest tests/functional/ -v

# Run quickstart tests
pytest tests/functional/test_quickstart.py

# Run with output capture disabled (see console output)
pytest tests/functional/ -s

# Run specific scenario
pytest tests/functional/ -k "django_workflow"
```

## Best Practices

### 1. User-Centric Testing
- Test from user's perspective
- Use only public APIs
- Verify documentation accuracy

### 2. Scenario Coverage
- Cover all user types
- Test common workflows
- Include error scenarios

### 3. Experience Testing
- First-time user experience
- Migration scenarios
- Upgrade paths

## Adding New Functional Tests

### 1. Identify User Story
```python
def test_microservice_developer():
    """As a microservice developer, I need structured logging."""
    # Implementation
```

### 2. Test End-to-End
```python
def test_complete_user_journey():
    """Test from install to production."""
    # 1. Configuration
    # 2. Development
    # 3. Testing
    # 4. Deployment
```

### 3. Validate Documentation
```python
def test_tutorial_scenario():
    """Ensure tutorial code works exactly as shown."""
    # Copy-paste from docs should work
```

## Next Steps

- Add more user story tests
- Test migration scenarios
- Validate all documentation examples
- Add performance expectation tests