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 unit tests for document_loaders module

LearningCircuit466d29a6bc20
diff --git a/tests/document_loaders/__init__.py b/tests/document_loaders/__init__.py
new file mode 100644
index 0000000000..1fbad0d53f
--- /dev/null
+++ b/tests/document_loaders/__init__.py
@@ -0,0 +1 @@
+"""Tests for document_loaders module."""
diff --git a/tests/document_loaders/test_bytes_loader.py b/tests/document_loaders/test_bytes_loader.py
new file mode 100644
index 0000000000..b8761d6f5e
--- /dev/null
+++ b/tests/document_loaders/test_bytes_loader.py
@@ -0,0 +1,229 @@
+"""Tests for bytes_loader module."""
+
+import pytest
+
+from local_deep_research.document_loaders.bytes_loader import (
+ extract_text_from_bytes,
+ load_from_bytes,
+)
+
+
+class TestLoadFromBytes:
+ """Tests for load_from_bytes function."""
+
+ def test_load_txt_bytes(self) -> None:
+ """Test loading text content from bytes."""
+ content = b"Hello, world!"
+ docs = load_from_bytes(content, ".txt", "test.txt")
+
+ assert len(docs) >= 1
+ assert "Hello, world!" in docs[0].page_content
+ assert docs[0].metadata["original_filename"] == "test.txt"
+
+ def test_load_json_bytes(self) -> None:
+ """Test loading JSON content from bytes."""
+ content = b'{"name": "test", "value": "hello"}'
+ docs = load_from_bytes(content, ".json", "test.json")
+
+ assert len(docs) >= 1
+ assert "name" in docs[0].page_content
+ assert "test" in docs[0].page_content
+
+ def test_load_yaml_bytes(self) -> None:
+ """Test loading YAML content from bytes."""
+ content = b"name: test\nvalue: 123"
+ docs = load_from_bytes(content, ".yaml", "test.yaml")
+
+ assert len(docs) >= 1
+ assert "name" in docs[0].page_content
+ assert "test" in docs[0].page_content
+
+ def test_load_yml_bytes(self) -> None:
+ """Test loading .yml content from bytes."""
+ content = b"key: value"
+ docs = load_from_bytes(content, ".yml", "test.yml")
+
+ assert len(docs) >= 1
+ assert "key" in docs[0].page_content
+
+ def test_extension_without_dot(self) -> None:
+ """Test that extension without dot is handled."""
+ content = b"Hello, world!"
+ docs = load_from_bytes(content, "txt", "test.txt")
+
+ assert len(docs) >= 1
+ assert "Hello, world!" in docs[0].page_content
+
+ def test_extension_case_insensitive(self) -> None:
+ """Test that extension is case insensitive."""
+ content = b"Hello, world!"
+ docs = load_from_bytes(content, ".TXT", "test.txt")
+
+ assert len(docs) >= 1
+
+ def test_unsupported_extension_raises_error(self) -> None:
+ """Test that unsupported extension raises ValueError."""
+ content = b"content"
+
+ with pytest.raises(ValueError, match="Unsupported file extension"):
+ load_from_bytes(content, ".xyz", "test.xyz")
+
+ def test_source_url_in_metadata(self) -> None:
+ """Test that source_url is added to metadata when provided."""
+ content = b"Hello, world!"
+ docs = load_from_bytes(
+ content,
+ ".txt",
+ "test.txt",
+ source_url="https://example.com/test.txt",
+ )
+
+ assert len(docs) >= 1
+ assert docs[0].metadata["source_url"] == "https://example.com/test.txt"
+
+ def test_no_source_url_when_not_provided(self) -> None:
+ """Test that source_url is not in metadata when not provided."""
+ content = b"Hello, world!"
+ docs = load_from_bytes(content, ".txt", "test.txt")
+
+ assert "source_url" not in docs[0].metadata
+
+ def test_original_filename_in_metadata(self) -> None:
+ """Test that original filename is in metadata."""
+ content = b"Hello, world!"
+ docs = load_from_bytes(content, ".txt", "my_document.txt")
+
+ assert docs[0].metadata["original_filename"] == "my_document.txt"
+
+
+class TestExtractTextFromBytes:
+ """Tests for extract_text_from_bytes function."""
+
+ def test_extract_txt(self) -> None:
+ """Test extracting text from TXT bytes."""
+ content = b"Hello, world!"
+ result = extract_text_from_bytes(content, ".txt", "test.txt")
+
+ assert result == "Hello, world!"
+
+ def test_extract_json(self) -> None:
+ """Test extracting text from JSON bytes."""
+ content = b'{"name": "Alice", "city": "Boston"}'
+ result = extract_text_from_bytes(content, ".json", "test.json")
+
+ assert result is not None
+ assert "Alice" in result
+ assert "Boston" in result
+
+ def test_extract_yaml(self) -> None:
+ """Test extracting text from YAML bytes."""
+ content = b"name: test\nvalue: hello"
+ result = extract_text_from_bytes(content, ".yaml", "test.yaml")
+
+ assert result is not None
+ assert "name" in result
+ assert "test" in result
+
+ def test_extract_unsupported_returns_none(self) -> None:
+ """Test that unsupported extension returns None."""
+ content = b"content"
+ result = extract_text_from_bytes(content, ".xyz", "test.xyz")
+
+ assert result is None
+
+ def test_extract_extension_without_dot(self) -> None:
+ """Test extraction with extension without dot."""
+ content = b"Hello!"
+ result = extract_text_from_bytes(content, "txt", "test.txt")
+
+ assert result == "Hello!"
+
+ def test_extract_case_insensitive(self) -> None:
+ """Test case insensitive extension handling."""
+ content = b"Hello!"
+ result = extract_text_from_bytes(content, ".TXT", "test.txt")
+
+ assert result == "Hello!"
+
+ def test_extract_empty_content(self) -> None:
+ """Test extracting from empty content."""
+ content = b""
+ result = extract_text_from_bytes(content, ".txt", "empty.txt")
+
+ # Should return empty string or None, not crash
+ assert result is not None or result is None
+
+ def test_extract_unicode_content(self) -> None:
+ """Test extracting unicode content."""
+ content = "Hello, 世界! 🌍".encode("utf-8")
+ result = extract_text_from_bytes(content, ".txt", "unicode.txt")
+
+ assert result is not None
+ assert "世界" in result
+ assert "🌍" in result
+
+ def test_extract_joins_multiple_documents(self) -> None:
+ """Test that multiple documents are joined with double newline."""
+ # Most loaders return single document, but test the join logic
+ content = b"Hello, world!"
+ result = extract_text_from_bytes(content, ".txt", "test.txt")
+
+ # Should be string (joined if multiple docs)
+ assert isinstance(result, str)
+
+
+class TestTempFileCleanup:
+ """Tests for temporary file cleanup."""
+
+ def test_temp_file_cleaned_up_on_success(self, tmp_path) -> None:
+ """Test that temp file is cleaned up after successful load."""
+ import os
+ import tempfile
+
+ content = b"Hello, world!"
+
+ # Get initial temp file count
+ temp_dir = tempfile.gettempdir()
+ initial_files = set(os.listdir(temp_dir))
+
+ # Load content
+ _docs = load_from_bytes(content, ".txt", "test.txt")
+ assert _docs is not None # Ensure load succeeded
+
+ # Check temp file was cleaned up
+ final_files = set(os.listdir(temp_dir))
+ new_ldr_files = [
+ f
+ for f in (final_files - initial_files)
+ if f.startswith("ldr_upload_")
+ ]
+
+ assert len(new_ldr_files) == 0, "Temp file was not cleaned up"
+
+ def test_temp_file_cleaned_up_on_error(self) -> None:
+ """Test that temp file is cleaned up even on error."""
+ import os
+ import tempfile
+
+ # Invalid JSON that will cause parsing error
+ content = b'{"invalid": json content'
+
+ temp_dir = tempfile.gettempdir()
+ initial_files = set(os.listdir(temp_dir))
+
+ # This should still work (JSON loader handles errors gracefully)
+ try:
+ load_from_bytes(content, ".json", "invalid.json")
+ except Exception:
+ pass
+
+ final_files = set(os.listdir(temp_dir))
+ new_ldr_files = [
+ f
+ for f in (final_files - initial_files)
+ if f.startswith("ldr_upload_")
+ ]
+
+ assert len(new_ldr_files) == 0, (
+ "Temp file was not cleaned up after error"
+ )
diff --git a/tests/document_loaders/test_json_loader.py b/tests/document_loaders/test_json_loader.py
new file mode 100644
index 0000000000..a05d6ed501
--- /dev/null
+++ b/tests/document_loaders/test_json_loader.py
@@ -0,0 +1,264 @@
+"""Tests for SimpleJSONLoader."""
+
+from pathlib import Path
+
+import pytest
+
+from local_deep_research.document_loaders.json_loader import (
+ SimpleJSONLoader,
+ extract_strings_from_json,
+ extract_text_from_json,
+)
+
+
+class TestExtractStringsFromJson:
+ """Tests for extract_strings_from_json helper function."""
+
+ def test_extract_simple_string(self) -> None:
+ """Test extracting a simple string value."""
+ data = "hello"
+ result = extract_strings_from_json(data)
+
+ assert result == [("", "hello")]
+
+ def test_extract_from_dict(self) -> None:
+ """Test extracting strings from a dictionary."""
+ data = {"name": "Alice", "city": "Boston"}
+ result = extract_strings_from_json(data)
+
+ assert ("name", "Alice") in result
+ assert ("city", "Boston") in result
+
+ def test_extract_from_nested_dict(self) -> None:
+ """Test extracting strings from nested dictionary."""
+ data = {"user": {"name": "Bob", "email": "[email protected]"}}
+ result = extract_strings_from_json(data)
+
+ assert ("user.name", "Bob") in result
+ assert ("user.email", "[email protected]") in result
+
+ def test_extract_from_list(self) -> None:
+ """Test extracting strings from a list."""
+ data = ["apple", "banana", "cherry"]
+ result = extract_strings_from_json(data)
+
+ assert ("[0]", "apple") in result
+ assert ("[1]", "banana") in result
+ assert ("[2]", "cherry") in result
+
+ def test_extract_from_nested_list(self) -> None:
+ """Test extracting strings from nested list in dict."""
+ data = {"fruits": ["apple", "banana"]}
+ result = extract_strings_from_json(data)
+
+ assert ("fruits[0]", "apple") in result
+ assert ("fruits[1]", "banana") in result
+
+ def test_skip_numbers_and_booleans(self) -> None:
+ """Test that numbers and booleans are skipped."""
+ data = {"count": 42, "active": True, "name": "test"}
+ result = extract_strings_from_json(data)
+
+ # Only name should be extracted
+ assert len(result) == 1
+ assert ("name", "test") in result
+
+ def test_skip_none(self) -> None:
+ """Test that None values are skipped."""
+ data = {"value": None, "name": "test"}
+ result = extract_strings_from_json(data)
+
+ assert len(result) == 1
+ assert ("name", "test") in result
+
+ def test_empty_dict(self) -> None:
+ """Test with empty dictionary."""
+ data = {}
+ result = extract_strings_from_json(data)
+
+ assert result == []
+
+ def test_empty_list(self) -> None:
+ """Test with empty list."""
+ data = []
+ result = extract_strings_from_json(data)
+
+ assert result == []
+
+ def test_deeply_nested(self) -> None:
+ """Test deeply nested structure."""
+ data = {"a": {"b": {"c": {"d": "deep"}}}}
+ result = extract_strings_from_json(data)
+
+ assert ("a.b.c.d", "deep") in result
+
+
+class TestSimpleJSONLoader:
+ """Tests for SimpleJSONLoader class."""
+
+ def test_load_simple_json(self, tmp_path: Path) -> None:
+ """Test loading a simple JSON file."""
+ json_file = tmp_path / "test.json"
+ json_file.write_text('{"name": "test", "value": "hello"}')
+
+ loader = SimpleJSONLoader(json_file)
+ docs = loader.load()
+
+ assert len(docs) == 1
+ assert "name: test" in docs[0].page_content
+ assert "value: hello" in docs[0].page_content
+ assert docs[0].metadata["file_type"] == "json"
+
+ def test_load_nested_json(self, tmp_path: Path) -> None:
+ """Test loading nested JSON structure."""
+ json_content = (
+ '{"user": {"name": "Alice", "email": "[email protected]"}}'
+ )
+ json_file = tmp_path / "nested.json"
+ json_file.write_text(json_content)
+
+ loader = SimpleJSONLoader(json_file)
+ docs = loader.load()
+
+ assert len(docs) == 1
+ assert "user.name: Alice" in docs[0].page_content
+ assert "user.email: [email protected]" in docs[0].page_content
+
+ def test_load_json_array(self, tmp_path: Path) -> None:
+ """Test loading JSON with array."""
+ json_content = '{"items": ["one", "two", "three"]}'
+ json_file = tmp_path / "array.json"
+ json_file.write_text(json_content)
+
+ loader = SimpleJSONLoader(json_file)
+ docs = loader.load()
+
+ assert len(docs) == 1
+ assert "items[0]: one" in docs[0].page_content
+ assert "items[1]: two" in docs[0].page_content
+
+ def test_load_invalid_json_returns_raw_content(
+ self, tmp_path: Path
+ ) -> None:
+ """Test that invalid JSON returns raw content with parse_error flag."""
+ json_file = tmp_path / "invalid.json"
+ json_file.write_text('{"invalid": json content')
+
+ loader = SimpleJSONLoader(json_file)
+ docs = loader.load()
+
+ assert len(docs) == 1
+ assert docs[0].metadata.get("parse_error") is True
+ assert '{"invalid":' in docs[0].page_content
+
+ def test_load_without_paths(self, tmp_path: Path) -> None:
+ """Test loading with include_paths=False."""
+ json_file = tmp_path / "test.json"
+ json_file.write_text('{"name": "test", "city": "Boston"}')
+
+ loader = SimpleJSONLoader(json_file, include_paths=False)
+ docs = loader.load()
+
+ assert len(docs) == 1
+ # Should contain values but not paths
+ assert "test" in docs[0].page_content
+ assert "Boston" in docs[0].page_content
+ # Should NOT contain "name:" prefix
+ assert "name:" not in docs[0].page_content
+
+ def test_load_json_with_unicode(self, tmp_path: Path) -> None:
+ """Test loading JSON with unicode characters."""
+ json_content = '{"greeting": "こんにちは", "emoji": "🎉"}'
+ json_file = tmp_path / "unicode.json"
+ json_file.write_text(json_content, encoding="utf-8")
+
+ loader = SimpleJSONLoader(json_file)
+ docs = loader.load()
+
+ assert len(docs) == 1
+ assert "こんにちは" in docs[0].page_content
+ assert "🎉" in docs[0].page_content
+
+ def test_string_count_metadata(self, tmp_path: Path) -> None:
+ """Test that string_count metadata is set correctly."""
+ json_file = tmp_path / "test.json"
+ json_file.write_text('{"a": "one", "b": "two", "c": "three"}')
+
+ loader = SimpleJSONLoader(json_file)
+ docs = loader.load()
+
+ assert docs[0].metadata["string_count"] == 3
+
+ def test_lazy_load(self, tmp_path: Path) -> None:
+ """Test lazy_load returns an iterator."""
+ json_file = tmp_path / "test.json"
+ json_file.write_text('{"key": "value"}')
+
+ loader = SimpleJSONLoader(json_file)
+ result = loader.lazy_load()
+
+ assert hasattr(result, "__iter__")
+ assert hasattr(result, "__next__")
+
+ docs = list(result)
+ assert len(docs) == 1
+
+ def test_file_not_found_raises_error(self) -> None:
+ """Test that missing file raises appropriate error."""
+ loader = SimpleJSONLoader("/nonexistent/path/file.json")
+
+ with pytest.raises(Exception):
+ loader.load()
+
+
+class TestExtractTextFromJson:
+ """Tests for extract_text_from_json function."""
+
+ def test_extract_simple_json(self) -> None:
+ """Test extracting text from simple JSON bytes."""
+ content = b'{"name": "test", "value": "hello"}'
+ result = extract_text_from_json(content)
+
+ assert "name: test" in result
+ assert "value: hello" in result
+
+ def test_extract_nested_json(self) -> None:
+ """Test extracting text from nested JSON bytes."""
+ content = b'{"user": {"name": "Alice"}}'
+ result = extract_text_from_json(content)
+
+ assert "user.name: Alice" in result
+
+ def test_extract_invalid_json_returns_raw(self) -> None:
+ """Test that invalid JSON returns raw content."""
+ content = b'{"invalid": json'
+ result = extract_text_from_json(content)
+
+ # Should return the raw content
+ assert '{"invalid":' in result
+
+ def test_extract_with_encoding_errors(self) -> None:
+ """Test handling of encoding errors."""
+ # Invalid UTF-8 bytes mixed with valid JSON
+ content = b'{"name": "test\xff\xfe"}'
+ result = extract_text_from_json(content)
+
+ # Should still return something
+ assert "name" in result
+
+ def test_extract_empty_object(self) -> None:
+ """Test extracting from empty JSON object."""
+ content = b"{}"
+ result = extract_text_from_json(content)
+
+ assert result == ""
+
+ def test_extract_filters_empty_strings(self) -> None:
+ """Test that empty strings are filtered out."""
+ content = b'{"empty": "", "valid": "value"}'
+ result = extract_text_from_json(content)
+
+ assert "valid: value" in result
+ # Empty string should not create a line
+ lines = [line for line in result.split("\n") if line.strip()]
+ assert len(lines) == 1
diff --git a/tests/document_loaders/test_loader_registry.py b/tests/document_loaders/test_loader_registry.py
new file mode 100644
index 0000000000..1f7dceabd5
--- /dev/null
+++ b/tests/document_loaders/test_loader_registry.py
@@ -0,0 +1,248 @@
+"""Tests for loader_registry module."""
+
+from pathlib import Path
+
+from langchain_core.document_loaders import BaseLoader
+
+from local_deep_research.document_loaders.loader_registry import (
+ LOADER_REGISTRY,
+ get_loader_class_for_extension,
+ get_loader_for_path,
+ get_supported_extensions,
+ is_extension_supported,
+)
+
+
+class TestGetSupportedExtensions:
+ """Tests for get_supported_extensions function."""
+
+ def test_returns_list(self) -> None:
+ """Test that function returns a list."""
+ result = get_supported_extensions()
+ assert isinstance(result, list)
+
+ def test_includes_common_extensions(self) -> None:
+ """Test that common extensions are included."""
+ extensions = get_supported_extensions()
+
+ # Core document formats
+ assert ".pdf" in extensions
+ assert ".txt" in extensions
+ assert ".md" in extensions
+ assert ".docx" in extensions
+ assert ".doc" in extensions
+
+ # Spreadsheets
+ assert ".csv" in extensions
+ assert ".xlsx" in extensions
+
+ # Web
+ assert ".html" in extensions
+
+ # Data formats
+ assert ".json" in extensions
+ assert ".yaml" in extensions
+ assert ".yml" in extensions
+
+ def test_includes_yaml_extensions(self) -> None:
+ """Test that YAML extensions are included."""
+ extensions = get_supported_extensions()
+
+ assert ".yaml" in extensions
+ assert ".yml" in extensions
+
+ def test_no_duplicates(self) -> None:
+ """Test that there are no duplicate extensions."""
+ extensions = get_supported_extensions()
+ assert len(extensions) == len(set(extensions))
+
+
+class TestIsExtensionSupported:
+ """Tests for is_extension_supported function."""
+
+ def test_supported_with_dot(self) -> None:
+ """Test checking supported extension with leading dot."""
+ assert is_extension_supported(".pdf") is True
+ assert is_extension_supported(".txt") is True
+ assert is_extension_supported(".json") is True
+
+ def test_supported_without_dot(self) -> None:
+ """Test checking supported extension without leading dot."""
+ assert is_extension_supported("pdf") is True
+ assert is_extension_supported("txt") is True
+ assert is_extension_supported("json") is True
+
+ def test_unsupported_extension(self) -> None:
+ """Test checking unsupported extension."""
+ assert is_extension_supported(".xyz") is False
+ assert is_extension_supported(".unknown") is False
+ assert is_extension_supported("notreal") is False
+
+ def test_case_insensitive(self) -> None:
+ """Test that extension check is case insensitive."""
+ assert is_extension_supported(".PDF") is True
+ assert is_extension_supported(".Pdf") is True
+ assert is_extension_supported("PDF") is True
+
+ def test_yaml_extensions(self) -> None:
+ """Test YAML extensions are supported."""
+ assert is_extension_supported(".yaml") is True
+ assert is_extension_supported(".yml") is True
+ assert is_extension_supported("yaml") is True
+ assert is_extension_supported("yml") is True
+
+
+class TestGetLoaderForPath:
+ """Tests for get_loader_for_path function."""
+
+ def test_returns_loader_for_txt(self, tmp_path: Path) -> None:
+ """Test getting loader for text file."""
+ txt_file = tmp_path / "test.txt"
+ txt_file.write_text("Hello world")
+
+ loader = get_loader_for_path(txt_file)
+
+ assert loader is not None
+ assert isinstance(loader, BaseLoader)
+
+ def test_returns_loader_for_json(self, tmp_path: Path) -> None:
+ """Test getting loader for JSON file."""
+ json_file = tmp_path / "test.json"
+ json_file.write_text('{"key": "value"}')
+
+ loader = get_loader_for_path(json_file)
+
+ assert loader is not None
+ assert isinstance(loader, BaseLoader)
+
+ def test_returns_loader_for_yaml(self, tmp_path: Path) -> None:
+ """Test getting loader for YAML file."""
+ yaml_file = tmp_path / "test.yaml"
+ yaml_file.write_text("key: value")
+
+ loader = get_loader_for_path(yaml_file)
+
+ assert loader is not None
+ assert isinstance(loader, BaseLoader)
+
+ def test_returns_loader_for_yml(self, tmp_path: Path) -> None:
+ """Test getting loader for .yml file."""
+ yml_file = tmp_path / "test.yml"
+ yml_file.write_text("key: value")
+
+ loader = get_loader_for_path(yml_file)
+
+ assert loader is not None
+ assert isinstance(loader, BaseLoader)
+
+ def test_returns_none_for_unsupported(self, tmp_path: Path) -> None:
+ """Test that None is returned for unsupported extension."""
+ unknown_file = tmp_path / "test.xyz"
+ unknown_file.write_text("content")
+
+ loader = get_loader_for_path(unknown_file)
+
+ assert loader is None
+
+ def test_accepts_string_path(self, tmp_path: Path) -> None:
+ """Test that function accepts string path."""
+ txt_file = tmp_path / "test.txt"
+ txt_file.write_text("content")
+
+ loader = get_loader_for_path(str(txt_file))
+
+ assert loader is not None
+
+ def test_case_insensitive_extension(self, tmp_path: Path) -> None:
+ """Test that extension matching is case insensitive."""
+ txt_file = tmp_path / "test.TXT"
+ txt_file.write_text("content")
+
+ loader = get_loader_for_path(txt_file)
+
+ assert loader is not None
+
+
+class TestGetLoaderClassForExtension:
+ """Tests for get_loader_class_for_extension function."""
+
+ def test_returns_tuple_for_supported(self) -> None:
+ """Test that function returns (class, kwargs) tuple."""
+ result = get_loader_class_for_extension(".txt")
+
+ assert result is not None
+ assert isinstance(result, tuple)
+ assert len(result) == 2
+
+ loader_class, kwargs = result
+ assert callable(loader_class)
+ assert isinstance(kwargs, dict)
+
+ def test_returns_none_for_unsupported(self) -> None:
+ """Test that function returns None for unsupported extension."""
+ result = get_loader_class_for_extension(".xyz")
+ assert result is None
+
+ def test_with_dot_prefix(self) -> None:
+ """Test with extension that has dot prefix."""
+ result = get_loader_class_for_extension(".pdf")
+ assert result is not None
+
+ def test_without_dot_prefix(self) -> None:
+ """Test with extension without dot prefix."""
+ result = get_loader_class_for_extension("pdf")
+ assert result is not None
+
+ def test_case_insensitive(self) -> None:
+ """Test case insensitivity."""
+ result1 = get_loader_class_for_extension(".PDF")
+ result2 = get_loader_class_for_extension(".pdf")
+
+ assert result1 is not None
+ assert result2 is not None
+ assert result1[0] == result2[0]
+
+ def test_json_returns_simple_json_loader(self) -> None:
+ """Test that JSON extension returns SimpleJSONLoader."""
+ from local_deep_research.document_loaders.json_loader import (
+ SimpleJSONLoader,
+ )
+
+ result = get_loader_class_for_extension(".json")
+ assert result is not None
+ assert result[0] == SimpleJSONLoader
+
+
+class TestLoaderRegistry:
+ """Tests for LOADER_REGISTRY constant."""
+
+ def test_registry_is_dict(self) -> None:
+ """Test that registry is a dictionary."""
+ assert isinstance(LOADER_REGISTRY, dict)
+
+ def test_registry_entries_have_loader_class(self) -> None:
+ """Test that all entries have loader_class."""
+ for ext, entry in LOADER_REGISTRY.items():
+ assert "loader_class" in entry, f"Missing loader_class for {ext}"
+ assert callable(entry["loader_class"]), (
+ f"loader_class not callable for {ext}"
+ )
+
+ def test_registry_entries_have_loader_kwargs(self) -> None:
+ """Test that all entries have loader_kwargs (even if empty)."""
+ for ext, entry in LOADER_REGISTRY.items():
+ # loader_kwargs should exist or default to empty dict
+ kwargs = entry.get("loader_kwargs", {})
+ assert isinstance(kwargs, dict), f"loader_kwargs not dict for {ext}"
+
+ def test_registry_keys_start_with_dot(self) -> None:
+ """Test that all registry keys start with a dot."""
+ for ext in LOADER_REGISTRY.keys():
+ assert ext.startswith("."), (
+ f"Extension {ext} doesn't start with dot"
+ )
+
+ def test_registry_keys_are_lowercase(self) -> None:
+ """Test that all registry keys are lowercase."""
+ for ext in LOADER_REGISTRY.keys():
+ assert ext == ext.lower(), f"Extension {ext} is not lowercase"
diff --git a/tests/document_loaders/test_yaml_loader.py b/tests/document_loaders/test_yaml_loader.py
new file mode 100644
index 0000000000..acbc5b6a19
--- /dev/null
+++ b/tests/document_loaders/test_yaml_loader.py
@@ -0,0 +1,172 @@
+"""Tests for YAMLLoader."""
+
+from pathlib import Path
+
+import pytest
+
+from local_deep_research.document_loaders.yaml_loader import (
+ YAMLLoader,
+ extract_text_from_yaml,
+)
+
+
+class TestYAMLLoader:
+ """Tests for YAMLLoader class."""
+
+ def test_load_simple_yaml(self, tmp_path: Path) -> None:
+ """Test loading a simple YAML file."""
+ yaml_file = tmp_path / "test.yaml"
+ yaml_file.write_text("name: test\nvalue: 123\n")
+
+ loader = YAMLLoader(yaml_file)
+ docs = loader.load()
+
+ assert len(docs) == 1
+ assert "name: test" in docs[0].page_content
+ assert "value: 123" in docs[0].page_content
+ assert docs[0].metadata["source"] == str(yaml_file)
+ assert docs[0].metadata["file_type"] == "yaml"
+
+ def test_load_nested_yaml(self, tmp_path: Path) -> None:
+ """Test loading nested YAML structure."""
+ yaml_content = """
+database:
+ host: localhost
+ port: 5432
+ credentials:
+ username: admin
+ password: secret
+"""
+ yaml_file = tmp_path / "nested.yaml"
+ yaml_file.write_text(yaml_content)
+
+ loader = YAMLLoader(yaml_file)
+ docs = loader.load()
+
+ assert len(docs) == 1
+ assert "database:" in docs[0].page_content
+ assert "host: localhost" in docs[0].page_content
+ assert "credentials:" in docs[0].page_content
+
+ def test_load_yaml_with_list(self, tmp_path: Path) -> None:
+ """Test loading YAML with list values."""
+ yaml_content = """
+fruits:
+ - apple
+ - banana
+ - cherry
+"""
+ yaml_file = tmp_path / "list.yaml"
+ yaml_file.write_text(yaml_content)
+
+ loader = YAMLLoader(yaml_file)
+ docs = loader.load()
+
+ assert len(docs) == 1
+ assert "apple" in docs[0].page_content
+ assert "banana" in docs[0].page_content
+
+ def test_load_invalid_yaml_returns_raw_content(
+ self, tmp_path: Path
+ ) -> None:
+ """Test that invalid YAML returns raw content with parse_error flag."""
+ yaml_file = tmp_path / "invalid.yaml"
+ yaml_file.write_text("invalid: yaml: content: [")
+
+ loader = YAMLLoader(yaml_file)
+ docs = loader.load()
+
+ assert len(docs) == 1
+ assert docs[0].metadata.get("parse_error") is True
+ assert "invalid: yaml: content:" in docs[0].page_content
+
+ def test_load_empty_yaml(self, tmp_path: Path) -> None:
+ """Test loading empty YAML file."""
+ yaml_file = tmp_path / "empty.yaml"
+ yaml_file.write_text("")
+
+ loader = YAMLLoader(yaml_file)
+ docs = loader.load()
+
+ assert len(docs) == 1
+ assert docs[0].page_content == ""
+
+ def test_load_yaml_with_unicode(self, tmp_path: Path) -> None:
+ """Test loading YAML with unicode characters."""
+ yaml_content = "greeting: こんにちは\nemoji: 🎉\n"
+ yaml_file = tmp_path / "unicode.yaml"
+ yaml_file.write_text(yaml_content, encoding="utf-8")
+
+ loader = YAMLLoader(yaml_file)
+ docs = loader.load()
+
+ assert len(docs) == 1
+ assert "こんにちは" in docs[0].page_content
+ assert "🎉" in docs[0].page_content
+
+ def test_lazy_load(self, tmp_path: Path) -> None:
+ """Test lazy_load returns an iterator."""
+ yaml_file = tmp_path / "test.yaml"
+ yaml_file.write_text("key: value\n")
+
+ loader = YAMLLoader(yaml_file)
+ result = loader.lazy_load()
+
+ # Should be an iterator
+ assert hasattr(result, "__iter__")
+ assert hasattr(result, "__next__")
+
+ # Should yield documents
+ docs = list(result)
+ assert len(docs) == 1
+
+ def test_file_not_found_raises_error(self) -> None:
+ """Test that missing file raises appropriate error."""
+ loader = YAMLLoader("/nonexistent/path/file.yaml")
+
+ with pytest.raises(Exception):
+ loader.load()
+
+
+class TestExtractTextFromYaml:
+ """Tests for extract_text_from_yaml function."""
+
+ def test_extract_simple_yaml(self) -> None:
+ """Test extracting text from simple YAML bytes."""
+ content = b"name: test\nvalue: 123"
+ result = extract_text_from_yaml(content)
+
+ assert "name: test" in result
+ assert "value: 123" in result
+
+ def test_extract_nested_yaml(self) -> None:
+ """Test extracting text from nested YAML bytes."""
+ content = b"parent:\n child: value\n number: 42"
+ result = extract_text_from_yaml(content)
+
+ assert "parent:" in result
+ assert "child: value" in result
+
+ def test_extract_invalid_yaml_returns_raw(self) -> None:
+ """Test that invalid YAML returns raw content."""
+ content = b"invalid: yaml: [unclosed"
+ result = extract_text_from_yaml(content)
+
+ # Should return the raw content
+ assert "invalid:" in result
+
+ def test_extract_with_encoding_errors(self) -> None:
+ """Test handling of encoding errors."""
+ # Invalid UTF-8 bytes
+ content = b"name: test\xff\xfe"
+ result = extract_text_from_yaml(content)
+
+ # Should still return something (with errors ignored)
+ assert "name" in result
+
+ def test_extract_empty_yaml(self) -> None:
+ """Test extracting from empty YAML."""
+ content = b""
+ result = extract_text_from_yaml(content)
+
+ assert result == ""