Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 35 additions & 3 deletions internal/adb/adb.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,11 @@ type Client struct {
Log *logx.Logger
Booting func(serial string) bool
OnReregistered func(serial string)
// Exec, when set, runs each adb command in place of an adb.exe process (tests: a guest faked inside the test
// process, where a process per command costs most of the test). It gets the arguments after adb.exe, writes what
// adb would print to stdout and stderr, and returns adb's exit code; ctx ends at the command's timeout. Nil (always,
// outside tests) runs Root.AdbExe(). Clients Derive makes keep it.
Exec func(ctx context.Context, args []string, stdout, stderr io.Writer) int

// hooks tracks the OnReregistered runs of this client and of the clients Derive made from it. Nil for a Client
// written as a literal, which then shares literalHooks.
Expand All @@ -72,10 +77,10 @@ func New(r *root.Root, log *logx.Logger) *Client {
return &Client{Root: r, Log: log, hooks: &hookGroup{}}
}

// Derive is a client on the same root with another logger and OnReregistered (Booting is kept). It shares c's hook
// Derive is a client on the same root with another logger and OnReregistered (Booting and Exec are kept). It shares c's hook
// tracking, so WaitHooks on either one also waits for the hooks the other started.
func (c *Client) Derive(log *logx.Logger, onReregistered func(serial string)) *Client {
return &Client{Root: c.Root, Log: log, Booting: c.Booting, OnReregistered: onReregistered, hooks: c.hookGroup()}
return &Client{Root: c.Root, Log: log, Booting: c.Booting, OnReregistered: onReregistered, Exec: c.Exec, hooks: c.hookGroup()}
}

// literalHooks tracks the hooks of clients not made by New or Derive.
Expand Down Expand Up @@ -550,6 +555,9 @@ func (c *Client) execAdb(ctx context.Context, raw bool, out io.Writer, limit, ti
}
tctx, cancel := context.WithTimeout(ctx, limit)
defer cancel()
if c.Exec != nil {
return c.execHook(ctx, tctx, raw, out, args, cmdArgs, timedOut)
}
cmd := exec.CommandContext(tctx, c.Root.AdbExe(), cmdArgs...)
cmd.Env = c.Env()
host.HideConsoleCmd(cmd)
Expand Down Expand Up @@ -587,7 +595,31 @@ func (c *Client) execAdb(ctx context.Context, raw bool, out io.Writer, limit, ti
}
return timedOut()
}
code := cmd.ProcessState.ExitCode()
return result(cmd.ProcessState.ExitCode(), raw, out, &stdout, &stderr)
}

// execHook is execAdb through Client.Exec: the same outputs and the same timeout and cancel results.
func (c *Client) execHook(ctx, tctx context.Context, raw bool, out io.Writer, args, cmdArgs []string, timedOut func() Result) Result {
var stdout, stderr bytes.Buffer
var w1, w2 io.Writer = &stdout, &stdout // merged, in order, as one pipe
switch {
case out != nil:
w1, w2 = out, &stderr
case raw:
w2 = &stderr
}
code := c.Exec(tctx, cmdArgs, w1, w2)
if tctx.Err() != nil {
if ctx.Err() != nil {
return failed(raw, fmt.Sprintf("adb %s 已取消", strings.Join(args, " ")))
}
return timedOut()
}
return result(code, raw, out, &stdout, &stderr)
}

// result is the Result of an adb run that exited with code (execAdb).
func result(code int, raw bool, out io.Writer, stdout, stderr *bytes.Buffer) Result {
if out != nil {
text := strings.TrimSpace(decodeOutput(stderr.Bytes()))
return Result{Code: code, Out: text, Stderr: text}
Expand Down
55 changes: 55 additions & 0 deletions internal/adb/fakeadb_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -773,3 +773,58 @@ func TestReregisterFakeAdb(t *testing.T) {
}
})
}

