File size: 12,138 Bytes
e5a3ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
#!/usr/bin/env python3
"""RB TestGen Kit — declare each test's NAVIGATION DEPTH and JUMP RIGOR so a suite's
real interaction depth is measured (not inferred), uniformly recorded, and auditable.

LOCATION ON THE VM: /workspace/output/rb_testgen_kit.py  (READ-ONLY — never edit;
`import rb_testgen_kit` from your tests and from audit commands).

Two orthogonal properties decide whether a suite really exercises an app:
  * navigation DEPTH — surfaces crossed to reach the asserted state
                       (0 = home, 1 = a dialog/page/submenu, 2+ = deeper).
  * jump RIGOR       — what the assertion after the trigger actually checks.
Every behavioral test DECLARES both via a pytest marker; conftest.py writes the superset
<module>_results.json (no RBResults class — pytest + the marker + the `rb` fixture record):

      @pytest.mark.rb(jump_kind=<str>, expect="<observed target>")
      def test_...(app, rb): ...

jump_kind (verbatim strings — the audit/stats key off them):
    "none"        no trigger; existence/structure only            -> tier 0
    "liveness"    only "did not crash / still alive"              -> tier 1 (weak; avoid)
    "reach"       a real page/dialog jump: the target surface
                  APPEARED and the source surface DISAPPEARED     -> tier 2
    "transition"  a state flip (CHECKED/ENABLED/mode), before->after -> tier 2
    "value"       a specific expected value/content asserted      -> tier 3

DEPTH is measured at runtime: call rb.enter("<surface>") on each real crossing; conftest
records the MAX depth (a runtime count can't be faked, so no source audit). A flat-tree
read of a deep element is NOT depth — depth counts surfaces you navigated.

TRUE-JUMP HELPER (so "reach" cannot be faked by reading a flat tree):
    @pytest.mark.rb(jump_kind="reach", expect="Preferences dialog visible; toolbar gone")
    def test_prefs_opens(app, rb):
        before = rb_showing(app)
        rb.enter("prefs"); <trigger: click the menu item / button>   # real nav -> depth 1
        after = rb_showing(app)
        check.is_true(rb_reach(before, after, target="Preferences", source="main toolbar"))

PORTABLE APP ACQUISITION (so the SAME suite scores reference AND recreation, which live
at DIFFERENT paths): the `app` fixture (conftest) attaches BY NAME via RB_APP_NAME — never
spawn the binary, name /workspace/install, use a CLI flag, or seed GSettings.
rb_lint_sources flags such non-portable code.

SELF-AUDIT (REPORT-ONLY — goals, not a gate; conftest's terminal summary prints these at
the end of run_baseline, or run them directly to target the next round):
    python3 -c "import rb_testgen_kit as k; k.rb_audit('<dir>'); \
                k.rb_lint('<dir>'); k.rb_lint_sources('/workspace/output')"
"""
from __future__ import annotations

import glob
import json
import os
import re

JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3}

# Double-axis quota TARGETS (fractions) — goals rb_audit REPORTS, NOT a hard gate.
QUOTAS = {
    "existence_max": 0.30,  # jump_kind=="none" share of ALL tests       (structure gate)
    "interactive_min": 0.60,  # reach|transition|value share of ALL tests
    "depth_ge1_min": 0.40,  # depth>=1 share of INTERACTIVE tests         (real navigation)
    "depth_ge2_min": 0.10,  # depth>=2 share of INTERACTIVE tests         (deep chains)
    "value_min": 0.25,  # jump_kind=="value" share of INTERACTIVE tests   (tier3 strength)
}


def tier_of(jump_kind: str) -> int:
    return JUMP_KINDS.get(jump_kind, 2)


