526 lines
20 KiB
Python
526 lines
20 KiB
Python
"""Tests for the fiona.__main__ CLI entry point."""
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
from unittest.mock import patch
|
|
|
|
import pytest
|
|
|
|
from fiona import logging_config
|
|
from fiona.__main__ import main
|
|
from fiona.librarian import toc_generator
|
|
|
|
|
|
@pytest.fixture
|
|
def hermetic_toc_settings(tmp_path, monkeypatch):
|
|
"""Pin the packaged-settings fallback for deterministic file TOCs."""
|
|
settings_file = tmp_path / "hermetic-settings.json"
|
|
settings_file.write_text(
|
|
json.dumps({"toc_generator": {"file": {"sectionize": False}}}),
|
|
encoding="utf-8",
|
|
)
|
|
monkeypatch.setattr(toc_generator, "DEFAULT_SETTINGS_FILE", settings_file)
|
|
return settings_file
|
|
|
|
|
|
class TestFionaMain:
|
|
"""Tests for fiona.__main__.main() function."""
|
|
|
|
def test_main_no_command(self, capsys):
|
|
"""Test main() with no command (default behavior)."""
|
|
with patch('sys.argv', ['fiona-assistant']):
|
|
with pytest.raises(SystemExit) as exc_info:
|
|
main()
|
|
|
|
assert exc_info.value.code == 0
|
|
|
|
captured = capsys.readouterr()
|
|
output = captured.out + captured.err
|
|
assert "usage" in output.lower()
|
|
|
|
|
|
def test_main_librarian_default_directory(self, capsys, monkeypatch, tmp_path):
|
|
"""Test main() with librarian command and default directory."""
|
|
|
|
# Isolate from the packaged fiona.log file logging: this test
|
|
# counts the files in the working directory.
|
|
monkeypatch.setattr(
|
|
logging_config, "DEFAULT_SETTINGS_FILE", tmp_path / "missing-settings.json"
|
|
)
|
|
with tempfile.TemporaryDirectory() as temp_dir:
|
|
original_dir = os.getcwd()
|
|
os.chdir(temp_dir)
|
|
|
|
# Create a test file
|
|
with open("test.txt", 'w') as f:
|
|
f.write("content")
|
|
|
|
try:
|
|
with patch('sys.argv', ['fiona-assistant', 'librarian', 'list']):
|
|
main()
|
|
|
|
captured = capsys.readouterr()
|
|
assert "Found 1 files" in captured.out
|
|
finally:
|
|
os.chdir(original_dir)
|
|
|
|
|
|
def test_main_unknown_command(self, capsys):
|
|
"""Test main() with an unknown command."""
|
|
with patch('sys.argv', ['fiona-assistant', 'unknown']):
|
|
with pytest.raises(SystemExit) as exc_info:
|
|
main()
|
|
|
|
# argparse exits with code 2 for unrecognized arguments
|
|
assert exc_info.value.code == 2
|
|
captured = capsys.readouterr()
|
|
# Should print help or error message (in stderr)
|
|
output = captured.out + captured.err
|
|
assert "usage" in output.lower() or "error" in output.lower()
|
|
|
|
def test_main_help_flag(self, capsys):
|
|
"""Test main() with --help flag."""
|
|
with patch('sys.argv', ['fiona-assistant', '--help']):
|
|
with pytest.raises(SystemExit) as exc_info:
|
|
main()
|
|
|
|
# Help should exit with code 0
|
|
assert exc_info.value.code == 0
|
|
captured = capsys.readouterr()
|
|
assert "usage" in captured.out.lower()
|
|
|
|
def test_main_mdoctor_default(self, capsys):
|
|
"""Test main() with mdoctor command and default arguments."""
|
|
with tempfile.TemporaryDirectory() as temp_dir:
|
|
original_dir = os.getcwd()
|
|
os.chdir(temp_dir)
|
|
|
|
# Create a test markdown file
|
|
with open("test.md", 'w') as f:
|
|
f.write("# Test\n")
|
|
|
|
try:
|
|
with patch('sys.argv', ['fiona-assistant', 'mdoctor']):
|
|
main()
|
|
|
|
captured = capsys.readouterr()
|
|
# mdoctor chklint should run and output something
|
|
assert "PyMarkdownLint" in captured.out or "test.md" in captured.out
|
|
finally:
|
|
os.chdir(original_dir)
|
|
|
|
def test_main_mdoctor_with_args(self, capsys):
|
|
"""Test main() with mdoctor command and custom args."""
|
|
with tempfile.TemporaryDirectory() as temp_dir:
|
|
original_dir = os.getcwd()
|
|
os.chdir(temp_dir)
|
|
|
|
# Create a test markdown file
|
|
with open("test.md", 'w') as f:
|
|
f.write("# Test\n")
|
|
|
|
try:
|
|
with patch('sys.argv', ['fiona-assistant', 'mdoctor', 'chklint', temp_dir]):
|
|
main()
|
|
|
|
captured = capsys.readouterr()
|
|
assert "test.md" in captured.out or "PyMarkdownLint" in captured.out
|
|
finally:
|
|
os.chdir(original_dir)
|
|
|
|
def test_main_mdoctor_fix(self, capsys):
|
|
"""Test main() dispatches mdoctor fix and auto-fixes the target."""
|
|
with tempfile.TemporaryDirectory() as temp_dir:
|
|
# Create a test markdown file with an auto-fixable violation
|
|
test_file = os.path.join(temp_dir, "test.md")
|
|
with open(test_file, 'w') as f:
|
|
f.write("# Test\n\nContent without trailing newline")
|
|
|
|
with patch('sys.argv', ['fiona-assistant', 'mdoctor', 'fix', temp_dir]):
|
|
main()
|
|
|
|
captured = capsys.readouterr()
|
|
assert "1 file(s) fixed" in captured.out
|
|
assert "test.md" in captured.out
|
|
with open(test_file, encoding="utf-8") as f:
|
|
assert f.read() == "# Test\n\nContent without trailing newline\n"
|
|
|
|
def test_main_librarian_default(self, capsys):
|
|
"""Test main() with librarian command and no subcommand lists cwd."""
|
|
with tempfile.TemporaryDirectory() as temp_dir:
|
|
original_dir = os.getcwd()
|
|
os.chdir(temp_dir)
|
|
|
|
try:
|
|
with open("sample.md", 'w') as f:
|
|
f.write("# Sample\n")
|
|
|
|
with patch('sys.argv', ['fiona-assistant', 'librarian']):
|
|
main()
|
|
|
|
captured = capsys.readouterr()
|
|
assert "Found" in captured.out
|
|
assert "sample.md" in captured.out
|
|
finally:
|
|
os.chdir(original_dir)
|
|
|
|
def test_main_wiki_init(self, capsys, tmp_path):
|
|
"""Test main() dispatches wiki init and prints the result."""
|
|
with patch('sys.argv', ['fiona-assistant', 'wiki', 'init', str(tmp_path)]):
|
|
main()
|
|
|
|
captured = capsys.readouterr()
|
|
assert "Successfully initialized llm-wiki directory" in captured.out
|
|
|
|
def test_main_wiki_sanity(self, capsys, minimal_wiki):
|
|
"""Test main() dispatches wiki sanity and exits 0 on clean wiki."""
|
|
with patch('sys.argv', ['fiona-assistant', 'wiki', 'sanity', str(minimal_wiki)]), \
|
|
pytest.raises(SystemExit) as exc_info:
|
|
main()
|
|
|
|
assert exc_info.value.code == 0
|
|
captured = capsys.readouterr()
|
|
assert "SANITY PASSED" in captured.out
|
|
assert re.search(r"mdlinter:\s+PASS", captured.out)
|
|
|
|
def test_main_wiki_sanity_dead_link_fails(self, capsys, minimal_wiki):
|
|
"""Test main() wiki sanity exits 1 when a dead link exists."""
|
|
page = minimal_wiki / "wiki" / "concepts" / "broken.md"
|
|
page.write_text(
|
|
"---\nname: broken\nversion: 1.0.0\n---\n\n# Broken\n\n"
|
|
"See [gone](../gone.md).\n",
|
|
encoding="utf-8",
|
|
)
|
|
|
|
with patch('sys.argv', ['fiona-assistant', 'wiki', 'sanity', str(minimal_wiki)]), \
|
|
pytest.raises(SystemExit) as exc_info:
|
|
main()
|
|
|
|
assert exc_info.value.code == 1
|
|
captured = capsys.readouterr()
|
|
assert re.search(r"mdlinter:\s+FAIL", captured.out)
|
|
assert "Sanity Failed" in captured.out
|
|
|
|
def test_main_wiki_sanity_non_interactive_flag(self, capsys, minimal_wiki):
|
|
"""Test main() wiki sanity accepts --non-interactive and exits 0."""
|
|
argv = ['fiona-assistant', 'wiki', 'sanity',
|
|
'--non-interactive', str(minimal_wiki)]
|
|
with patch('sys.argv', argv), \
|
|
pytest.raises(SystemExit) as exc_info:
|
|
main()
|
|
|
|
assert exc_info.value.code == 0
|
|
captured = capsys.readouterr()
|
|
assert "SANITY PASSED" in captured.out
|
|
# Non-interactive output carries no ANSI cursor codes (SPEC 7.16.2)
|
|
assert "\x1b[" not in captured.out
|
|
|
|
def test_main_wiki_sanity_passes_non_interactive(self, minimal_wiki):
|
|
"""Test main() forwards the --non-interactive flag to sanity_main."""
|
|
argv = ['fiona-assistant', 'wiki', 'sanity',
|
|
'--non-interactive', str(minimal_wiki)]
|
|
with patch('fiona.__main__.sanity_main', return_value=0) as mock_main, \
|
|
patch('sys.argv', argv), \
|
|
pytest.raises(SystemExit):
|
|
main()
|
|
|
|
assert mock_main.call_args.kwargs["non_interactive"] is True
|
|
|
|
def test_main_wiki_without_subcommand_shows_help(self, capsys):
|
|
"""Test main() with wiki command and no subcommand shows help."""
|
|
with patch('sys.argv', ['fiona-assistant', 'wiki']), \
|
|
pytest.raises(SystemExit) as exc_info:
|
|
main()
|
|
|
|
assert exc_info.value.code == 1
|
|
captured = capsys.readouterr()
|
|
assert "usage" in captured.out
|
|
|
|
def test_main_python_ruff_default(self, capsys):
|
|
"""Test main() with python-ruff command and default arguments."""
|
|
with tempfile.TemporaryDirectory() as temp_dir:
|
|
original_dir = os.getcwd()
|
|
os.chdir(temp_dir)
|
|
|
|
# Create a test python file
|
|
with open("test.py", 'w') as f:
|
|
f.write("x = 1\n")
|
|
|
|
try:
|
|
with patch('sys.argv', ['fiona-assistant', 'python-ruff']):
|
|
main()
|
|
|
|
captured = capsys.readouterr()
|
|
# Should output something about Ruff
|
|
assert "Ruff" in captured.out or "test.py" in captured.out
|
|
finally:
|
|
os.chdir(original_dir)
|
|
|
|
def test_main_python_ruff_with_args(self, capsys):
|
|
"""Test main() with python-ruff command and custom args."""
|
|
with tempfile.TemporaryDirectory() as temp_dir:
|
|
original_dir = os.getcwd()
|
|
os.chdir(temp_dir)
|
|
|
|
# Create a test python file
|
|
with open("test.py", 'w') as f:
|
|
f.write("x = 1\n")
|
|
|
|
try:
|
|
with patch('sys.argv', ['fiona-assistant', 'python-ruff', 'chklint', temp_dir]):
|
|
main()
|
|
|
|
captured = capsys.readouterr()
|
|
assert "Ruff" in captured.out or "test.py" in captured.out
|
|
finally:
|
|
os.chdir(original_dir)
|
|
|
|
def test_main_librarian_with_directory(self, capsys):
|
|
"""Test main() with librarian command and specific directory."""
|
|
with tempfile.TemporaryDirectory() as temp_dir:
|
|
original_dir = os.getcwd()
|
|
|
|
# Create a test file in temp_dir
|
|
with open(os.path.join(temp_dir, "test.txt"), 'w') as f:
|
|
f.write("content")
|
|
|
|
try:
|
|
with patch('sys.argv', ['fiona-assistant', 'librarian', 'list', temp_dir]):
|
|
main()
|
|
|
|
captured = capsys.readouterr()
|
|
assert "Found 1 files" in captured.out
|
|
finally:
|
|
os.chdir(original_dir)
|
|
|
|
def test_main_test_command(self, capsys):
|
|
"""Test main() with an unknown command exits via argparse, not a crash."""
|
|
with patch('sys.argv', ['fiona-assistant', 'test']):
|
|
with pytest.raises(SystemExit) as exc_info:
|
|
main()
|
|
|
|
# argparse rejects unknown subcommands with exit code 2
|
|
assert exc_info.value.code == 2
|
|
|
|
def test_main_no_command_shows_help(self, capsys):
|
|
"""Test that main() with no command shows help message."""
|
|
with patch('sys.argv', ['fiona-assistant']):
|
|
with pytest.raises(SystemExit) as exc_info:
|
|
main()
|
|
|
|
# Should exit with code 0 (help) or 2 (error from argparse)
|
|
assert exc_info.value.code in (0, 2)
|
|
|
|
captured = capsys.readouterr()
|
|
# Should show help text with usage
|
|
output = captured.out + captured.err
|
|
assert "usage" in output.lower()
|
|
|
|
def test_main_no_args(self, capsys):
|
|
"""Test main() with no arguments."""
|
|
with patch('sys.argv', ['fiona-assistant']):
|
|
with pytest.raises(SystemExit) as exc_info:
|
|
main()
|
|
|
|
assert exc_info.value.code == 0
|
|
|
|
captured = capsys.readouterr()
|
|
output = captured.out + captured.err
|
|
assert "usage" in output.lower()
|
|
|
|
def test_main_librarian_toc_generates_toc_file(self, capsys):
|
|
"""Test that 'fiona-assistant librarian toc <dir>' generates a TOC file."""
|
|
with tempfile.TemporaryDirectory() as temp_dir:
|
|
temp_path = pathlib.Path(temp_dir)
|
|
|
|
# Create markdown files with headers
|
|
(temp_path / "file1.md").write_text("# File 1\n## Section 1\n")
|
|
(temp_path / "file2.md").write_text("# File 2\n")
|
|
|
|
subdir = temp_path / "subdir"
|
|
subdir.mkdir()
|
|
(subdir / "file3.md").write_text("# File 3\n## Section 3\n")
|
|
|
|
original_dir = os.getcwd()
|
|
try:
|
|
with patch('sys.argv', ['fiona-assistant', 'librarian', 'toc', str(temp_path)]):
|
|
main()
|
|
|
|
# Check that table_of_contents.md was created
|
|
toc_file = temp_path / "table_of_contents.md"
|
|
assert toc_file.exists(), "TOC file should be created"
|
|
|
|
# Check TOC content
|
|
toc_content = toc_file.read_text()
|
|
assert "# Table of Contents" in toc_content
|
|
assert "file1.md" in toc_content
|
|
assert "file2.md" in toc_content
|
|
assert "subdir" in toc_content
|
|
assert "file3.md" in toc_content
|
|
assert "File 1" in toc_content
|
|
assert "Section 1" in toc_content
|
|
finally:
|
|
os.chdir(original_dir)
|
|
|
|
def test_main_librarian_toc_default_directory(self, capsys):
|
|
"""Test that 'fiona-assistant librarian toc' generates TOC in current directory."""
|
|
with tempfile.TemporaryDirectory() as temp_dir:
|
|
original_dir = os.getcwd()
|
|
os.chdir(temp_dir)
|
|
|
|
temp_path = pathlib.Path(temp_dir)
|
|
|
|
# Create markdown files with headers
|
|
(temp_path / "file1.md").write_text("# File 1\n## Section 1\n")
|
|
(temp_path / "file2.md").write_text("# File 2\n")
|
|
|
|
try:
|
|
with patch('sys.argv', ['fiona-assistant', 'librarian', 'toc']):
|
|
main()
|
|
|
|
# Check that table_of_contents.md was created in current directory
|
|
toc_file = temp_path / "table_of_contents.md"
|
|
assert toc_file.exists(), "TOC file should be created in current directory"
|
|
|
|
# Check TOC content
|
|
toc_content = toc_file.read_text()
|
|
assert "# Table of Contents" in toc_content
|
|
assert "file1.md" in toc_content
|
|
assert "file2.md" in toc_content
|
|
finally:
|
|
os.chdir(original_dir)
|
|
|
|
def test_main_fmlint_default(self, capsys):
|
|
"""Test main() with fmlint command and default arguments."""
|
|
with tempfile.TemporaryDirectory() as temp_dir:
|
|
# Create test markdown files with absolute paths
|
|
valid_file = os.path.join(temp_dir, "valid.md")
|
|
with open(valid_file, 'w') as f:
|
|
f.write("---\nname: Test\nversion: 1.0.0\n---\n# Test\n")
|
|
|
|
invalid_file = os.path.join(temp_dir, "invalid.md")
|
|
with open(invalid_file, 'w') as f:
|
|
f.write("# Invalid\n")
|
|
|
|
# Test with the temp_dir as the target
|
|
with patch('sys.argv', ['fiona-assistant', 'fmlint', 'chklint', temp_dir]):
|
|
main()
|
|
|
|
captured = capsys.readouterr()
|
|
# Should output something about Frontmatter Lint
|
|
assert "Frontmatter" in captured.out or "frontmatter" in captured.out
|
|
# Should find the invalid file
|
|
assert "invalid.md" in captured.out
|
|
|
|
def test_main_fmlint_with_directory(self, capsys):
|
|
"""Test main() with fmlint command and specific directory."""
|
|
with tempfile.TemporaryDirectory() as temp_dir:
|
|
# Create a test markdown file with missing fields
|
|
test_file = os.path.join(temp_dir, "test.md")
|
|
with open(test_file, 'w') as f:
|
|
f.write("---\ntitle: Test\n---\n# Test\n")
|
|
|
|
with patch('sys.argv', ['fiona-assistant', 'fmlint', 'chklint', temp_dir]):
|
|
main()
|
|
|
|
captured = capsys.readouterr()
|
|
assert "Frontmatter" in captured.out
|
|
assert "test.md" in captured.out
|
|
# Should report missing name and version
|
|
assert "name" in captured.out.lower() or "version" in captured.out.lower()
|
|
|
|
def test_main_fmlint_valid_files(self, capsys):
|
|
"""Test main() with fmlint command on directory with all valid files."""
|
|
with tempfile.TemporaryDirectory() as temp_dir:
|
|
# Create test markdown files with valid frontmatter
|
|
with open(os.path.join(temp_dir, "test1.md"), 'w') as f:
|
|
f.write("---\nname: Test1\nversion: 1.0.0\n---\n# Test1\n")
|
|
|
|
with open(os.path.join(temp_dir, "test2.md"), 'w') as f:
|
|
f.write("---\nname: Test2\nversion: 2.0.0\n---\n# Test2\n")
|
|
|
|
with patch('sys.argv', ['fiona-assistant', 'fmlint', 'chklint', temp_dir]):
|
|
main()
|
|
|
|
captured = capsys.readouterr()
|
|
assert "Frontmatter" in captured.out
|
|
# Should report no violations
|
|
assert "No violations found" in captured.out or "0" in captured.out
|
|
|
|
class TestFionaLibrarianTocFile:
|
|
"""Tests for 'fiona-assistant librarian toc file' dispatch (SPEC 7.15.2)."""
|
|
|
|
def test_main_librarian_toc_file_generates_per_file_toc(self, capsys, hermetic_toc_settings):
|
|
"""Test that 'librarian toc file <path>' writes a TOC inside the file."""
|
|
with tempfile.TemporaryDirectory() as temp_dir:
|
|
temp_path = pathlib.Path(temp_dir)
|
|
doc = temp_path / "doc.md"
|
|
doc.write_text("# Title\n## Section\n")
|
|
|
|
with patch('sys.argv',
|
|
['fiona-assistant', 'librarian', 'toc', 'file', str(doc)]):
|
|
main()
|
|
|
|
content = doc.read_text()
|
|
assert "<!-- toc-start: headings 2..6 -->" in content
|
|
assert "<!-- toc-end -->" in content
|
|
assert "- [Section](#section)" in content
|
|
assert "## Section" in content
|
|
|
|
out = capsys.readouterr().out
|
|
assert "wrote toc" in out
|
|
|
|
def test_main_librarian_toc_file_star_processes_tree(self, hermetic_toc_settings):
|
|
"""Test that 'librarian toc file *' writes TOCs across the tree."""
|
|
with tempfile.TemporaryDirectory() as temp_dir:
|
|
temp_path = pathlib.Path(temp_dir)
|
|
(temp_path / "a.md").write_text("# A\n## B\n")
|
|
sub = temp_path / "sub"
|
|
sub.mkdir()
|
|
(sub / "c.md").write_text("# C\n## D\n")
|
|
|
|
original_dir = os.getcwd()
|
|
os.chdir(temp_path)
|
|
try:
|
|
with patch('sys.argv',
|
|
['fiona-assistant', 'librarian', 'toc', 'file', '*']):
|
|
main()
|
|
finally:
|
|
os.chdir(original_dir)
|
|
|
|
assert "- [B](#b)" in (temp_path / "a.md").read_text()
|
|
assert "- [D](#d)" in (sub / "c.md").read_text()
|
|
|
|
def test_main_librarian_toc_file_sectionized_flag(self, hermetic_toc_settings):
|
|
"""Test that 'librarian toc file <path> --sectionized' numbers headings."""
|
|
with tempfile.TemporaryDirectory() as temp_dir:
|
|
temp_path = pathlib.Path(temp_dir)
|
|
doc = temp_path / "doc.md"
|
|
doc.write_text("# Title\n\n## Section\n")
|
|
|
|
with patch('sys.argv',
|
|
['fiona-assistant', 'librarian', 'toc', 'file',
|
|
str(doc), '--sectionized']):
|
|
main()
|
|
|
|
content = doc.read_text()
|
|
assert "## 1. Section" in content
|
|
assert "- [1. Section](#1-section)" in content
|
|
assert "<!-- toc-start: sectionized, headings 2..6 -->" in content
|
|
|
|
|
|
def test_cli_entry_imports_without_cycle():
|
|
"""Test a fresh interpreter can import the CLI."""
|
|
completed = subprocess.run(
|
|
[sys.executable, "-c", "import fiona.__main__"],
|
|
capture_output=True,
|
|
text=True,
|
|
check=False,
|
|
)
|
|
assert completed.returncode == 0, completed.stderr
|