From 34451a411d448c37b1a35cb5bf80fc981fcde4b1 Mon Sep 17 00:00:00 2001 From: Ruslan Strazhnyk Date: Fri, 27 Nov 2026 00:46:41 +0100 Subject: [PATCH 1/3] Observe full Playwright and Appium JUnit test runs --- .agents/skills/diffprowl/SKILL.md | 9 +- .agents/skills/diffprowl/agents/openai.yaml | 2 +- .github/workflows/ci.yml | 7 + README.md | 12 + adapter/e2e.py | 365 ++++++++++++++++++++ adapter/playwright_reporter.cjs | 30 ++ adapter/test_e2e.py | 213 ++++++++++++ adapter/test_playwright_live.py | 83 +++++ docs/ROADMAP.md | 4 +- docs/e2e.md | 138 ++++++++ examples/e2e/.gitignore | 4 + examples/e2e/appium.json | 5 + examples/e2e/landing.html | 1 + examples/e2e/landing.spec.cjs | 8 + examples/e2e/playwright.config.cjs | 12 + examples/e2e/playwright.json | 7 + examples/e2e/pytest.ini | 1 + examples/e2e/settings_appium.py | 41 +++ examples/e2e/status.spec.cjs | 6 + src/main.rs | 49 ++- 20 files changed, 984 insertions(+), 13 deletions(-) create mode 100644 adapter/e2e.py create mode 100644 adapter/playwright_reporter.cjs create mode 100644 adapter/test_e2e.py create mode 100644 adapter/test_playwright_live.py create mode 100644 docs/e2e.md create mode 100644 examples/e2e/.gitignore create mode 100644 examples/e2e/appium.json create mode 100644 examples/e2e/landing.html create mode 100644 examples/e2e/landing.spec.cjs create mode 100644 examples/e2e/playwright.config.cjs create mode 100644 examples/e2e/playwright.json create mode 100644 examples/e2e/pytest.ini create mode 100644 examples/e2e/settings_appium.py create mode 100644 examples/e2e/status.spec.cjs diff --git a/.agents/skills/diffprowl/SKILL.md b/.agents/skills/diffprowl/SKILL.md index 31fe688..c6974e4 100644 --- a/.agents/skills/diffprowl/SKILL.md +++ b/.agents/skills/diffprowl/SKILL.md @@ -1,6 +1,6 @@ --- name: diffprowl -description: Observe and qualify DiffProwl test selection for pytest, diagnose full-suite fallbacks, and replay historical failures using a pinned engine and a full control run. +description: Observe DiffProwl test selection for pytest, Playwright Test and Appium JUnit jobs, diagnose full-suite fallbacks, and qualify or replay pytest changes using a pinned engine and a full control run. --- # DiffProwl @@ -13,6 +13,13 @@ Follow “Observe an existing pytest CI job” in the engine README for the exac Match the run and report to the same head SHA. Check which ancestor baseline the observer actually loaded, its engine digest and scope, the collection on each worker, and the reported expansion reason. A published profile can exist even when CI could not load it. When diagnostics are incomplete, record the last confirmed step. A null omitted-failure count means the comparison was unavailable. +For a Playwright Test or Appium job, read `docs/e2e.md` and use the pinned +binary's `observe` command. Identify the actual runner, browser/device lane, app +build, scoped inputs and prior commit before interpreting selection. Use the +native runner's full command. Inspect receipt completeness, expansion reason, +selected groups and omitted failures. Treat a missing JUnit shard, setup error +or incomplete browser run as inconclusive. + ## Check a change against a failure Use the change's own base and head. For a historical replay, see “Bounded historical replay” in the pinned README and read the checked-in scope and manifest. For a seeded fault, use the pinned engine's `qualify` command with the reviewed scope, campaign, and a fresh output directory. Compare selected and full runs from equivalent clean inputs. Check the failing node and phase, including new parametrized cases, and distinguish assertion failures from collection errors. Record when the planner expanded to every test. diff --git a/.agents/skills/diffprowl/agents/openai.yaml b/.agents/skills/diffprowl/agents/openai.yaml index 8a7030b..acf4603 100644 --- a/.agents/skills/diffprowl/agents/openai.yaml +++ b/.agents/skills/diffprowl/agents/openai.yaml @@ -1,4 +1,4 @@ interface: display_name: "DiffProwl" - short_description: "Observe pytest plans and diagnose full-suite fallbacks" + short_description: "Observe pytest, Playwright and Appium test plans" default_prompt: "Use $diffprowl to explain why the pytest observer selected the full suite for this change." diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 76baeec..4f00a7c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -53,3 +53,10 @@ jobs: python -m ruff format --check adapter examples - name: adapter tests run: python -m unittest discover -s adapter -p 'test_*.py' -v + - name: Verify Playwright observation with Chromium + env: + DIFFPROWL_PLAYWRIGHT_MODULES: ${{ runner.temp }}/diffprowl-playwright/node_modules + run: | + npm install --prefix "$RUNNER_TEMP/diffprowl-playwright" --no-audit --no-fund @playwright/test@1.65.1 + "$DIFFPROWL_PLAYWRIGHT_MODULES/.bin/playwright" install --with-deps chromium + python -m unittest discover -s adapter -p 'test_playwright_live.py' -v diff --git a/README.md b/README.md index 586249b..3cd292e 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,18 @@ the resulting executable runs offline. This is a **bounded in-process fixture**, not a QualityMax production integration or a safe-to-skip recommendation for the repository's existing CI gates. +## Observe Playwright and Appium in CI + +Run the existing full test command through `diffprowl observe playwright` or +`diffprowl observe appium`. The command plans from a previous full run, executes +the project's normal runner once, and compares its results with the advisory plan. +The runner controls browsers, devices, workers, retries, and exit status. The +observer and Playwright reporter ship inside the binary built from this revision. +Use Python 3.11+ and Git on the runner. + +See the [setup and scope examples](docs/e2e.md) for Playwright Test (JS/TS) +and Appium runners that produce JUnit XML, including pytest and WebdriverIO. + ## Codex prompts for pytest Open this checkout in Codex to use the [DiffProwl skill](.agents/skills/diffprowl/SKILL.md). When working in another repository, install the skill there or in your personal skills directory. Paste a prompt and replace the placeholders with a PR, test ID, or CI run. diff --git a/adapter/e2e.py b/adapter/e2e.py new file mode 100644 index 0000000..734aa74 --- /dev/null +++ b/adapter/e2e.py @@ -0,0 +1,365 @@ +"""Observe a complete Playwright Test or Appium runner invocation from its Git root.""" + +import argparse +import collections +import hashlib +import json +import os +import platform +import subprocess +import sys +import tempfile +import time +import xml.etree.ElementTree as ET +from pathlib import Path + +from shadow import plan_shadow + + +def digest(value): + return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":")).encode()).hexdigest() + + +def git(*args): + return subprocess.check_output(["git", *args], stderr=subprocess.DEVNULL) + + +class ObservationError(ValueError): + """A diagnostic independent of user- and runner-supplied strings.""" + + +def snapshot(scope, engine, runner, command, runtime): + # Use index blob IDs and modes. A dirty tree cannot supply reusable evidence. + if git("rev-parse", "--show-prefix").strip(): + raise ObservationError("run from the application Git root") + entries = {} + ordinary = True + for row in git("ls-files", "-v", "--stage", "-z").split(b"\0"): + if row: + stat, name = row.split(b"\t", 1) + flag, mode, blob, stage = stat.decode().split() + ordinary = ordinary and flag == "H" and mode in {"100644", "100755"} and stage == "0" + entries[os.fsdecode(name)] = (mode, blob) + clean = ordinary and subprocess.run(["git", "diff-files", "--quiet", "--ignore-submodules=none"]).returncode == 0 + clean = clean and subprocess.run(["git", "diff-index", "--cached", "--quiet", "HEAD"]).returncode == 0 + clean = clean and not git("ls-files", "--others", "--exclude-standard", "-z") + owners = scope["inputs"] + symbols = {f"file:{p}": digest(entries[p]) for p in owners if p in entries} + shared = {p: v for p, v in entries.items() if p not in owners} + return ( + { + "symbols": symbols, + "shared": digest([runner, command, scope, runtime, platform.system(), platform.machine(), engine, shared]), + }, + git("rev-parse", "HEAD").decode().strip(), + clean and bool(runtime) and owners.keys() <= entries.keys(), + ) + + +def identifier(value): + if not isinstance(value, str) or not value.strip(): + raise ObservationError("missing test identity") + return value + + +def add_case(cases, key, group, outcome): + node = digest(key) + if node in cases: + raise ObservationError("duplicate test identity") + cases[node] = (identifier(group), outcome) + + +def playwright(directory): + data = json.loads((directory / "playwright.json").read_bytes()) + if data["globalError"] is not False or data["status"] not in {"passed", "failed"}: + raise ObservationError("incomplete Playwright run") + cases = {} + for test in data["cases"]: + attempts = test["attempts"] + if not isinstance(attempts, list): + raise ObservationError("invalid Playwright attempts") + if ( + ((not attempts or "notRun" in attempts) and test["expected"] != "skipped") + or "interrupted" in attempts + or test["outcome"] not in {"expected", "unexpected", "skipped", "flaky"} + ): + raise ObservationError("incomplete Playwright case") + if test["outcome"] == "unexpected": + outcome = "failed" + elif test["outcome"] == "expected" and test["expected"] == "passed" and attempts == ["passed"]: + outcome = "passed" + else: + outcome = "non_reusable" + add_case(cases, identifier(test["id"]), test["group"], outcome) + return cases, identifier(data["version"]) + + +class JUnitTree(ET.TreeBuilder): + def data(self, _): + # Identities and outcomes use attributes and element names only. + pass + + def doctype(self, *_): + raise ObservationError("JUnit DTD is unsupported") + + +def junit(directory, reports): + files = {p.relative_to(directory).as_posix() for p in directory.rglob("*.xml")} + if files != set(reports): + raise ObservationError("missing or unexpected JUnit report") + cases = {} + for name in reports: + root = ET.parse(directory / name, parser=ET.XMLParser(target=JUnitTree())).getroot() + for element in root.iter(): + element.tag = element.tag.rsplit("}", 1)[-1] + if root.tag not in {"testsuite", "testsuites"}: + raise ObservationError("unknown JUnit report") + if next(root.iter("testcase"), None) is None: + raise ObservationError("empty JUnit report") + before = len(cases) + for suite in root.iter(): + if suite.tag not in {"testsuite", "testsuites"}: + continue + items = list(suite.iter("testcase")) + if "tests" in suite.attrib and int(suite.get("tests")) != len(items): + raise ObservationError("incomplete JUnit inventory") + for counter, tag in (("errors", "error"), ("failures", "failure"), ("skipped", "skipped")): + if counter in suite.attrib and int(suite.get(counter)) != sum(t.find(tag) is not None for t in items): + raise ObservationError("unattributed JUnit outcome") + if suite.find("error") is not None or suite.find("failure") is not None: + raise ObservationError("JUnit suite error") + for case in suite.findall("testcase"): + group = identifier(case.get("classname") or suite.get("name")) + tags = {child.tag for child in case} + if "error" in tags or case.get("status") == "error": + outcome = "error" + elif "failure" in tags or case.get("status") == "failed": + outcome = "failed" + elif ( + tags - {"system-out", "system-err", "properties"} + or case.get("status", "passed") not in {"passed", "run", "success"} + or case.get("result", "completed") != "completed" + ): + outcome = "non_reusable" + else: + outcome = "passed" + add_case(cases, [name, group, identifier(case.get("name"))], group, outcome) + if len(cases) - before != sum(1 for _ in root.iter("testcase")): + raise ObservationError("unrecognized JUnit suite structure") + return cases, "junit" + + +def read_scope(path, runner): + scope = json.loads(path.read_bytes()) + if not isinstance(scope, dict) or scope.get("schema") != 1 or not isinstance(scope.get("inputs"), dict): + raise ObservationError("invalid scope") + for name, groups in scope["inputs"].items(): + if not isinstance(groups, list) or not groups or not all(identifier(g) for g in groups): + raise ObservationError("invalid input consumers") + if not relative(name): + raise ObservationError("invalid input path") + if runner == "appium": + reports = scope.get("junit_reports") + if not isinstance(reports, list) or not reports or not all(relative(p) and p.endswith(".xml") for p in reports): + raise ObservationError("declare expected relative JUnit XML report paths") + if len(set(reports)) != len(reports): + raise ObservationError("duplicate JUnit report path") + codes = scope.get("failure_exit_codes", [1]) + if not isinstance(codes, list) or not all(type(code) is int and 1 <= code <= 255 for code in codes): + raise ObservationError("invalid JUnit failure exit codes") + return scope + + +def relative(name): + path = Path(name) + return bool(path.parts and not path.is_absolute() and ".." not in path.parts and path.as_posix() == name) + + +def read_baseline(path, commit): + if path is None: + return None, "no_baseline" + try: + old = json.loads(path.read_bytes()) + ancestor = old["commit"] + if len(ancestor) != len(commit) or any(c not in "0123456789abcdef" for c in ancestor): + raise ValueError("invalid commit") + if ( + old["schema"] == 1 + and subprocess.run( + ["git", "merge-base", "--is-ancestor", ancestor, commit], stderr=subprocess.DEVNULL + ).returncode + == 0 + ): + if ( + isinstance(old["evidence"]["tests"], dict) + and old["evidence"]["tests"] + and isinstance(old["version"], str) + ): + return old, None + except (OSError, ValueError, TypeError, KeyError): + pass + return None, "incompatible_baseline" + + +def write(path, value): + temporary = path.with_suffix(".tmp") + try: + temporary.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n") + temporary.replace(path) + return True + except OSError: + print(f"DiffProwl could not write {path.name}", file=sys.stderr) + return False + + +def observe(args, command): + output = args.output.resolve() + scope = read_scope(args.scope, args.runner) + try: + output.mkdir(parents=True, exist_ok=False, mode=0o700) + except FileExistsError: + raise ObservationError("use a new output directory") from None + engine_digest = hashlib.sha256(args.engine.read_bytes()).hexdigest() + + def current(): + try: + return snapshot(scope, engine_digest, args.runner, command, args.runtime_id) + except (OSError, subprocess.SubprocessError): + return None, None, False + + started = time.monotonic() + state, commit, reusable = current() + old, reason = read_baseline(args.baseline, commit) if commit else (None, "unverified_inputs") + if not reusable: + reason = "unverified_inputs" + plan = {} + if not reason: + try: + plan = plan_shadow(state, old["evidence"], output, args.engine, schema=2) + reason = plan.get("expand_reason") or plan.get("transport_fallback") + except (OSError, ValueError, TypeError, KeyError, subprocess.SubprocessError): + reason = "planner_unavailable" + planning_seconds = time.monotonic() - started + planned_before_run = None if reason else plan["selected"] + cases = {} + version = None + receipt_problem = None + complete = False + with tempfile.TemporaryDirectory(prefix="diffprowl-results-") as directory: + env = dict(os.environ, DIFFPROWL_RESULTS_DIR=directory) + if args.runner == "playwright": + env["DIFFPROWL_PLAYWRIGHT_REPORTER"] = str(Path(__file__).with_name("playwright_reporter.cjs")) + started = time.monotonic() + code = subprocess.run(command, env=env).returncode + elapsed = time.monotonic() - started + try: + cases, version = ( + playwright(Path(directory)) + if args.runner == "playwright" + else junit(Path(directory), scope["junit_reports"]) + ) + outcomes = {outcome for _, outcome in cases.values()} + failure_codes = scope.get("failure_exit_codes", [1]) if args.runner == "appium" else [1] + complete = ( + bool(cases) + and "error" not in outcomes + and ((code == 0 and "failed" not in outcomes) or (code in failure_codes and "failed" in outcomes)) + ) + if not complete: + receipt_problem = "runner status and observed outcomes do not establish completion" + except ObservationError as error: + receipt_problem = str(error) + except (ValueError, OSError, KeyError, TypeError, ET.ParseError): + receipt_problem = "unreadable or invalid runner report" + + groups = collections.defaultdict(list) + for name, consumers in scope["inputs"].items(): + for group in consumers: + groups[group].append(f"file:{name}") + if code and (not old or cases.keys() != old["evidence"]["tests"].keys()): + complete = False + receipt_problem = receipt_problem or "failing inventory could not be matched to a baseline" + if current() != (state, commit, reusable): + reason, reusable = "inputs_changed_during_run", False + complete = False + receipt_problem = "source or input verification changed during execution" + elif groups.keys() - {group for group, _ in cases.values()}: + reason, reusable = "unknown_consumer", False + elif old and not reason: + if version != old["version"]: + reason = "runner_version_changed" + elif cases.keys() != old["evidence"]["tests"].keys(): + reason = "collection_changed" + if not complete and reason != "inputs_changed_during_run": + reason = "incomplete_run" + selected = sorted(cases if reason else plan["selected"]) + failed = sorted(node for node, (_, status) in cases.items() if status in {"failed", "error"}) + reported = write( + output / "report.json", + { + "schema": 1, + "runner": args.runner, + "commit": commit, + "baseline_commit": old["commit"] if old else None, + "shadow_only": True, + "exit_code": code, + "complete": complete, + "expand_reason": reason, + "receipt_problem": receipt_problem, + "observed": len(cases), + "planned_before_run": planned_before_run, + "selected": selected, + "selected_by_group": dict( + collections.Counter(cases[node][0] if cases[node][0] in groups else "(unmapped)" for node in selected) + ), + "failures": failed, + "omitted_failures": ( + sorted(set(failed) - set(planned_before_run if planned_before_run is not None else selected)) + if complete + else None + ), + "planning_seconds": planning_seconds, + "full_run_seconds": elapsed, + }, + ) + if reported and reusable and complete and code == 0: + tests = { + node: {"passed": status == "passed", "dependencies": sorted(groups[group])} + for node, (group, status) in cases.items() + } + write( + output / "baseline.json", + {"schema": 1, "commit": commit, "version": version, "evidence": {**state, "tests": tests}}, + ) + print(f"DiffProwl {args.runner}: {len(selected)}/{len(cases)} planned; {reason or 'bounded plan'}", file=sys.stderr) + return 128 - code if code < 0 else code + + +def main(): + parser = argparse.ArgumentParser( + description=__doc__, usage="diffprowl observe RUNNER [options] -- FULL_COMMAND ..." + ) + parser.add_argument("runner", choices=["playwright", "appium"]) + parser.add_argument("--scope", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--baseline", type=Path) + parser.add_argument("--runtime-id", help="non-secret immutable identity of the external test environment") + engine, *argv = sys.argv[1:] + separator = argv.index("--") if "--" in argv else len(argv) + args = parser.parse_args(argv[:separator]) + command = argv[separator + 1 :] + if not command: + parser.error("supply the full runner command after --") + args.engine = Path(engine).resolve() + return observe(args, command) + + +if __name__ == "__main__": + try: + sys.exit(main()) + except ObservationError as error: + print(f"DiffProwl: {error}", file=sys.stderr) + sys.exit(2) + except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError) as error: + print(f"DiffProwl observation unavailable ({type(error).__name__})", file=sys.stderr) + sys.exit(2) diff --git a/adapter/playwright_reporter.cjs b/adapter/playwright_reporter.cjs new file mode 100644 index 0000000..140af84 --- /dev/null +++ b/adapter/playwright_reporter.cjs @@ -0,0 +1,30 @@ +// Added alongside the project's existing reporters only during observation. +const fs = require('node:fs'); +const path = require('node:path'); + +module.exports = class DiffProwlReporter { + onBegin(config, suite) { + this.tests = suite.allTests(); + this.version = config.version; + this.globalError = false; + } + + onError() { + this.globalError = true; + } + + onEnd(result) { + if (!this.tests) return; + const cases = this.tests.map(test => ({ + id: test.id, // Includes project, title path and repeat index. + group: path.relative(process.cwd(), test.location.file).split(path.sep).join('/'), + outcome: test.outcome(), + expected: test.expectedStatus, + attempts: test.results.map(attempt => attempt.workerIndex === -1 ? 'notRun' : attempt.status), + })); + const file = path.join(process.env.DIFFPROWL_RESULTS_DIR, 'playwright.json'); + fs.writeFileSync(file, JSON.stringify({ + version: this.version, status: result.status, globalError: this.globalError, cases, + }), {flag: 'wx', mode: 0o600}); + } +}; diff --git a/adapter/test_e2e.py b/adapter/test_e2e.py new file mode 100644 index 0000000..34e89ef --- /dev/null +++ b/adapter/test_e2e.py @@ -0,0 +1,213 @@ +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +from e2e import junit, playwright + +ENGINE = Path(__file__).resolve().parents[1] / "target/debug/diffprowl" + + +class MobileObservation(unittest.TestCase): + def setUp(self): + work = tempfile.TemporaryDirectory() + self.addCleanup(work.cleanup) + self.root = Path(work.name) / "app" + self.root.mkdir() + self.artifacts = Path(work.name) / "output" + (self.root / "one").write_text("good") + (self.root / "two").write_text("good") + (self.root / "scope.json").write_text( + json.dumps({"schema": 1, "inputs": {"one": ["One"], "two": ["Two"]}, "junit_reports": ["tests.xml"]}) + ) + (self.root / "run.py").write_text( + """import os, sys +from pathlib import Path +from xml.etree.ElementTree import Element, SubElement, ElementTree +suite = Element('testsuite', tests='2') +for group in ('One', 'Two'): + case = SubElement(suite, 'testcase', classname=group, name='screen') + if Path(group.lower()).read_text() == 'broken' or group == os.environ.get('FAIL_GROUP'): + SubElement(case, 'failure') +if os.environ.get('MUTATE'): + Path('one').write_text('changed during the run') +if os.environ.get('REPORT') != 'missing': + ElementTree(suite).write(Path(os.environ['DIFFPROWL_RESULTS_DIR']) / 'tests.xml') +sys.exit(int(os.environ.get('EXIT', bool(suite.findall('.//failure'))))) +""" + ) + self.git("init", "-q") + self.commit() + + def git(self, *args): + subprocess.run( + [ + "git", + "-c", + "user.name=test", + "-c", + "user.email=test@example.invalid", + "-c", + "core.hooksPath=/dev/null", + "-c", + "commit.gpgsign=false", + *args, + ], + cwd=self.root, + check=True, + stdout=subprocess.DEVNULL, + ) + + def commit(self): + self.git("add", ".") + self.git("commit", "-qm", "fixture") + + def observe(self, name, baseline=None, runtime="device-image-1", **env): + output = self.artifacts / name + args = [ENGINE, "observe", "appium", "--scope", "scope.json", "--output", output, "--runtime-id", runtime] + if baseline: + args.extend(["--baseline", self.artifacts / baseline / "baseline.json"]) + result = subprocess.run( + [*args, "--", sys.executable, "run.py"], cwd=self.root, env={**os.environ, **env}, capture_output=True + ) + return result.returncode, json.loads((output / "report.json").read_text()) + + def test_full_control_observes_bounded_plan_and_a_failure(self): + self.assertEqual(self.observe("base")[1]["expand_reason"], "no_baseline") + self.assertEqual(self.observe("same", "base")[1]["selected"], []) + (self.root / "one").write_text("broken") + self.commit() + code, report = self.observe("changed", "base") + self.assertEqual(code, 1) + self.assertEqual(report["selected_by_group"], {"One": 1}) + self.assertEqual(report["observed"], 2) + self.assertEqual(report["failures"], report["selected"]) + self.assertEqual(report["omitted_failures"], []) + self.assertFalse((self.artifacts / "changed/baseline.json").exists()) + + def test_dirty_staged_shared_and_runtime_changes(self): + self.observe("base") + self.assertEqual( + self.observe("device", "base", runtime="device-image-2")[1]["expand_reason"], "shared_input_changed" + ) + (self.root / "shared").write_text("config") + for stage in ("untracked", "staged"): + if stage == "staged": + self.git("add", "shared") + self.assertEqual(self.observe(stage, "base")[1]["expand_reason"], "unverified_inputs") + self.assertFalse((self.artifacts / stage / "baseline.json").exists()) + self.commit() + self.assertEqual(self.observe("shared", "base")[1]["expand_reason"], "shared_input_changed") + + def test_report_errors_preserve_the_native_status(self): + self.observe("base") + for code in (0, 7): + status, report = self.observe(f"missing-{code}", "base", REPORT="missing", EXIT=str(code)) + self.assertEqual(status, code) + self.assertFalse(report["complete"]) + self.assertIsNone(report["omitted_failures"]) + self.assertFalse((self.artifacts / f"missing-{code}/baseline.json").exists()) + + def test_full_run_exposes_an_unselected_failure(self): + self.observe("base") + code, report = self.observe("unplanned", "base", FAIL_GROUP="Two") + self.assertEqual((code, report["complete"], report["planned_before_run"]), (1, True, [])) + self.assertEqual(len(report["failures"]), 1) + self.assertEqual(report["omitted_failures"], report["failures"]) + + def test_hidden_or_changing_inputs_cannot_supply_evidence(self): + self.observe("base") + _, report = self.observe("mutated", "base", MUTATE="yes") + self.assertEqual(report["expand_reason"], "inputs_changed_during_run") + self.assertFalse(report["complete"]) + self.assertIsNone(report["omitted_failures"]) + self.git("update-index", "--assume-unchanged", "one") + _, report = self.observe("hidden", "base") + self.assertEqual(report["expand_reason"], "unverified_inputs") + self.assertFalse((self.artifacts / "hidden/baseline.json").exists()) + + def test_declared_runner_failure_code_requires_a_matching_failure(self): + scope = self.root / "scope.json" + scope.write_text(json.dumps({**json.loads(scope.read_text()), "failure_exit_codes": [3]})) + self.commit() + self.observe("base") + code, report = self.observe("failed", "base", FAIL_GROUP="One", EXIT="3") + self.assertEqual((code, report["complete"]), (3, True)) + code, report = self.observe("infra", "base", EXIT="3") + self.assertEqual((code, report["complete"]), (3, False)) + + +class NativeReceipts(unittest.TestCase): + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.root = Path(directory.name) + + def test_junit_retries_skips_duplicate_ids_and_lost_shards(self): + path = self.root / "first.xml" + case = '{}' + for marker in ("", "", ""): + path.write_text("" + case.format(marker) + "") + cases, _ = junit(self.root, ["first.xml"]) + self.assertEqual(list(cases.values()), [("Mobile", "non_reusable")]) + with self.assertRaises(ValueError): + junit(self.root, ["first.xml", "second.xml"]) + for body in (case.format("") * 2, "", ''): + path.write_text("" + body + "") + with self.assertRaises(ValueError): + junit(self.root, ["first.xml"]) + + def test_namespaced_nested_shards_with_suite_name_fallback(self): + for shard in ("one.xml", "two.xml"): + (self.root / shard).write_text( + '' + '' + ) + cases, _ = junit(self.root, ["one.xml", "two.xml"]) + self.assertEqual(list(cases.values()), [("Device", "passed")] * 2) + + def test_playwright_project_repeats_retries_and_global_errors(self): + doc = { + "version": "1.65", + "status": "passed", + "globalError": False, + "cases": [ + { + "id": "project-one-0", + "group": "a.spec.ts", + "expected": "passed", + "attempts": ["passed"], + "outcome": "expected", + }, + { + "id": "project-one-1", + "group": "a.spec.ts", + "expected": "passed", + "attempts": ["failed", "passed"], + "outcome": "flaky", + }, + { + "id": "project-two-0", + "group": "a.spec.ts", + "expected": "failed", + "attempts": ["failed"], + "outcome": "expected", + }, + ], + } + path = self.root / "playwright.json" + path.write_text(json.dumps(doc)) + cases, _ = playwright(self.root) + self.assertCountEqual([v[1] for v in cases.values()], ["passed", "non_reusable", "non_reusable"]) + doc["globalError"] = True + path.write_text(json.dumps(doc)) + with self.assertRaises(ValueError): + playwright(self.root) + doc["globalError"] = False + doc["cases"][0]["attempts"] = ["notRun"] + path.write_text(json.dumps(doc)) + with self.assertRaises(ValueError): + playwright(self.root) diff --git a/adapter/test_playwright_live.py b/adapter/test_playwright_live.py new file mode 100644 index 0000000..3efbb9f --- /dev/null +++ b/adapter/test_playwright_live.py @@ -0,0 +1,83 @@ +"""Set DIFFPROWL_PLAYWRIGHT_MODULES to a node_modules with @playwright/test and installed Chromium.""" + +import json +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] + + +@unittest.skipUnless(os.environ.get("DIFFPROWL_PLAYWRIGHT_MODULES"), "requires a local Playwright installation") +class PlaywrightBrowser(unittest.TestCase): + def test_changed_page_selects_its_failing_spec(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) / "app" + shutil.copytree(ROOT / "examples/e2e", root, ignore=shutil.ignore_patterns("__pycache__", "node_modules")) + (root / "node_modules").symlink_to(Path(os.environ["DIFFPROWL_PLAYWRIGHT_MODULES"]).resolve()) + + def git(*args): + subprocess.run( + [ + "git", + "-c", + "user.name=test", + "-c", + "user.email=test@example.invalid", + "-c", + "core.hooksPath=/dev/null", + "-c", + "commit.gpgsign=false", + *args, + ], + cwd=root, + check=True, + stdout=subprocess.DEVNULL, + ) + + def run(name, baseline=False): + output = Path(tmp) / name + args = [ + ROOT / "target/debug/diffprowl", + "observe", + "playwright", + "--output", + output, + "--scope", + "playwright.json", + "--runtime-id", + "local-bundled-chromium", + ] + if baseline: + args.extend(["--baseline", Path(tmp) / "base/baseline.json"]) + code = subprocess.run( + [ + *args, + "--", + "node_modules/.bin/playwright", + "test", + "--config=playwright.config.cjs", + "--project=chromium", + "--workers=1", + ], + cwd=root, + stdout=subprocess.DEVNULL, + ).returncode + return code, json.loads((output / "report.json").read_bytes()) + + git("init", "-q") + git("add", ".") + git("commit", "-qm", "baseline") + code, base = run("base") + self.assertEqual((code, base["complete"], base["observed"]), (0, True, 2)) + (root / "landing.html").write_text("\n") + git("add", "landing.html") + git("commit", "-qm", "break checkout") + code, report = run("changed", baseline=True) + self.assertEqual((code, report["complete"], report["observed"]), (1, True, 2)) + self.assertEqual(report["selected_by_group"], {"landing.spec.cjs": 1}) + self.assertEqual(report["failures"], report["selected"]) + self.assertEqual(report["omitted_failures"], []) diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 72d7a69..4066b50 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -138,8 +138,8 @@ Concurrent writers need atomic publication and compatible source revisions. ### 5. Additional languages and 9lives -Choose the next adapter from measured CI spend. Potential candidates are -TypeScript/JavaScript plus Playwright, Go and Rust. Define a common receipt with +Playwright Test and Appium JUnit jobs have a [full-run observer](e2e.md). +Choose additional adapters such as Go or Rust from measured CI spend. Define a common receipt with runner/version, source/input identity, environment compatibility, phase results, dependencies, uncertainty/fallback reason and timing. diff --git a/docs/e2e.md b/docs/e2e.md new file mode 100644 index 0000000..5757d7a --- /dev/null +++ b/docs/e2e.md @@ -0,0 +1,138 @@ +# Observe a browser or mobile test suite + +Build the binary with `cargo build --release --locked`. From the **application's +Git root**, call it with a fresh output directory and the full command that CI +already runs. Use a separate observation for each browser shard, device lane or +application. DiffProwl runs all scoped tests on every invocation. + +## Playwright Test + +Append the embedded reporter in the existing JS/TS Playwright configuration. Keep +the project's current reporters. The observer sets the reporter path for the child +process. The reporter records one case per project and repeat, including its retry +outcomes. Runner errors and interruptions invalidate the comparison. + +```js +reporter: [ + ['list'], + ...(process.env.DIFFPROWL_PLAYWRIGHT_REPORTER + ? [[process.env.DIFFPROWL_PLAYWRIGHT_REPORTER]] + : []), +], +``` + +For the [example browser suite](../examples/e2e/playwright.config.cjs), copy +`examples/e2e/` into a fresh Git project as its root, install +`@playwright/test@1.65.1` there, install its browsers with +`npx playwright install`, and commit the fixture and lockfile. The example exercises +Chromium, Firefox and WebKit. Set `ENGINE` to the absolute path of the built binary. +Use a private artifact directory outside the application checkout. + +```sh +"$ENGINE" observe playwright --scope playwright.json --runtime-id "$BROWSER_IMAGE_DIGEST" \ + --output ../browser-base -- npx --no-install playwright test --config=playwright.config.cjs + +"$ENGINE" observe playwright --scope playwright.json --runtime-id "$BROWSER_IMAGE_DIGEST" \ + --baseline ../browser-base/baseline.json --output ../browser-head \ + -- npx --no-install playwright test --config=playwright.config.cjs +``` + +## Appium with JUnit XML + +Run the existing Appium client and test framework. Have its reporter write XML +under `DIFFPROWL_RESULTS_DIR`, a fresh private directory supplied for that run. +List **every** expected XML path in the scope. Each worker needs its own stable +filename. A missing file, extra XML, empty file, duplicate identity or inconsistent +suite total makes the observation incomplete. Keep existing CI report destinations +by using an additional reporter or copying the fresh XML into the observation +directory before your runner command exits. Preserve the original test exit status. + +For pytest and Appium-Python-Client, the shell expands the directory **inside** +the observed process. This example uses the [mobile scope](../examples/e2e/appium.json) +and its native Settings smoke test. Start a local Appium server on port 4789, supply +a dedicated booted test simulator/emulator in `DIFFPROWL_SIMULATOR`, and set +`DIFFPROWL_PLATFORM` to `ios` or `android`. Install the corresponding XCUITest or +UiAutomator2 driver. Use your own endpoint and normal test command for other suites. + +```sh +"$ENGINE" observe appium --scope appium.json --runtime-id "$DEVICE_IMAGE_AND_APP_DIGEST" \ + --output ../mobile-base -- sh -c \ + 'exec python -m pytest settings_appium.py --junitxml="$DIFFPROWL_RESULTS_DIR/results.xml"' +``` + +For WebdriverIO, configure the installed `@wdio/junit-reporter` alongside the +existing reporters. The following configuration uses the worker ID in the filename. +A job with workers `0-0` and `0-1` would declare +`"junit_reports": ["results-0-0.xml", "results-0-1.xml"]`. For concurrent devices +that assign unstable worker IDs, give each lane its own observation. + +```js +['junit', { + outputDir: process.env.DIFFPROWL_RESULTS_DIR, + outputFileFormat: ({ cid }) => `results-${cid}.xml`, +}] +``` + +```sh +"$ENGINE" observe appium --scope mobile-scope.json --runtime-id "$DEVICE_IMAGE_AND_APP_DIGEST" \ + --output ../mobile-head --baseline ../mobile-base/baseline.json \ + -- npx --no-install wdio run ./wdio.conf.js +``` + +Java, .NET and other Appium clients can use the same interface when their runner +emits compatible JUnit XML. The observer reads testcase names, classnames (or the +containing suite name), failures, errors, skips and retry markers. It supports +nested suites and XML namespaces. Configure the producer to report retries and +session/setup failures and propagate its normal exit code. Frameworks that hide +failed attempts cannot establish first-attempt success from XML alone. + +The default exit codes are 0 for success and 1 for test failure. If your runner +uses other specific codes for completed runs with failing assertions, declare +them in the Appium scope, for example `"failure_exit_codes": [1, 3]`. A failing +comparison also requires a matching baseline inventory and reported failures. +JUnit errors, including session setup errors, make the comparison incomplete. + +## What can select fewer tests? + +The scope maps a **tracked input owned by specific tests** to its complete list +of consumer groups. A Playwright group is the spec path relative to the application's +Git root. A JUnit group is the reported classname, falling back to the suite name. +Read those names from the runner's existing JUnit artifact when setting up a scope. +For example, a page used by two specs must list both spec paths. Keep shared +fixtures, page objects with unknown consumers, runner configuration and lockfiles +outside the map. DiffProwl fingerprints all other tracked entries together. +Unmapped cases and skipped or retried cases stay in the plan. Input ownership is +declared by the application. Browser traffic and mobile UI actions do not prove +which other tests consume a backend service. + +Use an immutable, nonsecret runtime identity covering the runner and driver versions, +device/OS or browser build, app build, backend/fixture revision, and any external +settings that affect discovery or behavior. Supply a new identity when any of those +change. Omit it for full observation without baseline reuse. Use equivalent reset +state for devices and accounts. The observer cannot detect hidden changes on a +remote device or endpoint. Keep generated dependencies and evidence outside Git +or in ignored directories, and include relevant ignored inputs in the runtime identity. + +## Evidence and exit status + +Each run writes `report.json` with the source and baseline commits, full runner +exit status, observed count, selected case hashes and group counts, expansion reason, +failures and omitted failures. Case hashes allow matching identities across runs. +The `planned_before_run` field records the original bounded selection, or `null` +when the plan already called for the full suite. Omitted failures are measured +against that original decision, including when the observed inventory expands. +Runner output, screenshots, session capabilities and raw XML stay out of the +DiffProwl report. Store the artifacts in private application-controlled storage. + +A complete, successful run in a clean committed checkout can also produce +`baseline.json`. Reuse it only within the same trusted application and lane. +The observer checks Git ancestry, the engine, command, scope, tracked inputs, +runtime identity and observed inventory. Dirty inputs or a changed inventory +expand the plan. An incomplete report has `complete: false` and +`omitted_failures: null`. Check these fields independently of the native exit +status. The normal CI gate still receives the runner's status. Selection counts +measure cases. The timing fields record planning and full-suite execution separately. + +[Playwright reporter API](https://playwright.dev/docs/api/class-reporter) · +[WebdriverIO JUnit reporter](https://webdriver.io/docs/junit-reporter/) · +[Appium client and driver concepts](https://appium.io/docs/en/latest/intro/) diff --git a/examples/e2e/.gitignore b/examples/e2e/.gitignore new file mode 100644 index 0000000..66592b6 --- /dev/null +++ b/examples/e2e/.gitignore @@ -0,0 +1,4 @@ +node_modules +test-results/ +__pycache__/ +.pytest_cache/ diff --git a/examples/e2e/appium.json b/examples/e2e/appium.json new file mode 100644 index 0000000..56fd342 --- /dev/null +++ b/examples/e2e/appium.json @@ -0,0 +1,5 @@ +{ + "schema": 1, + "inputs": {"settings_appium.py": ["settings_appium"]}, + "junit_reports": ["results.xml"] +} diff --git a/examples/e2e/landing.html b/examples/e2e/landing.html new file mode 100644 index 0000000..9732bfe --- /dev/null +++ b/examples/e2e/landing.html @@ -0,0 +1 @@ + diff --git a/examples/e2e/landing.spec.cjs b/examples/e2e/landing.spec.cjs new file mode 100644 index 0000000..2813a84 --- /dev/null +++ b/examples/e2e/landing.spec.cjs @@ -0,0 +1,8 @@ +const { test, expect } = require('@playwright/test'); +const fs = require('node:fs'); +const path = require('node:path'); + +test('renders the checkout button', async ({ page }) => { + await page.setContent(fs.readFileSync(path.join(__dirname, 'landing.html'), 'utf8')); + await expect(page.getByRole('button', { name: 'Checkout' })).toBeVisible(); +}); diff --git a/examples/e2e/playwright.config.cjs b/examples/e2e/playwright.config.cjs new file mode 100644 index 0000000..6eddc60 --- /dev/null +++ b/examples/e2e/playwright.config.cjs @@ -0,0 +1,12 @@ +const { defineConfig } = require('@playwright/test'); + +module.exports = defineConfig({ + testMatch: '*.spec.cjs', + projects: ['chromium', 'firefox', 'webkit'].map(browserName => ({ + name: browserName, use: { browserName }, + })), + reporter: [ + ['list'], + ...(process.env.DIFFPROWL_PLAYWRIGHT_REPORTER ? [[process.env.DIFFPROWL_PLAYWRIGHT_REPORTER]] : []), + ], +}); diff --git a/examples/e2e/playwright.json b/examples/e2e/playwright.json new file mode 100644 index 0000000..4e61e06 --- /dev/null +++ b/examples/e2e/playwright.json @@ -0,0 +1,7 @@ +{ + "schema": 1, + "inputs": { + "landing.html": ["landing.spec.cjs"], + "status.spec.cjs": ["status.spec.cjs"] + } +} diff --git a/examples/e2e/pytest.ini b/examples/e2e/pytest.ini new file mode 100644 index 0000000..eea2c18 --- /dev/null +++ b/examples/e2e/pytest.ini @@ -0,0 +1 @@ +[pytest] diff --git a/examples/e2e/settings_appium.py b/examples/e2e/settings_appium.py new file mode 100644 index 0000000..1a8ab35 --- /dev/null +++ b/examples/e2e/settings_appium.py @@ -0,0 +1,41 @@ +"""Smoke test for an explicitly selected local Android emulator or iOS simulator.""" + +import os + +import pytest +from appium import webdriver +from appium.options.android import UiAutomator2Options +from appium.options.ios import XCUITestOptions +from appium.webdriver.client_config import AppiumClientConfig + + +@pytest.fixture(scope="module") +def settings(): + udid = os.environ["DIFFPROWL_SIMULATOR"] + if os.environ["DIFFPROWL_PLATFORM"] == "android": + options = UiAutomator2Options() + options.app_package = "com.android.settings" + options.app_activity = ".Settings" + options.app_wait_activity = "*" + options.no_reset = True + options.set_capability("appium:forceAppLaunch", True) + options.set_capability("appium:uiautomator2ServerLaunchTimeout", 120000) + elif os.environ["DIFFPROWL_PLATFORM"] == "ios": + options = XCUITestOptions() + options.bundle_id = "com.apple.Preferences" + options.set_capability("appium:wdaLaunchTimeout", 180000) + else: + raise ValueError("choose android or ios") + options.udid = udid + endpoint = "http://127.0.0.1:4789" + client = AppiumClientConfig(remote_server_addr=endpoint, timeout=360) + driver = webdriver.Remote(endpoint, options=options, client_config=client) + try: + yield driver + finally: + driver.quit() + + +def test_settings_is_foreground(settings): + app = "com.android.settings" if os.environ["DIFFPROWL_PLATFORM"] == "android" else "com.apple.Preferences" + assert settings.query_app_state(app) == 4 diff --git a/examples/e2e/status.spec.cjs b/examples/e2e/status.spec.cjs new file mode 100644 index 0000000..742e56b --- /dev/null +++ b/examples/e2e/status.spec.cjs @@ -0,0 +1,6 @@ +const { test, expect } = require('@playwright/test'); + +test('shows the status message', async ({ page }) => { + await page.setContent('

