CrawlerTest.php 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201
  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\Component\DomCrawler\Tests;
  11. use Symfony\Component\DomCrawler\Crawler;
  12. class CrawlerTest extends \PHPUnit_Framework_TestCase
  13. {
  14. public function testConstructor()
  15. {
  16. $crawler = new Crawler();
  17. $this->assertCount(0, $crawler, '__construct() returns an empty crawler');
  18. $doc = new \DOMDocument();
  19. $node = $doc->createElement('test');
  20. $crawler = new Crawler($node);
  21. $this->assertCount(1, $crawler, '__construct() takes a node as a first argument');
  22. }
  23. public function testGetUri()
  24. {
  25. $uri = 'http://symfony.com';
  26. $crawler = new Crawler(null, $uri);
  27. $this->assertEquals($uri, $crawler->getUri());
  28. }
  29. public function testGetBaseHref()
  30. {
  31. $baseHref = 'http://symfony.com';
  32. $crawler = new Crawler(null, null, $baseHref);
  33. $this->assertEquals($baseHref, $crawler->getBaseHref());
  34. }
  35. public function testAdd()
  36. {
  37. $crawler = new Crawler();
  38. $crawler->add($this->createDomDocument());
  39. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->add() adds nodes from a \DOMDocument');
  40. $crawler = new Crawler();
  41. $crawler->add($this->createNodeList());
  42. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->add() adds nodes from a \DOMNodeList');
  43. $list = array();
  44. foreach ($this->createNodeList() as $node) {
  45. $list[] = $node;
  46. }
  47. $crawler = new Crawler();
  48. $crawler->add($list);
  49. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->add() adds nodes from an array of nodes');
  50. $crawler = new Crawler();
  51. $crawler->add($this->createNodeList()->item(0));
  52. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->add() adds nodes from a \DOMNode');
  53. $crawler = new Crawler();
  54. $crawler->add('<html><body>Foo</body></html>');
  55. $this->assertEquals('Foo', $crawler->filterXPath('//body')->text(), '->add() adds nodes from a string');
  56. }
  57. /**
  58. * @expectedException \InvalidArgumentException
  59. */
  60. public function testAddInvalidType()
  61. {
  62. $crawler = new Crawler();
  63. $crawler->add(1);
  64. }
  65. /**
  66. * @expectedException \InvalidArgumentException
  67. * @expectedExceptionMessage Attaching DOM nodes from multiple documents in the same crawler is forbidden.
  68. */
  69. public function testAddMultipleDocumentNode()
  70. {
  71. $crawler = $this->createTestCrawler();
  72. $crawler->addHtmlContent('<html><div class="foo"></html>', 'UTF-8');
  73. }
  74. public function testAddHtmlContent()
  75. {
  76. $crawler = new Crawler();
  77. $crawler->addHtmlContent('<html><div class="foo"></html>', 'UTF-8');
  78. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addHtmlContent() adds nodes from an HTML string');
  79. }
  80. public function testAddHtmlContentWithBaseTag()
  81. {
  82. $crawler = new Crawler();
  83. $crawler->addHtmlContent('<html><head><base href="http://symfony.com"></head><a href="/contact"></a></html>', 'UTF-8');
  84. $this->assertEquals('http://symfony.com', $crawler->filterXPath('//base')->attr('href'), '->addHtmlContent() adds nodes from an HTML string');
  85. $this->assertEquals('http://symfony.com/contact', $crawler->filterXPath('//a')->link()->getUri(), '->addHtmlContent() adds nodes from an HTML string');
  86. }
  87. /**
  88. * @requires extension mbstring
  89. */
  90. public function testAddHtmlContentCharset()
  91. {
  92. $crawler = new Crawler();
  93. $crawler->addHtmlContent('<html><div class="foo">Tiếng Việt</html>', 'UTF-8');
  94. $this->assertEquals('Tiếng Việt', $crawler->filterXPath('//div')->text());
  95. }
  96. public function testAddHtmlContentInvalidBaseTag()
  97. {
  98. $crawler = new Crawler(null, 'http://symfony.com');
  99. $crawler->addHtmlContent('<html><head><base target="_top"></head><a href="/contact"></a></html>', 'UTF-8');
  100. $this->assertEquals('http://symfony.com/contact', current($crawler->filterXPath('//a')->links())->getUri(), '->addHtmlContent() correctly handles a non-existent base tag href attribute');
  101. }
  102. public function testAddHtmlContentUnsupportedCharset()
  103. {
  104. $crawler = new Crawler();
  105. $crawler->addHtmlContent(file_get_contents(__DIR__.'/Fixtures/windows-1250.html'), 'Windows-1250');
  106. $this->assertEquals('Žťčýů', $crawler->filterXPath('//p')->text());
  107. }
  108. /**
  109. * @requires extension mbstring
  110. */
  111. public function testAddHtmlContentCharsetGbk()
  112. {
  113. $crawler = new Crawler();
  114. //gbk encode of <html><p>中文</p></html>
  115. $crawler->addHtmlContent(base64_decode('PGh0bWw+PHA+1tDOxDwvcD48L2h0bWw+'), 'gbk');
  116. $this->assertEquals('中文', $crawler->filterXPath('//p')->text());
  117. }
  118. public function testAddHtmlContentWithErrors()
  119. {
  120. $internalErrors = libxml_use_internal_errors(true);
  121. $crawler = new Crawler();
  122. $crawler->addHtmlContent(<<<'EOF'
  123. <!DOCTYPE html>
  124. <html>
  125. <head>
  126. </head>
  127. <body>
  128. <nav><a href="#"><a href="#"></nav>
  129. </body>
  130. </html>
  131. EOF
  132. , 'UTF-8');
  133. $errors = libxml_get_errors();
  134. $this->assertCount(1, $errors);
  135. $this->assertEquals("Tag nav invalid\n", $errors[0]->message);
  136. libxml_clear_errors();
  137. libxml_use_internal_errors($internalErrors);
  138. }
  139. public function testAddXmlContent()
  140. {
  141. $crawler = new Crawler();
  142. $crawler->addXmlContent('<html><div class="foo"></div></html>', 'UTF-8');
  143. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addXmlContent() adds nodes from an XML string');
  144. }
  145. public function testAddXmlContentCharset()
  146. {
  147. $crawler = new Crawler();
  148. $crawler->addXmlContent('<html><div class="foo">Tiếng Việt</div></html>', 'UTF-8');
  149. $this->assertEquals('Tiếng Việt', $crawler->filterXPath('//div')->text());
  150. }
  151. public function testAddXmlContentWithErrors()
  152. {
  153. $internalErrors = libxml_use_internal_errors(true);
  154. $crawler = new Crawler();
  155. $crawler->addXmlContent(<<<'EOF'
  156. <!DOCTYPE html>
  157. <html>
  158. <head>
  159. </head>
  160. <body>
  161. <nav><a href="#"><a href="#"></nav>
  162. </body>
  163. </html>
  164. EOF
  165. , 'UTF-8');
  166. $this->assertTrue(count(libxml_get_errors()) > 1);
  167. libxml_clear_errors();
  168. libxml_use_internal_errors($internalErrors);
  169. }
  170. public function testAddContent()
  171. {
  172. $crawler = new Crawler();
  173. $crawler->addContent('<html><div class="foo"></html>', 'text/html; charset=UTF-8');
  174. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addContent() adds nodes from an HTML string');
  175. $crawler = new Crawler();
  176. $crawler->addContent('<html><div class="foo"></html>', 'text/html; charset=UTF-8; dir=RTL');
  177. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addContent() adds nodes from an HTML string with extended content type');
  178. $crawler = new Crawler();
  179. $crawler->addContent('<html><div class="foo"></html>');
  180. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addContent() uses text/html as the default type');
  181. $crawler = new Crawler();
  182. $crawler->addContent('<html><div class="foo"></div></html>', 'text/xml; charset=UTF-8');
  183. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addContent() adds nodes from an XML string');
  184. $crawler = new Crawler();
  185. $crawler->addContent('<html><div class="foo"></div></html>', 'text/xml');
  186. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addContent() adds nodes from an XML string');
  187. $crawler = new Crawler();
  188. $crawler->addContent('foo bar', 'text/plain');
  189. $this->assertCount(0, $crawler, '->addContent() does nothing if the type is not (x|ht)ml');
  190. $crawler = new Crawler();
  191. $crawler->addContent('<html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><span>中文</span></html>');
  192. $this->assertEquals('中文', $crawler->filterXPath('//span')->text(), '->addContent() guess wrong charset');
  193. }
  194. /**
  195. * @requires extension iconv
  196. */
  197. public function testAddContentNonUtf8()
  198. {
  199. $crawler = new Crawler();
  200. $crawler->addContent(iconv('UTF-8', 'SJIS', '<html><head><meta charset="Shift_JIS"></head><body>日本語</body></html>'));
  201. $this->assertEquals('日本語', $crawler->filterXPath('//body')->text(), '->addContent() can recognize "Shift_JIS" in html5 meta charset tag');
  202. }
  203. public function testAddDocument()
  204. {
  205. $crawler = new Crawler();
  206. $crawler->addDocument($this->createDomDocument());
  207. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addDocument() adds nodes from a \DOMDocument');
  208. }
  209. public function testAddNodeList()
  210. {
  211. $crawler = new Crawler();
  212. $crawler->addNodeList($this->createNodeList());
  213. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addNodeList() adds nodes from a \DOMNodeList');
  214. }
  215. public function testAddNodes()
  216. {
  217. $list = array();
  218. foreach ($this->createNodeList() as $node) {
  219. $list[] = $node;
  220. }
  221. $crawler = new Crawler();
  222. $crawler->addNodes($list);
  223. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addNodes() adds nodes from an array of nodes');
  224. }
  225. public function testAddNode()
  226. {
  227. $crawler = new Crawler();
  228. $crawler->addNode($this->createNodeList()->item(0));
  229. $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addNode() adds nodes from a \DOMNode');
  230. }
  231. public function testClear()
  232. {
  233. $doc = new \DOMDocument();
  234. $node = $doc->createElement('test');
  235. $crawler = new Crawler($node);
  236. $crawler->clear();
  237. $this->assertCount(0, $crawler, '->clear() removes all the nodes from the crawler');
  238. }
  239. public function testEq()
  240. {
  241. $crawler = $this->createTestCrawler()->filterXPath('//li');
  242. $this->assertNotSame($crawler, $crawler->eq(0), '->eq() returns a new instance of a crawler');
  243. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->eq() returns a new instance of a crawler');
  244. $this->assertEquals('Two', $crawler->eq(1)->text(), '->eq() returns the nth node of the list');
  245. $this->assertCount(0, $crawler->eq(100), '->eq() returns an empty crawler if the nth node does not exist');
  246. }
  247. public function testEach()
  248. {
  249. $data = $this->createTestCrawler()->filterXPath('//ul[1]/li')->each(function ($node, $i) {
  250. return $i.'-'.$node->text();
  251. });
  252. $this->assertEquals(array('0-One', '1-Two', '2-Three'), $data, '->each() executes an anonymous function on each node of the list');
  253. }
  254. public function testIteration()
  255. {
  256. $crawler = $this->createTestCrawler()->filterXPath('//li');
  257. $this->assertInstanceOf('Traversable', $crawler);
  258. $this->assertContainsOnlyInstancesOf('DOMElement', iterator_to_array($crawler), 'Iterating a Crawler gives DOMElement instances');
  259. }
  260. public function testSlice()
  261. {
  262. $crawler = $this->createTestCrawler()->filterXPath('//ul[1]/li');
  263. $this->assertNotSame($crawler->slice(), $crawler, '->slice() returns a new instance of a crawler');
  264. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler->slice(), '->slice() returns a new instance of a crawler');
  265. $this->assertCount(3, $crawler->slice(), '->slice() does not slice the nodes in the list if any param is entered');
  266. $this->assertCount(1, $crawler->slice(1, 1), '->slice() slices the nodes in the list');
  267. }
  268. public function testReduce()
  269. {
  270. $crawler = $this->createTestCrawler()->filterXPath('//ul[1]/li');
  271. $nodes = $crawler->reduce(function ($node, $i) {
  272. return $i !== 1;
  273. });
  274. $this->assertNotSame($nodes, $crawler, '->reduce() returns a new instance of a crawler');
  275. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $nodes, '->reduce() returns a new instance of a crawler');
  276. $this->assertCount(2, $nodes, '->reduce() filters the nodes in the list');
  277. }
  278. public function testAttr()
  279. {
  280. $this->assertEquals('first', $this->createTestCrawler()->filterXPath('//li')->attr('class'), '->attr() returns the attribute of the first element of the node list');
  281. try {
  282. $this->createTestCrawler()->filterXPath('//ol')->attr('class');
  283. $this->fail('->attr() throws an \InvalidArgumentException if the node list is empty');
  284. } catch (\InvalidArgumentException $e) {
  285. $this->assertTrue(true, '->attr() throws an \InvalidArgumentException if the node list is empty');
  286. }
  287. }
  288. public function testMissingAttrValueIsNull()
  289. {
  290. $crawler = new Crawler();
  291. $crawler->addContent('<html><div non-empty-attr="sample value" empty-attr=""></div></html>', 'text/html; charset=UTF-8');
  292. $div = $crawler->filterXPath('//div');
  293. $this->assertEquals('sample value', $div->attr('non-empty-attr'), '->attr() reads non-empty attributes correctly');
  294. $this->assertEquals('', $div->attr('empty-attr'), '->attr() reads empty attributes correctly');
  295. $this->assertNull($div->attr('missing-attr'), '->attr() reads missing attributes correctly');
  296. }
  297. public function testNodeName()
  298. {
  299. $this->assertEquals('li', $this->createTestCrawler()->filterXPath('//li')->nodeName(), '->nodeName() returns the node name of the first element of the node list');
  300. try {
  301. $this->createTestCrawler()->filterXPath('//ol')->nodeName();
  302. $this->fail('->nodeName() throws an \InvalidArgumentException if the node list is empty');
  303. } catch (\InvalidArgumentException $e) {
  304. $this->assertTrue(true, '->nodeName() throws an \InvalidArgumentException if the node list is empty');
  305. }
  306. }
  307. public function testText()
  308. {
  309. $this->assertEquals('One', $this->createTestCrawler()->filterXPath('//li')->text(), '->text() returns the node value of the first element of the node list');
  310. try {
  311. $this->createTestCrawler()->filterXPath('//ol')->text();
  312. $this->fail('->text() throws an \InvalidArgumentException if the node list is empty');
  313. } catch (\InvalidArgumentException $e) {
  314. $this->assertTrue(true, '->text() throws an \InvalidArgumentException if the node list is empty');
  315. }
  316. }
  317. public function testHtml()
  318. {
  319. $this->assertEquals('<img alt="Bar">', $this->createTestCrawler()->filterXPath('//a[5]')->html());
  320. $this->assertEquals('<input type="text" value="TextValue" name="TextName"><input type="submit" value="FooValue" name="FooName" id="FooId"><input type="button" value="BarValue" name="BarName" id="BarId"><button value="ButtonValue" name="ButtonName" id="ButtonId"></button>', trim($this->createTestCrawler()->filterXPath('//form[@id="FooFormId"]')->html()));
  321. try {
  322. $this->createTestCrawler()->filterXPath('//ol')->html();
  323. $this->fail('->html() throws an \InvalidArgumentException if the node list is empty');
  324. } catch (\InvalidArgumentException $e) {
  325. $this->assertTrue(true, '->html() throws an \InvalidArgumentException if the node list is empty');
  326. }
  327. }
  328. public function testExtract()
  329. {
  330. $crawler = $this->createTestCrawler()->filterXPath('//ul[1]/li');
  331. $this->assertEquals(array('One', 'Two', 'Three'), $crawler->extract('_text'), '->extract() returns an array of extracted data from the node list');
  332. $this->assertEquals(array(array('One', 'first'), array('Two', ''), array('Three', '')), $crawler->extract(array('_text', 'class')), '->extract() returns an array of extracted data from the node list');
  333. $this->assertEquals(array(), $this->createTestCrawler()->filterXPath('//ol')->extract('_text'), '->extract() returns an empty array if the node list is empty');
  334. }
  335. public function testFilterXpathComplexQueries()
  336. {
  337. $crawler = $this->createTestCrawler()->filterXPath('//body');
  338. $this->assertCount(0, $crawler->filterXPath('/input'));
  339. $this->assertCount(0, $crawler->filterXPath('/body'));
  340. $this->assertCount(1, $crawler->filterXPath('./body'));
  341. $this->assertCount(1, $crawler->filterXPath('.//body'));
  342. $this->assertCount(5, $crawler->filterXPath('.//input'));
  343. $this->assertCount(4, $crawler->filterXPath('//form')->filterXPath('//button | //input'));
  344. $this->assertCount(1, $crawler->filterXPath('body'));
  345. $this->assertCount(6, $crawler->filterXPath('//button | //input'));
  346. $this->assertCount(1, $crawler->filterXPath('//body'));
  347. $this->assertCount(1, $crawler->filterXPath('descendant-or-self::body'));
  348. $this->assertCount(1, $crawler->filterXPath('//div[@id="parent"]')->filterXPath('./div'), 'A child selection finds only the current div');
  349. $this->assertCount(3, $crawler->filterXPath('//div[@id="parent"]')->filterXPath('descendant::div'), 'A descendant selector matches the current div and its child');
  350. $this->assertCount(3, $crawler->filterXPath('//div[@id="parent"]')->filterXPath('//div'), 'A descendant selector matches the current div and its child');
  351. $this->assertCount(5, $crawler->filterXPath('(//a | //div)//img'));
  352. $this->assertCount(7, $crawler->filterXPath('((//a | //div)//img | //ul)'));
  353. $this->assertCount(7, $crawler->filterXPath('( ( //a | //div )//img | //ul )'));
  354. $this->assertCount(1, $crawler->filterXPath("//a[./@href][((./@id = 'Klausi|Claudiu' or normalize-space(string(.)) = 'Klausi|Claudiu' or ./@title = 'Klausi|Claudiu' or ./@rel = 'Klausi|Claudiu') or .//img[./@alt = 'Klausi|Claudiu'])]"));
  355. }
  356. public function testFilterXPath()
  357. {
  358. $crawler = $this->createTestCrawler();
  359. $this->assertNotSame($crawler, $crawler->filterXPath('//li'), '->filterXPath() returns a new instance of a crawler');
  360. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->filterXPath() returns a new instance of a crawler');
  361. $crawler = $this->createTestCrawler()->filterXPath('//ul');
  362. $this->assertCount(6, $crawler->filterXPath('//li'), '->filterXPath() filters the node list with the XPath expression');
  363. $crawler = $this->createTestCrawler();
  364. $this->assertCount(3, $crawler->filterXPath('//body')->filterXPath('//button')->parents(), '->filterXpath() preserves parents when chained');
  365. }
  366. public function testFilterRemovesDuplicates()
  367. {
  368. $crawler = $this->createTestCrawler()->filter('html, body')->filter('li');
  369. $this->assertCount(6, $crawler, 'The crawler removes duplicates when filtering.');
  370. }
  371. public function testFilterXPathWithDefaultNamespace()
  372. {
  373. $crawler = $this->createTestXmlCrawler()->filterXPath('//default:entry/default:id');
  374. $this->assertCount(1, $crawler, '->filterXPath() automatically registers a namespace');
  375. $this->assertSame('tag:youtube.com,2008:video:kgZRZmEc9j4', $crawler->text());
  376. }
  377. public function testFilterXPathWithCustomDefaultNamespace()
  378. {
  379. $crawler = $this->createTestXmlCrawler();
  380. $crawler->setDefaultNamespacePrefix('x');
  381. $crawler = $crawler->filterXPath('//x:entry/x:id');
  382. $this->assertCount(1, $crawler, '->filterXPath() lets to override the default namespace prefix');
  383. $this->assertSame('tag:youtube.com,2008:video:kgZRZmEc9j4', $crawler->text());
  384. }
  385. public function testFilterXPathWithNamespace()
  386. {
  387. $crawler = $this->createTestXmlCrawler()->filterXPath('//yt:accessControl');
  388. $this->assertCount(2, $crawler, '->filterXPath() automatically registers a namespace');
  389. }
  390. public function testFilterXPathWithMultipleNamespaces()
  391. {
  392. $crawler = $this->createTestXmlCrawler()->filterXPath('//media:group/yt:aspectRatio');
  393. $this->assertCount(1, $crawler, '->filterXPath() automatically registers multiple namespaces');
  394. $this->assertSame('widescreen', $crawler->text());
  395. }
  396. public function testFilterXPathWithManuallyRegisteredNamespace()
  397. {
  398. $crawler = $this->createTestXmlCrawler();
  399. $crawler->registerNamespace('m', 'http://search.yahoo.com/mrss/');
  400. $crawler = $crawler->filterXPath('//m:group/yt:aspectRatio');
  401. $this->assertCount(1, $crawler, '->filterXPath() uses manually registered namespace');
  402. $this->assertSame('widescreen', $crawler->text());
  403. }
  404. public function testFilterXPathWithAnUrl()
  405. {
  406. $crawler = $this->createTestXmlCrawler();
  407. $crawler = $crawler->filterXPath('//media:category[@scheme="http://gdata.youtube.com/schemas/2007/categories.cat"]');
  408. $this->assertCount(1, $crawler);
  409. $this->assertSame('Music', $crawler->text());
  410. }
  411. public function testFilterXPathWithFakeRoot()
  412. {
  413. $crawler = $this->createTestCrawler();
  414. $this->assertCount(0, $crawler->filterXPath('.'), '->filterXPath() returns an empty result if the XPath references the fake root node');
  415. $this->assertCount(0, $crawler->filterXPath('self::*'), '->filterXPath() returns an empty result if the XPath references the fake root node');
  416. $this->assertCount(0, $crawler->filterXPath('self::_root'), '->filterXPath() returns an empty result if the XPath references the fake root node');
  417. }
  418. public function testFilterXPathWithAncestorAxis()
  419. {
  420. $crawler = $this->createTestCrawler()->filterXPath('//form');
  421. $this->assertCount(0, $crawler->filterXPath('ancestor::*'), 'The fake root node has no ancestor nodes');
  422. }
  423. public function testFilterXPathWithAncestorOrSelfAxis()
  424. {
  425. $crawler = $this->createTestCrawler()->filterXPath('//form');
  426. $this->assertCount(0, $crawler->filterXPath('ancestor-or-self::*'), 'The fake root node has no ancestor nodes');
  427. }
  428. public function testFilterXPathWithAttributeAxis()
  429. {
  430. $crawler = $this->createTestCrawler()->filterXPath('//form');
  431. $this->assertCount(0, $crawler->filterXPath('attribute::*'), 'The fake root node has no attribute nodes');
  432. }
  433. public function testFilterXPathWithAttributeAxisAfterElementAxis()
  434. {
  435. $this->assertCount(3, $this->createTestCrawler()->filterXPath('//form/button/attribute::*'), '->filterXPath() handles attribute axes properly when they are preceded by an element filtering axis');
  436. }
  437. public function testFilterXPathWithChildAxis()
  438. {
  439. $crawler = $this->createTestCrawler()->filterXPath('//div[@id="parent"]');
  440. $this->assertCount(1, $crawler->filterXPath('child::div'), 'A child selection finds only the current div');
  441. }
  442. public function testFilterXPathWithFollowingAxis()
  443. {
  444. $crawler = $this->createTestCrawler()->filterXPath('//a');
  445. $this->assertCount(0, $crawler->filterXPath('following::div'), 'The fake root node has no following nodes');
  446. }
  447. public function testFilterXPathWithFollowingSiblingAxis()
  448. {
  449. $crawler = $this->createTestCrawler()->filterXPath('//a');
  450. $this->assertCount(0, $crawler->filterXPath('following-sibling::div'), 'The fake root node has no following nodes');
  451. }
  452. public function testFilterXPathWithNamespaceAxis()
  453. {
  454. $crawler = $this->createTestCrawler()->filterXPath('//button');
  455. $this->assertCount(0, $crawler->filterXPath('namespace::*'), 'The fake root node has no namespace nodes');
  456. }
  457. public function testFilterXPathWithNamespaceAxisAfterElementAxis()
  458. {
  459. $crawler = $this->createTestCrawler()->filterXPath('//div[@id="parent"]/namespace::*');
  460. $this->assertCount(0, $crawler->filterXPath('namespace::*'), 'Namespace axes cannot be requested');
  461. }
  462. public function testFilterXPathWithParentAxis()
  463. {
  464. $crawler = $this->createTestCrawler()->filterXPath('//button');
  465. $this->assertCount(0, $crawler->filterXPath('parent::*'), 'The fake root node has no parent nodes');
  466. }
  467. public function testFilterXPathWithPrecedingAxis()
  468. {
  469. $crawler = $this->createTestCrawler()->filterXPath('//form');
  470. $this->assertCount(0, $crawler->filterXPath('preceding::*'), 'The fake root node has no preceding nodes');
  471. }
  472. public function testFilterXPathWithPrecedingSiblingAxis()
  473. {
  474. $crawler = $this->createTestCrawler()->filterXPath('//form');
  475. $this->assertCount(0, $crawler->filterXPath('preceding-sibling::*'), 'The fake root node has no preceding nodes');
  476. }
  477. public function testFilterXPathWithSelfAxes()
  478. {
  479. $crawler = $this->createTestCrawler()->filterXPath('//a');
  480. $this->assertCount(0, $crawler->filterXPath('self::a'), 'The fake root node has no "real" element name');
  481. $this->assertCount(0, $crawler->filterXPath('self::a/img'), 'The fake root node has no "real" element name');
  482. $this->assertCount(10, $crawler->filterXPath('self::*/a'));
  483. }
  484. public function testFilter()
  485. {
  486. $crawler = $this->createTestCrawler();
  487. $this->assertNotSame($crawler, $crawler->filter('li'), '->filter() returns a new instance of a crawler');
  488. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->filter() returns a new instance of a crawler');
  489. $crawler = $this->createTestCrawler()->filter('ul');
  490. $this->assertCount(6, $crawler->filter('li'), '->filter() filters the node list with the CSS selector');
  491. }
  492. public function testFilterWithDefaultNamespace()
  493. {
  494. $crawler = $this->createTestXmlCrawler()->filter('default|entry default|id');
  495. $this->assertCount(1, $crawler, '->filter() automatically registers namespaces');
  496. $this->assertSame('tag:youtube.com,2008:video:kgZRZmEc9j4', $crawler->text());
  497. }
  498. public function testFilterWithNamespace()
  499. {
  500. $crawler = $this->createTestXmlCrawler()->filter('yt|accessControl');
  501. $this->assertCount(2, $crawler, '->filter() automatically registers namespaces');
  502. }
  503. public function testFilterWithMultipleNamespaces()
  504. {
  505. $crawler = $this->createTestXmlCrawler()->filter('media|group yt|aspectRatio');
  506. $this->assertCount(1, $crawler, '->filter() automatically registers namespaces');
  507. $this->assertSame('widescreen', $crawler->text());
  508. }
  509. public function testFilterWithDefaultNamespaceOnly()
  510. {
  511. $crawler = new Crawler('<?xml version="1.0" encoding="UTF-8"?>
  512. <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  513. <url>
  514. <loc>http://localhost/foo</loc>
  515. <changefreq>weekly</changefreq>
  516. <priority>0.5</priority>
  517. <lastmod>2012-11-16</lastmod>
  518. </url>
  519. <url>
  520. <loc>http://localhost/bar</loc>
  521. <changefreq>weekly</changefreq>
  522. <priority>0.5</priority>
  523. <lastmod>2012-11-16</lastmod>
  524. </url>
  525. </urlset>
  526. ');
  527. $this->assertEquals(2, $crawler->filter('url')->count());
  528. }
  529. public function testSelectLink()
  530. {
  531. $crawler = $this->createTestCrawler();
  532. $this->assertNotSame($crawler, $crawler->selectLink('Foo'), '->selectLink() returns a new instance of a crawler');
  533. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->selectLink() returns a new instance of a crawler');
  534. $this->assertCount(1, $crawler->selectLink('Fabien\'s Foo'), '->selectLink() selects links by the node values');
  535. $this->assertCount(1, $crawler->selectLink('Fabien\'s Bar'), '->selectLink() selects links by the alt attribute of a clickable image');
  536. $this->assertCount(2, $crawler->selectLink('Fabien"s Foo'), '->selectLink() selects links by the node values');
  537. $this->assertCount(2, $crawler->selectLink('Fabien"s Bar'), '->selectLink() selects links by the alt attribute of a clickable image');
  538. $this->assertCount(1, $crawler->selectLink('\' Fabien"s Foo'), '->selectLink() selects links by the node values');
  539. $this->assertCount(1, $crawler->selectLink('\' Fabien"s Bar'), '->selectLink() selects links by the alt attribute of a clickable image');
  540. $this->assertCount(4, $crawler->selectLink('Foo'), '->selectLink() selects links by the node values');
  541. $this->assertCount(4, $crawler->selectLink('Bar'), '->selectLink() selects links by the node values');
  542. }
  543. public function testSelectImage()
  544. {
  545. $crawler = $this->createTestCrawler();
  546. $this->assertNotSame($crawler, $crawler->selectImage('Bar'), '->selectImage() returns a new instance of a crawler');
  547. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->selectImage() returns a new instance of a crawler');
  548. $this->assertCount(1, $crawler->selectImage('Fabien\'s Bar'), '->selectImage() selects images by alt attribute');
  549. $this->assertCount(2, $crawler->selectImage('Fabien"s Bar'), '->selectImage() selects images by alt attribute');
  550. $this->assertCount(1, $crawler->selectImage('\' Fabien"s Bar'), '->selectImage() selects images by alt attribute');
  551. }
  552. public function testSelectButton()
  553. {
  554. $crawler = $this->createTestCrawler();
  555. $this->assertNotSame($crawler, $crawler->selectButton('FooValue'), '->selectButton() returns a new instance of a crawler');
  556. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->selectButton() returns a new instance of a crawler');
  557. $this->assertEquals(1, $crawler->selectButton('FooValue')->count(), '->selectButton() selects buttons');
  558. $this->assertEquals(1, $crawler->selectButton('FooName')->count(), '->selectButton() selects buttons');
  559. $this->assertEquals(1, $crawler->selectButton('FooId')->count(), '->selectButton() selects buttons');
  560. $this->assertEquals(1, $crawler->selectButton('BarValue')->count(), '->selectButton() selects buttons');
  561. $this->assertEquals(1, $crawler->selectButton('BarName')->count(), '->selectButton() selects buttons');
  562. $this->assertEquals(1, $crawler->selectButton('BarId')->count(), '->selectButton() selects buttons');
  563. $this->assertEquals(1, $crawler->selectButton('FooBarValue')->count(), '->selectButton() selects buttons with form attribute too');
  564. $this->assertEquals(1, $crawler->selectButton('FooBarName')->count(), '->selectButton() selects buttons with form attribute too');
  565. }
  566. public function testSelectButtonWithSingleQuotesInNameAttribute()
  567. {
  568. $html = <<<'HTML'
  569. <!DOCTYPE html>
  570. <html lang="en">
  571. <body>
  572. <div id="action">
  573. <a href="/index.php?r=site/login">Login</a>
  574. </div>
  575. <form id="login-form" action="/index.php?r=site/login" method="post">
  576. <button type="submit" name="Click 'Here'">Submit</button>
  577. </form>
  578. </body>
  579. </html>
  580. HTML;
  581. $crawler = new Crawler($html);
  582. $this->assertCount(1, $crawler->selectButton('Click \'Here\''));
  583. }
  584. public function testSelectButtonWithDoubleQuotesInNameAttribute()
  585. {
  586. $html = <<<'HTML'
  587. <!DOCTYPE html>
  588. <html lang="en">
  589. <body>
  590. <div id="action">
  591. <a href="/index.php?r=site/login">Login</a>
  592. </div>
  593. <form id="login-form" action="/index.php?r=site/login" method="post">
  594. <button type="submit" name='Click "Here"'>Submit</button>
  595. </form>
  596. </body>
  597. </html>
  598. HTML;
  599. $crawler = new Crawler($html);
  600. $this->assertCount(1, $crawler->selectButton('Click "Here"'));
  601. }
  602. public function testLink()
  603. {
  604. $crawler = $this->createTestCrawler('http://example.com/bar/')->selectLink('Foo');
  605. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Link', $crawler->link(), '->link() returns a Link instance');
  606. $this->assertEquals('POST', $crawler->link('post')->getMethod(), '->link() takes a method as its argument');
  607. $crawler = $this->createTestCrawler('http://example.com/bar')->selectLink('GetLink');
  608. $this->assertEquals('http://example.com/bar?get=param', $crawler->link()->getUri(), '->link() returns a Link instance');
  609. try {
  610. $this->createTestCrawler()->filterXPath('//ol')->link();
  611. $this->fail('->link() throws an \InvalidArgumentException if the node list is empty');
  612. } catch (\InvalidArgumentException $e) {
  613. $this->assertTrue(true, '->link() throws an \InvalidArgumentException if the node list is empty');
  614. }
  615. }
  616. /**
  617. * @expectedException \InvalidArgumentException
  618. * @expectedExceptionMessage The selected node should be instance of DOMElement
  619. */
  620. public function testInvalidLink()
  621. {
  622. $crawler = $this->createTestCrawler('http://example.com/bar/');
  623. $crawler->filterXPath('//li/text()')->link();
  624. }
  625. /**
  626. * @expectedException \InvalidArgumentException
  627. * @expectedExceptionMessage The selected node should be instance of DOMElement
  628. */
  629. public function testInvalidLinks()
  630. {
  631. $crawler = $this->createTestCrawler('http://example.com/bar/');
  632. $crawler->filterXPath('//li/text()')->link();
  633. }
  634. public function testImage()
  635. {
  636. $crawler = $this->createTestCrawler('http://example.com/bar/')->selectImage('Bar');
  637. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Image', $crawler->image(), '->image() returns an Image instance');
  638. try {
  639. $this->createTestCrawler()->filterXPath('//ol')->image();
  640. $this->fail('->image() throws an \InvalidArgumentException if the node list is empty');
  641. } catch (\InvalidArgumentException $e) {
  642. $this->assertTrue(true, '->image() throws an \InvalidArgumentException if the node list is empty');
  643. }
  644. }
  645. public function testSelectLinkAndLinkFiltered()
  646. {
  647. $html = <<<'HTML'
  648. <!DOCTYPE html>
  649. <html lang="en">
  650. <body>
  651. <div id="action">
  652. <a href="/index.php?r=site/login">Login</a>
  653. </div>
  654. <form id="login-form" action="/index.php?r=site/login" method="post">
  655. <button type="submit">Submit</button>
  656. </form>
  657. </body>
  658. </html>
  659. HTML;
  660. $crawler = new Crawler($html);
  661. $filtered = $crawler->filterXPath("descendant-or-self::*[@id = 'login-form']");
  662. $this->assertCount(0, $filtered->selectLink('Login'));
  663. $this->assertCount(1, $filtered->selectButton('Submit'));
  664. $filtered = $crawler->filterXPath("descendant-or-self::*[@id = 'action']");
  665. $this->assertCount(1, $filtered->selectLink('Login'));
  666. $this->assertCount(0, $filtered->selectButton('Submit'));
  667. $this->assertCount(1, $crawler->selectLink('Login')->selectLink('Login'));
  668. $this->assertCount(1, $crawler->selectButton('Submit')->selectButton('Submit'));
  669. }
  670. public function testChaining()
  671. {
  672. $crawler = new Crawler('<div name="a"><div name="b"><div name="c"></div></div></div>');
  673. $this->assertEquals('a', $crawler->filterXPath('//div')->filterXPath('div')->filterXPath('div')->attr('name'));
  674. }
  675. public function testLinks()
  676. {
  677. $crawler = $this->createTestCrawler('http://example.com/bar/')->selectLink('Foo');
  678. $this->assertInternalType('array', $crawler->links(), '->links() returns an array');
  679. $this->assertCount(4, $crawler->links(), '->links() returns an array');
  680. $links = $crawler->links();
  681. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Link', $links[0], '->links() returns an array of Link instances');
  682. $this->assertEquals(array(), $this->createTestCrawler()->filterXPath('//ol')->links(), '->links() returns an empty array if the node selection is empty');
  683. }
  684. public function testImages()
  685. {
  686. $crawler = $this->createTestCrawler('http://example.com/bar/')->selectImage('Bar');
  687. $this->assertInternalType('array', $crawler->images(), '->images() returns an array');
  688. $this->assertCount(4, $crawler->images(), '->images() returns an array');
  689. $images = $crawler->images();
  690. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Image', $images[0], '->images() returns an array of Image instances');
  691. $this->assertEquals(array(), $this->createTestCrawler()->filterXPath('//ol')->links(), '->links() returns an empty array if the node selection is empty');
  692. }
  693. public function testForm()
  694. {
  695. $testCrawler = $this->createTestCrawler('http://example.com/bar/');
  696. $crawler = $testCrawler->selectButton('FooValue');
  697. $crawler2 = $testCrawler->selectButton('FooBarValue');
  698. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Form', $crawler->form(), '->form() returns a Form instance');
  699. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Form', $crawler2->form(), '->form() returns a Form instance');
  700. $this->assertEquals($crawler->form()->getFormNode()->getAttribute('id'), $crawler2->form()->getFormNode()->getAttribute('id'), '->form() works on elements with form attribute');
  701. $this->assertEquals(array('FooName' => 'FooBar', 'TextName' => 'TextValue', 'FooTextName' => 'FooTextValue'), $crawler->form(array('FooName' => 'FooBar'))->getValues(), '->form() takes an array of values to submit as its first argument');
  702. $this->assertEquals(array('FooName' => 'FooValue', 'TextName' => 'TextValue', 'FooTextName' => 'FooTextValue'), $crawler->form()->getValues(), '->getValues() returns correct form values');
  703. $this->assertEquals(array('FooBarName' => 'FooBarValue', 'TextName' => 'TextValue', 'FooTextName' => 'FooTextValue'), $crawler2->form()->getValues(), '->getValues() returns correct form values');
  704. try {
  705. $this->createTestCrawler()->filterXPath('//ol')->form();
  706. $this->fail('->form() throws an \InvalidArgumentException if the node list is empty');
  707. } catch (\InvalidArgumentException $e) {
  708. $this->assertTrue(true, '->form() throws an \InvalidArgumentException if the node list is empty');
  709. }
  710. }
  711. /**
  712. * @expectedException \InvalidArgumentException
  713. * @expectedExceptionMessage The selected node should be instance of DOMElement
  714. */
  715. public function testInvalidForm()
  716. {
  717. $crawler = $this->createTestCrawler('http://example.com/bar/');
  718. $crawler->filterXPath('//li/text()')->form();
  719. }
  720. public function testLast()
  721. {
  722. $crawler = $this->createTestCrawler()->filterXPath('//ul[1]/li');
  723. $this->assertNotSame($crawler, $crawler->last(), '->last() returns a new instance of a crawler');
  724. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->last() returns a new instance of a crawler');
  725. $this->assertEquals('Three', $crawler->last()->text());
  726. }
  727. public function testFirst()
  728. {
  729. $crawler = $this->createTestCrawler()->filterXPath('//li');
  730. $this->assertNotSame($crawler, $crawler->first(), '->first() returns a new instance of a crawler');
  731. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->first() returns a new instance of a crawler');
  732. $this->assertEquals('One', $crawler->first()->text());
  733. }
  734. public function testSiblings()
  735. {
  736. $crawler = $this->createTestCrawler()->filterXPath('//li')->eq(1);
  737. $this->assertNotSame($crawler, $crawler->siblings(), '->siblings() returns a new instance of a crawler');
  738. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->siblings() returns a new instance of a crawler');
  739. $nodes = $crawler->siblings();
  740. $this->assertEquals(2, $nodes->count());
  741. $this->assertEquals('One', $nodes->eq(0)->text());
  742. $this->assertEquals('Three', $nodes->eq(1)->text());
  743. $nodes = $this->createTestCrawler()->filterXPath('//li')->eq(0)->siblings();
  744. $this->assertEquals(2, $nodes->count());
  745. $this->assertEquals('Two', $nodes->eq(0)->text());
  746. $this->assertEquals('Three', $nodes->eq(1)->text());
  747. try {
  748. $this->createTestCrawler()->filterXPath('//ol')->siblings();
  749. $this->fail('->siblings() throws an \InvalidArgumentException if the node list is empty');
  750. } catch (\InvalidArgumentException $e) {
  751. $this->assertTrue(true, '->siblings() throws an \InvalidArgumentException if the node list is empty');
  752. }
  753. }
  754. public function testNextAll()
  755. {
  756. $crawler = $this->createTestCrawler()->filterXPath('//li')->eq(1);
  757. $this->assertNotSame($crawler, $crawler->nextAll(), '->nextAll() returns a new instance of a crawler');
  758. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->nextAll() returns a new instance of a crawler');
  759. $nodes = $crawler->nextAll();
  760. $this->assertEquals(1, $nodes->count());
  761. $this->assertEquals('Three', $nodes->eq(0)->text());
  762. try {
  763. $this->createTestCrawler()->filterXPath('//ol')->nextAll();
  764. $this->fail('->nextAll() throws an \InvalidArgumentException if the node list is empty');
  765. } catch (\InvalidArgumentException $e) {
  766. $this->assertTrue(true, '->nextAll() throws an \InvalidArgumentException if the node list is empty');
  767. }
  768. }
  769. public function testPreviousAll()
  770. {
  771. $crawler = $this->createTestCrawler()->filterXPath('//li')->eq(2);
  772. $this->assertNotSame($crawler, $crawler->previousAll(), '->previousAll() returns a new instance of a crawler');
  773. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->previousAll() returns a new instance of a crawler');
  774. $nodes = $crawler->previousAll();
  775. $this->assertEquals(2, $nodes->count());
  776. $this->assertEquals('Two', $nodes->eq(0)->text());
  777. try {
  778. $this->createTestCrawler()->filterXPath('//ol')->previousAll();
  779. $this->fail('->previousAll() throws an \InvalidArgumentException if the node list is empty');
  780. } catch (\InvalidArgumentException $e) {
  781. $this->assertTrue(true, '->previousAll() throws an \InvalidArgumentException if the node list is empty');
  782. }
  783. }
  784. public function testChildren()
  785. {
  786. $crawler = $this->createTestCrawler()->filterXPath('//ul');
  787. $this->assertNotSame($crawler, $crawler->children(), '->children() returns a new instance of a crawler');
  788. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->children() returns a new instance of a crawler');
  789. $nodes = $crawler->children();
  790. $this->assertEquals(3, $nodes->count());
  791. $this->assertEquals('One', $nodes->eq(0)->text());
  792. $this->assertEquals('Two', $nodes->eq(1)->text());
  793. $this->assertEquals('Three', $nodes->eq(2)->text());
  794. try {
  795. $this->createTestCrawler()->filterXPath('//ol')->children();
  796. $this->fail('->children() throws an \InvalidArgumentException if the node list is empty');
  797. } catch (\InvalidArgumentException $e) {
  798. $this->assertTrue(true, '->children() throws an \InvalidArgumentException if the node list is empty');
  799. }
  800. try {
  801. $crawler = new Crawler('<p></p>');
  802. $crawler->filter('p')->children();
  803. $this->assertTrue(true, '->children() does not trigger a notice if the node has no children');
  804. } catch (\PHPUnit_Framework_Error_Notice $e) {
  805. $this->fail('->children() does not trigger a notice if the node has no children');
  806. }
  807. }
  808. public function testParents()
  809. {
  810. $crawler = $this->createTestCrawler()->filterXPath('//li[1]');
  811. $this->assertNotSame($crawler, $crawler->parents(), '->parents() returns a new instance of a crawler');
  812. $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->parents() returns a new instance of a crawler');
  813. $nodes = $crawler->parents();
  814. $this->assertEquals(3, $nodes->count());
  815. $nodes = $this->createTestCrawler()->filterXPath('//html')->parents();
  816. $this->assertEquals(0, $nodes->count());
  817. try {
  818. $this->createTestCrawler()->filterXPath('//ol')->parents();
  819. $this->fail('->parents() throws an \InvalidArgumentException if the node list is empty');
  820. } catch (\InvalidArgumentException $e) {
  821. $this->assertTrue(true, '->parents() throws an \InvalidArgumentException if the node list is empty');
  822. }
  823. }
  824. /**
  825. * @dataProvider getBaseTagData
  826. */
  827. public function testBaseTag($baseValue, $linkValue, $expectedUri, $currentUri = null, $description = null)
  828. {
  829. $crawler = new Crawler('<html><base href="'.$baseValue.'"><a href="'.$linkValue.'"></a></html>', $currentUri);
  830. $this->assertEquals($expectedUri, $crawler->filterXPath('//a')->link()->getUri(), $description);
  831. }
  832. public function getBaseTagData()
  833. {
  834. return array(
  835. array('http://base.com', 'link', 'http://base.com/link'),
  836. array('//base.com', 'link', 'https://base.com/link', 'https://domain.com', '<base> tag can use a schema-less URL'),
  837. array('path/', 'link', 'https://domain.com/path/link', 'https://domain.com', '<base> tag can set a path'),
  838. array('http://base.com', '#', 'http://base.com#', 'http://domain.com/path/link', '<base> tag does work with links to an anchor'),
  839. array('http://base.com', '', 'http://base.com', 'http://domain.com/path/link', '<base> tag does work with empty links'),
  840. );
  841. }
  842. /**
  843. * @dataProvider getBaseTagWithFormData
  844. */
  845. public function testBaseTagWithForm($baseValue, $actionValue, $expectedUri, $currentUri = null, $description = null)
  846. {
  847. $crawler = new Crawler('<html><base href="'.$baseValue.'"><form method="post" action="'.$actionValue.'"><button type="submit" name="submit"/></form></html>', $currentUri);
  848. $this->assertEquals($expectedUri, $crawler->filterXPath('//button')->form()->getUri(), $description);
  849. }
  850. public function getBaseTagWithFormData()
  851. {
  852. return array(
  853. array('https://base.com/', 'link/', 'https://base.com/link/', 'https://base.com/link/', '<base> tag does work with a path and relative form action'),
  854. array('/basepath', '/registration', 'http://domain.com/registration', 'http://domain.com/registration', '<base> tag does work with a path and form action'),
  855. array('/basepath', '', 'http://domain.com/registration', 'http://domain.com/registration', '<base> tag does work with a path and empty form action'),
  856. array('http://base.com/', '/registration', 'http://base.com/registration', 'http://domain.com/registration', '<base> tag does work with a URL and form action'),
  857. array('http://base.com', '', 'http://domain.com/path/form', 'http://domain.com/path/form', '<base> tag does work with a URL and an empty form action'),
  858. array('http://base.com/path', '/registration', 'http://base.com/registration', 'http://domain.com/path/form', '<base> tag does work with a URL and form action'),
  859. );
  860. }
  861. public function testCountOfNestedElements()
  862. {
  863. $crawler = new Crawler('<html><body><ul><li>List item 1<ul><li>Sublist item 1</li><li>Sublist item 2</ul></li></ul></body></html>');
  864. $this->assertCount(1, $crawler->filter('li:contains("List item 1")'));
  865. }
  866. public function testEvaluateReturnsTypedResultOfXPathExpressionOnADocumentSubset()
  867. {
  868. $crawler = $this->createTestCrawler();
  869. $result = $crawler->filterXPath('//form/input')->evaluate('substring-before(@name, "Name")');
  870. $this->assertSame(array('Text', 'Foo', 'Bar'), $result);
  871. }
  872. public function testEvaluateReturnsTypedResultOfNamespacedXPathExpressionOnADocumentSubset()
  873. {
  874. $crawler = $this->createTestXmlCrawler();
  875. $result = $crawler->filterXPath('//yt:accessControl/@action')->evaluate('string(.)');
  876. $this->assertSame(array('comment', 'videoRespond'), $result);
  877. }
  878. public function testEvaluateReturnsTypedResultOfNamespacedXPathExpression()
  879. {
  880. $crawler = $this->createTestXmlCrawler();
  881. $crawler->registerNamespace('youtube', 'http://gdata.youtube.com/schemas/2007');
  882. $result = $crawler->evaluate('string(//youtube:accessControl/@action)');
  883. $this->assertSame(array('comment'), $result);
  884. }
  885. public function testEvaluateReturnsACrawlerIfXPathExpressionEvaluatesToANode()
  886. {
  887. $crawler = $this->createTestCrawler()->evaluate('//form/input[1]');
  888. $this->assertInstanceOf(Crawler::class, $crawler);
  889. $this->assertCount(1, $crawler);
  890. $this->assertSame('input', $crawler->first()->nodeName());
  891. }
  892. /**
  893. * @expectedException \LogicException
  894. */
  895. public function testEvaluateThrowsAnExceptionIfDocumentIsEmpty()
  896. {
  897. (new Crawler())->evaluate('//form/input[1]');
  898. }
  899. public function createTestCrawler($uri = null)
  900. {
  901. $dom = new \DOMDocument();
  902. $dom->loadHTML('
  903. <html>
  904. <body>
  905. <a href="foo">Foo</a>
  906. <a href="/foo"> Fabien\'s Foo </a>
  907. <a href="/foo">Fabien"s Foo</a>
  908. <a href="/foo">\' Fabien"s Foo</a>
  909. <a href="/bar"><img alt="Bar"/></a>
  910. <a href="/bar"><img alt=" Fabien\'s Bar "/></a>
  911. <a href="/bar"><img alt="Fabien&quot;s Bar"/></a>
  912. <a href="/bar"><img alt="\' Fabien&quot;s Bar"/></a>
  913. <a href="?get=param">GetLink</a>
  914. <a href="/example">Klausi|Claudiu</a>
  915. <form action="foo" id="FooFormId">
  916. <input type="text" value="TextValue" name="TextName" />
  917. <input type="submit" value="FooValue" name="FooName" id="FooId" />
  918. <input type="button" value="BarValue" name="BarName" id="BarId" />
  919. <button value="ButtonValue" name="ButtonName" id="ButtonId" />
  920. </form>
  921. <input type="submit" value="FooBarValue" name="FooBarName" form="FooFormId" />
  922. <input type="text" value="FooTextValue" name="FooTextName" form="FooFormId" />
  923. <ul class="first">
  924. <li class="first">One</li>
  925. <li>Two</li>
  926. <li>Three</li>
  927. </ul>
  928. <ul>
  929. <li>One Bis</li>
  930. <li>Two Bis</li>
  931. <li>Three Bis</li>
  932. </ul>
  933. <div id="parent">
  934. <div id="child"></div>
  935. <div id="child2" xmlns:foo="http://example.com"></div>
  936. </div>
  937. <div id="sibling"><img /></div>
  938. </body>
  939. </html>
  940. ');
  941. return new Crawler($dom, $uri);
  942. }
  943. protected function createTestXmlCrawler($uri = null)
  944. {
  945. $xml = '<?xml version="1.0" encoding="UTF-8"?>
  946. <entry xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:yt="http://gdata.youtube.com/schemas/2007">
  947. <id>tag:youtube.com,2008:video:kgZRZmEc9j4</id>
  948. <yt:accessControl action="comment" permission="allowed"/>
  949. <yt:accessControl action="videoRespond" permission="moderated"/>
  950. <media:group>
  951. <media:title type="plain">Chordates - CrashCourse Biology #24</media:title>
  952. <yt:aspectRatio>widescreen</yt:aspectRatio>
  953. </media:group>
  954. <media:category label="Music" scheme="http://gdata.youtube.com/schemas/2007/categories.cat">Music</media:category>
  955. </entry>';
  956. return new Crawler($xml, $uri);
  957. }
  958. protected function createDomDocument()
  959. {
  960. $dom = new \DOMDocument();
  961. $dom->loadXML('<html><div class="foo"></div></html>');
  962. return $dom;
  963. }
  964. protected function createNodeList()
  965. {
  966. $dom = new \DOMDocument();
  967. $dom->loadXML('<html><div class="foo"></div></html>');
  968. $domxpath = new \DOMXPath($dom);
  969. return $domxpath->query('//div');
  970. }
  971. }