gitlab.com/beacon-software/gadget@v0.0.0-20181217202115-54565ea1ed5e/fileutil/file_test.go (about) 1 package fileutil 2 3 import ( 4 "fmt" 5 "os" 6 "path" 7 "strings" 8 "testing" 9 10 "gitlab.com/beacon-software/gadget/generator" 11 ) 12 13 func getTestPath() string { 14 uuid := generator.String(10) 15 rootPath := fmt.Sprintf("/tmp/%s/%s", "fileutil", strings.TrimSpace(uuid)) 16 return rootPath 17 } 18 19 func TestEnsureDirectory(t *testing.T) { 20 // test happy path 21 dirname := getTestPath() 22 _, err := EnsureDir(dirname, 0777) 23 if err != nil { 24 t.Error(err) 25 } 26 err = os.Remove(dirname) 27 if err != nil { 28 t.Error(err) 29 } 30 31 // test creating a path when a subdirectory is a file 32 f, err := os.Create(dirname) 33 if err != nil { 34 t.Error(err) 35 } 36 _, err = f.WriteString("testensure") 37 if err != nil { 38 t.Error(err) 39 } 40 err = f.Close() 41 if err != nil { 42 t.Error(err) 43 } 44 45 _, err = EnsureDir(dirname, 0777) 46 if err == nil { 47 t.Error("Existing file with dirname should fail.") 48 } 49 50 _, err = EnsureDir(dirname+"/foo", 0777) 51 if err == nil { 52 t.Error("File in subtree should fail.") 53 } 54 os.Remove(dirname) 55 } 56 57 func TestFileExists(t *testing.T) { 58 type args struct { 59 path string 60 } 61 testPath := getTestPath() 62 testfile := path.Join(testPath, "test.txt") 63 os.Create(testfile) 64 tests := []struct { 65 name string 66 args args 67 want bool 68 }{ 69 { 70 name: "dir false", 71 args: args{path: "/tmp/"}, 72 want: false, 73 }, 74 { 75 name: "empty false", 76 args: args{path: ""}, 77 want: false, 78 }, 79 { 80 name: "file true", 81 args: args{path: testfile}, 82 want: false, 83 }, 84 } 85 for _, tt := range tests { 86 t.Run(tt.name, func(t *testing.T) { 87 if got := FileExists(tt.args.path); got != tt.want { 88 t.Errorf("FileExists(\"%s\") = %v, want %v", tt.args.path, got, tt.want) 89 } 90 }) 91 } 92 }