Skip to content
Shell
13.7 KB
Raw Blame

Test Coverage Improvement Plan

Branch: feature/test-coverage-improvement Current Coverage: 23.22% Target Coverage: 70%+ Estimated New Tests: 420-490 tests


Executive Summary

Increase test coverage from 23% to 70%+ by systematically addressing three critical gaps:

  1. Execution Layer (2,574 lines at 0%) - Order routing, TWAP, VWAP, slippage
  2. API Server (1,194 lines at 0%) - 35 endpoints including Stripe webhooks
  3. Data Clients (853 lines at 13%) - Alpaca WebSocket, rate limiting

Phase 1: Execution Layer (Critical Priority)

Target: +15% coverage (to ~38%) New Tests: ~180 tests Files to Create/Modify:

1.1 Create tests/unit/test_execution_router.py (~35 tests)

Test Categories:

  • Edge cases (None price fallback, invalid inputs)
  • Strategy selection logic (participation rate, urgency)
  • Error recovery (retries, fallbacks, cancellation)
  • Statistics and reporting

1.2 Create tests/unit/test_twap_executor.py (~40 tests)

Test Categories:

  • Slice planning (min/max slices, timing distribution)
  • Execution flow (cancellation, pause/resume, failures)
  • Partial fills handling
  • Performance metrics

1.3 Create tests/unit/test_vwap_executor.py (~40 tests)

Test Categories:

  • Volume profile (normalization, custom patterns)
  • Slice weighting accuracy
  • Deviation tracking and alerts
  • Results calculation

1.4 Create tests/unit/test_slippage_model.py (~35 tests)

Test Categories:

  • Estimation for various stock types (micro-cap to mega-cap)
  • Market impact models
  • Historical tracking and statistics
  • Execution quality scoring

1.5 Create tests/unit/test_execution_monitor.py (~30 tests)

Test Categories:

  • Alert generation and severity escalation
  • Alert lifecycle (acknowledge, resolve, expire)
  • Daily metrics aggregation
  • Quality score calculation

1.6 Create tests/fixtures/execution_fixtures.py

# Key fixtures to create:
mock_order_manager          # Standard mock
mock_order_manager_failing  # Simulates failures
mock_order_manager_partial  # Returns partial fills
twap_executor              # With mock dependencies
vwap_executor              # With mock dependencies
slippage_model             # Configured model
execution_router           # Full router setup
execution_monitor          # Monitor instance

Phase 2: API Server (High Priority)

Target: +12% coverage (to ~50%) New Tests: ~120 tests Files to Create:

2.1 Create tests/unit/test_api_server.py (~80 tests)

Endpoint Categories:

  • Health & core endpoints (15 tests)
  • Order management - place/cancel (25 tests)
  • Position management (20 tests)
  • Account & strategy (15 tests)
  • Error handling (20 tests)

2.2 Create tests/unit/test_api_stripe.py (~25 tests)

Test Categories:

  • Checkout session creation
  • Webhook signature verification
  • Subscription event handlers
  • Payment failure handling

2.3 Create tests/unit/test_api_websocket.py (~15 tests)

Test Categories:

  • Connection lifecycle
  • Message broadcasting
  • Concurrent connections

2.4 Create tests/fixtures/api_fixtures.py

# Key fixtures to create:
test_client       # FastAPI TestClient
mock_paper_trader # With positions
mock_stripe       # Mocked Stripe client
mock_supabase     # Mocked Supabase client
auth_headers      # Valid JWT headers

Phase 3: Data Clients (Medium Priority)

Target: +8% coverage (to ~58%) New Tests: ~80 tests Files to Modify:

3.1 Expand tests/unit/test_alpaca_client.py (~50 tests)

New Test Categories:

  • WebSocket streaming (quote/trade/bar handling)
  • Reconnection logic (exponential backoff)
  • Subscription management
  • Callback registration and execution
  • News API integration
  • Thread safety (locks, concurrent access)

