diff --git a/README.md b/README.md index c236689..b197ab5 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,10 @@ updater := &selfupdate.Updater{ rootCmd.AddCommand(cobracmd.New(updater)) ``` +A runnable version of this snippet lives in +[`examples/mytool`](examples/mytool/main.go). Build it with +`go build ./examples/mytool`. + That adds: ```text @@ -82,6 +86,10 @@ before it replaces the running one. `PostInstall` runs after the replace. A `PostInstall` error is returned with a note that the binary was already updated. +A hook that needs the binary's own path must resolve `os.Executable()` +before the update starts. After the replace, the running process reports +the old inode, not the new file. `examples/mytool` shows the pattern. + ```go updater.PreInstall = func(ctx context.Context, current, latest string) error { if semver.MajorMinor(latest) != semver.MajorMinor(current) { @@ -144,6 +152,14 @@ Installer: &selfupdate.ScriptInstaller{ `Release` field. `Latest` still holds the tag. - `Release` carries `Assets`. `Updater` gains `PostInstall`. +## Testing + +`go test ./...` runs the unit suite and the end-to-end suite under +`internal/e2e`. The end-to-end suite builds `examples/mytool` twice with +different versions, serves a fake GitHub release from a local server, and +updates one build to the other as a subprocess. It needs a Go toolchain on +PATH and adds a few seconds. `go test -short ./...` skips it. + ## Compatibility Go 1.26 or later. The root package depends only on the standard library and diff --git a/examples/mytool/main.go b/examples/mytool/main.go new file mode 100644 index 0000000..211c938 --- /dev/null +++ b/examples/mytool/main.go @@ -0,0 +1,86 @@ +// Command mytool is the runnable version of the README example. It wires +// selfupdate-go with cobra, uses ArchiveInstaller with every default, and +// shows PreInstall and PostInstall hooks that report which binary is on disk. +// +// MYTOOL_GITHUB_API overrides the GitHub API base URL, for GitHub Enterprise +// or a local mock. Unset means api.github.com. +package main + +import ( + "context" + "fmt" + "io" + "os" + "os/exec" + "strings" + + "github.com/sentiolabs/selfupdate-go" + "github.com/sentiolabs/selfupdate-go/cobracmd" + "github.com/spf13/cobra" +) + +// version is set at build time: -ldflags "-X main.version=v1.0.0". +var version = "dev" + +// envAPI overrides GitHubSource.BaseURL, for GitHub Enterprise or a local +// mock. Unset means api.github.com. +const envAPI = "MYTOOL_GITHUB_API" + +// toolName is the name of the binary and GitHub repo. +const toolName = "mytool" + +// exitStartup is the exit code when the executable path cannot be resolved. +const exitStartup = 2 + +// exitFailure is the exit code for general execution failures. +const exitFailure = 1 + +func main() { + exe, err := os.Executable() + if err != nil { + _, _ = fmt.Fprintln(os.Stderr, toolName+": locate executable:", err) + os.Exit(exitStartup) + } + root := &cobra.Command{ + Use: toolName, + Short: "Demo CLI for selfupdate-go", + Version: version, + } + root.SetVersionTemplate("{{.Version}}\n") + root.AddCommand(cobracmd.New(newUpdater(root.OutOrStdout(), exe))) + if err := root.Execute(); err != nil { + os.Exit(exitFailure) + } +} + +// newUpdater mirrors the README wiring. Every ArchiveInstaller field is +// left at its default so asset selection, target resolution and the +// managed-path list are production behaviour. +func newUpdater(w io.Writer, exe string) *selfupdate.Updater { + return &selfupdate.Updater{ + Name: toolName, + Version: version, + Source: &selfupdate.GitHubSource{Owner: "acme", Repo: toolName, BaseURL: os.Getenv(envAPI)}, + // MemStore keeps the channel for this process only; a real CLI persists it. + Store: &selfupdate.MemStore{}, + Installer: &selfupdate.ArchiveInstaller{}, + PreInstall: reportHook(w, exe, "pre-install"), + PostInstall: reportHook(w, exe, "post-install"), + } +} + +// reportHook returns a hook that runs exe --version and prints what the +// binary on disk reports. exe is resolved once at startup on purpose: after +// the update, os.Executable() in this process points at the replaced file's +// old inode, not the new binary. +func reportHook(w io.Writer, exe, name string) func(context.Context, string, string) error { + return func(ctx context.Context, _, _ string) error { + out, err := exec.CommandContext(ctx, exe, "--version").Output() + if err != nil { + // A failing hook aborts the update on purpose; the e2e suite relies on these lines. + return fmt.Errorf("%s: run %s --version: %w", name, exe, err) + } + _, _ = fmt.Fprintf(w, "%s: binary reports %s\n", name, strings.TrimSpace(string(out))) + return nil + } +} diff --git a/internal/e2e/doc.go b/internal/e2e/doc.go new file mode 100644 index 0000000..bee5c67 --- /dev/null +++ b/internal/e2e/doc.go @@ -0,0 +1,5 @@ +// Package e2e drives examples/mytool as a subprocess against a local +// GitHub-shaped release server. TestMain builds the demo twice with +// different versions; the scenarios update one build to the other and +// inspect the binary on disk. Run go test -short to skip the suite. +package e2e diff --git a/internal/e2e/e2e_test.go b/internal/e2e/e2e_test.go new file mode 100644 index 0000000..e0f8f41 --- /dev/null +++ b/internal/e2e/e2e_test.go @@ -0,0 +1,69 @@ +package e2e_test + +import ( + "flag" + "fmt" + "os" + "os/exec" + "path/filepath" + "testing" +) + +// Set by TestMain. Absolute paths of the two builds of examples/mytool. +var ( + oldBinary string // built with version v1.0.0 + newBinary string // built with version v1.1.0 +) + +const ( + oldVersion = "v1.0.0" + newVersion = "v1.1.0" + envAPI = "MYTOOL_GITHUB_API" +) + +// TestMain builds the demo twice. Under -short it builds nothing and every +// scenario skips itself through requireBinaries. +func TestMain(m *testing.M) { + flag.Parse() + if testing.Short() { + os.Exit(m.Run()) + } + dir, err := os.MkdirTemp("", "selfupdate-e2e-*") + if err != nil { + _, _ = fmt.Fprintln(os.Stderr, "e2e: temp dir:", err) + os.Exit(1) + } + oldBinary, err = buildDemo(dir, oldVersion) + if err == nil { + newBinary, err = buildDemo(dir, newVersion) + } + if err != nil { + _, _ = fmt.Fprintln(os.Stderr, "e2e:", err) + _ = os.RemoveAll(dir) + os.Exit(1) + } + code := m.Run() + _ = os.RemoveAll(dir) + os.Exit(code) +} + +// buildDemo compiles examples/mytool with version baked in and returns the +// binary path. The test's working directory is this package, so the +// relative source path resolves. +func buildDemo(dir, version string) (string, error) { + out := filepath.Join(dir, "mytool-"+version) + //nolint:gosec // version is one of the package's own oldVersion/newVersion constants, not external input + cmd := exec.Command("go", "build", "-ldflags", "-X main.version="+version, "-o", out, "../../examples/mytool") + if b, err := cmd.CombinedOutput(); err != nil { + return "", fmt.Errorf("build %s: %w\n%s", version, err, b) + } + return out, nil +} + +// requireBinaries skips t under -short, when TestMain built nothing. +func requireBinaries(t *testing.T) { + t.Helper() + if oldBinary == "" { + t.Skip("e2e suite skipped in -short mode") + } +} diff --git a/internal/e2e/fixture_test.go b/internal/e2e/fixture_test.go new file mode 100644 index 0000000..9312187 --- /dev/null +++ b/internal/e2e/fixture_test.go @@ -0,0 +1,281 @@ +package e2e_test + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" + "sync" + "testing" + "time" +) + +const ( + owner = "acme" + repo = "mytool" + // runTimeout bounds one subprocess invocation. + runTimeout = 60 * time.Second +) + +// ghAsset and ghRelease mirror the JSON fields GitHubSource reads. +type ghAsset struct { + Name string `json:"name"` + BrowserDownloadURL string `json:"browser_download_url"` + Size int64 `json:"size"` +} + +type ghRelease struct { + TagName string `json:"tag_name"` + Prerelease bool `json:"prerelease"` + Draft bool `json:"draft"` + Assets []ghAsset `json:"assets"` +} + +// assetName renders the goreleaser default asset name for the running +// platform. ArchiveInstaller derives the binary name from the resolved +// target's base name, so every path a scenario installs to must end in +// "mytool" (after following symlinks) for this name to match. +func assetName(version string) string { + return fmt.Sprintf("%s_%s_%s_%s.tar.gz", repo, strings.TrimPrefix(version, "v"), runtime.GOOS, runtime.GOARCH) +} + +// releaseServer serves one GitHub-shaped release for owner acme, repo mytool. +type releaseServer struct { + srv *httptest.Server + mu sync.Mutex + requests []string +} + +// newReleaseServer advertises latest as the newest release. The tarball +// always holds newBinary. When tamper is true the checksum file lists a +// wrong digest for it. Closed via t.Cleanup. +func newReleaseServer(t *testing.T, latest string, tamper bool) *releaseServer { + t.Helper() + s := &releaseServer{} + asset := assetName(latest) + archive := tarGzOf(t, newBinary) + sum := sha256.Sum256(archive) + if tamper { + sum[0] ^= 0xff + } + checksums := hex.EncodeToString(sum[:]) + " " + asset + "\n" + release := func() ghRelease { + return ghRelease{TagName: latest, Assets: []ghAsset{ + {Name: asset, BrowserDownloadURL: s.srv.URL + "/dl/" + asset, Size: int64(len(archive))}, + {Name: "checksums.txt", BrowserDownloadURL: s.srv.URL + "/dl/checksums.txt", Size: int64(len(checksums))}, + }} + } + mux := http.NewServeMux() + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + s.record(r.URL.Path) + switch r.URL.Path { + case "/repos/" + owner + "/" + repo + "/releases/latest": + _ = json.NewEncoder(w).Encode(release()) + case "/repos/" + owner + "/" + repo + "/releases": + _ = json.NewEncoder(w).Encode([]ghRelease{release()}) + case "/dl/" + asset: + w.Header().Set("Content-Length", strconv.Itoa(len(archive))) + _, _ = w.Write(archive) + case "/dl/checksums.txt": + _, _ = io.WriteString(w, checksums) + default: + w.WriteHeader(http.StatusNotFound) + } + }) + s.srv = httptest.NewServer(mux) + t.Cleanup(s.srv.Close) + return s +} + +func (s *releaseServer) record(path string) { + s.mu.Lock() + defer s.mu.Unlock() + s.requests = append(s.requests, path) +} + +// URL is the API base for MYTOOL_GITHUB_API. +func (s *releaseServer) URL() string { return s.srv.URL } + +// Requests returns the paths requested so far, in order. +func (s *releaseServer) Requests() []string { + s.mu.Lock() + defer s.mu.Unlock() + return append([]string(nil), s.requests...) +} + +// dlRequests filters Requests down to /dl/ paths, in order. +func (s *releaseServer) dlRequests() []string { + var out []string + for _, p := range s.Requests() { + if strings.HasPrefix(p, "/dl/") { + out = append(out, p) + } + } + return out +} + +// tarGzOf packs the file at path as a single entry named mytool, mode 0755. +func tarGzOf(t *testing.T, path string) []byte { + t.Helper() + body, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var buf bytes.Buffer + gz := gzip.NewWriter(&buf) + tw := tar.NewWriter(gz) + hdr := &tar.Header{Name: repo, Mode: 0o755, Size: int64(len(body)), Typeflag: tar.TypeReg} + if err := tw.WriteHeader(hdr); err != nil { + t.Fatal(err) + } + if _, err := tw.Write(body); err != nil { + t.Fatal(err) + } + if err := tw.Close(); err != nil { + t.Fatal(err) + } + if err := gz.Close(); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +// installOld copies oldBinary to path at mode 0755, creating parent dirs. +func installOld(t *testing.T, path string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + body, err := os.ReadFile(oldBinary) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, body, 0o755); err != nil { //nolint:gosec // executable fixture + t.Fatal(err) + } +} + +// runResult is one subprocess invocation. +type runResult struct { + Stdout string + Stderr string + Code int +} + +// run executes bin with args and MYTOOL_GITHUB_API set to api, under a +// 60s timeout. A non-zero exit is returned in Code, not treated as fatal. +func run(t *testing.T, bin, api string, args ...string) runResult { + t.Helper() + ctx, cancel := context.WithTimeout(t.Context(), runTimeout) + defer cancel() + cmd := exec.CommandContext(ctx, bin, args...) + cmd.WaitDelay = 10 * time.Second + cmd.Env = append(os.Environ(), envAPI+"="+api) + var stdout, stderr bytes.Buffer + cmd.Stdout, cmd.Stderr = &stdout, &stderr + err := cmd.Run() + res := runResult{Stdout: stdout.String(), Stderr: stderr.String()} + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + t.Fatalf("run %s %v: timed out after %s\nstdout:\n%s\nstderr:\n%s", + bin, args, runTimeout, stdout.String(), stderr.String()) + } + var exitErr *exec.ExitError + switch { + case err == nil: + case errors.As(err, &exitErr): + res.Code = exitErr.ExitCode() + default: + t.Fatalf("run %s %v: %v", bin, args, err) + } + return res +} + +// versionOf runs bin --version and returns the trimmed output. +func versionOf(t *testing.T, bin string) string { + t.Helper() + res := run(t, bin, "", "--version") + if res.Code != 0 { + t.Fatalf("%s --version exited %d: %s", bin, res.Code, res.Stderr) + } + return strings.TrimSpace(res.Stdout) +} + +// getBody fetches url from the fixture server and returns the body. +func getBody(t *testing.T, url string) []byte { + t.Helper() + req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, url, nil) + if err != nil { + t.Fatal(err) + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer func() { _ = resp.Body.Close() }() + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatal(err) + } + if resp.StatusCode != http.StatusOK { + t.Fatalf("GET %s: status %d", url, resp.StatusCode) + } + return body +} + +func TestFixture_BinariesReportTheirVersion(t *testing.T) { + requireBinaries(t) + if got := versionOf(t, oldBinary); got != oldVersion { + t.Fatalf("old binary reports %q", got) + } + if got := versionOf(t, newBinary); got != newVersion { + t.Fatalf("new binary reports %q", got) + } +} + +func TestFixture_ServesReleaseAndChecksums(t *testing.T) { + requireBinaries(t) + s := newReleaseServer(t, newVersion, false) + var rel ghRelease + if err := json.Unmarshal(getBody(t, s.URL()+"/repos/acme/mytool/releases/latest"), &rel); err != nil { + t.Fatal(err) + } + asset := assetName(newVersion) + if rel.TagName != newVersion || len(rel.Assets) != 2 || rel.Assets[0].Name != asset { + t.Fatalf("release: %+v", rel) + } + archive := getBody(t, rel.Assets[0].BrowserDownloadURL) + sums := string(getBody(t, rel.Assets[1].BrowserDownloadURL)) + sum := sha256.Sum256(archive) + if want := hex.EncodeToString(sum[:]) + " " + asset + "\n"; sums != want { + t.Fatalf("checksums.txt:\n%s\nwant:\n%s", sums, want) + } + if got := s.dlRequests(); len(got) != 2 || got[0] != "/dl/"+asset || got[1] != "/dl/checksums.txt" { + t.Fatalf("dl requests: %v", got) + } +} + +func TestFixture_TamperFlipsChecksum(t *testing.T) { + requireBinaries(t) + s := newReleaseServer(t, newVersion, true) + asset := assetName(newVersion) + archive := getBody(t, s.URL()+"/dl/"+asset) + sums := string(getBody(t, s.URL()+"/dl/checksums.txt")) + sum := sha256.Sum256(archive) + if strings.HasPrefix(sums, hex.EncodeToString(sum[:])) { + t.Fatal("tampered checksum must not match the archive") + } +} diff --git a/internal/e2e/scenarios_test.go b/internal/e2e/scenarios_test.go new file mode 100644 index 0000000..fd4abc7 --- /dev/null +++ b/internal/e2e/scenarios_test.go @@ -0,0 +1,254 @@ +package e2e_test + +import ( + "errors" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" +) + +// --- Contract assertions --- +// These pin the harness signatures the scenarios depend on. +var ( + _ func(*testing.T, string, bool) *releaseServer = newReleaseServer + _ func(*testing.T, string) = installOld + _ func(*testing.T, string, string, ...string) runResult = run + _ func(*testing.T, string) string = versionOf + _ func(*testing.T) = requireBinaries +) + +const ( + preLine = "pre-install: binary reports " + postLine = "post-install: binary reports " + dlChecksumsTxt = "/dl/checksums.txt" +) + +// assertNoLeftovers fails when a .new or .old file sits beside path. +func assertNoLeftovers(t *testing.T, path string) { + t.Helper() + for _, leftover := range []string{path + ".new", path + ".old"} { + if _, err := os.Stat(leftover); !errors.Is(err, os.ErrNotExist) { + t.Errorf("%s must not exist after an update (stat err %v)", leftover, err) + } + } +} + +// assertMode0755 fails when path is not executable by everyone. +func assertMode0755(t *testing.T, path string) { + t.Helper() + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0o755 { + t.Fatalf("mode %v, want 0755", info.Mode().Perm()) + } +} + +// assertNoHookLines fails when either hook printed. +func assertNoHookLines(t *testing.T, stdout string) { + t.Helper() + if strings.Contains(stdout, preLine) || strings.Contains(stdout, postLine) { + t.Fatalf("hooks must not run:\n%s", stdout) + } +} + +// failRun reports a subprocess result in full. +func failRun(t *testing.T, what string, res runResult) { + t.Helper() + t.Fatalf("%s: exit %d\nstdout:\n%s\nstderr:\n%s", what, res.Code, res.Stdout, res.Stderr) +} + +// resolved returns path with symlinks resolved, matching what the +// installer prints. +func resolved(t *testing.T, path string) string { + t.Helper() + p, err := filepath.EvalSymlinks(path) + if err != nil { + t.Fatal(err) + } + return p +} + +// updateOld installs the old build at path, runs self update -y against +// a server advertising latest, and returns the result and the server. +func updateOld(t *testing.T, path, latest string, tamper bool) (runResult, *releaseServer) { + t.Helper() + s := newReleaseServer(t, latest, tamper) + installOld(t, path) + return run(t, path, s.URL(), "self", "update", "-y"), s +} + +func TestUpdate_ReplacesRunningBinary(t *testing.T) { + requireBinaries(t) + bin := filepath.Join(t.TempDir(), "bin", "mytool") + res, s := updateOld(t, bin, newVersion, false) + if res.Code != 0 { + failRun(t, "self update", res) + } + asset := assetName(newVersion) + for _, want := range []string{ + "Downloading " + asset, + "Verified " + asset, + "Installed mytool " + newVersion + " to " + resolved(t, bin), + } { + if !strings.Contains(res.Stdout, want) { + t.Errorf("stdout missing %q:\n%s", want, res.Stdout) + } + } + if got := versionOf(t, bin); got != newVersion { + t.Fatalf("binary on disk reports %q, want %q", got, newVersion) + } + assertMode0755(t, bin) + assertNoLeftovers(t, bin) + if got := s.dlRequests(); len(got) != 2 || got[0] != "/dl/"+asset || got[1] != dlChecksumsTxt { + t.Fatalf("download requests: %v", got) + } +} + +func TestUpdate_HooksObserveTheSwap(t *testing.T) { + requireBinaries(t) + bin := filepath.Join(t.TempDir(), "bin", "mytool") + res, _ := updateOld(t, bin, newVersion, false) + if res.Code != 0 { + failRun(t, "self update", res) + } + pre := strings.Index(res.Stdout, preLine+oldVersion) + inst := strings.Index(res.Stdout, "Installed mytool") + post := strings.Index(res.Stdout, postLine+newVersion) + if pre < 0 || inst < 0 || post < 0 || pre > inst || inst > post { + t.Fatalf("hook lines out of order or missing (pre=%d installed=%d post=%d):\n%s", pre, inst, post, res.Stdout) + } +} + +func TestCheckOnly_InstallsNothing(t *testing.T) { + requireBinaries(t) + s := newReleaseServer(t, newVersion, false) + bin := filepath.Join(t.TempDir(), "bin", "mytool") + installOld(t, bin) + res := run(t, bin, s.URL(), "self", "update", "--check") + if res.Code != 0 { + failRun(t, "self update --check", res) + } + if !strings.Contains(res.Stdout, "Update available: "+oldVersion+" -> "+newVersion) { + t.Fatalf("stdout:\n%s", res.Stdout) + } + if got := versionOf(t, bin); got != oldVersion { + t.Fatalf("binary changed to %q", got) + } + assertNoHookLines(t, res.Stdout) + if got := s.dlRequests(); len(got) != 0 { + t.Fatalf("check must not download: %v", got) + } +} + +func TestUpToDate_InstallsNothing(t *testing.T) { + requireBinaries(t) + bin := filepath.Join(t.TempDir(), "bin", "mytool") + res, s := updateOld(t, bin, oldVersion, false) + if res.Code != 0 { + failRun(t, "self update", res) + } + if !strings.Contains(res.Stdout, "is up to date") { + t.Fatalf("stdout:\n%s", res.Stdout) + } + assertNoHookLines(t, res.Stdout) + if got := s.dlRequests(); len(got) != 0 { + t.Fatalf("up to date must not download: %v", got) + } + if got := versionOf(t, bin); got != oldVersion { + t.Fatalf("binary changed to %q", got) + } +} + +func TestChecksumMismatch_LeavesBinary(t *testing.T) { + requireBinaries(t) + bin := filepath.Join(t.TempDir(), "bin", "mytool") + res, _ := updateOld(t, bin, newVersion, true) + if res.Code == 0 { + failRun(t, "self update must fail on a bad checksum", res) + } + if !strings.Contains(res.Stderr, "checksum mismatch") { + t.Fatalf("stderr:\n%s", res.Stderr) + } + if got := versionOf(t, bin); got != oldVersion { + t.Fatalf("binary changed to %q", got) + } + assertNoHookLines(t, res.Stdout) + // Defensive: the checksum failure aborts in Prepare before any .new or .old exists. + assertNoLeftovers(t, bin) +} + +func TestSymlinkedPath_ReplacesTarget(t *testing.T) { + requireBinaries(t) + root := t.TempDir() + realPath := filepath.Join(root, "opt", "mytool", "bin", "mytool") + link := filepath.Join(root, "bin", "mytool") + s := newReleaseServer(t, newVersion, false) + installOld(t, realPath) + if err := os.MkdirAll(filepath.Dir(link), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(realPath, link); err != nil { + t.Fatal(err) + } + res := run(t, link, s.URL(), "self", "update", "-y") + if res.Code != 0 { + failRun(t, "self update via symlink", res) + } + if got := versionOf(t, realPath); got != newVersion { + t.Fatalf("real file reports %q", got) + } + info, err := os.Lstat(link) + if err != nil { + t.Fatal(err) + } + if info.Mode()&os.ModeSymlink == 0 { + t.Fatal("the symlink must survive; only its target is replaced") + } + if got, err := os.Readlink(link); err != nil || got != realPath { + t.Fatalf("symlink now points at %q (err %v), want %q", got, err, realPath) + } + if !strings.Contains(res.Stdout, preLine+oldVersion) || !strings.Contains(res.Stdout, postLine+newVersion) { + t.Fatalf("hook lines missing:\n%s", res.Stdout) + } +} + +func TestManagedPath_Refused(t *testing.T) { + requireBinaries(t) + bin := filepath.Join(t.TempDir(), "Cellar", "mytool", "1.0.0", "bin", "mytool") + res, s := updateOld(t, bin, newVersion, false) + if res.Code == 0 { + failRun(t, "self update must refuse a Cellar path", res) + } + for _, want := range []string{"Homebrew", "brew upgrade mytool"} { + if !strings.Contains(res.Stderr, want) { + t.Errorf("stderr missing %q:\n%s", want, res.Stderr) + } + } + if got := s.dlRequests(); len(got) != 0 { + t.Fatalf("managed refusal must happen before any download: %v", got) + } + if got := versionOf(t, bin); got != oldVersion { + t.Fatalf("binary changed to %q", got) + } +} + +func TestUpdate_CodesignValidOnDarwin(t *testing.T) { + requireBinaries(t) + if runtime.GOOS != "darwin" { + t.Skip("codesign is macOS only") + } + bin := filepath.Join(t.TempDir(), "bin", "mytool") + res, _ := updateOld(t, bin, newVersion, false) + if res.Code != 0 { + failRun(t, "self update", res) + } + out, err := exec.CommandContext(t.Context(), "codesign", "--verify", "--verbose", bin).CombinedOutput() + if err != nil { + t.Fatalf("codesign --verify failed: %v\n%s", err, out) + } +}