Tester des redirections avec le client HTTP Symfony

Publié le 15/04/2020 • Actualisé le 15/04/2020


English language detected! 🇬🇧

  We noticed that your browser is using English. Do you want to read this post in this language?

Read the english version 🇬🇧 Close

Dans ce bout de code, nous allons voir comment tester des redirections avec le client Http Symfony. Le code suivant est, en fait, un test fonctionnel. L'astuce ici est de mettre le paramètre max_redirects à 0. Dans ce cas, si une redirection est faite alors une exception sera levée. Autrement, la fonction $this->fail() sera appelée et le test est marqué comme en échec. Si l'exception est bien levée comme prévu, alors on teste le code de retour (on pourrait ne pas le faire puisque l'exception que nous attrapons est une RedirectionException). Puis, nous testons que l'URL est bien redirigée vers la destination attendue. On utilise un fournisseur de données (🇬🇧 @dataProvider) pour tester plusieurs cas. Comme ce test implique des ressources externes (le serveur de production en l'occurrence), il est inclus dans une suite de test particulière "externe".


<?php

declare(strict_types=1);

namespace App\Tests\External;

use App\Tests\WebTestCase;
use Symfony\Component\HttpClient\Exception\RedirectionException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\HttpClient\HttpClientInterface;

/**
 * Test the SSL redirections.
 *
 * @see http://www.strangebuzz.com
 */
final class SslTest extends WebTestCase
{
    private const CANONICAL = 'https://www.strangebuzz.com/';

    private HttpClientInterface $httpClient;

    protected function setUp(): void
    {
        $this->httpClient = $this->getHttpClientService();
    }

    /**
     * @return iterable<int, array{0: string, 1: string}>
     */
    public function urlProvider(): iterable
    {
        // http with www
        yield ['http://www.strangebuzz.com', self::CANONICAL];
        yield ['http://www.strangebuzz.com/', self::CANONICAL];
        yield ['http://www.strangebuzz.com/en/snippets/freezing-the-vue-js-version-to-a-minor-version', self::CANONICAL];

        // http with www
        yield ['http://strangebuzz.com', self::CANONICAL];
        yield ['http://strangebuzz.com/', self::CANONICAL];
        yield ['http://strangebuzz.com/en/snippets/freezing-the-vue-js-version-to-a-minor-version', self::CANONICAL];

        // https without www
        yield ['https://strangebuzz.com', self::CANONICAL];
        yield ['https://strangebuzz.com/', self::CANONICAL];
        yield ['https://strangebuzz.com/en/snippets/freezing-the-vue-js-version-to-a-minor-version', self::CANONICAL];
    }

    /**
     * @dataProvider urlProvider
     */
    public function testSsl(string $url, string $location): void
    {
        try {
            $this->httpClient->request('GET', $url, ['max_redirects' => 0])->getContent();
            self::fail(sprintf('URL "%s" non redirigée.', $url));
        } catch (RedirectionException $e) {
            self::assertSame(Response::HTTP_MOVED_PERMANENTLY, $e->getResponse()->getStatusCode());
            $info = $e->getResponse()->getInfo();
            if (!\is_array($info)) {
                throw new \TypeError('Incorrect type, array expected.');
            }
            self::assertSame($location, $info['redirect_url'] ?? '');
        }
    }
}

 Plus sur Stackoverflow   Lire la doc  Snippet aléatoire

  Travaillez avec moi !