-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcookie_test.go
More file actions
273 lines (242 loc) · 6.6 KB
/
Copy pathcookie_test.go
File metadata and controls
273 lines (242 loc) · 6.6 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
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
package httputil
import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
)
func TestSetCookie(t *testing.T) {
tests := []struct {
name string
key CookieKey
value string
maxAge time.Duration
secure bool
expected string
}{
{
name: "basic cookie",
key: CookieKey("session"),
value: "abc123",
maxAge: 1 * time.Hour,
secure: false,
expected: "session=abc123; Path=/; Max-Age=3600; HttpOnly",
},
{
name: "secure cookie",
key: CookieKey("auth"),
value: "token456",
maxAge: 24 * time.Hour,
secure: true,
expected: "auth=token456; Path=/; Max-Age=86400; HttpOnly; Secure",
},
{
name: "delete cookie (zero maxAge)",
key: CookieKey("old_session"),
value: "",
maxAge: 0,
secure: false,
expected: "old_session=; Path=/; Max-Age=0; HttpOnly",
},
{
name: "short expiry",
key: CookieKey("temp"),
value: "temporary",
maxAge: 30 * time.Second,
secure: true,
expected: "temp=temporary; Path=/; Max-Age=30; HttpOnly; Secure",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
w := httptest.NewRecorder()
SetCookie(w, tt.key, tt.value, tt.maxAge, tt.secure)
cookies := w.Header().Get("Set-Cookie")
// Check individual components since Expires timestamp varies
if !strings.Contains(cookies, "Path=/") {
t.Error("Expected Path=/ in cookie")
}
if !strings.Contains(cookies, "HttpOnly") {
t.Error("Expected HttpOnly in cookie")
}
if tt.secure && !strings.Contains(cookies, "Secure") {
t.Error("Expected Secure in cookie")
}
if !strings.Contains(cookies, fmt.Sprintf("%s=%s", tt.key, tt.value)) {
t.Errorf("Expected cookie name/value %s=%s", tt.key, tt.value)
}
// Verify expires time is set correctly (within reasonable margin)
if tt.maxAge > 0 {
if !strings.Contains(cookies, "Expires=") {
t.Error("Expected Expires to be set when maxAge > 0")
}
}
})
}
}
func TestGetCookie(t *testing.T) {
tests := []struct {
name string
cookieKey CookieKey
cookieValue string
setCookie bool
expectError bool
expectedVal string
}{
{
name: "existing cookie",
cookieKey: CookieKey("session"),
cookieValue: "abc123",
setCookie: true,
expectError: false,
expectedVal: "abc123",
},
{
name: "missing cookie",
cookieKey: CookieKey("nonexistent"),
cookieValue: "",
setCookie: false,
expectError: true,
expectedVal: "",
},
{
name: "empty cookie value",
cookieKey: CookieKey("empty"),
cookieValue: "",
setCookie: true,
expectError: false,
expectedVal: "",
},
{
name: "special characters in cookie",
cookieKey: CookieKey("special"),
cookieValue: "value-with_special.chars123",
setCookie: true,
expectError: false,
expectedVal: "value-with_special.chars123",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest("GET", "/", nil)
if tt.setCookie {
cookie := &http.Cookie{
Name: string(tt.cookieKey),
Value: tt.cookieValue,
}
req.AddCookie(cookie)
}
value, err := GetCookie(tt.cookieKey, req)
if tt.expectError && err == nil {
t.Error("Expected error but got none")
}
if !tt.expectError && err != nil {
t.Errorf("Unexpected error: %v", err)
}
if value != tt.expectedVal {
t.Errorf("GetCookie() = %v, want %v", value, tt.expectedVal)
}
// Test error wrapping
if tt.expectError && err != nil {
if !strings.Contains(err.Error(), "parsing cookie") {
t.Error("Error should wrap ErrParsingCookie")
}
if !strings.Contains(err.Error(), string(tt.cookieKey)) {
t.Error("Error should contain cookie key")
}
}
})
}
}
func TestCookieRoundTrip(t *testing.T) {
// Test setting and getting cookies in a full HTTP flow
key := CookieKey("test_session")
value := "test_value_123"
maxAge := 1 * time.Hour
// Create a test handler that sets a cookie
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/set" {
SetCookie(w, key, value, maxAge, false)
w.WriteHeader(http.StatusOK)
} else if r.URL.Path == "/get" {
cookieValue, err := GetCookie(key, r)
if err != nil {
// This is expected if no cookie was set
w.WriteHeader(http.StatusNoContent)
return
}
w.Write([]byte(cookieValue))
}
})
server := httptest.NewServer(handler)
defer server.Close()
// Use a cookie jar to automatically handle cookies
jar := &testCookieJar{cookies: make(map[string]*http.Cookie)}
client := &http.Client{Jar: jar}
// Set cookie
setResp, err := client.Get(server.URL + "/set")
if err != nil {
t.Fatalf("Failed to set cookie: %v", err)
}
setResp.Body.Close()
// Get cookie (the client should automatically send it back)
getResp, err := client.Get(server.URL + "/get")
if err != nil {
t.Fatalf("Failed to get cookie: %v", err)
}
defer getResp.Body.Close()
if getResp.StatusCode != http.StatusOK {
t.Errorf("Expected status 200, got %d", getResp.StatusCode)
}
}
// Simple cookie jar for testing
type testCookieJar struct {
cookies map[string]*http.Cookie
}
func (j *testCookieJar) SetCookies(u *url.URL, cookies []*http.Cookie) {
for _, cookie := range cookies {
j.cookies[cookie.Name] = cookie
}
}
func (j *testCookieJar) Cookies(u *url.URL) []*http.Cookie {
var result []*http.Cookie
for _, cookie := range j.cookies {
result = append(result, cookie)
}
return result
}
func TestCookieEdgeCases(t *testing.T) {
t.Run("multiple cookies with same name", func(t *testing.T) {
req := httptest.NewRequest("GET", "/", nil)
// Add multiple cookies with the same name (this can happen in real scenarios)
req.Header.Add("Cookie", "test=value1")
req.Header.Add("Cookie", "test=value2")
// GetCookie should return the first one
value, err := GetCookie(CookieKey("test"), req)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
// Should get one of the values (behavior may depend on Go's implementation)
if value != "value1" && value != "value2" {
t.Errorf("GetCookie() = %v, want value1 or value2", value)
}
})
t.Run("cookie with equals sign in value", func(t *testing.T) {
req := httptest.NewRequest("GET", "/", nil)
cookie := &http.Cookie{
Name: "encoded",
Value: "key=value&other=data",
}
req.AddCookie(cookie)
value, err := GetCookie(CookieKey("encoded"), req)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if value != "key=value&other=data" {
t.Errorf("GetCookie() = %v, want key=value&other=data", value)
}
})
}