# Story 11.1: fapilog-audit Test Coverage to 90%

**Status:** Ready
**Priority:** High
**Epic:** 11 - fapilog-audit Enterprise Audit Trail
**Effort:** Medium (2-3 days)
**Dependencies:** None

---

## Context / Background

The fapilog-audit package was extracted from core fapilog (Story 4.44) with existing tests, but coverage is insufficient for a production-grade package:

| Metric | Current | Target |
|--------|---------|--------|
| Line coverage | 52% | 90% |
| Branch coverage | 22% | 80% |

Before adding new features (pluggable storage, HMAC, alerting), the existing codebase must be properly tested to:
- Prevent regressions when refactoring
- Document expected behavior through tests
- Ensure edge cases are handled correctly
- Build confidence for enterprise adoption

---

## Scope

### In Scope

- Unit tests for all public API methods
- Edge case coverage (empty inputs, boundary conditions, invalid states)
- Error handling path coverage
- Async behavior tests under concurrent load
- Integration tests with fapilog core pipeline

### Out of Scope

- New features (covered by stories 4.10-4.18)
- Performance benchmarks (separate story if needed)
- Mutation testing (nice-to-have, not required)

---

## Acceptance Criteria

### AC1: Line Coverage >= 90%

**Description:** All modules meet 90% line coverage.

**Validation:**
```bash
cd packages/fapilog-audit
pytest --cov=src/fapilog_audit --cov-report=term-missing --cov-fail-under=90
```

### AC2: Branch Coverage >= 80%

**Description:** All conditional branches adequately tested.

**Validation:**
```bash
pytest --cov=src/fapilog_audit --cov-branch --cov-report=term-missing
# Branch coverage >= 80%
```

### AC3: audit.py Full Coverage

**Description:** The main `audit.py` module (917 lines) has comprehensive test coverage.

**Key areas to test:**
- `AuditTrail` lifecycle (start, stop, restart)
- `AuditEvent` creation and serialization
- Hash chain computation and verification
- `CompliancePolicy` validation and enforcement
- Named instance management
- File rotation and cleanup
- Error recovery paths

### AC4: compliance.py Full Coverage

**Description:** All validation functions tested with valid and invalid inputs.

**Key areas to test:**
- `validate_compliance_policy()` with all compliance levels
- `validate_data_handling()` edge cases
- `validate_audit_config()` with missing/invalid fields
- Warning emission paths

### AC5: sink.py Full Coverage

**Description:** `AuditSink` integration with fapilog pipeline tested.

**Key areas to test:**
- Sink lifecycle (start, emit, flush, close)
- Configuration validation
- Error handling during emit
- Backpressure behavior

### AC6: Concurrent Async Tests

**Description:** Async behavior tested under concurrent load.

**Validation:**
```python
async def test_concurrent_audit_events():
    trail = AuditTrail()
    await trail.start()

    # Fire 100 events concurrently
    await asyncio.gather(*[
        trail.log_event(f"event-{i}")
        for i in range(100)
    ])

    # Verify all events recorded with correct sequence
    assert trail.event_count == 100
```

---

## Implementation Notes

### Coverage Gaps to Address

Based on current coverage report, focus on:

1. **audit.py (~49% covered)**
   - `AuditTrail._store_event()` error paths
   - `verify_chain()` edge cases (empty chain, corrupted events)
   - `CompliancePolicy` level-specific behavior
   - File rotation triggers
   - Named instance creation/cleanup

2. **compliance.py (~60% covered)**
   - All validation error paths
   - Warning emission for each validation type
   - Edge cases in `DataHandlingSettings`

3. **sink.py (~55% covered)**
   - `AuditSink.emit()` with various event types
   - Configuration defaults and overrides
   - Graceful shutdown paths

### Test Organization

```
packages/fapilog-audit/tests/
├── test_audit_trail.py        # AuditTrail unit tests
├── test_audit_events.py       # AuditEvent creation/serialization
├── test_audit_chain.py        # Hash chain verification
├── test_compliance_policy.py  # CompliancePolicy tests
├── test_compliance_validation.py  # Validation function tests
├── test_sink.py               # AuditSink tests
├── test_concurrent.py         # Async concurrency tests
└── test_integration.py        # Integration with fapilog core
```

---

## Tasks

- [ ] Audit current coverage report to identify specific gaps
- [ ] Write unit tests for `AuditTrail` lifecycle methods
- [ ] Write unit tests for `AuditEvent` edge cases
- [ ] Write unit tests for hash chain verification
- [ ] Write unit tests for `CompliancePolicy` levels
- [ ] Write tests for all `compliance.py` validation functions
- [ ] Write tests for `AuditSink` lifecycle and error paths
- [ ] Write concurrent async tests
- [ ] Write integration tests with fapilog pipeline
- [ ] Verify coverage >= 90% line, >= 80% branch

---

## Definition of Done

- [ ] Line coverage >= 90% for all modules
- [ ] Branch coverage >= 80% for all modules
- [ ] All tests pass in CI
- [ ] No flaky tests
- [ ] Test code follows project conventions

---

## Risks

1. **Risk:** Some code paths may be dead code
   - **Mitigation:** Run vulture; remove dead code rather than testing it

2. **Risk:** Testing async file I/O is complex
   - **Mitigation:** Use `pytest-asyncio` and mock file system where needed

---

## Related Stories

- **Blocks:** 4.10, 4.11, 4.12, 4.14-4.18 (new features should build on tested foundation)
- **Related:** Story 4.44 (extraction that created this package)
