# 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 pytest import MonkeyPatch from webmentions_ssg import DATABASE as db from webmentions_ssg.models import SentWebmention, SentWebmentionStatus, Source BASE_URL = "https://dennisfink.me/blog/" SOURCE_URL = f"{BASE_URL}example/" @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)) return scanner def run_scan(app: Flask, scanner_module: ModuleType) -> None: with app.app_context(): scanner_module.scan_sources() def parse_html(html: str) -> BeautifulSoup: return BeautifulSoup(html, "html5lib") def write_post( root: Path, slug: str, content: str, *, canonical: str | None = None, entry_url: str | None = None, ) -> Path: directory = root / slug directory.mkdir(parents=True, exist_ok=True) source_url = f"{BASE_URL}{slug}/" if canonical is None: canonical = source_url if entry_url is None: entry_url = source_url path = directory / "index.html" path.write_text( f"""
Permalink
{content}
""", encoding="utf-8", ) return path def configure_scanner(app: Flask, root: Path, *, base_url: str | None = None) -> None: app.config["SOURCE_DIRECTORY"] = str(root) app.config["SOURCE_BASE_URL"] = base_url def test_parse_entry_returns_microformats_entry(scanner_module: ModuleType) -> None: document = parse_html( f"""
Permalink
Hello world
""" ) element = document.find(class_="h-entry") assert element is not None entry = scanner_module.parse_entry(element, SOURCE_URL) assert "h-entry" in entry["type"] assert entry["properties"]["url"] == [SOURCE_URL] def test_parse_entry_rejects_non_entry(scanner_module: ModuleType) -> None: document = parse_html( """

Hello world

""" ) element = document.find("article") assert element is not None with pytest.raises( scanner_module.SourceScanError, match="Expected exactly one parsed h-entry" ): scanner_module.parse_entry(element, SOURCE_URL) def test_primary_entry_returns_source_entry(scanner_module: ModuleType) -> None: document = parse_html( f"""
Permalink

Example post

Hello world
""" ) element, entry = scanner_module.primary_entry(document, SOURCE_URL) assert element["id"] == "source" assert entry["properties"]["name"] == ["Example post"] assert entry["properties"]["url"] == [SOURCE_URL] def test_primary_entry_rejects_missing_h_entry(scanner_module: ModuleType) -> None: document = parse_html( """

No microformats here.

""" ) with pytest.raises( scanner_module.SourceScanError, match="Expected exactly one h-entry, found 0" ): scanner_module.primary_entry(document, SOURCE_URL) def test_primary_entry_rejects_multiple_h_entries(scanner_module: ModuleType) -> None: document = parse_html( f"""
First
Second
""" ) with pytest.raises( scanner_module.SourceScanError, match="Expected exactly one h-entry, found 2" ): scanner_module.primary_entry(document, SOURCE_URL) def test_primary_entry_rejects_nested_h_entry(scanner_module: ModuleType) -> None: document = parse_html( f"""
Permalink
""" ) with pytest.raises( scanner_module.SourceScanError, match="Expected exactly one h-entry, found 2" ): scanner_module.primary_entry(document, SOURCE_URL) def test_primary_entry_rejects_missing_u_url(scanner_module: ModuleType) -> None: document = parse_html( """
Hello world
""" ) with pytest.raises(scanner_module.SourceScanError, match="does not match"): scanner_module.primary_entry(document, SOURCE_URL) def test_primary_entry_rejects_nonmatching_u_url(scanner_module: ModuleType) -> None: document = parse_html( """
Other
Hello world
""" ) with pytest.raises(scanner_module.SourceScanError, match="does not match"): scanner_module.primary_entry(document, SOURCE_URL) def test_content_element_returns_e_content(scanner_module: ModuleType) -> None: document = parse_html( """
Hello world
""" ) entry = document.find(class_="h-entry") assert entry is not None content = scanner_module.content_element(entry) assert content["id"] == "content" def test_content_element_rejects_missing_e_content(scanner_module: ModuleType) -> None: document = parse_html( """

Hello world

