Files
Medasset_ai/backend/tests/test_backup_paths.py
T
2026-11-18 18:06:22 +05:30

77 lines
2.5 KiB
Python

import os
from pathlib import Path
import sqlite3
import tarfile
import pytest
from scripts.backup import create_backup, get_db_path
def test_get_db_path_relative_dot_slash():
backend_dir = Path("/mock/backend").resolve()
p = get_db_path("sqlite:///./data/ams.db", backend_dir)
assert p == (backend_dir / "data" / "ams.db").resolve()
def test_get_db_path_relative_plain():
backend_dir = Path("/mock/backend").resolve()
p = get_db_path("sqlite:///data/ams.db", backend_dir)
assert p == (backend_dir / "data" / "ams.db").resolve()
def test_get_db_path_absolute_app():
backend_dir = Path("/mock/backend").resolve()
p = get_db_path("sqlite:////app/data/ams.db", backend_dir)
assert p == Path("/app/data/ams.db")
def test_get_db_path_absolute_tmp():
backend_dir = Path("/mock/backend").resolve()
p = get_db_path("sqlite:////tmp/x/custom.db", backend_dir)
assert p == Path("/tmp/x/custom.db")
def test_get_db_path_fallbacks():
backend_dir = Path("/mock/backend").resolve()
default_expected = backend_dir / "data" / "ams.db"
assert get_db_path(None, backend_dir) == default_expected
assert get_db_path("", backend_dir) == default_expected
assert get_db_path("sqlite:///:memory:", backend_dir) == default_expected
assert get_db_path("postgresql://localhost/ams", backend_dir) == default_expected
def test_create_backup_real_temp_sqlite_file(tmp_path):
# Create real SQLite file
db_file = tmp_path / "source.db"
conn = sqlite3.connect(str(db_file))
cur = conn.cursor()
cur.execute("CREATE TABLE test_table (id INTEGER PRIMARY KEY, note TEXT);")
cur.execute("INSERT INTO test_table (note) VALUES ('backup test');")
conn.commit()
conn.close()
uploads_dir = tmp_path / "uploads"
uploads_dir.mkdir()
(uploads_dir / "sample.pdf").write_bytes(b"%PDF-1.4 sample content")
dest_dir = tmp_path / "backups"
dest_dir.mkdir()
# Run backup producing a .tar.gz
archive_path = create_backup(
db_path=db_file,
uploads_dir=uploads_dir,
dest_dir=dest_dir,
archive_format="tar.gz",
)
assert archive_path is not None
assert archive_path.exists()
assert str(archive_path).endswith(".tar.gz")
# Verify that the tar.gz is valid and contains db.sqlite3
with tarfile.open(archive_path, "r:gz") as tf:
names = tf.getnames()
assert "db.sqlite3" in names
assert "ams.db" in names
assert any("uploads/sample.pdf" in n for n in names)