-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext_http_test.go
493 lines (410 loc) · 13.3 KB
/
context_http_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
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
package nodejs_test
import (
"context"
"encoding/json"
"io"
"math"
"net/http"
"net/http/httptest"
"testing"
"time"
nodejs "github.com/KarpelesLab/nodejs"
)
func TestContextServeHTTPToHandler(t *testing.T) {
// Skip this test if running under -short flag
if testing.Short() {
t.Skip("Skipping test in short mode")
}
// Create a factory for NodeJS processes
factory, err := nodejs.New()
if err != nil {
t.Fatalf("Failed to create NodeJS factory: %v", err)
}
// Create a NodeJS process
proc, err := factory.New()
if err != nil {
t.Fatalf("Failed to create NodeJS process: %v", err)
}
defer proc.Close()
// Create a JavaScript context
jsCtx, err := proc.NewContext()
if err != nil {
t.Fatalf("Failed to create JavaScript context: %v", err)
}
defer jsCtx.Close()
// Define a handler in the context
handlerCode := `
// Define a state variable in this context
this.requestCount = 0;
// Define an HTTP handler
this.httpHandler = function(request) {
// Increment request counter
this.requestCount++;
// No need to parse URL - just use the 'Guest' name
const name = 'TestUser';
// Create response data
const responseData = {
message: "Hello, " + name + "!",
count: this.requestCount,
method: request.method,
path: request.path
};
// Return a Response object
return new Response(
JSON.stringify(responseData),
{
status: 200,
headers: {
"Content-Type": "application/json",
"X-Context-Header": "ContextTest"
}
}
);
};
`
// Evaluate the handler code in the context
_, err = jsCtx.Eval(context.Background(), handlerCode, nil)
if err != nil {
t.Fatalf("Failed to evaluate handler code: %v", err)
}
// Test the handler with multiple requests to verify state persistence
for i := 1; i <= 50; i++ {
// Create a test HTTP request
req := httptest.NewRequest(http.MethodGet, "http://localhost/test?name=TestUser", nil)
req.Header.Set("X-Test-Header", "TestValue")
// Create a test response recorder
w := httptest.NewRecorder()
// Serve the HTTP request to our JavaScript handler in the context
jsCtx.ServeHTTPToHandler("httpHandler", w, req)
// Get the response
resp := w.Result()
// Check status code
if resp.StatusCode != http.StatusOK {
t.Errorf("Request %d: Expected status 200, got %d", i, resp.StatusCode)
}
// Check headers
if resp.Header.Get("Content-Type") != "application/json" {
t.Errorf("Request %d: Expected Content-Type: application/json, got %s", i, resp.Header.Get("Content-Type"))
}
if resp.Header.Get("X-Context-Header") != "ContextTest" {
t.Errorf("Request %d: Expected X-Context-Header: ContextTest, got %s", i, resp.Header.Get("X-Context-Header"))
}
// Read body
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Request %d: Failed to read response body: %v", i, err)
}
t.Logf("Request %d response body: %s", i, string(body))
// Parse JSON
var respData map[string]interface{}
if err := json.Unmarshal(body, &respData); err != nil {
t.Fatalf("Request %d: Failed to parse response JSON: %v", i, err)
}
// Check message value
if msg, ok := respData["message"].(string); !ok || msg != "Hello, TestUser!" {
t.Errorf("Request %d: Expected message 'Hello, TestUser!', got %v", i, respData["message"])
}
// Check counter value
count, ok := respData["count"].(float64)
if !ok || int(count) != i {
t.Errorf("Request %d: Expected count %d, got %v", i, i, respData["count"])
}
}
}
func TestContextClosedHTTPHandler(t *testing.T) {
// Skip this test if running under -short flag
if testing.Short() {
t.Skip("Skipping test in short mode")
}
// Create a factory for NodeJS processes
factory, err := nodejs.New()
if err != nil {
t.Fatalf("Failed to create NodeJS factory: %v", err)
}
// Create a NodeJS process
proc, err := factory.New()
if err != nil {
t.Fatalf("Failed to create NodeJS process: %v", err)
}
defer proc.Close()
// Create a JavaScript context
jsCtx, err := proc.NewContext()
if err != nil {
t.Fatalf("Failed to create JavaScript context: %v", err)
}
// Define a handler in the context
_, err = jsCtx.Eval(context.Background(), "this.handler = function(req) { return new Response('OK'); };", nil)
if err != nil {
t.Fatalf("Failed to define handler: %v", err)
}
// Close the context
err = jsCtx.Close()
if err != nil {
t.Fatalf("Failed to close context: %v", err)
}
// Create a test HTTP request
req := httptest.NewRequest(http.MethodGet, "http://localhost/test", nil)
// Create a test response recorder
w := httptest.NewRecorder()
// Try to serve the HTTP request to the closed context
jsCtx.ServeHTTPToHandler("handler", w, req)
// Get the response
resp := w.Result()
defer resp.Body.Close()
// Check status code - should be a server error
if resp.StatusCode != http.StatusInternalServerError {
t.Errorf("Expected status 500 for closed context, got %d", resp.StatusCode)
}
resp.Body.Close()
}
func TestServeHTTPWithOptions(t *testing.T) {
// Skip this test if running under -short flag
if testing.Short() {
t.Skip("Skipping test in short mode")
}
// Create a factory for NodeJS processes
factory, err := nodejs.New()
if err != nil {
t.Fatalf("Failed to create NodeJS factory: %v", err)
}
// Create a NodeJS process
proc, err := factory.New()
if err != nil {
t.Fatalf("Failed to create NodeJS process: %v", err)
}
defer proc.Close()
// Create a JavaScript context
jsCtx, err := proc.NewContext()
if err != nil {
t.Fatalf("Failed to create JavaScript context: %v", err)
}
defer jsCtx.Close()
// Define a handler in the context
handlerCode := `
// Define a state variable in this context
this.requestCount = 0;
// Define an HTTP handler
this.handler = function(request) {
// Increment request counter
this.requestCount++;
// Create response data
const responseData = {
message: "Hello from handler",
count: this.requestCount,
method: request.method,
path: request.path
};
// Return a Response object
return new Response(
JSON.stringify(responseData),
{
status: 200,
headers: {
"Content-Type": "application/json",
"X-Handler-Header": "OptionsTest"
}
}
);
};
`
// Evaluate the handler code in the context
_, err = jsCtx.Eval(context.Background(), handlerCode, nil)
if err != nil {
t.Fatalf("Failed to evaluate handler code: %v", err)
}
// Test the handler with multiple requests to verify state persistence
for i := 1; i <= 3; i++ {
// Create a test HTTP request
req := httptest.NewRequest(http.MethodGet, "http://localhost/test", nil)
req.Header.Set("X-Test-Header", "TestValue")
// Create a test response recorder
w := httptest.NewRecorder()
// Serve the HTTP request using ServeHTTPWithOptions
options := nodejs.HTTPHandlerOptions{
Context: jsCtx.ID(),
}
proc.ServeHTTPWithOptions("handler", options, w, req)
// Get the response
resp := w.Result()
// Check status code
if resp.StatusCode != http.StatusOK {
t.Errorf("Request %d: Expected status 200, got %d", i, resp.StatusCode)
}
// Check headers
if resp.Header.Get("Content-Type") != "application/json" {
t.Errorf("Request %d: Expected Content-Type: application/json, got %s", i, resp.Header.Get("Content-Type"))
}
if resp.Header.Get("X-Handler-Header") != "OptionsTest" {
t.Errorf("Request %d: Expected X-Handler-Header: OptionsTest, got %s", i, resp.Header.Get("X-Handler-Header"))
}
// Read body
body, err := io.ReadAll(resp.Body)
resp.Body.Close() // Close the body after reading
if err != nil {
t.Fatalf("Request %d: Failed to read response body: %v", i, err)
}
t.Logf("Request %d response body: %s", i, string(body))
// Parse JSON
var respData map[string]interface{}
if err := json.Unmarshal(body, &respData); err != nil {
t.Fatalf("Request %d: Failed to parse response JSON: %v", i, err)
}
// Check message value
if msg, ok := respData["message"].(string); !ok || msg != "Hello from handler" {
t.Errorf("Request %d: Expected message 'Hello from handler', got %v", i, respData["message"])
}
// Check counter value
count, ok := respData["count"].(float64)
if !ok || int(count) != i {
t.Errorf("Request %d: Expected count %d, got %v", i, i, respData["count"])
}
}
}
func TestLargeHTTPResponse(t *testing.T) {
// Skip this test if running under -short flag
if testing.Short() {
t.Skip("Skipping test in short mode")
}
// Create a factory for NodeJS processes
factory, err := nodejs.New()
if err != nil {
t.Fatalf("Failed to create NodeJS factory: %v", err)
}
// Create a NodeJS process
proc, err := factory.New()
if err != nil {
t.Fatalf("Failed to create NodeJS process: %v", err)
}
defer proc.Close()
// Create a JavaScript context
jsCtx, err := proc.NewContext()
if err != nil {
t.Fatalf("Failed to create JavaScript context: %v", err)
}
defer jsCtx.Close()
// Define a handler in the context that generates a large response
handlerCode := `
function makeid(length) {
let result = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const charactersLength = characters.length;
let counter = 0;
while (counter < length) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
counter += 1;
}
return result;
}
// Define a handler that returns a large JSON response
this.largeResponseHandler = function(request) {
// Create a large array with 10,000 items
const largeArray = [];
for (let i = 0; i < 10000; i++) {
largeArray.push({
index: i,
value: "Item " + i,
timestamp: new Date().toISOString(),
randomValue: makeid(16),
});
}
// Create large object with the array and additional metadata
const responseData = {
message: "Large response test",
method: request.method,
path: request.path,
timestamp: new Date().toISOString(),
items: largeArray
};
// Return a Response object with the large JSON
return new Response(
JSON.stringify(responseData),
{
status: 200,
headers: {
"Content-Type": "application/json",
"X-Large-Response": "true"
}
}
);
};
`
// Evaluate the handler code in the context
_, err = jsCtx.Eval(context.Background(), handlerCode, nil)
if err != nil {
t.Fatalf("Failed to evaluate handler code: %v", err)
}
// Create a test HTTP request
req := httptest.NewRequest(http.MethodGet, "http://localhost/large-data", nil)
// Create a test response recorder
w := httptest.NewRecorder()
// Measure response time to ensure streaming works properly
startTime := time.Now()
// Serve the HTTP request to our JavaScript handler in the context
jsCtx.ServeHTTPToHandler("largeResponseHandler", w, req)
// Get the response
resp := w.Result()
defer resp.Body.Close()
// Check status code
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status 200, got %d", resp.StatusCode)
}
// Check headers
if resp.Header.Get("Content-Type") != "application/json" {
t.Errorf("Expected Content-Type: application/json, got %s", resp.Header.Get("Content-Type"))
}
if resp.Header.Get("X-Large-Response") != "true" {
t.Errorf("Expected X-Large-Response: true, got %s", resp.Header.Get("X-Large-Response"))
}
totalBytes, err := io.Copy(io.Discard, resp.Body)
// Read body in chunks to verify streaming capability
if err != nil {
t.Fatalf("Error reading response body: %v", err)
}
// Log response size and timing information
responseTime := time.Since(startTime)
t.Logf("Large response size: %d bytes, time: %v", totalBytes, responseTime)
// Verify that we received a substantial amount of data (at least 1MB)
if totalBytes < 1000000 {
t.Errorf("Expected large response (>1MB), got only %d bytes", totalBytes)
}
// Also test reading the entire response at once to compare with chunked reading
req2 := httptest.NewRequest(http.MethodGet, "http://localhost/large-data", nil)
w2 := httptest.NewRecorder()
startTime2 := time.Now()
// Serve the request again
jsCtx.ServeHTTPToHandler("largeResponseHandler", w2, req2)
resp2 := w2.Result()
defer resp2.Body.Close()
// Read the entire body at once
fullBody, err := io.ReadAll(resp2.Body)
if err != nil {
t.Fatalf("Error reading full response body: %v", err)
}
responseTime2 := time.Since(startTime2)
t.Logf("Full read - Large response size: %d bytes, time: %v", len(fullBody), responseTime2)
// Verify that we got approximately the same amount of data both ways
// Allow for a small margin of error (0.1%) due to buffering differences
sizeDiff := math.Abs(float64(len(fullBody)) - float64(totalBytes))
diffPercent := (sizeDiff / float64(totalBytes)) * 100
if int64(len(fullBody)) != totalBytes {
t.Errorf("Inconsistent response sizes: chunked=%d bytes, full=%d bytes (diff: %.2f%%)",
totalBytes, len(fullBody), diffPercent)
}
// Parse the JSON to verify it's valid
var respData map[string]interface{}
if err := json.Unmarshal(fullBody, &respData); err != nil {
t.Fatalf("Failed to parse response JSON: %v", err)
}
// Check some expected values
if msg, ok := respData["message"].(string); !ok || msg != "Large response test" {
t.Errorf("Expected message 'Large response test', got %v", respData["message"])
}
// Check that the items array exists and has 10,000 elements
items, ok := respData["items"].([]interface{})
if !ok {
t.Fatalf("Expected items to be an array, got %T", respData["items"])
}
if len(items) != 10000 {
t.Errorf("Expected 10,000 items, got %d", len(items))
}
}