mirror of
https://github.com/BerriAI/litellm.git
synced 2026-09-27 01:22:18 +00:00
* ci: run the unit_selection.sh shard files on every event instead of only fork pull requests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * ci: rename fork-flag to unit-flag now that it applies on every event * test: move tests/test_litellm root and small trees into tests/unit Pure renames, no content changes. Follow-up commits in this PR fix references, merge the three files that already existed in tests/unit, keep live-provider tests in tests/test_litellm and wire CI. * test: carry tests/test_litellm conftest isolation into tests/unit Callback lists, routing fallbacks, cached HTTP clients, logger state, AWS, proxy-URL and keychain env, and session-end client cleanup now reset for unit tests too. The environment isolation owns its MonkeyPatch so a test's own monkeypatch is undone before the model-cost teardown runs. * test: merge, split and prune the moved root and small-tree tests Merge batches/test_batch_utils.py and the chat_completions and messages dispatch tests into the files that already existed in tests/unit. Keep the live Gemini interactions tests, the async image-fetch format test and the OpenAI embedding scorer test in tests/test_litellm since they need real network or keys. Put test_router.py under tests/unit/test_router so the existing package no longer shadows it. Delete eight tests the audit found superseded by stronger ones kept in this move. * ci: run the moved root and small-tree tests under their legacy flags Add the misc and responses-caching-types flags to unit_selection.sh and CircleCI, extend enterprise-routing and mcp-integration, and point the legacy GHA shards, Makefile, redis-compat workflow, merge smoke manifest and change classifier at the new paths. * test: make the new tests/unit directories packages tests/unit/test_package_layout.py requires every directory to carry an __init__.py, and without one the moved and retained test_litellm_responses_bridge.py modules collide on import. * test: scope the unit socket block to tests/unit in shared sessions The GHA shards collect the legacy test-path and the unit selection in one pytest session. The unit conftest's loopback-only block leaked into legacy modules that reach the network at import. The legacy conftest now lifts the restriction at collect and setup time, and the unit conftest re-applies it when collecting its own modules. * test: move tests/test_litellm/llms into tests/unit/llms Rename-only. Moves the provider tests and the fine-tuning fixtures they load, mirroring the old paths. Follow-up commits merge, split and wire them. * test: merge, split and prune the moved llms tests Merges the Databricks chat transformation tests into the existing unit file, keeps the tests that need real keys or the network in tests/test_litellm, deletes the audited tests a stronger unit test already covers, and points imports at tests.unit.llms. * ci: run the moved llms tests under their legacy flags The Vertex AI and All Other Providers shards keep their legacy test-path for the retained files and add the llm-vertex-ai and llm-other-providers unit selections. CircleCI gets matching unit jobs. * test: make the tests/unit/llms directories packages Adds __init__.py to the moved dirs and drops the legacy ones whose directories no longer hold tests. * test: drop script runners and path hacks the llms split left dangling The __main__ runners in the split openai_like files and the Databricks e2e runner called tests that now live in the other half of the split or were deleted. The retained legacy halves also no longer need sys.path edits. * test: give the shard-script tests their own GITHUB_OUTPUT They only passed where the runner set it. The CircleCI unit job's env allowlist drops it, so the script's redirect failed there. * test: point the router and module-deletion checks at tests/unit router_code_coverage and code_qa_check_tests only searched tests/test_litellm, so the moved router tests no longer counted. The two silent-experiment tests the audit deleted were the only direct callers of those methods; they are replaced with tests that assert the forwarded shadow request and the recursion guard. * test: move tests/test_litellm integrations and secret_managers into tests/unit Rename-only. Mirrors the old paths, including the directory conftests and the prompt and JSON fixtures. Follow-up commits prune and wire them. * test: prune and repoint the moved integrations tests Deletes the 7 audited tests a stronger test in the same tree already covers, imports the TLS sink helpers from their new conftest path, and restores os.environ after each integrations test. Some presets write OTEL_EXPORTER_OTLP_HEADERS straight into os.environ, and without the legacy tree's test ordering that header leaked into the AgentOps tests. * ci: run the moved integrations tests under their legacy flag The integrations GHA shard and a new CircleCI job run the integrations unit selection. secret_managers joins the misc selection. * docs: point integrations and secret_managers references at tests/unit * test: make the moved integrations directories packages * test: keep the Databricks manual e2e runner and fix the SageMaker Nova run path The Databricks e2e file is a manual script whose main() calls the tests that were pruned, so pruning them broke the documented run. It is back to its main version. The SageMaker Nova docstring now points at the file's real location in tests/local_testing. * test: keep the job's UNIT_FLAG out of the shard-script tests --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
179 lines
6.9 KiB
Python
179 lines
6.9 KiB
Python
import zoneinfo
|
|
from datetime import datetime, timezone
|
|
from unittest.mock import MagicMock, Mock, patch
|
|
|
|
import httpx
|
|
import polars as pl
|
|
import pytest
|
|
|
|
|
|
from litellm.integrations.cloudzero.cz_stream_api import CloudZeroStreamer
|
|
|
|
|
|
class TestCloudZeroStreamer:
|
|
"""Test suite for CloudZeroStreamer class."""
|
|
|
|
def test_init_with_defaults(self):
|
|
"""Test CloudZeroStreamer initialization with default parameters."""
|
|
streamer = CloudZeroStreamer(
|
|
api_key="test-key", connection_id="test-connection"
|
|
)
|
|
|
|
assert streamer.api_key == "test-key"
|
|
assert streamer.connection_id == "test-connection"
|
|
assert streamer.base_url == "https://api.cloudzero.com"
|
|
assert streamer.user_timezone == timezone.utc
|
|
|
|
def test_init_with_valid_timezone(self):
|
|
"""Test CloudZeroStreamer initialization with valid timezone."""
|
|
streamer = CloudZeroStreamer(
|
|
api_key="test-key",
|
|
connection_id="test-connection",
|
|
user_timezone="America/New_York",
|
|
)
|
|
|
|
assert streamer.user_timezone == zoneinfo.ZoneInfo("America/New_York")
|
|
|
|
def test_send_batched_with_valid_data(self):
|
|
"""Test send_batched method with valid data."""
|
|
streamer = CloudZeroStreamer("test-key", "test-connection")
|
|
with (
|
|
patch.object(streamer, "_group_by_date") as mock_group,
|
|
patch.object(streamer, "_send_daily_batch") as mock_send,
|
|
):
|
|
|
|
mock_group.return_value = {
|
|
"2025-01-19": pl.DataFrame({"test": ["data1"]}),
|
|
"2025-01-20": pl.DataFrame({"test": ["data2"]}),
|
|
}
|
|
|
|
data = pl.DataFrame({"test": ["data"]})
|
|
streamer.send_batched(data, "replace_hourly")
|
|
|
|
assert mock_send.call_count == 2
|
|
|
|
def test_group_by_date_valid_data(self):
|
|
"""Test _group_by_date method with valid data."""
|
|
streamer = CloudZeroStreamer("test-key", "test-connection")
|
|
with patch.object(streamer, "_parse_and_convert_timestamp") as mock_parse:
|
|
mock_parse.return_value = datetime(
|
|
2025, 1, 19, 10, 30, 0, tzinfo=timezone.utc
|
|
)
|
|
|
|
data = pl.DataFrame(
|
|
{"time/usage_start": ["2025-01-19T10:30:00Z"], "cost": [10.0]}
|
|
)
|
|
|
|
result = streamer._group_by_date(data)
|
|
|
|
assert "2025-01-19" in result
|
|
assert len(result["2025-01-19"]) == 1
|
|
|
|
def test_group_by_date_infers_schema_from_every_row(self):
|
|
"""Test daily batches retain optional string columns that are null for thousands of leading rows."""
|
|
streamer = CloudZeroStreamer("test-key", "test-connection")
|
|
leading_nulls = 10_000
|
|
rows = [
|
|
{"time/usage_start": "2025-01-19T10:30:00Z", "resource/tag:team_alias": None}
|
|
for _ in range(leading_nulls)
|
|
]
|
|
rows.append(
|
|
{"time/usage_start": "2025-01-19T10:30:00Z", "resource/tag:team_alias": "team-alias"}
|
|
)
|
|
data = pl.DataFrame(
|
|
rows,
|
|
schema={"time/usage_start": pl.String, "resource/tag:team_alias": pl.String},
|
|
)
|
|
|
|
result = streamer._group_by_date(data)
|
|
|
|
batch = result["2025-01-19"]
|
|
assert len(batch) == leading_nulls + 1
|
|
assert batch.schema["resource/tag:team_alias"] == pl.String
|
|
assert batch["resource/tag:team_alias"].null_count() == leading_nulls
|
|
assert batch.tail(1).item(0, "resource/tag:team_alias") == "team-alias"
|
|
|
|
def test_parse_and_convert_timestamp_utc(self):
|
|
"""Test _parse_and_convert_timestamp method with UTC timestamp."""
|
|
streamer = CloudZeroStreamer("test-key", "test-connection")
|
|
|
|
result = streamer._parse_and_convert_timestamp("2025-01-19T10:30:00Z")
|
|
|
|
assert result.year == 2025
|
|
assert result.month == 1
|
|
assert result.day == 19
|
|
assert result.hour == 10
|
|
assert result.minute == 30
|
|
assert result.tzinfo == timezone.utc
|
|
|
|
def test_parse_and_convert_timestamp_with_offset(self):
|
|
"""Test _parse_and_convert_timestamp method with timezone offset."""
|
|
streamer = CloudZeroStreamer("test-key", "test-connection")
|
|
|
|
result = streamer._parse_and_convert_timestamp("2025-01-19T10:30:00+05:00")
|
|
|
|
assert result.tzinfo == timezone.utc
|
|
assert result.hour == 5 # Converted to UTC
|
|
|
|
def test_parse_and_convert_timestamp_no_timezone(self):
|
|
"""Test _parse_and_convert_timestamp method without timezone info."""
|
|
streamer = CloudZeroStreamer(
|
|
"test-key", "test-connection", user_timezone="America/New_York"
|
|
)
|
|
|
|
result = streamer._parse_and_convert_timestamp("2025-01-19T10:30:00")
|
|
|
|
assert result.tzinfo == timezone.utc
|
|
|
|
def test_parse_and_convert_timestamp_invalid(self):
|
|
"""Test _parse_and_convert_timestamp method with invalid timestamp."""
|
|
streamer = CloudZeroStreamer("test-key", "test-connection")
|
|
|
|
with pytest.raises(ValueError, match="Could not parse timestamp 'invalid-timestamp': Invalid"):
|
|
streamer._parse_and_convert_timestamp("invalid-timestamp")
|
|
|
|
def test_prepare_batch_payload(self):
|
|
"""Test _prepare_batch_payload method."""
|
|
streamer = CloudZeroStreamer("test-key", "test-connection")
|
|
with patch.object(streamer, "_convert_cbf_to_api_format") as mock_convert:
|
|
mock_convert.return_value = {"test": "record"}
|
|
|
|
batch_data = pl.DataFrame({"cost": [10.0]})
|
|
result = streamer._prepare_batch_payload(
|
|
"2025-01-19", batch_data, "replace_hourly"
|
|
)
|
|
|
|
assert result["month"] == "2025-01"
|
|
assert result["operation"] == "replace_hourly"
|
|
assert len(result["data"]) == 1
|
|
|
|
def test_convert_cbf_to_api_format_valid_data(self):
|
|
"""Test _convert_cbf_to_api_format method with valid data."""
|
|
streamer = CloudZeroStreamer("test-key", "test-connection")
|
|
with patch.object(streamer, "_ensure_utc_timestamp") as mock_ensure:
|
|
mock_ensure.return_value = "2025-01-19T10:30:00Z"
|
|
|
|
row = {
|
|
"time/usage_start": "2025-01-19T10:30:00Z",
|
|
"cost/cost": 10.5,
|
|
"tokens": 100,
|
|
"text_field": "test",
|
|
}
|
|
|
|
result = streamer._convert_cbf_to_api_format(row)
|
|
|
|
assert result["cost/cost"] == "10.5"
|
|
assert result["tokens"] == "100"
|
|
assert result["text_field"] == "test"
|
|
|
|
def test_convert_cbf_to_api_format_float_precision(self):
|
|
"""Test _convert_cbf_to_api_format method handles float precision correctly."""
|
|
streamer = CloudZeroStreamer("test-key", "test-connection")
|
|
|
|
row = {"cost": 10.123456789012345, "large_float": 1234567890.0}
|
|
|
|
result = streamer._convert_cbf_to_api_format(row)
|
|
|
|
# Should avoid scientific notation
|
|
assert "e" not in result["cost"].lower()
|
|
assert "e" not in result["large_float"].lower()
|