Debian Codegraph @

tests/phpunit/unit/includes/json/FormatJsonTest.php

raw symbols SCIP
1 <?php
2
3 use MediaWiki\Json\FormatJson;
4
5 /**
6 * @covers \MediaWiki\Json\FormatJson
7 */
8 class FormatJsonTest extends MediaWikiUnitTestCase {
9
10 public static function provideEncoderPrettyPrinting() {
11 return [
12 // Four spaces
13 [ true, ' ' ],
14 [ ' ', ' ' ],
15 // Two spaces
16 [ ' ', ' ' ],
17 // One tab
18 [ "\t", "\t" ],
19 // Empty string
20 [ '', '' ],
21 ];
22 }
23
24 /**
25 * @dataProvider provideEncoderPrettyPrinting
26 */
27 public function testEncoderPrettyPrinting( $pretty, $expectedIndent ) {
28 $obj = [
29 'emptyObject' => (object)[],
30 'emptyArray' => [],
31 'string' => 'foobar\\',
32 'filledArray' => [
33 [
34 123,
35 456,
36 ],
37 // Nested json works without problems
38 '"7":["8",{"9":"10"}]',
39 // Whitespace clean up doesn't touch strings that look alike
40 "{\n\t\"emptyObject\": {\n\t},\n\t\"emptyArray\": [ ]\n}",
41 " []",
42 ],
43 ];
44
45 // No trailing whitespace, no trailing linefeed
46 $json = '{
47 "emptyObject": {},
48 "emptyArray": [],
49 "string": "foobar\\\\",
50 "filledArray": [
51 [
52 123,
53 456
54 ],
55 "\"7\":[\"8\",{\"9\":\"10\"}]",
56 "{\n\t\"emptyObject\": {\n\t},\n\t\"emptyArray\": [ ]\n}",
57 " []"
58 ]
59 }';
60
61 $json = str_replace( "\r", '', $json ); // Windows compat
62 $json = str_replace( "\t", $expectedIndent, $json );
63 $this->assertSame( $json, FormatJson::encode( $obj, $pretty ) );
64 }
65
66 public static function provideEncodeDefault() {
67 return self::getEncodeTestCases( [] );
68 }
69
70 /**
71 * @dataProvider provideEncodeDefault
72 */
73 public function testEncodeDefault( $from, $to ) {
74 $this->assertSame( $to, FormatJson::encode( $from ) );
75 }
76
77 public static function provideEncodeUtf8() {
78 return self::getEncodeTestCases( [ 'unicode' ] );
79 }
80
81 /**
82 * @dataProvider provideEncodeUtf8
83 */
84 public function testEncodeUtf8( $from, $to ) {
85 $this->assertSame( $to, FormatJson::encode( $from, false, FormatJson::UTF8_OK ) );
86 }
87
88 public static function provideEncodeXmlMeta() {
89 return self::getEncodeTestCases( [ 'xmlmeta' ] );
90 }
91
92 /**
93 * @dataProvider provideEncodeXmlMeta
94 */
95 public function testEncodeXmlMeta( $from, $to ) {
96 $this->assertSame( $to, FormatJson::encode( $from, false, FormatJson::XMLMETA_OK ) );
97 }
98
99 public static function provideEncodeAllOk() {
100 return self::getEncodeTestCases( [ 'unicode', 'xmlmeta' ] );
101 }
102
103 /**
104 * @dataProvider provideEncodeAllOk
105 */
106 public function testEncodeAllOk( $from, $to ) {
107 $this->assertSame( $to, FormatJson::encode( $from, false, FormatJson::ALL_OK ) );
108 }
109
110 public function testEncodePhpBug46944() {
111 $this->assertNotEquals(
112 '\ud840\udc00',
113 strtolower( FormatJson::encode( "\u{20000}" ) ),
114 'Test encoding of broken json_encode character (U+20000)'
115 );
116 }
117
118 public function testEncodeFail() {
119 // Set up a recursive object that can't be encoded.
120 $a = (object)[];
121 $b = (object)[];
122 $a->b = $b;
123 $b->a = $a;
124 $this->assertFalse( FormatJson::encode( $a ) );
125 }
126
127 public function testDecodeReturnType() {
128 $this->assertIsObject(
129
130 FormatJson::decode( '{"Name": "Cheeso", "Rank": 7}' ),
131 'Default to object'
132 );
133
134 $this->assertIsArray(
135
136 FormatJson::decode( '{"Name": "Cheeso", "Rank": 7}', true ),
137 'Optional array'
138 );
139 }
140
141 public static function provideParse() {
142 return [
143 [ null ],
144 [ true ],
145 [ false ],
146 [ 0 ],
147 [ 1 ],
148 [ 1.2 ],
149 [ '' ],
150 [ 'str' ],
151 [ [ 0, 1, 2 ] ],
152 [ [ 'a' => 'b' ] ],
153 [ [ 'a' => 'b' ] ],
154 [ [ 'a' => 'b', 'x' => [ 'c' => 'd' ] ] ],
155 ];
156 }
157
158 /**
159 * Recursively convert arrays into stdClass
160 * @param array|?scalar $value
161 * @return stdClass|?scalar
162 */
163 public static function toObject( $value ) {
164 return !is_array( $value ) ? $value : (object)array_map( __METHOD__, $value );
165 }
166
167 /**
168 * @dataProvider provideParse
169 */
170 public function testParse( $value ) {
171 $expected = self::toObject( $value );
172 $json = FormatJson::encode( $expected, false, FormatJson::ALL_OK );
173 $this->assertJson( $json );
174
175 $st = FormatJson::parse( $json );
176 $this->assertStatusGood( $st );
177 $this->assertStatusValue( $expected, $st );
178
179 $st = FormatJson::parse( $json, FormatJson::FORCE_ASSOC );
180 $this->assertStatusGood( $st );
181 $this->assertStatusValue( $value, $st );
182 }
183
184 public static function provideParseErrors() {
185 return [
186 [ 'aaa', 'json-error-syntax' ],
187 [ '{"j": 1 ] }', 'json-error-state-mismatch' ],
188 [ chr( 0 ), 'json-error-ctrl-char' ],
189 [ '"\ud834"', 'json-error-utf16' ],
190 [ '{"\u0000":1}', 'json-error-invalid-property-name' ],
191 ];
192 }
193
194 /**
195 * @dataProvider provideParseErrors
196 */
197 public function testParseErrors( $value, $error ) {
198 $this->assertStatusError( $error, FormatJson::parse( $value ) );
199 }
200
201 public static function provideStripComments() {
202 return [
203 [ '{"a":"b"}', '{"a":"b"}' ],
204 [ "{\"a\":\"b\"}\n", "{\"a\":\"b\"}\n" ],
205 [ '/*c*/{"c":"b"}', '{"c":"b"}' ],
206 [ '{"a":"c"}/*c*/', '{"a":"c"}' ],
207 [ '/*c//d*/{"c":"b"}', '{"c":"b"}' ],
208 [ '{/*c*/"c":"b"}', '{"c":"b"}' ],
209 [ "/*\nc\r\n*/{\"c\":\"b\"}", '{"c":"b"}' ],
210 [ "//c\n{\"c\":\"b\"}", '{"c":"b"}' ],
211 [ "//c\r\n{\"c\":\"b\"}", '{"c":"b"}' ],
212 [ '{"a":"c"}//c', '{"a":"c"}' ],
213 [ "{\"a-c\"://c\n\"b\"}", '{"a-c":"b"}' ],
214 [ '{"/*a":"b"}', '{"/*a":"b"}' ],
215 [ '{"a":"//b"}', '{"a":"//b"}' ],
216 [ '{"a":"b/*c*/"}', '{"a":"b/*c*/"}' ],
217 [ "{\"\\\"/*a\":\"b\"}", "{\"\\\"/*a\":\"b\"}" ],
218 [ '', '' ],
219 [ '/*c', '' ],
220 [ '//c', '' ],
221 [ '"http://example.com"', '"http://example.com"' ],
222 [ "\0", "\0" ],
223 [ '"Blåbærsyltetøy"', '"Blåbærsyltetøy"' ],
224 ];
225 }
226
227 /**
228 * @covers \MediaWiki\Json\FormatJson::stripComments
229 * @dataProvider provideStripComments
230 * @param string $json
231 * @param string $expect
232 */
233 public function testStripComments( $json, $expect ) {
234 $this->assertSame( $expect, FormatJson::stripComments( $json ) );
235 }
236
237 public static function provideParseStripComments() {
238 return [
239 [ '/* blah */true', true ],
240 [ "// blah \ntrue", true ],
241 [ '[ "a" , /* blah */ "b" ]', [ 'a', 'b' ] ],
242 ];
243 }
244
245 /**
246 * @covers \MediaWiki\Json\FormatJson::parse
247 * @covers \MediaWiki\Json\FormatJson::stripComments
248 * @dataProvider provideParseStripComments
249 */
250 public function testParseStripComments( $json, $expect ) {
251 $st = FormatJson::parse( $json, FormatJson::STRIP_COMMENTS );
252 $this->assertStatusGood( $st );
253 $this->assertStatusValue( $expect, $st );
254 }
255
256 /**
257 * Generate a set of test cases for a particular combination of encoder options.
258 *
259 * @param array $unescapedGroups List of character groups to leave unescaped
260 * @return array Arrays of unencoded strings and corresponding encoded strings
261 */
262 private static function getEncodeTestCases( array $unescapedGroups ) {
263 $groups = [
264 'always' => [
265 // Forward slash (always unescaped)
266 '/' => '/',
267
268 // Control characters
269 "\0" => '\u0000',
270 "\x08" => '\b',
271 "\t" => '\t',
272 "\n" => '\n',
273 "\r" => '\r',
274 "\f" => '\f',
275 "\x1f" => '\u001f', // representative example
276
277 // Double quotes
278 '"' => '\"',
279
280 // Backslashes
281 '\\' => '\\\\',
282 '\\\\' => '\\\\\\\\',
283 '\\u00e9' => '\\\u00e9', // security check for Unicode unescaping
284
285 // Line terminators
286 "\u{2028}" => '\u2028',
287 "\u{2029}" => '\u2029',
288 ],
289 'unicode' => [
290 "\u{00E9}" => '\u00e9',
291 "\u{1D49E}" => '\ud835\udc9e', // U+1D49E, outside the BMP
292 ],
293 'xmlmeta' => [
294 '<' => '\u003C', // JSON_HEX_TAG uses uppercase hex digits
295 '>' => '\u003E',
296 '&' => '\u0026',
297 ],
298 ];
299
300 $cases = [];
301 foreach ( $groups as $name => $rules ) {
302 $leaveUnescaped = in_array( $name, $unescapedGroups );
303 foreach ( $rules as $from => $to ) {
304 $cases[] = [ $from, '"' . ( $leaveUnescaped ? $from : $to ) . '"' ];
305 }
306 }
307
308 return $cases;
309 }
310
311 public static function provideEmptyJsonKeyStrings() {
312 return [
313 [
314 '{"":"foo"}',
315 '{"":"foo"}',
316 ''
317 ],
318 [
319 '{"_empty_":"foo"}',
320 '{"_empty_":"foo"}',
321 '_empty_' ],
322 [
323 '{"\u005F\u0065\u006D\u0070\u0074\u0079\u005F":"foo"}',
324 '{"_empty_":"foo"}',
325 '_empty_'
326 ],
327 [
328 '{"_empty_":"bar","":"foo"}',
329 '{"_empty_":"bar","":"foo"}',
330 ''
331 ],
332 [
333 '{"":"bar","_empty_":"foo"}',
334 '{"":"bar","_empty_":"foo"}',
335 '_empty_'
336 ]
337 ];
338 }
339
340 /**
341 * @covers \MediaWiki\Json\FormatJson::encode
342 * @covers \MediaWiki\Json\FormatJson::decode
343 * @dataProvider provideEmptyJsonKeyStrings
344 *
345 * Decoding behavior with empty keys can be surprising.
346 * See https://phabricator.wikimedia.org/T206411
347 */
348 public function testEmptyJsonKeyArray( $json, $expect, $php71Name ) {
349 // Decoding to array is consistent across supported PHP versions
350 $this->assertSame( $expect, FormatJson::encode(
351 FormatJson::decode( $json, true ) ) );
352
353 // Decoding to object differed for PHP versions less than 7.1
354 $obj = FormatJson::decode( $json );
355 $this->assertEquals( 'foo', $obj->{$php71Name} );
356 }
357
358 /**
359 * Test data for testParseTryFixing.
360 *
361 * Some PHP interpreters use json-c rather than the JSON.org canonical
362 * parser to avoid being encumbered by the "shall be used for Good, not
363 * Evil" clause of the JSON.org parser's license. By default, json-c
364 * parses in a non-strict mode which allows trailing commas for array and
365 * object delarations among other things, so our JSON_ERROR_SYNTAX rescue
366 * block is not always triggered. It however isn't lenient in exactly the
367 * same ways as our TRY_FIXING mode, so the assertions in this test are
368 * a bit more complicated than they ideally would be:
369 *
370 * Optional third argument: true if json-c parses the value without
371 * intervention, false otherwise. Defaults to true.
372 *
373 * Optional fourth argument: expected cannonical JSON serialization of
374 * json-c parsed result. Defaults to the second argument's value.
375 */
376 public static function provideParseTryFixing() {
377 return [
378 [ "[,]", '[]', false ],
379 [ "[ , ]", '[]', false ],
380 [ "[ , }", false ],
381 [ '[1],', false, true, '[1]' ],
382 [ "[1,]", '[1]' ],
383 [ "[1\n,]", '[1]' ],
384 [ "[1,\n]", '[1]' ],
385 [ "[1,]\n", '[1]' ],
386 [ "[1\n,\n]\n", '[1]' ],
387 [ '["a,",]', '["a,"]' ],
388 [ "[[1,]\n,[2,\n],[3\n,]]", '[[1],[2],[3]]' ],
389 // I wish we could parse this, but would need quote parsing
390 [ '[[1,],[2,],[3,]]', false, true, '[[1],[2],[3]]' ],
391 [ '[1,,]', false, false, '[1]' ],
392 ];
393 }
394
395 /**
396 * @dataProvider provideParseTryFixing
397 * @param string $value
398 * @param string|bool $expected Expected result with strict parser
399 * @param bool $jsoncParses Will json-c parse this value without TRY_FIXING?
400 * @param string|null $expectedJsonc Expected result with lenient parser
401 * if different from the strict expectation
402 */
403 public function testParseTryFixing(
404 $value, $expected,
405 $jsoncParses = true, $expectedJsonc = null
406 ) {
407 // PHP5 results are always expected to have isGood() === false
408 $expectedGoodStatus = false;
409
410 // Check to see if json parser allows trailing commas
411 if ( json_decode( '[1,]' ) !== null ) {
412 // Use json-c specific expected result if provided
413 $expected = ( $expectedJsonc === null ) ? $expected : $expectedJsonc;
414 // If json-c parses the value natively, expect isGood() === true
415 $expectedGoodStatus = $jsoncParses;
416 }
417
418 $st = FormatJson::parse( $value, FormatJson::TRY_FIXING );
419 if ( $expected === false ) {
420 $this->assertStatusNotOK( $st );
421 } else {
422 if ( $expectedGoodStatus ) {
423 $this->assertStatusGood( $st );
424 } else {
425 $this->assertStatusOK( $st );
426 }
427 $val = FormatJson::encode( $st->getValue(), false, FormatJson::ALL_OK );
428 $this->assertEquals( $expected, $val );
429 }
430 }
431 }