1
|
|
|
package test |
2
|
|
|
|
3
|
|
|
import ( |
4
|
|
|
"bytes" |
5
|
|
|
"github.com/gofiber/fiber/v2" |
6
|
|
|
"github.com/stretchr/testify/assert" |
7
|
|
|
"io/ioutil" |
8
|
|
|
"net/http" |
9
|
|
|
"testing" |
10
|
|
|
) |
11
|
|
|
|
12
|
|
|
type Test struct { |
13
|
|
|
description string |
14
|
|
|
|
15
|
|
|
// Test input |
16
|
|
|
route string |
17
|
|
|
body []byte |
18
|
|
|
reqType string |
19
|
|
|
// Expected output |
20
|
|
|
expectedError bool |
21
|
|
|
expectedCode int |
22
|
|
|
expectedBody string |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
func testIndex() []Test { |
26
|
|
|
tests := []Test{ |
27
|
|
|
|
28
|
|
|
{ |
29
|
|
|
description: "index", |
30
|
|
|
route: "/", |
31
|
|
|
body: []byte{}, |
32
|
|
|
reqType: "GET", |
33
|
|
|
expectedCode: fiber.StatusForbidden, |
34
|
|
|
expectedBody: "This is not a valid route", |
35
|
|
|
expectedError: false, |
36
|
|
|
}, |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
return tests |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
func TestRoute(t *testing.T) { |
43
|
|
|
app, _ := Setup() |
44
|
|
|
|
45
|
|
|
tests := testIndex() |
46
|
|
|
|
47
|
|
|
for _, test := range tests { |
48
|
|
|
req, _ := http.NewRequest(test.reqType, "/v1/"+test.route, bytes.NewBuffer(test.body)) |
49
|
|
|
// Perform the request plain with the app. |
50
|
|
|
// The -1 disables request latency. |
51
|
|
|
res, err := app.Test(req, -1) |
52
|
|
|
|
53
|
|
|
// verify that no error occured, that is not expected |
54
|
|
|
assert.Equalf(t, test.expectedError, err != nil, test.description) |
55
|
|
|
|
56
|
|
|
// As expected errors lead to broken responses, the next |
57
|
|
|
// test case needs to be processed |
58
|
|
|
if test.expectedError { |
59
|
|
|
continue |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
// Verify if the status code is as expected |
63
|
|
|
assert.Equalf(t, test.expectedCode, res.StatusCode, test.description) |
64
|
|
|
|
65
|
|
|
// Read the response body |
66
|
|
|
body, err := ioutil.ReadAll(res.Body) |
67
|
|
|
|
68
|
|
|
// Reading the response body should work everytime, such that |
69
|
|
|
// the err variable should be nil |
70
|
|
|
assert.Nilf(t, err, test.description) |
71
|
|
|
|
72
|
|
|
// Verify, that the reponse body equals the expected body |
73
|
|
|
assert.Equalf(t, test.expectedBody, string(body), test.description) |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|