# SPDX-FileCopyrightText: 2026 Dennis Fink # # SPDX-License-Identifier: BSD-3-Clause from datetime import UTC, datetime, timedelta from pathlib import Path from types import ModuleType from typing import Any from unittest.mock import Mock from uuid import UUID import pytest import sqlalchemy as sa from bs4 import BeautifulSoup from flask import Flask from huey.exceptions import RetryTask from pytest import MonkeyPatch from webmentions_ssg import db from webmentions_ssg.models import SentWebmention, SentWebmentionStatus, Source from webmentions_ssg.tasks import source_parser from .scanner_helpers import BASE_URL, SOURCE_URL, configure_scanner, write_post @pytest.fixture def scanner_module(app: Flask, monkeypatch: pytest.MonkeyPatch) -> ModuleType: _ = app from webmentions_ssg.tasks import scanner monkeypatch.setattr(scanner, "is_http_url", Mock(return_value=True)) monkeypatch.setattr(source_parser, "is_http_url", Mock(return_value=True)) return scanner def run_scan(app: Flask, scanner_module: ModuleType) -> None: with app.app_context(): scanner_module.scan_sources() def test_manual_scan_retries_when_periodic_scan_holds_lock( app: Flask, scanner_module: ModuleType ) -> None: with app.app_context(): # A task imported earlier must still use the reinitialized backend. previous_backend = scanner_module.huey.huey scanner_module.huey.init_app(app) assert scanner_module.huey.huey is not previous_backend with ( scanner_module.huey.lock_task("scan-webmention-sources"), pytest.raises(RetryTask) as exc_info, ): scanner_module.manual_scan_sources.call_local() assert exc_info.value.delay == 30 def test_manual_scan_runs_without_lock_contention( app: Flask, scanner_module: ModuleType, tmp_path: Path ) -> None: configure_scanner(app, tmp_path) write_post(tmp_path, "manual", "Hello!") with app.app_context(): scanner_module.manual_scan_sources.call_local() source = db.session.scalar( sa.select(Source).where(Source.path == "manual/index.html") ) assert source is not None assert source.url == f"{BASE_URL}manual/" def test_manual_scan_propagates_unrelated_errors( scanner_module: ModuleType, monkeypatch: MonkeyPatch ) -> None: monkeypatch.setattr( scanner_module, "scan_sources", Mock(side_effect=RuntimeError("scan failed")) ) with pytest.raises(RuntimeError, match="scan failed"): scanner_module.manual_scan_sources.call_local() def test_scan_tree_returns_count_and_seen_paths( app: Flask, scanner_module: ModuleType, tmp_path: Path, monkeypatch: MonkeyPatch ) -> None: for name in ("good", "bad"): directory = tmp_path / name directory.mkdir() (directory / "index.html").write_text("") def parse(index_path: Path, **kwargs: Any) -> source_parser.ScannedSource: if index_path.parent.name == "bad": raise source_parser.SourceScanError("Unparseable source") return source_parser.ScannedSource( path="good/index.html", url=f"{BASE_URL}good/", content_hash="0" * 32, targets=frozenset(), ) monkeypatch.setattr(scanner_module, "scan_source_file", parse) sources: dict[str, Source] = {} urls: dict[str, str] = {} with app.app_context(): scan = scanner_module.scan_tree( tmp_path, BASE_URL, sources, urls, datetime.now(UTC) ) assert scan.scanned_count == 1 assert scan.seen_paths == frozenset({"good/index.html", "bad/index.html"}) assert list(sources) == ["good/index.html"] assert urls == {f"{BASE_URL}good/": "good/index.html"} def test_scan_creates_source_and_webmentions( app: Flask, scanner_module: ModuleType, tmp_path: Path, monkeypatch: MonkeyPatch ) -> None: configure_scanner(app, tmp_path) write_post( tmp_path, "example", """ A B """, ) queued: list[UUID] = [] monkeypatch.setattr(scanner_module, "send_webmention", queued.append) run_scan(app, scanner_module) with app.app_context(): source = db.session.scalar(sa.select(Source)) assert source is not None assert source.path == "example/index.html" assert source.url == SOURCE_URL assert source.revision == 1 assert source.deleted_at is None assert len(source.content_hash) == 32 webmentions = list( db.session.scalars( sa.select(SentWebmention).order_by(SentWebmention.target) ) ) assert [webmention.target for webmention in webmentions] == [ "https://example.com/a", "https://example.com/b", ] assert all(webmention.active for webmention in webmentions) assert all(webmention.desired_revision == 1 for webmention in webmentions) assert all(webmention.processed_revision is None for webmention in webmentions) identifiers = {webmention.uuid for webmention in webmentions} assert set(queued) == identifiers def test_duplicate_canonical_url_skips_alias_and_commits_other_sources( app: Flask, scanner_module: ModuleType, tmp_path: Path, monkeypatch: MonkeyPatch, caplog: pytest.LogCaptureFixture, ) -> None: configure_scanner(app, tmp_path) for slug in ("first", "second"): write_post( tmp_path, slug, f'Link', canonical=SOURCE_URL, entry_url=SOURCE_URL, ) write_post( tmp_path, "unrelated", 'Link' ) queued: list[UUID] = [] monkeypatch.setattr(scanner_module, "send_webmention", queued.append) run_scan(app, scanner_module) run_scan(app, scanner_module) with app.app_context(): sources = list(db.session.scalars(sa.select(Source))) webmentions = list(db.session.scalars(sa.select(SentWebmention))) assert len(sources) == 2 assert {source.url for source in sources} == { SOURCE_URL, f"{BASE_URL}unrelated/", } duplicate_paths = {source.path for source in sources} & { "first/index.html", "second/index.html", } assert len(duplicate_paths) == 1 assert all(source.revision == 1 for source in sources) assert len(webmentions) == 2 assert {webmention.target for webmention in webmentions} in ( {"https://example.com/first", "https://example.com/unrelated"}, {"https://example.com/second", "https://example.com/unrelated"}, ) assert set(queued) == {webmention.uuid for webmention in webmentions} assert "duplicate canonical URL" in caplog.text assert SOURCE_URL in caplog.text def test_existing_source_owns_canonical_url_when_alias_is_added( app: Flask, scanner_module: ModuleType, tmp_path: Path, monkeypatch: MonkeyPatch, caplog: pytest.LogCaptureFixture, ) -> None: configure_scanner(app, tmp_path) write_post( tmp_path, "owner", "

