forked from jsonata-js/jsonata
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimplementation-tests.js
891 lines (817 loc) · 33.8 KB
/
implementation-tests.js
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
/**
* © Copyright IBM Corp. 2016 All Rights Reserved
* Project name: JSONata
* This project is licensed under the MIT License, see LICENSE
*
* The files in this directory are tests that aren't really portable
* to other implementations for various reasons but they are included
* in order to achieve 100% coverage for this implementation.
*/
"use strict";
var jsonata = require("../src/jsonata");
var chai = require("chai");
var expect = chai.expect;
var testdata1 = {
"foo": {
"bar": 42,
"blah": [{"baz": {"fud": "hello"}}, {"baz": {"fud": "world"}}, {"bazz": "gotcha"}],
"blah.baz": "here"
}, "bar": 98
};
var testdata2 = {
Account: {
"Account Name": "Firefly",
Order: [
{
OrderID: "order103",
Product: [
{
"Product Name": "Bowler Hat",
ProductID: 858383,
SKU: "0406654608",
Description: {
Colour: "Purple",
Width: 300,
Height: 200,
Depth: 210,
Weight: 0.75
},
Price: 34.45,
Quantity: 2
},
{
"Product Name": "Trilby hat",
ProductID: 858236,
SKU: "0406634348",
Description: {
Colour: "Orange",
Width: 300,
Height: 200,
Depth: 210,
Weight: 0.6
},
Price: 21.67,
Quantity: 1
}
]
},
{
OrderID: "order104",
Product: [
{
"Product Name": "Bowler Hat",
ProductID: 858383,
SKU: "040657863",
Description: {
Colour: "Purple",
Width: 300,
Height: 200,
Depth: 210,
Weight: 0.75
},
Price: 34.45,
Quantity: 4
},
{
ProductID: 345664,
SKU: "0406654603",
"Product Name": "Cloak",
Description: {
Colour: "Black",
Width: 30,
Height: 20,
Depth: 210,
Weight: 2.0
},
Price: 107.99,
Quantity: 1
}
]
}
]
}
};
describe("Functions with side-effects", () => {
describe("Evaluator - function: millis", function() {
describe("$millis() returns milliseconds since the epoch", function() {
it("should return result object", function() {
var expr = jsonata("$millis()");
var result = expr.evaluate(testdata2);
// number between 1502264152715 and 2000000000000 (18 May 2033)
var expected = result > 1502264152715 && result < 2000000000000;
expect(expected).to.deep.equal(true);
});
});
describe("$millis() always returns same value within an expression", function() {
it("should return result object", function() {
var expr = jsonata('{"now": $millis(), "delay": $sum([1..10000]), "later": $millis()}.(now = later)');
var result = expr.evaluate(testdata2);
var expected = true;
expect(result).to.deep.equal(expected);
});
});
describe("$millis() returns different timestamp for subsequent evaluate() calls", function() {
it("should return result object", function() {
var expr = jsonata("($sum([1..10000]); $millis())");
var result = expr.evaluate(testdata2);
var result2 = expr.evaluate(testdata2);
expect(result).to.not.equal(result2);
});
});
});
describe("$now() returns timestamp", function() {
it("should return result object", function() {
var expr = jsonata("$now()");
var result = expr.evaluate(testdata2);
// follows this pattern - "2017-05-09T10:10:16.918Z"
expect(result).to.match(/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d\d\dZ$/);
// var match = /^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d\d\dZ$/.test(result);
// expect(match).to.deep.equal(true);
});
});
describe("$now() returns timestamp with defined format", function() {
it("should return result object", function() {
var expr = jsonata("$now('[h]:[M01][P] [z]')");
var result = expr.evaluate(testdata2);
// follows this pattern - "10:23am GMT+00:00"
expect(result).to.match(/^\d?\d:\d\d[ap]m GMT\+00:00$/);
});
});
describe("$now() returns timestamp with defined format and timezone", function() {
it("should return result object", function() {
var expr = jsonata("$now('[h]:[M01][P] [z]', '-0500')");
var result = expr.evaluate(testdata2);
// follows this pattern - "10:23am GMT-05:00"
expect(result).to.match(/^\d?\d:\d\d[ap]m GMT-05:00$/);
});
});
describe("$now() always returns same value within an expression", function() {
it("should return result object", function() {
var expr = jsonata('{"now": $now(), "delay": $sum([1..10000]), "later": $now()}.(now = later)');
var result = expr.evaluate(testdata2);
var expected = true;
expect(result).to.deep.equal(expected);
});
});
describe("$now() returns different timestamp for subsequent evaluate() calls", function() {
it("should return result object", function() {
var expr = jsonata("($sum([1..10000]); $now())");
var result = expr.evaluate(testdata2);
var result2 = expr.evaluate(testdata2);
expect(result).to.not.equal(result2);
});
});
describe("$millis() returns milliseconds since the epoch", function() {
it("should return result object", function() {
var expr = jsonata("$millis()");
var result = expr.evaluate(testdata2);
// number between 1502264152715 and 2000000000000 (18 May 2033)
var expected = result > 1502264152715 && result < 2000000000000;
expect(expected).to.deep.equal(true);
});
});
describe("Evaluator - functions: random", function() {
describe('random number")', function() {
it("should return result object", function() {
var expr = jsonata("$random()");
var result = expr.evaluate();
var expected = result >= 0 && result < 1;
expect(true).to.deep.equal(expected);
});
});
describe('consequetive random numbers should be different")', function() {
it("should return result object", function() {
var expr = jsonata("$random() = $random()");
var result = expr.evaluate();
var expected = false;
expect(result).to.deep.equal(expected);
});
});
});
});
describe("Tests that rely on JavaScript-style object traversal", () => {
// A JSON object is an unordered list of key-value pairs.
// When traversing an object, the entries may be returned
// in a non-deterministic order (depending on the language).
// The following tests assume a traversal order which works
// in JavaScript but may not apply to other languages.
// See https://github.com/jsonata-js/jsonata/issues/179.
describe('foo.*[0]', function () {
it('should return result object', function () {
var expr = jsonata('foo.*[0]');
var result = expr.evaluate(testdata1);
var expected = 42;
expect(result).to.deep.equal(expected);
});
});
describe('**[2]', function () {
it('should return result object', function () {
var expr = jsonata('**[2]');
var result = expr.evaluate(testdata2);
var expected = "Firefly";
expect(result).to.deep.equal(expected);
});
});
});
describe("Tests that use the $clone() function", () => {
// $clone() allows jsonata-js to play nicely with Node-RED.
// It's not part of the JSONata standard.
// See https://github.com/jsonata-js/jsonata/issues/207.
describe('clone undefined', function () {
it('should return undefined', function () {
var expr = jsonata('$clone(foo)');
var result = expr.evaluate(testdata2);
var expected = undefined;
expect(result).to.deep.equal(expected);
});
});
describe('clone empty object', function () {
it('should return empty object', function () {
var expr = jsonata('$clone({})');
var result = expr.evaluate(testdata2);
var expected = {};
expect(result).to.deep.equal(expected);
});
});
describe('clone object', function () {
it('should return same object', function () {
var expr = jsonata('$clone({"a": 1})');
var result = expr.evaluate(testdata2);
var expected = {"a": 1};
expect(result).to.deep.equal(expected);
});
});
describe("transform expression with overridden $clone function", function() {
it("should return result object", function() {
var expr = jsonata('Account ~> |Order|{"Product":"blah"},nomatch|');
var count = 0;
expr.registerFunction("clone", function(arg) {
count++;
return JSON.parse(JSON.stringify(arg));
});
var result = expr.evaluate(testdata2);
var expected = {
"Account Name": "Firefly",
Order: [
{
OrderID: "order103",
Product: "blah"
},
{
OrderID: "order104",
Product: "blah"
}
]
};
expect(result).to.deep.equal(expected);
expect(count).to.equal(1);
});
});
describe('transform expression with overridden $clone value', function () {
it('should throw error', function () {
var expr = jsonata('( $clone := 5; $ ~> |Account.Order.Product|{"blah":"foo"}| )');
expect(function () {
expr.evaluate(testdata2);
})
.to.throw()
.to.deep.contain({ code: 'T2013' });
});
});
});
describe("Tests that bind Javascript functions", () => {
// These involve binding of functions
describe("Override implementation of $now()", function() {
it("should return result object", function() {
var expr = jsonata("$now()");
expr.registerFunction("now", function() {
return "time for tea";
});
var result = expr.evaluate(testdata2);
expect(result).to.equal("time for tea");
});
});
// Issue #261. Previously we would attempt to assign to the read-only `message` property,
// causing an unrelated `TypeError` to be thrown instead
describe("function throws a `DOMException` with a read-only `message` property", function() {
/**
* `DOMException` is not available in our testing environment. Additionally, we can't
* just import the `domexception` module since it doesn't work on Node.js v4, which
* we still support. So, here's a fake skeleton implementation which has the relevant
* qualities we need to reproduce the bug, most importantly a read-only `message`
* property
* @param {string} message - Error message
* @constructor
*/
function DOMException (message) {
Object.defineProperty(this, "message", {
get() {
return message;
},
enumerable: true,
configurable: true
});
}
Object.setPrototypeOf(DOMException.prototype, Error.prototype);
it("rethrows correctly", function() {
var expr = jsonata("$throwDomEx()");
expr.registerFunction("throwDomEx", function() {
throw new DOMException('Here is my message');
});
expect(function () {
expr.evaluate({});
})
.to.throw(DOMException)
.to.deep.contain({ message: 'Here is my message', position: 12, token: 'throwDomEx' });
});
});
describe("map a user-defined Javascript function with signature", function() {
it("should return result object", function() {
var expr = jsonata("$map([1,4,9,16], $squareroot)");
expr.registerFunction(
"squareroot",
function(num) {
return Math.sqrt(num);
},
"<n:n>"
);
var result = expr.evaluate(testdata2);
var expected = [1, 2, 3, 4];
expect(result).to.deep.equal(expected);
});
});
describe("map a user-defined Javascript function with undefined signature", function() {
it("should return result object", function() {
var expr = jsonata("$map([1,4,9,16], $squareroot)");
expr.registerFunction("squareroot", function(num) {
return Math.sqrt(num);
});
var result = expr.evaluate(testdata2);
var expected = [1, 2, 3, 4];
expect(result).to.deep.equal(expected);
});
});
describe("map a user-defined Javascript function", function() {
it("should return result object", function() {
var expr = jsonata("$map([1,4,9,16], $squareroot)");
expr.assign("squareroot", function(num) {
return Math.sqrt(num);
});
var result = expr.evaluate(testdata2);
var expected = [1, 2, 3, 4];
expect(result).to.deep.equal(expected);
});
});
describe("$filter with a user-defined Javascript function", function() {
it("should return result object", function() {
var expr = jsonata("$filter([1,4,9,16], $even)");
expr.assign("even", function(num) {
return num % 2 === 0;
});
var result = expr.evaluate(testdata2);
var expected = [4, 16];
expect(result).to.deep.equal(expected);
});
});
describe("$sift with a user-defined Javascript function", function() {
it("should return result object", function() {
var expr = jsonata("$sift({'one': 1, 'four': 4, 'nine': 9, 'sixteen': 16}, $even)");
expr.assign("even", function(num) {
return num % 2 === 0;
});
var result = expr.evaluate(testdata2);
var expected = {'four': 4, 'sixteen': 16};
expect(result).to.deep.equal(expected);
});
});
describe("$each with a user-defined Javascript function", function() {
it("should return result object", function() {
var expr = jsonata("$each({'one': 1, 'four': 4, 'nine': 9, 'sixteen': 16}, $squareroot)");
expr.assign("squareroot", function(num) {
return Math.sqrt(num);
});
var result = expr.evaluate(testdata2);
var expected = [1, 2, 3, 4];
expect(result).to.deep.equal(expected);
});
});
describe("Partially apply user-defined Javascript function", function() {
it("should return result object", function() {
var expr = jsonata(
"(" +
" $firstn := $substr(?, 0, ?);" +
" $first5 := $firstn(?, 5);" +
' $first5("Hello World")' +
")"
);
expr.assign("substr", function(str, start, len) {
return str.substr(start, len);
});
var result = expr.evaluate(testdata2);
var expected = "Hello";
expect(result).to.deep.equal(expected);
});
});
describe("User defined matchers", function() {
var repeatingLetters = function(char, repeat) {
// custom matcher to match `repeat` contiguous occurrences of `char`
var chars = char.repeat(repeat);
var match = function(str, offset) {
var pos = str.indexOf(chars, (offset || 0));
if (pos === -1) {
return;
} else {
return {
match: chars,
start: pos,
end: pos + chars.length,
groups: [],
next: function () {
return match(str, pos + chars.length);
}
};
}
};
return match;
};
it("should match using a custom matcher", function() {
var expr = jsonata("$match('LLANFAIRPWLLGWYNGYLLGOGERYCHWYRNDROBWLLLLANTYSILIOGOGOGOCH', $repeatingLetters('L', 2))");
expr.registerFunction("repeatingLetters", repeatingLetters);
var result = expr.evaluate();
var expected = [
{"match": "LL", "index": 0, "groups": []},
{"match": "LL", "index": 10, "groups": []},
{"match": "LL", "index": 18, "groups": []},
{"match": "LL", "index": 37, "groups": []},
{"match": "LL", "index": 39, "groups": []}
];
expect(result).to.deep.equal(expected);
});
it("should split using a custom matcher", function() {
var expr = jsonata("$split('LLANFAIRPWLLGWYNGYLLGOGERYCHWYRNDROBWLLLLANTYSILIOGOGOGOCH', $repeatingLetters('L', 2))");
expr.registerFunction("repeatingLetters", repeatingLetters);
var result = expr.evaluate();
var expected = ["","ANFAIRPW","GWYNGY","GOGERYCHWYRNDROBW","","ANTYSILIOGOGOGOCH"];
expect(result).to.deep.equal(expected);
});
it("should replace using a custom matcher", function() {
var expr = jsonata("$replace('LLANFAIRPWLLGWYNGYLLGOGERYCHWYRNDROBWLLLLANTYSILIOGOGOGOCH', $repeatingLetters('L', 2), 'Ỻ')");
expr.registerFunction("repeatingLetters", repeatingLetters);
var result = expr.evaluate();
var expected = "ỺANFAIRPWỺGWYNGYỺGOGERYCHWYRNDROBWỺỺANTYSILIOGOGOGOCH";
expect(result).to.deep.equal(expected);
});
it("should test inclusion using a custom matcher", function() {
var expr = jsonata("$contains('LLANFAIRPWLLGWYNGYLLGOGERYCHWYRNDROBWLLLLANTYSILIOGOGOGOCH', $repeatingLetters('L', 4))");
expr.registerFunction("repeatingLetters", repeatingLetters);
var result = expr.evaluate();
var expected = true;
expect(result).to.deep.equal(expected);
});
});
describe('User defined higher-order functions', () => {
var myfunc = function*(arr, fn) {
const val = yield * fn(arr);
return 2 * val;
};
var startsWith = function(str) {
// returns a function that returns true if its argument starts with the string `str`
return (arg) => {
return arg.startsWith(str);
};
};
it('should be able to invoke a built-in function passed as an argument', () => {
var expr = jsonata("$myfunc([1,2,3], $sum)");
expr.registerFunction('myfunc', myfunc);
var result = expr.evaluate();
var expected = 12;
expect(result).to.deep.equal(expected);
});
it('should be able to invoke a lambda function passed as an argument', () => {
var expr = jsonata("$myfunc([1,2,3], λ($arr) { $arr[1] + $arr[2] })");
expr.registerFunction('myfunc', myfunc);
var result = expr.evaluate();
var expected = 10;
expect(result).to.deep.equal(expected);
});
it('should be able to invoke a user-defined function passed as an argument', () => {
var expr = jsonata("$myfunc([1,2,3], $myfunc2)");
expr.registerFunction('myfunc', myfunc);
expr.registerFunction('myfunc2', (arr) => {
return 2 * arr[1];
});
var result = expr.evaluate();
var expected = 8;
expect(result).to.deep.equal(expected);
});
it('should be able to return a function from a user-defined function', () => {
var expr = jsonata(`
(
$startsWithHello := $startsWith("Hello");
[$startsWithHello("Hello, Bob"), $startsWithHello("Goodbye, Bill")]
)`);
expr.registerFunction('startsWith', startsWith);
var result = expr.evaluate();
var expected = [true, false];
expect(result).to.deep.equal(expected);
})
});
});
describe("Tests that are specific to a Javascript runtime", () => {
// Javascript specific
describe('/ab/ ("ab")', function() {
it("should return result object", function() {
var expr = jsonata('/ab/ ("ab")');
var result = expr.evaluate();
var expected = { match: "ab", start: 0, end: 2, groups: [] };
expect(JSON.stringify(result)).to.equal(JSON.stringify(expected));
});
});
describe("/ab/ ()", function() {
it("should return result object", function() {
var expr = jsonata("/ab/ ()");
var result = expr.evaluate();
var expected = undefined;
expect(JSON.stringify(result)).to.equal(JSON.stringify(expected));
});
});
describe('/ab+/ ("ababbabbcc")', function() {
it("should return result object", function() {
var expr = jsonata('/ab+/ ("ababbabbcc")');
var result = expr.evaluate();
var expected = { match: "ab", start: 0, end: 2, groups: [] };
expect(JSON.stringify(result)).to.equal(JSON.stringify(expected));
});
});
describe('/a(b+)/ ("ababbabbcc")', function() {
it("should return result object", function() {
var expr = jsonata('/a(b+)/ ("ababbabbcc")');
var result = expr.evaluate();
var expected = { match: "ab", start: 0, end: 2, groups: ["b"] };
expect(JSON.stringify(result)).to.equal(JSON.stringify(expected));
});
});
describe('/a(b+)/ ("ababbabbcc").next()', function() {
it("should return result object", function() {
var expr = jsonata('/a(b+)/ ("ababbabbcc").next()');
var result = expr.evaluate();
var expected = { match: "abb", start: 2, end: 5, groups: ["bb"] };
expect(JSON.stringify(result)).to.equal(JSON.stringify(expected));
});
});
describe('/a(b+)/ ("ababbabbcc").next().next()', function() {
it("should return result object", function() {
var expr = jsonata('/a(b+)/ ("ababbabbcc").next().next()');
var result = expr.evaluate();
var expected = { match: "abb", start: 5, end: 8, groups: ["bb"] };
expect(JSON.stringify(result)).to.equal(JSON.stringify(expected));
});
});
describe('/a(b+)/ ("ababbabbcc").next().next().next()', function() {
it("should return result object", function() {
var expr = jsonata('/a(b+)/ ("ababbabbcc").next().next().next()');
var result = expr.evaluate();
var expected = undefined;
expect(JSON.stringify(result)).to.equal(JSON.stringify(expected));
});
});
describe('/a(b+)/i ("Ababbabbcc")', function() {
it("should return result object", function() {
var expr = jsonata('/a(b+)/i ("Ababbabbcc")');
var result = expr.evaluate();
var expected = { match: "Ab", start: 0, end: 2, groups: ["b"] };
expect(JSON.stringify(result)).to.equal(JSON.stringify(expected));
});
});
describe("empty regex", function() {
it("should throw error", function() {
expect(function() {
var expr = jsonata("//");
expr.evaluate();
})
.to.throw()
.to.deep.contain({ position: 1, code: "S0301" });
});
});
describe("empty regex", function() {
it("should throw error", function() {
expect(function() {
var expr = jsonata("/");
expr.evaluate();
})
.to.throw()
.to.deep.contain({ position: 1, code: "S0302" });
});
});
describe("Functions - $match", function() {
describe('$match("ababbabbcc",/ab/)', function() {
it("should return result object", function() {
var expr = jsonata('$match("ababbabbcc",/ab/)');
var result = expr.evaluate();
var expected = [
{ match: "ab", index: 0, groups: [] },
{
match: "ab",
index: 2,
groups: []
},
{ match: "ab", index: 5, groups: [] }
];
expect(result).to.deep.equal(expected);
});
});
describe('$match("ababbabbcc",/a(b+)/)', function() {
it("should return result object", function() {
var expr = jsonata('$match("ababbabbcc",/a(b+)/)');
var result = expr.evaluate();
var expected = [
{ match: "ab", index: 0, groups: ["b"] },
{
match: "abb",
index: 2,
groups: ["bb"]
},
{ match: "abb", index: 5, groups: ["bb"] }
];
expect(result).to.deep.equal(expected);
});
});
describe('$match("ababbabbcc",/a(b+)/, 1)', function() {
it("should return result object", function() {
var expr = jsonata('$match("ababbabbcc",/a(b+)/, 1)');
var result = expr.evaluate();
var expected = { match: "ab", index: 0, groups: ["b"] };
expect(result).to.deep.equal(expected);
});
});
describe('$match("ababbabbcc",/a(b+)/, 0)', function() {
it("should return result object", function() {
var expr = jsonata('$match("ababbabbcc",/a(b+)/, 0)');
var result = expr.evaluate();
var expected = undefined;
expect(result).to.deep.equal(expected);
});
});
describe("$match(nothing,/a(xb+)/)", function() {
it("should return result object", function() {
var expr = jsonata("$match(nothing,/a(xb+)/)");
var result = expr.evaluate();
var expected = undefined;
expect(result).to.deep.equal(expected);
});
});
describe('$match("ababbabbcc",/a(xb+)/)', function() {
it("should return result object", function() {
var expr = jsonata('$match("ababbabbcc",/a(xb+)/)');
var result = expr.evaluate();
var expected = undefined;
expect(result).to.deep.equal(expected);
});
});
describe('$match("a, b, c, d", /ab/, -3)', function() {
it("should throw error", function() {
var expr = jsonata('$match("a, b, c, d", /ab/, -3)');
expect(function() {
expr.evaluate();
})
.to.throw()
.to.deep.contain({ position: 7, code: "D3040", token: "match", index: 3, value: -3 });
});
});
describe('$match("a, b, c, d", /ab/, null)', function() {
it("should throw error", function() {
var expr = jsonata('$match("a, b, c, d", /ab/, null)');
expect(function() {
expr.evaluate();
})
.to.throw()
.to.deep.contain({ position: 7, code: "T0410", token: "match", index: 3, value: null });
});
});
describe('$match("a, b, c, d", /ab/, "2")', function() {
it("should throw error", function() {
var expr = jsonata('$match("a, b, c, d", /ab/, "2")');
expect(function() {
expr.evaluate();
})
.to.throw()
.to.deep.contain({ position: 7, code: "T0410", token: "match", index: 3, value: "2" });
});
});
describe('$match("a, b, c, d", "ab")', function() {
it("should throw error", function() {
var expr = jsonata('$match("a, b, c, d", "ab")');
expect(function() {
expr.evaluate();
})
.to.throw()
.to.deep.contain({ position: 7, code: "T0410", token: "match", index: 2, value: "ab" });
});
});
describe('$match("a, b, c, d", true)', function() {
it("should throw error", function() {
var expr = jsonata('$match("a, b, c, d", true)');
expect(function() {
expr.evaluate();
})
.to.throw()
.to.deep.contain({ position: 7, code: "T0410", token: "match", index: 2, value: true });
});
});
describe("$match(12345, 3)", function() {
it("should throw error", function() {
var expr = jsonata("$match(12345, 3)");
expect(function() {
expr.evaluate();
})
.to.throw()
.to.deep.contain({ position: 7, code: "T0410", token: "match", index: 1, value: 12345 });
});
});
describe("$match(12345)", function() {
it("should throw error", function() {
var expr = jsonata("$match(12345)");
expect(function() {
expr.evaluate();
})
.to.throw()
.to.deep.contain({ position: 7, code: "T0410", token: "match", index: 1 });
});
});
});
});
describe("Test that yield platform specific results", () => {
// Platform specific
describe("$sqrt(10) * $sqrt(10)", function() {
it("should return result object", function() {
var expr = jsonata("$sqrt(10) * $sqrt(10)");
var result = expr.evaluate();
var expected = 10;
expect(result).to.be.closeTo(expected, 1e-13);
});
});
});
describe("Tests that include infinite recursion", () => {
describe("stack overflow - infinite recursive function - non-tail call", function() {
it("should throw error", function() {
expect(function() {
var expr = jsonata("(" + " $inf := function($n){$n+$inf($n-1)};" + " $inf(5)" + ")");
timeboxExpression(expr, 1000, 300);
expr.evaluate();
})
.to.throw()
.to.deep.contain({ token: "inf", position: 32, code: "U1001" });
});
});
describe("stack overflow - infinite recursive function - tail call", function() {
this.timeout(5000);
it("should throw error", function() {
expect(function() {
var expr = jsonata("( $inf := function(){$inf()}; $inf())");
timeboxExpression(expr, 1000, 500);
expr.evaluate();
})
.to.throw()
.to.deep.contain({ token: "inf", code: "U1001" });
});
});
});
/**
* Protect the process/browser from a runnaway expression
* i.e. Infinite loop (tail recursion), or excessive stack growth
*
* @param {Object} expr - expression to protect
* @param {Number} timeout - max time in ms
* @param {Number} maxDepth - max stack depth
*/
function timeboxExpression(expr, timeout, maxDepth) {
var depth = 0;
var time = Date.now();
var checkRunnaway = function() {
if (depth > maxDepth) {
// stack too deep
throw {
message:
"Stack overflow error: Check for non-terminating recursive function. Consider rewriting as tail-recursive.",
stack: new Error().stack,
code: "U1001"
};
}
if (Date.now() - time > timeout) {
// expression has run for too long
throw {
message: "Expression evaluation timeout: Check for infinite loop",
stack: new Error().stack,
code: "U1001"
};
}
};
// register callbacks
expr.assign("__evaluate_entry", function() {
depth++;
checkRunnaway();
});
expr.assign("__evaluate_exit", function() {
depth--;
checkRunnaway();
});
}