SearchMultilingualEntityTest.php 13.6 KB
Newer Older
webchick's avatar
webchick committed
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Definition of Drupal\search\Tests\SearchMultilingualEntityTest.
 */

namespace Drupal\search\Tests;

10
use Drupal\field\Entity\FieldStorageConfig;
11
use Drupal\language\Entity\ConfigurableLanguage;
12

webchick's avatar
webchick committed
13 14
/**
 * Tests entities with multilingual fields.
15 16
 *
 * @group search
webchick's avatar
webchick committed
17 18 19 20 21 22
 */
class SearchMultilingualEntityTest extends SearchTestBase {

  /**
   * List of searchable nodes.
   *
23
   * @var \Drupal\node\NodeInterface[]
webchick's avatar
webchick committed
24
   */
25
  protected $searchableNodes = array();
webchick's avatar
webchick committed
26

27 28 29 30 31 32 33
  /**
   * Node search plugin.
   *
   * @var \Drupal\node\Plugin\Search\NodeSearch
   */
  protected $plugin;

webchick's avatar
webchick committed
34 35
  public static $modules = array('language', 'locale', 'comment');

36
  protected function setUp() {
webchick's avatar
webchick committed
37 38
    parent::setUp();

39 40 41 42 43 44
    // Create a user who can administer search, do searches, see the status
    // report, and administer cron. Log in.
    $user = $this->drupalCreateUser(array('administer search', 'search content', 'use advanced search', 'access content', 'access site reports', 'administer site configuration'));
    $this->drupalLogin($user);

    // Make sure that auto-cron is disabled.
45
    $this->config('system.cron')->set('threshold.autorun', 0)->save();
46 47 48 49 50 51

    // Set up the search plugin.
    $this->plugin = $this->container->get('plugin.manager.search')->createInstance('node_search');

    // Check indexing counts before adding any nodes.
    $this->assertIndexCounts(0, 0, 'before adding nodes');
52
    $this->assertDatabaseCounts(0, 0, 'before adding nodes');
53

webchick's avatar
webchick committed
54
    // Add two new languages.
55 56
    ConfigurableLanguage::createFromLangcode('hu')->save();
    ConfigurableLanguage::createFromLangcode('sv')->save();
webchick's avatar
webchick committed
57

58 59 60
    // Make the body field translatable. The title is already translatable by
    // definition. The parent class has already created the article and page
    // content types.
61 62 63
    $field_storage = FieldStorageConfig::loadByName('node', 'body');
    $field_storage->translatable = TRUE;
    $field_storage->save();
webchick's avatar
webchick committed
64 65 66 67 68

    // Create a few page nodes with multilingual body values.
    $default_format = filter_default_format();
    $nodes = array(
      array(
69
        'title' => 'First node en',
webchick's avatar
webchick committed
70
        'type' => 'page',
71
        'body' => array(array('value' => $this->randomMachineName(32), 'format' => $default_format)),
webchick's avatar
webchick committed
72 73 74
        'langcode' => 'en',
      ),
      array(
75
        'title' => 'Second node this is the English title',
webchick's avatar
webchick committed
76
        'type' => 'page',
77
        'body' => array(array('value' => $this->randomMachineName(32), 'format' => $default_format)),
webchick's avatar
webchick committed
78 79 80
        'langcode' => 'en',
      ),
      array(
81
        'title' => 'Third node en',
webchick's avatar
webchick committed
82
        'type' => 'page',
83
        'body' => array(array('value' => $this->randomMachineName(32), 'format' => $default_format)),
webchick's avatar
webchick committed
84 85
        'langcode' => 'en',
      ),
86 87 88 89 90 91 92 93 94 95 96 97 98
      // After the third node, we don't care what the settings are. But we
      // need to have at least 5 to make sure the throttling is working
      // correctly. So, let's make 8 total.
      array(
      ),
      array(
      ),
      array(
      ),
      array(
      ),
      array(
      ),
webchick's avatar
webchick committed
99
    );
100
    $this->searchableNodes = array();
101
    foreach ($nodes as $setting) {
102
      $this->searchableNodes[] = $this->drupalCreateNode($setting);
webchick's avatar
webchick committed
103
    }
104

105
    // Add a single translation to the second node.
106
    $translation = $this->searchableNodes[1]->addTranslation('hu', array('title' => 'Second node hu'));
107
    $translation->body->value = $this->randomMachineName(32);
108
    $this->searchableNodes[1]->save();
109 110

    // Add two translations to the third node.
111
    $translation = $this->searchableNodes[2]->addTranslation('hu', array('title' => 'Third node this is the Hungarian title'));
112
    $translation->body->value = $this->randomMachineName(32);
113
    $translation = $this->searchableNodes[2]->addTranslation('sv', array('title' => 'Third node sv'));
114
    $translation->body->value = $this->randomMachineName(32);
115
    $this->searchableNodes[2]->save();
116

117 118
    // Verify that we have 8 nodes left to do.
    $this->assertIndexCounts(8, 8, 'before updating the search index');
119
    $this->assertDatabaseCounts(0, 0, 'before updating the search index');
webchick's avatar
webchick committed
120 121 122
  }

