| 1 | package instanceidentity |
| 2 | |
| 3 | import ( |
| 4 | "crypto/sha256" |
| 5 | "encoding/hex" |
| 6 | "os" |
| 7 | "path/filepath" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | |
| 11 | "github.com/google/uuid" |
| 12 | ) |
| 13 | |
| 14 | func TestIdentityPreservesExistingFormatAndAliases(t *testing.T) { |
| 15 | root := t.TempDir() |
| 16 | home := filepath.Join(root, "new", "home") |
| 17 | sum := sha256.Sum256([]byte(CanonicalHome(home))) |
| 18 | want := Prefix + "." + hex.EncodeToString(sum[:8]) |
| 19 | if got := ForHome(home); got != want { |
| 20 | t.Fatalf("identity %s != %s", got, want) |
| 21 | } |
| 22 | alias := filepath.Join(root, "alias") |
| 23 | if err := os.Symlink(root, alias); err == nil { |
| 24 | if got := ForHome(filepath.Join(alias, "new", "home")); got != want { |
| 25 | t.Fatalf("alias changed identity: %s", got) |
| 26 | } |
| 27 | } |
| 28 | other := ForHome(filepath.Join(root, "other")) |
| 29 | if other == want || TrayGUID(other) == TrayGUID(want) { |
| 30 | t.Fatal("independent homes collide") |
| 31 | } |
| 32 | id, err := uuid.Parse(TrayGUID(want)) |
| 33 | if err != nil || id.Version() != 5 { |
| 34 | t.Fatalf("tray ID %v: %v", id, err) |
| 35 | } |
| 36 | if TrayGUID(want) != TrayGUID(ForHome(filepath.Join(home, "."))) { |
| 37 | t.Fatal("equivalent home changed GUID") |
| 38 | } |
| 39 | } |
| 40 | func TestUpdateEnvironmentFreezesHome(t *testing.T) { |
| 41 | env := UpdateEnvironment([]string{"PATH=keep", "reasonix_home=old", "REASONIX_UPDATE_INSTANCE_ID=stale"}, "relative-home") |
| 42 | values := map[string]string{} |
| 43 | for _, e := range env { |
| 44 | k, v, _ := strings.Cut(e, "=") |
| 45 | values[k] = v |
| 46 | } |
| 47 | if len(env) != 3 || values["PATH"] != "keep" || !filepath.IsAbs(values["REASONIX_HOME"]) { |
| 48 | t.Fatalf("bad environment: %v", env) |
| 49 | } |
| 50 | if id := values[UpdateEnvironmentKey]; !Valid(id) || id != ForHome(values["REASONIX_HOME"]) { |
| 51 | t.Fatalf("bad identity %q", id) |
| 52 | } |
| 53 | for _, id := range []string{"", Prefix, Prefix + ".../../x", Prefix + ".0123456789ABCDEf"} { |
| 54 | if Valid(id) { |
| 55 | t.Fatalf("accepted %q", id) |
| 56 | } |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | func TestUpdateEnvironmentPreservesAccessSpelling(t *testing.T) { |
| 61 | home := filepath.Join(t.TempDir(), "MixedCaseHome") |
| 62 | env := UpdateEnvironment(nil, home) |
| 63 | if len(env) != 2 || env[0] != "REASONIX_HOME="+home { |
| 64 | t.Fatalf("environment = %v", env) |
| 65 | } |
| 66 | if got := strings.TrimPrefix(env[1], UpdateEnvironmentKey+"="); got != ForHome(home) { |
| 67 | t.Fatalf("instance id = %q, want %q", got, ForHome(home)) |
| 68 | } |
| 69 | } |
| 70 |