Files

937 lines
33 KiB
Python

"""Tests for the Python Custom Linter module."""
import json
import os
import pathlib
import sys
import tempfile
import pytest
from fiona.customlinter.base import CustomLintError
from fiona.customlinter.pycustomlint import (
READONLY_ZONES,
VIOLATION_CODES,
InlineImportVisitor,
LintViolation,
PythonCustomLinter,
main,
)
# =============================================================================
# Fixtures
# =============================================================================
@pytest.fixture
def temp_py_file(tmp_path):
"""Create a temporary Python file."""
def _create(content: str, name: str = "test.py"):
file_path = tmp_path / name
file_path.write_text(content, encoding="utf-8")
return file_path
return _create
@pytest.fixture
def linter():
"""Create a PythonCustomLinter instance."""
return PythonCustomLinter()
# =============================================================================
# Test InlineImportVisitor - Simple: indented imports are violations
# =============================================================================
class TestInlineImportVisitor:
"""Tests for the AST visitor that detects indented imports."""
def test_no_inline_imports(self, temp_py_file):
"""Test that a file with only module-level imports has no violations."""
content = """import os
import sys
from pathlib import Path
def foo():
pass
"""
filepath = temp_py_file(content)
tree = __import__('ast').parse(content, filename=str(filepath))
visitor = InlineImportVisitor(str(filepath))
visitor.visit(tree)
assert visitor.get_violations() == []
def test_inline_import_in_function(self, temp_py_file):
"""Test detection of import indented in function."""
content = """def foo():
import os
"""
filepath = temp_py_file(content)
tree = __import__('ast').parse(content, filename=str(filepath))
visitor = InlineImportVisitor(str(filepath))
visitor.visit(tree)
violations = visitor.get_violations()
assert len(violations) == 1
assert violations[0].code == "PYC001"
def test_inline_import_from_in_function(self, temp_py_file):
"""Test detection of 'from ... import' indented in function."""
content = """def foo():
from pathlib import Path
"""
filepath = temp_py_file(content)
tree = __import__('ast').parse(content, filename=str(filepath))
visitor = InlineImportVisitor(str(filepath))
visitor.visit(tree)
violations = visitor.get_violations()
assert len(violations) == 1
assert violations[0].code == "PYC001"
def test_inline_import_in_class(self, temp_py_file):
"""Test detection of import indented in class."""
content = """class MyClass:
import os
"""
filepath = temp_py_file(content)
tree = __import__('ast').parse(content, filename=str(filepath))
visitor = InlineImportVisitor(str(filepath))
visitor.visit(tree)
violations = visitor.get_violations()
assert len(violations) == 1
assert violations[0].code == "PYC001"
def test_inline_import_in_if_block(self, temp_py_file):
"""An if that follows a function is still an inline import."""
content = """def open_log():
pass
if True:
import os
"""
filepath = temp_py_file(content)
tree = __import__('ast').parse(content, filename=str(filepath))
visitor = InlineImportVisitor(str(filepath))
visitor.visit(tree)
violations = visitor.get_violations()
assert len(violations) == 1
assert violations[0].code == "PYC001"
def test_os_if_else_before_first_function_is_allowed(self, temp_py_file):
"""A module-level OS if/else before any function may import (SPEC 6.4.2)."""
content = """import os
import sys
if os.name == "nt":
import msvcrt
elif sys.platform == "darwin":
import ctypes
else:
import json
def open_log():
pass
"""
filepath = temp_py_file(content)
tree = __import__('ast').parse(content, filename=str(filepath))
visitor = InlineImportVisitor(str(filepath))
visitor.visit(tree)
assert visitor.get_violations() == []
def test_os_if_after_function_names_the_import(self, temp_py_file):
"""The same OS if after a function is PYC001 and names the import."""
content = """def open_log():
pass
if os.name == "nt":
import msvcrt
"""
filepath = temp_py_file(content)
tree = __import__('ast').parse(content, filename=str(filepath))
visitor = InlineImportVisitor(str(filepath))
visitor.visit(tree)
violations = visitor.get_violations()
assert len(violations) == 1
assert violations[0].code == "PYC001"
assert "import msvcrt" in violations[0].message
def test_try_import_before_first_function_is_inline(self, temp_py_file):
"""A try before the first function does not get the OS if/else exception."""
content = """try:
import os
except ImportError:
pass
"""
filepath = temp_py_file(content)
tree = __import__('ast').parse(content, filename=str(filepath))
visitor = InlineImportVisitor(str(filepath))
visitor.visit(tree)
violations = visitor.get_violations()
assert len(violations) == 1
assert violations[0].code == "PYC001"
def test_module_level_imports_allowed(self, temp_py_file):
"""Test that module-level (not indented) imports are not flagged."""
content = """import os
import sys
from pathlib import Path
import json
def foo():
pass
"""
filepath = temp_py_file(content)
tree = __import__('ast').parse(content, filename=str(filepath))
visitor = InlineImportVisitor(str(filepath))
visitor.visit(tree)
violations = visitor.get_violations()
assert len(violations) == 0
# =============================================================================
# Test late module declarations (SPEC 6.4.3)
# =============================================================================
class TestLateDeclaration:
"""Module-level assignments belong before the first function or class."""
def test_assignment_before_function_is_clean(self, linter, temp_py_file):
"""A constant above the first function is not PYC003."""
content = """SHORT_HASH_LENGTH = 8
def shorten(value):
return value[:SHORT_HASH_LENGTH]
"""
assert linter.lint_file(temp_py_file(content)) == []
def test_assignment_after_function_names_the_statement(self, linter, temp_py_file):
"""SHORT_HASH_LENGTH after a function is PYC003 and names that line."""
content = """def shorten(value):
return value
SHORT_HASH_LENGTH = 8
"""
violations = linter.lint_file(temp_py_file(content))
assert len(violations) == 1
assert violations[0].code == "PYC003"
assert violations[0].line == 4
assert "SHORT_HASH_LENGTH = 8" in violations[0].message
def test_assignment_after_class_is_pyc003(self, linter, temp_py_file):
"""A module assignment after a class is PYC003."""
content = """class Bucket:
pass
VALUE = 1
"""
violations = linter.lint_file(temp_py_file(content))
assert len(violations) == 1
assert violations[0].code == "PYC003"
assert "VALUE = 1" in violations[0].message
def test_only_the_late_assignment_is_reported(self, linter, temp_py_file):
"""A constant above the first function stays clean when a later one is not."""
content = """VALUE = 1
def first():
pass
OTHER = 2
"""
violations = linter.lint_file(temp_py_file(content))
assert len(violations) == 1
assert "OTHER = 2" in violations[0].message
def test_assignment_inside_function_is_clean(self, linter, temp_py_file):
"""A name bound inside a function is not a module declaration."""
content = """def open_log():
value = 1
return value
"""
assert linter.lint_file(temp_py_file(content)) == []
def test_assignment_inside_class_is_clean(self, linter, temp_py_file):
"""A class attribute is not a module declaration."""
content = """class Bucket:
VALUE = 1
"""
assert linter.lint_file(temp_py_file(content)) == []
def test_annotated_assignment_after_function_is_pyc003(self, linter, temp_py_file):
"""An annotated module assignment after a function is PYC003."""
content = """def open_log():
pass
count: int = 1
"""
violations = linter.lint_file(temp_py_file(content))
assert len(violations) == 1
assert violations[0].code == "PYC003"
assert "count: int = 1" in violations[0].message
def test_if_assignment_before_function_is_clean(self, linter, temp_py_file):
"""A module-level if before any function may assign (SPEC 6.4.3)."""
content = """import os
if os.name == "nt":
VALUE = 1
else:
VALUE = 2
def open_log():
pass
"""
assert linter.lint_file(temp_py_file(content)) == []
def test_if_assignment_after_function_is_pyc003(self, linter, temp_py_file):
"""The same if after a function is PYC003."""
content = """def open_log():
pass
if os.name == "nt":
VALUE = 1
"""
violations = linter.lint_file(temp_py_file(content))
assert len(violations) == 1
assert violations[0].code == "PYC003"
assert "VALUE = 1" in violations[0].message
def test_file_with_only_assignments_is_clean(self, linter, temp_py_file):
"""Without a function or class, module assignments are at the top."""
content = """VALUE = 1
count: int = 2
"""
assert linter.lint_file(temp_py_file(content)) == []
# =============================================================================
# Test PythonCustomLinter
# =============================================================================
class TestPythonCustomLinter:
"""Tests for the PythonCustomLinter class."""
def test_lint_file_no_violations(self, linter, temp_py_file):
"""Test linting a file with no import violations."""
content = """import os
import sys
def foo():
pass
"""
filepath = temp_py_file(content)
violations = linter.lint_file(filepath)
assert len(violations) == 0
def test_lint_file_with_inline_import(self, linter, temp_py_file):
"""Test linting a file with inline import."""
content = """def foo():
import os
"""
filepath = temp_py_file(content)
violations = linter.lint_file(filepath)
assert len(violations) == 1
assert isinstance(violations[0], LintViolation)
assert violations[0].code == "PYC001"
def test_format_violations(self, linter):
"""Test formatting violations for display."""
violations = [
LintViolation(
filepath=pathlib.Path("/test/file1.py"),
line=10,
column=4,
code="PYC001",
message="Inline import: import os",
rule_id="inline-import"
),
]
output = linter.format_violations(violations)
assert "file1.py:10:4" in output
assert "PYC001" in output
def test_format_violations_empty(self, linter):
"""Test formatting empty violations returns empty string."""
output = linter.format_violations([])
assert output == ""
def test_format_violations_json(self, linter):
"""Test formatting violations as JSON."""
violations = [
LintViolation(
filepath=pathlib.Path("/test/file.py"),
line=10,
column=4,
code="PYC001",
message="Inline import: import os",
rule_id="inline-import"
)
]
output = linter.format_violations_json(violations)
parsed = json.loads(output)
assert len(parsed) == 1
assert parsed[0]["file"] == "/test/file.py"
assert parsed[0]["line"] == 10
assert parsed[0]["code"] == "PYC001"
# =============================================================================
# Test Violation Codes
# =============================================================================
class TestViolationCodes:
"""Tests for violation code definitions."""
def test_pyi001_code_exists(self):
"""Test that PYC001 code is defined."""
assert "PYC001" in VIOLATION_CODES
assert VIOLATION_CODES["PYC001"]["rule_name"] == "Inline Import"
def test_pyc003_code_exists(self):
"""Test that PYC003 code is defined."""
assert "PYC003" in VIOLATION_CODES
assert VIOLATION_CODES["PYC003"]["rule_name"] == "Late Declaration"
# =============================================================================
# Test Read-only Zones
# =============================================================================
class TestReadonlyZones:
"""Tests for read-only zone configuration."""
def test_personal_is_readonly(self):
"""Test that personal directory is in read-only zones."""
assert "personal" in READONLY_ZONES
def test_raw_is_readonly(self):
"""Test that raw directory is in read-only zones."""
assert "raw" in READONLY_ZONES
# =============================================================================
# Test LintViolation
# =============================================================================
class TestLintViolation:
"""Tests for the LintViolation class."""
def test_violation_to_dict(self):
"""Test converting violation to dictionary."""
violation = LintViolation(
filepath=pathlib.Path("/test/file.py"),
line=10,
column=4,
code="PYC001",
message="Inline import: import os",
rule_id="inline-import",
severity="error"
)
result = violation.to_dict()
assert result["file"] == "/test/file.py"
assert result["line"] == 10
assert result["column"] == 4
assert result["code"] == "PYC001"
def test_violation_str(self):
"""Test string representation of violation."""
violation = LintViolation(
filepath=pathlib.Path("/test/file.py"),
line=10,
column=4,
code="PYC001",
message="Inline import: import os",
rule_id="inline-import"
)
result = str(violation)
assert "/test/file.py:10:4" in result
assert "PYC001" in result
# =============================================================================
# Test CustomLintError Exception
# =============================================================================
class TestCustomLintError:
"""Tests for the CustomLintError exception class."""
def test_exception_with_message(self):
"""Test creating exception with message."""
error = CustomLintError("Test error message")
assert str(error) == "Test error message"
assert error.message == "Test error message"
assert error.filepath is None
assert error.line is None
def test_exception_with_all_args(self):
"""Test creating exception with all arguments."""
error = CustomLintError(
"Test error",
filepath=pathlib.Path("/test/file.py"),
line=10
)
assert error.message == "Test error"
assert error.filepath == pathlib.Path("/test/file.py")
assert error.line == 10
# =============================================================================
# Test Settings Loading
# =============================================================================
class TestSettingsLoading:
"""Tests for settings loading functionality."""
def test_default_settings(self, linter):
"""Test that default settings are loaded."""
assert linter._settings == {}
def test_lint_directory_with_subdirs(self, linter, tmp_path):
"""Test linting a directory with subdirectories."""
# Create a subdirectory
subdir = tmp_path / "subdir"
subdir.mkdir()
# Create a file with inline import in subdirectory
bad_file = subdir / "bad.py"
bad_file.write_text("def foo():\n import os\n", encoding="utf-8")
violations = linter.lint_directory(tmp_path)
assert len(violations) == 1
def test_lint_file_with_path_string(self, linter, temp_py_file):
"""Test linting with a string path instead of Path object."""
content = """def foo():
import os
"""
filepath = temp_py_file(content)
violations = linter.lint_file(str(filepath)) # Pass as string
assert len(violations) == 1
def test_lint_nonexistent_file(self, linter):
"""Test linting a non-existent file returns empty list."""
violations = linter.lint_file(pathlib.Path("/nonexistent/file.py"))
assert violations == []
def test_collect_python_files_skips_non_py(self, linter, tmp_path):
"""Test that non-Python files are skipped."""
# Create a non-Python file
non_py_file = tmp_path / "not_python.txt"
non_py_file.write_text("not python", encoding="utf-8")
# Create a Python file
py_file = tmp_path / "test.py"
py_file.write_text("import os\n", encoding="utf-8")
py_files = linter._collect_python_files(tmp_path)
assert len(py_files) == 1
assert py_files[0].name == "test.py"
def test_collect_python_files_skips_pycache(self, linter, tmp_path):
"""Test that __pycache__ directories are skipped."""
# Create a __pycache__ directory
pycache_dir = tmp_path / "__pycache__"
pycache_dir.mkdir()
# Create a Python file in __pycache__
cached_file = pycache_dir / "module.pyc"
cached_file.write_text("compiled", encoding="utf-8")
# Create a normal Python file
py_file = tmp_path / "test.py"
py_file.write_text("import os\n", encoding="utf-8")
py_files = linter._collect_python_files(tmp_path)
# Should only find test.py, not the .pyc file
assert len(py_files) == 1
assert py_files[0].name == "test.py"
# =============================================================================
# Test Edge Cases
# =============================================================================
class TestEdgeCases:
"""Tests for edge cases in custom linter."""
def test_lint_directory_nonexistent(self, linter):
"""Test linting a non-existent directory raises error."""
with pytest.raises(CustomLintError) as exc_info:
linter.lint_directory("/nonexistent/directory")
assert "does not exist" in str(exc_info.value)
def test_skip_personal_directory(self, linter, tmp_path):
"""Test that files in personal directory are skipped."""
# Create a personal directory
personal_dir = tmp_path / "personal"
personal_dir.mkdir()
# Create a file with inline import in personal directory
bad_file = personal_dir / "bad.py"
bad_file.write_text("def foo():\n import os\n", encoding="utf-8")
violations = linter.lint_directory(tmp_path)
# Should not find any violations because personal/ is skipped
assert len(violations) == 0
def test_skip_raw_directory(self, linter, tmp_path):
"""Test that files in raw directory are skipped."""
# Create a raw directory
raw_dir = tmp_path / "raw"
raw_dir.mkdir()
# Create a file with inline import in raw directory
bad_file = raw_dir / "bad.py"
bad_file.write_text("def foo():\n import os\n", encoding="utf-8")
violations = linter.lint_directory(tmp_path)
# Should not find any violations because raw/ is skipped
assert len(violations) == 0
def test_matches_pattern(self, linter):
"""Test the pattern matching functionality."""
# Test exact match
assert linter._matches_pattern("test.py", ["test.py"]) is True
assert linter._matches_pattern("test.py", ["other.py"]) is False
# Test wildcard
assert linter._matches_pattern("test.py", ["*.py"]) is True
assert linter._matches_pattern("test.txt", ["*.py"]) is False
# Test directory pattern
assert linter._matches_pattern("test.py", ["build/"]) is False
def test_should_skip_with_string_path(self, linter):
"""Test _should_skip with string path."""
result = linter._should_skip("/path/to/personal/file.py")
assert result is True
result = linter._should_skip("/path/to/raw/file.py")
assert result is True
result = linter._should_skip("/path/to/src/file.py")
assert result is False
def test_lint_file_with_syntax_error(self, linter, tmp_path):
"""Test linting a file with syntax errors returns empty list."""
# Create a file with syntax error
bad_file = tmp_path / "syntax_error.py"
bad_file.write_text("def foo(", encoding="utf-8")
violations = linter.lint_file(bad_file)
# Should return empty list for syntax errors
assert violations == []
def test_lint_file_with_oserror(self, linter):
"""Test linting a non-existent file returns empty list."""
violations = linter.lint_file("/nonexistent/file.py")
assert violations == []
def test_load_settings_with_custom_file(self, linter, tmp_path):
"""Test loading settings from a custom file."""
# Create a custom settings file
settings_file = tmp_path / "custom_settings.json"
settings_file.write_text("""{
"python": {
"custom_lint": {
"ignore_patterns": ["test_*"],
"some_setting": "value"
}
}
}""", encoding="utf-8")
# Create a linter with custom settings
custom_linter = PythonCustomLinter(settings_file=settings_file)
# Check that settings were loaded
assert custom_linter._settings == {"ignore_patterns": ["test_*"], "some_setting": "value"}
def test_format_violations_multiple(self, linter):
"""Test formatting multiple violations."""
violations = [
LintViolation(
filepath=pathlib.Path("/test/file1.py"),
line=10,
column=4,
code="PYC001",
message="Inline import: import os",
rule_id="inline-import"
),
LintViolation(
filepath=pathlib.Path("/test/file2.py"),
line=5,
column=8,
code="PYC001",
message="Inline import: from sys import path",
rule_id="inline-import"
),
]
output = linter.format_violations(violations)
# Should contain both files
assert "file1.py" in output
assert "file2.py" in output
# Should be sorted by file, line, column
lines = output.strip().split("\n")
assert len(lines) == 2
def test_format_violations_json_multiple(self, linter):
"""Test formatting multiple violations as JSON."""
violations = [
LintViolation(
filepath=pathlib.Path("/test/file1.py"),
line=10,
column=4,
code="PYC001",
message="Inline import: import os",
rule_id="inline-import"
),
LintViolation(
filepath=pathlib.Path("/test/file2.py"),
line=5,
column=8,
code="PYC001",
message="Inline import: from sys import path",
rule_id="inline-import"
),
]
output = linter.format_violations_json(violations)
parsed = json.loads(output)
assert len(parsed) == 2
# Sorted by (file, line, column) - file1.py < file2.py alphabetically
assert parsed[0]["file"] == "/test/file1.py"
assert parsed[1]["file"] == "/test/file2.py"
# =============================================================================
# Test CLI Integration
# =============================================================================
class TestCliIntegration:
"""Tests for CLI integration of the custom linter."""
def test_cli_chklint_file(self, tmp_path, capsys):
"""Test CLI chklint with a file containing inline import."""
# Create a file with inline import
bad_file = tmp_path / "bad.py"
bad_file.write_text("def foo():\n import os\n", encoding="utf-8")
# Run the CLI
sys.argv = ["pycustomlint", "chklint", str(bad_file)]
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 1
captured = capsys.readouterr()
assert "PYC001" in captured.out
assert "Inline import" in captured.out
def test_cli_chklint_clean_file(self, tmp_path, capsys):
"""Test CLI chklint with a clean file."""
# Create a clean file
clean_file = tmp_path / "clean.py"
clean_file.write_text("import os\nimport sys\n\ndef foo():\n pass\n", encoding="utf-8")
# Run the CLI
sys.argv = ["pycustomlint", "chklint", str(clean_file)]
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 0
captured = capsys.readouterr()
assert "No custom lint violations found" in captured.out
def test_cli_chklint_directory(self, tmp_path, capsys):
"""Test CLI chklint with a directory."""
# Create a file with inline import
bad_file = tmp_path / "bad.py"
bad_file.write_text("def foo():\n import os\n", encoding="utf-8")
# Run the CLI with directory
sys.argv = ["pycustomlint", "chklint", str(tmp_path)]
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 1
captured = capsys.readouterr()
assert "PYC001" in captured.out
def test_cli_invalid_path(self, capsys):
"""Test CLI with invalid path."""
sys.argv = ["pycustomlint", "chklint", "/nonexistent/path"]
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 1
captured = capsys.readouterr()
assert "does not exist" in captured.err
def test_cli_json_output(self, tmp_path, capsys):
"""Test CLI with JSON output."""
# Create a file with inline import
bad_file = tmp_path / "bad.py"
bad_file.write_text("def foo():\n import os\n", encoding="utf-8")
# Run the CLI with --json flag
sys.argv = ["pycustomlint", "chklint", str(bad_file), "--json"]
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 1
captured = capsys.readouterr()
# Should output JSON
output = captured.out.strip()
assert output # Should have output
parsed = json.loads(output) # Parse the entire JSON output
assert len(parsed) == 1
assert parsed[0]["code"] == "PYC001"
assert "PYC001" in output
def test_cli_chklint_nonexistent_directory(self, capsys):
"""Test CLI chklint with non-existent directory."""
sys.argv = ["pycustomlint", "chklint", "/nonexistent/directory"]
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 1
captured = capsys.readouterr()
assert "does not exist" in captured.err
def test_cli_no_subcommand_default(self, capsys):
"""Test CLI with no subcommand defaults to chklint."""
# Create a temp directory with a clean file
with tempfile.TemporaryDirectory() as tmp_path:
clean_file = pathlib.Path(tmp_path) / "clean.py"
clean_file.write_text("import os\n", encoding="utf-8")
old_cwd = os.getcwd()
os.chdir(tmp_path)
old_argv = sys.argv
try:
sys.argv = ["pycustomlint"]
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 0
captured = capsys.readouterr()
assert "No custom lint violations found" in captured.out
finally:
sys.argv = old_argv
os.chdir(old_cwd)
def test_cli_help(self, capsys):
"""Test CLI with help or invalid subcommand shows help."""
old_argv = sys.argv
try:
sys.argv = ["pycustomlint", "invalid"]
with pytest.raises(SystemExit) as exc_info:
main()
# argparse returns exit code 2 for invalid subcommand
assert exc_info.value.code == 2
captured = capsys.readouterr()
# Should show help/error message
assert "usage" in captured.err or "error" in captured.err
finally:
sys.argv = old_argv
def test_gitignore_loading(self, linter, tmp_path):
"""Test that .gitignore is loaded and respected."""
# Create a .gitignore file
gitignore_file = tmp_path / ".gitignore"
gitignore_file.write_text("*.pyc\n__pycache__/\n", encoding="utf-8")
# Create a Python file
py_file = tmp_path / "test.py"
py_file.write_text("import os\n", encoding="utf-8")
# Create a .pyc file
pyc_file = tmp_path / "test.pyc"
pyc_file.write_text("compiled\n", encoding="utf-8")
py_files = linter._collect_python_files(tmp_path)
# Should only find test.py, not test.pyc
assert len(py_files) == 1
assert py_files[0].name == "test.py"
def test_matches_pattern_directory(self, linter):
"""Test directory pattern matching."""
# Test directory pattern with trailing slash
assert linter._matches_pattern("build/lib/test.py", ["build/"]) is True
assert linter._matches_pattern("src/test.py", ["build/"]) is False
def test_should_skip_with_settings_ignore(self, linter, tmp_path):
"""Test _should_skip with settings ignore patterns."""
# Create a custom settings file with ignore patterns
settings_file = tmp_path / "settings.json"
settings_file.write_text("""{
"python": {
"custom_lint": {
"ignore_patterns": ["*test_*", "*/temp/*"]
}
}
}""", encoding="utf-8")
custom_linter = PythonCustomLinter(settings_file=settings_file)
# Test that files matching patterns are skipped
result = custom_linter._should_skip(pathlib.Path("/path/to/test_ignore.py"))
assert result is True
result = custom_linter._should_skip(pathlib.Path("/path/to/src/file.py"))
assert result is False
def test_lint_file_with_string_path(self, linter, temp_py_file):
"""Test lint_file with string path (exercises path conversion)."""
content = """import os
import sys
def foo():
pass
"""
filepath = temp_py_file(content)
# Pass as string to test the path conversion branch
violations = linter.lint_file(str(filepath))
assert len(violations) == 0
def test_add_violation_exception_handling(self, linter, temp_py_file, mocker):
"""Test that exception in _add_inline_import_violation is handled gracefully."""
# Create a file with inline import
content = """def foo():
import os
"""
filepath = temp_py_file(content)
# Mock open to raise an exception
mocker.patch('builtins.open', side_effect=OSError("test error"))
# This should still work without crashing, just with default "import" message
violations = linter.lint_file(filepath)
assert len(violations) == 1
assert "Inline import" in violations[0].message
def test_cli_with_file_arg(self, tmp_path, capsys):
"""Test CLI chklint with a single file argument."""
# Create a clean file
clean_file = tmp_path / "clean.py"
clean_file.write_text("import os\nimport sys\n", encoding="utf-8")
# Run the CLI with file path
sys.argv = ["pycustomlint", "chklint", str(clean_file)]
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 0
captured = capsys.readouterr()
assert "No custom lint violations found" in captured.out