forked from nodejs/undici
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnapshot-testing.js
More file actions
1602 lines (1292 loc) · 53.6 KB
/
Copy pathsnapshot-testing.js
File metadata and controls
1602 lines (1292 loc) · 53.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
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict'
const { describe, it } = require('node:test')
const assert = require('node:assert')
const { createServer } = require('node:http')
const { promisify } = require('node:util')
const { unlink, writeFile, readFile } = require('node:fs/promises')
const { tmpdir } = require('node:os')
const { join } = require('node:path')
const { SnapshotAgent, setGlobalDispatcher, getGlobalDispatcher, request } = require('..')
// Test constants
const TEST_CONSTANTS = {
KEEP_ALIVE_TIMEOUT: 10,
KEEP_ALIVE_MAX_TIMEOUT: 10,
AUTO_FLUSH_INTERVAL: 100,
SEQUENTIAL_RESPONSE_DELAY: 200,
TEST_TIMESTAMP: '2024-01-01T00:00:00Z',
TEST_MESSAGE: 'Hello World',
MAX_SNAPSHOTS_FOR_LRU: 2,
TEST_ORIGINS: {
LOCALHOST_3000: 'http://localhost:3000'
},
ERROR_MESSAGES: {
INVALID_MODE: 'Invalid snapshot mode: invalid. Must be one of: record, playback, update',
MISSING_SNAPSHOT_PATH_PLAYBACK: "snapshotPath is required when mode is 'playback'",
MISSING_SNAPSHOT_PATH_UPDATE: "snapshotPath is required when mode is 'update'",
NO_SNAPSHOT_FOUND: 'No snapshot found for GET /nonexistent'
}
}
// Test helper functions
function createSnapshotPath (prefix = 'test-snapshots') {
return join(tmpdir(), `${prefix}-${Date.now()}.json`)
}
function createTestServer (handler) {
return createServer(handler)
}
async function setupServer (server) {
await promisify(server.listen.bind(server))(0)
const { port } = server.address()
const origin = `http://localhost:${port}`
return { port, origin }
}
function setupCleanup (t, resources) {
if (resources.server) {
t.after(() => {
resources.server.closeAllConnections?.()
resources.server.close()
})
}
if (resources.snapshotPath) {
t.after(() => unlink(resources.snapshotPath).catch(() => {}))
}
if (resources.agent) {
t.after(async () => await resources.agent.close())
}
if (resources.originalDispatcher) {
t.after(() => setGlobalDispatcher(resources.originalDispatcher))
}
}
function createJsonResponse (data) {
return JSON.stringify(data)
}
function createDefaultHandler () {
return (req, res) => {
if (req.url === '/test') {
res.writeHead(200, { 'content-type': 'application/json' })
res.end(createJsonResponse({
message: TEST_CONSTANTS.TEST_MESSAGE,
timestamp: TEST_CONSTANTS.TEST_TIMESTAMP
}))
} else {
res.writeHead(404)
res.end('Not Found')
}
}
}
function createEchoHandler () {
return (req, res) => {
let body = ''
req.on('data', chunk => { body += chunk })
req.on('end', async (t) => {
res.writeHead(200, { 'content-type': 'application/json' })
res.end(createJsonResponse({
received: body,
method: req.method,
headers: req.headers
}))
})
}
}
function createSequentialHandler (responses) {
let callCount = 0
return (req, res) => {
res.writeHead(200, { 'content-type': 'text/plain' })
res.end(responses[callCount++] || responses[responses.length - 1])
}
}
async function createLargeSnapshotFile (path, size = 1000) {
const { createRequestHash, formatRequestKey, createHeaderFilters } = require('../lib/mock/snapshot-recorder')
const snapshots = []
for (let i = 0; i < size; i++) {
const requestOpts = {
origin: 'http://localhost:3000',
path: `/api/test-${i}`,
method: 'GET'
}
const cachedSets = createHeaderFilters({})
const requestKey = formatRequestKey(requestOpts, cachedSets)
const hash = createRequestHash(requestKey)
snapshots.push({
hash,
snapshot: {
request: requestKey,
responses: [{
statusCode: 200,
headers: { 'content-type': 'application/json' },
body: Buffer.from(`{"data": "test-${i}"}`).toString('base64'),
trailers: {}
}],
callCount: 0,
timestamp: new Date().toISOString()
}
})
}
await writeFile(path, JSON.stringify(snapshots, null, 2))
}
// Organize tests with describe blocks
describe('SnapshotAgent - Basic Operations', () => {
it('record mode', async (t) => {
const server = createTestServer(createDefaultHandler())
const { origin } = await setupServer(server)
const snapshotPath = createSnapshotPath('record-mode')
setupCleanup(t, { server, snapshotPath })
const agent = new SnapshotAgent({
keepAliveTimeout: TEST_CONSTANTS.KEEP_ALIVE_TIMEOUT,
keepAliveMaxTimeout: TEST_CONSTANTS.KEEP_ALIVE_MAX_TIMEOUT,
mode: 'record',
snapshotPath
})
// Make a request that should be recorded
const response = await request(`${origin}/test`, {
dispatcher: agent
})
const body = await response.body.json()
assert.strictEqual(response.statusCode, 200, 'Response should have status 200')
assert.deepStrictEqual(body, {
message: TEST_CONSTANTS.TEST_MESSAGE,
timestamp: TEST_CONSTANTS.TEST_TIMESTAMP
}, 'Response body should match expected data')
// Save snapshots
await agent.saveSnapshots()
// Verify snapshot was recorded
const recorder = agent.getRecorder()
assert.strictEqual(recorder.size(), 1, 'Should have recorded exactly one snapshot')
const snapshots = recorder.getSnapshots()
assert.strictEqual(snapshots.length, 1, 'Snapshots array should contain one item')
assert.strictEqual(snapshots[0].request.method, 'GET', 'Recorded request method should be GET')
assert.strictEqual(snapshots[0].request.url, `${origin}/test`, 'Recorded request URL should match')
assert.strictEqual(snapshots[0].responses[0].statusCode, 200, 'Recorded response status should be 200')
})
it('playback mode', async (t) => {
const snapshotPath = createSnapshotPath('playback-mode')
setupCleanup(t, { snapshotPath })
// First, create a recording
const recordingAgent = new SnapshotAgent({
mode: 'record',
snapshotPath
})
// Create a simple server for recording
const server = createTestServer((req, res) => {
res.writeHead(200, { 'content-type': 'text/plain' })
res.end('Recorded response')
})
const { origin } = await setupServer(server)
const originalDispatcher = getGlobalDispatcher()
setupCleanup(t, { server, originalDispatcher })
setGlobalDispatcher(recordingAgent)
// Record the request
await request(`${origin}/api/test`)
await recordingAgent.saveSnapshots()
// Now test playback mode
const playbackAgent = new SnapshotAgent({
mode: 'playback',
snapshotPath
})
setGlobalDispatcher(playbackAgent)
// This should use the recorded response, not make a real request
const response = await request(`${origin}/api/test`)
const body = await response.body.text()
assert.strictEqual(response.statusCode, 200, 'Playback response should have status 200')
assert.strictEqual(body, 'Recorded response', 'Playback should return recorded response')
})
it('update mode', async (t) => {
const snapshotPath = createSnapshotPath('update-mode')
setupCleanup(t, { snapshotPath })
// Create agent in update mode
const agent = new SnapshotAgent({
mode: 'update',
snapshotPath
})
// Create a simple server
const server = createTestServer((req, res) => {
if (req.url === '/existing') {
res.writeHead(200, { 'content-type': 'text/plain' })
res.end('Existing endpoint')
} else if (req.url === '/new') {
res.writeHead(200, { 'content-type': 'text/plain' })
res.end('New endpoint')
} else {
res.writeHead(404)
res.end('Not Found')
}
})
const { origin } = await setupServer(server)
const originalDispatcher = getGlobalDispatcher()
setupCleanup(t, { server, originalDispatcher })
setGlobalDispatcher(agent)
// First request - should be recorded as new
const response1 = await request(`${origin}/existing`)
const body1 = await response1.body.text()
assert.strictEqual(body1, 'Existing endpoint', 'First request should get live response')
// Save and reload to simulate existing snapshots
await agent.saveSnapshots()
// Second request to same endpoint - should use existing snapshot
const response2 = await request(`${origin}/existing`)
const body2 = await response2.body.text()
assert.strictEqual(body2, 'Existing endpoint', 'Second request should use cached response')
// Request to new endpoint - should be recorded
const response3 = await request(`${origin}/new`)
const body3 = await response3.body.text()
assert.strictEqual(body3, 'New endpoint', 'New endpoint should get live response')
// Verify we have 2 different snapshots
const recorder = agent.getRecorder()
assert.strictEqual(recorder.size(), 2, 'Should have exactly two snapshots recorded')
})
})
describe('SnapshotAgent - Request Handling', () => {
it('handles POST requests with body', async (t) => {
const snapshotPath = createSnapshotPath('post-requests')
setupCleanup(t, { snapshotPath })
const server = createTestServer(createEchoHandler())
const { origin } = await setupServer(server)
setupCleanup(t, { server })
// Record mode
const recordingAgent = new SnapshotAgent({
mode: 'record',
snapshotPath
})
const originalDispatcher = getGlobalDispatcher()
setupCleanup(t, { originalDispatcher })
setGlobalDispatcher(recordingAgent)
const requestBody = createJsonResponse({ test: 'data' })
const response = await request(`${origin}/api/submit`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: requestBody
})
const responseBody = await response.body.json()
assert.strictEqual(responseBody.received, requestBody, 'Server should receive the request body')
assert.strictEqual(responseBody.method, 'POST', 'Server should receive POST method')
await recordingAgent.saveSnapshots()
// Playback mode
const playbackAgent = new SnapshotAgent({
mode: 'playback',
snapshotPath
})
setGlobalDispatcher(playbackAgent)
// Make the same request - should get recorded response
const playbackResponse = await request(`${origin}/api/submit`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: requestBody
})
const playbackBody = await playbackResponse.body.json()
assert.strictEqual(playbackBody.received, requestBody, 'Playback should return recorded request body')
assert.strictEqual(playbackBody.method, 'POST', 'Playback should return recorded method')
})
it('sequential response support', async (t) => {
const responses = ['First response', 'Second response', 'Third response']
const server = createTestServer(createSequentialHandler(responses))
const { origin } = await setupServer(server)
const snapshotPath = createSnapshotPath('sequential')
setupCleanup(t, { server, snapshotPath })
// Record multiple responses to the same endpoint
const recordingAgent = new SnapshotAgent({
mode: 'record',
snapshotPath
})
const originalDispatcher = getGlobalDispatcher()
setupCleanup(t, { originalDispatcher })
setGlobalDispatcher(recordingAgent)
// Make multiple requests to record sequential responses
{
const res = await request(`${origin}/api/test`)
await res.body.text()
}
{
const res = await request(`${origin}/api/test`)
await res.body.text()
}
{
const res = await request(`${origin}/api/test`)
await res.body.text()
}
// Ensure all recordings are saved and verify the recording state
await recordingAgent.saveSnapshots()
// Verify recording worked correctly before switching to playback
const recordingRecorder = recordingAgent.getRecorder()
assert.strictEqual(recordingRecorder.size(), 1, 'Should have recorded exactly one snapshot')
const recordedSnapshots = recordingRecorder.getSnapshots()
assert.strictEqual(recordedSnapshots[0].responses.length, 3, 'Should have recorded three responses')
// Close recording agent cleanly before starting playback
await recordingAgent.close()
// Switch to playback mode and test sequential responses
const playbackAgent = new SnapshotAgent({
mode: 'playback',
snapshotPath
})
setupCleanup(t, { agent: playbackAgent })
setGlobalDispatcher(playbackAgent)
// Ensure snapshots are loaded and call counts are reset before setting dispatcher
await playbackAgent.loadSnapshots()
// Reset call counts after loading to ensure clean state
playbackAgent.resetCallCounts()
// Verify we have the expected snapshots before proceeding
const recorder = playbackAgent.getRecorder()
assert.strictEqual(recorder.size(), 1, 'Should have exactly one snapshot loaded')
const snapshots = recorder.getSnapshots()
assert.strictEqual(snapshots.length, 1, 'Should have exactly one snapshot')
assert.strictEqual(snapshots[0].responses.length, 3, 'Should have three sequential responses')
// Test sequential responses
const response1 = await request(`${origin}/api/test`)
const body1 = await response1.body.text()
assert.strictEqual(body1, 'First response', 'First call should return first response')
const response2 = await request(`${origin}/api/test`)
const body2 = await response2.body.text()
assert.strictEqual(body2, 'Second response', 'Second call should return second response')
const response3 = await request(`${origin}/api/test`)
const body3 = await response3.body.text()
assert.strictEqual(body3, 'Third response', 'Third call should return third response')
// Fourth call should repeat the last response
const response4 = await request(`${origin}/api/test`)
const body4 = await response4.body.text()
assert.strictEqual(body4, 'Third response', 'Fourth call should repeat the last response')
})
})
describe('SnapshotAgent - Error Handling', () => {
it('error handling in playback mode', async (t) => {
const snapshotPath = createSnapshotPath('error-handling')
setupCleanup(t, { snapshotPath })
const agent = new SnapshotAgent({
mode: 'playback',
snapshotPath // File doesn't exist
})
const originalDispatcher = getGlobalDispatcher()
setupCleanup(t, { agent, originalDispatcher })
setGlobalDispatcher(agent)
// This should throw because no snapshot exists for this request
let errorThrown = false
try {
await request('http://localhost:9999/nonexistent')
} catch (error) {
errorThrown = true
assert.strictEqual(error.name, 'UndiciError', 'Error should be UndiciError')
assert(error.message.includes(TEST_CONSTANTS.ERROR_MESSAGES.NO_SNAPSHOT_FOUND),
'Error message should indicate no snapshot found')
assert.strictEqual(error.code, 'UND_ERR', 'Error code should be UND_ERR')
}
assert(errorThrown, 'Expected an error to be thrown for missing snapshot')
})
it('constructor options validation', async (t) => {
// Test invalid mode
assert.throws(() => {
return new SnapshotAgent({ mode: 'invalid' })
}, {
name: 'InvalidArgumentError',
message: new RegExp(TEST_CONSTANTS.ERROR_MESSAGES.INVALID_MODE.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
}, 'Should throw for invalid mode')
// Test missing snapshotPath for playback mode
assert.throws(() => {
return new SnapshotAgent({ mode: 'playback' })
}, {
name: 'InvalidArgumentError',
message: new RegExp(TEST_CONSTANTS.ERROR_MESSAGES.MISSING_SNAPSHOT_PATH_PLAYBACK)
}, 'Should throw for missing snapshotPath in playback mode')
// Test missing snapshotPath for update mode
assert.throws(() => {
return new SnapshotAgent({ mode: 'update' })
}, {
name: 'InvalidArgumentError',
message: new RegExp(TEST_CONSTANTS.ERROR_MESSAGES.MISSING_SNAPSHOT_PATH_UPDATE)
}, 'Should throw for missing snapshotPath in update mode')
// Test valid configurations should not throw
await assert.doesNotReject(async () => {
const agent1 = new SnapshotAgent({ mode: 'record' })
await agent1.close()
}, 'Should not throw for valid record mode')
await assert.doesNotReject(async () => {
const snapshotPath = createSnapshotPath('valid-playback')
const agent2 = new SnapshotAgent({ mode: 'playback', snapshotPath })
await agent2.close()
}, 'Should not throw for valid playback mode')
await assert.doesNotReject(async () => {
const snapshotPath = createSnapshotPath('valid-update')
const agent3 = new SnapshotAgent({ mode: 'update', snapshotPath })
await agent3.close()
}, 'Should not throw for valid update mode')
})
})
describe('SnapshotAgent - Edge Cases', () => {
it('handles large snapshot files', async (t) => {
const snapshotPath = createSnapshotPath('large')
setupCleanup(t, { snapshotPath })
await createLargeSnapshotFile(snapshotPath, 100)
const agent = new SnapshotAgent({
mode: 'playback',
snapshotPath
})
const originalDispatcher = getGlobalDispatcher()
setupCleanup(t, { agent, originalDispatcher })
// Should load large files without issues
await agent.loadSnapshots()
const recorder = agent.getRecorder()
assert.strictEqual(recorder.size(), 100, 'Should load all 100 snapshots from large file')
setGlobalDispatcher(agent)
// Should be able to find and use snapshots from large file
const response = await request('http://localhost:3000/api/test-0')
const body = await response.body.json()
assert.deepStrictEqual(body, { data: 'test-0' }, 'Should return correct data from large snapshot file')
})
it('concurrent access scenarios', async (t) => {
const snapshotPath = createSnapshotPath('concurrent')
setupCleanup(t, { snapshotPath })
const server = createTestServer((req, res) => {
res.writeHead(200, { 'content-type': 'application/json' })
res.end(createJsonResponse({ path: req.url }))
})
const { origin } = await setupServer(server)
setupCleanup(t, { server })
const agent = new SnapshotAgent({
mode: 'record',
snapshotPath
})
const originalDispatcher = getGlobalDispatcher()
setupCleanup(t, { agent, originalDispatcher })
setGlobalDispatcher(agent)
// Make multiple concurrent requests
const promises = []
for (let i = 0; i < 10; i++) {
promises.push(request(`${origin}/api/test-${i}`))
}
const responses = await Promise.all(promises)
// Verify all responses were handled correctly
for (let i = 0; i < responses.length; i++) {
const body = await responses[i].body.json()
assert.deepStrictEqual(body, { path: `/api/test-${i}` },
`Concurrent request ${i} should return correct response`)
}
await agent.saveSnapshots()
const recorder = agent.getRecorder()
assert.strictEqual(recorder.size(), 10, 'Should record all 10 concurrent requests')
})
})
describe('SnapshotAgent - Advanced Features', () => {
it('snapshot file format validation', async (t) => {
const snapshotPath = createSnapshotPath('format-validation')
setupCleanup(t, { snapshotPath })
const server = createTestServer((req, res) => {
res.writeHead(200, { 'x-custom-header': 'test-value' })
res.end('Test response')
})
const { origin } = await setupServer(server)
setupCleanup(t, { server })
const agent = new SnapshotAgent({
mode: 'record',
snapshotPath
})
const originalDispatcher = getGlobalDispatcher()
setupCleanup(t, { agent, originalDispatcher })
setGlobalDispatcher(agent)
await request(`${origin}/test-endpoint`)
await agent.saveSnapshots()
// Read and verify the snapshot file format
const snapshotData = JSON.parse(await readFile(snapshotPath, 'utf8'))
assert(Array.isArray(snapshotData), 'Snapshot data should be an array')
assert.strictEqual(snapshotData.length, 1, 'Should contain exactly one snapshot')
const snapshot = snapshotData[0]
assert(typeof snapshot.hash === 'string', 'Snapshot should have string hash')
assert(typeof snapshot.snapshot === 'object', 'Snapshot should have snapshot object')
const { request: req, responses, timestamp } = snapshot.snapshot
assert.strictEqual(req.method, 'GET', 'Request method should be GET')
assert.strictEqual(req.url, `${origin}/test-endpoint`, 'Request URL should match')
assert.strictEqual(responses[0].statusCode, 200, 'Response status should be 200')
// Headers should be normalized to lowercase
assert(responses[0].headers['x-custom-header'], 'Custom header should be present')
assert.strictEqual(responses[0].headers['x-custom-header'], 'test-value', 'Custom header value should match')
assert(typeof timestamp === 'string', 'Timestamp should be a string')
})
it('maxSnapshots and LRU eviction', async (t) => {
const server = createTestServer((req, res) => {
res.writeHead(200, { 'content-type': 'text/plain' })
res.end(`Response for ${req.url}`)
})
const { origin } = await setupServer(server)
const snapshotPath = createSnapshotPath('lru-eviction')
setupCleanup(t, { server, snapshotPath })
const agent = new SnapshotAgent({
mode: 'record',
snapshotPath,
maxSnapshots: TEST_CONSTANTS.MAX_SNAPSHOTS_FOR_LRU
})
const originalDispatcher = getGlobalDispatcher()
setupCleanup(t, { agent, originalDispatcher })
setGlobalDispatcher(agent)
// Make 3 requests to trigger LRU eviction
await request(`${origin}/first`)
await request(`${origin}/second`)
await request(`${origin}/third`)
const recorder = agent.getRecorder()
// Should only have 2 snapshots due to LRU eviction
assert.strictEqual(recorder.size(), TEST_CONSTANTS.MAX_SNAPSHOTS_FOR_LRU,
`Should only keep ${TEST_CONSTANTS.MAX_SNAPSHOTS_FOR_LRU} snapshots due to LRU eviction`)
const snapshots = recorder.getSnapshots()
const urls = snapshots.map(s => s.request.url)
// First snapshot should be evicted, should have second and third
assert(urls.includes(`${origin}/second`), 'Should contain second request')
assert(urls.includes(`${origin}/third`), 'Should contain third request')
assert(!urls.includes(`${origin}/first`), 'Should not contain first request (evicted)')
})
it('auto-flush functionality', async (t) => {
const server = createTestServer((req, res) => {
res.writeHead(200, { 'content-type': 'text/plain' })
res.end('Auto-flush test')
})
const { origin } = await setupServer(server)
const snapshotPath = createSnapshotPath('auto-flush')
setupCleanup(t, { server, snapshotPath })
const agent = new SnapshotAgent({
mode: 'record',
snapshotPath,
autoFlush: true,
flushInterval: TEST_CONSTANTS.AUTO_FLUSH_INTERVAL
})
const originalDispatcher = getGlobalDispatcher()
setupCleanup(t, { agent, originalDispatcher })
setGlobalDispatcher(agent)
// Make a request
await request(`${origin}/autoflush-test`)
// Wait for auto-flush to trigger and ensure it completes
await new Promise(resolve => setTimeout(resolve, TEST_CONSTANTS.SEQUENTIAL_RESPONSE_DELAY))
// Force a final flush to ensure all data is written
await agent.saveSnapshots()
// Verify file was written automatically
const fileData = await readFile(snapshotPath, 'utf8')
const snapshots = JSON.parse(fileData)
assert(Array.isArray(snapshots), 'Auto-flushed data should be an array')
assert.strictEqual(snapshots.length, 1, 'Should contain exactly one auto-flushed snapshot')
assert.strictEqual(snapshots[0].snapshot.request.url, `${origin}/autoflush-test`,
'Auto-flushed snapshot should have correct URL')
})
})
describe('SnapshotAgent - Header Management', () => {
it('custom header matching with matchHeaders', async (t) => {
const server = createTestServer((req, res) => {
res.writeHead(200, {
'content-type': 'application/json',
'x-request-id': '12345',
authorization: 'Bearer secret-token'
})
res.end('{"message": "test"}')
})
const { origin } = await setupServer(server)
const snapshotPath = createSnapshotPath('match-headers')
setupCleanup(t, { server, snapshotPath })
const agent = new SnapshotAgent({
mode: 'record',
snapshotPath,
matchHeaders: ['content-type'] // Only match on content-type header
})
const originalDispatcher = getGlobalDispatcher()
setupCleanup(t, { agent, originalDispatcher })
setGlobalDispatcher(agent)
// Make first request with authorization header
await request(`${origin}/test`, {
headers: {
authorization: 'Bearer secret-token',
'content-type': 'application/json'
}
})
// Save snapshots before switching to playback
await agent.saveSnapshots()
// Make second request with different authorization but same content-type
// This should match the first request due to matchHeaders config
const playbackAgent = new SnapshotAgent({
mode: 'playback',
snapshotPath,
matchHeaders: ['content-type']
})
setupCleanup(t, { agent: playbackAgent })
setGlobalDispatcher(playbackAgent)
const response = await request(`${origin}/test`, {
headers: {
authorization: 'Bearer different-token', // Different auth token
'content-type': 'application/json' // Same content-type
}
})
assert.strictEqual(response.statusCode, 200, 'Should match despite different auth token')
const body = await response.body.text()
assert.strictEqual(body, '{"message": "test"}', 'Should return recorded response')
})
it('ignore headers functionality', async (t) => {
const server = createTestServer((req, res) => {
res.writeHead(200, { 'content-type': 'text/plain' })
res.end('ignore headers test')
})
const { origin } = await setupServer(server)
const snapshotPath = createSnapshotPath('ignore-headers')
setupCleanup(t, { server, snapshotPath })
const agent = new SnapshotAgent({
mode: 'record',
snapshotPath,
ignoreHeaders: ['authorization', 'x-request-id'] // Ignore these for matching
})
const originalDispatcher = getGlobalDispatcher()
setupCleanup(t, { agent, originalDispatcher })
setGlobalDispatcher(agent)
// Make first request
await request(`${origin}/test`, {
headers: {
authorization: 'Bearer token1',
'x-request-id': 'req-123',
'content-type': 'application/json'
}
})
// Save snapshots before switching to playback
await agent.saveSnapshots()
// Switch to playback mode and make request with different ignored headers
const playbackAgent = new SnapshotAgent({
mode: 'playback',
snapshotPath,
ignoreHeaders: ['authorization', 'x-request-id']
})
setupCleanup(t, { agent: playbackAgent })
setGlobalDispatcher(playbackAgent)
const response = await request(`${origin}/test`, {
headers: {
authorization: 'Bearer different-token', // Different (ignored)
'x-request-id': 'req-456', // Different (ignored)
'content-type': 'application/json' // Same (not ignored)
}
})
assert.strictEqual(response.statusCode, 200, 'Should match despite different ignored headers')
const body = await response.body.text()
assert.strictEqual(body, 'ignore headers test', 'Should return recorded response')
})
it('exclude headers for security', async (t) => {
const server = createTestServer((req, res) => {
res.writeHead(200, {
'content-type': 'application/json',
'set-cookie': 'session=secret123; HttpOnly',
authorization: 'Bearer server-token'
})
res.end('{"data": "sensitive"}')
})
const { origin } = await setupServer(server)
const snapshotPath = createSnapshotPath('exclude-headers')
setupCleanup(t, { server, snapshotPath })
const agent = new SnapshotAgent({
mode: 'record',
snapshotPath,
excludeHeaders: ['authorization', 'set-cookie'] // Don't store these sensitive headers
})
const originalDispatcher = getGlobalDispatcher()
setupCleanup(t, { agent, originalDispatcher })
setGlobalDispatcher(agent)
await request(`${origin}/test`)
await agent.saveSnapshots()
// Read snapshot file and verify sensitive headers are not stored
const fileData = await readFile(snapshotPath, 'utf8')
const snapshots = JSON.parse(fileData)
assert.strictEqual(snapshots.length, 1, 'Should contain exactly one snapshot')
const snapshot = snapshots[0].snapshot
// Verify excluded headers are not in stored response
assert(!snapshot.responses[0].headers.authorization, 'Authorization header should be excluded from storage')
assert(!snapshot.responses[0].headers['set-cookie'], 'Set-Cookie header should be excluded from storage')
assert(snapshot.responses[0].headers['content-type'], 'Content-Type header should be preserved')
})
})
describe('SnapshotAgent - Request Matching', () => {
it('query parameter matching control', async (t) => {
const server = createTestServer((req, res) => {
res.writeHead(200, { 'content-type': 'text/plain' })
res.end(`Response for ${req.url}`)
})
const { origin } = await setupServer(server)
const snapshotPath = createSnapshotPath('query-matching')
setupCleanup(t, { server, snapshotPath })
const agent = new SnapshotAgent({
mode: 'record',
snapshotPath,
matchQuery: false // Ignore query parameters in matching
})
const originalDispatcher = getGlobalDispatcher()
setupCleanup(t, { agent, originalDispatcher })
setGlobalDispatcher(agent)
// Record request with query parameters
await request(`${origin}/api/data?timestamp=123&session=abc`)
// Save snapshots before switching to playback
await agent.saveSnapshots()
// Switch to playback with different query parameters
const playbackAgent = new SnapshotAgent({
mode: 'playback',
snapshotPath,
matchQuery: false
})
setupCleanup(t, { agent: playbackAgent })
setGlobalDispatcher(playbackAgent)
// This should match the recorded request despite different query params
const response = await request(`${origin}/api/data?timestamp=456&session=xyz`)
assert.strictEqual(response.statusCode, 200, 'Should match despite different query parameters')
const body = await response.body.text()
assert.strictEqual(body, 'Response for /api/data?timestamp=123&session=abc',
'Should return original recorded response with original query params')
})
it('normalizeQuery function for partial query matching', async (t) => {
const server = createTestServer((req, res) => {
res.writeHead(200, { 'content-type': 'application/json' })
res.end(JSON.stringify({ url: req.url }))
})
const { origin } = await setupServer(server)
const snapshotPath = createSnapshotPath('normalize-query')
setupCleanup(t, { server, snapshotPath })
// Strip the volatile '_cb' cache-buster param before matching
const normalizeQuery = (params) => {
const copy = new URLSearchParams(params)
copy.delete('_cb')
return copy.toString()
}
const agent = new SnapshotAgent({ mode: 'record', snapshotPath, normalizeQuery })
const originalDispatcher = getGlobalDispatcher()
setupCleanup(t, { agent, originalDispatcher })
setGlobalDispatcher(agent)
await request(`${origin}/api/data?filter=active&_cb=111`)
await agent.saveSnapshots()
// Playback with a different cache-buster — should still match
const playbackAgent = new SnapshotAgent({ mode: 'playback', snapshotPath, normalizeQuery })
setupCleanup(t, { agent: playbackAgent })
setGlobalDispatcher(playbackAgent)
const response = await request(`${origin}/api/data?filter=active&_cb=999`)
assert.strictEqual(response.statusCode, 200, 'Should match snapshot despite different cache-buster')
// Different filter value — should NOT match
await assert.rejects(
() => request(`${origin}/api/data?filter=inactive&_cb=111`),
/No snapshot found/,
'Should not match snapshot with different filter value'
)
})
it('body matching control', async (t) => {
const server = createTestServer((req, res) => {
let body = ''
req.on('data', chunk => { body += chunk })
req.on('end', async (t) => {
res.writeHead(200, { 'content-type': 'application/json' })
res.end(`{"received": "${body}"}`)
})
})
const { origin } = await setupServer(server)
const snapshotPath = createSnapshotPath('body-matching')
setupCleanup(t, { server, snapshotPath })
const agent = new SnapshotAgent({
mode: 'record',
snapshotPath,
matchBody: false // Ignore request body in matching
})
const originalDispatcher = getGlobalDispatcher()
setupCleanup(t, { agent, originalDispatcher })
setGlobalDispatcher(agent)
// Record request with specific body
await request(`${origin}/api/submit`, {
method: 'POST',
body: 'original-data',
headers: { 'content-type': 'text/plain' }
})
// Save snapshots before switching to playback
await agent.saveSnapshots()
// Switch to playback with different body
const playbackAgent = new SnapshotAgent({
mode: 'playback',
snapshotPath,
matchBody: false
})
setupCleanup(t, { agent: playbackAgent })
setGlobalDispatcher(playbackAgent)
// This should match despite different body content
const response = await request(`${origin}/api/submit`, {
method: 'POST',
body: 'different-data',
headers: { 'content-type': 'text/plain' }
})
assert.strictEqual(response.statusCode, 200, 'Should match despite different request body')
const responseBody = await response.body.json()
assert.strictEqual(responseBody.received, 'original-data',
'Should return recorded response with original body')
})
it('normalizeBody function for partial body matching', async (t) => {
const server = createTestServer((req, res) => {
let body = ''