"""Tests for Python Ruff module.""" import json import os import pathlib import tempfile from unittest.mock import MagicMock, patch import pytest from fiona.python_ruff.python_ruff import PythonRuff, main class TestPythonRuff: """Tests for PythonRuff class.""" @pytest.fixture def pyruff(self): """Fixture that provides a PythonRuff instance.""" return PythonRuff() def test_lint_detects_unused_import(self, pyruff, tmp_path): """Test lint detects unused import.""" test_file = tmp_path / "bad_code.py" test_file.write_text("import sys\n\ndef hello():\n print('world')\n") violations = pyruff.lint(str(test_file)) assert len(violations) > 0 first_violation = violations[0] assert first_violation["code"] == "I001" assert "Import block is un-sorted or un-formatted" in first_violation["message"] assert first_violation["location"]["row"] == 1 def test_lint_clean_file(self, pyruff, tmp_path): """Test lint returns list for clean file.""" clean_file = tmp_path / "clean_code.py" clean_file.write_text("def hello():\n print('world')\n") violations = pyruff.lint(str(clean_file)) assert isinstance(violations, list) def test_lint_with_fix(self, pyruff, tmp_path): """Test lint with fix option.""" test_file = tmp_path / "test.py" test_file.write_text("import os\nimport sys\n\ndef hello():\n print('world')\n") violations = pyruff.lint(str(test_file), fix=False) assert isinstance(violations, list) def test_compress_violations(self, pyruff): """Test compress_violations method.""" violations = [ { "filename": "/path/to/file.py", "location": {"row": 1, "column": 10}, "code": "F401", "message": "`os` imported but unused" }, { "filename": "/path/to/file.py", "location": {"row": 2, "column": 15}, "code": "F401", "message": "`sys` imported but unused" } ] target = pathlib.Path("/path/to") result = pyruff.compress_violations(violations, target) assert isinstance(result, dict) assert "files" in result assert "file.py" in result["files"] assert len(result["files"]["file.py"]) == 2 def test_compress_violations_with_string(self, pyruff): """Test compress_violations with string input.""" violations_json = '[{"filename": "/path/to/file.py", "location": {"row": 1, "column": 10}, "code": "F401", "message": "test"}]' target = pathlib.Path("/path/to") result = pyruff.compress_violations(violations_json, target) assert isinstance(result, dict) assert "files" in result assert "file.py" in result["files"] def test_format_violations(self, pyruff): """Test format_violations method.""" compressed = { "files": { "file.py": ["1:10 F401"] }, "descriptions": { "F401": {"rule_name": "F401", "description": "`os` imported but unused"} }, "meta": {"file_count": 1, "total_violations": 1, "target": "/path/to"} } result = pyruff.format_violations(compressed, target="/path/to") assert isinstance(result, str) assert "Ruff Violations" in result assert "F401" in result assert "imported but unused" in result or "unused import" in result assert "SUMMARY:" in result def test_format_violations_empty(self, pyruff): """Test format_violations with empty input.""" compressed = { "files": {}, "descriptions": {}, "meta": {"file_count": 0, "total_violations": 0} } result = pyruff.format_violations(compressed, target="/path/to") assert "Ruff Violations" in result assert "No violations found" in result def test_lint_file(self, pyruff, tmp_path): """Test lint_file method.""" test_file = tmp_path / "test.py" test_file.write_text("import os\n") violations = pyruff.lint_file(str(test_file)) assert isinstance(violations, list) # Should detect unused import assert len(violations) >= 0 # May have violations or not depending on ruff version def test_check_ruff(self, pyruff, tmp_path): """Test check_ruff method.""" test_file = tmp_path / "test.py" test_file.write_text("def hello():\n print('world')\n") result = pyruff.check_ruff(str(tmp_path)) assert isinstance(result, str) assert "Ruff Violations" in result def test_check_ruff_with_violations(self, pyruff, tmp_path): """Test check_ruff with file that has violations.""" test_file = tmp_path / "test.py" test_file.write_text("import os\nimport sys\n\ndef hello():\n print('world')\n") result = pyruff.check_ruff(str(tmp_path)) assert isinstance(result, str) assert "Ruff Violations" in result or "F401" in result or "I001" in result class TestPythonRuffMain: """Tests for python_ruff.main() function.""" def test_main_default(self, capsys): """Test main() with default arguments.""" with tempfile.TemporaryDirectory() as temp_dir: test_file = os.path.join(temp_dir, "test.py") with open(test_file, 'w') as f: f.write("def hello():\n print('world')\n") with patch('sys.argv', ['python-ruff']): main() captured = capsys.readouterr() assert "Ruff Violations" in captured.out def test_main_with_directory(self, capsys): """Test main() with directory argument.""" with tempfile.TemporaryDirectory() as temp_dir: test_file = os.path.join(temp_dir, "test.py") with open(test_file, 'w') as f: f.write("def hello():\n print('world')\n") with patch('sys.argv', ['python-ruff', 'chklint', temp_dir]): main() captured = capsys.readouterr() assert "Ruff Violations" in captured.out def test_main_invalid_directory(self, capsys): """Test main() with invalid directory.""" with patch('sys.argv', ['python-ruff', 'chklint', '/nonexistent/directory']): main() captured = capsys.readouterr() assert captured.out is not None or captured.err is not None class TestPythonRuffEdgeCases: """Tests for PythonRuff edge branches.""" def test_lint_with_fix_passes_flag(self, pyruff): """Test lint(fix=True) passes --fix to the ruff binary.""" with patch('fiona.python_ruff.python_ruff.subprocess.run') as mock_run: mock_run.return_value = MagicMock(returncode=0, stdout="[]", stderr="") pyruff.lint("src", fix=True) assert "--fix" in mock_run.call_args[0][0] def test_lint_non_list_json_returns_empty(self, pyruff): """Test lint returns [] when ruff emits a non-list JSON payload.""" with patch('fiona.python_ruff.python_ruff.subprocess.run') as mock_run: mock_run.return_value = MagicMock( returncode=0, stdout='{"violations": []}', stderr="" ) assert pyruff.lint("src") == [] def test_compress_violations_accepts_json_string(self, pyruff): """Test compress_violations parses a raw JSON string input.""" raw = json.dumps([{ "code": "F401", "filename": "/repo/src/mod.py", "location": {"row": 1, "column": 8}, "message": "unused import", }]) compressed = pyruff.compress_violations(raw, "/repo/src") assert "files" in compressed assert "mod.py" in compressed["files"] # The violations are stored as strings in the new format assert "1:8 F401" in compressed["files"]["mod.py"] def test_compress_violations_file_outside_target(self, pyruff, tmp_path): """Test compress_violations keeps the absolute path for outside files.""" outside = tmp_path / "elsewhere.py" compressed = pyruff.compress_violations([{ "code": "F401", "filename": str(outside), "location": {"row": 3, "column": 1}, "message": "unused import", }], "/repo/src") assert "files" in compressed assert outside.as_posix() in compressed["files"] def test_format_violations_empty(self, pyruff): """Test format_violations reports no violations for an empty dict.""" compressed = { "files": {}, "descriptions": {}, "meta": {"file_count": 0, "total_violations": 0} } output = pyruff.format_violations(compressed, target="src") assert "No violations found." in output