litellm/tests/llm_translation/interactions/test_google_interactions_integration.py
devin-ai-integration[bot] fa2c8984ba
test: move the unit half of 126 mixed legacy files into tests/unit (#45090)
* test: move the unit half of 126 mixed legacy files into tests/unit

* test: restore litellm globals that moved tests set

* test: finalize migration test cleanup

* test: restore original bodies of moved legacy tests

The move into tests/unit had rewritten 612 test bodies, and some of the rewrites dropped assertions. Each moved test now carries its original body from the legacy file, with only the imports, helpers, fake provider credentials and monkeypatched env it needs to run under tests/unit

test_timeout_streaming goes back to tests/local_testing because it needs the fake OpenAI endpoint server. The image payload fixture moves with its only user, and two tests that leaked global state (a registered model cost entry and queued logging tasks) are now isolated

* test: drop module imports shadowed by restored local imports

* test: assert on LiteLLM output in no-assertion moved tests and isolate leaks

Twenty no-assertion candidates get one assertion on the value LiteLLM returns, with the original lines unchanged. Four tests go back to their legacy files because they only check types or imports, write into the working directory, or cannot assert without a body change

Two moved tests leaked globals into later tests in the same worker, so monkeypatch fixtures now restore the retry-after header parser and the end user cost tracking flags

* test: drain queued logging tasks before the Phoenix span test

The moved Phoenix test counted spans from logging tasks that earlier tests had queued, so the drain fixture moves to tests/unit/conftest.py and both it and the Datadog batch test use it. test_factory_function goes back to its legacy file because its returned wrapper calls the real Assistants API and cannot be asserted on without a body change

---------

Co-authored-by: yuneng <yuneng@berri.ai>
2026-10-07 14:07:43 -07:00

253 lines
7.8 KiB
Python

"""
Integration tests for Google Interactions API.
Tests the litellm.interactions.create() and related methods against the Google AI Studio API.
Per OpenAPI spec: https://ai.google.dev/static/api/interactions.openapi.json
Run with: pytest tests/llm_translation/interactions/test_google_interactions_integration.py -v
"""
import asyncio
import os
import openai
import pytest
import litellm.interactions as interactions
# Test API key - should be set in environment
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
@pytest.fixture
def api_key():
"""Fixture to provide the API key."""
if not GEMINI_API_KEY:
pytest.skip("GEMINI_API_KEY not set")
return GEMINI_API_KEY
class TestGoogleInteractionsCreate:
"""Tests for creating interactions via litellm.interactions.create()."""
def test_create_simple_string_input(self, api_key):
"""Test creating an interaction with a simple string input."""
response = interactions.create(
model="gemini/gemini-2.5-flash",
input="Hello, what is 2 + 2?",
api_key=api_key,
)
print("SIMPLE RESPONSE: ", response)
assert response is not None
assert response.id is not None or response.status is not None
# Check outputs per OpenAPI spec
if response.outputs:
assert len(response.outputs) > 0
print(f"Response outputs: {response.outputs}")
# Check usage per OpenAPI spec
if response.usage:
print(f"Usage: {response.usage}")
def test_create_with_content_list(self, api_key):
"""Test creating an interaction with a structured content list (Content[] input)."""
response = interactions.create(
model="gemini/gemini-2.5-flash",
input=[{"type": "text", "text": "What is the capital of France?"}],
api_key=api_key,
)
assert response is not None
print(f"Response: {response}")
def test_create_with_system_instruction(self, api_key):
"""Test creating an interaction with system_instruction (per OpenAPI spec)."""
response = interactions.create(
model="gemini/gemini-2.5-flash",
input="What are you?",
system_instruction="You are a helpful pirate assistant. Always respond like a pirate.",
api_key=api_key,
)
assert response is not None
print(f"Response with system_instruction: {response}")
def test_create_with_tools(self, api_key):
"""Test creating an interaction with tools (per OpenAPI spec)."""
response = interactions.create(
model="gemini/gemini-2.5-flash",
input="What's the weather in Boston?",
tools=[
{
"type": "function",
"name": "get_weather",
"description": "Get the weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city name",
}
},
"required": ["location"],
},
}
],
api_key=api_key,
)
assert response is not None
# Check if status is requires_action (function call)
print(f"Response status: {response.status}")
print(f"Response outputs: {response.outputs}")
@pytest.mark.asyncio
async def test_acreate_simple(self, api_key):
"""Test async interaction creation."""
response = await interactions.acreate(
model="gemini/gemini-2.5-flash",
input="What is the speed of light?",
api_key=api_key,
)
assert response is not None
print(f"Async response: {response}")
class TestGoogleInteractionsStreaming:
"""Tests for streaming interactions."""
def test_create_streaming(self, api_key):
"""Test creating a streaming interaction."""
response_stream = interactions.create(
model="gemini/gemini-2.5-flash",
input="Count from 1 to 5 slowly.",
stream=True,
api_key=api_key,
)
# Collect all chunks
chunks = []
for chunk in response_stream:
chunks.append(chunk)
print(f"Streaming chunk: {chunk}")
assert len(chunks) > 0
print(f"Total chunks received: {len(chunks)}")
@pytest.mark.asyncio
async def test_acreate_streaming(self, api_key):
"""Test async streaming interaction."""
response_stream = await interactions.acreate(
model="gemini/gemini-2.5-flash",
input="Count from 1 to 3.",
stream=True,
api_key=api_key,
)
# Collect all chunks
chunks = []
async for chunk in response_stream:
chunks.append(chunk)
print(f"Async streaming chunk: {chunk}")
assert len(chunks) > 0
print(f"Total async chunks received: {len(chunks)}")
class TestGoogleInteractionsMultiTurn:
"""Tests for multi-turn conversations using Step[] input."""
class TestGoogleInteractionsAgent:
"""Tests for agent interactions (per OpenAPI spec)."""
class TestGoogleInteractionsGetDelete:
"""Tests for get and delete operations."""
class TestGoogleInteractionsErrorHandling:
"""Tests for error handling."""
def test_invalid_model(self, api_key):
"""Test error handling for invalid model."""
with pytest.raises(openai.APIError):
interactions.create(
model="gemini/invalid-model-name-xyz",
input="Hello",
api_key=api_key,
)
class TestGoogleInteractionsResponseStructure:
"""Tests to verify the response structure matches OpenAPI spec."""
def test_response_has_expected_fields(self, api_key):
"""Test that the response has fields per OpenAPI spec."""
response = interactions.create(
model="gemini/gemini-2.5-flash",
input="Hello",
api_key=api_key,
)
# Check fields per OpenAPI spec
assert hasattr(response, "id")
assert hasattr(response, "object")
assert hasattr(response, "status")
assert hasattr(response, "outputs")
assert hasattr(response, "usage")
assert hasattr(response, "model") or hasattr(response, "agent")
assert hasattr(response, "created")
assert hasattr(response, "updated")
print(
f"Response structure: id={response.id}, status={response.status}, object={response.object}"
)
if __name__ == "__main__":
# Run a quick smoke test
print("Running Google Interactions API smoke test...")
api_key = GEMINI_API_KEY
if not api_key:
print("GEMINI_API_KEY not set, skipping smoke test")
exit(1)
print("\n1. Testing basic interaction...")
response = interactions.create(
model="gemini/gemini-2.5-flash",
input="What is 2 + 2?",
api_key=api_key,
)
print(f"Response: {response}")
print("\n2. Testing streaming interaction...")
stream = interactions.create(
model="gemini/gemini-2.5-flash",
input="Count to 3.",
stream=True,
api_key=api_key,
)
print("Streaming response chunks:")
for chunk in stream:
print(f" {chunk}")
print("\n3. Testing async interaction...")
async def test_async():
response = await interactions.acreate(
model="gemini/gemini-2.5-flash",
input="Say hello!",
api_key=api_key,
)
return response
async_response = asyncio.run(test_async())
print(f"Async response: {async_response}")
print("\nSmoke test complete!")