More updates to stop using dev or alpha or beta versions.
[yaffs-website] / web / core / modules / search / src / Tests / SearchRankingTest.php
1 <?php
2
3 namespace Drupal\search\Tests;
4
5 use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
6 use Drupal\comment\Tests\CommentTestTrait;
7 use Drupal\Core\Url;
8 use Drupal\filter\Entity\FilterFormat;
9 use Drupal\search\Entity\SearchPage;
10
11 /**
12  * Indexes content and tests ranking factors.
13  *
14  * @group search
15  */
16 class SearchRankingTest extends SearchTestBase {
17
18   use CommentTestTrait;
19
20   /**
21    * The node search page.
22    *
23    * @var \Drupal\search\SearchPageInterface
24    */
25   protected $nodeSearch;
26
27   /**
28    * Modules to enable.
29    *
30    * @var array
31    */
32   public static $modules = ['statistics', 'comment'];
33
34   protected function setUp() {
35     parent::setUp();
36
37     // Create a plugin instance.
38     $this->nodeSearch = SearchPage::load('node_search');
39
40     // Log in with sufficient privileges.
41     $this->drupalLogin($this->drupalCreateUser(['post comments', 'skip comment approval', 'create page content', 'administer search']));
42   }
43
44   public function testRankings() {
45     // Add a comment field.
46     $this->addDefaultCommentField('node', 'page');
47
48     // Build a list of the rankings to test.
49     $node_ranks = ['sticky', 'promote', 'relevance', 'recent', 'comments', 'views'];
50
51     // Create nodes for testing.
52     $nodes = [];
53     foreach ($node_ranks as $node_rank) {
54       $settings = [
55         'type' => 'page',
56         'comment' => [
57           ['status' => CommentItemInterface::HIDDEN],
58         ],
59         'title' => 'Drupal rocks',
60         'body' => [['value' => "Drupal's search rocks"]],
61         // Node is one day old.
62         'created' => REQUEST_TIME - 24 * 3600,
63         'sticky' => 0,
64         'promote' => 0,
65       ];
66       foreach ([0, 1] as $num) {
67         if ($num == 1) {
68           switch ($node_rank) {
69             case 'sticky':
70             case 'promote':
71               $settings[$node_rank] = 1;
72               break;
73             case 'relevance':
74               $settings['body'][0]['value'] .= " really rocks";
75               break;
76             case 'recent':
77               // Node is 1 hour hold.
78               $settings['created'] = REQUEST_TIME - 3600;
79               break;
80             case 'comments':
81               $settings['comment'][0]['status'] = CommentItemInterface::OPEN;
82               break;
83           }
84         }
85         $nodes[$node_rank][$num] = $this->drupalCreateNode($settings);
86       }
87     }
88
89     // Add a comment to one of the nodes.
90     $edit = [];
91     $edit['subject[0][value]'] = 'my comment title';
92     $edit['comment_body[0][value]'] = 'some random comment';
93     $this->drupalGet('comment/reply/node/' . $nodes['comments'][1]->id() . '/comment');
94     $this->drupalPostForm(NULL, $edit, t('Preview'));
95     $this->drupalPostForm(NULL, $edit, t('Save'));
96
97     // Enable counting of statistics.
98     $this->config('statistics.settings')->set('count_content_views', 1)->save();
99
100     // Simulating content views is kind of difficult in the test. Leave that
101     // to the Statistics module. So instead go ahead and manually update the
102     // counter for this node.
103     $nid = $nodes['views'][1]->id();
104     db_insert('node_counter')
105       ->fields(['totalcount' => 5, 'daycount' => 5, 'timestamp' => REQUEST_TIME, 'nid' => $nid])
106       ->execute();
107
108     // Run cron to update the search index and comment/statistics totals.
109     $this->cronRun();
110
111     // Test that the settings form displays the content ranking section.
112     $this->drupalGet('admin/config/search/pages/manage/node_search');
113     $this->assertText(t('Content ranking'));
114
115     // Check that all rankings are visible and set to 0.
116     foreach ($node_ranks as $node_rank) {
117       $this->assertTrue($this->xpath('//select[@id="edit-rankings-' . $node_rank . '-value"]//option[@value="0"]'), 'Select list to prioritize ' . $node_rank . ' for node ranks is visible and set to 0.');
118     }
119
120     // Test each of the possible rankings.
121     $edit = [];
122     foreach ($node_ranks as $node_rank) {
123       // Enable the ranking we are testing.
124       $edit['rankings[' . $node_rank . '][value]'] = 10;
125       $this->drupalPostForm('admin/config/search/pages/manage/node_search', $edit, t('Save search page'));
126       $this->drupalGet('admin/config/search/pages/manage/node_search');
127       $this->assertTrue($this->xpath('//select[@id="edit-rankings-' . $node_rank . '-value"]//option[@value="10"]'), 'Select list to prioritize ' . $node_rank . ' for node ranks is visible and set to 10.');
128
129       // Reload the plugin to get the up-to-date values.
130       $this->nodeSearch = SearchPage::load('node_search');
131       // Do the search and assert the results.
132       $this->nodeSearch->getPlugin()->setSearch('rocks', [], []);
133       $set = $this->nodeSearch->getPlugin()->execute();
134       $this->assertEqual($set[0]['node']->id(), $nodes[$node_rank][1]->id(), 'Search ranking "' . $node_rank . '" order.');
135
136       // Clear this ranking for the next test.
137       $edit['rankings[' . $node_rank . '][value]'] = 0;
138     }
139
140     // Save the final node_rank change then check that all rankings are visible
141     // and have been set back to 0.
142     $this->drupalPostForm('admin/config/search/pages/manage/node_search', $edit, t('Save search page'));
143     $this->drupalGet('admin/config/search/pages/manage/node_search');
144     foreach ($node_ranks as $node_rank) {
145       $this->assertTrue($this->xpath('//select[@id="edit-rankings-' . $node_rank . '-value"]//option[@value="0"]'), 'Select list to prioritize ' . $node_rank . ' for node ranks is visible and set to 0.');
146     }
147
148     // Try with sticky, then promoted. This is a test for issue
149     // https://www.drupal.org/node/771596.
150     $node_ranks = [
151       'sticky' => 10,
152       'promote' => 1,
153       'relevance' => 0,
154       'recent' => 0,
155       'comments' => 0,
156       'views' => 0,
157     ];
158     $configuration = $this->nodeSearch->getPlugin()->getConfiguration();
159     foreach ($node_ranks as $var => $value) {
160       $configuration['rankings'][$var] = $value;
161     }
162     $this->nodeSearch->getPlugin()->setConfiguration($configuration);
163     $this->nodeSearch->save();
164
165     // Do the search and assert the results. The sticky node should show up
166     // first, then the promoted node, then all the rest.
167     $this->nodeSearch->getPlugin()->setSearch('rocks', [], []);
168     $set = $this->nodeSearch->getPlugin()->execute();
169     $this->assertEqual($set[0]['node']->id(), $nodes['sticky'][1]->id(), 'Search ranking for sticky first worked.');
170     $this->assertEqual($set[1]['node']->id(), $nodes['promote'][1]->id(), 'Search ranking for promoted second worked.');
171
172     // Try with recent, then comments. This is a test for issues
173     // https://www.drupal.org/node/771596 and
174     // https://www.drupal.org/node/303574.
175     $node_ranks = [
176       'sticky' => 0,
177       'promote' => 0,
178       'relevance' => 0,
179       'recent' => 10,
180       'comments' => 1,
181       'views' => 0,
182     ];
183     $configuration = $this->nodeSearch->getPlugin()->getConfiguration();
184     foreach ($node_ranks as $var => $value) {
185       $configuration['rankings'][$var] = $value;
186     }
187     $this->nodeSearch->getPlugin()->setConfiguration($configuration);
188     $this->nodeSearch->save();
189
190     // Do the search and assert the results. The recent node should show up
191     // first, then the commented node, then all the rest.
192     $this->nodeSearch->getPlugin()->setSearch('rocks', [], []);
193     $set = $this->nodeSearch->getPlugin()->execute();
194     $this->assertEqual($set[0]['node']->id(), $nodes['recent'][1]->id(), 'Search ranking for recent first worked.');
195     $this->assertEqual($set[1]['node']->id(), $nodes['comments'][1]->id(), 'Search ranking for comments second worked.');
196
197   }
198
199   /**
200    * Test rankings of HTML tags.
201    */
202   public function testHTMLRankings() {
203     $full_html_format = FilterFormat::create([
204       'format' => 'full_html',
205       'name' => 'Full HTML',
206     ]);
207     $full_html_format->save();
208
209     // Test HTML tags with different weights.
210     $sorted_tags = ['h1', 'h2', 'h3', 'h4', 'a', 'h5', 'h6', 'notag'];
211     $shuffled_tags = $sorted_tags;
212
213     // Shuffle tags to ensure HTML tags are ranked properly.
214     shuffle($shuffled_tags);
215     $settings = [
216       'type' => 'page',
217       'title' => 'Simple node',
218     ];
219     $nodes = [];
220     foreach ($shuffled_tags as $tag) {
221       switch ($tag) {
222         case 'a':
223           $settings['body'] = [['value' => \Drupal::l('Drupal Rocks', new Url('<front>')), 'format' => 'full_html']];
224           break;
225         case 'notag':
226           $settings['body'] = [['value' => 'Drupal Rocks']];
227           break;
228         default:
229           $settings['body'] = [['value' => "<$tag>Drupal Rocks</$tag>", 'format' => 'full_html']];
230           break;
231       }
232       $nodes[$tag] = $this->drupalCreateNode($settings);
233     }
234
235     // Update the search index.
236     $this->nodeSearch->getPlugin()->updateIndex();
237     search_update_totals();
238
239     $this->nodeSearch->getPlugin()->setSearch('rocks', [], []);
240     // Do the search and assert the results.
241     $set = $this->nodeSearch->getPlugin()->execute();
242
243     // Test the ranking of each tag.
244     foreach ($sorted_tags as $tag_rank => $tag) {
245       // Assert the results.
246       if ($tag == 'notag') {
247         $this->assertEqual($set[$tag_rank]['node']->id(), $nodes[$tag]->id(), 'Search tag ranking for plain text order.');
248       }
249       else {
250         $this->assertEqual($set[$tag_rank]['node']->id(), $nodes[$tag]->id(), 'Search tag ranking for "&lt;' . $sorted_tags[$tag_rank] . '&gt;" order.');
251       }
252     }
253
254     // Test tags with the same weight against the sorted tags.
255     $unsorted_tags = ['u', 'b', 'i', 'strong', 'em'];
256     foreach ($unsorted_tags as $tag) {
257       $settings['body'] = [['value' => "<$tag>Drupal Rocks</$tag>", 'format' => 'full_html']];
258       $node = $this->drupalCreateNode($settings);
259
260       // Update the search index.
261       $this->nodeSearch->getPlugin()->updateIndex();
262       search_update_totals();
263
264       $this->nodeSearch->getPlugin()->setSearch('rocks', [], []);
265       // Do the search and assert the results.
266       $set = $this->nodeSearch->getPlugin()->execute();
267
268       // Ranking should always be second to last.
269       $set = array_slice($set, -2, 1);
270
271       // Assert the results.
272       $this->assertEqual($set[0]['node']->id(), $node->id(), 'Search tag ranking for "&lt;' . $tag . '&gt;" order.');
273
274       // Delete node so it doesn't show up in subsequent search results.
275       $node->delete();
276     }
277   }
278
279 }