git-annex-mirror-orchestrator/gamo/tests/test_update_refs.py
Michael Hanke cb1e979533
All checks were successful
Ruff / Code linting (push) Successful in 38s
Codespell / Check for spelling errors (push) Successful in 53s
Type annotations / check (push) Successful in 58s
Unit tests (Linux) / check (push) Successful in 2m46s
feat: switch order of operations keys before push
2026-11-17 09:55:38 +01:00

258 lines
8.5 KiB
Python

"""
Functional tests for ``git-gamo-update-refs`` (gamo.update_refs).
The installed entry point is exercised against real local ``git``
repositories; the task record is fed to the command on STDIN. A logging
``git-annex`` stub is placed on PATH so the Git ref operations and the
scheduling state can be verified on systems without a working git-annex
binary; annexed content transfer is out of scope for this command.
"""
import json
from dataclasses import dataclass
from datetime import UTC
from pathlib import Path
from subprocess import CompletedProcess
import pytest
from gamo.tests.conftest import (
GIT_ANNEX_STUB,
AnnexRepos,
GitEnv,
entry_point,
)
from gamo.timestamps import (
parse_timestamp,
timestamp_str,
)
ENTRY_POINT = 'git-gamo-update-refs'
# number of commits across all branches of the seeded source repository
SEED_COMMITS = 2
@dataclass
class UpdateRefsEnv:
entry: str
source: Path
target: Path
workdir: Path
main: str
feature: str
base: GitEnv
@property
def work(self) -> Path:
return self.base.work
@property
def annex_log(self) -> Path:
return self.base.work / 'annex.log'
def record(self, target: Path | None = None) -> dict:
return {
'id': 'demo',
'source': {'url': str(self.source)},
'target': {'url': str(target or self.target)},
}
def git(self, *args: str, cwd: Path | None = None) -> CompletedProcess[str]:
return self.base.git(*args, cwd=cwd)
def git_oneline(self, *args: str, cwd: Path | None = None) -> str:
return self.base.git_oneline(*args, cwd=cwd)
def git_success(self, *args: str, cwd: Path | None = None) -> bool:
return self.base.git_success(*args, cwd=cwd)
def run(self, stdin: str) -> CompletedProcess[str]:
return self.base.run(self.entry, stdin=stdin, cwd=self.workdir)
def _has_ref(env: UpdateRefsEnv, ref: str) -> bool:
return env.git_success('show-ref', '--verify', '--quiet', ref, cwd=env.target)
def _rev(env: UpdateRefsEnv, ref: str) -> str:
return env.git_oneline('rev-parse', ref, cwd=env.target)
@pytest.fixture
def update_refs(git_env: GitEnv, annex_repos: AnnexRepos) -> UpdateRefsEnv:
annex_log = git_env.work / 'annex.log'
git_env.add_bin('git-annex', GIT_ANNEX_STUB, ANNEX_LOG=str(annex_log))
target = annex_repos.target
git_env.git('config', 'user.email', 't@example.com', cwd=target)
git_env.git('config', 'user.name', 'tester', cwd=target)
# update-refs fetches the git-annex branch from the target; a fresh
# target without that branch would be recorded as a task error
tree = git_env.git_oneline('mktree', cwd=target, inputs='')
ga_oid = git_env.git_oneline('commit-tree', tree, '-m', 'git-annex', cwd=target)
git_env.git('update-ref', 'refs/heads/git-annex', ga_oid, cwd=target)
# the entry point resolves configuration from the working directory,
# which must therefore be a git worktree
workdir = git_env.work / 'workdir'
git_env.git('init', '-q', '-b', 'main', str(workdir))
git_env.git('config', 'user.email', 't@example.com', cwd=workdir)
git_env.git('config', 'user.name', 'tester', cwd=workdir)
return UpdateRefsEnv(
entry=entry_point(ENTRY_POINT),
source=annex_repos.source,
target=target,
workdir=workdir,
main=annex_repos.main,
feature=annex_repos.feature,
base=git_env,
)
def test_empty_stdin_is_a_noop(update_refs: UpdateRefsEnv) -> None:
result = update_refs.run(' \n')
assert result.returncode == 0, result.stderr
assert result.stdout == ''
assert not _has_ref(update_refs, 'refs/heads/main')
def test_success_mirrors_refs_and_records_state(update_refs: UpdateRefsEnv) -> None:
result = update_refs.run(json.dumps(update_refs.record()))
assert result.returncode == 0, result.stderr
# the updated record is emitted as a single line of compact JSON
assert result.stdout.count('\n') == 1
record = json.loads(result.stdout)
assert _rev(update_refs, 'refs/heads/main') == update_refs.main
assert _rev(update_refs, 'refs/heads/feature') == update_refs.feature
# tags are mirrored and pushed to the target
assert _has_ref(update_refs, 'refs/tags/v1.0')
assert _rev(
update_refs,
'refs/tags/v1.0',
) == update_refs.git_oneline('rev-parse', 'refs/tags/v1.0', cwd=update_refs.source)
state = record['state']
assert 'last_success' in state
assert state['last30days_ncommits'] == SEED_COMMITS
assert state['n_tags'] == 1
assert 'errors' not in state
# source_last_modified is the newest source branch tip's committer date,
# normalized to UTC
dates = update_refs.git(
'for-each-ref',
'--sort=-committerdate',
'--format=%(committerdate:iso8601-strict)',
'refs/heads/',
cwd=update_refs.source,
).stdout.splitlines()
newest = next(date for date in dates if date.strip())
assert state['source_last_modified'] == timestamp_str(
parse_timestamp(newest).astimezone(UTC)
)
# next_due is no longer stored; next-task computes it on the fly
assert 'next_due' not in record.get('schedule', {})
assert update_refs.annex_log.read_text().splitlines() == [
'git-annex init --quiet',
'git-annex info origin',
'git-annex merge',
'git-annex merge --quiet',
'git-annex copy --all --from-anywhere --to origin --jobs 2 --time-limit 900s --json --json-error-messages',
'git-annex merge',
'git-annex findkeys --anything --json --json-error-messages',
'git-annex findkeys --not --in origin --json --json-error-messages',
]
def test_failure_records_error_without_crashing(update_refs: UpdateRefsEnv) -> None:
missing = update_refs.work / 'nope.git'
result = update_refs.run(json.dumps(update_refs.record(missing)))
assert result.returncode == 0, result.stderr
record = json.loads(result.stdout)
state = record['state']
assert state['errors']
assert state['errors'][0].startswith("Command ['git', 'clone'")
assert 'last_success' not in state
assert 'schedule' not in record
def test_missing_record_keys_are_recorded_as_errors(update_refs: UpdateRefsEnv) -> None:
result = update_refs.run(json.dumps({'id': 'demo'}))
assert result.returncode == 0, result.stderr
state = json.loads(result.stdout)['state']
assert state['errors'] == ["'target'"]
def test_success_clears_previous_errors(update_refs: UpdateRefsEnv) -> None:
record = update_refs.record()
record['state'] = {'errors': ['a previous failure']}
result = update_refs.run(json.dumps(record))
assert result.returncode == 0, result.stderr
state = json.loads(result.stdout)['state']
assert 'errors' not in state
assert 'last_success' in state
def test_auto_disable_after_threshold_errors(update_refs: UpdateRefsEnv) -> None:
update_refs.git(
'config',
'gamo.schedule.auto-disable-after-nerrors',
'1',
cwd=update_refs.workdir,
)
missing = update_refs.work / 'nope.git'
result = update_refs.run(json.dumps(update_refs.record(missing)))
assert result.returncode == 0, result.stderr
record = json.loads(result.stdout)
assert record['state']['errors']
assert record['schedule']['auto_disabled'] is True
def test_prune_defaults_to_false(update_refs: UpdateRefsEnv) -> None:
update_refs.git(
'update-ref',
'refs/heads/stale',
'refs/heads/git-annex',
cwd=update_refs.target,
)
result = update_refs.run(json.dumps(update_refs.record()))
assert result.returncode == 0, result.stderr
assert _has_ref(update_refs, 'refs/heads/stale')
def test_prune_from_record_removes_stale_local_branches(
update_refs: UpdateRefsEnv,
) -> None:
update_refs.git(
'update-ref',
'refs/heads/stale',
'refs/heads/git-annex',
cwd=update_refs.target,
)
record = update_refs.record()
record['target']['prune'] = True
result = update_refs.run(json.dumps(record))
assert result.returncode == 0, result.stderr
assert not _has_ref(update_refs, 'refs/heads/stale')
assert _has_ref(update_refs, 'refs/heads/main')
def test_force_tags_false_from_record_skips_tag_mirror(
update_refs: UpdateRefsEnv,
) -> None:
record = update_refs.record()
record['target']['force_tags'] = False
result = update_refs.run(json.dumps(record))
assert result.returncode == 0, result.stderr
assert not _has_ref(update_refs, 'refs/tags/v1.0')
assert json.loads(result.stdout)['state']['n_tags'] == 0