You are here

class SearchApiWebTest in Search API 7

Class for testing Search API functionality via the UI.

Hierarchy

Expanded class hierarchy of SearchApiWebTest

File

./search_api.test, line 11
Contains the SearchApiWebTest and the SearchApiUnitTest classes.

View source
class SearchApiWebTest extends DrupalWebTestCase {

  /**
   * The machine name of the created test server.
   *
   * @var string
   */
  protected $server_id;

  /**
   * The machine name of the created test index.
   *
   * @var string
   */
  protected $index_id;

  /**
   * Overrides DrupalWebTestCase::assertText().
   *
   * Changes the default message to be just the text checked for.
   */
  protected function assertText($text, $message = '', $group = 'Other') {
    return parent::assertText($text, $message ? $message : $text, $group);
  }

  /**
   * Overrides DrupalWebTestCase::drupalGet().
   *
   * Additionally asserts that the HTTP request returned a 200 status code.
   */
  protected function drupalGet($path, array $options = array(), array $headers = array()) {
    $ret = parent::drupalGet($path, $options, $headers);
    $this
      ->assertResponse(200, 'HTTP code 200 returned.');
    return $ret;
  }

  /**
   * Overrides DrupalWebTestCase::drupalPost().
   *
   * Additionally asserts that the HTTP request returned a 200 status code.
   */
  protected function drupalPost($path, $edit, $submit, array $options = array(), array $headers = array(), $form_html_id = NULL, $extra_post = NULL) {
    $ret = parent::drupalPost($path, $edit, $submit, $options, $headers, $form_html_id, $extra_post);
    $this
      ->assertResponse(200, 'HTTP code 200 returned.');
    return $ret;
  }

  /**
   * Returns information about this test case.
   *
   * @return array
   *   An array with information about this test case.
   */
  public static function getInfo() {
    return array(
      'name' => 'Test search API framework',
      'description' => 'Tests basic functions of the Search API, like creating, editing and deleting servers and indexes.',
      'group' => 'Search API',
    );
  }

  /**
   * {@inheritdoc}
   */
  public function setUp() {
    parent::setUp('entity', 'search_api', 'search_api_test');
  }

  /**
   * Tests correct admin UI, indexing and search behavior.
   *
   * We only use a single test method to avoid wasting ressources on setting up
   * the test environment multiple times. This will be the only method called
   * by the Simpletest framework (since the method name starts with "test"). It
   * in turn calls other methdos that set up the environment in a certain way
   * and then run tests on it.
   */
  public function testFramework() {
    module_enable(array(
      'search_api_test_2',
    ));
    $this
      ->drupalLogin($this
      ->drupalCreateUser(array(
      'administer search_api',
    )));
    $this
      ->insertItems();
    $this
      ->createIndex();
    $this
      ->insertItems();
    $this
      ->createServer();
    $this
      ->checkOverview();
    $this
      ->enableIndex();
    $this
      ->searchNoResults();
    $this
      ->indexItems();
    $this
      ->searchSuccess();
    $this
      ->checkIndexingOrder();
    $this
      ->editServer();
    $this
      ->clearIndex();
    $this
      ->searchNoResults();
    $this
      ->deleteServer();
    $this
      ->disableModules();
  }

  /**
   * Returns the test server in use by this test case.
   *
   * @return SearchApiServer
   *   The test server.
   */
  protected function server() {
    return search_api_server_load($this->server_id, TRUE);
  }

  /**
   * Returns the test index in use by this test case.
   *
   * @return SearchApiIndex
   *   The test index.
   */
  protected function index() {
    return search_api_index_load($this->index_id, TRUE);
  }

  /**
   * Inserts some test items into the database, via the test module.
   *
   * @param int $number
   *   The number of items to insert.
   *
   * @see insertItem()
   */
  protected function insertItems($number = 5) {
    $count = db_query('SELECT COUNT(*) FROM {search_api_test}')
      ->fetchField();
    for ($i = 1; $i <= $number; ++$i) {
      $id = $count + $i;
      $this
        ->insertItem(array(
        'id' => $id,
        'title' => "Title {$id}",
        'body' => "Body text {$id}.",
        'type' => 'Item',
      ));
    }
    $count = db_query('SELECT COUNT(*) FROM {search_api_test}')
      ->fetchField() - $count;
    $this
      ->assertEqual($count, $number, "{$number} items successfully inserted.");
  }

  /**
   * Helper function for inserting a single test item.
   *
   * @param array $values
   *   The property values of the test item.
   *
   * @see search_api_test_insert_item()
   */
  protected function insertItem(array $values) {
    $this
      ->drupalPost('search_api_test/insert', $values, t('Save'));
  }

