package main import ( "bytes" "encoding/json" "net/http/httptest" "os" "os/exec" "path/filepath" "runtime" "strings" "testing" ) func TestInstallCommandValidation(t *testing.T) { commands, e := parseInstallCommands("# comment\n adb shell settings delete system app_source_white_list\r\nshell am force-stop com.example.app\n") if e != nil || len(commands) != 2 || commands[0][0] != "shell" { t.Fatal(commands, e) } for _, command := range []string{"adb -s other shell settings delete x y", "adb -H host shell id", "adb install app.apk", "adb shell id;reboot", "adb shell echo $HOME", "adb shell id | cat", "adb shell sh -c 'id'", strings.Repeat("shell id\n", 11)} { if _, e := parseInstallCommands(command); e == nil { t.Fatalf("accepted %q", command) } } } func TestInstallActionsOrderingFailureAndLauncher(t *testing.T) { root := t.TempDir() exe := filepath.Join(root, "fake-adb") name := "aapt" if runtime.GOOS == "windows" { exe += ".exe" name += ".exe" } helper := filepath.Join(root, "helper.go") writeFixture(t, helper, `package main import("encoding/json";"os";"strings";"fmt") func main(){a:=os.Args[1:];f,_:=os.OpenFile(os.Getenv("HOOK_LOG"),os.O_CREATE|os.O_APPEND|os.O_WRONLY,0600);json.NewEncoder(f).Encode(a);f.Close();text:=strings.Join(a," ");if strings.Contains(text,"fail"){fmt.Println("hook failed");os.Exit(7)};if a[0]=="devices"{fmt.Println("List of devices attached\nselected device model:Tablet");return};if a[0]=="dump"{fmt.Println("package: name='com.example.variant' versionCode='1'");return};if strings.Contains(text,"resolve-activity"){if os.Getenv("NO_LAUNCHER")=="1"{fmt.Println("No activity found")}else{fmt.Println("com.example.variant/.LauncherAlias")};return};fmt.Println("Success")} `) cmd := exec.Command("go", "build", "-o", exe, helper) if out, e := cmd.CombinedOutput(); e != nil { t.Fatalf("%v %s", e, out) } sdk := filepath.Join(root, "sdk") aapt := filepath.Join(sdk, "build-tools", "35.0.0", name) os.MkdirAll(filepath.Dir(aapt), 0700) binary, e := os.ReadFile(exe) if e != nil { t.Fatal(e) } if e = os.WriteFile(aapt, binary, 0700); e != nil { t.Fatal(e) } cfg, _ := json.Marshal(BuildEnvironment{Adb: exe, AndroidHome: sdk}) config := filepath.Join(root, "env.json") writeFixture(t, config, string(cfg)) bid := strings.Repeat("c", 32) apk := []byte("fake-apk") artifact := Artifact{Name: "0.apk", Hash: digest(apk), Size: int64(len(apk))} s := &Server{root: root, token: "test", environmentFile: config, builds: map[string]*Build{bid: {ID: bid, Status: "success", Artifacts: []Artifact{artifact}}}} writeFixture(t, filepath.Join(root, "artifacts", bid, artifact.Name), string(apk)) log := filepath.Join(root, "calls.jsonl") t.Setenv("HOOK_LOG", log) run := func(before, after string, launch bool) *httptest.ResponseRecorder { os.WriteFile(log, nil, 0600) data, _ := json.Marshal(map[string]any{"buildId": bid, "artifact": artifact.Name, "serial": "selected", "beforeCommands": before, "afterCommands": after, "launchAfter": launch}) req := httptest.NewRequest("POST", "/api/v1/adb/install", bytes.NewReader(data)) req.Header.Set("Authorization", "Bearer test") w := httptest.NewRecorder() s.ServeHTTP(w, req) return w } w := run("adb shell settings delete system app_source_white_list", "adb shell settings put system ready 1", true) if w.Code != 200 { t.Fatal(w.Code, w.Body.String()) } raw, _ := os.ReadFile(log) calls := string(raw) last := -1 for _, part := range []string{`"delete"`, `"install"`, `"put"`, `"dump"`, `"resolve-activity"`, `"am","start"`} { pos := strings.Index(calls, part) if pos <= last { t.Fatalf("order %s: %s", part, calls) } last = pos } for _, line := range strings.Split(strings.TrimSpace(calls), "\n") { var args []string json.Unmarshal([]byte(line), &args) if args[0] != "dump" && args[0] != "devices" && (len(args) < 2 || args[0] != "-s" || args[1] != "selected") { t.Fatal("wrong target", args) } } w = run("shell fail", "shell id", true) raw, _ = os.ReadFile(log) if w.Code == 200 || strings.Contains(string(raw), `"install"`) { t.Fatal("pre failure did not stop install", w.Code, string(raw)) } w = run("", "shell fail", true) raw, _ = os.ReadFile(log) if w.Code != 200 || !strings.Contains(w.Body.String(), `"postActionsSuccess":false`) || strings.Contains(string(raw), "resolve-activity") { t.Fatal("post failure result", w.Code, w.Body.String()) } t.Setenv("NO_LAUNCHER", "1") w = run("", "", true) if w.Code != 200 || !strings.Contains(w.Body.String(), `"postActionsSuccess":false`) { t.Fatal("missing launcher must keep installed", w.Body.String()) } }