|
| 1 | +# Copyright 2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Tests for ContextVar error handling during cancellation.""" |
| 16 | + |
| 17 | +import asyncio |
| 18 | +import logging |
| 19 | +from typing import AsyncGenerator |
| 20 | +from unittest import mock |
| 21 | + |
| 22 | +from google.adk.agents.base_agent import BaseAgent |
| 23 | +from google.adk.agents.invocation_context import InvocationContext |
| 24 | +from google.adk.events.event import Event |
| 25 | +from google.adk.sessions.in_memory_session_service import InMemorySessionService |
| 26 | +from google.adk.telemetry.tracing import tracer |
| 27 | +from google.genai import types |
| 28 | +import pytest |
| 29 | +from typing_extensions import override |
| 30 | + |
| 31 | + |
| 32 | +class MinimalAgent(BaseAgent): |
| 33 | + |
| 34 | + @override |
| 35 | + async def _run_async_impl( |
| 36 | + self, ctx: InvocationContext |
| 37 | + ) -> AsyncGenerator[Event, None]: |
| 38 | + yield Event( |
| 39 | + author=self.name, |
| 40 | + content=types.Content(parts=[types.Part(text='Hello')]), |
| 41 | + ) |
| 42 | + |
| 43 | + |
| 44 | +class FailingCM: |
| 45 | + |
| 46 | + def __enter__(self): |
| 47 | + return mock.Mock() |
| 48 | + |
| 49 | + def __exit__(self, exc_type, exc_val, exc_tb): |
| 50 | + raise ValueError('Mocked ContextVar error') |
| 51 | + |
| 52 | + |
| 53 | +@pytest.mark.asyncio |
| 54 | +async def test_run_async_handles_context_var_error( |
| 55 | + caplog: pytest.LogCaptureFixture, |
| 56 | +): |
| 57 | + agent = MinimalAgent(name='test_agent') |
| 58 | + |
| 59 | + with mock.patch.object( |
| 60 | + tracer, 'start_as_current_span', return_value=FailingCM() |
| 61 | + ): |
| 62 | + |
| 63 | + session_service = InMemorySessionService() |
| 64 | + session = await session_service.create_session( |
| 65 | + app_name='test', user_id='user' |
| 66 | + ) |
| 67 | + ctx = InvocationContext( |
| 68 | + invocation_id='inv_id', |
| 69 | + agent=agent, |
| 70 | + session=session, |
| 71 | + session_service=session_service, |
| 72 | + ) |
| 73 | + |
| 74 | + events = [] |
| 75 | + with caplog.at_level(logging.WARNING): |
| 76 | + async for event in agent.run_async(ctx): |
| 77 | + events.append(event) |
| 78 | + |
| 79 | + assert len(events) == 1 |
| 80 | + assert events[0].content.parts[0].text == 'Hello' |
| 81 | + |
| 82 | + assert any( |
| 83 | + 'Failed to detach context during generator cleanup' in record.message |
| 84 | + for record in caplog.records |
| 85 | + ) |
0 commit comments