|
2 | 2 |
|
3 | 3 | from __future__ import annotations |
4 | 4 |
|
| 5 | +import asyncio |
| 6 | +import sys |
5 | 7 | import time |
| 8 | +from types import SimpleNamespace |
6 | 9 |
|
7 | 10 | import pytest |
8 | 11 |
|
| 12 | +import headroom.subscription.copilot_quota as quota_module |
9 | 13 | from headroom.subscription.copilot_quota import ( |
10 | 14 | CopilotQuotaCategory, |
11 | 15 | CopilotQuotaSnapshot, |
| 16 | + CopilotQuotaState, |
| 17 | + _CopilotQuotaTracker, |
12 | 18 | discover_github_token, |
| 19 | + get_copilot_quota_tracker, |
13 | 20 | parse_copilot_quota, |
14 | 21 | ) |
15 | 22 |
|
@@ -65,6 +72,10 @@ def test_used_percent_clipped_at_zero(self): |
65 | 72 | cat = CopilotQuotaCategory(name="chat", percent_remaining=110.0) |
66 | 73 | assert cat.used_percent == pytest.approx(0.0) |
67 | 74 |
|
| 75 | + def test_used_percent_none_when_entitlement_is_zero(self): |
| 76 | + cat = CopilotQuotaCategory(name="chat", entitlement=0, remaining=0) |
| 77 | + assert cat.used_percent is None |
| 78 | + |
68 | 79 |
|
69 | 80 | # --------------------------------------------------------------------------- |
70 | 81 | # parse_copilot_quota |
@@ -329,3 +340,129 @@ def _count_event_wait() -> int: |
329 | 340 | assert residual <= baseline, ( |
330 | 341 | f"CopilotQuotaTracker left residual Event.wait: baseline={baseline} residual={residual}" |
331 | 342 | ) |
| 343 | + |
| 344 | + |
| 345 | +def test_copilot_quota_state_to_dict_and_tracker_get_stats() -> None: |
| 346 | + state = CopilotQuotaState() |
| 347 | + tracker = _CopilotQuotaTracker() |
| 348 | + |
| 349 | + assert state.to_dict()["latest"] is None |
| 350 | + assert tracker.get_stats() is None |
| 351 | + |
| 352 | + state.latest = CopilotQuotaSnapshot(login="octocat") |
| 353 | + state.last_error = "boom" |
| 354 | + state.last_updated = 123.0 |
| 355 | + tracker._state = state |
| 356 | + |
| 357 | + assert tracker.get_stats()["last_error"] == "boom" |
| 358 | + |
| 359 | + |
| 360 | +@pytest.mark.asyncio |
| 361 | +async def test_tracker_stop_cancels_when_wait_times_out(monkeypatch: pytest.MonkeyPatch) -> None: |
| 362 | + tracker = _CopilotQuotaTracker() |
| 363 | + tracker._stop_event = asyncio.Event() |
| 364 | + tracker._task = asyncio.create_task(asyncio.sleep(60)) |
| 365 | + |
| 366 | + async def fake_wait_for(awaitable, timeout): # noqa: ANN001, ANN202 |
| 367 | + raise asyncio.TimeoutError |
| 368 | + |
| 369 | + monkeypatch.setattr(quota_module.asyncio, "wait_for", fake_wait_for) |
| 370 | + |
| 371 | + await tracker.stop() |
| 372 | + await asyncio.sleep(0) |
| 373 | + |
| 374 | + assert tracker._task.cancelled() is True |
| 375 | + |
| 376 | + |
| 377 | +def _install_fake_aiohttp( |
| 378 | + monkeypatch: pytest.MonkeyPatch, |
| 379 | + *, |
| 380 | + payload: dict | None = None, |
| 381 | + status: int = 200, |
| 382 | + ok: bool = True, |
| 383 | + exc: Exception | None = None, |
| 384 | +) -> None: |
| 385 | + class FakeTimeout: |
| 386 | + def __init__(self, total: float) -> None: |
| 387 | + self.total = total |
| 388 | + |
| 389 | + class FakeResponse: |
| 390 | + def __init__(self) -> None: |
| 391 | + self.status = status |
| 392 | + self.ok = ok |
| 393 | + |
| 394 | + async def __aenter__(self): |
| 395 | + if exc is not None: |
| 396 | + raise exc |
| 397 | + return self |
| 398 | + |
| 399 | + async def __aexit__(self, exc_type, exc_value, traceback) -> bool: |
| 400 | + return False |
| 401 | + |
| 402 | + async def json(self): |
| 403 | + return payload or {} |
| 404 | + |
| 405 | + class FakeSession: |
| 406 | + async def __aenter__(self): |
| 407 | + return self |
| 408 | + |
| 409 | + async def __aexit__(self, exc_type, exc_value, traceback) -> bool: |
| 410 | + return False |
| 411 | + |
| 412 | + def get(self, url: str, headers: dict[str, str], timeout: FakeTimeout): |
| 413 | + assert url.endswith("/copilot_internal/user") |
| 414 | + assert headers["Authorization"].startswith("Bearer ") |
| 415 | + assert timeout.total == 10 |
| 416 | + return FakeResponse() |
| 417 | + |
| 418 | + monkeypatch.setitem( |
| 419 | + sys.modules, |
| 420 | + "aiohttp", |
| 421 | + SimpleNamespace(ClientTimeout=FakeTimeout, ClientSession=lambda: FakeSession()), |
| 422 | + ) |
| 423 | + |
| 424 | + |
| 425 | +@pytest.mark.asyncio |
| 426 | +async def test_maybe_poll_covers_response_and_singleton_paths( |
| 427 | + monkeypatch: pytest.MonkeyPatch, |
| 428 | +) -> None: |
| 429 | + tracker = _CopilotQuotaTracker() |
| 430 | + monkeypatch.setattr(quota_module, "discover_github_token", lambda: "ghp-test") |
| 431 | + |
| 432 | + _install_fake_aiohttp(monkeypatch, status=401) |
| 433 | + await tracker._maybe_poll() |
| 434 | + assert tracker._state.last_error == "unauthorized — check GITHUB_TOKEN" |
| 435 | + |
| 436 | + _install_fake_aiohttp(monkeypatch, status=404) |
| 437 | + await tracker._maybe_poll() |
| 438 | + assert tracker._state.last_error == "endpoint not found (non-Copilot account?)" |
| 439 | + |
| 440 | + _install_fake_aiohttp(monkeypatch, status=500, ok=False) |
| 441 | + await tracker._maybe_poll() |
| 442 | + assert tracker._state.last_error == "HTTP 500" |
| 443 | + |
| 444 | + _install_fake_aiohttp(monkeypatch, exc=RuntimeError("network down")) |
| 445 | + await tracker._maybe_poll() |
| 446 | + assert tracker._state.last_error == "network down" |
| 447 | + |
| 448 | + _install_fake_aiohttp(monkeypatch, payload={"quota_snapshots": {}}) |
| 449 | + monkeypatch.setattr( |
| 450 | + quota_module, |
| 451 | + "parse_copilot_quota", |
| 452 | + lambda data: (_ for _ in ()).throw(ValueError("bad")), |
| 453 | + ) |
| 454 | + await tracker._maybe_poll() |
| 455 | + assert tracker._state.last_error == "parse error: bad" |
| 456 | + |
| 457 | + monkeypatch.setattr(quota_module, "parse_copilot_quota", parse_copilot_quota) |
| 458 | + _install_fake_aiohttp(monkeypatch, payload=_SAMPLE_RESPONSE) |
| 459 | + await tracker._maybe_poll() |
| 460 | + assert tracker._state.latest is not None |
| 461 | + assert tracker._state.latest.login == "octocat" |
| 462 | + assert tracker._state.last_error is None |
| 463 | + assert tracker._state.last_updated is not None |
| 464 | + |
| 465 | + quota_module._singleton = None |
| 466 | + first = get_copilot_quota_tracker() |
| 467 | + second = get_copilot_quota_tracker() |
| 468 | + assert first is second |
0 commit comments