Original content.

", canonical=SOURCE_URL, entry_url=SOURCE_URL, ) monkeypatch.setattr(scanner_module, "send_webmention", lambda identifier: None) run_scan(app, scanner_module) # The later-added alias must not take the persisted owner's URL, regardless # of filesystem traversal order. write_post( tmp_path, "alias", 'Link', canonical=SOURCE_URL, entry_url=SOURCE_URL, ) write_post( tmp_path, "owner", 'Link', canonical=SOURCE_URL, entry_url=SOURCE_URL, ) run_scan(app, scanner_module) with app.app_context(): sources = list(db.session.scalars(sa.select(Source))) targets = list(db.session.scalars(sa.select(SentWebmention.target))) assert len(sources) == 1 assert sources[0].path == "owner/index.html" assert sources[0].url == SOURCE_URL assert sources[0].revision == 2 assert targets == ["https://example.com/owner"] assert "duplicate canonical URL" in caplog.text assert "alias/index.html" in caplog.text assert "owner/index.html" in caplog.text def test_deleted_source_still_reserves_its_canonical_url( app: Flask, scanner_module: ModuleType, tmp_path: Path, monkeypatch: MonkeyPatch, caplog: pytest.LogCaptureFixture, ) -> None: configure_scanner(app, tmp_path) path = write_post( tmp_path, "owner", "

Original content.

", canonical=SOURCE_URL, entry_url=SOURCE_URL, ) monkeypatch.setattr(scanner_module, "send_webmention", lambda identifier: None) write_post(tmp_path, "unrelated", "

