followRedirects example

bool $enableReboot = false,
        bool $authorized = true,
        array $scopes = [],
        ?array $permissions = null
    ): TestBrowser {
        if (!$kernel) {
            $kernel = $this->getKernel();
        }

        $apiBrowser = KernelLifecycleManager::createBrowser($kernel$enableReboot);

        $apiBrowser->followRedirects();
        $apiBrowser->setServerParameters([
            'CONTENT_TYPE' => 'application/json',
            'HTTP_ACCEPT' => ['application/vnd.api+json,application/json'],
        ]);

        if ($authorized) {
            $this->authorizeBrowser($apiBrowser$scopes$permissions);
        }

        return $this->kernelBrowser = $apiBrowser;
    }

    
'acl_role_id' => Uuid::fromHexToBytes($ids->get('acl_role')),
            'created_at' => (new \DateTime())->format(Defaults::STORAGE_DATE_TIME_FORMAT),
        ]);

        $connection->insert('integration_role', [
            'integration_id' => Uuid::fromHexToBytes($ids->get('integration')),
            'acl_role_id' => Uuid::fromHexToBytes($ids->get('acl_role')),
        ]);

        $this->resetBrowser();
        $browser = $this->getBrowser();
        $browser->followRedirects();
        $browser->setServerParameter('HTTP_' . PlatformRequest::HEADER_APP_INTEGRATION_ID, $ids->get('integration'));

        $browser->request('POST', '/api/search/currency', [
            'limit' => 2,
        ]);
        $response = json_decode((string) $browser->getResponse()->getContent(), true, 512, \JSON_THROW_ON_ERROR);

        static::assertEquals(Response::HTTP_FORBIDDEN, $browser->getResponse()->getStatusCode(), \json_encode($response, \JSON_THROW_ON_ERROR));
        static::assertArrayHasKey('errors', $response);
    }

    
