import gzip import os import sqlite3 from datetime import date, datetime, timedelta import pytest from app import cli from app.config import get_settings from app.models import Role from app.services import backup from tests.conftest import login def restore(info, tmp_path): """Decompress a backup the way the README describes and open it.""" target = tmp_path / "restored.db" target.write_bytes(gzip.decompress(info.path.read_bytes())) return sqlite3.connect(target) def at(day: str, hour: int = 3) -> datetime: return datetime.fromisoformat(f"{day}T{hour:02d}:00:00").astimezone() def fake_backup(day: date, age_days: float = 0) -> None: directory = backup.backup_dir() directory.mkdir(parents=True, exist_ok=True) path = directory / f"app-{day.isoformat()}.db.gz" path.write_bytes(b"x") stamp = datetime.now().timestamp() - age_days * 86400 os.utime(path, (stamp, stamp)) @pytest.fixture(autouse=True) def no_last_error(): backup.last_error = None yield backup.last_error = None def test_backup_can_be_restored(app_env, make_user, tmp_path): make_user("anna") info = backup.create_backup(at("2026-10-25")) assert info.path.name == "app-2026-10-25.db.gz" assert info.size > 0 with restore(info, tmp_path) as conn: assert conn.execute("PRAGMA integrity_check").fetchone()[0] == "ok" assert conn.execute("SELECT username FROM users").fetchall() == [("anna",)] assert conn.execute("SELECT version_num FROM alembic_version").fetchone() is not None def test_backup_is_a_snapshot(app_env, make_user, tmp_path): make_user("anna") info = backup.create_backup(at("2026-10-25")) make_user("bert") with restore(info, tmp_path) as conn: assert conn.execute("SELECT count(*) FROM users").fetchone()[0] == 1 def test_second_backup_of_a_day_replaces_the_first(app_env, make_user, tmp_path): backup.create_backup(at("2026-10-25", 3)) make_user("anna") info = backup.create_backup(at("2026-10-25", 14)) assert [b.path.name for b in backup.list_backups()] == ["app-2026-10-25.db.gz"] with restore(info, tmp_path) as conn: assert conn.execute("SELECT count(*) FROM users").fetchone()[0] == 1 def test_failed_verification_leaves_no_backup(app_env, monkeypatch): def broken(_path): raise backup.BackupError("Integritätsprüfung fehlgeschlagen: page 3 corrupt") monkeypatch.setattr(backup, "_verify", broken) with pytest.raises(backup.BackupError): backup.create_backup(at("2026-10-25")) assert list(backup.backup_dir().iterdir()) == [] assert "page 3 corrupt" in backup.last_error def test_success_clears_last_error(app_env): backup.last_error = "earlier failure" backup.create_backup(at("2026-10-25")) assert backup.last_error is None def test_retention_keeps_daily_and_weekly(app_env, monkeypatch): monkeypatch.setenv("BACKUP_KEEP_DAILY", "7") monkeypatch.setenv("BACKUP_KEEP_WEEKLY", "4") get_settings.cache_clear() first = date(2026, 9, 1) for offset in range(55): fake_backup(first + timedelta(days=offset)) (backup.backup_dir() / "notes.txt").write_text("not a backup") removed = backup.prune() kept = [b.day for b in backup.list_backups()] newest = first + timedelta(days=54) # 2026-10-25, a Sunday daily = [newest - timedelta(days=i) for i in range(7)] assert kept[:7] == daily # Then the newest backup of each of the 4 calendar weeks before assert kept[7:] == [ date(2026, 10, 18), date(2026, 10, 11), date(2026, 10, 4), date(2026, 9, 27), ] assert removed == 55 - 11 assert (backup.backup_dir() / "notes.txt").exists() def test_needs_catch_up(app_env): assert backup.needs_catch_up() is True fake_backup(date.today(), age_days=0.5) assert backup.needs_catch_up() is False for path in backup.backup_dir().iterdir(): path.unlink() fake_backup(date.today() - timedelta(days=2), age_days=1.5) assert backup.needs_catch_up() is True @pytest.mark.parametrize( ("now", "expected_hours"), [("02:00", 1), ("03:00", 24), ("04:30", 22.5), ("23:00", 4)], ) def test_next_run(app_env, now, expected_hours): current = datetime.fromisoformat(f"2026-10-20T{now}:00").astimezone() assert backup.seconds_until_next_run(current) == expected_hours * 3600 def test_backup_hour_is_validated(app_env, monkeypatch): monkeypatch.setenv("BACKUP_HOUR", "24") get_settings.cache_clear() with pytest.raises(ValueError): get_settings() def test_cli_backup(app_env, monkeypatch, capsys): monkeypatch.setenv("LC_ALLOW_ROOT", "1") assert cli.main(["backup"]) == 0 assert "Sicherung geschrieben" in capsys.readouterr().out assert len(backup.list_backups()) == 1 def test_admin_sees_backup_status(client, make_user): make_user("root", role=Role.ADMIN) login(client, "root") status = client.get("/api/admin/backup").json() assert status["latest"] is None assert status["stale"] is True assert (status["enabled"], status["hour"]) == (True, 3) info = backup.create_backup() status = client.get("/api/admin/backup").json() assert status["latest"]["name"] == info.path.name assert status["latest"]["size"] == info.size assert status["count"] == 1 assert status["stale"] is False assert status["last_error"] is None def test_backup_status_is_admin_only(client, make_user): make_user("anna") login(client, "anna") assert client.get("/api/admin/backup").status_code == 403 def test_loop_catches_up_and_survives_failures(app_env, monkeypatch): import asyncio from app import main calls = [] real = backup.create_backup loop = asyncio.new_event_loop() done = asyncio.Event() def flaky(): calls.append(len(calls)) if len(calls) == 3: # Runs in the thread pool; wake the test on the event loop loop.call_soon_threadsafe(done.set) if len(calls) == 2: raise backup.BackupError("disk full") return real() monkeypatch.setattr(main, "BACKUP_CATCH_UP_DELAY_SECONDS", 0) monkeypatch.setattr(backup, "create_backup", flaky) monkeypatch.setattr(backup, "seconds_until_next_run", lambda: 0.01) async def run_briefly(): task = asyncio.create_task(main._backup_loop()) await asyncio.wait_for(done.wait(), timeout=10) task.cancel() loop.run_until_complete(run_briefly()) loop.close() # Catch-up at start, then scheduled runs; the failed second run did not stop the loop assert len(calls) >= 3 assert len(backup.list_backups()) == 1