def rb_showing(root) -> set:
    """Snapshot the SHOWING+VISIBLE nodes under an AT-SPI root as {"role|name"}.
    Safe no-op ({}) if AT-SPI/gi is unavailable. Use before+after a trigger to
    feed rb_reach() so a 'reach' test proves a real surface change."""
    out = set()
    try:
        import gi

        gi.require_version("Atspi", "2.0")
        from gi.repository import Atspi
    except Exception:
        return out
    stack = [root]
    seen = 0
    while stack and seen < 6000:
        n = stack.pop()
        seen += 1
        try:
            ss = n.get_state_set()
            if ss.contains(Atspi.StateType.SHOWING) and ss.contains(
                Atspi.StateType.VISIBLE
            ):
                out.add(f"{n.get_role_name()}|{n.get_name() or ''}")
        except Exception:
            pass
        try:
            for i in range(n.get_child_count()):
                c = n.get_child_at_index(i)
                if c is not None:
                    stack.append(c)
        except Exception:
            pass
    return out


def rb_reach(before, after, target: str, source: str | None = None) -> bool:
    """True-jump verdict: the TARGET surface's discriminating element newly APPEARED
    AND (if given) the SOURCE surface's discriminating element DISAPPEARED. This is
    what separates a real page jump from reading an element that was always present."""
    before = set(before or [])
    after = set(after or [])
    t = target.lower()
    appeared = any(t in k.lower() for k in (after - before))
    if source is None:
        return appeared
    s = source.lower()
    src_before = any(s in k.lower() for k in before)
    src_after = any(s in k.lower() for k in after)
    return appeared and src_before and not src_after


def _load_all(results_dir: str) -> list[dict]:
    recs: list[dict] = []
    seen_files = set()
    for pat in (
        os.path.join(results_dir, "*_results.json"),
        os.path.join(results_dir, "results", "*_results.json"),
    ):
        for path in glob.glob(pat):
            base = os.path.basename(path)
            if base in seen_files:
                continue
            seen_files.add(base)
            try:
                data = json.load(open(path))
            except Exception:
                continue
            for t in data.get("tests", []):
                if isinstance(t, dict) and "name" in t:
                    recs.append(t)
    return recs


def rb_audit(results_dir: str, quotas: dict | None = None) -> dict:
    """Aggregate declared depth/jump_kind across a suite and check the double-axis
    quotas. Prints PASS/FAIL per quota with the concrete gap (how many tests to add),
    so the orchestrator can target its Improve round. Call BEFORE finalizing."""
    q = quotas or QUOTAS
    recs = _load_all(results_dir)
    n = len(recs)
    if not n:
        print(f"[rb_audit] no records under {results_dir}")
        return {"total": 0}
    kinds = [r.get("jump_kind", "none") for r in recs]
    none_n = sum(1 for k in kinds if k == "none")
    live_n = sum(1 for k in kinds if k == "liveness")
    inter = [r for r in recs if r.get("jump_kind") in ("reach", "transition", "value")]
    ni = len(inter) or 1
    d1 = sum(1 for r in inter if int(r.get("depth", 0)) >= 1)
    d2 = sum(1 for r in inter if int(r.get("depth", 0)) >= 2)
    val = sum(1 for r in inter if r.get("jump_kind") == "value")

    def line(label, got, need, kind):
        ok = got >= need if kind == "min" else got <= need
        return (
            ok,
            f"  [{'ok ' if ok else 'GAP'}] {label}: {got:.0%} "
            f"({'>=' if kind == 'min' else '<='} {need:.0%})",
        )

    checks = [
        line("existence(none)/all", none_n / n, q["existence_max"], "max"),
        line("interactive/all", len(inter) / n, q["interactive_min"], "min"),
        line("depth>=1 /interactive", d1 / ni, q["depth_ge1_min"], "min"),
        line("depth>=2 /interactive", d2 / ni, q["depth_ge2_min"], "min"),
        line("value(tier3)/interactive", val / ni, q["value_min"], "min"),
    ]
    print(
        f"[rb_audit] {results_dir}  total={n}  interactive={len(inter)}  "
        f"none={none_n} liveness={live_n} depth>=1={d1} depth>=2={d2} value={val}"
    )
    for _ok, msg in checks:
        print(msg)
    passed = all(ok for ok, _ in checks)
    if passed:
        print("[rb_audit] ALL TARGETS MET")
    else:
        print(
            "[rb_audit] some targets below — OPTIONALLY add a deeper reach/value "
            "test, or finalize if you've tried enough angles (goals, NOT a gate)"
        )
    return {
        "total": n,
        "interactive": len(inter),
        "none": none_n,
        "liveness": live_n,
        "depth_ge1": d1,
        "depth_ge2": d2,
        "value": val,
        "passed": passed,
        "checks": [m for _o, m in checks],
    }


