Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

Add comprehensive metrics module tests (175 tests)

LearningCircuitaac0c58873cc
diff --git a/tests/metrics/__init__.py b/tests/metrics/__init__.py
new file mode 100644
index 0000000000..97451ef5bd
--- /dev/null
+++ b/tests/metrics/__init__.py
@@ -0,0 +1 @@
+"""Tests for the metrics module."""
diff --git a/tests/metrics/conftest.py b/tests/metrics/conftest.py
new file mode 100644
index 0000000000..e99ad52fc0
--- /dev/null
+++ b/tests/metrics/conftest.py
@@ -0,0 +1,75 @@
+"""Shared fixtures for metrics tests."""
+
+from unittest.mock import MagicMock, Mock, patch
+
+import pytest
+
+
+def mock_flask_session():
+ """Mock Flask session with username."""
+ mock_session = {"username": "testuser", "session_id": "test-session-id"}
+ with patch("flask.session", mock_session):
+ yield mock_session
+
+
+def mock_db_session():
+ """Mock database session."""
+ session = MagicMock()
+ session.query.return_value.filter.return_value.all.return_value = []
+ session.query.return_value.filter.return_value.first.return_value = None
+ session.query.return_value.filter_by.return_value.all.return_value = []
+ session.query.return_value.filter_by.return_value.first.return_value = None
+ return session
+
+
+def mock_search_context():
+ """Mock search context for SearchTracker."""
+ return {
+ "research_id": "test-uuid-123",
+ "research_query": "test query",
+ "research_mode": "quick",
+ "research_phase": "search",
+ "search_iteration": 1,
+ "username": "testuser",
+ "user_password": "testpass",
+ }
+
+
+def mock_token_usage_data():
+ """Sample token usage data for testing."""
+ return {
+ "model_name": "gpt-4",
+ "model_provider": "openai",
+ "prompt_tokens": 100,
+ "completion_tokens": 50,
+ "total_tokens": 150,
+ "research_id": "test-uuid-123",
+ }
+
+
+def mock_llm_response():
+ """Mock LangChain LLM response."""
+ response = Mock()
+ response.llm_output = {
+ "token_usage": {
+ "prompt_tokens": 100,
+ "completion_tokens": 50,
+ "total_tokens": 150,
+ }
+ }
+ response.generations = []
+ return response
+
+
+def mock_metrics_writer():
+ """Mock thread-safe metrics writer."""
+ writer = MagicMock()
+ writer.get_session.return_value.__enter__ = Mock(return_value=MagicMock())
+ writer.get_session.return_value.__exit__ = Mock(return_value=None)
+ return writer
diff --git a/tests/metrics/test_cost_calculator.py b/tests/metrics/test_cost_calculator.py
new file mode 100644
index 0000000000..dc488b03c2
--- /dev/null
+++ b/tests/metrics/test_cost_calculator.py
@@ -0,0 +1,380 @@
+"""Tests for metrics cost_calculator module."""
+
+import pytest
+
+from local_deep_research.metrics.pricing.cost_calculator import CostCalculator
+
+
+class TestCostCalculatorInit:
+ """Tests for CostCalculator initialization."""
+
+ def test_initializes_cache(self):
+ """Should initialize with a PricingCache."""
+ calculator = CostCalculator()
+ assert calculator.cache is not None
+
+ def test_initializes_fetcher_as_none(self):
+ """Should initialize pricing_fetcher as None."""
+ calculator = CostCalculator()
+ assert calculator.pricing_fetcher is None
+
+ def test_accepts_cache_dir_parameter(self):
+ """Should accept cache_dir parameter."""
+ calculator = CostCalculator(cache_dir="/some/path")
+ # Should not raise and cache should still work
+ assert calculator.cache is not None
+
+
+class TestCostCalculatorAsyncContext:
+ """Tests for async context manager."""
+
+ @pytest.mark.asyncio
+ async def test_creates_pricing_fetcher_on_enter(self):
+ """Should create and enter pricing fetcher."""
+ async with CostCalculator() as calculator:
+ assert calculator.pricing_fetcher is not None
+
+ @pytest.mark.asyncio
+ async def test_closes_pricing_fetcher_on_exit(self):
+ """Should close pricing fetcher on exit."""
+ calculator = CostCalculator()
+ async with calculator:
+ _fetcher = calculator.pricing_fetcher # noqa: F841
+
+ # Fetcher should have been exited
+
+
+class TestCostCalculatorGetModelPricing:
+ """Tests for get_model_pricing method."""
+
+ @pytest.mark.asyncio
+ async def test_returns_cached_pricing(self):
+ """Should return pricing from cache if available."""
+ calculator = CostCalculator()
+ cached_pricing = {"prompt": 0.01, "completion": 0.02}
+ calculator.cache.set("model:gpt-4", cached_pricing)
+
+ async with calculator:
+ result = await calculator.get_model_pricing("gpt-4")
+
+ assert result == cached_pricing
+
+ @pytest.mark.asyncio
+ async def test_fetches_pricing_when_not_cached(self):
+ """Should fetch pricing when not in cache."""
+ async with CostCalculator() as calculator:
+ result = await calculator.get_model_pricing("gpt-4")
+
+ assert result is not None
+ assert "prompt" in result
+ assert "completion" in result
+
+ @pytest.mark.asyncio
+ async def test_caches_fetched_pricing(self):
+ """Should cache pricing after fetching."""
+ async with CostCalculator() as calculator:
+ await calculator.get_model_pricing("gpt-4")
+
+ # Should now be in cache
+ cached = calculator.cache.get("model:gpt-4")
+ assert cached is not None
+
+ @pytest.mark.asyncio
+ async def test_returns_none_for_unknown_model(self):
+ """Should return None for unknown model."""
+ async with CostCalculator() as calculator:
+ result = await calculator.get_model_pricing("unknown-model-xyz")
+
+ assert result is None
+
+
+class TestCostCalculatorCalculateCost:
+ """Tests for calculate_cost method."""
+
+ @pytest.mark.asyncio
+ async def test_calculates_cost_correctly(self):
+ """Should calculate cost correctly based on pricing."""
+ async with CostCalculator() as calculator:
+ # gpt-4 has pricing: prompt=0.03, completion=0.06 per 1K tokens
+ result = await calculator.calculate_cost(
+ "gpt-4",
+ prompt_tokens=1000,
+ completion_tokens=500,
+ )
+
+ # 1000/1000 * 0.03 = 0.03 for prompt
+ # 500/1000 * 0.06 = 0.03 for completion
+ # Total = 0.06
+ assert result["prompt_cost"] == pytest.approx(0.03, rel=1e-4)
+ assert result["completion_cost"] == pytest.approx(0.03, rel=1e-4)
+ assert result["total_cost"] == pytest.approx(0.06, rel=1e-4)
+
+ @pytest.mark.asyncio
+ async def test_returns_zero_cost_for_unknown_model(self):
+ """Should return zero cost when no pricing available."""
+ async with CostCalculator() as calculator:
+ result = await calculator.calculate_cost(
+ "unknown-model",
+ prompt_tokens=1000,
+ completion_tokens=500,
+ )
+
+ assert result["prompt_cost"] == 0.0
+ assert result["completion_cost"] == 0.0
+ assert result["total_cost"] == 0.0
+ assert "error" in result
+
+ @pytest.mark.asyncio
+ async def test_returns_pricing_used(self):
+ """Should include pricing_used in result."""
+ async with CostCalculator() as calculator:
+ result = await calculator.calculate_cost(
+ "gpt-4",
+ prompt_tokens=100,
+ completion_tokens=50,
+ )
+
+ assert "pricing_used" in result
+ assert result["pricing_used"] is not None
+
+ @pytest.mark.asyncio
+ async def test_handles_zero_tokens(self):
+ """Should handle zero tokens correctly."""
+ async with CostCalculator() as calculator:
+ result = await calculator.calculate_cost(
+ "gpt-4",
+ prompt_tokens=0,
+ completion_tokens=0,
+ )
+
+ assert result["prompt_cost"] == 0.0
+ assert result["completion_cost"] == 0.0
+ assert result["total_cost"] == 0.0
+
+ @pytest.mark.asyncio
+ async def test_uses_provider_for_pricing(self):
+ """Should use provider to look up pricing."""
+ async with CostCalculator() as calculator:
+ # Local providers should have zero cost
+ result = await calculator.calculate_cost(
+ "any-model",
+ prompt_tokens=1000,
+ completion_tokens=500,
+ provider="ollama",
+ )
+
+ assert result["total_cost"] == 0.0
+
+
+class TestCostCalculatorCalculateBatchCosts:
+ """Tests for calculate_batch_costs method."""
+
+ @pytest.mark.asyncio
+ async def test_processes_all_records(self):
+ """Should process all records in batch."""
+ records = [
+ {
+ "model_name": "gpt-4",
+ "prompt_tokens": 100,
+ "completion_tokens": 50,
+ },
+ {
+ "model_name": "gpt-3.5-turbo",
+ "prompt_tokens": 200,
+ "completion_tokens": 100,
+ },
+ ]
+
+ async with CostCalculator() as calculator:
+ results = await calculator.calculate_batch_costs(records)
+
+ assert len(results) == 2
+
+ @pytest.mark.asyncio
+ async def test_preserves_original_record_data(self):
+ """Should preserve original record data in results."""
+ records = [
+ {
+ "model_name": "gpt-4",
+ "prompt_tokens": 100,
+ "completion_tokens": 50,
+ "research_id": "test-123",
+ },
+ ]
+
+ async with CostCalculator() as calculator:
+ results = await calculator.calculate_batch_costs(records)
+
+ assert results[0]["research_id"] == "test-123"
+ assert results[0]["model_name"] == "gpt-4"
+
+ @pytest.mark.asyncio
+ async def test_handles_errors_gracefully(self):
+ """Should handle errors in individual records."""
+ records = [
+ {
+ "model_name": "gpt-4",
+ "prompt_tokens": 100,
+ "completion_tokens": 50,
+ },
+ {
+ "model_name": None,
+ "prompt_tokens": 100,
+ "completion_tokens": 50,
+ }, # Invalid
+ ]
+
+ async with CostCalculator() as calculator:
+ results = await calculator.calculate_batch_costs(records)
+
+ assert len(results) == 2
+ # Second record should have zero cost due to error
+ assert "error" in results[1] or results[1]["total_cost"] == 0.0
+
+
+class TestCostCalculatorCalculateCostSync:
+ """Tests for calculate_cost_sync method."""
+
+ def test_uses_cached_pricing(self):
+ """Should use cached pricing."""
+ calculator = CostCalculator()
+ calculator.cache.set_model_pricing(
+ "gpt-4", {"prompt": 0.03, "completion": 0.06}
+ )
+
+ result = calculator.calculate_cost_sync("gpt-4", 1000, 500)
+
+ assert result["prompt_cost"] == pytest.approx(0.03, rel=1e-4)
+ assert result["completion_cost"] == pytest.approx(0.03, rel=1e-4)
+
+ def test_uses_static_fallback(self):
+ """Should use static pricing as fallback."""
+ calculator = CostCalculator()
+
+ result = calculator.calculate_cost_sync("gpt-4", 1000, 500)
+
+ assert result["total_cost"] > 0
+ assert result["pricing_used"] is not None
+
+ def test_returns_zero_for_unknown_model(self):
+ """Should return zero cost for unknown model."""
+ calculator = CostCalculator()
+
+ result = calculator.calculate_cost_sync("unknown-model-xyz", 1000, 500)
+
+ assert result["total_cost"] == 0.0
+ assert "error" in result
+
+ def test_handles_model_with_provider_prefix(self):
+ """Should handle model names with provider prefix."""
+ calculator = CostCalculator()
+
+ result = calculator.calculate_cost_sync("openai/gpt-4o-mini", 1000, 500)
+
+ # Should find pricing for gpt-4o-mini
+ assert result["pricing_used"] is not None
+
+
+class TestCostCalculatorGetResearchCostSummary:
+ """Tests for get_research_cost_summary method."""
+
+ @pytest.mark.asyncio
+ async def test_calculates_totals(self):
+ """Should calculate correct totals."""
+ records = [
+ {
+ "model_name": "gpt-4",
+ "prompt_tokens": 1000,
+ "completion_tokens": 500,
+ },
+ {
+ "model_name": "gpt-4",
+ "prompt_tokens": 2000,
+ "completion_tokens": 1000,
+ },
+ ]
+
+ async with CostCalculator() as calculator:
+ summary = await calculator.get_research_cost_summary(records)
+
+ assert summary["total_tokens"] == 4500
+ assert summary["prompt_tokens"] == 3000
+ assert summary["completion_tokens"] == 1500
+ assert summary["total_calls"] == 2
+
+ @pytest.mark.asyncio
+ async def test_calculates_model_breakdown(self):
+ """Should provide breakdown by model."""
+ records = [
+ {
+ "model_name": "gpt-4",
+ "prompt_tokens": 1000,
+ "completion_tokens": 500,
+ },
+ {
+ "model_name": "gpt-3.5-turbo",
+ "prompt_tokens": 2000,
+ "completion_tokens": 1000,
+ },
+ ]
+
+ async with CostCalculator() as calculator:
+ summary = await calculator.get_research_cost_summary(records)
+
+ assert "model_breakdown" in summary
+ assert "gpt-4" in summary["model_breakdown"]
+ assert "gpt-3.5-turbo" in summary["model_breakdown"]
+
+ @pytest.mark.asyncio
+ async def test_calculates_average_cost(self):
+ """Should calculate average cost per call."""
+ records = [
+ {
+ "model_name": "gpt-4",
+ "prompt_tokens": 1000,
+ "completion_tokens": 500,
+ },
+ {
+ "model_name": "gpt-4",
+ "prompt_tokens": 1000,
+ "completion_tokens": 500,
+ },
+ ]
+
+ async with CostCalculator() as calculator:
+ summary = await calculator.get_research_cost_summary(records)
+
+ assert "avg_cost_per_call" in summary
+ if summary["total_cost"] > 0:
+ assert summary["avg_cost_per_call"] == summary["total_cost"] / 2
+
+ @pytest.mark.asyncio
+ async def test_handles_empty_records(self):
+ """Should handle empty records list."""
+ async with CostCalculator() as calculator:
+ summary = await calculator.get_research_cost_summary([])
+
+ assert summary["total_cost"] == 0.0
+ assert summary["total_calls"] == 0
+ assert summary["avg_cost_per_call"] == 0.0
+
+ @pytest.mark.asyncio
+ async def test_calculates_cost_per_token(self):
+ """Should calculate cost per token."""
+ records = [
+ {
+ "model_name": "gpt-4",
+ "prompt_tokens": 1000,
+ "completion_tokens": 500,
+ },
+ ]
+
+ async with CostCalculator() as calculator:
+ summary = await calculator.get_research_cost_summary(records)
+
+ assert "cost_per_token" in summary
+ if summary["total_tokens"] > 0 and summary["total_cost"] > 0:
+ expected = summary["total_cost"] / summary["total_tokens"]
+ assert summary["cost_per_token"] == pytest.approx(
+ expected, rel=1e-6
+ )
diff --git a/tests/metrics/test_database.py b/tests/metrics/test_database.py
new file mode 100644
index 0000000000..407aa0d799
--- /dev/null
+++ b/tests/metrics/test_database.py
@@ -0,0 +1,206 @@
+"""Tests for metrics database module."""
+
+from unittest.mock import MagicMock, Mock, patch
+
+import pytest
+
+from local_deep_research.metrics.database import MetricsDatabase, get_metrics_db
+
+
+class TestMetricsDatabaseInit:
+ """Tests for MetricsDatabase initialization."""
+
+ def test_initializes_with_no_credentials(self):
+ """Should initialize without credentials."""
+ db = MetricsDatabase()
+ assert db.username is None
+ assert db.password is None
+
+ def test_initializes_with_username(self):
+ """Should store username if provided."""
+ db = MetricsDatabase(username="testuser")
+ assert db.username == "testuser"
+ assert db.password is None
+
+ def test_initializes_with_credentials(self):
+ """Should store both username and password."""
+ db = MetricsDatabase(username="testuser", password="testpass")
+ assert db.username == "testuser"
+ assert db.password == "testpass"
+
+
+class TestMetricsDatabaseGetSession:
+ """Tests for get_session method."""
+
+ def test_yields_none_when_no_username_available(self):
+ """Should yield None when no username available."""
+ db = MetricsDatabase()
+
+ with patch("flask.session", {}):
+ with db.get_session() as session:
+ assert session is None
+
+ def test_uses_provided_username(self):
+ """Should use username provided to get_session."""
+ db = MetricsDatabase()
+ mock_session = MagicMock()
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = Mock(return_value=mock_session)
+ mock_cm.__exit__ = Mock(return_value=None)
+
+ with patch(
+ "local_deep_research.metrics.database.get_user_db_session",
+ return_value=mock_cm,
+ ):
+ with db.get_session(username="testuser") as session:
+ assert session == mock_session
+
+ def test_uses_stored_username_as_fallback(self):
+ """Should use stored username if not provided."""
+ db = MetricsDatabase(username="stored_user")
+ mock_session = MagicMock()
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = Mock(return_value=mock_session)
+ mock_cm.__exit__ = Mock(return_value=None)
+
+ with patch(
+ "local_deep_research.metrics.database.get_user_db_session",
+ return_value=mock_cm,
+ ):
+ with db.get_session() as session:
+ assert session == mock_session
+
+ def test_uses_flask_session_as_fallback(self):
+ """Should try Flask session if no username provided."""
+ db = MetricsDatabase()
+ mock_session = MagicMock()
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = Mock(return_value=mock_session)
+ mock_cm.__exit__ = Mock(return_value=None)
+
+ with patch("flask.session", {"username": "flask_user"}):
+ with patch(
+ "local_deep_research.metrics.database.get_user_db_session",
+ return_value=mock_cm,
+ ):
+ with db.get_session() as session:
+ assert session == mock_session
+
+ def test_uses_thread_safe_access_with_password(self):
+ """Should use thread metrics writer when password provided."""
+ db = MetricsDatabase(username="testuser", password="testpass")
+ mock_session = MagicMock()
+ mock_writer = MagicMock()
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = Mock(return_value=mock_session)
+ mock_cm.__exit__ = Mock(return_value=None)
+ mock_writer.get_session.return_value = mock_cm
+
+ with patch(
+ "local_deep_research.database.thread_metrics.metrics_writer",
+ mock_writer,
+ ):
+ with db.get_session() as session:
+ mock_writer.set_user_password.assert_called_with(
+ "testuser", "testpass"
+ )
+ assert session == mock_session
+
+ def test_overrides_stored_username(self):
+ """Should use provided username over stored one."""
+ db = MetricsDatabase(username="stored")
+ mock_session = MagicMock()
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = Mock(return_value=mock_session)
+ mock_cm.__exit__ = Mock(return_value=None)
+
+ with patch(
+ "local_deep_research.metrics.database.get_user_db_session",
+ return_value=mock_cm,
+ ) as mock_get_session:
+ # Provide override username
+ with db.get_session(username="override"):
+ mock_get_session.assert_called_with("override")
+
+ def test_handles_flask_import_error(self):
+ """Should handle case when Flask is not available."""
+ db = MetricsDatabase()
+
+ # Simulate Flask not being available
+ with patch.dict("sys.modules", {"flask": None}):
+ with db.get_session() as session:
+ # Should yield None without raising
+ assert session is None
+
+
+class TestGetMetricsDb:
+ """Tests for get_metrics_db singleton function."""
+
+ def test_returns_metrics_database_instance(self):
+ """Should return a MetricsDatabase instance."""
+ # Reset singleton for test
+ import local_deep_research.metrics.database as db_module
+
+ db_module._metrics_db = None
+
+ result = get_metrics_db()
+ assert isinstance(result, MetricsDatabase)
+
+ def test_returns_same_instance_on_repeated_calls(self):
+ """Should return the same instance (singleton)."""
+ # Reset singleton for test
+ import local_deep_research.metrics.database as db_module
+
+ db_module._metrics_db = None
+
+ first = get_metrics_db()
+ second = get_metrics_db()
+
+ assert first is second
+
+ def test_singleton_persistence(self):
+ """Singleton should persist across calls."""
+ # Reset singleton for test
+ import local_deep_research.metrics.database as db_module
+
+ db_module._metrics_db = None
+
+ db1 = get_metrics_db()
+ db2 = get_metrics_db()
+ db3 = get_metrics_db()
+
+ assert db1 is db2 is db3
+
+
+class TestMetricsDatabaseContextManager:
+ """Tests for context manager behavior."""
+
+ def test_context_manager_returns_session(self):
+ """Context manager should yield a session."""
+ db = MetricsDatabase(username="testuser")
+ mock_session = MagicMock()
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = Mock(return_value=mock_session)
+ mock_cm.__exit__ = Mock(return_value=None)
+
+ with patch(
+ "local_deep_research.metrics.database.get_user_db_session",
+ return_value=mock_cm,
+ ):
+ with db.get_session() as session:
+ assert session is not None
+
+ def test_context_manager_handles_exceptions(self):
+ """Context manager should handle exceptions properly."""
+ db = MetricsDatabase(username="testuser")
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = Mock(side_effect=Exception("DB Error"))
+ mock_cm.__exit__ = Mock(return_value=None)
+
+ with patch(
+ "local_deep_research.metrics.database.get_user_db_session",
+ return_value=mock_cm,
+ ):
+ with pytest.raises(Exception, match="DB Error"):
+ with db.get_session():
+ pass
diff --git a/tests/metrics/test_pricing_cache.py b/tests/metrics/test_pricing_cache.py
new file mode 100644
index 0000000000..69dd7b3782
--- /dev/null
+++ b/tests/metrics/test_pricing_cache.py
@@ -0,0 +1,255 @@
+"""Tests for metrics pricing_cache module."""
+
+import time
+
+
+from local_deep_research.metrics.pricing.pricing_cache import PricingCache
+
+
+class TestPricingCacheInit:
+ """Tests for PricingCache initialization."""
+
+ def test_initializes_with_default_ttl(self):
+ """Should initialize with default TTL of 3600 seconds."""
+ cache = PricingCache()
+ assert cache.cache_ttl == 3600
+
+ def test_initializes_with_custom_ttl(self):
+ """Should initialize with custom TTL."""
+ cache = PricingCache(cache_ttl=7200)
+ assert cache.cache_ttl == 7200
+
+ def test_initializes_empty_cache(self):
+ """Should initialize with empty in-memory cache."""
+ cache = PricingCache()
+ assert cache._cache == {}
+
+ def test_cache_dir_is_deprecated(self):
+ """Cache dir parameter should be ignored (deprecated)."""
+ cache = PricingCache(cache_dir="/some/path")
+ # Should not raise and should work normally
+ assert cache._cache == {}
+
+
+class TestPricingCacheGetSet:
+ """Tests for PricingCache get/set methods."""
+
+ def test_get_returns_none_for_missing_key(self):
+ """Should return None for non-existent key."""
+ cache = PricingCache()
+ result = cache.get("nonexistent")
+ assert result is None
+
+ def test_set_stores_data_with_timestamp(self):
+ """Should store data with timestamp."""
+ cache = PricingCache()
+ cache.set("test_key", {"value": 123})
+
+ assert "test_key" in cache._cache
+ assert cache._cache["test_key"]["data"] == {"value": 123}
+ assert "timestamp" in cache._cache["test_key"]
+
+ def test_get_returns_valid_data(self):
+ """Should return data for valid key."""
+ cache = PricingCache()
+ cache.set("test_key", {"value": 456})
+
+ result = cache.get("test_key")
+ assert result == {"value": 456}
+
+ def test_get_returns_none_for_expired_key(self):
+ """Should return None and remove expired entries."""
+ cache = PricingCache(cache_ttl=1) # 1 second TTL
+ cache.set("test_key", {"value": 789})
+
+ # Wait for expiration
+ time.sleep(1.1)
+
+ result = cache.get("test_key")
+ assert result is None
+ assert "test_key" not in cache._cache
+
+
+class TestPricingCacheModelPricing:
+ """Tests for model pricing methods."""
+
+ def test_get_model_pricing_returns_none_for_missing(self):
+ """Should return None for missing model pricing."""
+ cache = PricingCache()
+ result = cache.get_model_pricing("gpt-4")
+ assert result is None
+
+ def test_set_model_pricing_stores_with_prefix(self):
+ """Should store pricing with 'model:' prefix."""
+ cache = PricingCache()
+ pricing = {"prompt": 0.03, "completion": 0.06}
+ cache.set_model_pricing("gpt-4", pricing)
+
+ assert "model:gpt-4" in cache._cache
+ assert cache._cache["model:gpt-4"]["data"] == pricing
+
+ def test_get_model_pricing_retrieves_stored(self):
+ """Should retrieve stored model pricing."""
+ cache = PricingCache()
+ pricing = {"prompt": 0.03, "completion": 0.06}
+ cache.set_model_pricing("gpt-4", pricing)
+
+ result = cache.get_model_pricing("gpt-4")
+ assert result == pricing
+
+
+class TestPricingCacheAllPricing:
+ """Tests for all pricing methods."""
+
+ def test_get_all_pricing_returns_none_when_not_set(self):
+ """Should return None when all pricing not cached."""
+ cache = PricingCache()
+ result = cache.get_all_pricing()
+ assert result is None
+
+ def test_set_all_pricing_stores_data(self):
+ """Should store all pricing data."""
+ cache = PricingCache()
+ all_pricing = {
+ "gpt-4": {"prompt": 0.03, "completion": 0.06},
+ "gpt-3.5-turbo": {"prompt": 0.001, "completion": 0.002},
+ }
+ cache.set_all_pricing(all_pricing)
+
+ assert "all_models" in cache._cache
+ assert cache._cache["all_models"]["data"] == all_pricing
+
+ def test_get_all_pricing_retrieves_stored(self):
+ """Should retrieve stored all pricing."""
+ cache = PricingCache()
+ all_pricing = {
+ "gpt-4": {"prompt": 0.03, "completion": 0.06},
+ }
+ cache.set_all_pricing(all_pricing)
+
+ result = cache.get_all_pricing()
+ assert result == all_pricing
+
+
+class TestPricingCacheClear:
+ """Tests for cache clearing methods."""
+
+ def test_clear_removes_all_entries(self):
+ """Should remove all cache entries."""
+ cache = PricingCache()
+ cache.set("key1", "value1")
+ cache.set("key2", "value2")
+
+ cache.clear()
+
+ assert cache._cache == {}
+
+ def test_clear_expired_removes_only_expired(self):
+ """Should remove only expired entries."""
+ cache = PricingCache(cache_ttl=2) # 2 second TTL
+ cache.set("old_key", "old_value")
+
+ # Wait for old entry to expire
+ time.sleep(2.1)
+
+ # Add new entry
+ cache.set("new_key", "new_value")
+
+ cache.clear_expired()
+
+ assert "old_key" not in cache._cache
+ assert "new_key" in cache._cache
+
+ def test_clear_expired_handles_empty_cache(self):
+ """Should handle empty cache without error."""
+ cache = PricingCache()
+ cache.clear_expired() # Should not raise
+ assert cache._cache == {}
+
+
+class TestPricingCacheStats:
+ """Tests for cache statistics."""
+
+ def test_get_cache_stats_returns_correct_structure(self):
+ """Should return stats with correct keys."""
+ cache = PricingCache(cache_ttl=3600)
+ stats = cache.get_cache_stats()
+
+ assert "total_entries" in stats
+ assert "expired_entries" in stats
+ assert "valid_entries" in stats
+ assert "cache_type" in stats
+ assert "cache_ttl" in stats
+
+ def test_get_cache_stats_counts_entries(self):
+ """Should count total entries correctly."""
+ cache = PricingCache()
+ cache.set("key1", "value1")
+ cache.set("key2", "value2")
+ cache.set("key3", "value3")
+
+ stats = cache.get_cache_stats()
+
+ assert stats["total_entries"] == 3
+ assert stats["valid_entries"] == 3
+ assert stats["expired_entries"] == 0
+
+ def test_get_cache_stats_counts_expired(self):
+ """Should count expired entries correctly."""
+ cache = PricingCache(cache_ttl=1)
+ cache.set("key1", "value1")
+
+ time.sleep(1.1)
+
+ stats = cache.get_cache_stats()
+
+ assert stats["total_entries"] == 1
+ assert stats["expired_entries"] == 1
+ assert stats["valid_entries"] == 0
+
+ def test_get_cache_stats_shows_cache_type(self):
+ """Should show in-memory cache type."""
+ cache = PricingCache()
+ stats = cache.get_cache_stats()
+
+ assert stats["cache_type"] == "in-memory"
+
+ def test_get_cache_stats_shows_ttl(self):
+ """Should show configured TTL."""
+ cache = PricingCache(cache_ttl=7200)
+ stats = cache.get_cache_stats()
+
+ assert stats["cache_ttl"] == 7200
+
+
+class TestPricingCacheIsExpired:
+ """Tests for _is_expired method."""
+
+ def test_is_expired_returns_false_for_recent(self):
+ """Should return False for recent timestamp."""
+ cache = PricingCache(cache_ttl=3600)
+ recent_time = time.time() - 100 # 100 seconds ago
+
+ result = cache._is_expired(recent_time)
+
+ assert result is False
+
+ def test_is_expired_returns_true_for_old(self):
+ """Should return True for old timestamp."""
+ cache = PricingCache(cache_ttl=3600)
+ old_time = time.time() - 4000 # 4000 seconds ago
+
+ result = cache._is_expired(old_time)
+
+ assert result is True
+
+ def test_is_expired_boundary_condition(self):
+ """Should handle boundary condition correctly."""
+ cache = PricingCache(cache_ttl=100)
+ boundary_time = time.time() - 100
+
+ # At exactly TTL seconds, should be expired
+ result = cache._is_expired(boundary_time)
+
+ # This may be True or False depending on exact timing
+ assert isinstance(result, bool)
diff --git a/tests/metrics/test_pricing_fetcher.py b/tests/metrics/test_pricing_fetcher.py
new file mode 100644
index 0000000000..f44d5da689
--- /dev/null
+++ b/tests/metrics/test_pricing_fetcher.py
@@ -0,0 +1,290 @@
+"""Tests for metrics pricing_fetcher module."""
+
+import pytest
+
+from local_deep_research.metrics.pricing.pricing_fetcher import PricingFetcher
+
+
+class TestPricingFetcherInit:
+ """Tests for PricingFetcher initialization."""
+
+ def test_initializes_with_no_session(self):
+ """Should initialize with session as None."""
+ fetcher = PricingFetcher()
+ assert fetcher.session is None
+
+ def test_loads_static_pricing_on_init(self):
+ """Should load static pricing on initialization."""
+ fetcher = PricingFetcher()
+ assert fetcher.static_pricing is not None
+ assert isinstance(fetcher.static_pricing, dict)
+
+
+class TestPricingFetcherStaticPricing:
+ """Tests for static pricing data."""
+
+ def test_static_pricing_includes_openai_models(self):
+ """Should include OpenAI models."""
+ fetcher = PricingFetcher()
+ assert "gpt-4" in fetcher.static_pricing
+ assert "gpt-4-turbo" in fetcher.static_pricing
+ assert "gpt-4o" in fetcher.static_pricing
+ assert "gpt-4o-mini" in fetcher.static_pricing
+ assert "gpt-3.5-turbo" in fetcher.static_pricing
+
+ def test_static_pricing_includes_anthropic_models(self):
+ """Should include Anthropic models."""
+ fetcher = PricingFetcher()
+ assert "claude-3-opus" in fetcher.static_pricing
+ assert "claude-3-sonnet" in fetcher.static_pricing
+ assert "claude-3-haiku" in fetcher.static_pricing
+ assert "claude-3-5-sonnet" in fetcher.static_pricing
+
+ def test_static_pricing_includes_google_models(self):
+ """Should include Google models."""
+ fetcher = PricingFetcher()
+ assert "gemini-pro" in fetcher.static_pricing
+ assert "gemini-1.5-pro" in fetcher.static_pricing
+ assert "gemini-1.5-flash" in fetcher.static_pricing
+
+ def test_static_pricing_includes_local_models(self):
+ """Should include local/free models with zero pricing."""
+ fetcher = PricingFetcher()
+ local_models = ["ollama", "llama", "mistral", "gemma", "qwen"]
+
+ for model in local_models:
+ assert model in fetcher.static_pricing
+ assert fetcher.static_pricing[model]["prompt"] == 0.0
+ assert fetcher.static_pricing[model]["completion"] == 0.0
+
+ def test_static_pricing_has_correct_structure(self):
+ """Each model should have prompt and completion prices."""
+ fetcher = PricingFetcher()
+
+ for model, pricing in fetcher.static_pricing.items():
+ assert "prompt" in pricing, f"Model {model} missing prompt price"
+ assert "completion" in pricing, (
+ f"Model {model} missing completion price"
+ )
+ assert isinstance(pricing["prompt"], (int, float))
+ assert isinstance(pricing["completion"], (int, float))
+
+
+class TestPricingFetcherAsyncContext:
+ """Tests for async context manager."""
+
+ @pytest.mark.asyncio
+ async def test_async_context_manager_creates_session(self):
+ """Should create aiohttp session on enter."""
+ async with PricingFetcher() as fetcher:
+ assert fetcher.session is not None
+
+ @pytest.mark.asyncio
+ async def test_async_context_manager_closes_session(self):
+ """Should close session on exit."""
+ fetcher = PricingFetcher()
+ async with fetcher:
+ session = fetcher.session
+
+ assert fetcher.session is None or session.closed
+
+
+class TestPricingFetcherGetModelPricing:
+ """Tests for get_model_pricing method."""
+
+ @pytest.mark.asyncio
+ async def test_returns_zero_cost_for_local_providers(self):
+ """Should return zero cost for local providers like ollama."""
+ async with PricingFetcher() as fetcher:
+ result = await fetcher.get_model_pricing("any-model", "ollama")
+
+ assert result == {"prompt": 0.0, "completion": 0.0}
+
+ @pytest.mark.asyncio
+ async def test_returns_pricing_for_exact_model_match(self):
+ """Should return pricing for exact model name match."""
+ async with PricingFetcher() as fetcher:
+ result = await fetcher.get_model_pricing("gpt-4")
+
+ assert result is not None
+ assert result["prompt"] == 0.03
+ assert result["completion"] == 0.06
+
+ @pytest.mark.asyncio
+ async def test_returns_pricing_with_provider_prefix_stripped(self):
+ """Should handle model names with provider prefix."""
+ async with PricingFetcher() as fetcher:
+ result = await fetcher.get_model_pricing("openai/gpt-4o-mini")
+
+ assert result is not None
+ assert "prompt" in result
+ assert "completion" in result
+
+ @pytest.mark.asyncio
+ async def test_returns_none_for_unknown_model(self):
+ """Should return None for completely unknown models."""
+ async with PricingFetcher() as fetcher:
+ result = await fetcher.get_model_pricing("unknown-model-xyz")
+
+ assert result is None
+
+ @pytest.mark.asyncio
+ async def test_local_providers_list(self):
+ """Should recognize all local providers."""
+ local_providers = ["ollama", "vllm", "lmstudio", "llamacpp"]
+
+ async with PricingFetcher() as fetcher:
+ for provider in local_providers:
+ result = await fetcher.get_model_pricing("any-model", provider)
+ assert result == {"prompt": 0.0, "completion": 0.0}
+
+
+class TestPricingFetcherGetModelsByProvider:
+ """Tests for _get_models_by_provider method."""
+
+ def test_returns_openai_models(self):
+ """Should return GPT models for openai provider."""
+ fetcher = PricingFetcher()
+ models = fetcher._get_models_by_provider("openai")
+
+ assert len(models) > 0
+ for model_name in models:
+ assert model_name.startswith("gpt")
+
+ def test_returns_anthropic_models(self):
+ """Should return Claude models for anthropic provider."""
+ fetcher = PricingFetcher()
+ models = fetcher._get_models_by_provider("anthropic")
+
+ assert len(models) > 0
+ for model_name in models:
+ assert model_name.startswith("claude")
+
+ def test_returns_google_models(self):
+ """Should return Gemini models for google provider."""
+ fetcher = PricingFetcher()
+ models = fetcher._get_models_by_provider("google")
+
+ assert len(models) > 0
+ for model_name in models:
+ assert model_name.startswith("gemini")
+
+ def test_returns_free_models_for_local_providers(self):
+ """Should return zero-cost models for local providers."""
+ fetcher = PricingFetcher()
+
+ for provider in ["ollama", "vllm", "lmstudio", "llamacpp"]:
+ models = fetcher._get_models_by_provider(provider)
+ for pricing in models.values():
+ assert pricing["prompt"] == 0.0
+ assert pricing["completion"] == 0.0
+
+ def test_returns_empty_for_unknown_provider(self):
+ """Should return empty dict for unknown provider."""
+ fetcher = PricingFetcher()
+ models = fetcher._get_models_by_provider("unknown_provider")
+
+ assert models == {}
+
+
+class TestPricingFetcherGetProviderFromModel:
+ """Tests for get_provider_from_model method."""
+
+ def test_detects_openai_from_gpt(self):
+ """Should detect OpenAI from GPT model names."""
+ fetcher = PricingFetcher()
+
+ assert fetcher.get_provider_from_model("gpt-4") == "openai"
+ assert fetcher.get_provider_from_model("gpt-3.5-turbo") == "openai"
+ assert fetcher.get_provider_from_model("openai/gpt-4") == "openai"
+
+ def test_detects_anthropic_from_claude(self):
+ """Should detect Anthropic from Claude model names."""
+ fetcher = PricingFetcher()
+
+ assert fetcher.get_provider_from_model("claude-3-opus") == "anthropic"
+ assert (
+ fetcher.get_provider_from_model("claude-3-5-sonnet") == "anthropic"
+ )
+
+ def test_detects_google_from_gemini(self):
+ """Should detect Google from Gemini model names."""
+ fetcher = PricingFetcher()
+
+ assert fetcher.get_provider_from_model("gemini-pro") == "google"
+ assert fetcher.get_provider_from_model("gemini-1.5-flash") == "google"
+
+ def test_detects_meta_from_llama(self):
+ """Should detect Meta from Llama model names."""
+ fetcher = PricingFetcher()
+
+ assert fetcher.get_provider_from_model("llama-2-70b") == "meta"
+ assert fetcher.get_provider_from_model("meta-llama") == "meta"
+
+ def test_detects_mistral(self):
+ """Should detect Mistral provider."""
+ fetcher = PricingFetcher()
+
+ assert fetcher.get_provider_from_model("mistral-7b") == "mistral"
+
+ def test_ollama_detection_edge_case(self):
+ """Document current behavior: 'llama' check runs before 'ollama'.
+
+ Note: Since 'ollama' contains 'llama' as a substring, any model name
+ containing 'ollama' will match 'llama' first and return 'meta'.
+ This is the documented current behavior of the implementation.
+ """
+ fetcher = PricingFetcher()
+
+ # "ollama" contains "llama" so these all match "llama" -> "meta"
+ assert fetcher.get_provider_from_model("ollama:llama2") == "meta"
+ assert fetcher.get_provider_from_model("my-ollama-server") == "meta"
+
+ # The ollama branch would only be reachable with names that don't contain "llama"
+ # but that's not possible if the name contains "ollama"
+
+ def test_returns_unknown_for_unrecognized(self):
+ """Should return 'unknown' for unrecognized models."""
+ fetcher = PricingFetcher()
+
+ assert fetcher.get_provider_from_model("random-model") == "unknown"
+
+
+class TestPricingFetcherGetAllPricing:
+ """Tests for get_all_pricing method."""
+
+ @pytest.mark.asyncio
+ async def test_returns_copy_of_static_pricing(self):
+ """Should return a copy of static pricing."""
+ async with PricingFetcher() as fetcher:
+ result = await fetcher.get_all_pricing()
+
+ assert result == fetcher.static_pricing
+ # Verify it's a copy
+ result["new_key"] = "test"
+ assert "new_key" not in fetcher.static_pricing
+
+
+class TestPricingFetcherFetchMethods:
+ """Tests for individual fetch methods."""
+
+ @pytest.mark.asyncio
+ async def test_fetch_openai_pricing_returns_none(self):
+ """OpenAI pricing fetch returns None (no public API)."""
+ async with PricingFetcher() as fetcher:
+ result = await fetcher.fetch_openai_pricing()
+ assert result is None
+
+ @pytest.mark.asyncio
+ async def test_fetch_anthropic_pricing_returns_none(self):
+ """Anthropic pricing fetch returns None (no public API)."""
+ async with PricingFetcher() as fetcher:
+ result = await fetcher.fetch_anthropic_pricing()
+ assert result is None
+
+ @pytest.mark.asyncio
+ async def test_fetch_google_pricing_returns_none(self):
+ """Google pricing fetch returns None (no public API)."""
+ async with PricingFetcher() as fetcher:
+ result = await fetcher.fetch_google_pricing()
+ assert result is None
diff --git a/tests/metrics/test_query_utils.py b/tests/metrics/test_query_utils.py
new file mode 100644
index 0000000000..552a5614b9
--- /dev/null
+++ b/tests/metrics/test_query_utils.py
@@ -0,0 +1,117 @@
+"""Tests for metrics query_utils module."""
+
+from sqlalchemy import Column, DateTime, String
+from sqlalchemy.orm import declarative_base
+
+from local_deep_research.metrics.query_utils import (
+ get_research_mode_condition,
+ get_time_filter_condition,
+)
+
+# Create a model for SQLAlchemy column testing
+Base = declarative_base()
+
+
+class QueryTestModel(Base):
+ """Model for SQLAlchemy column comparisons."""
+
+ __tablename__ = "query_test_table"
+ id = Column(String, primary_key=True)
+ timestamp = Column(DateTime)
+ mode = Column(String)
+
+
+class TestGetTimeFilterCondition:
+ """Tests for get_time_filter_condition function."""
+
+ def test_returns_none_for_all_period(self):
+ """Should return None when period is 'all'."""
+ result = get_time_filter_condition("all", QueryTestModel.timestamp)
+ assert result is None
+
+ def test_returns_condition_for_7_days(self):
+ """Should return a BinaryExpression for 7 days period."""
+ result = get_time_filter_condition("7d", QueryTestModel.timestamp)
+ assert result is not None
+ # Should be a comparison expression
+ assert hasattr(result, "left") or hasattr(result, "compare")
+
+ def test_returns_condition_for_30_days(self):
+ """Should return a condition for 30 days period."""
+ result = get_time_filter_condition("30d", QueryTestModel.timestamp)
+ assert result is not None
+
+ def test_returns_condition_for_3_months(self):
+ """Should return a condition for 90 days (3 months)."""
+ result = get_time_filter_condition("3m", QueryTestModel.timestamp)
+ assert result is not None
+
+ def test_returns_condition_for_1_year(self):
+ """Should return a condition for 365 days (1 year)."""
+ result = get_time_filter_condition("1y", QueryTestModel.timestamp)
+ assert result is not None
+
+ def test_defaults_to_30_days_for_unknown_period(self):
+ """Should default to 30 days for unknown period strings."""
+ result = get_time_filter_condition("unknown", QueryTestModel.timestamp)
+ # Should return condition (defaults to 30d)
+ assert result is not None
+
+ def test_defaults_to_30_days_for_empty_period(self):
+ """Should default to 30 days for empty period string."""
+ result = get_time_filter_condition("", QueryTestModel.timestamp)
+ assert result is not None
+
+ def test_all_valid_periods(self):
+ """All standard periods should return conditions."""
+ periods = ["7d", "30d", "3m", "1y"]
+ for period in periods:
+ result = get_time_filter_condition(period, QueryTestModel.timestamp)
+ assert result is not None, (
+ f"Period {period} should return a condition"
+ )
+
+
+class TestGetResearchModeCondition:
+ """Tests for get_research_mode_condition function."""
+
+ def test_returns_none_for_all_mode(self):
+ """Should return None when research_mode is 'all'."""
+ result = get_research_mode_condition("all", QueryTestModel.mode)
+ assert result is None
+
+ def test_returns_condition_for_quick(self):
+ """Should return condition for 'quick' mode."""
+ result = get_research_mode_condition("quick", QueryTestModel.mode)
+ assert result is not None
+
+ def test_returns_condition_for_detailed(self):
+ """Should return condition for 'detailed' mode."""
+ result = get_research_mode_condition("detailed", QueryTestModel.mode)
+ assert result is not None
+
+ def test_returns_none_for_unknown_mode(self):
+ """Should return None for unknown mode strings."""
+ result = get_research_mode_condition("unknown", QueryTestModel.mode)
+ assert result is None
+
+ def test_returns_none_for_empty_mode(self):
+ """Should return None for empty mode string."""
+ result = get_research_mode_condition("", QueryTestModel.mode)
+ assert result is None
+
+ def test_quick_and_detailed_are_valid_modes(self):
+ """Only 'quick' and 'detailed' should return conditions."""
+ # Valid modes
+ assert (
+ get_research_mode_condition("quick", QueryTestModel.mode)
+ is not None
+ )
+ assert (
+ get_research_mode_condition("detailed", QueryTestModel.mode)
+ is not None
+ )
+
+ # Invalid modes
+ assert get_research_mode_condition("fast", QueryTestModel.mode) is None
+ assert get_research_mode_condition("slow", QueryTestModel.mode) is None
diff --git a/tests/metrics/test_search_tracker.py b/tests/metrics/test_search_tracker.py
new file mode 100644
index 0000000000..7cde783950
--- /dev/null
+++ b/tests/metrics/test_search_tracker.py
@@ -0,0 +1,418 @@
+"""Tests for metrics search_tracker module."""
+
+from unittest.mock import MagicMock, Mock, patch
+
+
+from local_deep_research.metrics.search_tracker import (
+ SearchTracker,
+ get_search_tracker,
+)
+
+
+class TestSearchTrackerInit:
+ """Tests for SearchTracker initialization."""
+
+ def test_initializes_with_default_database(self):
+ """Should initialize with default MetricsDatabase."""
+ tracker = SearchTracker()
+ assert tracker.db is not None
+
+ def test_initializes_with_custom_database(self):
+ """Should use provided database."""
+ mock_db = MagicMock()
+ tracker = SearchTracker(db=mock_db)
+ assert tracker.db is mock_db
+
+
+class TestSearchTrackerRecordSearch:
+ """Tests for record_search static method."""
+
+ def test_skips_when_no_context(self):
+ """Should skip recording when no search context."""
+ with patch(
+ "local_deep_research.metrics.search_tracker.get_search_context",
+ return_value=None,
+ ):
+ # Should not raise and should return without recording
+ SearchTracker.record_search(
+ engine_name="google",
+ query="test query",
+ results_count=10,
+ )
+
+ def test_extracts_context_correctly(self, mock_search_context):
+ """Should extract research context from thread context."""
+ mock_session = MagicMock()
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = Mock(return_value=mock_session)
+ mock_cm.__exit__ = Mock(return_value=None)
+ mock_writer = MagicMock()
+ mock_writer.get_session.return_value = mock_cm
+
+ with patch(
+ "local_deep_research.metrics.search_tracker.get_search_context",
+ return_value=mock_search_context,
+ ):
+ with patch(
+ "local_deep_research.database.thread_metrics.metrics_writer",
+ mock_writer,
+ ):
+ SearchTracker.record_search(
+ engine_name="brave",
+ query="test query",
+ results_count=5,
+ response_time_ms=150,
+ )
+
+ # Should have added a SearchCall record
+ mock_session.add.assert_called_once()
+
+ def test_handles_integer_research_id(self, mock_search_context):
+ """Should convert integer research_id to string."""
+ mock_search_context["research_id"] = 12345 # Integer
+ mock_session = MagicMock()
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = Mock(return_value=mock_session)
+ mock_cm.__exit__ = Mock(return_value=None)
+ mock_writer = MagicMock()
+ mock_writer.get_session.return_value = mock_cm
+
+ with patch(
+ "local_deep_research.metrics.search_tracker.get_search_context",
+ return_value=mock_search_context,
+ ):
+ with patch(
+ "local_deep_research.database.thread_metrics.metrics_writer",
+ mock_writer,
+ ):
+ SearchTracker.record_search(
+ engine_name="duckduckgo",
+ query="test",
+ )
+
+ # Should have converted to string
+ call_args = mock_session.add.call_args[0][0]
+ assert call_args.research_id == "12345"
+
+ def test_skips_when_no_username(self, mock_search_context):
+ """Should skip recording when no username in context."""
+ mock_search_context["username"] = None
+
+ with patch(
+ "local_deep_research.metrics.search_tracker.get_search_context",
+ return_value=mock_search_context,
+ ):
+ # Should not raise
+ SearchTracker.record_search(
+ engine_name="google",
+ query="test",
+ )
+
+ def test_skips_when_no_password(self, mock_search_context):
+ """Should skip recording when no password in context."""
+ mock_search_context["user_password"] = None
+
+ with patch(
+ "local_deep_research.metrics.search_tracker.get_search_context",
+ return_value=mock_search_context,
+ ):
+ # Should not raise
+ SearchTracker.record_search(
+ engine_name="google",
+ query="test",
+ )
+
+ def test_sets_success_status_for_successful_search(
+ self, mock_search_context
+ ):
+ """Should set success_status to 'success' when success=True."""
+ mock_session = MagicMock()
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = Mock(return_value=mock_session)
+ mock_cm.__exit__ = Mock(return_value=None)
+ mock_writer = MagicMock()
+ mock_writer.get_session.return_value = mock_cm
+
+ with patch(
+ "local_deep_research.metrics.search_tracker.get_search_context",
+ return_value=mock_search_context,
+ ):
+ with patch(
+ "local_deep_research.database.thread_metrics.metrics_writer",
+ mock_writer,
+ ):
+ SearchTracker.record_search(
+ engine_name="google",
+ query="test",
+ success=True,
+ )
+
+ call_args = mock_session.add.call_args[0][0]
+ assert call_args.success_status == "success"
+
+ def test_sets_error_status_for_failed_search(self, mock_search_context):
+ """Should set success_status to 'error' when success=False."""
+ mock_session = MagicMock()
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = Mock(return_value=mock_session)
+ mock_cm.__exit__ = Mock(return_value=None)
+ mock_writer = MagicMock()
+ mock_writer.get_session.return_value = mock_cm
+
+ with patch(
+ "local_deep_research.metrics.search_tracker.get_search_context",
+ return_value=mock_search_context,
+ ):
+ with patch(
+ "local_deep_research.database.thread_metrics.metrics_writer",
+ mock_writer,
+ ):
+ SearchTracker.record_search(
+ engine_name="google",
+ query="test",
+ success=False,
+ error_message="Connection timeout",
+ )
+
+ call_args = mock_session.add.call_args[0][0]
+ assert call_args.success_status == "error"
+ assert call_args.error_message == "Connection timeout"
+
+
+class TestSearchTrackerGetSearchMetrics:
+ """Tests for get_search_metrics method."""
+
+ def test_applies_time_filter(self):
+ """Should apply time filter to query."""
+ mock_db = MagicMock()
+ mock_session = MagicMock()
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = Mock(return_value=mock_session)
+ mock_cm.__exit__ = Mock(return_value=None)
+ mock_db.get_session.return_value = mock_cm
+
+ # Setup query chain
+ mock_query = MagicMock()
+ mock_session.query.return_value = mock_query
+ mock_query.filter.return_value = mock_query
+ mock_query.group_by.return_value = mock_query
+ mock_query.order_by.return_value = mock_query
+ mock_query.limit.return_value = mock_query
+ mock_query.all.return_value = []
+
+ tracker = SearchTracker(db=mock_db)
+ tracker.get_search_metrics(period="7d")
+
+ # Should have called filter (for time)
+ assert mock_query.filter.called
+
+ def test_applies_mode_filter(self):
+ """Should apply research mode filter."""
+ mock_db = MagicMock()
+ mock_session = MagicMock()
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = Mock(return_value=mock_session)
+ mock_cm.__exit__ = Mock(return_value=None)
+ mock_db.get_session.return_value = mock_cm
+
+ # Setup query chain
+ mock_query = MagicMock()
+ mock_session.query.return_value = mock_query
+ mock_query.filter.return_value = mock_query
+ mock_query.group_by.return_value = mock_query
+ mock_query.order_by.return_value = mock_query
+ mock_query.limit.return_value = mock_query
+ mock_query.all.return_value = []
+
+ tracker = SearchTracker(db=mock_db)
+ tracker.get_search_metrics(research_mode="quick")
+
+ # Should have applied filters
+ assert mock_query.filter.called
+
+ def test_returns_engine_stats_structure(self):
+ """Should return search_engine_stats and recent_calls."""
+ mock_db = MagicMock()
+ mock_session = MagicMock()
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = Mock(return_value=mock_session)
+ mock_cm.__exit__ = Mock(return_value=None)
+ mock_db.get_session.return_value = mock_cm
+
+ # Setup query chain
+ mock_query = MagicMock()
+ mock_session.query.return_value = mock_query
+ mock_query.filter.return_value = mock_query
+ mock_query.group_by.return_value = mock_query
+ mock_query.order_by.return_value = mock_query
+ mock_query.limit.return_value = mock_query
+ mock_query.all.return_value = []
+
+ tracker = SearchTracker(db=mock_db)
+ result = tracker.get_search_metrics()
+
+ assert "search_engine_stats" in result
+ assert "recent_calls" in result
+ assert isinstance(result["search_engine_stats"], list)
+ assert isinstance(result["recent_calls"], list)
+
+ def test_handles_database_error(self):
+ """Should handle database errors gracefully."""
+ mock_db = MagicMock()
+ mock_session = MagicMock()
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = Mock(return_value=mock_session)
+ mock_cm.__exit__ = Mock(return_value=None)
+ mock_db.get_session.return_value = mock_cm
+
+ mock_session.query.side_effect = Exception("DB Error")
+
+ tracker = SearchTracker(db=mock_db)
+ result = tracker.get_search_metrics()
+
+ assert result == {"search_engine_stats": [], "recent_calls": []}
+
+
+class TestSearchTrackerGetResearchSearchMetrics:
+ """Tests for get_research_search_metrics method."""
+
+ def test_filters_by_research_id(self):
+ """Should filter results by research_id."""
+ mock_db = MagicMock()
+ mock_session = MagicMock()
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = Mock(return_value=mock_session)
+ mock_cm.__exit__ = Mock(return_value=None)
+ mock_db.get_session.return_value = mock_cm
+
+ # Setup query chain
+ mock_query = MagicMock()
+ mock_session.query.return_value = mock_query
+ mock_query.filter.return_value = mock_query
+ mock_query.group_by.return_value = mock_query
+ mock_query.order_by.return_value = mock_query
+ mock_query.all.return_value = []
+
+ tracker = SearchTracker(db=mock_db)
+ tracker.get_research_search_metrics("test-uuid-123")
+
+ # Should have called filter with research_id
+ assert mock_query.filter.called
+
+ def test_returns_metrics_structure(self):
+ """Should return expected metrics structure."""
+ mock_db = MagicMock()
+ mock_session = MagicMock()
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = Mock(return_value=mock_session)
+ mock_cm.__exit__ = Mock(return_value=None)
+ mock_db.get_session.return_value = mock_cm
+
+ # Setup query chain
+ mock_query = MagicMock()
+ mock_session.query.return_value = mock_query
+ mock_query.filter.return_value = mock_query
+ mock_query.group_by.return_value = mock_query
+ mock_query.order_by.return_value = mock_query
+ mock_query.all.return_value = []
+
+ tracker = SearchTracker(db=mock_db)
+ result = tracker.get_research_search_metrics("test-uuid")
+
+ assert "total_searches" in result
+ assert "total_results" in result
+ assert "avg_response_time" in result
+ assert "success_rate" in result
+ assert "search_calls" in result
+ assert "engine_stats" in result
+
+
+class TestSearchTrackerGetSearchTimeSeries:
+ """Tests for get_search_time_series method."""
+
+ def test_returns_ordered_data(self):
+ """Should return time series data ordered by timestamp."""
+ mock_db = MagicMock()
+ mock_session = MagicMock()
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = Mock(return_value=mock_session)
+ mock_cm.__exit__ = Mock(return_value=None)
+ mock_db.get_session.return_value = mock_cm
+
+ # Setup query chain
+ mock_query = MagicMock()
+ mock_session.query.return_value = mock_query
+ mock_query.filter.return_value = mock_query
+ mock_query.order_by.return_value = mock_query
+ mock_query.all.return_value = []
+
+ tracker = SearchTracker(db=mock_db)
+ result = tracker.get_search_time_series()
+
+ assert isinstance(result, list)
+
+ def test_applies_filters(self):
+ """Should apply time and mode filters."""
+ mock_db = MagicMock()
+ mock_session = MagicMock()
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = Mock(return_value=mock_session)
+ mock_cm.__exit__ = Mock(return_value=None)
+ mock_db.get_session.return_value = mock_cm
+
+ # Setup query chain
+ mock_query = MagicMock()
+ mock_session.query.return_value = mock_query
+ mock_query.filter.return_value = mock_query
+ mock_query.order_by.return_value = mock_query
+ mock_query.all.return_value = []
+
+ tracker = SearchTracker(db=mock_db)
+ tracker.get_search_time_series(period="30d", research_mode="detailed")
+
+ # Should have applied filters
+ assert mock_query.filter.called
+
+
+class TestGetSearchTracker:
+ """Tests for get_search_tracker factory function."""
+
+ def test_returns_search_tracker_instance(self):
+ """Should return a SearchTracker instance."""
+ # Reset singleton
+ import local_deep_research.metrics.search_tracker as module
+
+ module._search_tracker = None
+
+ # The function handles exceptions gracefully and returns a SearchTracker
+ tracker = get_search_tracker()
+
+ assert isinstance(tracker, SearchTracker)
+
+ def test_returns_singleton(self):
+ """Should return same instance on repeated calls."""
+ import local_deep_research.metrics.search_tracker as module
+
+ module._search_tracker = None
+
+ first = get_search_tracker()
+ second = get_search_tracker()
+
+ assert first is second
+
+ def test_singleton_can_be_reset(self):
+ """Should allow resetting the singleton."""
+ import local_deep_research.metrics.search_tracker as module
+
+ # Get instance
+ first = get_search_tracker()
+
+ # Reset singleton
+ module._search_tracker = None
+
+ # Get new instance
+ second = get_search_tracker()
+
+ # New instance should be created but both are SearchTracker
+ assert isinstance(first, SearchTracker)
+ assert isinstance(second, SearchTracker)
diff --git a/tests/metrics/test_token_counter.py b/tests/metrics/test_token_counter.py
new file mode 100644
index 0000000000..0640fa21eb
--- /dev/null
+++ b/tests/metrics/test_token_counter.py
@@ -0,0 +1,733 @@
+"""Tests for metrics token_counter module."""
+
+import time
+from unittest.mock import MagicMock, Mock, patch
+
+
+from local_deep_research.metrics.token_counter import (
+ TokenCounter,
+ TokenCountingCallback,
+)
+
+
+class TestTokenCountingCallbackInit:
+ """Tests for TokenCountingCallback initialization."""
+
+ def test_initializes_with_no_args(self):
+ """Should initialize without arguments."""
+ callback = TokenCountingCallback()
+ assert callback.research_id is None
+ assert callback.research_context == {}
+
+ def test_initializes_with_research_id(self):
+ """Should store research_id."""
+ callback = TokenCountingCallback(research_id="test-uuid")
+ assert callback.research_id == "test-uuid"
+
+ def test_initializes_with_research_context(self):
+ """Should store research context."""
+ context = {"query": "test", "mode": "quick"}
+ callback = TokenCountingCallback(research_context=context)
+ assert callback.research_context == context
+
+ def test_initializes_counts_structure(self):
+ """Should initialize counts with correct structure."""
+ callback = TokenCountingCallback()
+
+ assert "total_tokens" in callback.counts
+ assert "total_prompt_tokens" in callback.counts
+ assert "total_completion_tokens" in callback.counts
+ assert "by_model" in callback.counts
+ assert callback.counts["total_tokens"] == 0
+
+ def test_initializes_timing_fields(self):
+ """Should initialize timing fields."""
+ callback = TokenCountingCallback()
+
+ assert callback.start_time is None
+ assert callback.response_time_ms is None
+ assert callback.success_status == "success"
+
+ def test_initializes_context_overflow_fields(self):
+ """Should initialize context overflow tracking fields."""
+ callback = TokenCountingCallback()
+
+ assert callback.context_limit is None
+ assert callback.context_truncated is False
+ assert callback.tokens_truncated == 0
+
+
+class TestTokenCountingCallbackOnLlmStart:
+ """Tests for on_llm_start method."""
+
+ def test_captures_start_time(self):
+ """Should capture start time."""
+ callback = TokenCountingCallback()
+
+ callback.on_llm_start(
+ serialized={"_type": "ChatOpenAI"},
+ prompts=["test prompt"],
+ )
+
+ assert callback.start_time is not None
+ assert callback.start_time <= time.time()
+
+ def test_estimates_prompt_tokens(self):
+ """Should estimate prompt tokens from text length."""
+ callback = TokenCountingCallback()
+
+ callback.on_llm_start(
+ serialized={"_type": "ChatOpenAI"},
+ prompts=["A" * 400], # 400 chars ~= 100 tokens
+ )
+
+ assert callback.original_prompt_estimate == 100
+
+ def test_extracts_model_from_invocation_params(self):
+ """Should extract model from invocation_params."""
+ callback = TokenCountingCallback()
+
+ callback.on_llm_start(
+ serialized={},
+ prompts=["test"],
+ invocation_params={"model": "gpt-4"},
+ )
+
+ assert callback.current_model == "gpt-4"
+
+ def test_extracts_model_from_kwargs(self):
+ """Should extract model from kwargs."""
+ callback = TokenCountingCallback()
+
+ callback.on_llm_start(
+ serialized={},
+ prompts=["test"],
+ model="gpt-3.5-turbo",
+ )
+
+ assert callback.current_model == "gpt-3.5-turbo"
+
+ def test_extracts_model_from_serialized(self):
+ """Should extract model from serialized kwargs."""
+ callback = TokenCountingCallback()
+
+ callback.on_llm_start(
+ serialized={"kwargs": {"model": "claude-3-opus"}},
+ prompts=["test"],
+ )
+
+ assert callback.current_model == "claude-3-opus"
+
+ def test_uses_preset_model(self):
+ """Should use preset_model if set."""
+ callback = TokenCountingCallback()
+ callback.preset_model = "preset-model"
+
+ callback.on_llm_start(
+ serialized={"kwargs": {"model": "other-model"}},
+ prompts=["test"],
+ )
+
+ assert callback.current_model == "preset-model"
+
+ def test_extracts_provider_from_type(self):
+ """Should extract provider from serialized type."""
+ callback = TokenCountingCallback()
+
+ callback.on_llm_start(
+ serialized={"_type": "ChatOllama"},
+ prompts=["test"],
+ )
+
+ assert callback.current_provider == "ollama"
+
+ def test_extracts_openai_provider(self):
+ """Should detect OpenAI provider."""
+ callback = TokenCountingCallback()
+
+ callback.on_llm_start(
+ serialized={"_type": "ChatOpenAI"},
+ prompts=["test"],
+ )
+
+ assert callback.current_provider == "openai"
+
+ def test_extracts_anthropic_provider(self):
+ """Should detect Anthropic provider."""
+ callback = TokenCountingCallback()
+
+ callback.on_llm_start(
+ serialized={"_type": "ChatAnthropic"},
+ prompts=["test"],
+ )
+
+ assert callback.current_provider == "anthropic"
+
+ def test_uses_preset_provider(self):
+ """Should use preset_provider if set."""
+ callback = TokenCountingCallback()
+ callback.preset_provider = "custom-provider"
+
+ callback.on_llm_start(
+ serialized={"_type": "ChatOpenAI"},
+ prompts=["test"],
+ )
+
+ assert callback.current_provider == "custom-provider"
+
+ def test_increments_call_count(self):
+ """Should increment call count for model."""
+ callback = TokenCountingCallback()
+
+ callback.on_llm_start(
+ serialized={"kwargs": {"model": "gpt-4"}},
+ prompts=["test"],
+ )
+
+ assert callback.counts["by_model"]["gpt-4"]["calls"] == 1
+
+ callback.on_llm_start(
+ serialized={"kwargs": {"model": "gpt-4"}},
+ prompts=["test"],
+ )
+
+ assert callback.counts["by_model"]["gpt-4"]["calls"] == 2
+
+ def test_initializes_model_tracking(self):
+ """Should initialize tracking for new models."""
+ callback = TokenCountingCallback()
+
+ callback.on_llm_start(
+ serialized={"kwargs": {"model": "new-model"}},
+ prompts=["test"],
+ )
+
+ assert "new-model" in callback.counts["by_model"]
+ assert callback.counts["by_model"]["new-model"]["prompt_tokens"] == 0
+ assert (
+ callback.counts["by_model"]["new-model"]["completion_tokens"] == 0
+ )
+
+
+class TestTokenCountingCallbackOnLlmEnd:
+ """Tests for on_llm_end method."""
+
+ def test_calculates_response_time(self):
+ """Should calculate response time in milliseconds."""
+ callback = TokenCountingCallback()
+ callback.start_time = time.time() - 0.5 # 500ms ago
+
+ mock_response = Mock()
+ mock_response.llm_output = {
+ "token_usage": {
+ "prompt_tokens": 10,
+ "completion_tokens": 5,
+ "total_tokens": 15,
+ }
+ }
+ mock_response.generations = []
+
+ callback.on_llm_end(mock_response)
+
+ assert callback.response_time_ms is not None
+ assert callback.response_time_ms >= 500
+
+ def test_extracts_tokens_from_llm_output(self):
+ """Should extract token counts from llm_output."""
+ callback = TokenCountingCallback()
+ callback.current_model = "gpt-4"
+ callback.counts["by_model"]["gpt-4"] = {
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "total_tokens": 0,
+ "calls": 1,
+ }
+
+ mock_response = Mock()
+ mock_response.llm_output = {
+ "token_usage": {
+ "prompt_tokens": 100,
+ "completion_tokens": 50,
+ "total_tokens": 150,
+ }
+ }
+ mock_response.generations = []
+
+ callback.on_llm_end(mock_response)
+
+ assert callback.counts["total_prompt_tokens"] == 100
+ assert callback.counts["total_completion_tokens"] == 50
+ assert callback.counts["total_tokens"] == 150
+
+ def test_extracts_tokens_from_usage_metadata(self):
+ """Should extract tokens from usage_metadata (Ollama format)."""
+ callback = TokenCountingCallback()
+ callback.current_model = "llama"
+ callback.counts["by_model"]["llama"] = {
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "total_tokens": 0,
+ "calls": 1,
+ }
+
+ mock_message = Mock()
+ mock_message.usage_metadata = {
+ "input_tokens": 80,
+ "output_tokens": 40,
+ "total_tokens": 120,
+ }
+ mock_message.response_metadata = {}
+
+ mock_generation = Mock()
+ mock_generation.message = mock_message
+
+ mock_response = Mock()
+ mock_response.llm_output = None
+ mock_response.generations = [[mock_generation]]
+
+ callback.on_llm_end(mock_response)
+
+ assert callback.counts["total_prompt_tokens"] == 80
+ assert callback.counts["total_completion_tokens"] == 40
+
+ def test_extracts_tokens_from_response_metadata_ollama(self):
+ """Should extract tokens from Ollama response_metadata."""
+ callback = TokenCountingCallback()
+ callback.current_model = "mistral"
+ callback.counts["by_model"]["mistral"] = {
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "total_tokens": 0,
+ "calls": 1,
+ }
+
+ mock_message = Mock()
+ mock_message.usage_metadata = None
+ mock_message.response_metadata = {
+ "prompt_eval_count": 60,
+ "eval_count": 30,
+ }
+
+ mock_generation = Mock()
+ mock_generation.message = mock_message
+
+ mock_response = Mock()
+ mock_response.llm_output = None
+ mock_response.generations = [[mock_generation]]
+
+ callback.on_llm_end(mock_response)
+
+ assert callback.counts["total_prompt_tokens"] == 60
+ assert callback.counts["total_completion_tokens"] == 30
+
+ def test_detects_context_overflow(self):
+ """Should detect context overflow when near limit."""
+ callback = TokenCountingCallback()
+ callback.current_model = "model"
+ callback.context_limit = 1000
+ callback.original_prompt_estimate = 1100 # More than what was processed
+ callback.counts["by_model"]["model"] = {
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "total_tokens": 0,
+ "calls": 1,
+ }
+
+ mock_message = Mock()
+ mock_message.usage_metadata = None
+ mock_message.response_metadata = {
+ "prompt_eval_count": 950, # 95% of context_limit
+ "eval_count": 50,
+ }
+
+ mock_generation = Mock()
+ mock_generation.message = mock_message
+
+ mock_response = Mock()
+ mock_response.llm_output = None
+ mock_response.generations = [[mock_generation]]
+
+ callback.on_llm_end(mock_response)
+
+ assert callback.context_truncated is True
+ assert callback.tokens_truncated > 0
+
+ def test_updates_model_counts(self):
+ """Should update per-model token counts."""
+ callback = TokenCountingCallback()
+ callback.current_model = "gpt-4"
+ callback.counts["by_model"]["gpt-4"] = {
+ "prompt_tokens": 10,
+ "completion_tokens": 5,
+ "total_tokens": 15,
+ "calls": 1,
+ }
+
+ mock_response = Mock()
+ mock_response.llm_output = {
+ "token_usage": {
+ "prompt_tokens": 20,
+ "completion_tokens": 10,
+ "total_tokens": 30,
+ }
+ }
+ mock_response.generations = []
+
+ callback.on_llm_end(mock_response)
+
+ assert callback.counts["by_model"]["gpt-4"]["prompt_tokens"] == 30
+ assert callback.counts["by_model"]["gpt-4"]["completion_tokens"] == 15
+
+
+class TestTokenCountingCallbackOnLlmError:
+ """Tests for on_llm_error method."""
+
+ def test_tracks_error_status(self):
+ """Should set success_status to 'error'."""
+ callback = TokenCountingCallback()
+ callback.start_time = time.time()
+
+ callback.on_llm_error(ValueError("Test error"))
+
+ assert callback.success_status == "error"
+
+ def test_tracks_error_type(self):
+ """Should record error type name."""
+ callback = TokenCountingCallback()
+ callback.start_time = time.time()
+
+ callback.on_llm_error(TimeoutError("Timeout"))
+
+ assert callback.error_type == "TimeoutError"
+
+ def test_calculates_response_time_on_error(self):
+ """Should calculate response time even on error."""
+ callback = TokenCountingCallback()
+ callback.start_time = time.time() - 0.1 # 100ms ago
+
+ callback.on_llm_error(Exception("Error"))
+
+ assert callback.response_time_ms is not None
+ assert callback.response_time_ms >= 100
+
+
+class TestTokenCountingCallbackSaveToDb:
+ """Tests for _save_to_db method."""
+
+ def test_uses_thread_metrics_from_background(self):
+ """Should use thread metrics writer from background thread."""
+ callback = TokenCountingCallback(
+ research_id="test-uuid",
+ research_context={
+ "username": "testuser",
+ "user_password": "testpass",
+ },
+ )
+ callback.current_model = "gpt-4"
+ callback.current_provider = "openai"
+
+ mock_writer = MagicMock()
+
+ with patch("threading.current_thread") as mock_thread:
+ mock_thread.return_value.name = "WorkerThread"
+ with patch(
+ "local_deep_research.database.thread_metrics.metrics_writer",
+ mock_writer,
+ ):
+ callback._save_to_db(100, 50)
+
+ mock_writer.set_user_password.assert_called_with(
+ "testuser", "testpass"
+ )
+ mock_writer.write_token_metrics.assert_called()
+
+ def test_skips_save_without_username(self):
+ """Should skip save when no username available."""
+ callback = TokenCountingCallback(
+ research_id="test-uuid",
+ research_context={}, # No username
+ )
+
+ with patch("threading.current_thread") as mock_thread:
+ mock_thread.return_value.name = "WorkerThread"
+ # Should not raise
+ callback._save_to_db(100, 50)
+
+ def test_skips_save_without_research_id(self):
+ """Should skip save when no research_id."""
+ callback = TokenCountingCallback(research_id=None)
+ callback.current_model = "gpt-4"
+
+ # Should not raise - just returns early
+ callback._save_to_db(100, 50)
+
+
+class TestTokenCountingCallbackGetCounts:
+ """Tests for get_counts method."""
+
+ def test_returns_counts_dict(self):
+ """Should return the counts dictionary."""
+ callback = TokenCountingCallback()
+ callback.counts["total_tokens"] = 150
+
+ result = callback.get_counts()
+
+ assert result["total_tokens"] == 150
+
+
+class TestTokenCountingCallbackGetContextOverflowFields:
+ """Tests for _get_context_overflow_fields method."""
+
+ def test_returns_overflow_fields(self):
+ """Should return context overflow fields."""
+ callback = TokenCountingCallback()
+ callback.context_limit = 4096
+ callback.context_truncated = True
+ callback.tokens_truncated = 500
+ callback.truncation_ratio = 0.1
+
+ result = callback._get_context_overflow_fields()
+
+ assert result["context_limit"] == 4096
+ assert result["context_truncated"] is True
+ assert result["tokens_truncated"] == 500
+
+ def test_returns_none_for_non_truncated(self):
+ """Should return None for truncation fields when not truncated."""
+ callback = TokenCountingCallback()
+ callback.context_truncated = False
+
+ result = callback._get_context_overflow_fields()
+
+ assert result["tokens_truncated"] is None
+ assert result["truncation_ratio"] is None
+
+
+class TestTokenCounterInit:
+ """Tests for TokenCounter initialization."""
+
+ def test_initializes(self):
+ """Should initialize successfully."""
+ counter = TokenCounter()
+ assert counter._thread_metrics_db is None
+
+ def test_thread_metrics_db_lazy_loads(self):
+ """Should lazy load thread metrics writer."""
+ counter = TokenCounter()
+
+ with patch(
+ "local_deep_research.database.thread_metrics.metrics_writer",
+ MagicMock(),
+ ):
+ db = counter.thread_metrics_db
+ assert db is not None
+
+
+class TestTokenCounterCreateCallback:
+ """Tests for create_callback method."""
+
+ def test_returns_callback_instance(self):
+ """Should return TokenCountingCallback instance."""
+ counter = TokenCounter()
+
+ callback = counter.create_callback()
+
+ assert isinstance(callback, TokenCountingCallback)
+
+ def test_passes_research_id(self):
+ """Should pass research_id to callback."""
+ counter = TokenCounter()
+
+ callback = counter.create_callback(research_id="test-uuid")
+
+ assert callback.research_id == "test-uuid"
+
+ def test_passes_research_context(self):
+ """Should pass research_context to callback."""
+ counter = TokenCounter()
+ context = {"query": "test", "mode": "quick"}
+
+ callback = counter.create_callback(research_context=context)
+
+ assert callback.research_context == context
+
+
+class TestTokenCounterGetResearchMetrics:
+ """Tests for get_research_metrics method."""
+
+ def test_method_exists(self):
+ """TokenCounter should have get_research_metrics method."""
+ counter = TokenCounter()
+ assert hasattr(counter, "get_research_metrics")
+ assert callable(counter.get_research_metrics)
+
+
+class TestTokenCounterGetOverallMetrics:
+ """Tests for get_overall_metrics method."""
+
+ def test_merges_encrypted_and_thread_dbs(self):
+ """Should merge metrics from both databases."""
+ counter = TokenCounter()
+
+ # Mock _get_metrics_from_encrypted_db
+ encrypted_metrics = {
+ "total_tokens": 1000,
+ "total_researches": 5,
+ "by_model": [
+ {
+ "model": "gpt-4",
+ "tokens": 1000,
+ "calls": 5,
+ "prompt_tokens": 600,
+ "completion_tokens": 400,
+ }
+ ],
+ "recent_researches": [],
+ "token_breakdown": {
+ "total_input_tokens": 600,
+ "total_output_tokens": 400,
+ "avg_input_tokens": 120,
+ "avg_output_tokens": 80,
+ "avg_total_tokens": 200,
+ },
+ }
+
+ thread_metrics = {
+ "total_tokens": 500,
+ "total_researches": 2,
+ "by_model": [],
+ "recent_researches": [],
+ "token_breakdown": {
+ "total_input_tokens": 300,
+ "total_output_tokens": 200,
+ },
+ }
+
+ with patch.object(
+ counter,
+ "_get_metrics_from_encrypted_db",
+ return_value=encrypted_metrics,
+ ):
+ with patch.object(
+ counter,
+ "_get_metrics_from_thread_db",
+ return_value=thread_metrics,
+ ):
+ result = counter.get_overall_metrics()
+
+ assert result["total_tokens"] == 1500 # 1000 + 500
+
+
+class TestTokenCounterMergeMetrics:
+ """Tests for _merge_metrics method."""
+
+ def test_combines_totals(self):
+ """Should combine total tokens."""
+ counter = TokenCounter()
+
+ encrypted = {
+ "total_tokens": 1000,
+ "total_researches": 5,
+ "by_model": [],
+ "recent_researches": [],
+ "token_breakdown": {
+ "total_input_tokens": 600,
+ "total_output_tokens": 400,
+ },
+ }
+
+ thread = {
+ "total_tokens": 500,
+ "total_researches": 3,
+ "by_model": [],
+ "recent_researches": [],
+ "token_breakdown": {
+ "total_input_tokens": 300,
+ "total_output_tokens": 200,
+ },
+ }
+
+ result = counter._merge_metrics(encrypted, thread)
+
+ assert result["total_tokens"] == 1500
+
+ def test_merges_model_usage(self):
+ """Should merge model usage from both sources."""
+ counter = TokenCounter()
+
+ encrypted = {
+ "total_tokens": 1000,
+ "total_researches": 5,
+ "by_model": [
+ {
+ "model": "gpt-4",
+ "tokens": 1000,
+ "calls": 5,
+ "prompt_tokens": 600,
+ "completion_tokens": 400,
+ }
+ ],
+ "recent_researches": [],
+ "token_breakdown": {},
+ }
+
+ thread = {
+ "total_tokens": 500,
+ "total_researches": 3,
+ "by_model": [
+ {
+ "model": "gpt-4",
+ "tokens": 500,
+ "calls": 3,
+ "prompt_tokens": 300,
+ "completion_tokens": 200,
+ }
+ ],
+ "recent_researches": [],
+ "token_breakdown": {},
+ }
+
+ result = counter._merge_metrics(encrypted, thread)
+
+ # Should have merged gpt-4 entries
+ gpt4_entry = next(
+ m for m in result["by_model"] if m["model"] == "gpt-4"
+ )
+ assert gpt4_entry["tokens"] == 1500
+ assert gpt4_entry["calls"] == 8
+
+
+class TestTokenCounterGetEmptyMetrics:
+ """Tests for _get_empty_metrics method."""
+
+ def test_returns_correct_structure(self):
+ """Should return empty metrics with correct structure."""
+ counter = TokenCounter()
+
+ result = counter._get_empty_metrics()
+
+ assert result["total_tokens"] == 0
+ assert result["total_researches"] == 0
+ assert result["by_model"] == []
+ assert result["recent_researches"] == []
+ assert "token_breakdown" in result
+
+
+class TestTokenCounterGetEnhancedMetrics:
+ """Tests for get_enhanced_metrics method."""
+
+ def test_method_exists(self):
+ """TokenCounter should have get_enhanced_metrics method."""
+ counter = TokenCounter()
+ assert hasattr(counter, "get_enhanced_metrics")
+ assert callable(counter.get_enhanced_metrics)
+
+
+class TestTokenCounterGetResearchTimelineMetrics:
+ """Tests for get_research_timeline_metrics method."""
+
+ def test_method_exists(self):
+ """TokenCounter should have get_research_timeline_metrics method."""
+ counter = TokenCounter()
+ assert hasattr(counter, "get_research_timeline_metrics")
+ assert callable(counter.get_research_timeline_metrics)