-
-
Notifications
You must be signed in to change notification settings - Fork 471
/
Copy pathmain_test.go
82 lines (68 loc) · 1.92 KB
/
main_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
package main
import (
"io"
"net/http"
"testing"
"github.com/stretchr/testify/assert"
)
func TestIndexRoute(t *testing.T) {
// Define a structure for specifying input and output
// data of a single test case. This structure is then used
// to create a so called test map, which contains all test
// cases, that should be run for testing this function
tests := []struct {
description string
// Test input
route string
// Expected output
expectedError bool
expectedCode int
expectedBody string
}{
{
description: "index route",
route: "/",
expectedError: false,
expectedCode: 200,
expectedBody: "OK",
},
{
description: "non existing route",
route: "/i-dont-exist",
expectedError: false,
expectedCode: 404,
expectedBody: "Cannot GET /i-dont-exist",
},
}
// Setup the app as it is done in the main function
app := Setup()
// Iterate through test single test cases
for _, test := range tests {
// Create a new http request with the route
// from the test case
req, _ := http.NewRequest(
"GET",
test.route,
nil,
)
// Perform the request plain with the app.
// The -1 disables request latency.
res, err := app.Test(req, -1)
// verify that no error occured, that is not expected
assert.Equalf(t, test.expectedError, err != nil, test.description)
// As expected errors lead to broken responses, the next
// test case needs to be processed
if test.expectedError {
continue
}
// Verify if the status code is as expected
assert.Equalf(t, test.expectedCode, res.StatusCode, test.description)
// Read the response body
body, err := io.ReadAll(res.Body)
// Reading the response body should work everytime, such that
// the err variable should be nil
assert.Nilf(t, err, test.description)
// Verify, that the reponse body equals the expected body
assert.Equalf(t, test.expectedBody, string(body), test.description)
}
}