Other page remains published.

") run_scan(app, scanner_module) path.unlink() run_scan(app, scanner_module) write_post( tmp_path, "alias", "

Alias content.

", canonical=SOURCE_URL, entry_url=SOURCE_URL, ) write_post(tmp_path, "unrelated", "

Another source.

") run_scan(app, scanner_module) with app.app_context(): sources = { source.path: source for source in db.session.scalars(sa.select(Source)) } assert set(sources) == {"owner/index.html", "unrelated/index.html"} assert sources["owner/index.html"].deleted_at is not None assert sources["unrelated/index.html"].deleted_at is None assert "duplicate canonical URL" in caplog.text assert SOURCE_URL in caplog.text def test_unchanged_source_does_not_increment_revision( app: Flask, scanner_module: ModuleType, tmp_path: Path, monkeypatch: MonkeyPatch ) -> None: configure_scanner(app, tmp_path) write_post( tmp_path, "example", """ A """, ) queued: list[UUID] = [] monkeypatch.setattr(scanner_module, "send_webmention", queued.append) run_scan(app, scanner_module) with app.app_context(): webmention = db.session.scalar(sa.select(SentWebmention)) assert webmention is not None webmention.processed_revision = 1 webmention.sent_revision = 1 webmention.status = SentWebmentionStatus.SENT db.session.commit() queued.clear() run_scan(app, scanner_module) with app.app_context(): source = db.session.scalar(sa.select(Source)) assert source is not None assert source.revision == 1 assert queued == [] def test_changing_relative_timestamp_does_not_resend( app: Flask, scanner_module: ModuleType, tmp_path: Path, monkeypatch: MonkeyPatch ) -> None: configure_scanner(app, tmp_path) path = write_post( tmp_path, "example", 'Target' ) html = path.read_text(encoding="utf-8") path.write_text( html.replace( '
', '' '
', ), encoding="utf-8", ) queued: list[UUID] = [] monkeypatch.setattr(scanner_module, "send_webmention", queued.append) run_scan(app, scanner_module) with app.app_context(): source = db.session.scalar(sa.select(Source)) webmention = db.session.scalar(sa.select(SentWebmention)) assert source is not None and webmention is not None original_hash = source.content_hash webmention.processed_revision = 1 webmention.sent_revision = 1 webmention.status = SentWebmentionStatus.SENT db.session.commit() queued.clear() path.write_text( path.read_text(encoding="utf-8").replace("5 minutes ago", "6 minutes ago"), encoding="utf-8", ) run_scan(app, scanner_module) with app.app_context(): source = db.session.scalar(sa.select(Source)) webmention = db.session.scalar(sa.select(SentWebmention)) assert source is not None and webmention is not None assert source.content_hash == original_hash assert source.revision == 1 assert webmention.desired_revision == 1 assert webmention.processed_revision == 1 assert queued == [] def test_updated_source_increments_revision( app: Flask, scanner_module: ModuleType, tmp_path: Path, monkeypatch: MonkeyPatch ) -> None: configure_scanner(app, tmp_path) path = write_post( tmp_path, "example", """

Original content

A """, ) queued: list[UUID] = [] monkeypatch.setattr(scanner_module, "send_webmention", queued.append) run_scan(app, scanner_module) with app.app_context(): webmention = db.session.scalar(sa.select(SentWebmention)) assert webmention is not None webmention.processed_revision = 1 webmention.sent_revision = 1 webmention.status = SentWebmentionStatus.SENT db.session.commit() queued.clear() path.write_text( f""" """, encoding="utf-8", ) run_scan(app, scanner_module) with app.app_context(): source = db.session.scalar(sa.select(Source)) webmention = db.session.scalar(sa.select(SentWebmention)) assert source is not None assert webmention is not None assert source.revision == 2 assert webmention.active assert webmention.desired_revision == 2 assert webmention.processed_revision == 1 assert webmention.sent_revision == 1 identifier = webmention.uuid assert queued == [identifier] def test_new_target_is_added_on_update( app: Flask, scanner_module: ModuleType, tmp_path: Path, monkeypatch: MonkeyPatch ) -> None: configure_scanner(app, tmp_path) path = write_post( tmp_path, "example", """

