-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathtest_event_converter.py
More file actions
1130 lines (931 loc) · 40.4 KB
/
test_event_converter.py
File metadata and controls
1130 lines (931 loc) · 40.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
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from unittest.mock import Mock
from unittest.mock import patch
from a2a.types import DataPart
from a2a.types import Message
from a2a.types import Role
from a2a.types import Task
from a2a.types import TaskState
from a2a.types import TaskStatusUpdateEvent
from google.adk.a2a.converters.event_converter import _create_artifact_id
from google.adk.a2a.converters.event_converter import _create_error_status_event
from google.adk.a2a.converters.event_converter import _create_status_update_event
from google.adk.a2a.converters.event_converter import _get_adk_metadata_key
from google.adk.a2a.converters.event_converter import _get_context_metadata
from google.adk.a2a.converters.event_converter import _process_long_running_tool
from google.adk.a2a.converters.event_converter import _serialize_metadata_value
from google.adk.a2a.converters.event_converter import ARTIFACT_ID_SEPARATOR
from google.adk.a2a.converters.event_converter import convert_a2a_task_to_event
from google.adk.a2a.converters.event_converter import convert_event_to_a2a_events
from google.adk.a2a.converters.event_converter import convert_event_to_a2a_message
from google.adk.a2a.converters.event_converter import DEFAULT_ERROR_MESSAGE
from google.adk.a2a.converters.utils import ADK_METADATA_KEY_PREFIX
from google.adk.agents.invocation_context import InvocationContext
from google.adk.events.event import Event
from google.adk.events.event_actions import EventActions
import pytest
class TestEventConverter:
"""Test suite for event_converter module."""
def setup_method(self):
"""Set up test fixtures."""
self.mock_session = Mock()
self.mock_session.id = "test-session-id"
self.mock_artifact_service = Mock()
self.mock_invocation_context = Mock(spec=InvocationContext)
self.mock_invocation_context.app_name = "test-app"
self.mock_invocation_context.user_id = "test-user"
self.mock_invocation_context.session = self.mock_session
self.mock_invocation_context.artifact_service = self.mock_artifact_service
self.mock_event = Mock(spec=Event)
self.mock_event.id = None
self.mock_event.invocation_id = "test-invocation-id"
self.mock_event.author = "test-author"
self.mock_event.branch = None
self.mock_event.grounding_metadata = None
self.mock_event.custom_metadata = None
self.mock_event.usage_metadata = None
self.mock_event.error_code = None
self.mock_event.error_message = None
self.mock_event.content = None
self.mock_event.long_running_tool_ids = None
self.mock_event.actions = None
def test_get_adk_event_metadata_key_success(self):
"""Test successful metadata key generation."""
key = "test_key"
result = _get_adk_metadata_key(key)
assert result == f"{ADK_METADATA_KEY_PREFIX}{key}"
def test_get_adk_event_metadata_key_empty_string(self):
"""Test metadata key generation with empty string."""
with pytest.raises(ValueError) as exc_info:
_get_adk_metadata_key("")
assert "cannot be empty or None" in str(exc_info.value)
def test_get_adk_event_metadata_key_none(self):
"""Test metadata key generation with None."""
with pytest.raises(ValueError) as exc_info:
_get_adk_metadata_key(None)
assert "cannot be empty or None" in str(exc_info.value)
def test_serialize_metadata_value_with_model_dump(self):
"""Test serialization of value with model_dump method."""
mock_value = Mock()
mock_value.model_dump.return_value = {"key": "value"}
result = _serialize_metadata_value(mock_value)
assert result == {"key": "value"}
mock_value.model_dump.assert_called_once_with(
exclude_none=True, by_alias=True
)
def test_serialize_metadata_value_with_model_dump_exception(self):
"""Test serialization when model_dump raises exception."""
mock_value = Mock()
mock_value.model_dump.side_effect = Exception("Serialization failed")
with patch(
"google.adk.a2a.converters.event_converter.logger"
) as mock_logger:
result = _serialize_metadata_value(mock_value)
assert result == str(mock_value)
mock_logger.warning.assert_called_once()
def test_serialize_metadata_value_without_model_dump(self):
"""Test serialization of value without model_dump method."""
value = "simple_string"
result = _serialize_metadata_value(value)
assert result == "simple_string"
def test_get_context_metadata_success(self):
"""Test successful context metadata creation."""
result = _get_context_metadata(
self.mock_event, self.mock_invocation_context
)
assert result is not None
expected_keys = [
f"{ADK_METADATA_KEY_PREFIX}app_name",
f"{ADK_METADATA_KEY_PREFIX}user_id",
f"{ADK_METADATA_KEY_PREFIX}session_id",
f"{ADK_METADATA_KEY_PREFIX}invocation_id",
f"{ADK_METADATA_KEY_PREFIX}author",
f"{ADK_METADATA_KEY_PREFIX}event_id",
]
for key in expected_keys:
assert key in result
def test_get_context_metadata_with_optional_fields(self):
"""Test context metadata creation with optional fields."""
self.mock_event.branch = "test-branch"
self.mock_event.error_code = "ERROR_001"
mock_metadata = Mock()
mock_metadata.model_dump.return_value = {"test": "value"}
self.mock_event.grounding_metadata = mock_metadata
self.mock_event.actions = Mock()
self.mock_event.actions.model_dump.return_value = {"test_actions": "value"}
result = _get_context_metadata(
self.mock_event, self.mock_invocation_context
)
assert result is not None
assert f"{ADK_METADATA_KEY_PREFIX}branch" in result
assert f"{ADK_METADATA_KEY_PREFIX}grounding_metadata" in result
assert f"{ADK_METADATA_KEY_PREFIX}actions" in result
assert result[f"{ADK_METADATA_KEY_PREFIX}branch"] == "test-branch"
assert result[f"{ADK_METADATA_KEY_PREFIX}actions"] == {
"test_actions": "value"
}
# Check if error_code is in the result - it should be there since we set it
if f"{ADK_METADATA_KEY_PREFIX}error_code" in result:
assert result[f"{ADK_METADATA_KEY_PREFIX}error_code"] == "ERROR_001"
def test_get_context_metadata_none_event(self):
"""Test context metadata creation with None event."""
with pytest.raises(ValueError) as exc_info:
_get_context_metadata(None, self.mock_invocation_context)
assert "Event cannot be None" in str(exc_info.value)
def test_get_context_metadata_none_context(self):
"""Test context metadata creation with None context."""
with pytest.raises(ValueError) as exc_info:
_get_context_metadata(self.mock_event, None)
assert "Invocation context cannot be None" in str(exc_info.value)
def test_create_artifact_id(self):
"""Test artifact ID creation."""
app_name = "test-app"
user_id = "user123"
session_id = "session456"
filename = "test.txt"
version = 1
result = _create_artifact_id(
app_name, user_id, session_id, filename, version
)
expected = f"{app_name}{ARTIFACT_ID_SEPARATOR}{user_id}{ARTIFACT_ID_SEPARATOR}{session_id}{ARTIFACT_ID_SEPARATOR}{filename}{ARTIFACT_ID_SEPARATOR}{version}"
assert result == expected
def test_process_long_running_tool_marks_tool(self):
"""Test processing of long-running tool metadata."""
mock_a2a_part = Mock()
mock_data_part = Mock(spec=DataPart)
mock_data_part.metadata = {"adk_type": "function_call", "id": "tool-123"}
mock_data_part.data = Mock()
mock_data_part.data.get = Mock(return_value="tool-123")
mock_a2a_part.root = mock_data_part
self.mock_event.long_running_tool_ids = {"tool-123"}
with (
patch(
"google.adk.a2a.converters.event_converter.A2A_DATA_PART_METADATA_TYPE_KEY",
"type",
),
patch(
"google.adk.a2a.converters.event_converter.A2A_DATA_PART_METADATA_TYPE_FUNCTION_CALL",
"function_call",
),
patch(
"google.adk.a2a.converters.event_converter._get_adk_metadata_key"
) as mock_get_key,
):
mock_get_key.side_effect = lambda key: f"adk_{key}"
_process_long_running_tool(mock_a2a_part, self.mock_event)
expected_key = f"{ADK_METADATA_KEY_PREFIX}is_long_running"
assert mock_data_part.metadata[expected_key] is True
def test_process_long_running_tool_no_marking(self):
"""Test processing when tool should not be marked as long-running."""
mock_a2a_part = Mock()
mock_data_part = Mock(spec=DataPart)
mock_data_part.metadata = {"adk_type": "function_call", "id": "tool-456"}
mock_data_part.data = Mock()
mock_data_part.data.get = Mock(return_value="tool-456")
mock_a2a_part.root = mock_data_part
self.mock_event.long_running_tool_ids = {"tool-123"} # Different ID
with (
patch(
"google.adk.a2a.converters.event_converter.A2A_DATA_PART_METADATA_TYPE_KEY",
"type",
),
patch(
"google.adk.a2a.converters.event_converter.A2A_DATA_PART_METADATA_TYPE_FUNCTION_CALL",
"function_call",
),
patch(
"google.adk.a2a.converters.event_converter._get_adk_metadata_key"
) as mock_get_key,
):
mock_get_key.side_effect = lambda key: f"adk_{key}"
_process_long_running_tool(mock_a2a_part, self.mock_event)
expected_key = f"{ADK_METADATA_KEY_PREFIX}is_long_running"
assert expected_key not in mock_data_part.metadata
@patch(
"google.adk.a2a.converters.event_converter.convert_event_to_a2a_message"
)
@patch("google.adk.a2a.converters.event_converter._create_error_status_event")
@patch(
"google.adk.a2a.converters.event_converter._create_status_update_event"
)
def test_convert_event_to_a2a_events_full_scenario(
self,
mock_create_running,
mock_create_error,
mock_convert_message,
):
"""Test full event to A2A events conversion scenario."""
# Setup error
self.mock_event.error_code = "ERROR_001"
# Setup message
mock_message = Mock(spec=Message)
mock_convert_message.return_value = mock_message
# Setup mock returns
mock_error_event = Mock()
mock_create_error.return_value = mock_error_event
mock_running_event = Mock()
mock_create_running.return_value = mock_running_event
result = convert_event_to_a2a_events(
self.mock_event, self.mock_invocation_context
)
# Verify error event - now called with task_id and context_id parameters
mock_create_error.assert_called_once_with(
self.mock_event, self.mock_invocation_context, None, None
)
# Verify running event - now called with task_id and context_id parameters
mock_create_running.assert_called_once_with(
mock_message, self.mock_invocation_context, self.mock_event, None, None
)
# Verify result contains all events
assert len(result) == 2 # 1 error + 1 running
assert mock_error_event in result
assert mock_running_event in result
def test_convert_event_to_a2a_events_empty_scenario(self):
"""Test event to A2A events conversion with empty event."""
result = convert_event_to_a2a_events(
self.mock_event, self.mock_invocation_context
)
assert result == []
def test_convert_event_to_a2a_events_none_event(self):
"""Test event to A2A events conversion with None event."""
with pytest.raises(ValueError) as exc_info:
convert_event_to_a2a_events(None, self.mock_invocation_context)
assert "Event cannot be None" in str(exc_info.value)
def test_convert_event_to_a2a_events_none_context(self):
"""Test event to A2A events conversion with None context."""
with pytest.raises(ValueError) as exc_info:
convert_event_to_a2a_events(self.mock_event, None)
assert "Invocation context cannot be None" in str(exc_info.value)
@patch(
"google.adk.a2a.converters.event_converter.convert_event_to_a2a_message"
)
def test_convert_event_to_a2a_events_message_only(self, mock_convert_message):
"""Test event to A2A events conversion with message only."""
mock_message = Mock(spec=Message)
mock_convert_message.return_value = mock_message
with patch(
"google.adk.a2a.converters.event_converter._create_status_update_event"
) as mock_create_running:
mock_running_event = Mock()
mock_create_running.return_value = mock_running_event
result = convert_event_to_a2a_events(
self.mock_event, self.mock_invocation_context
)
assert len(result) == 1
assert result[0] == mock_running_event
# Verify the function is called with task_id and context_id parameters
mock_create_running.assert_called_once_with(
mock_message,
self.mock_invocation_context,
self.mock_event,
None,
None,
)
@patch("google.adk.a2a.converters.event_converter.logger")
def test_convert_event_to_a2a_events_exception_handling(self, mock_logger):
"""Test exception handling in convert_event_to_a2a_events."""
# Make convert_event_to_a2a_message raise an exception
with patch(
"google.adk.a2a.converters.event_converter.convert_event_to_a2a_message"
) as mock_convert_message:
mock_convert_message.side_effect = Exception("Test exception")
with pytest.raises(Exception):
convert_event_to_a2a_events(
self.mock_event, self.mock_invocation_context
)
mock_logger.error.assert_called_once()
def test_convert_event_to_a2a_events_with_task_id_and_context_id(self):
"""Test event to A2A events conversion with specific task_id and context_id."""
# Setup message
mock_message = Mock(spec=Message)
mock_message.parts = []
with patch(
"google.adk.a2a.converters.event_converter.convert_event_to_a2a_message"
) as mock_convert_message:
mock_convert_message.return_value = mock_message
with patch(
"google.adk.a2a.converters.event_converter._create_status_update_event"
) as mock_create_running:
mock_running_event = Mock()
mock_create_running.return_value = mock_running_event
task_id = "custom-task-id"
context_id = "custom-context-id"
result = convert_event_to_a2a_events(
self.mock_event, self.mock_invocation_context, task_id, context_id
)
assert len(result) == 1
assert result[0] == mock_running_event
# Verify the function is called with the specific task_id and context_id
mock_create_running.assert_called_once_with(
mock_message,
self.mock_invocation_context,
self.mock_event,
task_id,
context_id,
)
def test_convert_event_to_a2a_events_with_custom_ids(self):
"""Test event to A2A events conversion with custom IDs."""
# Setup message
mock_message = Mock(spec=Message)
mock_message.parts = []
with patch(
"google.adk.a2a.converters.event_converter.convert_event_to_a2a_message"
) as mock_convert_message:
mock_convert_message.return_value = mock_message
with patch(
"google.adk.a2a.converters.event_converter._create_status_update_event"
) as mock_create_running:
mock_running_event = Mock()
mock_create_running.return_value = mock_running_event
task_id = "custom-task-id"
context_id = "custom-context-id"
result = convert_event_to_a2a_events(
self.mock_event, self.mock_invocation_context, task_id, context_id
)
assert len(result) == 1 # 1 status
assert mock_running_event in result
# Verify status update is called with custom IDs
mock_create_running.assert_called_once_with(
mock_message,
self.mock_invocation_context,
self.mock_event,
task_id,
context_id,
)
def test_create_status_update_event_with_auth_required_state(self):
"""Test creation of status update event with auth_required state."""
from a2a.types import DataPart
from a2a.types import Part
# Create a mock message with a part that triggers auth_required state
mock_message = Mock(spec=Message)
mock_part = Mock()
mock_data_part = Mock(spec=DataPart)
mock_data_part.metadata = {
"adk_type": "function_call",
"adk_is_long_running": True,
}
mock_data_part.data = Mock()
mock_data_part.data.get = Mock(return_value="request_euc")
mock_part.root = mock_data_part
mock_message.parts = [mock_part]
task_id = "test-task-id"
context_id = "test-context-id"
with patch(
"google.adk.a2a.converters.event_converter.datetime"
) as mock_datetime:
mock_datetime.fromtimestamp.return_value.isoformat.return_value = (
"2023-01-01T00:00:00"
)
with (
patch(
"google.adk.a2a.converters.event_converter.A2A_DATA_PART_METADATA_TYPE_KEY",
"type",
),
patch(
"google.adk.a2a.converters.event_converter.A2A_DATA_PART_METADATA_TYPE_FUNCTION_CALL",
"function_call",
),
patch(
"google.adk.a2a.converters.event_converter.A2A_DATA_PART_METADATA_IS_LONG_RUNNING_KEY",
"is_long_running",
),
patch(
"google.adk.a2a.converters.event_converter.REQUEST_EUC_FUNCTION_CALL_NAME",
"request_euc",
),
patch(
"google.adk.a2a.converters.event_converter._get_adk_metadata_key"
) as mock_get_key,
):
mock_get_key.side_effect = lambda key: f"adk_{key}"
result = _create_status_update_event(
mock_message,
self.mock_invocation_context,
self.mock_event,
task_id,
context_id,
)
assert isinstance(result, TaskStatusUpdateEvent)
assert result.task_id == task_id
assert result.context_id == context_id
assert result.status.state == TaskState.auth_required
def test_create_status_update_event_with_input_required_state(self):
"""Test creation of status update event with input_required state."""
from a2a.types import DataPart
from a2a.types import Part
# Create a mock message with a part that triggers input_required state
mock_message = Mock(spec=Message)
mock_part = Mock()
mock_data_part = Mock(spec=DataPart)
mock_data_part.metadata = {
"adk_type": "function_call",
"adk_is_long_running": True,
}
mock_data_part.data = Mock()
mock_data_part.data.get = Mock(return_value="some_other_function")
mock_part.root = mock_data_part
mock_message.parts = [mock_part]
task_id = "test-task-id"
context_id = "test-context-id"
with patch(
"google.adk.a2a.converters.event_converter.datetime"
) as mock_datetime:
mock_datetime.fromtimestamp.return_value.isoformat.return_value = (
"2023-01-01T00:00:00"
)
with (
patch(
"google.adk.a2a.converters.event_converter.A2A_DATA_PART_METADATA_TYPE_KEY",
"type",
),
patch(
"google.adk.a2a.converters.event_converter.A2A_DATA_PART_METADATA_TYPE_FUNCTION_CALL",
"function_call",
),
patch(
"google.adk.a2a.converters.event_converter.A2A_DATA_PART_METADATA_IS_LONG_RUNNING_KEY",
"is_long_running",
),
patch(
"google.adk.a2a.converters.event_converter.REQUEST_EUC_FUNCTION_CALL_NAME",
"request_euc",
),
patch(
"google.adk.a2a.converters.event_converter._get_adk_metadata_key"
) as mock_get_key,
):
mock_get_key.side_effect = lambda key: f"adk_{key}"
result = _create_status_update_event(
mock_message,
self.mock_invocation_context,
self.mock_event,
task_id,
context_id,
)
assert isinstance(result, TaskStatusUpdateEvent)
assert result.task_id == task_id
assert result.context_id == context_id
assert result.status.state == TaskState.input_required
def test_convert_event_to_a2a_message_with_multiple_parts_returned(self):
"""Test event to message conversion when part_converter returns multiple parts."""
from a2a import types as a2a_types
from google.adk.a2a.converters.event_converter import convert_event_to_a2a_message
from google.genai import types as genai_types
# Arrange
mock_genai_part = genai_types.Part(text="source part")
mock_a2a_part1 = a2a_types.Part(root=a2a_types.TextPart(text="part 1"))
mock_a2a_part2 = a2a_types.Part(root=a2a_types.TextPart(text="part 2"))
mock_convert_part = Mock()
mock_convert_part.return_value = [mock_a2a_part1, mock_a2a_part2]
self.mock_event.content = genai_types.Content(
parts=[mock_genai_part], role="model"
)
# Act
result = convert_event_to_a2a_message(
self.mock_event,
self.mock_invocation_context,
part_converter=mock_convert_part,
)
# Assert
assert result is not None
assert len(result.parts) == 2
assert result.parts[0].root.text == "part 1"
assert result.parts[1].root.text == "part 2"
mock_convert_part.assert_called_once_with(mock_genai_part)
class TestA2AToEventConverters:
"""Test suite for A2A to Event conversion functions."""
def setup_method(self):
"""Set up test fixtures."""
self.mock_invocation_context = Mock(spec=InvocationContext)
self.mock_invocation_context.invocation_id = "test-invocation-id"
self.mock_invocation_context.branch = "test-branch"
def test_convert_a2a_task_to_event_with_artifacts_priority(self):
"""Test convert_a2a_task_to_event prioritizes artifacts over status/history."""
from a2a.types import Artifact
from a2a.types import Part
from a2a.types import TaskStatus
from a2a.types import TextPart
# Create mock artifacts
artifact_part = Part(root=TextPart(text="artifact content"))
mock_artifact = Mock(spec=Artifact)
mock_artifact.parts = [artifact_part]
# Create mock status and history
status_part = Part(root=TextPart(text="status content"))
mock_status = Mock(spec=TaskStatus)
mock_status.message = Mock(spec=Message)
mock_status.message.parts = [status_part]
history_part = Part(root=TextPart(text="history content"))
mock_history_message = Mock(spec=Message)
mock_history_message.parts = [history_part]
# Create task with all three sources
mock_task = Mock(spec=Task)
mock_task.artifacts = [mock_artifact]
mock_task.status = mock_status
mock_task.history = [mock_history_message]
with patch(
"google.adk.a2a.converters.event_converter.convert_a2a_message_to_event"
) as mock_convert_message:
mock_event = Mock(spec=Event)
mock_convert_message.return_value = mock_event
result = convert_a2a_task_to_event(
mock_task, "test-author", self.mock_invocation_context
)
assert result == mock_event
# Should call convert_a2a_message_to_event with a message created from artifacts
mock_convert_message.assert_called_once()
called_message = mock_convert_message.call_args[0][0]
assert called_message.role == Role.agent
assert called_message.parts == [artifact_part]
def test_convert_a2a_task_to_event_with_status_message(self):
"""Test convert_a2a_task_to_event with status message (no artifacts)."""
from a2a.types import Part
from a2a.types import TaskStatus
from a2a.types import TextPart
# Create mock status
status_part = Part(root=TextPart(text="status content"))
mock_status = Mock(spec=TaskStatus)
mock_status.message = Mock(spec=Message)
mock_status.message.parts = [status_part]
# Create task with no artifacts
mock_task = Mock(spec=Task)
mock_task.artifacts = None
mock_task.status = mock_status
mock_task.history = []
with patch(
"google.adk.a2a.converters.event_converter.convert_a2a_message_to_event"
) as mock_convert_message:
from google.adk.a2a.converters.part_converter import convert_a2a_part_to_genai_part
mock_event = Mock(spec=Event)
mock_convert_message.return_value = mock_event
result = convert_a2a_task_to_event(
mock_task, "test-author", self.mock_invocation_context
)
assert result == mock_event
# Should call convert_a2a_message_to_event with the status message
mock_convert_message.assert_called_once_with(
mock_status.message,
"test-author",
self.mock_invocation_context,
part_converter=convert_a2a_part_to_genai_part,
)
def test_convert_a2a_task_to_event_with_history_message(self):
"""Test converting A2A task with history message when no status message."""
from google.adk.a2a.converters.event_converter import convert_a2a_task_to_event
# Create mock message and task
mock_message = Mock(spec=Message)
mock_message.role = Role.agent
mock_task = Mock(spec=Task)
mock_task.artifacts = None
mock_task.status = None
mock_task.history = [mock_message]
# Mock the convert_a2a_message_to_event function
with patch(
"google.adk.a2a.converters.event_converter.convert_a2a_message_to_event"
) as mock_convert_message:
from google.adk.a2a.converters.part_converter import convert_a2a_part_to_genai_part
mock_event = Mock(spec=Event)
mock_event.invocation_id = "test-invocation-id"
mock_convert_message.return_value = mock_event
result = convert_a2a_task_to_event(mock_task, "test-author")
# Verify the message converter was called with correct parameters
mock_convert_message.assert_called_once_with(
mock_message,
"test-author",
None,
part_converter=convert_a2a_part_to_genai_part,
)
assert result == mock_event
def test_convert_a2a_task_to_event_no_message(self):
"""Test converting A2A task with no message."""
from google.adk.a2a.converters.event_converter import convert_a2a_task_to_event
# Create mock task with no message
mock_task = Mock(spec=Task)
mock_task.artifacts = None
mock_task.status = None
mock_task.history = []
result = convert_a2a_task_to_event(
mock_task, "test-author", self.mock_invocation_context
)
# Verify minimal event was created with correct invocation_id
assert result.author == "test-author"
assert result.branch == "test-branch"
assert result.invocation_id == "test-invocation-id"
@patch("google.adk.a2a.converters.event_converter.platform_uuid.new_uuid")
def test_convert_a2a_task_to_event_default_author(self, mock_uuid):
"""Test converting A2A task with default author and no invocation context."""
from google.adk.a2a.converters.event_converter import convert_a2a_task_to_event
# Create mock task with no message
mock_task = Mock(spec=Task)
mock_task.artifacts = None
mock_task.status = None
mock_task.history = []
# Mock UUID generation
mock_uuid.return_value = "generated-uuid"
result = convert_a2a_task_to_event(mock_task)
# Verify default author was used and UUID was generated for invocation_id
assert result.author == "a2a agent"
assert result.branch is None
assert result.invocation_id == "generated-uuid"
def test_convert_a2a_task_to_event_none_task(self):
"""Test converting None task raises ValueError."""
from google.adk.a2a.converters.event_converter import convert_a2a_task_to_event
with pytest.raises(ValueError, match="A2A task cannot be None"):
convert_a2a_task_to_event(None)
def test_convert_a2a_task_to_event_message_conversion_error(self):
"""Test error handling when message conversion fails."""
from google.adk.a2a.converters.event_converter import convert_a2a_task_to_event
# Create mock message and task
mock_message = Mock(spec=Message, parts=[Mock()])
mock_status = Mock(message=mock_message)
mock_task = Mock(spec=Task, artifacts=None, status=mock_status, history=[])
# Mock the convert_a2a_message_to_event function to raise an exception
with patch(
"google.adk.a2a.converters.event_converter.convert_a2a_message_to_event"
) as mock_convert_message:
mock_convert_message.side_effect = Exception("Conversion failed")
with pytest.raises(RuntimeError, match="Failed to convert task message"):
convert_a2a_task_to_event(mock_task, "test-author")
def test_convert_a2a_message_to_event_success(self):
"""Test successful conversion of A2A message to event."""
from google.adk.a2a.converters.event_converter import convert_a2a_message_to_event
from google.genai import types as genai_types
# Create mock parts and message with valid genai Part
mock_a2a_part = Mock()
mock_genai_part = genai_types.Part(text="test content")
mock_convert_part = Mock(return_value=mock_genai_part)
mock_message = Mock(spec=Message, parts=[mock_a2a_part])
mock_message.role = Role.agent
result = convert_a2a_message_to_event(
mock_message,
"test-author",
self.mock_invocation_context,
mock_convert_part,
)
# Verify conversion was successful
assert result.author == "test-author"
assert result.branch == "test-branch"
assert result.invocation_id == "test-invocation-id"
assert result.content.role == "model"
assert len(result.content.parts) == 1
assert result.content.parts[0].text == "test content"
mock_convert_part.assert_called_once_with(mock_a2a_part)
def test_convert_a2a_message_to_event_with_multiple_parts_returned(self):
"""Test message to event conversion when part_converter returns multiple parts."""
from google.adk.a2a.converters.event_converter import convert_a2a_message_to_event
from google.genai import types as genai_types
# Arrange
mock_a2a_part = Mock()
mock_genai_part1 = genai_types.Part(text="part 1")
mock_genai_part2 = genai_types.Part(text="part 2")
mock_convert_part = Mock(return_value=[mock_genai_part1, mock_genai_part2])
mock_message = Mock(spec=Message, parts=[mock_a2a_part])
mock_message.role = Role.agent
# Act
result = convert_a2a_message_to_event(
mock_message,
"test-author",
self.mock_invocation_context,
mock_convert_part,
)
# Assert
assert result.content.role == "model"
assert len(result.content.parts) == 2
assert result.content.parts[0].text == "part 1"
assert result.content.parts[1].text == "part 2"
mock_convert_part.assert_called_once_with(mock_a2a_part)
def test_convert_a2a_message_to_event_with_long_running_tools(self):
"""Test conversion with long-running tools by mocking the entire flow."""
from google.adk.a2a.converters.event_converter import convert_a2a_message_to_event
# Create mock parts and message
mock_message = Mock(spec=Message, parts=[Mock()])
mock_message.role = Role.agent
# Mock the part conversion to return None to simulate long-running tool detection logic
mock_convert_part = Mock(return_value=None)
# Patch the long-running tool detection since the main logic is in the actual conversion
with patch(
"google.adk.a2a.converters.event_converter.logger"
) as mock_logger:
result = convert_a2a_message_to_event(
mock_message,
"test-author",
self.mock_invocation_context,
mock_convert_part,
)
# Verify basic conversion worked
assert result.author == "test-author"
assert result.invocation_id == "test-invocation-id"
assert result.content.role == "model"
# Parts will be empty since conversion returned None, but that's expected for this test
def test_convert_a2a_message_to_event_empty_parts(self):
"""Test conversion with empty parts list."""
from google.adk.a2a.converters.event_converter import convert_a2a_message_to_event
mock_message = Mock(spec=Message, parts=[])
mock_message.role = Role.agent
result = convert_a2a_message_to_event(
mock_message, "test-author", self.mock_invocation_context
)
# Verify event was created with empty parts
assert result.author == "test-author"
assert result.invocation_id == "test-invocation-id"
assert result.content.role == "model"
assert len(result.content.parts) == 0
def test_convert_a2a_message_to_event_none_message(self):
"""Test converting None message raises ValueError."""
from google.adk.a2a.converters.event_converter import convert_a2a_message_to_event
with pytest.raises(ValueError, match="A2A message cannot be None"):
convert_a2a_message_to_event(None)
def test_convert_a2a_message_to_event_part_conversion_fails(self):
"""Test handling when part conversion returns None."""
from google.adk.a2a.converters.event_converter import convert_a2a_message_to_event
# Setup mock to return None (conversion failure)
mock_a2a_part = Mock()
mock_convert_part = Mock(return_value=None)
mock_message = Mock(spec=Message, parts=[mock_a2a_part])
mock_message.role = Role.agent
result = convert_a2a_message_to_event(
mock_message,
"test-author",
self.mock_invocation_context,
mock_convert_part,
)
# Verify event was created but with no parts
assert result.author == "test-author"
assert result.invocation_id == "test-invocation-id"
assert result.content.role == "model"
assert len(result.content.parts) == 0
def test_convert_a2a_message_to_event_part_conversion_exception(self):
"""Test handling when part conversion raises exception."""
from google.adk.a2a.converters.event_converter import convert_a2a_message_to_event
from google.genai import types as genai_types
# Setup mock to raise exception
mock_a2a_part1 = Mock()
mock_a2a_part2 = Mock()
mock_genai_part = genai_types.Part(text="successful conversion")
mock_convert_part = Mock(
side_effect=[
Exception("Conversion failed"), # First part fails
mock_genai_part, # Second part succeeds
]
)
mock_message = Mock(spec=Message, parts=[mock_a2a_part1, mock_a2a_part2])
mock_message.role = Role.agent
result = convert_a2a_message_to_event(
mock_message,
"test-author",
self.mock_invocation_context,
mock_convert_part,
)
# Verify event was created with only the successfully converted part
assert result.author == "test-author"
assert result.invocation_id == "test-invocation-id"
assert result.content.role == "model"
assert len(result.content.parts) == 1
assert result.content.parts[0].text == "successful conversion"
def test_convert_a2a_message_to_event_missing_tool_id(self):
"""Test handling of message conversion when part conversion fails."""
from google.adk.a2a.converters.event_converter import convert_a2a_message_to_event
# Create mock parts and message
mock_message = Mock(spec=Message, parts=[Mock()])
mock_message.role = Role.agent
# Mock the part conversion to return None
mock_convert_part = Mock(return_value=None)
result = convert_a2a_message_to_event(
mock_message,
"test-author",
self.mock_invocation_context,
mock_convert_part,
)
# Verify basic conversion worked
assert result.author == "test-author"
assert result.invocation_id == "test-invocation-id"
assert result.content.role == "model"
# Parts will be empty since conversion returned None
assert len(result.content.parts) == 0
@patch("google.adk.a2a.converters.event_converter.platform_uuid.new_uuid")
def test_convert_a2a_message_to_event_default_author(self, mock_uuid):
"""Test conversion with default author and no invocation context."""
from google.adk.a2a.converters.event_converter import convert_a2a_message_to_event
mock_message = Mock(spec=Message, parts=[])
mock_message.role = Role.agent
# Mock UUID generation
mock_uuid.return_value = "generated-uuid"
result = convert_a2a_message_to_event(mock_message)
# Verify default author was used and UUID was generated for invocation_id
assert result.author == "a2a agent"
assert result.branch is None