|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import asyncio |
| 4 | +from typing import Any |
| 5 | +from collections.abc import Iterator |
| 6 | + |
| 7 | +import httpx |
| 8 | +import pytest |
| 9 | + |
| 10 | +from kernel import Kernel, AsyncKernel |
| 11 | +from kernel._exceptions import KernelError |
| 12 | + |
| 13 | + |
| 14 | +def analysis_response( |
| 15 | + status: str, |
| 16 | + *, |
| 17 | + analysis_id: str = "analysis-1", |
| 18 | + finished_at: str | None = None, |
| 19 | +) -> dict[str, Any]: |
| 20 | + return { |
| 21 | + "analysis": { |
| 22 | + "id": analysis_id, |
| 23 | + "created_at": "2026-09-16T00:00:00Z", |
| 24 | + "expires_at": "2026-09-16T00:45:00Z", |
| 25 | + "failure": None, |
| 26 | + "finished_at": finished_at, |
| 27 | + "status": status, |
| 28 | + "intent": None, |
| 29 | + }, |
| 30 | + "recommendation": None, |
| 31 | + "target": { |
| 32 | + "domain": "example.com", |
| 33 | + "host": "example.com", |
| 34 | + "normalized": "https://example.com/", |
| 35 | + }, |
| 36 | + "working_configurations": [], |
| 37 | + "guidance": None, |
| 38 | + "workload_outcome": None, |
| 39 | + } |
| 40 | + |
| 41 | + |
| 42 | +def response_sequence(payloads: list[dict[str, Any]]) -> tuple[httpx.MockTransport, list[httpx.Request]]: |
| 43 | + remaining: Iterator[dict[str, Any]] = iter(payloads) |
| 44 | + requests: list[httpx.Request] = [] |
| 45 | + |
| 46 | + def handler(request: httpx.Request) -> httpx.Response: |
| 47 | + requests.append(request) |
| 48 | + return httpx.Response(200, json=next(remaining)) |
| 49 | + |
| 50 | + return httpx.MockTransport(handler), requests |
| 51 | + |
| 52 | + |
| 53 | +def test_wait_for_result_polls_unknown_unfinished_status_until_finished() -> None: |
| 54 | + transport, requests = response_sequence( |
| 55 | + [ |
| 56 | + analysis_response("running"), |
| 57 | + analysis_response("queued"), |
| 58 | + analysis_response("archived", finished_at="2026-09-16T00:01:00Z"), |
| 59 | + ] |
| 60 | + ) |
| 61 | + |
| 62 | + with httpx.Client(transport=transport) as http_client: |
| 63 | + client = Kernel(api_key="test", base_url="https://api.example", http_client=http_client) |
| 64 | + result = client.config_registry.analyses.wait_for_result( |
| 65 | + "analysis-1", |
| 66 | + poll_interval=0.001, |
| 67 | + extra_headers={"X-Test": "preserved", "X-Stainless-Poll-Helper": "caller"}, |
| 68 | + ) |
| 69 | + |
| 70 | + assert result.analysis is not None |
| 71 | + assert result.analysis.status == "archived" |
| 72 | + assert len(requests) == 3 |
| 73 | + assert all(request.headers["X-Test"] == "preserved" for request in requests) |
| 74 | + assert all(request.headers["X-Stainless-Poll-Helper"] == "true" for request in requests) |
| 75 | + |
| 76 | + |
| 77 | +@pytest.mark.parametrize("status", ["completed", "failed", "canceled", "expired"]) |
| 78 | +def test_wait_for_result_returns_known_terminal_status_without_finished_at(status: str) -> None: |
| 79 | + transport, requests = response_sequence([analysis_response(status)]) |
| 80 | + |
| 81 | + with httpx.Client(transport=transport) as http_client: |
| 82 | + client = Kernel(api_key="test", base_url="https://api.example", http_client=http_client) |
| 83 | + result = client.config_registry.analyses.wait_for_result("analysis-1") |
| 84 | + |
| 85 | + assert result.analysis is not None |
| 86 | + assert result.analysis.status == status |
| 87 | + assert len(requests) == 1 |
| 88 | + |
| 89 | + |
| 90 | +def test_wait_for_result_zero_max_wait_reads_once_then_times_out() -> None: |
| 91 | + transport, requests = response_sequence([analysis_response("running")]) |
| 92 | + |
| 93 | + with httpx.Client(transport=transport) as http_client: |
| 94 | + client = Kernel(api_key="test", base_url="https://api.example", http_client=http_client) |
| 95 | + with pytest.raises(TimeoutError, match="analysis-1"): |
| 96 | + client.config_registry.analyses.wait_for_result("analysis-1", max_wait_seconds=0) |
| 97 | + |
| 98 | + assert len(requests) == 1 |
| 99 | + |
| 100 | + |
| 101 | +@pytest.mark.parametrize( |
| 102 | + "payload, message", |
| 103 | + [ |
| 104 | + ({"analysis": None}, "missing an analysis"), |
| 105 | + (analysis_response("running", analysis_id="analysis-2"), "analysis-2"), |
| 106 | + ], |
| 107 | +) |
| 108 | +def test_wait_for_result_rejects_invalid_analysis_response(payload: dict[str, Any], message: str) -> None: |
| 109 | + transport, _ = response_sequence([payload]) |
| 110 | + |
| 111 | + with httpx.Client(transport=transport) as http_client: |
| 112 | + client = Kernel(api_key="test", base_url="https://api.example", http_client=http_client) |
| 113 | + with pytest.raises(KernelError, match=message): |
| 114 | + client.config_registry.analyses.wait_for_result("analysis-1") |
| 115 | + |
| 116 | + |
| 117 | +def test_wait_for_result_rejects_missing_finished_at() -> None: |
| 118 | + payload = analysis_response("running") |
| 119 | + analysis = payload["analysis"] |
| 120 | + assert isinstance(analysis, dict) |
| 121 | + del analysis["finished_at"] |
| 122 | + transport, _ = response_sequence([payload]) |
| 123 | + |
| 124 | + with httpx.Client(transport=transport) as http_client: |
| 125 | + client = Kernel(api_key="test", base_url="https://api.example", http_client=http_client) |
| 126 | + with pytest.raises(KernelError, match="finished_at"): |
| 127 | + client.config_registry.analyses.wait_for_result("analysis-1") |
| 128 | + |
| 129 | + |
| 130 | +@pytest.mark.parametrize( |
| 131 | + "kwargs", |
| 132 | + [ |
| 133 | + {"poll_interval": 0}, |
| 134 | + {"poll_interval": float("nan")}, |
| 135 | + {"max_wait_seconds": -1}, |
| 136 | + {"max_wait_seconds": float("inf")}, |
| 137 | + ], |
| 138 | +) |
| 139 | +def test_wait_for_result_rejects_invalid_timing_options(kwargs: dict[str, float]) -> None: |
| 140 | + client = Kernel(api_key="test", base_url="https://api.example") |
| 141 | + |
| 142 | + with pytest.raises(ValueError): |
| 143 | + client.config_registry.analyses.wait_for_result("analysis-1", **kwargs) # type: ignore[arg-type] |
| 144 | + |
| 145 | + |
| 146 | +async def test_async_wait_for_result_matches_sync_behavior() -> None: |
| 147 | + transport, requests = response_sequence( |
| 148 | + [ |
| 149 | + analysis_response("running"), |
| 150 | + analysis_response("completed", finished_at="2026-09-16T00:01:00Z"), |
| 151 | + ] |
| 152 | + ) |
| 153 | + |
| 154 | + async with httpx.AsyncClient(transport=transport) as http_client: |
| 155 | + client = AsyncKernel(api_key="test", base_url="https://api.example", http_client=http_client) |
| 156 | + result = await client.config_registry.analyses.wait_for_result("analysis-1", poll_interval=0.001) |
| 157 | + |
| 158 | + assert result.analysis is not None |
| 159 | + assert result.analysis.status == "completed" |
| 160 | + assert len(requests) == 2 |
| 161 | + |
| 162 | + |
| 163 | +async def test_async_wait_for_result_is_cancellable_during_poll_sleep() -> None: |
| 164 | + first_request = asyncio.Event() |
| 165 | + requests: list[httpx.Request] = [] |
| 166 | + |
| 167 | + def handler(request: httpx.Request) -> httpx.Response: |
| 168 | + requests.append(request) |
| 169 | + first_request.set() |
| 170 | + return httpx.Response(200, json=analysis_response("running")) |
| 171 | + |
| 172 | + async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http_client: |
| 173 | + client = AsyncKernel(api_key="test", base_url="https://api.example", http_client=http_client) |
| 174 | + task = asyncio.create_task(client.config_registry.analyses.wait_for_result("analysis-1", poll_interval=60)) |
| 175 | + await first_request.wait() |
| 176 | + await asyncio.sleep(0) |
| 177 | + task.cancel() |
| 178 | + with pytest.raises(asyncio.CancelledError): |
| 179 | + await task |
| 180 | + |
| 181 | + assert len(requests) == 1 |
0 commit comments