github.com/NeowayLabs/nash@v0.2.2-0.20200127205349-a227041ffd50/internal/testing/fixture/io.go (about) 1 package fixture 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "math/rand" 7 "os" 8 "path/filepath" 9 "testing" 10 ) 11 12 // Tmpdir creates a temporary dir and returns a function that can be used 13 // to remove it after usage. Any error on any operation returns on a Fatal 14 // call on the given testing.T. 15 func Tmpdir(t *testing.T) (string, func()) { 16 t.Helper() 17 18 dir, err := ioutil.TempDir("", "nash-tests") 19 if err != nil { 20 t.Fatal(err) 21 } 22 23 dir, err = filepath.EvalSymlinks(dir) 24 if err != nil { 25 t.Fatal(err) 26 } 27 28 return dir, func() { 29 err := os.RemoveAll(dir) 30 if err != nil { 31 t.Fatal(err) 32 } 33 } 34 } 35 36 // MkdirAll will do the same thing as os.Mkdirall but calling Fatal on 37 // the given testing.T if something goes wrong. 38 func MkdirAll(t *testing.T, nashlib string) { 39 t.Helper() 40 41 err := os.MkdirAll(nashlib, os.ModePerm) 42 if err != nil { 43 t.Fatal(err) 44 } 45 } 46 47 // CreateFiles will create all files and its dirs if 48 // necessary calling Fatal on the given testing if anything goes wrong. 49 // 50 // The files contents will be randomly generated strings (not a lot random, 51 // just for test purposes) and will be returned on the map that will map 52 // the filepath to its contents 53 func CreateFiles(t *testing.T, filepaths []string) map[string]string { 54 t.Helper() 55 56 createdFiles := map[string]string{} 57 58 for _, f := range filepaths { 59 contents := CreateFile(t, f) 60 createdFiles[f] = contents 61 } 62 63 return createdFiles 64 } 65 66 // CreateFile will create the file and its dirs if 67 // necessary calling Fatal on the given testing if anything goes wrong. 68 // 69 // The file content will be randomly generated strings (not a lot random, 70 // just for test purposes) and will be returned on the map that will map 71 // the filepath to its contents. 72 // 73 // Return the contents generated for the file (and that has been written on it). 74 func CreateFile(t *testing.T, f string) string { 75 t.Helper() 76 77 dir := filepath.Dir(f) 78 MkdirAll(t, dir) 79 80 contents := fmt.Sprintf("randomContents=%d", rand.Int()) 81 82 err := ioutil.WriteFile(f, []byte(contents), 0644) 83 if err != nil { 84 t.Fatalf("error[%s] writing file[%s]", err, f) 85 } 86 87 return contents 88 } 89 90 func WorkingDir(t *testing.T) string { 91 t.Helper() 92 93 wd, err := os.Getwd() 94 if err != nil { 95 t.Fatal(err) 96 } 97 return wd 98 } 99 100 func ChangeDir(t *testing.T, path string) { 101 t.Helper() 102 103 err := os.Chdir(path) 104 if err != nil { 105 t.Fatal(err) 106 } 107 } 108 109 func Chmod(t *testing.T, path string, mode os.FileMode) { 110 t.Helper() 111 112 err := os.Chmod(path, mode) 113 if err != nil { 114 t.Fatal(err) 115 } 116 }