No links yet.

""", ) queued: list[UUID] = [] monkeypatch.setattr(scanner_module, "send_webmention", queued.append) run_scan(app, scanner_module) assert queued == [] path.write_text( f""" """, encoding="utf-8", ) run_scan(app, scanner_module) with app.app_context(): source = db.session.scalar(sa.select(Source)) webmention = db.session.scalar(sa.select(SentWebmention)) assert source is not None assert webmention is not None assert source.revision == 2 assert webmention.target == ("https://example.com/new") assert webmention.active assert webmention.desired_revision == 2 assert webmention.processed_revision is None assert webmention.sent_revision is None identifier = webmention.uuid assert queued == [identifier] def test_removed_sent_target_is_queued_again( app: Flask, scanner_module: ModuleType, tmp_path: Path, monkeypatch: MonkeyPatch ) -> None: configure_scanner(app, tmp_path) path = write_post( tmp_path, "example", """ Sent """, ) queued: list[UUID] = [] monkeypatch.setattr(scanner_module, "send_webmention", queued.append) run_scan(app, scanner_module) with app.app_context(): webmention = db.session.scalar(sa.select(SentWebmention)) assert webmention is not None webmention.processed_revision = 1 webmention.sent_revision = 1 webmention.status = SentWebmentionStatus.SENT identifier = webmention.uuid db.session.commit() queued.clear() path.write_text( f""" """, encoding="utf-8", ) run_scan(app, scanner_module) with app.app_context(): source = db.session.scalar(sa.select(Source)) webmention = db.session.scalar(sa.select(SentWebmention)) assert source is not None assert webmention is not None assert source.revision == 2 assert not webmention.active assert webmention.desired_revision == 2 assert webmention.processed_revision == 1 assert webmention.sent_revision == 1 assert queued == [identifier] def test_removed_unsent_target_is_not_queued( app: Flask, scanner_module: ModuleType, tmp_path: Path, monkeypatch: MonkeyPatch ) -> None: configure_scanner(app, tmp_path) path = write_post( tmp_path, "example", """ Unsent """, ) queued: list[UUID] = [] monkeypatch.setattr(scanner_module, "send_webmention", queued.append) run_scan(app, scanner_module) queued.clear() path.write_text( f""" """, encoding="utf-8", ) run_scan(app, scanner_module) with app.app_context(): source = db.session.scalar(sa.select(Source)) webmention = db.session.scalar(sa.select(SentWebmention)) assert source is not None assert webmention is not None assert source.revision == 2 assert not webmention.active assert webmention.desired_revision == 2 assert webmention.processed_revision == 2 assert webmention.sent_revision is None assert queued == [] def test_empty_output_directory_does_not_delete_sources_or_queue_removals( app: Flask, scanner_module: ModuleType, tmp_path: Path, monkeypatch: MonkeyPatch, caplog: pytest.LogCaptureFixture, ) -> None: configure_scanner(app, tmp_path) paths = [ write_post(tmp_path, slug, f'Target') for slug in ("first", "second") ] queued: list[UUID] = [] monkeypatch.setattr(scanner_module, "send_webmention", queued.append) run_scan(app, scanner_module) with app.app_context(): for webmention in db.session.scalars(sa.select(SentWebmention)): webmention.processed_revision = 1 webmention.sent_revision = 1 webmention.status = SentWebmentionStatus.SENT db.session.commit() queued.clear() for path in paths: path.unlink() # Repeated empty scans must never turn a temporary rebuild into deletions. run_scan(app, scanner_module) run_scan(app, scanner_module) with app.app_context(): sources = list(db.session.scalars(sa.select(Source))) webmentions = list(db.session.scalars(sa.select(SentWebmention))) assert len(sources) == 2 assert all(source.revision == 1 for source in sources) assert all(source.deleted_at is None for source in sources) assert len(webmentions) == 2 assert all(webmention.active for webmention in webmentions) assert all(webmention.desired_revision == 1 for webmention in webmentions) assert queued == [] assert "No source documents successfully scanned" in caplog.text # Once the SSG rebuild completes, unchanged sources stay on revision 1. write_post(tmp_path, "first", 'Target') write_post(tmp_path, "second", 'Target') run_scan(app, scanner_module) with app.app_context(): sources = list(db.session.scalars(sa.select(Source))) assert all(source.revision == 1 for source in sources) assert all(source.deleted_at is None for source in sources) assert queued == [] def test_no_successful_pages_defers_pending_webmentions( app: Flask, scanner_module: ModuleType, tmp_path: Path, monkeypatch: MonkeyPatch ) -> None: configure_scanner(app, tmp_path) path = write_post( tmp_path, "example", 'Target' ) queued: list[UUID] = [] monkeypatch.setattr(scanner_module, "send_webmention", queued.append) run_scan(app, scanner_module) assert len(queued) == 1 identifier = queued.pop() # With no valid pages, even previously pending sends must wait for recovery. path.unlink() run_scan(app, scanner_module) assert queued == [] with app.app_context(): source = db.session.scalar(sa.select(Source)) webmention = db.session.scalar(sa.select(SentWebmention)) assert source is not None and source.deleted_at is None assert webmention is not None and webmention.desired_revision == 1 write_post(tmp_path, "example", 'Target') run_scan(app, scanner_module) assert queued == [identifier] def test_failed_scan_does_not_delete_missing_source( app: Flask, scanner_module: ModuleType, tmp_path: Path, monkeypatch: MonkeyPatch ) -> None: configure_scanner(app, tmp_path) missing = write_post(tmp_path, "missing", "

Original page.

") invalid = write_post(tmp_path, "invalid", "

Original page.

") monkeypatch.setattr(scanner_module, "send_webmention", lambda identifier: None) run_scan(app, scanner_module) missing.unlink() invalid.write_text("Incomplete rebuild", encoding="utf-8") run_scan(app, scanner_module) with app.app_context(): sources = list(db.session.scalars(sa.select(Source))) assert len(sources) == 2 assert all(source.revision == 1 for source in sources) assert all(source.deleted_at is None for source in sources) def test_deleted_source_queues_previously_sent_webmention( app: Flask, scanner_module: ModuleType, tmp_path: Path, monkeypatch: MonkeyPatch ) -> None: configure_scanner(app, tmp_path) path = write_post( tmp_path, "example", """ A """, ) queued: list[UUID] = [] monkeypatch.setattr(scanner_module, "send_webmention", queued.append) write_post(tmp_path, "other", "

Other page remains published.

") run_scan(app, scanner_module) with app.app_context(): webmention = db.session.scalar(sa.select(SentWebmention)) assert webmention is not None webmention.processed_revision = 1 webmention.sent_revision = 1 webmention.status = SentWebmentionStatus.SENT identifier = webmention.uuid db.session.commit() queued.clear() path.unlink() run_scan(app, scanner_module) with app.app_context(): source = db.session.scalar(sa.select(Source).where(Source.url == SOURCE_URL)) webmention = db.session.scalar(sa.select(SentWebmention)) assert source is not None assert webmention is not None assert source.revision == 2 assert source.deleted_at is not None assert not webmention.active assert webmention.desired_revision == 2 assert webmention.processed_revision == 1 assert webmention.sent_revision == 1 assert queued == [identifier] def test_deleted_source_does_not_queue_unsent_webmention( app: Flask, scanner_module: ModuleType, tmp_path: Path, monkeypatch: MonkeyPatch ) -> None: configure_scanner(app, tmp_path) path = write_post( tmp_path, "example", """ A """, ) queued: list[UUID] = [] monkeypatch.setattr(scanner_module, "send_webmention", queued.append) write_post(tmp_path, "other", "

Other page remains published.

") run_scan(app, scanner_module) queued.clear() path.unlink() run_scan(app, scanner_module) with app.app_context(): source = db.session.scalar(sa.select(Source).where(Source.url == SOURCE_URL)) webmention = db.session.scalar(sa.select(SentWebmention)) assert source is not None assert webmention is not None assert source.revision == 2 assert source.deleted_at is not None assert not webmention.active assert webmention.desired_revision == 2 assert webmention.processed_revision == 2 assert webmention.sent_revision is None assert queued == [] def test_restored_source_creates_new_revision( app: Flask, scanner_module: ModuleType, tmp_path: Path, monkeypatch: MonkeyPatch ) -> None: configure_scanner(app, tmp_path) path = write_post( tmp_path, "example", """ A """, ) queued: list[UUID] = [] monkeypatch.setattr(scanner_module, "send_webmention", queued.append) write_post(tmp_path, "other", "

Other page remains published.

") run_scan(app, scanner_module) with app.app_context(): webmention = db.session.scalar(sa.select(SentWebmention)) assert webmention is not None webmention.processed_revision = 1 webmention.sent_revision = 1 webmention.status = SentWebmentionStatus.SENT db.session.commit() path.unlink() run_scan(app, scanner_module) queued.clear() write_post( tmp_path, "example", """ A """, ) run_scan(app, scanner_module) with app.app_context(): source = db.session.scalar(sa.select(Source).where(Source.url == SOURCE_URL)) webmention = db.session.scalar(sa.select(SentWebmention)) assert source is not None assert webmention is not None assert source.revision == 3 assert source.deleted_at is None assert webmention.active assert webmention.desired_revision == 3 assert webmention.sent_revision == 1 identifier = webmention.uuid assert queued == [identifier] def test_pending_webmention_is_requeued_on_next_scan( app: Flask, scanner_module: ModuleType, tmp_path: Path, monkeypatch: MonkeyPatch ) -> None: configure_scanner(app, tmp_path) write_post( tmp_path, "example", """ A """, ) queued: list[UUID] = [] monkeypatch.setattr(scanner_module, "send_webmention", queued.append) run_scan(app, scanner_module) assert len(queued) == 1 identifier = queued[0] queued.clear() run_scan(app, scanner_module) assert queued == [identifier] def test_temporary_failure_waits_until_retry_deadline_and_revision_resets_budget( app: Flask, scanner_module: ModuleType, tmp_path: Path, monkeypatch: MonkeyPatch ) -> None: configure_scanner(app, tmp_path) path = write_post(tmp_path, "example", 'A') queued: list[UUID] = [] monkeypatch.setattr(scanner_module, "send_webmention", queued.append) run_scan(app, scanner_module) assert len(queued) == 1 identifier = queued.pop() with app.app_context(): webmention = db.session.get(SentWebmention, identifier) assert webmention is not None webmention.attempt_count = 2 webmention.next_retry_at = datetime.now(UTC) + timedelta(hours=4) db.session.commit() run_scan(app, scanner_module) assert queued == [] with app.app_context(): webmention = db.session.get(SentWebmention, identifier) assert webmention is not None webmention.next_retry_at = datetime.now(UTC) - timedelta(seconds=1) db.session.commit() run_scan(app, scanner_module) assert queued == [identifier] queued.clear() # Changing the h-entry creates a new desired revision with a fresh budget. path.write_text(path.read_text().replace(">A", ">A updated")) with app.app_context(): webmention = db.session.get(SentWebmention, identifier) assert webmention is not None webmention.next_retry_at = datetime.now(UTC) + timedelta(days=2) db.session.commit() run_scan(app, scanner_module) assert queued == [identifier] with app.app_context(): webmention = db.session.get(SentWebmention, identifier) assert webmention is not None assert webmention.desired_revision == 2 assert webmention.attempt_count == 0 assert webmention.next_retry_at is None def test_invalid_known_source_is_not_deleted( app: Flask, scanner_module: ModuleType, tmp_path: Path, monkeypatch: MonkeyPatch, caplog: pytest.LogCaptureFixture, ) -> None: configure_scanner(app, tmp_path) path = write_post( tmp_path, "example", """

