fix(sample-app): make it standalone, no repo_root assumptions (#8)

* fix(cli): fall back to node_modules for @uatu/spec resolution

Drop the hard failure when the uatu source tree is not reachable from
the spec file. Users integrating uatu in their own app have @uatu/spec
installed via npm; esbuild now resolves it from node_modules.

* build(gradle): drop :sample-app include from root settings

The sample now has its own Gradle project in examples/sample-app/android.

* build(sample-app): vendor gradle wrapper

Users running the sample build the APK via ./gradlew from inside the
sample-app's own android/ directory, no repo-root wrapper required.

* build(sample-app): make gradle project standalone

Drop the project(':sdk-android') dependency in favor of the Maven
Central coordinate io.github.priyanshujain:sdk-android. The sample now
owns its settings.gradle.kts and gradle.properties, so it builds
without any pieces of the uatu source tree.

* chore(sample-app): declare @uatu/spec npm dependency

Mirrors what a downstream user would put in their own package.json.
Uses file: for pre-release development; becomes a normal semver pin
once @uatu/spec ships to npm.

* docs(sample-app): rewrite justfile and add README

Justfile drops repo_root; all recipes run against the local gradle
wrapper and uatu from PATH. README is scoped to what a user needs to
run the sample against their own device.

* docs(manual): update sample install steps to standalone layout

./gradlew :sample-app:installDebug no longer exists; the sample owns
its own wrapper under android/.

* feat(sdk): log when Uatu.start succeeds

Silent SDK start makes the "SDK didn't connect" failure mode
impossible to debug. One INFO line at start time is enough.

* fix(sidecar): launch via am start -W instead of monkey

monkey -p <pkg> -c LAUNCHER 1 is unreliable on API 36+: it reports no
error but silently fails to start the activity, so the SDK never runs
and the CLI times out on the SDK-accept handshake.

Resolve the launcher activity via `cmd package resolve-activity
--brief` and launch it with `am start -W -n`. -W makes the call block
until the activity is up, which also makes the subsequent SDK
accept timing deterministic.

* feat(cli): auto-resolve Android device; boot AVD if none connected

--avd becomes optional. Resolution order:
 - use any already-connected adb device;
 - else if --avd names an existing AVD, boot it and wait for boot;
 - else if --avd is missing or names no AVD, error with a clear message.

Falls back to $ANDROID_HOME/emulator/emulator when the binary is not on
PATH, so a standard Android SDK install works without extra shell setup.

* docs(sample-app): AVD is optional; document both paths

just test runs against any connected device. If none, pass AVD=<name>
to have uatu boot the emulator for you.

* feat(cli): auto-discover Android SDK; auto-pick the lone AVD

adb and emulator are looked up via PATH, then $ANDROID_HOME,
$ANDROID_SDK_ROOT, ~/Library/Android/sdk, ~/Android/Sdk, and the
Homebrew cask path. The discovered platform-tools directory is
prepended to the sidecar's PATH so its adb subprocess calls work too.

When --avd isn't passed and no device is connected, the CLI picks the
sole local AVD and boots it. Multiple AVDs → error listing them.

* build(make): add `make install` that go-installs uatu onto PATH

Puts `uatu` into $GOBIN (or $GOPATH/bin) so the sample and any local
dev flow can call it without PATH= prefixes.

* docs(sample-app): zero-config just test; dotenv-load for persistence

Drop the expectation that users prefix commands with PATH=, ANDROID_HOME=,
or AVD=. `just test` now works as-is; optional knobs can be pinned in a
.env file alongside the justfile.

* fix(sample-app): auto-detect ANDROID_HOME for Gradle tasks

The Go CLI finds the SDK itself, but AGP still needs ANDROID_HOME to
resolve `sdk.dir`. The justfile now resolves it from env or canonical
install paths before invoking ./gradlew, so `just install` works out
of the box on a standard Android SDK setup.

* gitignore runs directory for sample app
This commit is contained in:
pj authored and GitHub committed 2026-04-18 15:31:47 +07:00
1 parent bf733f4f93
commit 6b1c17328c
26 files changed
+1094 -61

No files matched your search

+9 -1
View File
@@ -15,7 +15,7 @@ DOCS_SRC := $(shell find docs -type f -name '*.md' -not -path 'docs/_*')
DOCS_OUT := $(patsubst docs/%.md,build/site/%.html,$(DOCS_SRC)) DOCS_OUT := $(patsubst docs/%.md,build/site/%.html,$(DOCS_SRC))
DOCS_TEMPLATE := docs/_template/page.html DOCS_TEMPLATE := docs/_template/page.html
.PHONY: bootstrap proto sidecar sdk-android sdk-android-publish uatu test test-go test-kotlin test-spec-api docs clean release-cli release-android-local release-npm-dry .PHONY: bootstrap proto sidecar sdk-android sdk-android-publish uatu install test test-go test-kotlin test-spec-api docs clean release-cli release-android-local release-npm-dry
bootstrap: bootstrap:
$(GO) mod download $(GO) mod download
@@ -42,6 +42,14 @@ $(UATU_BIN): $(SIDECAR_JAR)
cp $(SIDECAR_JAR) $(SIDECAR_EMBED) cp $(SIDECAR_JAR) $(SIDECAR_EMBED)
$(GO) build -tags withsidecar -o $(UATU_BIN) ./cmd/uatu $(GO) build -tags withsidecar -o $(UATU_BIN) ./cmd/uatu
# Installs `uatu` into $GOBIN (or $GOPATH/bin) so it's directly on PATH for
# anyone with a standard Go toolchain setup.
install: $(SIDECAR_JAR)
mkdir -p $(dir $(SIDECAR_EMBED))
cp $(SIDECAR_JAR) $(SIDECAR_EMBED)
$(GO) install -tags withsidecar ./cmd/uatu
@dest="$$($(GO) env GOBIN)"; [ -n "$$dest" ] || dest="$$($(GO) env GOPATH)/bin"; echo "installed uatu to $$dest"
$(SIDECAR_JAR): $(SIDECAR_JAR):
$(MAKE) sidecar $(MAKE) sidecar
+49
View File
@@ -0,0 +1,49 @@
# Dokka / Java 25 publish failure
## What fails
Running `./gradlew :sdk-android:publishToMavenLocal` (or any task that triggers `javaDocReleaseGeneration`) on a JDK 25 host crashes with:
```
Execution failed for task ':sdk-android:javaDocReleaseGeneration'.
> A failure occurred while executing com.android.build.gradle.tasks.JavaDocGenerationTask$DokkaWorkAction
...
Caused by: java.lang.IllegalArgumentException: 25.0.2
at com.intellij.util.lang.JavaVersion.parse(JavaVersion.java:298)
```
## Why it happens
The publish flow is:
1. `com.vanniktech.maven.publish:0.30.0` (declared in `sdk/android/build.gradle.kts:7`) configures an `AndroidSingleVariantLibrary` with `publishJavadocJar = true`.
2. That wires AGP's `JavaDocGenerationTask` into the release publication. The task runs Dokka in a `WorkAction`.
3. Dokka ships a vendored copy of IntelliJ's platform SDK. When it boots, it probes the JDK version by calling `com.intellij.util.lang.JavaVersion.parse(System.getProperty("java.version"))`.
4. On the host JDK the property is literally the string `"25.0.2"`. Dokka's bundled `JavaVersion.parse` (an older IntelliJ build) only understands the legacy patterns (`1.8.0_x`, `9`, `11.0.x`, etc.) and refuses version 25's format, throwing `IllegalArgumentException: 25.0.2`.
5. The worker dies, Gradle marks `javaDocReleaseGeneration` failed, and the whole publish lifecycle aborts before any POM or AAR is written.
## Why it's latent in CI
CI runs on JDK 17 per `build.gradle.kts` compile targets and whatever `actions/setup-java` installs. `"17.0.x"` matches the old format, so the bundled `JavaVersion.parse` doesn't blow up. The bug only surfaces on developer machines running JDK 21+ where the version string format changed, and reliably on JDK 25.
## Workaround
```sh
./gradlew :sdk-android:publishToMavenLocal -x javaDocReleaseGeneration
```
The AAR, sources jar, and POM publish cleanly; only the Javadoc jar is skipped. That produces a usable `0.0.0-dev` artifact for local testing but is not a substitute for a real release publish, since Maven Central validation requires the Javadoc jar.
## Possible fixes
1. **Bump the `vanniktech.maven.publish` plugin to a version that ships a newer Dokka.** The `0.30.0` version pinned here is from mid-2024. Newer releases (0.33+) bundle Dokka 2.x, which has rewritten the JDK detection path and handles modern version strings. One line in `sdk/android/build.gradle.kts`, no build config change. Requires verifying the plugin's breaking changes for the publish config.
2. **Pin a compatible Dokka directly.** Add `id("org.jetbrains.dokka") version "1.9.20"` (or later) so the plugin picks up Dokka's own fix for IntelliJ `JavaVersion.parse`. Slightly more invasive; you now manage Dokka independently from the publish plugin.
3. **Force a JDK toolchain for the javadoc task.** Add a `java { toolchain { languageVersion = JavaLanguageVersion.of(17) } }` block scoped to the SDK module (or use `tasks.withType<JavaDocGenerationTask> { javaLauncher.set(...) }`). Gradle downloads JDK 17 and runs Dokka under it regardless of the host JDK. Robust but adds a toolchain dependency to every dev machine's first build.
4. **Don't generate a Javadoc jar.** Flip `publishJavadocJar = false` in the vanniktech config. Kills the problem by removing the failing path. Not viable for Maven Central release (they require a Javadoc jar).
## Recommendation
Option 1. Smallest diff, addresses the root cause, keeps the publish pipeline intact for Central releases, and newer plugin versions also bring AGP 8.x compatibility improvements.
+235
View File
@@ -0,0 +1,235 @@
package main
import (
"bufio"
"context"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"time"
)
// ensureDevice makes sure an Android device is ready for adb commands.
// Resolution order:
// - if an adb device is already online, use it;
// - else if avdName is set, validate and boot it;
// - else if exactly one AVD exists locally, boot it;
// - else fail with a helpful message listing the available AVDs.
func ensureDevice(ctx context.Context, avdName string, stdout io.Writer) error {
devices, err := listAdbDevices(ctx)
if err != nil {
return fmt.Errorf("list adb devices: %w", err)
}
if len(devices) > 0 {
fmt.Fprintf(stdout, "using connected device: %s\n", devices[0])
return nil
}
avds, err := listAVDs(ctx)
if err != nil {
return fmt.Errorf("list AVDs: %w", err)
}
target, err := pickAVD(avdName, avds)
if err != nil {
return err
}
fmt.Fprintf(stdout, "booting AVD %q...\n", target)
if err := bootAVD(ctx, target); err != nil {
return fmt.Errorf("boot AVD %q: %w", target, err)
}
if err := waitForBoot(ctx, 180*time.Second); err != nil {
return fmt.Errorf("wait for AVD boot: %w", err)
}
fmt.Fprintf(stdout, "AVD %q ready\n", target)
return nil
}
func pickAVD(requested string, available []string) (string, error) {
if requested != "" {
if !slices.Contains(available, requested) {
return "", fmt.Errorf("AVD %q does not exist (available: %s)", requested, strings.Join(available, ", "))
}
return requested, nil
}
switch len(available) {
case 0:
return "", fmt.Errorf("no android device connected and no AVD found; create one in Android Studio or `avdmanager create avd`")
case 1:
return available[0], nil
default:
return "", fmt.Errorf("no android device connected and multiple AVDs available (%s); pick one with --avd", strings.Join(available, ", "))
}
}
func listAdbDevices(ctx context.Context) ([]string, error) {
adb, err := adbBinary()
if err != nil {
return nil, err
}
output, err := exec.CommandContext(ctx, adb, "devices").Output()
if err != nil {
return nil, err
}
return parseAdbDevices(string(output)), nil
}
func parseAdbDevices(output string) []string {
var serials []string
scanner := bufio.NewScanner(strings.NewReader(output))
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "List of devices") {
continue
}
fields := strings.Fields(line)
if len(fields) >= 2 && fields[1] == "device" {
serials = append(serials, fields[0])
}
}
return serials
}
func listAVDs(ctx context.Context) ([]string, error) {
emulator, err := emulatorBinary()
if err != nil {
return nil, err
}
output, err := exec.CommandContext(ctx, emulator, "-list-avds").Output()
if err != nil {
return nil, err
}
return parseAVDList(string(output)), nil
}
func adbBinary() (string, error) { return findAndroidTool("adb", "platform-tools") }
func emulatorBinary() (string, error) { return findAndroidTool("emulator", "emulator") }
// findAndroidTool locates a binary from the Android SDK. It checks PATH,
// then $ANDROID_HOME/<subdir>/<name> and $ANDROID_SDK_ROOT/<subdir>/<name>,
// then the canonical install locations used by Android Studio and Homebrew.
// Returns a descriptive error when nothing works, so the user knows to set
// $ANDROID_HOME instead of getting a raw "executable file not found".
func findAndroidTool(name, subdir string) (string, error) {
if path, err := exec.LookPath(name); err == nil {
return path, nil
}
var tried []string
for _, root := range androidSDKCandidates() {
candidate := filepath.Join(root, subdir, name)
if info, err := os.Stat(candidate); err == nil && !info.IsDir() {
return candidate, nil
}
tried = append(tried, candidate)
}
return "", fmt.Errorf("could not locate %q: not on PATH and not under any known Android SDK root (set $ANDROID_HOME to point at your SDK; tried %v)", name, tried)
}
func androidSDKCandidates() []string {
var roots []string
seen := map[string]bool{}
addRoot := func(path string) {
if path == "" || seen[path] {
return
}
seen[path] = true
roots = append(roots, path)
}
addRoot(os.Getenv("ANDROID_HOME"))
addRoot(os.Getenv("ANDROID_SDK_ROOT"))
if home, err := os.UserHomeDir(); err == nil {
addRoot(filepath.Join(home, "Library", "Android", "sdk"))
addRoot(filepath.Join(home, "Android", "Sdk"))
}
addRoot("/opt/homebrew/share/android-commandlinetools")
addRoot("/usr/local/share/android-commandlinetools")
return roots
}
func parseAVDList(output string) []string {
var avds []string
scanner := bufio.NewScanner(strings.NewReader(output))
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "INFO") {
continue
}
avds = append(avds, line)
}
return avds
}
func bootAVD(_ context.Context, name string) error {
emulator, err := emulatorBinary()
if err != nil {
return err
}
command := exec.Command(emulator, "-avd", name, "-no-snapshot-save", "-no-audio", "-no-boot-anim")
if err := command.Start(); err != nil {
return err
}
go func() { _ = command.Wait() }()
return nil
}
func waitForBoot(ctx context.Context, timeout time.Duration) error {
deadline, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
if completed, _ := bootCompleted(deadline); completed {
return nil
}
select {
case <-deadline.Done():
return deadline.Err()
case <-ticker.C:
}
}
}
// envWithAndroidPlatformTools returns env with the directory containing adb
// prepended to PATH, so child processes (the sidecar) can invoke adb even
// when the user hasn't set up their shell PATH.
func envWithAndroidPlatformTools(env []string) []string {
adb, err := adbBinary()
if err != nil {
return env
}
adbDir := filepath.Dir(adb)
result := make([]string, 0, len(env))
found := false
for _, entry := range env {
if current, ok := strings.CutPrefix(entry, "PATH="); ok {
if !pathContains(current, adbDir) {
entry = "PATH=" + adbDir + string(os.PathListSeparator) + current
}
found = true
}
result = append(result, entry)
}
if !found {
result = append(result, "PATH="+adbDir)
}
return result
}
func pathContains(path, directory string) bool {
return slices.Contains(strings.Split(path, string(os.PathListSeparator)), directory)
}
func bootCompleted(ctx context.Context) (bool, error) {
adb, err := adbBinary()
if err != nil {
return false, err
}
output, err := exec.CommandContext(ctx, adb, "shell", "getprop", "sys.boot_completed").Output()
if err != nil {
return false, err
}
return strings.TrimSpace(string(output)) == "1", nil
}
+93
View File
@@ -0,0 +1,93 @@
package main
import (
"reflect"
"testing"
)
func TestParseAdbDevices_OnlineOnly(t *testing.T) {
output := `List of devices attached
emulator-5554 device
emulator-5556 offline
physical-abc device
`
got := parseAdbDevices(output)
want := []string{"emulator-5554", "physical-abc"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %v, want %v", got, want)
}
}
func TestParseAdbDevices_Empty(t *testing.T) {
output := "List of devices attached\n\n"
got := parseAdbDevices(output)
if len(got) != 0 {
t.Fatalf("got %v, want empty", got)
}
}
func TestParseAVDList_DropsInfoLines(t *testing.T) {
output := `INFO | Storing crashdata in: /tmp/x
Medium_Phone_API_36.0
uatu_test
`
got := parseAVDList(output)
want := []string{"Medium_Phone_API_36.0", "uatu_test"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %v, want %v", got, want)
}
}
func TestPickAVD_ExplicitName(t *testing.T) {
got, err := pickAVD("Pixel_7", []string{"Pixel_7", "uatu_test"})
if err != nil {
t.Fatal(err)
}
if got != "Pixel_7" {
t.Fatalf("got %q, want Pixel_7", got)
}
}
func TestPickAVD_ExplicitMissing(t *testing.T) {
_, err := pickAVD("Nope", []string{"Pixel_7"})
if err == nil {
t.Fatal("expected error")
}
}
func TestPickAVD_SingleAvailable(t *testing.T) {
got, err := pickAVD("", []string{"uatu_test"})
if err != nil {
t.Fatal(err)
}
if got != "uatu_test" {
t.Fatalf("got %q, want uatu_test", got)
}
}
func TestPickAVD_AmbiguousWithoutHint(t *testing.T) {
_, err := pickAVD("", []string{"a", "b"})
if err == nil {
t.Fatal("expected error when multiple AVDs and no --avd")
}
}
func TestPickAVD_NoneAvailable(t *testing.T) {
_, err := pickAVD("", nil)
if err == nil {
t.Fatal("expected error when no AVDs exist")
}
}
func TestPathContains(t *testing.T) {
path := "/usr/bin:/opt/tools:/usr/local/bin"
if !pathContains(path, "/opt/tools") {
t.Error("expected /opt/tools in PATH")
}
if pathContains(path, "/nope") {
t.Error("did not expect /nope in PATH")
}
}
+1 -4
View File
@@ -46,7 +46,7 @@ func parseTestArgs(args []string, stderr io.Writer) (testOptions, error) {
flagSet.StringVar(&options.bundleID, "bundle-id", "", "target app bundle ID (required)") flagSet.StringVar(&options.bundleID, "bundle-id", "", "target app bundle ID (required)")
flagSet.StringVar(&options.launcherActivity, "launcher-activity", "", "optional <pkg>/<activity> to launch (overrides default resolution)") flagSet.StringVar(&options.launcherActivity, "launcher-activity", "", "optional <pkg>/<activity> to launch (overrides default resolution)")
flagSet.StringVar(&options.platform, "platform", "android", "target platform: android (ios deferred)") flagSet.StringVar(&options.platform, "platform", "android", "target platform: android (ios deferred)")
flagSet.StringVar(&options.avd, "avd", "", "Android AVD name (required on android)") flagSet.StringVar(&options.avd, "avd", "", "Android AVD name to boot if no device is connected")
flagSet.DurationVar(&options.duration, "duration", 5*time.Minute, "total test duration") flagSet.DurationVar(&options.duration, "duration", 5*time.Minute, "total test duration")
flagSet.Int64Var(&options.seed, "seed", 0, "RNG seed (0 = random)") flagSet.Int64Var(&options.seed, "seed", 0, "RNG seed (0 = random)")
flagSet.StringVar(&options.output, "output", "./runs", "output directory for traces") flagSet.StringVar(&options.output, "output", "./runs", "output directory for traces")
@@ -59,9 +59,6 @@ func parseTestArgs(args []string, stderr io.Writer) (testOptions, error) {
if options.bundleID == "" { if options.bundleID == "" {
return testOptions{}, errors.New("--bundle-id is required") return testOptions{}, errors.New("--bundle-id is required")
} }
if options.platform == "android" && options.avd == "" {
return testOptions{}, errors.New("--avd is required on android")
}
if options.platform != "android" { if options.platform != "android" {
return testOptions{}, fmt.Errorf("unsupported platform: %q (only android in v0.1)", options.platform) return testOptions{}, fmt.Errorf("unsupported platform: %q (only android in v0.1)", options.platform)
} }
+22 -10
View File
@@ -66,10 +66,13 @@ func TestParseTestArgs_RequiresBundleID(t *testing.T) {
} }
} }
func TestParseTestArgs_RequiresAVDOnAndroid(t *testing.T) { func TestParseTestArgs_AVDIsOptional(t *testing.T) {
_, err := parseTestArgs([]string{"--spec", "s.ts", "--bundle-id", "com.example"}, io.Discard) options, err := parseTestArgs([]string{"--spec", "s.ts", "--bundle-id", "com.example"}, io.Discard)
if err == nil || !strings.Contains(err.Error(), "--avd") { if err != nil {
t.Fatalf("expected missing --avd error, got %v", err) t.Fatalf("unexpected error: %v", err)
}
if options.avd != "" {
t.Fatalf("avd default: got %q, want empty", options.avd)
} }
} }
@@ -129,16 +132,25 @@ func TestRun_Doctor(t *testing.T) {
} }
} }
func TestRun_TestSubcommand_ReportsBundleErrorForMissingSpec(t *testing.T) { func TestRun_TestSubcommand_PipelineErrors(t *testing.T) {
// Without a real spec file the pipeline should fail at the bundle step // Without a real spec, a real device, or a bootable AVD the pipeline
// rather than panicking — proves the flag wiring reaches the runner. // must surface a specific error rather than panicking — proves the flag
// wiring reaches the runner.
err := run([]string{ err := run([]string{
"uatu", "test", "uatu", "test",
"--spec", "definitely-missing-spec.ts", "--spec", "definitely-missing-spec.ts",
"--bundle-id", "com.example", "--bundle-id", "com.example",
"--avd", "Pixel_5_API_33", "--avd", "definitely-missing-avd",
}, io.Discard, io.Discard) }, io.Discard, io.Discard)
if err == nil || !strings.Contains(err.Error(), "bundle") { if err == nil {
t.Errorf("expected bundle error, got %v", err) t.Fatal("expected error, got nil")
}
message := err.Error()
ok := strings.Contains(message, "bundle") ||
strings.Contains(message, "device") ||
strings.Contains(message, "AVD") ||
strings.Contains(message, "emulator")
if !ok {
t.Errorf("expected pipeline error (bundle/device/AVD/emulator), got %v", err)
} }
} }
+26 -11
View File
@@ -28,17 +28,22 @@ const (
) )
func runTestPipeline(ctx context.Context, options testOptions, stdout io.Writer) error { func runTestPipeline(ctx context.Context, options testOptions, stdout io.Writer) error {
specApiPath, err := resolveSpecAPIPath(options.spec) if options.platform == "android" {
if err != nil { if err := ensureDevice(ctx, options.avd, stdout); err != nil {
return err return err
} }
}
aliases := map[string]string{}
if specApiPath := resolveSpecAPIPath(options.spec); specApiPath != "" {
aliases["@uatu/spec"] = specApiPath
}
bundle, err := bundler.Bundle(bundler.Options{ bundle, err := bundler.Bundle(bundler.Options{
EntryFile: options.spec, EntryFile: options.spec,
Defines: map[string]string{ Defines: map[string]string{
"UATU_TEST_PHONE": os.Getenv("UATU_TEST_PHONE"), "UATU_TEST_PHONE": os.Getenv("UATU_TEST_PHONE"),
"UATU_TEST_OTP": os.Getenv("UATU_TEST_OTP"), "UATU_TEST_OTP": os.Getenv("UATU_TEST_OTP"),
}, },
Aliases: map[string]string{"@uatu/spec": specApiPath}, Aliases: aliases,
}) })
if err != nil { if err != nil {
return fmt.Errorf("bundle spec: %w", err) return fmt.Errorf("bundle spec: %w", err)
@@ -62,6 +67,7 @@ func runTestPipeline(ctx context.Context, options testOptions, stdout io.Writer)
) )
sidecarCommand.Stdout = stdout sidecarCommand.Stdout = stdout
sidecarCommand.Stderr = stdout sidecarCommand.Stderr = stdout
sidecarCommand.Env = envWithAndroidPlatformTools(os.Environ())
if err := sidecarCommand.Start(); err != nil { if err := sidecarCommand.Start(); err != nil {
return fmt.Errorf("spawn sidecar: %w", err) return fmt.Errorf("spawn sidecar: %w", err)
} }
@@ -193,10 +199,11 @@ func runTestPipeline(ctx context.Context, options testOptions, stdout io.Writer)
return nil return nil
} }
// resolveSpecAPIPath finds pkg/spec-api/src/index.ts relative to the spec // resolveSpecAPIPath returns the path to pkg/spec-api/src/index.ts inside
// file or the current working directory so the bundler can resolve // a uatu source checkout, searched upward from the spec file and the cwd.
// `@uatu/spec` imports. // Returns "" when not found, in which case esbuild resolves @uatu/spec via
func resolveSpecAPIPath(specPath string) (string, error) { // node_modules the way a downstream user's project would.
func resolveSpecAPIPath(specPath string) string {
candidates := []string{} candidates := []string{}
if absoluteSpec, err := filepath.Abs(specPath); err == nil { if absoluteSpec, err := filepath.Abs(specPath); err == nil {
directory := filepath.Dir(absoluteSpec) directory := filepath.Dir(absoluteSpec)
@@ -214,10 +221,10 @@ func resolveSpecAPIPath(specPath string) (string, error) {
} }
for _, candidate := range candidates { for _, candidate := range candidates {
if _, err := os.Stat(candidate); err == nil { if _, err := os.Stat(candidate); err == nil {
return candidate, nil return candidate
} }
} }
return "", fmt.Errorf("could not locate pkg/spec-api/src/index.ts (searched %d paths)", len(candidates)) return ""
} }
func pickFreePort() (int, error) { func pickFreePort() (int, error) {
@@ -230,10 +237,18 @@ func pickFreePort() (int, error) {
} }
func adbReverse(socket string, port int) error { func adbReverse(socket string, port int) error {
command := exec.Command("adb", "reverse", "localabstract:"+socket, fmt.Sprintf("tcp:%d", port)) adb, err := adbBinary()
if err != nil {
return err
}
command := exec.Command(adb, "reverse", "localabstract:"+socket, fmt.Sprintf("tcp:%d", port))
return command.Run() return command.Run()
} }
func adbReverseRemove(socket string) error { func adbReverseRemove(socket string) error {
return exec.Command("adb", "reverse", "--remove", "localabstract:"+socket).Run() adb, err := adbBinary()
if err != nil {
return err
}
return exec.Command(adb, "reverse", "--remove", "localabstract:"+socket).Run()
} }
+52
View File
@@ -0,0 +1,52 @@
package main
import (
"os"
"path/filepath"
"testing"
)
func TestResolveSpecAPIPath_FindsUpwardSibling(t *testing.T) {
root := t.TempDir()
apiPath := filepath.Join(root, "pkg", "spec-api", "src", "index.ts")
if err := os.MkdirAll(filepath.Dir(apiPath), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(apiPath, []byte("export {}"), 0o644); err != nil {
t.Fatal(err)
}
specPath := filepath.Join(root, "examples", "app", "spec.ts")
if err := os.MkdirAll(filepath.Dir(specPath), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(specPath, []byte(""), 0o644); err != nil {
t.Fatal(err)
}
got := resolveSpecAPIPath(specPath)
if got != apiPath {
t.Fatalf("got %q, want %q", got, apiPath)
}
}
func TestResolveSpecAPIPath_ReturnsEmptyWhenMissing(t *testing.T) {
root := t.TempDir()
specPath := filepath.Join(root, "spec.ts")
if err := os.WriteFile(specPath, []byte(""), 0o644); err != nil {
t.Fatal(err)
}
cwd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.Chdir(cwd) })
if err := os.Chdir(root); err != nil {
t.Fatal(err)
}
got := resolveSpecAPIPath(specPath)
if got != "" {
t.Fatalf("got %q, want empty (no uatu source tree reachable)", got)
}
}
+2 -1
View File
@@ -53,7 +53,8 @@ dependencies {
The repo ships a working sample at `examples/sample-app`. From that directory: The repo ships a working sample at `examples/sample-app`. From that directory:
```sh ```sh
./gradlew :sample-app:installDebug npm install
(cd android && ./gradlew installDebug)
uatu test \ uatu test \
--spec spec.ts \ --spec spec.ts \
--bundle-id dev.uatu.sample \ --bundle-id dev.uatu.sample \
+1
View File
@@ -0,0 +1 @@
/runs
+50
View File
@@ -0,0 +1,50 @@
# uatu sample app
Tiny Android app wired to the uatu SDK, plus a TypeScript spec that drives it.
Use it as a reference for integrating uatu into your own app.
## Prerequisites
- `uatu` CLI on `PATH` (see [getting started](https://priyanshujain.github.io/uatu/manual/getting-started.html))
- Android SDK installed (uatu auto-discovers `adb` and `emulator` under
`$ANDROID_HOME`, `~/Library/Android/sdk`, or the Homebrew cask; nothing to
export if you use a standard install)
- `just` task runner
## Install the app
```sh
just install
```
## Run a test
```sh
just test
```
If no device is connected, uatu boots the single AVD it finds. With multiple
AVDs, pick one:
```sh
just AVD=Pixel_7 test
```
Persistent settings can live in `.env` alongside the justfile:
```
AVD=Pixel_7
DURATION=5m
```
Traces land in `./runs/<timestamp>/`.
## How the pieces connect
- `android/build.gradle.kts` depends on `io.github.priyanshujain:sdk-android` from
Maven Central
- `android/src/main/kotlin/.../SampleApplication.kt` calls `Uatu.start(this)` and
registers snapshot extractors (`app_state`, `click_count`)
- `spec.ts` imports `@uatu/spec` (see `package.json`), reads those snapshots,
asserts properties on them, and weights the actions the fuzzer picks from
- `just test` invokes `uatu test` against the installed APK on the named AVD
+4 -2
View File
@@ -3,6 +3,8 @@ plugins {
kotlin("android") version "2.1.21" kotlin("android") version "2.1.21"
} }
val uatuVersion = findProperty("uatu.version") as String? ?: "0.0.0-dev"
android { android {
namespace = "dev.uatu.sample" namespace = "dev.uatu.sample"
compileSdk = 35 compileSdk = 35
@@ -12,7 +14,7 @@ android {
minSdk = 24 minSdk = 24
targetSdk = 35 targetSdk = 35
versionCode = 1 versionCode = 1
versionName = findProperty("uatu.version") as String? ?: "0.0.0-dev" versionName = uatuVersion
} }
compileOptions { compileOptions {
@@ -32,5 +34,5 @@ android {
} }
dependencies { dependencies {
implementation(project(":sdk-android")) implementation("io.github.priyanshujain:sdk-android:$uatuVersion")
} }
@@ -0,0 +1,10 @@
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
org.gradle.parallel=true
org.gradle.caching=true
kotlin.code.style=official
android.useAndroidX=true
# Pin the uatu SDK version consumed by this sample. Override with
# `-Puatu.version=<version>` or edit build.gradle.kts once a stable release is
# available on Maven Central.
uatu.version=0.0.0-dev
Binary file not shown.
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+248
View File
@@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/2d6327017519d23b96af35865dc997fcb544fb40/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+93
View File
@@ -0,0 +1,93 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
@@ -0,0 +1,18 @@
pluginManagement {
repositories {
gradlePluginPortal()
google()
mavenCentral()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
mavenLocal()
}
}
rootProject.name = "uatu-sample"
+48 -22
View File
@@ -1,48 +1,74 @@
set shell := ["bash", "-cu"] set shell := ["bash", "-cu"]
set dotenv-load := true
repo_root := absolute_path(justfile_directory() / ".." / "..") uatu := env_var_or_default("UATU", "uatu")
uatu := env_var_or_default("UATU", repo_root / "bin/uatu")
avd := env_var_or_default("AVD", "") avd := env_var_or_default("AVD", "")
duration := env_var_or_default("DURATION", "1m") duration := env_var_or_default("DURATION", "1m")
seed := env_var_or_default("SEED", "0") seed := env_var_or_default("SEED", "0")
output := env_var_or_default("OUTPUT", repo_root / "runs") output := env_var_or_default("OUTPUT", justfile_directory() / "runs")
android := justfile_directory() / "android"
default: default:
@just --list @just --list
# Resolve ANDROID_HOME from the env or a short list of canonical install
# locations, so Gradle can find the Android SDK without the user having to
# export anything.
_android-home:
#!/usr/bin/env bash
set -euo pipefail
if [[ -n "${ANDROID_HOME:-}" && -d "$ANDROID_HOME" ]]; then
echo "$ANDROID_HOME"; exit 0
fi
if [[ -n "${ANDROID_SDK_ROOT:-}" && -d "$ANDROID_SDK_ROOT" ]]; then
echo "$ANDROID_SDK_ROOT"; exit 0
fi
for candidate in \
"$HOME/Library/Android/sdk" \
"$HOME/Android/Sdk" \
"/opt/homebrew/share/android-commandlinetools" \
"/usr/local/share/android-commandlinetools"; do
if [[ -d "$candidate" ]]; then
echo "$candidate"; exit 0
fi
done
echo "could not locate Android SDK (set ANDROID_HOME)" >&2
exit 1
# Build and install the sample APK on a running emulator/device. # Build and install the sample APK on a running emulator/device.
install: install:
cd {{repo_root}} && ./gradlew :sample-app:installDebug #!/usr/bin/env bash
set -euo pipefail
export ANDROID_HOME="$(just _android-home)"
cd {{android}} && ./gradlew installDebug
# Remove the sample APK from the connected device. # Remove the sample APK from the connected device.
uninstall: uninstall:
cd {{repo_root}} && ./gradlew :sample-app:uninstallDebug #!/usr/bin/env bash
set -euo pipefail
export ANDROID_HOME="$(just _android-home)"
cd {{android}} && ./gradlew uninstallDebug
# Build the uatu CLI (writes to repo's bin/uatu). # Remove the gradle build directory.
uatu: clean:
make -C {{repo_root}} uatu #!/usr/bin/env bash
set -euo pipefail
export ANDROID_HOME="$(just _android-home)"
cd {{android}} && ./gradlew clean
# Run the Go tests that bundle and exercise spec.ts (no device required). # Run 'uatu test' against the sample app. Uses a connected device if one is
verify: # online, otherwise boots AVD=<name> if provided.
cd {{repo_root}} && go test ./internal/verifier/ -run TestSampleAppSpec
# Run 'uatu test' against the sample app. AVD=<name> is required.
test: test:
#!/usr/bin/env bash #!/usr/bin/env bash
set -euo pipefail set -euo pipefail
if [[ -z "{{avd}}" ]]; then avd_flag=()
echo "AVD is required (usage: just AVD=<name> test)" >&2 if [[ -n "{{avd}}" ]]; then
exit 1 avd_flag=(--avd "{{avd}}")
fi fi
if [[ ! -x "{{uatu}}" ]]; then just uatu; fi
"{{uatu}}" test \ "{{uatu}}" test \
--spec "{{justfile_directory()}}/spec.ts" \ --spec "{{justfile_directory()}}/spec.ts" \
--bundle-id dev.uatu.sample \ --bundle-id dev.uatu.sample \
--avd "{{avd}}" \ "${avd_flag[@]}" \
--duration "{{duration}}" \ --duration "{{duration}}" \
--seed "{{seed}}" \ --seed "{{seed}}" \
--output "{{output}}" --output "{{output}}"
# Remove the gradle build directory for the sample app.
clean:
cd {{repo_root}} && ./gradlew :sample-app:clean
+28
View File
@@ -0,0 +1,28 @@
{
"name": "uatu-sample",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "uatu-sample",
"devDependencies": {
"@uatu/spec": "file:../../pkg/spec-api"
}
},
"../../pkg/spec-api": {
"name": "@uatu/spec",
"version": "0.0.0-dev",
"dev": true,
"license": "Apache-2.0",
"devDependencies": {
"@types/node": "^22.7.5",
"tsx": "^4.21.0",
"typescript": "^5.9.3"
}
},
"node_modules/@uatu/spec": {
"resolved": "../../pkg/spec-api",
"link": true
}
}
}
+8
View File
@@ -0,0 +1,8 @@
{
"name": "uatu-sample",
"private": true,
"description": "Minimal uatu integration example.",
"devDependencies": {
"@uatu/spec": "file:../../pkg/spec-api"
}
}
@@ -1,6 +1,7 @@
package dev.uatu.sdk package dev.uatu.sdk
import android.app.Application import android.app.Application
import android.util.Log
data class Configuration( data class Configuration(
val socketName: String = "uatu-agent", val socketName: String = "uatu-agent",
@@ -9,6 +10,7 @@ data class Configuration(
object Uatu { object Uatu {
const val VERSION: String = "0.0.1" const val VERSION: String = "0.0.1"
private const val LOG_TAG = "Uatu"
@Volatile private var runtime: UatuRuntime? = null @Volatile private var runtime: UatuRuntime? = null
@@ -24,6 +26,7 @@ object Uatu {
) )
newRuntime.start() newRuntime.start()
runtime = newRuntime runtime = newRuntime
Log.i(LOG_TAG, "SDK started (package=${application.packageName} socket=${configuration.socketName})")
} }
fun extract(name: String, function: () -> Any?) { fun extract(name: String, function: () -> Any?) {
-2
View File
@@ -19,5 +19,3 @@ rootProject.name = "uatu"
include(":sidecar") include(":sidecar")
include(":sdk-android") include(":sdk-android")
project(":sdk-android").projectDir = file("sdk/android") project(":sdk-android").projectDir = file("sdk/android")
include(":sample-app")
project(":sample-app").projectDir = file("examples/sample-app/android")
@@ -36,13 +36,47 @@ class StubDriverBackend(private val platform: String) : DriverBackend {
if (clearState) { if (clearState) {
runAdb(listOf("shell", "pm", "clear", bundleId)) runAdb(listOf("shell", "pm", "clear", bundleId))
} }
if (launcherActivity.isNotEmpty()) { val component = when {
val component = if (launcherActivity.contains('/')) launcherActivity else "$bundleId/$launcherActivity" launcherActivity.isEmpty() -> "$bundleId/${resolveLauncherActivity(bundleId)}"
runAdb(listOf("shell", "am", "start", "-n", component)) launcherActivity.contains('/') -> launcherActivity
} else { else -> "$bundleId/$launcherActivity"
// `monkey` uses PackageManager.getLaunchIntentForPackage, which }
// picks the canonical default launcher. runAdb(listOf("shell", "am", "start", "-W", "-n", component))
runAdb(listOf("shell", "monkey", "-p", bundleId, "-c", "android.intent.category.LAUNCHER", "1")) }
private fun resolveLauncherActivity(bundleId: String): String {
val output = captureAdb(
listOf(
"shell", "cmd", "package", "resolve-activity", "--brief",
"-a", "android.intent.action.MAIN",
"-c", "android.intent.category.LAUNCHER",
bundleId,
),
)
return parseResolvedActivity(bundleId, output)
?: throw IllegalStateException("could not resolve launcher activity for $bundleId: $output")
}
private fun captureAdb(arguments: List<String>): String {
val process = ProcessBuilder(listOf("adb") + arguments).redirectErrorStream(true).start()
val output = process.inputStream.bufferedReader().readText()
process.waitFor()
return output
}
companion object {
// parseResolvedActivity extracts the activity name from the output of
// `cmd package resolve-activity --brief`. The brief output is two
// lines: metadata, then `<pkg>/<activity>`.
internal fun parseResolvedActivity(bundleId: String, output: String): String? {
val prefix = "$bundleId/"
for (line in output.lines()) {
val trimmed = line.trim()
if (trimmed.startsWith(prefix)) {
return trimmed.removePrefix(prefix)
}
}
return null
} }
} }
@@ -35,7 +35,13 @@ class DriverServiceTest {
val backend = StubDriverBackend("android") val backend = StubDriverBackend("android")
val client = newClient(backend) val client = newClient(backend)
client.launch(LaunchRequest.newBuilder().setBundleId("com.example").setClearState(true).build()) client.launch(
LaunchRequest.newBuilder()
.setBundleId("com.example")
.setLauncherActivity(".MainActivity")
.setClearState(true)
.build(),
)
assertEquals("com.example", backend.lastBundleId) assertEquals("com.example", backend.lastBundleId)
assertEquals(1, backend.launchCount) assertEquals(1, backend.launchCount)
@@ -0,0 +1,39 @@
package dev.uatu.sidecar
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
class ResolveActivityTest {
@Test fun extractsActivityFromBriefOutput() {
val output = """
priority=0 preferredOrder=0 match=0x108000 specificIndex=-1 isDefault=false
dev.uatu.sample/.MainActivity
""".trimIndent()
val activity = StubDriverBackend.parseResolvedActivity("dev.uatu.sample", output)
assertEquals(".MainActivity", activity)
}
@Test fun extractsFullyQualifiedActivity() {
val output = "com.example.app/com.example.app.ui.LaunchActivity"
val activity = StubDriverBackend.parseResolvedActivity("com.example.app", output)
assertEquals("com.example.app.ui.LaunchActivity", activity)
}
@Test fun returnsNullWhenPackageNotFound() {
val output = "No activity found"
val activity = StubDriverBackend.parseResolvedActivity("dev.uatu.sample", output)
assertNull(activity)
}
@Test fun doesNotMatchDifferentPackagePrefix() {
val output = "other.pkg/.MainActivity"
val activity = StubDriverBackend.parseResolvedActivity("dev.uatu.sample", output)
assertNull(activity)
}
}