# SPDX-FileCopyrightText: 2026 Dennis Fink # # SPDX-License-Identifier: BSD-3-Clause """Test application initialization and its public integrations.""" import subprocess import sys from pathlib import Path import pytest from flask import Flask from sqlalchemy import create_engine from webmentions_ssg import VERSION, create_app, db, huey from webmentions_ssg.config import TestingConfig from webmentions_ssg.net import is_http_url from webmentions_ssg.template_filters import relative_time, utc_isoformat, utc_timestamp def test_create_app_registers_blueprint_and_extensions(app: Flask) -> None: assert "webmentions" in app.blueprints assert app.extensions["huey"] is huey assert app.jinja_env.filters["is_http_url"] is is_http_url assert app.jinja_env.filters["relative_time"] is relative_time assert app.jinja_env.filters["utc_isoformat"] is utc_isoformat assert app.jinja_env.filters["utc_timestamp"] is utc_timestamp def test_create_app_exposes_version_in_templates(app: Flask) -> None: with app.test_request_context(): context: dict[str, str] = {} app.update_template_context(context) assert context["VERSION"] == VERSION def test_importing_views_and_tasks_before_creating_app() -> None: """Verify that imports do not need an initialized Huey backend.""" script = """ from webmentions_ssg import huey from webmentions_ssg.tasks.scanner import manual_scan_sources from webmentions_ssg.tasks.verification import verify_webmention from webmentions_ssg.tasks.sender import send_webmention from webmentions_ssg.views import webmentions_bp assert huey.app is None assert huey._huey is None assert manual_scan_sources.__name__ == 'manual_scan_sources' assert verify_webmention.__name__ == 'verify_webmention' assert send_webmention.__name__ == 'send_webmention' assert webmentions_bp.name == 'webmentions' """ result = subprocess.run( [sys.executable, "-c", script], capture_output=True, text=True, check=False ) assert result.returncode == 0, result.stderr def test_in_memory_sqlite_enforces_foreign_keys_without_wal(app: Flask) -> None: with app.app_context(), db.engine.connect() as connection: assert connection.exec_driver_sql("PRAGMA foreign_keys").scalar() == 1 assert connection.exec_driver_sql("PRAGMA journal_mode").scalar() == "memory" def test_file_sqlite_enables_wal_and_foreign_keys(tmp_path: Path) -> None: class FileSQLiteConfig(TestingConfig): LOG_FILE = str(tmp_path / "sqlite-test.log") SQLALCHEMY_DATABASE_URI = f"sqlite:///{tmp_path / 'test.db'}" app = create_app(FileSQLiteConfig) with app.app_context(): try: with db.engine.connect() as connection: assert connection.exec_driver_sql("PRAGMA foreign_keys").scalar() == 1 assert ( connection.exec_driver_sql("PRAGMA journal_mode").scalar() == "wal" ) # Foreign-key enforcement must also apply to fresh pooled connections. db.engine.dispose() with db.engine.connect() as connection: assert connection.exec_driver_sql("PRAGMA foreign_keys").scalar() == 1 assert ( connection.exec_driver_sql("PRAGMA journal_mode").scalar() == "wal" ) finally: db.engine.dispose() def test_sqlite_settings_apply_to_sqlite_binds(tmp_path: Path) -> None: class SQLiteBindConfig(TestingConfig): LOG_FILE = str(tmp_path / "bind-test.log") SQLALCHEMY_BINDS = {"archive": f"sqlite:///{tmp_path / 'archive.db'}"} app = create_app(SQLiteBindConfig) with app.app_context(): try: with db.engines["archive"].connect() as connection: assert connection.exec_driver_sql("PRAGMA foreign_keys").scalar() == 1 assert ( connection.exec_driver_sql("PRAGMA journal_mode").scalar() == "wal" ) finally: db.engines["archive"].dispose() db.engine.dispose() def test_sqlite_connect_event_works_without_flask(tmp_path: Path) -> None: """SQLAlchemy's Engine connect event configures SQLite directly.""" engine = create_engine(f"sqlite:///{tmp_path / 'standalone.db'}") try: with engine.connect() as connection: assert connection.exec_driver_sql("PRAGMA foreign_keys").scalar() == 1 assert connection.exec_driver_sql("PRAGMA journal_mode").scalar() == "wal" finally: engine.dispose() def test_sqlite_pragmas_can_be_tuned_per_app(tmp_path: Path) -> None: """Custom settings take effect on fresh connections and survive disposal.""" class TunedSQLiteConfig(TestingConfig): LOG_FILE = str(tmp_path / "tuned-test.log") SQLALCHEMY_DATABASE_URI = f"sqlite:///{tmp_path / 'tuned.db'}" SQLITE_PRAGMAS = { "foreign_keys": False, "journal_mode": "DELETE", "busy_timeout": 9000, "trusted_schema": False, "synchronous": "NORMAL", "cache_size": -8192, "wal_autocheckpoint": 250, "journal_size_limit": 65536, } app = create_app(TunedSQLiteConfig) with app.app_context(): try: for _ in range(2): with db.engine.connect() as connection: for pragma, expected in ( ("foreign_keys", 0), ("journal_mode", "delete"), ("busy_timeout", 9000), ("trusted_schema", 0), ("synchronous", 1), ("cache_size", -8192), ("wal_autocheckpoint", 250), ("journal_size_limit", 65536), ): assert ( connection.exec_driver_sql(f"PRAGMA {pragma}").scalar() == expected ) db.engine.dispose() finally: db.engine.dispose() def test_in_memory_sqlite_skips_file_only_pragmas(tmp_path: Path) -> None: class MemorySQLiteConfig(TestingConfig): LOG_FILE = str(tmp_path / "memory-test.log") SQLITE_PRAGMAS = { "journal_mode": "WAL", "wal_autocheckpoint": 333, "journal_size_limit": 65536, "cache_size": -4096, } app = create_app(MemorySQLiteConfig) with app.app_context(): try: with db.engine.connect() as connection: assert ( connection.exec_driver_sql("PRAGMA journal_mode").scalar() == "memory" ) assert connection.exec_driver_sql("PRAGMA cache_size").scalar() == -4096 assert ( connection.exec_driver_sql("PRAGMA wal_autocheckpoint").scalar() == 1000 ) finally: db.engine.dispose() def test_sqlite_pragma_settings_also_apply_to_binds(tmp_path: Path) -> None: class TunedBindConfig(TestingConfig): LOG_FILE = str(tmp_path / "bind-tuned-test.log") SQLITE_PRAGMAS = {"busy_timeout": 1234, "cache_size": -2048} SQLALCHEMY_BINDS = {"archive": f"sqlite:///{tmp_path / 'archive-tuned.db'}"} app = create_app(TunedBindConfig) with app.app_context(): try: with db.engines["archive"].connect() as connection: assert ( connection.exec_driver_sql("PRAGMA busy_timeout").scalar() == 1234 ) assert connection.exec_driver_sql("PRAGMA cache_size").scalar() == -2048 finally: db.engines["archive"].dispose() db.engine.dispose() def test_sqlite_connect_listener_does_not_touch_other_dbapis() -> None: from webmentions_ssg.extensions import set_sqlite_pragmas # Non-SQLite DB-API connections bypass the listener completely. set_sqlite_pragmas(object(), object()) @pytest.mark.parametrize("development", [False, True]) def test_create_app_selects_default_configuration_from_environment( monkeypatch: pytest.MonkeyPatch, development: bool ) -> None: import webmentions_ssg as package class DefaultTestConfig(TestingConfig): LOG_FILE = str(Path.cwd() / "testing" / "default-config-test.log") class DevelopmentTestConfig(DefaultTestConfig): CONFIG_SELECTION = "development" class ProductionTestConfig(DefaultTestConfig): CONFIG_SELECTION = "production" monkeypatch.setattr(package, "DevelopmentConfig", DevelopmentTestConfig) monkeypatch.setattr(package, "ProductionConfig", ProductionTestConfig) if development: monkeypatch.setenv("WEBMENTIONS_SSG_DEV", "true") else: monkeypatch.delenv("WEBMENTIONS_SSG_DEV", raising=False) application = create_app() assert application.config["CONFIG_SELECTION"] == ( "development" if development else "production" ) def test_sqlite_connect_rejects_journal_mode_that_cannot_be_applied( app: Flask, monkeypatch: pytest.MonkeyPatch ) -> None: from unittest.mock import Mock from webmentions_ssg import extensions cursor = Mock() cursor.fetchall.return_value = [(0, "main", "/tmp/test-file.sqlite")] cursor.fetchone.side_effect = [("DELETE",), ("DELETE",)] class FakeConnection: def __init__(self) -> None: self.autocommit = False def cursor(self) -> Mock: return cursor connection = FakeConnection() with app.app_context(), monkeypatch.context() as patcher: patcher.setattr(extensions.sqlite3, "Connection", FakeConnection) with pytest.raises(RuntimeError, match="journal_mode WAL was not applied"): extensions.set_sqlite_pragmas(connection, None) assert connection.autocommit is False cursor.close.assert_called_once_with() cursor.execute.assert_any_call("PRAGMA journal_mode = WAL")