  /**
   * Creates a test index via the UI and tests whether this works correctly.
   */
  protected function createIndex() {
    $values = array(
      'name' => '',
      'item_type' => '',
      'enabled' => 1,
      'description' => 'An index used for testing.',
      'server' => '',
      'options[cron_limit]' => 5,
    );
    $this
      ->drupalPost('admin/config/search/search_api/add_index', $values, t('Create index'));
    $this
      ->assertText(t('!name field is required.', array(
      '!name' => t('Index name'),
    )));
    $this
      ->assertText(t('!name field is required.', array(
      '!name' => t('Item type'),
    )));
    $this->index_id = $id = 'test_index';
    $values = array(
      'name' => 'Search API test index',
      'machine_name' => $id,
      'item_type' => 'search_api_test',
      'enabled' => 1,
      'description' => 'An index used for testing.',
      'server' => '',
      'options[cron_limit]' => 1,
    );
    $this
      ->drupalPost(NULL, $values, t('Create index'));
    $this
      ->assertText(t('The index was successfully created. Please set up its indexed fields now.'), 'The index was successfully created.');
    $found = strpos($this
      ->getUrl(), 'admin/config/search/search_api/index/' . $id) !== FALSE;
    $this
      ->assertTrue($found, 'Correct redirect.');
    $index = $this
      ->index();
    $this
      ->assertEqual($index->name, $values['name'], 'Name correctly inserted.');
    $this
      ->assertEqual($index->item_type, $values['item_type'], 'Index item type correctly inserted.');
    $this
      ->assertFalse($index->enabled, 'Status correctly inserted.');
    $this
      ->assertEqual($index->description, $values['description'], 'Description correctly inserted.');
    $this
      ->assertNull($index->server, 'Index server correctly inserted.');
    $this
      ->assertEqual($index->options['cron_limit'], $values['options[cron_limit]'], 'Cron batch size correctly inserted.');
    $values = array(
      'additional[field]' => 'parent',
    );
    $this
      ->drupalPost("admin/config/search/search_api/index/{$id}/fields", $values, t('Add fields'));
    $this
      ->assertText(t('The available fields were successfully changed.'), 'Successfully added fields.');
    $this
      ->assertText('Parent » ID', 'Added fields are displayed.');
    $values = array(
      'fields[id][type]' => 'integer',
      'fields[id][boost]' => '1.0',
      'fields[id][indexed]' => 1,
      'fields[title][type]' => 'text',
      'fields[title][boost]' => '5.0',
      'fields[title][indexed]' => 1,
      'fields[body][type]' => 'text',
      'fields[body][boost]' => '1.0',
      'fields[body][indexed]' => 1,
      'fields[type][type]' => 'string',
      'fields[type][boost]' => '1.0',
      'fields[type][indexed]' => 1,
      'fields[parent:id][type]' => 'integer',
      'fields[parent:id][boost]' => '1.0',
      'fields[parent:id][indexed]' => 1,
      'fields[parent:title][type]' => 'text',
      'fields[parent:title][boost]' => '5.0',
      'fields[parent:title][indexed]' => 1,
      'fields[parent:body][type]' => 'text',
      'fields[parent:body][boost]' => '1.0',
      'fields[parent:body][indexed]' => 1,
      'fields[parent:type][type]' => 'string',
      'fields[parent:type][boost]' => '1.0',
      'fields[parent:type][indexed]' => 1,
    );
    $this
      ->drupalPost(NULL, $values, t('Save changes'));
    $this
      ->assertText(t('The indexed fields were successfully changed. The index was cleared and will have to be re-indexed with the new settings.'), 'Field settings saved.');
    $values = array(
      'callbacks[search_api_alter_add_url][status]' => 1,
      'callbacks[search_api_alter_add_url][weight]' => 0,
      'callbacks[search_api_alter_add_aggregation][status]' => 1,
      'callbacks[search_api_alter_add_aggregation][weight]' => 10,
      'processors[search_api_case_ignore][status]' => 1,
      'processors[search_api_case_ignore][weight]' => 0,
      'processors[search_api_case_ignore][settings][fields][title]' => 1,
      'processors[search_api_case_ignore][settings][fields][body]' => 1,
      'processors[search_api_case_ignore][settings][fields][parent:title]' => 1,
      'processors[search_api_case_ignore][settings][fields][parent:body]' => 1,
      'processors[search_api_tokenizer][status]' => 1,
      'processors[search_api_tokenizer][weight]' => 20,
      'processors[search_api_tokenizer][settings][spaces]' => '[^\\p{L}\\p{N}]',
      'processors[search_api_tokenizer][settings][ignorable]' => '[-]',
      'processors[search_api_tokenizer][settings][fields][title]' => 1,
      'processors[search_api_tokenizer][settings][fields][body]' => 1,
      'processors[search_api_tokenizer][settings][fields][parent:title]' => 1,
      'processors[search_api_tokenizer][settings][fields][parent:body]' => 1,
    );
    $this
      ->drupalPost(NULL, $values, t('Add new field'));
    $values = array(
      'callbacks[search_api_alter_add_aggregation][settings][fields][search_api_aggregation_1][name]' => 'Test fulltext field',
      'callbacks[search_api_alter_add_aggregation][settings][fields][search_api_aggregation_1][type]' => 'fulltext',
      'callbacks[search_api_alter_add_aggregation][settings][fields][search_api_aggregation_1][fields][title]' => 1,
      'callbacks[search_api_alter_add_aggregation][settings][fields][search_api_aggregation_1][fields][body]' => 1,
      'callbacks[search_api_alter_add_aggregation][settings][fields][search_api_aggregation_1][fields][parent:title]' => 1,
      'callbacks[search_api_alter_add_aggregation][settings][fields][search_api_aggregation_1][fields][parent:body]' => 1,
    );
    $this
      ->drupalPost(NULL, $values, t('Save configuration'));
    $this
      ->assertText(t("The indexing workflow was successfully edited. All content was scheduled for re-indexing so the new settings can take effect."), 'Workflow successfully edited.');
    $this
      ->drupalGet("admin/config/search/search_api/index/{$id}");
    $this
      ->assertTitle('Search API test index | Drupal', 'Correct title when viewing index.');
    $this
      ->assertText('An index used for testing.', 'Description displayed.');
    $this
      ->assertText('Search API test entity', 'Item type displayed.');
    $this
      ->assertText(t('disabled'), '"Disabled" status displayed.');
  }

  /**
   * Creates a test server via the UI and tests whether this works correctly.
   */
  protected function createServer() {
    $values = array(
      'name' => '',
      'enabled' => 1,
      'description' => 'A server used for testing.',
      'class' => '',
    );
    $this
      ->drupalPost('admin/config/search/search_api/add_server', $values, t('Create server'));
    $this
      ->assertText(t('!name field is required.', array(
      '!name' => t('Server name'),
    )));
    $this
      ->assertText(t('!name field is required.', array(
      '!name' => t('Service class'),
    )));
    $this->server_id = $id = 'test_server';
    $values = array(
      'name' => 'Search API test server',
      'machine_name' => $id,
      'enabled' => 1,
      'description' => 'A server used for testing.',
      'class' => 'search_api_test_service',
    );
    $this
      ->drupalPost(NULL, $values, t('Create server'));
    $values2 = array(
      'options[form][test]' => 'search_api_test foo bar',
    );
    $this
      ->drupalPost(NULL, $values2, t('Create server'));
    $this
      ->assertText(t('The server was successfully created.'));
    $found = strpos($this
      ->getUrl(), 'admin/config/search/search_api/server/' . $id) !== FALSE;
    $this
      ->assertTrue($found, 'Correct redirect.');
    $server = $this
      ->server();
    $this
      ->assertEqual($server->name, $values['name'], 'Name correctly inserted.');
    $this
      ->assertTrue($server->enabled, 'Status correctly inserted.');
    $this
      ->assertEqual($server->description, $values['description'], 'Description correctly inserted.');
    $this
      ->assertEqual($server->class, $values['class'], 'Service class correctly inserted.');
    $this
      ->assertEqual($server->options['test'], $values2['options[form][test]'], 'Service options correctly inserted.');
    $this
      ->assertTitle('Search API test server | Drupal', 'Correct title when viewing server.');
    $this
      ->assertText('A server used for testing.', 'Description displayed.');
    $this
      ->assertText('search_api_test_service', 'Service name displayed.');
    $this
      ->assertText('search_api_test foo bar', 'Service options displayed.');
  }

