-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_test.go
More file actions
359 lines (297 loc) · 9.25 KB
/
http_test.go
File metadata and controls
359 lines (297 loc) · 9.25 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
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
package main
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
// TestTimerHandlerGET tests GET requests to /timer
func TestTimerHandlerGET(t *testing.T) {
timer := NewSecondsTimer(10 * time.Second)
defer timer.Stop()
handler := timerHandler(timer)
req := httptest.NewRequest(http.MethodGet, "/timer", nil)
rec := httptest.NewRecorder()
handler(rec, req)
// Check status code
if rec.Code != http.StatusOK {
t.Errorf("GET returned status %d, expected %d", rec.Code, http.StatusOK)
}
// Check Content-Type
contentType := rec.Header().Get("Content-Type")
if contentType != "application/json" {
t.Errorf("Content-Type = %s, expected application/json", contentType)
}
// Parse response
var response outputTimer
if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
t.Fatalf("Failed to parse JSON response: %v", err)
}
// Verify response has expected fields
if response.Seconds < 9 || response.Seconds > 10 {
t.Errorf("Response seconds = %d, expected ~10", response.Seconds)
}
if response.End == "" {
t.Error("Response end time is empty")
}
// Verify end time is valid RFC3339
if _, err := time.Parse(time.RFC3339, response.End); err != nil {
t.Errorf("End time not valid RFC3339: %v", err)
}
}
// TestTimerHandlerPUTValid tests valid PUT requests
func TestTimerHandlerPUTValid(t *testing.T) {
timer := NewSecondsTimer(time.Hour)
defer timer.Stop()
handler := timerHandler(timer)
testCases := []struct {
name string
seconds int
}{
{"Zero seconds", 0},
{"One second", 1},
{"One minute", 60},
{"One hour", 3600},
{"One day", 86400},
{"Maximum (30 days)", maxTimerSeconds},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
payload := map[string]int{"seconds": tc.seconds}
body, _ := json.Marshal(payload)
req := httptest.NewRequest(http.MethodPut, "/timer", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
handler(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("PUT returned status %d, expected %d. Body: %s", rec.Code, http.StatusOK, rec.Body.String())
}
// Check response
var response map[string]bool
if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
t.Fatalf("Failed to parse JSON response: %v", err)
}
if !response["success"] {
t.Error("Expected success:true in response")
}
// Verify timer was actually set
remaining := timer.TimeRemaining()
expectedRemaining := time.Duration(tc.seconds) * time.Second
diff := (remaining - expectedRemaining).Abs()
if diff > time.Second {
t.Errorf("Timer not set correctly: remaining=%v, expected=%v", remaining, expectedRemaining)
}
})
}
}
// TestTimerHandlerPUTInvalid tests invalid PUT requests
func TestTimerHandlerPUTInvalid(t *testing.T) {
timer := NewSecondsTimer(time.Hour)
defer timer.Stop()
handler := timerHandler(timer)
testCases := []struct {
name string
payload string
expectedStatus int
expectedError string
}{
{
name: "Negative seconds",
payload: `{"seconds":-1}`,
expectedStatus: http.StatusBadRequest,
expectedError: "Timer must be positive",
},
{
name: "Too large",
payload: `{"seconds":99999999}`,
expectedStatus: http.StatusBadRequest,
expectedError: "Timer exceeds maximum duration",
},
{
name: "Invalid JSON",
payload: `{"seconds":`,
expectedStatus: http.StatusBadRequest,
expectedError: "Invalid request format",
},
{
name: "Wrong type",
payload: `{"seconds":"not a number"}`,
expectedStatus: http.StatusBadRequest,
expectedError: "Invalid request format",
},
{
name: "Unknown field",
payload: `{"seconds":10,"extra":"field"}`,
expectedStatus: http.StatusBadRequest,
expectedError: "Invalid request format",
},
{
name: "Empty body",
payload: ``,
expectedStatus: http.StatusBadRequest,
expectedError: "Invalid request format",
},
{
name: "Missing seconds field",
payload: `{}`,
expectedStatus: http.StatusOK, // seconds defaults to 0, which is valid
expectedError: "",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodPut, "/timer", strings.NewReader(tc.payload))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
handler(rec, req)
if rec.Code != tc.expectedStatus {
t.Errorf("Status = %d, expected %d", rec.Code, tc.expectedStatus)
}
if tc.expectedError != "" {
body := rec.Body.String()
if !strings.Contains(body, tc.expectedError) {
t.Errorf("Error message = %q, expected to contain %q", body, tc.expectedError)
}
}
})
}
}
// TestTimerHandlerPUTOversizedBody tests request body size limit
func TestTimerHandlerPUTOversizedBody(t *testing.T) {
timer := NewSecondsTimer(time.Hour)
defer timer.Stop()
handler := timerHandler(timer)
// Create payload larger than maxRequestBodyBytes (1024)
largePayload := `{"seconds":60,"padding":"` + strings.Repeat("x", 2000) + `"}`
req := httptest.NewRequest(http.MethodPut, "/timer", strings.NewReader(largePayload))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
handler(rec, req)
if rec.Code != http.StatusBadRequest {
t.Errorf("Oversized request status = %d, expected %d", rec.Code, http.StatusBadRequest)
}
}
// TestTimerHandlerUnsupportedMethod tests unsupported HTTP methods
func TestTimerHandlerUnsupportedMethod(t *testing.T) {
timer := NewSecondsTimer(time.Hour)
defer timer.Stop()
handler := timerHandler(timer)
methods := []string{http.MethodPost, http.MethodDelete, http.MethodPatch, http.MethodHead}
for _, method := range methods {
t.Run(method, func(t *testing.T) {
req := httptest.NewRequest(method, "/timer", nil)
rec := httptest.NewRecorder()
handler(rec, req)
if rec.Code != http.StatusNotImplemented {
t.Errorf("%s returned status %d, expected %d", method, rec.Code, http.StatusNotImplemented)
}
if !strings.Contains(rec.Body.String(), "Not supported") {
t.Errorf("Error message doesn't contain 'Not supported'")
}
})
}
}
// TestTimerHandlerConcurrent tests concurrent requests
func TestTimerHandlerConcurrent(t *testing.T) {
timer := NewSecondsTimer(time.Hour)
defer timer.Stop()
handler := timerHandler(timer)
// Launch multiple concurrent requests
const concurrency = 50
done := make(chan bool, concurrency)
for i := range concurrency {
go func(id int) {
// Alternate between GET and PUT
if id%2 == 0 {
req := httptest.NewRequest(http.MethodGet, "/timer", nil)
rec := httptest.NewRecorder()
handler(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("Concurrent GET %d failed: status=%d", id, rec.Code)
}
} else {
payload := `{"seconds":10}`
req := httptest.NewRequest(http.MethodPut, "/timer", strings.NewReader(payload))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
handler(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("Concurrent PUT %d failed: status=%d", id, rec.Code)
}
}
done <- true
}(i)
}
// Wait for all requests to complete
for range concurrency {
<-done
}
}
// TestInputTimerJSON tests inputTimer JSON marshaling
func TestInputTimerJSON(t *testing.T) {
input := inputTimer{Seconds: 123}
data, err := json.Marshal(input)
if err != nil {
t.Fatalf("Failed to marshal inputTimer: %v", err)
}
expected := `{"seconds":123}`
if string(data) != expected {
t.Errorf("JSON = %s, expected %s", string(data), expected)
}
// Test unmarshaling
var decoded inputTimer
if err := json.Unmarshal(data, &decoded); err != nil {
t.Fatalf("Failed to unmarshal: %v", err)
}
if decoded.Seconds != input.Seconds {
t.Errorf("Decoded seconds = %d, expected %d", decoded.Seconds, input.Seconds)
}
}
// TestOutputTimerJSON tests outputTimer JSON marshaling
func TestOutputTimerJSON(t *testing.T) {
output := outputTimer{
Seconds: 456,
End: "2026-01-15T12:00:00Z",
}
data, err := json.Marshal(output)
if err != nil {
t.Fatalf("Failed to marshal outputTimer: %v", err)
}
// Verify it contains expected fields
str := string(data)
if !strings.Contains(str, `"seconds":456`) {
t.Errorf("JSON missing seconds field: %s", str)
}
if !strings.Contains(str, `"end":"2026-01-15T12:00:00Z"`) {
t.Errorf("JSON missing end field: %s", str)
}
}
// BenchmarkTimerHandlerGET benchmarks GET requests
func BenchmarkTimerHandlerGET(b *testing.B) {
timer := NewSecondsTimer(time.Hour)
defer timer.Stop()
handler := timerHandler(timer)
req := httptest.NewRequest(http.MethodGet, "/timer", nil)
b.ResetTimer()
for i := 0; i < b.N; i++ {
rec := httptest.NewRecorder()
handler(rec, req)
}
}
// BenchmarkTimerHandlerPUT benchmarks PUT requests
func BenchmarkTimerHandlerPUT(b *testing.B) {
timer := NewSecondsTimer(time.Hour)
defer timer.Stop()
handler := timerHandler(timer)
payload := `{"seconds":60}`
b.ResetTimer()
for i := 0; i < b.N; i++ {
req := httptest.NewRequest(http.MethodPut, "/timer", strings.NewReader(payload))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
handler(rec, req)
}
}