-
Notifications
You must be signed in to change notification settings - Fork 0
/
tools_test.go
386 lines (312 loc) · 10.2 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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
package toolkit
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"image"
"image/png"
"io"
"log"
"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: io.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 field '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 receives 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 TestTools_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 field '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 receives 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 testTool Tools
err := testTool.CreateDirIfNotExist("./testdata/myDir")
if err != nil {
t.Error(err)
}
err = testTool.CreateDirIfNotExist("./testdata/myDir")
if err != nil {
t.Error(err)
}
_ = os.Remove("./testdata/myDir")
}
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: "complex string", s: "Now is the time for all GOOD men! + fish & such &^123", expected: "now-is-the-time-for-all-good-men-fish-such-123", errorExpected: false},
{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 testTool Tools
for _, e := range slugTests {
slug, err := testTool.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 testTool Tools
testTool.DownloadStaticFile(rr, req, "./testdata/pic.jpg", "moon.jpg")
res := rr.Result()
defer res.Body.Close()
if res.Header["Content-Length"][0] != "10598" {
t.Error("wrong content length of", res.Header["Content-Length"][0])
}
if res.Header["Content-Disposition"][0] != "attachment; filename=\"moon.jpg\"" {
t.Error("wrong content disposition")
}
_, err := io.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 in json", json: `{"fooo": "1"}`, errorExpected: true, maxSize: 1024, allowUnknown: false},
{name: "allow unknown fields in json", json: `{"fooo": "1"}`, errorExpected: false, maxSize: 1024, allowUnknown: true},
{name: "missing field name", json: `{jack: "1"}`, errorExpected: true, maxSize: 1024, allowUnknown: true},
{name: "file too large", json: `{"foo": "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 testTool Tools
for _, e := range jsonTests {
// set the max file size
testTool.MaxJSONSize = e.maxSize
// allow/disallow unknown fields
testTool.AllowUnknownFields = e.allowUnknown
// declare a variable to read the decoded json into
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 = testTool.ReadJSON(rr, req, &decodedJSON)
log.Printf("📢 err: %v\n", err)
if e.errorExpected && err == nil {
t.Errorf("%s: error expected, but none recieved", e.name)
}
if !e.errorExpected && err != nil {
t.Errorf("%s: error not expected, but one recieved: %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("recieved 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 503, but got %d", rr.Code)
}
}
func Test_app_authenticate(t *testing.T) {
var theTests = []struct {
name string
requestBody string
expectedStatusCode int
}{
{"valid user", `{"email":"[email protected]","password":"secret"}`, http.StatusOK},
{"not json", `I'm not JSON`, http.StatusUnauthorized},
{"empty json", `{}`, http.StatusUnauthorized},
{"empty email", `{"email":""}`, http.StatusUnauthorized},
{"empty password", `{"email":"[email protected]"}`, http.StatusUnauthorized},
{"invalid user", `{"email":"[email protected]","password":"secret"}`, http.StatusUnauthorized},
}
for _, e := range theTests {
var reader io.Reader = strings.NewReader(e.requestBody)
req, _ := http.NewRequest("POST", "/auth", reader) // url doesn't matter
rr := httptest.NewRecorder()
handler := http.HandlerFunc(app.authenticate)
handler.ServeHTTP(rr, req)
if e.expectedStatusCode != rr.Code {
t.Errorf("%s: return wrong status code; expected %d but got %d", e.name, e.expectedStatusCode, rr.Code)
}
}
}