$token = $client->getResponse()->headers->get('x-debug-token');
        $client->request('GET', '/_profiler/search?token='.$token);

        $this->assertSame(302, $client->getResponse()->getStatusCode());
        $this->assertSame('/_profiler/'.$token$client->getResponse()->getTargetUrl());
    }

    public function testSearchActionWithoutToken()
    {
        $kernel = new WebProfilerBundleKernel();
        $client = new KernelBrowser($kernel);
        $client->followRedirects();

        $client->request('GET', '/');
        $token = $client->getResponse()->headers->get('x-debug-token');
        $client->request('GET', '/_profiler/search?ip=&method=GET&status_code=&url=&token=&start=&end=&limit=10');

        $this->assertStringContainsString('results found', $client->getResponse()->getContent());
        $this->assertStringContainsString(sprintf('<a href="/_profiler/%s">%s</a>', $token$token)$client->getResponse()->getContent());
    }

    public function testPhpinfoActionWithProfilerDisabled()
    {
        
/** * Calls ::performMetaRefresh() and asserts the responses. * * @internal */
  protected function assertBigPipeNoJsMetaRefreshRedirect(): void {
    $original_url = $this->getSession()->getCurrentUrl();

    // Disable automatic following of redirects by the HTTP client, so that this     // test can analyze the response headers of each redirect response.     $this->getSession()->getDriver()->getClient()->followRedirects(FALSE);
    $this->performMetaRefresh();
    $headers[0] = $this->getSession()->getResponseHeaders();
    $statuses[0] = $this->getSession()->getStatusCode();
    $this->performMetaRefresh();
    $headers[1] = $this->getSession()->getResponseHeaders();
    $statuses[1] = $this->getSession()->getStatusCode();
    $this->getSession()->getDriver()->getClient()->followRedirects(TRUE);

    $this->assertEquals($original_url$this->getSession()->getCurrentUrl(), 'Redirected back to the original location.');

    // First response: redirect.
return [
            'unauthorized_user_cannot_switch' => ['user_cannot_switch_1', 'user_cannot_switch_1', 'user_cannot_switch_1', 403],
            'authorized_user_can_switch' => ['user_can_switch', 'user_cannot_switch_1', 'user_cannot_switch_1', 200],
            'authorized_user_cannot_switch_to_non_existent' => ['user_can_switch', 'user_does_not_exist', 'user_can_switch', 403],
            'authorized_user_can_switch_to_himself' => ['user_can_switch', 'user_can_switch', 'user_can_switch', 200],
        ];
    }

    protected function createAuthenticatedClient($username, array $options = [])
    {
        $client = $this->createClient(['test_case' => 'StandardFormLogin', 'root_config' => 'switchuser.yml'] + $options);
        $client->followRedirects(true);

        $form = $client->request('GET', '/login')->selectButton('login')->form();
        $form['_username'] = $username;
        $form['_password'] = 'test';
        $client->submit($form);

        return $client;
    }
}
if ($salesChannel !== null) {
            $orderData[0]['salesChannelId'] = $salesChannel->getId();
        }

        $productId = $this->createProduct($context);
        $orderData[0]['lineItems'][0]['identifier'] = $productId;
        $orderData[0]['lineItems'][0]['productId'] = $productId;

        $orderRepo = $this->getContainer()->get('order.repository');
        $orderRepo->create($orderData$context);

        $browser->followRedirects();

        $browser->request('GET', $_SERVER['APP_URL'] . '/account/order/' . $orderData[0]['deepLinkCode']);
        /** @var StorefrontResponse $response */
        $response = $browser->getResponse();

        static::assertSame('frontend.account.order.single.page', $response->getData()['redirectTo']);
        static::assertSame('BwvdEInxOHBbwfRw6oHF1Q_orfYeo9RY', $response->getData()['redirectParameters']['deepLinkCode']);

        $browser->request(
            'POST',
            $_SERVER['APP_URL'] . '/account/order/' . $orderData[0]['deepLinkCode'],
            

        $this->ids = new TestDataCollection();

        $this->createData();
    }

    public function testMaintenancePageLoadedHookScriptsAreExecuted(): void
    {
        $this->setMaintenanceMode();

        $browser = KernelLifecycleManager::createBrowser($this->getKernel());
        $browser->followRedirects();

        $browser->request('GET', EnvironmentHelper::getVariable('APP_URL') . '/');
        $response = $browser->getResponse();

        static::assertEquals(503, $response->getStatusCode());

        $traces = $this->getContainer()->get(ScriptTraces::class)->getTraces();

        static::assertArrayHasKey(MaintenancePageLoadedHook::HOOK_NAME, $traces);
    }

    
