github.com/mvdan/u-root-coreutils@v0.0.0-20230122170626-c2eef2898555/pkg/upath/symlink_test.go (about) 1 // Copyright 2015-2017 the u-root Authors. All rights reserved 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package upath 6 7 import ( 8 "log" 9 "os" 10 "path/filepath" 11 "testing" 12 ) 13 14 func TestSymlink(t *testing.T) { 15 td := t.TempDir() 16 for _, n := range []string{"bin", "buildbin"} { 17 p := filepath.Join(td, n) 18 if err := os.Mkdir(p, 0o777); err != nil { 19 log.Fatal(err) 20 } 21 } 22 tab := []struct { 23 s, t, v string 24 }{ 25 {filepath.Join(td, "bin/ash"), "sh", filepath.Join(td, "buildbin/elvish")}, 26 {filepath.Join(td, "bin/sh"), "../buildbin/elvish", filepath.Join(td, "buildbin/elvish")}, 27 {filepath.Join(td, "buildbin/elvish"), "installcommand", filepath.Join(td, "buildbin/elvish")}, 28 } 29 for _, s := range tab { 30 if err := os.Symlink(s.t, s.s); err != nil { 31 t.Fatalf("symlink %s->%s: got %v, want nil", s.s, s.t, err) 32 } 33 } 34 for _, s := range tab { 35 t.Logf("Check %v", s) 36 v, err := os.Readlink(s.s) 37 t.Logf("Symlink val %v", v) 38 if err != nil || v != s.t { 39 t.Errorf("readlink %v: got (%v, %v), want (%v, nil)", s.s, v, err, s.t) 40 } 41 v = ResolveUntilLastSymlink(s.s) 42 t.Logf("ResolveUntilLastSymlink val %v", v) 43 if v != s.v { 44 t.Errorf("ResolveUntilLastSymlink %v: got %v want %v", s.s, v, s.v) 45 } 46 } 47 // test to make sure a plain file gives a reasonable result. 48 ic := filepath.Join(td, "x") 49 if err := os.WriteFile(ic, nil, 0o666); err != nil { 50 t.Fatalf("WriteFile %v: got %v, want nil", ic, err) 51 } 52 v := ResolveUntilLastSymlink(ic) 53 t.Logf("ResolveUntilLastSymlink %v gets %v", ic, v) 54 if v != ic { 55 t.Errorf("ResolveUntilLastSymlink %v: got %v want %v", ic, v, ic) 56 } 57 }