ctokx commited on
Commit
db268d9
·
verified ·
1 Parent(s): 0f27fb6

Add tests/

Browse files
Files changed (2) hide show
  1. tests/test_data.py +116 -0
  2. tests/test_smoke.py +95 -0
tests/test_data.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Invariants the dataset must satisfy. These are the claims the cards make."""
2
+
3
+ import json
4
+ import sys
5
+ from collections import Counter
6
+ from pathlib import Path
7
+
8
+ import pytest
9
+
10
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
11
+
12
+ from cti_attack import config, data # noqa: E402
13
+
14
+ SCHEMES = ("document", "random")
15
+ SPLITS = ("train", "dev", "test")
16
+
17
+
18
+ def _built() -> bool:
19
+ return (config.BUILD_DIR / "labels.json").exists()
20
+
21
+
22
+ pytestmark = pytest.mark.skipif(
23
+ not _built(), reason="run scripts/01_build_dataset.py first")
24
+
25
+
26
+ @pytest.fixture(scope="module")
27
+ def labels():
28
+ return data.load_labels()
29
+
30
+
31
+ @pytest.fixture(scope="module")
32
+ def splits():
33
+ return {(s, p): data.load_split(s, p) for s in SCHEMES for p in SPLITS}
34
+
35
+
36
+ def test_no_document_spans_splits(splits):
37
+ """The core claim of the document split: no report appears in two splits."""
38
+ docs = {p: {r["doc_title"] for r in splits[("document", p)]} for p in SPLITS}
39
+ assert not docs["train"] & docs["dev"]
40
+ assert not docs["train"] & docs["test"]
41
+ assert not docs["dev"] & docs["test"]
42
+
43
+
44
+ def test_random_split_does_leak_documents(splits):
45
+ """The contrast case. If this ever passes cleanly the comparison is void."""
46
+ docs = {p: {r["doc_title"] for r in splits[("random", p)]} for p in SPLITS}
47
+ assert docs["train"] & docs["test"], "random split unexpectedly document-clean"
48
+
49
+
50
+ def test_every_technique_appears_in_every_document_split(splits, labels):
51
+ for p in SPLITS:
52
+ seen = {l for r in splits[("document", p)] for l in r["labels"]}
53
+ missing = set(labels) - seen
54
+ assert not missing, f"{p} is missing {sorted(missing)}"
55
+
56
+
57
+ def test_no_duplicate_sentences_within_scheme(splits):
58
+ for scheme in SCHEMES:
59
+ keys = [data.dedup_key(r["sentence"])
60
+ for p in SPLITS for r in splits[(scheme, p)]]
61
+ dupes = [k for k, c in Counter(keys).items() if c > 1]
62
+ assert not dupes, f"{scheme}: {len(dupes)} duplicate sentences survived"
63
+
64
+
65
+ def test_dropped_technique_is_absent(splits, labels):
66
+ stats = json.loads((config.BUILD_DIR / "build_stats.json").read_text(encoding="utf-8"))
67
+ assert "T1557.001" in stats["dropped_techniques"]
68
+ assert "T1557.001" not in labels
69
+ for key, rows in splits.items():
70
+ assert not any("T1557.001" in r["labels"] for r in rows), key
71
+
72
+
73
+ def test_label_count_matches_card(labels):
74
+ assert len(labels) == 49
75
+
76
+
77
+ def test_boilerplate_is_stripped(splits):
78
+ for rows in splits.values():
79
+ assert not any(r["sentence"].lower().startswith("title:") for r in rows)
80
+
81
+
82
+ def test_clean_sentence_removes_header():
83
+ raw = "title: Some Report url: https://example.com/x The dropper decodes its payload."
84
+ assert data.clean_sentence(raw) == "The dropper decodes its payload."
85
+
86
+
87
+ def test_dataset_card_numbers_match_the_build(splits):
88
+ """The dataset card must describe the dataset that actually exists.
89
+
90
+ Added after the card was written from a pre-rebuild build and silently
91
+ drifted by one or two rows on six different figures.
92
+ """
93
+ card = (config.REPO_ROOT / "DATASET_CARD.md").read_text(encoding="utf-8")
94
+ stats = json.loads((config.BUILD_DIR / "build_stats.json").read_text(encoding="utf-8"))
95
+
96
+ for key in ("final_sentences", "final_labelled", "duplicates_removed",
97
+ "duplicate_groups", "cross_document_duplicates"):
98
+ value = stats[key]
99
+ assert f"{value:,}" in card or str(value) in card, \
100
+ f"DATASET_CARD.md does not mention {key}={value}"
101
+
102
+ for (scheme, split), rows in splits.items():
103
+ n, labelled = len(rows), sum(1 for r in rows if r["labels"])
104
+ assert f"{n:,}" in card, f"card missing {scheme}/{split} size {n:,}"
105
+ assert f"{labelled:,}" in card, f"card missing {scheme}/{split} labelled {labelled:,}"
106
+
107
+
108
+ def test_dedup_merges_labels():
109
+ stats = data.BuildStats()
110
+ out = data.dedupe([
111
+ {"sentence": "It decodes the payload.", "labels": ["T1027"], "doc_title": "a"},
112
+ {"sentence": "It decodes the payload!", "labels": ["T1140"], "doc_title": "b"},
113
+ ], stats)
114
+ assert len(out) == 1
115
+ assert out[0]["labels"] == ["T1027", "T1140"]
116
+ assert stats.cross_document_duplicates == 1
tests/test_smoke.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """End-to-end smoke test: load the model and run real threat prose through it.
2
+
3
+ This is the test that stops the repo from shipping a checkpoint nobody ran. It
4
+ does not assert accuracy — it asserts the artifact loads, produces
5
+ well-formed output, and is wired to its thresholds and label set correctly.
6
+
7
+ pytest tests/test_smoke.py -v
8
+
9
+ Point it at a published model instead of a local one with:
10
+
11
+ CTI_MODEL_DIR=your-username/cti-attack-mapper-modernbert pytest tests/test_smoke.py
12
+ """
13
+
14
+ import os
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ import pytest
19
+
20
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
21
+
22
+ from cti_attack import config # noqa: E402
23
+
24
+ MODEL_DIR = os.environ.get(
25
+ "CTI_MODEL_DIR", str(config.MODELS_DIR / "modernbert__document"))
26
+
27
+ # Real sentences in the style of the training corpus, each with an ATT&CK
28
+ # technique a analyst would expect to see fire.
29
+ SAMPLES = [
30
+ "The dropper base64-encodes its configuration blob before writing it to disk.",
31
+ "It then executes the payload through cmd.exe using a batch script.",
32
+ "The implant establishes persistence by creating a scheduled task that runs at logon.",
33
+ "Credentials were harvested from the LSASS process memory.",
34
+ "The backdoor beacons to its command-and-control server over HTTPS.",
35
+ ]
36
+
37
+
38
+ def _available() -> bool:
39
+ p = Path(MODEL_DIR)
40
+ return p.exists() or "/" in MODEL_DIR
41
+
42
+
43
+ pytestmark = pytest.mark.skipif(
44
+ not _available(),
45
+ reason=f"no model at {MODEL_DIR}; run scripts/03_train.py first")
46
+
47
+
48
+ @pytest.fixture(scope="module")
49
+ def mapper():
50
+ from cti_attack.predict import AttackMapper
51
+ return AttackMapper(MODEL_DIR)
52
+
53
+
54
+ def test_model_loads_with_expected_label_space(mapper):
55
+ assert len(mapper.labels) == 49
56
+ assert all(l.startswith("T") for l in mapper.labels)
57
+ assert len(mapper.thresholds) == len(mapper.labels)
58
+
59
+
60
+ def test_single_prediction_is_well_formed(mapper):
61
+ preds = mapper.predict(SAMPLES[0])
62
+ assert isinstance(preds, list)
63
+ for p in preds:
64
+ assert p.technique_id in mapper.labels
65
+ assert 0.0 <= p.score <= 1.0
66
+ assert isinstance(p.name, str) and p.name
67
+
68
+
69
+ def test_batch_matches_single(mapper):
70
+ batch = mapper.predict_batch(SAMPLES)
71
+ assert len(batch) == len(SAMPLES)
72
+ single = mapper.predict(SAMPLES[2])
73
+ assert [p.technique_id for p in batch[2]] == [p.technique_id for p in single]
74
+
75
+
76
+ def test_predictions_are_sorted_by_confidence(mapper):
77
+ for preds in mapper.predict_batch(SAMPLES):
78
+ scores = [p.score for p in preds]
79
+ assert scores == sorted(scores, reverse=True)
80
+
81
+
82
+ def test_model_fires_on_at_least_some_clear_cases(mapper):
83
+ """Not an accuracy claim — a wiring check.
84
+
85
+ If a model trained to macro-F1 ~0.5 predicts nothing at all across five
86
+ textbook sentences, the thresholds or label mapping are broken.
87
+ """
88
+ total = sum(len(p) for p in mapper.predict_batch(SAMPLES))
89
+ assert total > 0, "model produced no predictions on any sample sentence"
90
+
91
+
92
+ def test_empty_and_odd_input_do_not_crash(mapper):
93
+ assert mapper.predict_batch([]) == []
94
+ assert isinstance(mapper.predict(""), list)
95
+ assert isinstance(mapper.predict("x" * 5000), list)