ai_upgrade_assistant-0.2.0-alpha2/tests/src/Unit/Service/OpenAI/OpenAIServiceTest.php

tests/src/Unit/Service/OpenAI/OpenAIServiceTest.php
<?php

namespace Drupal\Tests\ai_upgrade_assistant\Unit\Service\OpenAI;

use Drupal\ai_upgrade_assistant\Service\OpenAIService;
use Drupal\Tests\UnitTestCase;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Logger\LoggerChannelInterface;

/**
 * Tests the OpenAI service.
 *
 * @group ai_upgrade_assistant
 * @coversDefaultClass \Drupal\ai_upgrade_assistant\Service\OpenAIService
 */
class OpenAIServiceTest extends UnitTestCase {

  /**
   * The OpenAI service under test.
   *
   * @var \Drupal\ai_upgrade_assistant\Service\OpenAIService
   */
  protected $openAIService;

  /**
   * The mock HTTP client.
   *
   * @var \GuzzleHttp\Client
   */
  protected $httpClient;

  /**
   * The mock handler for HTTP requests.
   *
   * @var \GuzzleHttp\Handler\MockHandler
   */
  protected $mockHandler;

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

    // Create mock config.
    $config = $this->createMock(ImmutableConfig::class);
    $config->expects($this->any())
      ->method('get')
      ->willReturnMap([
        ['openai_api_key', 'test_key'],
        ['openai_model', 'gpt-4'],
        ['max_retries', 3],
      ]);

    $configFactory = $this->createMock(ConfigFactoryInterface::class);
    $configFactory->expects($this->any())
      ->method('get')
      ->with('ai_upgrade_assistant.settings')
      ->willReturn($config);

    // Create mock logger.
    $logger = $this->createMock(LoggerChannelInterface::class);
    $loggerFactory = $this->createMock(LoggerChannelFactoryInterface::class);
    $loggerFactory->expects($this->any())
      ->method('get')
      ->with('ai_upgrade_assistant')
      ->willReturn($logger);

    // Set up mock HTTP client.
    $this->mockHandler = new MockHandler();
    $handlerStack = HandlerStack::create($this->mockHandler);
    $this->httpClient = new Client(['handler' => $handlerStack]);

    // Create the service.
    $this->openAIService = new OpenAIService(
      $this->httpClient,
      $configFactory,
      $loggerFactory
    );
  }

  /**
   * Tests successful API calls.
   *
   * @covers ::generateCompletion
   */
  public function testSuccessfulApiCall() {
    $response_data = [
      'choices' => [
        [
          'message' => [
            'content' => 'Test response',
          ],
        ],
      ],
    ];

    $this->mockHandler->append(
      new Response(200, [], json_encode($response_data))
    );

    $result = $this->openAIService->generateCompletion('Test prompt');
    $this->assertEquals('Test response', $result);
  }

  /**
   * Tests rate limiting and retries.
   *
   * @covers ::generateCompletion
   */
  public function testRateLimitingAndRetries() {
    // Mock rate limit response followed by success.
    $this->mockHandler->append(
      new Response(429, [], 'Rate limited'),
      new Response(200, [], json_encode([
        'choices' => [
          [
            'message' => [
              'content' => 'Success after retry',
            ],
          ],
        ],
      ]))
    );

    $result = $this->openAIService->generateCompletion('Test prompt');
    $this->assertEquals('Success after retry', $result);
  }

  /**
   * Tests error handling.
   *
   * @covers ::generateCompletion
   */
  public function testErrorHandling() {
    $this->mockHandler->append(
      new Response(500, [], 'Server error'),
      new Response(500, [], 'Server error'),
      new Response(500, [], 'Server error')
    );

    $this->expectException(\Exception::class);
    $this->expectExceptionMessage('Failed to get response from OpenAI API after 3 attempts');

    $this->openAIService->generateCompletion('Test prompt');
  }
}

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

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