ParserTest.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /*
  3. * This file is part of the symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Tests\Components\CssSelector;
  11. use Symfony\Components\CssSelector\Parser;
  12. class ParserTest extends \PHPUnit_Framework_TestCase
  13. {
  14. public function testCssToXpath()
  15. {
  16. $this->assertEquals('descendant-or-self::h1', Parser::cssToXpath('h1'));
  17. $this->assertEquals("descendant-or-self::h1[@id = 'foo']", Parser::cssToXpath('h1#foo'));
  18. $this->assertEquals("descendant-or-self::h1[contains(concat(' ', normalize-space(@class), ' '), ' foo ')]", Parser::cssToXpath('h1.foo'));
  19. $this->assertEquals('descendant-or-self::foo:h1', Parser::cssToXpath('foo|h1'));
  20. }
  21. /**
  22. * @dataProvider getCssSelectors
  23. */
  24. public function testParse($css, $xpath)
  25. {
  26. $parser = new Parser();
  27. $this->assertEquals($xpath, (string) $parser->parse($css)->toXpath(), '->parse() parses an input string and returns a node');
  28. }
  29. public function testParseExceptions()
  30. {
  31. $parser = new Parser();
  32. try
  33. {
  34. $parser->parse('h1:');
  35. $this->fail('->parse() throws an Exception if the css selector is not valid');
  36. }
  37. catch (\Exception $e)
  38. {
  39. $this->assertType('\Symfony\Components\CssSelector\SyntaxError', $e, '->parse() throws an Exception if the css selector is not valid');
  40. $this->assertEquals("Expected symbol, got '' at h1: -> ", $e->getMessage(), '->parse() throws an Exception if the css selector is not valid');
  41. }
  42. }
  43. public function getCssSelectors()
  44. {
  45. return array(
  46. array('h1', "h1"),
  47. array('foo|h1', "foo:h1"),
  48. array('h1, h2, h3', "h1 | h2 | h3"),
  49. array('h1:nth-child(3n+1)', "*/*[name() = 'h1' and ((position() -1) mod 3 = 0 and position() >= 1)]"),
  50. array('h1 > p', "h1/p"),
  51. array('h1#foo', "h1[@id = 'foo']"),
  52. array('h1.foo', "h1[contains(concat(' ', normalize-space(@class), ' '), ' foo ')]"),
  53. array('h1[class*="foo bar"]', "h1[contains(@class, 'foo bar')]"),
  54. array('h1[foo|class*="foo bar"]', "h1[contains(@foo:class, 'foo bar')]"),
  55. array('h1[class]', "h1[@class]"),
  56. array('h1 .foo', "h1/descendant::*[contains(concat(' ', normalize-space(@class), ' '), ' foo ')]"),
  57. array('h1 #foo', "h1/descendant::*[@id = 'foo']"),
  58. array('h1 [class*=foo]', "h1/descendant::*[contains(@class, 'foo')]"),
  59. );
  60. }
  61. }