search_api_meilisearch-1.0.x-dev/tests/src/Kernel/Processor/SynonymsTest.php

tests/src/Kernel/Processor/SynonymsTest.php
<?php

namespace Drupal\Tests\search_api_meilisearch\Kernel\Processor;

use Drupal\Core\Form\FormState;
use Drupal\entity_test\Entity\EntityTest;
use PHPUnit\Framework\Attributes\Group;

/**
 * Tests synonyms processor.
 *
 * @group search_api_meilisearch
 */
#[Group('search_api_meilisearch')]
class SynonymsTest extends ProcessorKernelTestBase {

  /**
   * The test index.
   */
  protected const TEST_INDEX = 'kernel_search_synonyms_test_index';

  /**
   * The test processor id.
   */
  protected const PROCESSOR_ID = 'search_api_meilisearch_synonyms';

  /**
   * Tests synonyms processor.
   */
  public function testSynonymsProcessor(): void {
    $this->prepareTestIndex(self::TEST_INDEX, self::PROCESSOR_ID);
    $this->populateIndex();
    $this->configureSynonymsProcessor([
      'synonyms' => 'testing: test, the test, le test' . PHP_EOL . 'chad: giga chad',
    ]);

    $this->assertEquals(
      [
        'testing' => ['test', 'the test', 'le test'],
        'chad' => ['giga chad'],
      ],
      $this->index->getProcessor(self::PROCESSOR_ID)->getConfiguration()['synonyms']
    );

    $original_word_result = $this->index->query()
      ->keys('test')
      ->range(0, 10)
      ->execute();
    $this->assertCount(5, $original_word_result->getResultItems());

    $synonym_word_result = $this->index->query()
      ->keys('testing')
      ->range(0, 10)
      ->execute();
    $this->assertCount(5, $synonym_word_result->getResultItems());

    // Set score to 1 for all returned entities as it will be different
    // based on keys.
    foreach ($original_word_result->getResultItems() as $original) {
      $original->setScore(1.0);
    }
    foreach ($synonym_word_result->getResultItems() as $synonym) {
      $synonym->setScore(1.0);
    }

    $this->assertEquals(
      $original_word_result->getResultItems(),
      $synonym_word_result->getResultItems()
    );
  }

  /**
   * {@inheritdoc}
   */
  protected function getTestIndexes(): array {
    return [self::TEST_INDEX];
  }

  /**
   * Configure synonyms processor.
   */
  protected function configureSynonymsProcessor(array $configurations): void {
    $processor = $this->index->getProcessor(self::PROCESSOR_ID);

    $form = [];
    $form_state = new FormState();
    $form_state->setValues($configurations);
    $processor->submitConfigurationForm($form, $form_state);

    $this->index->save();
  }

  /**
   * Prepares search api index with items for tests.
   */
  protected function populateIndex(): void {
    foreach ([100, 99, 102, 80, 104] as $key => $weight) {
      EntityTest::create([
        'name' => 'Test entity ' . $key,
        'body' => 'This is the body of entity' . $key,
        'weight' => $weight,
      ])->save();
    }

    $this->index->indexItems();
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc