Download tests/test_research.py from Helinity/python-security-benchmark: direct link, hf CLI and curl.
- Browser
- Download file 10.6 kB
-
https://huggingface.co/datasets/Helinity/python-security-benchmark/resolve/main/tests/test_research.py
- Command line
-
hf download hf://datasets/Helinity/python-security-benchmark/tests/test_research.py
-
curl -L -o test_research.py https://huggingface.co/datasets/Helinity/python-security-benchmark/resolve/main/tests/test_research.py
10.6 kB
| from copy import deepcopy | |
| from hashlib import sha256 | |
| import json | |
| import pytest | |
| from research.build import OUTPUT, compare_release, release | |
| from research.catalog import BASELINE_SHA256, build_records, legacy_rows, validate_rows | |
| from research.evaluate import evaluate, lexical_baseline | |
| from research.leakage import grouped_assignments, similarity, validate_split_boundaries | |
| from research.verification_cases import verify_lock | |
| from research.verify import run_verification | |
| def evidence(): | |
| return run_verification() | |
| def built(evidence): | |
| return release(evidence) | |
| def split_rows(files, configuration, split): | |
| return [json.loads(line) for line in files[f"{configuration}/{split}.jsonl"].splitlines()] | |
| def test_research_release_is_reproducible_and_preserves_legacy(built): | |
| files, stats = built | |
| compare_release(files) | |
| originals = legacy_rows() | |
| research = { | |
| (row["pattern"], row["label"]): row | |
| for split in ("train", "validation", "test") for row in split_rows(files, "corpus", split) | |
| } | |
| assert len(originals) == 64 | |
| assert stats["baseline_sha256"] == BASELINE_SHA256 | |
| assert all({field: research[key][field] for field in legacy} == legacy for key, legacy in originals.items()) | |
| assert stats["corpus"]["samples"] == len(research) == 84 | |
| assert stats["benchmark"]["samples"] == 60 | |
| assert stats["benchmark"]["pairs"] == 24 | |
| assert stats["benchmark"]["hard_negatives"] == 12 | |
| assert len({row["cwe_id"] for row in research.values() if row["pair_id"] and row["evidence_reference"]}) >= 5 | |
| def test_verified_files_are_exact_subset_and_legacy_exclusions_are_explicit(built): | |
| files, _ = built | |
| full = [] | |
| for split in ("train", "validation", "test"): | |
| rows = split_rows(files, "corpus", split) | |
| subset = split_rows(files, "benchmark", split) | |
| assert subset == [row for row in rows if row["verification_status"] == "behavior_verified"] | |
| full.extend(rows) | |
| by_pattern = {(row["pattern"], row["label"]): row for row in full} | |
| traversal_fix = by_pattern["report-file-containment", "secure"] | |
| assert traversal_fix["verification_status"] == "ambiguous" | |
| assert traversal_fix["evidence_reference"] is None | |
| command = by_pattern["line-counter-process-arguments", "insecure"] | |
| assert command["verification_status"] == "unverified" | |
| assert command["verification_method"] is None | |
| secret_removed = by_pattern["reset-token-log-minimization", "secure"] | |
| assert secret_removed["source_location"] is None | |
| assert secret_removed["taint_path"] is None | |
| def test_evidence_observes_contrast_and_normal_function(evidence): | |
| cases = evidence["cases"] | |
| assert len(cases) == 36 | |
| archive = cases["project-archive-permission"]["observations"] | |
| assert archive["insecure"] == {"status": 204, "archive_calls": 1} | |
| assert archive["secure"] == {"status": 403, "archive_calls": 0} | |
| assert archive["normal"] == {"anonymous_status": 401, "maintainer_status": 204} | |
| assert cases["approved-dashboard-sort"]["observations"]["unknown_sort_reaches_database"] is False | |
| assert cases["local-value-roundtrip"]["observations"]["pickle_decoded"] is False | |
| assert cases["internal-shell-status"]["observations"]["process_started"] is False | |
| def test_generation_rejects_missing_and_incomplete_evidence(evidence): | |
| altered = deepcopy(evidence) | |
| altered["cases"].pop("moderation-note-log-framing") | |
| with pytest.raises(ValueError, match="missing executable evidence"): | |
| build_records(altered) | |
| altered = deepcopy(evidence) | |
| altered["cases"]["moderation-note-log-framing"]["observations"].pop("normal") | |
| with pytest.raises(ValueError, match="invalid evidence"): | |
| build_records(altered) | |
| altered["suite_sha256"] = "0" * 64 | |
| with pytest.raises(ValueError, match="different verifier or fixture sources"): | |
| build_records(altered) | |
| def test_validator_rejects_wrong_locations_and_unbacked_verified_records(built, evidence): | |
| files, _ = built | |
| rows = split_rows(files, "benchmark", "test") | |
| row = next(row for row in rows if row["expected_finding"]) | |
| row["vulnerable_lines"][0]["end_line"] = 1000 | |
| with pytest.raises(ValueError, match="outside its source file"): | |
| validate_rows(rows, evidence) | |
| rows = split_rows(files, "benchmark", "test") | |
| rows[0]["evidence_reference"] = None | |
| with pytest.raises(ValueError, match="lacks matching executable evidence"): | |
| validate_rows(rows, evidence) | |
| def test_fixture_lock_fails_closed_on_changed_or_unreviewed_programs(tmp_path): | |
| root = tmp_path / "fixture-root" | |
| root.mkdir() | |
| subject = root / "subject.py" | |
| source = b"def call():\n return 1\n" | |
| subject.write_bytes(source) | |
| lock = tmp_path / "lock.json" | |
| lock.write_text(json.dumps({"subject.py": sha256(source).hexdigest()}), encoding="utf-8") | |
| verify_lock(root, lock) | |
| subject.write_bytes(b"raise AssertionError('should not be imported')\n") | |
| with pytest.raises(ValueError, match="source lock differs"): | |
| verify_lock(root, lock) | |
| subject.write_bytes(source) | |
| (root / "subject.pyd").touch() | |
| with pytest.raises(ValueError, match="Unexpected non-source file"): | |
| verify_lock(root, lock) | |
| def candidate(sample_id, family, code): | |
| return { | |
| "sample_id": sample_id, "scenario_family_id": family, "pair_id": None, | |
| "code_files": [{"path": "snippet.py", "code": code}], | |
| } | |
| def test_detects_exact_and_renamed_variants_and_protects_their_boundaries(): | |
| first = candidate("first", "one", "def read(path):\n data = path.read_text()\n return data.strip()\n") | |
| duplicate = candidate("dup", "two", "# note\n" + first["code_files"][0]["code"]) | |
| duplicates = similarity([first, duplicate]) | |
| assert duplicates["exact_text"] == [] | |
| assert duplicates["exact_ast"] == [["dup", "first"]] | |
| with pytest.raises(ValueError, match="duplicate"): | |
| grouped_assignments([first, duplicate], duplicates) | |
| renamed = candidate("rename", "two", "def fetch(record):\n value = record.read_text()\n return value.strip()\n") | |
| rows = [ | |
| first, renamed, | |
| candidate("three", "other", "def compare(value):\n return value > 0 and value % 6 == 0\n"), | |
| candidate("four", "another", "def repeat(count):\n return [0] * count\n"), | |
| ] | |
| report = similarity(rows) | |
| assert report["near_matches"] == [ | |
| {"left": "first", "right": "rename", "normalized_ast_match": True, "token_jaccard": 1.0}, | |
| ] | |
| assignments, _ = grouped_assignments(rows, report) | |
| assert assignments["first"] == assignments["rename"] | |
| for row in rows: | |
| row["split"], row["leakage_group_id"] = assignments[row["sample_id"]] | |
| validate_split_boundaries(rows, report) | |
| renamed["split"] = "test" if first["split"] != "test" else "train" | |
| renamed["leakage_group_id"] = "tampered" | |
| with pytest.raises(ValueError, match="Near-duplicate crosses splits"): | |
| validate_split_boundaries(rows, report) | |
| def test_multi_file_ground_truth_uses_real_module_paths(built): | |
| files, _ = built | |
| rows = [ | |
| row for split in ("train", "validation", "test") | |
| for row in split_rows(files, "benchmark", split) | |
| ] | |
| row = next(row for row in rows if row["pattern"] == "helpdesk-transcript-renderer" and row["expected_finding"]) | |
| assert row["source_location"]["path"] == "subject.py" | |
| assert row["vulnerable_lines"][0]["path"] == "fragments.py" | |
| assert "# file: fragments.py" in row["code"] | |
| def example(sample_id, pair_id, label, cwe="CWE-79"): | |
| return { | |
| "sample_id": sample_id, "pair_id": pair_id, "label": label, "cwe_id": cwe, | |
| "hard_negative": pair_id is None, "verification_status": "behavior_verified", | |
| "vulnerable_lines": [{"path": "fragments.py", "start_line": 2, "end_line": 3}] if label == "insecure" else [], | |
| } | |
| def test_scores_errors_and_handles_nonmatching_locations(): | |
| rows = [ | |
| example("bad", "pair-a", "insecure"), | |
| example("good", "pair-a", "secure"), | |
| example("other-bad", "pair-b", "insecure"), | |
| example("other-good", "pair-b", "secure"), | |
| example("hard-negative", None, "secure", "CWE-78"), | |
| ] | |
| document = {"findings": [ | |
| {"sample_id": "bad", "cwe_id": "CWE-79", "path": "fragments.py", "line": 3}, | |
| {"sample_id": "other-bad", "cwe_id": "CWE-79", "path": "subject.py", "line": 3}, | |
| {"sample_id": "hard-negative", "cwe_id": "CWE-78"}, | |
| {"sample_id": "other-good", "cwe_id": "CWE-89"}, | |
| ]} | |
| report = evaluate(rows, document, match_location=True) | |
| overall = report["overall"] | |
| assert overall["confusion"] == {"tp": 1, "tn": 2, "fp": 1, "fn": 1} | |
| assert overall["precision"] == overall["recall"] == overall["f1"] == 0.5 | |
| assert overall["balanced_accuracy"] == pytest.approx(7 / 12) | |
| assert overall["false_positive_rate"] == pytest.approx(1 / 3) | |
| assert overall["false_negative_rate"] == 0.5 | |
| assert report["per_cwe"]["CWE-78"]["recall"] is None | |
| assert report["paired_consistency"]["both_correct_rate"] == 0.5 | |
| assert report["hard_negatives"]["false_positives"] == 1 | |
| assert {row["sample_id"] for row in report["errors"]} == {"other-bad", "hard-negative"} | |
| assert {item["reason"] for item in report["ignored_findings"]} == { | |
| "out_of_scope_cwe", "missing_or_nonmatching_location", | |
| } | |
| assert evaluate(rows, document)["overall"]["confusion"]["tp"] == 2 | |
| def test_rejects_invalid_prediction_inputs(document, phrase): | |
| with pytest.raises(ValueError, match=phrase): | |
| evaluate([example("sample", None, "secure")], document) | |
| def test_stored_demo_matches_fresh_research_scoring(built): | |
| files, _ = built | |
| ground_truth = files["benchmark/test.jsonl"] | |
| rows = split_rows(files, "benchmark", "test") | |
| expected = { | |
| "scope": "benchmark", "split": "test", "baseline": "lexical_keywords_v1", | |
| "ground_truth_sha256": sha256(ground_truth).hexdigest(), | |
| **evaluate(rows, lexical_baseline(rows)), | |
| } | |
| assert json.loads((OUTPUT / "baseline-test.json").read_bytes()) == expected | |