""" ) entry = document.find(class_="h-entry") assert entry is not None with pytest.raises( scanner_module.SourceScanError, match="Expected exactly one e-content, found 0" ): scanner_module.content_element(entry) def test_content_element_rejects_multiple_e_content(scanner_module: ModuleType) -> None: document = parse_html( """
First
Second
""" ) entry = document.find(class_="h-entry") assert entry is not None with pytest.raises( scanner_module.SourceScanError, match="Expected exactly one e-content, found 2" ): scanner_module.content_element(entry) def test_canonical_url_returns_absolute_url(scanner_module: ModuleType) -> None: document = parse_html( f""" """ ) result = scanner_module.canonical_url( document, relative_path=Path("example/index.html"), base_url=None ) assert result == SOURCE_URL def test_canonical_url_returns_none_when_missing(scanner_module: ModuleType) -> None: document = parse_html( """ Example """ ) result = scanner_module.canonical_url( document, relative_path=Path("example/index.html"), base_url=None ) assert result is None def test_canonical_url_resolves_relative_url_with_base_url( scanner_module: ModuleType, ) -> None: scanner_module.is_http_url.side_effect = [False, True] document = parse_html( """ """ ) result = scanner_module.canonical_url( document, relative_path=Path("example/index.html"), base_url=BASE_URL ) assert result == ("https://dennisfink.me/blog/example/canonical/") def test_relative_canonical_requires_base_url(scanner_module: ModuleType) -> None: scanner_module.is_http_url.return_value = False document = parse_html( """ """ ) with pytest.raises(scanner_module.SourceScanError, match="relative canonical"): scanner_module.canonical_url( document, relative_path=Path("example/index.html"), base_url=None ) def test_empty_canonical_is_rejected(scanner_module: ModuleType) -> None: document = parse_html( """ """ ) with pytest.raises(scanner_module.SourceScanError, match="empty canonical URL"): scanner_module.canonical_url( document, relative_path=Path("example/index.html"), base_url=BASE_URL ) def test_scan_source_uses_canonical_without_base_url( scanner_module: ModuleType, tmp_path: Path ) -> None: path = write_post( tmp_path, "example", """ Target """, ) scanned = scanner_module.scan_source_file(path, root=tmp_path, base_url=None) assert scanned.path == "example/index.html" assert scanned.url == SOURCE_URL assert scanned.targets == frozenset({"https://example.com/target"}) assert len(scanned.content_hash) == 32 def test_scan_source_falls_back_to_base_url( scanner_module: ModuleType, tmp_path: Path ) -> None: directory = tmp_path / "example" directory.mkdir() path = directory / "index.html" path.write_text( """
Permalink
""", encoding="utf-8", ) scanned = scanner_module.scan_source_file(path, root=tmp_path, base_url=BASE_URL) assert scanned.url == SOURCE_URL assert scanned.targets == frozenset({"https://example.com/target"}) def test_scan_source_requires_canonical_or_base_url( scanner_module: ModuleType, tmp_path: Path ) -> None: directory = tmp_path / "example" directory.mkdir() path = directory / "index.html" path.write_text( """
Permalink

Hello world.

""", encoding="utf-8", ) with pytest.raises(scanner_module.SourceScanError, match="no canonical URL"): scanner_module.scan_source_file(path, root=tmp_path, base_url=None) def test_scan_source_extracts_only_content_links( scanner_module: ModuleType, tmp_path: Path ) -> None: directory = tmp_path / "example" directory.mkdir() path = directory / "index.html" path.write_text( f"""
Permalink Metadata link
""", encoding="utf-8", ) scanned = scanner_module.scan_source_file(path, root=tmp_path, base_url=None) assert scanned.targets == frozenset({"https://example.com/content"}) def test_scan_source_extracts_relative_content_link( scanner_module: ModuleType, tmp_path: Path ) -> None: path = write_post( tmp_path, "example", """ Other post """, ) scanned = scanner_module.scan_source_file(path, root=tmp_path, base_url=None) assert scanned.targets == frozenset({"https://dennisfink.me/blog/other/"}) @pytest.mark.parametrize( "property_name", ("in-reply-to", "like-of", "repost-of", "bookmark-of") ) def test_scan_source_extracts_reaction_properties( scanner_module: ModuleType, tmp_path: Path, property_name: str ) -> None: directory = tmp_path / "example" directory.mkdir() target = f"https://example.com/{property_name}" path = directory / "index.html" path.write_text( f"""
Permalink Reaction target

Post content.

""", encoding="utf-8", ) scanned = scanner_module.scan_source_file(path, root=tmp_path, base_url=None) assert scanned.targets == frozenset({target}) @pytest.mark.parametrize("tag", ("link", "area")) def test_scan_source_ignores_non_anchor_href_elements( scanner_module: ModuleType, tmp_path: Path, tag: str ) -> None: path = write_post( tmp_path, "example", f""" <{tag} href="https://example.com/target"> """, ) scanned = scanner_module.scan_source_file(path, root=tmp_path, base_url=None) assert scanned.targets == frozenset() def test_scan_source_ignores_self_fragment( scanner_module: ModuleType, tmp_path: Path ) -> None: path = write_post( tmp_path, "example", """ Section Target """, ) scanned = scanner_module.scan_source_file(path, root=tmp_path, base_url=None) assert scanned.targets == frozenset({"https://example.com/target"}) 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_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"""
Permalink

