-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler_test.go
218 lines (188 loc) · 6.03 KB
/
handler_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package gulter_test
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/adelowo/gulter"
"github.com/adelowo/gulter/mocks"
"github.com/sebdah/goldie/v2"
"github.com/stretchr/testify/require"
"go.uber.org/mock/gomock"
)
func verifyMatch(t *testing.T, v interface{}) {
g := goldie.New(t, goldie.WithFixtureDir("./testdata/golden"))
b := new(bytes.Buffer)
var err error
if d, ok := v.(*httptest.ResponseRecorder); ok {
_, err = io.Copy(b, d.Body)
} else {
err = json.NewEncoder(b).Encode(v)
}
require.NoError(t, err)
g.Assert(t, t.Name(), b.Bytes())
}
func TestGulter(t *testing.T) {
tt := []struct {
name string
maxFileSize int64
pathToFile string
fn func(store *mocks.MockStorage, size int64)
expectedStatusCode int
validMimeTypes []string
// ignoreFormField instructs the test to not add the
// multipar form data part to the request
ignoreFormField bool
useIgnoreSkipOpt bool
}{
{
name: "uploading succeeds",
maxFileSize: 1024,
fn: func(store *mocks.MockStorage, size int64) {
store.EXPECT().
Upload(gomock.Any(), gomock.Any(), gomock.Any()).
Return(&gulter.UploadedFileMetadata{
Size: size,
}, nil).
Times(1)
},
expectedStatusCode: http.StatusAccepted,
pathToFile: "gulter.md",
validMimeTypes: []string{"text/markdown", "text/plain"},
},
{
name: "upload fails because form field does not exist",
maxFileSize: 1024,
fn: func(store *mocks.MockStorage, size int64) {
store.EXPECT().
Upload(gomock.Any(), gomock.Any(), gomock.Any()).
Return(&gulter.UploadedFileMetadata{
Size: size,
}, errors.New("could not upload file")).
Times(0) // make sure this is never called
},
expectedStatusCode: http.StatusInternalServerError,
pathToFile: "gulter.md",
validMimeTypes: []string{"image/png", "application/pdf"},
ignoreFormField: true,
},
{
// this test case will use the WithIgnore option
name: "upload middleware succeeds even if the form field does not exist",
maxFileSize: 1024,
fn: func(store *mocks.MockStorage, size int64) {
store.EXPECT().
Upload(gomock.Any(), gomock.Any(), gomock.Any()).
Return(&gulter.UploadedFileMetadata{
Size: size,
}, errors.New("could not upload file")).
Times(0) // make sure this is never called
},
expectedStatusCode: http.StatusAccepted,
pathToFile: "gulter.md",
validMimeTypes: []string{"image/png", "application/pdf"},
ignoreFormField: true,
useIgnoreSkipOpt: true,
},
{
name: "upload fails because of mimetype validation constraints",
maxFileSize: 1024,
fn: func(store *mocks.MockStorage, size int64) {
store.EXPECT().
Upload(gomock.Any(), gomock.Any(), gomock.Any()).
Return(&gulter.UploadedFileMetadata{
Size: size,
}, errors.New("could not upload file")).
Times(0) // make sure this is never called
},
expectedStatusCode: http.StatusInternalServerError,
pathToFile: "gulter.md",
validMimeTypes: []string{"image/png", "application/pdf"},
},
{
name: "upload fails because of storage layer",
maxFileSize: 1024,
fn: func(store *mocks.MockStorage, size int64) {
store.EXPECT().
Upload(gomock.Any(), gomock.Any(), gomock.Any()).
Return(&gulter.UploadedFileMetadata{
Size: size,
}, errors.New("could not upload file")).
Times(1)
},
expectedStatusCode: http.StatusInternalServerError,
pathToFile: "gulter.md",
validMimeTypes: []string{"text/markdown", "text/plain"},
},
{
name: "upload fails because file is too large",
maxFileSize: 1024,
fn: func(store *mocks.MockStorage, size int64) {
store.EXPECT().
Upload(gomock.Any(), gomock.Any(), gomock.Any()).
Return(&gulter.UploadedFileMetadata{
Size: size,
}, errors.New("could not upload file")).
Times(0) // never call this
},
expectedStatusCode: http.StatusInternalServerError,
pathToFile: "image.jpg",
validMimeTypes: []string{"image/jpeg"},
},
}
for _, v := range tt {
t.Run(v.name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
storage := mocks.NewMockStorage(ctrl)
opts := []gulter.Option{
gulter.WithMaxFileSize(v.maxFileSize),
gulter.WithStorage(storage),
gulter.WithValidationFunc(gulter.MimeTypeValidator(v.validMimeTypes...)),
}
if v.useIgnoreSkipOpt {
opts = append(opts, gulter.WithIgnoreNonExistentKey(true))
}
handler, err := gulter.New(opts...)
require.NoError(t, err)
buffer := bytes.NewBuffer(nil)
multipartWriter := multipart.NewWriter(buffer)
var formFieldWriter io.Writer = bytes.NewBuffer(nil)
if !v.ignoreFormField {
var err error
formFieldWriter, err = multipartWriter.CreateFormFile("form-field", v.pathToFile)
require.NoError(t, err)
}
fileToUpload, err := os.Open(filepath.Join("testdata", v.pathToFile))
require.NoError(t, err)
n, err := io.Copy(formFieldWriter, fileToUpload)
require.NoError(t, err)
v.fn(storage, int64(n))
require.NoError(t, multipartWriter.Close())
recorder := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodPatch, "/", buffer)
r.Header.Set("Content-Type", multipartWriter.FormDataContentType())
handler.Upload("form-field")(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if v.useIgnoreSkipOpt {
w.WriteHeader(http.StatusAccepted)
fmt.Fprintf(w, "skipping check since we did not upload any file")
return
}
file, err := gulter.FilesFromContextWithKey(r, "form-field")
require.NoError(t, err)
require.Equal(t, v.pathToFile, file[0].OriginalName)
w.WriteHeader(http.StatusAccepted)
fmt.Fprintf(w, "successfully uploaded the file")
})).ServeHTTP(recorder, r)
require.Equal(t, v.expectedStatusCode, recorder.Result().StatusCode)
verifyMatch(t, recorder)
})
}
}