Files
headroom/tests/test_integrations/langchain/test_extended.py
Tejas ChopraandClaude Opus 5.5 1b7466d1d7 test(integrations): drop duplicated LangChain and LiteLLM tests (#4133)
## Description

This PR removes duplicated tests for the LangChain and LiteLLM
integrations. It changes no product code.

- **`tests/test_integrations/langchain/test_extended.py`** repeated
tests for:
  - `HeadroomChatMessageHistory`
  - `HeadroomDocumentCompressor`
  - `HeadroomToolWrapper`
  - the streaming metrics tracker

The per-module test files already cover all four. Line and branch
coverage of `headroom/integrations/langchain` is identical with and
without these tests.
- **The LiteLLM tests removed** only asserted `hasattr`, `callable` or
not-None on hooks that other tests in the same files call and await.

Refs #4136

## Type of Change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [x] Code refactoring (no functional changes)

## Changes Made

- `test_extended.py`: delete these classes:
  - `TestHeadroomChatMessageHistory` (5 tests)
  - `TestHeadroomDocumentCompressor` (7)
  - `TestStreamingMetricsTracker` (8)
  - 5 of the 6 `TestHeadroomToolWrapper` tests
- Kept from `TestHeadroomToolWrapper`:
`test_call_compresses_large_json`. It is the only LangChain test that
runs `compress_tool_result` unmocked. It is also the only test in this
set that reaches the non-JSON fallback in
`headroom/integrations/mcp/server.py:343-344`;
`tests/test_integrations/mcp` does not cover those lines.
- Also kept: `TestProviderDetection`,
`TestHeadroomLangSmithCallbackHandler` and
`TestAutoDetectProviderInChatModel`. They are the only coverage for
`providers.py` and `langsmith.py`.
- Moved, not deleted: `test_output_tokens` and
`test_messages_passthrough_under_threshold`. Every other memory and
streaming test passes a mock provider or patches `OpenAIProvider`; these
two were the only ones that ran the real default provider
(`OpenAIProvider().get_token_counter(model)`) end to end. They now live
next to their siblings:
-
`test_streaming.py::TestStreamingMetricsTrackerProperties::test_output_tokens_with_default_provider`
-
`test_memory.py::TestHeadroomChatMessageHistoryMessages::test_messages_below_threshold_with_default_provider`
- The `langchain_core` availability probe now imports the package
instead of 4 names that are no longer used.
- `tests/test_litellm_callback.py`: delete
`test_instantiates_without_error`,
`test_has_async_post_call_success_hook`,
`test_async_post_call_success_hook_is_callable` and
`test_async_pre_call_hook_still_works`. Still covered by:
  - `test_async_post_call_success_hook_does_not_raise`;
  - `test_all_current_litellm_async_hooks_present`;
  - the route tests that await `async_pre_call_hook`.
- `tests/test_integrations/test_litellm_callback.py`: delete
`test_method_exists` and `test_method_is_coroutine`.
`test_returns_response_unchanged` awaits the same hook.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`)
- [ ] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ pytest tests/test_integrations/langchain/test_extended.py tests/test_litellm_callback.py tests/test_integrations/test_litellm_callback.py
origin/main: 59 passed
this branch: 28 passed   (31 removed: 25 + 4 + 2)
$ pytest <the same 3 files> tests/test_integrations/langchain/test_memory.py tests/test_integrations/langchain/test_streaming.py
origin/main: 124 passed
this branch: 95 passed   (29 fewer: 31 removed, 2 moved into test_memory.py / test_streaming.py)

# coverage evidence, on origin/main (coverage run --branch over tests/test_integrations/langchain, 244 passed / 21 skipped)
headroom/integrations/langchain/*  with the 26 tests:    1150 stmts, 161 miss, 346 branches, 52 partial
headroom/integrations/langchain/*  without the 26 tests: 1150 stmts, 161 miss, 346 branches, 52 partial
# the only difference outside langchain/ in that run: mcp/server.py 343-344, sqlite.py, compression_store.py, toin.py
# per-test check: mcp/server.py 343-344 come from test_call_compresses_large_json, which this branch keeps.
# The sqlite/compression_store/toin lines are side effects of real compression; their own test suites own them.

$ uvx ruff@0.16.8 check / format <3 touched files>  -> All checks passed! / unchanged
```

## Real Behavior Proof

- Environment: macOS, Python 3.12, repo venv (langchain-core and litellm
installed).
- Exact command / steps:
- `python -m coverage run --branch -m pytest -p no:cov
tests/test_integrations/langchain`, with and without `--deselect` of the
four classes, then `coverage report -m` and a diff.
- `pytest-cov` breaks the litellm import (`KeyError:
'pydantic.root_model'`), so coverage was run directly.
- Observed result: identical numbers for
`headroom/integrations/langchain`. The one test that adds unique
coverage elsewhere is kept.
- Smoke harness (real proxy started from this checkout against a local
fake upstream; temp HOME and workspace, offline):

```text
branch: cleanup/cli-integrations-dedupe-integration-tests @ fc66c0bc
health: 200
POST /v1/messages        -> HTTP200 smoke-ok
POST /v1/chat/completions -> HTTP200 smoke-ok
stats: requests=2 failed=0 tokens_saved=13574 savings_percent=99.82
proxy.log WARNING/ERROR lines (<tmp>/ws/logs/proxy-63921.log):
   2 headroom.proxy - WARNING - event=proxy_offline_mode air-gap active — every connection Headroom initiates is refused (telemetry, update check, license reporter, model/tokenizer/binary/dataset downloads, remote Kompress, OTLP/Langfuse export, Copilot auth, subscription polling, OpenAI embedders, Headroom Cloud compression). Still allowed on purpose: forwarding your requests to the upstream you configured, operator-configured local endpoints, loopback health probes.
   4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch found no usable file for chopratejas/kompress-v2-base
   4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch refused for chopratejas/kompress-v2-base (HEADROOM_OFFLINE is set): HEADROOM_OFFLINE is set: refusing outbound network access for HuggingFace download of chopratejas/kompress-v2-base/onnx/kompress-int8-wo.onnx to huggingface.co. Unset HEADROOM_OFFLINE, or turn off the feature that needs this connection.
(smoke dir: <tmp>)
```
- Direct runtime command on this PR's own path (temp HOME,
HEADROOM_WORKSPACE_DIR and CODEX_HOME):

