-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathruntime.spec.js
More file actions
694 lines (599 loc) · 23.9 KB
/
Copy pathruntime.spec.js
File metadata and controls
694 lines (599 loc) · 23.9 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
const { describe, it, expect, beforeAll } = require('@jest/globals');
const TestRuntime = require('../src/runtime/test-runtime');
const ScriptRuntime = require('../src/runtime/script-runtime');
const AssertRuntime = require('../src/runtime/assert-runtime');
const { loader: quickJsLoader } = require('../src/sandbox/quickjs');
describe('runtime', () => {
describe('test-runtime', () => {
const baseRequest = {
method: 'GET',
url: 'http://localhost:3000/',
headers: {},
data: undefined
};
const baseResponse = {
status: 200,
statusText: 'OK',
data: [
{
id: 1
},
{
id: 2
},
{
id: 3
}
]
};
it('should wait async tests', async () => {
const testFile = `
await test('async test', ()=> {
return new Promise((resolve)=> {
setTimeout(()=> {resolve()},200)
})
})
`;
const runtime = new TestRuntime({ runtime: 'nodevm' });
const result = await runtime.runTests(
testFile,
{ ...baseRequest },
{ ...baseResponse },
{},
{},
'.',
null,
process.env
);
expect(result.results.map((el) => ({ description: el.description, status: el.status }))).toEqual([
{ description: 'async test', status: 'pass' }
]);
});
it('should have ajv and ajv-formats dependencies available', async () => {
const testFile = `
const Ajv = require('ajv');
const addFormats = require("ajv-formats");
const ajv = new Ajv();
addFormats(ajv);
const schema = {
type: 'string',
format: 'date-time'
};
const validate = ajv.compile(schema)
test('format valid', () => {
const valid = validate(new Date().toISOString())
expect(valid).to.be.true;
})
`;
const runtime = new TestRuntime({ runtime: 'nodevm' });
const result = await runtime.runTests(
testFile,
{ ...baseRequest },
{ ...baseResponse },
{},
{},
'.',
null,
process.env
);
expect(result.results.map((el) => ({ description: el.description, status: el.status }))).toEqual([
{ description: 'format valid', status: 'pass' }
]);
});
it('should return stopExecution when bru.runner.stopExecution() is called in tests (nodevm)', async () => {
const testFile = `bru.runner.stopExecution();`;
const runtime = new TestRuntime({ runtime: 'nodevm' });
const result = await runtime.runTests(
testFile,
{ ...baseRequest },
{ ...baseResponse },
{},
{},
'.',
null,
process.env
);
expect(result.stopExecution).toBe(true);
});
it('should return stopExecution when bru.runner.stopExecution() is called in tests (quickjs)', async () => {
const testFile = `bru.runner.stopExecution();`;
const runtime = new TestRuntime({ runtime: 'quickjs' });
const onConsoleLog = () => {};
const result = await runtime.runTests(
testFile,
{ ...baseRequest },
{ ...baseResponse },
{},
{},
'.',
onConsoleLog,
process.env
);
expect(result.stopExecution).toBe(true);
});
it('should not set stopExecution when bru.runner.stopExecution() is not called', async () => {
const testFile = `test('noop', () => { expect(true).to.be.true; });`;
const runtime = new TestRuntime({ runtime: 'nodevm' });
const result = await runtime.runTests(
testFile,
{ ...baseRequest },
{ ...baseResponse },
{},
{},
'.',
null,
process.env
);
expect(result.stopExecution).toBeFalsy();
});
});
describe('script-runtime', () => {
describe('run-request-script', () => {
const baseRequest = {
method: 'GET',
url: 'http://localhost:3000/',
headers: {},
data: undefined
};
it('should have ajv and ajv-formats dependencies available', async () => {
const script = `
const Ajv = require('ajv');
const addFormats = require("ajv-formats");
const ajv = new Ajv();
addFormats(ajv);
const schema = {
type: 'string',
format: 'date-time'
};
const validate = ajv.compile(schema)
bru.setVar('validation', validate(new Date().toISOString()))
`;
const runtime = new ScriptRuntime({ runtime: 'nodevm' });
const result = await runtime.runRequestScript(script, { ...baseRequest }, {}, {}, '.', null, process.env);
expect(result.runtimeVariables.validation).toBeTruthy();
});
it('should return variable updates made in req.onFail', async () => {
const script = `
bru.setVar('runtimeToken', 'before');
bru.setEnvVar('environmentToken', 'before');
bru.setGlobalEnvVar('globalToken', 'before');
req.onFail(() => {
bru.setVar('runtimeToken', 'after');
bru.setEnvVar('environmentToken', 'after');
bru.setGlobalEnvVar('globalToken', 'after');
});
`;
const request = { ...baseRequest };
const runtime = new ScriptRuntime({ runtime: 'nodevm' });
await runtime.runRequestScript(script, request, {}, {}, '.', null, process.env);
const result = await request.onFailHandler(new Error('Connection failed'));
expect(result.runtimeVariables.runtimeToken).toBe('after');
expect(result.envVariables.environmentToken).toBe('after');
expect(result.globalEnvironmentVariables.globalToken).toBe('after');
});
describe.each(['nodevm', 'quickjs'])('URL helpers with variables (%s)', (runtimeName) => {
const onConsoleLog = () => {};
beforeAll(async () => {
if (runtimeName === 'quickjs') {
await quickJsLoader();
}
});
it('should resolve variables in req.getHost(), req.getPath() and req.getQueryString()', async () => {
const script = `
bru.setVar('resolvedHost', req.getHost());
bru.setVar('resolvedPath', req.getPath());
bru.setVar('resolvedQueryString', req.getQueryString());
`;
const request = { ...baseRequest, url: '{{HOST}}/test?page=1' };
const envVariables = { HOST: 'https://example.com' };
const runtime = new ScriptRuntime({ runtime: runtimeName });
const result = await runtime.runRequestScript(script, request, envVariables, {}, '.', onConsoleLog, process.env);
expect(result.runtimeVariables.resolvedHost).toBe('example.com');
expect(result.runtimeVariables.resolvedPath).toBe('/test');
expect(result.runtimeVariables.resolvedQueryString).toBe('page=1');
expect(request.url).toBe('{{HOST}}/test?page=1');
});
it('should resolve variables set earlier in the same script', async () => {
const script = `
bru.setVar('HOST', 'https://api.example.com');
bru.setVar('resolvedHost', req.getHost());
`;
const request = { ...baseRequest, url: '{{HOST}}/test' };
const runtime = new ScriptRuntime({ runtime: runtimeName });
const result = await runtime.runRequestScript(script, request, {}, {}, '.', onConsoleLog, process.env);
expect(result.runtimeVariables.resolvedHost).toBe('api.example.com');
});
});
});
describe('run-response-script', () => {
const baseRequest = {
method: 'GET',
url: 'http://localhost:3000/',
headers: {},
data: undefined
};
const baseResponse = {
status: 200,
statusText: 'OK',
data: [
{
id: 1
},
{
id: 2
},
{
id: 3
}
]
};
it('should have ajv and ajv-formats dependencies available', async () => {
const script = `
const Ajv = require('ajv');
const addFormats = require("ajv-formats");
const ajv = new Ajv();
addFormats(ajv);
const schema = {
type: 'string',
format: 'date-time'
};
const validate = ajv.compile(schema)
bru.setVar('validation', validate(new Date().toISOString()))
`;
const runtime = new ScriptRuntime({ runtime: 'nodevm' });
const result = await runtime.runResponseScript(
script,
{ ...baseRequest },
{ ...baseResponse },
{},
{},
'.',
null,
process.env
);
expect(result.runtimeVariables.validation).toBeTruthy();
});
});
});
describe('environment variables from scripts', () => {
it('should allow any value type', async () => {
const script = `
bru.setEnvVar('str', 'hello');
bru.setEnvVar('number', 42);
bru.setEnvVar('boolean', true);
bru.setEnvVar('object', {key: 'value'});
bru.setEnvVar('array', [1, 2, 3]);
`;
const runtime = new ScriptRuntime({ runtime: 'nodevm' });
const result = await runtime.runRequestScript(script, {}, {}, {}, '.', null, process.env);
expect(result.envVariables.str).toBe('hello');
expect(result.envVariables.number).toBe(42);
expect(result.envVariables.boolean).toBe(true);
expect(result.envVariables.object).toEqual({ key: 'value' });
expect(result.envVariables.array).toEqual([1, 2, 3]);
});
it('should preserve typed values through the QuickJS shim', async () => {
await quickJsLoader();
const script = `
bru.setEnvVar('num', 42);
bru.setEnvVar('bool', true);
bru.setEnvVar('obj', { key: 'value' });
bru.setCollectionVar('collNum', 7);
bru.setGlobalEnvVar('globalBool', false);
`;
const runtime = new ScriptRuntime({ runtime: 'quickjs' });
const onConsoleLog = () => {};
const result = await runtime.runRequestScript(script, {}, {}, {}, '.', onConsoleLog, process.env);
expect(typeof result.envVariables.num).toBe('number');
expect(result.envVariables.num).toBe(42);
expect(typeof result.envVariables.bool).toBe('boolean');
expect(result.envVariables.bool).toBe(true);
expect(typeof result.envVariables.obj).toBe('object');
expect(result.envVariables.obj).toEqual({ key: 'value' });
expect(typeof result.collectionVariables.collNum).toBe('number');
expect(result.collectionVariables.collNum).toBe(7);
expect(typeof result.globalEnvironmentVariables.globalBool).toBe('boolean');
expect(result.globalEnvironmentVariables.globalBool).toBe(false);
});
it('should return null for scopes the script did not touch (dirty-flag gating)', async () => {
const script = `bru.setEnvVar('only_env', 'val');`;
const runtime = new ScriptRuntime({ runtime: 'nodevm' });
const result = await runtime.runRequestScript(script, {}, {}, {}, '.', null, process.env);
expect(result.envVariables).not.toBeNull();
expect(result.envVariables.only_env).toBe('val');
expect(result.collectionVariables).toBeNull();
expect(result.globalEnvironmentVariables).toBeNull();
});
it('should return null for scopes the script did not touch — QuickJS parity', async () => {
await quickJsLoader();
const script = `bru.setEnvVar('only_env', 'val');`;
const runtime = new ScriptRuntime({ runtime: 'quickjs' });
const onConsoleLog = () => {};
const result = await runtime.runRequestScript(script, {}, {}, {}, '.', onConsoleLog, process.env);
expect(result.envVariables).not.toBeNull();
expect(result.envVariables.only_env).toBe('val');
expect(result.collectionVariables).toBeNull();
expect(result.globalEnvironmentVariables).toBeNull();
});
it('should include collectionVariables in result', async () => {
const script = `bru.setCollectionVar('myVar', 'myValue');`;
const runtime = new ScriptRuntime({ runtime: 'nodevm' });
const result = await runtime.runRequestScript(script, {}, {}, {}, '.', null, process.env);
expect(result.collectionVariables).toBeDefined();
expect(result.collectionVariables.myVar).toBe('myValue');
});
it('should silently ignore old persist flag as extra argument', async () => {
const scriptTrue = `bru.setEnvVar('key1', 'val1', { persist: true });`;
const scriptFalse = `bru.setEnvVar('key2', 'val2', { persist: false });`;
const runtime = new ScriptRuntime({ runtime: 'nodevm' });
const result1 = await runtime.runRequestScript(scriptTrue, {}, {}, {}, '.', null, process.env);
expect(result1.envVariables.key1).toBe('val1');
const result2 = await runtime.runRequestScript(scriptFalse, {}, {}, {}, '.', null, process.env);
expect(result2.envVariables.key2).toBe('val2');
});
it('should silently ignore old persist flag as extra argument — QuickJS parity', async () => {
await quickJsLoader();
const scriptTrue = `bru.setEnvVar('key1', 'val1', { persist: true });`;
const scriptFalse = `bru.setEnvVar('key2', 'val2', { persist: false });`;
const runtime = new ScriptRuntime({ runtime: 'quickjs' });
const onConsoleLog = () => {};
const result1 = await runtime.runRequestScript(scriptTrue, {}, {}, {}, '.', onConsoleLog, process.env);
expect(result1.envVariables.key1).toBe('val1');
const result2 = await runtime.runRequestScript(scriptFalse, {}, {}, {}, '.', onConsoleLog, process.env);
expect(result2.envVariables.key2).toBe('val2');
});
});
describe('bru.setVar random variable', () => {
it('should be able to set random variables as values', async () => {
const script = `bru.setVar('title', '{{$randomFirstName}}')`;
const runtime = new ScriptRuntime({ runtime: 'nodevm' });
const result = await runtime.runRequestScript(script, {}, {}, {}, '.', null, process.env);
expect(result.runtimeVariables.title).toBe('{{$randomFirstName}}');
});
});
describe('assert-runtime', () => {
beforeAll(async () => {
await quickJsLoader();
});
const baseRequest = {
method: 'GET',
url: 'http://localhost:3000/',
headers: {},
data: undefined
};
const makeResponse = (data) => ({
status: 200,
statusText: 'OK',
data,
headers: {}
});
const runAssertions = (assertions, response, runtime = 'nodevm', runtimeVariables = {}) => {
const assertRuntime = new AssertRuntime({ runtime });
return assertRuntime.runAssertions(assertions, { ...baseRequest }, response, {}, runtimeVariables, process.env);
};
// Ensures each QuickJS evaluation gets a fresh context
describe('quickjs context isolation across iterations', () => {
const ITERATION_COUNT = 350;
it('should return correct res.status on every iteration', () => {
for (let i = 0; i < ITERATION_COUNT; i++) {
const status = 200 + i;
const results = runAssertions(
[{ name: 'res.status', value: `eq ${status}`, enabled: true }],
{ status, statusText: 'OK', data: {}, headers: {} },
'quickjs'
);
expect(results[0].status).toBe('pass');
}
});
it('should return correct res.body values on every iteration', () => {
for (let i = 0; i < ITERATION_COUNT; i++) {
const results = runAssertions(
[{ name: 'res.body.id', value: `eq ${i}`, enabled: true }],
{ status: 200, statusText: 'OK', data: { id: i }, headers: {} },
'quickjs'
);
expect(results[0].status).toBe('pass');
}
});
it('should not return stale data from a previous iteration', () => {
// First call with status 200
runAssertions(
[{ name: 'res.status', value: 'eq 200', enabled: true }],
{ status: 200, statusText: 'OK', data: { token: 'bearer_abc' }, headers: { authorization: 'bearer xyz' } },
'quickjs'
);
// Second call with status 404 — must not return 200 or any data from previous call
const results = runAssertions(
[
{ name: 'res.status', value: 'eq 404', enabled: true },
{ name: 'res.body.error', value: 'eq not_found', enabled: true }
],
{ status: 404, statusText: 'Not Found', data: { error: 'not_found' }, headers: {} },
'quickjs'
);
expect(results[0].status).toBe('pass');
expect(results[1].status).toBe('pass');
});
it('should not persist runtime variables from a previous call', () => {
// First call with runtime variable token = "one"
const results1 = runAssertions(
[{ name: 'token', value: 'eq one', enabled: true }],
{ status: 200, statusText: 'OK', data: {}, headers: {} },
'quickjs',
{ token: 'one' }
);
expect(results1[0].status).toBe('pass');
// Second call without token
const results2 = runAssertions(
[{ name: 'token', value: 'eq one', enabled: true }],
{ status: 200, statusText: 'OK', data: {}, headers: {} },
'quickjs'
);
// Must fail — token should not exist in a fresh context
expect(results2[0].status).toBe('fail');
});
});
describe('isJson', () => {
it('should pass for a plain object', () => {
const results = runAssertions(
[{ name: 'res.body', value: 'isJson', enabled: true }],
makeResponse({ id: 1, name: 'test' })
);
expect(results[0].status).toBe('pass');
});
it('should pass for a nested object', () => {
const results = runAssertions(
[{ name: 'res.body', value: 'isJson', enabled: true }],
makeResponse({ user: { id: 1, tags: ['a', 'b'] } })
);
expect(results[0].status).toBe('pass');
});
it('should pass for objects from a different realm (e.g. after res.setBody in node-vm)', async () => {
const response = makeResponse({ id: 1, name: 'original' });
// res.setBody() inside node-vm creates a cross-realm object whose
// constructor is the VM's Object, not the host's Object
const scriptRuntime = new ScriptRuntime({ runtime: 'nodevm' });
await scriptRuntime.runResponseScript(
`res.setBody({ id: 2, name: 'updated' });`,
{ ...baseRequest },
response,
{}, {}, '.', null, process.env
);
const results = runAssertions(
[{ name: 'res.body', value: 'isJson', enabled: true }],
response
);
expect(results[0].status).toBe('pass');
});
it('should pass for an array', () => {
const results = runAssertions(
[{ name: 'res.body', value: 'isJson', enabled: true }],
makeResponse([1, 2, 3])
);
expect(results[0].status).toBe('pass');
});
it('should pass for an array of strings', () => {
const results = runAssertions(
[{ name: 'res.body', value: 'isJson', enabled: true }],
makeResponse(['A55001213ZX0A'])
);
expect(results[0].status).toBe('pass');
});
it('should pass for an empty array', () => {
const results = runAssertions(
[{ name: 'res.body', value: 'isJson', enabled: true }],
makeResponse([])
);
expect(results[0].status).toBe('pass');
});
it('should pass for an array of objects', () => {
const results = runAssertions(
[{ name: 'res.body', value: 'isJson', enabled: true }],
makeResponse([{ id: 1 }, { id: 2 }])
);
expect(results[0].status).toBe('pass');
});
it('should fail for a string', () => {
const results = runAssertions(
[{ name: 'res.body', value: 'isJson', enabled: true }],
makeResponse('hello')
);
expect(results[0].status).toBe('fail');
});
it('should fail for null', () => {
const results = runAssertions(
[{ name: 'res.body', value: 'isJson', enabled: true }],
makeResponse(null)
);
expect(results[0].status).toBe('fail');
});
});
describe('jsonSchema', () => {
const chai = require('chai');
it('should pass when body matches a valid schema', () => {
const body = { name: 'John', age: 30 };
const schema = {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'number' }
},
required: ['name', 'age']
};
chai.expect(body).to.have.jsonSchema(schema);
});
it('should fail when body has a type mismatch', () => {
const body = { name: 'John', age: 'thirty' };
const schema = {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'number' }
},
required: ['name', 'age']
};
expect(() => chai.expect(body).to.have.jsonSchema(schema)).toThrow(/validation errors/);
});
it('should fail when a required field is missing', () => {
const body = { name: 'John' };
const schema = {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'number' }
},
required: ['name', 'age']
};
expect(() => chai.expect(body).to.have.jsonSchema(schema)).toThrow(/validation errors/);
});
it('should pass with custom ajvOptions', () => {
const body = { name: 'John', age: 30 };
const schema = {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'number' }
},
required: ['name', 'age']
};
chai.expect(body).to.have.jsonSchema(schema, { allErrors: false });
});
it('should support negation with .not', () => {
const body = { name: 'John' };
const schema = { type: 'array' };
chai.expect(body).to.not.have.jsonSchema(schema);
});
it('should throw a clear error for unsupported Draft 2020-12 $schema', () => {
const body = { name: 'John' };
const schema = {
$schema: 'https://json-schema.org/draft/2020-12/schema',
type: 'object',
properties: { name: { type: 'string' } }
};
expect(() => chai.expect(body).to.have.jsonSchema(schema)).toThrow(/Unsupported JSON Schema version.*2020-12.*only supports Draft-07/);
});
it('should throw a clear error for unsupported Draft 2019-09 $schema', () => {
const body = { name: 'John' };
const schema = {
$schema: 'https://json-schema.org/draft/2019-09/schema',
type: 'object',
properties: { name: { type: 'string' } }
};
expect(() => chai.expect(body).to.have.jsonSchema(schema)).toThrow(/Unsupported JSON Schema version.*2019-09.*only supports Draft-07/);
});
it('should allow explicit Draft-07 $schema', () => {
const body = { name: 'John', age: 30 };
const schema = {
$schema: 'http://json-schema.org/draft-07/schema#',
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'number' }
},
required: ['name', 'age']
};
chai.expect(body).to.have.jsonSchema(schema);
});
});
});
});