forked from RezaSi/go-interview-practice
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution-template_test.go
More file actions
120 lines (112 loc) · 2.58 KB
/
Copy pathsolution-template_test.go
File metadata and controls
120 lines (112 loc) · 2.58 KB
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
package main
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// Test array for convenience
var testCases = []struct {
name string
method string
url string
token string
wantStatus int
wantBody string
}{
{
name: "Public /hello endpoint with no token",
method: "GET",
url: "/hello",
token: "",
wantStatus: http.StatusOK,
wantBody: "Hello!",
},
{
name: "Secure /secure endpoint no token",
method: "GET",
url: "/secure",
token: "",
wantStatus: http.StatusUnauthorized,
wantBody: "",
},
{
name: "Secure /secure endpoint invalid token",
method: "GET",
url: "/secure",
token: "invalid",
wantStatus: http.StatusUnauthorized,
wantBody: "",
},
{
name: "Secure /secure endpoint correct token",
method: "GET",
url: "/secure",
token: "secret",
wantStatus: http.StatusOK,
wantBody: "You are authorized!",
},
{
name: "Public /hello endpoint with invalid token",
method: "GET",
url: "/hello",
token: "wrong",
wantStatus: http.StatusOK,
wantBody: "Hello!",
},
{
name: "Public /hello endpoint with correct token",
method: "GET",
url: "/hello",
token: "secret",
wantStatus: http.StatusOK,
wantBody: "Hello!",
},
{
name: "Different method on /secure with valid token",
method: "POST",
url: "/secure",
token: "secret",
wantStatus: http.StatusOK,
wantBody: "You are authorized!",
},
{
name: "Different method on /secure with no token",
method: "POST",
url: "/secure",
token: "",
wantStatus: http.StatusUnauthorized,
wantBody: "",
},
}
func TestMiddleware(t *testing.T) {
server := SetupServer()
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
req := httptest.NewRequest(tc.method, tc.url, nil)
if tc.token != "" {
req.Header.Set("X-Auth-Token", tc.token)
}
rr := httptest.NewRecorder()
server.ServeHTTP(rr, req)
if rr.Code != tc.wantStatus {
t.Errorf("Expected status %d, got %d", tc.wantStatus, rr.Code)
}
body := strings.TrimSpace(rr.Body.String())
if body != tc.wantBody {
t.Errorf("Expected body %q, got %q", tc.wantBody, body)
}
})
}
}
func BenchmarkSecureRoute(b *testing.B) {
server := SetupServer()
for i := 0; i < b.N; i++ {
req := httptest.NewRequest("GET", "/secure", nil)
req.Header.Set("X-Auth-Token", "secret")
rr := httptest.NewRecorder()
server.ServeHTTP(rr, req)
io.Copy(io.Discard, rr.Result().Body)
}
}