```text
$ python stream_run.py  # real StreamingMetricsTracker and HeadroomChatMessageHistory, no provider passed
default-provider output_tokens: 9
default-provider history: ['Hello', 'Hi there!'] compressions: 0
```
- Not tested: n/a (tests only).

## Runtime Rollout Safety

- Rollout-managed feature(s): none.
- Minimum rollout channel: n/a, tests only.
- Stable/default behavior changed: no.
- Kill switch / disable path: n/a.
- Unsafe override required: no.
- Qualification impact: none.
- Rollback path: revert this commit.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [ ] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Screenshots (if applicable)

N/A

## Additional Notes

Part of maintainer-requested cleanup #4136 (dead code, duplication,
debuggability), split into small PRs for review.

- This keeps one more test than the audit proposed (25 of 26 removed
from `test_extended.py`), for the reason above, and moves two of the 25
into the focused files so the default-provider path stays tested.
- mypy is unchecked because the PR changes no product code. Docs need no
change.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4133"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 09:01:58 -07:00

276 lines
9.7 KiB
Python

"""Tests for extended LangChain integration modules.
Tests cover:
1. langchain_providers - Provider auto-detection
2. langchain_agents - HeadroomToolWrapper end-to-end compression
3. langchain_langsmith - LangSmith integration
4. HeadroomChatModel provider auto-detection
"""
import json
from unittest.mock import MagicMock
import pytest
# Check if LangChain is available
try:
import langchain_core # noqa: F401
LANGCHAIN_AVAILABLE = True
except ImportError:
LANGCHAIN_AVAILABLE = False
# Skip all tests if LangChain not installed
pytestmark = pytest.mark.skipif(not LANGCHAIN_AVAILABLE, reason="LangChain not installed")
class TestProviderDetection:
"""Tests for langchain_providers module."""
def test_detect_openai_provider(self):
"""Detect OpenAI from ChatOpenAI class."""
from headroom.integrations.langchain.providers import detect_provider
mock_model = MagicMock()
mock_model.__class__.__name__ = "ChatOpenAI"
mock_model.__class__.__module__ = "langchain_openai.chat_models"
provider = detect_provider(mock_model)
assert provider == "openai"
def test_detect_anthropic_provider(self):
"""Detect Anthropic from ChatAnthropic class."""
from headroom.integrations.langchain.providers import detect_provider
mock_model = MagicMock()
mock_model.__class__.__name__ = "ChatAnthropic"
mock_model.__class__.__module__ = "langchain_anthropic.chat_models"
provider = detect_provider(mock_model)
assert provider == "anthropic"
def test_detect_google_provider(self):
"""Detect Google from ChatGoogleGenerativeAI class."""
from headroom.integrations.langchain.providers import detect_provider
mock_model = MagicMock()
mock_model.__class__.__name__ = "ChatGoogleGenerativeAI"
mock_model.__class__.__module__ = "langchain_google_genai"
provider = detect_provider(mock_model)
assert provider == "google"
def test_detect_fallback_to_openai(self):
"""Fall back to OpenAI for unknown models."""
from headroom.integrations.langchain.providers import detect_provider
mock_model = MagicMock()
mock_model.__class__.__name__ = "CustomChatModel"
mock_model.__class__.__module__ = "my_custom_module"
provider = detect_provider(mock_model)
assert provider == "openai"
def test_detect_from_model_name_claude(self):
"""Detect Anthropic from model name containing 'claude'."""
from headroom.integrations.langchain.providers import detect_provider
mock_model = MagicMock()
mock_model.__class__.__name__ = "CustomModel"
mock_model.__class__.__module__ = "custom"
mock_model.model_name = "claude-3-5-sonnet-20241022"
provider = detect_provider(mock_model)
assert provider == "anthropic"
def test_get_headroom_provider_openai(self):
"""Get OpenAIProvider for OpenAI model."""
from headroom.integrations.langchain.providers import get_headroom_provider
from headroom.providers import OpenAIProvider
mock_model = MagicMock()
mock_model.__class__.__name__ = "ChatOpenAI"
mock_model.__class__.__module__ = "langchain_openai"
provider = get_headroom_provider(mock_model)
assert isinstance(provider, OpenAIProvider)
def test_get_headroom_provider_anthropic(self):
"""Get AnthropicProvider for Anthropic model."""
from headroom.integrations.langchain.providers import get_headroom_provider
from headroom.providers import AnthropicProvider
mock_model = MagicMock()
mock_model.__class__.__name__ = "ChatAnthropic"
mock_model.__class__.__module__ = "langchain_anthropic"
provider = get_headroom_provider(mock_model)
assert isinstance(provider, AnthropicProvider)
def test_get_model_name_from_langchain(self):
"""Extract model name from LangChain model."""
from headroom.integrations.langchain.providers import get_model_name_from_langchain
mock_model = MagicMock()
mock_model.model_name = "gpt-4o"
name = get_model_name_from_langchain(mock_model)
assert name == "gpt-4o"
def test_get_model_name_fallback(self):
"""Fall back when model name not available."""
from headroom.integrations.langchain.providers import get_model_name_from_langchain
mock_model = MagicMock(spec=[])
mock_model.__class__.__name__ = "ChatOpenAI"
name = get_model_name_from_langchain(mock_model)
assert name == "gpt-4o" # Default for OpenAI
class TestHeadroomToolWrapper:
"""End-to-end HeadroomToolWrapper compression (compress_tool_result not mocked)."""
def test_call_compresses_large_json(self):
"""Large JSON outputs get compressed."""
from headroom.integrations.langchain.agents import HeadroomToolWrapper
mock_tool = MagicMock()
mock_tool.name = "search"
mock_tool.description = "search"
# Large JSON output
large_output = json.dumps([{"id": i, "data": "x" * 100} for i in range(50)])
mock_tool.invoke.return_value = large_output
wrapper = HeadroomToolWrapper(mock_tool, min_chars_to_compress=100)
result = wrapper("query")
# Should be smaller after compression
assert len(result) <= len(large_output)
class TestHeadroomLangSmithCallbackHandler:
"""Tests for LangSmith integration."""
def test_init(self):
"""Initialize handler."""
from headroom.integrations.langchain.langsmith import (
HeadroomLangSmithCallbackHandler,
)
handler = HeadroomLangSmithCallbackHandler(auto_update_runs=False)
assert handler._auto_update is False
assert handler._pending_metrics == {}
def test_set_headroom_metrics(self):
"""Set metrics for a run."""
from headroom.integrations.langchain.langsmith import (
HeadroomLangSmithCallbackHandler,
)
handler = HeadroomLangSmithCallbackHandler(auto_update_runs=False)
handler.set_headroom_metrics(
run_id="test-run-123",
tokens_before=1000,
tokens_after=800,
transforms_applied=["smart_crusher"],
)
assert "test-run-123" in handler._pending_metrics
metrics = handler._pending_metrics["test-run-123"]
assert metrics.tokens_before == 1000
assert metrics.tokens_after == 800
assert metrics.tokens_saved == 200
assert metrics.savings_percent == 20.0
def test_get_run_metrics(self):
"""Get metrics for a specific run."""
from headroom.integrations.langchain.langsmith import (
HeadroomLangSmithCallbackHandler,
)
handler = HeadroomLangSmithCallbackHandler(auto_update_runs=False)
handler._run_metrics["run-1"] = {"headroom.tokens_saved": 100}
metrics = handler.get_run_metrics("run-1")
assert metrics["headroom.tokens_saved"] == 100
def test_get_summary(self):
"""Get summary statistics."""
from headroom.integrations.langchain.langsmith import (
HeadroomLangSmithCallbackHandler,
)
handler = HeadroomLangSmithCallbackHandler(auto_update_runs=False)
handler._run_metrics = {
"run-1": {"headroom.tokens_saved": 100, "headroom.savings_percent": 20},
"run-2": {"headroom.tokens_saved": 200, "headroom.savings_percent": 30},
}
summary = handler.get_summary()
assert summary["total_runs"] == 2
assert summary["total_tokens_saved"] == 300
assert summary["average_savings_percent"] == 25.0
def test_reset(self):
"""Reset clears all metrics."""
from headroom.integrations.langchain.langsmith import (
HeadroomLangSmithCallbackHandler,
)
handler = HeadroomLangSmithCallbackHandler(auto_update_runs=False)
handler._run_metrics = {"run-1": {}}
handler._pending_metrics = {"run-2": MagicMock()}
handler.reset()
assert handler._run_metrics == {}
assert handler._pending_metrics == {}
class TestAutoDetectProviderInChatModel:
"""Tests for auto_detect_provider in HeadroomChatModel."""
def test_auto_detect_enabled_by_default(self):
"""auto_detect_provider is True by default."""
from headroom.integrations import HeadroomChatModel
mock_model = MagicMock()
mock_model._llm_type = "test"
mock_model._identifying_params = {}
mock_model.__class__.__name__ = "ChatOpenAI"
mock_model.__class__.__module__ = "langchain_openai"
model = HeadroomChatModel(mock_model)
assert model.auto_detect_provider is True
def test_auto_detect_can_be_disabled(self):
"""auto_detect_provider can be set to False."""
from headroom.integrations import HeadroomChatModel
mock_model = MagicMock()
mock_model._llm_type = "test"
mock_model._identifying_params = {}
model = HeadroomChatModel(mock_model, auto_detect_provider=False)
assert model.auto_detect_provider is False
def test_pipeline_uses_detected_provider(self):
"""Pipeline uses auto-detected provider."""
from headroom.integrations import HeadroomChatModel
from headroom.providers import AnthropicProvider
mock_model = MagicMock()
mock_model._llm_type = "test"
mock_model._identifying_params = {}
mock_model.__class__.__name__ = "ChatAnthropic"
mock_model.__class__.__module__ = "langchain_anthropic"
model = HeadroomChatModel(mock_model)
_ = model.pipeline # Force lazy init
assert isinstance(model._provider, AnthropicProvider)