test_helpers-1.0.0-alpha6/tests/modules/test_helpers_http_client_mock/tests/src/Kernel/HttpClientFactoryMockTest.php

tests/modules/test_helpers_http_client_mock/tests/src/Kernel/HttpClientFactoryMockTest.php
<?php

declare(strict_types=1);

namespace Drupal\Tests\test_helpers_http_client_mock\Kernel;

use Drupal\KernelTests\KernelTestBase;
use GuzzleHttp\Psr7\Request;
use donatj\MockWebServer\MockWebServer;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Group;

/**
 * Tests the HttpClientFactoryMock class.
 */
#[CoversClass(\Drupal\test_helpers_http_client_mock\HttpClientFactoryMock::class)]
#[Group('test_helpers')]
#[Group('test_helpers_http_client_mock')]
class HttpClientFactoryMockTest extends KernelTestBase {

  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'test_helpers_test',
    'test_helpers_http_client_mock',
  ];

  /**
   * Tests the Store HTTP response feature.
   */
  public function testStoreHttpResponse() {
    $server = new MockWebServer();
    $server->start();
    $url = $server->getServerRoot() . '/endpoint?get=foobar';
    $request = new Request('GET', $url);

    $directory = __DIR__ . '/../../assets/testStoreHttpResponse';
    $service = \Drupal::service('http_client_factory');
    $service->stubSetResponsesStorageDirectory($directory);
    $service->stubSetRequestMockMode('store');
    $options = [];
    $clientStore = $service->fromOptions($options);
    $hash = $service->stubGetRequestHash($request);
    $resultsStoreFile = $service->stubGetRequestFilename($hash);

    // Deleting the file if exists, to check if it will be recreated.
    if (file_exists($resultsStoreFile)) {
      unlink($resultsStoreFile);
      unlink($service->stubGetRequestFilename($hash, TRUE));
    }
    $responseStore = $clientStore->request('GET', $url);
    $resultStore = $responseStore->getBody()->getContents();
    $resultStored = file_get_contents($resultsStoreFile);
    $this->assertEquals($resultStore, $resultStored);

    // Writing a modified response data to the file and checks if it is read.
    $service->stubSetRequestMockMode('mock');
    $clientMock = $service->fromOptions($options);
    $resultStoredArray = json_decode($resultStored, TRUE);
    $resultStoredArray['userId'] = 7;
    $resultStoredModified = json_encode($resultStoredArray);
    file_put_contents($resultsStoreFile, $resultStoredModified);
    $responseMock = $clientMock->request('GET', $url);
    $resultMocked = $responseMock->getBody()->getContents();
    $resultMockedArray = json_decode($resultMocked, TRUE);
    $this->assertEquals(7, $resultMockedArray['userId']);

    unlink($resultsStoreFile);
    unlink($service->stubGetRequestFilename($hash, TRUE));
    rmdir($directory);
    $server->stop();
  }

}

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

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