3.2 Create tests/unit/test_market_data_manager.py (~30 tests)

Test Categories:

  • Historical data retrieval
  • Multi-source aggregation
  • Data normalization
  • Caching behavior

Phase 4: Integration Tests (Medium Priority)

Target: +12% coverage (to ~70%) New Tests: ~40 tests Files to Create:

4.1 Create tests/integration/test_execution_integration.py (~25 tests)

  • Full order flow (market, TWAP, VWAP)
  • Execution with monitoring
  • Multi-order coordination

4.2 Expand tests/integration/test_api_integration.py (~15 tests)

  • Quote-to-order flow
  • Position management lifecycle
  • Strategy screen to order

Critical Files Reference

File Lines Current Action
core/execution/router.py 573 0% Test in Phase 1
core/execution/twap.py 478 0% Test in Phase 1
core/execution/vwap.py 551 0% Test in Phase 1
core/execution/slippage.py 444 0% Test in Phase 1
core/execution/monitor.py 528 0% Test in Phase 1
core/api_server.py 1194 0% Test in Phase 2
core/data/alpaca_client.py 854 13% Expand in Phase 3
tests/conftest.py 195 N/A Add fixtures

Implementation Order

Phase 1.1: test_execution_router.py + fixtures
Phase 1.2: test_twap_executor.py
Phase 1.3: test_vwap_executor.py
Phase 1.4: test_slippage_model.py
Phase 1.5: test_execution_monitor.py
   [CHECKPOINT: Run coverage, verify ~38%]

Phase 2.1: test_api_server.py + fixtures
Phase 2.2: test_api_stripe.py
Phase 2.3: test_api_websocket.py
   [CHECKPOINT: Run coverage, verify ~50%]

Phase 3.1: Expand test_alpaca_client.py
Phase 3.2: test_market_data_manager.py
   [CHECKPOINT: Run coverage, verify ~58%]

Phase 4.1: test_execution_integration.py
Phase 4.2: Expand test_api_integration.py
   [FINAL: Run coverage, verify ~70%]

Success Criteria

Phase Tests Coverage Verification Command
1 ~180 38% pytest tests/unit/test_execution*.py --cov=core/execution
2 ~120 50% pytest tests/unit/test_api*.py --cov=core/api_server
3 ~80 58% pytest tests/unit/test_alpaca*.py --cov=core/data
4 ~40 70% pytest --cov=core --cov-report=html

Quality Standards

  1. Speed: Each test < 100ms (use AsyncMock, no real I/O)
  2. Isolation: Tests must not share state
  3. Determinism: Mock time/random for reproducibility
  4. Patterns: Follow existing style in test_execution.py
  5. Coverage: Each module targets 80%+ line coverage

Orchestration Architecture

Delegation Strategy

Claude (Orchestrator) watches over agents, fixes errors, and verifies before moving to next task.

Phase 1 Agents (Parallel Execution)

Task Agent Type Tool/MCP Responsibility
1.1 Router Tests test-engineer Bash (pytest) Write test_execution_router.py
1.2 TWAP Tests test-engineer Bash (pytest) Write test_twap_executor.py
1.3 VWAP Tests test-engineer Bash (pytest) Write test_vwap_executor.py
1.4 Slippage Tests test-engineer Bash (pytest) Write test_slippage_model.py
1.5 Monitor Tests test-engineer Bash (pytest) Write test_execution_monitor.py
1.6 Fixtures test-engineer Write Create execution_fixtures.py
Verification code-reviewer Bash (pytest --cov) Verify 38% coverage reached

Phase 2 Agents (Parallel Execution)

Task Agent Type Tool/MCP Responsibility
2.1 API Server Tests test-engineer Bash (pytest) Write test_api_server.py
2.2 Stripe Tests test-engineer Bash (pytest) Write test_api_stripe.py
2.3 WebSocket Tests test-engineer Bash (pytest) Write test_api_websocket.py
2.4 API Fixtures test-engineer Write Create api_fixtures.py
Verification code-reviewer Bash (pytest --cov) Verify 50% coverage reached