Updated content

A
""", 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"""
Permalink
""", 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"""
Permalink

The link is gone.

""", 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"""
Permalink

The link is gone.

""", 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 = scanner_module.BeautifulSoup def failing_soup(markup: bytes, features: str) -> BeautifulSoup: if b"/bad/" in markup: raise failure return original_soup(markup, features) monkeypatch.setattr(scanner_module, "BeautifulSoup", failing_soup) else: original_parse = scanner_module.mf2py.parse def failing_parse(*, doc: str, url: str) -> dict[str, Any]: if "/bad/" in doc: raise failure return original_parse(doc=doc, url=url) monkeypatch.setattr(scanner_module.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_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( """
Permalink

Hello world.

""", 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) @pytest.mark.parametrize( "href", ( "https://dennisfink.me/blog/other/", "https://www.dennisfink.me/blog/other/", "https://webmentions.dennisfink.me/endpoint", "https://foo.bar.dennisfink.me/example", ), ) def test_scan_source_ignores_matching_hostname( scanner_module: ModuleType, tmp_path: Path, href: str ) -> None: path = write_post( tmp_path, "example", f""" Ignored External """, ) scanned = scanner_module.scan_source_file( path, root=tmp_path, base_url=None, ignored_hostnames=("dennisfink.me", "*.dennisfink.me"), ) assert scanned.targets == frozenset({"https://example.com/target"}) @pytest.mark.parametrize( "href", ( "https://notdennisfink.me/example", "https://dennisfink.me.example.com/example", "https://example.com/example", ), ) def test_scan_source_keeps_nonmatching_hostname( scanner_module: ModuleType, tmp_path: Path, href: str ) -> None: path = write_post( tmp_path, "example", f""" Target """, ) scanned = scanner_module.scan_source_file( path, root=tmp_path, base_url=None, ignored_hostnames=("dennisfink.me", "*.dennisfink.me"), ) assert scanned.targets == frozenset({href}) def test_scan_source_ignores_reaction_to_matching_hostname( scanner_module: ModuleType, tmp_path: Path ) -> None: directory = tmp_path / "example" directory.mkdir() path = directory / "index.html" path.write_text( f"""
Permalink Reply target

Reply content.

""", encoding="utf-8", ) scanned = scanner_module.scan_source_file( path, root=tmp_path, base_url=None, ignored_hostnames=("dennisfink.me", "*.dennisfink.me"), ) assert scanned.targets == frozenset() def test_canonical_url_rejects_non_http_resolved_url( scanner_module: ModuleType, ) -> None: scanner_module.is_http_url.return_value = False document = parse_html( """ """ ) with pytest.raises( scanner_module.SourceScanError, match="Canonical URL is not a valid HTTP or HTTPS URL", ): scanner_module.canonical_url( document, relative_path=Path("example/index.html"), base_url=BASE_URL ) def test_property_urls_ignores_non_mapping_properties( scanner_module: ModuleType, ) -> None: entry = {"properties": "invalid"} assert tuple(scanner_module.property_urls(entry, "url")) == () @pytest.mark.parametrize( ("parsed", "message"), [ pytest.param( [], "Microformats parser did not return a document object", id="non-object-document", ), pytest.param( {"items": [None]}, "Parsed h-entry is not an object", id="non-object-entry" ), pytest.param( {"items": [{"type": ["h-card"]}]}, "Parsed microformats item is not an h-entry", id="wrong-item-type", ), ], ) def test_parse_entry_rejects_invalid_parser_output( scanner_module: ModuleType, monkeypatch: MonkeyPatch, parsed: object, message: str ) -> None: document = parse_html( """

Hello world

""" ) element = document.find(class_="h-entry") assert element is not None monkeypatch.setattr(scanner_module.mf2py, "parse", lambda **kwargs: parsed) with pytest.raises(scanner_module.SourceScanError, match=message): scanner_module.parse_entry(element, SOURCE_URL) def test_normalize_target_ignores_empty_target(scanner_module: ModuleType) -> None: assert ( scanner_module.normalize_target(" ", base_url=SOURCE_URL, source_url=SOURCE_URL) is None ) def test_normalize_target_ignores_url_rejected_by_validator( scanner_module: ModuleType, ) -> None: scanner_module.is_http_url.return_value = False assert ( scanner_module.normalize_target( "https://example.com/target", base_url=SOURCE_URL, source_url=SOURCE_URL ) is None ) 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_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"""
Permalink

Blog index.

""", 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"