CssSelectorTest.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.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\Component\CssSelector;
  11. use Symfony\Component\CssSelector\CssSelector;
  12. class CssSelectorTest extends \PHPUnit_Framework_TestCase
  13. {
  14. public function testCsstoXPath()
  15. {
  16. $this->assertEquals('descendant-or-self::h1', CssSelector::toXPath('h1'));
  17. $this->assertEquals("descendant-or-self::h1[@id = 'foo']", CssSelector::toXPath('h1#foo'));
  18. $this->assertEquals("descendant-or-self::h1[contains(concat(' ', normalize-space(@class), ' '), ' foo ')]", CssSelector::toXPath('h1.foo'));
  19. $this->assertEquals('descendant-or-self::foo:h1', CssSelector::toXPath('foo|h1'));
  20. }
  21. /**
  22. * @dataProvider getCssSelectors
  23. */
  24. public function testParse($css, $xpath)
  25. {
  26. $parser = new CssSelector();
  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 CssSelector();
  32. try {
  33. $parser->parse('h1:');
  34. $this->fail('->parse() throws an Exception if the css selector is not valid');
  35. } catch (\Exception $e) {
  36. $this->assertInstanceOf('\Symfony\Component\CssSelector\Exception\ParseException', $e, '->parse() throws an Exception if the css selector is not valid');
  37. $this->assertEquals("Expected symbol, got '' at h1: -> ", $e->getMessage(), '->parse() throws an Exception if the css selector is not valid');
  38. }
  39. }
  40. public function getCssSelectors()
  41. {
  42. return array(
  43. array('h1', "h1"),
  44. array('foo|h1', "foo:h1"),
  45. array('h1, h2, h3', "h1 | h2 | h3"),
  46. array('h1:nth-child(3n+1)', "*/*[name() = 'h1' and ((position() -1) mod 3 = 0 and position() >= 1)]"),
  47. array('h1 > p', "h1/p"),
  48. array('h1#foo', "h1[@id = 'foo']"),
  49. array('h1.foo', "h1[contains(concat(' ', normalize-space(@class), ' '), ' foo ')]"),
  50. array('h1[class*="foo bar"]', "h1[contains(@class, 'foo bar')]"),
  51. array('h1[foo|class*="foo bar"]', "h1[contains(@foo:class, 'foo bar')]"),
  52. array('h1[class]', "h1[@class]"),
  53. array('h1 .foo', "h1/descendant::*[contains(concat(' ', normalize-space(@class), ' '), ' foo ')]"),
  54. array('h1 #foo', "h1/descendant::*[@id = 'foo']"),
  55. array('h1 [class*=foo]', "h1/descendant::*[contains(@class, 'foo')]"),
  56. );
  57. }
  58. }