Skip to content

Add an HTTP client dedicated to functional API testing #2608

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

Merged
merged 4 commits into from
Jun 26, 2019
Merged
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 composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@
"symfony/finder": "^3.4 || ^4.0",
"symfony/form": "^3.4 || ^4.0",
"symfony/framework-bundle": "^4.3",
"symfony/http-client": "^4.3",
"symfony/mercure-bundle": "*",
"symfony/messenger": "^4.3",
"symfony/phpunit-bridge": "^4.3.1",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
use Doctrine\Common\Annotations\Annotation;
use phpDocumentor\Reflection\DocBlockFactoryInterface;
use Ramsey\Uuid\Uuid;
use Symfony\Component\BrowserKit\AbstractBrowser;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Config\Resource\DirectoryResource;
Expand Down Expand Up @@ -120,6 +121,10 @@ public function load(array $configs, ContainerBuilder $container): void
->addTag('api_platform.subresource_data_provider');
$container->registerForAutoconfiguration(FilterInterface::class)
->addTag('api_platform.filter');

if ($container->hasParameter('test.client.parameters') && class_exists(AbstractBrowser::class)) {
$loader->load('test.xml');
}
}

private function registerCommonConfiguration(ContainerBuilder $container, array $config, XmlFileLoader $loader, array $formats, array $errorFormats): void
Expand Down
13 changes: 13 additions & 0 deletions src/Bridge/Symfony/Bundle/Resources/config/test.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

<services>
<service id="test.api_platform.client" class="ApiPlatform\Core\Bridge\Symfony\Bundle\Test\Client" public="true">
<argument type="service" id="test.client" />
</service>
</services>

</container>
48 changes: 48 additions & 0 deletions src/Bridge/Symfony/Bundle/Test/ApiTestCase.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Core\Bridge\Symfony\Bundle\Test;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;

/**
* Base class for functional API tests.
*
* @experimental
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
abstract class ApiTestCase extends KernelTestCase
{
/**
* Creates a Client.
*
* @param array $options An array of options to pass to the createKernel method
*/
protected static function createClient(array $options = []): Client
{
$kernel = static::bootKernel($options);

try {
/**
* @var Client
*/
$client = $kernel->getContainer()->get('test.api_platform.client');
} catch (ServiceNotFoundException $e) {
throw new \LogicException('You cannot create the client used in functional tests if the BrowserKit component is not available. Try running "composer require symfony/browser-kit".');
}

return $client;
}
}
180 changes: 180 additions & 0 deletions src/Bridge/Symfony/Bundle/Test/Client.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Core\Bridge\Symfony\Bundle\Test;

use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpClient\HttpClientTrait;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\HttpKernel\Profiler\Profile;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
use Symfony\Contracts\HttpClient\ResponseStreamInterface;

/**
* Convenient test client that makes requests to a Kernel object.
*
* @experimental
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
final class Client implements HttpClientInterface
{
/**
* @see HttpClientInterface::OPTIONS_DEFAULTS
*/
public const OPTIONS_DEFAULT = [
'auth_basic' => null,
'auth_bearer' => null,
'query' => [],
'headers' => ['accept' => ['application/ld+json']],
'body' => '',
'json' => null,
'base_uri' => 'http://example.com',
];

use HttpClientTrait;

private $kernelBrowser;

public function __construct(KernelBrowser $kernelBrowser)
{
$this->kernelBrowser = $kernelBrowser;
$kernelBrowser->followRedirects(false);
}

/**
* {@inheritdoc}
*
* @see Client::OPTIONS_DEFAULTS for available options
*
* @return Response
*/
public function request(string $method, string $url, array $options = []): ResponseInterface
{
$basic = $options['auth_basic'] ?? null;
[$url, $options] = self::prepareRequest($method, $url, $options, self::OPTIONS_DEFAULT);
$resolvedUrl = implode('', $url);

$server = [];
// Convert headers to a $_SERVER-like array
foreach ($options['headers'] as $key => $value) {
if ('content-type' === $key) {
$server['CONTENT_TYPE'] = $value[0] ?? '';

continue;
}

// BrowserKit doesn't support setting several headers with the same name
$server['HTTP_'.strtoupper(str_replace('-', '_', $key))] = $value[0] ?? '';
}

if ($basic) {
$credentials = \is_array($basic) ? $basic : explode(':', $basic, 2);
$server['PHP_AUTH_USER'] = $credentials[0];
$server['PHP_AUTH_PW'] = $credentials[1] ?? '';
}

$info = [
'response_headers' => [],
'redirect_count' => 0,
'redirect_url' => null,
'start_time' => 0.0,
'http_method' => $method,
'http_code' => 0,
'error' => null,
'user_data' => $options['user_data'] ?? null,
'url' => $resolvedUrl,
'primary_port' => 'http:' === $url['scheme'] ? 80 : 443,
];
$this->kernelBrowser->request($method, $resolvedUrl, [], [], $server, $options['body'] ?? null);

return new Response($this->kernelBrowser->getResponse(), $this->kernelBrowser->getInternalResponse(), $info);
}

/**
* {@inheritdoc}
*/
public function stream($responses, float $timeout = null): ResponseStreamInterface
{
throw new \LogicException('Not implemented yet');
}

/**
* Gets the underlying test client.
*/
public function getKernelBrowser(): KernelBrowser
{
return $this->kernelBrowser;
}

// The following methods are proxy methods for KernelBrowser's ones

/**
* Returns the container.
*
* @return ContainerInterface|null Returns null when the Kernel has been shutdown or not started yet
*/
public function getContainer(): ?ContainerInterface
{
return $this->kernelBrowser->getContainer();
}

/**
* Returns the kernel.
*/
public function getKernel(): KernelInterface
{
return $this->kernelBrowser->getKernel();
}

/**
* Gets the profile associated with the current Response.
*
* @return Profile|false A Profile instance
*/
public function getProfile()
{
return $this->kernelBrowser->getProfile();
}

/**
* Enables the profiler for the very next request.
*
* If the profiler is not enabled, the call to this method does nothing.
*/
public function enableProfiler(): void
{
$this->kernelBrowser->enableProfiler();
}

/**
* Disables kernel reboot between requests.
*
* By default, the Client reboots the Kernel for each request. This method
* allows to keep the same kernel across requests.
*/
public function disableReboot(): void
{
$this->kernelBrowser->disableReboot();
}

/**
* Enables kernel reboot between requests.
*/
public function enableReboot(): void
{
$this->kernelBrowser->enableReboot();
}
}
Loading