DeepTeam is a framework to red team LLMs and AI agents.
feat(tests): add code_scanner tests
tanayvaswani32185a267749
diff --git a/tests/test_core/test_code_scanner/test_cli.py b/tests/test_core/test_code_scanner/test_cli.pynew file mode 100644index 00000000..29ab06ab--- /dev/null+++ b/tests/test_core/test_code_scanner/test_cli.py@@ -0,0 +1,87 @@+import json++import pytest+from typer.testing import CliRunner++import deepteam.cli.main as climain+import deepteam.code_scanner.code_scanner as cs_module+from deepteam.code_scanner import CodeFinding, CodeFindingsList+++def runner():+ return CliRunner()+++def scan_dir(tmp_path):+ (tmp_path / "agent.py").write_text("x = eval(resp)\n")+ return str(tmp_path)++[email protected](autouse=True)+def mock_llm(monkeypatch):+ # No real model, no real LLM call.+ monkeypatch.setattr(climain, "load_model", lambda spec: object())+ monkeypatch.setattr(cs_module, "initialize_model", lambda m: (m, False))+ monkeypatch.setattr(+ cs_module,+ "generate",+ lambda *a, **k: CodeFindingsList(+ findings=[+ CodeFinding(+ filePath="agent.py",+ lineStart=2,+ vulnerability="Unexpected Code Execution",+ vulnerabilityType="eval_usage",+ severity="high",+ reason="eval on input",+ recommendation="use ast.literal_eval",+ )+ ]+ ),+ )+++class TestScanCli:+ def test_json_and_exit_code(self, runner, scan_dir):+ r = runner.invoke(climain.app, ["scan", scan_dir, "--format", "json"])+ assert r.exit_code == 1 # findings present -> CI-failing+ assert json.loads(r.stdout)[0]["vulnerabilityType"] == "eval_usage"++ def test_markdown_default(self, runner, scan_dir):+ r = runner.invoke(climain.app, ["scan", scan_dir])+ assert "DeepTeam Code" in r.stdout++ def test_min_severity_filters(self, runner, scan_dir):+ r = runner.invoke(+ climain.app,+ [+ "scan",+ scan_dir,+ "--min-severity",+ "critical",+ "--format",+ "json",+ ],+ )+ assert r.exit_code == 0+ assert json.loads(r.stdout) == []++ def test_no_fail_flag(self, runner, scan_dir):+ r = runner.invoke(+ climain.app, ["scan", scan_dir, "--no-fail-on-findings"]+ )+ assert r.exit_code == 0++ def test_output_file(self, runner, scan_dir, tmp_path):+ out = str(tmp_path / "out.sarif")+ runner.invoke(+ climain.app, ["scan", scan_dir, "--format", "sarif", "-o", out]+ )+ with open(out) as f:+ assert json.load(f)["version"] == "2.1.0"++ def test_bad_format(self, runner, scan_dir):+ r = runner.invoke(climain.app, ["scan", scan_dir, "--format", "xml"])+ assert r.exit_code != 0diff --git a/tests/test_core/test_code_scanner/test_code_scanner.py b/tests/test_core/test_code_scanner/test_code_scanner.pynew file mode 100644index 00000000..9cd3eb2e--- /dev/null+++ b/tests/test_core/test_code_scanner/test_code_scanner.py@@ -0,0 +1,87 @@+import asyncio++import pytest++import deepteam.code_scanner.code_scanner as cs_module+from deepteam.code_scanner import (+ CodeChunk,+ CodeFinding,+ CodeFindingsList,+ CodeScanner,+)+++def _finding(fp="a.py", ln=1):+ return CodeFinding(+ filePath=fp,+ lineStart=ln,+ vulnerability="SSRF",+ vulnerabilityType="port_scanning",+ severity="low",+ reason="x",+ )+++def no_model_init(monkeypatch):+ # Skip real model construction so tests need no API key.+ monkeypatch.setattr(cs_module, "initialize_model", lambda m: (m, False))+++def _chunks(n, size=40):+ return [+ CodeChunk(file_path=f"f{i}.py", content="y" * size) for i in range(n)+ ]+++class TestCodeScanner:+ def test_batching_splits_by_size(self, no_model_init):+ sc = CodeScanner(model=object(), limit=50)+ assert len(sc._make_batches(_chunks(3))) == 3++ def test_batching_packs_small_chunks(self, no_model_init):+ sc = CodeScanner(model=object(), limit=100_000)+ assert len(sc._make_batches(_chunks(5, size=1))) == 1++ def test_scan_dedupes(self, no_model_init, monkeypatch):+ monkeypatch.setattr(+ cs_module,+ "generate",+ lambda *a, **k: CodeFindingsList(findings=[_finding()]),+ )+ sc = CodeScanner(model=object(), limit=50)+ # 3 batches each return the identical finding -> deduped to one.+ assert len(sc.scan(_chunks(3))) == 1++ def test_dedupe_keeps_distinct(self):+ out = CodeScanner._dedupe(+ [_finding(ln=1), _finding(ln=2), _finding(ln=1)]+ )+ assert len(out) == 2++ def test_scan_resilient_to_batch_failure(self, no_model_init, monkeypatch):+ def boom(*a, **k):+ raise RuntimeError("boom")++ monkeypatch.setattr(cs_module, "generate", boom)+ sc = CodeScanner(model=object(), limit=50)+ # Every batch fails -> no crash, empty result.+ assert sc.scan(_chunks(2)) == []++ def test_a_scan(self, no_model_init, monkeypatch):+ counter = {"n": 0}++ async def fake(*a, **k):+ counter["n"] += 1+ return CodeFindingsList(+ findings=[_finding(fp=f"f{counter['n']}.py")]+ )++ monkeypatch.setattr(cs_module, "a_generate", fake)+ sc = CodeScanner(model=object(), limit=50)+ out = asyncio.run(sc.a_scan(_chunks(3)))+ assert len(out) == 3++ def test_instruction_stored(self, no_model_init):+ sc = CodeScanner(model=object(), instruction="be strict")+ assert sc.instruction == "be strict"diff --git a/tests/test_core/test_code_scanner/test_collect.py b/tests/test_core/test_code_scanner/test_collect.pynew file mode 100644index 00000000..121dd475--- /dev/null+++ b/tests/test_core/test_code_scanner/test_collect.py@@ -0,0 +1,87 @@+import subprocess+from pathlib import Path++from deepteam.code_scanner import collect_changed_files, collect_files+++def _tree(tmp_path: Path) -> Path:+ (tmp_path / "app").mkdir()+ (tmp_path / "app" / "agent.py").write_text("x = eval(resp)\n")+ (tmp_path / "app" / "util.ts").write_text("const a = 1;\n")+ (tmp_path / "node_modules").mkdir()+ (tmp_path / "node_modules" / "dep.py").write_text("y = 1\n")+ (tmp_path / "pnpm-lock.yaml").write_text("lock\n")+ (tmp_path / "logo.png").write_bytes(b"\x89PNG\x00\x00bin")+ return tmp_path+++class TestCollectFiles:+ def test_collects_source_skips_junk(self, tmp_path):+ d = _tree(tmp_path)+ paths = {c.file_path for c in collect_files(str(d))}+ assert "app/agent.py" in paths+ assert "app/util.ts" in paths+ assert not any("node_modules" in p for p in paths)+ assert "pnpm-lock.yaml" not in paths+ assert "logo.png" not in paths++ def test_language_detection(self, tmp_path):+ d = _tree(tmp_path)+ langs = {c.file_path: c.language for c in collect_files(str(d))}+ assert langs["app/agent.py"] == "python"+ assert langs["app/util.ts"] == "typescript"++ def test_include_exclude(self, tmp_path):+ d = _tree(tmp_path)+ only_ts = {c.file_path for c in collect_files(str(d), include=["*.ts"])}+ assert only_ts == {"app/util.ts"}+ no_py = {c.file_path for c in collect_files(str(d), exclude=["*.py"])}+ assert not any(p.endswith(".py") for p in no_py)++ def test_single_file(self, tmp_path):+ d = _tree(tmp_path)+ chunks = collect_files(str(d / "app" / "agent.py"))+ assert chunks and chunks[0].file_path == "agent.py"++ def test_large_file_split_with_line_offsets(self, tmp_path):+ (tmp_path / "big.py").write_text(+ "\n".join(f"x{i} = 1" for i in range(1, 4001)) + "\n"+ )+ chunks = sorted(+ collect_files(str(tmp_path), max_chunk_chars=2000),+ key=lambda c: c.start_line,+ )+ assert len(chunks) > 1+ assert chunks[0].start_line == 1+ # The next chunk starts right after the first chunk's last line.+ assert chunks[1].start_line == 1 + chunks[0].content.count("\n")+++class TestCollectChangedFiles:+ def test_diff_mode_returns_only_changed(self, tmp_path):+ def git(*args):+ subprocess.run(+ ["git", "-C", str(tmp_path), *args],+ check=True,+ capture_output=True,+ )++ git("init")+ git("config", "user.email", "[email protected]")+ git("config", "user.name", "t")+ (tmp_path / "a.py").write_text("a = 1\n")+ (tmp_path / "b.py").write_text("b = 1\n")+ git("add", "-A")+ git("commit", "-m", "base")+ (tmp_path / "b.py").write_text("b = eval(x)\n")+ (tmp_path / "c.py").write_text("c = 1\n")+ git("add", "-A")+ git("commit", "-m", "change")++ changed = {+ c.file_path+ for c in collect_changed_files(+ str(tmp_path), base="HEAD~1", head="HEAD"+ )+ }+ assert changed == {"b.py", "c.py"}diff --git a/tests/test_core/test_code_scanner/test_config.py b/tests/test_core/test_code_scanner/test_config.pynew file mode 100644index 00000000..216b0f02--- /dev/null+++ b/tests/test_core/test_code_scanner/test_config.py@@ -0,0 +1,35 @@+from deepteam.code_scanner import (+ CONFIG_FILENAMES,+ find_config_file,+ load_config,+)+++class TestConfig:+ def test_loads_yaml(self, tmp_path):+ (tmp_path / CONFIG_FILENAMES[0]).write_text(+ "min_severity: high\n"+ "instruction: |\n"+ " Be strict.\n"+ "exclude:\n"+ " - 'tests/**'\n"+ )+ cfg = load_config(directory=str(tmp_path))+ assert cfg.min_severity == "high"+ assert cfg.instruction.strip() == "Be strict."+ assert cfg.exclude == ["tests/**"]++ def test_defaults_when_missing(self, tmp_path):+ cfg = load_config(directory=str(tmp_path))+ assert cfg.min_severity == "low"+ assert cfg.instruction is None++ def test_explicit_path(self, tmp_path):+ p = tmp_path / "custom.yaml"+ p.write_text("min_severity: critical\n")+ assert load_config(path=str(p)).min_severity == "critical"++ def test_find_config_file(self, tmp_path):+ assert find_config_file(str(tmp_path)) is None+ (tmp_path / CONFIG_FILENAMES[0]).write_text("min_severity: low\n")+ assert find_config_file(str(tmp_path)).endswith(CONFIG_FILENAMES[0])diff --git a/tests/test_core/test_code_scanner/test_report.py b/tests/test_core/test_code_scanner/test_report.pynew file mode 100644index 00000000..20917d4e--- /dev/null+++ b/tests/test_core/test_code_scanner/test_report.py@@ -0,0 +1,52 @@+import json++from deepteam.code_scanner import (+ CodeFinding,+ filter_by_severity,+ to_json,+ to_markdown,+ to_sarif,+)+++def _f(severity, ln=1, recommendation=None):+ return CodeFinding(+ filePath="a.py",+ lineStart=ln,+ vulnerability="SSRF",+ vulnerabilityType="port_scanning",+ severity=severity,+ reason="r",+ recommendation=recommendation,+ )+++class TestReport:+ def test_filter_by_severity(self):+ fs = [_f("low"), _f("high"), _f("critical")]+ assert len(filter_by_severity(fs, "low")) == 3+ assert len(filter_by_severity(fs, "high")) == 2+ assert len(filter_by_severity(fs, "critical")) == 1++ def test_to_json_roundtrips(self):+ d = json.loads(to_json([_f("high")]))+ assert d[0]["vulnerability"] == "SSRF"+ assert d[0]["severity"] == "high"++ def test_markdown_empty(self):+ assert "No vulnerabilities found" in to_markdown([])++ def test_markdown_has_finding(self):+ md = to_markdown([_f("critical", recommendation="do x")])+ assert "SSRF / port_scanning" in md+ assert "**Critical**" in md # severity badge is capitalized+ assert "do x" in md++ def test_sarif_valid_and_level_mapping(self):+ s = json.loads(to_sarif([_f("critical"), _f("low", ln=9)]))+ assert s["version"] == "2.1.0"+ results = s["runs"][0]["results"]+ assert results[0]["level"] == "error" # critical -> error+ assert results[1]["level"] == "note" # low -> note+ region = results[1]["locations"][0]["physicalLocation"]["region"]+ assert region["startLine"] == 9diff --git a/tests/test_core/test_code_scanner/test_schema.py b/tests/test_core/test_code_scanner/test_schema.pynew file mode 100644index 00000000..e518f142--- /dev/null+++ b/tests/test_core/test_code_scanner/test_schema.py@@ -0,0 +1,56 @@+import pytest+from pydantic import ValidationError++from deepteam.code_scanner import CodeChunk, CodeFinding, CodeFindingsList+++class TestSchema:+ def test_code_finding_minimal(self):+ f = CodeFinding(+ filePath="a.py",+ lineStart=1,+ vulnerability="SSRF",+ vulnerabilityType="port_scanning",+ severity="high",+ reason="x",+ )+ assert f.filePath == "a.py"+ assert f.severity == "high"+ # Optional fields default to None and drop from an exclude_none dump.+ assert f.recommendation is None+ assert "recommendation" not in f.model_dump(exclude_none=True)++ def test_code_finding_full_roundtrip(self):+ f = CodeFinding(+ filePath="a.py",+ lineStart=1,+ lineEnd=3,+ vulnerability="Unexpected Code Execution",+ vulnerabilityType="eval_usage",+ severity="critical",+ reason="x",+ recommendation="y",+ codeSnippet="eval(z)",+ )+ d = f.model_dump(exclude_none=True)+ assert d["lineEnd"] == 3+ assert d["codeSnippet"] == "eval(z)"++ def test_invalid_severity_rejected(self):+ with pytest.raises(ValidationError):+ CodeFinding(+ filePath="a.py",+ lineStart=1,+ vulnerability="SSRF",+ vulnerabilityType="port_scanning",+ severity="extreme",+ reason="x",+ )++ def test_findings_list(self):+ assert CodeFindingsList(findings=[]).findings == []++ def test_code_chunk_defaults(self):+ c = CodeChunk(file_path="a.py", content="x=1")+ assert c.start_line == 1+ assert c.language is Nonediff --git a/tests/test_core/test_code_scanner/test_smoke.py b/tests/test_core/test_code_scanner/test_smoke.pynew file mode 100644index 00000000..2e65797b--- /dev/null+++ b/tests/test_core/test_code_scanner/test_smoke.py@@ -0,0 +1,15 @@+import pytest++from deepteam.code_scanner import CodeScanner, collect_files++# Real-LLM smoke test. Excluded by default (pyproject: addopts = -m 'not+# skip_test'). Run explicitly with: pytest -m skip_test (needs OPENAI_API_KEY).++[email protected]_test+def test_real_scan_flags_eval(tmp_path):+ (tmp_path / "agent.py").write_text(+ "def run(resp):\n return eval(resp)\n"+ )+ findings = CodeScanner(model="gpt-4o").scan(collect_files(str(tmp_path)))+ assert any(f.vulnerability == "Unexpected Code Execution" for f in findings)diff --git a/tests/test_core/test_code_scanner/test_taxonomy.py b/tests/test_core/test_code_scanner/test_taxonomy.pynew file mode 100644index 00000000..fcda179d--- /dev/null+++ b/tests/test_core/test_code_scanner/test_taxonomy.py@@ -0,0 +1,31 @@+from deepteam.code_scanner import (+ KNOWN_VULNERABILITIES,+ allowed_types,+ is_known,+ vulnerability_names,+)+from deepteam.code_scanner.taxonomy import to_name+from deepteam.vulnerabilities import SSRF+++class TestTaxonomy:+ def test_known_populated(self):+ assert len(KNOWN_VULNERABILITIES) > 0+ assert "SSRF" in KNOWN_VULNERABILITIES++ def test_allowed_types(self):+ assert "port_scanning" in allowed_types("SSRF")+ assert allowed_types("Does Not Exist") == []++ def test_is_known(self):+ assert is_known("SSRF")+ assert is_known("SSRF", "port_scanning")+ assert not is_known("SSRF", "made_up")+ assert not is_known("Does Not Exist")++ def test_to_name_accepts_class_or_string(self):+ assert to_name(SSRF) == "SSRF"+ assert to_name("SSRF") == "SSRF"++ def test_vulnerability_names(self):+ assert "SSRF" in vulnerability_names()diff --git a/tests/test_core/test_code_scanner/test_template.py b/tests/test_core/test_code_scanner/test_template.pynew file mode 100644index 00000000..6429ce40--- /dev/null+++ b/tests/test_core/test_code_scanner/test_template.py@@ -0,0 +1,50 @@+from deepteam.code_scanner import (+ DEFAULT_CODE_SCAN_VULNERABILITIES,+ CodeScanTemplate,+)+from deepteam.vulnerabilities import SSRF, BaseVulnerability+++def _catalog(prompt: str) -> str:+ return prompt.split("VULNERABILITIES TO LOOK FOR")[1].split(+ "WHAT TO FOCUS ON"+ )[0]+++class TestTemplate:+ def test_default_catalog_renders_known_types(self):+ p = CodeScanTemplate.generate_code_batch_evaluation(batch_data="[]")+ assert "Unexpected Code Execution: unauthorized_code_execution" in p+ assert "Prompt Leakage: secrets_and_credentials" in p++ def test_default_vulns_are_classes(self):+ assert all(+ isinstance(v, type) and issubclass(v, BaseVulnerability)+ for v in DEFAULT_CODE_SCAN_VULNERABILITIES+ )++ def test_subset_scoping_class_and_string(self):+ for vulns in ([SSRF], ["SSRF"]):+ p = CodeScanTemplate.generate_code_batch_evaluation(+ batch_data="[]", vulnerabilities=vulns+ )+ catalog = _catalog(p)+ assert "SSRF: internal_service_access" in catalog+ assert "Unexpected Code Execution:" not in catalog++ def test_instruction_injected(self):+ p = CodeScanTemplate.generate_code_batch_evaluation(+ batch_data="[]", instruction="Treat secrets as critical."+ )+ assert "ADDITIONAL PROJECT INSTRUCTION" in p+ assert "Treat secrets as critical." in p++ def test_no_instruction_no_block(self):+ p = CodeScanTemplate.generate_code_batch_evaluation(batch_data="[]")+ assert "ADDITIONAL PROJECT INSTRUCTION" not in p++ def test_batch_data_embedded(self):+ p = CodeScanTemplate.generate_code_batch_evaluation(+ batch_data='[{"x":1}]'+ )+ assert '[{"x":1}]' in p