  /**
123
   * Tests the indexing throttle and search results with multilingual nodes.
webchick's avatar
webchick committed
124
   */
125 126 127
  function testMultilingualSearch() {
    // Index only 2 nodes per cron run. We cannot do this setting in the UI,
    // because it doesn't go this low.
128
    $this->config('search.settings')->set('index.cron_limit', 2)->save();
129 130
    // Get a new search plugin, to make sure it has this setting.
    $this->plugin = $this->container->get('plugin.manager.search')->createInstance('node_search');
131

webchick's avatar
webchick committed
132
    // Update the index. This does the initial processing.
133
    $this->plugin->updateIndex();
webchick's avatar
webchick committed
134 135 136 137
    // Run the shutdown function. Testing is a unique case where indexing
    // and searching has to happen in the same request, so running the shutdown
    // function manually is needed to finish the indexing process.
    search_update_totals();
138
    $this->assertIndexCounts(6, 8, 'after updating partially');
139
    $this->assertDatabaseCounts(2, 0, 'after updating partially');
webchick's avatar
webchick committed
140

141 142
    // Now index the rest of the nodes.
    // Make sure index throttle is high enough, via the UI.
143
    $this->drupalPostForm('admin/config/search/pages', array('cron_limit' => 20), t('Save configuration'));
144
    $this->assertEqual(20, $this->config('search.settings')->get('index.cron_limit', 100), 'Config setting was saved correctly');
145 146
    // Get a new search plugin, to make sure it has this setting.
    $this->plugin = $this->container->get('plugin.manager.search')->createInstance('node_search');
147 148

    $this->plugin->updateIndex();
webchick's avatar
webchick committed
149
    search_update_totals();
150
    $this->assertIndexCounts(0, 8, 'after updating fully');
151 152 153 154 155 156 157 158 159
    $this->assertDatabaseCounts(8, 0, 'after updating fully');

    // Click the reindex button on the admin page, verify counts, and reindex.
    $this->drupalPostForm('admin/config/search/pages', array(), t('Re-index site'));
    $this->drupalPostForm(NULL, array(), t('Re-index site'));
    $this->assertIndexCounts(8, 8, 'after reindex');
    $this->assertDatabaseCounts(8, 0, 'after reindex');
    $this->plugin->updateIndex();
    search_update_totals();
160 161

    // Test search results.
162 163

    // This should find two results for the second and third node.
164 165
    $this->plugin->setSearch('English OR Hungarian', array(), array());
    $search_result = $this->plugin->execute();
166 167 168 169 170 171
    $this->assertEqual(count($search_result), 2, 'Found two results.');
    // Nodes are saved directly after each other and have the same created time
    // so testing for the order is not possible.
    $results = array($search_result[0]['title'], $search_result[1]['title']);
    $this->assertTrue(in_array('Third node this is the Hungarian title', $results), 'The search finds the correct Hungarian title.');
    $this->assertTrue(in_array('Second node this is the English title', $results), 'The search finds the correct English title.');
172 173

    // Now filter for Hungarian results only.
174 175
    $this->plugin->setSearch('English OR Hungarian', array('f' => array('language:hu')), array());
    $search_result = $this->plugin->execute();
176 177 178

    $this->assertEqual(count($search_result), 1, 'The search found only one result');
    $this->assertEqual($search_result[0]['title'], 'Third node this is the Hungarian title', 'The search finds the correct Hungarian title.');
179 180

    // Test for search with common key word across multiple languages.
181 182
    $this->plugin->setSearch('node', array(), array());
    $search_result = $this->plugin->execute();
183 184 185 186

    $this->assertEqual(count($search_result), 6, 'The search found total six results');

    // Test with language filters and common key word.
187 188
    $this->plugin->setSearch('node', array('f' => array('language:hu')), array());
    $search_result = $this->plugin->execute();
189 190 191 192 193 194 195

    $this->assertEqual(count($search_result), 2, 'The search found 2 results');

    // Test to check for the language of result items.
    foreach($search_result as $result) {
      $this->assertEqual($result['langcode'], 'hu', 'The search found the correct Hungarian result');
    }
196 197 198

    // Mark one of the nodes for reindexing, using the API function, and
    // verify indexing status.
199
    search_mark_for_reindex('node_search', $this->searchableNodes[0]->id());
200
    $this->assertIndexCounts(1, 8, 'after marking one node to reindex via API function');
201 202 203 204 205

    // Update the index and verify the totals again.
    $this->plugin = $this->container->get('plugin.manager.search')->createInstance('node_search');
    $this->plugin->updateIndex();
    search_update_totals();
206
    $this->assertIndexCounts(0, 8, 'after indexing again');
207 208

    // Mark one node for reindexing by saving it, and verify indexing status.
209
    $this->searchableNodes[1]->save();
210
    $this->assertIndexCounts(1, 8, 'after marking one node to reindex via save');
211 212 213 214 215 216 217 218 219 220 221 222

    // The request time is always the same throughout test runs. Update the
    // request time to a previous time, to simulate it having been marked
    // previously.
    $current = REQUEST_TIME;
    $old = $current - 10;
    db_update('search_dataset')
      ->fields(array('reindex' => $old))
      ->condition('reindex', $current, '>=')
      ->execute();

    // Save the node again. Verify that the request time on it is not updated.
223
    $this->searchableNodes[1]->save();
224 225 226
    $result = db_select('search_dataset', 'd')
      ->fields('d', array('reindex'))
      ->condition('type', 'node_search')
227
      ->condition('sid', $this->searchableNodes[1]->id())
228 229 230
      ->execute()
      ->fetchField();
    $this->assertEqual($result, $old, 'Reindex time was not updated if node was already marked');
231 232 233 234

    // Add a bogus entry to the search index table using a different search
    // type. This will not appear in the index status, because it is not
    // managed by a plugin.
235
    search_index('foo', $this->searchableNodes[0]->id(), 'en', 'some text');
236 237 238 239 240 241 242 243 244 245 246 247
    $this->assertIndexCounts(1, 8, 'after adding a different index item');

    // Mark just this "foo" index for reindexing.
    search_mark_for_reindex('foo');
    $this->assertIndexCounts(1, 8, 'after reindexing the other search type');

    // Mark everything for reindexing.
    search_mark_for_reindex();
    $this->assertIndexCounts(8, 8, 'after reindexing everything');

    // Clear one item from the index, but with wrong language.
    $this->assertDatabaseCounts(8, 1, 'before clear');
248
    search_index_clear('node_search', $this->searchableNodes[0]->id(), 'hu');
249 250
    $this->assertDatabaseCounts(8, 1, 'after clear with wrong language');
    // Clear using correct language.
251
    search_index_clear('node_search', $this->searchableNodes[0]->id(), 'en');
252 253
    $this->assertDatabaseCounts(7, 1, 'after clear with right language');
    // Don't specify language.
254
    search_index_clear('node_search', $this->searchableNodes[1]->id());
255 256 257 258 259 260 261
    $this->assertDatabaseCounts(6, 1, 'unspecified language clear');
    // Clear everything in 'foo'.
    search_index_clear('foo');
    $this->assertDatabaseCounts(6, 0, 'other index clear');
    // Clear everything.
    search_index_clear();
    $this->assertDatabaseCounts(0, 0, 'complete clear');
262 263 264 265 266 267 268 269 270 271 272 273 274
  }

