Files
sanderling/internal/runner/runner_test.go
T
pj 8ccf95c1cf refactor: rename project uatu -> sanderling (#24)
* refactor: rename Go module path uatu -> sanderling

Module path github.com/priyanshujain/uatu -> github.com/priyanshujain/sanderling,
including all imports and the proto go_package option. Generated .pb.go files
rewritten in-place; safe to regenerate with protoc later.

* chore(proto): regenerate driverpb after module path rename

The previous sed-based module rename corrupted the embedded descriptor
byte lengths. buf generate rewrites them cleanly.

* refactor: rename CLI binary uatu -> sanderling

Updates Makefile target + UATU_BIN var, .goreleaser project/build IDs,
.gitignore comment, and all user-facing strings in the CLI help text,
error messages, and tests. Binary is now bin/sanderling.

* refactor(sdk): rename Kotlin package dev.uatu.sdk -> dev.sanderling.sdk

Moves sdk/android/src/{main,test}/kotlin/dev/uatu -> dev/sanderling and
rewrites package declarations, imports, and the Gradle namespace. Class
names (Uatu, UatuRuntime) are renamed in a follow-up commit.

* refactor(sidecar): rename Kotlin package dev.uatu.sidecar -> dev.sanderling.sidecar

Moves sidecar/src/{main,test}/kotlin/dev/uatu -> dev/sanderling and
rewrites package declarations, imports, and the application mainClass.

* refactor: rename Uatu API surface -> Sanderling

- Kotlin: Uatu -> Sanderling, UatuRuntime -> SanderlingRuntime (+ files).
- JS host binding: globalThis.__uatu__ -> __sanderling__ (Go verifier,
  spec-api, tests).
- TS interface: UatuRuntime -> SanderlingRuntime; internal tags
  __uatuFormula / __uatuActionGenerator -> __sanderling* variants.
- Go trace: UatuVersion field + uatu_version JSON tag renamed.
- Socket naming: uatu-agent / uatu-agent-reader -> sanderling-agent*.
- Sample app, docs, inline-JS test strings updated to match.

* refactor(examples): rename examples/folio/uatu -> examples/folio/sanderling

Renames the example spec directory; updates justfile paths + gitignore
entries accordingly. Package.json name/description and @uatu/spec
dependency are renamed in the npm + docs commits.

* chore(build): rename gradle property + rootProject.name uatu -> sanderling

- Renames the uatu.version gradle property and all its -P references in
  Makefile, build.gradle.kts files, and .github/workflows/release.yml.
- settings.gradle.kts rootProject.name = "sanderling".
- Renames .env.local.example header + release-cli workflow job name.

* refactor(proto): rename proto package uatu.driver.v1 -> sanderling.driver.v1

Updates the proto package and java_package, regenerates driver.pb.go +
driver_grpc.pb.go, rewrites Kotlin imports and the gRPC ServiceName
assertion in driver_test.go.

* refactor: rename npm package @uatu/spec -> @sanderling/spec

Renames package name in pkg/spec-api/package.json + lockfile, all
consumer imports (examples/folio spec, testdata, verifier tests), the
esbuild alias in cmd/sanderling/test_run.go, and related doc references.

* docs: rename uatu -> sanderling in README, docs, and URLs

- README + docs/{manual,development}/*: narrative + GitHub + Pages URLs.
- POM + npm package.json repo/homepage/bugs URLs.
- .gitignore + embed_stub + Makefile-comment references updated to
  'make sanderling'.
- Minor narrative comments in cmd/sanderling/test_run.go and
  internal/inspect/server.go.

* refactor: rename remaining internal uatu strings -> sanderling

- SANDERLING_TEST_PHONE/OTP env vars (cmd + bundler tests).
- sanderling-sidecar runtime tmp dir + extracted JAR filename.
- Inspect web UI: @sanderling/inspect-web package, title, theme
  localStorage key, RunList empty-state copy, uatu_version TS field.
- Sample app storage key sanderling.ledger.v1.
- Test data: sanderling_test AVD name + com.example.sanderling_test.
- Release docs tarball name template.
2026-04-21 11:57:49 +07:00

476 lines
14 KiB
Go

package runner
import (
"bytes"
"context"
"encoding/json"
"errors"
"log/slog"
"net"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
"time"
"github.com/priyanshujain/sanderling/internal/agent"
mockdriver "github.com/priyanshujain/sanderling/internal/driver/mock"
"github.com/priyanshujain/sanderling/internal/trace"
"github.com/priyanshujain/sanderling/internal/verifier"
)
const fixtureSpec = `
const screen = __sanderling__.extract(state => state.snapshots.screen ?? "");
const balance = __sanderling__.extract(state => state.snapshots.balance ?? 0);
globalThis.properties = {
balanceNonNegative: __sanderling__.always(() => balance.current >= 0),
};
globalThis.actions = __sanderling__.actions(() => [__sanderling__.tap({ on: "id:next" })]);
`
type harness struct {
server *agent.Server
listener net.Listener
clientWG sync.WaitGroup
conn *agent.Conn
mock *mockdriver.Driver
verifier *verifier.Verifier
writer *trace.Writer
snapshot []map[string]json.RawMessage
}
func newHarness(t *testing.T, snapshots []map[string]json.RawMessage) *harness {
return newHarnessWithSpec(t, snapshots, fixtureSpec)
}
func newHarnessWithSpec(t *testing.T, snapshots []map[string]json.RawMessage, spec string) *harness {
t.Helper()
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
server := agent.NewServer(listener)
directory := t.TempDir()
writer, err := trace.NewWriter(directory)
if err != nil {
t.Fatal(err)
}
verifierInstance, err := verifier.New()
if err != nil {
t.Fatal(err)
}
if err := verifierInstance.Load(spec); err != nil {
t.Fatal(err)
}
state := &harness{
server: server,
listener: listener,
mock: mockdriver.New(),
verifier: verifierInstance,
writer: writer,
snapshot: snapshots,
}
t.Cleanup(func() {
_ = listener.Close()
_ = writer.Close()
})
return state
}
func (h *harness) startSDK(t *testing.T) {
t.Helper()
h.clientWG.Go(func() {
conn, err := net.Dial("tcp", h.listener.Addr().String())
if err != nil {
t.Errorf("dial: %v", err)
return
}
defer conn.Close()
if err := agent.WriteMessage(conn, agent.Hello("0.0.1", "android", "com.fixture")); err != nil {
t.Errorf("hello: %v", err)
return
}
index := 0
for {
message, err := agent.ReadMessage(conn)
if err != nil {
return
}
if message.Type == agent.MessageTypePause {
snapshots := map[string]json.RawMessage{}
if index < len(h.snapshot) {
snapshots = h.snapshot[index]
}
if err := agent.WriteMessage(conn, agent.State(message.ID, snapshots)); err != nil {
return
}
index++
}
}
})
}
func (h *harness) acceptConnection(t *testing.T) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
connection, err := h.server.Accept(ctx)
if err != nil {
t.Fatalf("Accept: %v", err)
}
h.conn = connection
}
func TestRunner_HappyPathStepsAndTraces(t *testing.T) {
snapshots := []map[string]json.RawMessage{
{"screen": json.RawMessage(`"home"`), "balance": json.RawMessage(`100`)},
{"screen": json.RawMessage(`"home"`), "balance": json.RawMessage(`200`)},
{"screen": json.RawMessage(`"home"`), "balance": json.RawMessage(`300`)},
}
state := newHarness(t, snapshots)
state.startSDK(t)
state.acceptConnection(t)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
summary, err := Run(ctx, Options{
Duration: 100 * time.Millisecond,
SnapshotTimeout: 2 * time.Second,
IdleTimeout: 50 * time.Millisecond,
Connection: state.conn,
Driver: state.mock,
Verifier: state.verifier,
TraceWriter: state.writer,
})
if err != nil {
t.Fatalf("Run: %v", err)
}
if summary.Steps == 0 {
t.Errorf("expected at least one step, got 0")
}
if len(summary.Violations) != 0 {
t.Errorf("no violations expected, got %v", summary.Violations)
}
actions := state.mock.Actions()
if !containsAction(actions, mockdriver.ActionTapSelector, "id:next") {
t.Errorf("expected TapSelector with id:next, got %v", actions)
}
}
func TestRunner_ViolationSurfacesInSummary(t *testing.T) {
snapshots := []map[string]json.RawMessage{
{"balance": json.RawMessage(`100`)},
{"balance": json.RawMessage(`-1`)},
{"balance": json.RawMessage(`50`)},
}
state := newHarness(t, snapshots)
state.startSDK(t)
state.acceptConnection(t)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
summary, err := Run(ctx, Options{
Duration: 100 * time.Millisecond,
SnapshotTimeout: 2 * time.Second,
IdleTimeout: 50 * time.Millisecond,
Connection: state.conn,
Driver: state.mock,
Verifier: state.verifier,
TraceWriter: state.writer,
})
if err != nil {
t.Fatalf("Run: %v", err)
}
if len(summary.Violations) == 0 {
t.Errorf("expected at least one violation, got %v", summary.Violations)
}
if !containsProperty(summary.Violations, "balanceNonNegative") {
t.Errorf("expected balanceNonNegative in violations: %v", summary.Violations)
}
}
func TestRunner_ThrowingPredicateIsLoggedNotPanic(t *testing.T) {
const throwingSpec = `
globalThis.properties = {
broken: __sanderling__.always(() => { throw new Error("bad predicate"); }),
};
globalThis.actions = __sanderling__.actions(() => [__sanderling__.tap({ on: "id:next" })]);
`
state := newHarnessWithSpec(t, []map[string]json.RawMessage{{}, {}}, throwingSpec)
state.startSDK(t)
state.acceptConnection(t)
var buffer bytes.Buffer
logger := slog.New(slog.NewTextHandler(&buffer, &slog.HandlerOptions{Level: slog.LevelWarn}))
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
summary, err := Run(ctx, Options{
Duration: 100 * time.Millisecond,
SnapshotTimeout: 2 * time.Second,
IdleTimeout: 50 * time.Millisecond,
Connection: state.conn,
Driver: state.mock,
Verifier: state.verifier,
TraceWriter: state.writer,
Logger: logger,
})
if err != nil {
t.Fatalf("Run: %v", err)
}
if !containsProperty(summary.Violations, "broken") {
t.Errorf("expected broken in violations: %v", summary.Violations)
}
if !strings.Contains(buffer.String(), "bad predicate") {
t.Errorf("expected predicate error in log, got %q", buffer.String())
}
}
func TestRunner_RejectsMissingFields(t *testing.T) {
_, err := Run(context.Background(), Options{Duration: time.Second})
if err == nil || !strings.Contains(err.Error(), "Connection") {
t.Errorf("expected Connection-required error, got %v", err)
}
}
func TestRunner_RejectsZeroDuration(t *testing.T) {
_, err := Run(context.Background(), Options{
Connection: &agent.Conn{},
Driver: mockdriver.New(),
Verifier: mustNewVerifier(t),
TraceWriter: mustNewTraceWriter(t),
})
if err == nil || !strings.Contains(err.Error(), "Duration") {
t.Errorf("expected Duration-required error, got %v", err)
}
}
func TestRunner_RecordsScreenFieldFromSnapshot(t *testing.T) {
snapshots := []map[string]json.RawMessage{
{"screen": json.RawMessage(`"customer_ledger"`), "balance": json.RawMessage(`1`)},
}
state := newHarness(t, snapshots)
state.startSDK(t)
state.acceptConnection(t)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if _, err := Run(ctx, Options{
Duration: 100 * time.Millisecond,
SnapshotTimeout: 2 * time.Second,
IdleTimeout: 50 * time.Millisecond,
Connection: state.conn,
Driver: state.mock,
Verifier: state.verifier,
TraceWriter: state.writer,
}); err != nil {
t.Fatal(err)
}
body, err := os.ReadFile(filepath.Join(state.writer.Directory(), "trace.jsonl"))
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(body), `"screen":"customer_ledger"`) {
t.Errorf("screen field not in trace: %s", body)
}
}
func TestScreenFromSnapshot(t *testing.T) {
t.Run("string value returns screen", func(t *testing.T) {
snapshots := map[string]json.RawMessage{"screen": json.RawMessage(`"home"`)}
screen, err := screenFromSnapshot(snapshots)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if screen != "home" {
t.Errorf("screen = %q, want %q", screen, "home")
}
})
t.Run("missing key returns empty with no error", func(t *testing.T) {
screen, err := screenFromSnapshot(map[string]json.RawMessage{})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if screen != "" {
t.Errorf("screen = %q, want empty", screen)
}
})
t.Run("non-string value returns error", func(t *testing.T) {
snapshots := map[string]json.RawMessage{"screen": json.RawMessage(`{"nested":1}`)}
screen, err := screenFromSnapshot(snapshots)
if err == nil {
t.Fatalf("expected error for non-string screen, got nil")
}
if screen != "" {
t.Errorf("screen = %q, want empty on error", screen)
}
})
}
func TestRunner_StampsHierarchyResolvedBoundsAndResiduals(t *testing.T) {
snapshots := []map[string]json.RawMessage{
{"balance": json.RawMessage(`100`)},
{"balance": json.RawMessage(`200`)},
}
state := newHarness(t, snapshots)
state.startSDK(t)
state.acceptConnection(t)
state.mock.HierarchyJSON = `<?xml version="1.0"?>
<hierarchy>
<node resource-id="com.fixture:id/next" clickable="true" enabled="true" bounds="[40,80][240,160]"/>
</hierarchy>`
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if _, err := Run(ctx, Options{
Duration: 100 * time.Millisecond,
SnapshotTimeout: 2 * time.Second,
IdleTimeout: 50 * time.Millisecond,
Connection: state.conn,
Driver: state.mock,
Verifier: state.verifier,
TraceWriter: state.writer,
}); err != nil {
t.Fatalf("Run: %v", err)
}
body, err := os.ReadFile(filepath.Join(state.writer.Directory(), "trace.jsonl"))
if err != nil {
t.Fatal(err)
}
text := string(body)
if !strings.Contains(text, `"selector":"id:next"`) {
t.Errorf("expected selector in trace: %s", text)
}
if !strings.Contains(text, `"resolved_bounds":{"x":40,"y":80,"width":200,"height":80}`) {
t.Errorf("expected resolved_bounds in trace: %s", text)
}
if !strings.Contains(text, `"tap_point":{"x":140,"y":120}`) {
t.Errorf("expected tap_point in trace: %s", text)
}
if !strings.Contains(text, `"hierarchy":{"elements":`) {
t.Errorf("expected hierarchy in trace: %s", text)
}
if !strings.Contains(text, `"residuals":{`) {
t.Errorf("expected residuals in trace: %s", text)
}
}
func TestRunner_LogsWaitForIdleDriverErrors(t *testing.T) {
snapshots := []map[string]json.RawMessage{
{"balance": json.RawMessage(`100`)},
}
state := newHarness(t, snapshots)
state.startSDK(t)
state.acceptConnection(t)
state.mock.Failures[mockdriver.ActionWaitForIdle] = errors.New("sidecar lost gRPC stream")
var logBuf bytes.Buffer
logger := slog.New(slog.NewTextHandler(&logBuf, &slog.HandlerOptions{Level: slog.LevelWarn}))
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if _, err := Run(ctx, Options{
Duration: 100 * time.Millisecond,
SnapshotTimeout: 2 * time.Second,
IdleTimeout: 50 * time.Millisecond,
Connection: state.conn,
Driver: state.mock,
Verifier: state.verifier,
TraceWriter: state.writer,
Logger: logger,
}); err != nil {
t.Fatalf("Run: %v", err)
}
output := logBuf.String()
if !strings.Contains(output, "wait_for_idle failed") {
t.Errorf("expected wait_for_idle warning, got: %q", output)
}
if !strings.Contains(output, "sidecar lost gRPC stream") {
t.Errorf("expected driver error message in warning, got: %q", output)
}
}
func TestApplyAction_InputTextSurfacesFocusTapError(t *testing.T) {
t.Run("selector focus tap fails", func(t *testing.T) {
driverMock := mockdriver.New()
driverMock.Failures[mockdriver.ActionTapSelector] = errors.New("adb unreachable")
action := verifier.Action{Kind: verifier.ActionKindInputText, On: "id:username", Text: "alice"}
err := applyAction(context.Background(), driverMock, action, nil)
if err == nil {
t.Fatalf("expected focus tap failure to surface, got nil")
}
if containsAction(driverMock.Actions(), mockdriver.ActionInputText, "") {
t.Errorf("InputText must not run after focus tap failed: %v", driverMock.Actions())
}
})
t.Run("coordinate focus tap fails", func(t *testing.T) {
driverMock := mockdriver.New()
driverMock.Failures[mockdriver.ActionTap] = errors.New("tap driver error")
action := verifier.Action{Kind: verifier.ActionKindInputText, X: 10, Y: 20, Text: "alice"}
err := applyAction(context.Background(), driverMock, action, nil)
if err == nil {
t.Fatalf("expected focus tap failure to surface, got nil")
}
if containsAction(driverMock.Actions(), mockdriver.ActionInputText, "") {
t.Errorf("InputText must not run after focus tap failed: %v", driverMock.Actions())
}
})
}
func mustNewVerifier(t *testing.T) *verifier.Verifier {
t.Helper()
verifierInstance, err := verifier.New()
if err != nil {
t.Fatal(err)
}
return verifierInstance
}
func mustNewTraceWriter(t *testing.T) *trace.Writer {
t.Helper()
writer, err := trace.NewWriter(t.TempDir())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = writer.Close() })
return writer
}
func containsAction(actions []mockdriver.Action, kind mockdriver.ActionKind, payload string) bool {
for _, action := range actions {
if action.Kind != kind {
continue
}
switch kind {
case mockdriver.ActionLaunch:
if action.BundleID == payload {
return true
}
case mockdriver.ActionTapSelector:
if action.Selector == payload {
return true
}
case mockdriver.ActionTerminate:
return true
default:
return true
}
}
return false
}
func containsProperty(records []ViolationRecord, property string) bool {
for _, record := range records {
if slices.Contains(record.Properties, property) {
return true
}
}
return false
}