vertex_ai_search-1.0.0-beta4/tests/src/Unit/Plugin/Autocomplete/VertexAutocompleteExceptionTest.php

tests/src/Unit/Plugin/Autocomplete/VertexAutocompleteExceptionTest.php
<?php

namespace Drupal\Tests\vertex_ai_search\Unit\Plugin\Autocomplete;

use Drupal\vertex_ai_search\Plugin\Autocomplete\VertexAutocomplete;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Google\ApiCore\ApiException;

/**
 * @coversDefaultClass \Drupal\vertex_ai_search\Plugin\Autocomplete\VertexAutocomplete
 */
class VertexAutocompleteExceptionTest extends TestCase {

  /**
   * Logger mock.
   *
   * @var \Psr\Log\LoggerInterface|\PHPUnit\Framework\MockObject\MockObject
   */
  protected $logger;

  /**
   * VertexAutocomplete testable instance.
   *
   * @var TestableVertexAutocomplete
   */
  protected $autocomplete;

  /**
   * {@inheritdoc}
   */
  protected function setUp(): void {

    /** @var \Psr\Log\LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */
    $this->logger = $this->createMock(LoggerInterface::class);

    $this->autocomplete = new TestableVertexAutocomplete(
      [],
      'vertex_autocomplete_vertex',
      [],
      $this->logger
    );
  }

  /**
   * Test that ApiException is logged as error.
   */
  public function testApiExceptionIsLogged() {
    $exception = new ApiException('API error', 0, NULL, [], NULL, 'ERROR');
    $this->autocomplete->setExceptionToThrow($exception);

    $this->logger->expects($this->once())
      ->method('error')
      ->with(
        $this->stringContains('APIException'),
        $this->arrayHasKey('@error')
      );

    $this->autocomplete->getSuggestions('test');
  }

  /**
   * Test that generic Exception is logged as error.
   */
  public function testGenericExceptionIsLogged() {
    $exception = new \Exception('Generic error');
    $this->autocomplete->setExceptionToThrow($exception);

    $this->logger->expects($this->once())
      ->method('error')
      ->with(
        $this->stringContains('Exception error'),
        $this->arrayHasKey('@message')
      );

    $this->autocomplete->getSuggestions('test');
  }

}

/**
 * Testable subclass to inject exceptions into getSuggestions.
 */
class TestableVertexAutocomplete extends VertexAutocomplete {

  /**
   * Exception to throw when doCompleteQuery is called.
   *
   * @var \Exception|null
   */
  protected $exceptionToThrow;

  /**
   * Set the exception to be thrown by doCompleteQuery.
   *
   * @param \Exception $exception
   *   The exception to throw.
   */
  public function setExceptionToThrow(\Exception $exception) {
    $this->exceptionToThrow = $exception;
  }

  /**
   * Override to inject exception throwing.
   */
  protected function doCompleteQuery($keys) {
    if ($this->exceptionToThrow) {
      throw $this->exceptionToThrow;
    }
    return [];
  }

}

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

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