64 lines
2.6 KiB
Python
64 lines
2.6 KiB
Python
import sqlite3
|
|
import tempfile
|
|
import unittest
|
|
from pathlib import Path
|
|
|
|
from snapshot import snapshot
|
|
|
|
|
|
class SnapshotTests(unittest.TestCase):
|
|
def test_copies_committed_wal_and_excludes_uncommitted_changes(self):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
source = Path(directory) / "live.sqlite"
|
|
target = Path(directory) / "backup.sqlite"
|
|
writer = sqlite3.connect(source)
|
|
try:
|
|
writer.execute("PRAGMA journal_mode=WAL")
|
|
writer.execute("CREATE TABLE records (value TEXT)")
|
|
writer.execute("INSERT INTO records VALUES ('committed')")
|
|
writer.commit()
|
|
writer.execute("INSERT INTO records VALUES ('uncommitted')")
|
|
snapshot(source, target)
|
|
reader = sqlite3.connect(target)
|
|
try:
|
|
self.assertEqual(reader.execute("SELECT * FROM records").fetchall(),
|
|
[("committed",)])
|
|
self.assertEqual(reader.execute("PRAGMA journal_mode").fetchone(),
|
|
("delete",))
|
|
finally:
|
|
reader.close()
|
|
finally:
|
|
writer.close()
|
|
|
|
def test_refuses_to_replace_source_or_existing_backup(self):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
source = Path(directory) / "live.sqlite"
|
|
db = sqlite3.connect(source)
|
|
db.execute("CREATE TABLE records (value TEXT)")
|
|
db.close()
|
|
original = source.read_bytes()
|
|
with self.assertRaises(FileExistsError):
|
|
snapshot(source, source)
|
|
self.assertEqual(source.read_bytes(), original)
|
|
target = Path(directory) / "backup.sqlite"
|
|
target.write_bytes(b"keep this")
|
|
with self.assertRaises(FileExistsError):
|
|
snapshot(source, target)
|
|
self.assertEqual(target.read_bytes(), b"keep this")
|
|
|
|
def test_missing_or_invalid_database_leaves_no_snapshot(self):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
source = Path(directory) / "missing.sqlite"
|
|
target = Path(directory) / "backup.sqlite"
|
|
with self.assertRaises(FileNotFoundError):
|
|
snapshot(source, target)
|
|
source.write_text("not a database")
|
|
with self.assertRaises(sqlite3.DatabaseError):
|
|
snapshot(source, target)
|
|
self.assertFalse(target.exists())
|
|
self.assertEqual(list(Path(directory).glob(".snapshot-*")), [])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|