You are here

public function ServerTaskTest::testRemoveIndex in Search API 8

Tests task system integration for the server's removeIndex() method.

File

tests/src/Kernel/Server/ServerTaskTest.php, line 206

Class

ServerTaskTest
Tests whether the server task system works correctly.

Namespace

Drupal\Tests\search_api\Kernel\Server

Code

public function testRemoveIndex() {

  // Set exception for updateIndex() and removeIndex().
  $this
    ->setError('backend', 'updateIndex');
  $this
    ->setError('backend', 'removeIndex');

  // First try to update the index and fail. Then try to remove it and check
  // that the tasks were set correctly.
  $this->server
    ->updateIndex($this->index);
  $this->server
    ->removeIndex($this->index);
  $this
    ->assertEquals([], $this
    ->getCalledMethods('backend'), 'updateIndex and removeIndex correctly threw exceptions.');
  $tasks = $this
    ->getServerTasks();
  if (count($tasks) == 1) {
    $task_created = $tasks[0]->type === 'removeIndex';
  }
  $this
    ->assertTrue(!empty($task_created), 'The removeIndex task was successfully added and other tasks removed.');
  if ($tasks) {
    $this
      ->assertEquals($this->index
      ->id(), $tasks[0]->index_id, 'The right index ID was used for the removeIndex task.');
  }

  // Check whether other task-system-integrated methods now fail, too.
  try {
    $this->server
      ->indexItems($this->index, []);
    $this
      ->fail('Pending server tasks did not prevent indexing of items.');
  } catch (SearchApiException $e) {
    $label = $this->index
      ->label();
    $expected_message = "Could not index items on index '{$label}' because pending server tasks could not be executed.";
    $this
      ->assertEquals($expected_message, $e
      ->getMessage(), 'Pending server tasks prevented indexing of items.');
  }
  $this
    ->assertEquals([], $this
    ->getCalledMethods('backend'), 'indexItems was not executed.');
  $tasks = $this
    ->getServerTasks();
  $this
    ->assertEquals(1, count($tasks), 'No task added for indexItems.');

  // Let removeIndex() succeed again, then trigger the task execution with a
  // cron run.
  $this
    ->setError('backend', 'removeIndex', FALSE);
  search_api_cron();
  $this
    ->assertEquals([], $this
    ->getServerTasks(), 'Server tasks were correctly executed.');
  $this
    ->assertEquals([
    'removeIndex',
  ], $this
    ->getCalledMethods('backend'), 'Right methods were called during task execution.');
}