477 lines
17 KiB
Python
477 lines
17 KiB
Python
"""Tests for Shellcheck module."""
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import tempfile
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
import pytest
|
|
|
|
from shellcheck.shellcheck import Shellcheck, main
|
|
|
|
|
|
@pytest.fixture
|
|
def shellcheck_linter():
|
|
"""Fixture that provides a Shellcheck instance."""
|
|
return Shellcheck()
|
|
|
|
|
|
class TestShellcheck:
|
|
"""Tests for Shellcheck class."""
|
|
|
|
def test_lint_file_with_violation(self, shellcheck_linter, tmp_path):
|
|
"""Test lint_file detects a known shellcheck violation."""
|
|
test_file = tmp_path / "test.sh"
|
|
test_file.write_text("#!/bin/bash\nfor file in $1; do echo $file; done\n")
|
|
|
|
mock_violation = {
|
|
"file": str(test_file),
|
|
"line": 2,
|
|
"column": 15,
|
|
"level": "warning",
|
|
"code": "SC2086",
|
|
"message": "Double quote to prevent globbing and word splitting."
|
|
}
|
|
|
|
with patch(
|
|
'shellcheck.shellcheck.shutil.which',
|
|
return_value='/usr/bin/shellcheck'
|
|
) as _, patch(
|
|
'shellcheck.shellcheck.subprocess.run'
|
|
) as mock_run:
|
|
mock_run.return_value = MagicMock(
|
|
returncode=0,
|
|
stdout=json.dumps([mock_violation]),
|
|
stderr=""
|
|
)
|
|
violations = shellcheck_linter.lint_file(str(test_file))
|
|
|
|
assert len(violations) == 1
|
|
assert violations[0].code == "SC2086"
|
|
assert violations[0].line == 2
|
|
assert violations[0].column == 15
|
|
assert violations[0].severity == "warning"
|
|
assert "SC2086" in violations[0].message
|
|
|
|
def test_lint_clean_file(self, shellcheck_linter, tmp_path):
|
|
"""Test lint_file returns empty list for clean file."""
|
|
clean_file = tmp_path / "clean.sh"
|
|
clean_file.write_text("#!/bin/bash\necho 'Hello World'\n")
|
|
|
|
with patch(
|
|
'shellcheck.shellcheck.shutil.which',
|
|
return_value='/usr/bin/shellcheck'
|
|
) as _, patch(
|
|
'shellcheck.shellcheck.subprocess.run'
|
|
) as mock_run:
|
|
mock_run.return_value = MagicMock(
|
|
returncode=0,
|
|
stdout="[]",
|
|
stderr=""
|
|
)
|
|
violations = shellcheck_linter.lint_file(str(clean_file))
|
|
|
|
assert isinstance(violations, list)
|
|
assert len(violations) == 0
|
|
|
|
def test_compress_violations(self, shellcheck_linter):
|
|
"""Test compress_violations method."""
|
|
violations = [
|
|
{
|
|
"file": "/path/to/script.sh",
|
|
"line": 1,
|
|
"column": 10,
|
|
"code": "SC2086",
|
|
"message": "Double quote to prevent globbing.",
|
|
"level": "warning"
|
|
},
|
|
{
|
|
"file": "/path/to/script.sh",
|
|
"line": 2,
|
|
"column": 15,
|
|
"code": "SC2086",
|
|
"message": "Double quote to prevent globbing."
|
|
}
|
|
]
|
|
|
|
target = pathlib.Path("/path/to")
|
|
result = shellcheck_linter.compress_violations(violations, target)
|
|
|
|
assert isinstance(result, dict)
|
|
assert "files" in result
|
|
assert "script.sh" in result["files"]
|
|
assert len(result["files"]["script.sh"]) == 2
|
|
|
|
def test_compress_violations_with_string(self, shellcheck_linter):
|
|
"""Test compress_violations with string input."""
|
|
violations_json = '[{"file": "/path/to/script.sh", "line": 1, "column": 10, "code": "SC2086", "message": "test", "level": "warning"}]'
|
|
|
|
target = pathlib.Path("/path/to")
|
|
result = shellcheck_linter.compress_violations(violations_json, target)
|
|
|
|
assert isinstance(result, dict)
|
|
assert "files" in result
|
|
assert "script.sh" in result["files"]
|
|
|
|
def test_format_violations(self, shellcheck_linter):
|
|
"""Test format_violations method."""
|
|
compressed = {
|
|
"files": {
|
|
"script.sh": ["1:10 SC2086"]
|
|
},
|
|
"descriptions": {
|
|
"SC2086": {"rule_name": "SC2086", "description": "Double quote"}
|
|
},
|
|
"meta": {"file_count": 1, "total_violations": 1, "target": "/path/to"}
|
|
}
|
|
|
|
result = shellcheck_linter.format_violations(compressed, target="/path/to")
|
|
|
|
assert isinstance(result, str)
|
|
assert "Shellcheck Violations" in result
|
|
assert "SC2086" in result
|
|
assert "SUMMARY:" in result
|
|
|
|
def test_format_violations_empty(self, shellcheck_linter):
|
|
"""Test format_violations with empty input."""
|
|
compressed = {
|
|
"files": {},
|
|
"descriptions": {},
|
|
"meta": {"file_count": 0, "total_violations": 0}
|
|
}
|
|
result = shellcheck_linter.format_violations(compressed, target="/path/to")
|
|
|
|
assert "Shellcheck Violations" in result
|
|
assert "No violations found" in result
|
|
|
|
def test_check_shellcheck(self, shellcheck_linter, tmp_path):
|
|
"""Test check_shellcheck method."""
|
|
test_file = tmp_path / "test.sh"
|
|
test_file.write_text("#!/bin/bash\necho 'Hello'\n")
|
|
|
|
with patch(
|
|
'shellcheck.shellcheck.shutil.which',
|
|
return_value='/usr/bin/shellcheck'
|
|
) as _, patch(
|
|
'shellcheck.shellcheck.subprocess.run'
|
|
) as mock_run:
|
|
mock_run.return_value = MagicMock(
|
|
returncode=0,
|
|
stdout="[]",
|
|
stderr=""
|
|
)
|
|
result = shellcheck_linter.check_shellcheck(str(tmp_path))
|
|
|
|
assert isinstance(result, str)
|
|
assert "Shellcheck Violations" in result
|
|
|
|
|
|
class TestShellcheckMain:
|
|
"""Tests for shellcheck.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.sh")
|
|
with open(test_file, 'w') as f:
|
|
f.write("#!/bin/bash\necho 'world'\n")
|
|
|
|
with patch(
|
|
'sys.argv', ['shellcheck']
|
|
), patch(
|
|
'shellcheck.shellcheck.shutil.which',
|
|
return_value='/usr/bin/shellcheck'
|
|
) as _, patch(
|
|
'shellcheck.shellcheck.subprocess.run'
|
|
) as mock_run:
|
|
mock_run.return_value = MagicMock(
|
|
returncode=0,
|
|
stdout="[]",
|
|
stderr=""
|
|
)
|
|
main()
|
|
|
|
captured = capsys.readouterr()
|
|
assert "Shellcheck 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.sh")
|
|
with open(test_file, 'w') as f:
|
|
f.write("#!/bin/bash\necho 'world'\n")
|
|
|
|
with patch(
|
|
'sys.argv', ['shellcheck', 'chklint', temp_dir]
|
|
), patch(
|
|
'shellcheck.shellcheck.shutil.which',
|
|
return_value='/usr/bin/shellcheck'
|
|
) as _, patch(
|
|
'shellcheck.shellcheck.subprocess.run'
|
|
) as mock_run:
|
|
mock_run.return_value = MagicMock(
|
|
returncode=0,
|
|
stdout="[]",
|
|
stderr=""
|
|
)
|
|
main()
|
|
|
|
captured = capsys.readouterr()
|
|
assert "Shellcheck Violations" in captured.out
|
|
|
|
|
|
class TestShellcheckBinaryNotFound:
|
|
"""Tests for shellcheck binary not found scenario."""
|
|
|
|
def test_find_shellcheck_bin_raises_error(self, shellcheck_linter):
|
|
"""Test _find_shellcheck_bin raises RuntimeError when shellcheck not found."""
|
|
with patch(
|
|
'shellcheck.shellcheck.shutil.which',
|
|
return_value=None
|
|
) as _, patch.object(
|
|
pathlib.Path, 'exists', return_value=False
|
|
):
|
|
with pytest.raises(RuntimeError) as exc_info:
|
|
shellcheck_linter._find_shellcheck_bin()
|
|
|
|
error_msg = str(exc_info.value)
|
|
assert "shellcheck is not installed" in error_msg
|
|
assert "pip install shellcheck-py" in error_msg
|
|
|
|
def test_lint_returns_error_when_binary_missing(self, shellcheck_linter, tmp_path):
|
|
"""Test lint returns SHELLCHECK_NOT_FOUND violation when binary is missing."""
|
|
test_file = tmp_path / "test.sh"
|
|
test_file.write_text("#!/bin/bash\necho 'test'\n")
|
|
|
|
with patch(
|
|
'shellcheck.shellcheck.shutil.which',
|
|
return_value=None
|
|
) as _, patch.object(
|
|
pathlib.Path, 'exists', return_value=False
|
|
):
|
|
violations = shellcheck_linter.lint(str(test_file))
|
|
|
|
assert len(violations) == 1
|
|
assert violations[0]["code"] == "SHELLCHECK_NOT_FOUND"
|
|
assert "shellcheck is not installed" in violations[0]["message"]
|
|
|
|
def test_lint_file_returns_error_when_binary_missing(self, shellcheck_linter, tmp_path):
|
|
"""Test lint_file returns SHELLCHECK_NOT_FOUND violation when binary is missing."""
|
|
test_file = tmp_path / "test.sh"
|
|
test_file.write_text("#!/bin/bash\necho 'test'\n")
|
|
|
|
with patch(
|
|
'shellcheck.shellcheck.shutil.which',
|
|
return_value=None
|
|
) as _, patch.object(
|
|
pathlib.Path, 'exists', return_value=False
|
|
):
|
|
violations = shellcheck_linter.lint_file(str(test_file))
|
|
|
|
assert len(violations) == 1
|
|
assert violations[0].code == "SHELLCHECK_NOT_FOUND"
|
|
assert "shellcheck is not installed" in violations[0].message
|
|
|
|
def test_missing_binary_produces_clear_message(self, tmp_path):
|
|
"""Test that missing binary produces a clear install-hint message."""
|
|
test_file = tmp_path / "test.sh"
|
|
test_file.write_text("#!/bin/bash\necho 'test'\n")
|
|
|
|
shellcheck_linter = Shellcheck()
|
|
|
|
with patch(
|
|
'shellcheck.shellcheck.shutil.which',
|
|
return_value=None
|
|
) as _, patch.object(
|
|
pathlib.Path, 'exists', return_value=False
|
|
):
|
|
violations = shellcheck_linter.lint_file(str(test_file))
|
|
compressed = shellcheck_linter.compress_violations(violations, str(tmp_path))
|
|
formatted = shellcheck_linter.format_compressed_violations(compressed)
|
|
|
|
assert "SHELLCHECK_NOT_FOUND" in formatted
|
|
assert "shellcheck is not installed" in formatted
|
|
assert "not installed" in formatted.lower()
|
|
assert "Traceback" not in formatted
|
|
|
|
|
|
class TestShellcheckEdgeCases:
|
|
"""Tests for Shellcheck edge branches."""
|
|
|
|
def test_lint_with_empty_output(self, shellcheck_linter):
|
|
"""Test lint returns [] when shellcheck emits empty output."""
|
|
with patch(
|
|
'shellcheck.shellcheck.shutil.which',
|
|
return_value='/usr/bin/shellcheck'
|
|
) as _, patch(
|
|
'shellcheck.shellcheck.subprocess.run'
|
|
) as mock_run:
|
|
mock_run.return_value = MagicMock(
|
|
returncode=0, stdout="", stderr=""
|
|
)
|
|
assert shellcheck_linter.lint("src") == []
|
|
|
|
def test_lint_with_non_list_json(self, shellcheck_linter):
|
|
"""Test lint returns [] when shellcheck emits a non-list JSON payload."""
|
|
with patch(
|
|
'shellcheck.shellcheck.shutil.which',
|
|
return_value='/usr/bin/shellcheck'
|
|
) as _, patch(
|
|
'shellcheck.shellcheck.subprocess.run'
|
|
) as mock_run:
|
|
mock_run.return_value = MagicMock(
|
|
returncode=0, stdout='{"violations": []}', stderr=""
|
|
)
|
|
assert shellcheck_linter.lint("src") == []
|
|
|
|
def test_lint_with_invalid_json(self, shellcheck_linter):
|
|
"""Test lint returns [] when shellcheck output is not valid JSON."""
|
|
with patch(
|
|
'shellcheck.shellcheck.shutil.which',
|
|
return_value='/usr/bin/shellcheck'
|
|
) as _, patch(
|
|
'shellcheck.shellcheck.subprocess.run'
|
|
) as mock_run:
|
|
mock_run.return_value = MagicMock(
|
|
returncode=0, stdout='not valid json', stderr=""
|
|
)
|
|
assert shellcheck_linter.lint("src") == []
|
|
|
|
def test_compress_violations_with_missing_file_key(self, shellcheck_linter):
|
|
"""Test compress_violations handles violations without file key."""
|
|
violations = [{
|
|
"line": 1,
|
|
"column": 10,
|
|
"code": "SC1000",
|
|
"message": "test"
|
|
}]
|
|
|
|
with patch.object(pathlib.Path, 'cwd', return_value=pathlib.Path("/mock/cwd")):
|
|
compressed = shellcheck_linter.compress_violations(violations, "/mock/target")
|
|
assert "files" in compressed
|
|
|
|
def test_severity_mapping(self, shellcheck_linter, tmp_path):
|
|
"""Test that shellcheck severity levels are mapped correctly."""
|
|
test_file = tmp_path / "test.sh"
|
|
|
|
for level, expected_severity in [("error", "error"), ("warning", "warning"), ("info", "info"), ("style", "info")]:
|
|
with patch(
|
|
'shellcheck.shellcheck.shutil.which',
|
|
return_value='/usr/bin/shellcheck'
|
|
) as _, patch(
|
|
'shellcheck.shellcheck.subprocess.run'
|
|
) as mock_run:
|
|
mock_violation = {
|
|
"file": str(test_file),
|
|
"line": 1,
|
|
"column": 1,
|
|
"code": "SC0001",
|
|
"message": "test",
|
|
"level": level
|
|
}
|
|
mock_run.return_value = MagicMock(
|
|
returncode=0,
|
|
stdout=json.dumps([mock_violation]),
|
|
stderr=""
|
|
)
|
|
violations = shellcheck_linter.lint_file(str(test_file))
|
|
assert violations[0].severity == expected_severity
|
|
|
|
def test_file_extensions(self, shellcheck_linter):
|
|
"""Test that shellcheck recognizes the correct file extensions."""
|
|
assert ".sh" in shellcheck_linter.file_extensions
|
|
assert ".bash" in shellcheck_linter.file_extensions
|
|
assert ".zsh" in shellcheck_linter.file_extensions
|
|
assert ".dash" in shellcheck_linter.file_extensions
|
|
|
|
def test_linter_name(self, shellcheck_linter):
|
|
"""Test that the linter name is Shellcheck."""
|
|
assert shellcheck_linter.linter_name == "Shellcheck"
|
|
|
|
|
|
def test_lint_shellcheck_not_found(self, shellcheck_linter, tmp_path):
|
|
"""Test lint returns SHELLCHECK_NOT_FOUND when binary not found."""
|
|
test_file = tmp_path / "test.sh"
|
|
test_file.write_text("#!/bin/bash\necho test\n")
|
|
|
|
with patch(
|
|
'shellcheck.shellcheck.shutil.which',
|
|
return_value=None
|
|
) as _, patch.object(
|
|
pathlib.Path, 'exists', return_value=False
|
|
):
|
|
violations = shellcheck_linter.lint(str(test_file))
|
|
|
|
assert len(violations) == 1
|
|
assert violations[0]["code"] == "SHELLCHECK_NOT_FOUND"
|
|
|
|
def test_lint_empty_stdout(self, shellcheck_linter, tmp_path):
|
|
"""Test lint returns [] when stdout is empty."""
|
|
test_file = tmp_path / "test.sh"
|
|
test_file.write_text("#!/bin/bash\necho test\n")
|
|
|
|
with patch(
|
|
'shellcheck.shellcheck.shutil.which',
|
|
return_value='/usr/bin/shellcheck'
|
|
) as _, patch(
|
|
'shellcheck.shellcheck.subprocess.run'
|
|
) as mock_run:
|
|
mock_run.return_value = MagicMock(
|
|
returncode=0,
|
|
stdout="",
|
|
stderr=""
|
|
)
|
|
violations = shellcheck_linter.lint(str(test_file))
|
|
|
|
assert violations == []
|
|
|
|
def test_lint_json_decode_error(self, shellcheck_linter, tmp_path):
|
|
"""Test lint handles JSON decode errors."""
|
|
test_file = tmp_path / "test.sh"
|
|
test_file.write_text("#!/bin/bash\necho test\n")
|
|
|
|
with patch(
|
|
'shellcheck.shellcheck.shutil.which',
|
|
return_value='/usr/bin/shellcheck'
|
|
) as _, patch(
|
|
'shellcheck.shellcheck.subprocess.run'
|
|
) as mock_run:
|
|
mock_run.return_value = MagicMock(
|
|
returncode=0,
|
|
stdout='not valid json',
|
|
stderr=""
|
|
)
|
|
violations = shellcheck_linter.lint(str(test_file))
|
|
|
|
assert violations == []
|
|
|
|
def test_format_violations_with_target_path(self, shellcheck_linter):
|
|
"""Test format_violations with target_path parameter."""
|
|
compressed = {
|
|
"files": {"test.sh": ["1:1 SC2086"]},
|
|
"descriptions": {"SC2086": {"rule_name": "SC2086", "description": "test"}},
|
|
"meta": {"file_count": 1, "total_violations": 1}
|
|
}
|
|
|
|
result = shellcheck_linter.format_violations(
|
|
compressed, target_path="/some/path"
|
|
)
|
|
|
|
assert isinstance(result, str)
|
|
assert "Shellcheck Violations" in result
|
|
|
|
def test_lint_file_skips_readonly_zones(self, shellcheck_linter, tmp_path):
|
|
"""Test lint_file skips files in read-only zones."""
|
|
# Create a file in a read-only zone directory
|
|
readonly_dir = tmp_path / "personal"
|
|
readonly_dir.mkdir()
|
|
readonly_file = readonly_dir / "test.sh"
|
|
readonly_file.write_text("#!/bin/bash\necho test\n")
|
|
|
|
violations = shellcheck_linter.lint_file(str(readonly_file))
|
|
|
|
# Should return empty because it's in a read-only zone
|
|
assert violations == []
|
|
|