import json from pathlib import Path import subprocess import sys import pytest from scripts.generate_dataset import build_dataset, write_dataset from scripts.validate_dataset import DATA_PATH, DatasetError, validate def test_validation_logs_redact_environment_and_preserve_results(monkeypatch): from scripts.generate_dataset import SOURCE_PATH, sanitize_log_output monkeypatch.setattr('getpass.getuser', lambda: 'fixture-person') text = ('Current: ' + str(SOURCE_PATH.parents[1] / 'data' / 'examples.jsonl') + '\nfixture-person ' + 'Z:' + '\\private\\file.txt' + ' /private/work/file.txt fixture@example.invalid\n65 passed; exit_code=0') clean = sanitize_log_output(text) assert 'fixture-person' not in clean and 'fixture@example.invalid' not in clean assert 'Z:' not in clean and '/private/' not in clean assert 'Current: data' in clean and '65 passed; exit_code=0' in clean @pytest.fixture def rows(): return [json.loads(line) for line in DATA_PATH.read_text(encoding="utf-8").splitlines()] def write_rows(path, rows): path.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8") def run_script(name, *args, cwd): script = Path(__file__).resolve().parents[1] / "scripts" / name return subprocess.run( [sys.executable, str(script), *map(str, args)], cwd=cwd, capture_output=True, text=True, check=False, ) def test_committed_dataset_is_balanced_and_current(): summary = validate(DATA_PATH) assert summary.rows == 64 assert summary.patterns == 32 assert summary.cwes == 16 assert summary.labels == {"secure": 32, "insecure": 32} assert build_dataset() == DATA_PATH.read_bytes() def test_regeneration_is_deterministic_and_creates_output_directory(tmp_path): output = tmp_path / "nested" / "generated.jsonl" expected = DATA_PATH.read_bytes() write_dataset(output, build_dataset()) assert output.read_bytes() == expected output.write_bytes(b"stale") write_dataset(output, build_dataset()) assert output.read_bytes() == expected @pytest.mark.parametrize( ("manifest", "message"), [("pair = 1\n", r"only \[\[pair"), ("[[pair]]\npattern = 42\n", "pair 1")], ) def test_rejects_malformed_curation_manifest(tmp_path, manifest, message): source = tmp_path / "pairs.toml" source.write_text(manifest, encoding="utf-8") with pytest.raises(ValueError, match=message): build_dataset(source) def test_failed_write_cleans_temporary_file(tmp_path): output = tmp_path / "conflicting-directory" output.mkdir() with pytest.raises(OSError): write_dataset(output, b"example") assert list(tmp_path.iterdir()) == [output] @pytest.mark.parametrize( ("field", "value", "message"), [ ("label", "safe", "unknown label"), ("id", "bad-id", "invalid id"), ("pattern", "Invalid Pattern", "invalid pattern"), ("cwe_id", "CWE-000", "unsupported CWE"), ("source_type", "real", "source_type must be synthetic"), ("explanation", " ", "non-empty string"), ("secure_fix", 123, "non-empty string"), ("code", "def broken(:\n", "invalid Python syntax"), ("code", "return 1\n", "invalid Python syntax"), ("code", "# Only a comment\n", "no Python statements"), ], ) def test_rejects_invalid_fields(tmp_path, rows, field, value, message): rows[0][field] = value path = tmp_path / "invalid.jsonl" write_rows(path, rows) with pytest.raises(DatasetError, match=message): validate(path) def test_rejects_missing_and_unexpected_fields(tmp_path, rows): rows[0]["extra"] = rows[0].pop("explanation") path = tmp_path / "invalid.jsonl" write_rows(path, rows) with pytest.raises(DatasetError, match=r"missing=\['explanation'\].*unexpected=\['extra'\]"): validate(path) @pytest.mark.parametrize( ("line", "message"), [ ("\n", "blank record"), ("{\n", "invalid JSON"), ("[]\n", "expected a JSON object"), ('{"id": "one", "id": "two"}\n', "duplicate JSON key"), ], ) def test_rejects_invalid_jsonl_records(tmp_path, line, message): path = tmp_path / "invalid.jsonl" path.write_text(line, encoding="utf-8") with pytest.raises(DatasetError, match=f"line 1: .*{message}"): validate(path) def test_rejects_duplicate_ids(tmp_path, rows): rows[1]["id"] = rows[0]["id"] path = tmp_path / "duplicate.jsonl" write_rows(path, rows) with pytest.raises(DatasetError, match="duplicate id"): validate(path) def test_rejects_code_repeated_with_different_formatting(tmp_path, rows): rows[1]["code"] = "# Different formatting\n\n" + rows[0]["code"] + "\n" path = tmp_path / "duplicate.jsonl" write_rows(path, rows) with pytest.raises(DatasetError, match="duplicate code"): validate(path) def test_rejects_incomplete_pairs(tmp_path, rows): rows.pop() path = tmp_path / "unpaired.jsonl" write_rows(path, rows) with pytest.raises(DatasetError, match="one secure and one insecure"): validate(path) @pytest.mark.parametrize(("field", "value"), [ ("cwe_id", "CWE-89"), ("secure_fix", "Unrelated remediation."), ]) def test_rejects_disagreement_within_a_pair(tmp_path, rows, field, value): row = next(row for row in rows if row["cwe_id"] != value) row[field] = value path = tmp_path / "mismatch.jsonl" write_rows(path, rows) with pytest.raises(DatasetError, match=f"pair disagrees on {field}"): validate(path) def test_rejects_a_corpus_below_sixty_rows(tmp_path, rows): path = tmp_path / "small.jsonl" write_rows(path, rows[:59]) with pytest.raises(DatasetError, match="at least 60"): validate(path) def test_rejects_missing_cwe_coverage(tmp_path, rows): path = tmp_path / "missing-cwe.jsonl" write_rows(path, [row for row in rows if row["cwe_id"] != "CWE-22"]) with pytest.raises(DatasetError, match="CWE-22 needs at least two pairs"): validate(path) def test_generation_cli_detects_missing_and_stale_output(tmp_path): output = tmp_path / "generated.jsonl" generated = run_script("generate_dataset.py", "--output", output, cwd=tmp_path) assert generated.returncode == 0, generated.stderr assert output.read_bytes() == DATA_PATH.read_bytes() current = run_script("generate_dataset.py", "--check", "--output", output, cwd=tmp_path) assert current.returncode == 0, current.stderr output.write_bytes(b"stale\n") stale = run_script("generate_dataset.py", "--check", "--output", output, cwd=tmp_path) assert stale.returncode == 1 assert "stale" in stale.stderr assert output.read_bytes() == b"stale\n" output.unlink() missing = run_script("generate_dataset.py", "--check", "--output", output, cwd=tmp_path) assert missing.returncode == 1 assert "missing" in missing.stderr def test_validation_cli_supports_other_working_directories_and_reports_errors(tmp_path): result = run_script("validate_dataset.py", cwd=tmp_path) assert result.returncode == 0, result.stderr assert "64 rows" in result.stdout assert "SHA-256" in result.stdout bad_data = tmp_path / "broken.jsonl" bad_data.write_bytes(b"\xff") result = run_script("validate_dataset.py", bad_data, cwd=tmp_path) assert result.returncode == 1 assert "UTF-8" in result.stderr