getResponse example

$this->browser
            ->request(
                'POST',
                '/store-api/account/login',
                [
                    'email' => $email,
                    'password' => 'shopware',
                ]
            );

        $response = $this->browser->getResponse();

        // After login successfully, the context token will be set in the header         $contextToken = $response->headers->get(PlatformRequest::HEADER_CONTEXT_TOKEN) ?? '';
        static::assertNotEmpty($contextToken);

        $this->browser->setServerParameter('HTTP_SW_CONTEXT_TOKEN', $contextToken);
    }

    public function testDeleteProductShouldReturnSuccess(): void
    {
        $productId = $this->createProduct($this->context);
        
$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);
    }

    public function testMaintenancePageLoadedHookScriptsAreExecutedForSinglePage(): void
    {
        $response = $this->request('GET', '/maintenance/singlepage/' . $this->ids->get('page')[]);
        
/** * Bubbles the route's access result' cacheability metadata. * * @param \Symfony\Component\HttpKernel\Event\ResponseEvent $event * The event to process. */
  public function onRespond(ResponseEvent $event) {
    if (!$event->isMainRequest()) {
      return;
    }

    $response = $event->getResponse();
    if (!$response instanceof CacheableResponseInterface) {
      return;
    }

    $request = $event->getRequest();
    $access_result = $request->attributes->get(AccessAwareRouterInterface::ACCESS_RESULT);
    $response->addCacheableDependency($access_result);
  }

  /** * {@inheritdoc} */
$this->browser
            ->request(
                'POST',
                '/store-api/account/login',
                [
                    'email' => $email,
                    'password' => 'shopware',
                ]
            );

        $response = $this->browser->getResponse();

        // After login successfully, the context token will be set in the header         $contextToken = $response->headers->get(PlatformRequest::HEADER_CONTEXT_TOKEN) ?? '';
        static::assertNotEmpty($contextToken);

        $this->browser->setServerParameter('HTTP_SW_CONTEXT_TOKEN', $contextToken);
    }

    public function testEmptyRequest(): void
    {
        $this->browser
            

        $browser = $this->getBrowserWithLoggedInCustomer();

        $browser->request(
            'POST',
            $_SERVER['APP_URL'] . '/checkout/order',
            [
                'tos' => 'on',
            ]
        );

        $response = $browser->getResponse();
        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();
        
$registrationData = $this->getRegistrationData();
        $this->browser
            ->request(
                'POST',
                '/store-api/account/register',
                [],
                [],
                ['CONTENT_TYPE' => 'application/json'],
                json_encode($registrationData, \JSON_THROW_ON_ERROR)
            );

        $response = json_decode((string) $this->browser->getResponse()->getContent(), true, 512, \JSON_THROW_ON_ERROR);

        /** * @var Connection $connection */
        $connection = $this->getContainer()->get(Connection::class);
        $result = $connection->fetchOne(
            'SELECT `payload` FROM `sales_channel_api_context` WHERE `customer_id` = :customerId ',
            [
                'customerId' => Uuid::fromHexToBytes($response['id']),
            ]
        );
        

    public function onKernelResponse(ResponseEvent $event)
    {
        $request = $event->getRequest();

        /** @var Cache[] $attributes */
        if (!\is_array($attributes = $request->attributes->get('_cache'))) {
            return;
        }
        $response = $event->getResponse();

        // http://tools.ietf.org/html/draft-ietf-httpbis-p4-conditional-12#section-3.1         if (!\in_array($response->getStatusCode()[200, 203, 300, 301, 302, 304, 404, 410])) {
            unset($this->lastModified[$request]);
            unset($this->etags[$request]);

            return;
        }

        if (isset($this->lastModified[$request]) && !$response->headers->has('Last-Modified')) {
            $response->setLastModified($this->lastModified[$request]);
        }

    public function testFormLogin(array $options)
    {
        $client = $this->createClient($options);

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

        $this->assertRedirect($client->getResponse(), '/profile');

        $text = $client->followRedirect()->text(null, true);
        $this->assertStringContainsString('Hello johannes!', $text);
        $this->assertStringContainsString('You\'re browsing to path "/profile".', $text);
    }

    /** * @dataProvider provideClientOptions */
    public function testFormLogout(array $options)
    {
        
public function testSalutation(): void
    {
        $this->browser
            ->request(
                'POST',
                '/store-api/salutation',
                [
                ]
            );

        $response = json_decode((string) $this->browser->getResponse()->getContent(), true, 512, \JSON_THROW_ON_ERROR);

        static::assertSame(3, $response['total']);
        static::assertArrayHasKey('salutationKey', $response['elements'][0]);
        static::assertArrayHasKey('displayName', $response['elements'][0]);
        static::assertArrayHasKey('letterName', $response['elements'][0]);
    }

    public function testIncludes(): void
    {
        $this->browser
            ->request(
                
private HttpUtils $httpUtils;
    private string $targetUrl;

    public function __construct(HttpUtils $httpUtils, string $targetUrl = '/')
    {
        $this->httpUtils = $httpUtils;
        $this->targetUrl = $targetUrl;
    }

    public function onLogout(LogoutEvent $event): void
    {
        if (null !== $event->getResponse()) {
            return;
        }

        $event->setResponse($this->httpUtils->createRedirectResponse($event->getRequest()$this->targetUrl));
    }

    public static function getSubscribedEvents(): array
    {
        return [
            LogoutEvent::class => ['onLogout', 64],
        ];
    }
$baseResource = '/api/';

        $this->getBrowser()->request(
            'POST',
            $baseResource . '_action/order/document/invoice/create',
            [],
            [],
            [],
            (string) json_encode([$document])
        );

        $response = json_decode((string) $this->getBrowser()->getResponse()->getContent(), true, 512, \JSON_THROW_ON_ERROR);
        static::assertArrayHasKey('data', $response);

        $filename = 'invoice';
        $expectedFileContent = 'simple invoice';
        $expectedContentType = 'text/plain; charset=UTF-8';

        $this->getBrowser()->request(
            'POST',
            $baseResource . '_action/document/' . $response['data'][0]['documentId'] . '/upload?fileName=' . $filename . '&extension=txt',
            [],
            [],
            [

        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage('$firewallName must not be empty');
        new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, '', $this->accessDecisionManager);
    }

    public function testEventIsIgnoredIfUsernameIsNotPassedWithTheRequest()
    {
        $listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
        $listener($this->event);

        $this->assertNull($this->event->getResponse());
        $this->assertNull($this->tokenStorage->getToken());
    }

    public function testExitUserThrowsAuthenticationExceptionIfNoCurrentToken()
    {
        $this->expectException(AuthenticationCredentialsNotFoundException::class);
        $this->tokenStorage->setToken(null);
        $this->request->query->set('_switch_user', '_exit');
        $listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
        $listener($this->event);
    }

    
public function testListEndpoint(): void
    {
        $this->gateway->increment($this->userId, 'foo');
        $this->gateway->increment($this->userId, 'foo');
        $this->gateway->increment($this->userId, 'bar');

        $url = '/api/_action/increment/user_activity?cluster=' . $this->userId;
        $client = $this->getBrowser();
        $client->request('GET', $url);

        static::assertSame(200, $client->getResponse()->getStatusCode());

        $entries = json_decode((string) $client->getResponse()->getContent(), true, 512, \JSON_THROW_ON_ERROR);

        static::assertArrayHasKey('foo', $entries);
        static::assertEquals(2, $entries['foo']['count']);
        static::assertArrayHasKey('bar', $entries);
        static::assertEquals(1, $entries['bar']['count']);
    }

    public function testEndpointWithoutCluster(): void
    {
        
public function authorizeBrowser(KernelBrowser $browser): void
    {
        $authPayload = [
            'grant_type' => 'password',
            'client_id' => 'administration',
            'username' => $this->name,
            'password' => $this->password,
        ];

        $browser->request('POST', '/api/oauth/token', $authPayload);

        $data = json_decode((string) $browser->getResponse()->getContent(), true, 512, \JSON_THROW_ON_ERROR);

        if (!\array_key_exists('access_token', $data)) {
            throw new \RuntimeException(
                'No token returned from API: ' . ($data['errors'][0]['detail'] ?? 'unknown error' . print_r($data, true))
            );
        }

        if (!\array_key_exists('refresh_token', $data)) {
            throw new \RuntimeException(
                'No refresh_token returned from API: ' . ($data['errors'][0]['detail'] ?? 'unknown error')
            );
        }

    public function __construct(callable $listener)
    {
        $this->listener = $listener;
    }

    public function __invoke(RequestEvent $event): void
    {
        $startTime = microtime(true);
        ($this->listener)($event);
        $this->time = microtime(true) - $startTime;
        $this->response = $event->getResponse();
    }
}
Home | Imprint | This part of the site doesn't use cookies.