  /**
   * Checks whether the server and index are correctly listed in the overview.
   */
  protected function checkOverview() {
    $this
      ->drupalGet('admin/config/search/search_api');
    $this
      ->assertText('Search API test server', 'Server displayed.');
    $this
      ->assertText('Search API test index', 'Index displayed.');
    $this
      ->assertNoText(t('There are no search servers or indexes defined yet.'), '"No servers" message not displayed.');
  }

  /**
   * Moves the index onto the server and enables it.
   */
  protected function enableIndex() {
    $values = array(
      'server' => $this->server_id,
    );
    $this
      ->drupalPost("admin/config/search/search_api/index/{$this->index_id}/edit", $values, t('Save settings'));
    $this
      ->assertText(t('The search index was successfully edited.'));
    $this
      ->assertText('Search API test server', 'Server displayed.');
    $this
      ->clickLink(t('enable'));
    $this
      ->assertText(t('The index was successfully enabled.'));
  }

  /**
   * Asserts that a search on the index works but yields no results.
   *
   * This is the case since no items should have been indexed yet.
   */
  protected function searchNoResults() {
    $results = $this
      ->doSearch();
    $this
      ->assertEqual($results['result count'], 0, 'No search results returned without indexing.');
    $this
      ->assertEqual(array_keys($results['results']), array(), 'No search results returned without indexing.');
  }

  /**
   * Executes a search on the test index.
   *
   * Helper method used for testing search results.
   *
   * @param int|null $offset
   *   (optional) The offset for the returned results.
   * @param int|null $limit
   *   (optional) The limit for the returned results.
   *
   * @return array
   *   Search results as specified by SearchApiQueryInterface::execute().
   */
  protected function doSearch($offset = NULL, $limit = NULL) {

    // Since we change server and index settings via the UI (and, therefore, in
    // different page requests), the static cache in this page request
    // (executing the tests) will get stale. Therefore, we clear it before
    // executing the search.
    $this
      ->index();
    $this
      ->server();
    $query = search_api_query($this->index_id);
    if ($offset || $limit) {
      $query
        ->range($offset, $limit);
    }
    return $query
      ->execute();
  }

  /**
   * Tests indexing via the UI "Index now" functionality.
   *
   * Asserts that errors during indexing are handled properly and that the
   * status readings work.
   */
  protected function indexItems() {
    $this
      ->checkIndexStatus();

    // Here we test the indexing + the warning message when some items
    // cannot be indexed.
    // The server refuses (for test purpose) to index the item that has the same
    // ID as the "search_api_test_indexing_break" variable (default: 8).
    // Therefore, if we try to index 8 items, only the first seven will be
    // successfully indexed and a warning should be displayed.
    $values = array(
      'limit' => 8,
    );
    $this
      ->drupalPost(NULL, $values, t('Index now'));
    $this
      ->assertText(t('Successfully indexed @count items.', array(
      '@count' => 7,
    )));
    $this
      ->assertText(t('1 item could not be indexed. Check the logs for details.'), 'Index errors warning is displayed.');
    $this
      ->assertNoText(t("Couldn't index items. Check the logs for details."), "Index error isn't displayed.");
    $this
      ->checkIndexStatus(7);

    // Here we're testing the error message when no item could be indexed.
    // The item with ID 8 is still not indexed, but it will be the first to be
    // indexed now. Therefore, if we try to index a single items, only item 8
    // will be passed to the server, which will reject it and no items will be
    // indexed. Since normally this signifies a more serious error than when
    // only some items couldn't be indexed, this is handled differently.
    $values = array(
      'limit' => 1,
    );
    $this
      ->drupalPost(NULL, $values, t('Index now'));
    $this
      ->assertNoPattern('/' . str_replace('144', '-?\\d*', t('Successfully indexed @count items.', array(
      '@count' => 144,
    ))) . '/', 'No items could be indexed.');
    $this
      ->assertNoText(t('1 item could not be indexed. Check the logs for details.'), "Index errors warning isn't displayed.");
    $this
      ->assertText(t("Couldn't index items. Check the logs for details."), 'Index error is displayed.');

    // No we set the "search_api_test_indexing_break" variable to 0, so all
    // items will be indexed. The remaining items (8, 9, 10) should therefore
    // be successfully indexed and no warning should show.
    variable_set('search_api_test_indexing_break', 0);
    $values = array(
      'limit' => -1,
    );
    $this
      ->drupalPost(NULL, $values, t('Index now'));
    $this
      ->assertText(t('Successfully indexed @count items.', array(
      '@count' => 3,
    )));
    $this
      ->assertNoText(t("Some items couldn't be indexed. Check the logs for details."), "Index errors warning isn't displayed.");
    $this
      ->assertNoText(t("Couldn't index items. Check the logs for details."), "Index error isn't displayed.");
    $this
      ->checkIndexStatus(10);

    // Reset the static cache for the server.
    $this
      ->server();
  }

  /**
   * Checks whether the index's "Status" tab shows the correct values.
   *
   * Helper method used by indexItems() and others.
   *
   * The internal browser will point to the index's "Status" tab after this
   * method is called.
   *
   * @param int $indexed
   *   (optional) The number of items that should be indexed at the moment.
   *   Defaults to 0.
   * @param int $total
   *   (optional) The (correct) total number of items. Defaults to 10.
   * @param bool $check_buttons
   *   (optional) Whether to check for the correct presence/absence of buttons.
   *   Defaults to TRUE.
   * @param int|null $on_server
   *   (optional) The number of items actually on the server. Defaults to
   *   $indexed.
   */
  protected function checkIndexStatus($indexed = 0, $total = 10, $check_buttons = TRUE, $on_server = NULL) {
    $url = "admin/config/search/search_api/index/{$this->index_id}";
    if (strpos($this->url, $url) === FALSE) {
      $this
        ->drupalGet($url);
    }
    $index_status = t('@indexed/@total indexed', array(
      '@indexed' => $indexed,
      '@total' => $total,
    ));
    $this
      ->assertText($index_status, 'Correct index status displayed.');
    if (!isset($on_server)) {
      $on_server = $indexed;
    }
    $info = format_plural($on_server, 'There is 1 item indexed on the server for this index.', 'There are @count items indexed on the server for this index.');
    $this
      ->assertText(t('Server index status'), 'Server index status displayed.');
    $this
      ->assertText($info, 'Correct server index status displayed.');
    if (!$check_buttons) {
      return;
    }
    $this
      ->assertText(t('enabled'), '"Enabled" status displayed.');
    if ($indexed == $total) {
      $this
        ->assertRaw('disabled="disabled"', '"Index now" form disabled.');
    }
    else {
      $this
        ->assertNoRaw('disabled="disabled"', '"Index now" form enabled.');
    }
  }