Hello world.

""", ) monkeypatch.setattr(scanner_module, "send_webmention", lambda identifier: None) run_scan(app, scanner_module) path.write_text( f"""

The h-entry disappeared.

""", encoding="utf-8", ) run_scan(app, scanner_module) with app.app_context(): source = db.session.scalar(sa.select(Source)) assert source is not None assert source.revision == 1 assert source.deleted_at is None assert "Could not scan source" in caplog.text assert "Expected exactly one h-entry, found 0" in caplog.text @pytest.mark.parametrize( ("parser", "failure"), ( ("bs4", ValueError("BeautifulSoup failed")), ("mf2py", RuntimeError("mf2py failed")), ("mf2py", RecursionError("HTML nesting exceeded recursion limit")), ), ids=("bs4-error", "mf2py-error", "recursion-error"), ) def test_unexpected_parser_error_does_not_abort_other_sources( app: Flask, scanner_module: ModuleType, tmp_path: Path, monkeypatch: MonkeyPatch, caplog: pytest.LogCaptureFixture, parser: str, failure: Exception, ) -> None: configure_scanner(app, tmp_path) write_post(tmp_path, "bad", "

Cannot parse this page.

") write_post(tmp_path, "good", 'Link') if parser == "bs4": original_soup = source_parser.BeautifulSoup def failing_soup(markup: bytes, features: str) -> BeautifulSoup: if b"/bad/" in markup: raise failure return original_soup(markup, features) monkeypatch.setattr(source_parser, "BeautifulSoup", failing_soup) else: original_parse = source_parser.mf2py.parse def failing_parse(*, doc: str, url: str) -> dict[str, Any] | list[Any]: if "/bad/" in doc: raise failure return original_parse(doc=doc, url=url) monkeypatch.setattr(source_parser.mf2py, "parse", failing_parse) queued: list[UUID] = [] monkeypatch.setattr(scanner_module, "send_webmention", queued.append) run_scan(app, scanner_module) with app.app_context(): sources = list(db.session.scalars(sa.select(Source))) webmention = db.session.scalar(sa.select(SentWebmention)) assert [source.path for source in sources] == ["good/index.html"] assert sources[0].revision == 1 assert webmention is not None assert webmention.target == "https://example.com/target" assert queued == [webmention.uuid] assert "Unexpected error scanning source" in caplog.text assert str(failure) in caplog.text def test_unexpected_parser_error_does_not_delete_known_source( app: Flask, scanner_module: ModuleType, tmp_path: Path, monkeypatch: MonkeyPatch ) -> None: configure_scanner(app, tmp_path) write_post(tmp_path, "bad", "

Original bad page.

") write_post(tmp_path, "good", "

Original good page.

") monkeypatch.setattr(scanner_module, "send_webmention", lambda identifier: None) run_scan(app, scanner_module) write_post(tmp_path, "good", 'Link') original_scan_source_file = scanner_module.scan_source_file def failing_scan_source_file(path: Path, **kwargs: Any) -> Any: if path.parent.name == "bad": raise RecursionError("nested page") return original_scan_source_file(path, **kwargs) monkeypatch.setattr(scanner_module, "scan_source_file", failing_scan_source_file) queued: list[UUID] = [] monkeypatch.setattr(scanner_module, "send_webmention", queued.append) run_scan(app, scanner_module) with app.app_context(): sources = { source.path: source for source in db.session.scalars(sa.select(Source)) } bad = sources["bad/index.html"] good = sources["good/index.html"] webmention = db.session.scalar(sa.select(SentWebmention)) assert bad.revision == 1 assert bad.deleted_at is None assert good.revision == 2 assert good.deleted_at is None assert webmention is not None assert webmention.target == "https://example.com/new-target" assert queued == [webmention.uuid] def test_unexpected_persistence_error_is_not_suppressed( app: Flask, scanner_module: ModuleType, tmp_path: Path, monkeypatch: MonkeyPatch ) -> None: configure_scanner(app, tmp_path) write_post(tmp_path, "example", "

Content

") monkeypatch.setattr( scanner_module, "create_source", Mock(side_effect=RuntimeError("database failed")), ) with pytest.raises(RuntimeError, match="database failed"): run_scan(app, scanner_module) def test_scan_sources_skips_symlink_outside_root( app: Flask, scanner_module: ModuleType, tmp_path: Path, caplog: pytest.LogCaptureFixture, ) -> None: root = tmp_path / "site" root.mkdir() write_post(root, "example", "Normal content") external = write_post(tmp_path / "outside", "private", "Outside content") linked = root / "escaped" / "index.html" linked.parent.mkdir() linked.symlink_to(external) configure_scanner(app, root) run_scan(app, scanner_module) with app.app_context(): sources = list(db.session.scalars(sa.select(Source))) assert len(sources) == 1 assert sources[0].path == "example/index.html" assert "escapes source directory" in caplog.text def test_scan_sources_accepts_valid_base_url( app: Flask, scanner_module: ModuleType, tmp_path: Path, monkeypatch: MonkeyPatch ) -> None: configure_scanner(app, tmp_path, base_url=BASE_URL) directory = tmp_path / "example" directory.mkdir() path = directory / "index.html" path.write_text( """ """, encoding="utf-8", ) monkeypatch.setattr(scanner_module, "send_webmention", lambda identifier: None) run_scan(app, scanner_module) with app.app_context(): source = db.session.scalar(sa.select(Source)) assert source is not None assert source.url == SOURCE_URL def test_scan_sources_rejects_invalid_base_url( app: Flask, scanner_module: ModuleType, tmp_path: Path ) -> None: scanner_module.is_http_url.return_value = False configure_scanner(app, tmp_path, base_url="not-a-url") with pytest.raises(RuntimeError, match="absolute HTTP or HTTPS URL"): run_scan(app, scanner_module) def test_changed_source_url_is_rejected( app: Flask, scanner_module: ModuleType, tmp_path: Path, caplog: pytest.LogCaptureFixture, ) -> None: configure_scanner(app, tmp_path) write_post( tmp_path, "example", """

