4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Yaml\Tests;
14 use PHPUnit\Framework\TestCase;
15 use Symfony\Component\Yaml\Exception\ParseException;
16 use Symfony\Component\Yaml\Yaml;
17 use Symfony\Component\Yaml\Parser;
19 class ParserTest extends TestCase
24 protected function setUp()
26 $this->parser = new Parser();
29 protected function tearDown()
35 * @dataProvider getDataFormSpecifications
37 public function testSpecifications($file, $expected, $yaml, $comment, $deprecated)
39 $deprecations = array();
42 set_error_handler(function ($type, $msg) use (&$deprecations) {
43 if (E_USER_DEPRECATED !== $type) {
44 restore_error_handler();
46 if (class_exists('PHPUnit_Util_ErrorHandler')) {
47 return call_user_func_array('PHPUnit_Util_ErrorHandler::handleError', func_get_args());
50 return call_user_func_array('PHPUnit\Util\ErrorHandler::handleError', func_get_args());
53 $deprecations[] = $msg;
57 $this->assertEquals($expected, var_export($this->parser->parse($yaml), true), $comment);
60 restore_error_handler();
62 $this->assertCount(1, $deprecations);
63 $this->assertContains('Using the comma as a group separator for floats is deprecated since version 3.2 and will be removed in 4.0.', $deprecations[0]);
67 public function getDataFormSpecifications()
69 $parser = new Parser();
70 $path = __DIR__.'/Fixtures';
73 $files = $parser->parse(file_get_contents($path.'/index.yml'));
74 foreach ($files as $file) {
75 $yamls = file_get_contents($path.'/'.$file.'.yml');
77 // split YAMLs documents
78 foreach (preg_split('/^---( %YAML\:1\.0)?/m', $yamls) as $yaml) {
83 $test = $parser->parse($yaml);
84 if (isset($test['todo']) && $test['todo']) {
87 eval('$expected = '.trim($test['php']).';');
89 $tests[] = array($file, var_export($expected, true), $test['yaml'], $test['test'], isset($test['deprecated']) ? $test['deprecated'] : false);
97 public function testTabsInYaml()
107 foreach ($yamls as $yaml) {
109 $content = $this->parser->parse($yaml);
111 $this->fail('YAML files must not contain tabs');
112 } catch (\Exception $e) {
113 $this->assertInstanceOf('\Exception', $e, 'YAML files must not contain tabs');
114 $this->assertEquals('A YAML file cannot contain tabs as indentation at line 2 (near "'.strpbrk($yaml, "\t").'").', $e->getMessage(), 'YAML files must not contain tabs');
119 public function testEndOfTheDocumentMarker()
127 $this->assertEquals('foo', $this->parser->parse($yaml));
130 public function getBlockChompingTests()
147 $tests['Literal block chomping strip with single trailing newline'] = array($expected, $yaml);
164 $tests['Literal block chomping strip with multiple trailing newlines'] = array($expected, $yaml);
172 $tests['Literal block chomping strip with multiple trailing newlines after a 1-liner'] = array($expected, $yaml);
186 $tests['Literal block chomping strip without trailing newline'] = array($expected, $yaml);
198 'foo' => "one\ntwo\n",
199 'bar' => "one\ntwo\n",
201 $tests['Literal block chomping clip with single trailing newline'] = array($expected, $yaml);
215 'foo' => "one\ntwo\n",
216 'bar' => "one\ntwo\n",
218 $tests['Literal block chomping clip with multiple trailing newlines'] = array($expected, $yaml);
230 'bar' => "one\n\ntwo",
234 $tests['Literal block chomping clip with embedded blank line inside unindented collection'] = array($expected, $yaml);
245 'foo' => "one\ntwo\n",
248 $tests['Literal block chomping clip without trailing newline'] = array($expected, $yaml);
260 'foo' => "one\ntwo\n",
261 'bar' => "one\ntwo\n",
263 $tests['Literal block chomping keep with single trailing newline'] = array($expected, $yaml);
277 'foo' => "one\ntwo\n\n",
278 'bar' => "one\ntwo\n\n",
280 $tests['Literal block chomping keep with multiple trailing newlines'] = array($expected, $yaml);
291 'foo' => "one\ntwo\n",
294 $tests['Literal block chomping keep without trailing newline'] = array($expected, $yaml);
309 $tests['Folded block chomping strip with single trailing newline'] = array($expected, $yaml);
326 $tests['Folded block chomping strip with multiple trailing newlines'] = array($expected, $yaml);
340 $tests['Folded block chomping strip without trailing newline'] = array($expected, $yaml);
352 'foo' => "one two\n",
353 'bar' => "one two\n",
355 $tests['Folded block chomping clip with single trailing newline'] = array($expected, $yaml);
369 'foo' => "one two\n",
370 'bar' => "one two\n",
372 $tests['Folded block chomping clip with multiple trailing newlines'] = array($expected, $yaml);
383 'foo' => "one two\n",
386 $tests['Folded block chomping clip without trailing newline'] = array($expected, $yaml);
398 'foo' => "one two\n",
399 'bar' => "one two\n",
401 $tests['Folded block chomping keep with single trailing newline'] = array($expected, $yaml);
415 'foo' => "one two\n\n",
416 'bar' => "one two\n\n",
418 $tests['Folded block chomping keep with multiple trailing newlines'] = array($expected, $yaml);
429 'foo' => "one two\n",
432 $tests['Folded block chomping keep without trailing newline'] = array($expected, $yaml);
438 * @dataProvider getBlockChompingTests
440 public function testBlockChomping($expected, $yaml)
442 $this->assertSame($expected, $this->parser->parse($yaml));
446 * Regression test for issue #7989.
448 * @see https://github.com/symfony/symfony/issues/7989
450 public function testBlockLiteralWithLeadingNewlines()
463 $this->assertSame($expected, $this->parser->parse($yaml));
466 public function testObjectSupportEnabled()
469 foo: !php/object:O:30:"Symfony\Component\Yaml\Tests\B":1:{s:1:"b";s:3:"foo";}
472 $this->assertEquals(array('foo' => new B(), 'bar' => 1), $this->parser->parse($input, Yaml::PARSE_OBJECT), '->parse() is able to parse objects');
478 public function testObjectSupportEnabledPassingTrue()
481 foo: !php/object:O:30:"Symfony\Component\Yaml\Tests\B":1:{s:1:"b";s:3:"foo";}
484 $this->assertEquals(array('foo' => new B(), 'bar' => 1), $this->parser->parse($input, false, true), '->parse() is able to parse objects');
490 public function testObjectSupportEnabledWithDeprecatedTag()
493 foo: !!php/object:O:30:"Symfony\Component\Yaml\Tests\B":1:{s:1:"b";s:3:"foo";}
496 $this->assertEquals(array('foo' => new B(), 'bar' => 1), $this->parser->parse($input, Yaml::PARSE_OBJECT), '->parse() is able to parse objects');
500 * @dataProvider invalidDumpedObjectProvider
502 public function testObjectSupportDisabledButNoExceptions($input)
504 $this->assertEquals(array('foo' => null, 'bar' => 1), $this->parser->parse($input), '->parse() does not parse objects');
508 * @dataProvider getObjectForMapTests
510 public function testObjectForMap($yaml, $expected)
512 $this->assertEquals($expected, $this->parser->parse($yaml, Yaml::PARSE_OBJECT_FOR_MAP));
517 * @dataProvider getObjectForMapTests
519 public function testObjectForMapEnabledWithMappingUsingBooleanToggles($yaml, $expected)
521 $this->assertEquals($expected, $this->parser->parse($yaml, false, false, true));
524 public function getObjectForMapTests()
532 $expected = new \stdClass();
533 $expected->foo = new \stdClass();
534 $expected->foo->fiz = array('cat');
535 $tests['mapping'] = array($yaml, $expected);
537 $yaml = '{ "foo": "bar", "fiz": "cat" }';
538 $expected = new \stdClass();
539 $expected->foo = 'bar';
540 $expected->fiz = 'cat';
541 $tests['inline-mapping'] = array($yaml, $expected);
543 $yaml = "foo: bar\nbaz: foobar";
544 $expected = new \stdClass();
545 $expected->foo = 'bar';
546 $expected->baz = 'foobar';
547 $tests['object-for-map-is-applied-after-parsing'] = array($yaml, $expected);
554 $expected = new \stdClass();
555 $expected->array = array();
556 $expected->array[0] = new \stdClass();
557 $expected->array[0]->key = 'one';
558 $expected->array[1] = new \stdClass();
559 $expected->array[1]->key = 'two';
560 $tests['nest-map-and-sequence'] = array($yaml, $expected);
567 $expected = new \stdClass();
568 $expected->map = new \stdClass();
569 $expected->map->{1} = 'one';
570 $expected->map->{2} = 'two';
571 $tests['numeric-keys'] = array($yaml, $expected);
578 $expected = new \stdClass();
579 $expected->map = new \stdClass();
580 $expected->map->{0} = 'one';
581 $expected->map->{1} = 'two';
582 $tests['zero-indexed-numeric-keys'] = array($yaml, $expected);
588 * @dataProvider invalidDumpedObjectProvider
589 * @expectedException \Symfony\Component\Yaml\Exception\ParseException
591 public function testObjectsSupportDisabledWithExceptions($yaml)
593 $this->parser->parse($yaml, Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE);
598 * @dataProvider invalidDumpedObjectProvider
599 * @expectedException \Symfony\Component\Yaml\Exception\ParseException
601 public function testObjectsSupportDisabledWithExceptionsUsingBooleanToggles($yaml)
603 $this->parser->parse($yaml, true);
606 public function invalidDumpedObjectProvider()
609 foo: !!php/object:O:30:"Symfony\Tests\Component\Yaml\B":1:{s:1:"b";s:3:"foo";}
613 foo: !php/object:O:30:"Symfony\Tests\Component\Yaml\B":1:{s:1:"b";s:3:"foo";}
618 'yaml-tag' => array($yamlTag),
619 'local-tag' => array($localTag),
624 * @requires extension iconv
626 public function testNonUtf8Exception()
629 iconv('UTF-8', 'ISO-8859-1', "foo: 'äöüß'"),
630 iconv('UTF-8', 'ISO-8859-15', "euro: '€'"),
631 iconv('UTF-8', 'CP1252', "cp1252: '©ÉÇáñ'"),
634 foreach ($yamls as $yaml) {
636 $this->parser->parse($yaml);
638 $this->fail('charsets other than UTF-8 are rejected.');
639 } catch (\Exception $e) {
640 $this->assertInstanceOf('Symfony\Component\Yaml\Exception\ParseException', $e, 'charsets other than UTF-8 are rejected.');
646 * @expectedException \Symfony\Component\Yaml\Exception\ParseException
648 public function testUnindentedCollectionException()
659 $this->parser->parse($yaml);
663 * @expectedException \Symfony\Component\Yaml\Exception\ParseException
665 public function testShortcutKeyUnindentedCollectionException()
675 $this->parser->parse($yaml);
679 * @expectedException \Symfony\Component\Yaml\Exception\ParseException
680 * @expectedExceptionMessageRegExp /^Multiple documents are not supported.+/
682 public function testMultipleDocumentsNotSupportedException()
685 # Ranking of 1998 home runs
700 * @expectedException \Symfony\Component\Yaml\Exception\ParseException
702 public function testSequenceInAMapping()
712 public function testSequenceInMappingStartedBySingleDashLine()
737 $this->assertSame($expected, $this->parser->parse($yaml));
740 public function testSequenceFollowedByCommentEmbeddedInMapping()
756 $this->assertSame($expected, $this->parser->parse($yaml));
760 * @expectedException \Symfony\Component\Yaml\Exception\ParseException
762 public function testMappingInASequence()
773 * @expectedException \Symfony\Component\Yaml\Exception\ParseException
774 * @expectedExceptionMessage missing colon
776 public function testScalarInSequence()
788 * > It is an error for two equal keys to appear in the same mapping node.
789 * > In such a case the YAML processor may continue, ignoring the second
790 * > `key: value` pair and issuing an appropriate warning. This strategy
791 * > preserves a consistent information model for one-pass and random access
794 * @see http://yaml.org/spec/1.2/spec.html#id2759572
795 * @see http://yaml.org/spec/1.1/#id932806
798 public function testMappingDuplicateKeyBlock()
813 $this->assertSame($expected, Yaml::parse($input));
819 public function testMappingDuplicateKeyFlow()
822 parent: { child: first, child: duplicate }
823 parent: { child: duplicate, child: duplicate }
830 $this->assertSame($expected, Yaml::parse($input));
835 * @dataProvider getParseExceptionOnDuplicateData
836 * @expectedDeprecation Duplicate key "%s" detected on line %d whilst parsing YAML. Silent handling of duplicate mapping keys in YAML is deprecated %s.
837 * throws \Symfony\Component\Yaml\Exception\ParseException in 4.0
839 public function testParseExceptionOnDuplicate($input, $duplicateKey, $lineNumber)
844 public function getParseExceptionOnDuplicateData()
849 parent: { child: first, child: duplicate }
851 $tests[] = array($yaml, 'child', 1);
858 $tests[] = array($yaml, 'child', 3);
861 parent: { child: foo }
862 parent: { child: bar }
864 $tests[] = array($yaml, 'parent', 2);
867 parent: { child_mapping: { value: bar}, child_mapping: { value: bar} }
869 $tests[] = array($yaml, 'child_mapping', 1);
878 $tests[] = array($yaml, 'child_mapping', 4);
881 parent: { child_sequence: ['key1', 'key2', 'key3'], child_sequence: ['key1', 'key2', 'key3'] }
883 $tests[] = array($yaml, 'child_sequence', 1);
896 $tests[] = array($yaml, 'child_sequence', 6);
901 public function testEmptyValue()
907 $this->assertEquals(array('hash' => null), Yaml::parse($input));
910 public function testCommentAtTheRootIndent()
912 $this->assertEquals(array(
914 'app.foo_service' => array(
917 'app/bar_service' => array(
921 ), Yaml::parse(<<<'EOF'
936 public function testStringBlockWithComments()
938 $this->assertEquals(array('content' => <<<'EOT'
949 ), Yaml::parse(<<<'EOF'
964 public function testFoldedStringBlockWithComments()
966 $this->assertEquals(array(array('content' => <<<'EOT'
977 )), Yaml::parse(<<<'EOF'
993 public function testNestedFoldedStringBlockWithComments()
995 $this->assertEquals(array(array(
996 'title' => 'some title',
997 'content' => <<<'EOT'
1008 )), Yaml::parse(<<<'EOF'
1025 public function testReferenceResolvingInInlineStrings()
1027 $this->assertEquals(array(
1028 'var' => 'var-value',
1029 'scalar' => 'var-value',
1030 'list' => array('var-value'),
1031 'list_in_list' => array(array('var-value')),
1032 'map_in_list' => array(array('key' => 'var-value')),
1033 'embedded_mapping' => array(array('key' => 'var-value')),
1034 'map' => array('key' => 'var-value'),
1035 'list_in_map' => array('key' => array('var-value')),
1036 'map_in_map' => array('foo' => array('bar' => 'var-value')),
1037 ), Yaml::parse(<<<'EOF'
1041 list_in_list: [[ *var ]]
1042 map_in_list: [ { key: *var } ]
1043 embedded_mapping: [ key: *var ]
1045 list_in_map: { key: [*var] }
1046 map_in_map: { foo: { bar: *var } }
1051 public function testYamlDirective()
1059 $this->assertEquals(array('foo' => 1, 'bar' => 2), $this->parser->parse($yaml));
1062 public function testFloatKeys()
1077 $this->assertEquals($expected, $this->parser->parse($yaml));
1081 * @expectedException \Symfony\Component\Yaml\Exception\ParseException
1082 * @expectedExceptionMessage A colon cannot be used in an unquoted mapping value
1084 public function testColonInMappingValueException()
1090 $this->parser->parse($yaml);
1093 public function testColonInMappingValueExceptionNotTriggeredByColonInComment()
1097 bar: foobar # Note: a comment after a colon
1100 $this->assertSame(array('foo' => array('bar' => 'foobar')), $this->parser->parse($yaml));
1104 * @dataProvider getCommentLikeStringInScalarBlockData
1106 public function testCommentLikeStringsAreNotStrippedInBlockScalars($yaml, $expectedParserResult)
1108 $this->assertSame($expectedParserResult, $this->parser->parse($yaml));
1111 public function getCommentLikeStringInScalarBlockData()
1133 'title' => 'some title',
1134 'content' => <<<'EOT'
1149 $tests[] = array($yaml, $expected);
1174 'collection' => array(
1194 $tests[] = array($yaml, $expected);
1209 'scalar-block' => "line1 line2>\n",
1216 $tests[] = array($yaml, $expected);
1232 $tests[] = array($yaml, $expected);
1237 public function testBlankLinesAreParsedAsNewLinesInFoldedBlocks()
1245 <li>may be a good example</li>
1253 <ul> <li>a list</li> <li>may be a good example</li> </ul>
1257 $this->parser->parse($yaml)
1261 public function testAdditionallyIndentedLinesAreParsedAsNewLinesInFoldedBlocks()
1269 <li>may be a good example</li>
1279 <li>may be a good example</li>
1284 $this->parser->parse($yaml)
1289 * @dataProvider getBinaryData
1291 public function testParseBinaryData($data)
1293 $this->assertSame(array('data' => 'Hello world'), $this->parser->parse($data));
1296 public function getBinaryData()
1299 'enclosed with double quotes' => array('data: !!binary "SGVsbG8gd29ybGQ="'),
1300 'enclosed with single quotes' => array("data: !!binary 'SGVsbG8gd29ybGQ='"),
1301 'containing spaces' => array('data: !!binary "SGVs bG8gd 29ybGQ="'),
1302 'in block scalar' => array(
1308 'containing spaces in block scalar' => array(
1318 * @dataProvider getInvalidBinaryData
1319 * @expectedException \Symfony\Component\Yaml\Exception\ParseException
1321 public function testParseInvalidBinaryData($data, $expectedMessage)
1323 if (method_exists($this, 'expectException')) {
1324 $this->expectExceptionMessageRegExp($expectedMessage);
1326 $this->setExpectedExceptionRegExp(ParseException::class, $expectedMessage);
1329 $this->parser->parse($data);
1332 public function getInvalidBinaryData()
1335 'length not a multiple of four' => array('data: !!binary "SGVsbG8d29ybGQ="', '/The normalized base64 encoded data \(data without whitespace characters\) length must be a multiple of four \(\d+ bytes given\)/'),
1336 'invalid characters' => array('!!binary "SGVsbG8#d29ybGQ="', '/The base64 encoded data \(.*\) contains invalid characters/'),
1337 'too many equals characters' => array('data: !!binary "SGVsbG8gd29yb==="', '/The base64 encoded data \(.*\) contains invalid characters/'),
1338 'misplaced equals character' => array('data: !!binary "SGVsbG8gd29ybG=Q"', '/The base64 encoded data \(.*\) contains invalid characters/'),
1339 'length not a multiple of four in block scalar' => array(
1345 '/The normalized base64 encoded data \(data without whitespace characters\) length must be a multiple of four \(\d+ bytes given\)/',
1347 'invalid characters in block scalar' => array(
1353 '/The base64 encoded data \(.*\) contains invalid characters/',
1355 'too many equals characters in block scalar' => array(
1361 '/The base64 encoded data \(.*\) contains invalid characters/',
1363 'misplaced equals character in block scalar' => array(
1369 '/The base64 encoded data \(.*\) contains invalid characters/',
1374 public function testParseDateAsMappingValue()
1379 $expectedDate = new \DateTime();
1380 $expectedDate->setTimeZone(new \DateTimeZone('UTC'));
1381 $expectedDate->setDate(2002, 12, 14);
1382 $expectedDate->setTime(0, 0, 0);
1384 $this->assertEquals(array('date' => $expectedDate), $this->parser->parse($yaml, Yaml::PARSE_DATETIME));
1388 * @param $lineNumber
1390 * @dataProvider parserThrowsExceptionWithCorrectLineNumberProvider
1392 public function testParserThrowsExceptionWithCorrectLineNumber($lineNumber, $yaml)
1394 if (method_exists($this, 'expectException')) {
1395 $this->expectException('\Symfony\Component\Yaml\Exception\ParseException');
1396 $this->expectExceptionMessage(sprintf('Unexpected characters near "," at line %d (near "bar: "123",").', $lineNumber));
1398 $this->setExpectedException('\Symfony\Component\Yaml\Exception\ParseException', sprintf('Unexpected characters near "," at line %d (near "bar: "123",").', $lineNumber));
1401 $this->parser->parse($yaml);
1404 public function parserThrowsExceptionWithCorrectLineNumberProvider()
1457 public function testParseMultiLineQuotedString()
1467 $this->assertSame(array('foo' => 'bar baz foobar foo', 'bar' => 'baz'), $this->parser->parse($yaml));
1470 public function testParseMultiLineUnquotedString()
1480 $this->assertSame(array('foo' => 'bar baz foobar foo', 'bar' => 'baz'), $this->parser->parse($yaml));
1483 public function testCanParseVeryLongValue()
1485 $longStringWithSpaces = str_repeat('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ', 20000);
1486 $trickyVal = array('x' => $longStringWithSpaces);
1488 $yamlString = Yaml::dump($trickyVal);
1489 $arrayFromYaml = $this->parser->parse($yamlString);
1491 $this->assertEquals($trickyVal, $arrayFromYaml);
1495 * @expectedException \Symfony\Component\Yaml\Exception\ParseException
1496 * @expectedExceptionMessage Reference "foo" does not exist at line 2
1498 public function testParserCleansUpReferencesBetweenRuns()
1506 $this->parser->parse($yaml);
1512 $this->parser->parse($yaml);