init repo
This commit is contained in:
commit
6c63a20d8d
24 files changed
+2010
No files matched your search
@@ -0,0 +1,129 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from gitea_backup.backup import prune_snapshots, run_backup
|
||||
from gitea_backup.config import Config
|
||||
from gitea_backup.scheduler import seconds_until_next
|
||||
|
||||
|
||||
class FakeGit:
|
||||
def __init__(self) -> None:
|
||||
self.calls: list[tuple[str, Path]] = []
|
||||
|
||||
def mirror_or_fetch(self, clone_url: str, dest: Path) -> None:
|
||||
dest.mkdir(parents=True, exist_ok=True)
|
||||
(dest / "HEAD").write_text("ref: refs/heads/main\n", encoding="utf-8")
|
||||
self.calls.append((clone_url, dest))
|
||||
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, repos: list[dict]) -> None:
|
||||
self._repos = repos
|
||||
self.token = "tok"
|
||||
|
||||
def __enter__(self) -> FakeClient:
|
||||
return self
|
||||
|
||||
def __exit__(self, *args: object) -> None:
|
||||
return None
|
||||
|
||||
def ping(self) -> str:
|
||||
return "1.22.0"
|
||||
|
||||
def list_repos(self) -> list[dict]:
|
||||
return self._repos
|
||||
|
||||
def clone_url(self, repo: dict) -> str:
|
||||
return f"http://oauth2:tok@192.168.1.9:3000/{repo['full_name']}.git"
|
||||
|
||||
|
||||
def _config(root: Path, **kwargs) -> Config:
|
||||
values = dict(
|
||||
gitea_url="http://192.168.1.9:3000",
|
||||
token="tok",
|
||||
backup_dir=root,
|
||||
backup_at="03:00",
|
||||
timezone="Europe/Moscow",
|
||||
run_on_start=True,
|
||||
snapshots=True,
|
||||
keep_days=7,
|
||||
include_wiki=True,
|
||||
include_lfs=False,
|
||||
)
|
||||
values.update(kwargs)
|
||||
return Config(**values)
|
||||
|
||||
|
||||
class SnapshotPruneTest(unittest.TestCase):
|
||||
def test_removes_old_dated_dirs(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
(root / "2026-08-01").mkdir()
|
||||
(root / "2026-09-07").mkdir()
|
||||
(root / "notes.txt").write_text("skip", encoding="utf-8")
|
||||
now = datetime(2026, 9, 8, tzinfo=ZoneInfo("Europe/Moscow"))
|
||||
removed = prune_snapshots(root, keep_days=7, now=now)
|
||||
self.assertEqual(removed, ["2026-08-01"])
|
||||
self.assertTrue((root / "2026-09-07").is_dir())
|
||||
|
||||
|
||||
class SchedulerTest(unittest.TestCase):
|
||||
def test_waits_until_tomorrow_if_time_passed(self) -> None:
|
||||
tz = ZoneInfo("Europe/Moscow")
|
||||
now = datetime(2026, 9, 8, 4, 0, tzinfo=tz)
|
||||
wait = seconds_until_next("03:00", tz, now=now)
|
||||
self.assertGreater(wait, 22 * 3600)
|
||||
self.assertLess(wait, 24 * 3600)
|
||||
|
||||
def test_waits_same_day_if_upcoming(self) -> None:
|
||||
tz = ZoneInfo("Europe/Moscow")
|
||||
now = datetime(2026, 9, 8, 1, 0, tzinfo=tz)
|
||||
wait = seconds_until_next("03:00", tz, now=now)
|
||||
self.assertAlmostEqual(wait, 2 * 3600, delta=1)
|
||||
|
||||
|
||||
class RunBackupTest(unittest.TestCase):
|
||||
def test_mirrors_repos_and_writes_status(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
cfg = _config(root)
|
||||
git = FakeGit()
|
||||
repos = [
|
||||
{
|
||||
"full_name": "alice/app",
|
||||
"clone_url": "http://192.168.1.9:3000/alice/app.git",
|
||||
"has_wiki": True,
|
||||
"private": True,
|
||||
},
|
||||
{
|
||||
"full_name": "bob/lib",
|
||||
"clone_url": "http://192.168.1.9:3000/bob/lib.git",
|
||||
"has_wiki": False,
|
||||
"private": False,
|
||||
},
|
||||
]
|
||||
status = run_backup(
|
||||
cfg,
|
||||
client_factory=lambda _c: FakeClient(repos),
|
||||
git=git, # type: ignore[arg-type]
|
||||
)
|
||||
self.assertTrue(status["ok"])
|
||||
self.assertEqual(status["repos_ok"], 2)
|
||||
self.assertEqual(status["gitea_version"], "1.22.0")
|
||||
names = [Path(dest).name for _url, dest in git.calls]
|
||||
self.assertIn("app.git", names)
|
||||
self.assertIn("app.wiki.git", names)
|
||||
self.assertIn("lib.git", names)
|
||||
saved = json.loads((root / "status.json").read_text(encoding="utf-8"))
|
||||
self.assertEqual(saved["repos_total"], 2)
|
||||
self.assertTrue((root / "mirrors" / "alice" / "app.git.meta.json").exists())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,59 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from gitea_backup.client import GiteaClient, inject_token, wiki_clone_url
|
||||
|
||||
|
||||
class UrlHelpersTest(unittest.TestCase):
|
||||
def test_inject_token_keeps_port(self) -> None:
|
||||
url = inject_token("http://192.168.1.9:3000/alice/app.git", "s3cret")
|
||||
self.assertEqual(url, "http://oauth2:s3cret@192.168.1.9:3000/alice/app.git")
|
||||
|
||||
def test_wiki_url(self) -> None:
|
||||
self.assertEqual(
|
||||
wiki_clone_url("http://gitea/alice/app.git"),
|
||||
"http://gitea/alice/app.wiki.git",
|
||||
)
|
||||
|
||||
|
||||
class ListReposTest(unittest.TestCase):
|
||||
def test_deduplicates_and_paginates(self) -> None:
|
||||
client = GiteaClient.__new__(GiteaClient)
|
||||
client.base_url = "http://192.168.1.9:3000"
|
||||
client.token = "t"
|
||||
calls: list[tuple[str, dict]] = []
|
||||
|
||||
def fake_get(path: str, params: dict | None = None):
|
||||
calls.append((path, dict(params or {})))
|
||||
response = MagicMock()
|
||||
page = int((params or {}).get("page", 1))
|
||||
if path == "/api/v1/repos/search":
|
||||
if page == 1:
|
||||
response.json.return_value = {
|
||||
"data": [
|
||||
{"full_name": "alice/app", "clone_url": "http://g/alice/app.git"},
|
||||
{"full_name": "bob/lib", "clone_url": "http://g/bob/lib.git"},
|
||||
]
|
||||
}
|
||||
else:
|
||||
response.json.return_value = {"data": []}
|
||||
elif path == "/api/v1/user/repos":
|
||||
response.json.return_value = [
|
||||
{"full_name": "alice/app", "clone_url": "http://g/alice/app.git"},
|
||||
]
|
||||
else:
|
||||
response.json.return_value = []
|
||||
return response
|
||||
|
||||
client._get = fake_get # type: ignore[method-assign]
|
||||
repos = client.list_repos()
|
||||
names = [r["full_name"] for r in repos]
|
||||
self.assertEqual(names, ["alice/app", "bob/lib"])
|
||||
search_pages = [p for path, p in calls if path == "/api/v1/repos/search"]
|
||||
self.assertGreaterEqual(len(search_pages), 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,47 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from gitea_backup.config import load_config
|
||||
|
||||
|
||||
class LoadConfigTest(unittest.TestCase):
|
||||
def test_defaults_point_to_local_gitea(self) -> None:
|
||||
env = {
|
||||
"GITEA_TOKEN": "abc",
|
||||
"BACKUP_DIR": "/tmp/gitea-backups",
|
||||
"GITEA_BACKUP_SKIP_DOTENV": "1",
|
||||
}
|
||||
with patch.dict(os.environ, env, clear=True):
|
||||
cfg = load_config()
|
||||
self.assertEqual(cfg.gitea_url, "http://192.168.1.9:3000")
|
||||
self.assertEqual(cfg.backup_at, "03:00")
|
||||
self.assertTrue(cfg.snapshots)
|
||||
self.assertEqual(cfg.keep_days, 30)
|
||||
self.assertEqual(cfg.backup_dir, Path("/tmp/gitea-backups"))
|
||||
|
||||
def test_relative_backup_dir_is_resolved(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
env = {
|
||||
"GITEA_TOKEN": "abc",
|
||||
"BACKUP_DIR": "./backups",
|
||||
"GITEA_BACKUP_SKIP_DOTENV": "1",
|
||||
}
|
||||
with patch.dict(os.environ, env, clear=True):
|
||||
with patch("gitea_backup.config.Path.cwd", return_value=Path(tmp)):
|
||||
cfg = load_config()
|
||||
self.assertEqual(cfg.backup_dir, (Path(tmp) / "backups").resolve())
|
||||
|
||||
def test_rejects_bad_url(self) -> None:
|
||||
env = {
|
||||
"GITEA_URL": "192.168.1.9",
|
||||
"GITEA_TOKEN": "x",
|
||||
"GITEA_BACKUP_SKIP_DOTENV": "1",
|
||||
}
|
||||
with patch.dict(os.environ, env, clear=True):
|
||||
with self.assertRaises(ValueError):
|
||||
load_config()
|
||||
Reference in new issue
Block a user