Skip to content

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]

[Infra] Speed up proxy unit tests by replacing litellm reload with state snapshot

Yuneng Jiangccf928361be6
diff --git a/tests/proxy_unit_tests/conftest.py b/tests/proxy_unit_tests/conftest.py
index 1421700c9a8..0cde5bdf28b 100644
--- a/tests/proxy_unit_tests/conftest.py
+++ b/tests/proxy_unit_tests/conftest.py
@@ -1,6 +1,7 @@
# conftest.py
-import importlib
+import asyncio
+import copy
import os
import sys
@@ -9,40 +10,70 @@ import pytest
sys.path.insert(
0, os.path.abspath("../..")
) # Adds the parent directory to the system path
+
import litellm
+import litellm.proxy.proxy_server
[email protected](scope="function", autouse=True)
-def setup_and_teardown():
- """
- This fixture reloads litellm before every function. To speed up testing by removing callbacks being chained.
+def _snapshot_mutable_state(module):
+ """Deep-copy every list/dict/set module attribute for later restore.
+
+ Classes, functions, submodules and primitives are skipped — only the
+ collections that tests mutate (callbacks, caches, routers, etc.) need
+ per-test isolation.
"""
- curr_dir = os.getcwd() # Get the current working directory
- sys.path.insert(
- 0, os.path.abspath("../..")
- ) # Adds the project directory to the system path
+ snapshot = {}
+ for attr in list(vars(module)):
+ if attr.startswith("_"):
+ continue
+ try:
+ value = getattr(module, attr)
+ except Exception:
+ continue
+ if isinstance(value, (list, dict, set)):
+ try:
+ snapshot[attr] = copy.deepcopy(value)
+ except Exception:
+ # Unpickleable collections (e.g. holding open clients) can't
+ # round-trip through deepcopy; skip them rather than crash.
+ pass
+ return snapshot
- import litellm
- from litellm import Router
- importlib.reload(litellm)
- try:
- if hasattr(litellm, "proxy") and hasattr(litellm.proxy, "proxy_server"):
- importlib.reload(litellm.proxy.proxy_server)
- except Exception as e:
- print(f"Error reloading litellm.proxy.proxy_server: {e}")
+def _restore_mutable_state(module, snapshot):
+ for attr, default in snapshot.items():
+ try:
+ setattr(module, attr, copy.deepcopy(default))
+ except Exception:
+ pass
+
+
+# Snapshot once at conftest import — these are the "clean" module states.
+_LITELLM_STATE = _snapshot_mutable_state(litellm)
+_PROXY_SERVER_STATE = _snapshot_mutable_state(litellm.proxy.proxy_server)
- import asyncio
+
[email protected](scope="function", autouse=True)
+def setup_and_teardown():
+ """
+ Reset mutable module state on litellm and proxy_server before every test.
+
+ Replaces a previous importlib.reload(litellm) approach that cost ~17s
+ per test (re-executing the full litellm __init__ import chain). The
+ snapshot-and-restore below only touches collections that actually leak
+ across tests — callbacks, caches, router, etc. — and is effectively
+ instantaneous.
+ """
+ _restore_mutable_state(litellm, _LITELLM_STATE)
+ _restore_mutable_state(litellm.proxy.proxy_server, _PROXY_SERVER_STATE)
loop = asyncio.get_event_loop_policy().new_event_loop()
asyncio.set_event_loop(loop)
- print(litellm)
- # from litellm import Router, completion, aembedding, acompletion, embedding
- yield
-
- # Teardown code (executes after the yield point)
- loop.close() # Close the loop created earlier
- asyncio.set_event_loop(None) # Remove the reference to the loop
+ try:
+ yield
+ finally:
+ loop.close()
+ asyncio.set_event_loop(None)
def pytest_collection_modifyitems(config, items):