View source
<?php
namespace Drupal\Tests\search_api_db\Kernel;
use Drupal\KernelTests\KernelTestBase;
use Drupal\search_api\Utility\Utility;
use Drupal\search_api_autocomplete\Entity\Search;
use Drupal\search_api_db\Plugin\search_api\backend\Database;
use Drupal\Tests\search_api\Functional\ExampleContentTrait;
class AutocompleteTest extends KernelTestBase {
use ExampleContentTrait;
public static $modules = [
'entity_test',
'field',
'system',
'filter',
'text',
'user',
'search_api',
'search_api_autocomplete',
'search_api_db',
'search_api_db_test_autocomplete',
'search_api_test_db',
'search_api_test_example_content',
];
protected $serverId = 'database_search_server';
protected $indexId = 'database_search_index';
public function setUp() {
parent::setUp();
$this
->installSchema('search_api', [
'search_api_item',
]);
$this
->installSchema('user', [
'users_data',
]);
$this
->installEntitySchema('entity_test_mulrev_changed');
$this
->installEntitySchema('search_api_task');
$this
->installConfig('search_api');
if (!Utility::isRunningInCli()) {
\Drupal::state()
->set('search_api_use_tracking_batch', FALSE);
}
$this
->installConfig([
'search_api_db',
'search_api_test_example_content',
'search_api_test_db',
'search_api_db_test_autocomplete',
]);
$this
->setUpExampleStructure();
$this
->insertExampleContent();
$this
->indexItems($this->indexId);
}
public function testAutocompletion() {
$autocomplete = Search::load('search_api_db_test_autocomplete');
$index = $autocomplete
->getIndex();
$backend = $index
->getServerInstance()
->getBackend();
$this
->assertInstanceOf(Database::class, $backend);
$query = $index
->query()
->range(0, 10);
$suggestions = $backend
->getAutocompleteSuggestions($query, $autocomplete, 'fo', 'fo');
$expected = [
'foo' => 4,
'foobar' => 1,
'foobaz' => 1,
'foobuz' => 1,
];
$this
->assertSuggestionsEqual($expected, $suggestions);
$query = $index
->query()
->keys('foo')
->range(0, 10);
$suggestions = $backend
->getAutocompleteSuggestions($query, $autocomplete, 'fo', 'foo fo');
$expected = [
'foo foobaz' => 1,
'foo foobuz' => 1,
];
$this
->assertSuggestionsEqual($expected, $suggestions);
}
protected function assertSuggestionsEqual(array $expected, array $suggestions) {
$terms = [];
foreach ($suggestions as $suggestion) {
$terms[$suggestion
->getSuggestedKeys()] = $suggestion
->getResultsCount();
}
$this
->assertEquals($expected, $terms);
}
}