aboutsummaryrefslogtreecommitdiff
path: root/tests/test_init.py
blob: 8f2bbb758aea25d3c608dfc999d151a66dc24303 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause

"""Test application initialization and its public integrations."""

import subprocess
import sys
from pathlib import Path

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


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


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():
        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() == "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())