1636 lines
62 KiB
Python
1636 lines
62 KiB
Python
"""Tests for the update_manager module.
|
|
|
|
This module tests the wiki update manager functionality including:
|
|
- File comparison functions
|
|
- Update summary generation
|
|
- Version checking
|
|
- SHA256 hash calculation
|
|
- Core file identification
|
|
- Settings preservation during updates
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
import re
|
|
import shutil
|
|
import sys
|
|
import tempfile
|
|
from pathlib import Path
|
|
from unittest.mock import patch
|
|
|
|
import pytest
|
|
|
|
from fiona.wiki.update_manager import (
|
|
CORE_DIRECTORIES,
|
|
CORE_FILES,
|
|
READ_ONLY_ZONES,
|
|
SETTINGS_FILE,
|
|
FileComparisonResult,
|
|
UpdateSummary,
|
|
calculate_sha256,
|
|
check_update_main,
|
|
check_wiki_updates,
|
|
compare_md_file,
|
|
compare_non_md_file,
|
|
compare_settings_file,
|
|
copy_settings_with_preservation,
|
|
find_missing_core_files,
|
|
find_missing_directories,
|
|
format_check_update_output,
|
|
get_all_template_files,
|
|
get_llm_wiki_source_path,
|
|
is_core_file,
|
|
is_read_only_file,
|
|
is_version_newer,
|
|
update_core_files,
|
|
update_main,
|
|
)
|
|
from fiona.wiki.wiki import _copy_file
|
|
|
|
# =============================================================================
|
|
# Fixtures
|
|
# =============================================================================
|
|
|
|
@pytest.fixture
|
|
def temp_wiki_dir():
|
|
"""Create a temporary wiki directory for testing."""
|
|
with tempfile.TemporaryDirectory() as tmpdir:
|
|
wiki_dir = Path(tmpdir) / "test_wiki"
|
|
wiki_dir.mkdir()
|
|
|
|
# Create a basic fiona-settings.json to mark it as an llm-wiki
|
|
settings_file = wiki_dir / "fiona-settings.json"
|
|
settings_file.write_text(json.dumps({"markdown": {"pymarkdown": {}}}, indent=2))
|
|
|
|
yield wiki_dir
|
|
|
|
|
|
@pytest.fixture
|
|
def temp_template_dir():
|
|
"""Create a temporary template directory for testing."""
|
|
with tempfile.TemporaryDirectory() as tmpdir:
|
|
template_dir = Path(tmpdir) / "template"
|
|
template_dir.mkdir()
|
|
|
|
# Create some template files
|
|
(template_dir / "AGENTS.md").write_text("---\nname: AGENTS\nversion: 1.0.0\n---\n# Agents")
|
|
(template_dir / "README.md").write_text("---\nname: README\nversion: 1.0.0\n---\n# README")
|
|
(template_dir / "fiona-settings.json").write_text(json.dumps({"version": "1.0.0"}, indent=2))
|
|
|
|
# Create subdirectory
|
|
wiki_subdir = template_dir / "wiki"
|
|
wiki_subdir.mkdir()
|
|
(wiki_subdir / "index.md").write_text("---\nname: index\nversion: 1.0.0\n---\n# Index")
|
|
|
|
yield template_dir
|
|
|
|
|
|
@pytest.fixture
|
|
def mock_wiki_root():
|
|
"""Create a mock wiki root with some files."""
|
|
with tempfile.TemporaryDirectory() as tmpdir:
|
|
wiki_root = Path(tmpdir)
|
|
|
|
# Create core files
|
|
(wiki_root / "AGENTS.md").write_text("---\nname: AGENTS\nversion: 1.0.0\n---\n# Agents")
|
|
(wiki_root / "fiona-settings.json").write_text(json.dumps({"version": "1.0.0"}, indent=2))
|
|
|
|
# Create user file (not core)
|
|
(wiki_root / "user_notes.md").write_text("# User Notes")
|
|
|
|
# Create read-only zone
|
|
personal_dir = wiki_root / "personal"
|
|
personal_dir.mkdir()
|
|
(personal_dir / "private.md").write_text("# Private")
|
|
|
|
yield wiki_root
|
|
|
|
|
|
# =============================================================================
|
|
# Data Class Tests
|
|
# =============================================================================
|
|
|
|
class TestFileComparisonResult:
|
|
"""Tests for FileComparisonResult dataclass."""
|
|
|
|
def test_default_values(self):
|
|
"""Test that default values are set correctly."""
|
|
result = FileComparisonResult(file_path=Path("/test/file.md"))
|
|
|
|
assert result.file_path == Path("/test/file.md")
|
|
assert result.is_core_file is False
|
|
assert result.has_template_version is False
|
|
assert result.current_version is None
|
|
assert result.template_version is None
|
|
assert result.current_hash is None
|
|
assert result.template_hash is None
|
|
assert result.needs_update is False
|
|
assert result.is_new_file is False
|
|
assert result.is_settings_file is False
|
|
|
|
def test_needs_update_when_new_file(self):
|
|
"""Test that new files are marked as needing update."""
|
|
result = FileComparisonResult(file_path=Path("/test/file.md"), is_new_file=True)
|
|
|
|
assert result.needs_update is True
|
|
|
|
def test_custom_values(self):
|
|
"""Test that custom values can be set."""
|
|
result = FileComparisonResult(
|
|
file_path=Path("/test/file.md"),
|
|
is_core_file=True,
|
|
has_template_version=True,
|
|
current_version="1.0.0",
|
|
template_version="2.0.0",
|
|
needs_update=True
|
|
)
|
|
|
|
assert result.is_core_file is True
|
|
assert result.has_template_version is True
|
|
assert result.current_version == "1.0.0"
|
|
assert result.template_version == "2.0.0"
|
|
assert result.needs_update is True
|
|
|
|
|
|
class TestUpdateSummary:
|
|
"""Tests for UpdateSummary dataclass."""
|
|
|
|
def test_empty_summary(self):
|
|
"""Test empty update summary."""
|
|
summary = UpdateSummary()
|
|
|
|
assert summary.files_to_update == []
|
|
assert summary.files_to_add == []
|
|
assert summary.settings_file is None
|
|
assert summary.has_updates is False
|
|
assert summary.total_files == 0
|
|
|
|
def test_summary_with_updates(self):
|
|
"""Test summary with files to update."""
|
|
result1 = FileComparisonResult(
|
|
file_path=Path("/test/file1.md"),
|
|
needs_update=True
|
|
)
|
|
result2 = FileComparisonResult(
|
|
file_path=Path("/test/file2.md"),
|
|
needs_update=True
|
|
)
|
|
|
|
summary = UpdateSummary(
|
|
files_to_update=[result1, result2],
|
|
files_to_add=[Path("/test/new_file.md")]
|
|
)
|
|
|
|
assert len(summary.files_to_update) == 2
|
|
assert len(summary.files_to_add) == 1
|
|
assert summary.has_updates is True
|
|
assert summary.total_files == 3
|
|
|
|
def test_summary_with_settings_file(self):
|
|
"""Test summary with settings file."""
|
|
summary = UpdateSummary(
|
|
settings_file=Path("/test/fiona-settings.json")
|
|
)
|
|
|
|
assert summary.settings_file == Path("/test/fiona-settings.json")
|
|
|
|
|
|
# =============================================================================
|
|
# Helper Function Tests
|
|
# =============================================================================
|
|
|
|
class TestCalculateSha256:
|
|
"""Tests for SHA256 hash calculation."""
|
|
|
|
def test_calculate_sha256(self, tmp_path):
|
|
"""Test SHA256 hash calculation for a file."""
|
|
test_file = tmp_path / "test.txt"
|
|
test_file.write_text("test content")
|
|
|
|
result = calculate_sha256(test_file)
|
|
|
|
# Calculate expected hash
|
|
expected = hashlib.sha256(b"test content").hexdigest()
|
|
|
|
assert result == expected
|
|
assert len(result) == 64 # SHA256 hash is 64 hex characters
|
|
|
|
def test_calculate_sha256_nonexistent_file(self):
|
|
"""Test that FileNotFoundError is raised for non-existent file."""
|
|
with pytest.raises(FileNotFoundError):
|
|
calculate_sha256(Path("/nonexistent/file.txt"))
|
|
|
|
|
|
class TestIsCoreFile:
|
|
"""Tests for core file identification."""
|
|
|
|
def test_core_file_in_root(self, temp_wiki_dir):
|
|
"""Test that core files in root are identified."""
|
|
for core_file in CORE_FILES:
|
|
file_path = temp_wiki_dir / core_file
|
|
file_path.write_text("test")
|
|
assert is_core_file(file_path, temp_wiki_dir) is True
|
|
|
|
def test_core_file_in_core_directory(self, temp_wiki_dir):
|
|
"""Test that files in core directories are identified."""
|
|
for core_dir in CORE_DIRECTORIES:
|
|
dir_path = temp_wiki_dir / core_dir
|
|
dir_path.mkdir(exist_ok=True)
|
|
file_path = dir_path / "test.md"
|
|
file_path.write_text("test")
|
|
assert is_core_file(file_path, temp_wiki_dir) is True
|
|
|
|
def test_non_core_file(self, temp_wiki_dir):
|
|
"""Test that non-core files are not identified as core."""
|
|
file_path = temp_wiki_dir / "user_notes.md"
|
|
file_path.write_text("test")
|
|
assert is_core_file(file_path, temp_wiki_dir) is False
|
|
|
|
def test_file_outside_wiki(self, temp_wiki_dir):
|
|
"""Test that files outside wiki root are not core."""
|
|
outside_file = Path("/tmp/outside.md")
|
|
assert is_core_file(outside_file, temp_wiki_dir) is False
|
|
|
|
|
|
class TestIsReadOnlyFile:
|
|
"""Tests for read-only file identification."""
|
|
|
|
def test_personal_zone(self, temp_wiki_dir):
|
|
"""Test that files in personal/ are read-only."""
|
|
personal_dir = temp_wiki_dir / "personal"
|
|
personal_dir.mkdir()
|
|
file_path = personal_dir / "private.md"
|
|
file_path.write_text("test")
|
|
|
|
assert is_read_only_file(file_path, temp_wiki_dir) is True
|
|
|
|
def test_raw_zone(self, temp_wiki_dir):
|
|
"""Test that files in raw/ are read-only."""
|
|
raw_dir = temp_wiki_dir / "raw"
|
|
raw_dir.mkdir()
|
|
file_path = raw_dir / "data.json"
|
|
file_path.write_text("test")
|
|
|
|
assert is_read_only_file(file_path, temp_wiki_dir) is True
|
|
|
|
def test_non_read_only_file(self, temp_wiki_dir):
|
|
"""Test that files outside read-only zones are not read-only."""
|
|
file_path = temp_wiki_dir / "AGENTS.md"
|
|
file_path.write_text("test")
|
|
|
|
assert is_read_only_file(file_path, temp_wiki_dir) is False
|
|
|
|
def test_file_outside_wiki_not_read_only(self, temp_wiki_dir):
|
|
"""Test that files outside wiki root are not read-only."""
|
|
outside_file = Path("/tmp/outside.md")
|
|
assert is_read_only_file(outside_file, temp_wiki_dir) is False
|
|
|
|
|
|
class TestGetLlmWikiSourcePath:
|
|
"""Tests for getting the llm-wiki source path."""
|
|
|
|
def test_returns_path(self):
|
|
"""Test that a Path is returned."""
|
|
result = get_llm_wiki_source_path()
|
|
assert isinstance(result, Path)
|
|
|
|
def test_returns_existing_path(self):
|
|
"""Test that the path exists or the fallback exists."""
|
|
result = get_llm_wiki_source_path()
|
|
# Either the direct path or the fallback should exist
|
|
assert result.is_dir()
|
|
assert result.name == "llm_wiki"
|
|
assert (result / "AGENTS.md").is_file()
|
|
|
|
|
|
# =============================================================================
|
|
# Comparison Function Tests
|
|
# =============================================================================
|
|
|
|
class TestCompareMdFile:
|
|
"""Tests for markdown file comparison."""
|
|
|
|
def test_compare_identical_versions(self, tmp_path):
|
|
"""Test comparing files with identical versions."""
|
|
wiki_file = tmp_path / "file.md"
|
|
template_file = tmp_path / "template.md"
|
|
|
|
content = "---\nname: Test\nversion: 1.0.0\n---\n# Content"
|
|
wiki_file.write_text(content)
|
|
template_file.write_text(content)
|
|
|
|
result = compare_md_file(wiki_file, template_file)
|
|
|
|
assert result.file_path == wiki_file
|
|
assert result.is_core_file is True
|
|
assert result.has_template_version is True
|
|
# Note: Version comparison logic is stubbed, so we just verify the function runs
|
|
|
|
def test_compare_different_versions(self, tmp_path):
|
|
"""Test comparing files with different versions."""
|
|
wiki_file = tmp_path / "file.md"
|
|
template_file = tmp_path / "template.md"
|
|
|
|
wiki_content = "---\nname: Test\nversion: 1.0.0\n---\n# Content"
|
|
template_content = "---\nname: Test\nversion: 2.0.0\n---\n# Content"
|
|
|
|
wiki_file.write_text(wiki_content)
|
|
template_file.write_text(template_content)
|
|
|
|
result = compare_md_file(wiki_file, template_file)
|
|
|
|
assert result.file_path == wiki_file
|
|
assert result.is_core_file is True
|
|
|
|
|
|
class TestCompareNonMdFile:
|
|
"""Tests for non-markdown file comparison."""
|
|
|
|
def test_compare_json_files(self, tmp_path):
|
|
"""Test comparing JSON files using hash."""
|
|
wiki_file = tmp_path / "settings.json"
|
|
template_file = tmp_path / "template_settings.json"
|
|
|
|
content = json.dumps({"version": "1.0.0"}, indent=2)
|
|
wiki_file.write_text(content)
|
|
template_file.write_text(content)
|
|
|
|
result = compare_non_md_file(wiki_file, template_file)
|
|
|
|
assert result.file_path == wiki_file
|
|
assert result.is_core_file is True
|
|
assert result.has_template_version is False
|
|
|
|
|
|
class TestCompareSettingsFile:
|
|
"""Tests for settings file comparison."""
|
|
|
|
def test_compare_settings(self, tmp_path):
|
|
"""Test comparing settings files."""
|
|
wiki_settings = tmp_path / "fiona-settings.json"
|
|
template_settings = tmp_path / "template_settings.json"
|
|
|
|
wiki_content = json.dumps({"version": "1.0.0", "custom": "value"}, indent=2)
|
|
template_content = json.dumps({"version": "2.0.0", "new_setting": "new"}, indent=2)
|
|
|
|
wiki_settings.write_text(wiki_content)
|
|
template_settings.write_text(template_content)
|
|
|
|
result = compare_settings_file(wiki_settings, template_settings)
|
|
|
|
assert result.file_path == wiki_settings
|
|
assert result.is_core_file is True
|
|
assert result.is_settings_file is True
|
|
|
|
|
|
# =============================================================================
|
|
# Template File Tests
|
|
# =============================================================================
|
|
|
|
class TestGetAllTemplateFiles:
|
|
"""Tests for getting all template files."""
|
|
|
|
def test_get_all_template_files(self, temp_template_dir):
|
|
"""Test getting all files from template directory."""
|
|
files = get_all_template_files(temp_template_dir)
|
|
|
|
# Should return a list (may be empty in stub)
|
|
assert isinstance(files, list)
|
|
|
|
|
|
class TestFindMissingCoreFiles:
|
|
"""Tests for finding missing core files."""
|
|
|
|
def test_find_missing_files(self, temp_wiki_dir, temp_template_dir):
|
|
"""Test finding files that exist in template but not in wiki."""
|
|
# Create a file in template that doesn't exist in wiki
|
|
(temp_template_dir / "new_file.md").write_text("---\nname: New\nversion: 1.0.0\n---\n# New")
|
|
|
|
missing = find_missing_core_files(temp_wiki_dir, temp_template_dir)
|
|
|
|
# Should return a list (may be empty in stub)
|
|
assert isinstance(missing, list)
|
|
|
|
|
|
# =============================================================================
|
|
# Check Update Tests
|
|
# =============================================================================
|
|
|
|
class TestCheckWikiUpdates:
|
|
"""Tests for checking wiki updates."""
|
|
|
|
def test_check_pristine_wiki(self, temp_wiki_dir):
|
|
"""Test checking a pristine wiki (no updates needed)."""
|
|
# A wiki created by init should have no updates needed
|
|
summary = check_wiki_updates(str(temp_wiki_dir))
|
|
|
|
assert isinstance(summary, UpdateSummary)
|
|
|
|
def test_real_init_is_up_to_date(self, pristine_wiki):
|
|
"""Test a real wiki init reports nothing to update on any OS (SPEC 7.1.2.5).
|
|
|
|
Generated by AI/LLM: 2026-09-30 - init must keep template line endings.
|
|
"""
|
|
summary = check_wiki_updates(pristine_wiki)
|
|
|
|
assert [r.file_path.name for r in summary.files_to_update] == []
|
|
assert summary.has_updates is False
|
|
|
|
def test_check_nonexistent_directory(self):
|
|
"""Test checking a non-existent directory."""
|
|
with pytest.raises(FileNotFoundError):
|
|
check_wiki_updates("/nonexistent/directory")
|
|
|
|
def test_check_non_wiki_directory(self, tmp_path):
|
|
"""Test checking a directory that is not an llm-wiki."""
|
|
# Create a directory without fiona-settings.json
|
|
non_wiki_dir = tmp_path / "non_wiki"
|
|
non_wiki_dir.mkdir()
|
|
|
|
with pytest.raises(NotADirectoryError):
|
|
check_wiki_updates(str(non_wiki_dir))
|
|
|
|
@patch("fiona.wiki.update_manager.get_llm_wiki_source_path")
|
|
def test_check_template_not_found(self, mock_get_source, tmp_path):
|
|
"""Test checking when template directory is not found."""
|
|
# Create a valid wiki directory
|
|
wiki_dir = tmp_path / "wiki"
|
|
wiki_dir.mkdir()
|
|
(wiki_dir / "fiona-settings.json").write_text(json.dumps({}))
|
|
|
|
# Mock get_llm_wiki_source_path to return non-existent path
|
|
mock_get_source.return_value = Path("/nonexistent/template")
|
|
|
|
with pytest.raises(FileNotFoundError, match="Template directory not found"):
|
|
check_wiki_updates(str(wiki_dir))
|
|
|
|
|
|
# =============================================================================
|
|
# Format Output Tests
|
|
# =============================================================================
|
|
|
|
class TestFormatCheckUpdateOutput:
|
|
"""Tests for formatting check update output."""
|
|
|
|
def test_format_empty_summary(self):
|
|
"""Test formatting an empty summary."""
|
|
summary = UpdateSummary()
|
|
output = format_check_update_output(summary)
|
|
|
|
assert "Wiki is up to date" in output
|
|
|
|
def test_format_summary_with_updates(self):
|
|
"""Test formatting a summary with updates."""
|
|
result = FileComparisonResult(
|
|
file_path=Path("/test/file.md"),
|
|
needs_update=True
|
|
)
|
|
summary = UpdateSummary(
|
|
files_to_update=[result],
|
|
files_to_add=[Path("/test/new_file.md")]
|
|
)
|
|
|
|
output = format_check_update_output(summary)
|
|
|
|
assert "Files to update: 1" in output
|
|
assert "Files to add: 1" in output
|
|
assert "Total: 2" in output
|
|
|
|
|
|
# =============================================================================
|
|
# Update Core Files Tests
|
|
# =============================================================================
|
|
|
|
class TestUpdateCoreFiles:
|
|
"""Tests for updating core files."""
|
|
|
|
def test_update_no_changes_needed(self, temp_wiki_dir):
|
|
"""Test updating when no changes are needed."""
|
|
summary = update_core_files(str(temp_wiki_dir), force=True)
|
|
|
|
assert isinstance(summary, UpdateSummary)
|
|
|
|
def test_update_with_force(self, temp_wiki_dir):
|
|
"""Test updating with force flag."""
|
|
summary = update_core_files(str(temp_wiki_dir), force=True)
|
|
|
|
assert isinstance(summary, UpdateSummary)
|
|
|
|
def test_update_without_force_raises(self, temp_wiki_dir):
|
|
"""Test that update without force raises error when changes needed."""
|
|
# In stub, this will raise RuntimeError if there are updates needed
|
|
# but no force/yes flag
|
|
try:
|
|
summary = update_core_files(str(temp_wiki_dir), force=False, yes=False)
|
|
# If no updates needed, it should succeed
|
|
assert isinstance(summary, UpdateSummary)
|
|
except RuntimeError as e:
|
|
# If there are updates needed, it should raise
|
|
assert "confirmation" in str(e).lower() or "force" in str(e).lower() or "yes" in str(e).lower()
|
|
|
|
|
|
# =============================================================================
|
|
# Settings Preservation Tests
|
|
# =============================================================================
|
|
|
|
class TestCopySettingsWithPreservation:
|
|
"""Tests for copying settings while preserving user customizations."""
|
|
|
|
def test_preserve_user_settings(self, tmp_path):
|
|
"""Test that user settings are preserved during update."""
|
|
wiki_settings = tmp_path / "wiki_settings.json"
|
|
template_settings = tmp_path / "template_settings.json"
|
|
|
|
wiki_content = json.dumps({
|
|
"version": "1.0.0",
|
|
"markdown": {"pymarkdown": {"line_length": 120}},
|
|
"user_custom": "value"
|
|
}, indent=2)
|
|
|
|
template_content = json.dumps({
|
|
"version": "2.0.0",
|
|
"markdown": {"pymarkdown": {"line_length": 100}},
|
|
"new_setting": "new"
|
|
}, indent=2)
|
|
|
|
wiki_settings.write_text(wiki_content)
|
|
template_settings.write_text(template_content)
|
|
|
|
# This is a stub, so it just shouldn't crash
|
|
copy_settings_with_preservation(wiki_settings, template_settings)
|
|
|
|
|
|
# =============================================================================
|
|
# CLI Function Tests
|
|
# =============================================================================
|
|
|
|
class TestCheckUpdateMain:
|
|
"""Tests for check-update main function."""
|
|
|
|
def test_check_update_main_default(self, temp_wiki_dir):
|
|
"""Test check-update main with default arguments."""
|
|
result = check_update_main(directory=str(temp_wiki_dir))
|
|
|
|
assert result == 0
|
|
|
|
def test_check_update_main_json(self, temp_wiki_dir):
|
|
"""Test check-update main with JSON output."""
|
|
result = check_update_main(directory=str(temp_wiki_dir), json_output=True)
|
|
|
|
assert result == 0
|
|
|
|
def test_check_update_main_nonexistent(self):
|
|
"""Test check-update main with non-existent directory."""
|
|
result = check_update_main(directory="/nonexistent")
|
|
|
|
assert result == 1
|
|
|
|
|
|
class TestUpdateMain:
|
|
"""Tests for update main function."""
|
|
|
|
def test_update_main_default(self, tmp_path, temp_wiki_dir, monkeypatch):
|
|
"""Test update main on an up-to-date wiki with default arguments."""
|
|
# Template with exactly the wiki's settings file: nothing to update
|
|
template = tmp_path / "in_sync_template"
|
|
template.mkdir()
|
|
shutil.copy2(
|
|
temp_wiki_dir / "fiona-settings.json", template / "fiona-settings.json"
|
|
)
|
|
monkeypatch.setattr(
|
|
"fiona.wiki.update_manager.get_llm_wiki_source_path", lambda: template
|
|
)
|
|
|
|
result = update_main(directory=str(temp_wiki_dir))
|
|
|
|
assert result == 0
|
|
|
|
def test_update_main_default_needs_confirmation(self, temp_wiki_dir):
|
|
"""Test update without flags refuses non-interactively when needed."""
|
|
# temp_wiki_dir is missing template files, so updates are needed;
|
|
# without --force/--yes and a non-interactive stdin the update is refused
|
|
result = update_main(directory=str(temp_wiki_dir))
|
|
|
|
assert result == 1
|
|
|
|
def test_update_main_with_force(self, temp_wiki_dir):
|
|
"""Test update main with force flag."""
|
|
result = update_main(directory=str(temp_wiki_dir), force=True)
|
|
|
|
assert result == 0
|
|
|
|
def test_update_main_with_yes(self, temp_wiki_dir):
|
|
"""Test update main with yes flag."""
|
|
result = update_main(directory=str(temp_wiki_dir), yes=True)
|
|
|
|
assert result == 0
|
|
|
|
def test_update_main_dry_run(self, temp_wiki_dir):
|
|
"""Test update main with dry-run flag."""
|
|
result = update_main(directory=str(temp_wiki_dir), dry_run=True)
|
|
|
|
assert result == 0
|
|
|
|
def test_update_main_json(self, temp_wiki_dir):
|
|
"""Test update main with JSON output."""
|
|
result = update_main(directory=str(temp_wiki_dir), yes=True, json_output=True)
|
|
|
|
assert result == 0
|
|
|
|
def test_update_main_nonexistent(self):
|
|
"""Test update main with non-existent directory."""
|
|
result = update_main(directory="/nonexistent")
|
|
|
|
assert result == 1
|
|
|
|
@patch("fiona.wiki.update_manager.update_core_files")
|
|
def test_update_main_runtime_error(self, mock_update, tmp_path):
|
|
"""Test update main when RuntimeError is raised."""
|
|
# Create a valid wiki directory
|
|
wiki_dir = tmp_path / "wiki"
|
|
wiki_dir.mkdir()
|
|
(wiki_dir / "fiona-settings.json").write_text(json.dumps({}))
|
|
|
|
# Mock update_core_files to raise RuntimeError
|
|
mock_update.side_effect = RuntimeError("Test error")
|
|
|
|
result = update_main(directory=str(wiki_dir))
|
|
|
|
assert result == 1
|
|
|
|
|
|
# =============================================================================
|
|
# Constants Tests
|
|
# =============================================================================
|
|
|
|
class TestConstants:
|
|
"""Tests for module constants."""
|
|
|
|
def test_core_files_constant(self):
|
|
"""Test that CORE_FILES is a list."""
|
|
assert isinstance(CORE_FILES, list)
|
|
assert "AGENTS.md" in CORE_FILES
|
|
assert "fiona-settings.json" in CORE_FILES
|
|
|
|
def test_core_directories_constant(self):
|
|
"""Test that CORE_DIRECTORIES is a list."""
|
|
assert isinstance(CORE_DIRECTORIES, list)
|
|
assert "wiki" in CORE_DIRECTORIES
|
|
assert "ingest" in CORE_DIRECTORIES
|
|
|
|
def test_read_only_zones_constant(self):
|
|
"""Test that READ_ONLY_ZONES is a list."""
|
|
assert isinstance(READ_ONLY_ZONES, list)
|
|
assert "personal/" in READ_ONLY_ZONES
|
|
assert "raw/" in READ_ONLY_ZONES
|
|
|
|
def test_settings_file_constant(self):
|
|
"""Test that SETTINGS_FILE is a string."""
|
|
assert SETTINGS_FILE == "fiona-settings.json"
|
|
|
|
|
|
# =============================================================================
|
|
# Implementation Tests (SPEC 7.1.2)
|
|
# =============================================================================
|
|
|
|
def _write_md(path: Path, version: str, body: str = "# Doc\n", name: str = "doc"):
|
|
"""Write a small md file with frontmatter at path."""
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_text(
|
|
f"---\nname: {name}\nversion: {version}\n---\n{body}", encoding="utf-8"
|
|
)
|
|
|
|
|
|
def _build_template(template_root: Path) -> Path:
|
|
"""Build a small template tree for implementation tests."""
|
|
_write_md(template_root / "AGENTS.md", "2.0.0", body="# Agents v2\n", name="agents")
|
|
_write_md(template_root / "README.md", "1.0.0", body="# Readme\n", name="readme")
|
|
(template_root / "fiona-settings.json").write_text(
|
|
json.dumps({"a": 1}), encoding="utf-8"
|
|
)
|
|
_write_md(template_root / "wiki" / "index.md", "1.0.0", body="# Index\n", name="index")
|
|
(template_root / "wiki" / "queries").mkdir(parents=True, exist_ok=True)
|
|
(template_root / "wiki" / "queries" / ".gitkeep").write_text("", encoding="utf-8")
|
|
_write_md(
|
|
template_root / "personal" / "README.md", "2.0.0", body="# Personal v2\n",
|
|
name="personal",
|
|
)
|
|
return template_root
|
|
|
|
|
|
def _build_wiki_from_template(template_root: Path, wiki_root: Path) -> Path:
|
|
"""Create a pristine wiki by copying every template file."""
|
|
wiki_root.mkdir(parents=True, exist_ok=True)
|
|
for item in template_root.rglob("*"):
|
|
if item.is_file():
|
|
dest = wiki_root / item.relative_to(template_root)
|
|
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
shutil.copy2(item, dest)
|
|
return wiki_root
|
|
|
|
|
|
@pytest.fixture
|
|
def template_wiki_pair(tmp_path, monkeypatch):
|
|
"""Provide a template and a pristine wiki copy, with source path patched."""
|
|
template = _build_template(tmp_path / "template")
|
|
wiki = _build_wiki_from_template(template, tmp_path / "wiki")
|
|
monkeypatch.setattr(
|
|
"fiona.wiki.update_manager.get_llm_wiki_source_path", lambda: template
|
|
)
|
|
return template, wiki
|
|
|
|
|
|
class TestIsVersionNewer:
|
|
"""Tests for semantic version comparison."""
|
|
|
|
def test_newer_patch(self):
|
|
assert is_version_newer("1.0.1", "1.0.0") is True
|
|
|
|
def test_newer_minor(self):
|
|
assert is_version_newer("1.1.0", "1.0.9") is True
|
|
|
|
def test_older_version(self):
|
|
assert is_version_newer("1.0.0", "2.0.0") is False
|
|
|
|
def test_equal_version(self):
|
|
assert is_version_newer("1.0.0", "1.0.0") is False
|
|
|
|
def test_non_numeric_falls_back_to_string(self):
|
|
assert is_version_newer("1.0.0-alpha.2", "1.0.0-alpha.1") is True
|
|
assert is_version_newer("1.0.0-alpha.1", "1.0.0-alpha.2") is False
|
|
|
|
|
|
class TestCompareMdFileVersions:
|
|
"""Tests for md file comparison via frontmatter versions."""
|
|
|
|
def test_identical_files_need_no_update(self, tmp_path):
|
|
wiki_file = tmp_path / "file.md"
|
|
template_file = tmp_path / "template.md"
|
|
content = "---\nname: Test\nversion: 1.0.0\n---\n# Content"
|
|
wiki_file.write_text(content, encoding="utf-8")
|
|
template_file.write_text(content, encoding="utf-8")
|
|
|
|
result = compare_md_file(wiki_file, template_file)
|
|
|
|
assert result.needs_update is False
|
|
assert result.is_locally_modified is False
|
|
assert result.current_version == "1.0.0"
|
|
assert result.template_version == "1.0.0"
|
|
|
|
def test_newer_template_is_conflict(self, tmp_path):
|
|
"""Test a newer template is a conflict, never an overwrite (SPEC 7.1.2.1.1)."""
|
|
wiki_file = tmp_path / "file.md"
|
|
template_file = tmp_path / "template.md"
|
|
_write_md(wiki_file, "1.0.0", body="# Old\n")
|
|
_write_md(template_file, "2.0.0", body="# New\n")
|
|
|
|
result = compare_md_file(wiki_file, template_file)
|
|
|
|
assert result.needs_update is False
|
|
assert result.is_conflict is True
|
|
assert result.update_path == tmp_path / "file-update.md"
|
|
assert result.is_locally_modified is False
|
|
assert result.current_version == "1.0.0"
|
|
assert result.template_version == "2.0.0"
|
|
|
|
def test_newer_wiki_version_is_locally_modified(self, tmp_path):
|
|
wiki_file = tmp_path / "file.md"
|
|
template_file = tmp_path / "template.md"
|
|
_write_md(wiki_file, "3.0.0", body="# User\n")
|
|
_write_md(template_file, "2.0.0", body="# Template\n")
|
|
|
|
result = compare_md_file(wiki_file, template_file)
|
|
|
|
assert result.needs_update is False
|
|
assert result.is_locally_modified is True
|
|
|
|
def test_diverged_content_same_version_is_locally_modified(self, tmp_path):
|
|
wiki_file = tmp_path / "file.md"
|
|
template_file = tmp_path / "template.md"
|
|
_write_md(wiki_file, "1.0.0", body="# User edit\n")
|
|
_write_md(template_file, "1.0.0", body="# Template\n")
|
|
|
|
result = compare_md_file(wiki_file, template_file)
|
|
|
|
assert result.needs_update is False
|
|
assert result.is_locally_modified is True
|
|
|
|
def test_no_versions_falls_back_to_content(self, tmp_path):
|
|
wiki_file = tmp_path / "file.md"
|
|
template_file = tmp_path / "template.md"
|
|
wiki_file.write_text("plain text\n", encoding="utf-8")
|
|
template_file.write_text("plain text\n", encoding="utf-8")
|
|
|
|
assert compare_md_file(wiki_file, template_file).is_conflict is False
|
|
|
|
template_file.write_text("changed text\n", encoding="utf-8")
|
|
|
|
result = compare_md_file(wiki_file, template_file)
|
|
assert result.is_conflict is True
|
|
assert result.needs_update is False
|
|
|
|
|
|
class TestCompareNonMdFileHashes:
|
|
"""Tests for non-md file comparison via SHA256."""
|
|
|
|
def test_identical_files_need_no_update(self, tmp_path):
|
|
wiki_file = tmp_path / "script.py"
|
|
template_file = tmp_path / "template_script.py"
|
|
wiki_file.write_text("print('x')\n", encoding="utf-8")
|
|
template_file.write_text("print('x')\n", encoding="utf-8")
|
|
|
|
result = compare_non_md_file(wiki_file, template_file)
|
|
|
|
assert result.needs_update is False
|
|
assert result.current_hash == result.template_hash
|
|
|
|
def test_different_files_need_update(self, tmp_path):
|
|
wiki_file = tmp_path / "script.py"
|
|
template_file = tmp_path / "template_script.py"
|
|
wiki_file.write_text("print('old')\n", encoding="utf-8")
|
|
template_file.write_text("print('new')\n", encoding="utf-8")
|
|
|
|
result = compare_non_md_file(wiki_file, template_file)
|
|
|
|
assert result.needs_update is True
|
|
|
|
|
|
class TestCompareSettingsFileHashes:
|
|
"""Tests for settings file comparison via SHA256."""
|
|
|
|
def test_identical_files_need_no_update(self, tmp_path):
|
|
content = json.dumps({"a": 1}, indent=2)
|
|
wiki_file = tmp_path / "fiona-settings.json"
|
|
template_file = tmp_path / "template_settings.json"
|
|
wiki_file.write_text(content, encoding="utf-8")
|
|
template_file.write_text(content, encoding="utf-8")
|
|
|
|
result = compare_settings_file(wiki_file, template_file)
|
|
|
|
assert result.needs_update is False
|
|
assert result.is_settings_file is True
|
|
|
|
def test_diverged_files_need_update(self, tmp_path):
|
|
wiki_file = tmp_path / "fiona-settings.json"
|
|
template_file = tmp_path / "template_settings.json"
|
|
wiki_file.write_text(json.dumps({"a": 1, "user": True}), encoding="utf-8")
|
|
template_file.write_text(json.dumps({"a": 1}), encoding="utf-8")
|
|
|
|
result = compare_settings_file(wiki_file, template_file)
|
|
|
|
assert result.needs_update is False
|
|
assert result.is_conflict is True
|
|
assert result.update_path == wiki_file.with_name("fiona-settings-update.json")
|
|
|
|
|
|
class TestGetAllTemplateFilesImplemented:
|
|
"""Tests for template file discovery."""
|
|
|
|
def test_returns_relative_paths(self, temp_template_dir):
|
|
files = {f.as_posix() for f in get_all_template_files(temp_template_dir)}
|
|
|
|
assert files == {
|
|
"AGENTS.md",
|
|
"README.md",
|
|
"fiona-settings.json",
|
|
"wiki/index.md",
|
|
}
|
|
|
|
def test_honors_ignore_files(self, temp_template_dir):
|
|
(temp_template_dir / "fiona-settings.json").write_text(json.dumps({
|
|
"fiona": {"llm-wiki": {"ignore_files": ["wiki/*"]}}
|
|
}), encoding="utf-8")
|
|
|
|
files = {f.as_posix() for f in get_all_template_files(temp_template_dir)}
|
|
|
|
assert "wiki/index.md" not in files
|
|
assert "AGENTS.md" in files
|
|
|
|
def test_skips_repository_gitignore(self, temp_template_dir):
|
|
"""Test byte-code caches are not template update candidates."""
|
|
cached = temp_template_dir / "utils" / "scripts" / "__pycache__"
|
|
cached.mkdir(parents=True)
|
|
(cached / "example.pyc").write_bytes(b"pyc")
|
|
|
|
files = {path.as_posix() for path in get_all_template_files(temp_template_dir)}
|
|
|
|
assert "utils/scripts/__pycache__/example.pyc" not in files
|
|
|
|
|
|
class TestFindMissingCoreFilesImplemented:
|
|
"""Tests for finding missing core files."""
|
|
|
|
def test_missing_files_reported(self, temp_wiki_dir, temp_template_dir):
|
|
missing = {m.as_posix() for m in find_missing_core_files(
|
|
temp_wiki_dir, temp_template_dir
|
|
)}
|
|
|
|
assert "AGENTS.md" in missing
|
|
assert "README.md" in missing
|
|
assert "wiki/index.md" not in missing
|
|
|
|
def test_present_file_not_reported(self, temp_wiki_dir, temp_template_dir):
|
|
shutil.copy2(
|
|
temp_template_dir / "AGENTS.md", temp_wiki_dir / "AGENTS.md"
|
|
)
|
|
|
|
missing = {m.as_posix() for m in find_missing_core_files(
|
|
temp_wiki_dir, temp_template_dir
|
|
)}
|
|
|
|
assert "AGENTS.md" not in missing
|
|
|
|
def test_read_only_zone_excluded(self, temp_wiki_dir, temp_template_dir):
|
|
_write_md(
|
|
temp_template_dir / "personal" / "README.md", "1.0.0",
|
|
body="# Personal\n", name="personal",
|
|
)
|
|
|
|
missing = {m.as_posix() for m in find_missing_core_files(
|
|
temp_wiki_dir, temp_template_dir
|
|
)}
|
|
|
|
assert not any(m.startswith("personal/") for m in missing)
|
|
|
|
|
|
class TestFindMissingDirectories:
|
|
"""Tests for finding missing template directories."""
|
|
|
|
def _template(self, tmp_path):
|
|
template = tmp_path / "template"
|
|
_write_md(template / "wiki" / "index.md", "1.0.0", name="index")
|
|
_write_md(template / "personal" / "README.md", "1.0.0", name="personal")
|
|
_write_md(template / "utils" / "scripts" / "map.md", "1.0.0", name="map")
|
|
return template
|
|
|
|
def test_missing_directories_reported(self, tmp_path):
|
|
template = self._template(tmp_path)
|
|
wiki = tmp_path / "wiki_root"
|
|
wiki.mkdir()
|
|
(wiki / "fiona-settings.json").write_text("{}", encoding="utf-8")
|
|
|
|
missing = {d.as_posix() for d in find_missing_directories(wiki, template)}
|
|
|
|
assert missing == {"utils", "utils/scripts"}
|
|
|
|
def test_existing_directories_not_reported(self, tmp_path):
|
|
template = self._template(tmp_path)
|
|
wiki = tmp_path / "wiki_root"
|
|
(wiki / "wiki").mkdir(parents=True)
|
|
(wiki / "utils" / "scripts").mkdir(parents=True)
|
|
|
|
missing = find_missing_directories(wiki, template)
|
|
|
|
assert missing == []
|
|
|
|
def test_read_only_zone_directories_excluded(self, tmp_path):
|
|
template = self._template(tmp_path)
|
|
wiki = tmp_path / "wiki_root"
|
|
wiki.mkdir()
|
|
|
|
missing = {d.as_posix() for d in find_missing_directories(wiki, template)}
|
|
|
|
assert "personal" not in missing
|
|
|
|
|
|
class TestCheckWikiUpdatesImplemented:
|
|
"""Tests for the full update check."""
|
|
|
|
def test_pristine_wiki_is_up_to_date(self, template_wiki_pair):
|
|
_template, wiki = template_wiki_pair
|
|
|
|
summary = check_wiki_updates(str(wiki))
|
|
|
|
assert summary.has_updates is False
|
|
assert summary.files_to_update == []
|
|
assert summary.files_to_add == []
|
|
assert summary.files_skipped == []
|
|
assert summary.directories_to_add == []
|
|
|
|
def test_outdated_md_reported_as_conflict(self, template_wiki_pair):
|
|
_template, wiki = template_wiki_pair
|
|
_write_md(wiki / "AGENTS.md", "1.0.0", body="# Agents v1\n", name="agents")
|
|
|
|
summary = check_wiki_updates(str(wiki))
|
|
|
|
assert summary.has_updates is True
|
|
assert summary.files_to_update == []
|
|
assert len(summary.conflicts) == 1
|
|
result = summary.conflicts[0]
|
|
assert result.file_path == (wiki / "AGENTS.md").resolve()
|
|
assert result.update_path == (wiki / "AGENTS-update.md").resolve()
|
|
assert result.current_version == "1.0.0"
|
|
assert result.template_version == "2.0.0"
|
|
assert not (wiki / "AGENTS-update.md").exists()
|
|
|
|
def test_wiki_page_older_than_template_is_conflict(self, template_wiki_pair):
|
|
"""Test an older wiki/ template page is a conflict (SPEC 7.1.2.9)."""
|
|
_template, wiki = template_wiki_pair
|
|
_write_md(wiki / "wiki" / "index.md", "0.1.0", body="# User index\n", name="index")
|
|
|
|
summary = check_wiki_updates(str(wiki))
|
|
|
|
assert [r.update_path for r in summary.conflicts] == [
|
|
(wiki / "wiki" / "index-update.md").resolve()
|
|
]
|
|
|
|
def test_conflict_clears_at_template_version(self, template_wiki_pair):
|
|
"""Test a merged file at the template version is no conflict (SPEC 7.1.2.11.4)."""
|
|
_template, wiki = template_wiki_pair
|
|
_write_md(wiki / "AGENTS.md", "2.0.0", body="# Merged agents\n", name="agents")
|
|
|
|
summary = check_wiki_updates(str(wiki))
|
|
|
|
assert summary.conflicts == []
|
|
|
|
def test_missing_file_reported_as_add(self, template_wiki_pair):
|
|
_template, wiki = template_wiki_pair
|
|
(wiki / "README.md").unlink()
|
|
|
|
summary = check_wiki_updates(str(wiki))
|
|
|
|
assert Path("README.md").as_posix() in [
|
|
p.as_posix() for p in summary.files_to_add
|
|
]
|
|
assert summary.has_updates is True
|
|
|
|
def test_missing_directory_reported(self, template_wiki_pair):
|
|
_template, wiki = template_wiki_pair
|
|
shutil.rmtree(wiki / "wiki" / "queries")
|
|
|
|
summary = check_wiki_updates(str(wiki))
|
|
|
|
assert "wiki/queries" not in [
|
|
d.as_posix() for d in summary.directories_to_add
|
|
]
|
|
assert not any(
|
|
path.as_posix() == "wiki" or path.as_posix().startswith("wiki/")
|
|
for path in summary.files_to_add
|
|
)
|
|
|
|
def test_locally_modified_version_skipped_and_reported(self, template_wiki_pair):
|
|
_template, wiki = template_wiki_pair
|
|
_write_md(wiki / "AGENTS.md", "9.0.0", body="# User agents\n", name="agents")
|
|
|
|
summary = check_wiki_updates(str(wiki))
|
|
|
|
assert summary.files_to_update == []
|
|
assert [r.file_path for r in summary.files_skipped] == [
|
|
(wiki / "AGENTS.md").resolve()
|
|
]
|
|
|
|
def test_diverged_content_skipped(self, template_wiki_pair):
|
|
_template, wiki = template_wiki_pair
|
|
_write_md(wiki / "README.md", "1.0.0", body="# User readme\n", name="readme")
|
|
|
|
summary = check_wiki_updates(str(wiki))
|
|
|
|
assert summary.files_to_update == []
|
|
assert [r.file_path for r in summary.files_skipped] == [
|
|
(wiki / "README.md").resolve()
|
|
]
|
|
|
|
def test_settings_divergence_flagged(self, template_wiki_pair):
|
|
_template, wiki = template_wiki_pair
|
|
(wiki / "fiona-settings.json").write_text(
|
|
json.dumps({"a": 1, "user_key": "custom"}), encoding="utf-8"
|
|
)
|
|
|
|
summary = check_wiki_updates(str(wiki))
|
|
|
|
assert summary.settings_file == (wiki / "fiona-settings.json").resolve()
|
|
settings_results = [
|
|
r for r in summary.conflicts if r.is_settings_file
|
|
]
|
|
assert len(settings_results) == 1
|
|
assert settings_results[0].update_path.name == "fiona-settings-update.json"
|
|
assert not any(r.is_settings_file for r in summary.files_to_update)
|
|
|
|
def test_user_created_file_not_flagged(self, template_wiki_pair):
|
|
_template, wiki = template_wiki_pair
|
|
_write_md(wiki / "wiki" / "concepts" / "note.md", "1.0.0", name="note")
|
|
|
|
summary = check_wiki_updates(str(wiki))
|
|
|
|
assert summary.has_updates is False
|
|
|
|
def test_wiki_pages_stay_out_of_the_report(self, template_wiki_pair):
|
|
"""Test a newer wiki page is not an update, add, skip, or conflict."""
|
|
_template, wiki = template_wiki_pair
|
|
_write_md(
|
|
wiki / "wiki" / "index.md", "3.0.0", body="# User index\n", name="index"
|
|
)
|
|
(wiki / "wiki" / "queries" / ".gitkeep").write_text("local", encoding="utf-8")
|
|
|
|
summary = check_wiki_updates(str(wiki))
|
|
|
|
reported = [result.file_path.as_posix() for result in summary.files_to_update]
|
|
reported += [result.file_path.as_posix() for result in summary.files_skipped]
|
|
reported += [result.file_path.as_posix() for result in summary.conflicts]
|
|
reported += [path.as_posix() for path in summary.files_to_add]
|
|
reported += [path.as_posix() for path in summary.directories_to_add]
|
|
assert not any(
|
|
path == "wiki" or path.startswith("wiki/") or path.endswith("/wiki/index.md")
|
|
for path in reported
|
|
)
|
|
|
|
def test_repository_gitignore_artifact_is_not_reported(self, template_wiki_pair):
|
|
"""Test a template byte-code file is not offered as an update."""
|
|
template, wiki = template_wiki_pair
|
|
cached = template / "utils" / "scripts" / "__pycache__"
|
|
cached.mkdir(parents=True)
|
|
(cached / "example.pyc").write_bytes(b"template")
|
|
wiki_cached = wiki / "utils" / "scripts" / "__pycache__"
|
|
wiki_cached.mkdir(parents=True)
|
|
(wiki_cached / "example.pyc").write_bytes(b"local")
|
|
|
|
summary = check_wiki_updates(str(wiki))
|
|
|
|
reported = [result.file_path.as_posix() for result in summary.files_to_update]
|
|
reported += [result.file_path.as_posix() for result in summary.files_skipped]
|
|
reported += [path.as_posix() for path in summary.files_to_add]
|
|
assert not any(path.endswith("example.pyc") for path in reported)
|
|
|
|
def test_wiki_gitignore_hides_drifted_file(self, template_wiki_pair):
|
|
"""Test a path listed in the wiki gitignore is absent from the report."""
|
|
template, wiki = template_wiki_pair
|
|
(template / "utils" / "scripts").mkdir(parents=True)
|
|
(template / "utils" / "scripts" / "example.py").write_text(
|
|
"print('new')\n", encoding="utf-8"
|
|
)
|
|
(wiki / "utils" / "scripts").mkdir(parents=True)
|
|
(wiki / "utils" / "scripts" / "example.py").write_text(
|
|
"print('old')\n", encoding="utf-8"
|
|
)
|
|
(wiki / ".gitignore").write_text("example.py\n", encoding="utf-8")
|
|
|
|
summary = check_wiki_updates(str(wiki))
|
|
|
|
assert not any(
|
|
result.file_path.name == "example.py" for result in summary.files_to_update
|
|
)
|
|
assert not any(
|
|
result.file_path.name == "example.py" for result in summary.files_skipped
|
|
)
|
|
|
|
def test_read_only_template_files_ignored(self, template_wiki_pair):
|
|
_template, wiki = template_wiki_pair
|
|
(wiki / "personal" / "README.md").unlink()
|
|
|
|
summary = check_wiki_updates(str(wiki))
|
|
|
|
assert summary.has_updates is False
|
|
assert summary.files_to_add == []
|
|
|
|
|
|
class TestUpdateCoreFilesImplemented:
|
|
"""Tests for performing the actual update."""
|
|
|
|
def test_yes_keeps_outdated_file_and_writes_update_file(self, template_wiki_pair):
|
|
"""Test update yields to the owner and writes AGENTS-update.md (SPEC 7.1.2.6)."""
|
|
_template, wiki = template_wiki_pair
|
|
owner = "---\nname: agents\nversion: 1.0.0\n---\n# Agents v1\n"
|
|
(wiki / "AGENTS.md").write_text(owner, encoding="utf-8")
|
|
|
|
summary = update_core_files(str(wiki), yes=True)
|
|
|
|
assert (wiki / "AGENTS.md").read_text(encoding="utf-8") == owner
|
|
assert (wiki / "AGENTS-update.md").read_text(encoding="utf-8") == (
|
|
"---\nname: agents\nversion: 2.0.0\n---\n# Agents v2\n"
|
|
)
|
|
assert len(summary.conflicts) == 1
|
|
assert summary.files_to_update == []
|
|
|
|
def test_update_file_expands_date_placeholder(self, template_wiki_pair):
|
|
"""Test the update file holds the expanded template (SPEC 7.1.2.11.2)."""
|
|
template, wiki = template_wiki_pair
|
|
_write_md(
|
|
template / "README.md", "2.0.0",
|
|
body="updated: DATE_PLACEHOLDER\n", name="readme",
|
|
)
|
|
|
|
update_core_files(str(wiki), yes=True)
|
|
first = (wiki / "README-update.md").read_bytes()
|
|
update_core_files(str(wiki), yes=True)
|
|
|
|
assert b"DATE_PLACEHOLDER" not in first
|
|
assert (wiki / "README-update.md").read_bytes() == first
|
|
assert sorted(p.name for p in wiki.glob("*-update.md")) == ["README-update.md"]
|
|
|
|
def test_dry_run_writes_no_update_file(self, template_wiki_pair):
|
|
"""Test --dry-run lists the conflict and writes nothing (SPEC 7.1.2.11.3)."""
|
|
_template, wiki = template_wiki_pair
|
|
_write_md(wiki / "AGENTS.md", "1.0.0", body="# Agents v1\n", name="agents")
|
|
|
|
assert update_main(directory=str(wiki), dry_run=True) == 0
|
|
|
|
assert list(wiki.rglob("*-update.md")) == []
|
|
|
|
def test_wiki_schema_conflict_writes_only_its_update_file(self, template_wiki_pair):
|
|
"""Test a wiki/ conflict writes one sibling update file (SPEC 7.1.2.11.1)."""
|
|
template, wiki = template_wiki_pair
|
|
_write_md(template / "wiki" / "schema.md", "1.5.0", body="# Schema\n", name="schema")
|
|
owner = "---\nname: schema\nversion: 1.4.0\n---\n# My tags\n"
|
|
(wiki / "wiki" / "schema.md").write_text(owner, encoding="utf-8")
|
|
before = {p for p in wiki.rglob("*") if p.is_file()}
|
|
|
|
update_core_files(str(wiki), yes=True)
|
|
|
|
after = {p for p in wiki.rglob("*") if p.is_file()}
|
|
assert after - before == {wiki / "wiki" / "schema-update.md"}
|
|
assert (wiki / "wiki" / "schema.md").read_text(encoding="utf-8") == owner
|
|
|
|
def test_yes_adds_missing_file_and_directory(self, template_wiki_pair):
|
|
template, wiki = template_wiki_pair
|
|
(wiki / "README.md").unlink()
|
|
shutil.rmtree(wiki / "wiki" / "queries")
|
|
_write_md(template / "utils" / "scripts" / "map.md", "1.0.0", name="map")
|
|
|
|
update_core_files(str(wiki), yes=True)
|
|
|
|
assert (wiki / "README.md").read_text(encoding="utf-8") == (
|
|
"---\nname: readme\nversion: 1.0.0\n---\n# Readme\n"
|
|
)
|
|
assert (wiki / "utils" / "scripts" / "map.md").is_file()
|
|
assert not (wiki / "wiki" / "queries").exists()
|
|
|
|
def test_yes_leaves_wiki_pages_unchanged(self, template_wiki_pair):
|
|
"""Test update does not rewrite or restore anything under wiki/."""
|
|
_template, wiki = template_wiki_pair
|
|
user = "---\nname: index\nversion: 0.1.0\n---\n# User index\n"
|
|
(wiki / "wiki" / "index.md").write_text(user, encoding="utf-8")
|
|
shutil.rmtree(wiki / "wiki" / "queries")
|
|
|
|
update_core_files(str(wiki), yes=True)
|
|
|
|
assert (wiki / "wiki" / "index.md").read_text(encoding="utf-8") == user
|
|
assert (wiki / "wiki" / "index-update.md").read_text(encoding="utf-8") == (
|
|
"---\nname: index\nversion: 1.0.0\n---\n# Index\n"
|
|
)
|
|
assert not (wiki / "wiki" / "queries").exists()
|
|
|
|
def test_yes_leaves_gitignored_file_unchanged(self, template_wiki_pair):
|
|
"""Test update does not overwrite a file the wiki gitignore names."""
|
|
template, wiki = template_wiki_pair
|
|
(template / "utils" / "scripts").mkdir(parents=True)
|
|
(template / "utils" / "scripts" / "example.py").write_text(
|
|
"print('new')\n", encoding="utf-8"
|
|
)
|
|
original = "print('old')\n"
|
|
(wiki / "utils" / "scripts").mkdir(parents=True)
|
|
(wiki / "utils" / "scripts" / "example.py").write_text(
|
|
original, encoding="utf-8"
|
|
)
|
|
(wiki / ".gitignore").write_text("example.py\n", encoding="utf-8")
|
|
|
|
update_core_files(str(wiki), yes=True)
|
|
|
|
assert (wiki / "utils" / "scripts" / "example.py").read_text(
|
|
encoding="utf-8"
|
|
) == original
|
|
|
|
def test_locally_modified_file_left_untouched(self, template_wiki_pair):
|
|
_template, wiki = template_wiki_pair
|
|
user_content = "---\nname: agents\nversion: 9.0.0\n---\n# User agents\n"
|
|
(wiki / "AGENTS.md").write_text(user_content, encoding="utf-8")
|
|
|
|
update_core_files(str(wiki), yes=True)
|
|
|
|
assert (wiki / "AGENTS.md").read_text(encoding="utf-8") == user_content
|
|
|
|
def test_read_only_zone_untouched(self, template_wiki_pair):
|
|
_template, wiki = template_wiki_pair
|
|
user_content = "---\nname: personal\nversion: 1.0.0\n---\n# Old personal\n"
|
|
(wiki / "personal" / "README.md").write_text(user_content, encoding="utf-8")
|
|
|
|
update_core_files(str(wiki), yes=True)
|
|
|
|
assert (wiki / "personal" / "README.md").read_text(encoding="utf-8") == (
|
|
user_content
|
|
)
|
|
|
|
def test_settings_conflict_keeps_owner_and_writes_update(self, template_wiki_pair):
|
|
"""SPEC 7.1.2.3: a drifted settings file is a conflict, not a merge."""
|
|
template, wiki = template_wiki_pair
|
|
owner = json.dumps({"a": 1, "user_key": "custom"})
|
|
(wiki / "fiona-settings.json").write_text(owner, encoding="utf-8")
|
|
|
|
update_core_files(str(wiki), yes=True)
|
|
|
|
assert (wiki / "fiona-settings.json").read_text(encoding="utf-8") == owner
|
|
assert (wiki / "fiona-settings-update.json").read_text(encoding="utf-8") == (
|
|
(template / "fiona-settings.json").read_text(encoding="utf-8")
|
|
)
|
|
|
|
def test_requires_confirmation_without_flags(self, template_wiki_pair):
|
|
_template, wiki = template_wiki_pair
|
|
_write_md(wiki / "AGENTS.md", "1.0.0", body="# Agents v1\n", name="agents")
|
|
|
|
with pytest.raises(RuntimeError, match="--force|--yes"):
|
|
update_core_files(str(wiki))
|
|
|
|
def test_interactive_confirmation_accepts_yes(
|
|
self, template_wiki_pair, monkeypatch
|
|
):
|
|
_template, wiki = template_wiki_pair
|
|
_write_md(wiki / "AGENTS.md", "1.0.0", body="# Agents v1\n", name="agents")
|
|
monkeypatch.setattr("builtins.input", lambda prompt="": "y")
|
|
monkeypatch.setattr(sys.stdin, "isatty", lambda: True)
|
|
|
|
update_core_files(str(wiki))
|
|
|
|
assert "version: 2.0.0" in (wiki / "AGENTS-update.md").read_text(encoding="utf-8")
|
|
|
|
def test_interactive_confirmation_declined(
|
|
self, template_wiki_pair, monkeypatch
|
|
):
|
|
_template, wiki = template_wiki_pair
|
|
_write_md(wiki / "AGENTS.md", "1.0.0", body="# Agents v1\n", name="agents")
|
|
monkeypatch.setattr("builtins.input", lambda prompt="": "n")
|
|
monkeypatch.setattr(sys.stdin, "isatty", lambda: True)
|
|
|
|
with pytest.raises(RuntimeError):
|
|
update_core_files(str(wiki))
|
|
|
|
assert "version: 1.0.0" in (wiki / "AGENTS.md").read_text(encoding="utf-8")
|
|
|
|
|
|
class TestCopySettingsWithPreservationImplemented:
|
|
"""Tests for settings merge."""
|
|
|
|
def test_merge_preserves_user_values_and_adds_template_keys(self, tmp_path):
|
|
wiki_settings = tmp_path / "fiona-settings.json"
|
|
template_settings = tmp_path / "template_settings.json"
|
|
wiki_settings.write_text(json.dumps({
|
|
"markdown": {"pymarkdown": {"line_length": 120}},
|
|
"user_custom": "value",
|
|
}), encoding="utf-8")
|
|
template_settings.write_text(json.dumps({
|
|
"markdown": {"pymarkdown": {"line_length": 100, "md041": True}},
|
|
"new_section": {"x": 1},
|
|
}), encoding="utf-8")
|
|
|
|
copy_settings_with_preservation(wiki_settings, template_settings)
|
|
|
|
merged = json.loads(wiki_settings.read_text(encoding="utf-8"))
|
|
assert merged["markdown"]["pymarkdown"]["line_length"] == 120
|
|
assert merged["markdown"]["pymarkdown"]["md041"] is True
|
|
assert merged["user_custom"] == "value"
|
|
assert merged["new_section"] == {"x": 1}
|
|
|
|
|
|
class TestCheckUpdateMainJson:
|
|
"""Tests for check-update JSON output."""
|
|
|
|
def test_json_reports_updates(self, template_wiki_pair, capsys):
|
|
_template, wiki = template_wiki_pair
|
|
_write_md(wiki / "AGENTS.md", "1.0.0", body="# Agents v1\n", name="agents")
|
|
|
|
result = check_update_main(directory=str(wiki), json_output=True)
|
|
output = json.loads(capsys.readouterr().out)
|
|
|
|
assert result == 0
|
|
assert output["has_updates"] is True
|
|
assert output["files_to_update"] == []
|
|
conflict = output["conflicts"][0]
|
|
assert conflict["current_version"] == "1.0.0"
|
|
assert conflict["template_version"] == "2.0.0"
|
|
assert conflict["update_path"].endswith("AGENTS-update.md")
|
|
assert output["total"] == 1
|
|
|
|
def test_json_reports_skipped_files(self, template_wiki_pair, capsys):
|
|
_template, wiki = template_wiki_pair
|
|
_write_md(wiki / "AGENTS.md", "9.0.0", body="# User agents\n", name="agents")
|
|
|
|
result = check_update_main(directory=str(wiki), json_output=True)
|
|
output = json.loads(capsys.readouterr().out)
|
|
|
|
assert result == 0
|
|
assert output["has_updates"] is False
|
|
assert len(output["files_skipped"]) == 1
|
|
|
|
def test_json_up_to_date(self, template_wiki_pair, capsys):
|
|
_template, wiki = template_wiki_pair
|
|
|
|
result = check_update_main(directory=str(wiki), json_output=True)
|
|
output = json.loads(capsys.readouterr().out)
|
|
|
|
assert result == 0
|
|
assert output["has_updates"] is False
|
|
assert output["files_to_update"] == []
|
|
assert output["files_to_add"] == []
|
|
assert output["files_skipped"] == []
|
|
|
|
|
|
class TestUpdateMainJsonImplemented:
|
|
"""Tests for update JSON output."""
|
|
|
|
def test_json_reports_updated_files(self, template_wiki_pair, capsys):
|
|
_template, wiki = template_wiki_pair
|
|
_write_md(wiki / "AGENTS.md", "1.0.0", body="# Agents v1\n", name="agents")
|
|
(wiki / "README.md").unlink()
|
|
|
|
result = update_main(
|
|
directory=str(wiki), yes=True, json_output=True
|
|
)
|
|
output = json.loads(capsys.readouterr().out)
|
|
|
|
assert result == 0
|
|
assert output["files_updated"] == []
|
|
assert len(output["files_added"]) == 1
|
|
assert output["conflicts"][0]["update_path"].endswith("AGENTS-update.md")
|
|
assert output["files_skipped"] == []
|
|
|
|
def test_human_output_reports_conflicts(self, template_wiki_pair, capsys):
|
|
"""Test the success line counts conflicts and names housekeeping."""
|
|
_template, wiki = template_wiki_pair
|
|
_write_md(wiki / "AGENTS.md", "1.0.0", body="# Agents v1\n", name="agents")
|
|
|
|
assert update_main(directory=str(wiki), yes=True) == 0
|
|
|
|
out = capsys.readouterr().out
|
|
assert "Conflicts (owner copy kept): 1" in out
|
|
assert "AGENTS.md (1.0.0 -> 2.0.0) -> AGENTS-update.md" in out
|
|
assert "0 file(s) updated, 0 added, 1 conflict(s), 0 skipped." in out
|
|
assert "run fiona-assistant housekeeping" in out
|
|
|
|
|
|
class TestFormatCheckUpdateOutputSkipped:
|
|
"""Tests for skipped files in the formatted output."""
|
|
|
|
def test_skipped_files_listed(self):
|
|
result = FileComparisonResult(
|
|
file_path=Path("/test/file.md"),
|
|
is_locally_modified=True,
|
|
)
|
|
summary = UpdateSummary(files_skipped=[result])
|
|
|
|
output = format_check_update_output(summary)
|
|
|
|
assert "Files skipped" in output
|
|
assert "/test/file.md" in output
|
|
|
|
def test_up_to_date_with_skips_mentions_skips(self):
|
|
result = FileComparisonResult(
|
|
file_path=Path("/test/file.md"),
|
|
is_locally_modified=True,
|
|
)
|
|
summary = UpdateSummary(files_skipped=[result])
|
|
|
|
output = format_check_update_output(summary)
|
|
|
|
assert "Wiki is up to date" in output
|
|
assert "Files skipped" in output
|
|
|
|
|
|
# =============================================================================
|
|
# SHA-256 comparison for files without a version (SPEC 7.1.2.12)
|
|
# Generated by AI/LLM: 2026-09-30 - hash compare and short-hash report.
|
|
# =============================================================================
|
|
|
|
HEX64 = r"^[0-9a-f]{64}$"
|
|
|
|
|
|
def _sha(text: str) -> str:
|
|
"""Return the SHA-256 hex digest of UTF-8 text."""
|
|
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
|
|
|
|
|
class TestSha256Comparison:
|
|
"""Tests for hash comparison of files without a version."""
|
|
|
|
def test_date_placeholder_template_matches_init_copy(self, tmp_path):
|
|
"""A template with DATE_PLACEHOLDER matches its init copy (SPEC 7.1.2.12.1)."""
|
|
template_file = tmp_path / "template.py"
|
|
wiki_file = tmp_path / "example.py"
|
|
template_file.write_text("# created DATE_PLACEHOLDER\n", encoding="utf-8", newline="\n")
|
|
_copy_file(template_file, wiki_file)
|
|
|
|
result = compare_non_md_file(wiki_file, template_file)
|
|
|
|
assert result.needs_update is False
|
|
assert result.current_hash == result.template_hash
|
|
|
|
def test_binary_template_hashes_raw_bytes(self, tmp_path):
|
|
template_file = tmp_path / "template.bin"
|
|
wiki_file = tmp_path / "blob.bin"
|
|
template_file.write_bytes(b"\xff\xfe\x00DATE_PLACEHOLDER")
|
|
wiki_file.write_bytes(b"\xff\xfe\x00DATE_PLACEHOLDER")
|
|
|
|
result = compare_non_md_file(wiki_file, template_file)
|
|
|
|
assert result.needs_update is False
|
|
assert result.template_hash == calculate_sha256(template_file)
|
|
|
|
def test_unversioned_md_equal_is_up_to_date(self, tmp_path):
|
|
wiki_file = tmp_path / "file.md"
|
|
template_file = tmp_path / "template.md"
|
|
wiki_file.write_text("plain\n", encoding="utf-8", newline="\n")
|
|
template_file.write_text("plain\n", encoding="utf-8", newline="\n")
|
|
|
|
result = compare_md_file(wiki_file, template_file)
|
|
|
|
assert result.is_conflict is False
|
|
assert result.current_hash == _sha("plain\n")
|
|
assert result.template_hash == _sha("plain\n")
|
|
|
|
def test_unversioned_md_differs_is_conflict_with_hashes(self, tmp_path):
|
|
wiki_file = tmp_path / "file.md"
|
|
template_file = tmp_path / "template.md"
|
|
wiki_file.write_text("mine\n", encoding="utf-8", newline="\n")
|
|
template_file.write_text("theirs\n", encoding="utf-8", newline="\n")
|
|
|
|
result = compare_md_file(wiki_file, template_file)
|
|
|
|
assert result.is_conflict is True
|
|
assert result.current_hash == _sha("mine\n")
|
|
assert result.template_hash == _sha("theirs\n")
|
|
|
|
def test_versioned_md_has_no_hashes(self, tmp_path):
|
|
wiki_file = tmp_path / "file.md"
|
|
template_file = tmp_path / "template.md"
|
|
_write_md(wiki_file, "1.0.0")
|
|
_write_md(template_file, "2.0.0")
|
|
|
|
result = compare_md_file(wiki_file, template_file)
|
|
|
|
assert result.current_hash is None
|
|
assert result.template_hash is None
|
|
|
|
|
|
class TestSha256Report:
|
|
"""Tests for the short-hash detail in the update report (SPEC 7.1.2.12.2)."""
|
|
|
|
def test_update_line_shows_short_hashes(self):
|
|
result = FileComparisonResult(
|
|
file_path=Path("utils/scripts/example.py"),
|
|
current_hash="1a2b3c4d" + "0" * 56,
|
|
template_hash="9f8e7d6c" + "0" * 56,
|
|
needs_update=True,
|
|
)
|
|
output = format_check_update_output(UpdateSummary(files_to_update=[result]))
|
|
|
|
assert "example.py (sha256 1a2b3c4d -> 9f8e7d6c)" in output
|
|
assert "0" * 56 not in output
|
|
|
|
def test_conflict_line_shows_short_hashes(self):
|
|
result = FileComparisonResult(
|
|
file_path=Path("notes.md"),
|
|
current_hash="aaaaaaaa" + "1" * 56,
|
|
template_hash="bbbbbbbb" + "1" * 56,
|
|
is_conflict=True,
|
|
update_path=Path("notes-update.md"),
|
|
)
|
|
output = format_check_update_output(UpdateSummary(conflicts=[result]))
|
|
|
|
assert "notes.md (sha256 aaaaaaaa -> bbbbbbbb) -> notes-update.md" in output
|
|
|
|
def test_version_line_keeps_versions(self):
|
|
result = FileComparisonResult(
|
|
file_path=Path("AGENTS.md"),
|
|
current_version="1.0.0",
|
|
template_version="2.0.0",
|
|
is_conflict=True,
|
|
update_path=Path("AGENTS-update.md"),
|
|
)
|
|
output = format_check_update_output(UpdateSummary(conflicts=[result]))
|
|
|
|
assert "AGENTS.md (1.0.0 -> 2.0.0) -> AGENTS-update.md" in output
|
|
assert "sha256" not in output
|
|
|
|
def test_drifted_script_listed_with_hashes(self, template_wiki_pair, capsys):
|
|
template, wiki = template_wiki_pair
|
|
script = Path("utils") / "scripts" / "example.py"
|
|
(template / script).parent.mkdir(parents=True, exist_ok=True)
|
|
(template / script).write_text("print('new')\n", encoding="utf-8", newline="\n")
|
|
(wiki / script).parent.mkdir(parents=True, exist_ok=True)
|
|
(wiki / script).write_text("print('old')\n", encoding="utf-8", newline="\n")
|
|
|
|
assert check_update_main(directory=str(wiki)) == 0
|
|
|
|
out = capsys.readouterr().out
|
|
short_cur = _sha("print('old')\n")[:8]
|
|
short_tmpl = _sha("print('new')\n")[:8]
|
|
assert f"(sha256 {short_cur} -> {short_tmpl})" in out
|
|
|
|
def test_json_carries_full_hashes(self, template_wiki_pair, capsys):
|
|
template, wiki = template_wiki_pair
|
|
script = Path("utils") / "scripts" / "example.py"
|
|
(template / script).parent.mkdir(parents=True, exist_ok=True)
|
|
(template / script).write_text("print('new')\n", encoding="utf-8", newline="\n")
|
|
(wiki / script).parent.mkdir(parents=True, exist_ok=True)
|
|
(wiki / script).write_text("print('old')\n", encoding="utf-8", newline="\n")
|
|
_write_md(wiki / "AGENTS.md", "1.0.0", body="# Agents v1\n", name="agents")
|
|
|
|
assert check_update_main(directory=str(wiki), json_output=True) == 0
|
|
output = json.loads(capsys.readouterr().out)
|
|
|
|
entry = output["files_to_update"][0]
|
|
assert re.match(HEX64, entry["current_sha256"])
|
|
assert entry["template_sha256"] == _sha("print('new')\n")
|
|
conflict = output["conflicts"][0]
|
|
assert conflict["current_sha256"] is None
|
|
assert conflict["template_sha256"] is None
|