js/src/tests/ecma_5/JSON/cyclic-stringify.js

changeset 0
6474c204b198
equal deleted inserted replaced
-1:000000000000 0:4a966efae531
1 // Any copyright is dedicated to the Public Domain.
2 // http://creativecommons.org/licenses/publicdomain/
3
4 //-----------------------------------------------------------------------------
5 var BUGNUMBER = 578273;
6 var summary =
7 "ES5: Properly detect cycles in JSON.stringify (throw TypeError, check for " +
8 "cycles rather than imprecisely rely on recursion limits)";
9
10 print(BUGNUMBER + ": " + summary);
11
12 /**************
13 * BEGIN TEST *
14 **************/
15
16 // objects
17
18 var count = 0;
19 var desc =
20 {
21 get: function() { count++; return obj; },
22 enumerable: true,
23 configurable: true
24 };
25 var obj = Object.defineProperty({ p1: 0 }, "p2", desc);
26
27 try
28 {
29 var str = JSON.stringify(obj);
30 assertEq(false, true, "should have thrown, got " + str);
31 }
32 catch (e)
33 {
34 assertEq(e instanceof TypeError, true,
35 "wrong error type: " + e.constructor.name);
36 assertEq(count, 1,
37 "cyclic data structures not detected immediately");
38 }
39
40 count = 0;
41 var obj2 = Object.defineProperty({}, "obj", desc);
42 try
43 {
44 var str = JSON.stringify(obj2);
45 assertEq(false, true, "should have thrown, got " + str);
46 }
47 catch (e)
48 {
49 assertEq(e instanceof TypeError, true,
50 "wrong error type: " + e.constructor.name);
51 assertEq(count, 2,
52 "cyclic data structures not detected immediately");
53 }
54
55
56 // arrays
57
58 var count = 0;
59 var desc =
60 {
61 get: function() { count++; return arr; },
62 enumerable: true,
63 configurable: true
64 };
65 var arr = Object.defineProperty([], "0", desc);
66
67 try
68 {
69 var str = JSON.stringify(arr);
70 assertEq(false, true, "should have thrown, got " + str);
71 }
72 catch (e)
73 {
74 assertEq(e instanceof TypeError, true,
75 "wrong error type: " + e.constructor.name);
76 assertEq(count, 1,
77 "cyclic data structures not detected immediately");
78 }
79
80 count = 0;
81 var arr2 = Object.defineProperty([], "0", desc);
82 try
83 {
84 var str = JSON.stringify(arr2);
85 assertEq(false, true, "should have thrown, got " + str);
86 }
87 catch (e)
88 {
89 assertEq(e instanceof TypeError, true,
90 "wrong error type: " + e.constructor.name);
91 assertEq(count, 2,
92 "cyclic data structures not detected immediately");
93 }
94
95 /******************************************************************************/
96
97 if (typeof reportCompare === "function")
98 reportCompare(true, true);
99
100 print("Tests complete");

mercurial