litellm/tests/unit/test_cost_calculation_log_level.py
yuneng-jiang f6882246d4
test: move tests/test_litellm root and small trees into tests/unit (#43186)
* 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: 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.

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-09-25 11:30:43 -07:00

137 lines
4.6 KiB
Python

"""Test that cost calculation uses appropriate log levels"""
import logging
import litellm
from litellm import completion_cost
def test_cost_calculation_uses_debug_level():
"""
Test that cost calculation logs use DEBUG level instead of INFO.
This ensures cost calculation details don't appear in production logs.
Part of fix for issue #9815.
Note: This test uses a custom log handler instead of caplog because
caplog doesn't work reliably with pytest-xdist parallel execution.
"""
from litellm._logging import verbose_logger
# Create a custom handler to capture log records
class LogRecordHandler(logging.Handler):
def __init__(self):
super().__init__()
self.records = []
def emit(self, record):
self.records.append(record)
# Set up custom handler
handler = LogRecordHandler()
handler.setLevel(logging.DEBUG)
original_level = verbose_logger.level
verbose_logger.setLevel(logging.DEBUG)
verbose_logger.addHandler(handler)
try:
# Create a mock completion response
mock_response = {
"id": "test",
"object": "chat.completion",
"created": 1234567890,
"model": "gpt-3.5-turbo",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": "Test response"},
"finish_reason": "stop",
}
],
"usage": {"prompt_tokens": 10, "completion_tokens": 20, "total_tokens": 30},
}
# Call completion_cost to trigger logs
try:
cost = completion_cost(
completion_response=mock_response, model="gpt-3.5-turbo"
)
except Exception:
pass # Cost calculation may fail, but we're checking log levels
# Find the cost calculation log records
cost_calc_records = [
record
for record in handler.records
if "selected model name for cost calculation" in record.getMessage()
]
# Verify that cost calculation logs are at DEBUG level
assert len(cost_calc_records) > 0, "No cost calculation logs found"
for record in cost_calc_records:
assert (
record.levelno == logging.DEBUG
), f"Cost calculation log should be DEBUG level, but was {record.levelname}"
finally:
# Clean up: remove handler and restore original logger level
verbose_logger.removeHandler(handler)
verbose_logger.setLevel(original_level)
def test_batch_cost_calculation_uses_debug_level():
"""
Test that batch cost calculation logs also use DEBUG level.
Note: This test uses a custom log handler instead of caplog because
caplog doesn't work reliably with pytest-xdist parallel execution.
"""
from litellm.cost_calculator import batch_cost_calculator
from litellm.types.utils import Usage
from litellm._logging import verbose_logger
# Create a custom handler to capture log records
class LogRecordHandler(logging.Handler):
def __init__(self):
super().__init__()
self.records = []
def emit(self, record):
self.records.append(record)
# Set up custom handler
handler = LogRecordHandler()
handler.setLevel(logging.DEBUG)
original_level = verbose_logger.level
verbose_logger.setLevel(logging.DEBUG)
verbose_logger.addHandler(handler)
try:
# Create a mock usage object
usage = Usage(prompt_tokens=100, completion_tokens=200, total_tokens=300)
# Call batch_cost_calculator to trigger logs
try:
batch_cost_calculator(
usage=usage, model="gpt-3.5-turbo", custom_llm_provider="openai"
)
except Exception:
pass # May fail, but we're checking log levels
# Find batch cost calculation log records
batch_cost_records = [
record
for record in handler.records
if "Calculating batch cost per token" in record.getMessage()
]
# Verify logs exist and are at DEBUG level
if batch_cost_records: # May not always log depending on the code path
for record in batch_cost_records:
assert (
record.levelno == logging.DEBUG
), f"Batch cost calculation log should be DEBUG level, but was {record.levelname}"
finally:
# Clean up: remove handler and restore original logger level
verbose_logger.removeHandler(handler)
verbose_logger.setLevel(original_level)