-
Notifications
You must be signed in to change notification settings - Fork 429
Expand file tree
/
Copy pathtest_default_request_handler_v2.py
More file actions
1413 lines (1260 loc) · 50.4 KB
/
test_default_request_handler_v2.py
File metadata and controls
1413 lines (1260 loc) · 50.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
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import logging
import time
import uuid
from unittest.mock import AsyncMock, patch, MagicMock
import pytest
from a2a.auth.user import UnauthenticatedUser
from a2a.server.agent_execution import (
RequestContextBuilder,
AgentExecutor,
RequestContext,
SimpleRequestContextBuilder,
)
from a2a.server.agent_execution.active_task_registry import ActiveTaskRegistry
from a2a.server.context import ServerCallContext
from a2a.server.events import EventQueue, InMemoryQueueManager, QueueManager
from a2a.server.request_handlers import DefaultRequestHandlerV2
from a2a.server.tasks import (
InMemoryPushNotificationConfigStore,
InMemoryTaskStore,
PushNotificationConfigStore,
PushNotificationSender,
TaskStore,
TaskUpdater,
)
from a2a.types import (
InternalError,
InvalidAgentResponseError,
InvalidParamsError,
TaskNotFoundError,
PushNotificationNotSupportedError,
)
from a2a.types.a2a_pb2 import (
AgentCapabilities,
AgentCard,
Artifact,
CancelTaskRequest,
DeleteTaskPushNotificationConfigRequest,
GetTaskPushNotificationConfigRequest,
GetTaskRequest,
ListTaskPushNotificationConfigsRequest,
ListTasksRequest,
ListTasksResponse,
Message,
Part,
Role,
SendMessageConfiguration,
SendMessageRequest,
SubscribeToTaskRequest,
Task,
TaskPushNotificationConfig,
TaskState,
TaskStatus,
TaskStatusUpdateEvent,
)
from a2a.helpers.proto_helpers import (
new_text_message,
new_task_from_user_message,
)
def create_default_agent_card():
"""Provides a standard AgentCard with streaming and push notifications enabled for tests."""
return AgentCard(
name='test_agent',
version='1.0',
capabilities=AgentCapabilities(streaming=True, push_notifications=True),
)
class MockAgentExecutor(AgentExecutor):
async def execute(self, context: RequestContext, event_queue: EventQueue):
if context.message:
await event_queue.enqueue_event(
new_task_from_user_message(context.message)
)
task_updater = TaskUpdater(
event_queue,
str(context.task_id or ''),
str(context.context_id or ''),
)
async for i in self._run():
parts = [Part(text=f'Event {i}')]
try:
await task_updater.update_status(
TaskState.TASK_STATE_WORKING,
message=task_updater.new_agent_message(parts),
)
except RuntimeError:
break
async def _run(self):
for i in range(1000000):
yield i
async def cancel(self, context: RequestContext, event_queue: EventQueue):
pass
def create_sample_task(
task_id='task1',
status_state=TaskState.TASK_STATE_SUBMITTED,
context_id='ctx1',
) -> Task:
return Task(
id=task_id, context_id=context_id, status=TaskStatus(state=status_state)
)
def create_server_call_context() -> ServerCallContext:
return ServerCallContext(user=UnauthenticatedUser())
def test_init_default_dependencies():
"""Test that default dependencies are created if not provided."""
agent_executor = MockAgentExecutor()
task_store = InMemoryTaskStore()
handler = DefaultRequestHandlerV2(
agent_executor=agent_executor,
task_store=task_store,
agent_card=create_default_agent_card(),
)
assert isinstance(handler._active_task_registry, ActiveTaskRegistry)
assert isinstance(
handler._request_context_builder, SimpleRequestContextBuilder
)
assert handler._push_config_store is None
assert handler._push_sender is None
assert (
handler._request_context_builder._should_populate_referred_tasks
is False
)
assert handler._request_context_builder._task_store == task_store
@pytest.mark.asyncio
async def test_on_get_task_not_found():
"""Test on_get_task when task_store.get returns None."""
mock_task_store = AsyncMock(spec=TaskStore)
mock_task_store.get.return_value = None
request_handler = DefaultRequestHandlerV2(
agent_executor=MockAgentExecutor(),
task_store=mock_task_store,
agent_card=create_default_agent_card(),
)
params = GetTaskRequest(id='non_existent_task')
context = create_server_call_context()
with pytest.raises(TaskNotFoundError):
await request_handler.on_get_task(params, context)
mock_task_store.get.assert_awaited_once_with('non_existent_task', context)
@pytest.mark.asyncio
async def test_on_list_tasks_success():
"""Test on_list_tasks successfully returns a page of tasks ."""
mock_task_store = AsyncMock(spec=TaskStore)
task2 = create_sample_task(task_id='task2')
task2.artifacts.extend(
[
Artifact(
artifact_id='artifact1',
parts=[Part(text='Hello world!')],
name='conversion_result',
)
]
)
mock_page = ListTasksResponse(
tasks=[create_sample_task(task_id='task1'), task2],
next_page_token='123', # noqa: S106
)
mock_task_store.list.return_value = mock_page
request_handler = DefaultRequestHandlerV2(
agent_executor=AsyncMock(spec=AgentExecutor),
task_store=mock_task_store,
agent_card=create_default_agent_card(),
)
params = ListTasksRequest(include_artifacts=True, page_size=10)
context = create_server_call_context()
result = await request_handler.on_list_tasks(params, context)
mock_task_store.list.assert_awaited_once_with(params, context)
assert result.tasks == mock_page.tasks
assert result.next_page_token == mock_page.next_page_token
@pytest.mark.asyncio
async def test_on_list_tasks_excludes_artifacts():
"""Test on_list_tasks excludes artifacts from returned tasks."""
mock_task_store = AsyncMock(spec=TaskStore)
task2 = create_sample_task(task_id='task2')
task2.artifacts.extend(
[
Artifact(
artifact_id='artifact1',
parts=[Part(text='Hello world!')],
name='conversion_result',
)
]
)
mock_page = ListTasksResponse(
tasks=[create_sample_task(task_id='task1'), task2],
next_page_token='123', # noqa: S106
)
mock_task_store.list.return_value = mock_page
request_handler = DefaultRequestHandlerV2(
agent_executor=AsyncMock(spec=AgentExecutor),
task_store=mock_task_store,
agent_card=create_default_agent_card(),
)
params = ListTasksRequest(include_artifacts=False, page_size=10)
context = create_server_call_context()
result = await request_handler.on_list_tasks(params, context)
assert not result.tasks[1].artifacts
@pytest.mark.asyncio
async def test_on_list_tasks_applies_history_length():
"""Test on_list_tasks applies history length filter."""
mock_task_store = AsyncMock(spec=TaskStore)
history = [
new_text_message('Hello 1!'),
new_text_message('Hello 2!'),
]
task2 = create_sample_task(task_id='task2')
task2.history.extend(history)
mock_page = ListTasksResponse(
tasks=[create_sample_task(task_id='task1'), task2],
next_page_token='123', # noqa: S106
)
mock_task_store.list.return_value = mock_page
request_handler = DefaultRequestHandlerV2(
agent_executor=AsyncMock(spec=AgentExecutor),
task_store=mock_task_store,
agent_card=create_default_agent_card(),
)
params = ListTasksRequest(history_length=1, page_size=10)
context = create_server_call_context()
result = await request_handler.on_list_tasks(params, context)
assert result.tasks[1].history == [history[1]]
@pytest.mark.asyncio
async def test_on_list_tasks_negative_history_length_error():
"""Test on_list_tasks raises error for negative history length."""
mock_task_store = AsyncMock(spec=TaskStore)
request_handler = DefaultRequestHandlerV2(
agent_executor=AsyncMock(spec=AgentExecutor),
task_store=mock_task_store,
agent_card=create_default_agent_card(),
)
params = ListTasksRequest(history_length=-1, page_size=10)
context = create_server_call_context()
with pytest.raises(InvalidParamsError) as exc_info:
await request_handler.on_list_tasks(params, context)
assert 'history length must be non-negative' in exc_info.value.message
@pytest.mark.asyncio
async def test_on_cancel_task_task_not_found():
"""Test on_cancel_task when the task is not found."""
mock_task_store = AsyncMock(spec=TaskStore)
mock_task_store.get.return_value = None
request_handler = DefaultRequestHandlerV2(
agent_executor=MockAgentExecutor(),
task_store=mock_task_store,
agent_card=create_default_agent_card(),
)
params = CancelTaskRequest(id='task_not_found_for_cancel')
context = create_server_call_context()
with pytest.raises(TaskNotFoundError):
await request_handler.on_cancel_task(params, context)
mock_task_store.get.assert_awaited_once_with(
'task_not_found_for_cancel', context
)
class HelloAgentExecutor(AgentExecutor):
async def execute(self, context: RequestContext, event_queue: EventQueue):
task = context.current_task
if not task:
assert context.message is not None, (
'A message is required to create a new task'
)
task = new_task_from_user_message(context.message)
await event_queue.enqueue_event(task)
updater = TaskUpdater(event_queue, task.id, task.context_id)
try:
parts = [Part(text='I am working')]
await updater.update_status(
TaskState.TASK_STATE_WORKING,
message=updater.new_agent_message(parts),
)
except Exception as e: # noqa: BLE001
logging.warning('Error: %s', e)
return
await updater.add_artifact(
[Part(text='Hello world!')], name='conversion_result'
)
await updater.complete()
async def cancel(self, context: RequestContext, event_queue: EventQueue):
pass
@pytest.mark.asyncio
async def test_on_get_task_limit_history():
task_store = InMemoryTaskStore()
push_store = InMemoryPushNotificationConfigStore()
request_handler = DefaultRequestHandlerV2(
agent_executor=HelloAgentExecutor(),
task_store=task_store,
push_config_store=push_store,
agent_card=create_default_agent_card(),
)
params = SendMessageRequest(
message=Message(
role=Role.ROLE_USER, message_id='msg_push', parts=[Part(text='Hi')]
),
configuration=SendMessageConfiguration(
accepted_output_modes=['text/plain']
),
)
result = await request_handler.on_message_send(
params, create_server_call_context()
)
assert result is not None
assert isinstance(result, Task)
get_task_result = await request_handler.on_get_task(
GetTaskRequest(id=result.id, history_length=1),
create_server_call_context(),
)
assert get_task_result is not None
assert isinstance(get_task_result, Task)
assert (
get_task_result.history is not None
and len(get_task_result.history) == 1
)
async def wait_until(predicate, timeout: float = 0.2, interval: float = 0.0):
"""Await until predicate() is True or timeout elapses."""
loop = asyncio.get_running_loop()
end = loop.time() + timeout
while True:
if predicate():
return
if loop.time() >= end:
raise AssertionError('condition not met within timeout')
await asyncio.sleep(interval)
@pytest.mark.asyncio
async def test_set_task_push_notification_config_no_notifier():
"""Test on_create_task_push_notification_config when _push_config_store is None."""
request_handler = DefaultRequestHandlerV2(
agent_executor=MockAgentExecutor(),
task_store=AsyncMock(spec=TaskStore),
push_config_store=None,
agent_card=create_default_agent_card(),
)
params = TaskPushNotificationConfig(
task_id='task1', url='http://example.com'
)
with pytest.raises(PushNotificationNotSupportedError):
await request_handler.on_create_task_push_notification_config(
params, create_server_call_context()
)
@pytest.mark.asyncio
async def test_set_task_push_notification_config_task_not_found():
"""Test on_create_task_push_notification_config when task is not found."""
mock_task_store = AsyncMock(spec=TaskStore)
mock_task_store.get.return_value = None
mock_push_store = AsyncMock(spec=PushNotificationConfigStore)
mock_push_sender = AsyncMock(spec=PushNotificationSender)
request_handler = DefaultRequestHandlerV2(
agent_executor=MockAgentExecutor(),
task_store=mock_task_store,
push_config_store=mock_push_store,
push_sender=mock_push_sender,
agent_card=create_default_agent_card(),
)
params = TaskPushNotificationConfig(
task_id='non_existent_task', url='http://example.com'
)
context = create_server_call_context()
with pytest.raises(TaskNotFoundError):
await request_handler.on_create_task_push_notification_config(
params, context
)
mock_task_store.get.assert_awaited_once_with('non_existent_task', context)
mock_push_store.set_info.assert_not_awaited()
@pytest.mark.asyncio
async def test_get_task_push_notification_config_no_store():
"""Test on_get_task_push_notification_config when _push_config_store is None."""
request_handler = DefaultRequestHandlerV2(
agent_executor=MockAgentExecutor(),
task_store=AsyncMock(spec=TaskStore),
push_config_store=None,
agent_card=create_default_agent_card(),
)
params = GetTaskPushNotificationConfigRequest(
task_id='task1', id='task_push_notification_config'
)
with pytest.raises(PushNotificationNotSupportedError):
await request_handler.on_get_task_push_notification_config(
params, create_server_call_context()
)
@pytest.mark.asyncio
async def test_get_task_push_notification_config_task_not_found():
"""Test on_get_task_push_notification_config when task is not found."""
mock_task_store = AsyncMock(spec=TaskStore)
mock_task_store.get.return_value = None
mock_push_store = AsyncMock(spec=PushNotificationConfigStore)
request_handler = DefaultRequestHandlerV2(
agent_executor=MockAgentExecutor(),
task_store=mock_task_store,
push_config_store=mock_push_store,
agent_card=create_default_agent_card(),
)
params = GetTaskPushNotificationConfigRequest(
task_id='non_existent_task', id='task_push_notification_config'
)
context = create_server_call_context()
with pytest.raises(TaskNotFoundError):
await request_handler.on_get_task_push_notification_config(
params, context
)
mock_task_store.get.assert_awaited_once_with('non_existent_task', context)
mock_push_store.get_info.assert_not_awaited()
@pytest.mark.asyncio
async def test_get_task_push_notification_config_info_not_found():
"""Test on_get_task_push_notification_config when push_config_store.get_info returns None."""
mock_task_store = AsyncMock(spec=TaskStore)
sample_task = create_sample_task(task_id='non_existent_task')
mock_task_store.get.return_value = sample_task
mock_push_store = AsyncMock(spec=PushNotificationConfigStore)
mock_push_store.get_info.return_value = None
request_handler = DefaultRequestHandlerV2(
agent_executor=MockAgentExecutor(),
task_store=mock_task_store,
push_config_store=mock_push_store,
agent_card=create_default_agent_card(),
)
params = GetTaskPushNotificationConfigRequest(
task_id='non_existent_task', id='task_push_notification_config'
)
context = create_server_call_context()
with pytest.raises(TaskNotFoundError):
await request_handler.on_get_task_push_notification_config(
params, context
)
mock_task_store.get.assert_awaited_once_with('non_existent_task', context)
mock_push_store.get_info.assert_awaited_once_with(
'non_existent_task', context
)
@pytest.mark.asyncio
async def test_get_task_push_notification_config_info_with_config():
"""Test on_get_task_push_notification_config with valid push config id"""
mock_task_store = AsyncMock(spec=TaskStore)
mock_task_store.get.return_value = Task(id='task_1', context_id='ctx_1')
push_store = InMemoryPushNotificationConfigStore()
request_handler = DefaultRequestHandlerV2(
agent_executor=MockAgentExecutor(),
task_store=mock_task_store,
push_config_store=push_store,
agent_card=create_default_agent_card(),
)
set_config_params = TaskPushNotificationConfig(
task_id='task_1', id='config_id', url='http://1.example.com'
)
context = create_server_call_context()
await request_handler.on_create_task_push_notification_config(
set_config_params, context
)
params = GetTaskPushNotificationConfigRequest(
task_id='task_1', id='config_id'
)
result: TaskPushNotificationConfig = (
await request_handler.on_get_task_push_notification_config(
params, context
)
)
assert result is not None
assert result.task_id == 'task_1'
assert result.url == set_config_params.url
assert result.id == 'config_id'
@pytest.mark.asyncio
async def test_get_task_push_notification_config_info_with_config_no_id():
"""Test on_get_task_push_notification_config with no push config id"""
mock_task_store = AsyncMock(spec=TaskStore)
mock_task_store.get.return_value = Task(id='task_1', context_id='ctx_1')
push_store = InMemoryPushNotificationConfigStore()
request_handler = DefaultRequestHandlerV2(
agent_executor=MockAgentExecutor(),
task_store=mock_task_store,
push_config_store=push_store,
agent_card=create_default_agent_card(),
)
set_config_params = TaskPushNotificationConfig(
task_id='task_1', url='http://1.example.com'
)
await request_handler.on_create_task_push_notification_config(
set_config_params, create_server_call_context()
)
params = GetTaskPushNotificationConfigRequest(task_id='task_1', id='task_1')
result: TaskPushNotificationConfig = (
await request_handler.on_get_task_push_notification_config(
params, create_server_call_context()
)
)
assert result is not None
assert result.task_id == 'task_1'
assert result.url == set_config_params.url
assert result.id == 'task_1'
@pytest.mark.asyncio
async def test_on_subscribe_to_task_task_not_found():
"""Test on_subscribe_to_task when the task is not found."""
mock_task_store = AsyncMock(spec=TaskStore)
mock_task_store.get.return_value = None
request_handler = DefaultRequestHandlerV2(
agent_executor=MockAgentExecutor(),
task_store=mock_task_store,
agent_card=create_default_agent_card(),
)
params = SubscribeToTaskRequest(id='resub_task_not_found')
context = create_server_call_context()
with pytest.raises(TaskNotFoundError):
async for _ in request_handler.on_subscribe_to_task(params, context):
pass
mock_task_store.get.assert_awaited_once_with(
'resub_task_not_found', context
)
@pytest.mark.asyncio
async def test_on_message_send_stream():
request_handler = DefaultRequestHandlerV2(
MockAgentExecutor(),
InMemoryTaskStore(),
create_default_agent_card(),
)
message_params = SendMessageRequest(
message=Message(
role=Role.ROLE_USER,
message_id='msg-123',
parts=[Part(text='How are you?')],
)
)
async def consume_stream():
events = []
async for event in request_handler.on_message_send_stream(
message_params, create_server_call_context()
):
events.append(event)
if len(events) >= 3:
break
return events
start = time.perf_counter()
events = await consume_stream()
elapsed = time.perf_counter() - start
assert len(events) == 3
assert elapsed < 0.5
task, event0, event1 = events
assert isinstance(task, Task)
assert task.history[0].parts[0].text == 'How are you?'
assert isinstance(event0, TaskStatusUpdateEvent)
assert event0.status.message.parts[0].text == 'Event 0'
assert isinstance(event1, TaskStatusUpdateEvent)
assert event1.status.message.parts[0].text == 'Event 1'
@pytest.mark.asyncio
async def test_list_task_push_notification_config_no_store():
"""Test on_list_task_push_notification_configs when _push_config_store is None."""
request_handler = DefaultRequestHandlerV2(
agent_executor=MockAgentExecutor(),
task_store=AsyncMock(spec=TaskStore),
push_config_store=None,
agent_card=create_default_agent_card(),
)
params = ListTaskPushNotificationConfigsRequest(task_id='task1')
with pytest.raises(PushNotificationNotSupportedError):
await request_handler.on_list_task_push_notification_configs(
params, create_server_call_context()
)
@pytest.mark.asyncio
async def test_list_task_push_notification_config_task_not_found():
"""Test on_list_task_push_notification_configs when task is not found."""
mock_task_store = AsyncMock(spec=TaskStore)
mock_task_store.get.return_value = None
mock_push_store = AsyncMock(spec=PushNotificationConfigStore)
request_handler = DefaultRequestHandlerV2(
agent_executor=MockAgentExecutor(),
task_store=mock_task_store,
push_config_store=mock_push_store,
agent_card=create_default_agent_card(),
)
params = ListTaskPushNotificationConfigsRequest(task_id='non_existent_task')
context = create_server_call_context()
with pytest.raises(TaskNotFoundError):
await request_handler.on_list_task_push_notification_configs(
params, context
)
mock_task_store.get.assert_awaited_once_with('non_existent_task', context)
mock_push_store.get_info.assert_not_awaited()
@pytest.mark.asyncio
async def test_list_no_task_push_notification_config_info():
"""Test on_get_task_push_notification_config when push_config_store.get_info returns []"""
mock_task_store = AsyncMock(spec=TaskStore)
sample_task = create_sample_task(task_id='non_existent_task')
mock_task_store.get.return_value = sample_task
push_store = InMemoryPushNotificationConfigStore()
request_handler = DefaultRequestHandlerV2(
agent_executor=MockAgentExecutor(),
task_store=mock_task_store,
push_config_store=push_store,
agent_card=create_default_agent_card(),
)
params = ListTaskPushNotificationConfigsRequest(task_id='non_existent_task')
result = await request_handler.on_list_task_push_notification_configs(
params, create_server_call_context()
)
assert result.configs == []
@pytest.mark.asyncio
async def test_list_task_push_notification_config_info_with_config():
"""Test on_list_task_push_notification_configs with push config+id"""
mock_task_store = AsyncMock(spec=TaskStore)
sample_task = create_sample_task(task_id='non_existent_task')
mock_task_store.get.return_value = sample_task
push_config1 = TaskPushNotificationConfig(
task_id='task_1', id='config_1', url='http://example.com'
)
push_config2 = TaskPushNotificationConfig(
task_id='task_1', id='config_2', url='http://example.com'
)
push_store = InMemoryPushNotificationConfigStore()
context = create_server_call_context()
await push_store.set_info('task_1', push_config1, context)
await push_store.set_info('task_1', push_config2, context)
await push_store.set_info('task_2', push_config1, context)
request_handler = DefaultRequestHandlerV2(
agent_executor=MockAgentExecutor(),
task_store=mock_task_store,
push_config_store=push_store,
agent_card=create_default_agent_card(),
)
params = ListTaskPushNotificationConfigsRequest(task_id='task_1')
result = await request_handler.on_list_task_push_notification_configs(
params, create_server_call_context()
)
assert len(result.configs) == 2
assert result.configs[0].task_id == 'task_1'
assert result.configs[0] == push_config1
assert result.configs[1].task_id == 'task_1'
assert result.configs[1] == push_config2
@pytest.mark.asyncio
async def test_list_task_push_notification_config_info_with_config_and_no_id():
"""Test on_list_task_push_notification_configs with no push config id"""
mock_task_store = AsyncMock(spec=TaskStore)
mock_task_store.get.return_value = Task(id='task_1', context_id='ctx_1')
push_store = InMemoryPushNotificationConfigStore()
request_handler = DefaultRequestHandlerV2(
agent_executor=MockAgentExecutor(),
task_store=mock_task_store,
push_config_store=push_store,
agent_card=create_default_agent_card(),
)
set_config_params1 = TaskPushNotificationConfig(
task_id='task_1', url='http://1.example.com'
)
await request_handler.on_create_task_push_notification_config(
set_config_params1, create_server_call_context()
)
set_config_params2 = TaskPushNotificationConfig(
task_id='task_1', url='http://2.example.com'
)
await request_handler.on_create_task_push_notification_config(
set_config_params2, create_server_call_context()
)
params = ListTaskPushNotificationConfigsRequest(task_id='task_1')
result = await request_handler.on_list_task_push_notification_configs(
params, create_server_call_context()
)
assert len(result.configs) == 1
assert result.configs[0].task_id == 'task_1'
assert result.configs[0].url == set_config_params2.url
assert result.configs[0].id == 'task_1'
@pytest.mark.asyncio
async def test_delete_task_push_notification_config_no_store():
"""Test on_delete_task_push_notification_config when _push_config_store is None."""
request_handler = DefaultRequestHandlerV2(
agent_executor=MockAgentExecutor(),
task_store=AsyncMock(spec=TaskStore),
push_config_store=None,
agent_card=create_default_agent_card(),
)
params = DeleteTaskPushNotificationConfigRequest(
task_id='task1', id='config1'
)
with pytest.raises(PushNotificationNotSupportedError) as exc_info:
await request_handler.on_delete_task_push_notification_config(
params, create_server_call_context()
)
assert isinstance(exc_info.value, PushNotificationNotSupportedError)
@pytest.mark.asyncio
async def test_delete_task_push_notification_config_task_not_found():
"""Test on_delete_task_push_notification_config when task is not found."""
mock_task_store = AsyncMock(spec=TaskStore)
mock_task_store.get.return_value = None
mock_push_store = AsyncMock(spec=PushNotificationConfigStore)
request_handler = DefaultRequestHandlerV2(
agent_executor=MockAgentExecutor(),
task_store=mock_task_store,
push_config_store=mock_push_store,
agent_card=create_default_agent_card(),
)
params = DeleteTaskPushNotificationConfigRequest(
task_id='non_existent_task', id='config1'
)
context = create_server_call_context()
with pytest.raises(TaskNotFoundError):
await request_handler.on_delete_task_push_notification_config(
params, context
)
mock_task_store.get.assert_awaited_once_with('non_existent_task', context)
mock_push_store.get_info.assert_not_awaited()
@pytest.mark.asyncio
async def test_delete_no_task_push_notification_config_info():
"""Test on_delete_task_push_notification_config without config info"""
mock_task_store = AsyncMock(spec=TaskStore)
sample_task = create_sample_task(task_id='task_1')
mock_task_store.get.return_value = sample_task
push_store = InMemoryPushNotificationConfigStore()
await push_store.set_info(
'task_2',
TaskPushNotificationConfig(id='config_1', url='http://example.com'),
create_server_call_context(),
)
request_handler = DefaultRequestHandlerV2(
agent_executor=MockAgentExecutor(),
task_store=mock_task_store,
push_config_store=push_store,
agent_card=create_default_agent_card(),
)
params = DeleteTaskPushNotificationConfigRequest(
task_id='task1', id='config_non_existant'
)
result = await request_handler.on_delete_task_push_notification_config(
params, create_server_call_context()
)
assert result is None
params = DeleteTaskPushNotificationConfigRequest(
task_id='task2', id='config_non_existant'
)
result = await request_handler.on_delete_task_push_notification_config(
params, create_server_call_context()
)
assert result is None
@pytest.mark.asyncio
async def test_delete_task_push_notification_config_info_with_config():
"""Test on_list_task_push_notification_configs with push config+id"""
mock_task_store = AsyncMock(spec=TaskStore)
sample_task = create_sample_task(task_id='non_existent_task')
mock_task_store.get.return_value = sample_task
push_config1 = TaskPushNotificationConfig(
task_id='task_1', id='config_1', url='http://example.com'
)
push_config2 = TaskPushNotificationConfig(
task_id='task_1', id='config_2', url='http://example.com'
)
push_store = InMemoryPushNotificationConfigStore()
context = create_server_call_context()
await push_store.set_info('task_1', push_config1, context)
await push_store.set_info('task_1', push_config2, context)
await push_store.set_info('task_2', push_config1, context)
request_handler = DefaultRequestHandlerV2(
agent_executor=MockAgentExecutor(),
task_store=mock_task_store,
push_config_store=push_store,
agent_card=create_default_agent_card(),
)
params = DeleteTaskPushNotificationConfigRequest(
task_id='task_1', id='config_1'
)
result1 = await request_handler.on_delete_task_push_notification_config(
params, create_server_call_context()
)
assert result1 is None
result2 = await request_handler.on_list_task_push_notification_configs(
ListTaskPushNotificationConfigsRequest(task_id='task_1'),
create_server_call_context(),
)
assert len(result2.configs) == 1
assert result2.configs[0].task_id == 'task_1'
assert result2.configs[0] == push_config2
@pytest.mark.asyncio
async def test_delete_task_push_notification_config_info_with_config_and_no_id():
"""Test on_list_task_push_notification_configs with no push config id"""
mock_task_store = AsyncMock(spec=TaskStore)
sample_task = create_sample_task(task_id='non_existent_task')
mock_task_store.get.return_value = sample_task
push_config = TaskPushNotificationConfig(url='http://example.com')
push_store = InMemoryPushNotificationConfigStore()
context = create_server_call_context()
await push_store.set_info('task_1', push_config, context)
await push_store.set_info('task_1', push_config, context)
request_handler = DefaultRequestHandlerV2(
agent_executor=MockAgentExecutor(),
task_store=mock_task_store,
push_config_store=push_store,
agent_card=create_default_agent_card(),
)
params = DeleteTaskPushNotificationConfigRequest(
task_id='task_1', id='task_1'
)
result = await request_handler.on_delete_task_push_notification_config(
params, create_server_call_context()
)
assert result is None
result2 = await request_handler.on_list_task_push_notification_configs(
ListTaskPushNotificationConfigsRequest(task_id='task_1'),
create_server_call_context(),
)
assert len(result2.configs) == 0
TERMINAL_TASK_STATES = {
TaskState.TASK_STATE_COMPLETED,
TaskState.TASK_STATE_CANCELED,
TaskState.TASK_STATE_FAILED,
TaskState.TASK_STATE_REJECTED,
}
@pytest.mark.asyncio
@pytest.mark.parametrize('terminal_state', TERMINAL_TASK_STATES)
async def test_on_message_send_task_in_terminal_state(terminal_state):
"""Test on_message_send when task is already in a terminal state."""
state_name = TaskState.Name(terminal_state)
task_id = f'terminal_task_{state_name}'
terminal_task = create_sample_task(
task_id=task_id, status_state=terminal_state
)
mock_task_store = AsyncMock(spec=TaskStore)
request_handler = DefaultRequestHandlerV2(
agent_executor=MockAgentExecutor(),
task_store=mock_task_store,
agent_card=create_default_agent_card(),
)
params = SendMessageRequest(
message=Message(
role=Role.ROLE_USER,
message_id='msg_terminal',
parts=[Part(text='hello')],
task_id=task_id,
)
)
with (
patch(
'a2a.server.request_handlers.default_request_handler.TaskManager.get_task',
return_value=terminal_task,
),
pytest.raises(InvalidParamsError) as exc_info,
):
await request_handler.on_message_send(
params, create_server_call_context()
)
assert (
f'Task {task_id} is in terminal state: {terminal_state}'
in exc_info.value.message
)
@pytest.mark.asyncio
@pytest.mark.parametrize('terminal_state', TERMINAL_TASK_STATES)
async def test_on_message_send_stream_task_in_terminal_state(terminal_state):
"""Test on_message_send_stream when task is already in a terminal state."""
state_name = TaskState.Name(terminal_state)
task_id = f'terminal_stream_task_{state_name}'
terminal_task = create_sample_task(
task_id=task_id, status_state=terminal_state
)
mock_task_store = AsyncMock(spec=TaskStore)
request_handler = DefaultRequestHandlerV2(
agent_executor=MockAgentExecutor(),
task_store=mock_task_store,
agent_card=create_default_agent_card(),
)
params = SendMessageRequest(
message=Message(
role=Role.ROLE_USER,
message_id='msg_terminal_stream',
parts=[Part(text='hello')],
task_id=task_id,
)
)
with (
patch(
'a2a.server.request_handlers.default_request_handler.TaskManager.get_task',
return_value=terminal_task,
),
pytest.raises(InvalidParamsError) as exc_info,
):
async for _ in request_handler.on_message_send_stream(
params, create_server_call_context()
):
pass
assert (
f'Task {task_id} is in terminal state: {terminal_state}'
in exc_info.value.message
)
@pytest.mark.asyncio
async def test_on_message_send_task_id_provided_but_task_not_found():
"""Test on_message_send when task_id is provided but task doesn't exist."""
pass
@pytest.mark.asyncio
async def test_on_message_send_stream_task_id_provided_but_task_not_found():
"""Test on_message_send_stream when task_id is provided but task doesn't exist."""
pass
class HelloWorldAgentExecutor(AgentExecutor):
"""Test Agent Implementation."""
async def execute(
self, context: RequestContext, event_queue: EventQueue
) -> None:
if context.message:
await event_queue.enqueue_event(
new_task_from_user_message(context.message)
)
updater = TaskUpdater(
event_queue,
task_id=context.task_id or str(uuid.uuid4()),
context_id=context.context_id or str(uuid.uuid4()),
)
await updater.update_status(TaskState.TASK_STATE_WORKING)
await updater.complete()
async def cancel(
self, context: RequestContext, event_queue: EventQueue
) -> None:
raise NotImplementedError('cancel not supported')
@pytest.mark.asyncio
@pytest.mark.timeout(1)
async def test_on_message_send_error_does_not_hang():
"""Test that if the consumer raises an exception during blocking wait, the producer is cancelled and no deadlock occurs."""
agent = HelloWorldAgentExecutor()
task_store = AsyncMock(spec=TaskStore)
task_store.get.return_value = None
task_store.save.side_effect = RuntimeError('This is an Error!')
request_handler = DefaultRequestHandlerV2(
agent_executor=agent,