From 053865c57a90210a00f3dbc1d3e700ff9151c583 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Sat, 5 Dec 2026 23:21:15 +0100 Subject: [PATCH] =?UTF-8?q?=E6=B5=8B=E8=AF=95=EF=BC=9A=E7=BC=A9=E7=9F=AD?= =?UTF-8?q?=20internal/emu=20=E5=9C=A8=20Windows=20=E4=B8=8A=E7=9A=84?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=E8=80=97=E6=97=B6=EF=BC=88=E7=BA=A6=20332=20?= =?UTF-8?q?=E2=86=92=20205=20=E7=A7=92=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 按根因改,产品默认值和行为不变: - 假 adb / 假 qemu 子进程:stop_record_test.go 的包级变量用了 time.Local, 每个拷成 adb.exe / qemu.exe 的测试二进制在包初始化时都去查本机时区(约 35 ms)。改成函数,子进程启动从约 55 ms 降到约 19 ms。 - 走完整 Start 的测试:adb.Client 加可选的 Exec(产品里永远是 nil), newStartRun 用进程内的假 guest 代替每条命令一个假 adb 进程。真 adb 进程 这条路径仍由 port plan 那组测试覆盖。 - 等开机的轮询:bootPollInterval 改成包内变量(默认 1 秒),不依赖 1 秒 节奏的测试改成 100 ms;TestStartTimeoutSavesBootDiag 改成等开机找到 qemu 时取消,不靠固定时间。 - 文件替换重试:root.replaceRetry 改成变量(默认 3 秒),加 SetReplaceRetryForTest,测「一直替换不了」的三条测试用 200 ms。 - TestStopOpsShutdownExitCode 的等待窗口 1.5 秒改成 800 ms。 Refs ModAVD/ModAVD#403 --- internal/adb/adb.go | 38 ++++++++++++++++-- internal/adb/fakeadb_test.go | 55 +++++++++++++++++++++++++++ internal/emu/appproxy_fake_test.go | 11 +++--- internal/emu/bootadb_windows_test.go | 3 ++ internal/emu/bootdiag_windows_test.go | 21 +++++++++- internal/emu/bootready_test.go | 5 +++ internal/emu/early_windows_test.go | 1 + internal/emu/guestfix_test.go | 1 + internal/emu/manager.go | 5 ++- internal/emu/overlay_test.go | 7 ++++ internal/emu/portplan_test.go | 34 ++++++++++------- internal/emu/start_test.go | 2 + internal/emu/stop_record_test.go | 20 +++++----- internal/emu/stop_test.go | 6 +-- internal/root/root.go | 13 ++++++- 15 files changed, 184 insertions(+), 38 deletions(-) diff --git a/internal/adb/adb.go b/internal/adb/adb.go index 387b2bcc..75e70ee8 100644 --- a/internal/adb/adb.go +++ b/internal/adb/adb.go @@ -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. @@ -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. @@ -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) @@ -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} diff --git a/internal/adb/fakeadb_test.go b/internal/adb/fakeadb_test.go index 3becced6..652424bd 100644 --- a/internal/adb/fakeadb_test.go +++ b/internal/adb/fakeadb_test.go @@ -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)) + } +} diff --git a/internal/emu/appproxy_fake_test.go b/internal/emu/appproxy_fake_test.go index 8224329c..755aadb9 100644 --- a/internal/emu/appproxy_fake_test.go +++ b/internal/emu/appproxy_fake_test.go @@ -9,6 +9,7 @@ import ( "encoding/json" "errors" "fmt" + "io" "os" "path/filepath" "regexp" @@ -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 @@ -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") != "" { @@ -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) { @@ -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 } diff --git a/internal/emu/bootadb_windows_test.go b/internal/emu/bootadb_windows_test.go index 37e97752..cc7546e8 100644 --- a/internal/emu/bootadb_windows_test.go +++ b/internal/emu/bootadb_windows_test.go @@ -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) @@ -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) @@ -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) diff --git a/internal/emu/bootdiag_windows_test.go b/internal/emu/bootdiag_windows_test.go index 606d11cc..aa9b2cf3 100644 --- a/internal/emu/bootdiag_windows_test.go +++ b/internal/emu/bootdiag_windows_test.go @@ -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" @@ -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)) diff --git a/internal/emu/bootready_test.go b/internal/emu/bootready_test.go index baffe3eb..71efc2c7 100644 --- a/internal/emu/bootready_test.go +++ b/internal/emu/bootready_test.go @@ -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()) @@ -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 { @@ -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() diff --git a/internal/emu/early_windows_test.go b/internal/emu/early_windows_test.go index 316bed0d..19c92eb4 100644 --- a/internal/emu/early_windows_test.go +++ b/internal/emu/early_windows_test.go @@ -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) diff --git a/internal/emu/guestfix_test.go b/internal/emu/guestfix_test.go index de7bbd98..3c5d97ca 100644 --- a/internal/emu/guestfix_test.go +++ b/internal/emu/guestfix_test.go @@ -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 { diff --git a/internal/emu/manager.go b/internal/emu/manager.go index 6af71699..62a7cb2d 100644 --- a/internal/emu/manager.go +++ b/internal/emu/manager.go @@ -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 diff --git a/internal/emu/overlay_test.go b/internal/emu/overlay_test.go index 377dd264..f711f5ea 100644 --- a/internal/emu/overlay_test.go +++ b/internal/emu/overlay_test.go @@ -21,6 +21,7 @@ import ( "modavd/internal/host" "modavd/internal/jsonord" "modavd/internal/logx" + "modavd/internal/root" "modavd/internal/win" "modavd/internal/win/wintest" ) @@ -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 diff --git a/internal/emu/portplan_test.go b/internal/emu/portplan_test.go index e7733baf..05550432 100644 --- a/internal/emu/portplan_test.go +++ b/internal/emu/portplan_test.go @@ -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) } @@ -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, " ") @@ -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 } diff --git a/internal/emu/start_test.go b/internal/emu/start_test.go index aaf79973..ad1c6fe0 100644 --- a/internal/emu/start_test.go +++ b/internal/emu/start_test.go @@ -695,6 +695,7 @@ func TestStartNoSwitchWhileRunning(t *testing.T) { // the instance once more); an emulator.exe this start launched that exits is a plain launch failure. A stop of the // instance holding its lock during the wait is reported (stopSeen), and only for an adopted qemu. func TestWaitBootAdoptedGone(t *testing.T) { + withVar(t, &bootPollInterval, 100*time.Millisecond) m, _ := opsTestManager(t) q, kill := startSleeper(t) kill() @@ -733,6 +734,7 @@ func TestWaitBootAdoptedGone(t *testing.T) { } func TestWaitBootSeesStopDuringAdbProbe(t *testing.T) { + withVar(t, &bootPollInterval, 100*time.Millisecond) m, _ := opsTestManager(t) q, kill := startSleeper(t) var stop *win.FileLock diff --git a/internal/emu/stop_record_test.go b/internal/emu/stop_record_test.go index 4c359d02..159e9bf0 100644 --- a/internal/emu/stop_record_test.go +++ b/internal/emu/stop_record_test.go @@ -212,7 +212,9 @@ func (g *fakeShutdownGuest) run(command string, timeout time.Duration) adb.Resul return adb.Result{Code: 127, Out: "unexpected " + command} } -var shutdownNow = time.Date(2026, 11, 29, 21, 5, 7, 0, time.Local) +// shutdownNow is a function, not a package variable: time.Local read at package init costs every copy of this test +// binary that runs as a fake adb / qemu / helper tens of milliseconds on Windows (the zone is looked up in the registry). +func shutdownNow() time.Time { return time.Date(2026, 11, 29, 21, 5, 7, 0, time.Local) } func linesAt(lines []clockLine, level logx.Level) []string { var out []string @@ -258,7 +260,7 @@ func TestRecordBeforeShutdownDownloads(t *testing.T) { } { m, lines := clockManager(t) g := &fakeShutdownGuest{downloads: c.res, kernel: kernel} - m.recordBeforeShutdown(2, 3*time.Second, g.run, func() time.Time { return shutdownNow }) + m.recordBeforeShutdown(2, 3*time.Second, g.run, shutdownNow) if !slices.Equal(linesAt(*lines, logx.Warn), c.warns) { t.Errorf("%s: warnings %q", c.name, linesAt(*lines, logx.Warn)) } @@ -338,7 +340,7 @@ func TestRecordBeforeShutdownKernelUnread(t *testing.T) { // The file: the agreed name (the problem report collects it), the comment line, an empty line, the log with LF. func TestSaveShutdownKernelLog(t *testing.T) { m, _ := clockManager(t) - path, err := m.saveShutdownKernelLog(3, adb.Result{Out: "<6>[ 0.000000] a\r\n<3>[ 12.5] EXT4-fs error\r\n"}, shutdownNow) + path, err := m.saveShutdownKernelLog(3, adb.Result{Out: "<6>[ 0.000000] a\r\n<3>[ 12.5] EXT4-fs error\r\n"}, shutdownNow()) if err != nil { t.Fatal(err) } @@ -349,7 +351,7 @@ func TestSaveShutdownKernelLog(t *testing.T) { if err != nil { t.Fatal(err) } - want := "# 实例 3 关机前的客体内核日志,读于 " + shutdownNow.Format(time.RFC3339) + ";来源 adb shell su 0 logcat -b kernel -d\n" + + want := "# 实例 3 关机前的客体内核日志,读于 " + shutdownNow().Format(time.RFC3339) + ";来源 adb shell su 0 logcat -b kernel -d\n" + "\n<6>[ 0.000000] a\n<3>[ 12.5] EXT4-fs error\n" if string(b) != want { t.Fatalf("content %q\nwant %q", b, want) @@ -370,7 +372,7 @@ func TestShutdownKernelLogContentTruncates(t *testing.T) { fmt.Fprintf(&log, "<6>[%10d.000000] 第 %d 行 kernel line\n", k, k) } full := log.String() - b := shutdownKernelLogContent(1, full, shutdownNow, shutdownKernelLogMax) + b := shutdownKernelLogContent(1, full, shutdownNow(), shutdownKernelLogMax) if len(b) > shutdownKernelLogMax { t.Fatalf("%d bytes, over %d", len(b), shutdownKernelLogMax) } @@ -392,7 +394,7 @@ func TestShutdownKernelLogContentTruncates(t *testing.T) { // one huge line: cut at a character start, still within the limit huge := strings.Repeat("内核", 200) - b = shutdownKernelLogContent(1, huge, shutdownNow, 600) + b = shutdownKernelLogContent(1, huge, shutdownNow(), 600) if len(b) > 600 || !strings.HasSuffix(huge, string(b[strings.LastIndex(string(b), "\n\n")+2:])) { t.Fatalf("huge line: %d bytes %q", len(b), b) } @@ -409,7 +411,7 @@ func TestShutdownKernelLogContentTruncates(t *testing.T) { } full = log.String() for limit := 1000; limit < 1400; limit++ { - b := shutdownKernelLogContent(1, full, shutdownNow, limit) + b := shutdownKernelLogContent(1, full, shutdownNow(), limit) parts := strings.SplitN(string(b), "\n", 4) body := parts[3] cut := len(full) - len(body) @@ -435,7 +437,7 @@ func TestShutdownKernelLogKeepsFive(t *testing.T) { } } for k := range 7 { - if _, err := m.saveShutdownKernelLog(3, adb.Result{Out: "k\n"}, shutdownNow.Add(time.Duration(k)*time.Second)); err != nil { + if _, err := m.saveShutdownKernelLog(3, adb.Result{Out: "k\n"}, shutdownNow().Add(time.Duration(k)*time.Second)); err != nil { t.Fatal(err) } } @@ -449,7 +451,7 @@ func TestShutdownKernelLogKeepsFive(t *testing.T) { } want := append([]string{}, others...) for k := 2; k < 7; k++ { - want = append(want, "mas_3-"+shutdownNow.Add(time.Duration(k)*time.Second).Format("20060102-150405")+"-kernel.txt") + want = append(want, "mas_3-"+shutdownNow().Add(time.Duration(k)*time.Second).Format("20060102-150405")+"-kernel.txt") } slices.Sort(kept) slices.Sort(want) diff --git a/internal/emu/stop_test.go b/internal/emu/stop_test.go index 4a5c0d2b..38989e3e 100644 --- a/internal/emu/stop_test.go +++ b/internal/emu/stop_test.go @@ -373,12 +373,12 @@ func TestStopOpsShutdownExitCode(t *testing.T) { t.Fatal("cannot read our own process") } ops := m.stopOpsFor(context.Background(), 6, running) - const window = 1500 * time.Millisecond + const window = 800 * time.Millisecond // four of the five calls wait it out t.Setenv(fakeAdbSvcExitEnv, "255") began := time.Now() why := ops.graceful(window) - if took := time.Since(began); took < window || why != "2 秒内没有自己退出" { + if took := time.Since(began); took < window || why != "1 秒内没有自己退出" { t.Errorf("exit 255: %q after %v, want the whole %v", why, took, window) } @@ -400,7 +400,7 @@ func TestStopOpsShutdownExitCode(t *testing.T) { t.Setenv(fakeAdbProbeExitEnv, probe.code) began = time.Now() why = ops.graceful(window) - if took := time.Since(began); took < window || why != "2 秒内没有自己退出" { + if took := time.Since(began); took < window || why != "1 秒内没有自己退出" { t.Errorf("exit 0, %s: %q after %v, want the whole %v", name, why, took, window) } } diff --git a/internal/root/root.go b/internal/root/root.go index 1084bc25..28c7dfb8 100644 --- a/internal/root/root.go +++ b/internal/root/root.go @@ -374,8 +374,17 @@ func (r *Root) ManifestPath() string { return filepath.Join(r.Dir, ManifestFil // ---- mas-avd.json ------------------------------------------------------------------------------------------------ -// replaceRetry: AUTO-MAS _REPLACE_RETRY_SECONDS. -const replaceRetry = 3 * time.Second +// replaceRetry: AUTO-MAS _REPLACE_RETRY_SECONDS. A variable for tests (SetReplaceRetryForTest). +var replaceRetry = 3 * time.Second + +// SetReplaceRetryForTest makes ReplaceWithRetry give up after d instead of 3 s until restore is called. Only for tests +// whose replace is meant to keep failing (the target held open, a folder in its place): they need not wait out the +// whole retry each time. +func SetReplaceRetryForTest(d time.Duration) (restore func()) { + old := replaceRetry + replaceRetry = d + return func() { replaceRetry = old } +} // metadataLockWait bounds the wait for another modavd's read-modify-write (each takes milliseconds, plus at most // replaceRetry). A variable for tests.