-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathtest_base_acp_server.py
More file actions
503 lines (395 loc) · 16.8 KB
/
test_base_acp_server.py
File metadata and controls
503 lines (395 loc) · 16.8 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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
# ruff: noqa: ARG001
import asyncio
from unittest.mock import patch
import pytest
from fastapi.testclient import TestClient
from agentex.lib.types.acp import (
RPCMethod,
SendEventParams,
CancelTaskParams,
)
from agentex.lib.sdk.fastacp.base.base_acp_server import BaseACPServer
class TestBaseACPServerInitialization:
"""Test BaseACPServer initialization and setup"""
def test_base_acp_server_init(self):
"""Test BaseACPServer initialization sets up routes correctly"""
with patch.dict("os.environ", {"AGENTEX_BASE_URL": ""}):
server = BaseACPServer()
# Check that FastAPI routes are set up
routes = [route.path for route in server.routes] # type: ignore[attr-defined]
assert "/healthz" in routes
assert "/api" in routes
# Check that handlers dict is initialized
assert hasattr(server, "_handlers")
assert isinstance(server._handlers, dict)
def test_base_acp_server_create_classmethod(self):
"""Test BaseACPServer.create() class method"""
with patch.dict("os.environ", {"AGENTEX_BASE_URL": ""}):
server = BaseACPServer.create()
assert isinstance(server, BaseACPServer)
assert hasattr(server, "_handlers")
def test_lifespan_function_setup(self):
"""Test that lifespan function is properly configured"""
with patch.dict("os.environ", {"AGENTEX_BASE_URL": ""}):
server = BaseACPServer()
# Check that lifespan is configured
assert server.router.lifespan_context is not None
class TestHealthCheckEndpoint:
"""Test health check endpoint functionality"""
def test_health_check_endpoint(self, base_acp_server):
"""Test GET /healthz endpoint returns correct response"""
client = TestClient(base_acp_server)
response = client.get("/healthz")
assert response.status_code == 200
assert response.json() == {"status": "healthy"}
def test_health_check_content_type(self, base_acp_server):
"""Test health check returns JSON content type"""
client = TestClient(base_acp_server)
response = client.get("/healthz")
assert response.headers["content-type"] == "application/json"
class TestJSONRPCEndpointCore:
"""Test core JSON-RPC endpoint functionality"""
def test_jsonrpc_endpoint_exists(self, base_acp_server):
"""Test POST /api endpoint exists"""
client = TestClient(base_acp_server)
# Send a basic request to check endpoint exists
response = client.post("/api", json={})
# Should not return 404 (endpoint exists)
assert response.status_code != 404
def test_jsonrpc_malformed_request(self, base_acp_server):
"""Test JSON-RPC endpoint handles malformed requests"""
client = TestClient(base_acp_server)
# Send malformed JSON
response = client.post("/api", json={"invalid": "request"})
assert response.status_code == 200
data = response.json()
assert "error" in data
assert data["jsonrpc"] == "2.0"
def test_jsonrpc_method_not_found(self, base_acp_server):
"""Test JSON-RPC method not found error"""
client = TestClient(base_acp_server)
request = {
"jsonrpc": "2.0",
"method": "nonexistent/method",
"params": {},
"id": "test-1",
}
response = client.post("/api", json=request)
assert response.status_code == 200
data = response.json()
assert "error" in data
assert data["error"]["code"] == -32601 # Method not found
assert data["id"] == "test-1"
def test_jsonrpc_valid_request_structure(self, base_acp_server):
"""Test JSON-RPC request parsing with valid structure"""
client = TestClient(base_acp_server)
# Add a mock handler for testing
async def mock_handler(params):
return {"status": "success"}
base_acp_server._handlers[RPCMethod.EVENT_SEND] = mock_handler
request = {
"jsonrpc": "2.0",
"method": "event/send",
"params": {
"agent": {
"id": "test-agent-456",
"name": "test-agent",
"description": "test agent",
"acp_type": "sync",
"created_at": "2023-01-01T00:00:00Z",
"updated_at": "2023-01-01T00:00:00Z",
},
"task": {"id": "test-task"},
"event": {
"id": "evt-1",
"agent_id": "test-agent-456",
"sequence_id": 1,
"task_id": "test-task",
},
},
"id": "test-1",
}
response = client.post("/api", json=request)
assert response.status_code == 200
data = response.json()
assert data["jsonrpc"] == "2.0"
assert data["id"] == "test-1"
# Should return immediate acknowledgment
assert data["result"]["status"] == "processing"
class TestHandlerRegistration:
"""Test handler registration and management"""
def test_on_task_event_send_decorator(self):
"""Test on_task_event_send decorator registration"""
with patch.dict("os.environ", {"AGENTEX_BASE_URL": ""}):
server = BaseACPServer()
@server.on_task_event_send
async def test_handler(params: SendEventParams):
return {"test": "response"}
# Check handler is registered
assert RPCMethod.EVENT_SEND in server._handlers
assert server._handlers[RPCMethod.EVENT_SEND] is not None
def test_cancel_task_decorator(self):
"""Test cancel_task decorator registration"""
with patch.dict("os.environ", {"AGENTEX_BASE_URL": ""}):
server = BaseACPServer()
@server.on_task_cancel
async def test_handler(params: CancelTaskParams):
return {"test": "response"}
# Check handler is registered
assert RPCMethod.TASK_CANCEL in server._handlers
assert server._handlers[RPCMethod.TASK_CANCEL] is not None
@pytest.mark.asyncio
async def test_handler_wrapper_functionality(self):
"""Test that handler wrapper works correctly"""
with patch.dict("os.environ", {"AGENTEX_BASE_URL": ""}):
server = BaseACPServer()
# Create a test handler
async def test_handler(params):
return {"handler_called": True, "params_received": True}
# Wrap the handler
wrapped = server._wrap_handler(test_handler)
# Test the wrapped handler
result = await wrapped({"test": "params"})
assert result["handler_called"] is True
assert result["params_received"] is True
class TestBackgroundProcessing:
"""Test background processing functionality"""
@pytest.mark.asyncio
async def test_notification_processing(self, async_base_acp_server):
"""Test notification processing (requests with no ID)"""
# Add a mock handler
handler_called = False
received_params = None
async def mock_handler(params):
nonlocal handler_called, received_params
handler_called = True
received_params = params
return {"status": "processed"}
async_base_acp_server._handlers[RPCMethod.EVENT_SEND] = mock_handler
client = TestClient(async_base_acp_server)
request = {
"jsonrpc": "2.0",
"method": "event/send",
"params": {
"agent": {
"id": "test-agent-456",
"name": "test-agent",
"description": "test agent",
"acp_type": "sync",
"created_at": "2023-01-01T00:00:00Z",
"updated_at": "2023-01-01T00:00:00Z",
},
"task": {"id": "test-task"},
"event": {
"id": "evt-1",
"agent_id": "test-agent-456",
"sequence_id": 1,
"task_id": "test-task",
},
},
# No ID = notification
}
response = client.post("/api", json=request)
assert response.status_code == 200
data = response.json()
assert data["id"] is None # Notification response
# Give background task time to execute
await asyncio.sleep(0.1)
# Handler should have been called
assert handler_called is True
assert received_params is not None
@pytest.mark.asyncio
async def test_request_processing_with_id(self, async_base_acp_server):
"""Test request processing with ID returns immediate acknowledgment"""
# Add a mock handler
async def mock_handler(params):
return {"status": "processed"}
async_base_acp_server._handlers[RPCMethod.TASK_CANCEL] = mock_handler
client = TestClient(async_base_acp_server)
request = {
"jsonrpc": "2.0",
"method": "task/cancel",
"params": {
"agent": {
"id": "test-agent-456",
"name": "test-agent",
"description": "test agent",
"acp_type": "sync",
"created_at": "2023-01-01T00:00:00Z",
"updated_at": "2023-01-01T00:00:00Z",
},
"task": {"id": "test-task-123"},
},
"id": "test-request-1",
}
response = client.post("/api", json=request)
assert response.status_code == 200
data = response.json()
assert data["jsonrpc"] == "2.0"
assert data["id"] == "test-request-1"
assert data["result"]["status"] == "processing" # Immediate acknowledgment
class TestSynchronousRPCMethods:
"""Test synchronous RPC methods that return results immediately"""
def test_send_message_synchronous_response(self, base_acp_server):
"""Test that MESSAGE_SEND method returns handler result synchronously"""
client = TestClient(base_acp_server)
# Add a mock handler that returns a specific result
async def mock_execute_handler(params):
return {
"task_id": params.task.id,
"message_content": params.content.content,
"status": "executed_synchronously",
"custom_data": {"processed": True, "timestamp": "2024-01-01T12:00:00Z"},
}
base_acp_server._handlers[RPCMethod.MESSAGE_SEND] = mock_execute_handler
request = {
"jsonrpc": "2.0",
"method": "message/send",
"params": {
"agent": {
"id": "test-agent-456",
"name": "test-agent",
"description": "test agent",
"acp_type": "sync",
"created_at": "2023-01-01T00:00:00Z",
"updated_at": "2023-01-01T00:00:00Z",
},
"task": {"id": "test-task-123"},
"content": {
"type": "text",
"author": "user",
"content": "Execute this task please",
},
},
"id": "test-execute-1",
}
response = client.post("/api", json=request)
assert response.status_code == 200
data = response.json()
# Verify JSON-RPC structure
assert data["jsonrpc"] == "2.0"
assert data["id"] == "test-execute-1"
assert "result" in data
assert data.get("error") is None
# Verify the handler's result is returned directly (not "processing" status)
result = data["result"]
assert result["task_id"] == "test-task-123"
assert result["message_content"] == "Execute this task please"
assert result["status"] == "executed_synchronously"
assert result["custom_data"]["processed"] is True
assert result["custom_data"]["timestamp"] == "2024-01-01T12:00:00Z"
# Verify it's NOT the async "processing" response
assert result.get("status") != "processing"
def test_create_task_async_response(self, base_acp_server):
"""Test that TASK_CREATE method returns processing status (async behavior)"""
client = TestClient(base_acp_server)
# Add a mock handler for init task
async def mock_init_handler(params):
return {
"task_id": params.task.id,
"status": "initialized",
}
base_acp_server._handlers[RPCMethod.TASK_CREATE] = mock_init_handler
request = {
"jsonrpc": "2.0",
"method": "task/create",
"params": {
"agent": {
"id": "test-agent-456",
"name": "test-agent",
"description": "test agent",
"acp_type": "sync",
"created_at": "2023-01-01T00:00:00Z",
"updated_at": "2023-01-01T00:00:00Z",
},
"task": {"id": "test-task-456"},
},
"id": "test-init-1",
}
response = client.post("/api", json=request)
assert response.status_code == 200
data = response.json()
# Verify JSON-RPC structure
assert data["jsonrpc"] == "2.0"
assert data["id"] == "test-init-1"
assert "result" in data
assert data.get("error") is None
# Verify it returns async "processing" status (not the handler's result)
result = data["result"]
assert result["status"] == "processing"
# Verify it's NOT the handler's actual result
assert result.get("status") != "initialized"
class TestErrorHandling:
"""Test error handling scenarios"""
def test_invalid_json_request(self, base_acp_server):
"""Test handling of invalid JSON in request body"""
client = TestClient(base_acp_server)
# Send invalid JSON
response = client.post(
"/api", content="invalid json", headers={"Content-Type": "application/json"}
)
assert response.status_code == 200
data = response.json()
assert "error" in data
assert data["jsonrpc"] == "2.0"
def test_missing_required_fields(self, base_acp_server):
"""Test handling of requests missing required JSON-RPC fields"""
client = TestClient(base_acp_server)
# Missing method field
request = {"jsonrpc": "2.0", "params": {}, "id": "test-1"}
response = client.post("/api", json=request)
assert response.status_code == 200
data = response.json()
assert "error" in data
def test_invalid_method_enum(self, base_acp_server):
"""Test handling of invalid method names"""
client = TestClient(base_acp_server)
request = {
"jsonrpc": "2.0",
"method": "invalid/method/name",
"params": {},
"id": "test-1",
}
response = client.post("/api", json=request)
assert response.status_code == 200
data = response.json()
assert "error" in data
assert data["error"]["code"] == -32601 # Method not found
@pytest.mark.asyncio
async def test_handler_exception_handling(self, async_base_acp_server):
"""Test that handler exceptions are properly handled"""
# Add a handler that raises an exception
async def failing_handler(params):
raise ValueError("Test exception")
async_base_acp_server._handlers[RPCMethod.EVENT_SEND] = failing_handler
client = TestClient(async_base_acp_server)
request = {
"jsonrpc": "2.0",
"method": "event/send",
"params": {
"agent": {
"id": "test-agent-456",
"name": "test-agent",
"description": "test agent",
"acp_type": "sync",
"created_at": "2023-01-01T00:00:00Z",
"updated_at": "2023-01-01T00:00:00Z",
},
"task": {"id": "test-task"},
"event": {
"id": "evt-1",
"agent_id": "test-agent-456",
"sequence_id": 1,
"task_id": "test-task",
},
},
"id": "test-1",
}
response = client.post("/api", json=request)
# Should still return immediate acknowledgment
assert response.status_code == 200
data = response.json()
assert data["result"]["status"] == "processing"
# Give background task time to fail
await asyncio.sleep(0.1)
# Exception should be logged but not crash the server