search.test

Tests for search.module.

File

drupal/modules/search/search.test
View source
  1. <?php
  2. /**
  3. * @file
  4. * Tests for search.module.
  5. */
  6. // The search index can contain different types of content. Typically the type is 'node'.
  7. // Here we test with _test_ and _test2_ as the type.
  8. define('SEARCH_TYPE', '_test_');
  9. define('SEARCH_TYPE_2', '_test2_');
  10. define('SEARCH_TYPE_JPN', '_test3_');
  11. class SearchMatchTestCase extends DrupalWebTestCase {
  12. public static function getInfo() {
  13. return array(
  14. 'name' => 'Search engine queries',
  15. 'description' => 'Indexes content and queries it.',
  16. 'group' => 'Search',
  17. );
  18. }
  19. /**
  20. * Implementation setUp().
  21. */
  22. function setUp() {
  23. parent::setUp('search');
  24. }
  25. /**
  26. * Test search indexing.
  27. */
  28. function testMatching() {
  29. $this->_setup();
  30. $this->_testQueries();
  31. }
  32. /**
  33. * Set up a small index of items to test against.
  34. */
  35. function _setup() {
  36. variable_set('minimum_word_size', 3);
  37. for ($i = 1; $i <= 7; ++$i) {
  38. search_index($i, SEARCH_TYPE, $this->getText($i));
  39. }
  40. for ($i = 1; $i <= 5; ++$i) {
  41. search_index($i + 7, SEARCH_TYPE_2, $this->getText2($i));
  42. }
  43. // No getText builder function for Japanese text; just a simple array.
  44. foreach (array(
  45. 13 => '以呂波耳・ほへとち。リヌルヲ。',
  46. 14 => 'ドルーパルが大好きよ!',
  47. 15 => 'コーヒーとケーキ',
  48. ) as $i => $jpn) {
  49. search_index($i, SEARCH_TYPE_JPN, $jpn);
  50. }
  51. search_update_totals();
  52. }
  53. /**
  54. * _test_: Helper method for generating snippets of content.
  55. *
  56. * Generated items to test against:
  57. * 1 ipsum
  58. * 2 dolore sit
  59. * 3 sit am ut
  60. * 4 am ut enim am
  61. * 5 ut enim am minim veniam
  62. * 6 enim am minim veniam es cillum
  63. * 7 am minim veniam es cillum dolore eu
  64. */
  65. function getText($n) {
  66. $words = explode(' ', "Ipsum dolore sit am. Ut enim am minim veniam. Es cillum dolore eu.");
  67. return implode(' ', array_slice($words, $n - 1, $n));
  68. }
  69. /**
  70. * _test2_: Helper method for generating snippets of content.
  71. *
  72. * Generated items to test against:
  73. * 8 dear
  74. * 9 king philip
  75. * 10 philip came over
  76. * 11 came over from germany
  77. * 12 over from germany swimming
  78. */
  79. function getText2($n) {
  80. $words = explode(' ', "Dear King Philip came over from Germany swimming.");
  81. return implode(' ', array_slice($words, $n - 1, $n));
  82. }
  83. /**
  84. * Run predefine queries looking for indexed terms.
  85. */
  86. function _testQueries() {
  87. /*
  88. Note: OR queries that include short words in OR groups are only accepted
  89. if the ORed terms are ANDed with at least one long word in the rest of the query.
  90. e.g. enim dolore OR ut = enim (dolore OR ut) = (enim dolor) OR (enim ut) -> good
  91. e.g. dolore OR ut = (dolore) OR (ut) -> bad
  92. This is a design limitation to avoid full table scans.
  93. */
  94. $queries = array(
  95. // Simple AND queries.
  96. 'ipsum' => array(1),
  97. 'enim' => array(4, 5, 6),
  98. 'xxxxx' => array(),
  99. 'enim minim' => array(5, 6),
  100. 'enim xxxxx' => array(),
  101. 'dolore eu' => array(7),
  102. 'dolore xx' => array(),
  103. 'ut minim' => array(5),
  104. 'xx minim' => array(),
  105. 'enim veniam am minim ut' => array(5),
  106. // Simple OR queries.
  107. 'dolore OR ipsum' => array(1, 2, 7),
  108. 'dolore OR xxxxx' => array(2, 7),
  109. 'dolore OR ipsum OR enim' => array(1, 2, 4, 5, 6, 7),
  110. 'ipsum OR dolore sit OR cillum' => array(2, 7),
  111. 'minim dolore OR ipsum' => array(7),
  112. 'dolore OR ipsum veniam' => array(7),
  113. 'minim dolore OR ipsum OR enim' => array(5, 6, 7),
  114. 'dolore xx OR yy' => array(),
  115. 'xxxxx dolore OR ipsum' => array(),
  116. // Negative queries.
  117. 'dolore -sit' => array(7),
  118. 'dolore -eu' => array(2),
  119. 'dolore -xxxxx' => array(2, 7),
  120. 'dolore -xx' => array(2, 7),
  121. // Phrase queries.
  122. '"dolore sit"' => array(2),
  123. '"sit dolore"' => array(),
  124. '"am minim veniam es"' => array(6, 7),
  125. '"minim am veniam es"' => array(),
  126. // Mixed queries.
  127. '"am minim veniam es" OR dolore' => array(2, 6, 7),
  128. '"minim am veniam es" OR "dolore sit"' => array(2),
  129. '"minim am veniam es" OR "sit dolore"' => array(),
  130. '"am minim veniam es" -eu' => array(6),
  131. '"am minim veniam" -"cillum dolore"' => array(5, 6),
  132. '"am minim veniam" -"dolore cillum"' => array(5, 6, 7),
  133. 'xxxxx "minim am veniam es" OR dolore' => array(),
  134. 'xx "minim am veniam es" OR dolore' => array()
  135. );
  136. foreach ($queries as $query => $results) {
  137. $result = db_select('search_index', 'i')
  138. ->extend('SearchQuery')
  139. ->searchExpression($query, SEARCH_TYPE)
  140. ->execute();
  141. $set = $result ? $result->fetchAll() : array();
  142. $this->_testQueryMatching($query, $set, $results);
  143. $this->_testQueryScores($query, $set, $results);
  144. }
  145. // These queries are run against the second index type, SEARCH_TYPE_2.
  146. $queries = array(
  147. // Simple AND queries.
  148. 'ipsum' => array(),
  149. 'enim' => array(),
  150. 'enim minim' => array(),
  151. 'dear' => array(8),
  152. 'germany' => array(11, 12),
  153. );
  154. foreach ($queries as $query => $results) {
  155. $result = db_select('search_index', 'i')
  156. ->extend('SearchQuery')
  157. ->searchExpression($query, SEARCH_TYPE_2)
  158. ->execute();
  159. $set = $result ? $result->fetchAll() : array();
  160. $this->_testQueryMatching($query, $set, $results);
  161. $this->_testQueryScores($query, $set, $results);
  162. }
  163. // These queries are run against the third index type, SEARCH_TYPE_JPN.
  164. $queries = array(
  165. // Simple AND queries.
  166. '呂波耳' => array(13),
  167. '以呂波耳' => array(13),
  168. 'ほへと ヌルヲ' => array(13),
  169. 'とちリ' => array(),
  170. 'ドルーパル' => array(14),
  171. 'パルが大' => array(14),
  172. 'コーヒー' => array(15),
  173. 'ヒーキ' => array(),
  174. );
  175. foreach ($queries as $query => $results) {
  176. $result = db_select('search_index', 'i')
  177. ->extend('SearchQuery')
  178. ->searchExpression($query, SEARCH_TYPE_JPN)
  179. ->execute();
  180. $set = $result ? $result->fetchAll() : array();
  181. $this->_testQueryMatching($query, $set, $results);
  182. $this->_testQueryScores($query, $set, $results);
  183. }
  184. }
  185. /**
  186. * Test the matching abilities of the engine.
  187. *
  188. * Verify if a query produces the correct results.
  189. */
  190. function _testQueryMatching($query, $set, $results) {
  191. // Get result IDs.
  192. $found = array();
  193. foreach ($set as $item) {
  194. $found[] = $item->sid;
  195. }
  196. // Compare $results and $found.
  197. sort($found);
  198. sort($results);
  199. $this->assertEqual($found, $results, "Query matching '$query'");
  200. }
  201. /**
  202. * Test the scoring abilities of the engine.
  203. *
  204. * Verify if a query produces normalized, monotonous scores.
  205. */
  206. function _testQueryScores($query, $set, $results) {
  207. // Get result scores.
  208. $scores = array();
  209. foreach ($set as $item) {
  210. $scores[] = $item->calculated_score;
  211. }
  212. // Check order.
  213. $sorted = $scores;
  214. sort($sorted);
  215. $this->assertEqual($scores, array_reverse($sorted), "Query order '$query'");
  216. // Check range.
  217. $this->assertEqual(!count($scores) || (min($scores) > 0.0 && max($scores) <= 1.0001), TRUE, "Query scoring '$query'");
  218. }
  219. }
  220. /**
  221. * Tests the bike shed text on no results page, and text on the search page.
  222. */
  223. class SearchPageText extends DrupalWebTestCase {
  224. protected $searching_user;
  225. public static function getInfo() {
  226. return array(
  227. 'name' => 'Search page text',
  228. 'description' => 'Tests the bike shed text on the no results page, and various other text on search pages.',
  229. 'group' => 'Search'
  230. );
  231. }
  232. function setUp() {
  233. parent::setUp('search');
  234. // Create user.
  235. $this->searching_user = $this->drupalCreateUser(array('search content', 'access user profiles'));
  236. }
  237. /**
  238. * Tests the failed search text, and various other text on the search page.
  239. */
  240. function testSearchText() {
  241. $this->drupalLogin($this->searching_user);
  242. $this->drupalGet('search/node');
  243. $this->assertText(t('Enter your keywords'));
  244. $this->assertText(t('Search'));
  245. $title = t('Search') . ' | Drupal';
  246. $this->assertTitle($title, 'Search page title is correct');
  247. $edit = array();
  248. $edit['keys'] = 'bike shed ' . $this->randomName();
  249. $this->drupalPost('search/node', $edit, t('Search'));
  250. $this->assertText(t('Consider loosening your query with OR. bike OR shed will often show more results than bike shed.'), 'Help text is displayed when search returns no results.');
  251. $this->assertText(t('Search'));
  252. $this->assertTitle($title, 'Search page title is correct');
  253. $edit['keys'] = $this->searching_user->name;
  254. $this->drupalPost('search/user', $edit, t('Search'));
  255. $this->assertText(t('Search'));
  256. $this->assertTitle($title, 'Search page title is correct');
  257. // Test that search keywords containing slashes are correctly loaded
  258. // from the path and displayed in the search form.
  259. $arg = $this->randomName() . '/' . $this->randomName();
  260. $this->drupalGet('search/node/' . $arg);
  261. $input = $this->xpath("//input[@id='edit-keys' and @value='{$arg}']");
  262. $this->assertFalse(empty($input), 'Search keys with a / are correctly set as the default value in the search box.');
  263. // Test a search input exceeding the limit of AND/OR combinations to test
  264. // the Denial-of-Service protection.
  265. $limit = variable_get('search_and_or_limit', 7);
  266. $keys = array();
  267. for ($i = 0; $i < $limit + 1; $i++) {
  268. $keys[] = $this->randomName(3);
  269. if ($i % 2 == 0) {
  270. $keys[] = 'OR';
  271. }
  272. }
  273. $edit['keys'] = implode(' ', $keys);
  274. $this->drupalPost('search/node', $edit, t('Search'));
  275. $this->assertRaw(t('Your search used too many AND/OR expressions. Only the first @count terms were included in this search.', array('@count' => $limit)));
  276. }
  277. }
  278. class SearchAdvancedSearchForm extends DrupalWebTestCase {
  279. protected $node;
  280. public static function getInfo() {
  281. return array(
  282. 'name' => 'Advanced search form',
  283. 'description' => 'Indexes content and tests the advanced search form.',
  284. 'group' => 'Search',
  285. );
  286. }
  287. function setUp() {
  288. parent::setUp('search');
  289. // Create and login user.
  290. $test_user = $this->drupalCreateUser(array('access content', 'search content', 'use advanced search', 'administer nodes'));
  291. $this->drupalLogin($test_user);
  292. // Create initial node.
  293. $node = $this->drupalCreateNode();
  294. $this->node = $this->drupalCreateNode();
  295. // First update the index. This does the initial processing.
  296. node_update_index();
  297. // Then, run the shutdown function. Testing is a unique case where indexing
  298. // and searching has to happen in the same request, so running the shutdown
  299. // function manually is needed to finish the indexing process.
  300. search_update_totals();
  301. }
  302. /**
  303. * Test using the search form with GET and POST queries.
  304. * Test using the advanced search form to limit search to nodes of type "Basic page".
  305. */
  306. function testNodeType() {
  307. $this->assertTrue($this->node->type == 'page', 'Node type is Basic page.');
  308. // Assert that the dummy title doesn't equal the real title.
  309. $dummy_title = 'Lorem ipsum';
  310. $this->assertNotEqual($dummy_title, $this->node->title, "Dummy title doesn't equal node title");
  311. // Search for the dummy title with a GET query.
  312. $this->drupalGet('search/node/' . $dummy_title);
  313. $this->assertNoText($this->node->title, 'Basic page node is not found with dummy title.');
  314. // Search for the title of the node with a GET query.
  315. $this->drupalGet('search/node/' . $this->node->title);
  316. $this->assertText($this->node->title, 'Basic page node is found with GET query.');
  317. // Search for the title of the node with a POST query.
  318. $edit = array('or' => $this->node->title);
  319. $this->drupalPost('search/node', $edit, t('Advanced search'));
  320. $this->assertText($this->node->title, 'Basic page node is found with POST query.');
  321. // Advanced search type option.
  322. $this->drupalPost('search/node', array_merge($edit, array('type[page]' => 'page')), t('Advanced search'));
  323. $this->assertText($this->node->title, 'Basic page node is found with POST query and type:page.');
  324. $this->drupalPost('search/node', array_merge($edit, array('type[article]' => 'article')), t('Advanced search'));
  325. $this->assertText('bike shed', 'Article node is not found with POST query and type:article.');
  326. }
  327. }
  328. class SearchRankingTestCase extends DrupalWebTestCase {
  329. public static function getInfo() {
  330. return array(
  331. 'name' => 'Search engine ranking',
  332. 'description' => 'Indexes content and tests ranking factors.',
  333. 'group' => 'Search',
  334. );
  335. }
  336. /**
  337. * Implementation setUp().
  338. */
  339. function setUp() {
  340. parent::setUp('search', 'statistics', 'comment');
  341. }
  342. function testRankings() {
  343. // Login with sufficient privileges.
  344. $this->drupalLogin($this->drupalCreateUser(array('skip comment approval', 'create page content')));
  345. // Build a list of the rankings to test.
  346. $node_ranks = array('sticky', 'promote', 'relevance', 'recent', 'comments', 'views');
  347. // Create nodes for testing.
  348. foreach ($node_ranks as $node_rank) {
  349. $settings = array(
  350. 'type' => 'page',
  351. 'title' => 'Drupal rocks',
  352. 'body' => array(LANGUAGE_NONE => array(array('value' => "Drupal's search rocks"))),
  353. );
  354. foreach (array(0, 1) as $num) {
  355. if ($num == 1) {
  356. switch ($node_rank) {
  357. case 'sticky':
  358. case 'promote':
  359. $settings[$node_rank] = 1;
  360. break;
  361. case 'relevance':
  362. $settings['body'][LANGUAGE_NONE][0]['value'] .= " really rocks";
  363. break;
  364. case 'recent':
  365. $settings['created'] = REQUEST_TIME + 3600;
  366. break;
  367. case 'comments':
  368. $settings['comment'] = 2;
  369. break;
  370. }
  371. }
  372. $nodes[$node_rank][$num] = $this->drupalCreateNode($settings);
  373. }
  374. }
  375. // Update the search index.
  376. module_invoke_all('update_index');
  377. search_update_totals();
  378. // Refresh variables after the treatment.
  379. $this->refreshVariables();
  380. // Add a comment to one of the nodes.
  381. $edit = array();
  382. $edit['subject'] = 'my comment title';
  383. $edit['comment_body[' . LANGUAGE_NONE . '][0][value]'] = 'some random comment';
  384. $this->drupalGet('comment/reply/' . $nodes['comments'][1]->nid);
  385. $this->drupalPost(NULL, $edit, t('Preview'));
  386. $this->drupalPost(NULL, $edit, t('Save'));
  387. // Enable counting of statistics.
  388. variable_set('statistics_count_content_views', 1);
  389. // Then View one of the nodes a bunch of times.
  390. for ($i = 0; $i < 5; $i ++) {
  391. $this->drupalGet('node/' . $nodes['views'][1]->nid);
  392. }
  393. // Test each of the possible rankings.
  394. foreach ($node_ranks as $node_rank) {
  395. // Disable all relevancy rankings except the one we are testing.
  396. foreach ($node_ranks as $var) {
  397. variable_set('node_rank_' . $var, $var == $node_rank ? 10 : 0);
  398. }
  399. // Do the search and assert the results.
  400. $set = node_search_execute('rocks');
  401. $this->assertEqual($set[0]['node']->nid, $nodes[$node_rank][1]->nid, 'Search ranking "' . $node_rank . '" order.');
  402. }
  403. }
  404. /**
  405. * Test rankings of HTML tags.
  406. */
  407. function testHTMLRankings() {
  408. // Login with sufficient privileges.
  409. $this->drupalLogin($this->drupalCreateUser(array('create page content')));
  410. // Test HTML tags with different weights.
  411. $sorted_tags = array('h1', 'h2', 'h3', 'h4', 'a', 'h5', 'h6', 'notag');
  412. $shuffled_tags = $sorted_tags;
  413. // Shuffle tags to ensure HTML tags are ranked properly.
  414. shuffle($shuffled_tags);
  415. $settings = array(
  416. 'type' => 'page',
  417. 'title' => 'Simple node',
  418. );
  419. foreach ($shuffled_tags as $tag) {
  420. switch ($tag) {
  421. case 'a':
  422. $settings['body'] = array(LANGUAGE_NONE => array(array('value' => l('Drupal Rocks', 'node'), 'format' => 'full_html')));
  423. break;
  424. case 'notag':
  425. $settings['body'] = array(LANGUAGE_NONE => array(array('value' => 'Drupal Rocks')));
  426. break;
  427. default:
  428. $settings['body'] = array(LANGUAGE_NONE => array(array('value' => "<$tag>Drupal Rocks</$tag>", 'format' => 'full_html')));
  429. break;
  430. }
  431. $nodes[$tag] = $this->drupalCreateNode($settings);
  432. }
  433. // Update the search index.
  434. module_invoke_all('update_index');
  435. search_update_totals();
  436. // Refresh variables after the treatment.
  437. $this->refreshVariables();
  438. // Disable all other rankings.
  439. $node_ranks = array('sticky', 'promote', 'recent', 'comments', 'views');
  440. foreach ($node_ranks as $node_rank) {
  441. variable_set('node_rank_' . $node_rank, 0);
  442. }
  443. $set = node_search_execute('rocks');
  444. // Test the ranking of each tag.
  445. foreach ($sorted_tags as $tag_rank => $tag) {
  446. // Assert the results.
  447. if ($tag == 'notag') {
  448. $this->assertEqual($set[$tag_rank]['node']->nid, $nodes[$tag]->nid, 'Search tag ranking for plain text order.');
  449. } else {
  450. $this->assertEqual($set[$tag_rank]['node']->nid, $nodes[$tag]->nid, 'Search tag ranking for "&lt;' . $sorted_tags[$tag_rank] . '&gt;" order.');
  451. }
  452. }
  453. // Test tags with the same weight against the sorted tags.
  454. $unsorted_tags = array('u', 'b', 'i', 'strong', 'em');
  455. foreach ($unsorted_tags as $tag) {
  456. $settings['body'] = array(LANGUAGE_NONE => array(array('value' => "<$tag>Drupal Rocks</$tag>", 'format' => 'full_html')));
  457. $node = $this->drupalCreateNode($settings);
  458. // Update the search index.
  459. module_invoke_all('update_index');
  460. search_update_totals();
  461. // Refresh variables after the treatment.
  462. $this->refreshVariables();
  463. $set = node_search_execute('rocks');
  464. // Ranking should always be second to last.
  465. $set = array_slice($set, -2, 1);
  466. // Assert the results.
  467. $this->assertEqual($set[0]['node']->nid, $node->nid, 'Search tag ranking for "&lt;' . $tag . '&gt;" order.');
  468. // Delete node so it doesn't show up in subsequent search results.
  469. node_delete($node->nid);
  470. }
  471. }
  472. /**
  473. * Verifies that if we combine two rankings, search still works.
  474. *
  475. * See issue http://drupal.org/node/771596
  476. */
  477. function testDoubleRankings() {
  478. // Login with sufficient privileges.
  479. $this->drupalLogin($this->drupalCreateUser(array('skip comment approval', 'create page content')));
  480. // See testRankings() above - build a node that will rank high for sticky.
  481. $settings = array(
  482. 'type' => 'page',
  483. 'title' => 'Drupal rocks',
  484. 'body' => array(LANGUAGE_NONE => array(array('value' => "Drupal's search rocks"))),
  485. 'sticky' => 1,
  486. );
  487. $node = $this->drupalCreateNode($settings);
  488. // Update the search index.
  489. module_invoke_all('update_index');
  490. search_update_totals();
  491. // Refresh variables after the treatment.
  492. $this->refreshVariables();
  493. // Set up for ranking sticky and lots of comments; make sure others are
  494. // disabled.
  495. $node_ranks = array('sticky', 'promote', 'relevance', 'recent', 'comments', 'views');
  496. foreach ($node_ranks as $var) {
  497. $value = ($var == 'sticky' || $var == 'comments') ? 10 : 0;
  498. variable_set('node_rank_' . $var, $value);
  499. }
  500. // Do the search and assert the results.
  501. $set = node_search_execute('rocks');
  502. $this->assertEqual($set[0]['node']->nid, $node->nid, 'Search double ranking order.');
  503. }
  504. }
  505. class SearchBlockTestCase extends DrupalWebTestCase {
  506. public static function getInfo() {
  507. return array(
  508. 'name' => 'Block availability',
  509. 'description' => 'Check if the search form block is available.',
  510. 'group' => 'Search',
  511. );
  512. }
  513. function setUp() {
  514. parent::setUp('search');
  515. // Create and login user
  516. $admin_user = $this->drupalCreateUser(array('administer blocks', 'search content'));
  517. $this->drupalLogin($admin_user);
  518. }
  519. function testSearchFormBlock() {
  520. // Set block title to confirm that the interface is available.
  521. $this->drupalPost('admin/structure/block/manage/search/form/configure', array('title' => $this->randomName(8)), t('Save block'));
  522. $this->assertText(t('The block configuration has been saved.'), 'Block configuration set.');
  523. // Set the block to a region to confirm block is available.
  524. $edit = array();
  525. $edit['blocks[search_form][region]'] = 'footer';
  526. $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
  527. $this->assertText(t('The block settings have been updated.'), 'Block successfully move to footer region.');
  528. }
  529. /**
  530. * Test that the search block form works correctly.
  531. */
  532. function testBlock() {
  533. // Enable the block, and place it in the 'content' region so that it isn't
  534. // hidden on 404 pages.
  535. $edit = array('blocks[search_form][region]' => 'content');
  536. $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
  537. // Test a normal search via the block form, from the front page.
  538. $terms = array('search_block_form' => 'test');
  539. $this->drupalPost('node', $terms, t('Search'));
  540. $this->assertText('Your search yielded no results');
  541. // Test a search from the block on a 404 page.
  542. $this->drupalGet('foo');
  543. $this->assertResponse(404);
  544. $this->drupalPost(NULL, $terms, t('Search'));
  545. $this->assertResponse(200);
  546. $this->assertText('Your search yielded no results');
  547. // Test a search from the block when it doesn't appear on the search page.
  548. $edit = array('pages' => 'search');
  549. $this->drupalPost('admin/structure/block/manage/search/form/configure', $edit, t('Save block'));
  550. $this->drupalPost('node', $terms, t('Search'));
  551. $this->assertText('Your search yielded no results');
  552. // Confirm that the user is redirected to the search page.
  553. $this->assertEqual(
  554. $this->getUrl(),
  555. url('search/node/' . $terms['search_block_form'], array('absolute' => TRUE)),
  556. 'Redirected to correct url.'
  557. );
  558. // Test an empty search via the block form, from the front page.
  559. $terms = array('search_block_form' => '');
  560. $this->drupalPost('node', $terms, t('Search'));
  561. $this->assertText('Please enter some keywords');
  562. // Confirm that the user is redirected to the search page, when form is submitted empty.
  563. $this->assertEqual(
  564. $this->getUrl(),
  565. url('search/node/', array('absolute' => TRUE)),
  566. 'Redirected to correct url.'
  567. );
  568. }
  569. }
  570. /**
  571. * Tests that searching for a phrase gets the correct page count.
  572. */
  573. class SearchExactTestCase extends DrupalWebTestCase {
  574. public static function getInfo() {
  575. return array(
  576. 'name' => 'Search engine phrase queries',
  577. 'description' => 'Tests that searching for a phrase gets the correct page count.',
  578. 'group' => 'Search',
  579. );
  580. }
  581. function setUp() {
  582. parent::setUp('search');
  583. }
  584. /**
  585. * Tests that the correct number of pager links are found for both keywords and phrases.
  586. */
  587. function testExactQuery() {
  588. // Login with sufficient privileges.
  589. $this->drupalLogin($this->drupalCreateUser(array('create page content', 'search content')));
  590. $settings = array(
  591. 'type' => 'page',
  592. 'title' => 'Simple Node',
  593. );
  594. // Create nodes with exact phrase.
  595. for ($i = 0; $i <= 17; $i++) {
  596. $settings['body'] = array(LANGUAGE_NONE => array(array('value' => 'love pizza')));
  597. $this->drupalCreateNode($settings);
  598. }
  599. // Create nodes containing keywords.
  600. for ($i = 0; $i <= 17; $i++) {
  601. $settings['body'] = array(LANGUAGE_NONE => array(array('value' => 'love cheesy pizza')));
  602. $this->drupalCreateNode($settings);
  603. }
  604. // Update the search index.
  605. module_invoke_all('update_index');
  606. search_update_totals();
  607. // Refresh variables after the treatment.
  608. $this->refreshVariables();
  609. // Test that the correct number of pager links are found for keyword search.
  610. $edit = array('keys' => 'love pizza');
  611. $this->drupalPost('search/node', $edit, t('Search'));
  612. $this->assertLinkByHref('page=1', 0, '2nd page link is found for keyword search.');
  613. $this->assertLinkByHref('page=2', 0, '3rd page link is found for keyword search.');
  614. $this->assertLinkByHref('page=3', 0, '4th page link is found for keyword search.');
  615. $this->assertNoLinkByHref('page=4', '5th page link is not found for keyword search.');
  616. // Test that the correct number of pager links are found for exact phrase search.
  617. $edit = array('keys' => '"love pizza"');
  618. $this->drupalPost('search/node', $edit, t('Search'));
  619. $this->assertLinkByHref('page=1', 0, '2nd page link is found for exact phrase search.');
  620. $this->assertNoLinkByHref('page=2', '3rd page link is not found for exact phrase search.');
  621. }
  622. }
  623. /**
  624. * Test integration searching comments.
  625. */
  626. class SearchCommentTestCase extends DrupalWebTestCase {
  627. protected $admin_user;
  628. public static function getInfo() {
  629. return array(
  630. 'name' => 'Comment Search tests',
  631. 'description' => 'Verify text formats and filters used elsewhere.',
  632. 'group' => 'Search',
  633. );
  634. }
  635. function setUp() {
  636. parent::setUp('comment', 'search');
  637. // Create and log in an administrative user having access to the Full HTML
  638. // text format.
  639. $full_html_format = filter_format_load('full_html');
  640. $permissions = array(
  641. 'administer filters',
  642. filter_permission_name($full_html_format),
  643. 'administer permissions',
  644. 'create page content',
  645. 'skip comment approval',
  646. 'access comments',
  647. );
  648. $this->admin_user = $this->drupalCreateUser($permissions);
  649. $this->drupalLogin($this->admin_user);
  650. }
  651. /**
  652. * Verify that comments are rendered using proper format in search results.
  653. */
  654. function testSearchResultsComment() {
  655. $comment_body = 'Test comment body';
  656. variable_set('comment_preview_article', DRUPAL_OPTIONAL);
  657. // Enable check_plain() for 'Filtered HTML' text format.
  658. $filtered_html_format_id = 'filtered_html';
  659. $edit = array(
  660. 'filters[filter_html_escape][status]' => TRUE,
  661. );
  662. $this->drupalPost('admin/config/content/formats/' . $filtered_html_format_id, $edit, t('Save configuration'));
  663. // Allow anonymous users to search content.
  664. $edit = array(
  665. DRUPAL_ANONYMOUS_RID . '[search content]' => 1,
  666. DRUPAL_ANONYMOUS_RID . '[access comments]' => 1,
  667. DRUPAL_ANONYMOUS_RID . '[post comments]' => 1,
  668. );
  669. $this->drupalPost('admin/people/permissions', $edit, t('Save permissions'));
  670. // Create a node.
  671. $node = $this->drupalCreateNode(array('type' => 'article'));
  672. // Post a comment using 'Full HTML' text format.
  673. $edit_comment = array();
  674. $edit_comment['subject'] = 'Test comment subject';
  675. $edit_comment['comment_body[' . LANGUAGE_NONE . '][0][value]'] = '<h1>' . $comment_body . '</h1>';
  676. $full_html_format_id = 'full_html';
  677. $edit_comment['comment_body[' . LANGUAGE_NONE . '][0][format]'] = $full_html_format_id;
  678. $this->drupalPost('comment/reply/' . $node->nid, $edit_comment, t('Save'));
  679. // Invoke search index update.
  680. $this->drupalLogout();
  681. $this->cronRun();
  682. // Search for the comment subject.
  683. $edit = array(
  684. 'search_block_form' => "'" . $edit_comment['subject'] . "'",
  685. );
  686. $this->drupalPost('', $edit, t('Search'));
  687. $this->assertText($node->title, 'Node found in search results.');
  688. $this->assertText($edit_comment['subject'], 'Comment subject found in search results.');
  689. // Search for the comment body.
  690. $edit = array(
  691. 'search_block_form' => "'" . $comment_body . "'",
  692. );
  693. $this->drupalPost('', $edit, t('Search'));
  694. $this->assertText($node->title, 'Node found in search results.');
  695. // Verify that comment is rendered using proper format.
  696. $this->assertText($comment_body, 'Comment body text found in search results.');
  697. $this->assertNoRaw(t('n/a'), 'HTML in comment body is not hidden.');
  698. $this->assertNoRaw(check_plain($edit_comment['comment_body[' . LANGUAGE_NONE . '][0][value]']), 'HTML in comment body is not escaped.');
  699. // Hide comments.
  700. $this->drupalLogin($this->admin_user);
  701. $node->comment = 0;
  702. node_save($node);
  703. // Invoke search index update.
  704. $this->drupalLogout();
  705. $this->cronRun();
  706. // Search for $title.
  707. $this->drupalPost('', $edit, t('Search'));
  708. $this->assertNoText($comment_body, 'Comment body text not found in search results.');
  709. }
  710. /**
  711. * Verify access rules for comment indexing with different permissions.
  712. */
  713. function testSearchResultsCommentAccess() {
  714. $comment_body = 'Test comment body';
  715. $this->comment_subject = 'Test comment subject';
  716. $this->admin_role = $this->admin_user->roles;
  717. unset($this->admin_role[DRUPAL_AUTHENTICATED_RID]);
  718. $this->admin_role = key($this->admin_role);
  719. // Create a node.
  720. variable_set('comment_preview_article', DRUPAL_OPTIONAL);
  721. $this->node = $this->drupalCreateNode(array('type' => 'article'));
  722. // Post a comment using 'Full HTML' text format.
  723. $edit_comment = array();
  724. $edit_comment['subject'] = $this->comment_subject;
  725. $edit_comment['comment_body[' . LANGUAGE_NONE . '][0][value]'] = '<h1>' . $comment_body . '</h1>';
  726. $this->drupalPost('comment/reply/' . $this->node->nid, $edit_comment, t('Save'));
  727. $this->drupalLogout();
  728. $this->setRolePermissions(DRUPAL_ANONYMOUS_RID);
  729. $this->checkCommentAccess('Anon user has search permission but no access comments permission, comments should not be indexed');
  730. $this->setRolePermissions(DRUPAL_ANONYMOUS_RID, TRUE);
  731. $this->checkCommentAccess('Anon user has search permission and access comments permission, comments should be indexed', TRUE);
  732. $this->drupalLogin($this->admin_user);
  733. $this->drupalGet('admin/people/permissions');
  734. // Disable search access for authenticated user to test admin user.
  735. $this->setRolePermissions(DRUPAL_AUTHENTICATED_RID, FALSE, FALSE);
  736. $this->setRolePermissions($this->admin_role);
  737. $this->checkCommentAccess('Admin user has search permission but no access comments permission, comments should not be indexed');
  738. $this->setRolePermissions($this->admin_role, TRUE);
  739. $this->checkCommentAccess('Admin user has search permission and access comments permission, comments should be indexed', TRUE);
  740. $this->setRolePermissions(DRUPAL_AUTHENTICATED_RID);
  741. $this->checkCommentAccess('Authenticated user has search permission but no access comments permission, comments should not be indexed');
  742. $this->setRolePermissions(DRUPAL_AUTHENTICATED_RID, TRUE);
  743. $this->checkCommentAccess('Authenticated user has search permission and access comments permission, comments should be indexed', TRUE);
  744. // Verify that access comments permission is inherited from the
  745. // authenticated role.
  746. $this->setRolePermissions(DRUPAL_AUTHENTICATED_RID, TRUE, FALSE);
  747. $this->setRolePermissions($this->admin_role);
  748. $this->checkCommentAccess('Admin user has search permission and no access comments permission, but comments should be indexed because admin user inherits authenticated user\'s permission to access comments', TRUE);
  749. // Verify that search content permission is inherited from the authenticated
  750. // role.
  751. $this->setRolePermissions(DRUPAL_AUTHENTICATED_RID, TRUE, TRUE);
  752. $this->setRolePermissions($this->admin_role, TRUE, FALSE);
  753. $this->checkCommentAccess('Admin user has access comments permission and no search permission, but comments should be indexed because admin user inherits authenticated user\'s permission to search', TRUE);
  754. }
  755. /**
  756. * Set permissions for role.
  757. */
  758. function setRolePermissions($rid, $access_comments = FALSE, $search_content = TRUE) {
  759. $permissions = array(
  760. 'access comments' => $access_comments,
  761. 'search content' => $search_content,
  762. );
  763. user_role_change_permissions($rid, $permissions);
  764. }
  765. /**
  766. * Update search index and search for comment.
  767. */
  768. function checkCommentAccess($message, $assume_access = FALSE) {
  769. // Invoke search index update.
  770. search_touch_node($this->node->nid);
  771. $this->cronRun();
  772. // Search for the comment subject.
  773. $edit = array(
  774. 'search_block_form' => "'" . $this->comment_subject . "'",
  775. );
  776. $this->drupalPost('', $edit, t('Search'));
  777. $method = $assume_access ? 'assertText' : 'assertNoText';
  778. $verb = $assume_access ? 'found' : 'not found';
  779. $this->{$method}($this->node->title, "Node $verb in search results: " . $message);
  780. $this->{$method}($this->comment_subject, "Comment subject $verb in search results: " . $message);
  781. }
  782. /**
  783. * Verify that 'add new comment' does not appear in search results or index.
  784. */
  785. function testAddNewComment() {
  786. // Create a node with a short body.
  787. $settings = array(
  788. 'type' => 'article',
  789. 'title' => 'short title',
  790. 'body' => array(LANGUAGE_NONE => array(array('value' => 'short body text'))),
  791. );
  792. $user = $this->drupalCreateUser(array('search content', 'create article content', 'access content'));
  793. $this->drupalLogin($user);
  794. $node = $this->drupalCreateNode($settings);
  795. // Verify that if you view the node on its own page, 'add new comment'
  796. // is there.
  797. $this->drupalGet('node/' . $node->nid);
  798. $this->assertText(t('Add new comment'), 'Add new comment appears on node page');
  799. // Run cron to index this page.
  800. $this->drupalLogout();
  801. $this->cronRun();
  802. // Search for 'comment'. Should be no results.
  803. $this->drupalLogin($user);
  804. $this->drupalPost('search/node', array('keys' => 'comment'), t('Search'));
  805. $this->assertText(t('Your search yielded no results'), 'No results searching for the word comment');
  806. // Search for the node title. Should be found, and 'Add new comment' should
  807. // not be part of the search snippet.
  808. $this->drupalPost('search/node', array('keys' => 'short'), t('Search'));
  809. $this->assertText($node->title, 'Search for keyword worked');
  810. $this->assertNoText(t('Add new comment'), 'Add new comment does not appear on search results page');
  811. }
  812. }
  813. /**
  814. * Tests search_expression_insert() and search_expression_extract().
  815. *
  816. * @see http://drupal.org/node/419388 (issue)
  817. */
  818. class SearchExpressionInsertExtractTestCase extends DrupalUnitTestCase {
  819. public static function getInfo() {
  820. return array(
  821. 'name' => 'Search expression insert/extract',
  822. 'description' => 'Tests the functions search_expression_insert() and search_expression_extract()',
  823. 'group' => 'Search',
  824. );
  825. }
  826. function setUp() {
  827. drupal_load('module', 'search');
  828. parent::setUp();
  829. }
  830. /**
  831. * Tests search_expression_insert() and search_expression_extract().
  832. */
  833. function testInsertExtract() {
  834. $base_expression = "mykeyword";
  835. // Build an array of option, value, what should be in the expression, what
  836. // should be retrieved from expression.
  837. $cases = array(
  838. array('foo', 'bar', 'foo:bar', 'bar'), // Normal case.
  839. array('foo', NULL, '', NULL), // Empty value: shouldn't insert.
  840. array('foo', ' ', 'foo:', ''), // Space as value: should insert but retrieve empty string.
  841. array('foo', '', 'foo:', ''), // Empty string as value: should insert but retrieve empty string.
  842. array('foo', '0', 'foo:0', '0'), // String zero as value: should insert.
  843. array('foo', 0, 'foo:0', '0'), // Numeric zero as value: should insert.
  844. );
  845. foreach ($cases as $index => $case) {
  846. $after_insert = search_expression_insert($base_expression, $case[0], $case[1]);
  847. if (empty($case[2])) {
  848. $this->assertEqual($after_insert, $base_expression, "Empty insert does not change expression in case $index");
  849. }
  850. else {
  851. $this->assertEqual($after_insert, $base_expression . ' ' . $case[2], "Insert added correct expression for case $index");
  852. }
  853. $retrieved = search_expression_extract($after_insert, $case[0]);
  854. if (!isset($case[3])) {
  855. $this->assertFalse(isset($retrieved), "Empty retrieval results in unset value in case $index");
  856. }
  857. else {
  858. $this->assertEqual($retrieved, $case[3], "Value is retrieved for case $index");
  859. }
  860. $after_clear = search_expression_insert($after_insert, $case[0]);
  861. $this->assertEqual(trim($after_clear), $base_expression, "After clearing, base expression is restored for case $index");
  862. $cleared = search_expression_extract($after_clear, $case[0]);
  863. $this->assertFalse(isset($cleared), "After clearing, value could not be retrieved for case $index");
  864. }
  865. }
  866. }
  867. /**
  868. * Tests that comment count display toggles properly on comment status of node
  869. *
  870. * Issue 537278
  871. *
  872. * - Nodes with comment status set to Open should always how comment counts
  873. * - Nodes with comment status set to Closed should show comment counts
  874. * only when there are comments
  875. * - Nodes with comment status set to Hidden should never show comment counts
  876. */
  877. class SearchCommentCountToggleTestCase extends DrupalWebTestCase {
  878. protected $searching_user;
  879. protected $searchable_nodes;
  880. public static function getInfo() {
  881. return array(
  882. 'name' => 'Comment count toggle',
  883. 'description' => 'Verify that comment count display toggles properly on comment status of node.',
  884. 'group' => 'Search',
  885. );
  886. }
  887. function setUp() {
  888. parent::setUp('search');
  889. // Create searching user.
  890. $this->searching_user = $this->drupalCreateUser(array('search content', 'access content', 'access comments', 'skip comment approval'));
  891. // Create initial nodes.
  892. $node_params = array('type' => 'article', 'body' => array(LANGUAGE_NONE => array(array('value' => 'SearchCommentToggleTestCase'))));
  893. $this->searchable_nodes['1 comment'] = $this->drupalCreateNode($node_params);
  894. $this->searchable_nodes['0 comments'] = $this->drupalCreateNode($node_params);
  895. // Login with sufficient privileges.
  896. $this->drupalLogin($this->searching_user);
  897. // Create a comment array
  898. $edit_comment = array();
  899. $edit_comment['subject'] = $this->randomName();
  900. $edit_comment['comment_body[' . LANGUAGE_NONE . '][0][value]'] = $this->randomName();
  901. $filtered_html_format_id = 'filtered_html';
  902. $edit_comment['comment_body[' . LANGUAGE_NONE . '][0][format]'] = $filtered_html_format_id;
  903. // Post comment to the test node with comment
  904. $this->drupalPost('comment/reply/' . $this->searchable_nodes['1 comment']->nid, $edit_comment, t('Save'));
  905. // First update the index. This does the initial processing.
  906. node_update_index();
  907. // Then, run the shutdown function. Testing is a unique case where indexing
  908. // and searching has to happen in the same request, so running the shutdown
  909. // function manually is needed to finish the indexing process.
  910. search_update_totals();
  911. }
  912. /**
  913. * Verify that comment count display toggles properly on comment status of node
  914. */
  915. function testSearchCommentCountToggle() {
  916. // Search for the nodes by string in the node body.
  917. $edit = array(
  918. 'search_block_form' => "'SearchCommentToggleTestCase'",
  919. );
  920. // Test comment count display for nodes with comment status set to Open
  921. $this->drupalPost('', $edit, t('Search'));
  922. $this->assertText(t('0 comments'), 'Empty comment count displays for nodes with comment status set to Open');
  923. $this->assertText(t('1 comment'), 'Non-empty comment count displays for nodes with comment status set to Open');
  924. // Test comment count display for nodes with comment status set to Closed
  925. $this->searchable_nodes['0 comments']->comment = COMMENT_NODE_CLOSED;
  926. node_save($this->searchable_nodes['0 comments']);
  927. $this->searchable_nodes['1 comment']->comment = COMMENT_NODE_CLOSED;
  928. node_save($this->searchable_nodes['1 comment']);
  929. $this->drupalPost('', $edit, t('Search'));
  930. $this->assertNoText(t('0 comments'), 'Empty comment count does not display for nodes with comment status set to Closed');
  931. $this->assertText(t('1 comment'), 'Non-empty comment count displays for nodes with comment status set to Closed');
  932. // Test comment count display for nodes with comment status set to Hidden
  933. $this->searchable_nodes['0 comments']->comment = COMMENT_NODE_HIDDEN;
  934. node_save($this->searchable_nodes['0 comments']);
  935. $this->searchable_nodes['1 comment']->comment = COMMENT_NODE_HIDDEN;
  936. node_save($this->searchable_nodes['1 comment']);
  937. $this->drupalPost('', $edit, t('Search'));
  938. $this->assertNoText(t('0 comments'), 'Empty comment count does not display for nodes with comment status set to Hidden');
  939. $this->assertNoText(t('1 comment'), 'Non-empty comment count does not display for nodes with comment status set to Hidden');
  940. }
  941. }
  942. /**
  943. * Test search_simplify() on every Unicode character, and some other cases.
  944. */
  945. class SearchSimplifyTestCase extends DrupalWebTestCase {
  946. public static function getInfo() {
  947. return array(
  948. 'name' => 'Search simplify',
  949. 'description' => 'Check that the search_simply() function works as intended.',
  950. 'group' => 'Search',
  951. );
  952. }
  953. /**
  954. * Tests that all Unicode characters simplify correctly.
  955. */
  956. function testSearchSimplifyUnicode() {
  957. // This test uses a file that was constructed so that the even lines are
  958. // boundary characters, and the odd lines are valid word characters. (It
  959. // was generated as a sequence of all the Unicode characters, and then the
  960. // boundary chararacters (punctuation, spaces, etc.) were split off into
  961. // their own lines). So the even-numbered lines should simplify to nothing,
  962. // and the odd-numbered lines we need to split into shorter chunks and
  963. // verify that simplification doesn't lose any characters.
  964. $input = file_get_contents(DRUPAL_ROOT . '/modules/search/tests/UnicodeTest.txt');
  965. $basestrings = explode(chr(10), $input);
  966. $strings = array();
  967. foreach ($basestrings as $key => $string) {
  968. if ($key %2) {
  969. // Even line - should simplify down to a space.
  970. $simplified = search_simplify($string);
  971. $this->assertIdentical($simplified, ' ', "Line $key is excluded from the index");
  972. }
  973. else {
  974. // Odd line, should be word characters.
  975. // Split this into 30-character chunks, so we don't run into limits
  976. // of truncation in search_simplify().
  977. $start = 0;
  978. while ($start < drupal_strlen($string)) {
  979. $newstr = drupal_substr($string, $start, 30);
  980. // Special case: leading zeros are removed from numeric strings,
  981. // and there's one string in this file that is numbers starting with
  982. // zero, so prepend a 1 on that string.
  983. if (preg_match('/^[0-9]+$/', $newstr)) {
  984. $newstr = '1' . $newstr;
  985. }
  986. $strings[] = $newstr;
  987. $start += 30;
  988. }
  989. }
  990. }
  991. foreach ($strings as $key => $string) {
  992. $simplified = search_simplify($string);
  993. $this->assertTrue(drupal_strlen($simplified) >= drupal_strlen($string), "Nothing is removed from string $key.");
  994. }
  995. // Test the low-numbered ASCII control characters separately. They are not
  996. // in the text file because they are problematic for diff, especially \0.
  997. $string = '';
  998. for ($i = 0; $i < 32; $i++) {
  999. $string .= chr($i);
  1000. }
  1001. $this->assertIdentical(' ', search_simplify($string), 'Search simplify works for ASCII control characters.');
  1002. }
  1003. /**
  1004. * Tests that search_simplify() does the right thing with punctuation.
  1005. */
  1006. function testSearchSimplifyPunctuation() {
  1007. $cases = array(
  1008. array('20.03/94-28,876', '20039428876', 'Punctuation removed from numbers'),
  1009. array('great...drupal--module', 'great drupal module', 'Multiple dot and dashes are word boundaries'),
  1010. array('very_great-drupal.module', 'verygreatdrupalmodule', 'Single dot, dash, underscore are removed'),
  1011. array('regular,punctuation;word', 'regular punctuation word', 'Punctuation is a word boundary'),
  1012. );
  1013. foreach ($cases as $case) {
  1014. $out = trim(search_simplify($case[0]));
  1015. $this->assertEqual($out, $case[1], $case[2]);
  1016. }
  1017. }
  1018. }
  1019. /**
  1020. * Tests keywords and conditions.
  1021. */
  1022. class SearchKeywordsConditions extends DrupalWebTestCase {
  1023. public static function getInfo() {
  1024. return array(
  1025. 'name' => 'Keywords and conditions',
  1026. 'description' => 'Verify the search pulls in keywords and extra conditions.',
  1027. 'group' => 'Search',
  1028. );
  1029. }
  1030. function setUp() {
  1031. parent::setUp('search', 'search_extra_type');
  1032. // Create searching user.
  1033. $this->searching_user = $this->drupalCreateUser(array('search content', 'access content', 'access comments', 'skip comment approval'));
  1034. // Login with sufficient privileges.
  1035. $this->drupalLogin($this->searching_user);
  1036. // Test with all search modules enabled.
  1037. variable_set('search_active_modules', array('node' => 'node', 'user' => 'user', 'search_extra_type' => 'search_extra_type'));
  1038. menu_rebuild();
  1039. }
  1040. /**
  1041. * Verify the kewords are captured and conditions respected.
  1042. */
  1043. function testSearchKeyswordsConditions() {
  1044. // No keys, not conditions - no results.
  1045. $this->drupalGet('search/dummy_path');
  1046. $this->assertNoText('Dummy search snippet to display');
  1047. // With keys - get results.
  1048. $keys = 'bike shed ' . $this->randomName();
  1049. $this->drupalGet("search/dummy_path/{$keys}");
  1050. $this->assertText("Dummy search snippet to display. Keywords: {$keys}");
  1051. $keys = 'blue drop ' . $this->randomName();
  1052. $this->drupalGet("search/dummy_path", array('query' => array('keys' => $keys)));
  1053. $this->assertText("Dummy search snippet to display. Keywords: {$keys}");
  1054. // Add some conditions and keys.
  1055. $keys = 'moving drop ' . $this->randomName();
  1056. $this->drupalGet("search/dummy_path/bike", array('query' => array('search_conditions' => $keys)));
  1057. $this->assertText("Dummy search snippet to display.");
  1058. $this->assertRaw(print_r(array('search_conditions' => $keys), TRUE));
  1059. // Add some conditions and no keys.
  1060. $keys = 'drop kick ' . $this->randomName();
  1061. $this->drupalGet("search/dummy_path", array('query' => array('search_conditions' => $keys)));
  1062. $this->assertText("Dummy search snippet to display.");
  1063. $this->assertRaw(print_r(array('search_conditions' => $keys), TRUE));
  1064. }
  1065. }
  1066. /**
  1067. * Tests that numbers can be searched.
  1068. */
  1069. class SearchNumbersTestCase extends DrupalWebTestCase {
  1070. protected $test_user;
  1071. protected $numbers;
  1072. protected $nodes;
  1073. public static function getInfo() {
  1074. return array(
  1075. 'name' => 'Search numbers',
  1076. 'description' => 'Check that numbers can be searched',
  1077. 'group' => 'Search',
  1078. );
  1079. }
  1080. function setUp() {
  1081. parent::setUp('search');
  1082. $this->test_user = $this->drupalCreateUser(array('search content', 'access content', 'administer nodes', 'access site reports'));
  1083. $this->drupalLogin($this->test_user);
  1084. // Create content with various numbers in it.
  1085. // Note: 50 characters is the current limit of the search index's word
  1086. // field.
  1087. $this->numbers = array(
  1088. 'ISBN' => '978-0446365383',
  1089. 'UPC' => '036000 291452',
  1090. 'EAN bar code' => '5901234123457',
  1091. 'negative' => '-123456.7890',
  1092. 'quoted negative' => '"-123456.7890"',
  1093. 'leading zero' => '0777777777',
  1094. 'tiny' => '111',
  1095. 'small' => '22222222222222',
  1096. 'medium' => '333333333333333333333333333',
  1097. 'large' => '444444444444444444444444444444444444444',
  1098. 'gigantic' => '5555555555555555555555555555555555555555555555555',
  1099. 'over fifty characters' => '666666666666666666666666666666666666666666666666666666666666',
  1100. 'date', '01/02/2009',
  1101. 'commas', '987,654,321',
  1102. );
  1103. foreach ($this->numbers as $doc => $num) {
  1104. $info = array(
  1105. 'body' => array(LANGUAGE_NONE => array(array('value' => $num))),
  1106. 'type' => 'page',
  1107. 'language' => LANGUAGE_NONE,
  1108. 'title' => $doc . ' number',
  1109. );
  1110. $this->nodes[$doc] = $this->drupalCreateNode($info);
  1111. }
  1112. // Run cron to ensure the content is indexed.
  1113. $this->cronRun();
  1114. $this->drupalGet('admin/reports/dblog');
  1115. $this->assertText(t('Cron run completed'), 'Log shows cron run completed');
  1116. }
  1117. /**
  1118. * Tests that all the numbers can be searched.
  1119. */
  1120. function testNumberSearching() {
  1121. $types = array_keys($this->numbers);
  1122. foreach ($types as $type) {
  1123. $number = $this->numbers[$type];
  1124. // If the number is negative, remove the - sign, because - indicates
  1125. // "not keyword" when searching.
  1126. $number = ltrim($number, '-');
  1127. $node = $this->nodes[$type];
  1128. // Verify that the node title does not appear on the search page
  1129. // with a dummy search.
  1130. $this->drupalPost('search/node',
  1131. array('keys' => 'foo'),
  1132. t('Search'));
  1133. $this->assertNoText($node->title, $type . ': node title not shown in dummy search');
  1134. // Verify that the node title does appear as a link on the search page
  1135. // when searching for the number.
  1136. $this->drupalPost('search/node',
  1137. array('keys' => $number),
  1138. t('Search'));
  1139. $this->assertText($node->title, format_string('%type: node title shown (search found the node) in search for number %number.', array('%type' => $type, '%number' => $number)));
  1140. }
  1141. }
  1142. }
  1143. /**
  1144. * Tests that numbers can be searched, with more complex matching.
  1145. */
  1146. class SearchNumberMatchingTestCase extends DrupalWebTestCase {
  1147. protected $test_user;
  1148. protected $numbers;
  1149. protected $nodes;
  1150. public static function getInfo() {
  1151. return array(
  1152. 'name' => 'Search number matching',
  1153. 'description' => 'Check that numbers can be searched with more complex matching',
  1154. 'group' => 'Search',
  1155. );
  1156. }
  1157. function setUp() {
  1158. parent::setUp('search');
  1159. $this->test_user = $this->drupalCreateUser(array('search content', 'access content', 'administer nodes', 'access site reports'));
  1160. $this->drupalLogin($this->test_user);
  1161. // Define a group of numbers that should all match each other --
  1162. // numbers with internal punctuation should match each other, as well
  1163. // as numbers with and without leading zeros and leading/trailing
  1164. // . and -.
  1165. $this->numbers = array(
  1166. '123456789',
  1167. '12/34/56789',
  1168. '12.3456789',
  1169. '12-34-56789',
  1170. '123,456,789',
  1171. '-123456789',
  1172. '0123456789',
  1173. );
  1174. foreach ($this->numbers as $num) {
  1175. $info = array(
  1176. 'body' => array(LANGUAGE_NONE => array(array('value' => $num))),
  1177. 'type' => 'page',
  1178. 'language' => LANGUAGE_NONE,
  1179. );
  1180. $this->nodes[] = $this->drupalCreateNode($info);
  1181. }
  1182. // Run cron to ensure the content is indexed.
  1183. $this->cronRun();
  1184. $this->drupalGet('admin/reports/dblog');
  1185. $this->assertText(t('Cron run completed'), 'Log shows cron run completed');
  1186. }
  1187. /**
  1188. * Tests that all the numbers can be searched.
  1189. */
  1190. function testNumberSearching() {
  1191. for ($i = 0; $i < count($this->numbers); $i++) {
  1192. $node = $this->nodes[$i];
  1193. // Verify that the node title does not appear on the search page
  1194. // with a dummy search.
  1195. $this->drupalPost('search/node',
  1196. array('keys' => 'foo'),
  1197. t('Search'));
  1198. $this->assertNoText($node->title, format_string('%number: node title not shown in dummy search', array('%number' => $i)));
  1199. // Now verify that we can find node i by searching for any of the
  1200. // numbers.
  1201. for ($j = 0; $j < count($this->numbers); $j++) {
  1202. $number = $this->numbers[$j];
  1203. // If the number is negative, remove the - sign, because - indicates
  1204. // "not keyword" when searching.
  1205. $number = ltrim($number, '-');
  1206. $this->drupalPost('search/node',
  1207. array('keys' => $number),
  1208. t('Search'));
  1209. $this->assertText($node->title, format_string('%i: node title shown (search found the node) in search for number %number', array('%i' => $i, '%number' => $number)));
  1210. }
  1211. }
  1212. }
  1213. }
  1214. /**
  1215. * Test config page.
  1216. */
  1217. class SearchConfigSettingsForm extends DrupalWebTestCase {
  1218. public $search_user;
  1219. public $search_node;
  1220. public static function getInfo() {
  1221. return array(
  1222. 'name' => 'Config settings form',
  1223. 'description' => 'Verify the search config settings form.',
  1224. 'group' => 'Search',
  1225. );
  1226. }
  1227. function setUp() {
  1228. parent::setUp('search', 'search_extra_type');
  1229. // Login as a user that can create and search content.
  1230. $this->search_user = $this->drupalCreateUser(array('search content', 'administer search', 'administer nodes', 'bypass node access', 'access user profiles', 'administer users', 'administer blocks'));
  1231. $this->drupalLogin($this->search_user);
  1232. // Add a single piece of content and index it.
  1233. $node = $this->drupalCreateNode();
  1234. $this->search_node = $node;
  1235. // Link the node to itself to test that it's only indexed once. The content
  1236. // also needs the word "pizza" so we can use it as the search keyword.
  1237. $langcode = LANGUAGE_NONE;
  1238. $body_key = "body[$langcode][0][value]";
  1239. $edit[$body_key] = l($node->title, 'node/' . $node->nid) . ' pizza sandwich';
  1240. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  1241. node_update_index();
  1242. search_update_totals();
  1243. // Enable the search block.
  1244. $edit = array();
  1245. $edit['blocks[search_form][region]'] = 'content';
  1246. $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
  1247. }
  1248. /**
  1249. * Verify the search settings form.
  1250. */
  1251. function testSearchSettingsPage() {
  1252. // Test that the settings form displays the correct count of items left to index.
  1253. $this->drupalGet('admin/config/search/settings');
  1254. $this->assertText(t('There are @count items left to index.', array('@count' => 0)));
  1255. // Test the re-index button.
  1256. $this->drupalPost('admin/config/search/settings', array(), t('Re-index site'));
  1257. $this->assertText(t('Are you sure you want to re-index the site'));
  1258. $this->drupalPost('admin/config/search/settings/reindex', array(), t('Re-index site'));
  1259. $this->assertText(t('The index will be rebuilt'));
  1260. $this->drupalGet('admin/config/search/settings');
  1261. $this->assertText(t('There is 1 item left to index.'));
  1262. // Test that the form saves with the default values.
  1263. $this->drupalPost('admin/config/search/settings', array(), t('Save configuration'));
  1264. $this->assertText(t('The configuration options have been saved.'), 'Form saves with the default values.');
  1265. // Test that the form does not save with an invalid word length.
  1266. $edit = array(
  1267. 'minimum_word_size' => $this->randomName(3),
  1268. );
  1269. $this->drupalPost('admin/config/search/settings', $edit, t('Save configuration'));
  1270. $this->assertNoText(t('The configuration options have been saved.'), 'Form does not save with an invalid word length.');
  1271. }
  1272. /**
  1273. * Verify that you can disable individual search modules.
  1274. */
  1275. function testSearchModuleDisabling() {
  1276. // Array of search modules to test: 'path' is the search path, 'title' is
  1277. // the tab title, 'keys' are the keywords to search for, and 'text' is
  1278. // the text to assert is on the results page.
  1279. $module_info = array(
  1280. 'node' => array(
  1281. 'path' => 'node',
  1282. 'title' => 'Content',
  1283. 'keys' => 'pizza',
  1284. 'text' => $this->search_node->title,
  1285. ),
  1286. 'user' => array(
  1287. 'path' => 'user',
  1288. 'title' => 'User',
  1289. 'keys' => $this->search_user->name,
  1290. 'text' => $this->search_user->mail,
  1291. ),
  1292. 'search_extra_type' => array(
  1293. 'path' => 'dummy_path',
  1294. 'title' => 'Dummy search type',
  1295. 'keys' => 'foo',
  1296. 'text' => 'Dummy search snippet to display',
  1297. ),
  1298. );
  1299. $modules = array_keys($module_info);
  1300. // Test each module if it's enabled as the only search module.
  1301. foreach ($modules as $module) {
  1302. // Enable the one module and disable other ones.
  1303. $info = $module_info[$module];
  1304. $edit = array();
  1305. foreach ($modules as $other) {
  1306. $edit['search_active_modules[' . $other . ']'] = (($other == $module) ? $module : FALSE);
  1307. }
  1308. $edit['search_default_module'] = $module;
  1309. $this->drupalPost('admin/config/search/settings', $edit, t('Save configuration'));
  1310. // Run a search from the correct search URL.
  1311. $this->drupalGet('search/' . $info['path'] . '/' . $info['keys']);
  1312. $this->assertNoText('no results', $info['title'] . ' search found results');
  1313. $this->assertText($info['text'], 'Correct search text found');
  1314. // Verify that other module search tab titles are not visible.
  1315. foreach ($modules as $other) {
  1316. if ($other != $module) {
  1317. $title = $module_info[$other]['title'];
  1318. $this->assertNoText($title, $title . ' search tab is not shown');
  1319. }
  1320. }
  1321. // Run a search from the search block on the node page. Verify you get
  1322. // to this module's search results page.
  1323. $terms = array('search_block_form' => $info['keys']);
  1324. $this->drupalPost('node', $terms, t('Search'));
  1325. $this->assertEqual(
  1326. $this->getURL(),
  1327. url('search/' . $info['path'] . '/' . $info['keys'], array('absolute' => TRUE)),
  1328. 'Block redirected to right search page');
  1329. // Try an invalid search path. Should redirect to our active module.
  1330. $this->drupalGet('search/not_a_module_path');
  1331. $this->assertEqual(
  1332. $this->getURL(),
  1333. url('search/' . $info['path'], array('absolute' => TRUE)),
  1334. 'Invalid search path redirected to default search page');
  1335. }
  1336. // Test with all search modules enabled. When you go to the search
  1337. // page or run search, all modules should be shown.
  1338. $edit = array();
  1339. foreach ($modules as $module) {
  1340. $edit['search_active_modules[' . $module . ']'] = $module;
  1341. }
  1342. $edit['search_default_module'] = 'node';
  1343. $this->drupalPost('admin/config/search/settings', $edit, t('Save configuration'));
  1344. foreach (array('search/node/pizza', 'search/node') as $path) {
  1345. $this->drupalGet($path);
  1346. foreach ($modules as $module) {
  1347. $title = $module_info[$module]['title'];
  1348. $this->assertText($title, format_string('%title search tab is shown', array('%title' => $title)));
  1349. }
  1350. }
  1351. }
  1352. }
  1353. /**
  1354. * Tests the search_excerpt() function.
  1355. */
  1356. class SearchExcerptTestCase extends DrupalUnitTestCase {
  1357. public static function getInfo() {
  1358. return array(
  1359. 'name' => 'Search excerpt extraction',
  1360. 'description' => 'Tests that the search_excerpt() function works.',
  1361. 'group' => 'Search',
  1362. );
  1363. }
  1364. function setUp() {
  1365. drupal_load('module', 'search');
  1366. parent::setUp();
  1367. }
  1368. /**
  1369. * Tests search_excerpt() with several simulated search keywords.
  1370. *
  1371. * Passes keywords and a sample marked up string, "The quick
  1372. * brown fox jumps over the lazy dog", and compares it to the
  1373. * correctly marked up string. The correctly marked up string
  1374. * contains either highlighted keywords or the original marked
  1375. * up string if no keywords matched the string.
  1376. */
  1377. function testSearchExcerpt() {
  1378. // Make some text with entities and tags.
  1379. $text = 'The <strong>quick</strong> <a href="#">brown</a> fox &amp; jumps <h2>over</h2> the lazy dog';
  1380. // Note: The search_excerpt() function adds some extra spaces -- not
  1381. // important for HTML formatting. Remove these for comparison.
  1382. $expected = 'The quick brown fox &amp; jumps over the lazy dog';
  1383. $result = preg_replace('| +|', ' ', search_excerpt('nothing', $text));
  1384. $this->assertEqual(preg_replace('| +|', ' ', $result), $expected, 'Entire string is returned when keyword is not found in short string');
  1385. $result = preg_replace('| +|', ' ', search_excerpt('fox', $text));
  1386. $this->assertEqual($result, 'The quick brown <strong>fox</strong> &amp; jumps over the lazy dog ...', 'Found keyword is highlighted');
  1387. $longtext = str_repeat($text . ' ', 10);
  1388. $result = preg_replace('| +|', ' ', search_excerpt('nothing', $text));
  1389. $this->assertTrue(strpos($result, $expected) === 0, 'When keyword is not found in long string, return value starts as expected');
  1390. $entities = str_repeat('k&eacute;sz&iacute;t&eacute;se ', 20);
  1391. $result = preg_replace('| +|', ' ', search_excerpt('nothing', $entities));
  1392. $this->assertFalse(strpos($result, '&'), 'Entities are not present in excerpt');
  1393. $this->assertTrue(strpos($result, 'í') > 0, 'Entities are converted in excerpt');
  1394. // The node body that will produce this rendered $text is:
  1395. // 123456789 HTMLTest +123456789+&lsquo; +&lsquo; +&lsquo; +&lsquo; +12345678 &nbsp;&nbsp; +&lsquo; +&lsquo; +&lsquo; &lsquo;
  1396. $text = "<div class=\"field field-name-body field-type-text-with-summary field-label-hidden\"><div class=\"field-items\"><div class=\"field-item even\" property=\"content:encoded\"><p>123456789 HTMLTest +123456789+‘ +‘ +‘ +‘ +12345678    +‘ +‘ +‘ ‘</p>\n</div></div></div> ";
  1397. $result = search_excerpt('HTMLTest', $text);
  1398. $this->assertFalse(empty($result), 'Rendered Multi-byte HTML encodings are not corrupted in search excerpts');
  1399. }
  1400. /**
  1401. * Tests search_excerpt() with search keywords matching simplified words.
  1402. *
  1403. * Excerpting should handle keywords that are matched only after going through
  1404. * search_simplify(). This test passes keywords that match simplified words
  1405. * and compares them with strings that contain the original unsimplified word.
  1406. */
  1407. function testSearchExcerptSimplified() {
  1408. $lorem1 = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam vitae arcu at leo cursus laoreet. Curabitur dui tortor, adipiscing malesuada tempor in, bibendum ac diam. Cras non tellus a libero pellentesque condimentum. What is a Drupalism? Suspendisse ac lacus libero. Ut non est vel nisl faucibus interdum nec sed leo. Pellentesque sem risus, vulputate eu semper eget, auctor in libero.';
  1409. $lorem2 = 'Ut fermentum est vitae metus convallis scelerisque. Phasellus pellentesque rhoncus tellus, eu dignissim purus posuere id. Quisque eu fringilla ligula. Morbi ullamcorper, lorem et mattis egestas, tortor neque pretium velit, eget eleifend odio turpis eu purus. Donec vitae metus quis leo pretium tincidunt a pulvinar sem. Morbi adipiscing laoreet mauris vel placerat. Nullam elementum, nisl sit amet scelerisque malesuada, dolor nunc hendrerit quam, eu ultrices erat est in orci.';
  1410. // Make some text with some keywords that will get simplified.
  1411. $text = $lorem1 . ' Number: 123456.7890 Hyphenated: one-two abc,def ' . $lorem2;
  1412. // Note: The search_excerpt() function adds some extra spaces -- not
  1413. // important for HTML formatting. Remove these for comparison.
  1414. $result = preg_replace('| +|', ' ', search_excerpt('123456.7890', $text));
  1415. $this->assertTrue(strpos($result, 'Number: <strong>123456.7890</strong>') !== FALSE, 'Numeric keyword is highlighted with exact match');
  1416. $result = preg_replace('| +|', ' ', search_excerpt('1234567890', $text));
  1417. $this->assertTrue(strpos($result, 'Number: <strong>123456.7890</strong>') !== FALSE, 'Numeric keyword is highlighted with simplified match');
  1418. $result = preg_replace('| +|', ' ', search_excerpt('Number 1234567890', $text));
  1419. $this->assertTrue(strpos($result, '<strong>Number</strong>: <strong>123456.7890</strong>') !== FALSE, 'Punctuated and numeric keyword is highlighted with simplified match');
  1420. $result = preg_replace('| +|', ' ', search_excerpt('"Number 1234567890"', $text));
  1421. $this->assertTrue(strpos($result, '<strong>Number: 123456.7890</strong>') !== FALSE, 'Phrase with punctuated and numeric keyword is highlighted with simplified match');
  1422. $result = preg_replace('| +|', ' ', search_excerpt('"Hyphenated onetwo"', $text));
  1423. $this->assertTrue(strpos($result, '<strong>Hyphenated: one-two</strong>') !== FALSE, 'Phrase with punctuated and hyphenated keyword is highlighted with simplified match');
  1424. $result = preg_replace('| +|', ' ', search_excerpt('"abc def"', $text));
  1425. $this->assertTrue(strpos($result, '<strong>abc,def</strong>') !== FALSE, 'Phrase with keyword simplified into two separate words is highlighted with simplified match');
  1426. // Test phrases with characters which are being truncated.
  1427. $result = preg_replace('| +|', ' ', search_excerpt('"ipsum _"', $text));
  1428. $this->assertTrue(strpos($result, '<strong>ipsum </strong>') !== FALSE, 'Only valid part of the phrase is highlighted and invalid part containing "_" is ignored.');
  1429. $result = preg_replace('| +|', ' ', search_excerpt('"ipsum 0000"', $text));
  1430. $this->assertTrue(strpos($result, '<strong>ipsum </strong>') !== FALSE, 'Only valid part of the phrase is highlighted and invalid part "0000" is ignored.');
  1431. // Test combination of the valid keyword and keyword containing only
  1432. // characters which are being truncated during simplification.
  1433. $result = preg_replace('| +|', ' ', search_excerpt('ipsum _', $text));
  1434. $this->assertTrue(strpos($result, '<strong>ipsum</strong>') !== FALSE, 'Only valid keyword is highlighted and invalid keyword "_" is ignored.');
  1435. $result = preg_replace('| +|', ' ', search_excerpt('ipsum 0000', $text));
  1436. $this->assertTrue(strpos($result, '<strong>ipsum</strong>') !== FALSE, 'Only valid keyword is highlighted and invalid keyword "0000" is ignored.');
  1437. }
  1438. }
  1439. /**
  1440. * Test the CJK tokenizer.
  1441. */
  1442. class SearchTokenizerTestCase extends DrupalWebTestCase {
  1443. public static function getInfo() {
  1444. return array(
  1445. 'name' => 'CJK tokenizer',
  1446. 'description' => 'Check that CJK tokenizer works as intended.',
  1447. 'group' => 'Search',
  1448. );
  1449. }
  1450. function setUp() {
  1451. parent::setUp('search');
  1452. }
  1453. /**
  1454. * Verifies that strings of CJK characters are tokenized.
  1455. *
  1456. * The search_simplify() function does special things with numbers, symbols,
  1457. * and punctuation. So we only test that CJK characters that are not in these
  1458. * character classes are tokenized properly. See PREG_CLASS_CKJ for more
  1459. * information.
  1460. */
  1461. function testTokenizer() {
  1462. // Set the minimum word size to 1 (to split all CJK characters) and make
  1463. // sure CJK tokenizing is turned on.
  1464. variable_set('minimum_word_size', 1);
  1465. variable_set('overlap_cjk', TRUE);
  1466. $this->refreshVariables();
  1467. // Create a string of CJK characters from various character ranges in
  1468. // the Unicode tables.
  1469. // Beginnings of the character ranges.
  1470. $starts = array(
  1471. 'CJK unified' => 0x4e00,
  1472. 'CJK Ext A' => 0x3400,
  1473. 'CJK Compat' => 0xf900,
  1474. 'Hangul Jamo' => 0x1100,
  1475. 'Hangul Ext A' => 0xa960,
  1476. 'Hangul Ext B' => 0xd7b0,
  1477. 'Hangul Compat' => 0x3131,
  1478. 'Half non-punct 1' => 0xff21,
  1479. 'Half non-punct 2' => 0xff41,
  1480. 'Half non-punct 3' => 0xff66,
  1481. 'Hangul Syllables' => 0xac00,
  1482. 'Hiragana' => 0x3040,
  1483. 'Katakana' => 0x30a1,
  1484. 'Katakana Ext' => 0x31f0,
  1485. 'CJK Reserve 1' => 0x20000,
  1486. 'CJK Reserve 2' => 0x30000,
  1487. 'Bomofo' => 0x3100,
  1488. 'Bomofo Ext' => 0x31a0,
  1489. 'Lisu' => 0xa4d0,
  1490. 'Yi' => 0xa000,
  1491. );
  1492. // Ends of the character ranges.
  1493. $ends = array(
  1494. 'CJK unified' => 0x9fcf,
  1495. 'CJK Ext A' => 0x4dbf,
  1496. 'CJK Compat' => 0xfaff,
  1497. 'Hangul Jamo' => 0x11ff,
  1498. 'Hangul Ext A' => 0xa97f,
  1499. 'Hangul Ext B' => 0xd7ff,
  1500. 'Hangul Compat' => 0x318e,
  1501. 'Half non-punct 1' => 0xff3a,
  1502. 'Half non-punct 2' => 0xff5a,
  1503. 'Half non-punct 3' => 0xffdc,
  1504. 'Hangul Syllables' => 0xd7af,
  1505. 'Hiragana' => 0x309f,
  1506. 'Katakana' => 0x30ff,
  1507. 'Katakana Ext' => 0x31ff,
  1508. 'CJK Reserve 1' => 0x2fffd,
  1509. 'CJK Reserve 2' => 0x3fffd,
  1510. 'Bomofo' => 0x312f,
  1511. 'Bomofo Ext' => 0x31b7,
  1512. 'Lisu' => 0xa4fd,
  1513. 'Yi' => 0xa48f,
  1514. );
  1515. // Generate characters consisting of starts, midpoints, and ends.
  1516. $chars = array();
  1517. $charcodes = array();
  1518. foreach ($starts as $key => $value) {
  1519. $charcodes[] = $starts[$key];
  1520. $chars[] = $this->code2utf($starts[$key]);
  1521. $mid = round(0.5 * ($starts[$key] + $ends[$key]));
  1522. $charcodes[] = $mid;
  1523. $chars[] = $this->code2utf($mid);
  1524. $charcodes[] = $ends[$key];
  1525. $chars[] = $this->code2utf($ends[$key]);
  1526. }
  1527. // Merge into a string and tokenize.
  1528. $string = implode('', $chars);
  1529. $out = trim(search_simplify($string));
  1530. $expected = drupal_strtolower(implode(' ', $chars));
  1531. // Verify that the output matches what we expect.
  1532. $this->assertEqual($out, $expected, 'CJK tokenizer worked on all supplied CJK characters');
  1533. }
  1534. /**
  1535. * Verifies that strings of non-CJK characters are not tokenized.
  1536. *
  1537. * This is just a sanity check - it verifies that strings of letters are
  1538. * not tokenized.
  1539. */
  1540. function testNoTokenizer() {
  1541. // Set the minimum word size to 1 (to split all CJK characters) and make
  1542. // sure CJK tokenizing is turned on.
  1543. variable_set('minimum_word_size', 1);
  1544. variable_set('overlap_cjk', TRUE);
  1545. $this->refreshVariables();
  1546. $letters = 'abcdefghijklmnopqrstuvwxyz';
  1547. $out = trim(search_simplify($letters));
  1548. $this->assertEqual($letters, $out, 'Letters are not CJK tokenized');
  1549. }
  1550. /**
  1551. * Like PHP chr() function, but for unicode characters.
  1552. *
  1553. * chr() only works for ASCII characters up to character 255. This function
  1554. * converts a number to the corresponding unicode character. Adapted from
  1555. * functions supplied in comments on several functions on php.net.
  1556. */
  1557. function code2utf($num) {
  1558. if ($num < 128) {
  1559. return chr($num);
  1560. }
  1561. if ($num < 2048) {
  1562. return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
  1563. }
  1564. if ($num < 65536) {
  1565. return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
  1566. }
  1567. if ($num < 2097152) {
  1568. return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
  1569. }
  1570. return '';
  1571. }
  1572. }
  1573. /**
  1574. * Tests that we can embed a form in search results and submit it.
  1575. */
  1576. class SearchEmbedForm extends DrupalWebTestCase {
  1577. /**
  1578. * Node used for testing.
  1579. */
  1580. public $node;
  1581. /**
  1582. * Count of how many times the form has been submitted.
  1583. */
  1584. public $submit_count = 0;
  1585. public static function getInfo() {
  1586. return array(
  1587. 'name' => 'Embedded forms',
  1588. 'description' => 'Verifies that a form embedded in search results works',
  1589. 'group' => 'Search',
  1590. );
  1591. }
  1592. function setUp() {
  1593. parent::setUp('search', 'search_embedded_form');
  1594. // Create a user and a node, and update the search index.
  1595. $test_user = $this->drupalCreateUser(array('access content', 'search content', 'administer nodes'));
  1596. $this->drupalLogin($test_user);
  1597. $this->node = $this->drupalCreateNode();
  1598. node_update_index();
  1599. search_update_totals();
  1600. // Set up a dummy initial count of times the form has been submitted.
  1601. $this->submit_count = 12;
  1602. variable_set('search_embedded_form_submitted', $this->submit_count);
  1603. $this->refreshVariables();
  1604. }
  1605. /**
  1606. * Tests that the embedded form appears and can be submitted.
  1607. */
  1608. function testEmbeddedForm() {
  1609. // First verify we can submit the form from the module's page.
  1610. $this->drupalPost('search_embedded_form',
  1611. array('name' => 'John'),
  1612. t('Send away'));
  1613. $this->assertText(t('Test form was submitted'), 'Form message appears');
  1614. $count = variable_get('search_embedded_form_submitted', 0);
  1615. $this->assertEqual($this->submit_count + 1, $count, 'Form submission count is correct');
  1616. $this->submit_count = $count;
  1617. // Now verify that we can see and submit the form from the search results.
  1618. $this->drupalGet('search/node/' . $this->node->title);
  1619. $this->assertText(t('Your name'), 'Form is visible');
  1620. $this->drupalPost('search/node/' . $this->node->title,
  1621. array('name' => 'John'),
  1622. t('Send away'));
  1623. $this->assertText(t('Test form was submitted'), 'Form message appears');
  1624. $count = variable_get('search_embedded_form_submitted', 0);
  1625. $this->assertEqual($this->submit_count + 1, $count, 'Form submission count is correct');
  1626. $this->submit_count = $count;
  1627. // Now verify that if we submit the search form, it doesn't count as
  1628. // our form being submitted.
  1629. $this->drupalPost('search',
  1630. array('keys' => 'foo'),
  1631. t('Search'));
  1632. $this->assertNoText(t('Test form was submitted'), 'Form message does not appear');
  1633. $count = variable_get('search_embedded_form_submitted', 0);
  1634. $this->assertEqual($this->submit_count, $count, 'Form submission count is correct');
  1635. $this->submit_count = $count;
  1636. }
  1637. }
  1638. /**
  1639. * Tests that hook_search_page runs.
  1640. */
  1641. class SearchPageOverride extends DrupalWebTestCase {
  1642. public $search_user;
  1643. public static function getInfo() {
  1644. return array(
  1645. 'name' => 'Search page override',
  1646. 'description' => 'Verify that hook_search_page can override search page display.',
  1647. 'group' => 'Search',
  1648. );
  1649. }
  1650. function setUp() {
  1651. parent::setUp('search', 'search_extra_type');
  1652. // Login as a user that can create and search content.
  1653. $this->search_user = $this->drupalCreateUser(array('search content', 'administer search'));
  1654. $this->drupalLogin($this->search_user);
  1655. // Enable the extra type module for searching.
  1656. variable_set('search_active_modules', array('node' => 'node', 'user' => 'user', 'search_extra_type' => 'search_extra_type'));
  1657. menu_rebuild();
  1658. }
  1659. function testSearchPageHook() {
  1660. $keys = 'bike shed ' . $this->randomName();
  1661. $this->drupalGet("search/dummy_path/{$keys}");
  1662. $this->assertText('Dummy search snippet', 'Dummy search snippet is shown');
  1663. $this->assertText('Test page text is here', 'Page override is working');
  1664. }
  1665. }
  1666. /**
  1667. * Test node search with multiple languages.
  1668. */
  1669. class SearchLanguageTestCase extends DrupalWebTestCase {
  1670. public static function getInfo() {
  1671. return array(
  1672. 'name' => 'Search language selection',
  1673. 'description' => 'Tests advanced search with different languages enabled.',
  1674. 'group' => 'Search',
  1675. );
  1676. }
  1677. /**
  1678. * Implementation setUp().
  1679. */
  1680. function setUp() {
  1681. parent::setUp('search', 'locale');
  1682. // Create and login user.
  1683. $test_user = $this->drupalCreateUser(array('access content', 'search content', 'use advanced search', 'administer nodes', 'administer languages', 'access administration pages'));
  1684. $this->drupalLogin($test_user);
  1685. }
  1686. function testLanguages() {
  1687. // Check that there are initially no languages displayed.
  1688. $this->drupalGet('search/node');
  1689. $this->assertNoText(t('Languages'), 'No languages to choose from.');
  1690. // Add predefined language.
  1691. $edit = array('langcode' => 'fr');
  1692. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add language'));
  1693. $this->assertText('fr', 'Language added successfully.');
  1694. // Now we should have languages displayed.
  1695. $this->drupalGet('search/node');
  1696. $this->assertText(t('Languages'), 'Languages displayed to choose from.');
  1697. $this->assertText(t('English'), 'English is a possible choice.');
  1698. $this->assertText(t('French'), 'French is a possible choice.');
  1699. // Ensure selecting no language does not make the query different.
  1700. $this->drupalPost('search/node', array(), t('Advanced search'));
  1701. $this->assertEqual($this->getUrl(), url('search/node/', array('absolute' => TRUE)), 'Correct page redirection, no language filtering.');
  1702. // Pick French and ensure it is selected.
  1703. $edit = array('language[fr]' => TRUE);
  1704. $this->drupalPost('search/node', $edit, t('Advanced search'));
  1705. $this->assertFieldByXPath('//input[@name="keys"]', 'language:fr', 'Language filter added to query.');
  1706. // Change the default language and disable English.
  1707. $path = 'admin/config/regional/language';
  1708. $this->drupalGet($path);
  1709. $this->assertFieldChecked('edit-site-default-en', 'English is the default language.');
  1710. $edit = array('site_default' => 'fr');
  1711. $this->drupalPost(NULL, $edit, t('Save configuration'));
  1712. $this->assertNoFieldChecked('edit-site-default-en', 'Default language updated.');
  1713. $edit = array('enabled[en]' => FALSE);
  1714. $this->drupalPost('admin/config/regional/language', $edit, t('Save configuration'));
  1715. $this->assertNoFieldChecked('edit-enabled-en', 'Language disabled.');
  1716. // Check that there are again no languages displayed.
  1717. $this->drupalGet('search/node');
  1718. $this->assertNoText(t('Languages'), 'No languages to choose from.');
  1719. }
  1720. }
  1721. /**
  1722. * Tests node search with node access control.
  1723. */
  1724. class SearchNodeAccessTest extends DrupalWebTestCase {
  1725. public $test_user;
  1726. public static function getInfo() {
  1727. return array(
  1728. 'name' => 'Search and node access',
  1729. 'description' => 'Tests search functionality with node access control.',
  1730. 'group' => 'Search',
  1731. );
  1732. }
  1733. function setUp() {
  1734. parent::setUp('search', 'node_access_test');
  1735. node_access_rebuild();
  1736. // Create a test user and log in.
  1737. $this->test_user = $this->drupalCreateUser(array('access content', 'search content', 'use advanced search'));
  1738. $this->drupalLogin($this->test_user);
  1739. }
  1740. /**
  1741. * Tests that search returns results with punctuation in the search phrase.
  1742. */
  1743. function testPhraseSearchPunctuation() {
  1744. $node = $this->drupalCreateNode(array('body' => array(LANGUAGE_NONE => array(array('value' => "The bunny's ears were fuzzy.")))));
  1745. // Update the search index.
  1746. module_invoke_all('update_index');
  1747. search_update_totals();
  1748. // Refresh variables after the treatment.
  1749. $this->refreshVariables();
  1750. // Submit a phrase wrapped in double quotes to include the punctuation.
  1751. $edit = array('keys' => '"bunny\'s"');
  1752. $this->drupalPost('search/node', $edit, t('Search'));
  1753. $this->assertText($node->title);
  1754. }
  1755. }

Constants

Classes

Namesort descending Description
SearchAdvancedSearchForm
SearchBlockTestCase
SearchCommentCountToggleTestCase Tests that comment count display toggles properly on comment status of node
SearchCommentTestCase Test integration searching comments.
SearchConfigSettingsForm Test config page.
SearchEmbedForm Tests that we can embed a form in search results and submit it.
SearchExactTestCase Tests that searching for a phrase gets the correct page count.
SearchExcerptTestCase Tests the search_excerpt() function.
SearchExpressionInsertExtractTestCase Tests search_expression_insert() and search_expression_extract().
SearchKeywordsConditions Tests keywords and conditions.
SearchLanguageTestCase Test node search with multiple languages.
SearchMatchTestCase
SearchNodeAccessTest Tests node search with node access control.
SearchNumberMatchingTestCase Tests that numbers can be searched, with more complex matching.
SearchNumbersTestCase Tests that numbers can be searched.
SearchPageOverride Tests that hook_search_page runs.
SearchPageText Tests the bike shed text on no results page, and text on the search page.
SearchRankingTestCase
SearchSimplifyTestCase Test search_simplify() on every Unicode character, and some other cases.
SearchTokenizerTestCase Test the CJK tokenizer.