File size: 12,987 Bytes
e042d72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
"""Build the bug catalog for Five Desks Code: single-token mutants of real libraries that their own tests detect.

Runs inside the builder container (no network), never on the host:

    docker run --rm --network none -v $PWD/sdists:/sdists:ro -v $PWD/out:/out -v $PWD:/build:ro \
        codedesk-builder python /build/catalog.py [--per-lib 80]

For each library: run its test suite once (baseline), enumerate mutation sites inside function bodies (comparison,
arithmetic, boolean and constant changes), apply each one alone, run the tests again and keep mutants that 1 to 8
previously passing tests catch. Writes /out/<lib>/ (the pristine source tree) and /out/catalog.json.
"""

import argparse
import ast
import io
import json
import os
import random
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
import tokenize
import xml.etree.ElementTree as ET
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

# name: (sdist stem, package path inside the sdist, tests path, domain, test runner timeout s)
LIBS = {
    "croniter": ("croniter-6.2.4", "src/croniter", "src/croniter/tests", "office-white-collar", 120),
    "isodate": ("isodate-0.7.2", "src/isodate", "tests", "office-white-collar", 60),
    "humanize": ("humanize-4.16.0", "src/humanize", "tests", "office-white-collar", 60),
    "numpy_financial": ("numpy-financial-1.0.0", "numpy_financial", "numpy_financial/tests", "finance-economics", 60),
    "uncertainties": ("uncertainties-3.2.3", "uncertainties", "tests", "natural-science", 120),
    "simple_pid": ("simple_pid-2.0.1", "simple_pid", "tests", "industrial-physical-systems", 60),
    "srt": ("srt-3.5.3", "srt.py", "tests", "media-content-production", 180),
    "webvtt": ("webvtt-py-0.5.1", "webvtt", "tests", "media-content-production", 60),
    "slugify": ("python_slugify-9.1.3", "slugify", "tests", "media-content-production", 60),
    "itsdangerous": ("itsdangerous-2.2.0", "src/itsdangerous", "tests", "cybersecurity", 60),
    "jwt": ("pyjwt-2.15.1", "jwt", "tests", "cybersecurity", 60),
    "toolz": ("toolz-1.2.0", "toolz", "toolz/tests", "software-engineering", 60),
    "tabulate": ("tabulate-0.10.0", "tabulate", "test", "software-engineering", 60),
    "inflection": ("inflection-0.5.1", "inflection", "test_inflection.py", "software-engineering", 60),
    "more_itertools": ("more_itertools-11.1.0", "more_itertools", "tests", "mathematics-or-formal-reasoning", 240),
    "semver": ("semver-3.1.0", "src/semver", "tests", "software-engineering", 60),
    "fluids": ("fluids-1.3.1", "fluids", "tests", "industrial-physical-systems", 120),
}
# libraries whose catalog uses only some modules and the test files that cover them
SUBSET = {
    "fluids": {m: f"tests/test_{m}.py" for m in ["pump", "control_valve", "friction", "fittings", "core", "compressible",
                                                 "safety_valve", "piping", "flow_meter", "separator", "two_phase",
                                                 "open_flow", "jet_pump", "packed_bed", "drag", "mixing"]},
}

# tests that never finish on their own (real-time simulation); they are also removed from the shipped copies
DESELECT = ["--deselect", "tests/test_pid.py::test_converge_system"]

SWAPS = {ast.Lt: "<=", ast.LtE: "<", ast.Gt: ">=", ast.GtE: ">", ast.Eq: "!=", ast.NotEq: "==",
         ast.Add: "-", ast.Sub: "+", ast.Mult: "/", ast.Div: "*", ast.FloorDiv: "/", ast.Mod: "//",
         ast.And: "or", ast.Or: "and"}
OP_TEXT = {ast.Lt: "<", ast.LtE: "<=", ast.Gt: ">", ast.GtE: ">=", ast.Eq: "==", ast.NotEq: "!=", ast.Add: "+",
           ast.Sub: "-", ast.Mult: "*", ast.Div: "/", ast.FloorDiv: "//", ast.Mod: "%", ast.And: "and", ast.Or: "or"}


