File size: 7,471 Bytes
1340dfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
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