Files
fiona-assistant/tests/test_customlinter_base.py
T
2026-09-29 16:01:16 +02:00

1024 lines
37 KiB
Python

"""Tests for the Custom Linter Base module.
This module tests the base classes and utilities that all custom linters
inherit from.
"""
from __future__ import annotations
import json
import pathlib
from typing import ClassVar
import pytest
from fiona.customlinter.base import (
DEFAULT_SETTINGS_FILE,
READONLY_ZONES,
BaseLinter,
CustomLintError,
FrontmatterLintError,
LinterError,
LintViolation,
)
# =============================================================================
# Fixtures
# =============================================================================
@pytest.fixture
def temp_file(tmp_path):
"""Create a temporary file."""
def _create(content: str = "", name: str = "test.txt"):
file_path = tmp_path / name
file_path.write_text(content, encoding="utf-8")
return file_path
return _create
@pytest.fixture
def temp_dir(tmp_path):
"""Create a temporary directory with files."""
def _create(files: dict[str, str]):
for name, content in files.items():
(tmp_path / name).write_text(content, encoding="utf-8")
return tmp_path
return _create
# =============================================================================
# Test LintViolation class
# =============================================================================
class TestLintViolation:
"""Tests for the LintViolation class."""
def test_lint_violation_creation(self):
"""Test creating a LintViolation with all fields."""
violation = LintViolation(
filepath=pathlib.Path("/test/file.py"),
line=10,
column=5,
code="TEST001",
message="Test message",
rule_id="test-rule",
severity="error"
)
assert violation.filepath == pathlib.Path("/test/file.py")
assert violation.line == 10
assert violation.column == 5
assert violation.code == "TEST001"
assert violation.message == "Test message"
assert violation.rule_id == "test-rule"
assert violation.severity == "error"
def test_lint_violation_to_dict(self):
"""Test converting LintViolation to dictionary."""
violation = LintViolation(
filepath=pathlib.Path("/test/file.py"),
line=10,
column=5,
code="TEST001",
message="Test message",
rule_id="test-rule",
severity="warning"
)
result = violation.to_dict()
assert result["file"] == "/test/file.py"
assert result["line"] == 10
assert result["column"] == 5
assert result["code"] == "TEST001"
assert result["message"] == "Test message"
assert result["rule"] == "test-rule"
assert result["severity"] == "warning"
def test_lint_violation_str(self):
"""Test string representation of LintViolation."""
violation = LintViolation(
filepath=pathlib.Path("/test/file.py"),
line=10,
column=5,
code="TEST001",
message="Test message",
rule_id="test-rule"
)
result = str(violation)
assert "/test/file.py:10:5 TEST001 Test message" == result
def test_lint_violation_default_severity(self):
"""Test LintViolation has default severity of 'error'."""
violation = LintViolation(
filepath=pathlib.Path("/test/file.py"),
line=1,
column=1,
code="TEST001",
message="Test",
rule_id="test"
)
assert violation.severity == "error"
# =============================================================================
# Test Exception classes
# =============================================================================
class TestExceptions:
"""Tests for exception classes."""
def test_linter_error_basic(self):
"""Test LinterError with basic message."""
error = LinterError("Test error")
assert str(error) == "Test error"
assert error.message == "Test error"
assert error.filepath is None
assert error.line is None
def test_linter_error_with_filepath(self):
"""Test LinterError with filepath."""
error = LinterError("Test error", filepath=pathlib.Path("/test/file.py"))
assert error.filepath == pathlib.Path("/test/file.py")
def test_linter_error_with_line(self):
"""Test LinterError with line number."""
error = LinterError("Test error", line=42)
assert error.line == 42
def test_linter_error_with_all_args(self):
"""Test LinterError with all arguments."""
error = LinterError(
"Test error",
filepath=pathlib.Path("/test/file.py"),
line=42
)
assert str(error) == "Test error"
assert error.filepath == pathlib.Path("/test/file.py")
assert error.line == 42
def test_custom_lint_error_inheritance(self):
"""Test CustomLintError inherits from LinterError."""
error = CustomLintError("Custom error")
assert isinstance(error, LinterError)
def test_frontmatter_lint_error_inheritance(self):
"""Test FrontmatterLintError inherits from LinterError."""
error = FrontmatterLintError("Frontmatter error")
assert isinstance(error, LinterError)
# =============================================================================
# Test Constants
# =============================================================================
class TestConstants:
"""Tests for module constants."""
def test_readonly_zones(self):
"""Test READONLY_ZONES constant."""
assert "personal" in READONLY_ZONES
assert "raw" in READONLY_ZONES
def test_default_settings_file(self):
"""Test DEFAULT_SETTINGS_FILE is a Path."""
assert isinstance(DEFAULT_SETTINGS_FILE, pathlib.Path)
# =============================================================================
# Test BaseLinter class - basic functionality
# =============================================================================
class TestBaseLinterBasics:
"""Tests for BaseLinter basic functionality."""
def test_base_linter_is_abstract(self):
"""Test that BaseLinter cannot be instantiated directly."""
with pytest.raises(TypeError):
BaseLinter()
def test_base_linter_has_required_class_attrs(self):
"""Test that BaseLinter has required class attributes."""
assert hasattr(BaseLinter, "VIOLATION_CODES")
assert hasattr(BaseLinter, "file_extensions")
assert hasattr(BaseLinter, "settings_key_path")
def test_get_violation_message_found(self):
"""Test get_violation_message with existing code."""
# Create a concrete subclass for testing
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {
"TEST001": {
"rule_name": "Test Rule",
"description": "Test description",
"message_template": "TEST001 - {error}",
"severity": "error"
}
}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
result = linter.get_violation_message("TEST001", error="test error")
assert result == "TEST001 - test error"
def test_get_violation_message_not_found(self):
"""Test get_violation_message with non-existing code."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
result = linter.get_violation_message("UNKNOWN001")
assert "UNKNOWN001" in result
def test_get_violation_message_missing_template_args(self):
"""Test get_violation_message with missing template args."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {
"TEST001": {
"rule_name": "Test Rule",
"description": "Test description",
"message_template": "TEST001 - {missing_key}",
"severity": "error"
}
}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
# Should handle KeyError gracefully
result = linter.get_violation_message("TEST001")
assert "TEST001" in result
# =============================================================================
# Test BaseLinter._matches_pattern
# =============================================================================
class TestMatchesPattern:
"""Tests for _matches_pattern method."""
def test_matches_pattern_exact_match(self):
"""Test matching exact pattern."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
assert linter._matches_pattern("test.py", ["test.py"]) is True
assert linter._matches_pattern("test.py", ["other.py"]) is False
def test_matches_pattern_wildcard(self):
"""Test matching with wildcard patterns."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
assert linter._matches_pattern("test.py", ["*.py"]) is True
assert linter._matches_pattern("test.txt", ["*.py"]) is False
def test_matches_pattern_directory(self):
"""Test matching directory patterns."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
assert linter._matches_pattern("test", ["test/"]) is True
assert linter._matches_pattern("other", ["test/"]) is False
def test_matches_pattern_empty_patterns(self):
"""Test with empty pattern list."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
assert linter._matches_pattern("test.py", []) is False
# =============================================================================
# Test BaseLinter._should_skip
# =============================================================================
class TestShouldSkip:
"""Tests for _should_skip method."""
def test_should_skip_readonly_zone(self):
"""Test skipping files in read-only zones."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
# Create a path that includes a read-only zone
filepath = pathlib.Path("/some/path/personal/test.py")
assert linter._should_skip(filepath) is True
def test_should_skip_raw_zone(self):
"""Test skipping files in raw zone."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
filepath = pathlib.Path("/some/path/raw/test.py")
assert linter._should_skip(filepath) is True
def test_should_skip_not_in_readonly_zone(self):
"""Test not skipping files outside read-only zones."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
filepath = pathlib.Path("/some/path/src/test.py")
assert linter._should_skip(filepath) is False
def test_should_skip_with_string_path(self):
"""Test _should_skip with string path."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
filepath = "/some/path/personal/test.py"
assert linter._should_skip(filepath) is True
# =============================================================================
# Test BaseLinter._load_settings
# =============================================================================
class TestLoadSettings:
"""Tests for _load_settings method."""
def test_load_settings_nonexistent_file(self):
"""Test loading settings from non-existent file."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter(settings_file=pathlib.Path("/nonexistent/file.json"))
settings = linter._settings
assert settings == {}
def test_load_settings_valid_file(self, temp_file):
"""Test loading settings from valid file."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test", "custom"]
def lint_file(self, filepath):
return []
# Create a temporary settings file
settings_content = {
"test": {
"custom": {
"ignore_patterns": ["*.tmp"]
}
}
}
settings_path = temp_file(json.dumps(settings_content), "settings.json")
linter = TestLinter(settings_file=settings_path)
settings = linter._settings
assert settings.get("ignore_patterns") == ["*.tmp"]
def test_load_settings_malformed_json(self, temp_file):
"""Test loading settings from malformed JSON file."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
settings_path = temp_file("not valid json", "settings.json")
linter = TestLinter(settings_file=settings_path)
settings = linter._settings
assert settings == {}
# =============================================================================
# Test BaseLinter._collect_files
# =============================================================================
class TestCollectFiles:
"""Tests for _collect_files method."""
def test_collect_files_empty_directory(self, temp_dir):
"""Test collecting files from empty directory."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
directory = temp_dir({})
files = linter._collect_files(directory)
assert files == []
def test_collect_files_with_matching_files(self, temp_dir):
"""Test collecting files with matching extensions."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
directory = temp_dir({
"file1.txt": "content1",
"file2.txt": "content2",
"file3.py": "content3"
})
files = linter._collect_files(directory)
file_names = [f.name for f in files]
assert "file1.txt" in file_names
assert "file2.txt" in file_names
assert "file3.py" not in file_names
def test_collect_files_respects_gitignore(self, temp_dir):
"""Test that _collect_files respects .gitignore."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt", ".py"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
directory = temp_dir({
".gitignore": "*.tmp\n",
"file1.txt": "content1",
"file2.tmp": "content2",
"file3.py": "content3"
})
files = linter._collect_files(directory)
file_names = [f.name for f in files]
assert "file1.txt" in file_names
assert "file2.tmp" not in file_names
assert "file3.py" in file_names
def test_collect_files_skips_readonly_zones(self, tmp_path):
"""Test that _collect_files skips read-only zones."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
# Create directory structure with read-only zone
directory = tmp_path
# Create the subdirectories
(directory / "personal").mkdir(exist_ok=True)
(directory / "raw").mkdir(exist_ok=True)
(directory / "src").mkdir(exist_ok=True)
# Create files in proper locations
(directory / "personal" / "test.txt").write_text("content1")
(directory / "raw" / "test.txt").write_text("content2")
(directory / "src" / "test.txt").write_text("content3")
files = linter._collect_files(directory)
file_paths = [str(f) for f in files]
# Should not include files in personal or raw directories
assert not any("personal" in p for p in file_paths)
assert not any("raw" in p for p in file_paths)
# Should include file in src
assert any("src" in p for p in file_paths)
def test_collect_files_nested_directories(self, tmp_path):
"""Test collecting files from nested directories."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
directory = tmp_path
# Create nested structure
(directory / "subdir1").mkdir(exist_ok=True)
(directory / "subdir1" / "subdir2").mkdir(exist_ok=True)
(directory / "subdir1" / "file.txt").write_text("content1")
(directory / "subdir1" / "subdir2" / "file.txt").write_text("content2")
files = linter._collect_files(directory)
assert len(files) == 2
# =============================================================================
# Test BaseLinter format methods
# =============================================================================
class TestFormatMethods:
"""Tests for formatting methods."""
def test_format_violations_empty(self):
"""Test format_violations with empty list."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
result = linter.format_violations([])
assert result == ""
def test_format_violations_single(self):
"""Test format_violations with single violation."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
violation = LintViolation(
filepath=pathlib.Path("/test/file.txt"),
line=10,
column=5,
code="TEST001",
message="Test message",
rule_id="test-rule"
)
result = linter.format_violations([violation])
assert "/test/file.txt:10:5 TEST001 Test message" in result
def test_format_violations_multiple(self):
"""Test format_violations with multiple violations."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
violations = [
LintViolation(
filepath=pathlib.Path("/test/file1.txt"),
line=10,
column=5,
code="TEST001",
message="Message 1",
rule_id="rule1"
),
LintViolation(
filepath=pathlib.Path("/test/file2.txt"),
line=20,
column=10,
code="TEST002",
message="Message 2",
rule_id="rule2"
)
]
result = linter.format_violations(violations)
assert "file1.txt:10:5 TEST001 Message 1" in result
assert "file2.txt:20:10 TEST002 Message 2" in result
def test_format_violations_json_empty(self):
"""Test format_violations_json with empty list."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
result = linter.format_violations_json([])
assert result == "[]"
def test_format_violations_json_single(self):
"""Test format_violations_json with single violation."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
violation = LintViolation(
filepath=pathlib.Path("/test/file.txt"),
line=10,
column=5,
code="TEST001",
message="Test message",
rule_id="test-rule"
)
result = linter.format_violations_json([violation])
parsed = json.loads(result)
assert len(parsed) == 1
assert parsed[0]["code"] == "TEST001"
assert parsed[0]["message"] == "Test message"
def test_format_violations_report_empty(self):
"""Test format_violations_report with empty list."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {
"TEST001": {
"rule_name": "Test Rule",
"description": "Test description"
}
}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
result = linter.format_violations_report([], "/test", "Test Linter")
assert "Test Linter Violations" in result
assert "TARGET: /test" in result
assert "No violations found" in result
def test_format_violations_report_with_violations(self):
"""Test format_violations_report with violations."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {
"TEST001": {
"rule_name": "Test Rule",
"description": "Test description"
}
}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
violation = LintViolation(
filepath=pathlib.Path("/test/file.txt"),
line=10,
column=5,
code="TEST001",
message="Test message",
rule_id="test-rule"
)
result = linter.format_violations_report(
[violation], "/test", "Test Linter"
)
assert "Test Linter Violations" in result
assert "TARGET: /test" in result
assert "TEST001" in result
assert "Test message" in result
assert "Total violations: 1" in result
# =============================================================================
# Test compressed violations format methods
# =============================================================================
class TestCompressedFormatMethods:
"""Tests for compress_violations and format_compressed_violations."""
def _make_linter(self, linter_name: str | None = None):
"""Create a concrete linter for testing compressed formatting."""
class_attributes = {
"VIOLATION_CODES": {
"TEST001": {
"rule_name": "Test Rule",
"description": "Test description",
"message_template": "TEST001",
}
},
"file_extensions": [".txt"],
"settings_key_path": ["test"],
"lint_file": lambda self, filepath: [],
}
if linter_name is not None:
class_attributes["linter_name"] = linter_name
TestLinter = type("TestLinter", (BaseLinter,), class_attributes)
return TestLinter()
def _make_violation(self, filepath, code="TEST001", message="TEST001"):
"""Create a LintViolation for testing."""
return LintViolation(
filepath=pathlib.Path(filepath),
line=1,
column=1,
code=code,
message=message,
rule_id="test-rule",
)
def test_compress_violations_builds_structure(self, tmp_path):
"""Test compress_violations groups violations by file with meta counts."""
linter = self._make_linter()
file_a = tmp_path / "a.txt"
file_b = tmp_path / "b.txt"
violations = [
self._make_violation(file_a),
self._make_violation(file_a),
self._make_violation(file_b),
]
result = linter.compress_violations(violations, tmp_path)
assert result["files"] == {
"a.txt": ["TEST001", "TEST001"],
"b.txt": ["TEST001"],
}
assert result["descriptions"]["TEST001"] == {
"rule_name": "Test Rule",
"description": "Test description",
}
assert result["meta"]["file_count"] == 2
assert result["meta"]["total_violations"] == 3
assert result["meta"]["target"] == tmp_path.resolve().as_posix()
def test_compress_violations_empty(self, tmp_path):
"""Test compress_violations with no violations."""
linter = self._make_linter()
result = linter.compress_violations([], tmp_path)
assert result["files"] == {}
assert result["descriptions"] == {}
assert result["meta"]["file_count"] == 0
assert result["meta"]["total_violations"] == 0
def test_compress_violations_outside_target_uses_full_path(self, tmp_path):
"""Test compress_violations keeps full path for files outside target."""
linter = self._make_linter()
violation = self._make_violation("/elsewhere/file.txt")
result = linter.compress_violations([violation], tmp_path)
assert "/elsewhere/file.txt" in result["files"]
def test_compress_violations_unknown_code_description(self, tmp_path):
"""Test compress_violations falls back to code for unknown codes."""
linter = self._make_linter()
violation = self._make_violation(
tmp_path / "a.txt", code="UNKNOWN", message="Unknown violation"
)
result = linter.compress_violations([violation], tmp_path)
assert result["descriptions"]["UNKNOWN"] == {
"rule_name": "UNKNOWN",
"description": "",
}
def test_format_compressed_violations_structure(self, tmp_path):
"""Test format_compressed_violations produces the shared report."""
linter = self._make_linter(linter_name="Test Linter")
compressed = linter.compress_violations(
[self._make_violation(tmp_path / "a.txt")], tmp_path
)
result = linter.format_compressed_violations(compressed)
lines = result.splitlines()
assert lines[0] == "Test Linter Violations"
assert lines[1] == f"TARGET: {tmp_path.resolve().as_posix()}"
assert "- DEFINITIONS:" in lines
assert " - TEST001: Test Rule, Test description" in lines
assert "- FILE: a.txt" in lines
assert " - TEST001" in lines
assert "- SUMMARY:" in lines
assert " - Total files with violations: 1" in lines
assert " - Total violations: 1" in lines
def test_format_compressed_violations_no_violations(self):
"""Test format_compressed_violations with empty results."""
linter = self._make_linter(linter_name="Test Linter")
compressed = {
"files": {},
"descriptions": {},
"meta": {"file_count": 0, "total_violations": 0, "target": "x"},
}
result = linter.format_compressed_violations(compressed)
assert "Test Linter Violations" in result
assert "- No violations found." in result
def test_format_compressed_violations_default_linter_name(self):
"""Test format_compressed_violations falls back to default name."""
linter = self._make_linter()
compressed = {
"files": {},
"descriptions": {},
"meta": {"file_count": 0, "total_violations": 0, "target": "x"},
}
result = linter.format_compressed_violations(compressed)
assert result.splitlines()[0] == "Lint Violations"
# =============================================================================
# Test lint_directory method
# =============================================================================
class TestLintDirectory:
"""Tests for lint_directory method."""
def test_lint_directory_with_violations(self, temp_dir):
"""Test lint_directory finds violations."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {
"TEST001": {
"rule_name": "Test Rule",
"description": "Test description",
"message_template": "TEST001",
"severity": "error"
}
}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
# Return a violation for every file
return [
LintViolation(
filepath=filepath,
line=1,
column=1,
code="TEST001",
message="Test violation",
rule_id="test-rule"
)
]
linter = TestLinter()
directory = temp_dir({"file1.txt": "content1", "file2.txt": "content2"})
violations = linter.lint_directory(directory)
assert len(violations) == 2
assert all(v.code == "TEST001" for v in violations)
def test_lint_directory_no_violations(self, temp_dir):
"""Test lint_directory with no violations."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
directory = temp_dir({"file1.txt": "content1"})
violations = linter.lint_directory(directory)
assert violations == []
def test_lint_directory_nonexistent_directory(self, tmp_path):
"""Test lint_directory with non-existent directory."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
nonexistent = tmp_path / "nonexistent"
with pytest.raises(LinterError):
linter.lint_directory(nonexistent)
# =============================================================================
# Test _load_settings edge cases
# =============================================================================
class TestLoadSettingsEdgeCases:
"""Tests for edge cases in _load_settings method."""
def test_load_settings_non_dict_in_path(self, temp_file):
"""Test _load_settings when value in path is not a dict."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test", "custom"]
def lint_file(self, filepath):
return []
# Create a settings file where test.custom is a string, not a dict
settings_content = {"test": {"custom": "not a dict"}}
settings_path = temp_file(json.dumps(settings_content), "settings.json")
linter = TestLinter(settings_file=settings_path)
settings = linter._settings
assert settings == {}
# =============================================================================
# Test _collect_files OSError handling
# =============================================================================
class TestCollectFilesOSError:
"""Tests for OSError handling in _collect_files method."""
def test_collect_files_oserror_on_gitignore_read(self, temp_dir, mocker):
"""Test _collect_files handles OSError when reading .gitignore."""
class TestLinter(BaseLinter):
VIOLATION_CODES: ClassVar[dict] = {}
file_extensions: ClassVar[list[str]] = [".txt"]
settings_key_path: ClassVar[list[str]] = ["test"]
def lint_file(self, filepath):
return []
linter = TestLinter()
directory = temp_dir({".gitignore": "*.tmp\n", "file1.txt": "content1"})
# Mock open to raise OSError when reading .gitignore
# We need to mock it in a way that only affects the .gitignore read
# Since .gitignore exists, the code will try to open it
original_open = open
def mock_open(path, *args, **kwargs):
if ".gitignore" in str(path):
raise OSError("Cannot read")
return original_open(path, *args, **kwargs)
mocker.patch("builtins.open", side_effect=mock_open)
# This should not raise, just return empty list or handle gracefully
files = linter._collect_files(directory)
# The behavior depends on implementation - it might return [] or handle the error
# Just ensure it doesn't crash
assert isinstance(files, list)