ajhahn.de
← eeco
Go 42 lines
//go:build !windows

package selfupdate

import (
	"os"
	"path/filepath"
	"testing"
)

func TestSwap_StatErr(t *testing.T) {
	dir := t.TempDir()
	newPath := filepath.Join(dir, "new")
	if err := os.WriteFile(newPath, []byte("NEW"), 0o755); err != nil {
		t.Fatal(err)
	}
	// swap stats the target first; a nonexistent target fails up-front.
	if err := swap(newPath, filepath.Join(dir, "does-not-exist", "target")); err == nil {
		t.Fatal("expected error when target stat fails")
	}
}

func TestSwap_CopyFileFails(t *testing.T) {
	dir := t.TempDir()
	target := filepath.Join(dir, "target")
	if err := os.WriteFile(target, []byte("ORIG"), 0o755); err != nil {
		t.Fatal(err)
	}
	// A nonexistent newPath makes copyFile's open fail after the temp file
	// is created → swap returns the error and the target is left untouched.
	if err := swap(filepath.Join(dir, "missing-new"), target); err == nil {
		t.Fatal("expected error when copyFile source is missing")
	}
	got, err := os.ReadFile(target)
	if err != nil {
		t.Fatalf("read target: %v", err)
	}
	if string(got) != "ORIG" {
		t.Errorf("target changed after a failed swap: %q, want ORIG", got)
	}
}