# Test Report — Token Usage Tracking & Quota Enforcement

**Date:** 2026-06-19
**Command:** `pytest tests/ -v`
**Result:** ✅ **52 passed, 0 failed** in 3.41s
**Environment:** `.venv` (Python 3.11.9), pytest 9.0.3

## Summary by file

| Test file | Cases | Status | Scope |
|---|---|---|---|
| `tests/test_quota_service.py` | 10 | ✅ All passed | Core quota logic: precedence, timezone boundaries, 80%/100% thresholds, usage recording |
| `tests/test_admin_quota_routes.py` | 11 | ✅ All passed | Admin API-key auth + CRUD + usage report endpoints |
| `tests/test_api.py` → `TestQuotaEnforcement` | 2 | ✅ All passed | End-to-end: 429 blocks before LLM call, 80% warning surfaces via SSE |
| `tests/test_api.py` → pre-existing suites | 29 | ✅ All passed (no regressions) | `/hr-assist-stream`, Redis-failure resilience, `/conversations` |

**New tests added for this feature: 23. Pre-existing tests: 29 — all still green after the change.**

## Detailed results

### `tests/test_quota_service.py` (quota resolution & threshold logic)

| # | Test | Verifies |
|---|---|---|
| 1 | `test_resolve_policy_returns_none_when_no_rows` | No policy configured → `None` (unlimited) |
| 2 | `test_resolve_policy_precedence_user_over_role_over_default` | Most-specific-wins: user > role > default |
| 3 | `test_resolve_policy_ignores_inactive_rows` | `is_active=False` rows are skipped |
| 4 | `test_period_boundary_respects_configured_timezone` | A 23:59 local-time entry doesn't leak into the next day's window (Asia/Kolkata) |
| 5 | `test_usage_in_window_sums_only_current_period` | Daily sum excludes rows outside the window; monthly includes them |
| 6 | `test_check_quota_unlimited_when_no_policy` | No policy → `allowed=True`, `policy_source="unlimited"` |
| 7 | `test_check_quota_warns_at_80_percent` | 850/1000 tokens → warning, still allowed |
| 8 | `test_check_quota_blocks_at_100_percent` | 1000/1000 tokens → breach, `allowed=False` |
| 9 | `test_check_quota_allows_when_under_limit` | 500/1000 tokens → no warning, no breach |
| 10 | `test_record_usage_inserts_row` | `record_usage()` persists a correct `TokenUsageLog` row |

### `tests/test_admin_quota_routes.py` (admin surface, gated by `X-Api-Key`)

| # | Test | Verifies |
|---|---|---|
| 1 | `test_missing_api_key_returns_401` | No `X-Api-Key` header → 401 |
| 2 | `test_wrong_api_key_returns_401` | Wrong key → 401 |
| 3 | `test_correct_api_key_is_allowed` | Correct key → 200 |
| 4 | `test_create_and_list_policy` | POST then GET round-trip |
| 5 | `test_create_default_scope_requires_no_scope_id` | `scope_type="default"` with no `scope_id` → 201 |
| 6 | `test_create_non_default_scope_without_scope_id_is_rejected` | `scope_type="user"` with no `scope_id` → 400 |
| 7 | `test_create_duplicate_active_scope_is_rejected` | Second active policy for the same scope → 409 |
| 8 | `test_patch_updates_limits` | PATCH updates limits and `is_active` |
| 9 | `test_patch_nonexistent_policy_returns_404` | PATCH on missing ID → 404 |
| 10 | `test_delete_policy` | DELETE removes the row |
| 11 | `test_usage_report_filters_by_user_id` | Usage report correctly filters and aggregates by `user_id` |

### `tests/test_api.py::TestQuotaEnforcement` (full-stack integration)

| # | Test | Verifies |
|---|---|---|
| 1 | `test_quota_exceeded_blocks_before_llm_call` | A breached quota returns HTTP 429 with `quota_exceeded` detail, and `hr_graph.astream` is **never invoked** — zero token spend on a blocked request |
| 2 | `test_quota_allowed_with_warning_surfaces_quota_status_event` | An 80%+ warning is delivered as the first SSE event (`quota_status`), and the request still completes normally |

### Pre-existing suites (regression check — all still passing)

- `TestHrAssistStream` (10 tests) — happy path, cache hits, non-HR redirect, guardrail blocking, auth failures
- `TestRedisFailure` (8 tests) — Redis outage resilience for reads/writes/cache
- `TestListConversations` (5 tests) — listing, auth, JWT validation
- `TestDeleteConversation` (6 tests) — soft-delete, auth, JWT validation

## Notes

- `tests/test_quota_service.py` and `tests/test_admin_quota_routes.py` use a real in-memory SQLite session (not a `MagicMock`) so that `SUM`/`WHERE` aggregation and timezone math execute against genuine SQL — a mock can't fake that semantics.
- `tests/conftest.py` was extended to override `enforce_token_quota` (defaulting to "allowed") for all pre-existing tests that don't exercise quota logic, so the new dependency doesn't break unrelated test coverage.
- Warnings in the raw log output (DeepSeek `401 Unauthorized`, Redis `connection refused`) are **expected** — tests run with fake API keys and no local Redis, and the code's fallback paths are exactly what's being tested (titles fall back to truncated text, history falls back to DB, etc.). They are not failures.
