chore: fix unit tests

PiperOrigin-RevId: 764107186
This commit is contained in:
Xiang (Sean) Zhou
2025-05-27 23:06:46 -07:00
committed by Copybara-Service
parent a66f12273c
commit d40df2edf2
3 changed files with 62 additions and 53 deletions

View File

@@ -14,10 +14,7 @@
import asyncio
import logging
import os
import sys
import time
import types as ptypes
from unittest.mock import MagicMock
from unittest.mock import patch
@@ -25,7 +22,6 @@ from fastapi.testclient import TestClient
from google.adk.agents.base_agent import BaseAgent
from google.adk.agents.run_config import RunConfig
from google.adk.cli.fast_api import get_fast_api_app
from google.adk.cli.utils import envs
from google.adk.events import Event
from google.adk.runners import Runner
from google.adk.sessions.base_session_service import ListSessionsResponse
@@ -48,22 +44,7 @@ class DummyAgent(BaseAgent):
self.sub_agents = []
# Set up dummy module and add to sys.modules
dummy_module = ptypes.ModuleType("test_agent")
dummy_module.agent = ptypes.SimpleNamespace(
root_agent=DummyAgent(name="dummy_agent")
)
sys.modules["test_app"] = dummy_module
# Try to load environment variables, with a fallback for testing
try:
envs.load_dotenv_for_agent("test_app", ".")
except Exception as e:
logger.warning(f"Could not load environment variables: {e}")
# Create a basic .env file if needed
if not os.path.exists(".env"):
with open(".env", "w") as f:
f.write("# Test environment variables\n")
root_agent = DummyAgent(name="dummy_agent")
# Create sample events that our mocked runner will return
@@ -150,6 +131,20 @@ def test_session_info():
}
@pytest.fixture
def mock_agent_loader():
class MockAgentLoader:
def __init__(self, agents_dir: str):
pass
def load_agent(self, app_name):
return root_agent
return MockAgentLoader(".")
@pytest.fixture
def mock_session_service():
"""Create a mock session service that uses an in-memory dictionary."""
@@ -287,24 +282,33 @@ def mock_memory_service():
@pytest.fixture
def test_app(mock_session_service, mock_artifact_service, mock_memory_service):
def test_app(
mock_session_service,
mock_artifact_service,
mock_memory_service,
mock_agent_loader,
):
"""Create a TestClient for the FastAPI app without starting a server."""
# Patch multiple services and signal handlers
with (
patch("signal.signal", return_value=None),
patch(
"google.adk.cli.fast_api.InMemorySessionService", # Changed this line
"google.adk.cli.fast_api.InMemorySessionService",
return_value=mock_session_service,
),
patch(
"google.adk.cli.fast_api.InMemoryArtifactService", # Make consistent
"google.adk.cli.fast_api.InMemoryArtifactService",
return_value=mock_artifact_service,
),
patch(
"google.adk.cli.fast_api.InMemoryMemoryService", # Make consistent
"google.adk.cli.fast_api.InMemoryMemoryService",
return_value=mock_memory_service,
),
patch(
"google.adk.cli.fast_api.AgentLoader",
return_value=mock_agent_loader,
),
):
# Get the FastAPI app, but don't actually run it
app = get_fast_api_app(