Files
fiona-assistant/tests/test_gittool.py
T
nvaldez de28441943 feat: sync Nokia fork product through SPEC 1.18 (v1.16.0)
MEMORY.md and skill memory template, ingest auth and html_sweep, TOC slug fix, run_tests CI output, and matching tests. Excludes GitLab CI and publishing docs.
2026-10-19 09:12:04 +02:00

329 lines
12 KiB
Python

"""Tests for the gittool module."""
from __future__ import annotations
import git
import pytest
from fiona.gittool.git_tool import GitTool
def _configure_test_repo(repo: git.Repo) -> None:
"""Set local git identity so commits and tags work without global config.
Generated by AI/LLM: 2026-10-14 - GitLab CI runs as root without user.name.
"""
with repo.config_writer() as config:
config.set_value("user", "email", "fiona-test@example.com")
config.set_value("user", "name", "Fiona Test")
@pytest.fixture(scope="session")
def read_only_repo(tmp_path_factory):
"""One git repo for tests that only read it.
Generated by AI/LLM: 2026-09-30 - avoid a git init per read-only test.
"""
path = tmp_path_factory.mktemp("read_only_git")
repo = git.Repo.init(path)
_configure_test_repo(repo)
(path / "file1.txt").write_text("initial content")
repo.index.add(["file1.txt"])
repo.index.commit("Initial commit")
return path
@pytest.fixture
def git_repo(tmp_path):
"""Create a temporary git repository for testing."""
repo = git.Repo.init(tmp_path)
_configure_test_repo(repo)
# Create an initial commit
(tmp_path / "file1.txt").write_text("initial content")
repo.index.add(["file1.txt"])
repo.index.commit("Initial commit")
return repo
class TestGitTool:
"""Tests for GitTool class."""
def test_init(self, read_only_repo):
"""Test GitTool initialization."""
git_tool = GitTool(read_only_repo)
assert git_tool.repo_path == read_only_repo.resolve()
assert git_tool.repo is not None
def test_is_working_tree_clean_true(self, read_only_repo):
"""Test _is_working_tree_clean returns True when tree is clean."""
git_tool = GitTool(read_only_repo)
assert git_tool._is_working_tree_clean() is True
def test_is_working_tree_clean_false_modified(self, git_repo, tmp_path):
"""Test _is_working_tree_clean returns False when files are modified."""
git_tool = GitTool(tmp_path)
# Modify a file
(tmp_path / "file1.txt").write_text("modified content")
assert git_tool._is_working_tree_clean() is False
def test_is_working_tree_clean_false_untracked(self, git_repo, tmp_path):
"""Test _is_working_tree_clean returns False when there are untracked files."""
git_tool = GitTool(tmp_path)
# Create an untracked file
(tmp_path / "untracked.txt").write_text("untracked content")
assert git_tool._is_working_tree_clean() is False
def test_get_timestamp_format(self, read_only_repo):
"""Test _get_timestamp returns correct format."""
# AI/LLM: do not require the project checkout itself to be a git repo.
git_tool = GitTool(read_only_repo)
timestamp = git_tool._get_timestamp()
# Should be in format: yyyy-mm-dd HH:MM:SS
assert len(timestamp) == 19
assert timestamp[4] == "-"
assert timestamp[7] == "-"
assert timestamp[10] == " "
assert timestamp[13] == ":"
assert timestamp[16] == ":"
def test_get_tag_timestamp_format(self):
"""Test _get_tag_timestamp returns tag-safe format."""
tag_timestamp = GitTool._get_tag_timestamp()
# Should be in format: yyyy-mm-dd_HH-MM-SS (no spaces)
assert " " not in tag_timestamp
assert len(tag_timestamp) == 19
assert tag_timestamp[4] == "-"
assert tag_timestamp[7] == "-"
assert tag_timestamp[10] == "_"
assert tag_timestamp[13] == "-"
assert tag_timestamp[16] == "-"
def test_save(self, git_repo, tmp_path):
"""Test save creates a commit with timestamp prefix."""
git_tool = GitTool(tmp_path)
# Modify a file
(tmp_path / "file1.txt").write_text("modified content")
commit_hash = git_tool.save("test commit")
# Verify commit was created
assert commit_hash is not None
assert len(commit_hash) == 40 # SHA-1 hash length
# Verify commit message format
commits = list(git_repo.iter_commits())
latest = commits[0]
assert "test commit" in latest.message
# Check timestamp prefix
assert len(latest.message) > len("test commit")
def test_save_clean_tree_raises(self, read_only_repo):
"""Test save raises ValueError when tree is clean."""
git_tool = GitTool(read_only_repo)
with pytest.raises(ValueError, match="Working tree is clean"):
git_tool.save("test commit")
def test_snapshot(self, git_repo, tmp_path):
"""Test snapshot creates commit and tag."""
git_tool = GitTool(tmp_path)
# Modify a file
(tmp_path / "file1.txt").write_text("modified content")
commit_hash, tag = git_tool.snapshot("testtag", "test snapshot")
# Verify commit was created
assert commit_hash is not None
# Verify tag was created with correct format
assert tag.startswith("2026-")
assert "_testtag" in tag
assert " " not in tag # No spaces in tag name
# Verify tag exists
assert tag in git_repo.tags
def test_snapshot_clean_tree_raises(self, read_only_repo):
"""Test snapshot raises ValueError when tree is clean."""
git_tool = GitTool(read_only_repo)
with pytest.raises(ValueError, match="Working tree is clean"):
git_tool.snapshot("testtag", "test snapshot")
def test_clean(self, git_repo, tmp_path):
"""Test clean discards current edits."""
git_tool = GitTool(tmp_path)
# Modify a file
(tmp_path / "file1.txt").write_text("modified content")
assert git_tool._is_working_tree_clean() is False
# Clean
result = git_tool.clean()
assert "cleaned" in result.lower()
# Verify tree is clean
assert git_tool._is_working_tree_clean() is True
# Verify file was reverted
assert (tmp_path / "file1.txt").read_text() == "initial content"
def test_clean_already_clean_raises(self, read_only_repo):
"""Test clean raises ValueError when tree is already clean."""
git_tool = GitTool(read_only_repo)
with pytest.raises(ValueError, match="already clean"):
git_tool.clean()
def test_undo(self, git_repo, tmp_path):
"""Test undo moves back one commit."""
# Create another commit
(tmp_path / "file2.txt").write_text("second content")
git_repo.index.add(["file2.txt"])
git_repo.index.commit("Second commit")
git_tool = GitTool(tmp_path)
previous_head = git_repo.head.commit.hexsha
commit_hash = git_tool.undo()
# Verify we moved back
assert commit_hash != previous_head
assert git_repo.head.commit.hexsha == commit_hash
def test_undo_dirty_tree_raises(self, git_repo, tmp_path):
"""Test undo raises ValueError when tree is dirty."""
git_tool = GitTool(tmp_path)
# Create another commit first
(tmp_path / "file2.txt").write_text("second content")
git_repo.index.add(["file2.txt"])
git_repo.index.commit("Second commit")
# Make tree dirty
(tmp_path / "file1.txt").write_text("modified content")
with pytest.raises(ValueError, match="Working tree is dirty"):
git_tool.undo()
def test_undo_single_commit_raises(self, read_only_repo):
"""Test undo raises error when only one commit exists."""
git_tool = GitTool(read_only_repo)
with pytest.raises(git.GitCommandError):
git_tool.undo()
def test_restore_by_full_tag(self, git_repo, tmp_path):
"""Test restore with full tag name."""
git_tool = GitTool(tmp_path)
# Create a tag
(tmp_path / "file1.txt").write_text("tagged content")
git_repo.index.add(["file1.txt"])
commit = git_repo.index.commit("Tagged commit")
git_repo.create_tag("test_tag_full", ref=commit)
# Modify file after tag
(tmp_path / "file1.txt").write_text("modified after tag")
git_repo.index.add(["file1.txt"])
git_repo.index.commit("After tag commit")
# Restore to tag
commit_hash = git_tool.restore("test_tag_full")
# Verify new commit was created
assert commit_hash is not None
# Verify file was restored
assert (tmp_path / "file1.txt").read_text() == "tagged content"
# Verify history was preserved (new commit on top)
commits = list(git_repo.iter_commits())
assert len(commits) >= 3 # original + tag + restore
def test_restore_by_partial_tag(self, git_repo, tmp_path):
"""Test restore with partial tag name (without timestamp)."""
git_tool = GitTool(tmp_path)
# Create a tag with timestamp prefix
(tmp_path / "file1.txt").write_text("tagged content")
git_repo.index.add(["file1.txt"])
commit = git_repo.index.commit("Tagged commit")
git_repo.create_tag("2026-01-01_12-00-00_partial", ref=commit)
# Modify file after tag
(tmp_path / "file1.txt").write_text("modified after tag")
git_repo.index.add(["file1.txt"])
git_repo.index.commit("After tag commit")
# Restore using partial tag name
git_tool.restore("partial")
# Verify file was restored
assert (tmp_path / "file1.txt").read_text() == "tagged content"
def test_restore_dirty_tree_raises(self, git_repo, tmp_path):
"""Test restore raises ValueError when tree is dirty."""
git_tool = GitTool(tmp_path)
# Create a tag
(tmp_path / "file1.txt").write_text("tagged content")
git_repo.index.add(["file1.txt"])
commit = git_repo.index.commit("Tagged commit")
git_repo.create_tag("test_tag", ref=commit)
# Make tree dirty
(tmp_path / "file2.txt").write_text("untracked")
with pytest.raises(ValueError, match="Working tree is dirty"):
git_tool.restore("test_tag")
def test_restore_nonexistent_tag_raises(self, read_only_repo):
"""Test restore raises error when tag does not exist."""
git_tool = GitTool(read_only_repo)
with pytest.raises(git.GitCommandError):
git_tool.restore("nonexistent_tag")
def test_status(self, read_only_repo):
"""Test status returns git status information."""
git_tool = GitTool(read_only_repo)
status = git_tool.status()
assert isinstance(status, str)
assert "Status:" in status
def test_init_repo(self, tmp_path):
"""Test init_repo initializes a git repository."""
repo = GitTool.init_repo(tmp_path)
assert repo is not None
assert (tmp_path / ".git").exists()
def test_init_wiki_repo(self, tmp_path):
"""Test init_wiki_repo initializes git with .gitignore for personal/."""
# Create some files first
(tmp_path / "file1.txt").write_text("content")
(tmp_path / "personal").mkdir()
(tmp_path / "personal" / "private.txt").write_text("private")
repo = GitTool.init_wiki_repo(tmp_path, "Initial commit")
# Verify .gitignore exists and excludes personal/
gitignore_path = tmp_path / ".gitignore"
assert gitignore_path.exists()
gitignore_content = gitignore_path.read_text()
assert "personal/" in gitignore_content
# Verify initial commit was created
assert repo is not None
commits = list(repo.iter_commits())
assert len(commits) >= 1
def test_init_wiki_repo_ignores_obsidian_user_state(self, tmp_path):
"""SPEC 3.2.3: Obsidian per-user state is ignored, vault settings are not.
Generated by AI/LLM: 2026-10-15 - Obsidian vault support.
"""
repo = GitTool.init_wiki_repo(tmp_path, "Initial commit")
paths = [
".obsidian/workspace.json",
".obsidian/workspace-mobile.json",
".obsidian/cache",
".obsidian/app.json",
]
ignored = repo.git.check_ignore(*paths).splitlines()
assert ignored == paths[:3]