def rb_lint(results_dir: str) -> list:
    """Flag weak/inconsistent declarations: missing expect on a value/transition/reach
    test, unknown jump_kind, or negative depth. Prints and returns the issues."""
    recs = _load_all(results_dir)
    issues = []
    for r in recs:
        jk = r.get("jump_kind", "none")
        nm = r.get("name", "?")
        if jk not in JUMP_KINDS:
            issues.append(f"{nm}: unknown jump_kind {jk!r}")
        if (
            jk in ("reach", "transition", "value")
            and not str(r.get("expect", "")).strip()
        ):
            issues.append(
                f"{nm}: jump_kind={jk} but empty expect (name the observed target)"
            )
        if jk == "liveness":
            issues.append(
                f"{nm}: liveness is tier1 — replace with an observable app effect"
            )
        if int(r.get("depth", 0)) < 0:
            issues.append(f"{nm}: negative depth")
    if issues:
        print(f"[rb_lint] {len(issues)} issue(s):")
        for i in issues:
            print("  - " + i)
    else:
        print("[rb_lint] no issues")
    return issues


# Non-portable source patterns: each PASSES on the reference (app @ /workspace/install)
# but BREAKS on the recreation (app elsewhere). The baseline pytest run can't catch them
# (they pass on the reference), so this static scan is their only guard.
_BAD_SOURCE_PATTERNS = [
    (
        r"/workspace/install",
        "names the reference install path /workspace/install (gone at eval) — "
        "attach to the running app via the `app` fixture (RB_APP_NAME)",
    ),
    (
        r"/workspace/output/recreation",
        "names an eval-only path — a test must not know where the app is installed",
    ),
    (
        r"[\"']gsettings[\"']|\bgsettings\s+set\b",
        "seeds state via gsettings — the recreation may not ship the reference schema; "
        "drive state through the GUI instead",
    ),
    (
        r"subprocess\.(?:Popen|run|call)\([^)]*[\"'][^\"']*/(?:bin|usr|lib)/",
        "spawns the app by an absolute binary path — attach via the `app` fixture, "
        "do not launch the binary",
    ),
]


def rb_lint_sources(testgen_dir: str) -> list:
    """Scan authored test/helper .py for NON-PORTABLE patterns (hardcoded install paths,
    self-spawn by absolute path, gsettings/schema seeding). Each PASSES on the reference
    but BREAKS on the recreation (different path) — the one defect class the baseline run
    can't surface. Run BEFORE finalize; a clean result means the suite will drive the
    recreation, not just the reference."""
    py = [
        p
        for p in (
            glob.glob(os.path.join(testgen_dir, "*.py"))
            + glob.glob(os.path.join(testgen_dir, "tests", "*.py"))
        )
        if os.path.basename(p)
        not in ("rb_testgen_kit.py", "run_atspi_tests.py", "rb_atspi.py", "conftest.py")
    ]
    issues = []
    for p in py:
        base = os.path.basename(p)
        try:
            src = open(p).read()
        except Exception:
            continue
        for pat, why in _BAD_SOURCE_PATTERNS:
            if re.search(pat, src):
                issues.append(f"{base}: {why}")
    if issues:
        print(f"[rb_lint_sources] {len(issues)} portability issue(s):")
        for i in issues:
            print("  - " + i)
    else:
        print("[rb_lint_sources] no portability issues")
    return issues


if __name__ == "__main__":
    import sys

    _fns = {"audit": rb_audit, "lint": rb_lint, "lint_sources": rb_lint_sources}
    if len(sys.argv) >= 3 and sys.argv[1] in _fns:
        _fns[sys.argv[1]](sys.argv[2])
    else:
        print("usage: rb_testgen_kit.py {audit|lint|lint_sources} <dir>")