~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
test: add 111 tests for LLM rate limiting, topic validation, and card helpers (#2490)
LearningCircuitf840ab79d47d
diff --git a/tests/news/test_base_card_helpers.py b/tests/news/test_base_card_helpers.pynew file mode 100644index 0000000000..0fb62a97db--- /dev/null+++ b/tests/news/test_base_card_helpers.py@@ -0,0 +1,194 @@+"""Tests for BaseCard pure helper methods.++Tests cover:+- _calculate_impact: scoring based on findings and sources count+- _extract_headline: multi-field fallback extraction+- _extract_summary: multi-field fallback extraction+- _extract_topics: topic extraction with keyword fallback+- _extract_entities: entity extraction with default structure+"""++import pytest++from local_deep_research.news.core.base_card import CardSource, NewsCard+++# ---------------------------------------------------------------------------+# Fixtures+# ---------------------------------------------------------------------------+++def card():+ """Build a minimal NewsCard for testing helper methods."""+ return NewsCard(+ topic="Test Topic",+ source=CardSource(type="news_item"),+ user_id="user-1",+ )+++# ===================================================================+# _calculate_impact+# ===================================================================+++class TestCalculateImpact:+ """Tests for BaseCard._calculate_impact()."""++ def test_empty_result_returns_base_score(self, card):+ assert card._calculate_impact({}) == 5++ def test_findings_increase_score(self, card):+ result = {"findings": [f"f{i}" for i in range(10)]}+ score = card._calculate_impact(result)+ assert score == 7 # 5 + 10//5 = 7++ def test_sources_increase_score(self, card):+ result = {"sources": [f"s{i}" for i in range(9)]}+ score = card._calculate_impact(result)+ assert score == 8 # 5 + 9//3 = 8++ def test_combined_findings_and_sources(self, card):+ result = {+ "findings": [f"f{i}" for i in range(5)],+ "sources": [f"s{i}" for i in range(6)],+ }+ score = card._calculate_impact(result)+ assert score == 8 # 5 + 5//5 + 6//3 = 8++ def test_max_score_capped_at_10(self, card):+ result = {+ "findings": list(range(100)),+ "sources": list(range(100)),+ }+ assert card._calculate_impact(result) == 10++ def test_min_score_is_1(self, card):+ # Even with no findings/sources, min(10, 5+0+0)=5, max(1,5)=5+ # Score can't go below 1 by design+ assert card._calculate_impact({}) >= 1+++# ===================================================================+# _extract_headline+# ===================================================================+++class TestExtractHeadline:+ """Tests for BaseCard._extract_headline()."""++ def test_headline_field_preferred(self, card):+ result = {"headline": "Breaking News", "title": "Alt Title"}+ assert card._extract_headline(result) == "Breaking News"++ def test_title_fallback(self, card):+ result = {"title": "Article Title"}+ assert card._extract_headline(result) == "Article Title"++ def test_query_fallback_truncated(self, card):+ long_query = "x" * 200+ result = {"query": long_query}+ headline = card._extract_headline(result)+ assert len(headline) == 100++ def test_empty_result_returns_empty(self, card):+ assert card._extract_headline({}) == ""++ def test_headline_none_falls_through(self, card):+ result = {"headline": None, "title": "Fallback"}+ assert card._extract_headline(result) == "Fallback"++ def test_all_none_falls_to_query(self, card):+ result = {"headline": None, "title": None, "query": "my query"}+ assert card._extract_headline(result) == "my query"+++# ===================================================================+# _extract_summary+# ===================================================================+++class TestExtractSummary:+ """Tests for BaseCard._extract_summary()."""++ def test_summary_field_preferred(self, card):+ result = {"summary": "Brief summary", "current_knowledge": "Knowledge"}+ assert card._extract_summary(result) == "Brief summary"++ def test_current_knowledge_fallback(self, card):+ result = {"current_knowledge": "Deep knowledge"}+ assert card._extract_summary(result) == "Deep knowledge"++ def test_formatted_findings_fallback_truncated(self, card):+ long_findings = "z" * 1000+ result = {"formatted_findings": long_findings}+ summary = card._extract_summary(result)+ assert len(summary) == 500++ def test_empty_result_returns_empty(self, card):+ assert card._extract_summary({}) == ""+++# ===================================================================+# _extract_topics+# ===================================================================+++class TestExtractTopics:+ """Tests for BaseCard._extract_topics()."""++ def test_explicit_topics_returned(self, card):+ result = {"topics": ["AI", "Climate"]}+ assert card._extract_topics(result) == ["AI", "Climate"]++ def test_query_keyword_fallback(self, card):+ result = {"query": "global climate change effects"}+ topics = card._extract_topics(result)+ # Words > 4 chars: global, climate, change, effects+ assert "global" in topics+ assert "climate" in topics++ def test_query_short_words_excluded(self, card):+ result = {"query": "how is the AI doing today"}+ topics = card._extract_topics(result)+ # "how", "is", "the", "AI" (2 chars), "doing" (5), "today" (5)+ assert "doing" in topics+ assert "today" in topics++ def test_max_five_topics_from_query(self, card):+ result = {+ "query": "these words are all quite longer than four characters each"+ }+ topics = card._extract_topics(result)+ assert len(topics) <= 5++ def test_empty_result_returns_empty(self, card):+ assert card._extract_topics({}) == []++ def test_empty_topics_triggers_query_fallback(self, card):+ result = {"topics": [], "query": "quantum computing advances"}+ topics = card._extract_topics(result)+ assert len(topics) > 0+++# ===================================================================+# _extract_entities+# ===================================================================+++class TestExtractEntities:+ """Tests for BaseCard._extract_entities()."""++ def test_explicit_entities_returned(self, card):+ entities = {+ "people": ["Alice"],+ "places": ["NYC"],+ "organizations": ["UN"],+ }+ result = {"entities": entities}+ assert card._extract_entities(result) == entities++ def test_default_entities_structure(self, card):+ result = card._extract_entities({})+ assert result == {"people": [], "places": [], "organizations": []}diff --git a/tests/news/test_validate_topics.py b/tests/news/test_validate_topics.pynew file mode 100644index 0000000000..dbc14e170b--- /dev/null+++ b/tests/news/test_validate_topics.py@@ -0,0 +1,119 @@+"""Tests for _validate_topics() pure logic in topic_generator.++Tests cover:+- Length filtering (min 2, max 30)+- Case-insensitive deduplication+- Whitespace stripping+- max_topics enforcement+- Empty/falsy topic handling+- Output normalization to lowercase+"""++from local_deep_research.news.utils.topic_generator import _validate_topics+++class TestValidateTopics:+ """Tests for _validate_topics()."""++ # -- basic functionality -------------------------------------------++ def test_valid_topics_pass_through(self):+ result = _validate_topics(["AI", "Climate"], max_topics=5)+ assert result == ["ai", "climate"]++ def test_output_normalized_to_lowercase(self):+ result = _validate_topics(+ ["CLIMATE Change", "AI Research"], max_topics=5+ )+ assert result == ["climate change", "ai research"]++ # -- length filtering ----------------------------------------------++ def test_single_char_topics_filtered(self):+ result = _validate_topics(["a", "AI", "b"], max_topics=5)+ assert result == ["ai"]++ def test_exactly_two_char_topic_kept(self):+ result = _validate_topics(["AI"], max_topics=5)+ assert result == ["ai"]++ def test_topics_over_30_chars_filtered(self):+ long_topic = "a" * 31+ result = _validate_topics([long_topic, "valid"], max_topics=5)+ assert result == ["valid"]++ def test_exactly_30_char_topic_kept(self):+ topic = "a" * 30+ result = _validate_topics([topic], max_topics=5)+ assert result == [topic]++ # -- deduplication -------------------------------------------------++ def test_case_insensitive_dedup(self):+ result = _validate_topics(["AI", "ai", "Ai", "aI"], max_topics=5)+ assert result == ["ai"]++ def test_dedup_preserves_first_occurrence_normalized(self):+ result = _validate_topics(+ ["Climate", "Economy", "climate"], max_topics=5+ )+ assert result == ["climate", "economy"]++ # -- whitespace handling -------------------------------------------++ def test_leading_trailing_whitespace_stripped(self):+ result = _validate_topics([" AI ", " Climate "], max_topics=5)+ assert result == ["ai", "climate"]++ def test_whitespace_only_topic_filtered(self):+ result = _validate_topics([" ", "valid"], max_topics=5)+ assert result == ["valid"]++ # -- empty / falsy handling ----------------------------------------++ def test_empty_string_filtered(self):+ result = _validate_topics(["", "valid"], max_topics=5)+ assert result == ["valid"]++ def test_none_topic_filtered(self):+ """None values should be skipped (falsy check)."""+ result = _validate_topics([None, "valid"], max_topics=5)+ assert result == ["valid"]++ def test_all_invalid_returns_fallback(self):+ result = _validate_topics(["", "a", None], max_topics=5)+ assert result == ["[No valid topics]"]++ def test_empty_list_returns_fallback(self):+ result = _validate_topics([], max_topics=5)+ assert result == ["[No valid topics]"]++ # -- max_topics enforcement ----------------------------------------++ def test_max_topics_limits_output(self):+ topics = ["one", "two", "three", "four", "five"]+ result = _validate_topics(topics, max_topics=3)+ assert len(result) == 3+ assert result == ["one", "two", "three"]++ def test_max_topics_one(self):+ result = _validate_topics(["first", "second"], max_topics=1)+ assert result == ["first"]++ def test_fewer_topics_than_max(self):+ result = _validate_topics(["one", "two"], max_topics=10)+ assert result == ["one", "two"]++ # -- combined edge cases -------------------------------------------++ def test_dedup_then_max_topics(self):+ """Dedup reduces count, max_topics applied after."""+ topics = ["AI", "ai", "Climate", "climate", "Economy"]+ result = _validate_topics(topics, max_topics=2)+ assert result == ["ai", "climate"]++ def test_length_filter_then_dedup(self):+ """Short topics filtered before dedup counting."""+ topics = ["a", "AI", "AI"]+ result = _validate_topics(topics, max_topics=5)+ assert result == ["ai"]diff --git a/tests/web_search_engines/rate_limiting/test_llm_detection.py b/tests/web_search_engines/rate_limiting/test_llm_detection.pynew file mode 100644index 0000000000..9acaa595ea--- /dev/null+++ b/tests/web_search_engines/rate_limiting/test_llm_detection.py@@ -0,0 +1,203 @@+"""Tests for LLM rate limit error detection and retry-after extraction.++Tests cover:+- is_llm_rate_limit_error: HTTP 429 detection, message pattern matching,+ exception type detection, provider-specific error handling+- extract_retry_after: header parsing, regex extraction from error messages+"""++import types++import pytest++from local_deep_research.web_search_engines.rate_limiting.llm.detection import (+ extract_retry_after,+ is_llm_rate_limit_error,+)+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _exc_with_response(status_code, headers=None):+ """Build an Exception whose .response has a status_code and headers."""+ exc = Exception("http error")+ resp = types.SimpleNamespace(status_code=status_code)+ if headers is not None:+ resp.headers = headers+ exc.response = resp+ return exc+++def _exc_with_type(type_name, msg="error", module="builtins"):+ """Build an exception whose __class__.__name__ and __module__ are set."""+ cls = type(type_name, (Exception,), {})+ cls.__module__ = module+ return cls(msg)+++# ===================================================================+# is_llm_rate_limit_error+# ===================================================================+++class TestIsLLMRateLimitError:+ """Tests for is_llm_rate_limit_error()."""++ # -- HTTP 429 detection ---------------------------------------------++ def test_http_429_returns_true(self):+ exc = _exc_with_response(429)+ assert is_llm_rate_limit_error(exc) is True++ def test_http_200_returns_false(self):+ exc = _exc_with_response(200)+ assert is_llm_rate_limit_error(exc) is False++ def test_http_500_returns_false(self):+ exc = _exc_with_response(500)+ assert is_llm_rate_limit_error(exc) is False++ # -- message-based detection ----------------------------------------++ @pytest.mark.parametrize(+ "msg",+ [+ "Rate limit exceeded",+ "rate_limit_error: too many tokens",+ "RateLimit hit for model",+ "Too many requests, please slow down",+ "Quota exceeded for this month",+ "quota has been exhausted",+ "Resource has been exhausted",+ "Error 429: too many requests",+ "Request threshold reached",+ "Please try again later",+ "Slow down, you're sending too fast",+ ],+ )+ def test_known_rate_limit_messages(self, msg):+ assert is_llm_rate_limit_error(Exception(msg)) is True++ def test_generic_error_returns_false(self):+ assert is_llm_rate_limit_error(Exception("connection refused")) is False++ def test_empty_message_returns_false(self):+ assert is_llm_rate_limit_error(Exception("")) is False++ # -- exception type detection ---------------------------------------++ def test_ratelimiterror_type_detected(self):+ exc = _exc_with_type("RateLimitError", msg="nope")+ assert is_llm_rate_limit_error(exc) is True++ def test_quotaexceedederror_type_detected(self):+ exc = _exc_with_type("QuotaExceededError", msg="nope")+ assert is_llm_rate_limit_error(exc) is True++ def test_valueerror_type_not_detected(self):+ assert is_llm_rate_limit_error(ValueError("bad value")) is False++ # -- OpenAI-specific detection --------------------------------------++ def test_openai_ratelimiterror_with_429(self):+ exc = _exc_with_type(+ "RateLimitError", msg="Error code: 429", module="openai"+ )+ assert is_llm_rate_limit_error(exc) is True++ def test_openai_apierror_with_429(self):+ exc = _exc_with_type("APIError", msg="status 429", module="openai")+ assert is_llm_rate_limit_error(exc) is True++ def test_openai_apierror_without_429(self):+ exc = _exc_with_type("APIError", msg="invalid api key", module="openai")+ assert is_llm_rate_limit_error(exc) is False++ # -- Anthropic-specific detection -----------------------------------++ def test_anthropic_rate_limit(self):+ exc = _exc_with_type(+ "RateLimitError", msg="rate_limit reached", module="anthropic"+ )+ assert is_llm_rate_limit_error(exc) is True++ def test_anthropic_429(self):+ exc = _exc_with_type("APIError", msg="429 too many", module="anthropic")+ assert is_llm_rate_limit_error(exc) is True++ def test_anthropic_too_many(self):+ exc = _exc_with_type(+ "APIError", msg="too many requests", module="anthropic._errors"+ )+ assert is_llm_rate_limit_error(exc) is True++ def test_anthropic_unrelated_error(self):+ exc = _exc_with_type(+ "AuthenticationError", msg="invalid key", module="anthropic"+ )+ assert is_llm_rate_limit_error(exc) is False++ # -- no response attribute -----------------------------------------++ def test_plain_exception_no_response(self):+ """Exception without .response attribute doesn't crash."""+ assert is_llm_rate_limit_error(RuntimeError("oops")) is False+++# ===================================================================+# extract_retry_after+# ===================================================================+++class TestExtractRetryAfter:+ """Tests for extract_retry_after()."""++ # -- Retry-After header --------------------------------------------++ def test_retry_after_header_integer(self):+ exc = _exc_with_response(429, headers={"Retry-After": "30"})+ assert extract_retry_after(exc) == 30.0++ def test_retry_after_header_float(self):+ exc = _exc_with_response(429, headers={"Retry-After": "2.5"})+ assert extract_retry_after(exc) == 2.5++ def test_retry_after_header_non_numeric(self):+ exc = _exc_with_response(+ 429, headers={"Retry-After": "Wed, 21 Oct 2025"}+ )+ assert extract_retry_after(exc) == 0++ def test_retry_after_header_missing(self):+ exc = _exc_with_response(429, headers={})+ assert extract_retry_after(exc) == 0++ # -- message pattern extraction ------------------------------------++ def test_try_again_in_seconds(self):+ exc = Exception("Please try again in 15 seconds")+ assert extract_retry_after(exc) == 15.0++ def test_retry_after_seconds(self):+ exc = Exception("Retry after 3.5 seconds before next request")+ assert extract_retry_after(exc) == 3.5++ def test_wait_seconds(self):+ exc = Exception("Please wait 60 seconds")+ assert extract_retry_after(exc) == 60.0++ def test_singular_second(self):+ exc = Exception("try again in 1 second")+ assert extract_retry_after(exc) == 1.0++ def test_no_time_in_message(self):+ exc = Exception("rate limit exceeded")+ assert extract_retry_after(exc) == 0++ # -- no response attribute -----------------------------------------++ def test_plain_exception_returns_zero(self):+ assert extract_retry_after(ValueError("bad")) == 0diff --git a/tests/web_search_engines/rate_limiting/test_llm_wrapper_pure_logic.py b/tests/web_search_engines/rate_limiting/test_llm_wrapper_pure_logic.pynew file mode 100644index 0000000000..e09e0a76a0--- /dev/null+++ b/tests/web_search_engines/rate_limiting/test_llm_wrapper_pure_logic.py@@ -0,0 +1,174 @@+"""Tests for pure logic in the LLM rate limit wrapper.++Tests cover:+- _check_if_local_model: provider name matching, base_url localhost detection+- _get_rate_limit_key: provider-url-model composite key building, URL+ parsing, model name cleaning+"""++import types++import pytest++from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (+ create_rate_limited_llm_wrapper,+)+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_llm(**attrs):+ """Build a simple namespace that acts as an LLM with given attributes."""+ return types.SimpleNamespace(**attrs)+++def _wrapper(llm=None, provider=None):+ """Build a RateLimitedLLMWrapper (rate limiting disabled by default)."""+ if llm is None:+ llm = _make_llm()+ return create_rate_limited_llm_wrapper(llm, provider=provider)+++# ===================================================================+# _check_if_local_model+# ===================================================================+++class TestCheckIfLocalModel:+ """Tests for RateLimitedLLMWrapper._check_if_local_model()."""++ # -- provider name matching ----------------------------------------++ @pytest.mark.parametrize(+ "provider",+ ["ollama", "lmstudio", "llamacpp", "vllm", "local", "none"],+ )+ def test_local_providers_detected(self, provider):+ w = _wrapper(provider=provider)+ assert w._check_if_local_model() is True++ @pytest.mark.parametrize(+ "provider",+ ["Ollama", "LMSTUDIO", "LlamaCpp", "VLLM", "LOCAL", "NONE"],+ )+ def test_local_providers_case_insensitive(self, provider):+ w = _wrapper(provider=provider)+ assert w._check_if_local_model() is True++ @pytest.mark.parametrize("provider", ["openai", "anthropic", "google"])+ def test_cloud_providers_not_local(self, provider):+ w = _wrapper(provider=provider)+ assert w._check_if_local_model() is False++ def test_none_provider_with_remote_url(self):+ llm = _make_llm(base_url="https://api.openai.com/v1")+ w = _wrapper(llm=llm, provider=None)+ assert w._check_if_local_model() is False++ # -- base_url localhost detection ----------------------------------++ def test_localhost_url_detected(self):+ llm = _make_llm(base_url="http://localhost:11434")+ w = _wrapper(llm=llm, provider="unknown")+ assert w._check_if_local_model() is True++ def test_127_0_0_1_url_detected(self):+ llm = _make_llm(base_url="http://127.0.0.1:8000")+ w = _wrapper(llm=llm, provider="unknown")+ assert w._check_if_local_model() is True++ def test_0_0_0_0_url_detected(self):+ llm = _make_llm(base_url="http://0.0.0.0:5000")+ w = _wrapper(llm=llm, provider="unknown")+ assert w._check_if_local_model() is True++ def test_remote_url_not_detected(self):+ llm = _make_llm(base_url="https://api.anthropic.com")+ w = _wrapper(llm=llm, provider="unknown")+ assert w._check_if_local_model() is False++ def test_no_base_url_attribute(self):+ llm = _make_llm()+ w = _wrapper(llm=llm, provider="unknown")+ assert w._check_if_local_model() is False+++# ===================================================================+# _get_rate_limit_key+# ===================================================================+++class TestGetRateLimitKey:+ """Tests for RateLimitedLLMWrapper._get_rate_limit_key()."""++ def test_basic_key_structure(self):+ llm = _make_llm(+ base_url="https://api.openai.com/v1",+ model_name="gpt-4",+ )+ w = _wrapper(llm=llm, provider="openai")+ key = w._get_rate_limit_key()+ assert key == "openai-api.openai.com-gpt-4"++ def test_unknown_provider_fallback(self):+ llm = _make_llm(base_url="https://example.com", model_name="test")+ w = _wrapper(llm=llm, provider=None)+ key = w._get_rate_limit_key()+ assert key.startswith("unknown-")++ def test_unknown_url_fallback(self):+ llm = _make_llm(model_name="test-model")+ w = _wrapper(llm=llm, provider="openai")+ key = w._get_rate_limit_key()+ assert key == "openai-unknown-test-model"++ def test_unknown_model_fallback(self):+ llm = _make_llm(base_url="https://api.openai.com/v1")+ w = _wrapper(llm=llm, provider="openai")+ key = w._get_rate_limit_key()+ assert key == "openai-api.openai.com-unknown"++ def test_model_name_slashes_replaced(self):+ llm = _make_llm(model_name="meta/llama-3/70b")+ w = _wrapper(llm=llm, provider="ollama")+ key = w._get_rate_limit_key()+ assert "meta-llama-3-70b" in key++ def test_model_name_colons_replaced(self):+ llm = _make_llm(model_name="llama3:latest")+ w = _wrapper(llm=llm, provider="ollama")+ key = w._get_rate_limit_key()+ assert "llama3-latest" in key++ def test_model_attr_fallback_to_model(self):+ """Falls back from model_name to model attribute."""+ llm = _make_llm(model="claude-3-opus")+ w = _wrapper(llm=llm, provider="anthropic")+ key = w._get_rate_limit_key()+ assert "claude-3-opus" in key++ def test_url_trailing_slash_stripped(self):+ llm = _make_llm(+ base_url="https://api.openai.com/v1/",+ model_name="gpt-4",+ )+ w = _wrapper(llm=llm, provider="openai")+ key = w._get_rate_limit_key()+ # netloc is api.openai.com, path /v1/ is stripped to get netloc+ assert "api.openai.com" in key++ def test_client_base_url_fallback(self):+ """Falls back to _client.base_url when base_url absent."""+ client = types.SimpleNamespace(base_url="https://api.example.com")+ llm = _make_llm(_client=client, model_name="test")+ w = _wrapper(llm=llm, provider="custom")+ key = w._get_rate_limit_key()+ assert "api.example.com" in key++ def test_all_unknown(self):+ llm = _make_llm()+ w = _wrapper(llm=llm, provider=None)+ assert w._get_rate_limit_key() == "unknown-unknown-unknown"