  /**
   * Tests whether searches yield the right results after indexing.
   *
   * The test server only implements range functionality, no kind of fulltext
   * search capabilities, so we can only test for that.
   */
  protected function searchSuccess() {
    $results = $this
      ->doSearch();
    $this
      ->assertEqual($results['result count'], 10, 'Correct search result count returned after indexing.');
    $this
      ->assertEqual(array_keys($results['results']), array(
      1,
      2,
      3,
      4,
      5,
      6,
      7,
      8,
      9,
      10,
    ), 'Correct search results returned after indexing.');
    $results = $this
      ->doSearch(2, 4);
    $this
      ->assertEqual($results['result count'], 10, 'Correct search result count with ranged query.');
    $this
      ->assertEqual(array_keys($results['results']), array(
      3,
      4,
      5,
      6,
    ), 'Correct search results with ranged query.');
  }

  /**
   * Tests whether items are indexed in the right order.
   *
   * The indexing order should always be that new items are indexed before
   * changed ones, and only then the changed items in the order of their change.
   *
   * This method also assures that this behavior is even observed when indexing
   * temporarily fails.
   *
   * @see https://drupal.org/node/2115127
   */
  protected function checkIndexingOrder() {

    // Set cron batch size to 1 so not all items will get indexed right away.
    // This also ensures that later, when indexing of a single item will be
    // rejected by using the "search_api_test_indexing_break" variable, this
    // will have the effect of rejecting "all" items of a batch (since that
    // batch only consists of a single item).
    $values = array(
      'options[cron_limit]' => 1,
    );
    $this
      ->drupalPost("admin/config/search/search_api/index/{$this->index_id}/edit", $values, t('Save settings'));
    $this
      ->assertText(t('The search index was successfully edited.'));

    // Manually clear the server's item storage – that way, the items will still
    // count as  indexed for the Search API, but won't be returned in searches.
    // We do this so we have finer-grained control over the order in which items
    // are indexed.
    $this
      ->server()
      ->deleteItems();
    $results = $this
      ->doSearch();
    $this
      ->assertEqual($results['result count'], 0, 'Indexed items were successfully deleted from the server.');
    $this
      ->assertEqual(array_keys($results['results']), array(), 'Indexed items were successfully deleted from the server.');

    // Now insert some new items, and mark others as changed. Make sure that
    // each action has a unique timestamp, so the order will be correct.
    $this
      ->drupalGet('search_api_test/touch/8');
    $this
      ->insertItems(1);

    // item 11
    sleep(1);
    $this
      ->drupalGet('search_api_test/touch/2');
    $this
      ->insertItems(1);

    // item 12
    sleep(1);
    $this
      ->drupalGet('search_api_test/touch/5');
    $this
      ->insertItems(1);

    // item 13
    sleep(1);
    $this
      ->drupalGet('search_api_test/touch/8');
    $this
      ->insertItems(1);

    // item 14
    // Check whether the status display is right.
    $this
      ->checkIndexStatus(7, 14, FALSE, 0);

    // Indexing order should now be: 11, 12, 13, 14, 8, 2, 4. Let's try it out!
    // First manually index one item, and see if it's 11.
    $values = array(
      'limit' => 1,
    );
    $this
      ->drupalPost(NULL, $values, t('Index now'));
    $this
      ->assertText(t('Successfully indexed @count item.', array(
      '@count' => 1,
    )));
    $this
      ->assertNoText(t("Some items couldn't be indexed. Check the logs for details."), "Index errors warning isn't displayed.");
    $this
      ->assertNoText(t("Couldn't index items. Check the logs for details."), "Index error isn't displayed.");
    $this
      ->checkIndexStatus(8, 14, FALSE, 1);
    $results = $this
      ->doSearch();
    $this
      ->assertEqual($results['result count'], 1, 'Indexing order test 1: correct result count.');
    $this
      ->assertEqual(array_keys($results['results']), array(
      11,
    ), 'Indexing order test 1: correct results.');

    // Now index with a cron run, but stop at item 8.
    variable_set('search_api_test_indexing_break', 8);
    $this
      ->cronRun();

    // Now just the four new items should have been indexed.
    $results = $this
      ->doSearch();
    $this
      ->assertEqual($results['result count'], 4, 'Indexing order test 2: correct result count.');
    $this
      ->assertEqual(array_keys($results['results']), array(
      11,
      12,
      13,
      14,
    ), 'Indexing order test 2: correct results.');

    // This time stop at item 5 (should be the last one).
    variable_set('search_api_test_indexing_break', 5);
    $this
      ->cronRun();

    // Now all new and changed items should have been indexed, except item 5.
    $results = $this
      ->doSearch();
    $this
      ->assertEqual($results['result count'], 6, 'Indexing order test 3: correct result count.');
    $this
      ->assertEqual(array_keys($results['results']), array(
      2,
      8,
      11,
      12,
      13,
      14,
    ), 'Indexing order test 3: correct results.');

    // Index the remaining item.
    variable_set('search_api_test_indexing_break', 0);
    $this
      ->cronRun();

    // Now all new and changed items should have been indexed.
    $results = $this
      ->doSearch();
    $this
      ->assertEqual($results['result count'], 7, 'Indexing order test 4: correct result count.');
    $this
      ->assertEqual(array_keys($results['results']), array(
      2,
      5,
      8,
      11,
      12,
      13,
      14,
    ), 'Indexing order test 4: correct results.');
  }

