github.com/aca02djr/gb@v0.4.1/cmd/path_test.go (about) 1 package cmd 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "os" 7 "path/filepath" 8 "reflect" 9 "testing" 10 ) 11 12 var join = filepath.Join 13 14 // makeTestData constructs 15 func makeTestdata(t *testing.T) string { 16 tempdir, err := filepath.EvalSymlinks(os.TempDir()) 17 if err != nil { 18 t.Fatal(err) 19 } 20 21 root, err := ioutil.TempDir(tempdir, "path-test") 22 if err != nil { 23 t.Fatal(err) 24 } 25 mkdir := func(args ...string) string { 26 path := join(args...) 27 if err := os.MkdirAll(path, 0777); err != nil { 28 t.Fatal(err) 29 } 30 return path 31 } 32 mkfile := func(path string, content string) { 33 if err := ioutil.WriteFile(path, []byte(content), 0755); err != nil { 34 t.Fatal(err) 35 } 36 } 37 38 srcdir := mkdir(root, "src") 39 mkfile(join(mkdir(srcdir, "a"), "a.go"), "package a") 40 41 return root 42 } 43 44 func TestFindProjectroot(t *testing.T) { 45 root := makeTestdata(t) 46 defer os.RemoveAll(root) 47 tests := []struct { 48 path string 49 want string 50 err error 51 }{ 52 {path: root, want: root}, 53 {path: join(root, "src"), want: root}, 54 {path: join(join(root, "src"), "a"), want: root}, 55 {path: join(root, ".."), err: fmt.Errorf(`could not find project root in "%s" or its parents`, join(root, ".."))}, 56 } 57 58 for _, tt := range tests { 59 got, err := FindProjectroot(tt.path) 60 if got != tt.want || !reflect.DeepEqual(err, tt.err) { 61 t.Errorf("FindProjectroot(%v): want: %v, %v, got %v, %v", tt.path, tt.want, tt.err, got, err) 62 } 63 } 64 }