Ready

'); + await expect(page.getByRole('status')).toHaveText('Ready'); +}); diff --git a/src/main.rs b/src/main.rs index c368776..e72c3ec 100644 --- a/src/main.rs +++ b/src/main.rs @@ -31,12 +31,43 @@ fn qualify(args: &[String]) -> Result { if args.len() < 4 { return Err("qualify requires REPOSITORY SCOPE.json CAMPAIGN.json OUTPUT_DIR [--python PYTHON] [--timeout SECONDS] [--full-every N]".into()); } + let mut adapter_args = args[..4].to_vec(); + adapter_args.push(std::env::current_exe()?.to_string_lossy().into_owned()); + adapter_args.extend_from_slice(&args[4..]); + run_adapter( + &python, + "qualify.py", + serde_json::json!({ + "shadow.py": include_str!("../adapter/shadow.py"), + "qualify.py": include_str!("../adapter/qualify.py"), + }), + &adapter_args, + ) +} + +fn observe(args: &[String]) -> Result { + let mut adapter_args = vec![std::env::current_exe()?.to_string_lossy().into_owned()]; + adapter_args.extend_from_slice(args); + run_adapter( + "python3", + "e2e.py", + serde_json::json!({ + "shadow.py": include_str!("../adapter/shadow.py"), + "e2e.py": include_str!("../adapter/e2e.py"), + "playwright_reporter.cjs": include_str!("../adapter/playwright_reporter.cjs"), + }), + &adapter_args, + ) +} + +fn run_adapter( + python: &str, + entry: &str, + sources: serde_json::Value, + args: &[String], +) -> Result { // Embed the adapter so a copied release binary does not need a source checkout. // Materialize it temporarily because pytest workers launch shadow.py by path. - let sources = serde_json::json!({ - "shadow.py": include_str!("../adapter/shadow.py"), - "qualify.py": include_str!("../adapter/qualify.py"), - }); let bootstrap = r#"import json, pathlib, runpy, sys, tempfile sources = json.loads(sys.argv.pop(1)) with tempfile.TemporaryDirectory(prefix="diffprowl-adapter-") as directory: @@ -44,16 +75,15 @@ with tempfile.TemporaryDirectory(prefix="diffprowl-adapter-") as directory: for name, source in sources.items(): (root / name).write_text(source) sys.path.insert(0, directory) - sys.argv[0] = str(root / "qualify.py") + sys.argv[0] = str(root / sys.argv.pop(1)) runpy.run_path(sys.argv[0], run_name="__main__") "#; let status = std::process::Command::new(python) .arg("-c") .arg(bootstrap) .arg(serde_json::to_string(&sources)?) - .args(&args[..4]) - .arg(std::env::current_exe()?) - .args(&args[4..]) + .arg(entry) + .args(args) .status()?; Ok(status.code().unwrap_or(2)) } @@ -65,6 +95,7 @@ fn cli() -> Result { println!("diffprowl {}", env!("CARGO_PKG_VERSION")); Ok(0) } + Some("observe") => observe(&args[1..]), Some("qualify") => qualify(&args[1..]), Some("shadow-plan") if args.len() == 2 => { let request = read_json(Path::new(&args[1]))?; @@ -115,7 +146,7 @@ fn cli() -> Result { } Some("help" | "--help" | "-h") | None => { println!( - "diffprowl demo OUTPUT_DIR [SEEDS=32] [REPETITIONS=25]\ndiffprowl run OUTPUT_DIR DEFECT [SEEDS=32] [BASELINE_EVIDENCE.json]\ndiffprowl replay REPLAY.json\ndiffprowl shadow-plan REQUEST.json\ndiffprowl qualify REPOSITORY SCOPE.json CAMPAIGN.json OUTPUT_DIR [--python PYTHON] [--timeout SECONDS] [--full-every N]\n\nDefects: none, double_release, missing_authorization, lost_cancellation, double_settlement, duplicate_submission\nExit codes: 0 success/matching replay, 1 detected regression or failed experiment, 2 invalid input/I/O.\nLocal fixture only. Evidence is trusted local input, not a signed CI attestation." + "diffprowl demo OUTPUT_DIR [SEEDS=32] [REPETITIONS=25]\ndiffprowl run OUTPUT_DIR DEFECT [SEEDS=32] [BASELINE_EVIDENCE.json]\ndiffprowl replay REPLAY.json\ndiffprowl shadow-plan REQUEST.json\ndiffprowl observe --scope SCOPE.json --output NEW_DIR [--baseline BASELINE.json] [--runtime-id ID] -- FULL_COMMAND ...\ndiffprowl qualify REPOSITORY SCOPE.json CAMPAIGN.json OUTPUT_DIR [--python PYTHON] [--timeout SECONDS] [--full-every N]\n\nDefects: none, double_release, missing_authorization, lost_cancellation, double_settlement, duplicate_submission\nExit codes: 0 success/matching replay, 1 detected regression or failed experiment, 2 invalid input/I/O.\nLocal fixture only. Evidence is trusted local input, not a signed CI attestation." ); Ok(0) } From f2bf7fc06994806b9d80203165eb33557aa3516a Mon Sep 17 00:00:00 2001 From: Ruslan Strazhnyk Date: Fri, 27 Nov 2026 00:49:19 +0100 Subject: [PATCH 2/3] Document the verified Appium simulator setup --- docs/e2e.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/e2e.md b/docs/e2e.md index 5757d7a..6199ad5 100644 --- a/docs/e2e.md +++ b/docs/e2e.md @@ -54,6 +54,12 @@ a dedicated booted test simulator/emulator in `DIFFPROWL_SIMULATOR`, and set `DIFFPROWL_PLATFORM` to `ios` or `android`. Install the corresponding XCUITest or UiAutomator2 driver. Use your own endpoint and normal test command for other suites. +Install `pytest` and `Appium-Python-Client` in the Python environment used below. +For iOS, XCUITest needs a working WebDriverAgent. If you already built its runner +for the simulator, the Appium server can use it with the default capabilities +`appium:usePreinstalledWDA=true` and `appium:prebuiltWDAPath` pointing to the +runner's `.app` directory. + ```sh "$ENGINE" observe appium --scope appium.json --runtime-id "$DEVICE_IMAGE_AND_APP_DIGEST" \ --output ../mobile-base -- sh -c \ From 5a0ad61410abe9e56fd44800dcc56241f9aa524a Mon Sep 17 00:00:00 2001 From: Ruslan Strazhnyk Date: Fri, 27 Nov 2026 13:54:51 +0100 Subject: [PATCH 3/3] Verify native Playwright identities across projects and repeats --- adapter/test_playwright_live.py | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/adapter/test_playwright_live.py b/adapter/test_playwright_live.py index 3efbb9f..c3f1574 100644 --- a/adapter/test_playwright_live.py +++ b/adapter/test_playwright_live.py @@ -13,11 +13,18 @@ @unittest.skipUnless(os.environ.get("DIFFPROWL_PLAYWRIGHT_MODULES"), "requires a local Playwright installation") class PlaywrightBrowser(unittest.TestCase): - def test_changed_page_selects_its_failing_spec(self): + def test_project_and_repeat_ids_survive_reuse_and_select_the_failing_spec(self): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) / "app" shutil.copytree(ROOT / "examples/e2e", root, ignore=shutil.ignore_patterns("__pycache__", "node_modules")) (root / "node_modules").symlink_to(Path(os.environ["DIFFPROWL_PLAYWRIGHT_MODULES"]).resolve()) + (root / "repeated.config.cjs").write_text( + "module.exports = {\n" + " ...require('./playwright.config.cjs'),\n" + " repeatEach: 2,\n" + " projects: ['desktop', 'laptop'].map(name => ({ name, use: { browserName: 'chromium' } })),\n" + "};\n" + ) def git(*args): subprocess.run( @@ -59,8 +66,7 @@ def run(name, baseline=False): "--", "node_modules/.bin/playwright", "test", - "--config=playwright.config.cjs", - "--project=chromium", + "--config=repeated.config.cjs", "--workers=1", ], cwd=root, @@ -72,12 +78,21 @@ def run(name, baseline=False): git("add", ".") git("commit", "-qm", "baseline") code, base = run("base") - self.assertEqual((code, base["complete"], base["observed"]), (0, True, 2)) + self.assertEqual((code, base["complete"], base["observed"]), (0, True, 8)) + self.assertEqual(len(set(base["selected"])), 8) + code, same = run("unchanged", baseline=True) + self.assertEqual((code, same["complete"], same["observed"]), (0, True, 8)) + self.assertEqual(same["baseline_commit"], base["commit"]) + self.assertIsNone(same["expand_reason"]) + self.assertEqual(same["planned_before_run"], []) + self.assertEqual(same["selected"], []) + rerun_evidence = json.loads((Path(tmp) / "unchanged/baseline.json").read_bytes()) + self.assertCountEqual(rerun_evidence["evidence"]["tests"], base["selected"]) (root / "landing.html").write_text("\n") git("add", "landing.html") git("commit", "-qm", "break checkout") code, report = run("changed", baseline=True) - self.assertEqual((code, report["complete"], report["observed"]), (1, True, 2)) - self.assertEqual(report["selected_by_group"], {"landing.spec.cjs": 1}) + self.assertEqual((code, report["complete"], report["observed"]), (1, True, 8)) + self.assertEqual(report["selected_by_group"], {"landing.spec.cjs": 4}) self.assertEqual(report["failures"], report["selected"]) self.assertEqual(report["omitted_failures"], [])