  /**
   * Verifies the indexing status counts.
   *
   * @param $remaining
   *   Count of remaining items to verify.
   * @param $total
   *   Count of total items to verify.
   * @param $message
   *   Message to use, something like "after updating the search index".
   */
  protected function assertIndexCounts($remaining, $total, $message) {
275
    // Check status via plugin method call.
276 277 278
    $status = $this->plugin->indexStatus();
    $this->assertEqual($status['remaining'], $remaining, 'Remaining items ' . $message . ' is ' . $remaining);
    $this->assertEqual($status['total'], $total, 'Total items ' . $message . ' is ' . $total);
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295

    // Check text in progress section of Search settings page. Note that this
    // test avoids using format_plural(), so it tests for fragments of text.
    $indexed = $total - $remaining;
    $percent = ($total > 0) ? floor(100 * $indexed / $total) : 100;
    $this->drupalGet('admin/config/search/pages');
    $this->assertText($percent . '% of the site has been indexed.', 'Progress percent text at top of Search settings page is correct at: ' . $message);
    $this->assertText($remaining . ' item', 'Remaining text at top of Search settings page is correct at: ' . $message);

    // Check text in pages section of Search settings page.
    $this->assertText($indexed . ' of ' . $total . ' indexed', 'Progress text in pages section of Search settings page is correct at: ' . $message);

    // Check text on status report page.
    $this->drupalGet('admin/reports/status');
    $this->assertText('Search index progress', 'Search status section header is present on status report page');
    $this->assertText($percent . '%', 'Correct percentage is shown on status report page at: ' . $message);
    $this->assertText('(' . $remaining . ' remaining)', 'Correct remaining value is shown on status report page at: ' . $message);
webchick's avatar
webchick committed
296
  }
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326

  /**
   * Checks actual database counts of items in the search index.
   *
   * @param int $count_node
   *   Count of node items to assert.
   * @param int $count_foo
   *   Count of "foo" items to assert.
   * @param string $message
   *   Message suffix to use.
   */
  protected function assertDatabaseCounts($count_node, $count_foo, $message) {
    // Count number of distinct nodes by ID.
    $results = db_select('search_dataset', 'i')
      ->fields('i', array('sid'))
      ->condition('type', 'node_search')
      ->groupBy('sid')
      ->execute()
      ->fetchCol();
    $this->assertEqual($count_node, count($results), 'Node count was ' . $count_node . ' for ' . $message);

    // Count number of "foo" records.
    $results = db_select('search_dataset', 'i')
      ->fields('i', array('sid'))
      ->condition('type', 'foo')
      ->execute()
      ->fetchCol();
    $this->assertEqual($count_foo, count($results), 'Foo count was ' . $count_foo . ' for ' . $message);

  }
webchick's avatar
webchick committed
327
}