1"""Shared test helpers."""
2
3from __future__ import annotations
4
5import inspect
6import json
7from typing import Any
8from collections.abc import Callable
9
10from airouter.provider import AssistantTurn, ToolCall, Usage
11
12
13class FakeProvider:
14 """Duck-typed replacement for OpenAIClient."""
15
16 def __init__(self, responders: dict[str, Any] | Callable[..., Any]) -> None:
17 self.responders = responders
18 self.calls: list[dict[str, Any]] = []
19 self.closed = False
20 self._counts: dict[str, int] = {}
21
22 async def stream_chat(
23 self,
24 *,
25 model: str,
26 messages: list[dict[str, Any]],
27 tools: list[dict[str, Any]] | None = None,
28 session_id: str,
29 on_text: Callable[[str], None] | None = None,
30 on_reasoning: Callable[[str], None] | None = None,
31 temperature: float | None = 0.2,
32 max_tokens: int | None = None,
33 extra_headers: dict[str, str] | None = None,
34 ) -> AssistantTurn:
35 self.calls.append(
36 {
37 "model": model,
38 "messages": messages,
39 "tools": tools,
40 "session_id": session_id,
41 }
42 )
43 count = self._counts.get(model, 0)
44 self._counts[model] = count + 1
45 responder = self.responders[model] if isinstance(self.responders, dict) else self.responders
46 if callable(responder):
47 try:
48 result = responder(messages, count, session_id)
49 except TypeError:
50 result = responder(messages)
51 elif isinstance(responder, list):
52 if count >= len(responder):
53 result = responder[-1]
54 else:
55 result = responder[count]
56 else:
57 result = responder
58 if inspect.isawaitable(result):
59 result = await result
60 if isinstance(result, str):
61 result = AssistantTurn(content=result)
62 if not result.usage.total_tokens:
63 result.usage = Usage(prompt_tokens=10, completion_tokens=5, total_tokens=15)
64 if result.content and on_text:
65 on_text(result.content)
66 if result.reasoning and on_reasoning:
67 on_reasoning(result.reasoning)
68 return result
69
70 async def aclose(self) -> None:
71 self.closed = True
72
73
74def tool_call(name: str, args: dict[str, Any], call_id: str = "call_1") -> ToolCall:
75 return ToolCall(id=call_id, name=name, arguments=json.dumps(args, ensure_ascii=False))
76
77
78def turn_with_tool(name: str, args: dict[str, Any], call_id: str = "call_1") -> AssistantTurn:
79 return AssistantTurn(tool_calls=[tool_call(name, args, call_id)], finish_reason="tool_calls")
80
81
82def turn_text(text: str) -> AssistantTurn:
83 return AssistantTurn(content=text, finish_reason="stop")