$request->setInformationalResponseHandler(static function DResponse $response) use ($multi$id, &$info, &$headers) {
            self::addResponseHeaders($response$info$headers);
            $multi->handlesActivity[$id][] = new InformationalChunk($response->getStatus()$response->getHeaders());
            self::stopLoop();
        });

        try {
            /* @var Response $response */
            if (null === $response = yield from self::getPushedResponse($request$multi$info$headers$options$logger)) {
                $logger?->info(sprintf('Request: "%s %s"', $info['http_method']$info['url']));

                $response = yield from self::followRedirects($request$multi$info$headers$canceller$options$onProgress$handle$logger$pause);
            }

            $options = null;

            $multi->handlesActivity[$id][] = new FirstChunk();

            if ('HEAD' === $response->getRequest()->getMethod() || \in_array($info['http_code'][204, 304], true)) {
                $multi->handlesActivity[$id][] = null;
                $multi->handlesActivity[$id][] = null;
                self::stopLoop();

                
// Test that users have the correct time zone set.     $this->assertEquals($expected$this->rootUser->getTimeZone());
    $admin_user = $this->drupalCreateUser(['administer site configuration']);
    $this->assertEquals($expected$admin_user->getTimeZone());
  }

  /** * Tests the ::checkForMetaRefresh() method. */
  public function testCheckForMetaRefresh() {
    // Disable following redirects in the client.     $this->getSession()->getDriver()->getClient()->followRedirects(FALSE);
    // Set the maximumMetaRefreshCount to zero to make sure the redirect doesn't     // happen when doing a drupalGet.     $this->maximumMetaRefreshCount = 0;
    $this->drupalGet('test-meta-refresh');
    $this->assertNotEmpty($this->cssSelect('meta[http-equiv="refresh"]'));
    // Allow one redirect to happen.     $this->maximumMetaRefreshCount = 1;
    $this->checkForMetaRefresh();
    // Check that we are now on the test page.     $this->assertSession()->pageTextContains('Test page text.');
  }

  
$client->submit($crawler->filter('input')->form()[]$headers);

        $server = $client->getRequest()->getServer();
        $this->assertArrayHasKey('Accept-Language', $server);
        $this->assertSame('de', $server['Accept-Language']);
    }

    public function testFollowRedirect()
    {
        $client = $this->getBrowser();
        $client->followRedirects(false);
        $client->request('GET', 'http://www.example.com/foo/foobar');

        try {
            $client->followRedirect();
            $this->fail('->followRedirect() throws a \LogicException if the request was not redirected');
        } catch (\Exception $e) {
            $this->assertInstanceOf(\LogicException::class$e, '->followRedirect() throws a \LogicException if the request was not redirected');
        }

        $client->setNextResponse(new Response('', 302, ['Location' => 'http://www.example.com/redirected']));
        $client->request('GET', 'http://www.example.com/foo/foobar');
        
static::assertLessThan(400, $response->getStatusCode()(string) $response->getContent());
    }

    /** * @dataProvider errorDataProvider * * @param array<string> $errorKeys */
    public function testOffCanvasWithErrorsFlash(ErrorCollection $errors, array $errorKeys, bool $testSwitchToDefault = false): void
    {
        $browser = $this->getBrowserWithLoggedInCustomer();
        $browser->followRedirects(true);

        // Clear flashback from login and/or register         /** @var Session $session */
        $session = $this->getSession();
        $session->getFlashBag()->clear();

        $browserSalesChannelId = $browser->getServerParameter('test-sales-channel-id');

        $productId = Uuid::randomHex();
        $this->createProductOnDatabase($productId, 'test.123', $browserSalesChannelId);

        
$products = [
            (new ProductBuilder($ids, 'p1'))->price(100)->build(),
        ];

        $this->getContainer()->get('product.repository')->create($products, Context::createDefaultContext());

        $json = \json_encode(['productId' => $ids->get('p1')], \JSON_THROW_ON_ERROR);
        static::assertNotFalse($json);

        $browser = $this->getBrowser();
        $browser->followRedirects(false);
        $browser->request('POST', '/api/script/redirect-response', [][][]$json);
        $response = $browser->getResponse();

        static::assertSame(Response::HTTP_FOUND, $response->getStatusCode());

        static::assertTrue($response->headers->has('location'));
        static::assertSame('/api/product/' . $ids->get('p1')$response->headers->get('location'));
    }

    public function testAccessToInnerSymfonyResponseIsProhibited(): void
    {
        

        $this->loadAppsFromDir(__DIR__ . '/_fixtures');

        $ids = new IdsCollection();

        $products = [
            (new ProductBuilder($ids, 'p1'))->price(100)->build(),
        ];

        $this->getContainer()->get('product.repository')->create($products, Context::createDefaultContext());

        $this->browser->followRedirects(false);
        $this->browser->request('POST', '/store-api/script/redirect-response', ['productId' => $ids->get('p1')]);
        $response = $this->browser->getResponse();

        static::assertSame(Response::HTTP_FOUND, $response->getStatusCode());

        static::assertTrue($response->headers->has('location'));
        static::assertSame('/api/product/' . $ids->get('p1')$response->headers->get('location'));
    }

    public function testCaching(): void
    {
        
Home | Imprint | This part of the site doesn't use cookies.