// TestRunThroughExec: with Client.Exec set, Run hands it what adb.exe would get (after the server check) and makes the
// same Result of what it writes and returns; a deadline or a cancel while it runs are adb's timeout and cancel; Derive
// keeps it.
func TestRunThroughExec(t *testing.T) {
f := newFakeAdb(t)
ctx := context.Background()
if ok, err := f.c.EnsureServer(ctx, 10*time.Second); err != nil || !ok {
t.Fatalf("fake server did not start: %v %v", ok, err)
}
var got [][]string
f.c.Exec = func(ctx context.Context, args []string, stdout, stderr io.Writer) int {
got = append(got, args)
switch args[len(args)-1] {
case "hang":
<-ctx.Done()
return -1
case "both":
io.WriteString(stdout, "out\n")
io.WriteString(stderr, "err\n")
return 3
}
io.WriteString(stdout, "device\n")
return 0
}
port := strconv.Itoa(f.c.Root.AdbServerPort())
if res := f.c.Run(ctx, RunOptions{Serial: "emulator-20080"}, "get-state"); res.Code != 0 || res.Out != "device" {
t.Errorf("get-state: %+v", res)
}
if want := []string{"-P", port, "-s", "emulator-20080", "get-state"}; len(got) != 1 || !slices.Equal(got[0], want) {
t.Errorf("args %q, want %q", got, want)
}
if res := f.c.Run(ctx, RunOptions{}, "both"); res.Code != 3 || res.Out != "out\nerr" {
t.Errorf("merged: %+v", res)
}
if res := f.c.Run(ctx, RunOptions{Raw: true}, "both"); res.Code != 3 || string(res.Stdout) != "out\n" || res.Stderr != "err" || res.Out != "err" {
t.Errorf("raw: %+v", res)
}
var out strings.Builder
if res := f.c.Run(ctx, RunOptions{Stdout: &out}, "both"); res.Code != 3 || out.String() != "out\n" || res.Out != "err" {
t.Errorf("stdout writer: %+v, %q", res, out.String())
}
if res := f.c.Run(ctx, RunOptions{Timeout: 100 * time.Millisecond}, "hang"); res.Code != -1 || res.Out != "adb hang 超时(0 秒)" {
t.Errorf("timeout: %+v", res)
}
cctx, cancel := context.WithCancel(ctx)
time.AfterFunc(100*time.Millisecond, cancel)
if res := f.c.Run(cctx, RunOptions{Timeout: time.Minute}, "hang"); res.Code != -1 || res.Out != "adb hang 已取消" {
t.Errorf("cancel: %+v", res)
}
got = nil
if res := f.c.Derive(logx.Nop(), nil).Run(ctx, RunOptions{}, "get-state"); res.Code != 0 || len(got) != 1 {
t.Errorf("derived client: %+v, %d calls", res, len(got))
}
}
11 changes: 6 additions & 5 deletions internal/emu/appproxy_fake_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
Expand Down Expand Up @@ -43,7 +44,7 @@ var (
)