  /**
   * Tests whether the server tasks system works correctly.
   *
   * Uses the "search_api_test_error_state" variable to trigger exceptions in
   * the test service class and asserts that the Search API reacts correctly and
   * re-attempts the operation on the next cron run.
   */
  protected function checkServerTasks() {

    // Make sure none of the previous operations added any tasks.
    $task_count = db_query('SELECT COUNT(id) FROM {search_api_task}')
      ->fetchField();
    $this
      ->assertEqual($task_count, 0, 'No server tasks were previously saved.');

    // Set error state for test service, so all operations will fail.
    variable_set('search_api_test_error_state', TRUE);

    // Delete some items.
    $this
      ->drupalGet('search_api_test/delete/8');
    $this
      ->drupalGet('search_api_test/delete/12');

    // Assert that the indexed items haven't changed yet.
    $results = $this
      ->doSearch();
    $this
      ->assertEqual(array_keys($results['results']), array(
      2,
      5,
      8,
      11,
      12,
      13,
      14,
    ), 'During error state, no indexed items were deleted.');

    // Check that tasks were correctly inserted.
    $task_count = db_query('SELECT COUNT(id) FROM {search_api_task}')
      ->fetchField();
    $this
      ->assertEqual($task_count, 2, 'Server tasks for deleted items were saved.');

    // Now reset the error state variable and run cron to delete the items.
    variable_set('search_api_test_error_state', FALSE);
    $this
      ->cronRun();

    // Assert that the indexed items were indeed deleted from the server.
    $results = $this
      ->doSearch();
    $this
      ->assertEqual(array_keys($results['results']), array(
      2,
      5,
      11,
      13,
      14,
    ), 'Pending "delete item" server tasks were correctly executed during the cron run.');

    // Check that the tasks were correctly deleted.
    $task_count = db_query('SELECT COUNT(id) FROM {search_api_task}')
      ->fetchField();
    $this
      ->assertEqual($task_count, 0, 'Server tasks were correctly deleted after being executed.');

    // Now we first delete more items, then disable the server (thereby removing
    // the index from it) – all while in error state.
    variable_set('search_api_test_error_state', TRUE);
    $this
      ->drupalGet('search_api_test/delete/14');
    $this
      ->drupalGet('search_api_test/delete/2');
    $settings['enabled'] = 0;
    $this
      ->drupalPost("admin/config/search/search_api/server/{$this->server_id}/edit", $settings, t('Save settings'));

    // Check whether the index was correctly removed from the server.
    $this
      ->assertEqual($this
      ->index()
      ->server(), NULL, 'The index was successfully set to have no server.');
    $exception = FALSE;
    try {
      $this
        ->doSearch();
    } catch (SearchApiException $e) {
      $exception = TRUE;
    }
    $this
      ->assertTrue($exception, 'Searching on the index failed with an exception.');

    // Check that only one task – to remove the index from the server – is now
    // present in the tasks table.
    $task_count = db_query('SELECT COUNT(id) FROM {search_api_task}')
      ->fetchField();
    $this
      ->assertEqual($task_count, 1, 'Only the "remove index" task is present in the server tasks.');

    // Reset the error state variable, re-enable the server.
    variable_set('search_api_test_error_state', FALSE);
    $settings['enabled'] = 1;
    $this
      ->drupalPost("admin/config/search/search_api/server/{$this->server_id}/edit", $settings, t('Save settings'));

    // Check whether the index was really removed from the server now.
    $server = $this
      ->server();
    $this
      ->assertTrue(empty($server->options['indexes'][$this->index_id]), 'The index was removed from the server after cron ran.');
    $task_count = db_query('SELECT COUNT(id) FROM {search_api_task}')
      ->fetchField();
    $this
      ->assertEqual($task_count, 0, 'Server tasks were correctly deleted after being executed.');

    // Put the index back on the server and index some items for the next tests.
    $settings = array(
      'server' => $this->server_id,
    );
    $this
      ->drupalPost("admin/config/search/search_api/index/{$this->index_id}/edit", $settings, t('Save settings'));
    $this
      ->cronRun();
  }

  /**
   * Tests whether editing the server works correctly.
   */
  protected function editServer() {
    $values = array(
      'name' => 'test-name-foo',
      'description' => 'test-description-bar',
      'options[form][test]' => 'test-test-baz',
    );
    $this
      ->drupalPost("admin/config/search/search_api/server/{$this->server_id}/edit", $values, t('Save settings'));
    $this
      ->assertText(t('The search server was successfully edited.'));
    $this
      ->assertText('test-name-foo', 'Name changed.');
    $this
      ->assertText('test-description-bar', 'Description changed.');
    $this
      ->assertText('test-test-baz', 'Service options changed.');
  }

  /**
   * Tests whether clearing the index works correctly.
   */
  protected function clearIndex() {
    $this
      ->drupalPost("admin/config/search/search_api/index/{$this->index_id}", array(), t('Clear all indexed data'));
    $this
      ->drupalPost(NULL, array(), t('Confirm'));
    $this
      ->assertText(t('The index was successfully cleared.'));
    $this
      ->assertText(t('@indexed/@total indexed', array(
      '@indexed' => 0,
      '@total' => 14,
    )), 'Correct index status displayed.');
  }

  /**
   * Tests whether deleting the server works correctly.
   *
   * The index still lying on the server should be disabled and removed from it.
   * Also, any tasks with that server's ID should be deleted.
   */
  protected function deleteServer() {

    // Insert some dummy tasks to check for.
    $server = $this
      ->server();
    search_api_server_tasks_add($server, 'foo');
    search_api_server_tasks_add($server, 'bar', $this
      ->index());
    $task_count = db_query('SELECT COUNT(id) FROM {search_api_task}')
      ->fetchField();
    $this
      ->assertEqual($task_count, 2, 'Dummy tasks were added.');

    // Delete the server.
    $this
      ->drupalPost("admin/config/search/search_api/server/{$this->server_id}/delete", array(), t('Confirm'));
    $this
      ->assertNoText('test-name-foo', 'Server no longer listed.');
    $this
      ->drupalGet("admin/config/search/search_api/index/{$this->index_id}");
    $this
      ->assertNoText(t('Server'), 'The index was removed from the server.');
    $this
      ->assertText(t('disabled'), 'The index was disabled.');

    // Check whether the tasks were correctly deleted.
    $task_count = db_query('SELECT COUNT(id) FROM {search_api_task}')
      ->fetchField();
    $this
      ->assertEqual($task_count, 0, 'Remaining server tasks were correctly deleted.');
  }

