getStatusCode example

$storeClientMock = $this->createMock(StoreClient::class);
        $storeClientMock->expects(static::once())
            ->method('loginWithShopwareId')
            ->with('j.doe@shopware.com', 'v3rys3cr3t');

        $storeController = $this->getStoreController($storeClientMock);

        $response = $storeController->login($request$context);

        static::assertInstanceOf(JsonResponse::class$response);
        static::assertSame(200, $response->getStatusCode());
    }

    public function testLoginWithInvalidCredentials(): void
    {
        $request = new Request([][
            'shopwareId' => 'j.doe@shopware.com',
            'password' => 'v3rys3cr3t',
        ]);

        /** @var UserEntity $adminUser */
        $adminUser = $this->userRepository->search(new Criteria()$this->defaultContext)->first();

        
throw $e;
        }

        $response = $event->getResponse();

        // the developer asked for a specific status code         if (!$event->isAllowingCustomResponseCode() && !$response->isClientError() && !$response->isServerError() && !$response->isRedirect()) {
            // ensure that we actually have an error response             if ($e instanceof HttpExceptionInterface) {
                // keep the HTTP status code and headers                 $response->setStatusCode($e->getStatusCode());
                $response->headers->add($e->getHeaders());
            } else {
                $response->setStatusCode(500);
            }
        }

        try {
            return $this->filterResponse($response$request$type);
        } catch (\Throwable $e) {
            if ($e instanceof \Error && !$this->handleAllThrowables) {
                throw $e;
            }
/** * @internal * * @covers \Shopware\Core\Content\ProductExport\ProductExportException */
class ProductExportExceptionTest extends TestCase
{
    public function testTemplateBodyNotSet(): void
    {
        $exception = ProductExportException::templateBodyNotSet();
        static::assertSame(Response::HTTP_BAD_REQUEST, $exception->getStatusCode());
        static::assertSame('PRODUCT_EXPORT__TEMPLATE_BODY_NOT_SET', $exception->getErrorCode());

        static::expectException(ProductExportException::class);

        throw $exception;
    }

    /** * @DisabledFeatures(features={"v6.6.0.0"}) */
    public function testRenderFooterException(): void
    {
public function testCanReadWithPermission(): void
    {
        $this->loadAppsFromDir(self::$fixturesPath . '/test');

        $browser = $this->createClient();
        $this->authorizeBrowserWithIntegrationByAppName($this->getBrowser(), 'test');

        $browser->request('GET', '/api/product');
        $response = $browser->getResponse();

        static::assertIsString($response->getContent());
        static::assertEquals(200, $response->getStatusCode()$response->getContent());
    }

    public function testCantReadWithoutPermission(): void
    {
        $this->loadAppsFromDir(self::$fixturesPath . '/test');

        $browser = $this->createClient();
        $this->authorizeBrowserWithIntegrationByAppName($browser, 'test');

        $browser->request('GET', '/api/media');

        
public function testAddressBook(): void
    {
        $context = Generator::createSalesChannelContext();
        $request = new Request();
        $dataBag = new RequestDataBag();

        $customer = new CustomerEntity();
        $customer->setId(Uuid::randomHex());

        $response = $this->controller->addressBook($request$dataBag$context$customer);
        static::assertEquals(Response::HTTP_OK, $response->getStatusCode());

        $renderParams = $this->controller->renderStorefrontParameters;

        static::assertArrayHasKey('messages', $renderParams);
        static::assertCount(0, $renderParams['messages']);
        static::assertArrayHasKey('page', $renderParams);
        static::assertArrayNotHasKey('formViolations', $renderParams);
        static::assertArrayNotHasKey('postedData', $renderParams);
    }

    public function testAddressBookWithConstraintViolation(): void
    {

class SystemGenerateJwtSecretCommandTest extends TestCase
{
    public function testMissingPassphrase(): void
    {
        $tester = new CommandTester(new SystemGenerateJwtSecretCommand(
            __DIR__,
            $this->createMock(JwtCertificateGenerator::class)
        ));

        $tester->execute(['--jwt-passphrase' => false]);
        static::assertSame(Command::FAILURE, $tester->getStatusCode());
        static::assertStringContainsString('Passphrase is invalid', $tester->getDisplay());
    }

    public function testUseEnv(): void
    {
        $tester = new CommandTester(new SystemGenerateJwtSecretCommand(
            __DIR__,
            $this->getGenerator()
        ));

        $tester->execute(['--use-env' => true]);
        
$request = Request::create('/test');
    $request->setRequestFormat('json');

    $e = new MethodNotAllowedHttpException(['POST', 'PUT'], 'test message');
    $event = new ExceptionEvent($kernel->reveal()$request, HttpKernelInterface::MAIN_REQUEST, $e);
    $subscriber = new DefaultExceptionSubscriber(new Serializer([][new JsonEncoder()])[]);
    $subscriber->on4xx($event);
    $response = $event->getResponse();

    $this->assertInstanceOf(Response::class$response);
    $this->assertEquals('{"message":"test message"}', $response->getContent());
    $this->assertEquals(405, $response->getStatusCode());
    $this->assertEquals('POST, PUT', $response->headers->get('Allow'));
    $this->assertEquals('application/json', $response->headers->get('Content-Type'));
  }

}
$endpoint = sprintf('https://%s/v1/events/trigger', $this->getEndpoint());
        $response = $this->client->request('POST', $endpoint[
            'body' => $body,
            'headers' => [
                'Authorization' => sprintf('ApiKey %s', $this->apiKey),
                'Content-Type' => 'application/json',
            ],
        ]);

        try {
            $statusCode = $response->getStatusCode();
        } catch (TransportExceptionInterface $e) {
            throw new TransportException('Could not reach the remote Novu server.', $response, 0, $e);
        }

        if (201 !== $statusCode) {
            $originalContent = $message->getSubject();
            $result = $response->toArray(false);
            $error = $result['message'];
            throw new TransportException(sprintf('Unable to post the Novu message: "%s" (%d: "%s").', $originalContent$statusCode$error)$response);
        }

        
$customerCollection = new CustomerCollection($customers);
            $this->setRestorerReturn();
            $this->setSearchReturn($context$customerCollection);
            $this->setCustomerGroupSearchReturn($context);
        }

        if ($errorMessage !== null && $expectedResCode === null) {
            static::expectExceptionMessage($errorMessage);
        }

        $res = $this->controllerMock->accept($request$context);
        static::assertSame($expectedResCode$res->getStatusCode());
    }

    /** * @param CustomerEntity[] $customers * * @dataProvider getRegistrationValues * * @throws Exception */
    public function testGroupRegistrationDeclineMatches(?int $expectedResCode, ?array $customers, Request $request, ?string $errorMessage): void
    {
        
return $fn($request$options)
            ->then(function DResponseInterface $response) use ($request$options) {
                return $this->checkRedirect($request$options$response);
            });
    }

    /** * @return ResponseInterface|PromiseInterface */
    public function checkRedirect(RequestInterface $request, array $options, ResponseInterface $response)
    {
        if (\strpos((string) $response->getStatusCode(), '3') !== 0
            || !$response->hasHeader('Location')
        ) {
            return $response;
        }

        $this->guardMax($request$response$options);
        $nextRequest = $this->modifyRequest($request$options$response);

        // If authorization is handled by curl, unset it if URI is cross-origin.         if (Psr7\UriComparator::isCrossOrigin($request->getUri()$nextRequest->getUri()) && defined('\CURLOPT_HTTPAUTH')) {
            unset(
                
$format = $request->getRequestFormat();
    $content = ['message' => $exception->getMessage()];
    $encoded_content = $this->serializer->serialize($content$format);
    $headers = $exception->getHeaders();

    // Add the MIME type from the request to send back in the header.     $headers['Content-Type'] = $request->getMimeType($format);

    // If the exception is cacheable, generate a cacheable response.     if ($exception instanceof CacheableDependencyInterface) {
      $response = new CacheableResponse($encoded_content$exception->getStatusCode()$headers);
      $response->addCacheableDependency($exception);
    }
    else {
      $response = new Response($encoded_content$exception->getStatusCode()$headers);
    }

    $event->setResponse($response);
  }

}
public function testRedirectOn404() {
    \Drupal::configFactory()->getEditable('system.site')
      ->set('page.404', '/test-http-response-exception/' . Response::HTTP_PERMANENTLY_REDIRECT)
      ->save();

    /** @var \Symfony\Component\HttpKernel\HttpKernelInterface $http_kernel */
    $http_kernel = \Drupal::service('http_kernel');

    // Foo doesn't exist, so this triggers the 404 page.     $request = Request::create('/foo');
    $response = $http_kernel->handle($request);
    $this->assertEquals(Response::HTTP_PERMANENTLY_REDIRECT, $response->getStatusCode());
  }

}
protected function doRequest(object $request): Response
    {
        $headers = $this->getHeaders($request);
        [$body$extraHeaders] = $this->getBodyAndExtraHeaders($request$headers);

        $response = $this->client->request($request->getMethod()$request->getUri()[
            'headers' => array_merge($headers$extraHeaders),
            'body' => $body,
            'max_redirects' => 0,
        ]);

        return new Response($response->getContent(false)$response->getStatusCode()$response->getHeaders(false));
    }

    /** * @return array [$body, $headers] */
    private function getBodyAndExtraHeaders(Request $request, array $headers): array
    {
        if (\in_array($request->getMethod()['GET', 'HEAD']) && !isset($headers['content-type'])) {
            return ['', []];
        }

        
$this->createMock(ReleaseInfoProvider::class),
            $this->createMock(FlexMigrator::class),
            $this->createMock(StreamedCommandResponseGenerator::class),
        );

        $controller->setContainer($this->getContainer());

        $request = new Request();
        $request->setSession(new Session(new MockArraySessionStorage()));
        $response = $controller->index($request);

        static::assertSame(Response::HTTP_FOUND, $response->getStatusCode());
        static::assertSame('configure', $response->headers->get('location'));
    }

    public function testRedirectToFinishWhenNoUpdateThere(): void
    {
        $recoveryManager = $this->createMock(RecoveryManager::class);

        $recoveryManager->method('getShopwareLocation')->willReturn('/path/to/shopware');
        $recoveryManager->method('getCurrentShopwareVersion')->willReturn('6.4.18.0');

        $controller = new UpdateController(
            
$triggerFlowController = new TriggerFlowController(new EventDispatcher()$appFlowEventRepository);
        $triggerFlowController->trigger('custom.checkout.event', $request$context);
    }

    public function testTriggerWithInvalidAware(): void
    {
        $request = new Request();
        $request->setMethod('POST');
        $context = Context::createDefaultContext();

        $response = $this->triggerFlowController->trigger('custom.checkout.event', $request$context);
        static::assertEquals(Response::HTTP_OK, $response->getStatusCode());
        static::assertIsString($response->getContent());
        static::assertEquals('The trigger `custom.checkout.event`successfully dispatched!', json_decode($response->getContent(), true)['message']);
    }

    public function testTriggerWithValidAware(): void
    {
        $request = new Request();
        $context = Context::createDefaultContext();

        $response = $this->triggerFlowController->trigger('custom.checkout.event', $request$context);
        static::assertEquals(Response::HTTP_OK, $response->getStatusCode());
        
Home | Imprint | This part of the site doesn't use cookies.