mirror of
https://github.com/priyanshujain/sanderling.git
synced 2026-10-02 11:07:10 +00:00
UX refactor (#52)
* feat(ltl): bound fields on AlwaysFormula and named thunks Add StepBound/Duration/Deadline to AlwaysFormula as the dual of bounded Eventually, give ThunkFormula a Name for stable identity, add ThunkNamed, and surface both in describe() and MarshalJSON. * feat(ltl): negation normal form pass nnf/pushNot rewrite a formula so every Not wraps only a Thunk or Error leaf, dualizing Always<->Eventually and preserving bounds. * feat(ltl): NNF in NewEvaluator, bounded-always, Finalize, collapse Apply nnf on construction, reduce bounded Always symmetric to bounded Eventually (vacuous holds once the window closes), add Finalize to resolve undischarged liveness obligations to Violated at run end, and collapse structurally-identical pending obligations. * test(ltl): property-based NNF laws Lock double-negation identity, Always/Eventually duality with bound preservation, leaf pushdown, and not(always true) reaching Violated. * test(ltl): Finalize, bounded eventually, latch, collapse Property tests for monotonic violation latch and eventually-within violating iff n consecutive false, plus Finalize and collapse cases. * feat(inspect): within clause on always residual node A negated bounded eventually serializes as a bounded always; render its bound instead of dropping it. * feat(ltl): witness violations and (bool,error) predicate thunks * test(ltl): migrate thunk call sites to (bool,error) * feat(ltl): flag thrown-predicate witnesses with IsError * refactor(verifier): replace predicate err side-channel with violation witness * test(verifier): witness API for thrown predicates * feat(trace): witnesses map and skipped-verification marker on Step * feat(runner): thread violation witnesses, finalize, skip marker into trace * test(ltl): lock violation witness reason, IsError, and step * test(verifier): finalize surfaces unmet eventually with witness * fix(ltl): eliminate implies and bounded-always false-negatives Rewrite a -> b to (not a) or b in NNF so a pending temporal antecedent can no longer defer the whole implication and drop a consequent that was false at the current step. Carry a pending inner past a bounded-Always window close instead of dropping it to holds, so a deferred obligation is resolved by a later step or Finalize. * test(ltl): lock implies and bounded-always false-negative regressions * fix(web-runtime): seed PRNG for reproducible runs and align weighted pick * feat(testrun): inject seed into web bundle via SANDERLING_SEED define * test: cover web-runtime seeded PRNG, weighted pick, and seed define wiring * test(spec): add Go math/rand/v2 PCG oracle and golden fixture * feat(spec): bit-exact PCG port of Go math/rand/v2 * test(spec): assert pcg.ts matches the PCG golden fixture * feat(spec): shared input corpus and press-key pools * feat(spec): action-tree types and Host interface * feat(spec): verb support matrix and warn-once helper * feat(spec): deterministic shared action picker * test(spec): verb matrix and warn-once semantics * test(spec): picker draw-order and determinism * refactor(spec): actions.ts returns pure GeneratorNode data trees * refactor(spec): wire from() sampling through the picker rng * feat(spec): shared runtime-entry installs next-action over pick.ts * feat(spec): export LongPress/Scroll/longPresses/scrolls factories * test(spec): assert data-tree shapes for action factories * test(spec): runtime-entry serializeAction wire-contract round-trip * refactor(spec): bridge data-tree nodes to the legacy goja picker tags * fix(spec): web runtime walks the spec's globalThis.actions data tree * test(spec): tolerate legacy bridge fields on builtin nodes * refactor(spec): installRuntime accepts a lazy root resolver The web bundle imports the runtime before the spec, so the action root on globalThis.actions only exists after the spec evaluates. Accept a function form so the goja and web hosts resolve the root per tick. * refactor(spec): web-runtime becomes the WEB Host, delegates to shared picker Delete the duplicate picker (resolveGenerator/pickWeighted/randomTap/ randomInput/randomSwipe/randomPressKey/pickFromArray, the mulberry32 PRNG, and the snake_case serializeAction) plus the __sanderling__ action factory binds. web-runtime now implements Host (platform/seedHi/seedLo from the injected 64-bit seed via BigInt, queryCandidates over the live DOM with a per-tick cache, reportUnsupported) and calls installRuntime so both engines run pick.ts over the same Pcg. Swipe/longPress/scroll follow the verbs.ts matrix instead of silently returning null. Keeps the DOM helpers (selector translation, queryElement, elementHandle, buildState, sanitize, extractors) and the global locking. Net -214 lines (741 -> 527). * test(spec): cover the WEB Host surface and seed precision Replace the deleted-picker tests with Host coverage: platform()==web, seedHi() parsing a 64-bit seed without Number precision loss, seedLo()==0, reportUnsupported warning, the installed next-action/extractor globals, and queryCandidates verb routing + per-tick caching over a querySelectorAll stub. * refactor(spec): picker emits native selector + scroll endpoints, setup precedence * feat(spec): goja runtime entry wires the shared picker over the Go host * feat(bundler): optional RuntimeFile prepends a runtime-entry import via stdin * feat(testrun): bundle the goja runtime entry so the verifier runs the shared picker * refactor(spec): drop the legacy goja bridge fields from action factories * feat(spec): serialize selector-only string targets for the runner to re-resolve * refactor(verifier): one DecodeAction reads the unified flat wire contract * refactor(verifier): goja host + shared picker replace the duplicate Go picker * refactor(runner): decode V8 actions via the unified DecodeAction; wire goja runtime * test(verifier): author specs through the shared picker path * test(runner): bundle authored specs with the goja runtime entry * feat(verifier): collect unsupported verbs for the run report * refactor(runner): collapse WebDriver forks behind ActionSource/ExtractorSource * feat(testrun): surface unsupported verbs in run report * test(verifier): cross-runtime goja/node parity gate on the shared picker * test(verifier): unsupported verbs collected deduped in first-seen order * test(runner): summary reports no unsupported verbs on a clean run * test(spec): golden-fixture cross-runtime parity gate for the node picker Replace the env-driven parity harness with a shared scenario module and a committed golden the node picker asserts independently. The goja side asserts the same golden, so neither runtime invokes the other at test time. * test(verifier): assert goja picker against the same cross-runtime golden Drop the node-subprocess coupling: the goja side now installs a stub __sanderlingHost__ with the fixed candidate list and asserts the committed golden, matching pkg/spec/test/parity.test.ts. * refactor(spec): rename pressKey generator export to pressKeys * refactor(spec): update barrel re-exports for pressKeys * test(spec): update pressKeys generator export name * docs(spec): rename pressKey generator to pressKeys * refactor(spec): extract samplerRng into shared sampler-rng module * feat(spec): add fluent seeded value generators (strings/integers/emails/edgeCaseText) * test(spec): cover fluent value generators determinism and chaining * refactor(bundler): inject globalThis trailer from spec named exports * refactor(bundler): reuse registration trailer in web bundler * test(bundler): cover named-export globalThis registration * feat(spec): add named() to Extracted handle type * feat(web-runtime): named() and cross-extractor read guard * feat(verifier): named() and cross-extractor read guard in goja * test(verifier): cross-extractor read guard and named() * test(web-runtime): export runtime and extractors for tests * test(web-runtime): named() and cross-extractor read guard * refactor(folio): drop manual globalThis trailer (bundler injects it) * refactor(folio): seed txn amounts via integers().between(1,500) * refactor(folio-web): drop manual globalThis trailer (bundler injects it) * fix(folio-web): seed card/txn-type selection via from().generate() for reproducible runs * refactor(folio-web): weight valid generators against edgeCaseText for names/amounts * refactor(folio-web): name extractors so violation witnesses are readable * fix(web-runtime): propagate extractor getter throws and unpoison locked global Stop swallowing getter errors in evaluateExtractors so the cross-extractor read guard aborts loudly, matching goja's PushSnapshot. Make the __sanderling__ lock configurable (still non-writable) so a shared test process can reinstall a fake. * test(spec): install fake runtime via defineProperty to survive locked global * test(web-runtime): assert uncaught cross-extractor read aborts evaluateExtractors * feat(runner): add MaxSteps bound to Options * test(runner): MaxSteps stops after exactly N steps * test(driverpb): drop proto getter round-trip tautology * test(sidecar): drop stub-mode placeholder tautology tests * test(mock): drop default-field-value assertion test * test(ltl): drop Verdict.String tautology tests * refactor(runner): extract RenderSummary for snapshot testing * test(runner): golden snapshots for trace stream and violation summary * feat(web-runtime): capture uncaught errors into state.exceptions * test(integration): add throwing and counter web fixtures * test(integration): add specs for the web fixtures * test(integration): drive web fixtures through the real pipeline in headless Chrome * chore(make): add test-browser target for the Chrome-driven suite * ci: run the Chrome-driven browser suite in a separate job * refactor(test): relocate browser suite to test/browser * refactor(permissions): delete dead internal/permissions package * refactor(test): rename package to browser_test * refactor(sidecarassets): rename internal/sidecar to internal/sidecarassets * chore(make): point test-browser at test/browser * docs(decisions): record internal/permissions deletion * refactor(doctor): use sidecarassets package * refactor(testrun): use sidecarassets package * fix(test): resolve testdata relative to browser_test.go * refactor(verifier): remove dead __sanderlingIndex compat alias * refactor(bundler): use encoding/json for JS string literals * docs(action-space): use vendor-neutral native driver wording * refactor(hierarchy): scrub backend tool name from comments * refactor(driver): scrub backend tool name from comments * refactor(driver): add DoubleTap and DoubleTapSelector to DeviceDriver * refactor(sidecar): implement DoubleTap with the sub-100ms inter-tap gap * refactor(chrome): implement DoubleTap as two taps with the gap * refactor(mock): record DoubleTap and DoubleTapSelector actions * refactor(runner): delegate double-tap to driver, drop gesture timing * test(runner): assert double-tap delegates to driver DoubleTap * docs(cmd): add package docs to CLI and developer tools * docs(driver): add package docs to driver interface and chrome backend * docs(driver): add package docs to mock and sidecar backends * docs(platform): add package docs to android and ios device prep * docs: add package docs to bundler and inspect * docs(ltl): add package doc to temporal logic evaluator * docs: add package docs to runner and testrun pipeline * docs: add package docs to trace and verifier * docs(sidecarassets): add package doc for embedded JAR loader * fix(chrome): add disable-dev-shm-usage so Chrome starts in CI * test(chrome): gate real-Chrome driver tests behind the browser tag * chore(make): run chrome driver tests in the browser job * fix(web-runtime): guard global error listeners for non-browser hosts The module registered window error/unhandledrejection listeners at top level, which threw under Node (the spec-api test runner) where globalThis.addEventListener is absent. Register only when the API exists; the real browser run is unaffected. * ci(browser): re-enable unprivileged user namespaces for headless Chrome ubuntu-latest moved to 24.04, whose AppArmor restriction on unprivileged user namespaces stops headless Chrome from opening its DevTools socket even with --no-sandbox, surfacing as the driver's 'websocket url timeout'. Relax the sysctl for the job and add a direct launch check so a future breakage shows Chrome's own stderr rather than an opaque driver timeout. * ci(browser): pin stable Chrome for the driver tests setup-chrome's default latest pulled a dev Chromium (150) whose remote debugging socket never came up under chromedp, while plain --dump-dom worked. Pin the stable channel, which the driver is tested against. * feat(defaults): add scroll and rebalance action weights Use relative-integer weights (taps/typing co-primary 100, scrolls 50, swipes 25, doubleTaps 10); the picker normalizes by their total. Adds scrolls to defaultActions as a first-class reveal behavior. * feat(defaults): trim scroll action weight wiring * fix(build): point sidecar jar ignore and embed paths at sidecarassets * test(defaults): drop stale longPresses re-export assertion longPresses is opt-in vocabulary, no longer re-exported from defaults/actions.ts since e0d3b20; its builtin resolution is already covered by api.test.ts. Trim the defaults test to scrolls, which is an actual default export. * fix(chrome): raise DevTools websocket read timeout to 60s Chrome cold-start on a loaded CI runner can exceed chromedp's 20s default for reading the DevTools websocket URL, flaking the browser tests with "websocket url timeout reached". Give launch more headroom.
This commit is contained in:
98 files changed
+6898
-2227
No files matched your search
+126
-135
@@ -4,38 +4,46 @@ import { test } from "node:test";
|
||||
import {
|
||||
DoubleTap,
|
||||
InputText,
|
||||
LongPress,
|
||||
PressKey,
|
||||
Scroll,
|
||||
Swipe,
|
||||
Tap,
|
||||
Wait,
|
||||
actions,
|
||||
always,
|
||||
doubleTaps,
|
||||
eventually,
|
||||
extract,
|
||||
from,
|
||||
keyedBy,
|
||||
longPresses,
|
||||
next,
|
||||
now,
|
||||
pressKey,
|
||||
pressKeys,
|
||||
scrolls,
|
||||
swipes,
|
||||
taps,
|
||||
typing,
|
||||
waitOnce,
|
||||
weighted,
|
||||
whenRoute,
|
||||
} from "../src/index.ts";
|
||||
import { setSamplerRng } from "../src/actions.ts";
|
||||
import { Pcg } from "../src/pcg.ts";
|
||||
import type { GeneratorNode } from "../src/action-tree.ts";
|
||||
import type {
|
||||
AccessibilityElement,
|
||||
Action,
|
||||
ActionGenerator,
|
||||
EventuallyFormula,
|
||||
Extracted,
|
||||
Formula,
|
||||
Sampler,
|
||||
State,
|
||||
SanderlingRuntime,
|
||||
WeightedEntry,
|
||||
} from "../src/types.ts";
|
||||
|
||||
// extract() and the LTL constructors stay host-bound on __sanderling__; the
|
||||
// action factories now return plain data and need no runtime. This fake records
|
||||
// the host-bound calls so the forwarding tests can assert them.
|
||||
interface RecordedRuntime extends SanderlingRuntime {
|
||||
extracts: Array<(state: State) => unknown>;
|
||||
extractNames: Array<string | undefined>;
|
||||
@@ -48,13 +56,10 @@ interface RecordedRuntime extends SanderlingRuntime {
|
||||
orCalls: number;
|
||||
andCalls: number;
|
||||
notCalls: number;
|
||||
actionGenerators: Array<() => Action[]>;
|
||||
weightedCalls: WeightedEntry[][];
|
||||
fromCalls: unknown[][];
|
||||
}
|
||||
|
||||
function makeChainableFormula(record: RecordedRuntime): Formula {
|
||||
const formula: Formula = {
|
||||
return {
|
||||
__sanderlingFormula: true,
|
||||
implies(other: Formula): Formula {
|
||||
record.impliesCalls++;
|
||||
@@ -76,7 +81,6 @@ function makeChainableFormula(record: RecordedRuntime): Formula {
|
||||
return makeChainableFormula(record);
|
||||
},
|
||||
};
|
||||
return formula;
|
||||
}
|
||||
|
||||
function makeChainableEventually(record: RecordedRuntime): EventuallyFormula {
|
||||
@@ -103,11 +107,8 @@ function installFakeRuntime(): RecordedRuntime {
|
||||
orCalls: 0,
|
||||
andCalls: 0,
|
||||
notCalls: 0,
|
||||
actionGenerators: [] as Array<() => Action[]>,
|
||||
weightedCalls: [] as WeightedEntry[][],
|
||||
fromCalls: [] as unknown[][],
|
||||
};
|
||||
const runtime = {
|
||||
const runtime: SanderlingRuntime = {
|
||||
extract: <T>(getter: (state: State) => T, name?: string): Extracted<T> => {
|
||||
calls.extracts.push(getter as (state: State) => unknown);
|
||||
calls.extractNames.push(name);
|
||||
@@ -129,42 +130,17 @@ function installFakeRuntime(): RecordedRuntime {
|
||||
calls.eventuallyPredicates.push(predicate);
|
||||
return makeChainableEventually(recorded);
|
||||
},
|
||||
actions: (generator: () => Action[]): ActionGenerator => {
|
||||
calls.actionGenerators.push(generator);
|
||||
return { __sanderlingActionGenerator: true, generate: generator };
|
||||
},
|
||||
weighted: (...entries: WeightedEntry[]): ActionGenerator => {
|
||||
calls.weightedCalls.push(entries);
|
||||
return { __sanderlingActionGenerator: true, generate: () => [] };
|
||||
},
|
||||
from: <T>(items: readonly T[]): Sampler<T> => {
|
||||
calls.fromCalls.push(items as unknown[]);
|
||||
return { generate: () => items[0] as T };
|
||||
},
|
||||
tap: ({ on }) => ({ kind: "Tap", on }),
|
||||
doubleTap: ({ on }) => ({ kind: "DoubleTap", on }),
|
||||
longPress: ({ on }) => ({ kind: "LongPress", on }),
|
||||
scroll: ({ direction, in: container }) => ({ kind: "Scroll", direction, in: container }),
|
||||
inputText: ({ into, text }) => ({ kind: "InputText", into, text }),
|
||||
swipe: ({ from: fromPoint, to, durationMillis }) => ({
|
||||
kind: "Swipe",
|
||||
from: fromPoint,
|
||||
to,
|
||||
durationMillis,
|
||||
}),
|
||||
pressKey: ({ key }) => ({ kind: "PressKey", key }),
|
||||
wait: ({ durationMillis }) => ({ kind: "Wait", durationMillis }),
|
||||
taps: { __sanderlingActionGenerator: true, generate: () => [] },
|
||||
doubleTaps: { __sanderlingActionGenerator: true, generate: () => [] },
|
||||
longPresses: { __sanderlingActionGenerator: true, generate: () => [] },
|
||||
scrolls: { __sanderlingActionGenerator: true, generate: () => [] },
|
||||
typing: { __sanderlingActionGenerator: true, generate: () => [] },
|
||||
swipes: { __sanderlingActionGenerator: true, generate: () => [] },
|
||||
waitOnce: { __sanderlingActionGenerator: true, generate: () => [] },
|
||||
pressKeys: { __sanderlingActionGenerator: true, generate: () => [] },
|
||||
} satisfies SanderlingRuntime;
|
||||
};
|
||||
const recorded = Object.assign(runtime, calls) as RecordedRuntime;
|
||||
globalThis.__sanderling__ = recorded;
|
||||
// web-runtime.ts locks __sanderling__ as non-writable (configurable) when it
|
||||
// is imported earlier in the same bun-test process, so a plain assignment
|
||||
// would throw. defineProperty installs (and reinstalls) the fake regardless.
|
||||
Object.defineProperty(globalThis, "__sanderling__", {
|
||||
value: recorded,
|
||||
writable: false,
|
||||
configurable: true,
|
||||
enumerable: false,
|
||||
});
|
||||
return recorded;
|
||||
}
|
||||
|
||||
@@ -202,14 +178,6 @@ test("always wraps a predicate into a formula via the runtime", () => {
|
||||
assert.equal(formula.__sanderlingFormula, true);
|
||||
});
|
||||
|
||||
test("always accepts a formula handle", () => {
|
||||
const runtime = installFakeRuntime();
|
||||
const inner = now(() => true);
|
||||
const wrapped = always(inner);
|
||||
assert.equal(runtime.alwaysArgs.at(-1), inner);
|
||||
assert.equal(wrapped.__sanderlingFormula, true);
|
||||
});
|
||||
|
||||
test("now/next/eventually forward predicates", () => {
|
||||
const runtime = installFakeRuntime();
|
||||
const p1 = () => true;
|
||||
@@ -240,20 +208,30 @@ test("formula chaining exposes implies/or/and/not", () => {
|
||||
assert.equal(runtime.notCalls, 1);
|
||||
});
|
||||
|
||||
test("Tap returns a TapAction with the supplied selector", () => {
|
||||
installFakeRuntime();
|
||||
const action = Tap({ on: "id:login_continue" });
|
||||
assert.deepEqual(action, { kind: "Tap", on: "id:login_continue" });
|
||||
test("Tap returns a TapAction descriptor", () => {
|
||||
assert.deepEqual(Tap({ on: "id:login_continue" }), {
|
||||
kind: "Tap",
|
||||
on: "id:login_continue",
|
||||
});
|
||||
});
|
||||
|
||||
test("DoubleTap returns a DoubleTapAction with the supplied selector", () => {
|
||||
installFakeRuntime();
|
||||
const action = DoubleTap({ on: "id:save" });
|
||||
assert.deepEqual(action, { kind: "DoubleTap", on: "id:save" });
|
||||
test("DoubleTap returns a DoubleTapAction descriptor", () => {
|
||||
assert.deepEqual(DoubleTap({ on: "id:save" }), { kind: "DoubleTap", on: "id:save" });
|
||||
});
|
||||
|
||||
test("LongPress returns a LongPressAction descriptor", () => {
|
||||
assert.deepEqual(LongPress({ on: "id:row" }), { kind: "LongPress", on: "id:row" });
|
||||
});
|
||||
|
||||
test("Scroll returns a ScrollAction descriptor", () => {
|
||||
assert.deepEqual(Scroll({ direction: "down", in: "id:list" }), {
|
||||
kind: "Scroll",
|
||||
direction: "down",
|
||||
in: "id:list",
|
||||
});
|
||||
});
|
||||
|
||||
test("Tap accepts an AccessibilityElement", () => {
|
||||
installFakeRuntime();
|
||||
const element: AccessibilityElement = {
|
||||
id: "login_continue",
|
||||
find: () => undefined,
|
||||
@@ -264,63 +242,92 @@ test("Tap accepts an AccessibilityElement", () => {
|
||||
assert.equal(action.on, element);
|
||||
});
|
||||
|
||||
test("InputText returns an InputTextAction", () => {
|
||||
installFakeRuntime();
|
||||
const action = InputText({ into: "id:phone", text: "+1234567890" });
|
||||
assert.deepEqual(action, { kind: "InputText", into: "id:phone", text: "+1234567890" });
|
||||
});
|
||||
|
||||
test("Swipe returns a SwipeAction with the supplied endpoints", () => {
|
||||
installFakeRuntime();
|
||||
const action = Swipe({ from: { x: 10, y: 20 }, to: { x: 30, y: 40 }, durationMillis: 400 });
|
||||
assert.deepEqual(action, {
|
||||
kind: "Swipe",
|
||||
from: { x: 10, y: 20 },
|
||||
to: { x: 30, y: 40 },
|
||||
durationMillis: 400,
|
||||
test("InputText returns an InputTextAction descriptor", () => {
|
||||
assert.deepEqual(InputText({ into: "id:phone", text: "+1234567890" }), {
|
||||
kind: "InputText",
|
||||
into: "id:phone",
|
||||
text: "+1234567890",
|
||||
});
|
||||
});
|
||||
|
||||
test("PressKey returns a PressKeyAction", () => {
|
||||
installFakeRuntime();
|
||||
const action = PressKey({ key: "back" });
|
||||
assert.deepEqual(action, { kind: "PressKey", key: "back" });
|
||||
test("Swipe returns a SwipeAction descriptor", () => {
|
||||
assert.deepEqual(
|
||||
Swipe({ from: { x: 10, y: 20 }, to: { x: 30, y: 40 }, durationMillis: 400 }),
|
||||
{ kind: "Swipe", from: { x: 10, y: 20 }, to: { x: 30, y: 40 }, durationMillis: 400 },
|
||||
);
|
||||
});
|
||||
|
||||
test("Wait returns a WaitAction", () => {
|
||||
installFakeRuntime();
|
||||
const action = Wait({ durationMillis: 500 });
|
||||
assert.deepEqual(action, { kind: "Wait", durationMillis: 500 });
|
||||
test("PressKey returns a PressKeyAction descriptor", () => {
|
||||
assert.deepEqual(PressKey({ key: "back" }), { kind: "PressKey", key: "back" });
|
||||
});
|
||||
|
||||
test("actions wraps a generator into the runtime's ActionGenerator", () => {
|
||||
const runtime = installFakeRuntime();
|
||||
test("Wait returns a WaitAction descriptor", () => {
|
||||
assert.deepEqual(Wait({ durationMillis: 500 }), { kind: "Wait", durationMillis: 500 });
|
||||
});
|
||||
|
||||
test("actions returns an actions node carrying the generator", () => {
|
||||
const generator = () => [Tap({ on: "id:x" })];
|
||||
const wrapped = actions(generator);
|
||||
assert.equal(runtime.actionGenerators[0], generator);
|
||||
assert.equal(wrapped.__sanderlingActionGenerator, true);
|
||||
const node = actions(generator);
|
||||
assert.equal(node.kind, "actions");
|
||||
assert.equal((node as { generate: unknown }).generate, generator);
|
||||
});
|
||||
|
||||
test("weighted forwards weighted entries to the runtime", () => {
|
||||
const runtime = installFakeRuntime();
|
||||
const entries: WeightedEntry[] = [
|
||||
test("weighted returns a weighted node carrying the branches", () => {
|
||||
const node = weighted([80, taps], [20, swipes]);
|
||||
assert.equal(node.kind, "weighted");
|
||||
assert.deepEqual((node as { branches: unknown }).branches, [
|
||||
[80, taps],
|
||||
[20, swipes],
|
||||
]);
|
||||
});
|
||||
|
||||
test("builtin factories return builtin nodes carrying their verb", () => {
|
||||
const cases: Array<[GeneratorNode, string]> = [
|
||||
[taps, "taps"],
|
||||
[doubleTaps, "doubleTaps"],
|
||||
[longPresses, "longPresses"],
|
||||
[scrolls, "scrolls"],
|
||||
[typing, "typing"],
|
||||
[swipes, "swipes"],
|
||||
[waitOnce, "waitOnce"],
|
||||
[pressKeys, "pressKeys"],
|
||||
];
|
||||
weighted(...entries);
|
||||
assert.deepEqual(runtime.weightedCalls[0], entries);
|
||||
for (const [node, verb] of cases) {
|
||||
assert.equal(node.kind, "builtin");
|
||||
assert.equal((node as { verb: string }).verb, verb);
|
||||
}
|
||||
});
|
||||
|
||||
test("from forwards items to the runtime", () => {
|
||||
const runtime = installFakeRuntime();
|
||||
const sampler = from(["a", "b", "c"]);
|
||||
assert.deepEqual(runtime.fromCalls[0], ["a", "b", "c"]);
|
||||
assert.equal(sampler.generate(), "a");
|
||||
test("from with a single item returns it without drawing", () => {
|
||||
const sampler = from(["only"]);
|
||||
setSamplerRng(new Pcg(42n, 0n));
|
||||
try {
|
||||
assert.equal(sampler.generate(), "only");
|
||||
} finally {
|
||||
setSamplerRng(null);
|
||||
}
|
||||
});
|
||||
|
||||
function elementWithChildren(
|
||||
cells: Record<string, string>,
|
||||
): AccessibilityElement {
|
||||
test("from draws intN(len) from the active picker rng", () => {
|
||||
const items = ["a", "b", "c"];
|
||||
const sampler = from(items);
|
||||
const rng = new Pcg(42n, 0n);
|
||||
const oracle = new Pcg(42n, 0n);
|
||||
setSamplerRng(rng);
|
||||
try {
|
||||
const index = oracle.intN(items.length);
|
||||
assert.equal(sampler.generate(), items[index]);
|
||||
} finally {
|
||||
setSamplerRng(null);
|
||||
}
|
||||
});
|
||||
|
||||
test("from falls back to the first item outside a picker walk", () => {
|
||||
setSamplerRng(null);
|
||||
assert.equal(from(["a", "b", "c"]).generate(), "a");
|
||||
});
|
||||
|
||||
function elementWithChildren(cells: Record<string, string>): AccessibilityElement {
|
||||
return {
|
||||
find: selector => {
|
||||
if (typeof selector === "string" || Array.isArray(selector)) return undefined;
|
||||
@@ -346,58 +353,42 @@ test("keyedBy joins testTag-resolved texts with a stable delimiter", () => {
|
||||
});
|
||||
|
||||
test("keyedBy returns empty string for an undefined element", () => {
|
||||
installFakeRuntime();
|
||||
assert.equal(keyedBy(undefined, ["TxnDate"]), "");
|
||||
});
|
||||
|
||||
test("keyedBy substitutes empty strings for missing children", () => {
|
||||
installFakeRuntime();
|
||||
const row = elementWithChildren({ TxnDate: "2026-04-26" });
|
||||
assert.equal(
|
||||
keyedBy(row, ["TxnDate", "TxnNote", "TxnAmount"]),
|
||||
"2026-04-26\x1f\x1f",
|
||||
);
|
||||
assert.equal(keyedBy(row, ["TxnDate", "TxnNote", "TxnAmount"]), "2026-04-26\x1f\x1f");
|
||||
});
|
||||
|
||||
test("whenRoute returns [] when current route does not match", () => {
|
||||
installFakeRuntime();
|
||||
test("whenRoute body is skipped when the current route does not match", () => {
|
||||
const route = { current: "home" as string | null };
|
||||
let bodyCalled = false;
|
||||
const generator = whenRoute(route, "ledger", () => {
|
||||
const node = whenRoute(route, "ledger", () => {
|
||||
bodyCalled = true;
|
||||
return [Tap({ on: "id:x" })];
|
||||
});
|
||||
assert.deepEqual(generator.generate(), []);
|
||||
assert.equal(node.kind, "actions");
|
||||
assert.deepEqual((node as { generate: () => unknown }).generate(), []);
|
||||
assert.equal(bodyCalled, false);
|
||||
});
|
||||
|
||||
test("whenRoute calls body when current route matches", () => {
|
||||
installFakeRuntime();
|
||||
test("whenRoute runs the body when the current route matches", () => {
|
||||
const route = { current: "ledger" as string | null };
|
||||
const generator = whenRoute(route, "ledger", () => [Tap({ on: "id:x" })]);
|
||||
const result = generator.generate();
|
||||
const node = whenRoute(route, "ledger", () => [Tap({ on: "id:x" })]);
|
||||
const result = (node as { generate: () => Array<{ kind: string }> }).generate();
|
||||
assert.equal(result.length, 1);
|
||||
assert.equal(result[0]?.kind, "Tap");
|
||||
});
|
||||
|
||||
test("whenRoute accepts an array of allowed routes", () => {
|
||||
installFakeRuntime();
|
||||
const route = { current: "add-account" as string | null };
|
||||
const generator = whenRoute(route, ["home", "add-account"], () => [Tap({ on: "id:x" })]);
|
||||
assert.equal(generator.generate().length, 1);
|
||||
const node = whenRoute(route, ["home", "add-account"], () => [Tap({ on: "id:x" })]);
|
||||
assert.equal((node as { generate: () => unknown[] }).generate().length, 1);
|
||||
});
|
||||
|
||||
test("whenRoute returns [] for null route", () => {
|
||||
installFakeRuntime();
|
||||
test("whenRoute body is skipped for a null route", () => {
|
||||
const route = { current: null as string | null };
|
||||
const generator = whenRoute(route, ["home"], () => [Tap({ on: "id:x" })]);
|
||||
assert.deepEqual(generator.generate(), []);
|
||||
});
|
||||
|
||||
test("default generators proxy through to the runtime", () => {
|
||||
installFakeRuntime();
|
||||
assert.equal(taps.__sanderlingActionGenerator, true);
|
||||
assert.equal(swipes.__sanderlingActionGenerator, true);
|
||||
assert.equal(waitOnce.__sanderlingActionGenerator, true);
|
||||
assert.equal(pressKey.__sanderlingActionGenerator, true);
|
||||
const node = whenRoute(route, ["home"], () => [Tap({ on: "id:x" })]);
|
||||
assert.deepEqual((node as { generate: () => unknown }).generate(), []);
|
||||
});
|
||||
@@ -2,99 +2,29 @@ import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
|
||||
import type {
|
||||
Action,
|
||||
ActionGenerator,
|
||||
EventuallyFormula,
|
||||
Extracted,
|
||||
Formula,
|
||||
Sampler,
|
||||
State,
|
||||
SanderlingRuntime,
|
||||
WeightedEntry,
|
||||
} from "../src/types.ts";
|
||||
|
||||
interface RecordedRuntime extends SanderlingRuntime {
|
||||
currentState: State;
|
||||
extractors: Array<(state: State) => unknown>;
|
||||
alwaysArgs: Array<(() => boolean) | Formula>;
|
||||
lastPredicate: (() => boolean) | undefined;
|
||||
}
|
||||
|
||||
function installRuntime(initialState: State): RecordedRuntime {
|
||||
const extractors: Array<(state: State) => unknown> = [];
|
||||
const extracted: Array<{ value: unknown }> = [];
|
||||
const alwaysArgs: Array<(() => boolean) | Formula> = [];
|
||||
let lastPredicate: (() => boolean) | undefined;
|
||||
|
||||
const runtime = {
|
||||
extract: <T>(getter: (state: State) => T): Extracted<T> => {
|
||||
extractors.push(getter as (state: State) => unknown);
|
||||
const slot = { value: getter(state.currentState) };
|
||||
extracted.push(slot);
|
||||
return {
|
||||
get current(): T {
|
||||
return slot.value as T;
|
||||
},
|
||||
previous: undefined,
|
||||
};
|
||||
},
|
||||
always: (predicateOrFormula: (() => boolean) | Formula): Formula => {
|
||||
alwaysArgs.push(predicateOrFormula);
|
||||
if (typeof predicateOrFormula === "function") {
|
||||
lastPredicate = predicateOrFormula;
|
||||
}
|
||||
return { __sanderlingFormula: true } as Formula;
|
||||
},
|
||||
// The defaults bundle still calls extract() and the LTL constructors, which
|
||||
// stay host-bound on __sanderling__. Action factories now return plain data
|
||||
// trees, so the fake runtime only needs the extract + formula surface.
|
||||
function installRuntime(initialState: State): void {
|
||||
const state = { current: initialState };
|
||||
const runtime: SanderlingRuntime = {
|
||||
extract: <T>(getter: (s: State) => T): Extracted<T> => ({
|
||||
current: getter(state.current),
|
||||
previous: undefined,
|
||||
}),
|
||||
always: () => ({ __sanderlingFormula: true } as Formula),
|
||||
now: () => ({ __sanderlingFormula: true } as Formula),
|
||||
next: () => ({ __sanderlingFormula: true } as Formula),
|
||||
eventually: () => ({ __sanderlingFormula: true } as EventuallyFormula),
|
||||
actions: (generator: () => Action[]): ActionGenerator => ({
|
||||
__sanderlingActionGenerator: true,
|
||||
generate: generator,
|
||||
}),
|
||||
weighted: (..._entries: WeightedEntry[]): ActionGenerator => ({
|
||||
__sanderlingActionGenerator: true,
|
||||
generate: () => [],
|
||||
}),
|
||||
from: <T>(_items: readonly T[]): Sampler<T> => ({ generate: () => _items[0] as T }),
|
||||
tap: ({ on }) => ({ kind: "Tap", on }),
|
||||
doubleTap: ({ on }) => ({ kind: "DoubleTap", on }),
|
||||
longPress: ({ on }) => ({ kind: "LongPress", on }),
|
||||
scroll: ({ direction, in: container }) => ({ kind: "Scroll", direction, in: container }),
|
||||
inputText: ({ into, text }) => ({ kind: "InputText", into, text }),
|
||||
swipe: (p) => ({ kind: "Swipe", from: p.from, to: p.to, durationMillis: p.durationMillis }),
|
||||
pressKey: ({ key }) => ({ kind: "PressKey", key }),
|
||||
wait: ({ durationMillis }) => ({ kind: "Wait", durationMillis }),
|
||||
taps: { __sanderlingActionGenerator: true, generate: () => [] } as ActionGenerator,
|
||||
doubleTaps: { __sanderlingActionGenerator: true, generate: () => [] } as ActionGenerator,
|
||||
longPresses: { __sanderlingActionGenerator: true, generate: () => [] } as ActionGenerator,
|
||||
scrolls: { __sanderlingActionGenerator: true, generate: () => [] } as ActionGenerator,
|
||||
typing: { __sanderlingActionGenerator: true, generate: () => [] } as ActionGenerator,
|
||||
swipes: { __sanderlingActionGenerator: true, generate: () => [] } as ActionGenerator,
|
||||
waitOnce: { __sanderlingActionGenerator: true, generate: () => [] } as ActionGenerator,
|
||||
pressKeys: { __sanderlingActionGenerator: true, generate: () => [] } as ActionGenerator,
|
||||
} satisfies SanderlingRuntime;
|
||||
|
||||
const state = { currentState: initialState };
|
||||
const recorded = Object.assign(runtime, {
|
||||
currentState: initialState,
|
||||
extractors,
|
||||
alwaysArgs,
|
||||
get lastPredicate() {
|
||||
return lastPredicate;
|
||||
},
|
||||
}) as unknown as RecordedRuntime;
|
||||
globalThis.__sanderling__ = recorded;
|
||||
// Re-bind state ref so subsequent extract() calls read the up-to-date state.
|
||||
Object.defineProperty(recorded, "currentState", {
|
||||
get() {
|
||||
return state.currentState;
|
||||
},
|
||||
set(next: State) {
|
||||
state.currentState = next;
|
||||
},
|
||||
});
|
||||
return recorded;
|
||||
};
|
||||
globalThis.__sanderling__ = runtime;
|
||||
}
|
||||
|
||||
const emptyState: State = {
|
||||
@@ -116,29 +46,29 @@ test("defaults bundle exports formulas tagged as LTL properties", async () => {
|
||||
assert.equal(defaults.noLogcatErrors.__sanderlingFormula, true);
|
||||
});
|
||||
|
||||
test("defaults bundle exports defaultActions as a valid ActionGenerator", async () => {
|
||||
test("defaults bundle exports defaultActions as a weighted node", async () => {
|
||||
installRuntime(emptyState);
|
||||
const defaults = await import("../src/defaults/actions.ts");
|
||||
assert.equal(defaults.defaultActions.__sanderlingActionGenerator, true);
|
||||
assert.equal(typeof defaults.defaultActions.generate, "function");
|
||||
assert.equal(defaults.defaultActions.kind, "weighted");
|
||||
});
|
||||
|
||||
test("typing resolves as a valid ActionGenerator", async () => {
|
||||
test("typing resolves as a builtin node", async () => {
|
||||
installRuntime(emptyState);
|
||||
const { typing } = await import("../src/defaults/actions.ts");
|
||||
assert.equal(typing.__sanderlingActionGenerator, true);
|
||||
assert.equal(typing.kind, "builtin");
|
||||
assert.equal((typing as { verb: string }).verb, "typing");
|
||||
});
|
||||
|
||||
test("longPresses and scrolls resolve as valid ActionGenerators", async () => {
|
||||
test("scrolls resolves as a builtin node", async () => {
|
||||
installRuntime(emptyState);
|
||||
const { longPresses, scrolls } = await import("../src/defaults/actions.ts");
|
||||
assert.equal(longPresses.__sanderlingActionGenerator, true);
|
||||
assert.equal(scrolls.__sanderlingActionGenerator, true);
|
||||
const { scrolls } = await import("../src/defaults/actions.ts");
|
||||
assert.equal(scrolls.kind, "builtin");
|
||||
assert.equal((scrolls as { verb: string }).verb, "scrolls");
|
||||
});
|
||||
|
||||
test("defaults barrel re-exports both properties and actions", async () => {
|
||||
installRuntime(emptyState);
|
||||
const barrel = await import("../src/defaults/index.ts");
|
||||
assert.equal(barrel.defaultActions.__sanderlingActionGenerator, true);
|
||||
assert.equal(barrel.defaultActions.kind, "weighted");
|
||||
assert.equal(barrel.noUncaughtExceptions.__sanderlingFormula, true);
|
||||
});
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
[
|
||||
{
|
||||
"kind": "Tap",
|
||||
"x": 250,
|
||||
"y": 260,
|
||||
"selector": "id:gamma"
|
||||
},
|
||||
{
|
||||
"kind": "Tap",
|
||||
"x": 150,
|
||||
"y": 160,
|
||||
"selector": "id:beta"
|
||||
},
|
||||
{
|
||||
"kind": "Tap",
|
||||
"x": 50,
|
||||
"y": 60,
|
||||
"selector": "id:alpha"
|
||||
},
|
||||
{
|
||||
"kind": "InputText",
|
||||
"x": 150,
|
||||
"y": 160,
|
||||
"text": "a",
|
||||
"selector": "id:beta"
|
||||
},
|
||||
{
|
||||
"kind": "InputText",
|
||||
"x": 50,
|
||||
"y": 60,
|
||||
"text": "\t\n",
|
||||
"selector": "id:alpha"
|
||||
},
|
||||
{
|
||||
"kind": "Tap",
|
||||
"x": 250,
|
||||
"y": 260,
|
||||
"selector": "id:gamma"
|
||||
},
|
||||
{
|
||||
"kind": "Tap",
|
||||
"x": 150,
|
||||
"y": 160,
|
||||
"selector": "id:beta"
|
||||
},
|
||||
{
|
||||
"kind": "Tap",
|
||||
"x": 250,
|
||||
"y": 260,
|
||||
"selector": "id:gamma"
|
||||
},
|
||||
{
|
||||
"kind": "Tap",
|
||||
"x": 150,
|
||||
"y": 160,
|
||||
"selector": "id:beta"
|
||||
},
|
||||
{
|
||||
"kind": "Tap",
|
||||
"x": 250,
|
||||
"y": 260,
|
||||
"selector": "id:gamma"
|
||||
},
|
||||
{
|
||||
"kind": "Tap",
|
||||
"x": 250,
|
||||
"y": 260,
|
||||
"selector": "id:gamma"
|
||||
},
|
||||
{
|
||||
"kind": "Tap",
|
||||
"x": 150,
|
||||
"y": 160,
|
||||
"selector": "id:beta"
|
||||
},
|
||||
{
|
||||
"kind": "Tap",
|
||||
"x": 250,
|
||||
"y": 260,
|
||||
"selector": "id:gamma"
|
||||
},
|
||||
{
|
||||
"kind": "Tap",
|
||||
"x": 50,
|
||||
"y": 60,
|
||||
"selector": "id:alpha"
|
||||
},
|
||||
{
|
||||
"kind": "InputText",
|
||||
"x": 150,
|
||||
"y": 160,
|
||||
"text": "999999999999999999999",
|
||||
"selector": "id:beta"
|
||||
},
|
||||
{
|
||||
"kind": "InputText",
|
||||
"x": 150,
|
||||
"y": 160,
|
||||
"text": "-1",
|
||||
"selector": "id:beta"
|
||||
},
|
||||
{
|
||||
"kind": "InputText",
|
||||
"x": 250,
|
||||
"y": 260,
|
||||
"text": "-1",
|
||||
"selector": "id:gamma"
|
||||
},
|
||||
{
|
||||
"kind": "Tap",
|
||||
"x": 50,
|
||||
"y": 60,
|
||||
"selector": "id:alpha"
|
||||
},
|
||||
{
|
||||
"kind": "Tap",
|
||||
"x": 250,
|
||||
"y": 260,
|
||||
"selector": "id:gamma"
|
||||
},
|
||||
{
|
||||
"kind": "Tap",
|
||||
"x": 50,
|
||||
"y": 60,
|
||||
"selector": "id:alpha"
|
||||
}
|
||||
]
|
||||
+1512
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,52 @@
|
||||
// Shared cross-runtime parity scenario: the FIXED seed, FIXED candidate list,
|
||||
// and FIXED action root that both the node test (parity.test.ts) and the goja
|
||||
// test (internal/verifier/parity_test.go) drive. Each side runs the SAME
|
||||
// pick.ts over the SAME Pcg and asserts the SAME committed golden
|
||||
// (fixtures/parity-golden.json); matching one golden on both sides proves the
|
||||
// two engines agree without either invoking the other.
|
||||
//
|
||||
// The candidate ORDER and the per-tick PCG draw order are the parity contract.
|
||||
// The weighted root mixes a tap branch (1 candidate draw) with a typing branch
|
||||
// (1 candidate draw + 1 corpus draw), so a tick exercises weighted selection, a
|
||||
// builtin, and the input corpus together; reordering candidates or adding or
|
||||
// dropping a draw on either side shifts the stream and fails the golden.
|
||||
|
||||
import { Pcg } from "../src/pcg.ts";
|
||||
import { nextAction } from "../src/pick.ts";
|
||||
import { serializeAction, type SerializedAction } from "../src/runtime-entry.ts";
|
||||
import { taps, typing, weighted } from "../src/actions.ts";
|
||||
import type { BuiltinVerb, Candidate, GeneratorNode, Host } from "../src/action-tree.ts";
|
||||
|
||||
export const PARITY_SEED_HI = 0x9e3779b97f4a7c15n;
|
||||
export const PARITY_STEPS = 20;
|
||||
|
||||
export const PARITY_CANDIDATES: Candidate[] = [
|
||||
{ x: 50, y: 60, selector: "id:alpha", width: 100, height: 40 },
|
||||
{ x: 150, y: 160, selector: "id:beta", width: 120, height: 48 },
|
||||
{ x: 250, y: 260, selector: "id:gamma", width: 80, height: 32 },
|
||||
];
|
||||
|
||||
// A 3:1 weighted split over taps and typing. The stub host returns the same
|
||||
// candidate list for every verb so the only variables are the draw order and
|
||||
// the JS engine's number/bigint behavior.
|
||||
export const PARITY_ROOT: GeneratorNode = weighted([3, taps], [1, typing]);
|
||||
|
||||
const HOST: Host = {
|
||||
platform: () => "android",
|
||||
queryCandidates: (_verb: BuiltinVerb) => PARITY_CANDIDATES,
|
||||
reportUnsupported: () => {},
|
||||
seedHi: () => PARITY_SEED_HI,
|
||||
seedLo: () => 0n,
|
||||
};
|
||||
|
||||
// runParity emits the parity scenario's action stream from a fresh Pcg. It
|
||||
// drives pick.ts directly (not installRuntime, whose globals are locked once)
|
||||
// so the caller can run it repeatedly to assert determinism.
|
||||
export function runParity(): (SerializedAction | null)[] {
|
||||
const rng = new Pcg(PARITY_SEED_HI, 0n);
|
||||
const stream: (SerializedAction | null)[] = [];
|
||||
for (let i = 0; i < PARITY_STEPS; i++) {
|
||||
stream.push(serializeAction(nextAction(PARITY_ROOT, rng, HOST)));
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { test } from "node:test";
|
||||
|
||||
import { PARITY_STEPS, runParity } from "./parity-harness.ts";
|
||||
|
||||
const goldenPath = fileURLToPath(new URL("./fixtures/parity-golden.json", import.meta.url));
|
||||
const golden = JSON.parse(readFileSync(goldenPath, "utf8"));
|
||||
|
||||
// The node side of the W2 acceptance gate: the shared picker's stream for the
|
||||
// fixed parity scenario must match the committed golden byte-for-byte. The goja
|
||||
// test asserts the SAME golden, so a match on both sides proves cross-runtime
|
||||
// parity. A drift here means pick.ts, the corpus, or the Pcg changed.
|
||||
test("node picker matches the cross-runtime golden", () => {
|
||||
const stream = runParity();
|
||||
assert.equal(stream.length, PARITY_STEPS);
|
||||
assert.deepEqual(stream, golden);
|
||||
});
|
||||
|
||||
// Determinism: a second run from the same seed yields the identical stream.
|
||||
test("node picker is deterministic across repeated runs", () => {
|
||||
assert.deepEqual(runParity(), runParity());
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { dirname, join } from "node:path";
|
||||
import { Pcg } from "../src/pcg.ts";
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const fixturePath = join(here, "fixtures", "pcg-golden.json");
|
||||
|
||||
interface GoldenCase {
|
||||
seed: { hi: string; lo: string };
|
||||
uint64: string[];
|
||||
float64: number[];
|
||||
intN: Record<string, number[]>;
|
||||
}
|
||||
|
||||
const cases: GoldenCase[] = JSON.parse(readFileSync(fixturePath, "utf8"));
|
||||
|
||||
function seedLabel(c: GoldenCase): string {
|
||||
return `seed(${c.seed.hi}, ${c.seed.lo})`;
|
||||
}
|
||||
|
||||
test("golden fixture has the expected shape", () => {
|
||||
assert.ok(cases.length >= 5, "expected several seed cases");
|
||||
for (const c of cases) {
|
||||
assert.equal(c.uint64.length, 40);
|
||||
assert.equal(c.float64.length, 40);
|
||||
for (const draws of Object.values(c.intN)) {
|
||||
assert.equal(draws.length, 40);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
for (const c of cases) {
|
||||
test(`${seedLabel(c)} uint64 sequence is bit-exact`, () => {
|
||||
const pcg = new Pcg(BigInt(c.seed.hi), BigInt(c.seed.lo));
|
||||
c.uint64.forEach((want, i) => {
|
||||
assert.equal(pcg.uint64(), BigInt(want), `uint64 draw ${i}`);
|
||||
});
|
||||
});
|
||||
|
||||
test(`${seedLabel(c)} float64 sequence is bit-exact`, () => {
|
||||
const pcg = new Pcg(BigInt(c.seed.hi), BigInt(c.seed.lo));
|
||||
c.float64.forEach((want, i) => {
|
||||
assert.equal(pcg.float64(), want, `float64 draw ${i}`);
|
||||
});
|
||||
});
|
||||
|
||||
for (const [n, expected] of Object.entries(c.intN)) {
|
||||
test(`${seedLabel(c)} intN(${n}) sequence is bit-exact`, () => {
|
||||
const pcg = new Pcg(BigInt(c.seed.hi), BigInt(c.seed.lo));
|
||||
expected.forEach((want, i) => {
|
||||
assert.equal(pcg.intN(Number(n)), want, `intN(${n}) draw ${i}`);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { Pcg } from "../src/pcg.ts";
|
||||
import { nextAction, walk } from "../src/pick.ts";
|
||||
import { INPUT_CORPUS, NATIVE_PRESS_KEYS, WEB_PRESS_KEYS } from "../src/corpus.ts";
|
||||
import { resetWarnings } from "../src/verbs.ts";
|
||||
import type {
|
||||
ActionDescriptor,
|
||||
BuiltinVerb,
|
||||
Candidate,
|
||||
GeneratorNode,
|
||||
Host,
|
||||
} from "../src/action-tree.ts";
|
||||
|
||||
type Platform = "android" | "ios" | "web";
|
||||
|
||||
// stubHost returns a fixed candidate list for every verb and records each
|
||||
// reportUnsupported call so warn-once semantics are observable.
|
||||
function stubHost(
|
||||
platform: Platform,
|
||||
candidates: Candidate[],
|
||||
): Host & { unsupported: BuiltinVerb[] } {
|
||||
const unsupported: BuiltinVerb[] = [];
|
||||
return {
|
||||
unsupported,
|
||||
platform: () => platform,
|
||||
queryCandidates: () => candidates,
|
||||
reportUnsupported: (verb) => {
|
||||
unsupported.push(verb);
|
||||
},
|
||||
seedHi: () => 0n,
|
||||
seedLo: () => 0n,
|
||||
};
|
||||
}
|
||||
|
||||
const POINTS: Candidate[] = [
|
||||
{ x: 10, y: 20, selector: "id:a", width: 100, height: 200 },
|
||||
{ x: 30, y: 40, selector: "id:b", width: 100, height: 200 },
|
||||
{ x: 50, y: 60, selector: "id:c", width: 100, height: 200 },
|
||||
];
|
||||
|
||||
function builtin(verb: BuiltinVerb): GeneratorNode {
|
||||
return { kind: "builtin", verb };
|
||||
}
|
||||
|
||||
test("taps draws one candidate index and targets its point", () => {
|
||||
resetWarnings();
|
||||
const host = stubHost("android", POINTS);
|
||||
const rng = new Pcg(42n, 0n);
|
||||
const oracle = new Pcg(42n, 0n);
|
||||
const expectedIndex = oracle.intN(POINTS.length);
|
||||
|
||||
const action = walk(builtin("taps"), rng, host);
|
||||
assert.deepEqual(action, {
|
||||
kind: "Tap",
|
||||
on: {
|
||||
x: POINTS[expectedIndex]!.x,
|
||||
y: POINTS[expectedIndex]!.y,
|
||||
selector: POINTS[expectedIndex]!.selector,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("typing draws candidate index then corpus index, in that order", () => {
|
||||
resetWarnings();
|
||||
const host = stubHost("android", POINTS);
|
||||
const rng = new Pcg(42n, 0n);
|
||||
const oracle = new Pcg(42n, 0n);
|
||||
const candidateIndex = oracle.intN(POINTS.length);
|
||||
const corpusIndex = oracle.intN(INPUT_CORPUS.length);
|
||||
|
||||
const action = walk(builtin("typing"), rng, host) as ActionDescriptor & {
|
||||
kind: "InputText";
|
||||
};
|
||||
assert.equal(action.kind, "InputText");
|
||||
assert.deepEqual(action.into, {
|
||||
x: POINTS[candidateIndex]!.x,
|
||||
y: POINTS[candidateIndex]!.y,
|
||||
selector: POINTS[candidateIndex]!.selector,
|
||||
});
|
||||
assert.equal(action.text, INPUT_CORPUS[corpusIndex]);
|
||||
});
|
||||
|
||||
test("swipes draw candidate, magnitude (200+intN(401)), then direction", () => {
|
||||
resetWarnings();
|
||||
const host = stubHost("android", POINTS);
|
||||
const rng = new Pcg(7n, 0n);
|
||||
const oracle = new Pcg(7n, 0n);
|
||||
const candidateIndex = oracle.intN(POINTS.length);
|
||||
const magnitude = 200 + oracle.intN(401);
|
||||
const direction = oracle.intN(4);
|
||||
|
||||
const from = { x: POINTS[candidateIndex]!.x, y: POINTS[candidateIndex]!.y };
|
||||
const expectedTo = { x: from.x, y: from.y };
|
||||
switch (direction) {
|
||||
case 0:
|
||||
expectedTo.y = Math.max(0, from.y - magnitude);
|
||||
break;
|
||||
case 1:
|
||||
expectedTo.y = Math.max(0, from.y + magnitude);
|
||||
break;
|
||||
case 2:
|
||||
expectedTo.x = Math.max(0, from.x - magnitude);
|
||||
break;
|
||||
case 3:
|
||||
expectedTo.x = Math.max(0, from.x + magnitude);
|
||||
break;
|
||||
}
|
||||
|
||||
const action = walk(builtin("swipes"), rng, host) as ActionDescriptor & {
|
||||
kind: "Swipe";
|
||||
};
|
||||
assert.equal(action.kind, "Swipe");
|
||||
assert.deepEqual(action.from, from);
|
||||
assert.deepEqual(action.to, expectedTo);
|
||||
assert.equal(action.durationMillis, 250);
|
||||
});
|
||||
|
||||
test("scrolls draw candidate index then direction", () => {
|
||||
resetWarnings();
|
||||
const host = stubHost("android", POINTS);
|
||||
const rng = new Pcg(99n, 0n);
|
||||
const oracle = new Pcg(99n, 0n);
|
||||
const candidateIndex = oracle.intN(POINTS.length);
|
||||
const directionIndex = oracle.intN(4);
|
||||
const directions = ["up", "down", "left", "right"] as const;
|
||||
|
||||
const action = walk(builtin("scrolls"), rng, host) as ActionDescriptor & {
|
||||
kind: "Scroll";
|
||||
};
|
||||
assert.equal(action.kind, "Scroll");
|
||||
assert.equal(action.direction, directions[directionIndex]);
|
||||
assert.deepEqual(action.in, {
|
||||
x: POINTS[candidateIndex]!.x,
|
||||
y: POINTS[candidateIndex]!.y,
|
||||
});
|
||||
});
|
||||
|
||||
test("doubleTaps and longPresses draw exactly one candidate index", () => {
|
||||
resetWarnings();
|
||||
for (const verb of ["doubleTaps", "longPresses"] as const) {
|
||||
const host = stubHost("android", POINTS);
|
||||
const rng = new Pcg(123n, 0n);
|
||||
const oracle = new Pcg(123n, 0n);
|
||||
const index = oracle.intN(POINTS.length);
|
||||
const action = walk(builtin(verb), rng, host);
|
||||
const kind = verb === "doubleTaps" ? "DoubleTap" : "LongPress";
|
||||
assert.deepEqual(action, {
|
||||
kind,
|
||||
on: {
|
||||
x: POINTS[index]!.x,
|
||||
y: POINTS[index]!.y,
|
||||
selector: POINTS[index]!.selector,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test("waitOnce emits a 500ms wait and draws nothing", () => {
|
||||
resetWarnings();
|
||||
const host = stubHost("android", POINTS);
|
||||
const rng = new Pcg(42n, 0n);
|
||||
const before = rng.float64();
|
||||
const after = rng.float64();
|
||||
|
||||
const fresh = new Pcg(42n, 0n);
|
||||
fresh.float64();
|
||||
const action = walk(builtin("waitOnce"), fresh, host);
|
||||
const afterWait = fresh.float64();
|
||||
|
||||
assert.deepEqual(action, { kind: "Wait", durationMillis: 500 });
|
||||
// The wait consumed no draw, so the stream is identical with or without it.
|
||||
assert.equal(afterWait, after);
|
||||
assert.notEqual(before, after);
|
||||
});
|
||||
|
||||
test("pressKeys on native draws from NATIVE_PRESS_KEYS", () => {
|
||||
resetWarnings();
|
||||
const host = stubHost("android", POINTS);
|
||||
const rng = new Pcg(42n, 0n);
|
||||
const oracle = new Pcg(42n, 0n);
|
||||
const index = oracle.intN(NATIVE_PRESS_KEYS.length);
|
||||
const action = walk(builtin("pressKeys"), rng, host);
|
||||
assert.deepEqual(action, { kind: "PressKey", key: NATIVE_PRESS_KEYS[index] });
|
||||
});
|
||||
|
||||
test("pressKeys on web draws from WEB_PRESS_KEYS", () => {
|
||||
resetWarnings();
|
||||
const host = stubHost("web", POINTS);
|
||||
const rng = new Pcg(2024n, 0n);
|
||||
const oracle = new Pcg(2024n, 0n);
|
||||
const index = oracle.intN(WEB_PRESS_KEYS.length);
|
||||
const action = walk(builtin("pressKeys"), rng, host);
|
||||
assert.deepEqual(action, { kind: "PressKey", key: WEB_PRESS_KEYS[index] });
|
||||
});
|
||||
|
||||
test("empty candidate list yields null without drawing", () => {
|
||||
resetWarnings();
|
||||
const host = stubHost("android", []);
|
||||
const rng = new Pcg(42n, 0n);
|
||||
assert.equal(walk(builtin("taps"), rng, host), null);
|
||||
// No draw consumed: next float64 matches a fresh stream's first draw.
|
||||
assert.equal(rng.float64(), new Pcg(42n, 0n).float64());
|
||||
});
|
||||
|
||||
test("weighted: one float64 draw, ascending cumulative scan", () => {
|
||||
resetWarnings();
|
||||
const host = stubHost("android", POINTS);
|
||||
const tap: GeneratorNode = builtin("taps");
|
||||
const wait: GeneratorNode = builtin("waitOnce");
|
||||
// total = 3; draw = float64()*3 decides the branch by ascending cumulative.
|
||||
const node: GeneratorNode = {
|
||||
kind: "weighted",
|
||||
branches: [
|
||||
[1, tap],
|
||||
[2, wait],
|
||||
],
|
||||
};
|
||||
|
||||
const rng = new Pcg(42n, 0n);
|
||||
const oracle = new Pcg(42n, 0n);
|
||||
const draw = oracle.float64() * 3;
|
||||
const expectFirst = draw < 1; // cumulative after branch 0 is 1.
|
||||
|
||||
const action = walk(node, rng, host);
|
||||
if (expectFirst) {
|
||||
assert.equal((action as ActionDescriptor).kind, "Tap");
|
||||
} else {
|
||||
assert.deepEqual(action, { kind: "Wait", durationMillis: 500 });
|
||||
}
|
||||
});
|
||||
|
||||
test("weighted: a zero-weight branch is never selected", () => {
|
||||
resetWarnings();
|
||||
const host = stubHost("android", POINTS);
|
||||
const poison: GeneratorNode = {
|
||||
kind: "actions",
|
||||
generate: () => {
|
||||
throw new Error("zero-weight branch must never be walked");
|
||||
},
|
||||
};
|
||||
const node: GeneratorNode = {
|
||||
kind: "weighted",
|
||||
branches: [
|
||||
[0, poison],
|
||||
[1, builtin("waitOnce")],
|
||||
],
|
||||
};
|
||||
// Drive many seeds: the zero-weight branch must never be entered.
|
||||
for (let seed = 1; seed <= 200; seed++) {
|
||||
const action = walk(node, new Pcg(BigInt(seed), 0n), host);
|
||||
assert.deepEqual(action, { kind: "Wait", durationMillis: 500 });
|
||||
}
|
||||
});
|
||||
|
||||
test("weighted: all-zero (or negative) weights return null", () => {
|
||||
resetWarnings();
|
||||
const host = stubHost("android", POINTS);
|
||||
const node: GeneratorNode = {
|
||||
kind: "weighted",
|
||||
branches: [
|
||||
[0, builtin("waitOnce")],
|
||||
[-5, builtin("taps")],
|
||||
],
|
||||
};
|
||||
assert.equal(walk(node, new Pcg(42n, 0n), host), null);
|
||||
});
|
||||
|
||||
test("actions: single-element list draws nothing", () => {
|
||||
resetWarnings();
|
||||
const only: ActionDescriptor = { kind: "Wait", durationMillis: 10 };
|
||||
const node: GeneratorNode = { kind: "actions", generate: () => [only] };
|
||||
const rng = new Pcg(42n, 0n);
|
||||
const action = walk(node, rng, stubHost("android", POINTS));
|
||||
assert.deepEqual(action, only);
|
||||
// No draw consumed for a singleton list.
|
||||
assert.equal(rng.float64(), new Pcg(42n, 0n).float64());
|
||||
});
|
||||
|
||||
test("actions: multi-element list draws one intN(len) index", () => {
|
||||
resetWarnings();
|
||||
const list: ActionDescriptor[] = [
|
||||
{ kind: "Wait", durationMillis: 1 },
|
||||
{ kind: "Wait", durationMillis: 2 },
|
||||
{ kind: "Wait", durationMillis: 3 },
|
||||
];
|
||||
const node: GeneratorNode = { kind: "actions", generate: () => [...list] };
|
||||
const rng = new Pcg(42n, 0n);
|
||||
const oracle = new Pcg(42n, 0n);
|
||||
const index = oracle.intN(list.length);
|
||||
assert.deepEqual(walk(node, rng, stubHost("android", POINTS)), list[index]);
|
||||
});
|
||||
|
||||
test("actions: empty list yields null", () => {
|
||||
resetWarnings();
|
||||
const node: GeneratorNode = { kind: "actions", generate: () => [] };
|
||||
assert.equal(walk(node, new Pcg(42n, 0n), stubHost("android", POINTS)), null);
|
||||
});
|
||||
|
||||
test("corpus reproducibility: same seed yields the same typed text", () => {
|
||||
resetWarnings();
|
||||
const host = stubHost("android", POINTS);
|
||||
const first = walk(builtin("typing"), new Pcg(2024n, 0n), host) as ActionDescriptor & {
|
||||
kind: "InputText";
|
||||
};
|
||||
const second = walk(builtin("typing"), new Pcg(2024n, 0n), host) as ActionDescriptor & {
|
||||
kind: "InputText";
|
||||
};
|
||||
assert.equal(first.text, second.text);
|
||||
assert.ok(INPUT_CORPUS.includes(first.text));
|
||||
});
|
||||
|
||||
test("nextAction retries up to 16 times then returns null", () => {
|
||||
resetWarnings();
|
||||
// An empty weighted tree always returns null; nextAction must give up, not loop.
|
||||
const empty: GeneratorNode = { kind: "weighted", branches: [] };
|
||||
assert.equal(nextAction(empty, new Pcg(42n, 0n), stubHost("android", POINTS)), null);
|
||||
});
|
||||
|
||||
test("nextAction returns the first non-null walk result", () => {
|
||||
resetWarnings();
|
||||
let calls = 0;
|
||||
// First two walks yield null (empty list), third yields an action. nextAction
|
||||
// should return on the third attempt.
|
||||
const node: GeneratorNode = {
|
||||
kind: "actions",
|
||||
generate: () => {
|
||||
calls++;
|
||||
return calls >= 3 ? [{ kind: "Wait", durationMillis: 5 }] : [];
|
||||
},
|
||||
};
|
||||
const action = nextAction(node, new Pcg(42n, 0n), stubHost("android", POINTS));
|
||||
assert.deepEqual(action, { kind: "Wait", durationMillis: 5 });
|
||||
assert.equal(calls, 3);
|
||||
});
|
||||
@@ -0,0 +1,181 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
|
||||
import { serializeAction } from "../src/runtime-entry.ts";
|
||||
import type { ActionDescriptor } from "../src/action-tree.ts";
|
||||
|
||||
// decodeWire mirrors the Go decodeAction reading the unified flat contract: a
|
||||
// field rename (fromX vs from_x) would make these assertions fail here, the
|
||||
// same way it would silently no-op web actions in production.
|
||||
const POINT = { x: 12, y: 34 };
|
||||
|
||||
test("Tap serializes to the flat point contract", () => {
|
||||
assert.deepEqual(serializeAction({ kind: "Tap", on: POINT }), {
|
||||
kind: "Tap",
|
||||
x: 12,
|
||||
y: 34,
|
||||
});
|
||||
});
|
||||
|
||||
test("Tap carries a resolved selector when present", () => {
|
||||
const target = { x: 1, y: 2, selector: "id:save" };
|
||||
assert.deepEqual(serializeAction({ kind: "Tap", on: target }), {
|
||||
kind: "Tap",
|
||||
x: 1,
|
||||
y: 2,
|
||||
selector: "id:save",
|
||||
});
|
||||
});
|
||||
|
||||
test("DoubleTap and LongPress share the point contract", () => {
|
||||
assert.deepEqual(serializeAction({ kind: "DoubleTap", on: POINT }), {
|
||||
kind: "DoubleTap",
|
||||
x: 12,
|
||||
y: 34,
|
||||
});
|
||||
assert.deepEqual(serializeAction({ kind: "LongPress", on: POINT }), {
|
||||
kind: "LongPress",
|
||||
x: 12,
|
||||
y: 34,
|
||||
});
|
||||
});
|
||||
|
||||
test("InputText carries x, y and text", () => {
|
||||
assert.deepEqual(serializeAction({ kind: "InputText", into: POINT, text: "hi" }), {
|
||||
kind: "InputText",
|
||||
x: 12,
|
||||
y: 34,
|
||||
text: "hi",
|
||||
});
|
||||
});
|
||||
|
||||
test("Swipe emits camelCase fromX/fromY/toX/toY/durationMillis", () => {
|
||||
const action: ActionDescriptor = {
|
||||
kind: "Swipe",
|
||||
from: { x: 5, y: 6 },
|
||||
to: { x: 7, y: 8 },
|
||||
durationMillis: 300,
|
||||
};
|
||||
assert.deepEqual(serializeAction(action), {
|
||||
kind: "Swipe",
|
||||
fromX: 5,
|
||||
fromY: 6,
|
||||
toX: 7,
|
||||
toY: 8,
|
||||
durationMillis: 300,
|
||||
});
|
||||
});
|
||||
|
||||
test("Swipe defaults durationMillis to 250", () => {
|
||||
const action = serializeAction({
|
||||
kind: "Swipe",
|
||||
from: { x: 0, y: 0 },
|
||||
to: { x: 0, y: 1 },
|
||||
}) as { durationMillis: number };
|
||||
assert.equal(action.durationMillis, 250);
|
||||
});
|
||||
|
||||
test("Scroll emits direction plus from/to point and duration", () => {
|
||||
assert.deepEqual(serializeAction({ kind: "Scroll", direction: "down", in: POINT }), {
|
||||
kind: "Scroll",
|
||||
direction: "down",
|
||||
fromX: 12,
|
||||
fromY: 34,
|
||||
toX: 12,
|
||||
toY: 34,
|
||||
durationMillis: 250,
|
||||
});
|
||||
});
|
||||
|
||||
test("PressKey and Wait pass through their fields", () => {
|
||||
assert.deepEqual(serializeAction({ kind: "PressKey", key: "enter" }), {
|
||||
kind: "PressKey",
|
||||
key: "enter",
|
||||
});
|
||||
assert.deepEqual(serializeAction({ kind: "Wait", durationMillis: 500 }), {
|
||||
kind: "Wait",
|
||||
durationMillis: 500,
|
||||
});
|
||||
});
|
||||
|
||||
test("builtin Scroll carries the pre-computed to endpoint", () => {
|
||||
assert.deepEqual(
|
||||
serializeAction({
|
||||
kind: "Scroll",
|
||||
direction: "down",
|
||||
in: { x: 100, y: 200 },
|
||||
from: { x: 100, y: 200 },
|
||||
to: { x: 100, y: 120 },
|
||||
}),
|
||||
{
|
||||
kind: "Scroll",
|
||||
direction: "down",
|
||||
fromX: 100,
|
||||
fromY: 200,
|
||||
toX: 100,
|
||||
toY: 120,
|
||||
durationMillis: 250,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("a string target serializes selector-only for the runner to re-resolve", () => {
|
||||
assert.deepEqual(serializeAction({ kind: "Tap", on: "id:save" }), {
|
||||
kind: "Tap",
|
||||
x: 0,
|
||||
y: 0,
|
||||
selector: "id:save",
|
||||
});
|
||||
});
|
||||
|
||||
test("an empty target or null action is dropped", () => {
|
||||
assert.equal(serializeAction({ kind: "Tap", on: "" }), null);
|
||||
assert.equal(serializeAction(null), null);
|
||||
});
|
||||
|
||||
// Wire round-trip: serialize -> JSON -> parse asserts every field the Go
|
||||
// decodeAction reads survives by its exact camelCase name. A rename (fromX vs
|
||||
// from_x) would silently turn web/native actions into no-ops; this catches it.
|
||||
test("serialized actions JSON round-trip with the decoder's field names", () => {
|
||||
const cases: ActionDescriptor[] = [
|
||||
{ kind: "Tap", on: { x: 1, y: 2, selector: "id:a" } as never },
|
||||
{ kind: "InputText", into: { x: 3, y: 4 } as never, text: "x" },
|
||||
{ kind: "Swipe", from: { x: 5, y: 6 }, to: { x: 7, y: 8 }, durationMillis: 9 },
|
||||
{ kind: "Scroll", direction: "up", in: { x: 1, y: 1 } as never },
|
||||
{ kind: "PressKey", key: "enter" },
|
||||
{ kind: "Wait", durationMillis: 10 },
|
||||
];
|
||||
for (const descriptor of cases) {
|
||||
const wire = serializeAction(descriptor);
|
||||
assert.ok(wire, `expected ${descriptor.kind} to serialize`);
|
||||
const decoded = JSON.parse(JSON.stringify(wire)) as Record<string, unknown>;
|
||||
assert.equal(decoded.kind, wire!.kind);
|
||||
switch (wire!.kind) {
|
||||
case "Tap":
|
||||
assert.equal(typeof decoded.x, "number");
|
||||
assert.equal(typeof decoded.y, "number");
|
||||
assert.equal(decoded.selector, "id:a");
|
||||
break;
|
||||
case "InputText":
|
||||
assert.equal(typeof decoded.x, "number");
|
||||
assert.equal(decoded.text, "x");
|
||||
break;
|
||||
case "Swipe":
|
||||
assert.equal(decoded.fromX, 5);
|
||||
assert.equal(decoded.toY, 8);
|
||||
assert.equal(decoded.durationMillis, 9);
|
||||
break;
|
||||
case "Scroll":
|
||||
assert.equal(decoded.direction, "up");
|
||||
assert.equal(typeof decoded.fromX, "number");
|
||||
assert.equal(typeof decoded.toX, "number");
|
||||
break;
|
||||
case "PressKey":
|
||||
assert.equal(decoded.key, "enter");
|
||||
break;
|
||||
case "Wait":
|
||||
assert.equal(decoded.durationMillis, 10);
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { Pcg } from "../src/pcg.ts";
|
||||
import { setSamplerRng } from "../src/sampler-rng.ts";
|
||||
import { edgeCaseText, emails, integers, strings } from "../src/values.ts";
|
||||
import { INPUT_CORPUS } from "../src/corpus.ts";
|
||||
import type { Sampler } from "../src/types.ts";
|
||||
|
||||
function withRng<T>(seed: bigint, body: () => T): T {
|
||||
setSamplerRng(new Pcg(seed, 0n));
|
||||
try {
|
||||
return body();
|
||||
} finally {
|
||||
setSamplerRng(null);
|
||||
}
|
||||
}
|
||||
|
||||
test("same seed yields an identical draw sequence", () => {
|
||||
const drawAll = () => [
|
||||
strings().generate(),
|
||||
integers().between(0, 999).generate(),
|
||||
emails().domain("folio.app").generate(),
|
||||
edgeCaseText().generate(),
|
||||
];
|
||||
assert.deepEqual(withRng(7n, drawAll), withRng(7n, drawAll));
|
||||
});
|
||||
|
||||
test("a different seed yields a different sequence", () => {
|
||||
const drawAll = () => [strings().generate(), integers().generate()];
|
||||
assert.notDeepEqual(withRng(1n, drawAll), withRng(2n, drawAll));
|
||||
});
|
||||
|
||||
test("integers().between constrains the output range", () => {
|
||||
withRng(42n, () => {
|
||||
for (let i = 0; i < 200; i++) {
|
||||
const value = integers().between(5, 9).generate();
|
||||
assert.ok(Number.isInteger(value));
|
||||
assert.ok(value >= 5 && value <= 9, `out of range: ${value}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test("strings().length(min, max).alpha() constrains length and charset", () => {
|
||||
withRng(99n, () => {
|
||||
for (let i = 0; i < 200; i++) {
|
||||
const value = strings().length(3, 6).alpha().generate();
|
||||
assert.ok(value.length >= 3 && value.length <= 6, `bad length: ${value}`);
|
||||
assert.match(value, /^[A-Za-z]*$/);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test("emails().domain sets the host and edgeCaseText draws from the corpus", () => {
|
||||
withRng(3n, () => {
|
||||
const email = emails().domain("folio.app").generate();
|
||||
assert.match(email, /^[A-Za-z]+@folio\.app$/);
|
||||
assert.ok(INPUT_CORPUS.includes(edgeCaseText().generate()));
|
||||
});
|
||||
});
|
||||
|
||||
test("a builder is itself a Sampler<T>", () => {
|
||||
withRng(11n, () => {
|
||||
const sampler: Sampler<number> = integers().between(0, 9);
|
||||
const value = sampler.generate();
|
||||
assert.ok(value >= 0 && value <= 9);
|
||||
});
|
||||
});
|
||||
|
||||
test("outside a walk generators return a fixed deterministic default", () => {
|
||||
setSamplerRng(null);
|
||||
assert.equal(integers().between(10, 20).generate(), 10);
|
||||
assert.equal(strings().length(4, 8).alpha().generate(), "aaaa");
|
||||
assert.equal(emails().domain("folio.app").generate(), "[email protected]");
|
||||
assert.equal(edgeCaseText().generate(), INPUT_CORPUS[0]);
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { supports, warnUnsupportedOnce, resetWarnings } from "../src/verbs.ts";
|
||||
import type { BuiltinVerb, Host } from "../src/action-tree.ts";
|
||||
|
||||
const ALL_VERBS: BuiltinVerb[] = [
|
||||
"taps",
|
||||
"doubleTaps",
|
||||
"longPresses",
|
||||
"scrolls",
|
||||
"typing",
|
||||
"swipes",
|
||||
"waitOnce",
|
||||
"pressKeys",
|
||||
];
|
||||
|
||||
function countingHost(platform: "android" | "ios" | "web"): Host & { calls: BuiltinVerb[] } {
|
||||
const calls: BuiltinVerb[] = [];
|
||||
return {
|
||||
calls,
|
||||
platform: () => platform,
|
||||
queryCandidates: () => [],
|
||||
reportUnsupported: (verb) => {
|
||||
calls.push(verb);
|
||||
},
|
||||
seedHi: () => 0n,
|
||||
seedLo: () => 0n,
|
||||
};
|
||||
}
|
||||
|
||||
test("every verb is supported on native platforms", () => {
|
||||
for (const verb of ALL_VERBS) {
|
||||
assert.equal(supports(verb, "android"), true, `android ${verb}`);
|
||||
assert.equal(supports(verb, "ios"), true, `ios ${verb}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("web supports the full builtin verb set (declared, not silently no-op)", () => {
|
||||
for (const verb of ALL_VERBS) {
|
||||
assert.equal(supports(verb, "web"), true, `web ${verb}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("warn-once reports a verb exactly once per platform", () => {
|
||||
resetWarnings();
|
||||
const host = countingHost("web");
|
||||
assert.equal(warnUnsupportedOnce(host, "swipes"), true);
|
||||
assert.equal(warnUnsupportedOnce(host, "swipes"), false);
|
||||
assert.equal(warnUnsupportedOnce(host, "swipes"), false);
|
||||
assert.deepEqual(host.calls, ["swipes"]);
|
||||
});
|
||||
|
||||
test("warn-once keys by verb@platform independently", () => {
|
||||
resetWarnings();
|
||||
const web = countingHost("web");
|
||||
const android = countingHost("android");
|
||||
warnUnsupportedOnce(web, "scrolls");
|
||||
warnUnsupportedOnce(android, "scrolls");
|
||||
warnUnsupportedOnce(web, "scrolls");
|
||||
// Same verb on two platforms: one report each, suppressed on repeat.
|
||||
assert.deepEqual(web.calls, ["scrolls"]);
|
||||
assert.deepEqual(android.calls, ["scrolls"]);
|
||||
});
|
||||
|
||||
test("resetWarnings re-arms reporting", () => {
|
||||
resetWarnings();
|
||||
const host = countingHost("web");
|
||||
warnUnsupportedOnce(host, "longPresses");
|
||||
resetWarnings();
|
||||
warnUnsupportedOnce(host, "longPresses");
|
||||
assert.deepEqual(host.calls, ["longPresses", "longPresses"]);
|
||||
});
|
||||
@@ -0,0 +1,185 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
|
||||
// The web runtime is the WEB Host: it parses the injected seed, reports its
|
||||
// platform, and delegates action generation to the shared picker. These tests
|
||||
// guard the Host surface and the seed-precision contract. DOM candidate
|
||||
// enumeration is exercised against a minimal querySelectorAll stub.
|
||||
|
||||
// A 64-bit seed that loses precision as a JS Number must survive as a BigInt.
|
||||
process.env.SANDERLING_SEED = "9007199254740993";
|
||||
|
||||
const { __testing__ } = await import("../src/web-runtime.ts");
|
||||
const { host } = __testing__;
|
||||
|
||||
test("platform is web", () => {
|
||||
assert.equal(host.platform(), "web");
|
||||
});
|
||||
|
||||
test("seedHi parses the injected 64-bit seed without Number precision loss", () => {
|
||||
assert.equal(host.seedHi(), 9007199254740993n);
|
||||
});
|
||||
|
||||
test("seedLo is 0 to match goja rand.NewPCG(seed, 0)", () => {
|
||||
assert.equal(host.seedLo(), 0n);
|
||||
});
|
||||
|
||||
test("reportUnsupported warns once via console.warn", () => {
|
||||
const original = console.warn;
|
||||
const messages: string[] = [];
|
||||
console.warn = (m: string) => messages.push(m);
|
||||
try {
|
||||
host.reportUnsupported("swipes");
|
||||
} finally {
|
||||
console.warn = original;
|
||||
}
|
||||
assert.equal(messages.length, 1);
|
||||
assert.match(messages[0]!, /swipes/);
|
||||
});
|
||||
|
||||
// installRuntime locked the next-action and extractor globals at import.
|
||||
test("installRuntime defined the host-invoked globals", () => {
|
||||
const g = globalThis as Record<string, unknown>;
|
||||
assert.equal(typeof g.__sanderlingNextAction__, "function");
|
||||
assert.equal(typeof g.__sanderlingExtractors__, "function");
|
||||
assert.equal(typeof g.__sanderling__, "object");
|
||||
});
|
||||
|
||||
// A button and a text input, each with a deterministic bounding box, exercise
|
||||
// the per-verb selector routing without a full DOM.
|
||||
function fakeElement(tag: string, rect: { x: number; y: number; w: number; h: number }) {
|
||||
return {
|
||||
tagName: tag.toUpperCase(),
|
||||
disabled: false,
|
||||
isContentEditable: false,
|
||||
type: tag === "input" ? "text" : "",
|
||||
scrollHeight: 0,
|
||||
clientHeight: 0,
|
||||
scrollWidth: 0,
|
||||
clientWidth: 0,
|
||||
getBoundingClientRect: () => ({
|
||||
left: rect.x,
|
||||
top: rect.y,
|
||||
width: rect.w,
|
||||
height: rect.h,
|
||||
right: rect.x + rect.w,
|
||||
bottom: rect.y + rect.h,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function withFakeDocument(map: Record<string, unknown[]>, run: () => void) {
|
||||
const g = globalThis as Record<string, unknown>;
|
||||
const original = g.document;
|
||||
g.document = {
|
||||
querySelectorAll: (selector: string) => map[selector] ?? [],
|
||||
scrollingElement: null,
|
||||
documentElement: null,
|
||||
};
|
||||
try {
|
||||
run();
|
||||
} finally {
|
||||
g.document = original;
|
||||
}
|
||||
}
|
||||
|
||||
test("queryCandidates routes taps to the tappable selector set", () => {
|
||||
const button = fakeElement("button", { x: 10, y: 20, w: 40, h: 8 });
|
||||
withFakeDocument(
|
||||
{ 'a, button, input, select, textarea, [role="button"], [onclick]': [button] },
|
||||
() => {
|
||||
__testing__.resetCandidateCache();
|
||||
const candidates = host.queryCandidates("taps");
|
||||
assert.equal(candidates.length, 1);
|
||||
assert.deepEqual({ x: candidates[0]!.x, y: candidates[0]!.y }, { x: 30, y: 24 });
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("queryCandidates routes typing to editable inputs only", () => {
|
||||
const input = fakeElement("input", { x: 0, y: 0, w: 100, h: 20 });
|
||||
withFakeDocument({ "input, textarea, [contenteditable]": [input] }, () => {
|
||||
__testing__.resetCandidateCache();
|
||||
const candidates = host.queryCandidates("typing");
|
||||
assert.equal(candidates.length, 1);
|
||||
assert.deepEqual({ x: candidates[0]!.x, y: candidates[0]!.y }, { x: 50, y: 10 });
|
||||
});
|
||||
});
|
||||
|
||||
test("queryCandidates caches within a tick until reset", () => {
|
||||
const first = fakeElement("button", { x: 0, y: 0, w: 10, h: 10 });
|
||||
withFakeDocument(
|
||||
{ 'a, button, input, select, textarea, [role="button"], [onclick]': [first] },
|
||||
() => {
|
||||
__testing__.resetCandidateCache();
|
||||
const a = host.queryCandidates("taps");
|
||||
const b = host.queryCandidates("taps");
|
||||
assert.equal(a, b);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
// evaluateExtractors builds State, which references document and window.
|
||||
const emptyDocument = {
|
||||
querySelector: () => null,
|
||||
querySelectorAll: () => [],
|
||||
};
|
||||
|
||||
function withState(run: () => void) {
|
||||
const g = globalThis as Record<string, unknown>;
|
||||
const originalDocument = g.document;
|
||||
const originalWindow = g.window;
|
||||
g.document = emptyDocument;
|
||||
g.window = {};
|
||||
try {
|
||||
run();
|
||||
} finally {
|
||||
g.document = originalDocument;
|
||||
g.window = originalWindow;
|
||||
}
|
||||
}
|
||||
|
||||
test("named() sets the extractor's display name", () => {
|
||||
const handle = __testing__.runtime.extract(() => "home").named("route");
|
||||
const entry = __testing__.extractors.find((e) => e.handle === handle);
|
||||
assert.equal(entry?.name, "route");
|
||||
});
|
||||
|
||||
test("reading another extractor's current inside a getter throws", () => {
|
||||
const first = __testing__.runtime.extract(() => 1);
|
||||
let caught: Error | undefined;
|
||||
__testing__.runtime.extract(() => {
|
||||
try {
|
||||
return first.current;
|
||||
} catch (error) {
|
||||
caught = error as Error;
|
||||
return undefined;
|
||||
}
|
||||
});
|
||||
withState(() => __testing__.evaluateExtractors());
|
||||
assert.match(
|
||||
caught?.message ?? "",
|
||||
/inside another extractor is not allowed/,
|
||||
);
|
||||
});
|
||||
|
||||
// An uncaught cross-extractor read must abort evaluateExtractors loudly, exactly
|
||||
// like goja's PushSnapshot. If the getter throw were swallowed, web would
|
||||
// silently yield undefined and the guard would be a no-op for real authors.
|
||||
test("an uncaught cross-extractor read aborts evaluateExtractors", () => {
|
||||
__testing__.extractors.length = 0;
|
||||
const first = __testing__.runtime.extract(() => 1);
|
||||
__testing__.runtime.extract(() => first.previous);
|
||||
let thrown: Error | undefined;
|
||||
withState(() => {
|
||||
try {
|
||||
__testing__.evaluateExtractors();
|
||||
} catch (error) {
|
||||
thrown = error as Error;
|
||||
}
|
||||
});
|
||||
assert.match(
|
||||
thrown?.message ?? "",
|
||||
/inside another extractor is not allowed/,
|
||||
);
|
||||
});
|
||||
Reference in new issue
Block a user