  /**
   * Tests whether disabling and uninstalling the modules works correctly.
   *
   * This will disable and uninstall both the test module and the Search API. It
   * asserts that this works correctly (since the server has been deleted in
   * deleteServer()) and that all associated tables and variables are removed.
   */
  protected function disableModules() {
    module_disable(array(
      'search_api_test_2',
    ), FALSE);
    $this
      ->assertFalse(module_exists('search_api_test_2'), 'Second test module was successfully disabled.');
    module_disable(array(
      'search_api_test',
    ), FALSE);
    $this
      ->assertFalse(module_exists('search_api_test'), 'First test module was successfully disabled.');
    module_disable(array(
      'search_api',
    ), FALSE);
    $this
      ->assertFalse(module_exists('search_api'), 'Search API module was successfully disabled.');
    drupal_uninstall_modules(array(
      'search_api_test_2',
    ), FALSE);
    $this
      ->assertEqual(drupal_get_installed_schema_version('search_api_test_2', TRUE), SCHEMA_UNINSTALLED, 'Second test module was successfully uninstalled.');
    drupal_uninstall_modules(array(
      'search_api_test',
    ), FALSE);
    $this
      ->assertEqual(drupal_get_installed_schema_version('search_api_test', TRUE), SCHEMA_UNINSTALLED, 'First test module was successfully uninstalled.');
    $this
      ->assertFalse(db_table_exists('search_api_test'), 'Test module table was successfully removed.');
    drupal_uninstall_modules(array(
      'search_api',
    ), FALSE);
    $this
      ->assertEqual(drupal_get_installed_schema_version('search_api', TRUE), SCHEMA_UNINSTALLED, 'Search API module was successfully uninstalled.');
    $this
      ->assertFalse(db_table_exists('search_api_server'), 'Search server table was successfully removed.');
    $this
      ->assertFalse(db_table_exists('search_api_index'), 'Search index table was successfully removed.');
    $this
      ->assertFalse(db_table_exists('search_api_item'), 'Index items table was successfully removed.');
    $this
      ->assertFalse(db_table_exists('search_api_task'), 'Server tasks table was successfully removed.');
    $this
      ->assertNull(variable_get('search_api_index_worker_callback_runtime'), 'Worker runtime variable was correctly removed.');
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DrupalTestCase::$assertions protected property Assertions thrown in that test case.
DrupalTestCase::$databasePrefix protected property The database prefix of this test run.
DrupalTestCase::$originalFileDirectory protected property The original file directory, before it was changed for testing purposes.
DrupalTestCase::$results public property Current results of this test case.
DrupalTestCase::$setup protected property Flag to indicate whether the test has been set up.
DrupalTestCase::$setupDatabasePrefix protected property
DrupalTestCase::$setupEnvironment protected property
DrupalTestCase::$skipClasses protected property This class is skipped when looking for the source of an assertion.
DrupalTestCase::$testId protected property The test run ID.
DrupalTestCase::$timeLimit protected property Time limit for the test.
DrupalTestCase::$useSetupInstallationCache public property Whether to cache the installation part of the setUp() method.
DrupalTestCase::$useSetupModulesCache public property Whether to cache the modules installation part of the setUp() method.
DrupalTestCase::$verboseDirectoryUrl protected property URL to the verbose output file directory.
DrupalTestCase::assert protected function Internal helper: stores the assert.
DrupalTestCase::assertEqual protected function Check to see if two values are equal.
DrupalTestCase::assertFalse protected function Check to see if a value is false (an empty string, 0, NULL, or FALSE).
DrupalTestCase::assertIdentical protected function Check to see if two values are identical.
DrupalTestCase::assertNotEqual protected function Check to see if two values are not equal.
DrupalTestCase::assertNotIdentical protected function Check to see if two values are not identical.
DrupalTestCase::assertNotNull protected function Check to see if a value is not NULL.
DrupalTestCase::assertNull protected function Check to see if a value is NULL.
DrupalTestCase::assertTrue protected function Check to see if a value is not false (not an empty string, 0, NULL, or FALSE).
DrupalTestCase::deleteAssert public static function Delete an assertion record by message ID.
DrupalTestCase::error protected function Fire an error assertion. 1
DrupalTestCase::errorHandler public function Handle errors during test runs. 1
DrupalTestCase::exceptionHandler protected function Handle exceptions.
DrupalTestCase::fail protected function Fire an assertion that is always negative.
DrupalTestCase::generatePermutations public static function Converts a list of possible parameters into a stack of permutations.
DrupalTestCase::getAssertionCall protected function Cycles through backtrace until the first non-assertion method is found.
DrupalTestCase::getDatabaseConnection public static function Returns the database connection to the site running Simpletest.
DrupalTestCase::insertAssert public static function Store an assertion from outside the testing context.
DrupalTestCase::pass protected function Fire an assertion that is always positive.
DrupalTestCase::randomName public static function Generates a random string containing letters and numbers.
DrupalTestCase::randomString public static function Generates a random string of ASCII characters of codes 32 to 126.
DrupalTestCase::run public function Run all tests in this class.
DrupalTestCase::verbose protected function Logs a verbose message in a text file.
DrupalWebTestCase::$additionalCurlOptions protected property Additional cURL options.
DrupalWebTestCase::$content protected property The content of the page currently loaded in the internal browser.
DrupalWebTestCase::$cookieFile protected property The current cookie file used by cURL.
DrupalWebTestCase::$cookies protected property The cookies of the page currently loaded in the internal browser.
DrupalWebTestCase::$curlHandle protected property The handle of the current cURL connection.
DrupalWebTestCase::$drupalSettings protected property The value of the Drupal.settings JavaScript variable for the page currently loaded in the internal browser.
DrupalWebTestCase::$elements protected property The parsed version of the page.
DrupalWebTestCase::$generatedTestFiles protected property Whether the files were copied to the test files directory.
DrupalWebTestCase::$headers protected property The headers of the page currently loaded in the internal browser.
DrupalWebTestCase::$httpauth_credentials protected property HTTP authentication credentials (<username>:<password>).
DrupalWebTestCase::$httpauth_method protected property HTTP authentication method
DrupalWebTestCase::$loggedInUser protected property The current user logged in using the internal browser.
DrupalWebTestCase::$originalShutdownCallbacks protected property The original shutdown handlers array, before it was cleaned for testing purposes.
DrupalWebTestCase::$originalUser protected property The original user, before it was changed to a clean uid = 1 for testing purposes.
DrupalWebTestCase::$plainTextContent protected property The content of the page currently loaded in the internal browser (plain text version).
DrupalWebTestCase::$profile protected property The profile to install as a basis for testing. 20
DrupalWebTestCase::$redirect_count protected property The number of redirects followed during the handling of a request.
DrupalWebTestCase::$session_id protected property The current session ID, if available.
DrupalWebTestCase::$session_name protected property The current session name, if available.
DrupalWebTestCase::$url protected property The URL currently loaded in the internal browser.
DrupalWebTestCase::assertField protected function Asserts that a field exists with the given name or ID.
DrupalWebTestCase::assertFieldById protected function Asserts that a field exists in the current page with the given ID and value.
DrupalWebTestCase::assertFieldByName protected function Asserts that a field exists in the current page with the given name and value.
DrupalWebTestCase::assertFieldByXPath protected function Asserts that a field exists in the current page by the given XPath.
DrupalWebTestCase::assertFieldChecked protected function Asserts that a checkbox field in the current page is checked.
DrupalWebTestCase::assertLink protected function Pass if a link with the specified label is found, and optional with the specified index.
DrupalWebTestCase::assertLinkByHref protected function Pass if a link containing a given href (part) is found.
DrupalWebTestCase::assertMail protected function Asserts that the most recently sent e-mail message has the given value.
DrupalWebTestCase::assertMailPattern protected function Asserts that the most recently sent e-mail message has the pattern in it.
DrupalWebTestCase::assertMailString protected function Asserts that the most recently sent e-mail message has the string in it.
DrupalWebTestCase::assertNoDuplicateIds protected function Asserts that each HTML ID is used for just a single element.
DrupalWebTestCase::assertNoField protected function Asserts that a field does not exist with the given name or ID.
DrupalWebTestCase::assertNoFieldById protected function Asserts that a field does not exist with the given ID and value.
DrupalWebTestCase::assertNoFieldByName protected function Asserts that a field does not exist with the given name and value.
DrupalWebTestCase::assertNoFieldByXPath protected function Asserts that a field doesn't exist or its value doesn't match, by XPath.
DrupalWebTestCase::assertNoFieldChecked protected function Asserts that a checkbox field in the current page is not checked.
DrupalWebTestCase::assertNoLink protected function Pass if a link with the specified label is not found.
DrupalWebTestCase::assertNoLinkByHref protected function Pass if a link containing a given href (part) is not found.
DrupalWebTestCase::assertNoOptionSelected protected function Asserts that a select option in the current page is not checked.
DrupalWebTestCase::assertNoPattern protected function Will trigger a pass if the perl regex pattern is not present in raw content.
DrupalWebTestCase::assertNoRaw protected function Pass if the raw text is NOT found on the loaded page, fail otherwise. Raw text refers to the raw HTML that the page generated.
DrupalWebTestCase::assertNoResponse protected function Asserts the page did not return the specified response code.
DrupalWebTestCase::assertNoText protected function Pass if the text is NOT found on the text version of the page. The text version is the equivalent of what a user would see when viewing through a web browser. In other words the HTML has been filtered out of the contents.
DrupalWebTestCase::assertNoTitle protected function Pass if the page title is not the given string.
DrupalWebTestCase::assertNoUniqueText protected function Pass if the text is found MORE THAN ONCE on the text version of the page.
DrupalWebTestCase::assertOptionSelected protected function Asserts that a select option in the current page is checked.
DrupalWebTestCase::assertPattern protected function Will trigger a pass if the Perl regex pattern is found in the raw content.
DrupalWebTestCase::assertRaw protected function Pass if the raw text IS found on the loaded page, fail otherwise. Raw text refers to the raw HTML that the page generated.
DrupalWebTestCase::assertResponse protected function Asserts the page responds with the specified response code.
DrupalWebTestCase::assertTextHelper protected function Helper for assertText and assertNoText.
DrupalWebTestCase::assertThemeOutput protected function Asserts themed output.
DrupalWebTestCase::assertTitle protected function Pass if the page title is the given string.
DrupalWebTestCase::assertUniqueText protected function Pass if the text is found ONLY ONCE on the text version of the page.
DrupalWebTestCase::assertUniqueTextHelper protected function Helper for assertUniqueText and assertNoUniqueText.
DrupalWebTestCase::assertUrl protected function Pass if the internal browser's URL matches the given path.
DrupalWebTestCase::buildXPathQuery protected function Builds an XPath query.
DrupalWebTestCase::changeDatabasePrefix protected function Changes the database connection to the prefixed one.
DrupalWebTestCase::checkForMetaRefresh protected function Check for meta refresh tag and if found call drupalGet() recursively. This function looks for the http-equiv attribute to be set to "Refresh" and is case-sensitive.
DrupalWebTestCase::checkPermissions protected function Check to make sure that the array of permissions are valid.
DrupalWebTestCase::clickLink protected function Follows a link by name.
DrupalWebTestCase::constructFieldXpath protected function Helper function: construct an XPath for the given set of attributes and value.
DrupalWebTestCase::copySetupCache protected function Copy the setup cache from/to another table and files directory.
DrupalWebTestCase::cronRun protected function Runs cron in the Drupal installed by Simpletest.
DrupalWebTestCase::curlClose protected function Close the cURL handler and unset the handler.
DrupalWebTestCase::curlExec protected function Initializes and executes a cURL request.
DrupalWebTestCase::curlHeaderCallback protected function Reads headers and registers errors received from the tested site.
DrupalWebTestCase::curlInitialize protected function Initializes the cURL connection.
DrupalWebTestCase::drupalCompareFiles protected function Compare two files based on size and file name.
DrupalWebTestCase::drupalCreateContentType protected function Creates a custom content type based on default settings.
DrupalWebTestCase::drupalCreateNode protected function Creates a node based on default settings.
DrupalWebTestCase::drupalCreateRole protected function Creates a role with specified permissions.
DrupalWebTestCase::drupalCreateUser protected function Create a user with a given set of permissions.
DrupalWebTestCase::drupalGetAJAX protected function Retrieve a Drupal path or an absolute path and JSON decode the result.
DrupalWebTestCase::drupalGetContent protected function Gets the current raw HTML of requested page.
DrupalWebTestCase::drupalGetHeader protected function Gets the value of an HTTP response header. If multiple requests were required to retrieve the page, only the headers from the last request will be checked by default. However, if TRUE is passed as the second argument, all requests will be processed…
DrupalWebTestCase::drupalGetHeaders protected function Gets the HTTP response headers of the requested page. Normally we are only interested in the headers returned by the last request. However, if a page is redirected or HTTP authentication is in use, multiple requests will be required to retrieve the…
DrupalWebTestCase::drupalGetMails protected function Gets an array containing all e-mails sent during this test case.
DrupalWebTestCase::drupalGetNodeByTitle function Get a node from the database based on its title.
DrupalWebTestCase::drupalGetSettings protected function Gets the value of the Drupal.settings JavaScript variable for the currently loaded page.
DrupalWebTestCase::drupalGetTestFiles protected function Get a list files that can be used in tests.
DrupalWebTestCase::drupalGetToken protected function Generate a token for the currently logged in user.
DrupalWebTestCase::drupalHead protected function Retrieves only the headers for a Drupal path or an absolute path.
DrupalWebTestCase::drupalLogin protected function Log in a user with the internal browser.
DrupalWebTestCase::drupalLogout protected function
DrupalWebTestCase::drupalPostAJAX protected function Execute an Ajax submission.
DrupalWebTestCase::drupalSetContent protected function Sets the raw HTML content. This can be useful when a page has been fetched outside of the internal browser and assertions need to be made on the returned page.
DrupalWebTestCase::drupalSetSettings protected function Sets the value of the Drupal.settings JavaScript variable for the currently loaded page.
DrupalWebTestCase::getAbsoluteUrl protected function Takes a path and returns an absolute path.
DrupalWebTestCase::getAllOptions protected function Get all option elements, including nested options, in a select.
DrupalWebTestCase::getSelectedItem protected function Get the selected value from a select field.
DrupalWebTestCase::getSetupCacheKey protected function Returns the cache key used for the setup caching.
DrupalWebTestCase::getUrl protected function Get the current URL from the cURL handler.
DrupalWebTestCase::handleForm protected function Handle form input related to drupalPost(). Ensure that the specified fields exist and attempt to create POST data in the correct manner for the particular field type.
DrupalWebTestCase::loadSetupCache protected function Copies the cached tables and files for a cached installation setup.
DrupalWebTestCase::parse protected function Parse content returned from curlExec using DOM and SimpleXML.
DrupalWebTestCase::preloadRegistry protected function Preload the registry from the testing site.
DrupalWebTestCase::prepareDatabasePrefix protected function Generates a database prefix for running tests.
DrupalWebTestCase::prepareEnvironment protected function Prepares the current environment for running the test.
DrupalWebTestCase::recursiveDirectoryCopy protected function Recursively copy one directory to another.
DrupalWebTestCase::refreshVariables protected function Refresh the in-memory set of variables. Useful after a page request is made that changes a variable in a different thread. 1
DrupalWebTestCase::resetAll protected function Reset all data structures after having enabled new modules.
DrupalWebTestCase::storeSetupCache protected function Store the installation setup to a cache.
DrupalWebTestCase::tearDown protected function Delete created files and temporary files directory, delete the tables created by setUp(), and reset the database prefix. 6
DrupalWebTestCase::verboseEmail protected function Outputs to verbose the most recent $count emails sent.
DrupalWebTestCase::xpath protected function Perform an xpath search on the contents of the internal browser. The search is relative to the root element (HTML tag normally) of the page.
DrupalWebTestCase::__construct function Constructor for DrupalWebTestCase. Overrides DrupalTestCase::__construct 1
SearchApiWebTest::$index_id protected property The machine name of the created test index.
SearchApiWebTest::$server_id protected property The machine name of the created test server.
SearchApiWebTest::assertText protected function Overrides DrupalWebTestCase::assertText(). Overrides DrupalWebTestCase::assertText
SearchApiWebTest::checkIndexingOrder protected function Tests whether items are indexed in the right order.
SearchApiWebTest::checkIndexStatus protected function Checks whether the index's "Status" tab shows the correct values.
SearchApiWebTest::checkOverview protected function Checks whether the server and index are correctly listed in the overview.
SearchApiWebTest::checkServerTasks protected function Tests whether the server tasks system works correctly.
SearchApiWebTest::clearIndex protected function Tests whether clearing the index works correctly.
SearchApiWebTest::createIndex protected function Creates a test index via the UI and tests whether this works correctly.
SearchApiWebTest::createServer protected function Creates a test server via the UI and tests whether this works correctly.
SearchApiWebTest::deleteServer protected function Tests whether deleting the server works correctly.
SearchApiWebTest::disableModules protected function Tests whether disabling and uninstalling the modules works correctly.
SearchApiWebTest::doSearch protected function Executes a search on the test index.
SearchApiWebTest::drupalGet protected function Overrides DrupalWebTestCase::drupalGet(). Overrides DrupalWebTestCase::drupalGet
SearchApiWebTest::drupalPost protected function Overrides DrupalWebTestCase::drupalPost(). Overrides DrupalWebTestCase::drupalPost
SearchApiWebTest::editServer protected function Tests whether editing the server works correctly.
SearchApiWebTest::enableIndex protected function Moves the index onto the server and enables it.
SearchApiWebTest::getInfo public static function Returns information about this test case.
SearchApiWebTest::index protected function Returns the test index in use by this test case.
SearchApiWebTest::indexItems protected function Tests indexing via the UI "Index now" functionality.
SearchApiWebTest::insertItem protected function Helper function for inserting a single test item.
SearchApiWebTest::insertItems protected function Inserts some test items into the database, via the test module.
SearchApiWebTest::searchNoResults protected function Asserts that a search on the index works but yields no results.
SearchApiWebTest::searchSuccess protected function Tests whether searches yield the right results after indexing.
SearchApiWebTest::server protected function Returns the test server in use by this test case.
SearchApiWebTest::setUp public function Sets up a Drupal site for running functional and integration tests. Overrides DrupalWebTestCase::setUp
SearchApiWebTest::testFramework public function Tests correct admin UI, indexing and search behavior.