Phase 3 Agents (Parallel Execution)

Task Agent Type Tool/MCP Responsibility
3.1 Alpaca Client test-engineer Bash (pytest) Expand test_alpaca_client.py
3.2 Market Data test-engineer Bash (pytest) Write test_market_data_manager.py
Verification code-reviewer Bash (pytest --cov) Verify 58% coverage reached

Phase 4 Agents (Parallel Execution)

Task Agent Type Tool/MCP Responsibility
4.1 Execution Integration test-engineer Bash (pytest) Write test_execution_integration.py
4.2 API Integration test-engineer Bash (pytest) Expand test_api_integration.py
Final Verification code-reviewer Bash (pytest --cov) Verify 70% coverage reached

Verification Protocol (After Each Task)

1. Run: pytest <test_file> -v --tb=short
2. Check: All tests pass (0 failures)
3. Run: pytest <test_file> --cov=<module> --cov-report=term-missing
4. Check: Coverage meets target for module (80%+)
5. If failures: Debug, fix, re-run
6. If coverage low: Add more test cases
7. Commit only when both pass and coverage targets met

Tools & MCPs Assignment

Tool/MCP Purpose When Used
Bash (pytest) Run tests, coverage After each test file written
Write Create new test files Phase 1-4 test creation
Edit Modify existing tests Fix failures, add tests
Read Examine source modules Understanding code to test
Grep Find patterns in tests Ensure consistent patterns
code-reviewer agent Review test quality After each phase
test-engineer agent Write tests All phases
debugger agent Fix test failures When tests fail

Execution Flow

┌─────────────────────────────────────────────────────────┐
│                    PHASE 1 START                        │
├─────────────────────────────────────────────────────────┤
│  [Parallel] test-engineer agents write:                 │
│    - test_execution_router.py                           │
│    - test_twap_executor.py                              │
│    - test_vwap_executor.py                              │
│    - test_slippage_model.py                             │
│    - test_execution_monitor.py                          │
│    - execution_fixtures.py                              │
├─────────────────────────────────────────────────────────┤
│  Claude: Run pytest --cov, verify each file passes     │
│  If failure → debugger agent fixes → re-verify         │
├─────────────────────────────────────────────────────────┤
│  code-reviewer: Verify 38% total coverage              │
│  If not met → add more tests → re-verify               │
├─────────────────────────────────────────────────────────┤
│  CHECKPOINT: git commit "Phase 1: Execution tests"      │
└─────────────────────────────────────────────────────────┘
                         ↓
┌─────────────────────────────────────────────────────────┐
│                    PHASE 2 START                        │
│            (Same pattern as Phase 1)                    │
└─────────────────────────────────────────────────────────┘
                         ↓
                    (Phase 3, 4...)
                         ↓
┌─────────────────────────────────────────────────────────┐
│                   FINAL VERIFICATION                    │
├─────────────────────────────────────────────────────────┤
│  pytest --cov=core --cov-report=html                    │
│  Verify: Overall coverage >= 70%                        │
│  Generate: htmlcov/index.html report                    │
│  Commit: All changes with coverage report               │
└─────────────────────────────────────────────────────────┘

Error Handling Protocol

Error Type Handler Action
Test failure debugger agent Analyze traceback, fix test or source
Import error Claude Fix imports, check module paths
Async error Claude Verify @pytest.mark.asyncio, AsyncMock usage
Coverage below target test-engineer Add more test cases for uncovered lines
Flaky test Claude Mock time/random, ensure determinism

Commit Strategy

Phase 1 complete → git commit -m "test: add execution layer tests (38% coverage)"
Phase 2 complete → git commit -m "test: add API server tests (50% coverage)"
Phase 3 complete → git commit -m "test: expand data client tests (58% coverage)"
Phase 4 complete → git commit -m "test: add integration tests (70% coverage)"
Final → git push origin feature/test-coverage-improvement