github.com/keikoproj/manny@v0.0.0-20210726112440-8571e4c99ced/utils/file_test.go (about) 1 package utils 2 3 import ( 4 "io/ioutil" 5 "os" 6 "reflect" 7 "strings" 8 "testing" 9 ) 10 11 func Test_ValidateAndWrite(t *testing.T) { 12 // test table 13 tt := []struct { 14 // Name of the test 15 Identifier string 16 // PreDir will create a directory before ValidateAndWrite() is called 17 PreDir string 18 // PreWrite will write to a file before ValidateAndWrite() is called 19 PreWrite string 20 // File location to write to, passed to ValidateAndWrite() 21 Location string 22 // File content to write, passed to ValidateAndWrite() 23 Content []byte 24 // Whether we want an error 25 WantErr bool 26 // What you want the return bool to be 27 Output bool 28 // The error that the message should be prefixed with 29 ErrPrefix string 30 }{ 31 { 32 "Valid", 33 "", 34 "", 35 "/tmp/manny_test", 36 []byte("test"), 37 false, 38 true, 39 "", 40 }, 41 { 42 "Location already exists", 43 "", 44 "/tmp/manny_test", 45 "/tmp/manny_test", 46 []byte("test"), 47 true, 48 false, 49 ErrDestinationExists, 50 }, 51 { 52 "Location is a directory", 53 "/tmp/manny_test", 54 "", 55 "/tmp/manny_test", 56 []byte("test"), 57 true, 58 false, 59 ErrDestinationIsDir, 60 }, 61 } 62 63 // testing loop 64 for _, tc := range tt { 65 var cleanup []string 66 67 t.Run(tc.Identifier, func(t *testing.T) { 68 // creates a file 69 if tc.PreWrite != "" { 70 cleanup = append(cleanup, tc.PreWrite) 71 err := ioutil.WriteFile(tc.PreWrite, tc.Content, 0644) 72 if err != nil { 73 t.Errorf("Error reading file: %s", err) 74 } 75 } 76 77 // creates a directory 78 if tc.PreDir != "" { 79 cleanup = append(cleanup, tc.PreDir) 80 err := os.Mkdir(tc.PreDir, 0644) 81 if err != nil { 82 t.Errorf("Error reading file: %s", err) 83 } 84 } 85 86 got, err := ValidateAndWrite(tc.Location, tc.Content) 87 haveErr := err != nil 88 89 // clean up any files that were generated 90 if got { 91 cleanup = append(cleanup, tc.Location) 92 } 93 94 // evaluate output 95 if tc.Output != got { 96 t.Errorf("Error with output: got: %t, want: %t", got, tc.Output) 97 } 98 99 // err prefix is wrong 100 if haveErr && tc.WantErr && !strings.HasPrefix(err.Error(), tc.ErrPrefix) { 101 t.Errorf("Error not prefixed as expected. got: %s, want: %s", err.Error(), tc.ErrPrefix) 102 } 103 104 // didn't expect an error but got one 105 if haveErr && !tc.WantErr { 106 t.Errorf("Got: %s, want: nil", err) 107 } 108 109 // expected an error but didn't get one 110 if haveErr && err == nil { 111 t.Errorf("Got: nil,") 112 } 113 114 b, err := ioutil.ReadFile(tc.Location) 115 if err != nil && tc.Output { 116 t.Errorf("Error reading file: %s", err) 117 } 118 119 if !reflect.DeepEqual(tc.Content, b) && tc.Output { 120 t.Errorf("File content is not the same. got: %s, want: %s", b, tc.Content) 121 } 122 }) 123 124 for _, location := range cleanup { 125 err := os.Remove(location) 126 if err != nil { 127 t.Errorf("Error removing file: %s", err) 128 } 129 } 130 } 131 }