def sites(src: str):
    """Yield (line, col, old, new, kind, function) for single-token mutations inside function bodies."""
    tree = ast.parse(src)
    toks = [t for t in tokenize.generate_tokens(io.StringIO(src).readline) if t.type in (tokenize.OP, tokenize.NAME)]

    def token_between(a, b, text):
        for t in toks:
            if a <= t.start and t.end <= b and t.string == text:
                return t
        return None

    def walk(node, func):
        for child in ast.iter_child_nodes(node):
            name = child.name if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)) else func
            if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
                # skip decorators and defaults: mutate the body only
                for stmt in child.body:
                    if not (isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Constant)):  # docstrings
                        yield from walk_stmt(stmt, name)
                continue
            if isinstance(child, ast.ClassDef):
                yield from walk(child, func)

    def walk_stmt(stmt, func):
        for n in ast.walk(stmt):
            if isinstance(n, ast.Compare):
                left = n.left
                for op, right in zip(n.ops, n.comparators):
                    if type(op) in SWAPS:
                        t = token_between((left.end_lineno, left.end_col_offset), (right.lineno, right.col_offset),
                                          OP_TEXT[type(op)])
                        if t:
                            yield t.start[0], t.start[1], t.string, SWAPS[type(op)], "compare", func
                    left = right
            elif isinstance(n, ast.BinOp) and type(n.op) in SWAPS:
                if isinstance(n.left, ast.Constant) and isinstance(n.left.value, str):
                    continue  # string formatting with %, concatenation
                t = token_between((n.left.end_lineno, n.left.end_col_offset), (n.right.lineno, n.right.col_offset),
                                  OP_TEXT[type(n.op)])
                if t:
                    yield t.start[0], t.start[1], t.string, SWAPS[type(n.op)], "arith", func
            elif isinstance(n, ast.BoolOp) and type(n.op) in SWAPS:
                for a, b in zip(n.values, n.values[1:]):
                    t = token_between((a.end_lineno, a.end_col_offset), (b.lineno, b.col_offset), OP_TEXT[type(n.op)])
                    if t:
                        yield t.start[0], t.start[1], t.string, SWAPS[type(n.op)], "bool", func
            elif isinstance(n, ast.UnaryOp) and isinstance(n.op, ast.Not):
                yield n.lineno, n.col_offset, "not ", "", "not", func
            elif (isinstance(n, ast.Constant) and type(n.value) is int and 0 <= n.value <= 64
                  and n.end_lineno == n.lineno and n.end_col_offset - n.col_offset == len(str(n.value))):
                yield n.lineno, n.col_offset, str(n.value), str(n.value + 1 if n.value != 1 else 0), "const", func

    yield from walk(tree, None)


def apply(src: str, line: int, col: int, old: str, new: str) -> str:
    lines = src.splitlines(keepends=True)
    text = lines[line - 1]
    assert text[col:col + len(old)] == old, (text, col, old)
    lines[line - 1] = text[:col] + new + text[col + len(old):]
    return "".join(lines)


def run_tests(root: Path, tests: str, timeout: int, select=None):
    """Run pytest; return ({nodeid: outcome}, output) or (None, output) on a crash or timeout."""
    with tempfile.TemporaryDirectory() as tmp:
        xml = Path(tmp) / "r.xml"
        cmd = [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", "-p", "no:randomly", "--tb=no",
               "--hypothesis-seed=0", f"--junitxml={xml}", "-o", "junit_family=xunit1", *DESELECT,
               *(select or [tests])]
        env = {**os.environ, "PYTHONPATH": f"{root}:{root}/src", "PYTHONDONTWRITEBYTECODE": "1"}
        try:
            proc = subprocess.run(cmd, cwd=root, env=env, capture_output=True, text=True, timeout=timeout)
        except subprocess.TimeoutExpired:
            return None, "timeout"
        if not xml.exists():
            return None, proc.stdout[-2000:] + proc.stderr[-2000:]
        results = {}
        for case in ET.parse(xml).getroot().iter("testcase"):
            nodeid = f"{case.get('file') or case.get('classname')}::{case.get('name')}"
            kids = {c.tag for c in case}
            results[nodeid] = ("failed" if kids & {"failure", "error"} else "skipped" if "skipped" in kids else "passed")
        return results, proc.stdout[-4000:]


