From c992e06d8b6b759d18b65d4de7ea97bceee0290f Mon Sep 17 00:00:00 2001 From: tuutti Date: Thu, 24 Aug 2023 16:35:16 +0300 Subject: [PATCH 1/2] UHF-5265: Allow http_client_factory to be mocked --- tests/src/Traits/ApiTestTrait.php | 36 +++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/tests/src/Traits/ApiTestTrait.php b/tests/src/Traits/ApiTestTrait.php index 60a7aa68..2681c401 100644 --- a/tests/src/Traits/ApiTestTrait.php +++ b/tests/src/Traits/ApiTestTrait.php @@ -6,7 +6,9 @@ use Drupal\Component\Serialization\Json; use Drupal\Core\Extension\ExtensionPathResolver; +use Drupal\Core\Http\ClientFactory; use GuzzleHttp\Client; +use GuzzleHttp\ClientInterface; use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\HandlerStack; use GuzzleHttp\Middleware; @@ -34,6 +36,40 @@ protected function createMockHttpClient(array $responses) : Client { return new Client(['handler' => $handlerStack]); } + /** + * Overrides the default http_client service with mocked client. + * + * @param \Psr\Http\Message\ResponseInterface[] $responses + * The expected responses. + * + * @return \GuzzleHttp\Client + * The client. + */ + protected function setupMockHttpClient(array $responses) : Client { + $client = $this->createMockHttpClient($responses); + + $this->container->set('http_client_factory', new class ($client) extends ClientFactory { + + /** + * Constructs a new instance. + * + * @param \GuzzleHttp\ClientInterface $client + * The http client. + */ + public function __construct(private readonly ClientInterface $client) { + } + + /** + * {@inheritdoc} + */ + public function fromOptions(array $config = []) : ClientInterface { + return $this->client; + } + + }); + return $client; + } + /** * Process a request. * From 3b3971dfbf57359ab51e2c5c13082bcf569ca869 Mon Sep 17 00:00:00 2001 From: tuutti Date: Thu, 24 Aug 2023 16:37:15 +0300 Subject: [PATCH 2/2] UHF-5265: Fixed comment --- tests/src/Traits/ApiTestTrait.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/src/Traits/ApiTestTrait.php b/tests/src/Traits/ApiTestTrait.php index 2681c401..2a2f5c9b 100644 --- a/tests/src/Traits/ApiTestTrait.php +++ b/tests/src/Traits/ApiTestTrait.php @@ -37,7 +37,7 @@ protected function createMockHttpClient(array $responses) : Client { } /** - * Overrides the default http_client service with mocked client. + * Overrides the default 'http_client_factory' service with mock. * * @param \Psr\Http\Message\ResponseInterface[] $responses * The expected responses.