diff --git a/Makefile b/Makefile index 8b3fa41..417cc97 100644 --- a/Makefile +++ b/Makefile @@ -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_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: $(GO) mod download @@ -42,6 +42,14 @@ $(UATU_BIN): $(SIDECAR_JAR) cp $(SIDECAR_JAR) $(SIDECAR_EMBED) $(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): $(MAKE) sidecar diff --git a/bug.md b/bug.md new file mode 100644 index 0000000..f88c328 --- /dev/null +++ b/bug.md @@ -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 { 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. diff --git a/cmd/uatu/android_env.go b/cmd/uatu/android_env.go new file mode 100644 index 0000000..0455a04 --- /dev/null +++ b/cmd/uatu/android_env.go @@ -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// and $ANDROID_SDK_ROOT//, +// 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 +} + diff --git a/cmd/uatu/android_env_test.go b/cmd/uatu/android_env_test.go new file mode 100644 index 0000000..dd9e532 --- /dev/null +++ b/cmd/uatu/android_env_test.go @@ -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") + } +} diff --git a/cmd/uatu/main.go b/cmd/uatu/main.go index bcb0949..5c57697 100644 --- a/cmd/uatu/main.go +++ b/cmd/uatu/main.go @@ -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.launcherActivity, "launcher-activity", "", "optional / to launch (overrides default resolution)") 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.Int64Var(&options.seed, "seed", 0, "RNG seed (0 = random)") 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 == "" { 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" { return testOptions{}, fmt.Errorf("unsupported platform: %q (only android in v0.1)", options.platform) } diff --git a/cmd/uatu/main_test.go b/cmd/uatu/main_test.go index ee401ab..ef8265d 100644 --- a/cmd/uatu/main_test.go +++ b/cmd/uatu/main_test.go @@ -66,10 +66,13 @@ func TestParseTestArgs_RequiresBundleID(t *testing.T) { } } -func TestParseTestArgs_RequiresAVDOnAndroid(t *testing.T) { - _, err := parseTestArgs([]string{"--spec", "s.ts", "--bundle-id", "com.example"}, io.Discard) - if err == nil || !strings.Contains(err.Error(), "--avd") { - t.Fatalf("expected missing --avd error, got %v", err) +func TestParseTestArgs_AVDIsOptional(t *testing.T) { + options, err := parseTestArgs([]string{"--spec", "s.ts", "--bundle-id", "com.example"}, io.Discard) + if err != nil { + 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) { - // Without a real spec file the pipeline should fail at the bundle step - // rather than panicking — proves the flag wiring reaches the runner. +func TestRun_TestSubcommand_PipelineErrors(t *testing.T) { + // Without a real spec, a real device, or a bootable AVD the pipeline + // must surface a specific error rather than panicking — proves the flag + // wiring reaches the runner. err := run([]string{ "uatu", "test", "--spec", "definitely-missing-spec.ts", "--bundle-id", "com.example", - "--avd", "Pixel_5_API_33", + "--avd", "definitely-missing-avd", }, io.Discard, io.Discard) - if err == nil || !strings.Contains(err.Error(), "bundle") { - t.Errorf("expected bundle error, got %v", err) + if err == nil { + 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) } } diff --git a/cmd/uatu/test_run.go b/cmd/uatu/test_run.go index 91f06a8..d9dedcd 100644 --- a/cmd/uatu/test_run.go +++ b/cmd/uatu/test_run.go @@ -28,9 +28,14 @@ const ( ) func runTestPipeline(ctx context.Context, options testOptions, stdout io.Writer) error { - specApiPath, err := resolveSpecAPIPath(options.spec) - if err != nil { - return err + if options.platform == "android" { + if err := ensureDevice(ctx, options.avd, stdout); err != nil { + return err + } + } + aliases := map[string]string{} + if specApiPath := resolveSpecAPIPath(options.spec); specApiPath != "" { + aliases["@uatu/spec"] = specApiPath } bundle, err := bundler.Bundle(bundler.Options{ EntryFile: options.spec, @@ -38,7 +43,7 @@ func runTestPipeline(ctx context.Context, options testOptions, stdout io.Writer) "UATU_TEST_PHONE": os.Getenv("UATU_TEST_PHONE"), "UATU_TEST_OTP": os.Getenv("UATU_TEST_OTP"), }, - Aliases: map[string]string{"@uatu/spec": specApiPath}, + Aliases: aliases, }) if err != nil { 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.Stderr = stdout + sidecarCommand.Env = envWithAndroidPlatformTools(os.Environ()) if err := sidecarCommand.Start(); err != nil { return fmt.Errorf("spawn sidecar: %w", err) } @@ -193,10 +199,11 @@ func runTestPipeline(ctx context.Context, options testOptions, stdout io.Writer) return nil } -// resolveSpecAPIPath finds pkg/spec-api/src/index.ts relative to the spec -// file or the current working directory so the bundler can resolve -// `@uatu/spec` imports. -func resolveSpecAPIPath(specPath string) (string, error) { +// resolveSpecAPIPath returns the path to pkg/spec-api/src/index.ts inside +// a uatu source checkout, searched upward from the spec file and the cwd. +// Returns "" when not found, in which case esbuild resolves @uatu/spec via +// node_modules the way a downstream user's project would. +func resolveSpecAPIPath(specPath string) string { candidates := []string{} if absoluteSpec, err := filepath.Abs(specPath); err == nil { directory := filepath.Dir(absoluteSpec) @@ -214,10 +221,10 @@ func resolveSpecAPIPath(specPath string) (string, error) { } for _, candidate := range candidates { 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) { @@ -230,10 +237,18 @@ func pickFreePort() (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() } 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() } diff --git a/cmd/uatu/test_run_test.go b/cmd/uatu/test_run_test.go new file mode 100644 index 0000000..490d4e9 --- /dev/null +++ b/cmd/uatu/test_run_test.go @@ -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) + } +} diff --git a/docs/manual/getting-started.md b/docs/manual/getting-started.md index b04a65d..2249df0 100644 --- a/docs/manual/getting-started.md +++ b/docs/manual/getting-started.md @@ -53,7 +53,8 @@ dependencies { The repo ships a working sample at `examples/sample-app`. From that directory: ```sh -./gradlew :sample-app:installDebug +npm install +(cd android && ./gradlew installDebug) uatu test \ --spec spec.ts \ --bundle-id dev.uatu.sample \ diff --git a/examples/sample-app/.gitignore b/examples/sample-app/.gitignore new file mode 100644 index 0000000..f491bf0 --- /dev/null +++ b/examples/sample-app/.gitignore @@ -0,0 +1 @@ +/runs \ No newline at end of file diff --git a/examples/sample-app/README.md b/examples/sample-app/README.md new file mode 100644 index 0000000..eed65af --- /dev/null +++ b/examples/sample-app/README.md @@ -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//`. + +## 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 diff --git a/examples/sample-app/android/build.gradle.kts b/examples/sample-app/android/build.gradle.kts index 280fafa..f7c9ad2 100644 --- a/examples/sample-app/android/build.gradle.kts +++ b/examples/sample-app/android/build.gradle.kts @@ -3,6 +3,8 @@ plugins { kotlin("android") version "2.1.21" } +val uatuVersion = findProperty("uatu.version") as String? ?: "0.0.0-dev" + android { namespace = "dev.uatu.sample" compileSdk = 35 @@ -12,7 +14,7 @@ android { minSdk = 24 targetSdk = 35 versionCode = 1 - versionName = findProperty("uatu.version") as String? ?: "0.0.0-dev" + versionName = uatuVersion } compileOptions { @@ -32,5 +34,5 @@ android { } dependencies { - implementation(project(":sdk-android")) + implementation("io.github.priyanshujain:sdk-android:$uatuVersion") } diff --git a/examples/sample-app/android/gradle.properties b/examples/sample-app/android/gradle.properties new file mode 100644 index 0000000..29c722d --- /dev/null +++ b/examples/sample-app/android/gradle.properties @@ -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=` or edit build.gradle.kts once a stable release is +# available on Maven Central. +uatu.version=0.0.0-dev diff --git a/examples/sample-app/android/gradle/wrapper/gradle-wrapper.jar b/examples/sample-app/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d997cfc Binary files /dev/null and b/examples/sample-app/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/examples/sample-app/android/gradle/wrapper/gradle-wrapper.properties b/examples/sample-app/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..c61a118 --- /dev/null +++ b/examples/sample-app/android/gradle/wrapper/gradle-wrapper.properties @@ -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 diff --git a/examples/sample-app/android/gradlew b/examples/sample-app/android/gradlew new file mode 100755 index 0000000..739907d --- /dev/null +++ b/examples/sample-app/android/gradlew @@ -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" "$@" diff --git a/examples/sample-app/android/gradlew.bat b/examples/sample-app/android/gradlew.bat new file mode 100644 index 0000000..e509b2d --- /dev/null +++ b/examples/sample-app/android/gradlew.bat @@ -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 diff --git a/examples/sample-app/android/settings.gradle.kts b/examples/sample-app/android/settings.gradle.kts new file mode 100644 index 0000000..7b8693f --- /dev/null +++ b/examples/sample-app/android/settings.gradle.kts @@ -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" diff --git a/examples/sample-app/justfile b/examples/sample-app/justfile index 1d5ecf7..a561f27 100644 --- a/examples/sample-app/justfile +++ b/examples/sample-app/justfile @@ -1,48 +1,74 @@ set shell := ["bash", "-cu"] +set dotenv-load := true -repo_root := absolute_path(justfile_directory() / ".." / "..") -uatu := env_var_or_default("UATU", repo_root / "bin/uatu") -avd := env_var_or_default("AVD", "") -duration := env_var_or_default("DURATION", "1m") -seed := env_var_or_default("SEED", "0") -output := env_var_or_default("OUTPUT", repo_root / "runs") +uatu := env_var_or_default("UATU", "uatu") +avd := env_var_or_default("AVD", "") +duration := env_var_or_default("DURATION", "1m") +seed := env_var_or_default("SEED", "0") +output := env_var_or_default("OUTPUT", justfile_directory() / "runs") +android := justfile_directory() / "android" default: @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. 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. 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). -uatu: - make -C {{repo_root}} uatu +# Remove the gradle build directory. +clean: + #!/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). -verify: - cd {{repo_root}} && go test ./internal/verifier/ -run TestSampleAppSpec - -# Run 'uatu test' against the sample app. AVD= is required. +# Run 'uatu test' against the sample app. Uses a connected device if one is +# online, otherwise boots AVD= if provided. test: #!/usr/bin/env bash set -euo pipefail - if [[ -z "{{avd}}" ]]; then - echo "AVD is required (usage: just AVD= test)" >&2 - exit 1 + avd_flag=() + if [[ -n "{{avd}}" ]]; then + avd_flag=(--avd "{{avd}}") fi - if [[ ! -x "{{uatu}}" ]]; then just uatu; fi "{{uatu}}" test \ --spec "{{justfile_directory()}}/spec.ts" \ --bundle-id dev.uatu.sample \ - --avd "{{avd}}" \ + "${avd_flag[@]}" \ --duration "{{duration}}" \ --seed "{{seed}}" \ --output "{{output}}" - -# Remove the gradle build directory for the sample app. -clean: - cd {{repo_root}} && ./gradlew :sample-app:clean diff --git a/examples/sample-app/package-lock.json b/examples/sample-app/package-lock.json new file mode 100644 index 0000000..53b04fe --- /dev/null +++ b/examples/sample-app/package-lock.json @@ -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 + } + } +} diff --git a/examples/sample-app/package.json b/examples/sample-app/package.json new file mode 100644 index 0000000..477525b --- /dev/null +++ b/examples/sample-app/package.json @@ -0,0 +1,8 @@ +{ + "name": "uatu-sample", + "private": true, + "description": "Minimal uatu integration example.", + "devDependencies": { + "@uatu/spec": "file:../../pkg/spec-api" + } +} diff --git a/sdk/android/src/main/kotlin/dev/uatu/sdk/Uatu.kt b/sdk/android/src/main/kotlin/dev/uatu/sdk/Uatu.kt index 3588a86..5225a35 100644 --- a/sdk/android/src/main/kotlin/dev/uatu/sdk/Uatu.kt +++ b/sdk/android/src/main/kotlin/dev/uatu/sdk/Uatu.kt @@ -1,6 +1,7 @@ package dev.uatu.sdk import android.app.Application +import android.util.Log data class Configuration( val socketName: String = "uatu-agent", @@ -9,6 +10,7 @@ data class Configuration( object Uatu { const val VERSION: String = "0.0.1" + private const val LOG_TAG = "Uatu" @Volatile private var runtime: UatuRuntime? = null @@ -24,6 +26,7 @@ object Uatu { ) newRuntime.start() runtime = newRuntime + Log.i(LOG_TAG, "SDK started (package=${application.packageName} socket=${configuration.socketName})") } fun extract(name: String, function: () -> Any?) { diff --git a/settings.gradle.kts b/settings.gradle.kts index 78d4475..030f14c 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -19,5 +19,3 @@ rootProject.name = "uatu" include(":sidecar") include(":sdk-android") project(":sdk-android").projectDir = file("sdk/android") -include(":sample-app") -project(":sample-app").projectDir = file("examples/sample-app/android") diff --git a/sidecar/src/main/kotlin/dev/uatu/sidecar/DriverBackend.kt b/sidecar/src/main/kotlin/dev/uatu/sidecar/DriverBackend.kt index b2f44ec..1fee58d 100644 --- a/sidecar/src/main/kotlin/dev/uatu/sidecar/DriverBackend.kt +++ b/sidecar/src/main/kotlin/dev/uatu/sidecar/DriverBackend.kt @@ -36,13 +36,47 @@ class StubDriverBackend(private val platform: String) : DriverBackend { if (clearState) { runAdb(listOf("shell", "pm", "clear", bundleId)) } - if (launcherActivity.isNotEmpty()) { - val component = if (launcherActivity.contains('/')) launcherActivity else "$bundleId/$launcherActivity" - runAdb(listOf("shell", "am", "start", "-n", component)) - } else { - // `monkey` uses PackageManager.getLaunchIntentForPackage, which - // picks the canonical default launcher. - runAdb(listOf("shell", "monkey", "-p", bundleId, "-c", "android.intent.category.LAUNCHER", "1")) + val component = when { + launcherActivity.isEmpty() -> "$bundleId/${resolveLauncherActivity(bundleId)}" + launcherActivity.contains('/') -> launcherActivity + else -> "$bundleId/$launcherActivity" + } + runAdb(listOf("shell", "am", "start", "-W", "-n", component)) + } + + 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 { + 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 `/`. + 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 } } diff --git a/sidecar/src/test/kotlin/dev/uatu/sidecar/DriverServiceTest.kt b/sidecar/src/test/kotlin/dev/uatu/sidecar/DriverServiceTest.kt index e3b17bc..3faec45 100644 --- a/sidecar/src/test/kotlin/dev/uatu/sidecar/DriverServiceTest.kt +++ b/sidecar/src/test/kotlin/dev/uatu/sidecar/DriverServiceTest.kt @@ -35,7 +35,13 @@ class DriverServiceTest { val backend = StubDriverBackend("android") 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(1, backend.launchCount) diff --git a/sidecar/src/test/kotlin/dev/uatu/sidecar/ResolveActivityTest.kt b/sidecar/src/test/kotlin/dev/uatu/sidecar/ResolveActivityTest.kt new file mode 100644 index 0000000..6bf9155 --- /dev/null +++ b/sidecar/src/test/kotlin/dev/uatu/sidecar/ResolveActivityTest.kt @@ -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) + } +}