-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathtest_remote_a2a_agent.py
More file actions
2435 lines (2032 loc) · 82.8 KB
/
test_remote_a2a_agent.py
File metadata and controls
2435 lines (2032 loc) · 82.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
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.
import json
from pathlib import Path
import tempfile
from unittest.mock import AsyncMock
from unittest.mock import create_autospec
from unittest.mock import MagicMock
from unittest.mock import Mock
from unittest.mock import patch
from a2a.client.client import ClientConfig
from a2a.client.client import Consumer
from a2a.client.client_factory import ClientFactory
from a2a.client.middleware import ClientCallContext
from a2a.types import AgentCapabilities
from a2a.types import AgentCard
from a2a.types import AgentSkill
from a2a.types import Artifact
from a2a.types import Message as A2AMessage
from a2a.types import SendMessageSuccessResponse
from a2a.types import Task as A2ATask
from a2a.types import TaskArtifactUpdateEvent
from a2a.types import TaskState
from a2a.types import TaskStatus as A2ATaskStatus
from a2a.types import TaskStatusUpdateEvent
from a2a.types import TextPart
from google.adk.agents.invocation_context import InvocationContext
from google.adk.agents.remote_a2a_agent import A2A_METADATA_PREFIX
from google.adk.agents.remote_a2a_agent import AgentCardResolutionError
from google.adk.agents.remote_a2a_agent import RemoteA2aAgent
import google.adk.agents.remote_a2a_agent as remote_a2a_agent
from google.adk.events.event import Event
from google.adk.sessions.session import Session
from google.genai import types as genai_types
import httpx
import pytest
# Helper function to create a proper AgentCard for testing
def create_test_agent_card(
name: str = "test-agent",
url: str = "https://example.com/rpc",
description: str = "Test agent",
) -> AgentCard:
"""Create a test AgentCard with all required fields."""
return AgentCard(
name=name,
url=url,
description=description,
version="1.0",
capabilities=AgentCapabilities(),
default_input_modes=["text/plain"],
default_output_modes=["application/json"],
skills=[
AgentSkill(
id="test-skill",
name="Test Skill",
description="A test skill",
tags=["test"],
)
],
)
class TestRemoteA2aAgentInit:
"""Test RemoteA2aAgent initialization and validation."""
def test_init_with_agent_card_object(self):
"""Test initialization with AgentCard object."""
agent_card = create_test_agent_card()
agent = RemoteA2aAgent(
name="test_agent", agent_card=agent_card, description="Test description"
)
assert agent.name == "test_agent"
assert agent.description == "Test description"
assert agent._agent_card == agent_card
assert agent._agent_card_source is None
assert agent._httpx_client_needs_cleanup is True
assert agent._is_resolved is False
def test_init_with_url_string(self):
"""Test initialization with URL string."""
agent = RemoteA2aAgent(
name="test_agent", agent_card="https://example.com/agent.json"
)
assert agent.name == "test_agent"
assert agent._agent_card is None
assert agent._agent_card_source == "https://example.com/agent.json"
def test_init_with_file_path(self):
"""Test initialization with file path."""
agent = RemoteA2aAgent(name="test_agent", agent_card="/path/to/agent.json")
assert agent.name == "test_agent"
assert agent._agent_card is None
assert agent._agent_card_source == "/path/to/agent.json"
def test_init_with_shared_httpx_client(self):
"""Test initialization with shared httpx client."""
httpx_client = httpx.AsyncClient()
agent = RemoteA2aAgent(
name="test_agent",
agent_card="https://example.com/agent.json",
httpx_client=httpx_client,
)
assert agent._httpx_client is not None
assert agent._httpx_client_needs_cleanup is False
def test_init_with_factory(self):
"""Test initialization with shared httpx client."""
httpx_client = httpx.AsyncClient()
agent = RemoteA2aAgent(
name="test_agent",
agent_card="https://example.com/agent.json",
httpx_client=httpx_client,
)
assert agent._httpx_client == httpx_client
assert agent._httpx_client_needs_cleanup is False
def test_init_with_none_agent_card(self):
"""Test initialization with None agent card raises ValueError."""
with pytest.raises(ValueError, match="agent_card cannot be None"):
RemoteA2aAgent(name="test_agent", agent_card=None)
def test_init_with_empty_string_agent_card(self):
"""Test initialization with empty string agent card raises ValueError."""
with pytest.raises(ValueError, match="agent_card string cannot be empty"):
RemoteA2aAgent(name="test_agent", agent_card=" ")
def test_init_with_invalid_type_agent_card(self):
"""Test initialization with invalid type agent card raises TypeError."""
with pytest.raises(TypeError, match="agent_card must be AgentCard"):
RemoteA2aAgent(name="test_agent", agent_card=123)
def test_init_with_custom_timeout(self):
"""Test initialization with custom timeout."""
agent = RemoteA2aAgent(
name="test_agent",
agent_card="https://example.com/agent.json",
timeout=300.0,
)
assert agent._timeout == 300.0
class TestRemoteA2aAgentResolution:
"""Test agent card resolution functionality."""
def setup_method(self):
"""Setup test fixtures."""
self.agent_card_data = {
"name": "test-agent",
"url": "https://example.com/rpc",
"description": "Test agent",
"version": "1.0",
"capabilities": {},
"defaultInputModes": ["text/plain"],
"defaultOutputModes": ["application/json"],
"skills": [{
"id": "test-skill",
"name": "Test Skill",
"description": "A test skill",
"tags": ["test"],
}],
}
self.agent_card = create_test_agent_card()
@pytest.mark.asyncio
async def test_ensure_httpx_client_creates_new_client(self):
"""Test that _ensure_httpx_client creates new client when none exists."""
agent = RemoteA2aAgent(
name="test_agent", agent_card=create_test_agent_card()
)
client = await agent._ensure_httpx_client()
assert client is not None
assert agent._httpx_client == client
assert agent._httpx_client_needs_cleanup is True
@pytest.mark.asyncio
async def test_ensure_httpx_client_reuses_existing_client(self):
"""Test that _ensure_httpx_client reuses existing client."""
existing_client = httpx.AsyncClient()
agent = RemoteA2aAgent(
name="test_agent",
agent_card=create_test_agent_card(),
httpx_client=existing_client,
)
client = await agent._ensure_httpx_client()
assert client == existing_client
assert agent._httpx_client_needs_cleanup is False
@pytest.mark.asyncio
async def test_ensure_factory_reuses_existing_client(self):
"""Test that _ensure_httpx_client reuses existing client."""
existing_client = httpx.AsyncClient()
agent = RemoteA2aAgent(
name="test_agent",
agent_card=create_test_agent_card(),
a2a_client_factory=ClientFactory(
ClientConfig(httpx_client=existing_client),
),
)
client = await agent._ensure_httpx_client()
assert client == existing_client
assert agent._httpx_client_needs_cleanup is False
@pytest.mark.asyncio
async def test_ensure_httpx_client_updates_factory_with_new_client(self):
"""Test that _ensure_httpx_client updates factory with new client."""
agent = RemoteA2aAgent(
name="test_agent",
agent_card=create_test_agent_card(),
a2a_client_factory=ClientFactory(
ClientConfig(httpx_client=None),
),
)
assert agent._a2a_client_factory._config.httpx_client is None
client = await agent._ensure_httpx_client()
assert client is not None
assert agent._httpx_client == client
assert agent._httpx_client_needs_cleanup is True
assert agent._a2a_client_factory._config.httpx_client == client
@pytest.mark.asyncio
async def test_ensure_httpx_client_reregisters_transports_with_new_client(
self,
):
"""Test that _ensure_httpx_client registers transports with new client."""
factory = ClientFactory(
ClientConfig(httpx_client=None),
)
factory.register("transport_label", lambda: "test")
agent = RemoteA2aAgent(
name="test_agent",
agent_card=create_test_agent_card(),
a2a_client_factory=factory,
)
assert agent._a2a_client_factory._config.httpx_client is None
assert "transport_label" in agent._a2a_client_factory._registry
client = await agent._ensure_httpx_client()
assert client is not None
assert agent._httpx_client == client
assert agent._httpx_client_needs_cleanup is True
assert agent._a2a_client_factory._config.httpx_client == client
assert "transport_label" in agent._a2a_client_factory._registry
@pytest.mark.asyncio
async def test_resolve_agent_card_from_url_success(self):
"""Test successful agent card resolution from URL."""
agent = RemoteA2aAgent(
name="test_agent", agent_card="https://example.com/agent.json"
)
with patch.object(agent, "_ensure_httpx_client") as mock_ensure_client:
mock_client = AsyncMock()
mock_ensure_client.return_value = mock_client
with patch(
"google.adk.agents.remote_a2a_agent.A2ACardResolver"
) as mock_resolver_class:
mock_resolver = AsyncMock()
mock_resolver.get_agent_card.return_value = self.agent_card
mock_resolver_class.return_value = mock_resolver
result = await agent._resolve_agent_card_from_url(
"https://example.com/agent.json"
)
assert result == self.agent_card
mock_resolver_class.assert_called_once_with(
httpx_client=mock_client, base_url="https://example.com"
)
mock_resolver.get_agent_card.assert_called_once_with(
relative_card_path="/agent.json"
)
@pytest.mark.asyncio
async def test_resolve_agent_card_from_url_invalid_url(self):
"""Test agent card resolution from invalid URL raises error."""
agent = RemoteA2aAgent(name="test_agent", agent_card="invalid-url")
with pytest.raises(AgentCardResolutionError, match="Invalid URL format"):
await agent._resolve_agent_card_from_url("invalid-url")
@pytest.mark.asyncio
async def test_resolve_agent_card_from_file_success(self):
"""Test successful agent card resolution from file."""
agent = RemoteA2aAgent(name="test_agent", agent_card="/path/to/agent.json")
with tempfile.NamedTemporaryFile(
mode="w", suffix=".json", delete=False
) as f:
json.dump(self.agent_card_data, f)
temp_path = f.name
try:
result = await agent._resolve_agent_card_from_file(temp_path)
assert result.name == self.agent_card.name
assert result.url == self.agent_card.url
finally:
Path(temp_path).unlink()
@pytest.mark.asyncio
async def test_resolve_agent_card_from_file_not_found(self):
"""Test agent card resolution from nonexistent file raises error."""
agent = RemoteA2aAgent(
name="test_agent", agent_card="/path/to/nonexistent.json"
)
with pytest.raises(
AgentCardResolutionError, match="Agent card file not found"
):
await agent._resolve_agent_card_from_file("/path/to/nonexistent.json")
@pytest.mark.asyncio
async def test_resolve_agent_card_from_file_invalid_json(self):
"""Test agent card resolution from file with invalid JSON raises error."""
agent = RemoteA2aAgent(name="test_agent", agent_card="/path/to/agent.json")
with tempfile.NamedTemporaryFile(
mode="w", suffix=".json", delete=False
) as f:
f.write("invalid json")
temp_path = f.name
try:
with pytest.raises(AgentCardResolutionError, match="Invalid JSON"):
await agent._resolve_agent_card_from_file(temp_path)
finally:
Path(temp_path).unlink()
@pytest.mark.asyncio
async def test_validate_agent_card_success(self):
"""Test successful agent card validation."""
agent_card = create_test_agent_card()
agent = RemoteA2aAgent(name="test_agent", agent_card=agent_card)
# Should not raise any exception
await agent._validate_agent_card(agent_card)
@pytest.mark.asyncio
async def test_validate_agent_card_no_url(self):
"""Test agent card validation fails when no URL."""
agent = RemoteA2aAgent(
name="test_agent", agent_card=create_test_agent_card()
)
invalid_card = AgentCard(
name="test",
description="test",
version="1.0",
capabilities=AgentCapabilities(),
default_input_modes=["text/plain"],
default_output_modes=["application/json"],
skills=[
AgentSkill(
id="test-skill",
name="Test Skill",
description="A test skill",
tags=["test"],
)
],
url="", # Empty URL to trigger validation error
)
with pytest.raises(
AgentCardResolutionError, match="Agent card must have a valid URL"
):
await agent._validate_agent_card(invalid_card)
@pytest.mark.asyncio
async def test_validate_agent_card_invalid_url(self):
"""Test agent card validation fails with invalid URL."""
agent = RemoteA2aAgent(
name="test_agent", agent_card=create_test_agent_card()
)
invalid_card = AgentCard(
name="test",
url="invalid-url",
description="test",
version="1.0",
capabilities=AgentCapabilities(),
default_input_modes=["text/plain"],
default_output_modes=["application/json"],
skills=[
AgentSkill(
id="test-skill",
name="Test Skill",
description="A test skill",
tags=["test"],
)
],
)
with pytest.raises(AgentCardResolutionError, match="Invalid RPC URL"):
await agent._validate_agent_card(invalid_card)
@pytest.mark.asyncio
async def test_ensure_resolved_with_direct_agent_card(self):
"""Test _ensure_resolved with direct agent card."""
agent_card = create_test_agent_card()
agent = RemoteA2aAgent(name="test_agent", agent_card=agent_card)
with patch("httpx.AsyncClient") as mock_client_class:
mock_client = AsyncMock()
mock_client_class.return_value = mock_client
with patch(
"google.adk.agents.remote_a2a_agent.A2AClientFactory"
) as mock_factory_class:
mock_factory = Mock()
mock_a2a_client = Mock()
mock_factory.create.return_value = mock_a2a_client
mock_factory_class.return_value = mock_factory
await agent._ensure_resolved()
assert agent._is_resolved is True
assert agent._a2a_client == mock_a2a_client
@pytest.mark.asyncio
async def test_ensure_resolved_with_direct_agent_card_with_factory(self):
"""Test _ensure_resolved with direct agent card."""
agent_card = create_test_agent_card()
agent = RemoteA2aAgent(
name="test_agent",
agent_card=agent_card,
a2a_client_factory=ClientFactory(
ClientConfig(),
),
)
with patch("httpx.AsyncClient") as mock_client_class:
mock_client = AsyncMock()
mock_client_class.return_value = mock_client
with patch(
"google.adk.agents.remote_a2a_agent.A2AClientFactory"
) as mock_factory_class:
mock_a2a_client = Mock()
mock_factory = Mock()
mock_factory.create.return_value = mock_a2a_client
mock_factory_class.return_value = mock_factory
await agent._ensure_resolved()
assert agent._is_resolved is True
assert agent._a2a_client == mock_a2a_client
@pytest.mark.asyncio
async def test_ensure_resolved_with_url_source(self):
"""Test _ensure_resolved with URL source."""
agent = RemoteA2aAgent(
name="test_agent", agent_card="https://example.com/agent.json"
)
agent_card = create_test_agent_card()
with patch.object(agent, "_resolve_agent_card") as mock_resolve:
mock_resolve.return_value = agent_card
with patch.object(agent, "_ensure_httpx_client") as mock_ensure_client:
mock_client = AsyncMock()
mock_ensure_client.return_value = mock_client
with patch(
"google.adk.agents.remote_a2a_agent.A2AClient"
) as mock_client_class:
mock_a2a_client = AsyncMock()
mock_client_class.return_value = mock_a2a_client
await agent._ensure_resolved()
assert agent._is_resolved is True
assert agent._agent_card == agent_card
assert agent.description == agent_card.description
@pytest.mark.asyncio
async def test_ensure_resolved_already_resolved(self):
"""Test _ensure_resolved when already resolved."""
agent_card = create_test_agent_card()
agent = RemoteA2aAgent(name="test_agent", agent_card=agent_card)
# Set up as already resolved
agent._is_resolved = True
agent._a2a_client = AsyncMock()
with patch.object(agent, "_resolve_agent_card") as mock_resolve:
await agent._ensure_resolved()
# Should not call resolution again
mock_resolve.assert_not_called()
class TestRemoteA2aAgentMessageHandling:
"""Test message handling functionality."""
def setup_method(self):
"""Setup test fixtures."""
self.agent_card = create_test_agent_card()
self.mock_genai_part_converter = Mock()
self.mock_a2a_part_converter = Mock()
self.agent = RemoteA2aAgent(
name="test_agent",
agent_card=self.agent_card,
genai_part_converter=self.mock_genai_part_converter,
a2a_part_converter=self.mock_a2a_part_converter,
)
# Mock session and context
self.mock_session = Mock(spec=Session)
self.mock_session.id = "session-123"
self.mock_session.events = []
self.mock_context = Mock(spec=InvocationContext)
self.mock_context.session = self.mock_session
self.mock_context.invocation_id = "invocation-123"
self.mock_context.branch = "main"
def test_create_a2a_request_for_user_function_response_no_function_call(self):
"""Test function response request creation when no function call exists."""
with patch(
"google.adk.agents.remote_a2a_agent.find_matching_function_call"
) as mock_find:
mock_find.return_value = None
result = self.agent._create_a2a_request_for_user_function_response(
self.mock_context
)
assert result is None
def test_create_a2a_request_for_user_function_response_success(self):
"""Test successful function response request creation."""
# Mock function call event
mock_function_event = Mock()
mock_function_event.custom_metadata = {
A2A_METADATA_PREFIX + "task_id": "task-123"
}
# Mock latest event with function response - set proper author
mock_latest_event = Mock()
mock_latest_event.author = "user"
self.mock_session.events = [mock_latest_event]
with patch(
"google.adk.agents.remote_a2a_agent.find_matching_function_call"
) as mock_find:
mock_find.return_value = mock_function_event
with patch(
"google.adk.agents.remote_a2a_agent.convert_event_to_a2a_message"
) as mock_convert:
# Create a proper mock A2A message
mock_a2a_message = create_autospec(A2AMessage, instance=True)
mock_a2a_message.task_id = None # Will be set by the method
mock_convert.return_value = mock_a2a_message
result = self.agent._create_a2a_request_for_user_function_response(
self.mock_context
)
assert result is not None
assert result == mock_a2a_message
assert mock_a2a_message.task_id == "task-123"
def test_construct_message_parts_from_session_success(self):
"""Test successful message parts construction from session."""
# Mock event with text content
mock_part = Mock()
mock_part.text = "Hello world"
mock_content = Mock()
mock_content.parts = [mock_part]
mock_event = Mock()
mock_event.content = mock_content
self.mock_session.events = [mock_event]
with patch(
"google.adk.agents.remote_a2a_agent._present_other_agent_message"
) as mock_convert:
mock_convert.return_value = mock_event
mock_a2a_part = Mock()
self.mock_genai_part_converter.return_value = mock_a2a_part
parts, context_id = self.agent._construct_message_parts_from_session(
self.mock_context
)
assert len(parts) == 1
assert parts[0] == mock_a2a_part
assert context_id is None
def test_construct_message_parts_from_session_success_multiple_parts(self):
"""Test successful message parts construction from session."""
# Mock event with text content
mock_part = Mock()
mock_part.text = "Hello world"
mock_content = Mock()
mock_content.parts = [mock_part]
mock_event = Mock()
mock_event.content = mock_content
self.mock_session.events = [mock_event]
with patch(
"google.adk.agents.remote_a2a_agent._present_other_agent_message"
) as mock_convert:
mock_convert.return_value = mock_event
mock_a2a_part1 = Mock()
mock_a2a_part2 = Mock()
self.mock_genai_part_converter.return_value = [
mock_a2a_part1,
mock_a2a_part2,
]
parts, context_id = self.agent._construct_message_parts_from_session(
self.mock_context
)
assert parts == [mock_a2a_part1, mock_a2a_part2]
assert context_id is None
def test_construct_message_parts_from_session_empty_events(self):
"""Test message parts construction with empty events."""
self.mock_session.events = []
parts, context_id = self.agent._construct_message_parts_from_session(
self.mock_context
)
assert parts == []
assert context_id is None
def test_construct_message_parts_from_session_stops_on_agent_reply(self):
"""Test message parts construction stops on agent reply by default."""
part1 = Mock()
part1.text = "User 1"
content1 = Mock()
content1.parts = [part1]
user1 = Mock()
user1.content = content1
user1.author = "user"
user1.custom_metadata = None
part2 = Mock()
part2.text = "Agent 1"
content2 = Mock()
content2.parts = [part2]
agent1 = Mock()
agent1.content = content2
agent1.author = self.agent.name
agent1.custom_metadata = {
A2A_METADATA_PREFIX + "response": True,
}
agent2 = Mock()
agent2.content = None
agent2.author = self.agent.name
# Just actions, no content. Not marked as a response.
agent2.actions = Mock()
agent2.custom_metadata = None
part3 = Mock()
part3.text = "User 2"
content3 = Mock()
content3.parts = [part3]
user2 = Mock()
user2.content = content3
user2.author = "user"
user2.custom_metadata = None
self.mock_session.events = [user1, agent1, user2, agent2]
def mock_converter(part):
mock_a2a_part = Mock()
mock_a2a_part.text = part.text
return mock_a2a_part
self.mock_genai_part_converter.side_effect = mock_converter
with patch(
"google.adk.agents.remote_a2a_agent._present_other_agent_message"
) as mock_present:
mock_present.side_effect = lambda event: event
parts, context_id = self.agent._construct_message_parts_from_session(
self.mock_context
)
assert len(parts) == 1
assert parts[0].text == "User 2"
assert context_id is None
def test_construct_message_parts_from_session_stateless_full_history(self):
"""Test full history for stateless agent when enabled."""
self.agent._full_history_when_stateless = True
part1 = Mock()
part1.text = "User 1"
content1 = Mock()
content1.parts = [part1]
user1 = Mock()
user1.content = content1
user1.author = "user"
user1.custom_metadata = None
part2 = Mock()
part2.text = "Agent 1"
content2 = Mock()
content2.parts = [part2]
agent1 = Mock()
agent1.content = content2
agent1.author = self.agent.name
agent1.custom_metadata = None
part3 = Mock()
part3.text = "User 2"
content3 = Mock()
content3.parts = [part3]
user2 = Mock()
user2.content = content3
user2.author = "user"
user2.custom_metadata = None
self.mock_session.events = [user1, agent1, user2]
def mock_converter(part):
mock_a2a_part = Mock()
mock_a2a_part.text = part.text
return mock_a2a_part
self.mock_genai_part_converter.side_effect = mock_converter
with patch(
"google.adk.agents.remote_a2a_agent._present_other_agent_message"
) as mock_present:
mock_present.side_effect = lambda event: event
parts, context_id = self.agent._construct_message_parts_from_session(
self.mock_context
)
assert len(parts) == 3
assert parts[0].text == "User 1"
assert parts[1].text == "Agent 1"
assert parts[2].text == "User 2"
assert context_id is None
def test_construct_message_parts_from_session_stateful_partial_history(self):
"""Test partial history for stateful agent when full history is enabled."""
self.agent._full_history_when_stateless = True
part1 = Mock()
part1.text = "User 1"
content1 = Mock()
content1.parts = [part1]
user1 = Mock()
user1.content = content1
user1.author = "user"
user1.custom_metadata = None
part2 = Mock()
part2.text = "Agent 1"
content2 = Mock()
content2.parts = [part2]
agent1 = Mock()
agent1.content = content2
agent1.author = self.agent.name
agent1.custom_metadata = {
A2A_METADATA_PREFIX + "response": True,
A2A_METADATA_PREFIX + "context_id": "ctx-1",
}
part3 = Mock()
part3.text = "User 2"
content3 = Mock()
content3.parts = [part3]
user2 = Mock()
user2.content = content3
user2.author = "user"
user2.custom_metadata = None
self.mock_session.events = [user1, agent1, user2]
def mock_converter(part):
mock_a2a_part = Mock()
mock_a2a_part.text = part.text
return mock_a2a_part
self.mock_genai_part_converter.side_effect = mock_converter
with patch(
"google.adk.agents.remote_a2a_agent._present_other_agent_message"
) as mock_present:
mock_present.side_effect = lambda event: event
parts, context_id = self.agent._construct_message_parts_from_session(
self.mock_context
)
assert len(parts) == 1
assert parts[0].text == "User 2"
assert context_id == "ctx-1"
@pytest.mark.asyncio
async def test_handle_a2a_response_success_with_message(self):
"""Test successful A2A response handling with message."""
mock_a2a_message = Mock(spec=A2AMessage)
mock_a2a_message.context_id = "context-123"
# Create a proper Event mock that can handle custom_metadata
mock_event = Event(
author=self.agent.name,
invocation_id=self.mock_context.invocation_id,
branch=self.mock_context.branch,
)
with patch(
"google.adk.agents.remote_a2a_agent.convert_a2a_message_to_event"
) as mock_convert:
mock_convert.return_value = mock_event
result = await self.agent._handle_a2a_response(
mock_a2a_message, self.mock_context
)
assert result == mock_event
mock_convert.assert_called_once_with(
mock_a2a_message,
self.agent.name,
self.mock_context,
self.mock_a2a_part_converter,
)
# Check that metadata was added
assert result.custom_metadata is not None
assert A2A_METADATA_PREFIX + "context_id" in result.custom_metadata
@pytest.mark.asyncio
async def test_handle_a2a_response_with_task_completed_and_no_update(self):
"""Test successful A2A response handling with non-streaming task and no update."""
mock_a2a_task = Mock(spec=A2ATask)
mock_a2a_task.id = "task-123"
mock_a2a_task.context_id = "context-123"
mock_a2a_task.status = Mock(spec=A2ATaskStatus)
mock_a2a_task.status.state = TaskState.completed
# Create a proper Event mock that can handle custom_metadata
mock_a2a_part = Mock(spec=TextPart)
mock_event = Event(
author=self.agent.name,
invocation_id=self.mock_context.invocation_id,
branch=self.mock_context.branch,
content=genai_types.Content(role="model", parts=[mock_a2a_part]),
)
with patch.object(
remote_a2a_agent,
"convert_a2a_task_to_event",
autospec=True,
) as mock_convert:
mock_convert.return_value = mock_event
result = await self.agent._handle_a2a_response(
(mock_a2a_task, None), self.mock_context
)
assert result == mock_event
mock_convert.assert_called_once_with(
mock_a2a_task,
self.agent.name,
self.mock_context,
self.mock_a2a_part_converter,
)
# Check the parts are not updated as Thought
assert result.content.parts[0].thought is None
# Check that metadata was added
assert result.custom_metadata is not None
assert A2A_METADATA_PREFIX + "task_id" in result.custom_metadata
assert A2A_METADATA_PREFIX + "context_id" in result.custom_metadata
def test_construct_message_parts_from_session_preserves_order(self):
"""Test that message parts are in correct order with multi-part messages.
This test verifies the fix for the bug where _present_other_agent_message
creates multi-part messages with "For context:" prefix, and ensures the
parts are in the correct chronological order (not reversed).
"""
# Create mock events with multiple parts
# Event 1: User message
user_part = Mock()
user_part.text = "User question"
user_content = Mock()
user_content.parts = [user_part]
user_event = Mock()
user_event.content = user_content
user_event.author = "user"
# Event 2: Other agent message (will be transformed by
# _present_other_agent_message)
other_agent_part1 = Mock()
other_agent_part1.text = "For context:"
other_agent_part2 = Mock()
other_agent_part2.text = "[other_agent] said: Response text"
other_agent_content = Mock()
other_agent_content.parts = [other_agent_part1, other_agent_part2]
other_agent_event = Mock()
other_agent_event.content = other_agent_content
other_agent_event.author = "other_agent"
self.mock_session.events = [user_event, other_agent_event]
with patch(
"google.adk.agents.remote_a2a_agent._present_other_agent_message"
) as mock_present:
# Mock _present_other_agent_message to return the transformed event
mock_present.return_value = other_agent_event
# Mock the converter to track the order of parts
converted_parts = []
def mock_converter(part):
mock_a2a_part = Mock()
mock_a2a_part.original_text = part.text
converted_parts.append(mock_a2a_part)
return mock_a2a_part
self.mock_genai_part_converter.side_effect = mock_converter
parts, context_id = self.agent._construct_message_parts_from_session(
self.mock_context
)
# Verify the parts are in correct order
assert len(parts) == 3 # 1 user part + 2 other agent parts
assert context_id is None
# Verify order: user part, then "For context:", then agent message
assert converted_parts[0].original_text == "User question"
assert converted_parts[1].original_text == "For context:"
assert (
converted_parts[2].original_text
== "[other_agent] said: Response text"
)
@pytest.mark.asyncio
async def test_handle_a2a_response_with_task_submitted_and_no_update(self):
"""Test successful A2A response handling with streaming task and no update."""
mock_a2a_task = Mock(spec=A2ATask)
mock_a2a_task.id = "task-123"
mock_a2a_task.context_id = "context-123"
mock_a2a_task.status = Mock(spec=A2ATaskStatus)
mock_a2a_task.status.state = TaskState.submitted
# Create a proper Event mock that can handle custom_metadata
mock_a2a_part = Mock(spec=TextPart)
mock_event = Event(
author=self.agent.name,
invocation_id=self.mock_context.invocation_id,
branch=self.mock_context.branch,
content=genai_types.Content(role="model", parts=[mock_a2a_part]),
)
with patch.object(
remote_a2a_agent,
"convert_a2a_task_to_event",
autospec=True,
) as mock_convert:
mock_convert.return_value = mock_event
result = await self.agent._handle_a2a_response(
(mock_a2a_task, None), self.mock_context
)