-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathtest_tools_unit.py
More file actions
387 lines (313 loc) · 12.4 KB
/
test_tools_unit.py
File metadata and controls
387 lines (313 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
"""Unit tests for define_tool"""
import json
import pytest
from pydantic import BaseModel, Field
from copilot import define_tool
from copilot.tools import (
ToolInvocation,
ToolResult,
_normalize_result,
convert_mcp_call_tool_result,
)
class TestDefineTool:
def test_creates_tool_with_correct_name_and_description(self):
class Params(BaseModel):
query: str
@define_tool("search", description="Search for something")
def search(params: Params, invocation: ToolInvocation) -> str:
return "result"
assert search.name == "search"
assert search.description == "Search for something"
assert search.handler is not None
assert search.parameters is not None
def test_infers_name_from_function(self):
class Params(BaseModel):
query: str
@define_tool(description="Search for something")
def my_search_tool(params: Params) -> str:
return "result"
assert my_search_tool.name == "my_search_tool"
def test_generates_schema_from_pydantic_model(self):
class Params(BaseModel):
city: str = Field(description="City name")
unit: str = Field(description="Temperature unit")
@define_tool("get_weather", description="Get weather")
def get_weather(params: Params, invocation: ToolInvocation) -> str:
return "sunny"
schema = get_weather.parameters
assert schema is not None
assert schema["type"] == "object"
assert "city" in schema["properties"]
assert "unit" in schema["properties"]
assert schema["properties"]["city"]["description"] == "City name"
async def test_handler_receives_typed_arguments(self):
class Params(BaseModel):
name: str
count: int
received_params = None
@define_tool("test", description="Test tool")
def test_tool(params: Params, invocation: ToolInvocation) -> str:
nonlocal received_params
received_params = params
return "ok"
invocation = ToolInvocation(
session_id="session-1",
tool_call_id="call-1",
tool_name="test",
arguments={"name": "Alice", "count": 42},
)
await test_tool.handler(invocation)
assert received_params is not None
assert received_params.name == "Alice"
assert received_params.count == 42
async def test_handler_receives_invocation(self):
class Params(BaseModel):
pass
received_inv = None
@define_tool("test", description="Test tool")
def test_tool(params: Params, invocation: ToolInvocation) -> str:
nonlocal received_inv
received_inv = invocation
return "ok"
invocation = ToolInvocation(
session_id="session-123",
tool_call_id="call-456",
tool_name="test",
arguments={},
)
await test_tool.handler(invocation)
assert received_inv.session_id == "session-123"
assert received_inv.tool_call_id == "call-456"
async def test_zero_param_handler(self):
"""Handler with no parameters: def handler() -> str"""
called = False
@define_tool("test", description="Test tool")
def test_tool() -> str:
nonlocal called
called = True
return "ok"
invocation = ToolInvocation(
session_id="s1",
tool_call_id="c1",
tool_name="test",
arguments={},
)
result = await test_tool.handler(invocation)
assert called
assert result.text_result_for_llm == "ok"
async def test_invocation_only_handler(self):
"""Handler with only invocation: def handler(invocation) -> str"""
received_inv = None
@define_tool("test", description="Test tool")
def test_tool(invocation: ToolInvocation) -> str:
nonlocal received_inv
received_inv = invocation
return "ok"
invocation = ToolInvocation(
session_id="s1",
tool_call_id="c1",
tool_name="test",
arguments={},
)
await test_tool.handler(invocation)
assert received_inv is not None
assert received_inv.session_id == "s1"
async def test_params_only_handler(self):
"""Handler with only params: def handler(params) -> str"""
class Params(BaseModel):
value: str
received_params = None
@define_tool("test", description="Test tool")
def test_tool(params: Params) -> str:
nonlocal received_params
received_params = params
return "ok"
invocation = ToolInvocation(
session_id="s1",
tool_call_id="c1",
tool_name="test",
arguments={"value": "hello"},
)
await test_tool.handler(invocation)
assert received_params is not None
assert received_params.value == "hello"
async def test_handler_error_is_hidden_from_llm(self):
class Params(BaseModel):
pass
@define_tool("failing", description="A failing tool")
def failing_tool(params: Params, invocation: ToolInvocation) -> str:
raise ValueError("secret error message")
invocation = ToolInvocation(
session_id="s1",
tool_call_id="c1",
tool_name="failing",
arguments={},
)
result = await failing_tool.handler(invocation)
assert result.result_type == "failure"
assert "secret error message" not in result.text_result_for_llm
assert "error" in result.text_result_for_llm.lower()
# But the actual error is stored internally
assert result.error == "secret error message"
async def test_function_style_api(self):
class Params(BaseModel):
value: str
tool = define_tool(
"my_tool",
description="My tool",
handler=lambda params, inv: params.value.upper(),
params_type=Params,
)
assert tool.name == "my_tool"
assert tool.description == "My tool"
result = await tool.handler(
ToolInvocation(
session_id="s",
tool_call_id="c",
tool_name="my_tool",
arguments={"value": "hello"},
)
)
assert result.text_result_for_llm == "HELLO"
def test_function_style_requires_name(self):
class Params(BaseModel):
value: str
with pytest.raises(ValueError, match="name is required"):
define_tool(
description="My tool",
handler=lambda params, inv: params.value.upper(),
params_type=Params,
)
class TestNormalizeResult:
def test_none_returns_empty_success(self):
result = _normalize_result(None)
assert result.text_result_for_llm == ""
assert result.result_type == "success"
def test_string_passes_through(self):
result = _normalize_result("hello world")
assert result.text_result_for_llm == "hello world"
assert result.result_type == "success"
def test_tool_result_passes_through(self):
input_result = ToolResult(
text_result_for_llm="custom",
result_type="failure",
error="some error",
)
result = _normalize_result(input_result)
assert result.text_result_for_llm == "custom"
assert result.result_type == "failure"
def test_dict_is_json_serialized(self):
result = _normalize_result({"key": "value", "num": 42})
parsed = json.loads(result.text_result_for_llm)
assert parsed == {"key": "value", "num": 42}
assert result.result_type == "success"
def test_list_is_json_serialized(self):
result = _normalize_result(["a", "b", "c"])
assert result.text_result_for_llm == '["a", "b", "c"]'
assert result.result_type == "success"
def test_pydantic_model_is_serialized(self):
class Response(BaseModel):
status: str
count: int
result = _normalize_result(Response(status="ok", count=5))
parsed = json.loads(result.text_result_for_llm)
assert parsed == {"status": "ok", "count": 5}
def test_list_of_pydantic_models_is_serialized(self):
class Item(BaseModel):
name: str
value: int
items = [Item(name="a", value=1), Item(name="b", value=2)]
result = _normalize_result(items)
parsed = json.loads(result.text_result_for_llm)
assert parsed == [{"name": "a", "value": 1}, {"name": "b", "value": 2}]
assert result.result_type == "success"
def test_raises_for_unserializable_value(self):
# Functions cannot be JSON serialized
with pytest.raises(TypeError, match="Failed to serialize"):
_normalize_result(lambda x: x)
class TestConvertMcpCallToolResult:
def test_text_only_call_tool_result(self):
result = convert_mcp_call_tool_result(
{
"content": [{"type": "text", "text": "hello"}],
}
)
assert result.text_result_for_llm == "hello"
assert result.result_type == "success"
def test_multiple_text_blocks(self):
result = convert_mcp_call_tool_result(
{
"content": [
{"type": "text", "text": "line 1"},
{"type": "text", "text": "line 2"},
],
}
)
assert result.text_result_for_llm == "line 1\nline 2"
def test_is_error_maps_to_failure(self):
result = convert_mcp_call_tool_result(
{
"content": [{"type": "text", "text": "oops"}],
"isError": True,
}
)
assert result.result_type == "failure"
def test_is_error_false_maps_to_success(self):
result = convert_mcp_call_tool_result(
{
"content": [{"type": "text", "text": "ok"}],
"isError": False,
}
)
assert result.result_type == "success"
def test_image_content_to_binary(self):
result = convert_mcp_call_tool_result(
{
"content": [{"type": "image", "data": "base64data", "mimeType": "image/png"}],
}
)
assert result.binary_results_for_llm is not None
assert len(result.binary_results_for_llm) == 1
assert result.binary_results_for_llm[0].data == "base64data"
assert result.binary_results_for_llm[0].mime_type == "image/png"
assert result.binary_results_for_llm[0].type == "image"
def test_resource_text_to_text_result(self):
result = convert_mcp_call_tool_result(
{
"content": [
{
"type": "resource",
"resource": {"uri": "file:///data.txt", "text": "file contents"},
},
],
}
)
assert result.text_result_for_llm == "file contents"
def test_resource_blob_to_binary(self):
result = convert_mcp_call_tool_result(
{
"content": [
{
"type": "resource",
"resource": {
"uri": "file:///img.png",
"blob": "blobdata",
"mimeType": "image/png",
},
},
],
}
)
assert result.binary_results_for_llm is not None
assert len(result.binary_results_for_llm) == 1
assert result.binary_results_for_llm[0].data == "blobdata"
assert result.binary_results_for_llm[0].description == "file:///img.png"
def test_empty_content_array(self):
result = convert_mcp_call_tool_result({"content": []})
assert result.text_result_for_llm == ""
assert result.result_type == "success"
def test_call_tool_result_dict_is_json_serialized_by_normalize(self):
"""_normalize_result does NOT auto-detect MCP results; it JSON-serializes them."""
result = _normalize_result({"content": [{"type": "text", "text": "hello"}]})
parsed = json.loads(result.text_result_for_llm)
assert parsed == {"content": [{"type": "text", "text": "hello"}]}