-
Notifications
You must be signed in to change notification settings - Fork 0
/
tools_test.go
371 lines (285 loc) · 9.05 KB
/
tools_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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package toolkit
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"image"
"image/png"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/http/httptest"
"os"
"sync"
"testing"
)
type RoundTripFunc func(req *http.Request) *http.Response
func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req), nil
}
func NewTestClient(fn RoundTripFunc) *http.Client {
return &http.Client{
Transport: fn,
}
}
func TestTools_PushJSONToRemote(t *testing.T) {
client := NewTestClient(func(req *http.Request) *http.Response {
// test request parameters
return &http.Response{
StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewBufferString("ok")),
Header: make(http.Header),
}
})
var testTools Tools
var foo struct {
Bar string `json:"bar"`
}
foo.Bar = "bar"
_, _, err := testTools.PushJSONToRemote("http://example.com/some/path", foo, client)
if err != nil {
t.Error("failed to call remote url", err)
}
}
func TestTools_RandomString(t *testing.T) {
var testTools Tools
s := testTools.RandomString(10)
if len(s) != 10 {
t.Error("Wrong length random string returned")
}
}
var uploadTests = []struct {
name string
allowedTypes []string
renameFile bool
errorExpected bool
}{
{name: "allowed no rename", allowedTypes: []string{"image/jpeg", "image/png"}, renameFile: false, errorExpected: false},
{name: "allowed rename", allowedTypes: []string{"image/jpeg", "image/png"}, renameFile: true, errorExpected: false},
{name: "not allowed", allowedTypes: []string{"image/jpeg"}, renameFile: false, errorExpected: true},
}
func TestTools_UploadFiles(t *testing.T) {
for _, e := range uploadTests {
// set up a pipe to avoid buffering
pr, pw := io.Pipe()
writer := multipart.NewWriter(pw)
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer writer.Close()
defer wg.Done()
/// create the form data filed 'file'
part, err := writer.CreateFormFile("file", "./testdata/img.png")
if err != nil {
t.Error(err)
}
f, err := os.Open("./testdata/img.png")
if err != nil {
t.Error(err)
}
defer f.Close()
img, _, err := image.Decode(f)
if err != nil {
t.Error("error decoding image", err)
}
err = png.Encode(part, img)
if err != nil {
t.Error(err)
}
}()
// read from the pipe which recieves data
request := httptest.NewRequest("Post", "/", pr)
request.Header.Add("Content-Type", writer.FormDataContentType())
var testTools Tools
testTools.AllowedFileTypes = e.allowedTypes
uploadedFiles, err := testTools.UploadFiles(request, "./testdata/uploads/", e.renameFile)
if err != nil && !e.errorExpected {
t.Error(err)
}
if !e.errorExpected {
if _, err := os.Stat(fmt.Sprintf("./testdata/uploads/%s", uploadedFiles[0].NewFileName)); os.IsNotExist(err) {
t.Errorf("%s: expected file to exist: %s", e.name, err.Error())
}
// clean up
_ = os.Remove(fmt.Sprintf("./testdata/uploads/%s", uploadedFiles[0].NewFileName))
if !e.errorExpected && err != nil {
t.Errorf("%s: error expected but none received", e.name)
}
wg.Wait()
}
}
}
func TestTool_UploadOneFile(t *testing.T) {
// set up a pipe to avoid buffering
pr, pw := io.Pipe()
writer := multipart.NewWriter(pw)
go func() {
defer writer.Close()
/// create the form data filed 'file'
part, err := writer.CreateFormFile("file", "./testdata/img.png")
if err != nil {
t.Error(err)
}
f, err := os.Open("./testdata/img.png")
if err != nil {
t.Error(err)
}
defer f.Close()
img, _, err := image.Decode(f)
if err != nil {
t.Error("error decoding image", err)
}
err = png.Encode(part, img)
if err != nil {
t.Error(err)
}
}()
// read from the pipe which recieves data
request := httptest.NewRequest("Post", "/", pr)
request.Header.Add("Content-Type", writer.FormDataContentType())
var testTools Tools
uploadedFiles, err := testTools.UploadOneFile(request, "./testdata/uploads/", true)
if err != nil {
t.Error(err)
}
if _, err := os.Stat(fmt.Sprintf("./testdata/uploads/%s", uploadedFiles.NewFileName)); os.IsNotExist(err) {
t.Errorf("expected file to exist: %s", err.Error())
}
// clean up
_ = os.Remove(fmt.Sprintf("./testdata/uploads/%s", uploadedFiles.NewFileName))
}
func TestTools_CreateDirIfNotExist(t *testing.T) {
var testTools Tools
err := testTools.CreateDirIfNotExist("./testdata/testDir")
if err != nil {
t.Error(err)
}
err = testTools.CreateDirIfNotExist("./testdata/testDir")
if err != nil {
t.Error(err)
}
_ = os.Remove("./testdata/testDir")
}
var slugTests = []struct {
name string
s string
expected string
errorExpected bool
}{
{name: "valid string", s: "now is the time", expected: "now-is-the-time", errorExpected: false},
{name: "empty string", s: "", expected: "", errorExpected: true},
{name: "empty string", s: "", expected: "", errorExpected: true},
{name: "japanese string", s: "こんにちは世界", expected: "", errorExpected: true},
{name: "japanese string and roman characters", s: "hello world こんにちは世界", expected: "hello-world", errorExpected: false},
}
func TestTools_Slugify(t *testing.T) {
var testTools Tools
for _, e := range slugTests {
slug, err := testTools.Slugify(e.s)
if err != nil && !e.errorExpected {
t.Errorf("%s: error received when none expected: %s", e.name, err.Error())
}
if !e.errorExpected && slug != e.expected {
t.Errorf("%s: wrong slug returned; expected %s but got %s", e.name, e.expected, slug)
}
}
}
func TestTools_DownloadStaticFile(t *testing.T) {
rr := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/", nil)
var testTools Tools
testTools.DownloadStaticFile(rr, req, "./testdata", "img.png", "puppy.png")
res := rr.Result()
defer res.Body.Close()
if res.Header["Content-Length"][0] != "603724" {
t.Error("wrong content length of", res.Header["Content-Length"][0])
}
if res.Header["Content-Disposition"][0] != "attachment; filename=\"puppy.png\"" {
t.Error("Wrong content disposition of", res.Header["Content-Disposition"][0])
}
_, err := ioutil.ReadAll(res.Body)
if err != nil {
t.Error(err)
}
}
var jsonTests = []struct {
name string
json string
errorExpected bool
maxSize int
allowUnknown bool
}{
{name: "good json", json: `{"foo": "bar"}`, errorExpected: false, maxSize: 1024, allowUnknown: false},
{name: "badly formatted json", json: `{"foo": }`, errorExpected: true, maxSize: 1024, allowUnknown: false},
{name: "incorrect type", json: `{"foo": 1 }`, errorExpected: true, maxSize: 1024, allowUnknown: false},
{name: "two json files", json: `{"foo": "1"}{"alpha": "beta"}`, errorExpected: true, maxSize: 1024, allowUnknown: false},
{name: "empty body", json: ``, errorExpected: true, maxSize: 1024, allowUnknown: false},
{name: "syntax error in json", json: `{"foo":1"`, errorExpected: true, maxSize: 1024, allowUnknown: false},
{name: "unknown field", json: `{"fooo":"a"}`, errorExpected: true, maxSize: 1024, allowUnknown: false},
{name: "allow unknown field", json: `{"fooo":"a"}`, errorExpected: false, maxSize: 1024, allowUnknown: true},
{name: "missing field name", json: `{jack:"a"}`, errorExpected: true, maxSize: 1024, allowUnknown: true},
{name: "file too large", json: `{"foor":"bar"}`, errorExpected: true, maxSize: 5, allowUnknown: true},
{name: "not json", json: `Hello, world`, errorExpected: true, maxSize: 1024, allowUnknown: true},
}
func TestTools_ReadJSON(t *testing.T) {
var testTools Tools
for _, e := range jsonTests {
// set the max file size
testTools.MaxJSONSize = e.maxSize
testTools.AllowUnknownFields = e.allowUnknown
var decodedJSON struct {
Foo string `json:"foo"`
}
// create a request with the body
req, err := http.NewRequest("POST", "/", bytes.NewReader([]byte(e.json)))
if err != nil {
t.Log("Error:", err)
}
// create a recorder
rr := httptest.NewRecorder()
err = testTools.ReadJSON(rr, req, &decodedJSON)
if e.errorExpected && err == nil {
t.Errorf("%s: error expected, but none received", e.name)
}
if !e.errorExpected && err != nil {
t.Errorf("%s: error not expected, but one received: %s", e.name, err.Error())
}
req.Body.Close()
}
}
func TestTools_WriteJSON(t *testing.T) {
var testTools Tools
rr := httptest.NewRecorder()
payload := JSONResponse{
Error: false,
Message: "foo",
}
headers := make(http.Header)
headers.Add("FOO", "BAR")
err := testTools.WriteJSON(rr, http.StatusOK, payload, headers)
if err != nil {
t.Errorf("failed to write JSON: %v", err)
}
}
func TestTools_ErrorJSON(t *testing.T) {
var testTools Tools
rr := httptest.NewRecorder()
err := testTools.ErrorJSON(rr, errors.New("some error"), http.StatusServiceUnavailable)
if err != nil {
t.Error(err)
}
var payload JSONResponse
decoder := json.NewDecoder(rr.Body)
err = decoder.Decode(&payload)
if err != nil {
t.Error("received error when decoding JSON", err)
}
if !payload.Error {
t.Error("error set to false in JSON, and it should be true")
}
if rr.Code != http.StatusServiceUnavailable {
t.Errorf("wrong status code returned; expected 502, but go %d", rr.Code)
}
}