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.

test: add 92 coverage tests for data_sanitizer and log_sanitizer (#2891)

LearningCircuit5f7a1119112e
diff --git a/tests/security/test_sanitizer_coverage.py b/tests/security/test_sanitizer_coverage.py
new file mode 100644
index 0000000000..4630c0acee
--- /dev/null
+++ b/tests/security/test_sanitizer_coverage.py
@@ -0,0 +1,562 @@
+"""Comprehensive coverage tests for data_sanitizer and log_sanitizer modules.
+
+Module 1 -- data_sanitizer:
+ DataSanitizer.sanitize, DataSanitizer.redact, sanitize_data, redact_data,
+ filter_research_metadata, strip_settings_snapshot
+
+Module 2 -- log_sanitizer:
+ strip_control_chars, sanitize_for_log
+"""
+
+import json
+
+import pytest
+
+from local_deep_research.security.data_sanitizer import (
+ DataSanitizer,
+ filter_research_metadata,
+ redact_data,
+ sanitize_data,
+ strip_settings_snapshot,
+)
+from local_deep_research.security.log_sanitizer import (
+ sanitize_for_log,
+ strip_control_chars,
+)
+
+
+# ===================================================================
+# DataSanitizer.sanitize
+# ===================================================================
+
+
+class TestSanitizeNestedDicts:
+ """sanitize removes sensitive keys inside deeply nested dicts."""
+
+ def test_two_levels_deep(self):
+ data = {"outer": {"api_key": "abc", "safe": 1}}
+ result = DataSanitizer.sanitize(data)
+ assert result == {"outer": {"safe": 1}}
+
+ def test_three_levels_deep(self):
+ data = {"a": {"b": {"password": "pw", "x": 9}}}
+ result = DataSanitizer.sanitize(data)
+ assert result == {"a": {"b": {"x": 9}}}
+
+ def test_multiple_sensitive_keys_at_different_depths(self):
+ data = {
+ "secret": "top",
+ "level1": {
+ "refresh_token": "tok",
+ "level2": {"private_key": "pk", "ok": True},
+ },
+ }
+ result = DataSanitizer.sanitize(data)
+ assert result == {"level1": {"level2": {"ok": True}}}
+
+
+class TestSanitizeLists:
+ """sanitize recurses into lists and sanitizes dicts inside them."""
+
+ def test_list_of_dicts(self):
+ data = [{"api_key": "k", "id": 1}, {"password": "p", "id": 2}]
+ result = DataSanitizer.sanitize(data)
+ assert result == [{"id": 1}, {"id": 2}]
+
+ def test_empty_list(self):
+ assert DataSanitizer.sanitize([]) == []
+
+ def test_list_of_primitives_unchanged(self):
+ data = [1, "hello", None, True]
+ assert DataSanitizer.sanitize(data) == [1, "hello", None, True]
+
+
+class TestSanitizeSensitiveKeyRemoval:
+ """Verify all default sensitive keys are removed."""
+
+ @pytest.mark.parametrize(
+ "key", sorted(DataSanitizer.DEFAULT_SENSITIVE_KEYS)
+ )
+ def test_each_default_key_removed(self, key):
+ data = {key: "value", "keep_me": 42}
+ result = DataSanitizer.sanitize(data)
+ assert key not in result
+ assert result["keep_me"] == 42
+
+
+class TestSanitizeCaseInsensitive:
+ """sanitize matches keys case-insensitively."""
+
+ def test_uppercase_key(self):
+ data = {"API_KEY": "secret", "name": "ok"}
+ result = DataSanitizer.sanitize(data)
+ assert "API_KEY" not in result
+ assert result == {"name": "ok"}
+
+ def test_mixed_case_key(self):
+ data = {"PaSsWoRd": "secret", "name": "ok"}
+ result = DataSanitizer.sanitize(data)
+ assert "PaSsWoRd" not in result
+
+ def test_title_case_key(self):
+ data = {"Access_Token": "tok", "status": "active"}
+ result = DataSanitizer.sanitize(data)
+ assert "Access_Token" not in result
+ assert result == {"status": "active"}
+
+
+class TestSanitizeJsonStringInput:
+ """sanitize treats a JSON string as a primitive -- it is NOT parsed."""
+
+ def test_json_string_returned_as_is(self):
+ json_str = json.dumps({"api_key": "secret"})
+ result = DataSanitizer.sanitize(json_str)
+ assert result == json_str
+
+ def test_json_array_string_returned_as_is(self):
+ json_str = json.dumps([{"password": "pw"}])
+ assert DataSanitizer.sanitize(json_str) == json_str
+
+
+class TestSanitizeCustomKeys:
+ """sanitize accepts a custom set of sensitive keys."""
+
+ def test_custom_keys_only(self):
+ data = {"my_token": "t", "api_key": "k", "name": "n"}
+ result = DataSanitizer.sanitize(data, sensitive_keys={"my_token"})
+ assert "my_token" not in result
+ assert "api_key" in result # not in custom set
+
+ def test_empty_custom_keys_removes_nothing(self):
+ data = {"api_key": "k", "password": "p"}
+ result = DataSanitizer.sanitize(data, sensitive_keys=set())
+ assert result == data
+
+
+# ===================================================================
+# DataSanitizer.redact
+# ===================================================================
+
+
+class TestRedactBasic:
+ """redact replaces sensitive values with placeholder text."""
+
+ def test_default_redaction_text(self):
+ data = {"api_key": "secret123", "name": "ok"}
+ result = DataSanitizer.redact(data)
+ assert result["api_key"] == "[REDACTED]"
+ assert result["name"] == "ok"
+
+ def test_key_preserved_value_replaced(self):
+ data = {"password": "mypass"}
+ result = DataSanitizer.redact(data)
+ assert "password" in result
+ assert result["password"] == "[REDACTED]"
+
+
+class TestRedactCustomText:
+ """redact accepts custom redaction placeholder text."""
+
+ def test_custom_redaction_text(self):
+ data = {"api_key": "secret", "name": "ok"}
+ result = DataSanitizer.redact(data, redaction_text="***")
+ assert result["api_key"] == "***"
+ assert result["name"] == "ok"
+
+ def test_empty_string_redaction_text(self):
+ data = {"secret": "val"}
+ result = DataSanitizer.redact(data, redaction_text="")
+ assert result["secret"] == ""
+
+ def test_long_redaction_text(self):
+ text = "SENSITIVE DATA REMOVED BY SECURITY FILTER"
+ data = {"password": "pw"}
+ result = DataSanitizer.redact(data, redaction_text=text)
+ assert result["password"] == text
+
+
+class TestRedactNestedStructures:
+ """redact recurses into nested dicts and lists."""
+
+ def test_nested_dict(self):
+ data = {"config": {"auth_token": "tok", "host": "localhost"}}
+ result = DataSanitizer.redact(data)
+ assert result["config"]["auth_token"] == "[REDACTED]"
+ assert result["config"]["host"] == "localhost"
+
+ def test_list_of_dicts(self):
+ data = [{"session_token": "s1"}, {"csrf_token": "c1"}]
+ result = DataSanitizer.redact(data)
+ assert result[0]["session_token"] == "[REDACTED]"
+ assert result[1]["csrf_token"] == "[REDACTED]"
+
+ def test_dict_in_list_in_dict(self):
+ data = {"items": [{"private_key": "pk", "id": 1}]}
+ result = DataSanitizer.redact(data)
+ assert result["items"][0]["private_key"] == "[REDACTED]"
+ assert result["items"][0]["id"] == 1
+
+ def test_original_data_not_mutated(self):
+ data = {"api_key": "original_value", "name": "ok"}
+ DataSanitizer.redact(data)
+ assert data["api_key"] == "original_value"
+
+
+class TestRedactCaseInsensitive:
+ """redact matches keys case-insensitively."""
+
+ def test_uppercase_key_redacted(self):
+ data = {"SECRET": "val"}
+ result = DataSanitizer.redact(data)
+ assert result["SECRET"] == "[REDACTED]"
+
+ def test_mixed_case_key_redacted(self):
+ data = {"Apikey": "val", "name": "ok"}
+ result = DataSanitizer.redact(data)
+ assert result["Apikey"] == "[REDACTED]"
+ assert result["name"] == "ok"
+
+
+# ===================================================================
+# sanitize_data wrapper
+# ===================================================================
+
+
+class TestSanitizeDataWrapper:
+ """sanitize_data convenience function delegates to DataSanitizer.sanitize."""
+
+ def test_removes_default_sensitive_keys(self):
+ data = {"api_key": "k", "name": "n"}
+ result = sanitize_data(data)
+ assert result == {"name": "n"}
+
+ def test_accepts_custom_sensitive_keys(self):
+ data = {"custom_field": "v", "api_key": "k"}
+ result = sanitize_data(data, sensitive_keys={"custom_field"})
+ assert "custom_field" not in result
+ assert "api_key" in result
+
+ def test_primitive_passthrough(self):
+ assert sanitize_data(99) == 99
+ assert sanitize_data(None) is None
+
+
+# ===================================================================
+# redact_data wrapper
+# ===================================================================
+
+
+class TestRedactDataWrapper:
+ """redact_data convenience function delegates to DataSanitizer.redact."""
+
+ def test_redacts_default_sensitive_keys(self):
+ data = {"password": "pw", "name": "n"}
+ result = redact_data(data)
+ assert result["password"] == "[REDACTED]"
+ assert result["name"] == "n"
+
+ def test_accepts_custom_keys_and_text(self):
+ data = {"my_key": "v", "password": "pw"}
+ result = redact_data(
+ data, sensitive_keys={"my_key"}, redaction_text="XXX"
+ )
+ assert result["my_key"] == "XXX"
+ assert result["password"] == "pw"
+
+ def test_primitive_passthrough(self):
+ assert redact_data("hello") == "hello"
+ assert redact_data(None) is None
+
+
+# ===================================================================
+# filter_research_metadata
+# ===================================================================
+
+
+class TestFilterResearchMetadata:
+ """filter_research_metadata extracts only safe allowlisted fields."""
+
+ def test_extracts_is_news_search_true(self):
+ result = filter_research_metadata(
+ {"is_news_search": True, "extra": "x"}
+ )
+ assert result == {"is_news_search": True}
+ assert "extra" not in result
+
+ def test_extracts_is_news_search_false(self):
+ result = filter_research_metadata({"is_news_search": False})
+ assert result == {"is_news_search": False}
+
+ def test_missing_is_news_search_defaults_false(self):
+ result = filter_research_metadata({"some_other_key": 123})
+ assert result == {"is_news_search": False}
+
+ def test_none_input(self):
+ result = filter_research_metadata(None)
+ assert result == {"is_news_search": False}
+
+ def test_json_string_input_dict(self):
+ meta_json = json.dumps(
+ {"is_news_search": True, "settings_snapshot": {}}
+ )
+ result = filter_research_metadata(meta_json)
+ assert result == {"is_news_search": True}
+ assert "settings_snapshot" not in result
+
+ def test_json_string_input_false(self):
+ meta_json = json.dumps({"is_news_search": False})
+ result = filter_research_metadata(meta_json)
+ assert result == {"is_news_search": False}
+
+ def test_invalid_json_string(self):
+ result = filter_research_metadata("{bad json!!!")
+ assert result == {"is_news_search": False}
+
+ def test_integer_input_returns_default(self):
+ result = filter_research_metadata(42)
+ assert result == {"is_news_search": False}
+
+ def test_is_news_search_truthy_int_coerced(self):
+ """Non-zero int is truthy, coerced to True via bool()."""
+ result = filter_research_metadata({"is_news_search": 1})
+ assert result["is_news_search"] is True
+ assert type(result["is_news_search"]) is bool
+
+ def test_settings_snapshot_never_leaks(self):
+ meta = {
+ "is_news_search": False,
+ "settings_snapshot": {"api_key": "SUPER_SECRET"},
+ }
+ result = filter_research_metadata(meta)
+ assert "settings_snapshot" not in result
+
+
+# ===================================================================
+# strip_settings_snapshot
+# ===================================================================
+
+
+class TestStripSettingsSnapshot:
+ """strip_settings_snapshot removes settings_snapshot, preserves the rest."""
+
+ def test_removes_settings_snapshot(self):
+ meta = {"phase": "done", "settings_snapshot": {"api_key": "k"}}
+ result = strip_settings_snapshot(meta)
+ assert "settings_snapshot" not in result
+ assert result["phase"] == "done"
+
+ def test_preserves_all_other_keys(self):
+ meta = {
+ "mode": "quick",
+ "duration": 5.2,
+ "is_news_search": True,
+ "settings_snapshot": {},
+ }
+ result = strip_settings_snapshot(meta)
+ assert result == {
+ "mode": "quick",
+ "duration": 5.2,
+ "is_news_search": True,
+ }
+
+ def test_none_input(self):
+ result = strip_settings_snapshot(None)
+ assert result == {}
+
+ def test_string_metadata_json(self):
+ meta_json = json.dumps(
+ {"phase": "complete", "settings_snapshot": {"k": "v"}}
+ )
+ result = strip_settings_snapshot(meta_json)
+ assert result == {"phase": "complete"}
+ assert "settings_snapshot" not in result
+
+ def test_no_settings_snapshot_key_noop(self):
+ meta = {"phase": "done", "duration": 3.0}
+ result = strip_settings_snapshot(meta)
+ assert result == meta
+
+ def test_invalid_json_string_returns_empty(self):
+ result = strip_settings_snapshot("not valid json {{{")
+ assert result == {}
+
+ def test_non_dict_type_returns_empty(self):
+ assert strip_settings_snapshot(123) == {}
+ assert strip_settings_snapshot([1, 2]) == {}
+
+
+# ===================================================================
+# strip_control_chars (log_sanitizer)
+# ===================================================================
+
+
+class TestStripControlCharsComprehensive:
+ """strip_control_chars removes C0/C1 control, zero-width, and format chars."""
+
+ def test_c0_null_and_bell(self):
+ assert strip_control_chars("a\x00b\x07c") == "abc"
+
+ def test_c0_tab_newline_carriage_return(self):
+ assert strip_control_chars("a\tb\nc\rd") == "abcd"
+
+ def test_c1_range(self):
+ """C1 control characters (0x80-0x9F) are stripped."""
+ assert strip_control_chars("a\x80b\x8fc\x9fd") == "abcd"
+
+ def test_del_character(self):
+ """DEL (0x7F) is stripped."""
+ assert strip_control_chars("hello\x7fworld") == "helloworld"
+
+ def test_zero_width_space(self):
+ assert strip_control_chars("hello\u200bworld") == "helloworld"
+
+ def test_zero_width_non_joiner(self):
+ assert strip_control_chars("a\u200cb") == "ab"
+
+ def test_zero_width_joiner(self):
+ assert strip_control_chars("a\u200db") == "ab"
+
+ def test_ltr_rtl_marks(self):
+ assert strip_control_chars("a\u200eb\u200fc") == "abc"
+
+ def test_unicode_format_chars_rlo(self):
+ """Right-to-left override (RLO) is stripped."""
+ assert strip_control_chars("hello\u202eworld") == "helloworld"
+
+ def test_unicode_embedding_chars(self):
+ """LRE, RLE, PDF, LRO are stripped."""
+ assert strip_control_chars("\u202a\u202b\u202c\u202dtext") == "text"
+
+ def test_bom_stripped(self):
+ assert strip_control_chars("\ufeffhello") == "hello"
+
+ def test_word_joiner_stripped(self):
+ assert strip_control_chars("a\u2060b") == "ab"
+
+ def test_arabic_letter_mark_stripped(self):
+ assert strip_control_chars("a\u061cb") == "ab"
+
+ def test_isolate_chars_stripped(self):
+ """LRI, RLI, FSI, PDI are stripped."""
+ assert strip_control_chars("\u2066\u2067\u2068\u2069text") == "text"
+
+ def test_preserves_valid_unicode(self):
+ assert (
+ strip_control_chars("cafe\u0301") == "cafe\u0301"
+ ) # e-acute combining
+
+ def test_preserves_emoji(self):
+ result = strip_control_chars("hello world")
+ assert result == "hello world"
+
+ def test_preserves_cjk(self):
+ assert strip_control_chars("test") == "test"
+
+ def test_empty_string(self):
+ assert strip_control_chars("") == ""
+
+ def test_all_control_chars_yields_empty(self):
+ assert strip_control_chars("\x00\x01\x02\x7f\x80") == ""
+
+
+# ===================================================================
+# sanitize_for_log (log_sanitizer)
+# ===================================================================
+
+
+class TestSanitizeForLogTruncation:
+ """sanitize_for_log truncates with '...' suffix when exceeding max_length."""
+
+ def test_long_string_truncated_with_ellipsis(self):
+ result = sanitize_for_log("a" * 100, max_length=50)
+ assert result == "a" * 47 + "..."
+ assert len(result) == 50
+
+ def test_default_max_length_50(self):
+ result = sanitize_for_log("b" * 200)
+ assert len(result) == 50
+ assert result.endswith("...")
+
+ def test_exact_max_length_no_truncation(self):
+ result = sanitize_for_log("c" * 50, max_length=50)
+ assert result == "c" * 50
+ assert "..." not in result
+
+ def test_shorter_than_max_no_truncation(self):
+ result = sanitize_for_log("short", max_length=50)
+ assert result == "short"
+
+
+class TestSanitizeForLogMaxLengthEdgeCases:
+ """Edge-case max_length values: 0, 1, 3, 50."""
+
+ def test_max_length_zero(self):
+ """max_length=0 returns empty string (no room for anything)."""
+ result = sanitize_for_log("hello", max_length=0)
+ assert result == ""
+
+ def test_max_length_one(self):
+ """max_length=1 -- too short for '...' so just truncates."""
+ result = sanitize_for_log("hello", max_length=1)
+ assert len(result) <= 1
+ assert result == "h"
+
+ def test_max_length_three(self):
+ """max_length=3 -- exactly the length of '...', uses raw truncation."""
+ result = sanitize_for_log("hello", max_length=3)
+ assert len(result) <= 3
+ assert result == "hel"
+
+ def test_max_length_four_uses_ellipsis(self):
+ """max_length=4 -- enough room for 1 char + '...'."""
+ result = sanitize_for_log("hello world", max_length=4)
+ assert result == "h..."
+ assert len(result) == 4
+
+ def test_max_length_50_default(self):
+ result = sanitize_for_log("x" * 60, max_length=50)
+ assert len(result) == 50
+ assert result == "x" * 47 + "..."
+
+
+class TestSanitizeForLogEmptyString:
+ """sanitize_for_log on empty input."""
+
+ def test_empty_string_returns_empty(self):
+ assert sanitize_for_log("") == ""
+
+ def test_empty_string_with_explicit_max_length(self):
+ assert sanitize_for_log("", max_length=10) == ""
+
+
+class TestSanitizeForLogControlCharsAndTruncation:
+ """Control chars are stripped BEFORE truncation is applied."""
+
+ def test_control_chars_removed_then_truncated(self):
+ # 10 visible chars + control chars = still only 10 visible after strip
+ raw = "abcde\x00\x01\x02fghij"
+ result = sanitize_for_log(raw, max_length=50)
+ assert result == "abcdefghij"
+
+ def test_control_chars_reduce_length_below_max(self):
+ """After stripping, string may become shorter than max_length."""
+ raw = "\x00\x01\x02abc"
+ result = sanitize_for_log(raw, max_length=50)
+ assert result == "abc"
+
+ def test_control_chars_stripped_still_needs_truncation(self):
+ """Even after stripping, result may still exceed max_length."""
+ raw = "a" * 40 + "\x00" * 5 + "b" * 40
+ result = sanitize_for_log(raw, max_length=50)
+ # After strip: 80 visible chars, needs truncation to 50
+ assert len(result) == 50
+ assert result.endswith("...")
+
+ def test_all_control_chars_yields_empty(self):
+ result = sanitize_for_log("\x00\x01\x7f", max_length=50)
+ assert result == ""
+
+ def test_unicode_preserved_controls_stripped(self):
+ raw = "cafe\u0301\x00\x07 world"
+ result = sanitize_for_log(raw, max_length=50)
+ assert result == "cafe\u0301 world"
diff --git a/tests/utilities/test_json_utils_coverage.py b/tests/utilities/test_json_utils_coverage.py
index 872b3773a1..f0f70845e0 100644
--- a/tests/utilities/test_json_utils_coverage.py
+++ b/tests/utilities/test_json_utils_coverage.py
@@ -1,18 +1,16 @@
-"""Comprehensive coverage tests for json_utils.py.
-
-Targets edge cases and code paths not covered by existing test files:
-- get_llm_response_text: text=None fallthrough, non-string .text, objects with neither attr
-- extract_json: cleaning pipeline ordering, artifact cleaning after bracket extraction,
- multiple bracket pairs, expected_type interactions with cleaning
-- _remove_think_tags: multiple think blocks, nested tags, adjacent tags, whitespace handling
-- _strip_code_fences: multiple ```json blocks, ```json without closing, edge split behavior
-- _extract_by_brackets: same-position brackets, single char between brackets
-- _clean_llm_json_artifacts: combined artifacts, edge regex patterns, trailing ellipsis
+"""Comprehensive coverage tests for json_utils and type_utils.
+
+Tests every public and private function in:
+- local_deep_research.utilities.json_utils
+- local_deep_research.utilities.type_utils
+
+Pure-function tests -- no complex mocks required.
"""
import json
from unittest.mock import MagicMock
+import pytest
from local_deep_research.utilities.json_utils import (
_clean_llm_json_artifacts,
@@ -22,858 +20,480 @@ from local_deep_research.utilities.json_utils import (
extract_json,
get_llm_response_text,
)
+from local_deep_research.utilities.type_utils import to_bool
-
-# ---------------------------------------------------------------------------
-# get_llm_response_text — coverage gaps
-# ---------------------------------------------------------------------------
+MODULE_JSON = "local_deep_research.utilities.json_utils"
+MODULE_TYPE = "local_deep_research.utilities.type_utils"
-class TestGetLlmResponseTextCoverage:
- """Cover paths in get_llm_response_text not hit by existing tests."""
+# ===================================================================
+# get_llm_response_text
+# ===================================================================
- def test_text_attribute_none_falls_to_str(self):
- """When .content is absent and .text is None, falls through to str()."""
- obj = MagicMock(spec=[])
- obj.text = None
- result = get_llm_response_text(obj)
- # Falls through both branches to str(response)
- assert isinstance(result, str)
- def test_object_without_content_or_text(self):
- """Object with neither .content nor .text uses str()."""
+class TestGetLlmResponseText:
+ """Cover .content, .text, str() fallback, think-tag removal, None."""
- class Bare:
- pass
+ def test_content_attribute_string(self):
+ obj = MagicMock()
+ obj.content = "hello from content"
+ assert get_llm_response_text(obj) == "hello from content"
- obj = Bare()
+ def test_text_attribute_string(self):
+ """Falls to .text when .content is absent."""
+ obj = MagicMock(spec=[]) # spec=[] -> no .content
+ obj.text = "hello from text"
result = get_llm_response_text(obj)
- assert isinstance(result, str)
- # str() of an object includes class name
- assert "Bare" in result
+ assert result == "hello from text"
- def test_non_string_text_attribute_converted(self):
- """Non-string .text attribute is converted via str()."""
- obj = MagicMock(spec=[])
- obj.text = [1, 2, 3]
- result = get_llm_response_text(obj)
- assert isinstance(result, str)
- assert "1" in result
+ def test_plain_string_passthrough(self):
+ assert get_llm_response_text("raw string") == "raw string"
- def test_content_is_empty_list(self):
- """Content that is an empty list (truthy check: empty list is falsy but not None)."""
+ def test_think_tags_removed_from_content(self):
obj = MagicMock()
- obj.content = []
- # [] is not None, so the content branch is taken; [] is not a str, so str([]) = "[]"
- result = get_llm_response_text(obj)
- assert result == "[]"
+ obj.content = "<think>internal reasoning</think>visible answer"
+ assert get_llm_response_text(obj) == "visible answer"
- def test_content_is_dict(self):
- """Content that is a dict gets stringified."""
+ def test_none_returns_empty_string(self):
+ assert get_llm_response_text(None) == ""
+
+ def test_content_none_falls_to_text(self):
+ """When .content is None, the .text branch is tried."""
obj = MagicMock()
- obj.content = {"key": "value"}
+ obj.content = None
+ obj.text = "fallback text"
+ assert get_llm_response_text(obj) == "fallback text"
+
+ def test_text_none_falls_to_str(self):
+ """When both .content and .text are None, str(response) is used."""
+ obj = MagicMock(spec=[])
+ obj.text = None
result = get_llm_response_text(obj)
assert isinstance(result, str)
- assert "key" in result
- def test_content_is_boolean_false(self):
- """Content that is boolean False (not None) — should use it."""
+ def test_non_string_content_converted(self):
+ """Non-string .content is converted via str()."""
obj = MagicMock()
- obj.content = False
- result = get_llm_response_text(obj)
- assert result == "False"
+ obj.content = 12345
+ assert get_llm_response_text(obj) == "12345"
- def test_content_is_zero(self):
- """Content that is integer 0 (not None) — should use it."""
+ def test_integer_input_uses_str(self):
+ assert get_llm_response_text(42) == "42"
+
+ def test_multiple_think_blocks(self):
obj = MagicMock()
- obj.content = 0
- result = get_llm_response_text(obj)
- assert result == "0"
+ obj.content = "<think>a</think>X<think>b</think>Y"
+ assert get_llm_response_text(obj) == "XY"
- def test_plain_integer_input(self):
- """Integer input has no .content or .text, uses str()."""
- result = get_llm_response_text(12345)
- assert result == "12345"
- def test_plain_list_input(self):
- """List input has no .content or .text, uses str()."""
- result = get_llm_response_text([1, 2])
- assert result == "[1, 2]"
+# ===================================================================
+# extract_json
+# ===================================================================
- def test_multiple_think_tags_in_content(self):
- """Multiple think tag blocks in .content are all removed."""
- obj = MagicMock()
- obj.content = "<think>a</think>B<think>c</think>D"
- result = get_llm_response_text(obj)
- assert result == "BD"
- def test_think_tags_in_text_attribute(self):
- """Think tags in .text attribute are removed too."""
- obj = MagicMock(spec=[])
- obj.text = "<think>reasoning</think>answer"
- result = get_llm_response_text(obj)
- assert result == "answer"
+class TestExtractJson:
+ """Cover valid JSON, code-fenced JSON, surrounding text, malformed
+ JSON, expected_type filtering, empty/None inputs."""
- def test_content_with_only_think_tags(self):
- """Content that is entirely think tags results in empty string."""
- obj = MagicMock()
- obj.content = "<think>all reasoning no answer</think>"
- result = get_llm_response_text(obj)
- assert result == ""
+ # --- valid JSON -------------------------------------------------
+ def test_valid_dict(self):
+ assert extract_json('{"a": 1}') == {"a": 1}
-# ---------------------------------------------------------------------------
-# _remove_think_tags — coverage gaps
-# ---------------------------------------------------------------------------
+ def test_valid_list(self):
+ assert extract_json("[1, 2, 3]") == [1, 2, 3]
+ def test_valid_nested(self):
+ text = '{"x": [1, {"y": 2}]}'
+ assert extract_json(text) == {"x": [1, {"y": 2}]}
-class TestRemoveThinkTagsCoverage:
- """Cover edge cases in _remove_think_tags regex processing."""
+ # --- JSON inside code fences ------------------------------------
- def test_multiple_paired_tags(self):
- """Multiple separate paired think blocks."""
- text = "<think>a</think>X<think>b</think>Y"
- assert _remove_think_tags(text) == "XY"
+ def test_json_in_json_fence(self):
+ text = '```json\n{"key": "val"}\n```'
+ assert extract_json(text) == {"key": "val"}
+
+ def test_json_in_plain_fence(self):
+ text = '```\n{"key": "val"}\n```'
+ assert extract_json(text) == {"key": "val"}
+
+ # --- JSON with surrounding prose --------------------------------
+
+ def test_prose_around_dict(self):
+ text = 'Here is the result: {"score": 9} -- done.'
+ assert extract_json(text) == {"score": 9}
+
+ def test_prose_around_list(self):
+ text = "The indices are: [0, 3, 5] as computed."
+ assert extract_json(text, expected_type=list) == [0, 3, 5]
+
+ # --- malformed JSON cleaned up ----------------------------------
+
+ def test_trailing_comma_in_dict(self):
+ text = '{"a": 1, "b": 2,}'
+ assert extract_json(text) == {"a": 1, "b": 2}
+
+ def test_trailing_comma_in_list(self):
+ text = "[1, 2, 3,]"
+ assert extract_json(text) == [1, 2, 3]
+
+ def test_js_line_comments(self):
+ text = '{\n"a": 1, // first\n"b": 2 // second\n}'
+ assert extract_json(text) == {"a": 1, "b": 2}
+
+ def test_ellipsis_entry_removed(self):
+ text = "[1, 2, 3, ...]"
+ assert extract_json(text, expected_type=list) == [1, 2, 3]
- def test_nested_think_tags(self):
- """Nested think tags — outer pair consumed by DOTALL regex."""
- text = "<think>outer<think>inner</think>still outer</think>result"
- result = _remove_think_tags(text)
- # The .*? with DOTALL matches from first <think> to first </think>
- # Then orphaned tags are cleaned up
- assert "result" in result
- assert "<think>" not in result
- assert "</think>" not in result
-
- def test_only_closing_tag(self):
- """Only a closing </think> tag is removed."""
+ # --- expected_type filtering ------------------------------------
+
+ def test_expected_dict_returns_dict(self):
+ assert extract_json('{"k": 1}', expected_type=dict) == {"k": 1}
+
+ def test_expected_list_returns_list(self):
+ assert extract_json("[1]", expected_type=list) == [1]
+
+ def test_expected_list_but_got_dict_falls_to_bracket(self):
+ """Direct parse gives dict; bracket extraction for [] finds inner list."""
+ text = '{"items": [10, 20]}'
+ result = extract_json(text, expected_type=list)
+ assert result == [10, 20]
+
+ def test_expected_dict_but_got_list_returns_none(self):
+ """Plain list when dict expected and no inner dict exists."""
+ assert extract_json("[1, 2]", expected_type=dict) is None
+
+ # --- empty / None -----------------------------------------------
+
+ def test_empty_string(self):
+ assert extract_json("") is None
+
+ def test_whitespace_only(self):
+ assert extract_json(" \n\t ") is None
+
+ def test_none_input(self):
+ assert extract_json(None) is None
+
+ # --- scalar JSON values are not returned ------------------------
+
+ def test_scalar_number(self):
+ assert extract_json("42") is None
+
+ def test_scalar_string(self):
+ assert extract_json('"hello"') is None
+
+ def test_scalar_bool(self):
+ assert extract_json("true") is None
+
+ def test_scalar_null(self):
+ assert extract_json("null") is None
+
+ # --- deepseek-style think+fence pattern -------------------------
+
+ def test_think_then_fence(self):
+ text = '<think>reasoning</think>\n```json\n{"answer": "yes"}\n```'
+ assert extract_json(text) == {"answer": "yes"}
+
+ # --- completely invalid text ------------------------------------
+
+ def test_no_json_at_all(self):
+ assert extract_json("Hello, this is plain text.") is None
+
+ def test_brackets_with_garbage(self):
+ assert extract_json("{not json at all!}") is None
+
+
+# ===================================================================
+# _remove_think_tags
+# ===================================================================
+
+
+class TestRemoveThinkTags:
+ """Paired tags, orphaned tags, no tags, empty input."""
+
+ def test_paired_tags_removed(self):
+ assert _remove_think_tags("<think>x</think>y") == "y"
+
+ def test_multiline_content_removed(self):
+ text = "<think>\nline1\nline2\n</think>result"
+ assert _remove_think_tags(text) == "result"
+
+ def test_orphaned_closing_tag(self):
assert _remove_think_tags("before</think>after") == "beforeafter"
- def test_only_opening_tag(self):
- """Only an opening <think> tag is removed."""
+ def test_orphaned_opening_tag(self):
assert _remove_think_tags("before<think>after") == "beforeafter"
- def test_multiple_orphaned_closing_tags(self):
- """Multiple orphaned closing tags."""
- text = "</think>A</think>B</think>C"
- result = _remove_think_tags(text)
- assert result == "ABC"
-
- def test_think_tags_with_whitespace_inside(self):
- """Think tags with leading/trailing whitespace inside."""
- text = "<think> \n reasoning \n </think>answer"
- result = _remove_think_tags(text)
- assert result == "answer"
-
- def test_empty_think_tags(self):
- """Empty <think></think> tags."""
- text = "<think></think>content"
- result = _remove_think_tags(text)
- assert result == "content"
-
- def test_think_tags_case_sensitive(self):
- """Think tags are case-sensitive — <THINK> is not removed."""
- text = "<THINK>loud</THINK>quiet"
- result = _remove_think_tags(text)
- assert "<THINK>" in result
-
- def test_think_tag_at_end_of_string(self):
- """Think tag at the very end."""
- text = "content<think>trailing"
- result = _remove_think_tags(text)
- assert "content" in result
- assert "<think>" not in result
-
- def test_whitespace_only_after_removal(self):
- """Result is whitespace-only after think tag removal — stripped to empty."""
- text = "<think>everything</think> "
- result = _remove_think_tags(text)
- assert result == ""
-
- def test_think_tags_with_special_chars_inside(self):
- """Think tags containing JSON-like content inside."""
- text = '<think>{"reasoning": true}</think>{"answer": 42}'
- result = _remove_think_tags(text)
- assert result == '{"answer": 42}'
-
-
-# ---------------------------------------------------------------------------
-# _strip_code_fences — coverage gaps
-# ---------------------------------------------------------------------------
-
-
-class TestStripCodeFencesCoverage:
- """Cover edge cases in _strip_code_fences split logic."""
-
- def test_json_fence_no_closing_fence(self):
- """```json without closing ``` — split("```")[0] returns everything."""
- text = '```json\n{"key": "value"}'
- result = _strip_code_fences(text)
- # split("```json") -> ['', '\n{"key": "value"}']
- # parts[1].split("```")[0] -> '\n{"key": "value"}'
- assert '{"key": "value"}' in result
+ def test_no_tags(self):
+ assert _remove_think_tags("no tags here") == "no tags here"
- def test_json_fence_empty_content(self):
- """```json with empty content."""
- text = "```json\n\n```"
- result = _strip_code_fences(text)
- assert result == ""
+ def test_empty_string(self):
+ assert _remove_think_tags("") == ""
- def test_bare_fence_with_only_two_backtick_groups(self):
- """Only two ``` markers — fewer than 3 parts from split, returns original."""
- text = "some text ``` more text"
- result = _strip_code_fences(text)
- # split("```") gives ['some text ', ' more text'] — len < 3
- assert result == text
+ def test_multiple_paired_blocks(self):
+ text = "<think>a</think>X<think>b</think>Y"
+ assert _remove_think_tags(text) == "XY"
- def test_json_fence_with_extra_whitespace(self):
- """```json fence with extra whitespace around content."""
- text = '```json\n\n {"key": "value"} \n\n```'
- result = _strip_code_fences(text)
- assert result == '{"key": "value"}'
+ def test_only_think_tags_returns_empty(self):
+ assert _remove_think_tags("<think>all gone</think>") == ""
- def test_json_fence_preferred_over_bare(self):
- """```json fence is checked before bare ``` fence."""
- text = '```\nbare content\n```\n```json\n{"json": true}\n```'
- result = _strip_code_fences(text)
- # "```json" is found first in the elif, but actually "```json" is checked
- # first in the if branch — yes, ```json is checked first
- # The text contains "```json", so the if branch handles it
- # split("```json") -> ['```\nbare content\n```\n', '\n{"json": true}\n```']
- assert '{"json": true}' in result
-
- def test_code_fence_with_language_tag_not_json(self):
- """```python — no ```json match, falls to bare ``` path."""
- text = '```python\nx = {"key": "val"}\n```'
- result = _strip_code_fences(text)
- # split("```") gives ['', 'python\nx = {"key": "val"}\n', '']
- # parts[1] = 'python\nx = {"key": "val"}\n'
- assert "python" in result
- assert '"key"' in result
-
- def test_multiple_json_fences_first_wins(self):
- """Multiple ```json fences — first one is extracted."""
- text = '```json\n{"first": 1}\n```\ntext\n```json\n{"second": 2}\n```'
+ def test_result_is_stripped(self):
+ assert _remove_think_tags(" <think>x</think> y ") == "y"
+
+
+# ===================================================================
+# _strip_code_fences
+# ===================================================================
+
+
+class TestStripCodeFences:
+ """```json fences, plain ``` fences, no fences."""
+
+ def test_json_fence(self):
+ text = '```json\n{"a": 1}\n```'
+ assert _strip_code_fences(text) == '{"a": 1}'
+
+ def test_plain_fence(self):
+ text = '```\n{"a": 1}\n```'
+ assert _strip_code_fences(text) == '{"a": 1}'
+
+ def test_no_fences(self):
+ text = '{"a": 1}'
+ assert _strip_code_fences(text) == '{"a": 1}'
+
+ def test_json_fence_preferred_over_plain(self):
+ """```json is checked before plain ```."""
+ text = '```json\n{"first": 1}\n```\n```\n{"second": 2}\n```'
result = _strip_code_fences(text)
assert '{"first": 1}' in result
- def test_json_fence_immediately_adjacent(self):
- """```json``` with no content between markers."""
- text = "```json```"
+ def test_only_two_backtick_groups_returns_original(self):
+ """Single ``` without a matching close returns original text."""
+ text = "some ``` text"
+ assert _strip_code_fences(text) == text
+
+ def test_json_fence_no_closing(self):
+ text = '```json\n{"key": "val"}'
result = _strip_code_fences(text)
- # split("```json") -> ['', '```']
- # parts[1].split("```") -> ['', '']
- # parts[1].split("```")[0] -> ''
- assert result == ""
+ assert '{"key": "val"}' in result
+ def test_json_fence_with_whitespace(self):
+ text = '```json\n {"a": 1} \n```'
+ assert _strip_code_fences(text) == '{"a": 1}'
-# ---------------------------------------------------------------------------
-# _extract_by_brackets — coverage gaps
-# ---------------------------------------------------------------------------
+# ===================================================================
+# _extract_by_brackets
+# ===================================================================
-class TestExtractByBracketsCoverage:
- """Cover edge cases in _extract_by_brackets find/rfind logic."""
- def test_minimal_brackets(self):
- """Minimal content: just {} or []."""
- assert _extract_by_brackets("{}", "{", "}") == "{}"
- assert _extract_by_brackets("[]", "[", "]") == "[]"
+class TestExtractByBrackets:
+ """Dict brackets, list brackets, nested, no brackets."""
- def test_single_char_content(self):
- """Single character between brackets."""
- assert _extract_by_brackets("{x}", "{", "}") == "{x}"
+ def test_dict_brackets(self):
+ assert _extract_by_brackets('x{"a":1}y', "{", "}") == '{"a":1}'
- def test_brackets_at_start_and_end(self):
- """Brackets at exact start and end of string."""
- text = '{"key": "value"}'
+ def test_list_brackets(self):
+ assert _extract_by_brackets("x[1,2]y", "[", "]") == "[1,2]"
+
+ def test_nested_brackets(self):
+ text = '{"a": {"b": 1}}'
assert _extract_by_brackets(text, "{", "}") == text
- def test_multiple_close_brackets_uses_last(self):
- """rfind finds the last closing bracket."""
- text = '{"a": {"b": 1}} extra }'
- result = _extract_by_brackets(text, "{", "}")
- # find("{")=0, rfind("}")=last "}" at end
- assert result == text
+ def test_no_opening_bracket(self):
+ assert _extract_by_brackets("no brackets", "{", "}") is None
- def test_multiple_open_brackets_uses_first(self):
- """find finds the first opening bracket."""
- text = '{ extra {"a": 1}}'
- result = _extract_by_brackets(text, "{", "}")
- assert result == text
+ def test_no_closing_bracket(self):
+ assert _extract_by_brackets("{no close", "{", "}") is None
- def test_deeply_nested_brackets(self):
- """Deeply nested bracket structure."""
- text = '{"a": {"b": {"c": {"d": 1}}}}'
- result = _extract_by_brackets(text, "{", "}")
- assert result == text
-
- def test_mixed_bracket_types(self):
- """Square brackets inside curly braces."""
- text = '{"list": [1, [2, 3], 4]}'
- result = _extract_by_brackets(text, "{", "}")
- assert result == text
-
- def test_square_brackets_with_nested_objects(self):
- """Objects inside square brackets."""
- text = '[{"a": 1}, {"b": 2}]'
- result = _extract_by_brackets(text, "[", "]")
- assert result == text
+ def test_close_before_open(self):
+ """Closing bracket appears before opening -- end <= start."""
+ assert _extract_by_brackets("}text{", "{", "}") is None
def test_empty_string(self):
- """Empty string input."""
assert _extract_by_brackets("", "{", "}") is None
- assert _extract_by_brackets("", "[", "]") is None
-
- def test_only_open_no_close(self):
- """Only opening bracket, no closing."""
- assert _extract_by_brackets("[no close", "[", "]") is None
- def test_only_close_no_open(self):
- """Only closing bracket, no opening."""
- assert _extract_by_brackets("no open]", "[", "]") is None
+ def test_adjacent_brackets(self):
+ assert _extract_by_brackets("prefix{}suffix", "{", "}") == "{}"
- def test_adjacent_same_position(self):
- """Open and close at adjacent positions."""
- text = "prefix{}suffix"
+ def test_multiple_opens_uses_first(self):
+ text = "{ extra { inner }}"
result = _extract_by_brackets(text, "{", "}")
- assert result == "{}"
+ assert result.startswith("{")
- def test_open_equals_close_position(self):
- """When open_char == close_char scenario (degenerate)."""
- # Not a real use case, but tests the find/rfind logic
- text = "x|y|z"
- result = _extract_by_brackets(text, "|", "|")
- # find("|")=1, rfind("|")=3, 3 > 1 -> "|y|"
- assert result == "|y|"
+ def test_multiple_closes_uses_last(self):
+ text = '{"a": {"b": 1}} }'
+ result = _extract_by_brackets(text, "{", "}")
+ assert result.endswith("}")
-# ---------------------------------------------------------------------------
-# _clean_llm_json_artifacts — coverage gaps
-# ---------------------------------------------------------------------------
+# ===================================================================
+# _clean_llm_json_artifacts
+# ===================================================================
-class TestCleanLlmJsonArtifactsCoverage:
- """Cover edge cases in _clean_llm_json_artifacts regex patterns."""
+class TestCleanLlmJsonArtifacts:
+ """Trailing commas, JS comments, ellipsis entries."""
- def test_trailing_comma_with_whitespace(self):
- """Trailing comma with various whitespace before closing bracket."""
- text = '{"a": 1 , \n }'
+ def test_trailing_comma_before_close_brace(self):
+ text = '{"a": 1,}'
result = _clean_llm_json_artifacts(text)
- parsed = json.loads(result)
- assert parsed == {"a": 1}
+ assert json.loads(result) == {"a": 1}
- def test_multiple_trailing_commas(self):
- """Multiple trailing commas (nested structures)."""
- text = '{"a": [1, 2,], "b": 3,}'
+ def test_trailing_comma_before_close_bracket(self):
+ text = "[1, 2,]"
result = _clean_llm_json_artifacts(text)
- parsed = json.loads(result)
- assert parsed == {"a": [1, 2], "b": 3}
+ assert json.loads(result) == [1, 2]
- def test_comment_at_end_of_line(self):
- """Comment at end of line with content before it."""
- text = '{"key": "value" // this is important\n}'
+ def test_trailing_comma_with_whitespace(self):
+ text = '{"a": 1 , \n }'
result = _clean_llm_json_artifacts(text)
- assert "//" not in result
- parsed = json.loads(result)
- assert parsed == {"key": "value"}
+ assert json.loads(result) == {"a": 1}
- def test_multiple_comments_on_different_lines(self):
- """Multiple // comments on separate lines."""
- text = '{\n"a": 1, // first\n"b": 2 // second\n}'
+ def test_inline_comment_removed(self):
+ text = '{"a": 1 // comment\n}'
result = _clean_llm_json_artifacts(text)
assert "//" not in result
- parsed = json.loads(result)
- assert parsed == {"a": 1, "b": 2}
+ assert json.loads(result) == {"a": 1}
- def test_comment_on_empty_line(self):
- """Comment on a line by itself."""
- text = '{\n// this is a comment\n"a": 1\n}'
+ def test_multiple_comments(self):
+ text = '{\n"a": 1, // first\n"b": 2 // second\n}'
result = _clean_llm_json_artifacts(text)
- assert "//" not in result
- parsed = json.loads(result)
- assert parsed == {"a": 1}
+ assert json.loads(result) == {"a": 1, "b": 2}
- def test_ellipsis_at_end_of_array(self):
- """Trailing ellipsis at end of array."""
- text = "[1, 2, 3, ...]"
+ def test_trailing_ellipsis_removed(self):
+ text = "[1, 2, ...]"
result = _clean_llm_json_artifacts(text)
assert "..." not in result
- parsed = json.loads(result)
- assert parsed == [1, 2, 3]
- def test_ellipsis_at_start_of_array(self):
- """Leading ellipsis at start of array — unusual but possible."""
- text = "[..., 1, 2]"
+ def test_quoted_ellipsis_between_items(self):
+ text = '[1, "...", 2]'
result = _clean_llm_json_artifacts(text)
assert "..." not in result
- def test_multiple_dots_more_than_three(self):
- """More than three dots: ....."""
- text = "[1, 2, .....]"
+ def test_ellipsis_between_items_keeps_one_comma(self):
+ """The comma-preserving regex handles , ... , correctly."""
+ text = "[1, ..., 2]"
result = _clean_llm_json_artifacts(text)
- # The regex \.\.\.+ matches 3 or more dots
assert "..." not in result
- def test_combined_trailing_comma_and_comment(self):
- """Both trailing comma and comment in same JSON."""
- text = '{"a": 1, // comment\n"b": 2,}'
- result = _clean_llm_json_artifacts(text)
- parsed = json.loads(result)
- assert parsed == {"a": 1, "b": 2}
+ def test_single_slash_not_touched(self):
+ """A single / is not a comment."""
+ text = '{"path": "/api/v1"}'
+ assert _clean_llm_json_artifacts(text) == text
- def test_combined_all_artifacts(self):
- """All artifact types combined."""
- text = "[\n1, // first item\n2,\n...,\n]"
+ def test_clean_json_unchanged(self):
+ text = '{"a": 1, "b": [2, 3]}'
+ assert _clean_llm_json_artifacts(text) == text
+
+ def test_all_artifacts_combined(self):
+ text = "[\n1, // comment\n2,\n...,\n]"
result = _clean_llm_json_artifacts(text)
assert "//" not in result
assert "..." not in result
parsed = json.loads(result)
assert parsed == [1, 2]
- def test_no_artifacts_leaves_valid_json_unchanged(self):
- """Clean JSON is not modified."""
- text = '{"key": "value", "num": 42}'
- assert _clean_llm_json_artifacts(text) == text
- def test_single_slash_not_treated_as_comment(self):
- """Single / is not a comment delimiter."""
- text = '{"path": "/api/v1"}'
- result = _clean_llm_json_artifacts(text)
- assert "/api/v1" in result
+# ===================================================================
+# to_bool (from type_utils)
+# ===================================================================
- def test_empty_object(self):
- """Empty object is unchanged."""
- text = "{}"
- assert _clean_llm_json_artifacts(text) == "{}"
- def test_empty_array(self):
- """Empty array is unchanged."""
- text = "[]"
- assert _clean_llm_json_artifacts(text) == "[]"
+class TestToBool:
+ """Cover every documented truthy/falsy string, types, defaults."""
- def test_ellipsis_between_items_uses_first_regex(self):
- """Ellipsis between commas uses the comma-preserving regex."""
- text = "[1, ..., 2]"
- result = _clean_llm_json_artifacts(text)
- assert "..." not in result
- # First regex: ',\\s*"?\\.\\.\\.+"?\\s*,' -> ','
- # Should produce [1, 2] ideally
+ # --- truthy strings ---------------------------------------------
- def test_quoted_ellipsis_between_items(self):
- """Quoted ellipsis "..." between items."""
- text = '[1, "...", 2]'
- result = _clean_llm_json_artifacts(text)
- assert "..." not in result
+ @pytest.mark.parametrize("val", ["true", "True", "TRUE", "tRuE"])
+ def test_true_variants(self, val):
+ assert to_bool(val) is True
+ @pytest.mark.parametrize("val", ["yes", "Yes", "YES"])
+ def test_yes_variants(self, val):
+ assert to_bool(val) is True
-# ---------------------------------------------------------------------------
-# extract_json — comprehensive coverage
-# ---------------------------------------------------------------------------
+ def test_one_string(self):
+ assert to_bool("1") is True
+ @pytest.mark.parametrize("val", ["on", "On", "ON"])
+ def test_on_variants(self, val):
+ assert to_bool(val) is True
-class TestExtractJsonCoverage:
- """Cover remaining code paths in extract_json."""
+ @pytest.mark.parametrize("val", ["enabled", "Enabled", "ENABLED"])
+ def test_enabled_variants(self, val):
+ assert to_bool(val) is True
- # --- Cleaning pipeline ordering ---
+ # --- falsy strings ----------------------------------------------
- def test_code_fences_stripped_before_think_tags(self):
- """Code fences are stripped, then think tags removed."""
- text = '```json\n<think>reasoning</think>{"key": "value"}\n```'
- result = extract_json(text)
- assert result == {"key": "value"}
+ @pytest.mark.parametrize("val", ["false", "False", "FALSE"])
+ def test_false_variants(self, val):
+ assert to_bool(val) is False
- def test_think_tags_inside_code_fence(self):
- """Think tags inside code fence content."""
- text = '```json\n{"key": "<think>not removed</think>"}\n```'
- # After fence stripping: {"key": "<think>not removed</think>"}
- # After think tag removal: {"key": ""}
- result = extract_json(text)
- assert result is not None
- assert isinstance(result, dict)
+ @pytest.mark.parametrize("val", ["no", "No", "NO"])
+ def test_no_variants(self, val):
+ assert to_bool(val) is False
- # --- Direct parse success paths ---
+ def test_zero_string(self):
+ assert to_bool("0") is False
- def test_direct_parse_dict_no_expected_type(self):
- """Direct parse succeeds with dict, no expected_type."""
- result = extract_json('{"a": 1}')
- assert result == {"a": 1}
+ @pytest.mark.parametrize("val", ["off", "Off", "OFF"])
+ def test_off_variants(self, val):
+ assert to_bool(val) is False
- def test_direct_parse_list_no_expected_type(self):
- """Direct parse succeeds with list, no expected_type."""
- result = extract_json("[1, 2, 3]")
- assert result == [1, 2, 3]
+ @pytest.mark.parametrize("val", ["disabled", "Disabled", "DISABLED"])
+ def test_disabled_variants(self, val):
+ assert to_bool(val) is False
- def test_direct_parse_matching_expected_type(self):
- """Direct parse succeeds and matches expected_type."""
- result = extract_json('{"a": 1}', expected_type=dict)
- assert result == {"a": 1}
+ # --- whitespace handling ----------------------------------------
- def test_direct_parse_type_mismatch_falls_to_bracket_extraction(self):
- """Direct parse succeeds as dict but expected list — falls through."""
- text = '{"items": [1, 2]}'
- result = extract_json(text, expected_type=list)
- # Direct parse gives dict, but expected list
- # Bracket extraction with "[" first finds [1, 2]
- assert result == [1, 2]
-
- # --- Bracket extraction with artifact cleaning ---
-
- def test_bracket_extraction_then_artifact_cleaning(self):
- """Bracket extraction finds JSON but it has artifacts, cleaning fixes it."""
- text = 'Result: {"a": 1, "b": 2,} end'
- result = extract_json(text)
- assert result == {"a": 1, "b": 2}
-
- def test_bracket_extraction_with_comment_artifact(self):
- """Bracket extraction finds JSON with // comment, cleaning fixes it."""
- text = 'Output: {"a": 1 // comment\n} done'
- result = extract_json(text)
- assert result == {"a": 1}
-
- def test_bracket_extraction_with_ellipsis_artifact(self):
- """Bracket extraction finds array with ellipsis, cleaning fixes it."""
- text = "Items: [1, 2, 3, ...] end"
- result = extract_json(text, expected_type=list)
- assert result == [1, 2, 3]
+ def test_leading_trailing_whitespace(self):
+ assert to_bool(" true ") is True
- # --- expected_type bracket ordering ---
+ def test_whitespace_false(self):
+ assert to_bool(" false ") is False
- def test_expected_type_list_tries_square_first(self):
- """expected_type=list makes bracket_pairs start with ('[', ']')."""
- # Both valid JSON types present
- text = 'prefix {"d": 1} middle [10, 20] suffix'
- result = extract_json(text, expected_type=list)
- assert isinstance(result, list)
- assert result == [10, 20]
+ # --- None uses default ------------------------------------------
- def test_expected_type_dict_tries_curly_first(self):
- """expected_type=dict makes bracket_pairs start with ('{', '}')."""
- text = 'prefix [10, 20] middle {"d": 1} suffix'
- result = extract_json(text, expected_type=dict)
- assert isinstance(result, dict)
+ def test_none_default_false(self):
+ assert to_bool(None) is False
- def test_no_expected_type_tries_curly_first(self):
- """No expected_type tries curly braces first (default ordering)."""
- text = '{"a": 1}'
- result = extract_json(text, expected_type=None)
- assert result == {"a": 1}
+ def test_none_default_true(self):
+ assert to_bool(None, default=True) is True
- # --- Edge cases for None/empty ---
+ # --- bool pass-through ------------------------------------------
- def test_none_input(self):
- assert extract_json(None) is None
+ def test_bool_true_passthrough(self):
+ assert to_bool(True) is True
- def test_empty_string(self):
- assert extract_json("") is None
+ def test_bool_false_passthrough(self):
+ assert to_bool(False) is False
- def test_whitespace_tabs_newlines(self):
- assert extract_json("\t\n \r\n") is None
+ # --- integer input ----------------------------------------------
- def test_only_text_no_json(self):
- assert extract_json("This is just plain text without any JSON.") is None
+ def test_int_one(self):
+ assert to_bool(1) is True
- # --- Scalar JSON values ---
+ def test_int_zero(self):
+ assert to_bool(0) is False
- def test_json_number_returns_none(self):
- """JSON number is valid JSON but not dict/list."""
- assert extract_json("42") is None
+ def test_int_negative(self):
+ """Negative int is truthy via bool()."""
+ assert to_bool(-1) is True
- def test_json_string_returns_none(self):
- """JSON string is valid JSON but not dict/list."""
- assert extract_json('"hello"') is None
+ # --- unknown strings use the truthy set -------------------------
- def test_json_boolean_returns_none(self):
- """JSON boolean is valid JSON but not dict/list."""
- assert extract_json("true") is None
-
- def test_json_null_returns_none(self):
- """JSON null is valid JSON but not dict/list."""
- assert extract_json("null") is None
+ def test_unknown_string_returns_false(self):
+ """A string not in the truthy set returns False."""
+ assert to_bool("maybe") is False
- # --- Complex nested JSON ---
+ def test_empty_string_returns_false(self):
+ assert to_bool("") is False
- def test_deeply_nested_dict(self):
- text = '{"a": {"b": {"c": {"d": {"e": 1}}}}}'
- result = extract_json(text)
- assert result == {"a": {"b": {"c": {"d": {"e": 1}}}}}
+ # --- default ignored for non-None values ------------------------
- def test_list_of_lists(self):
- text = "[[1, 2], [3, 4], [5, 6]]"
- result = extract_json(text)
- assert result == [[1, 2], [3, 4], [5, 6]]
+ def test_default_ignored_for_string(self):
+ assert to_bool("false", default=True) is False
- def test_mixed_nested_structure(self):
- text = '[{"name": "A", "values": [1, 2]}, {"name": "B", "values": [3]}]'
- result = extract_json(text, expected_type=list)
- assert len(result) == 2
- assert result[0]["name"] == "A"
- assert result[1]["values"] == [3]
-
- # --- Unicode and special characters ---
-
- def test_unicode_keys_and_values(self):
- text = '{"name": "日本語", "city": "Zürich"}'
- result = extract_json(text)
- assert result == {"name": "日本語", "city": "Zürich"}
-
- def test_escaped_quotes_in_values(self):
- text = '{"quote": "He said \\"hello\\""}'
- result = extract_json(text)
- assert result == {"quote": 'He said "hello"'}
-
- def test_newlines_in_values(self):
- text = '{"text": "line1\\nline2"}'
- result = extract_json(text)
- assert result == {"text": "line1\nline2"}
-
- # --- Real LLM output patterns ---
-
- def test_deepseek_think_then_code_fence(self):
- """DeepSeek-style: long think block then code fence."""
- text = (
- "<think>\nLet me analyze this carefully.\n"
- "The user wants a JSON response.\n"
- "I should structure it as follows.\n"
- "</think>\n\n"
- '```json\n{"answer": "structured response", "confidence": 0.95}\n```'
- )
- result = extract_json(text)
- assert result == {"answer": "structured response", "confidence": 0.95}
-
- def test_chatgpt_style_prose_then_json(self):
- """ChatGPT-style: conversational intro then JSON."""
- text = (
- "Based on my analysis, here is the structured output:\n\n"
- '{"summary": "key findings", "relevance_scores": [0.9, 0.7, 0.5]}'
- )
- result = extract_json(text)
- assert result["summary"] == "key findings"
- assert result["relevance_scores"] == [0.9, 0.7, 0.5]
-
- def test_llm_numbering_before_json(self):
- """LLM provides numbered reasoning then JSON."""
- text = (
- "1. First I considered X\n"
- "2. Then I evaluated Y\n"
- "3. My conclusion:\n\n"
- '{"result": "Y is better", "score": 8.5}'
- )
- result = extract_json(text)
- assert result == {"result": "Y is better", "score": 8.5}
-
- def test_json_with_markdown_bold_in_prose(self):
- """JSON embedded in text with markdown formatting."""
- text = '**Result**: {"key": "value"}\n\n*Note: this is important*'
- result = extract_json(text)
- assert result == {"key": "value"}
-
- # --- Artifact cleaning integration ---
-
- def test_trailing_comma_in_nested_structure(self):
- """Trailing commas in nested object."""
- text = '{"outer": {"inner": [1, 2,], "key": "val",},}'
- result = extract_json(text)
- assert result == {"outer": {"inner": [1, 2], "key": "val"}}
-
- def test_comments_in_multiline_json(self):
- """Comments in multiline JSON object."""
- text = '{\n "name": "test", // the name\n "value": 42 // the value\n}'
- result = extract_json(text)
- assert result == {"name": "test", "value": 42}
-
- def test_ellipsis_in_large_array_pattern(self):
- """LLM truncates array with ellipsis."""
- text = "[1, 2, 3, ...]"
- result = extract_json(text, expected_type=list)
- assert result == [1, 2, 3]
-
- # --- Multiple JSON objects in text ---
-
- def test_two_separate_dicts_in_prose(self):
- """Two separate dicts — bracket extraction spans both (may fail)."""
- text = '{"a": 1} some text {"b": 2}'
- result = extract_json(text)
- # find("{")=0, rfind("}")=end -> spans both, invalid JSON -> None
- assert result is None
-
- def test_dict_then_list_expected_dict(self):
- """Dict then list, expected_type=dict."""
- text = '{"a": 1}\n[1, 2, 3]'
- result = extract_json(text, expected_type=dict)
- # Bracket extraction for {} spans from first { to last }
- # which is just {"a": 1} since last } is at pos 7
- # Actually rfind("}") finds the } at position 7 (last one)
- # Direct parse fails because the whole text isn't valid JSON
- # Then bracket extraction for "{" finds {"a": 1}\n[1, 2, 3]
- # Wait — find("{")=0, rfind("}")=7, text[0:8] = '{"a": 1}'
- assert result == {"a": 1}
-
- # --- Completely invalid inputs ---
-
- def test_html_without_json(self):
- assert extract_json("<html><body>No JSON</body></html>") is None
-
- def test_xml_without_json(self):
- assert extract_json("<root><item>No JSON</item></root>") is None
-
- def test_brackets_with_non_json_content(self):
- """Brackets containing non-JSON content."""
- assert extract_json("{this is not: json: at: all}") is None
-
- def test_square_brackets_with_non_json(self):
- """Square brackets with non-JSON content."""
- assert extract_json("[not, valid, json, either]") is None
-
- # --- Whitespace handling ---
-
- def test_json_with_leading_trailing_whitespace(self):
- """JSON with lots of whitespace around it."""
- text = ' \n\n {"key": "value"} \n\n '
- result = extract_json(text)
- assert result == {"key": "value"}
-
- def test_json_with_internal_whitespace(self):
- """JSON with lots of internal whitespace."""
- text = '{\n\n "key" : "value" \n\n}'
- result = extract_json(text)
- assert result == {"key": "value"}
-
- # --- Empty structures ---
-
- def test_empty_dict(self):
- result = extract_json("{}")
- assert result == {}
-
- def test_empty_list(self):
- result = extract_json("[]")
- assert result == []
-
- def test_empty_dict_expected_dict(self):
- result = extract_json("{}", expected_type=dict)
- assert result == {}
-
- def test_empty_list_expected_list(self):
- result = extract_json("[]", expected_type=list)
- assert result == []
-
- def test_empty_dict_expected_list_returns_none(self):
- """Empty dict when list expected — falls through."""
- result = extract_json("{}", expected_type=list)
- # Direct parse gives dict, type mismatch
- # Bracket extraction for "[]" finds nothing
- assert result is None
-
- def test_empty_list_expected_dict_returns_none(self):
- """Empty list when dict expected — falls through."""
- result = extract_json("[]", expected_type=dict)
- assert result is None
-
- # --- Large/complex real patterns ---
-
- def test_search_result_format(self):
- """Typical search result JSON format from LDR."""
- text = (
- "```json\n"
- "{\n"
- ' "queries": [\n'
- ' {"query": "machine learning basics", "priority": 1},\n'
- ' {"query": "neural network architecture", "priority": 2}\n'
- " ],\n"
- ' "reasoning": "These queries cover the fundamentals"\n'
- "}\n"
- "```"
- )
- result = extract_json(text)
- assert result is not None
- assert len(result["queries"]) == 2
- assert result["queries"][0]["priority"] == 1
-
- def test_relevance_indices_format(self):
- """Typical relevance indices list from LDR."""
- text = (
- "<think>Let me rank these by relevance...</think>\n"
- "```json\n[0, 3, 1, 7, 2]\n```"
- )
- result = extract_json(text, expected_type=list)
- assert result == [0, 3, 1, 7, 2]
-
- def test_boolean_and_null_values(self):
- """JSON with boolean and null values."""
- text = '{"active": true, "deleted": false, "metadata": null}'
- result = extract_json(text)
- assert result == {"active": True, "deleted": False, "metadata": None}
-
- def test_numeric_values_int_and_float(self):
- """JSON with integer and float values."""
- text = '{"count": 42, "score": 3.14, "negative": -7}'
- result = extract_json(text)
- assert result == {"count": 42, "score": 3.14, "negative": -7}
-
- def test_artifact_cleaning_only_on_bracket_extracted_text(self):
- """Artifact cleaning is only attempted on bracket-extracted text,
- not on the original full text."""
- # This text has trailing comma but is surrounded by prose
- text = "Result: [1, 2, 3,] which is the answer"
- result = extract_json(text, expected_type=list)
- assert result == [1, 2, 3]
-
- def test_cleaning_does_not_run_when_bracket_parse_succeeds(self):
- """If bracket-extracted text parses fine, cleaning is skipped."""
- text = 'Prefix: {"a": 1, "b": 2} suffix'
- result = extract_json(text)
- assert result == {"a": 1, "b": 2}
-
- def test_cleaning_skipped_when_cleaned_equals_extracted(self):
- """If cleaning produces the same string, parsing is not retried."""
- # Invalid JSON that cleaning cannot fix
- text = "{key: value}"
- result = extract_json(text)
- assert result is None
-
-
-# ---------------------------------------------------------------------------
-# Integration: get_llm_response_text -> extract_json pipeline
-# ---------------------------------------------------------------------------
-
-
-class TestPipelineIntegration:
- """Test the common pattern of extracting text then parsing JSON."""
-
- def test_aimessage_to_json(self):
- """Simulate LangChain AIMessage -> extract_json pipeline."""
- msg = MagicMock()
- msg.content = '```json\n{"answer": "yes"}\n```'
- text = get_llm_response_text(msg)
- result = extract_json(text)
- assert result == {"answer": "yes"}
-
- def test_think_tags_cleaned_before_json_extraction(self):
- """Think tags removed by get_llm_response_text, then JSON extracted."""
- msg = MagicMock()
- msg.content = '<think>long reasoning</think>{"result": true}'
- text = get_llm_response_text(msg)
- result = extract_json(text)
- assert result == {"result": True}
-
- def test_none_response_produces_none_json(self):
- """None response -> empty string -> None JSON."""
- text = get_llm_response_text(None)
- result = extract_json(text)
- assert result is None
-
- def test_complex_deepseek_pipeline(self):
- """Full DeepSeek-style response through the pipeline."""
- msg = MagicMock()
- msg.content = (
- "<think>\nI need to analyze the search results.\n"
- "Result 1 is most relevant.\n"
- "Result 3 is partially relevant.\n"
- "</think>\n"
- "```json\n"
- "[0, 2]\n"
- "```"
- )
- text = get_llm_response_text(msg)
- result = extract_json(text, expected_type=list)
- assert result == [0, 2]
+ def test_default_ignored_for_bool(self):
+ assert to_bool(False, default=True) is False