Hello world.

""", ) run_scan(app, scanner_module) changed_url = f"{BASE_URL}changed/" write_post( tmp_path, "example", """

Hello world.

""", canonical=changed_url, entry_url=changed_url, ) run_scan(app, scanner_module) with app.app_context(): source = db.session.scalar(sa.select(Source)) assert source is not None assert source.url == SOURCE_URL assert source.revision == 1 assert "changed public URL" in caplog.text def test_scan_sources_returns_when_source_directory_is_not_configured( app: Flask, scanner_module: ModuleType ) -> None: app.config["SOURCE_DIRECTORY"] = None run_scan(app, scanner_module) with app.app_context(): assert db.session.scalar(sa.select(Source)) is None def test_scan_sources_rejects_missing_source_directory( app: Flask, scanner_module: ModuleType, tmp_path: Path ) -> None: path = tmp_path / "missing" configure_scanner(app, path) with pytest.raises(RuntimeError, match="Source directory is not a directory"): run_scan(app, scanner_module) def test_scan_sources_rejects_source_directory_that_is_not_directory( app: Flask, scanner_module: ModuleType, tmp_path: Path ) -> None: path = tmp_path / "source.html" path.write_text("

Hello world.

", encoding="utf-8") configure_scanner(app, path) with pytest.raises(RuntimeError, match="Source directory is not a directory"): run_scan(app, scanner_module) def test_scan_sources_ignores_root_index( app: Flask, scanner_module: ModuleType, tmp_path: Path ) -> None: configure_scanner(app, tmp_path) (tmp_path / "index.html").write_text( f""" """, encoding="utf-8", ) write_post( tmp_path, "example", """

Hello world.

""", ) run_scan(app, scanner_module) with app.app_context(): sources = list(db.session.scalars(sa.select(Source))) assert len(sources) == 1 assert sources[0].path == "example/index.html"