// fakeProxyGuest answers the per-app proxy's adb calls; handled is false for the others.
func fakeProxyGuest(args []string) (handled bool, code int) {
func fakeProxyGuest(args []string, out io.Writer) (handled bool, code int) {
dir := os.Getenv(fakeProxyEnv)
if dir == "" {
return false, 0
Expand Down Expand Up @@ -91,10 +92,10 @@ func fakeProxyGuest(args []string) (handled bool, code int) {
return true, 0
case strings.HasPrefix(cmd, "sha256sum "+proxyExe):
if s := read("sum"); s != "" {
fmt.Printf("%s %s\n", s, proxyExe)
fmt.Fprintf(out, "%s %s\n", s, proxyExe)
return true, 0
}
fmt.Printf("sha256sum: %s: No such file or directory\n", proxyExe)
fmt.Fprintf(out, "sha256sum: %s: No such file or directory\n", proxyExe)
return true, 1
case strings.HasPrefix(cmd, "test -x "+proxyExe):
if read("sum") != "" {
Expand All @@ -109,7 +110,7 @@ func fakeProxyGuest(args []string) (handled bool, code int) {
}
script := strings.TrimSuffix(strings.TrimPrefix(cmd, "su 0 sh -c '"), "'")
if _, err := os.Stat(filepath.Join(dir, "mute")); err == nil {
fmt.Println("error: closed")
fmt.Fprintln(out, "error: closed")
return true, 1
}
if strings.Contains(script, "mv -f "+proxyExe+".new "+proxyExe) {
Expand Down Expand Up @@ -147,7 +148,7 @@ func fakeProxyGuest(args []string) (handled bool, code int) {
st.Rules = read("rules")
}
b, _ := json.Marshal(st)
fmt.Println(string(b))
fmt.Fprintln(out, string(b))
if st.Rules != appproxy.RulesOK && verb == "start" {
return true, 1
}
Expand Down
3 changes: 3 additions & 0 deletions internal/emu/bootadb_windows_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ func bootAdbFakes(t *testing.T, q win.Process, booted bool) *atomic.Int32 {
// Android booted but adb never answers: the wait tries to register the instance, stops adbAfterBootWait after the
// emulator reported the boot (not at the far timeout), and says Android is up; at the timeout, it says the same.
func TestWaitBootAdbUnusableAfterBoot(t *testing.T) {
withVar(t, &bootPollInterval, 100*time.Millisecond) // what is waited here is the timeout, not the polls
m, _ := opsTestManager(t)
q, _ := startSleeper(t)
tries := bootAdbFakes(t, q, true)
Expand Down Expand Up @@ -70,6 +71,7 @@ func TestWaitBootAdbUnusableAfterBoot(t *testing.T) {

// Without a boot report from the emulator nothing changes: no register tries, the plain timeout.
func TestWaitBootNoBootReport(t *testing.T) {
withVar(t, &bootPollInterval, 100*time.Millisecond) // what is waited here is the timeout, not the polls
m, _ := opsTestManager(t)
q, _ := startSleeper(t)
tries := bootAdbFakes(t, q, false)
Expand All @@ -85,6 +87,7 @@ func TestWaitBootNoBootReport(t *testing.T) {
// A boot wait that times out on a boot whose emulator log says Windows refused the virtual machine (ModAVD/ModAVD#301)
// says so: timeout with the reason hypervisor_access_denied.
func TestWaitBootTimeoutHypervisorDenied(t *testing.T) {
withVar(t, &bootPollInterval, 100*time.Millisecond) // what is waited here is the timeout, not the polls
m, _ := opsTestManager(t)
q, _ := startSleeper(t)
bootAdbFakes(t, q, false)
Expand Down
21 changes: 19 additions & 2 deletions internal/emu/bootdiag_windows_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ import (
"path/filepath"
"slices"
"strings"
"sync/atomic"
"testing"
"time"

"modavd/internal/errs"
"modavd/internal/host"
"modavd/internal/jsonord"
"modavd/internal/logx"
"modavd/internal/testutil"
Expand Down Expand Up @@ -141,14 +143,29 @@ func TestStartTimeoutSavesBootDiag(t *testing.T) {
return matches
}

// The first start is canceled as soon as its boot wait has found the qemu, not after a fixed time: the wait
// is reached for sure and none of its 30 s is waited out. The waits poll every 100 ms; the second start
// times out after 500 ms.
withVar(t, &bootPollInterval, 100*time.Millisecond)
var cancelWait atomic.Pointer[context.CancelFunc]
find := waitBootFindQemu
withVar(t, &waitBootFindQemu, func(m *Manager, i int) (host.Process, bool, error) {
p, found, err := find(m, i)
if c := cancelWait.Load(); found && c != nil {
(*c)()
}
return p, found, err
})
ctx, cancel := context.WithCancel(context.Background())
time.AfterFunc(1500*time.Millisecond, cancel)
defer cancel()
cancelWait.Store(&cancel)
if _, err := m.Start(ctx, 6, StartOptions{Timeout: 30 * time.Second}); errs.CodeOf(err) != errs.Canceled ||
errs.DetailsOf(err)[errs.BootDiagDir] != "" || len(diagDirs()) != 0 {
t.Fatalf("canceled start: %v, details %v, dirs %v", err, errs.DetailsOf(err), diagDirs())
}
cancelWait.Store(nil)

_, err := m.Start(context.Background(), 6, StartOptions{Timeout: 2 * time.Second})
_, err := m.Start(context.Background(), 6, StartOptions{Timeout: 500 * time.Millisecond})
dir := errs.DetailsOf(err)[errs.BootDiagDir]
if errs.CodeOf(err) != errs.Timeout || dir == "" {
t.Fatalf("timed-out start: %v (%s), details %v", err, errs.CodeOf(err), errs.DetailsOf(err))
Expand Down
5 changes: 5 additions & 0 deletions internal/emu/bootready_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,7 @@ func TestReadyTrackerFile(t *testing.T) {
// A record that cannot be written is warned about, nothing is tracked, and the marker's heartbeat stops: status does
// not wait for a setup it cannot see.
func TestBeginReadyWriteFailure(t *testing.T) {
shortReplaceRetry(t)
logs := &logx.Collector{}
m := markerTestManager(t)
m.Log = logx.New(logs.Sink())
Expand Down Expand Up @@ -580,6 +581,9 @@ func newStartRun(t *testing.T) *startRun {
r, _ := portPlanRoot(t)
logs := &logx.Collector{}
m := New(r, logx.New(logs.Sink()))
// The fake guest answers inside this process: a start runs some 45 adb commands, and a copy of the test binary per
// command was most of each test's time on Windows. The adb process path itself is covered by the port plan tests.
m.ADB.Exec = fakeAdbInProcess
const i = 6
six := i
if _, err := m.Create(context.Background(), CreateRequest{filesOnly: true, Index: &six}); err != nil {
Expand Down Expand Up @@ -894,6 +898,7 @@ func TestStartPastTheCapReportsOnline(t *testing.T) {

// A record that cannot be written: the start warns, goes on, and status never waits for it.
func TestStartWithoutARecordIsNotWaitedFor(t *testing.T) {
shortReplaceRetry(t)
s := newStartRun(t)
setCap(t, time.Hour)
s.owedMarker()
Expand Down
1 change: 1 addition & 0 deletions internal/emu/early_windows_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
// TestWaitBootEarly: the boot wait hands each poll where adb answers before the boot has completed to early, until
// early says done; a poll where adb does not answer does not call it; the boot completing ends the wait.
func TestWaitBootEarly(t *testing.T) {
withVar(t, &bootPollInterval, 100*time.Millisecond)
m, _ := opsTestManager(t)
q, _ := startSleeper(t)
bootAdbFakes(t, q, false)
Expand Down
1 change: 1 addition & 0 deletions internal/emu/guestfix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -641,6 +641,7 @@ func TestGuestFixConstants(t *testing.T) {
}

func TestWriteFileReplace(t *testing.T) {
shortReplaceRetry(t)
dir := testutil.TempDir(t)
path := filepath.Join(dir, ndkfix.CacheName)
if err := writeFileReplace(path, []byte("first"), "1-0"); err != nil {
Expand Down
5 changes: 4 additions & 1 deletion internal/emu/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,13 @@ import (
"modavd/internal/root"
)

// bootPollInterval: how often the boot wait asks whether Android has booted (AUTO-MAS _wait_boot: every second). A
// variable for tests.
var bootPollInterval = time.Second

// Timeouts, from AUTO-MAS constants.py where they exist there.
const (
DefaultBootTimeout = 300 * time.Second
bootPollInterval = time.Second
statusAdbTimeout = 5 * time.Second
// how long a start waits for an earlier start / stop of the same instance
startLockWait = DefaultBootTimeout + 300*time.Second
Expand Down
7 changes: 7 additions & 0 deletions internal/emu/overlay_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"modavd/internal/host"
"modavd/internal/jsonord"
"modavd/internal/logx"
"modavd/internal/root"
"modavd/internal/win"
"modavd/internal/win/wintest"
)
Expand Down Expand Up @@ -142,6 +143,12 @@ func withVar[T any](t *testing.T, v *T, val T) {
t.Cleanup(func() { *v = saved })
}

// shortReplaceRetry: a replace meant to keep failing (a folder where the file goes, the target held open) gives up
// after a moment instead of root's 3 s.
func shortReplaceRetry(t *testing.T) {
t.Cleanup(root.SetReplaceRetryForTest(200 * time.Millisecond))
}

// winsOf names windows as an overlay's mark does: of qemu q, with the class the fake gives.
func winsOf(q win.Process, hs ...uint64) []overlayWin {
var out []overlayWin
Expand Down
34 changes: 21 additions & 13 deletions internal/emu/portplan_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,15 @@ func startFake(t *testing.T, exe, mode string, listen int, args ...string) win.P
return p
}

func fakeAdbClientMain(args []string) int {
func fakeAdbClientMain(args []string) int { return fakeAdbClient(args, os.Stdout) }

// fakeAdbInProcess is fakeAdbClient as adb.Client.Exec: the same answers without a process per command.
func fakeAdbInProcess(_ context.Context, args []string, stdout, _ io.Writer) int {
return fakeAdbClient(args, stdout)
}

// fakeAdbClient is the fake adb client: it logs args and writes the guest's answer to out.
func fakeAdbClient(args []string, out io.Writer) int {
if slices.Contains(args, "logcat") && os.Getenv(fakeLogcatStreamEnv) != "" {
return fakeLogcatStream(args)
}
Expand All @@ -179,7 +187,7 @@ func fakeAdbClientMain(args []string) int {
f.Write(append(line, '\n'))
f.Close()
}
if handled, code := fakeProxyGuest(args); handled {
if handled, code := fakeProxyGuest(args, out); handled {
return code
}
all := strings.Join(args, " ")
Expand All @@ -189,38 +197,38 @@ func fakeAdbClientMain(args []string) int {
case strings.Contains(all, sdcardProbeMarker) && os.Getenv(fakeAdbSdcardFailEnv) != "":
return 1 // /sdcard never accepts a file
case strings.Contains(all, "org.modavd.regional.Regional"):
fmt.Print(os.Getenv(fakeAdbRegionalAppliedEnv))
fmt.Fprint(out, os.Getenv(fakeAdbRegionalAppliedEnv))
code, _ := strconv.Atoi(os.Getenv(fakeAdbRegionalExitEnv))
return code
case strings.Contains(all, "getprop persist.sys.locale"):
fmt.Print(os.Getenv(fakeAdbRegionalPropertiesEnv))
fmt.Fprint(out, os.Getenv(fakeAdbRegionalPropertiesEnv))
code, _ := strconv.Atoi(os.Getenv(fakeAdbRegionalExitEnv))
return code
case strings.Contains(all, "get-state"):
fmt.Println("device")
fmt.Fprintln(out, "device")
case strings.Contains(all, "sys.boot_completed"):
if os.Getenv(fakeAdbNoBootEnv) == "" {
fmt.Println("1")
fmt.Fprintln(out, "1")
}
case strings.Contains(all, "topResumedActivity") && os.Getenv(fakeAdbForegroundEnv) != "":
fmt.Println(os.Getenv(fakeAdbForegroundEnv))
fmt.Fprintln(out, os.Getenv(fakeAdbForegroundEnv))
case strings.Contains(all, "KEYCODE_HOME"): // guestHomeScript: what is in front
fmt.Println(cmp.Or(os.Getenv(fakeAdbHomeEnv), "home"))
fmt.Fprintln(out, cmp.Or(os.Getenv(fakeAdbHomeEnv), "home"))
case strings.Contains(all, guestShutdownCommand):
code, _ := strconv.Atoi(os.Getenv(fakeAdbSvcExitEnv))
return code
case strings.Contains(all, shutdownProbeEnd): // guestShutdownProbe
if out, ok := os.LookupEnv(fakeAdbProbeEnv); ok {
fmt.Print(out)
if probe, ok := os.LookupEnv(fakeAdbProbeEnv); ok {
fmt.Fprint(out, probe)
} else {
fmt.Println("req=\nctl=\n" + shutdownProbeEnd)
fmt.Fprintln(out, "req=\nctl=\n"+shutdownProbeEnd)
}
code, _ := strconv.Atoi(os.Getenv(fakeAdbProbeExitEnv))
return code
case strings.Contains(all, "logcat -d -b all"): // bootdiag.go
fmt.Println("11-04 10:00:00.000 E zygote: fake")
fmt.Fprintln(out, "11-04 10:00:00.000 E zygote: fake")
case strings.HasSuffix(all, "shell getprop"):
fmt.Println("[sys.boot_completed]: []")
fmt.Fprintln(out, "[sys.boot_completed]: []")
}
return 0
}
Expand Down
Loading
Loading