Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
test(ingest): add unit tests for file, web, and feed ingestors
Mohammed23715b32f49be5c
diff --git a/tests/ingest/test_feed_ingestor.py b/tests/ingest/test_feed_ingestor.pynew file mode 100644index 00000000..244cc358--- /dev/null+++ b/tests/ingest/test_feed_ingestor.py@@ -0,0 +1,259 @@+from unittest.mock import MagicMock, patch++import pytest+import requests++from semantica.ingest.feed_ingestor import (+ FeedData,+ FeedIngestor,+ FeedItem,+ FeedParser,+ ProcessingError,+)+++# --- Fixtures ---+def complex_atom_xml() -> str:+ """Return a complex Atom feed XML string."""++ return """+ <feed xmlns="http://www.w3.org/2005/Atom">+ <title>Atom</title>+ <link href="http://example.com" rel="self"/>+ <subtitle>Subtitle</subtitle>+ <updated>2025-01-01T00:00:00Z</updated>+ <entry>+ <title>Entry 1</title>+ <link href="http://example.com/1" rel="alternate"/>+ <summary>Summary</summary>+ <content>Full Content</content>+ <id>uuid:123</id>+ <published>2025-01-01T00:00:00Z</published>+ <updated>2025-01-02T00:00:00Z</updated>+ <category term="tech"/>+ <category term="news"/>+ </entry>+ </feed>+ """+++# --- Tests ---+def test_parse_atom_complex(complex_atom_xml: str) -> None:+ """Test parsing a complex Atom feed."""++ parser = FeedParser()+ data = parser.parse_feed(complex_atom_xml)+ item = data.items[0]++ assert data.title == "Atom"+ assert len(data.items) == 1+ assert item.description == "Summary"+ assert item.content == "Full Content"+ assert "tech" in item.categories+ assert "news" in item.categories+ assert item.published.year == 2025+++def test_parse_rss_dates() -> None:+ """Test date parsing logic specific to RSS."""++ xml = """+ <rss version="2.0">+ <channel>+ <title>T</title>+ <link>http://l.com</link>+ <item>+ <title>T</title>+ <pubDate>Mon, 27 Jan 2025 12:00:00 GMT</pubDate>+ </item>+ </channel>+ </rss>+ """+ parser = FeedParser()+ data = parser.parse_feed(xml)++ assert data.items[0].published.year == 2025+++def test_ingest_feed_errors() -> None:+ """Test error handling in ingest_feed."""++ ingestor = FeedIngestor()++ with pytest.raises(Exception):+ ingestor.ingest_feed("not_a_url")++ with patch(+ "requests.get",+ side_effect=requests.exceptions.RequestException("Fail"),+ ):+ with pytest.raises(ProcessingError):+ ingestor.ingest_feed("http://valid.com")+++def test_monitor_loop_lifecycle() -> None:+ """Test start, run loop once, and stop."""++ ingestor = FeedIngestor()+ ingestor.monitor.add_feed("http://test.com")++ def side_effect_sleep(seconds: float) -> None:+ ingestor.monitor.monitoring = False++ with patch("time.sleep", side_effect=side_effect_sleep):+ with patch.object(+ ingestor.monitor,+ "check_updates",+ side_effect=Exception("Check Fail"),+ ):+ ingestor.monitor.monitoring = True+ ingestor.monitor._monitoring_loop()++ assert ingestor.monitor.monitoring is False+++def test_monitor_threading() -> None:+ """Test that start_monitoring actually spawns a thread."""++ ingestor = FeedIngestor()+ ingestor.monitor.add_feed("http://test.com")++ with patch("threading.Thread") as mock_thread:+ ingestor.monitor.start_monitoring()+ mock_thread.return_value.start.assert_called_once()++ # Test double start and stop+ ingestor.monitor.start_monitoring()+ ingestor.monitor.stop_monitoring()++ assert ingestor.monitor.monitoring is False+++def test_extract_content_helper() -> None:+ """Test the extract_content method full fields."""++ ingestor = FeedIngestor()+ item = FeedItem(+ title="T",+ link="L",+ description="D",+ content="C",+ categories=["cat"],+ )++ res = ingestor.extract_content(item)++ assert res["content"] == "C"+ assert res["categories"] == ["cat"]+++def test_extract_content_missing_fields() -> None:+ """Test extract_content with missing optional fields."""++ ingestor = FeedIngestor()+ item = FeedItem(title="T", link="L", description="D")++ res = ingestor.extract_content(item)++ assert res["content"] == "D"+ assert res["published"] is None+ assert res["updated"] is None+++def test_parse_date_formats() -> None:+ """Test various date formats."""++ parser = FeedParser()+ d1 = parser._parse_date("Mon, 27 Jan 2025 12:00:00 GMT")+ d2 = parser._parse_date("2025-01-27T12:00:00Z")+ d3 = parser._parse_date("2025-01-27")++ assert d1.year == 2025+ assert d2.year == 2025+ assert d3.year == 2025+ with pytest.raises(ValueError):+ parser._parse_date("Not a date")+++def test_validate_feed() -> None:+ """Test feed validation logic."""++ parser = FeedParser()++ f1 = FeedData(+ title="T",+ link="http://e.com",+ items=[MagicMock(title="t")],+ )+ f2 = FeedData(+ title="",+ link="http://e.com",+ items=[MagicMock(title="t")],+ )+ f3 = FeedData(title="T", link="http://e.com", items=[])++ assert parser.validate_feed(f1) is True+ assert parser.validate_feed(f2) is False+ assert parser.validate_feed(f3) is False+++def test_discover_feeds_empty() -> None:+ """Test discovery finding nothing."""++ ingestor = FeedIngestor()+ html = "<html><body>No feeds here</body></html>"++ with patch("requests.get", return_value=MagicMock(text=html)):+ feeds = ingestor.discover_feeds("http://site.com")++ assert len(feeds) == 0+++def test_discover_feeds_found() -> None:+ """Test discovering feeds in HTML content."""+ ingestor = FeedIngestor()+ html = """+ <html>+ <head>+ <link rel="alternate" type="application/rss+xml" href="/rss.xml">+ </head>+ <body>+ <a href="/feed">RSS</a>+ </body>+ </html>+ """++ mock_response = MagicMock()+ mock_response.text = html+ mock_response.status_code = 200++ with patch("requests.get", return_value=mock_response):+ with patch("requests.head") as mock_head:+ # Mock HEAD request headers for the verification step+ mock_head.return_value.headers = {+ "Content-Type": "application/rss+xml",+ }+ mock_head.return_value.status_code = 200++ feeds = ingestor.discover_feeds("http://site.com")++ assert "http://site.com/rss.xml" in feeds+ assert "http://site.com/feed" in feeds+++def test_feed_monitor_options() -> None:+ """Test adding feeds with specific options."""++ ingestor = FeedIngestor()++ with patch.object(ingestor.monitor, "add_feed") as mock_add:+ with patch.object(ingestor.monitor, "start_monitoring") as mock_start:+ ingestor.monitor_feeds(["http://f.com"], interval=60, start=True)++ mock_add.assert_called_with(+ "http://f.com",+ interval=60,+ start=True,+ )+ mock_start.assert_called_once()diff --git a/tests/ingest/test_file_ingestor.py b/tests/ingest/test_file_ingestor.pynew file mode 100644index 00000000..60a18ac6--- /dev/null+++ b/tests/ingest/test_file_ingestor.py@@ -0,0 +1,324 @@+import sys+import types+from unittest.mock import MagicMock++# --- Mock missing cloud modules ---+# We must mock these BEFORE importing the file_ingestor module+# and we must populate the attributes that the code tries to import/patch.++module_names = [+ "google",+ "google.cloud",+ "google.cloud.storage",+ "azure",+ "azure.storage",+ "azure.storage.blob",+]++for name in module_names:+ if name not in sys.modules:+ mod = types.ModuleType(name)+ sys.modules[name] = mod++# Explicitly add the classes that will be patched/used+sys.modules["google.cloud.storage"].Client = MagicMock()+sys.modules["azure.storage.blob"].BlobServiceClient = MagicMock()++from pathlib import Path # noqa: E402+from unittest.mock import patch # noqa: E402++# Now proceed with normal imports+import pytest # noqa: E402++from semantica.ingest.file_ingestor import ( # noqa: E402+ CloudStorageIngestor,+ FileIngestor,+ FileObject,+ FileTypeDetector,+ ProcessingError,+ ValidationError,+)+++# --- Fixtures ---+def temp_files(tmp_path: Path) -> Path:+ """Create a temporary directory with some dummy files."""+ txt_file = tmp_path / "test.txt"+ txt_file.write_text("Hello World", encoding="utf-8") # 11 bytes++ # Binary file (PDF signature)+ pdf_file = tmp_path / "test.pdf"+ pdf_file.write_bytes(b"%PDF-1.4 content")++ # Subdirectory+ sub_dir = tmp_path / "subdir"+ sub_dir.mkdir()+ sub_file = sub_dir / "sub.log"+ sub_file.write_text("Log content")++ # Latin-1 file to test encoding fallback (4 bytes)+ latin_file = tmp_path / "latin.txt"+ latin_file.write_bytes(b"Caf\xe9")++ return tmp_path+++# --- FileObject Tests ---+def test_file_object_text_decoding() -> None:+ """Test text property decoding logic."""+ f1 = FileObject(+ path="p",+ name="n",+ size=1,+ file_type="txt",+ content=b"Hello",+ )+ f2 = FileObject(+ path="p",+ name="n",+ size=1,+ file_type="txt",+ content=b"Caf\xe9",+ )+ f3 = FileObject(+ path="p",+ name="n",+ size=1,+ file_type="txt",+ content=None,+ )+ f4 = FileObject(+ path="p", name="n", size=1, file_type="txt", content="Already String"+ )++ assert f1.text == "Hello"+ assert f2.text == "Café"+ assert f3.text == ""+ assert f4.text == "Already String"+++# --- FileTypeDetector Tests ---+def test_type_detector_extended() -> None:+ """Test extended file type detection logic."""++ detector = FileTypeDetector()+ png_sig = b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a"++ # We must mock .exists() so detect_type enters the mime detection block+ with patch("pathlib.Path.exists", return_value=True):+ with patch("mimetypes.guess_type", return_value=("video/mp4", None)):+ is_mp4 = detector.detect_type("movie.mp4")++ detected_gz = detector.detect_type("file.tar.gz")+ detected_png = detector.detect_type("test", content=png_sig)+ detected_unknown = detector.detect_type("unknown")++ assert detected_gz == "gz"+ assert is_mp4 == "mp4"+ assert detected_png == "png"+ assert detected_unknown == "unknown"+++# --- CloudStorageIngestor Tests ---+@patch("boto3.client")+def test_cloud_storage_s3(mock_boto: MagicMock) -> None:+ """Test S3 provider."""++ mock_s3 = mock_boto.return_value+ mock_s3.get_paginator.return_value.paginate.return_value = [+ {+ "Contents": [+ {+ "Key": "doc.txt",+ "Size": 100,+ "LastModified": "2025",+ "ETag": "tag",+ }+ ]+ }+ ]+ mock_s3.get_object.return_value = {+ "Body": MagicMock(read=lambda: b"s3_data"),+ }++ ingestor = CloudStorageIngestor(+ "s3",+ access_key_id="x",+ secret_access_key="y",+ )+ objects = ingestor.list_objects("bucket")+ content = ingestor.download_object("bucket", "doc.txt")++ assert objects[0]["key"] == "doc.txt"+ assert content == b"s3_data"+++@patch("google.cloud.storage.Client")+def test_cloud_storage_gcs(mock_gcs_cls: MagicMock) -> None:+ """Test Google Cloud Storage provider."""++ mock_client = mock_gcs_cls.return_value+ mock_blob = MagicMock()+ mock_blob.name = "gcs.txt"+ mock_blob.size = 200+ mock_blob.updated = "2025"+ mock_blob.etag = "tag"+ mock_blob.download_as_bytes.return_value = b"gcs_data"++ mock_client.bucket.return_value.list_blobs.return_value = [mock_blob]+ mock_client.bucket.return_value.blob.return_value = mock_blob++ ingestor = CloudStorageIngestor("gcs")+ objects = ingestor.list_objects("bucket")+ content = ingestor.download_object("bucket", "gcs.txt")++ assert objects[0]["key"] == "gcs.txt"+ assert content == b"gcs_data"+++@patch("azure.storage.blob.BlobServiceClient.from_connection_string")+def test_cloud_storage_azure(mock_azure_cls: MagicMock) -> None:+ """Test Azure Blob Storage provider."""++ mock_client = mock_azure_cls.return_value+ mock_blob = MagicMock()+ mock_blob.name = "azure.txt"+ mock_blob.size = 300+ mock_blob.last_modified = "2025"+ mock_blob.etag = "tag"++ mock_container = mock_client.get_container_client.return_value+ mock_container.list_blobs.return_value = [mock_blob]++ mock_blob_client = mock_container.get_blob_client.return_value+ mock_download = mock_blob_client.download_blob.return_value+ mock_download.readall.return_value = b"azure_data"++ ingestor = CloudStorageIngestor("azure", connection_string="conn")+ objects = ingestor.list_objects("bucket")+ content = ingestor.download_object("bucket", "azure.txt")++ assert objects[0]["key"] == "azure.txt"+ assert content == b"azure_data"+++def test_cloud_storage_invalid() -> None:+ """Test invalid cloud provider raises error."""++ with pytest.raises(ValueError):+ CloudStorageIngestor("dropbox")+++def test_cloud_storage_list_error() -> None:+ """Test error handling in list_objects."""++ with patch("boto3.client") as mock_boto:+ # Raise error on the METHOD call, not the constructor+ mock_boto.return_value.get_paginator.side_effect = Exception(+ "Auth Fail",+ )++ ingestor = CloudStorageIngestor("s3")+ with pytest.raises(ProcessingError):+ ingestor.list_objects("bucket")+++def test_cloud_storage_download_error() -> None:+ """Test error handling in download_object."""++ with patch("boto3.client") as mock_boto:+ mock_boto.return_value.get_object.side_effect = Exception("Fail")+ ingestor = CloudStorageIngestor("s3")+ with pytest.raises(ProcessingError):+ ingestor.download_object("bucket", "key")+++# --- FileIngestor Tests ---+def test_ingest_directory_recursive(temp_files: Path) -> None:+ """Test recursive directory ingestion."""++ ingestor = FileIngestor()+ results = ingestor.ingest_directory(temp_files, recursive=True)++ assert len(results) >= 3+++def test_ingest_directory_non_recursive(temp_files: Path) -> None:+ """Test scanning only top level."""++ ingestor = FileIngestor()+ results = ingestor.ingest_directory(temp_files, recursive=False)+ has_sub_log = any("sub.log" in f.name for f in results)++ assert len(results) == 3+ assert not has_sub_log+++def test_ingest_file_callback(temp_files: Path) -> None:+ """Test progress callback."""++ ingestor = FileIngestor()+ mock_cb = MagicMock()+ ingestor.set_progress_callback(mock_cb)++ ingestor.ingest_directory(temp_files, recursive=False)++ assert mock_cb.called+++def test_ingest_file_fail_fast(temp_files: Path) -> None:+ """Test directory ingestion failure handling."""++ ingestor = FileIngestor(fail_fast=True)++ with patch.object(ingestor, "ingest_file", side_effect=Exception("Boom")):+ with pytest.raises(ProcessingError):+ ingestor.ingest_directory(temp_files)+++def test_ingest_alias(temp_files: Path) -> None:+ """Test the .ingest() alias method."""++ ingestor = FileIngestor()+ res_dir = ingestor.ingest(temp_files)+ res_file = ingestor.ingest(temp_files / "test.txt")++ assert len(res_dir) > 0+ assert len(res_file) == 1+ with pytest.raises(ValidationError):+ ingestor.ingest("ghost_path")+++@patch("semantica.ingest.file_ingestor.CloudStorageIngestor")+def test_ingest_cloud_loop_errors(mock_cloud_cls: MagicMock) -> None:+ """Test cloud ingestion where one file fails."""++ ingestor = FileIngestor(fail_fast=False)+ mock_inst = mock_cloud_cls.return_value+ mock_inst.list_objects.return_value = [+ {"key": "good.txt", "size": 10, "last_modified": "2025", "etag": "1"},+ {"key": "bad.txt", "size": 10, "last_modified": "2025", "etag": "2"},+ ]+ mock_inst.download_object.side_effect = [b"good", Exception("Bad dl")]++ results = ingestor.ingest_cloud("s3", "bucket")++ assert len(results) == 1+ assert results[0].name == "good.txt"+++def test_scan_directory_filters(temp_files: Path) -> None:+ """Deep dive into filter logic."""++ ingestor = FileIngestor()++ # latin.txt is 4 bytes. 4 <= 5 is True.+ # So we expect latin.txt to survive.+ res_max = ingestor.scan_directory(temp_files, max_size=5)++ # All files are small.+ res_min = ingestor.scan_directory(temp_files, min_size=1)++ assert len(res_max) == 1 # Expect latin.txt+ assert len(res_min) >= 3diff --git a/tests/ingest/test_web_ingestor.py b/tests/ingest/test_web_ingestor.pynew file mode 100644index 00000000..167d3be0--- /dev/null+++ b/tests/ingest/test_web_ingestor.py@@ -0,0 +1,415 @@+from unittest.mock import MagicMock, patch++import pytest+import requests++from semantica.ingest.web_ingestor import (+ ContentExtractor,+ ProcessingError,+ RateLimiter,+ RobotsChecker,+ SitemapCrawler,+ WebContent,+ WebIngestor,+)+++# --- Fixtures ---+def sample_html() -> str:+ """Return a simple HTML string."""++ return """<html>+ <head><title>T</title></head>+ <body><a href='/1'>1</a></body>+ </html>"""+++# --- Sitemap Tests ---+def test_sitemap_index_recursion() -> None:+ """Test crawling a sitemap index that points to other sitemaps."""++ crawler = SitemapCrawler()++ index_xml = """+ <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">+ <sitemap><loc>http://ex.com/s1.xml</loc></sitemap>+ </sitemapindex>+ """++ child_xml = """+ <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">+ <url><loc>http://ex.com/page1</loc></url>+ </urlset>+ """++ with patch("requests.get") as mock_get:+ mock_get.side_effect = [+ MagicMock(status_code=200, content=index_xml.encode()),+ MagicMock(status_code=200, content=child_xml.encode()),+ ]+ urls = crawler.crawl_sitemap_index("http://ex.com/index.xml")++ assert "http://ex.com/page1" in urls+++def test_sitemap_fallback_parsing() -> None:+ """Test sitemap parsing without namespaces."""++ crawler = SitemapCrawler()+ xml = "<urlset><url><loc>http://a.com</loc></url></urlset>"++ with patch(+ "requests.get",+ return_value=MagicMock(+ status_code=200,+ content=xml.encode(),+ ),+ ):+ urls = crawler.parse_sitemap("http://s.xml")++ assert "http://a.com" in urls+++def test_sitemap_invalid_xml() -> None:+ """Test parsing invalid XML raises ProcessingError."""++ crawler = SitemapCrawler()++ with patch(+ "requests.get",+ return_value=MagicMock(status_code=200, content=b"NOT XML"),+ ):+ with pytest.raises(ProcessingError):+ crawler.parse_sitemap("http://s.xml")+++# --- Content Extraction Tests ---+def test_extract_links_schemes() -> None:+ """Ensure we ignore mailto and javascript links."""++ extractor = ContentExtractor()+ html = """+ <a href="http://good.com">Good</a>+ <a href="mailto:[email protected]">Mail</a>+ <a href="tel:123">Phone</a>+ <a href="javascript:void(0)">JS</a>+ """+ links = extractor.extract_links(html)++ assert len(links) == 1+ assert links[0] == "http://good.com"+++def test_extract_metadata_empty() -> None:+ """Test extraction with missing meta tags."""++ extractor = ContentExtractor()+ html = "<html><body>No Head</body></html>"+ meta = extractor.extract_metadata(html, "http://u.com")++ assert meta.get("title") is None or meta.get("title") == ""+ assert meta.get("description") is None or meta.get("description") == ""+++# --- WebIngestor Tests ---+@patch("requests.Session.get")+def test_ingest_url_happy(mock_get: MagicMock, sample_html: str) -> None:+ """Test successful URL ingestion."""++ mock_get.return_value = MagicMock(status_code=200, text=sample_html)+ ingestor = WebIngestor(respect_robots=False)+ res = ingestor.ingest_url("http://site.com")++ assert res.title == "T"+++@patch("semantica.ingest.web_ingestor.RobotFileParser")+def test_robots_blocking(mock_parser_cls: MagicMock) -> None:+ """Test that we actually block if robots says no."""++ mock_inst = mock_parser_cls.return_value+ mock_inst.can_fetch.return_value = False++ ingestor = WebIngestor(respect_robots=True)++ with pytest.raises(ProcessingError):+ ingestor.ingest_url("http://site.com/private")+++def test_crawl_domain_visited_logic() -> None:+ """Test that we don't crawl the same page twice."""++ with patch.object(WebIngestor, "ingest_url") as mock_ingest:+ p1 = WebContent(url="http://a.com", links=["http://a.com"])+ mock_ingest.return_value = p1++ ingestor = WebIngestor(respect_robots=False)+ results = ingestor.crawl_domain("http://a.com", max_pages=10)++ assert len(results) == 1+ assert mock_ingest.call_count == 1+++def test_rate_limiter() -> None:+ """Test that rate limiter actually sleeps."""++ limiter = RateLimiter(delay=0.1)++ with patch("time.sleep") as mock_sleep:+ # Need 4 values: [init_check, init_set, 2nd_check, 2nd_set]+ with patch("time.time", side_effect=[100.0, 100.0, 100.05, 100.2]):+ limiter.wait_if_needed()+ limiter.wait_if_needed()++ assert mock_sleep.called+++def test_rate_limiter_no_delay() -> None:+ """Test that 0 delay does not sleep."""++ limiter = RateLimiter(delay=0.0)+ with patch("time.sleep") as mock_sleep:+ limiter.wait_if_needed()++ assert not mock_sleep.called+++@patch("requests.Session.get")+def test_ingest_url_retry(mock_get: MagicMock) -> None:+ """Test that it retries on failure."""++ mock_get.side_effect = [+ requests.exceptions.ConnectionError("Fail 1"),+ requests.exceptions.ConnectionError("Fail 2"),+ MagicMock(status_code=200, text="<html></html>"),+ ]++ ingestor = WebIngestor(respect_robots=False)++ assert ingestor.session.adapters["https://"].max_retries.total == 3+++def test_url_filters() -> None:+ """Test URL filtering logic."""++ ingestor = WebIngestor(respect_robots=False)+ urls = ["https://good.com/a", "https://bad.com/b", "https://good.com/skip"]++ f1 = ingestor._apply_url_filters(urls, {"domains": ["good.com"]})+ f2 = ingestor._apply_url_filters(urls, {"pattern": r"/a$"})+ f3 = ingestor._apply_url_filters(urls, {"exclude_pattern": "skip"})++ assert len(f1) == 2+ assert f2 == ["https://good.com/a"]+ assert "https://good.com/skip" not in f3+++def test_extract_text_cleaning() -> None:+ """Test stripping scripts and styles from text."""++ extractor = ContentExtractor()+ html = """+ <html>+ <style>body { color: red; }</style>+ <script>alert('x');</script>+ <body>+ <h1>Real Text</h1>+ </body>+ </html>+ """+ text = extractor.extract_text(html)++ assert "Real Text" in text+ assert "alert" not in text+ assert "color: red" not in text+++def test_robots_checker_cache() -> None:+ """Test that robots.txt is cached per domain."""++ with patch("semantica.ingest.web_ingestor.RobotFileParser") as mock_parser:+ mock_parser.return_value.can_fetch.return_value = True+ checker = RobotsChecker()++ # First call: Should trigger parser creation+ checker.can_fetch("http://example.com/a")++ # Second call: Should use cache (no new parser)+ checker.can_fetch("http://example.com/b")++ # Verify parser was initialized only once+ assert mock_parser.call_count == 1+++def test_web_ingestor_crawl_sitemap_integration() -> None:+ """Test the high-level crawl_sitemap method in WebIngestor."""++ ingestor = WebIngestor(respect_robots=False)++ # 1. Mock the SitemapCrawler to return 2 URLs+ with patch(+ "semantica.ingest.web_ingestor.SitemapCrawler.parse_sitemap"+ ) as mock_parse:+ mock_parse.return_value = ["http://site.com/1", "http://site.com/2"]++ # 2. Mock ingest_url to successfully process those URLs+ with patch.object(ingestor, "ingest_url") as mock_ingest:+ mock_ingest.return_value = MagicMock(url="http://site.com/1")++ results = ingestor.crawl_sitemap("http://site.com/sitemap.xml")++ # Should have called ingest_url twice+ assert len(results) == 2+ assert mock_ingest.call_count == 2+++def test_metadata_priority() -> None:+ """Test that OpenGraph tags take precedence over standard meta tags."""++ extractor = ContentExtractor()+ html = """+ <html>+ <head>+ <meta name="description" content="Standard Description">+ <meta property="og:description" content="OG Description">+ <meta name="author" content="Standard Author">+ </head>+ </html>+ """+ meta = extractor.extract_metadata(html, "http://site.com")++ assert meta["description"] == "Standard Description"+ assert meta["og"]["description"] == "OG Description"+ assert meta["author"] == "Standard Author"+++def test_crawl_domain_max_depth() -> None:+ """Test that crawling respects max depth/pages."""++ ingestor = WebIngestor(respect_robots=False)++ # Create a chain of links: P1 -> P2 -> P3+ p1 = WebContent(url="http://a.com/1", links=["http://a.com/2"])+ p2 = WebContent(url="http://a.com/2", links=["http://a.com/3"])+ p3 = WebContent(url="http://a.com/3", links=[])++ with patch.object(ingestor, "ingest_url") as mock_ingest:+ mock_ingest.side_effect = [p1, p2, p3]++ # Limit to 2 pages+ results = ingestor.crawl_domain("http://a.com/1", max_pages=2)++ assert len(results) == 2+ # Should have stopped before P3+ assert "http://a.com/3" not in [r.url for r in results]+++def test_crawl_sitemap_integration() -> None:+ """Test the full flow of crawling a sitemap and ingesting its URLs."""++ ingestor = WebIngestor(respect_robots=False)++ # 1. Mock the sitemap parser to return specific URLs+ with patch(+ "semantica.ingest.web_ingestor.SitemapCrawler.parse_sitemap"+ ) as mock_parse:+ mock_parse.return_value = ["http://site.com/1", "http://site.com/2"]++ # 2. Mock ingest_url to simulate successful extraction for each URL+ with patch.object(ingestor, "ingest_url") as mock_ingest:+ # Return dummy content for each call+ mock_ingest.side_effect = [+ WebContent(+ url="http://site.com/1",+ title="Page 1",+ text="1",+ html="",+ metadata={},+ links=[],+ ),+ WebContent(+ url="http://site.com/2",+ title="Page 2",+ text="2",+ html="",+ metadata={},+ links=[],+ ),+ ]++ results = ingestor.crawl_sitemap("http://site.com/sitemap.xml")++ # Verify the loop ran correctly+ assert len(results) == 2+ assert results[0].title == "Page 1"+ assert mock_ingest.call_count == 2+++def test_crawl_domain_max_pages() -> None:+ """Test that the crawler stops exactly at max_pages."""+ ingestor = WebIngestor(respect_robots=False)++ # Create a chain: P1 -> P2 -> P3 -> P4+ p1 = WebContent(+ url="http://a.com/1",+ links=["http://a.com/2"],+ title="",+ text="",+ html="",+ metadata={},+ )+ p2 = WebContent(+ url="http://a.com/2",+ links=["http://a.com/3"],+ title="",+ text="",+ html="",+ metadata={},+ )+ p3 = WebContent(+ url="http://a.com/3",+ links=["http://a.com/4"],+ title="",+ text="",+ html="",+ metadata={},+ )++ with patch.object(ingestor, "ingest_url") as mock_ingest:+ mock_ingest.side_effect = [p1, p2, p3]++ # Set limit to 2 pages+ results = ingestor.crawl_domain("http://a.com/1", max_pages=2)++ assert len(results) == 2+ assert results[0].url == "http://a.com/1"+ assert results[1].url == "http://a.com/2"++ # Verify P3 was never ingested+ res = [c[0][0] for c in mock_ingest.call_args_list]+ assert "http://a.com/3" not in res+++def test_metadata_opengraph_priority() -> None:+ """Test that OpenGraph tags are captured correctly."""+ extractor = ContentExtractor()+ # HTML with both standard meta and OG tags+ html = """+ <html>+ <head>+ <meta name="description" content="Basic Desc">+ <meta property="og:description" content="OG Desc">+ <meta property="og:title" content="OG Title">+ <meta property="og:image" content="http://img.jpg">+ </head>+ </html>+ """+ meta = extractor.extract_metadata(html, "http://site.com")++ # Check that OG data is structured correctly in the 'og' dict+ assert meta["og"]["description"] == "OG Desc"+ assert meta["og"]["title"] == "OG Title"+ assert meta["og"]["image"] == "http://img.jpg"+ # Basic description should still be available+ assert meta["description"] == "Basic Desc"