The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
import os
from typing import Final
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from litellm.integrations.gcs_bucket.gcs_bucket import GCSBucketLogger
from litellm.integrations.gcs_bucket.gcs_bucket_base import GCSBucketBase
def test_ollama_payload_key_matches_returned_response_id() -> None:
from datetime import datetime
from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import convert_to_model_response_object
from litellm.proxy.spend_tracking.spend_tracking_utils import get_logging_payload
from litellm.types.utils import ModelResponse
logger: Final = object.__new__(GCSBucketLogger)
response: Final = convert_to_model_response_object(
response_object={
"id": "chatcmpl-0",
"system_fingerprint": "fp_ollama",
"choices": [{"index": 0, "message": {"role": "assistant", "content": "hi"}}],
},
model_response_object=ModelResponse(),
)
logged: Final = get_logging_payload(
kwargs={"call_type": "acompletion", "response_cost": 0.01},
response_obj=response,
start_time=datetime(2025, 1, 1),
end_time=datetime(2025, 1, 1),
)
object_name: Final = logger._get_object_name({}, {"error_str": None}, response)
assert response.id != "chatcmpl-0"
assert object_name.split("/", 1)[1] == response.id
assert logged["request_id"] == response.id
class TestGCSBucketBase:
def test_construct_request_headers_with_project_id(self, monkeypatch):
"""Test that construct_request_headers correctly uses project_id if passed from env"""
test_project_id = "test-project"
monkeypatch.setenv("GOOGLE_SECRET_MANAGER_PROJECT_ID", test_project_id)
try:
# Create handler
handler = GCSBucketBase(bucket_name="test-bucket")
# Mock the Vertex AI auth calls
mock_auth_header = "mock-auth-header"
mock_token = "mock-token"
with (
patch(
"litellm.vertex_chat_completion.ensure_access_token"
) as mock_ensure_token,
patch(
"litellm.vertex_chat_completion._get_token_and_url"
) as mock_get_token,
):
mock_ensure_token.return_value = (mock_auth_header, test_project_id)
mock_get_token.return_value = (mock_token, "mock-url")
# Call construct_request_headers
headers = handler.sync_construct_request_headers()
# Verify headers
assert headers == {
"Authorization": f"Bearer {mock_token}",
"Content-Type": "application/json",
}
# Verify _ensure_access_token was called with correct project_id
mock_ensure_token.assert_called_once_with(
credentials=None, # No service account in this test
project_id=test_project_id, # Should use project_id from env
custom_llm_provider="vertex_ai",
)
finally:
# Clean up environment variable
del os.environ["GOOGLE_SECRET_MANAGER_PROJECT_ID"]
def test_construct_request_headers_without_project_id(self):
"""Test that construct_request_headers works when no project_id is in env"""
# Ensure environment variable is not set
if "GOOGLE_SECRET_MANAGER_PROJECT_ID" in os.environ:
del os.environ["GOOGLE_SECRET_MANAGER_PROJECT_ID"]
# Create handler
handler = GCSBucketBase(bucket_name="test-bucket")
# Mock the Vertex AI auth calls
mock_auth_header = "mock-auth-header"
mock_token = "mock-token"
with (
patch(
"litellm.vertex_chat_completion.ensure_access_token"
) as mock_ensure_token,
patch(
"litellm.vertex_chat_completion._get_token_and_url"
) as mock_get_token,
):
mock_ensure_token.return_value = (mock_auth_header, None)
mock_get_token.return_value = (mock_token, "mock-url")
# Call construct_request_headers
headers = handler.sync_construct_request_headers()
# Verify headers
assert headers == {
"Authorization": f"Bearer {mock_token}",
"Content-Type": "application/json",
}
# Verify _ensure_access_token was called with project_id as None
mock_ensure_token.assert_called_once_with(
credentials=None, # No service account in this test
project_id=None, # Should be None when no env var is set
custom_llm_provider="vertex_ai",
)
@pytest.mark.asyncio
async def test_log_json_data_on_gcs_url_encodes_object_name(self):
handler = GCSBucketBase(bucket_name="test-bucket")
handler.async_httpx_client = AsyncMock()
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.json.return_value = {"name": "logs/object"}
handler.async_httpx_client.post.return_value = mock_response
await handler._log_json_data_on_gcs(
headers={"Authorization": "Bearer token"},
bucket_name="test-bucket",
object_name="logs/object?uploadType=media&name=evil",
logging_payload={"ok": True},
)
post_url = handler.async_httpx_client.post.call_args.kwargs["url"]
assert "name=logs%2Fobject%3FuploadType%3Dmedia%26name%3Devil" in post_url
assert "name=logs/object?" not in post_url
def test_gcs_log_id_is_only_used_as_sanitized_hint(self):
logger = GCSBucketLogger.__new__(GCSBucketLogger)
object_name = logger._get_object_name(
kwargs={
"litellm_params": {
"metadata": {"gcs_log_id": "../../target?uploadType=media"}
}
},
logging_payload={"id": "payload"},
response_obj={"id": "response-id"},
)
assert "/custom-" in object_name
assert object_name.endswith("-target_uploadType_media")
assert ".." not in object_name
assert "?" not in object_name
class TestGCSBucketLoggerBucketName:
@pytest.mark.asyncio
async def test_constructor_rejects_non_premium_user(self, monkeypatch):
monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", False)
with pytest.raises(ValueError, match="GCS Bucket logging is a premium feature"):
GCSBucketLogger(bucket_name="config-bucket")
@pytest.mark.asyncio
async def test_the_bucket_name_it_is_constructed_with_survives(self, monkeypatch):
"""Reading config.yaml out of a GCS bucket asks for that bucket, not the logging one (LIT-6982)."""
monkeypatch.setenv("GCS_BUCKET_NAME", "logging-bucket")
monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
assert GCSBucketLogger(bucket_name="config-bucket").BUCKET_NAME == "config-bucket"
@pytest.mark.asyncio
async def test_no_bucket_name_still_falls_back_to_the_environment(self, monkeypatch):
monkeypatch.setenv("GCS_BUCKET_NAME", "logging-bucket")
monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
assert GCSBucketLogger().BUCKET_NAME == "logging-bucket"
@pytest.mark.asyncio
async def test_async_logging_rejects_non_premium_user(self, monkeypatch):
monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", False)
logger = object.__new__(GCSBucketLogger)
with pytest.raises(ValueError, match="GCS Bucket logging is a premium feature"):
await logger.async_log_success_event({}, None, None, None)