-
Notifications
You must be signed in to change notification settings - Fork 428
Expand file tree
/
Copy pathtest_types.py
More file actions
1666 lines (1396 loc) · 55.2 KB
/
test_types.py
File metadata and controls
1666 lines (1396 loc) · 55.2 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
from typing import Any
import pytest
from pydantic import ValidationError
from a2a.types import (
A2AError,
A2ARequest,
APIKeySecurityScheme,
AgentCapabilities,
AgentCard,
AgentProvider,
AgentSkill,
Artifact,
CancelTaskRequest,
CancelTaskResponse,
CancelTaskSuccessResponse,
ContentTypeNotSupportedError,
DataPart,
FileBase,
FilePart,
FileWithBytes,
FileWithUri,
GetAuthenticatedExtendedCardRequest,
GetAuthenticatedExtendedCardResponse,
GetAuthenticatedExtendedCardSuccessResponse,
GetTaskPushNotificationConfigParams,
GetTaskPushNotificationConfigRequest,
GetTaskPushNotificationConfigResponse,
GetTaskPushNotificationConfigSuccessResponse,
GetTaskRequest,
GetTaskResponse,
GetTaskSuccessResponse,
In,
InternalError,
InvalidParamsError,
InvalidRequestError,
JSONParseError,
JSONRPCError,
JSONRPCErrorResponse,
JSONRPCMessage,
JSONRPCRequest,
JSONRPCResponse,
Message,
MessageSendParams,
MethodNotFoundError,
OAuth2SecurityScheme,
Part,
PartBase,
PushNotificationAuthenticationInfo,
PushNotificationConfig,
PushNotificationNotSupportedError,
Role,
SecurityScheme,
SendMessageRequest,
SendMessageResponse,
SendMessageSuccessResponse,
SendStreamingMessageRequest,
SendStreamingMessageResponse,
SendStreamingMessageSuccessResponse,
SetTaskPushNotificationConfigRequest,
SetTaskPushNotificationConfigResponse,
SetTaskPushNotificationConfigSuccessResponse,
Task,
TaskArtifactUpdateEvent,
TaskIdParams,
TaskNotCancelableError,
TaskNotFoundError,
TaskPushNotificationConfig,
TaskQueryParams,
TaskResubscriptionRequest,
TaskState,
TaskStatus,
TaskStatusUpdateEvent,
TextPart,
UnsupportedOperationError,
)
# --- Helper Data ---
MINIMAL_AGENT_SECURITY_SCHEME: dict[str, Any] = {
'type': 'apiKey',
'in': 'header',
'name': 'X-API-KEY',
}
MINIMAL_AGENT_SKILL: dict[str, Any] = {
'id': 'skill-123',
'name': 'Recipe Finder',
'description': 'Finds recipes',
'tags': ['cooking'],
}
FULL_AGENT_SKILL: dict[str, Any] = {
'id': 'skill-123',
'name': 'Recipe Finder',
'description': 'Finds recipes',
'tags': ['cooking', 'food'],
'examples': ['Find me a pasta recipe'],
'inputModes': ['text/plain'],
'outputModes': ['application/json'],
}
MINIMAL_AGENT_CARD: dict[str, Any] = {
'capabilities': {}, # AgentCapabilities is required but can be empty
'defaultInputModes': ['text/plain'],
'defaultOutputModes': ['application/json'],
'description': 'Test Agent',
'name': 'TestAgent',
'skills': [MINIMAL_AGENT_SKILL],
'url': 'http://example.com/agent',
'version': '1.0',
}
TEXT_PART_DATA: dict[str, Any] = {'kind': 'text', 'text': 'Hello'}
FILE_URI_PART_DATA: dict[str, Any] = {
'kind': 'file',
'file': {'uri': 'file:///path/to/file.txt', 'mimeType': 'text/plain'},
}
FILE_BYTES_PART_DATA: dict[str, Any] = {
'kind': 'file',
'file': {'bytes': 'aGVsbG8=', 'name': 'hello.txt'}, # base64 for "hello"
}
DATA_PART_DATA: dict[str, Any] = {'kind': 'data', 'data': {'key': 'value'}}
MINIMAL_MESSAGE_USER: dict[str, Any] = {
'role': 'user',
'parts': [TEXT_PART_DATA],
'message_id': 'msg-123',
'kind': 'message',
}
AGENT_MESSAGE_WITH_FILE: dict[str, Any] = {
'role': 'agent',
'parts': [TEXT_PART_DATA, FILE_URI_PART_DATA],
'metadata': {'timestamp': 'now'},
'message_id': 'msg-456',
}
MINIMAL_TASK_STATUS: dict[str, Any] = {'state': 'submitted'}
FULL_TASK_STATUS: dict[str, Any] = {
'state': 'working',
'message': MINIMAL_MESSAGE_USER,
'timestamp': '2023-10-27T10:00:00Z',
}
MINIMAL_TASK: dict[str, Any] = {
'id': 'task-abc',
'context_id': 'session-xyz',
'status': MINIMAL_TASK_STATUS,
'kind': 'task',
}
FULL_TASK: dict[str, Any] = {
'id': 'task-abc',
'context_id': 'session-xyz',
'status': FULL_TASK_STATUS,
'history': [MINIMAL_MESSAGE_USER, AGENT_MESSAGE_WITH_FILE],
'artifacts': [
{
'artifactId': 'artifact-123',
'parts': [DATA_PART_DATA],
'name': 'result_data',
}
],
'metadata': {'priority': 'high'},
'kind': 'task',
}
MINIMAL_TASK_ID_PARAMS: dict[str, Any] = {'id': 'task-123'}
FULL_TASK_ID_PARAMS: dict[str, Any] = {
'id': 'task-456',
'metadata': {'source': 'test'},
}
JSONRPC_ERROR_DATA: dict[str, Any] = {
'code': -32600,
'message': 'Invalid Request',
}
JSONRPC_SUCCESS_RESULT: dict[str, Any] = {'status': 'ok', 'data': [1, 2, 3]}
# --- Test Functions ---
def test_security_scheme_valid():
scheme = SecurityScheme.model_validate(MINIMAL_AGENT_SECURITY_SCHEME)
assert isinstance(scheme.root, APIKeySecurityScheme)
assert scheme.root.type == 'apiKey'
assert scheme.root.in_ == In.header
assert scheme.root.name == 'X-API-KEY'
def test_security_scheme_invalid():
with pytest.raises(ValidationError):
APIKeySecurityScheme(
name='my_api_key',
) # Missing "in" # type: ignore
with pytest.raises(ValidationError):
OAuth2SecurityScheme(
description='OAuth2 scheme missing flows',
) # Missing "flows" # type: ignore
def test_agent_capabilities():
caps = AgentCapabilities(
streaming=None, state_transition_history=None, push_notifications=None
) # All optional
assert caps.push_notifications is None
assert caps.state_transition_history is None
assert caps.streaming is None
caps_full = AgentCapabilities(
push_notifications=True, state_transition_history=False, streaming=True
)
assert caps_full.push_notifications is True
assert caps_full.state_transition_history is False
assert caps_full.streaming is True
def test_agent_provider():
provider = AgentProvider(organization='Test Org', url='http://test.org')
assert provider.organization == 'Test Org'
assert provider.url == 'http://test.org'
with pytest.raises(ValidationError):
AgentProvider(organization='Test Org') # Missing url # type: ignore
def test_agent_skill_valid():
skill = AgentSkill(**MINIMAL_AGENT_SKILL)
assert skill.id == 'skill-123'
assert skill.name == 'Recipe Finder'
assert skill.description == 'Finds recipes'
assert skill.tags == ['cooking']
assert skill.examples is None
skill_full = AgentSkill(**FULL_AGENT_SKILL)
assert skill_full.examples == ['Find me a pasta recipe']
assert skill_full.input_modes == ['text/plain']
def test_agent_skill_invalid():
with pytest.raises(ValidationError):
AgentSkill(
id='abc', name='n', description='d'
) # Missing tags # type: ignore
AgentSkill(
**MINIMAL_AGENT_SKILL,
invalid_extra='foo', # type: ignore
) # Extra field
def test_agent_card_valid():
card = AgentCard(**MINIMAL_AGENT_CARD)
assert card.name == 'TestAgent'
assert card.version == '1.0'
assert len(card.skills) == 1
assert card.skills[0].id == 'skill-123'
assert card.provider is None # Optional
def test_agent_card_invalid():
bad_card_data = MINIMAL_AGENT_CARD.copy()
del bad_card_data['name']
with pytest.raises(ValidationError):
AgentCard(**bad_card_data) # Missing name
# --- Test Parts ---
def test_text_part():
part = TextPart(**TEXT_PART_DATA)
assert part.kind == 'text'
assert part.text == 'Hello'
assert part.metadata is None
with pytest.raises(ValidationError):
TextPart(type='text') # Missing text # type: ignore
with pytest.raises(ValidationError):
TextPart(
kind='file', # type: ignore
text='hello',
) # Wrong type literal
def test_file_part_variants():
# URI variant
file_uri = FileWithUri(
uri='file:///path/to/file.txt', mime_type='text/plain'
)
part_uri = FilePart(kind='file', file=file_uri)
assert isinstance(part_uri.file, FileWithUri)
assert part_uri.file.uri == 'file:///path/to/file.txt'
assert part_uri.file.mime_type == 'text/plain'
assert not hasattr(part_uri.file, 'bytes')
# Bytes variant
file_bytes = FileWithBytes(bytes='aGVsbG8=', name='hello.txt')
part_bytes = FilePart(kind='file', file=file_bytes)
assert isinstance(part_bytes.file, FileWithBytes)
assert part_bytes.file.bytes == 'aGVsbG8='
assert part_bytes.file.name == 'hello.txt'
assert not hasattr(part_bytes.file, 'uri')
# Test deserialization directly
part_uri_deserialized = FilePart.model_validate(FILE_URI_PART_DATA)
assert isinstance(part_uri_deserialized.file, FileWithUri)
assert part_uri_deserialized.file.uri == 'file:///path/to/file.txt'
part_bytes_deserialized = FilePart.model_validate(FILE_BYTES_PART_DATA)
assert isinstance(part_bytes_deserialized.file, FileWithBytes)
assert part_bytes_deserialized.file.bytes == 'aGVsbG8='
# Invalid - wrong type literal
with pytest.raises(ValidationError):
FilePart(kind='text', file=file_uri) # type: ignore
FilePart(**FILE_URI_PART_DATA, extra='extra') # type: ignore
def test_data_part():
part = DataPart(**DATA_PART_DATA)
assert part.kind == 'data'
assert part.data == {'key': 'value'}
with pytest.raises(ValidationError):
DataPart(type='data') # Missing data # type: ignore
def test_part_root_model():
# Test deserialization of the Union RootModel
part_text = Part.model_validate(TEXT_PART_DATA)
assert isinstance(part_text.root, TextPart)
assert part_text.root.text == 'Hello'
part_file = Part.model_validate(FILE_URI_PART_DATA)
assert isinstance(part_file.root, FilePart)
assert isinstance(part_file.root.file, FileWithUri)
part_data = Part.model_validate(DATA_PART_DATA)
assert isinstance(part_data.root, DataPart)
assert part_data.root.data == {'key': 'value'}
# Test serialization
assert part_text.model_dump(exclude_none=True) == TEXT_PART_DATA
assert part_file.model_dump(exclude_none=True) == FILE_URI_PART_DATA
assert part_data.model_dump(exclude_none=True) == DATA_PART_DATA
# --- Test Message and Task ---
def test_message():
msg = Message(**MINIMAL_MESSAGE_USER)
assert msg.role == Role.user
assert len(msg.parts) == 1
assert isinstance(
msg.parts[0].root, TextPart
) # Access root for RootModel Part
assert msg.metadata is None
msg_agent = Message(**AGENT_MESSAGE_WITH_FILE)
assert msg_agent.role == Role.agent
assert len(msg_agent.parts) == 2
assert isinstance(msg_agent.parts[1].root, FilePart)
assert msg_agent.metadata == {'timestamp': 'now'}
with pytest.raises(ValidationError):
Message(
role='invalid_role', # type: ignore
parts=[TEXT_PART_DATA], # type: ignore
) # Invalid enum
with pytest.raises(ValidationError):
Message(role=Role.user) # Missing parts # type: ignore
def test_task_status():
status = TaskStatus(**MINIMAL_TASK_STATUS)
assert status.state == TaskState.submitted
assert status.message is None
assert status.timestamp is None
status_full = TaskStatus(**FULL_TASK_STATUS)
assert status_full.state == TaskState.working
assert isinstance(status_full.message, Message)
assert status_full.timestamp == '2023-10-27T10:00:00Z'
with pytest.raises(ValidationError):
TaskStatus(state='invalid_state') # Invalid enum # type: ignore
def test_task():
task = Task(**MINIMAL_TASK)
assert task.id == 'task-abc'
assert task.context_id == 'session-xyz'
assert task.status.state == TaskState.submitted
assert task.history is None
assert task.artifacts is None
assert task.metadata is None
task_full = Task(**FULL_TASK)
assert task_full.id == 'task-abc'
assert task_full.status.state == TaskState.working
assert task_full.history is not None and len(task_full.history) == 2
assert isinstance(task_full.history[0], Message)
assert task_full.artifacts is not None and len(task_full.artifacts) == 1
assert isinstance(task_full.artifacts[0], Artifact)
assert task_full.artifacts[0].name == 'result_data'
assert task_full.metadata == {'priority': 'high'}
with pytest.raises(ValidationError):
Task(id='abc', sessionId='xyz') # Missing status # type: ignore
# --- Test JSON-RPC Structures ---
def test_jsonrpc_error():
err = JSONRPCError(code=-32600, message='Invalid Request')
assert err.code == -32600
assert err.message == 'Invalid Request'
assert err.data is None
err_data = JSONRPCError(
code=-32001, message='Task not found', data={'taskId': '123'}
)
assert err_data.code == -32001
assert err_data.data == {'taskId': '123'}
def test_jsonrpc_request():
req = JSONRPCRequest(jsonrpc='2.0', method='test_method', id=1)
assert req.jsonrpc == '2.0'
assert req.method == 'test_method'
assert req.id == 1
assert req.params is None
req_params = JSONRPCRequest(
jsonrpc='2.0', method='add', params={'a': 1, 'b': 2}, id='req-1'
)
assert req_params.params == {'a': 1, 'b': 2}
assert req_params.id == 'req-1'
with pytest.raises(ValidationError):
JSONRPCRequest(
jsonrpc='1.0', # type: ignore
method='m',
id=1,
) # Wrong version
with pytest.raises(ValidationError):
JSONRPCRequest(jsonrpc='2.0', id=1) # Missing method # type: ignore
def test_jsonrpc_error_response():
err_obj = JSONRPCError(**JSONRPC_ERROR_DATA)
resp = JSONRPCErrorResponse(jsonrpc='2.0', error=err_obj, id='err-1')
assert resp.jsonrpc == '2.0'
assert resp.id == 'err-1'
assert resp.error.code == -32600
assert resp.error.message == 'Invalid Request'
with pytest.raises(ValidationError):
JSONRPCErrorResponse(
jsonrpc='2.0', id='err-1'
) # Missing error # type: ignore
def test_jsonrpc_response_root_model() -> None:
# Success case
success_data: dict[str, Any] = {
'jsonrpc': '2.0',
'result': MINIMAL_TASK,
'id': 1,
}
resp_success = JSONRPCResponse.model_validate(success_data)
assert isinstance(resp_success.root, SendMessageSuccessResponse)
assert resp_success.root.result == Task(**MINIMAL_TASK)
# Error case
error_data: dict[str, Any] = {
'jsonrpc': '2.0',
'error': JSONRPC_ERROR_DATA,
'id': 'err-1',
}
resp_error = JSONRPCResponse.model_validate(error_data)
assert isinstance(resp_error.root, JSONRPCErrorResponse)
assert resp_error.root.error.code == -32600
# Note: .model_dump() might serialize the nested error model
assert resp_error.model_dump(exclude_none=True) == error_data
# Invalid case (neither success nor error structure)
with pytest.raises(ValidationError):
JSONRPCResponse.model_validate({'jsonrpc': '2.0', 'id': 1})
# --- Test Request/Response Wrappers ---
def test_send_message_request() -> None:
params = MessageSendParams(message=Message(**MINIMAL_MESSAGE_USER))
req_data: dict[str, Any] = {
'jsonrpc': '2.0',
'method': 'message/send',
'params': params.model_dump(),
'id': 5,
}
req = SendMessageRequest.model_validate(req_data)
assert req.method == 'message/send'
assert isinstance(req.params, MessageSendParams)
assert req.params.message.role == Role.user
with pytest.raises(ValidationError): # Wrong method literal
SendMessageRequest.model_validate(
{**req_data, 'method': 'wrong/method'}
)
def test_send_subscribe_request() -> None:
params = MessageSendParams(message=Message(**MINIMAL_MESSAGE_USER))
req_data: dict[str, Any] = {
'jsonrpc': '2.0',
'method': 'message/stream',
'params': params.model_dump(),
'id': 5,
}
req = SendStreamingMessageRequest.model_validate(req_data)
assert req.method == 'message/stream'
assert isinstance(req.params, MessageSendParams)
assert req.params.message.role == Role.user
with pytest.raises(ValidationError): # Wrong method literal
SendStreamingMessageRequest.model_validate(
{**req_data, 'method': 'wrong/method'}
)
def test_get_task_request() -> None:
params = TaskQueryParams(id='task-1', history_length=2)
req_data: dict[str, Any] = {
'jsonrpc': '2.0',
'method': 'tasks/get',
'params': params.model_dump(),
'id': 5,
}
req = GetTaskRequest.model_validate(req_data)
assert req.method == 'tasks/get'
assert isinstance(req.params, TaskQueryParams)
assert req.params.id == 'task-1'
assert req.params.history_length == 2
with pytest.raises(ValidationError): # Wrong method literal
GetTaskRequest.model_validate({**req_data, 'method': 'wrong/method'})
def test_cancel_task_request() -> None:
params = TaskIdParams(id='task-1')
req_data: dict[str, Any] = {
'jsonrpc': '2.0',
'method': 'tasks/cancel',
'params': params.model_dump(),
'id': 5,
}
req = CancelTaskRequest.model_validate(req_data)
assert req.method == 'tasks/cancel'
assert isinstance(req.params, TaskIdParams)
assert req.params.id == 'task-1'
with pytest.raises(ValidationError): # Wrong method literal
CancelTaskRequest.model_validate({**req_data, 'method': 'wrong/method'})
def test_get_task_response() -> None:
resp_data: dict[str, Any] = {
'jsonrpc': '2.0',
'result': MINIMAL_TASK,
'id': 'resp-1',
}
resp = GetTaskResponse.model_validate(resp_data)
assert resp.root.id == 'resp-1'
assert isinstance(resp.root, GetTaskSuccessResponse)
assert isinstance(resp.root.result, Task)
assert resp.root.result.id == 'task-abc'
with pytest.raises(ValidationError): # Result is not a Task
GetTaskResponse.model_validate(
{'jsonrpc': '2.0', 'result': {'wrong': 'data'}, 'id': 1}
)
resp_data_err: dict[str, Any] = {
'jsonrpc': '2.0',
'error': JSONRPCError(**TaskNotFoundError().model_dump()),
'id': 'resp-1',
}
resp_err = GetTaskResponse.model_validate(resp_data_err)
assert resp_err.root.id == 'resp-1'
assert isinstance(resp_err.root, JSONRPCErrorResponse)
assert resp_err.root.error is not None
assert isinstance(resp_err.root.error, JSONRPCError)
def test_send_message_response() -> None:
resp_data: dict[str, Any] = {
'jsonrpc': '2.0',
'result': MINIMAL_TASK,
'id': 'resp-1',
}
resp = SendMessageResponse.model_validate(resp_data)
assert resp.root.id == 'resp-1'
assert isinstance(resp.root, SendMessageSuccessResponse)
assert isinstance(resp.root.result, Task)
assert resp.root.result.id == 'task-abc'
with pytest.raises(ValidationError): # Result is not a Task
SendMessageResponse.model_validate(
{'jsonrpc': '2.0', 'result': {'wrong': 'data'}, 'id': 1}
)
resp_data_err: dict[str, Any] = {
'jsonrpc': '2.0',
'error': JSONRPCError(**TaskNotFoundError().model_dump()),
'id': 'resp-1',
}
resp_err = SendMessageResponse.model_validate(resp_data_err)
assert resp_err.root.id == 'resp-1'
assert isinstance(resp_err.root, JSONRPCErrorResponse)
assert resp_err.root.error is not None
assert isinstance(resp_err.root.error, JSONRPCError)
def test_cancel_task_response() -> None:
resp_data: dict[str, Any] = {
'jsonrpc': '2.0',
'result': MINIMAL_TASK,
'id': 1,
}
resp = CancelTaskResponse.model_validate(resp_data)
assert resp.root.id == 1
assert isinstance(resp.root, CancelTaskSuccessResponse)
assert isinstance(resp.root.result, Task)
assert resp.root.result.id == 'task-abc'
resp_data_err: dict[str, Any] = {
'jsonrpc': '2.0',
'error': JSONRPCError(**TaskNotFoundError().model_dump()),
'id': 'resp-1',
}
resp_err = CancelTaskResponse.model_validate(resp_data_err)
assert resp_err.root.id == 'resp-1'
assert isinstance(resp_err.root, JSONRPCErrorResponse)
assert resp_err.root.error is not None
assert isinstance(resp_err.root.error, JSONRPCError)
def test_send_message_streaming_status_update_response() -> None:
task_status_update_event_data: dict[str, Any] = {
'status': MINIMAL_TASK_STATUS,
'taskId': '1',
'context_id': '2',
'final': False,
'kind': 'status-update',
}
event_data: dict[str, Any] = {
'jsonrpc': '2.0',
'id': 1,
'result': task_status_update_event_data,
}
response = SendStreamingMessageResponse.model_validate(event_data)
assert response.root.id == 1
assert isinstance(response.root, SendStreamingMessageSuccessResponse)
assert isinstance(response.root.result, TaskStatusUpdateEvent)
assert response.root.result.status.state == TaskState.submitted
assert response.root.result.task_id == '1'
assert not response.root.result.final
with pytest.raises(
ValidationError
): # Result is not a TaskStatusUpdateEvent
SendStreamingMessageResponse.model_validate(
{'jsonrpc': '2.0', 'result': {'wrong': 'data'}, 'id': 1}
)
event_data = {
'jsonrpc': '2.0',
'id': 1,
'result': {**task_status_update_event_data, 'final': True},
}
response = SendStreamingMessageResponse.model_validate(event_data)
assert response.root.id == 1
assert isinstance(response.root, SendStreamingMessageSuccessResponse)
assert isinstance(response.root.result, TaskStatusUpdateEvent)
assert response.root.result.final
resp_data_err: dict[str, Any] = {
'jsonrpc': '2.0',
'error': JSONRPCError(**TaskNotFoundError().model_dump()),
'id': 'resp-1',
}
resp_err = SendStreamingMessageResponse.model_validate(resp_data_err)
assert resp_err.root.id == 'resp-1'
assert isinstance(resp_err.root, JSONRPCErrorResponse)
assert resp_err.root.error is not None
assert isinstance(resp_err.root.error, JSONRPCError)
def test_send_message_streaming_artifact_update_response() -> None:
text_part = TextPart(**TEXT_PART_DATA)
data_part = DataPart(**DATA_PART_DATA)
artifact = Artifact(
artifact_id='artifact-123',
name='result_data',
parts=[Part(root=text_part), Part(root=data_part)],
)
task_artifact_update_event_data: dict[str, Any] = {
'artifact': artifact,
'taskId': 'task_id',
'context_id': '2',
'append': False,
'lastChunk': True,
'kind': 'artifact-update',
}
event_data: dict[str, Any] = {
'jsonrpc': '2.0',
'id': 1,
'result': task_artifact_update_event_data,
}
response = SendStreamingMessageResponse.model_validate(event_data)
assert response.root.id == 1
assert isinstance(response.root, SendStreamingMessageSuccessResponse)
assert isinstance(response.root.result, TaskArtifactUpdateEvent)
assert response.root.result.artifact.artifact_id == 'artifact-123'
assert response.root.result.artifact.name == 'result_data'
assert response.root.result.task_id == 'task_id'
assert not response.root.result.append
assert response.root.result.last_chunk
assert len(response.root.result.artifact.parts) == 2
assert isinstance(response.root.result.artifact.parts[0].root, TextPart)
assert isinstance(response.root.result.artifact.parts[1].root, DataPart)
def test_set_task_push_notification_response() -> None:
task_push_config = TaskPushNotificationConfig(
task_id='t2',
push_notification_config=PushNotificationConfig(
url='https://example.com', token='token'
),
)
resp_data: dict[str, Any] = {
'jsonrpc': '2.0',
'result': task_push_config.model_dump(),
'id': 1,
}
resp = SetTaskPushNotificationConfigResponse.model_validate(resp_data)
assert resp.root.id == 1
assert isinstance(resp.root, SetTaskPushNotificationConfigSuccessResponse)
assert isinstance(resp.root.result, TaskPushNotificationConfig)
assert resp.root.result.task_id == 't2'
assert (
resp.root.result.push_notification_config.url == 'https://example.com'
)
assert resp.root.result.push_notification_config.token == 'token'
assert resp.root.result.push_notification_config.authentication is None
auth_info_dict: dict[str, Any] = {
'schemes': ['Bearer', 'Basic'],
'credentials': 'user:pass',
}
task_push_config.push_notification_config.authentication = (
PushNotificationAuthenticationInfo(**auth_info_dict)
)
resp_data = {
'jsonrpc': '2.0',
'result': task_push_config.model_dump(),
'id': 1,
}
resp = SetTaskPushNotificationConfigResponse.model_validate(resp_data)
assert isinstance(resp.root, SetTaskPushNotificationConfigSuccessResponse)
assert resp.root.result.push_notification_config.authentication is not None
assert resp.root.result.push_notification_config.authentication.schemes == [
'Bearer',
'Basic',
]
assert (
resp.root.result.push_notification_config.authentication.credentials
== 'user:pass'
)
resp_data_err: dict[str, Any] = {
'jsonrpc': '2.0',
'error': JSONRPCError(**TaskNotFoundError().model_dump()),
'id': 'resp-1',
}
resp_err = SetTaskPushNotificationConfigResponse.model_validate(
resp_data_err
)
assert resp_err.root.id == 'resp-1'
assert isinstance(resp_err.root, JSONRPCErrorResponse)
assert resp_err.root.error is not None
assert isinstance(resp_err.root.error, JSONRPCError)
def test_get_task_push_notification_response() -> None:
task_push_config = TaskPushNotificationConfig(
task_id='t2',
push_notification_config=PushNotificationConfig(
url='https://example.com', token='token'
),
)
resp_data: dict[str, Any] = {
'jsonrpc': '2.0',
'result': task_push_config.model_dump(),
'id': 1,
}
resp = GetTaskPushNotificationConfigResponse.model_validate(resp_data)
assert resp.root.id == 1
assert isinstance(resp.root, GetTaskPushNotificationConfigSuccessResponse)
assert isinstance(resp.root.result, TaskPushNotificationConfig)
assert resp.root.result.task_id == 't2'
assert (
resp.root.result.push_notification_config.url == 'https://example.com'
)
assert resp.root.result.push_notification_config.token == 'token'
assert resp.root.result.push_notification_config.authentication is None
auth_info_dict: dict[str, Any] = {
'schemes': ['Bearer', 'Basic'],
'credentials': 'user:pass',
}
task_push_config.push_notification_config.authentication = (
PushNotificationAuthenticationInfo(**auth_info_dict)
)
resp_data = {
'jsonrpc': '2.0',
'result': task_push_config.model_dump(),
'id': 1,
}
resp = GetTaskPushNotificationConfigResponse.model_validate(resp_data)
assert isinstance(resp.root, GetTaskPushNotificationConfigSuccessResponse)
assert resp.root.result.push_notification_config.authentication is not None
assert resp.root.result.push_notification_config.authentication.schemes == [
'Bearer',
'Basic',
]
assert (
resp.root.result.push_notification_config.authentication.credentials
== 'user:pass'
)
resp_data_err: dict[str, Any] = {
'jsonrpc': '2.0',
'error': JSONRPCError(**TaskNotFoundError().model_dump()),
'id': 'resp-1',
}
resp_err = GetTaskPushNotificationConfigResponse.model_validate(
resp_data_err
)
assert resp_err.root.id == 'resp-1'
assert isinstance(resp_err.root, JSONRPCErrorResponse)
assert resp_err.root.error is not None
assert isinstance(resp_err.root.error, JSONRPCError)
# --- Test A2ARequest Root Model ---
def test_a2a_request_root_model() -> None:
# SendMessageRequest case
send_params = MessageSendParams(message=Message(**MINIMAL_MESSAGE_USER))
send_req_data: dict[str, Any] = {
'jsonrpc': '2.0',
'method': 'message/send',
'params': send_params.model_dump(),
'id': 1,
}
a2a_req_send = A2ARequest.model_validate(send_req_data)
assert isinstance(a2a_req_send.root, SendMessageRequest)
assert a2a_req_send.root.method == 'message/send'
# SendStreamingMessageRequest case
send_subs_req_data: dict[str, Any] = {
'jsonrpc': '2.0',
'method': 'message/stream',
'params': send_params.model_dump(),
'id': 1,
}
a2a_req_send_subs = A2ARequest.model_validate(send_subs_req_data)
assert isinstance(a2a_req_send_subs.root, SendStreamingMessageRequest)
assert a2a_req_send_subs.root.method == 'message/stream'
# GetTaskRequest case
get_params = TaskQueryParams(id='t2')
get_req_data: dict[str, Any] = {
'jsonrpc': '2.0',
'method': 'tasks/get',
'params': get_params.model_dump(),
'id': 2,
}
a2a_req_get = A2ARequest.model_validate(get_req_data)
assert isinstance(a2a_req_get.root, GetTaskRequest)
assert a2a_req_get.root.method == 'tasks/get'
# CancelTaskRequest case
id_params = TaskIdParams(id='t2')
cancel_req_data: dict[str, Any] = {
'jsonrpc': '2.0',
'method': 'tasks/cancel',
'params': id_params.model_dump(),
'id': 2,
}
a2a_req_cancel = A2ARequest.model_validate(cancel_req_data)
assert isinstance(a2a_req_cancel.root, CancelTaskRequest)
assert a2a_req_cancel.root.method == 'tasks/cancel'
# SetTaskPushNotificationConfigRequest
task_push_config = TaskPushNotificationConfig(
task_id='t2',
push_notification_config=PushNotificationConfig(
url='https://example.com', token='token'
),
)
set_push_notif_req_data: dict[str, Any] = {
'id': 1,
'jsonrpc': '2.0',
'method': 'tasks/pushNotificationConfig/set',
'params': task_push_config.model_dump(),
}
a2a_req_set_push_req = A2ARequest.model_validate(set_push_notif_req_data)
assert isinstance(
a2a_req_set_push_req.root, SetTaskPushNotificationConfigRequest
)
assert isinstance(
a2a_req_set_push_req.root.params, TaskPushNotificationConfig
)
assert (
a2a_req_set_push_req.root.method == 'tasks/pushNotificationConfig/set'
)
# GetTaskPushNotificationConfigRequest
id_params = TaskIdParams(id='t2')
get_push_notif_req_data: dict[str, Any] = {
'id': 1,
'jsonrpc': '2.0',
'method': 'tasks/pushNotificationConfig/get',
'params': id_params.model_dump(),
}
a2a_req_get_push_req = A2ARequest.model_validate(get_push_notif_req_data)
assert isinstance(
a2a_req_get_push_req.root, GetTaskPushNotificationConfigRequest
)
assert isinstance(a2a_req_get_push_req.root.params, TaskIdParams)
assert (
a2a_req_get_push_req.root.method == 'tasks/pushNotificationConfig/get'
)
# TaskResubscriptionRequest
task_resubscribe_req_data: dict[str, Any] = {
'jsonrpc': '2.0',
'method': 'tasks/resubscribe',
'params': id_params.model_dump(),
'id': 2,
}
a2a_req_task_resubscribe_req = A2ARequest.model_validate(
task_resubscribe_req_data
)
assert isinstance(
a2a_req_task_resubscribe_req.root, TaskResubscriptionRequest
)
assert isinstance(a2a_req_task_resubscribe_req.root.params, TaskIdParams)
assert a2a_req_task_resubscribe_req.root.method == 'tasks/resubscribe'
# GetAuthenticatedExtendedCardRequest
get_auth_card_req_data: dict[str, Any] = {
'jsonrpc': '2.0',
'method': 'agent/getAuthenticatedExtendedCard',
'id': 2,
}
a2a_req_get_auth_card = A2ARequest.model_validate(get_auth_card_req_data)
assert isinstance(
a2a_req_get_auth_card.root, GetAuthenticatedExtendedCardRequest
)
assert (
a2a_req_get_auth_card.root.method
== 'agent/getAuthenticatedExtendedCard'
)
# Invalid method case
invalid_req_data: dict[str, Any] = {
'jsonrpc': '2.0',
'method': 'invalid/method',
'params': {},
'id': 3,
}
with pytest.raises(ValidationError):
A2ARequest.model_validate(invalid_req_data)
def test_a2a_request_root_model_id_validation() -> None: