Buckets:

download
raw
34.8 kB
"""Comprehensive unit tests for tools/semgrep_integration.py.
These tests exercise the SemgrepScanner, result/findings dataclasses,
parsing helpers, sync wrappers, LangChain tool functions and tool-registry
integration. All external calls (subprocess, filesystem existence checks)
are fully mocked.
"""
import asyncio
import json
from unittest.mock import AsyncMock, MagicMock, Mock, patch
import pytest
from tools.semgrep_integration import (
SemgrepConfidence,
SemgrepFinding,
SemgrepResult,
SemgrepScanner,
SemgrepSeverity,
register_semgrep_tools,
semgrep_scan,
semgrep_scan_ci,
semgrep_scan_code,
semgrep_scan_owasp,
semgrep_scan_secrets,
)
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture(autouse=True)
def _patch_shutil_which(monkeypatch):
"""Pretend semgrep is always installed unless a test overrides this."""
monkeypatch.setattr("shutil.which", lambda _path: "/usr/bin/semgrep")
@pytest.fixture
def scanner() -> SemgrepScanner:
"""Default scanner instance with mocked semgrep binary."""
return SemgrepScanner()
@pytest.fixture
def target_exists(monkeypatch):
"""Make every pathlib.Path.exists() check return True."""
monkeypatch.setattr("pathlib.Path.exists", lambda _self: True)
@pytest.fixture
def sample_output():
return {
"version": "1.78.0",
"results": [
{
"check_id": "python.lang.security.audit.dangerous-eval-string",
"path": "app.py",
"start": {"line": 15, "col": 10},
"end": {"line": 15, "col": 30},
"extra": {
"message": "Detected eval().",
"severity": "ERROR",
"confidence": "HIGH",
"lines": "result = eval(user_input)",
"metadata": {
"cwe": ["CWE-95: Improper Neutralization ..."],
"owasp": ["A03:2021 - Injection"],
"references": ["https://owasp.org/Top10/A03_2021-Injection"],
"category": "security",
"technology": ["python"],
"confidence": "HIGH",
"likelihood": "HIGH",
"impact": "HIGH",
},
"fix": "result = ast.literal_eval(user_input)",
"fix_regex": {"regex": "eval", "replacement": "ast.literal_eval"},
},
},
{
"check_id": "javascript.lang.security.audit.path-traversal",
"path": "server.js",
"start": {"line": 42, "col": 20},
"end": {"line": 42, "col": 50},
"extra": {
"message": "Path traversal vulnerability detected",
"severity": "WARNING",
"confidence": "MEDIUM",
"lines": "const file = path.join(__dirname, req.query.file);",
"metadata": {
"cwe": ["CWE-22: Improper Limitation ..."],
"owasp": ["A01:2021 - Broken Access Control"],
"category": "security",
"technology": ["javascript"],
"confidence": "MEDIUM",
},
},
},
],
"errors": [],
"paths": {"scanned": ["app.py", "server.js"]},
"engine_requested": "PRO",
}
@pytest.fixture
def sample_error_output():
return {
"version": "1.78.0",
"results": [],
"errors": [
{
"code": 3,
"level": "warn",
"message": "Syntax error in file",
"path": "broken.py",
"type": "Syntax error",
}
],
}
@pytest.fixture
def mock_completed_process():
def _make(stdout="", returncode=0, stderr=""):
p = Mock()
p.stdout = stdout
p.returncode = returncode
p.stderr = stderr
return p
return _make
# ---------------------------------------------------------------------------
# Enums & dataclasses
# ---------------------------------------------------------------------------
class TestEnums:
def test_severity_values(self):
assert SemgrepSeverity.ERROR.value == "ERROR"
assert SemgrepSeverity.WARNING.value == "WARNING"
assert SemgrepSeverity.INFO.value == "INFO"
def test_confidence_values(self):
assert SemgrepConfidence.HIGH.value == "HIGH"
assert SemgrepConfidence.MEDIUM.value == "MEDIUM"
assert SemgrepConfidence.LOW.value == "LOW"
class TestDataclasses:
def test_finding_defaults(self):
finding = SemgrepFinding(
check_id="r",
path="p.py",
start_line=1,
end_line=2,
start_col=0,
end_col=5,
message="m",
severity="WARNING",
confidence="MEDIUM",
)
assert finding.metadata == {}
assert finding.fix == ""
assert finding.fix_regex == {}
assert finding.code_snippet == ""
def test_result_defaults(self):
result = SemgrepResult(success=True, target="/tmp")
assert result.findings == []
assert result.errors == []
assert result.scan_time == 0.0
assert result.error is None
assert result.stats == {}
# ---------------------------------------------------------------------------
# Scanner initialization
# ---------------------------------------------------------------------------
class TestScannerInitialization:
def test_default_init(self, scanner):
assert scanner.semgrep_path == "/usr/bin/semgrep"
assert scanner.config == scanner.DEFAULT_RULES
assert scanner.num_jobs == 4
assert scanner.timeout == 300
assert scanner.autofix is False
assert scanner.dry_run is True
assert scanner.verbose is False
assert scanner.max_memory == 0
def test_init_custom(self):
s = SemgrepScanner(
semgrep_path="/opt/semgrep",
config=["p/owasp-top-ten"],
exclude_patterns=["tests"],
include_patterns=["*.py"],
max_memory=2048,
max_target_bytes=500000,
num_jobs=8,
timeout=600,
timeout_threshold=5,
autofix=True,
dry_run=False,
strict=True,
verbose=True,
)
assert s.semgrep_path == "/usr/bin/semgrep" # because shutil.which mapped it
assert s.config == ["p/owasp-top-ten"]
assert s.exclude_patterns == ["tests"]
assert s.include_patterns == ["*.py"]
assert s.max_memory == 2048
assert s.max_target_bytes == 500000
assert s.num_jobs == 8
assert s.timeout == 600
assert s.timeout_threshold == 5
assert s.autofix is True
assert s.dry_run is False
assert s.strict is True
assert s.verbose is True
def test_init_not_found(self, monkeypatch):
monkeypatch.setattr("shutil.which", lambda _p: None)
with pytest.raises(RuntimeError, match="semgrep not found"):
SemgrepScanner(semgrep_path="missing")
def test_validate_installation_returns_which(self, scanner):
# Already exercised through __init__, but test explicitly.
assert scanner._validate_installation("semgrep") == "/usr/bin/semgrep"
# ---------------------------------------------------------------------------
# Version helpers
# ---------------------------------------------------------------------------
class TestVersion:
def test_get_version_success(self, scanner):
with patch("tools.semgrep_integration.subprocess.run") as run:
run.return_value = Mock(returncode=0, stdout="1.2.3\n")
assert scanner._get_version() == "1.2.3"
run.assert_called_once()
def test_get_version_failure_returncode(self, scanner):
with patch("tools.semgrep_integration.subprocess.run") as run:
run.return_value = Mock(returncode=1, stdout="boom")
assert scanner._get_version() == "unknown"
def test_get_version_exception(self, scanner):
with patch("tools.semgrep_integration.subprocess.run", side_effect=OSError("nope")):
assert scanner._get_version() == "unknown"
def test_public_get_version(self, scanner):
with patch.object(scanner, "_get_version", return_value="v123"):
assert scanner.get_version() == "v123"
# ---------------------------------------------------------------------------
# Command building
# ---------------------------------------------------------------------------
class TestCommandBuilding:
def test_basic_command(self, scanner):
cmd = scanner._build_command("/code")
assert cmd[0] == "/usr/bin/semgrep"
assert "--json" in cmd
assert "/code" in cmd
for rule in scanner.DEFAULT_RULES:
assert rule in cmd
def test_excludes(self, scanner):
scanner.exclude_patterns = ["tests", "node_modules"]
cmd = scanner._build_command("/code")
assert cmd.count("--exclude") == 2
assert "tests" in cmd and "node_modules" in cmd
def test_includes(self, scanner):
scanner.include_patterns = ["*.py", "*.js"]
cmd = scanner._build_command("/code")
assert cmd.count("--include") == 2
assert "*.py" in cmd and "*.js" in cmd
def test_performance_options(self, scanner):
scanner.max_memory = 4096
scanner.num_jobs = 8
scanner.timeout = 600
scanner.max_target_bytes = 1234
scanner.timeout_threshold = 7
cmd = scanner._build_command("/code")
assert "--max-memory" in cmd and "4096" in cmd
assert "--jobs" in cmd and "8" in cmd
assert "--timeout" in cmd and "600" in cmd
assert "--max-target-bytes" in cmd and "1234" in cmd
assert "--timeout-threshold" in cmd and "7" in cmd
def test_no_max_memory_when_zero(self, scanner):
scanner.max_memory = 0
cmd = scanner._build_command("/code")
assert "--max-memory" not in cmd
def test_behavior_options(self, scanner):
scanner.autofix = True
scanner.dry_run = False
scanner.strict = True
scanner.verbose = True
cmd = scanner._build_command("/code")
assert "--autofix" in cmd
assert "--dryrun" not in cmd
assert "--strict" in cmd
assert "--verbose" in cmd
def test_output_file(self, scanner):
cmd = scanner._build_command("/code", output_file="/tmp/out.json")
assert "--output" in cmd
assert "/tmp/out.json" in cmd
def test_empty_include_patterns(self, scanner):
scanner.include_patterns = []
cmd = scanner._build_command("/code")
assert "--include" not in cmd
# ---------------------------------------------------------------------------
# Parsing helpers
# ---------------------------------------------------------------------------
class TestFindingParsing:
def test_parse_findings_full(self, scanner, sample_output):
findings = scanner._parse_findings(sample_output)
assert len(findings) == 2
first = findings[0]
assert first.check_id == "python.lang.security.audit.dangerous-eval-string"
assert first.path == "app.py"
assert first.start_line == 15
assert first.end_line == 15
assert first.start_col == 10
assert first.end_col == 30
assert first.severity == "ERROR"
assert first.confidence == "HIGH"
assert first.fix == "result = ast.literal_eval(user_input)"
assert first.fix_regex == {"regex": "eval", "replacement": "ast.literal_eval"}
assert "CWE-95" in first.metadata["cwe"][0]
def test_parse_findings_empty(self, scanner):
assert scanner._parse_findings({"results": []}) == []
assert scanner._parse_findings({}) == []
def test_parse_findings_defaults(self, scanner):
data = {
"results": [
{
"check_id": "x",
"path": "y.py",
"extra": {"message": "m"},
}
]
}
f = scanner._parse_findings(data)[0]
assert f.start_line == 0
assert f.end_line == 0
assert f.start_col == 0
assert f.end_col == 0
assert f.severity == "WARNING"
assert f.confidence == "MEDIUM"
assert f.metadata == {}
assert f.fix == ""
assert f.fix_regex == {}
assert f.code_snippet == ""
class TestErrorParsing:
def test_extract_errors(self, scanner, sample_error_output):
assert scanner._extract_errors(sample_error_output) == ["Syntax error in file"]
def test_extract_errors_missing_message(self, scanner):
data = {"errors": [{"code": 1}]}
assert scanner._extract_errors(data) == ["Unknown error"]
def test_extract_errors_no_key(self, scanner):
assert scanner._extract_errors({}) == []
class TestStatsParsing:
def test_extract_stats_full(self, scanner, sample_output):
stats = scanner._extract_stats(sample_output)
assert stats["engine"] == "PRO"
assert stats["version"] == "1.78.0"
assert stats["severity_counts"] == {"ERROR": 1, "WARNING": 1}
def test_extract_stats_defaults(self, scanner):
stats = scanner._extract_stats({"results": []})
assert stats["engine"] == "OS"
assert stats["version"] == "unknown"
assert stats["severity_counts"] == {}
# ---------------------------------------------------------------------------
# Async scan
# ---------------------------------------------------------------------------
class TestAsyncScan:
@pytest.mark.asyncio
async def test_scan_success(self, scanner, target_exists, sample_output):
mock_proc = Mock(returncode=0, stdout=json.dumps(sample_output), stderr="")
with patch.object(scanner, "_run_subprocess", return_value=mock_proc):
result = await scanner.scan("/code")
assert result.success is True
assert result.target == "/code"
assert len(result.findings) == 2
assert result.stats["severity_counts"]["ERROR"] == 1
assert result.scan_time >= 0
@pytest.mark.asyncio
async def test_scan_success_with_findings_returncode_one(self, scanner, target_exists, sample_output):
mock_proc = Mock(returncode=1, stdout=json.dumps(sample_output), stderr="")
with patch.object(scanner, "_run_subprocess", return_value=mock_proc):
result = await scanner.scan("/code")
# The implementation uses `success = ... and findings`, so the value is
# truthy (the findings list) rather than a literal bool.
assert result.success # truthy because findings exist
@pytest.mark.asyncio
async def test_scan_failure_returncode_one_no_findings(self, scanner, target_exists):
data = {"results": [], "errors": [], "version": "1"}
mock_proc = Mock(returncode=1, stdout=json.dumps(data), stderr="")
with patch.object(scanner, "_run_subprocess", return_value=mock_proc):
result = await scanner.scan("/code")
assert not result.success # empty list is falsy
@pytest.mark.asyncio
async def test_scan_target_missing(self, scanner, monkeypatch):
monkeypatch.setattr("pathlib.Path.exists", lambda _self: False)
result = await scanner.scan("/does/not/exist")
assert result.success is False
assert "does not exist" in result.error
@pytest.mark.asyncio
async def test_scan_json_decode_error(self, scanner, target_exists):
mock_proc = Mock(returncode=0, stdout="not-json{{", stderr="")
with patch.object(scanner, "_run_subprocess", return_value=mock_proc):
result = await scanner.scan("/code")
assert result.success is False
assert "Failed to parse output" in result.error
@pytest.mark.asyncio
async def test_scan_timeout(self, scanner, target_exists):
with patch.object(scanner, "_run_subprocess", side_effect=asyncio.TimeoutError):
result = await scanner.scan("/code")
assert result.success is False
assert "timed out" in result.error.lower()
assert result.scan_time >= 0
@pytest.mark.asyncio
async def test_scan_generic_exception(self, scanner, target_exists):
with patch.object(scanner, "_run_subprocess", side_effect=RuntimeError("boom")):
result = await scanner.scan("/code")
assert result.success is False
assert "boom" in result.error
@pytest.mark.asyncio
async def test_scan_custom_config_restored(self, scanner, target_exists, sample_output):
original_config = scanner.config.copy()
custom = ["p/custom"]
mock_proc = Mock(returncode=0, stdout=json.dumps(sample_output), stderr="")
with patch.object(scanner, "_run_subprocess", return_value=mock_proc):
result = await scanner.scan("/code", custom_config=custom)
assert result.success is True
assert scanner.config == original_config
@pytest.mark.asyncio
async def test_scan_custom_config_restored_on_error(self, scanner, target_exists):
original_config = scanner.config.copy()
custom = ["p/custom"]
with patch.object(scanner, "_run_subprocess", side_effect=RuntimeError("oops")):
result = await scanner.scan("/code", custom_config=custom)
assert result.success is False
assert scanner.config == original_config
# ---------------------------------------------------------------------------
# Subprocess runner
# ---------------------------------------------------------------------------
class TestRunSubprocess:
def test_run_subprocess(self, scanner):
with patch("tools.semgrep_integration.subprocess.run") as run:
run.return_value = Mock(stdout="x")
result = scanner._run_subprocess(["semgrep", "--json", "/code"])
run.assert_called_once_with(["semgrep", "--json", "/code"], capture_output=True, text=True)
assert result.stdout == "x"
# ---------------------------------------------------------------------------
# Output formatting / normalization
# ---------------------------------------------------------------------------
class TestOutputParsing:
def test_parse_output_full(self, scanner):
finding = SemgrepFinding(
check_id="r1",
path="app.py",
start_line=10,
end_line=10,
start_col=5,
end_col=20,
message="Dangerous eval",
severity="ERROR",
confidence="HIGH",
metadata={
"cwe": ["CWE-95"],
"owasp": ["A03:2021"],
"references": ["https://owasp.org"],
"category": "security",
"technology": ["python"],
"likelihood": "HIGH",
"impact": "HIGH",
},
code_snippet="eval(x)",
fix="literal_eval(x)",
)
result = SemgrepResult(success=True, target="/code", findings=[finding])
parsed = scanner.parse_output(result)
assert len(parsed) == 1
p = parsed[0]
assert p["tool"] == "semgrep"
assert p["severity"] == "high"
assert p["confidence"] == "high"
assert p["cwe_ids"] == ["CWE-95"]
assert p["owasp"] == ["A03:2021"]
assert p["category"] == "security"
assert p["fix"] == "literal_eval(x)"
def test_parse_output_string_metadata(self, scanner):
finding = SemgrepFinding(
check_id="r1",
path="app.py",
start_line=1,
end_line=1,
start_col=1,
end_col=5,
message="m",
severity="WARNING",
confidence="MEDIUM",
metadata={
"cwe": "CWE-79",
"owasp": "A07:2021",
"references": "https://example.com",
"technology": "java",
},
)
parsed = scanner.parse_output(SemgrepResult(success=True, target="/code", findings=[finding]))
assert parsed[0]["cwe_ids"] == ["CWE-79"]
assert parsed[0]["owasp"] == ["A07:2021"]
assert parsed[0]["references"] == ["https://example.com"]
assert parsed[0]["languages"] == ["java"]
def test_parse_output_defaults(self, scanner):
finding = SemgrepFinding(
check_id="r",
path="x.py",
start_line=1,
end_line=1,
start_col=1,
end_col=2,
message="m",
severity="UNKNOWN",
confidence="LOW",
metadata={},
)
parsed = scanner.parse_output(SemgrepResult(success=True, target="/code", findings=[finding]))
assert parsed[0]["severity"] == "medium"
assert parsed[0]["category"] == "security"
assert parsed[0]["subcategory"] == []
assert parsed[0]["likelihood"] == "LOW"
assert parsed[0]["impact"] == "LOW"
class TestNormalizeFindings:
def test_with_fix(self, scanner):
findings = [
{
"tool": "semgrep",
"check_id": "r",
"path": "a.py",
"line": 1,
"column": 2,
"message": "M" * 120,
"severity": "HIGH",
"confidence": "high",
"cwe_ids": ["CWE-95"],
"owasp": ["A03"],
"references": ["https://x"],
"code": "eval(y)",
"fix": "literal_eval(y)",
}
]
norm = scanner.normalize_findings(findings)
assert len(norm) == 1
n = norm[0]
assert n["remediation"] == "literal_eval(y)"
assert n["title"] == "M" * 100
assert n["severity"] == "high"
assert n["evidence"]["code"] == "eval(y)"
assert "https://cwe.mitre.org/data/definitions/95.html" in n["references"]
def test_without_fix(self, scanner):
findings = [
{
"path": "a.py",
"line": 1,
"column": 2,
"message": "issue",
"severity": "medium",
}
]
norm = scanner.normalize_findings(findings)[0]
assert "Review the code" in norm["remediation"]
assert norm["cwe_ids"] == []
assert norm["owasp"] == []
assert norm["confidence"] == "medium"
def test_cwe_reference_generation(self, scanner):
findings = [
{
"path": "a.py",
"line": 1,
"column": 1,
"message": "m",
"cwe_ids": ["CWE-22", "not-a-cwe", "CWE-79"],
"references": [],
}
]
refs = scanner.normalize_findings(findings)[0]["references"]
assert "https://cwe.mitre.org/data/definitions/22.html" in refs
assert "https://cwe.mitre.org/data/definitions/79.html" in refs
assert "not-a-cwe" not in refs
# ---------------------------------------------------------------------------
# Rule helpers
# ---------------------------------------------------------------------------
class TestRuleConfiguration:
def test_add_owasp_rules(self):
# Use a truthy config so the `or` fallback in __init__ does not replace it.
s = SemgrepScanner(config=["p/other"])
s.add_owasp_rules()
assert "p/owasp-top-ten" in s.config
s.add_owasp_rules()
assert s.config.count("p/owasp-top-ten") == 1
def test_add_cwe_rules(self):
s = SemgrepScanner(config=["p/other"])
s.add_cwe_rules()
assert "p/cwe-top-25" in s.config
s.add_cwe_rules()
assert s.config.count("p/cwe-top-25") == 1
def test_add_security_audit_rules(self):
s = SemgrepScanner(config=["p/other"])
s.add_security_audit_rules()
assert "p/security-audit" in s.config
s.add_security_audit_rules()
assert s.config.count("p/security-audit") == 1
def test_add_secrets_rules(self):
s = SemgrepScanner(config=["p/other"])
s.add_secrets_rules()
assert "p/secrets" in s.config
s.add_secrets_rules()
assert s.config.count("p/secrets") == 1
# ---------------------------------------------------------------------------
# False-positive filtering
# ---------------------------------------------------------------------------
class TestFalsePositiveFiltering:
def mk(self, path="app.py", code="x"):
return SemgrepFinding(
check_id="r",
path=path,
start_line=1,
end_line=1,
start_col=1,
end_col=2,
message="m",
severity="WARNING",
confidence="MEDIUM",
code_snippet=code,
)
def test_filters_test_files_by_path(self, scanner):
findings = [self.mk("test_security.py"), self.mk("app.py")]
filtered = scanner.filter_false_positives(findings)
assert len(filtered) == 1
assert filtered[0].path == "app.py"
def test_filters_by_code_snippet(self, scanner):
findings = [self.mk("app.py", "this is a mock object"), self.mk("app.py", "real code")]
filtered = scanner.filter_false_positives(findings)
assert len(filtered) == 1
assert filtered[0].code_snippet == "real code"
def test_custom_patterns(self, scanner):
findings = [self.mk("my_custom_file.py"), self.mk("app.py")]
filtered = scanner.filter_false_positives(findings, ["custom"])
assert len(filtered) == 1
def test_no_match_keeps_all(self, scanner):
findings = [self.mk("app.py", "production code")]
filtered = scanner.filter_false_positives(findings)
assert len(filtered) == 1
def test_empty_findings(self, scanner):
assert scanner.filter_false_positives([]) == []
# ---------------------------------------------------------------------------
# LangChain tool wrappers
# ---------------------------------------------------------------------------
class TestLangChainTools:
@pytest.fixture
def mock_findings(self):
return [
SemgrepFinding(
check_id="python.lang.security.eval",
path="app.py",
start_line=1,
end_line=1,
start_col=1,
end_col=5,
message="eval is dangerous",
severity="ERROR",
confidence="HIGH",
),
SemgrepFinding(
check_id="python.lang.security.exec",
path="app.py",
start_line=2,
end_line=2,
start_col=1,
end_col=5,
message="exec is dangerous",
severity="WARNING",
confidence="MEDIUM",
),
]
@patch("tools.semgrep_integration.asyncio.run")
def test_semgrep_scan_code_success(self, mock_run, mock_findings):
result = Mock()
result.success = True
result.scan_time = 1.5
result.findings = mock_findings
mock_run.return_value = result
text = semgrep_scan_code("/code")
assert "Semgrep Scan: /code" in text
assert "Rules:" in text
assert "Findings: 2" in text
assert "HIGH Severity (1):" in text
assert "python.lang.security.eval" in text
@patch("tools.semgrep_integration.asyncio.run")
def test_semgrep_scan_code_failure(self, mock_run):
result = Mock()
result.success = False
result.error = "broken"
mock_run.return_value = result
text = semgrep_scan_code("/code")
assert "Semgrep scan failed: broken" == text
@patch("tools.semgrep_integration.asyncio.run")
def test_semgrep_scan_code_with_rules(self, mock_run):
result = Mock()
result.success = True
result.scan_time = 0.1
result.findings = []
mock_run.return_value = result
text = semgrep_scan_code("/code", rules="p/custom, p/other")
assert "p/custom" in text or "p/other" in text
@patch("tools.semgrep_integration.asyncio.run")
def test_semgrep_scan_owasp_success(self, mock_run):
f = SemgrepFinding(
check_id="owasp.rule",
path="app.py",
start_line=1,
end_line=1,
start_col=1,
end_col=2,
message="m",
severity="WARNING",
confidence="MEDIUM",
metadata={"owasp": ["A01"]},
)
result = Mock(success=True, scan_time=2.0, findings=[f])
mock_run.return_value = result
text = semgrep_scan_owasp("/code")
assert "OWASP Top 10 Scan: /code" in text
assert "OWASP-related: 1" in text
@patch("tools.semgrep_integration.asyncio.run")
def test_semgrep_scan_owasp_failure(self, mock_run):
mock_run.return_value = Mock(success=False, error="nope")
text = semgrep_scan_owasp("/code")
assert "OWASP scan failed: nope" == text
@patch("tools.semgrep_integration.asyncio.run")
def test_semgrep_scan_secrets_success(self, mock_run):
result = Mock(success=True, scan_time=0.5, findings=[Mock()])
mock_run.return_value = result
text = semgrep_scan_secrets("/code")
assert "Secrets Scan: /code" in text
assert "Potential secrets found: 1" in text
@patch("tools.semgrep_integration.asyncio.run")
def test_semgrep_scan_secrets_failure(self, mock_run):
mock_run.return_value = Mock(success=False, error="bad")
text = semgrep_scan_secrets("/code")
assert "Secrets scan failed: bad" == text
@patch("tools.semgrep_integration.asyncio.run")
def test_semgrep_scan_ci_pass(self, mock_run):
result = Mock(success=True, scan_time=1.0, findings=[])
mock_run.return_value = result
text = semgrep_scan_ci("/code")
assert "CI Security Scan: /code" in text
assert "PASS" in text
@patch("tools.semgrep_integration.asyncio.run")
def test_semgrep_scan_ci_fail(self, mock_run):
bad = SemgrepFinding(
check_id="x",
path="a.py",
start_line=1,
end_line=1,
start_col=1,
end_col=2,
message="m",
severity="ERROR",
confidence="HIGH",
)
result = Mock(success=True, scan_time=1.0, findings=[bad])
mock_run.return_value = result
text = semgrep_scan_ci("/code")
assert "FAIL" in text
assert "High Severity: 1" in text
def test_semgrep_scan_alias(self):
assert semgrep_scan is semgrep_scan_code
@patch("tools.semgrep_integration.asyncio.run")
def test_semgrep_scan_ci_failure(self, mock_run):
mock_run.return_value = Mock(success=False, error="ci failed")
text = semgrep_scan_ci("/code")
assert text == "CI scan failed: ci failed"
# ---------------------------------------------------------------------------
# Tool registry integration
# ---------------------------------------------------------------------------
class TestRegistryIntegration:
def test_register_when_unavailable(self, monkeypatch):
monkeypatch.setattr("tools.semgrep_integration.TOOL_REGISTRY_AVAILABLE", False)
# Should return silently without raising.
register_semgrep_tools()
def test_register_when_langchain_missing(self, monkeypatch):
monkeypatch.setattr("tools.semgrep_integration.LANGCHAIN_AVAILABLE", False)
monkeypatch.setattr("tools.semgrep_integration.TOOL_REGISTRY_AVAILABLE", True)
# Also should return silently because of LANGCHAIN guard.
register_semgrep_tools()
def test_register_success(self, monkeypatch):
fake_registry = Mock()
fake_category = Mock()
fake_safety = Mock()
monkeypatch.setattr("tools.semgrep_integration.TOOL_REGISTRY_AVAILABLE", True)
monkeypatch.setattr("tools.semgrep_integration.LANGCHAIN_AVAILABLE", True)
monkeypatch.setattr("tools.semgrep_integration.registry", fake_registry)
monkeypatch.setattr("tools.semgrep_integration.ToolCategory", fake_category)
monkeypatch.setattr("tools.semgrep_integration.ToolSafetyLevel", fake_safety)
register_semgrep_tools()
assert fake_registry.register.call_count == 4
def test_register_warning_on_exception(self, monkeypatch):
fake_registry = Mock()
fake_registry.register.side_effect = RuntimeError("registration failed")
monkeypatch.setattr("tools.semgrep_integration.TOOL_REGISTRY_AVAILABLE", True)
monkeypatch.setattr("tools.semgrep_integration.LANGCHAIN_AVAILABLE", True)
monkeypatch.setattr("tools.semgrep_integration.registry", fake_registry)
# Should log a warning, not propagate.
register_semgrep_tools()
fake_registry.register.assert_called()
# ---------------------------------------------------------------------------
# Module-level exports
# ---------------------------------------------------------------------------
class TestFallbackToolDecorator:
def test_fallback_tool_direct(self):
from tools.semgrep_integration import tool
@tool
def bare():
return 42
assert bare() == 42
def test_fallback_tool_with_kwargs(self):
from tools.semgrep_integration import tool
@tool(response_format="json")
def decorated():
return 99
assert decorated() == 99
class TestModuleExports:
def test_all_contains_expected_names(self):
from tools import semgrep_integration as mod
for name in [
"SemgrepScanner",
"SemgrepFinding",
"SemgrepResult",
"SemgrepSeverity",
"SemgrepConfidence",
"semgrep_scan_code",
"semgrep_scan",
"semgrep_scan_owasp",
"semgrep_scan_secrets",
"semgrep_scan_ci",
"register_semgrep_tools",
]:
assert name in mod.__all__

Xet Storage Details

Size:
34.8 kB
·
Xet hash:
d44081bdb2501e4bc49a16237ae59b695e0f4bac9c4e7a7b6c5b00b4b921b8a6

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.