-
Notifications
You must be signed in to change notification settings - Fork 422
Expand file tree
/
Copy pathtest_rest_fastapi_app.py
More file actions
574 lines (483 loc) · 18.1 KB
/
test_rest_fastapi_app.py
File metadata and controls
574 lines (483 loc) · 18.1 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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
import logging
from typing import Any
from unittest.mock import MagicMock
import pytest
from fastapi import FastAPI
from google.protobuf import json_format
from httpx import ASGITransport, AsyncClient
from a2a.server.apps.rest import fastapi_app, rest_adapter
from a2a.server.apps.rest.fastapi_app import A2ARESTFastAPIApplication
from a2a.server.apps.rest.rest_adapter import RESTAdapter
from a2a.server.request_handlers.request_handler import RequestHandler
from a2a.types import a2a_pb2
from a2a.types.a2a_pb2 import (
AgentCard,
ListTaskPushNotificationConfigsResponse,
ListTasksResponse,
Message,
Part,
Role,
Task,
TaskPushNotificationConfig,
TaskState,
TaskStatus,
)
logger = logging.getLogger(__name__)
@pytest.fixture
async def agent_card() -> AgentCard:
mock_agent_card = MagicMock(spec=AgentCard)
mock_agent_card.url = 'http://mockurl.com'
# Mock the capabilities object with streaming disabled
mock_capabilities = MagicMock()
mock_capabilities.streaming = False
mock_capabilities.push_notifications = True
mock_capabilities.extended_agent_card = True
mock_agent_card.capabilities = mock_capabilities
return mock_agent_card
@pytest.fixture
async def streaming_agent_card() -> AgentCard:
"""Agent card that supports streaming for testing streaming endpoints."""
mock_agent_card = MagicMock(spec=AgentCard)
mock_agent_card.url = 'http://mockurl.com'
# Mock the capabilities object with streaming enabled
mock_capabilities = MagicMock()
mock_capabilities.streaming = True
mock_agent_card.capabilities = mock_capabilities
return mock_agent_card
@pytest.fixture
async def request_handler() -> RequestHandler:
return MagicMock(spec=RequestHandler)
@pytest.fixture
async def extended_card_modifier() -> MagicMock | None:
return None
@pytest.fixture
async def streaming_app(
streaming_agent_card: AgentCard, request_handler: RequestHandler
) -> FastAPI:
"""Builds the FastAPI application for testing streaming endpoints."""
return A2ARESTFastAPIApplication(
streaming_agent_card, request_handler
).build(agent_card_url='/well-known/agent-card.json', rpc_url='')
@pytest.fixture
async def streaming_client(streaming_app: FastAPI) -> AsyncClient:
"""HTTP client for the streaming FastAPI application."""
return AsyncClient(
transport=ASGITransport(app=streaming_app), base_url='http://test'
)
@pytest.fixture
async def app(
agent_card: AgentCard,
request_handler: RequestHandler,
extended_card_modifier: MagicMock | None,
) -> FastAPI:
"""Builds the FastAPI application for testing."""
return A2ARESTFastAPIApplication(
agent_card,
request_handler,
extended_card_modifier=extended_card_modifier,
).build(agent_card_url='/well-known/agent.json', rpc_url='')
@pytest.fixture
async def client(app: FastAPI) -> AsyncClient:
return AsyncClient(
transport=ASGITransport(app=app), base_url='http://testapp'
)
@pytest.fixture
def mark_pkg_starlette_not_installed():
pkg_starlette_installed_flag = rest_adapter._package_starlette_installed
rest_adapter._package_starlette_installed = False
yield
rest_adapter._package_starlette_installed = pkg_starlette_installed_flag
@pytest.fixture
def mark_pkg_fastapi_not_installed():
pkg_fastapi_installed_flag = fastapi_app._package_fastapi_installed
fastapi_app._package_fastapi_installed = False
yield
fastapi_app._package_fastapi_installed = pkg_fastapi_installed_flag
@pytest.mark.anyio
async def test_create_rest_adapter_with_present_deps_succeeds(
agent_card: AgentCard, request_handler: RequestHandler
):
try:
_app = RESTAdapter(agent_card, request_handler)
except ImportError:
pytest.fail(
'With packages starlette and see-starlette present, creating an'
' RESTAdapter instance should not raise ImportError'
)
@pytest.mark.anyio
async def test_create_rest_adapter_with_missing_deps_raises_importerror(
agent_card: AgentCard,
request_handler: RequestHandler,
mark_pkg_starlette_not_installed: Any,
):
with pytest.raises(
ImportError,
match=(
r'Packages `starlette` and `sse-starlette` are required to use'
r' the `RESTAdapter`.'
),
):
_app = RESTAdapter(agent_card, request_handler)
@pytest.mark.anyio
async def test_create_a2a_rest_fastapi_app_with_present_deps_succeeds(
agent_card: AgentCard, request_handler: RequestHandler
):
try:
_app = A2ARESTFastAPIApplication(agent_card, request_handler).build(
agent_card_url='/well-known/agent.json', rpc_url=''
)
except ImportError:
pytest.fail(
'With the fastapi package present, creating a'
' A2ARESTFastAPIApplication instance should not raise ImportError'
)
@pytest.mark.anyio
async def test_create_a2a_rest_fastapi_app_with_missing_deps_raises_importerror(
agent_card: AgentCard,
request_handler: RequestHandler,
mark_pkg_fastapi_not_installed: Any,
):
with pytest.raises(
ImportError,
match=(
'The `fastapi` package is required to use the'
' `A2ARESTFastAPIApplication`'
),
):
_app = A2ARESTFastAPIApplication(agent_card, request_handler).build(
agent_card_url='/well-known/agent.json', rpc_url=''
)
@pytest.mark.anyio
async def test_create_a2a_rest_fastapi_app_with_v0_3_compat(
agent_card: AgentCard, request_handler: RequestHandler
):
app = A2ARESTFastAPIApplication(
agent_card, request_handler, enable_v0_3_compat=True
).build(agent_card_url='/well-known/agent.json', rpc_url='')
routes = [getattr(route, 'path', '') for route in app.routes]
assert '/v0.3/well-known/agent.json' in routes
assert '/v0.3/v1/message:send' in routes
@pytest.mark.anyio
async def test_send_message_success_message(
client: AsyncClient, request_handler: MagicMock
) -> None:
expected_response = a2a_pb2.SendMessageResponse(
message=a2a_pb2.Message(
message_id='test',
role=a2a_pb2.Role.ROLE_AGENT,
parts=[
a2a_pb2.Part(text='response message'),
],
),
)
request_handler.on_message_send.return_value = Message(
message_id='test',
role=Role.ROLE_AGENT,
parts=[Part(text='response message')],
)
request = a2a_pb2.SendMessageRequest(
message=a2a_pb2.Message(),
configuration=a2a_pb2.SendMessageConfiguration(),
)
# To see log output, run pytest with '--log-cli=true --log-cli-level=INFO'
response = await client.post(
'/message:send', json=json_format.MessageToDict(request)
)
# request should always be successful
response.raise_for_status()
actual_response = a2a_pb2.SendMessageResponse()
json_format.Parse(response.text, actual_response)
assert expected_response == actual_response
@pytest.mark.anyio
async def test_send_message_success_task(
client: AsyncClient, request_handler: MagicMock
) -> None:
expected_response = a2a_pb2.SendMessageResponse(
task=a2a_pb2.Task(
id='test_task_id',
context_id='test_context_id',
status=a2a_pb2.TaskStatus(
state=a2a_pb2.TaskState.TASK_STATE_COMPLETED,
message=a2a_pb2.Message(
message_id='test',
role=a2a_pb2.Role.ROLE_AGENT,
parts=[
a2a_pb2.Part(text='response task message'),
],
),
),
),
)
request_handler.on_message_send.return_value = Task(
id='test_task_id',
context_id='test_context_id',
status=TaskStatus(
state=TaskState.TASK_STATE_COMPLETED,
message=Message(
message_id='test',
role=Role.ROLE_AGENT,
parts=[Part(text='response task message')],
),
),
)
request = a2a_pb2.SendMessageRequest(
message=a2a_pb2.Message(),
configuration=a2a_pb2.SendMessageConfiguration(),
)
# To see log output, run pytest with '--log-cli=true --log-cli-level=INFO'
response = await client.post(
'/message:send', json=json_format.MessageToDict(request)
)
# request should always be successful
response.raise_for_status()
actual_response = a2a_pb2.SendMessageResponse()
json_format.Parse(response.text, actual_response)
assert expected_response == actual_response
@pytest.mark.anyio
async def test_streaming_message_request_body_consumption(
streaming_client: AsyncClient, request_handler: MagicMock
) -> None:
"""Test that streaming endpoint properly handles request body consumption.
This test verifies the fix for the deadlock issue where request.body()
was being consumed inside the EventSourceResponse context, causing
the application to hang indefinitely.
"""
# Mock the async generator response from the request handler
async def mock_stream_response():
"""Mock streaming response generator."""
yield Message(
message_id='stream_msg_1',
role=Role.ROLE_AGENT,
parts=[Part(text='First streaming response')],
)
yield Message(
message_id='stream_msg_2',
role=Role.ROLE_AGENT,
parts=[Part(text='Second streaming response')],
)
request_handler.on_message_send_stream.return_value = mock_stream_response()
# Create a valid streaming request
request = a2a_pb2.SendMessageRequest(
message=a2a_pb2.Message(
message_id='test_stream_msg',
role=a2a_pb2.ROLE_USER,
parts=[a2a_pb2.Part(text='Test streaming message')],
),
configuration=a2a_pb2.SendMessageConfiguration(),
)
# This should not hang indefinitely (previously it would due to the deadlock)
response = await streaming_client.post(
'/message:stream',
json=json_format.MessageToDict(request),
headers={'Accept': 'text/event-stream'},
timeout=10.0, # Reasonable timeout to prevent hanging in tests
)
# The response should be successful
response.raise_for_status()
assert response.status_code == 200
assert 'text/event-stream' in response.headers.get('content-type', '')
# Verify that the request handler was called
request_handler.on_message_send_stream.assert_called_once()
@pytest.mark.anyio
async def test_streaming_endpoint_with_invalid_content_type(
streaming_client: AsyncClient, request_handler: MagicMock
) -> None:
"""Test streaming endpoint behavior with invalid content type."""
async def mock_stream_response():
yield Message(
message_id='stream_msg_1',
role=Role.ROLE_AGENT,
parts=[Part(text='Response')],
)
request_handler.on_message_send_stream.return_value = mock_stream_response()
request = a2a_pb2.SendMessageRequest(
message=a2a_pb2.Message(
message_id='test_stream_msg',
role=a2a_pb2.ROLE_USER,
parts=[a2a_pb2.Part(text='Test message')],
),
configuration=a2a_pb2.SendMessageConfiguration(),
)
# Send request without proper event-stream headers
response = await streaming_client.post(
'/message:stream',
json=json_format.MessageToDict(request),
timeout=10.0,
)
# Should still succeed (the adapter handles content-type internally)
response.raise_for_status()
assert response.status_code == 200
@pytest.mark.anyio
async def test_send_message_rejected_task(
client: AsyncClient, request_handler: MagicMock
) -> None:
expected_response = a2a_pb2.SendMessageResponse(
task=a2a_pb2.Task(
id='test_task_id',
context_id='test_context_id',
status=a2a_pb2.TaskStatus(
state=a2a_pb2.TaskState.TASK_STATE_REJECTED,
message=a2a_pb2.Message(
message_id='test',
role=a2a_pb2.Role.ROLE_AGENT,
parts=[
a2a_pb2.Part(text="I don't want to work"),
],
),
),
),
)
request_handler.on_message_send.return_value = Task(
id='test_task_id',
context_id='test_context_id',
status=TaskStatus(
state=TaskState.TASK_STATE_REJECTED,
message=Message(
message_id='test',
role=Role.ROLE_AGENT,
parts=[Part(text="I don't want to work")],
),
),
)
request = a2a_pb2.SendMessageRequest(
message=a2a_pb2.Message(),
configuration=a2a_pb2.SendMessageConfiguration(),
)
response = await client.post(
'/message:send', json=json_format.MessageToDict(request)
)
response.raise_for_status()
actual_response = a2a_pb2.SendMessageResponse()
json_format.Parse(response.text, actual_response)
assert expected_response == actual_response
@pytest.mark.anyio
class TestTenantExtraction:
@pytest.fixture(autouse=True)
def configure_mocks(self, request_handler: MagicMock) -> None:
# Setup default return values for all handlers
request_handler.on_message_send.return_value = Message(
message_id='test',
role=Role.ROLE_AGENT,
parts=[Part(text='response message')],
)
request_handler.on_cancel_task.return_value = Task(id='1')
request_handler.on_get_task.return_value = Task(id='1')
request_handler.on_list_tasks.return_value = ListTasksResponse()
request_handler.on_create_task_push_notification_config.return_value = (
TaskPushNotificationConfig()
)
request_handler.on_get_task_push_notification_config.return_value = (
TaskPushNotificationConfig()
)
request_handler.on_list_task_push_notification_configs.return_value = (
ListTaskPushNotificationConfigsResponse()
)
request_handler.on_delete_task_push_notification_config.return_value = (
None
)
@pytest.fixture
def extended_card_modifier(self) -> MagicMock:
modifier = MagicMock()
modifier.return_value = AgentCard()
return modifier
@pytest.mark.parametrize(
'path_template, method, handler_method_name, json_body',
[
('/message:send', 'POST', 'on_message_send', {'message': {}}),
('/tasks/1:cancel', 'POST', 'on_cancel_task', None),
('/tasks/1', 'GET', 'on_get_task', None),
('/tasks', 'GET', 'on_list_tasks', None),
(
'/tasks/1/pushNotificationConfigs/p1',
'GET',
'on_get_task_push_notification_config',
None,
),
(
'/tasks/1/pushNotificationConfigs/p1',
'DELETE',
'on_delete_task_push_notification_config',
None,
),
(
'/tasks/1/pushNotificationConfigs',
'POST',
'on_create_task_push_notification_config',
{'url': 'http://foo'},
),
(
'/tasks/1/pushNotificationConfigs',
'GET',
'on_list_task_push_notification_configs',
None,
),
],
)
async def test_tenant_extraction_parametrized( # noqa: PLR0913 # Test parametrization requires many arguments
self,
client: AsyncClient,
request_handler: MagicMock,
path_template: str,
method: str,
handler_method_name: str,
json_body: dict | None,
) -> None:
"""Test tenant extraction for standard REST endpoints."""
# Test with tenant
tenant = 'my-tenant'
tenant_path = f'/{tenant}{path_template}'
response = await client.request(method, tenant_path, json=json_body)
response.raise_for_status()
# Verify handler call
handler_mock = getattr(request_handler, handler_method_name)
assert handler_mock.called
args, _ = handler_mock.call_args
context = args[1]
assert context.tenant == tenant
# Reset mock for non-tenant test
handler_mock.reset_mock()
# Test without tenant
response = await client.request(method, path_template, json=json_body)
response.raise_for_status()
# Verify context.tenant == ""
assert handler_mock.called
args, _ = handler_mock.call_args
context = args[1]
assert context.tenant == ''
async def test_tenant_extraction_extended_agent_card(
self,
client: AsyncClient,
extended_card_modifier: MagicMock,
) -> None:
"""Test tenant extraction specifically for extendedAgentCard endpoint."""
# Test with tenant
tenant = 'my-tenant'
tenant_path = f'/{tenant}/extendedAgentCard'
response = await client.get(tenant_path)
response.raise_for_status()
# Verify extended_card_modifier called with tenant context
assert extended_card_modifier.called
args, _ = extended_card_modifier.call_args
context = args[1]
assert context.tenant == tenant
# Reset mock for non-tenant test
extended_card_modifier.reset_mock()
# Test without tenant
response = await client.get('/extendedAgentCard')
response.raise_for_status()
# Verify extended_card_modifier called with empty tenant context
assert extended_card_modifier.called
args, _ = extended_card_modifier.call_args
context = args[1]
assert context.tenant == ''
@pytest.mark.anyio
async def test_get_task_invalid_history_length_returns_400(
client: AsyncClient,
) -> None:
"""Non-numeric historyLength query param returns 400 ParseError."""
response = await client.get('/tasks/some-task-id?historyLength=abc')
assert response.status_code == 400
data = response.json()
assert data.get('type') == 'ParseError'
if __name__ == '__main__':
pytest.main([__file__])