Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[HttpClient] Configure MockClient if mock_response_factory has been set on a scoped client #52265

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: 7.4
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ CHANGELOG
6.4
---

* Add support for setting mock_response_factory per scoped http client
* Add `HttpClientAssertionsTrait`
* Add `AbstractController::renderBlock()` and `renderBlockView()`
* Add native return type to `Translator` and to `Application::reset()`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1866,8 +1866,13 @@ private function addHttpClientSection(ArrayNodeDefinition $rootNode, callable $e
->append($this->createHttpClientRetrySection())
->end()
->end()
->booleanNode('mock_client')
->info('Inject a mock client.')
->defaultFalse()
->end()
->scalarNode('mock_response_factory')
->info('The id of the service that should generate mock responses. It should be either an invokable or an iterable.')
->defaultNull()
->info('The id of the service that should generate mock responses. It should be either an invokable or an iterable. Requires mock_client = true')
->end()
->arrayNode('scoped_clients')
->useAttributeAsKey('name')
Expand Down Expand Up @@ -2006,6 +2011,12 @@ private function addHttpClientSection(ArrayNodeDefinition $rootNode, callable $e
->variableNode('md5')->end()
->end()
->end()
->booleanNode('mock_client')
->info('Inject a mock client.')
->end()
->scalarNode('mock_response_factory')
->info('The id of the service that should generate mock responses. It should be either an invokable or an iterable')
->end()
->arrayNode('extra')
->info('Extra options for specific HTTP client')
->normalizeKeys(false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2456,6 +2456,14 @@ private function registerHttpClientConfiguration(array $config, ContainerBuilder
->getDefinition('http_client.uri_template')
->setArgument(2, $defaultUriTemplateVars);

$mockByDefault = $config['mock_client'] ?? false;
$defaultMockResponseFactory = $config['mock_response_factory'] ?? null;
if ($mockByDefault) {
$container->register('http_client.mock_client', MockHttpClient::class)
->setDecoratedService('http_client.transport', null, -10) // lower priority than TraceableHttpClient (5)
->setArguments($defaultMockResponseFactory === null ? [] : [new Reference($defaultMockResponseFactory)]);
}

foreach ($config['scoped_clients'] as $name => $scopeConfig) {
if ($container->has($name)) {
throw new InvalidArgumentException(sprintf('Invalid scope name: "%s" is reserved.', $name));
Expand All @@ -2468,18 +2476,28 @@ private function registerHttpClientConfiguration(array $config, ContainerBuilder
$retryOptions = $scopeConfig['retry_failed'] ?? ['enabled' => false];
unset($scopeConfig['retry_failed']);

$httpClientTransport = new Reference('http_client.transport');

if ($scopeConfig['mock_client'] ?? $mockByDefault) {
$mockResponseFactory = $scopeConfig['mock_response_factory'] ?? $defaultMockResponseFactory;
$mockClientArguments = ($mockResponseFactory) ? [new Reference($mockResponseFactory)]: [];
$container->register('http_client.mock_client.'.$name, MockHttpClient::class)
->setDecoratedService($httpClientTransport, null, -10) // lower priority than TraceableHttpClient (5)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it is also decorated with priority 10 for the global mock_response_factory. Maybe worth having a lower priority here so it superseeds the global one ?

->setArguments($mockClientArguments);
}

if (null === $scope) {
$baseUri = $scopeConfig['base_uri'];
unset($scopeConfig['base_uri']);

$container->register($name, ScopingHttpClient::class)
->setFactory([ScopingHttpClient::class, 'forBaseUri'])
->setArguments([new Reference('http_client.transport'), $baseUri, $scopeConfig])
->setArguments([$httpClientTransport, $baseUri, $scopeConfig])
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not sure this change is needed. Sure you save a few objects and memory but only during build time and this is like 3 objects.

->addTag('http_client.client')
;
} else {
$container->register($name, ScopingHttpClient::class)
->setArguments([new Reference('http_client.transport'), [$scope => $scopeConfig], $scope])
->setArguments([$httpClientTransport, [$scope => $scopeConfig], $scope])
->addTag('http_client.client')
;
}
Expand All @@ -2501,6 +2519,7 @@ private function registerHttpClientConfiguration(array $config, ContainerBuilder
$defaultUriTemplateVars,
]);


$container->registerAliasForArgument($name, HttpClientInterface::class);

if ($hasPsr18) {
Expand All @@ -2518,11 +2537,7 @@ private function registerHttpClientConfiguration(array $config, ContainerBuilder
}
}

if ($responseFactoryId = $config['mock_response_factory'] ?? null) {
$container->register('http_client.mock_client', MockHttpClient::class)
->setDecoratedService('http_client.transport', null, -10) // lower priority than TraceableHttpClient (5)
->setArguments([new Reference($responseFactoryId)]);
}

}

private function registerThrottlingHttpClient(string $rateLimiter, string $name, ContainerBuilder $container): void
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -640,6 +640,7 @@
</xsd:sequence>
<xsd:attribute name="enabled" type="xsd:boolean" />
<xsd:attribute name="max-host-connections" type="xsd:integer" />
<xsd:attribute name="mock-client" type="xsd:boolean" />
<xsd:attribute name="mock-response-factory" type="xsd:string" />
</xsd:complexType>

Expand Down Expand Up @@ -697,6 +698,8 @@
<xsd:attribute name="local-pk" type="xsd:string" />
<xsd:attribute name="passphrase" type="xsd:string" />
<xsd:attribute name="ciphers" type="xsd:string" />
<xsd:attribute name="mock-client" type="xsd:boolean" />
<xsd:attribute name="mock-response-factory" type="xsd:string" />
<xsd:attribute name="rate-limiter" type="xsd:string" />
</xsd:complexType>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -808,6 +808,8 @@ class_exists(SemaphoreStore::class) && SemaphoreStore::isSupported() ? 'semaphor
'disallow_search_engine_index' => true,
'http_client' => [
'enabled' => !class_exists(FullStack::class) && class_exists(HttpClient::class),
'mock_client' => false,
'mock_response_factory' => null,
'scoped_clients' => [],
],
'mailer' => [
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
d<?php

$container->loadFromExtension('framework', [
'annotations' => false,
'http_method_override' => false,
'handle_all_throwables' => true,
'php_errors' => ['log' => true],
'http_client' => [
'default_options' => null,
'mock_client' => true,
'scoped_clients' => [
'notMocked' => [
'base_uri' => 'https://symfony.com',
'mock_client' => false,
],
'mocked' => [
'base_uri' => 'https://symfony.com'
],
'mocked_with_factory' => [
'base_uri' => 'https://symfony.com',
'mock_response_factory' => 'my_response_factory'
],

]
],
]);
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,20 @@
'php_errors' => ['log' => true],
'http_client' => [
'default_options' => null,
'mock_response_factory' => 'my_response_factory',
'mock_client' => true,
'mock_response_factory' => 'my_factory',
'scoped_clients' => [
'notMocked' => [
'base_uri' => 'https://symfony.com',
'mock_client' => false,
],
'mocked' => [
'base_uri' => 'https://symfony.com'
],
'mocked_custom_factory' => [
'base_uri' => 'https://symfony.com',
'mock_response_factory' => 'my_other_factory'
]
]
],
]);
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">

<framework:config http-method-override="false" handle-all-throwables="true">
<framework:annotations enabled="false" />
<framework:php-errors log="true" />
<framework:http-client mock-client="true">
<framework:default-options />
<framework:scoped-client name="notMocked" base-uri="https://symfony.com" mock-client="false"/>
<framework:scoped-client name="mocked" base-uri="https://symfony.com" />
<framework:scoped-client name="mocked_with_factory" base-uri="https://symfony.com" mock-response-factory="my_response_factory" />
</framework:http-client>
</framework:config>
</container>
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,12 @@
<framework:config http-method-override="false" handle-all-throwables="true">
<framework:annotations enabled="false" />
<framework:php-errors log="true" />
<framework:http-client mock-response-factory="my_response_factory">
<framework:http-client mock-response-factory="my_factory" mock-client="true">
<framework:default-options />
<framework:scoped-client name="notMocked" base-uri="https://symfony.com" mock-client="false" />
<framework:scoped-client name="mocked" base-uri="https://symfony.com" mock-client="true" />
<framework:scoped-client name="mocked_custom_factory" base-uri="https://symfony.com" mock-client="true" mock-response-factory="my_other_factory" />

</framework:http-client>
</framework:config>
</container>
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
framework:
annotations: false
http_method_override: false
handle_all_throwables: true
php_errors:
log: true
http_client:
default_options: ~
mock_client: true
scoped_clients:
notMocked:
base_uri : https://symfony.com
mock_client : false
mocked:
base_uri: https://symfony.com
mocked_with_factory:
base_uri: https://symfony.com
mock_response_factory: 'my_response_factory'
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,14 @@ framework:
log: true
http_client:
default_options: ~
mock_response_factory: my_response_factory
mock_client: true
mock_response_factory: 'my_factory'
scoped_clients:
notMocked:
base_uri : https://symfony.com
mock_client : false
mocked:
base_uri: https://symfony.com
mocked_custom_factory:
base_uri: https://symfony.com
mock_response_factory: 'my_other_factory'
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
framework:
annotations: false
http_method_override: false
handle_all_throwables: true
php_errors:
log: true
http_client:
default_options: ~
mock_response_factory: ~

scoped_clients:
notMocked:
base_uri: https://symfony.com
mocked:
base_uri: https://symfony.com
mock_response_factory: true
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
framework:
annotations: false
http_method_override: false
handle_all_throwables: true
php_errors:
log: true
http_client:
default_options: ~
mock_response_factory: ~

scoped_clients:
notMocked:
base_uri: https://symfony.com
mocked:
base_uri: https://symfony.com
mock_response_factory: "my_response_factory"
Original file line number Diff line number Diff line change
Expand Up @@ -2095,20 +2095,63 @@ public function testMailerWithSpecificMessageBus()
$this->assertEquals(new Reference('app.another_bus'), $container->getDefinition('mailer.mailer')->getArgument(1));
}

public function testHttpClientNoMock()
{
$container = $this->createContainerFromFile('http_client_scoped_without_query_option');

$this->assertFalse($container->hasDefinition('http_client.mock_client.foo'));
$this->assertFalse($container->hasDefinition('http_client.mock_client'));

}

public function testHttpClientMockResponseFactory()
{
$container = $this->createContainerFromFile('http_client_mock_response_factory');

$definition = $container->getDefinition('http_client.mock_client');
$this->assertFalse($container->hasDefinition('http_client.mock_client.notMocked'));

$definition = $container->getDefinition('http_client.mock_client.mocked');

$this->assertSame(MockHttpClient::class, $definition->getClass());
$this->assertCount(1, $definition->getArguments());

$argument = $definition->getArgument(0);
$this->assertInstanceOf(Reference::class, $argument);
$this->assertSame('http_client.transport', current($definition->getDecoratedService()));
$this->assertSame('my_factory', (string) $argument);

$definition = $container->getDefinition('http_client.mock_client.mocked_custom_factory');

$this->assertSame(MockHttpClient::class, $definition->getClass());
$this->assertCount(1, $definition->getArguments());

$argument = $definition->getArgument(0);
$this->assertInstanceOf(Reference::class, $argument);
$this->assertSame('http_client.transport', current($definition->getDecoratedService()));
$this->assertSame('my_response_factory', (string) $argument);
$this->assertSame('my_other_factory', (string) $argument);
}

public function testHttpClientUseMockClientButOverrideInScopedClientsAndEnableFactories()
{
$container = $this->createContainerFromFile('http_client_mock');

$definition = $container->getDefinition('http_client.mock_client');

$this->assertSame(MockHttpClient::class, $definition->getClass());
$this->assertCount(0, $definition->getArguments());

$this->assertFalse($container->hasDefinition('http_client.mock_client.notMocked'));

$definition = $container->getDefinition('http_client.mock_client.mocked');

$this->assertSame(MockHttpClient::class, $definition->getClass());
$this->assertCount(0, $definition->getArguments());

$definition = $container->getDefinition('http_client.mock_client.mocked_with_factory');

$this->assertSame(MockHttpClient::class, $definition->getClass());
$this->assertCount(1, $definition->getArguments());

}

public function testRegisterParameterCollectingBehaviorDescribingTags()
Expand Down