mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-22 10:40:46 +00:00
test: annotate the new regression tests' locals with Final
This commit is contained in:
parent
f7f6d76e62
commit
6eb4d310fd
12 changed files with 34 additions and 26 deletions
|
|
@ -1,6 +1,7 @@
|
|||
"""Tests for litellm/a2a_protocol/utils.py token/usage extraction."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from typing import Final
|
||||
|
||||
import pytest
|
||||
|
||||
|
|
@ -45,9 +46,9 @@ def test_calculate_usage_counts_input_tokens_from_request_object():
|
|||
|
||||
|
||||
def test_calculate_usage_counts_input_tokens_from_a_message_that_forwards_its_fields():
|
||||
request = _request("count these input tokens please")
|
||||
forwarded_request = SimpleNamespace(params=SimpleNamespace(message=AttributeForwarder(request.params.message)))
|
||||
response_dict = {"result": {"kind": "message", "parts": [{"kind": "text", "text": "ok"}]}}
|
||||
request: Final = _request("count these input tokens please")
|
||||
forwarded_request: Final = SimpleNamespace(params=SimpleNamespace(message=AttributeForwarder(request.params.message)))
|
||||
response_dict: Final = {"result": {"kind": "message", "parts": [{"kind": "text", "text": "ok"}]}}
|
||||
|
||||
assert A2ARequestUtils.calculate_usage_from_request_response(
|
||||
request=forwarded_request, response_dict=response_dict
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import json
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
from typing import Final
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
|
@ -100,9 +101,9 @@ async def test_should_not_mutate_dict_container_response_when_recording_owner(
|
|||
|
||||
@pytest.mark.asyncio
|
||||
async def test_should_store_the_full_container_of_a_response_that_forwards_its_fields(monkeypatch):
|
||||
table = AsyncMock()
|
||||
table: Final = AsyncMock()
|
||||
table.find_unique.return_value = None
|
||||
prisma_client = SimpleNamespace(db=SimpleNamespace(litellm_managedobjecttable=table))
|
||||
prisma_client: Final = SimpleNamespace(db=SimpleNamespace(litellm_managedobjecttable=table))
|
||||
monkeypatch.setattr(ownership, "_get_prisma_client", AsyncMock(return_value=prisma_client))
|
||||
|
||||
await ownership.record_container_owner(
|
||||
|
|
@ -111,7 +112,7 @@ async def test_should_store_the_full_container_of_a_response_that_forwards_its_f
|
|||
custom_llm_provider="openai",
|
||||
)
|
||||
|
||||
file_obj = json.loads(table.create.await_args.kwargs["data"]["file_object"])
|
||||
file_obj: Final = json.loads(table.create.await_args.kwargs["data"]["file_object"])
|
||||
assert file_obj["status"] == "active"
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -454,14 +454,14 @@ async def test_async_pre_call_deployment_hook_prefers_top_level_model_info():
|
|||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_pre_call_deployment_hook_reads_model_info_that_forwards_its_fields():
|
||||
proxy_managed_files = PROXY_LiteLLMManagedFiles(DualCache(), prisma_client=MagicMock())
|
||||
kwargs = {
|
||||
proxy_managed_files: Final = PROXY_LiteLLMManagedFiles(DualCache(), prisma_client=MagicMock())
|
||||
kwargs: Final = {
|
||||
"input_file_id": "managed-file-abc",
|
||||
"model_file_id_mapping": {"managed-file-abc": {"deployment-xyz": "file-provider-123"}},
|
||||
"model_info": AttributeForwarder({"id": "deployment-xyz"}),
|
||||
}
|
||||
|
||||
result = await proxy_managed_files.async_pre_call_deployment_hook(kwargs=kwargs, call_type=CallTypes.acreate_batch)
|
||||
result: Final = await proxy_managed_files.async_pre_call_deployment_hook(kwargs=kwargs, call_type=CallTypes.acreate_batch)
|
||||
|
||||
assert result["input_file_id"] == "file-provider-123"
|
||||
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ from fastapi.testclient import TestClient
|
|||
|
||||
|
||||
|
||||
from typing import Final
|
||||
from unittest.mock import MagicMock, Mock, patch
|
||||
|
||||
import httpx
|
||||
|
|
@ -683,17 +684,17 @@ def test_prompt_initializer_accepts_params_without_dotprompt_content():
|
|||
from litellm.integrations.dotprompt import prompt_initializer
|
||||
from litellm.types.prompts.init_prompts import PromptLiteLLMParams, PromptSpec
|
||||
|
||||
litellm_params = SimpleNamespace(
|
||||
litellm_params: Final = SimpleNamespace(
|
||||
prompt_data={"content": "AHOY {{name}}", "metadata": {"model": "gpt-4o-mini"}},
|
||||
)
|
||||
prompt_spec = PromptSpec(
|
||||
prompt_spec: Final = PromptSpec(
|
||||
prompt_id="agent-prompt",
|
||||
litellm_params=PromptLiteLLMParams(prompt_integration="dotprompt"),
|
||||
)
|
||||
|
||||
dotprompt_manager = prompt_initializer(litellm_params, prompt_spec)
|
||||
dotprompt_manager: Final = prompt_initializer(litellm_params, prompt_spec)
|
||||
|
||||
template = dotprompt_manager.prompt_manager.get_prompt("agent-prompt")
|
||||
template: Final = dotprompt_manager.prompt_manager.get_prompt("agent-prompt")
|
||||
assert template is not None
|
||||
assert template.content == "AHOY {{name}}"
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import os
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from typing import Final
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
|
@ -496,11 +497,11 @@ class TestExtractAllMessagesTimestamps:
|
|||
def timestamp(self) -> float:
|
||||
return 1_000_000.0
|
||||
|
||||
kwargs = {**make_kwargs(messages=[{"role": "user", "content": "Hi"}]), "start_time": EpochSeconds()}
|
||||
kwargs: Final = {**make_kwargs(messages=[{"role": "user", "content": "Hi"}]), "start_time": EpochSeconds()}
|
||||
|
||||
messages = self.logger._extract_all_messages(kwargs, make_response(), response_model="gpt-4", vendor="openai")
|
||||
messages: Final = self.logger._extract_all_messages(kwargs, make_response(), response_model="gpt-4", vendor="openai")
|
||||
|
||||
input_msg = next(m for m in messages if not m.get("is_response"))
|
||||
input_msg: Final = next(m for m in messages if not m.get("is_response"))
|
||||
assert input_msg["timestamp"] == int(1_000_000.0 * 1000.0)
|
||||
|
||||
def test_output_messages_get_end_time_timestamp(self):
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import io
|
||||
import os
|
||||
import pathlib
|
||||
from typing import Final
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import httpx
|
||||
|
|
@ -608,7 +609,7 @@ def test_transform_response_wraps_malformed_words_with_the_raw_body(words: objec
|
|||
],
|
||||
)
|
||||
def test_transform_response_wraps_the_error_of_the_failing_lookup_in_a_malformed_body(payload: object, error: str):
|
||||
raw_response = httpx.Response(200, json=payload)
|
||||
raw_response: Final = httpx.Response(200, json=payload)
|
||||
|
||||
with pytest.raises(ValueError, match="Error transforming Deepgram response: ") as exc_info:
|
||||
DeepgramAudioTranscriptionConfig().transform_audio_transcription_response(raw_response)
|
||||
|
|
|
|||
|
|
@ -1786,7 +1786,7 @@ class TestOpenAIResponsesHandlerStreamingOutputProcessing:
|
|||
|
||||
@pytest.mark.asyncio
|
||||
async def test_deliver_ended_stream_rewrites_syncs_events_that_forward_their_fields(self):
|
||||
handler = OpenAIResponsesHandler()
|
||||
handler: Final = OpenAIResponsesHandler()
|
||||
plain_events: Final = self._ended_stream_events()
|
||||
forwarded_delta: Final = AttributeForwarder(plain_events[0])
|
||||
events: Final = [forwarded_delta, *plain_events[1:]]
|
||||
|
|
|
|||
|
|
@ -5,6 +5,8 @@ check vs POST migrate, dry-run param) and its residual-state messaging without a
|
|||
live proxy.
|
||||
"""
|
||||
|
||||
from typing import Final
|
||||
|
||||
import pytest
|
||||
from click.testing import CliRunner
|
||||
|
||||
|
|
@ -74,7 +76,7 @@ def test_migrate_reports_residual_legacy(runner):
|
|||
@pytest.mark.parametrize("residual", [-1, float("nan")])
|
||||
def test_migrate_prints_no_residual_status_for_a_residual_below_zero_or_nan(runner, residual):
|
||||
_FakeHTTPClient.response = {"status": "success", "report": {"residual_legacy": residual}}
|
||||
result = runner.invoke(cli_main.cli, ["encryption", "migrate", "--check"])
|
||||
result: Final = runner.invoke(cli_main.cli, ["encryption", "migrate", "--check"])
|
||||
assert result.exit_code == 0, result.output
|
||||
assert "No legacy values remaining" not in result.output
|
||||
assert "Residual legacy values remaining" not in result.output
|
||||
|
|
|
|||
|
|
@ -4266,7 +4266,7 @@ class TestCreatorTurnedOffMessageLogging:
|
|||
import litellm
|
||||
|
||||
monkeypatch.setattr(litellm, "turn_off_message_logging", False)
|
||||
instance = self._instance()
|
||||
instance: Final = self._instance()
|
||||
|
||||
assert await instance._creator_turned_off_message_logging(SimpleNamespace(id="job-1")) is False
|
||||
|
||||
|
|
|
|||
|
|
@ -1240,7 +1240,7 @@ class TestFailClosed:
|
|||
class TestStreamingRehydration:
|
||||
@pytest.mark.asyncio
|
||||
async def test_held_text_behind_a_chunk_that_cannot_be_copied_fails_closed(self):
|
||||
guardrail = _guardrail(event_hook="post_call")
|
||||
guardrail: Final = _guardrail(event_hook="post_call")
|
||||
_mock_post(guardrail, {"text": "", "carry": "[EMAIL"}, {"text": "a@b.com", "carry": ""})
|
||||
|
||||
async def stream():
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
from typing import Final
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
|
@ -154,11 +155,11 @@ async def test_upload_with_target_model_names_and_hook_stores_unified_id(monkeyp
|
|||
|
||||
@pytest.mark.asyncio
|
||||
async def test_upload_stores_the_unified_id_through_a_hook_that_forwards_its_writer(monkeypatch):
|
||||
backend = _RecordingStorageBackend()
|
||||
backend: Final = _RecordingStorageBackend()
|
||||
monkeypatch.setattr(storage_backend_service, "get_storage_backend", lambda name, prisma_client=None: backend)
|
||||
writer = _FakeManagedFilesHook()
|
||||
writer: Final = _FakeManagedFilesHook()
|
||||
|
||||
file_object = await StorageBackendFileService.upload_file_to_storage_backend(
|
||||
file_object: Final = await StorageBackendFileService.upload_file_to_storage_backend(
|
||||
file_data=_file_data(),
|
||||
target_storage="azure_storage",
|
||||
target_model_names=["gpt-x"],
|
||||
|
|
|
|||
|
|
@ -212,9 +212,9 @@ def test_inject_websocket_stubs_into_openapi_schema_adds_stub():
|
|||
|
||||
def test_inject_websocket_stubs_into_openapi_schema_documents_query_params_that_forward_their_fields():
|
||||
query_param: Final = AttributeForwarder(SimpleNamespace(name="session_id", required=True))
|
||||
route = SimpleNamespace(path="/ws/chat", name="ws_chat", dependant=SimpleNamespace(query_params=[query_param]))
|
||||
route: Final = SimpleNamespace(path="/ws/chat", name="ws_chat", dependant=SimpleNamespace(query_params=[query_param]))
|
||||
|
||||
result = _inject_websocket_stubs_into_openapi_schema({"paths": {}}, [route])
|
||||
result: Final = _inject_websocket_stubs_into_openapi_schema({"paths": {}}, [route])
|
||||
|
||||
assert result["paths"]["/ws/chat"]["get"]["parameters"] == [
|
||||
{"name": "session_id", "in": "query", "required": True, "schema": {"type": "string"}}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue