shell.js (3332B)
1 /*--- 2 defines: [testJSON] 3 allow_unused: True 4 ---*/ 5 function testJSON(str, expectSyntaxError) 6 { 7 // Leading and trailing whitespace never affect parsing, so test the string 8 // multiple times with and without whitespace around it as it's easy and can 9 // potentially detect bugs. 10 11 // Try the provided string 12 try 13 { 14 JSON.parse(str); 15 reportCompare(false, expectSyntaxError, 16 "string <" + str + "> " + 17 "should" + (expectSyntaxError ? "n't" : "") + " " + 18 "have parsed as JSON"); 19 } 20 catch (e) 21 { 22 if (!(e instanceof SyntaxError)) 23 { 24 reportCompare(true, false, 25 "parsing string <" + str + "> threw a non-SyntaxError " + 26 "exception: " + e); 27 } 28 else 29 { 30 reportCompare(true, expectSyntaxError, 31 "string <" + str + "> " + 32 "should" + (expectSyntaxError ? "n't" : "") + " " + 33 "have parsed as JSON, exception: " + e); 34 } 35 } 36 37 // Now try the provided string with trailing whitespace 38 try 39 { 40 JSON.parse(str + " "); 41 reportCompare(false, expectSyntaxError, 42 "string <" + str + " > " + 43 "should" + (expectSyntaxError ? "n't" : "") + " " + 44 "have parsed as JSON"); 45 } 46 catch (e) 47 { 48 if (!(e instanceof SyntaxError)) 49 { 50 reportCompare(true, false, 51 "parsing string <" + str + " > threw a non-SyntaxError " + 52 "exception: " + e); 53 } 54 else 55 { 56 reportCompare(true, expectSyntaxError, 57 "string <" + str + " > " + 58 "should" + (expectSyntaxError ? "n't" : "") + " " + 59 "have parsed as JSON, exception: " + e); 60 } 61 } 62 63 // Now try the provided string with leading whitespace 64 try 65 { 66 JSON.parse(" " + str); 67 reportCompare(false, expectSyntaxError, 68 "string < " + str + "> " + 69 "should" + (expectSyntaxError ? "n't" : "") + " " + 70 "have parsed as JSON"); 71 } 72 catch (e) 73 { 74 if (!(e instanceof SyntaxError)) 75 { 76 reportCompare(true, false, 77 "parsing string < " + str + "> threw a non-SyntaxError " + 78 "exception: " + e); 79 } 80 else 81 { 82 reportCompare(true, expectSyntaxError, 83 "string < " + str + "> " + 84 "should" + (expectSyntaxError ? "n't" : "") + " " + 85 "have parsed as JSON, exception: " + e); 86 } 87 } 88 89 // Now try the provided string with whitespace surrounding it 90 try 91 { 92 JSON.parse(" " + str + " "); 93 reportCompare(false, expectSyntaxError, 94 "string < " + str + " > " + 95 "should" + (expectSyntaxError ? "n't" : "") + " " + 96 "have parsed as JSON"); 97 } 98 catch (e) 99 { 100 if (!(e instanceof SyntaxError)) 101 { 102 reportCompare(true, false, 103 "parsing string < " + str + " > threw a non-SyntaxError " + 104 "exception: " + e); 105 } 106 else 107 { 108 reportCompare(true, expectSyntaxError, 109 "string < " + str + " > " + 110 "should" + (expectSyntaxError ? "n't" : "") + " " + 111 "have parsed as JSON, exception: " + e); 112 } 113 } 114 }