def failure_text(root: Path, nodeid: str, timeout: int) -> str:
    file_part, _, name = nodeid.partition("::")
    env = {**os.environ, "PYTHONPATH": f"{root}:{root}/src", "PYTHONDONTWRITEBYTECODE": "1"}
    cmd = [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", "--tb=short", "-x", "--hypothesis-seed=0",
           *DESELECT, "-k", name.split("[")[0]]
    path = file_part.replace(".", "/") + ".py" if not file_part.endswith(".py") else file_part
    if (root / path).exists():
        cmd.append(path)
    try:
        out = subprocess.run(cmd, cwd=root, env=env, capture_output=True, text=True, timeout=timeout).stdout
    except subprocess.TimeoutExpired:
        return ""
    return out[-3000:]


def build_lib(name, spec, per_lib, out_dir, workers):
    stem, pkg, tests, domain, timeout = spec
    pristine = out_dir / name
    if pristine.exists():
        shutil.rmtree(pristine)
    with tarfile.open(f"/sdists/{stem}.tar.gz") as tf:
        tf.extractall(out_dir / "_extract", filter="data")
    shutil.move(str(out_dir / "_extract" / stem), str(pristine))
    import time
    subset = SUBSET.get(name)
    select = sorted(set(subset.values())) if subset else None
    t0 = time.monotonic()
    base, out = run_tests(pristine, tests, timeout * 2, select)
    timeout = max(15, int(5 * (time.monotonic() - t0)))  # mutants that loop forever are cut off early
    if base is None:
        print(f"{name}: baseline failed: {out[-300:]}", flush=True)
        return []
    passing = {k for k, v in base.items() if v == "passed"}
    (out_dir / f"{name}.baseline.json").write_text(json.dumps(base, indent=0))
    files = [pristine / pkg] if pkg.endswith(".py") else sorted((pristine / pkg).rglob("*.py"))
    files = [f for f in files if "test" not in f.relative_to(pristine).as_posix().split("/")[-1]
             and "/tests/" not in f.relative_to(pristine).as_posix()]
    if subset:
        files = [f for f in files if f.stem in subset and f.parent == pristine / pkg]
    cands = []
    for f in files:
        src = f.read_text()
        try:
            for s in sites(src):
                cands.append((f.relative_to(pristine).as_posix(), *s))
        except (SyntaxError, tokenize.TokenError):
            continue
    rng = random.Random(f"catalog:{name}")
    rng.shuffle(cands)
    cands = cands[:per_lib * 3]
    print(f"{name}: {len(passing)} passing tests, {len(cands)} candidate sites", flush=True)

    def try_one(c):
        rel, line, col, old, new, kind, func = c
        work = Path(tempfile.mkdtemp())
        try:
            shutil.copytree(pristine, work / "lib")
            path = work / "lib" / rel
            mutated = apply(path.read_text(), line, col, old, new)
            try:
                ast.parse(mutated)
            except SyntaxError:
                return None
            path.write_text(mutated)
            res, _ = run_tests(work / "lib", tests, timeout, [subset[Path(rel).stem]] if subset else None)
            if res is None:
                return None
            killed = sorted(k for k in passing if res.get(k) == "failed")
            if not 1 <= len(killed) <= 8:
                return None
            fail = failure_text(work / "lib", killed[0], timeout)
            return {"lib": name, "domain": domain, "file": rel, "line": line, "col": col, "old": old, "new": new,
                    "kind": kind, "function": func, "killed": killed, "failure": fail,
                    "tests_root": tests}
        finally:
            shutil.rmtree(work, ignore_errors=True)

    kept = []
    with ThreadPoolExecutor(workers) as pool:
        for m in pool.map(try_one, cands):
            if m and len(kept) < per_lib:
                kept.append(m)
    print(f"{name}: kept {len(kept)} mutants", flush=True)
    return kept


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--per-lib", type=int, default=40)
    ap.add_argument("--libs", default="")
    ap.add_argument("--workers", type=int, default=4)
    args = ap.parse_args()
    out_dir = Path("/out")
    out_dir.mkdir(exist_ok=True)
    catalog_path = out_dir / "catalog.json"
    catalog = json.loads(catalog_path.read_text()) if catalog_path.exists() else []
    names = [n for n in LIBS if not args.libs or n in args.libs.split(",")]
    catalog = [m for m in catalog if m["lib"] not in names]
    for name in names:
        catalog += build_lib(name, LIBS[name], args.per_lib, out_dir, args.workers)
        catalog_path.write_text(json.dumps(catalog, indent=1))
    shutil.rmtree(out_dir / "_extract", ignore_errors=True)
    print("total mutants:", len(catalog))


if __name__ == "__main__":
    main()