github.com/blend/go-sdk@v1.20220411.3/fileutil/exists_test.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package fileutil_test 9 10 import ( 11 "fmt" 12 "os" 13 "strings" 14 "testing" 15 16 "github.com/blend/go-sdk/assert" 17 "github.com/blend/go-sdk/fileutil" 18 ) 19 20 func TestFileExists(t *testing.T) { 21 t.Parallel() 22 it := assert.New(t) 23 24 // Exists: Yes, File: Yes 25 f := tempFile(it) 26 exists, err := fileutil.FileExists(f.Name()) 27 it.Nil(err) 28 it.True(exists) 29 30 // Exists: No 31 name := f.Name() + "-missing" 32 exists, err = fileutil.FileExists(name) 33 it.Nil(err) 34 it.False(exists) 35 36 // Exists: Yes, File: No 37 dir := tempDir(it) 38 exists, err = fileutil.FileExists(dir) 39 it.False(exists) 40 it.NotNil(err) 41 expected := fmt.Sprintf("Path exists but is a directory; Path: %q", dir) 42 it.Equal(expected, fmt.Sprintf("%v", err)) 43 44 // Stat fails 45 path := tooLongPath() 46 exists, err = fileutil.FileExists(path) 47 it.False(exists) 48 it.NotNil(err) 49 expected = fmt.Sprintf("stat %s: file name too long\nfile name too long", path) 50 it.Equal(expected, fmt.Sprintf("%v", err)) 51 } 52 53 func TestDirExists(t *testing.T) { 54 t.Parallel() 55 it := assert.New(t) 56 57 // Exists: Yes, File: Yes 58 f := tempFile(it) 59 exists, err := fileutil.DirExists(f.Name()) 60 it.False(exists) 61 it.NotNil(err) 62 expected := fmt.Sprintf("Path exists but is not a directory; Path: %q", f.Name()) 63 it.Equal(expected, fmt.Sprintf("%v", err)) 64 65 // Exists: No 66 name := f.Name() + "-missing" 67 exists, err = fileutil.DirExists(name) 68 it.Nil(err) 69 it.False(exists) 70 71 // Exists: Yes, File: No 72 dir := tempDir(it) 73 exists, err = fileutil.DirExists(dir) 74 it.Nil(err) 75 it.True(exists) 76 77 // Stat fails 78 path := tooLongPath() 79 exists, err = fileutil.DirExists(path) 80 it.False(exists) 81 it.NotNil(err) 82 expected = fmt.Sprintf("stat %s: file name too long\nfile name too long", path) 83 it.Equal(expected, fmt.Sprintf("%v", err)) 84 } 85 86 func tempFile(it *assert.Assertions) *os.File { 87 f, err := os.CreateTemp("", "") 88 it.Nil(err) 89 90 it.T.Cleanup(func() { 91 err := f.Close() 92 it.Nil(err) 93 err = os.Remove(f.Name()) 94 it.Nil(err) 95 }) 96 97 return f 98 } 99 100 func tempDir(it *assert.Assertions) string { 101 dir, err := os.MkdirTemp("", "") 102 it.Nil(err) 103 104 it.T.Cleanup(func() { 105 err = os.RemoveAll(dir) 106 it.Nil(err) 107 }) 108 109 return dir 110 } 111 112 func tooLongPath() string { 113 parts := make([]string, 1024) 114 parts[0] = "" 115 parts[1] = "path" 116 parts[2] = "to" 117 for i := 3; i < 1024; i++ { 118 parts[i] = "more-content" 119 } 120 return strings.Join(parts, string(os.PathSeparator)) 121 }