import datetime import tomllib from pathlib import Path from src import cli from src.config import Config, FetchConfig from src.gitea_api import GiteaApiError from src.models import GiteaRepository, GiteaUser def make_repo(repo_id=42, name="repo") -> GiteaRepository: return GiteaRepository( ssh_url="ssh://git@example.com/alex/repo.git", clone_url="https://example.com/alex/repo.git", name=name, id=repo_id, updated_at=datetime.datetime.now(), owner=GiteaUser( id=23, login="alex", email="alex@example.com", ), ) def make_config(tmp_path, fetch: FetchConfig | None = None) -> Config: return Config( api_token="api-token", endpoint="https://example.com", repository_format="{owner}/{name}", out_dir=str(tmp_path), fetch=fetch or FetchConfig(ssh_key="/tmp/test_key"), ) def test_project_defines_console_script(): data = tomllib.loads(Path("pyproject.toml").read_text()) assert data["project"]["scripts"]["gitea-mirror"] == "src.cli:main" def test_run_returns_failure_when_api_fetch_fails(monkeypatch, tmp_path): class FakeApi: def __init__(self, endpoint, api_token): pass def get_repositories(self): raise GiteaApiError("request failed") monkeypatch.setattr(cli, "GiteaApi", FakeApi) assert cli.run(make_config(tmp_path)) == 1 def test_run_returns_failure_when_any_repo_fails(monkeypatch, tmp_path): class FakeApi: def __init__(self, endpoint, api_token): pass def get_repositories(self): return [ make_repo(repo_id=1, name="repo-1"), make_repo(repo_id=2, name="repo-2"), ] calls = [] def fake_process_repo(config, repo): calls.append(repo.repo_id) return repo.repo_id == 1 monkeypatch.setattr(cli, "GiteaApi", FakeApi) monkeypatch.setattr(cli, "process_repo", fake_process_repo) assert cli.run(make_config(tmp_path)) == 1 assert calls == [1, 2] def test_run_returns_success_when_all_repos_succeed(monkeypatch, tmp_path): class FakeApi: def __init__(self, endpoint, api_token): pass def get_repositories(self): return [make_repo()] monkeypatch.setattr(cli, "GiteaApi", FakeApi) monkeypatch.setattr(cli, "process_repo", lambda config, repo: True) assert cli.run(make_config(tmp_path)) == 0 def test_main_returns_failure_for_invalid_config(monkeypatch): def fake_read_toml_config(path): raise RuntimeError("bad") monkeypatch.setattr(cli, "read_toml_config", fake_read_toml_config) assert cli.main(["bad.toml"]) == 1 def test_main_uses_config_path(monkeypatch, tmp_path): config = make_config(tmp_path) calls = [] monkeypatch.setattr(cli, "read_toml_config", lambda path: config) monkeypatch.setattr(cli, "setup_logging", lambda logging_config: None) monkeypatch.setattr(cli, "run", lambda config: calls.append(config) or 0) assert cli.main(["config.toml"]) == 0 assert calls == [config]