3dfc1179c0d388b9f7e20ce169336d6517f772d2
[yaffs-website] / web / core / modules / search / tests / src / Functional / SearchMultilingualEntityTest.php
1 <?php
2
3 namespace Drupal\Tests\search\Functional;
4
5 use Drupal\field\Entity\FieldStorageConfig;
6 use Drupal\language\Entity\ConfigurableLanguage;
7
8 /**
9  * Tests entities with multilingual fields.
10  *
11  * @group search
12  */
13 class SearchMultilingualEntityTest extends SearchTestBase {
14
15   /**
16    * List of searchable nodes.
17    *
18    * @var \Drupal\node\NodeInterface[]
19    */
20   protected $searchableNodes = [];
21
22   /**
23    * Node search plugin.
24    *
25    * @var \Drupal\node\Plugin\Search\NodeSearch
26    */
27   protected $plugin;
28
29   public static $modules = ['language', 'locale', 'comment'];
30
31   protected function setUp() {
32     parent::setUp();
33
34     // Create a user who can administer search, do searches, see the status
35     // report, and administer cron. Log in.
36     $user = $this->drupalCreateUser(['administer search', 'search content', 'use advanced search', 'access content', 'access site reports', 'administer site configuration']);
37     $this->drupalLogin($user);
38
39     // Set up the search plugin.
40     $this->plugin = $this->container->get('plugin.manager.search')->createInstance('node_search');
41
42     // Check indexing counts before adding any nodes.
43     $this->assertIndexCounts(0, 0, 'before adding nodes');
44     $this->assertDatabaseCounts(0, 0, 'before adding nodes');
45
46     // Add two new languages.
47     ConfigurableLanguage::createFromLangcode('hu')->save();
48     ConfigurableLanguage::createFromLangcode('sv')->save();
49
50     // Make the body field translatable. The title is already translatable by
51     // definition. The parent class has already created the article and page
52     // content types.
53     $field_storage = FieldStorageConfig::loadByName('node', 'body');
54     $field_storage->setTranslatable(TRUE);
55     $field_storage->save();
56
57     // Create a few page nodes with multilingual body values.
58     $default_format = filter_default_format();
59     $nodes = [
60       [
61         'title' => 'First node en',
62         'type' => 'page',
63         'body' => [['value' => $this->randomMachineName(32), 'format' => $default_format]],
64         'langcode' => 'en',
65       ],
66       [
67         'title' => 'Second node this is the English title',
68         'type' => 'page',
69         'body' => [['value' => $this->randomMachineName(32), 'format' => $default_format]],
70         'langcode' => 'en',
71       ],
72       [
73         'title' => 'Third node en',
74         'type' => 'page',
75         'body' => [['value' => $this->randomMachineName(32), 'format' => $default_format]],
76         'langcode' => 'en',
77       ],
78       // After the third node, we don't care what the settings are. But we
79       // need to have at least 5 to make sure the throttling is working
80       // correctly. So, let's make 8 total.
81       [
82       ],
83       [
84       ],
85       [
86       ],
87       [
88       ],
89       [
90       ],
91     ];
92     $this->searchableNodes = [];
93     foreach ($nodes as $setting) {
94       $this->searchableNodes[] = $this->drupalCreateNode($setting);
95     }
96
97     // Add a single translation to the second node.
98     $translation = $this->searchableNodes[1]->addTranslation('hu', ['title' => 'Second node hu']);
99     $translation->body->value = $this->randomMachineName(32);
100     $this->searchableNodes[1]->save();
101
102     // Add two translations to the third node.
103     $translation = $this->searchableNodes[2]->addTranslation('hu', ['title' => 'Third node this is the Hungarian title']);
104     $translation->body->value = $this->randomMachineName(32);
105     $translation = $this->searchableNodes[2]->addTranslation('sv', ['title' => 'Third node sv']);
106     $translation->body->value = $this->randomMachineName(32);
107     $this->searchableNodes[2]->save();
108
109     // Verify that we have 8 nodes left to do.
110     $this->assertIndexCounts(8, 8, 'before updating the search index');
111     $this->assertDatabaseCounts(0, 0, 'before updating the search index');
112   }
113
114   /**
115    * Tests the indexing throttle and search results with multilingual nodes.
116    */
117   public function testMultilingualSearch() {
118     // Index only 2 nodes per cron run. We cannot do this setting in the UI,
119     // because it doesn't go this low.
120     $this->config('search.settings')->set('index.cron_limit', 2)->save();
121     // Get a new search plugin, to make sure it has this setting.
122     $this->plugin = $this->container->get('plugin.manager.search')->createInstance('node_search');
123
124     // Update the index. This does the initial processing.
125     $this->plugin->updateIndex();
126     // Run the shutdown function. Testing is a unique case where indexing
127     // and searching has to happen in the same request, so running the shutdown
128     // function manually is needed to finish the indexing process.
129     search_update_totals();
130     $this->assertIndexCounts(6, 8, 'after updating partially');
131     $this->assertDatabaseCounts(2, 0, 'after updating partially');
132
133     // Now index the rest of the nodes.
134     // Make sure index throttle is high enough, via the UI.
135     $this->drupalPostForm('admin/config/search/pages', ['cron_limit' => 20], t('Save configuration'));
136     $this->assertEqual(20, $this->config('search.settings')->get('index.cron_limit', 100), 'Config setting was saved correctly');
137     // Get a new search plugin, to make sure it has this setting.
138     $this->plugin = $this->container->get('plugin.manager.search')->createInstance('node_search');
139
140     $this->plugin->updateIndex();
141     search_update_totals();
142     $this->assertIndexCounts(0, 8, 'after updating fully');
143     $this->assertDatabaseCounts(8, 0, 'after updating fully');
144
145     // Click the reindex button on the admin page, verify counts, and reindex.
146     $this->drupalPostForm('admin/config/search/pages', [], t('Re-index site'));
147     $this->drupalPostForm(NULL, [], t('Re-index site'));
148     $this->assertIndexCounts(8, 8, 'after reindex');
149     $this->assertDatabaseCounts(8, 0, 'after reindex');
150     $this->plugin->updateIndex();
151     search_update_totals();
152
153     // Test search results.
154
155     // This should find two results for the second and third node.
156     $this->plugin->setSearch('English OR Hungarian', [], []);
157     $search_result = $this->plugin->execute();
158     $this->assertEqual(count($search_result), 2, 'Found two results.');
159     // Nodes are saved directly after each other and have the same created time
160     // so testing for the order is not possible.
161     $results = [$search_result[0]['title'], $search_result[1]['title']];
162     $this->assertTrue(in_array('Third node this is the Hungarian title', $results), 'The search finds the correct Hungarian title.');
163     $this->assertTrue(in_array('Second node this is the English title', $results), 'The search finds the correct English title.');
164
165     // Now filter for Hungarian results only.
166     $this->plugin->setSearch('English OR Hungarian', ['f' => ['language:hu']], []);
167     $search_result = $this->plugin->execute();
168
169     $this->assertEqual(count($search_result), 1, 'The search found only one result');
170     $this->assertEqual($search_result[0]['title'], 'Third node this is the Hungarian title', 'The search finds the correct Hungarian title.');
171
172     // Test for search with common key word across multiple languages.
173     $this->plugin->setSearch('node', [], []);
174     $search_result = $this->plugin->execute();
175
176     $this->assertEqual(count($search_result), 6, 'The search found total six results');
177
178     // Test with language filters and common key word.
179     $this->plugin->setSearch('node', ['f' => ['language:hu']], []);
180     $search_result = $this->plugin->execute();
181
182     $this->assertEqual(count($search_result), 2, 'The search found 2 results');
183
184     // Test to check for the language of result items.
185     foreach ($search_result as $result) {
186       $this->assertEqual($result['langcode'], 'hu', 'The search found the correct Hungarian result');
187     }
188
189     // Mark one of the nodes for reindexing, using the API function, and
190     // verify indexing status.
191     search_mark_for_reindex('node_search', $this->searchableNodes[0]->id());
192     $this->assertIndexCounts(1, 8, 'after marking one node to reindex via API function');
193
194     // Update the index and verify the totals again.
195     $this->plugin = $this->container->get('plugin.manager.search')->createInstance('node_search');
196     $this->plugin->updateIndex();
197     search_update_totals();
198     $this->assertIndexCounts(0, 8, 'after indexing again');
199
200     // Mark one node for reindexing by saving it, and verify indexing status.
201     $this->searchableNodes[1]->save();
202     $this->assertIndexCounts(1, 8, 'after marking one node to reindex via save');
203
204     // The request time is always the same throughout test runs. Update the
205     // request time to a previous time, to simulate it having been marked
206     // previously.
207     $current = REQUEST_TIME;
208     $old = $current - 10;
209     db_update('search_dataset')
210       ->fields(['reindex' => $old])
211       ->condition('reindex', $current, '>=')
212       ->execute();
213
214     // Save the node again. Verify that the request time on it is not updated.
215     $this->searchableNodes[1]->save();
216     $result = db_select('search_dataset', 'd')
217       ->fields('d', ['reindex'])
218       ->condition('type', 'node_search')
219       ->condition('sid', $this->searchableNodes[1]->id())
220       ->execute()
221       ->fetchField();
222     $this->assertEqual($result, $old, 'Reindex time was not updated if node was already marked');
223
224     // Add a bogus entry to the search index table using a different search
225     // type. This will not appear in the index status, because it is not
226     // managed by a plugin.
227     search_index('foo', $this->searchableNodes[0]->id(), 'en', 'some text');
228     $this->assertIndexCounts(1, 8, 'after adding a different index item');
229
230     // Mark just this "foo" index for reindexing.
231     search_mark_for_reindex('foo');
232     $this->assertIndexCounts(1, 8, 'after reindexing the other search type');
233
234     // Mark everything for reindexing.
235     search_mark_for_reindex();
236     $this->assertIndexCounts(8, 8, 'after reindexing everything');
237
238     // Clear one item from the index, but with wrong language.
239     $this->assertDatabaseCounts(8, 1, 'before clear');
240     search_index_clear('node_search', $this->searchableNodes[0]->id(), 'hu');
241     $this->assertDatabaseCounts(8, 1, 'after clear with wrong language');
242     // Clear using correct language.
243     search_index_clear('node_search', $this->searchableNodes[0]->id(), 'en');
244     $this->assertDatabaseCounts(7, 1, 'after clear with right language');
245     // Don't specify language.
246     search_index_clear('node_search', $this->searchableNodes[1]->id());
247     $this->assertDatabaseCounts(6, 1, 'unspecified language clear');
248     // Clear everything in 'foo'.
249     search_index_clear('foo');
250     $this->assertDatabaseCounts(6, 0, 'other index clear');
251     // Clear everything.
252     search_index_clear();
253     $this->assertDatabaseCounts(0, 0, 'complete clear');
254   }
255
256   /**
257    * Verifies the indexing status counts.
258    *
259    * @param int $remaining
260    *   Count of remaining items to verify.
261    * @param int $total
262    *   Count of total items to verify.
263    * @param string $message
264    *   Message to use, something like "after updating the search index".
265    */
266   protected function assertIndexCounts($remaining, $total, $message) {
267     // Check status via plugin method call.
268     $status = $this->plugin->indexStatus();
269     $this->assertEqual($status['remaining'], $remaining, 'Remaining items ' . $message . ' is ' . $remaining);
270     $this->assertEqual($status['total'], $total, 'Total items ' . $message . ' is ' . $total);
271
272     // Check text in progress section of Search settings page. Note that this
273     // test avoids using
274     // \Drupal\Core\StringTranslation\TranslationInterface::formatPlural(), so
275     // it tests for fragments of text.
276     $indexed = $total - $remaining;
277     $percent = ($total > 0) ? floor(100 * $indexed / $total) : 100;
278     $this->drupalGet('admin/config/search/pages');
279     $this->assertText($percent . '% of the site has been indexed.', 'Progress percent text at top of Search settings page is correct at: ' . $message);
280     $this->assertText($remaining . ' item', 'Remaining text at top of Search settings page is correct at: ' . $message);
281
282     // Check text in pages section of Search settings page.
283     $this->assertText($indexed . ' of ' . $total . ' indexed', 'Progress text in pages section of Search settings page is correct at: ' . $message);
284
285     // Check text on status report page.
286     $this->drupalGet('admin/reports/status');
287     $this->assertText('Search index progress', 'Search status section header is present on status report page');
288     $this->assertText($percent . '%', 'Correct percentage is shown on status report page at: ' . $message);
289     $this->assertText('(' . $remaining . ' remaining)', 'Correct remaining value is shown on status report page at: ' . $message);
290   }
291
292   /**
293    * Checks actual database counts of items in the search index.
294    *
295    * @param int $count_node
296    *   Count of node items to assert.
297    * @param int $count_foo
298    *   Count of "foo" items to assert.
299    * @param string $message
300    *   Message suffix to use.
301    */
302   protected function assertDatabaseCounts($count_node, $count_foo, $message) {
303     // Count number of distinct nodes by ID.
304     $results = db_select('search_dataset', 'i')
305       ->fields('i', ['sid'])
306       ->condition('type', 'node_search')
307       ->groupBy('sid')
308       ->execute()
309       ->fetchCol();
310     $this->assertEqual($count_node, count($results), 'Node count was ' . $count_node . ' for ' . $message);
311
312     // Count number of "foo" records.
313     $results = db_select('search_dataset', 'i')
314       ->fields('i', ['sid'])
315       ->condition('type', 'foo')
316       ->execute()
317       ->fetchCol();
318     $this->assertEqual($count_foo, count($results), 'Foo count was ' . $count_foo . ' for ' . $message);
319
320   }
321
322 }