File size: 4,096 Bytes
b3991a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Harvest the dev split of canary-eval from the Canary test suite.

Only checker calls whose verdict is explicitly asserted by a test are kept
(`self.assertEqual(check(...)["result"], expected)`), and the label is that asserted
expectation - never the engine's own output. Run from the repository root:

    python hf/dataset/scripts/harvest_dev.py hf/dataset/data/dev.jsonl
"""
import copy
import json
import re
import sys
import unittest

sys.path.insert(0, ".")
import logging  # noqa: E402


def main() -> None:
    """Runs the test suite with recording hooks and writes the asserted cases (the regex worker re-imports this module, so nothing may run at import time)."""
    logging.disable(logging.CRITICAL)
    import test_app

    JA = re.compile(r"[぀-ヿ㐀-鿿]")
    records: list[dict] = []
    current_test = {"name": ""}


    class Tagged(str):
        """A verdict string that remembers which recorded call produced it."""


    class Rec(dict):
        def __getitem__(self, key):
            value = dict.__getitem__(self, key)
            if key == "result" and isinstance(value, str):
                tagged = Tagged(value)
                tagged.rec = self.rec  # type: ignore[attr-defined]
                return tagged
            return value


    original_check = test_app.check


    def recording_check(c, output, case=None, samples=None):
        res = original_check(c, output, case, samples)
        rec = {"test": current_test["name"], "contract": copy.deepcopy(c), "output": copy.deepcopy(output),
               "case": copy.deepcopy(case or {}), "samples": copy.deepcopy(samples), "label": None}
        records.append(rec)
        out = Rec(res)
        out.rec = rec
        return out


    test_app.check = recording_check
    original_assert_equal = unittest.TestCase.assertEqual


    def recording_assert_equal(self, first, second, msg=None):
        if isinstance(first, Tagged) and isinstance(second, str) and second in ("pass", "fail", "skipped", "error"):
            first.rec["label"] = second
        return original_assert_equal(self, first, second, msg)


    unittest.TestCase.assertEqual = recording_assert_equal


    class Tracker(unittest.TextTestResult):
        def startTest(self, test):
            current_test["name"] = test.id().split(".", 1)[1]
            super().startTest(test)


    suite = unittest.defaultTestLoader.loadTestsFromModule(test_app)
    result = unittest.TextTestRunner(resultclass=Tracker, verbosity=0, stream=open("/dev/null", "w")).run(suite)
    assert result.wasSuccessful(), "the test suite must pass before harvesting"

    SKIP_TESTS = ("TestPerformance", "test_whitespace_heavy", "TestNeverRaises", "regex_guard", "regex_worker", "timeouts_do_not")
    seen = set()
    rows = []
    for r in records:
        if r["label"] not in ("pass", "fail", "skipped") or any(s in r["test"] for s in SKIP_TESTS):
            continue
        contract = r["contract"]
        output = r["samples"] if r["samples"] else r["output"]
        key = json.dumps([contract, output, r["case"]], sort_keys=True, ensure_ascii=False)
        if key in seen:
            continue
        seen.add(key)
        text = json.dumps([output, r["case"]], ensure_ascii=False)
        rows.append({
            "id": f"dev-{len(rows) + 1:04d}",
            "contract_type": contract["type"],
            "contract": {k: v for k, v in contract.items() if k not in ("id", "severity")},
            "output": output,
            "case": r["case"],
            "label": r["label"],
            "lang": "ja" if JA.search(text) else "en",
            "source": "test_app.py::" + r["test"],
        })
    with open(sys.argv[1], "w", encoding="utf-8") as fh:
        for row in rows:
            fh.write(json.dumps(row, ensure_ascii=False) + "\n")
    by_type = {}
    for row in rows:
        by_type.setdefault(row["contract_type"], {"pass": 0, "fail": 0, "skipped": 0})[row["label"]] += 1
    print(len(rows), "dev cases")
    for t, c in sorted(by_type.items()):
        print(f"  {t:18s} {c}")


if __name__ == "__main__":
    main()