Repository navigation
Expand file tree
/
Copy pathtest_callback_context.py
More file actions
407 lines (329 loc) · 14.1 KB
/
Copy pathtest_callback_context.py
File metadata and controls
407 lines (329 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# Copyright 2025 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.
"""Tests for the CallbackContext class."""
from unittest.mock import AsyncMock
from unittest.mock import MagicMock
from unittest.mock import Mock
from google.adk.agents.callback_context import CallbackContext
from google.adk.auth.auth_credential import AuthCredential
from google.adk.auth.auth_credential import AuthCredentialTypes
from google.adk.auth.auth_tool import AuthConfig
from google.adk.tools.tool_context import ToolContext
from google.genai.types import Part
import pytest
@pytest.fixture
def mock_invocation_context():
"""Create a mock invocation context for testing."""
mock_context = MagicMock()
mock_context.invocation_id = "test-invocation-id"
mock_context.agent.name = "test-agent-name"
mock_context.session.state = {"key1": "value1", "key2": "value2"}
mock_context.session.id = "test-session-id"
mock_context.app_name = "test-app"
mock_context.user_id = "test-user"
mock_context.artifact_service = None
mock_context.credential_service = None
return mock_context
@pytest.fixture
def mock_artifact_service():
"""Create a mock artifact service for testing."""
mock_service = AsyncMock()
mock_service.list_artifact_keys.return_value = [
"file1.txt",
"file2.txt",
"file3.txt",
]
return mock_service
@pytest.fixture
def callback_context_with_artifact_service(
mock_invocation_context, mock_artifact_service
):
"""Create a CallbackContext with a mock artifact service."""
mock_invocation_context.artifact_service = mock_artifact_service
return CallbackContext(mock_invocation_context)
@pytest.fixture
def callback_context_without_artifact_service(mock_invocation_context):
"""Create a CallbackContext without an artifact service."""
mock_invocation_context.artifact_service = None
return CallbackContext(mock_invocation_context)
@pytest.fixture
def mock_auth_config():
"""Create a mock auth config for testing."""
mock_config = Mock(spec=AuthConfig)
return mock_config
@pytest.fixture
def mock_auth_credential():
"""Create a mock auth credential for testing."""
mock_credential = Mock(spec=AuthCredential)
mock_credential.auth_type = AuthCredentialTypes.OAUTH2
return mock_credential
class TestCallbackContextListArtifacts:
"""Test the list_artifacts method in CallbackContext."""
@pytest.mark.asyncio
async def test_list_artifacts_returns_artifact_keys(
self, callback_context_with_artifact_service, mock_artifact_service
):
"""Test that list_artifacts returns the artifact keys from the service."""
result = await callback_context_with_artifact_service.list_artifacts()
assert result == ["file1.txt", "file2.txt", "file3.txt"]
mock_artifact_service.list_artifact_keys.assert_called_once_with(
app_name="test-app",
user_id="test-user",
session_id="test-session-id",
)
@pytest.mark.asyncio
async def test_list_artifacts_returns_empty_list(
self, callback_context_with_artifact_service, mock_artifact_service
):
"""Test that list_artifacts returns an empty list when no artifacts exist."""
mock_artifact_service.list_artifact_keys.return_value = []
result = await callback_context_with_artifact_service.list_artifacts()
assert result == []
mock_artifact_service.list_artifact_keys.assert_called_once_with(
app_name="test-app",
user_id="test-user",
session_id="test-session-id",
)
@pytest.mark.asyncio
async def test_list_artifacts_raises_value_error_when_service_is_none(
self, callback_context_without_artifact_service
):
"""Test that list_artifacts raises ValueError when artifact service is None."""
with pytest.raises(
ValueError, match="Artifact service is not initialized."
):
await callback_context_without_artifact_service.list_artifacts()
@pytest.mark.asyncio
async def test_list_artifacts_passes_through_service_exceptions(
self, callback_context_with_artifact_service, mock_artifact_service
):
"""Test that list_artifacts passes through exceptions from the artifact service."""
mock_artifact_service.list_artifact_keys.side_effect = Exception(
"Service error"
)
with pytest.raises(Exception, match="Service error"):
await callback_context_with_artifact_service.list_artifacts()
class TestCallbackContext:
"""Test suite for CallbackContext."""
@pytest.mark.asyncio
async def test_tool_context_inherits_list_artifacts(
self, mock_invocation_context, mock_artifact_service
):
"""Test that ToolContext inherits the list_artifacts method from CallbackContext."""
mock_invocation_context.artifact_service = mock_artifact_service
tool_context = ToolContext(mock_invocation_context)
result = await tool_context.list_artifacts()
assert result == ["file1.txt", "file2.txt", "file3.txt"]
mock_artifact_service.list_artifact_keys.assert_called_once_with(
app_name="test-app",
user_id="test-user",
session_id="test-session-id",
)
@pytest.mark.asyncio
async def test_tool_context_list_artifacts_raises_value_error_when_service_is_none(
self, mock_invocation_context
):
"""Test that ToolContext's list_artifacts raises ValueError when artifact service is None."""
mock_invocation_context.artifact_service = None
tool_context = ToolContext(mock_invocation_context)
with pytest.raises(
ValueError, match="Artifact service is not initialized."
):
await tool_context.list_artifacts()
def test_tool_context_has_list_artifacts_method(self):
"""Test that ToolContext has the list_artifacts method available."""
assert hasattr(ToolContext, "list_artifacts")
assert callable(getattr(ToolContext, "list_artifacts"))
def test_callback_context_has_list_artifacts_method(self):
"""Test that CallbackContext has the list_artifacts method available."""
assert hasattr(CallbackContext, "list_artifacts")
assert callable(getattr(CallbackContext, "list_artifacts"))
def test_tool_context_shares_same_list_artifacts_method_with_callback_context(
self,
):
"""Test that ToolContext and CallbackContext share the same list_artifacts method."""
assert ToolContext.list_artifacts is CallbackContext.list_artifacts
def test_initialization(self, mock_invocation_context):
"""Test CallbackContext initialization."""
context = CallbackContext(mock_invocation_context)
assert context._invocation_context == mock_invocation_context
assert context._event_actions is not None
assert context._state is not None
@pytest.mark.asyncio
async def test_save_credential_with_service(
self, mock_invocation_context, mock_auth_config
):
"""Test save_credential when credential service is available."""
# Mock credential service
credential_service = AsyncMock()
mock_invocation_context.credential_service = credential_service
context = CallbackContext(mock_invocation_context)
await context.save_credential(mock_auth_config)
credential_service.save_credential.assert_called_once_with(
mock_auth_config, context
)
@pytest.mark.asyncio
async def test_save_credential_no_service(
self, mock_invocation_context, mock_auth_config
):
"""Test save_credential when credential service is not available."""
mock_invocation_context.credential_service = None
context = CallbackContext(mock_invocation_context)
with pytest.raises(
ValueError, match="Credential service is not initialized"
):
await context.save_credential(mock_auth_config)
@pytest.mark.asyncio
async def test_load_credential_with_service(
self, mock_invocation_context, mock_auth_config, mock_auth_credential
):
"""Test load_credential when credential service is available."""
# Mock credential service
credential_service = AsyncMock()
credential_service.load_credential.return_value = mock_auth_credential
mock_invocation_context.credential_service = credential_service
context = CallbackContext(mock_invocation_context)
result = await context.load_credential(mock_auth_config)
credential_service.load_credential.assert_called_once_with(
mock_auth_config, context
)
assert result == mock_auth_credential
@pytest.mark.asyncio
async def test_load_credential_no_service(
self, mock_invocation_context, mock_auth_config
):
"""Test load_credential when credential service is not available."""
mock_invocation_context.credential_service = None
context = CallbackContext(mock_invocation_context)
with pytest.raises(
ValueError, match="Credential service is not initialized"
):
await context.load_credential(mock_auth_config)
@pytest.mark.asyncio
async def test_load_credential_returns_none(
self, mock_invocation_context, mock_auth_config
):
"""Test load_credential returns None when credential not found."""
# Mock credential service
credential_service = AsyncMock()
credential_service.load_credential.return_value = None
mock_invocation_context.credential_service = credential_service
context = CallbackContext(mock_invocation_context)
result = await context.load_credential(mock_auth_config)
credential_service.load_credential.assert_called_once_with(
mock_auth_config, context
)
assert result is None
@pytest.mark.asyncio
async def test_save_artifact_integration(self, mock_invocation_context):
"""Test save_artifact to ensure credential methods follow same pattern."""
# Mock artifact service
artifact_service = AsyncMock()
artifact_service.save_artifact.return_value = 1
mock_invocation_context.artifact_service = artifact_service
context = CallbackContext(mock_invocation_context)
test_artifact = Part.from_text(text="test content")
version = await context.save_artifact("test_file.txt", test_artifact)
artifact_service.save_artifact.assert_called_once_with(
app_name="test-app",
user_id="test-user",
session_id="test-session-id",
filename="test_file.txt",
artifact=test_artifact,
custom_metadata=None,
)
assert version == 1
@pytest.mark.asyncio
async def test_load_artifact_integration(self, mock_invocation_context):
"""Test load_artifact to ensure credential methods follow same pattern."""
# Mock artifact service
artifact_service = AsyncMock()
test_artifact = Part.from_text(text="test content")
artifact_service.load_artifact.return_value = test_artifact
mock_invocation_context.artifact_service = artifact_service
context = CallbackContext(mock_invocation_context)
result = await context.load_artifact("test_file.txt")
artifact_service.load_artifact.assert_called_once_with(
app_name="test-app",
user_id="test-user",
session_id="test-session-id",
filename="test_file.txt",
version=None,
)
assert result == test_artifact
class TestCallbackContextAddSessionToMemory:
"""Test the add_session_to_memory method in CallbackContext."""
@pytest.mark.asyncio
async def test_add_session_to_memory_success(self, mock_invocation_context):
"""Test that add_session_to_memory calls the memory service correctly."""
memory_service = AsyncMock()
mock_invocation_context.memory_service = memory_service
context = CallbackContext(mock_invocation_context)
await context.add_session_to_memory()
memory_service.add_session_to_memory.assert_called_once_with(
mock_invocation_context.session
)
@pytest.mark.asyncio
async def test_add_session_to_memory_no_service_raises(
self, mock_invocation_context
):
"""Test that add_session_to_memory raises ValueError when memory service is None."""
mock_invocation_context.memory_service = None
context = CallbackContext(mock_invocation_context)
with pytest.raises(
ValueError,
match=(
r"Cannot add session to memory: memory service is not available\."
),
):
await context.add_session_to_memory()
@pytest.mark.asyncio
async def test_add_session_to_memory_passes_through_service_exceptions(
self, mock_invocation_context
):
"""Test that add_session_to_memory passes through exceptions from the memory service."""
memory_service = AsyncMock()
memory_service.add_session_to_memory.side_effect = Exception(
"Memory service error"
)
mock_invocation_context.memory_service = memory_service
context = CallbackContext(mock_invocation_context)
with pytest.raises(Exception, match="Memory service error"):
await context.add_session_to_memory()
class TestToolContextAddSessionToMemory:
"""Test the add_session_to_memory method in ToolContext."""
@pytest.mark.asyncio
async def test_add_session_to_memory_success(self, mock_invocation_context):
"""Test that ToolContext.add_session_to_memory calls the memory service correctly."""
memory_service = AsyncMock()
mock_invocation_context.memory_service = memory_service
tool_context = ToolContext(mock_invocation_context)
await tool_context.add_session_to_memory()
memory_service.add_session_to_memory.assert_called_once_with(
mock_invocation_context.session
)
@pytest.mark.asyncio
async def test_add_session_to_memory_no_service_raises(
self, mock_invocation_context
):
"""Test that ToolContext.add_session_to_memory raises ValueError when memory service is None."""
mock_invocation_context.memory_service = None
tool_context = ToolContext(mock_invocation_context)
with pytest.raises(
ValueError,
match=(
r"Cannot add session to memory: memory service is not available\."
),
):
await tool_context.add_session_to_memory()