setSession example

public function testHasSession()
    {
        $request = new Request();

        $this->assertFalse($request->hasSession());
        $this->assertFalse($request->hasSession(true));

        $request->setSessionFactory(function D) {});
        $this->assertTrue($request->hasSession());
        $this->assertFalse($request->hasSession(true));

        $request->setSession(new Session(new MockArraySessionStorage()));
        $this->assertTrue($request->hasSession());
        $this->assertTrue($request->hasSession(true));
    }

    public function testGetSession()
    {
        $request = new Request();

        $request->setSession(new Session(new MockArraySessionStorage()));
        $this->assertTrue($request->hasSession());

        
$controller = new UpdateController(
            $recoveryManager,
            $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');
        
/** * @internal */
class CartMergedSubscriberTest extends TestCase
{
    use IntegrationTestBehaviour;

    public function testMergedHintIsAdded(): void
    {
        $session = new Session(new MockArraySessionStorage());
        $request = new Request();
        $request->setSession($session);
        $requestStack = new RequestStack();
        $requestStack->push($request);

        $translator = $this->createMock(TranslatorInterface::class);
        $translator->expects(static::once())
            ->method('trans')
            ->with('checkout.cart-merged-hint')
            ->willReturn('checkout.cart-merged-hint');

        $subscriber = new CartMergedSubscriber($translator$requestStack);

        

        $event->getRequest()->attributes->set('_route', 'install');

        $listener($event);

        static::assertInstanceOf(RedirectResponse::class$event->getResponse());
    }

    public function getRequest(): Request
    {
        $request = new Request();
        $request->setSession(new Session(new MockArraySessionStorage()));

        return $request;
    }
}
return;
        }

        $request = $event->getRequest();
        if (!$request->hasSession()) {
            $request->setSessionFactory(function D) use ($request) {
                // Prevent calling `$this->getSession()` twice in case the Request (and the below factory) is cloned                 static $sess;

                if (!$sess) {
                    $sess = $this->getSession();
                    $request->setSession($sess);

                    /* * For supporting sessions in php runtime with runners like roadrunner or swoole, the session * cookie needs to be read from the cookie bag and set on the session storage. * * Do not set it when a native php session is active. */
                    if ($sess && !$sess->isStarted() && \PHP_SESSION_ACTIVE !== session_status()) {
                        $sessionId = $sess->getId() ?: $request->cookies->get($sess->getName(), '');
                        $sess->setId($sessionId);
                    }
                }
$tmpDir,
                '--no-interaction',
                '--no-ansi',
                '-v',
            ])
            ->willReturn(new StreamedResponse());

        $controller = new InstallController($recovery$responseGenerator$this->createMock(ReleaseInfoProvider::class));
        $controller->setContainer($this->getContainer());

        $request = new Request();
        $request->setSession(new Session(new MockArraySessionStorage()));
        $request->query->set('shopwareVersion', '6.4.10.0');

        $controller->run($request);

        (new Filesystem())->remove($tmpDir);
    }

    private function getContainer(): ContainerInterface
    {
        $container = new Container();

        
->willThrowException(new ConstraintViolationException(new ConstraintViolationList()[]));

        $response = $this->controller->register($request$dataBag$context);

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

    private function createRegisterRequest(): Request
    {
        $request = new Request();
        $request->attributes->set(RequestTransformer::STOREFRONT_URL, $_SERVER['APP_URL']);
        $request->setSession(new Session(new MockArraySessionStorage()));

        return $request;
    }
}

/** * @internal */
class RegisterControllerTestClass extends RegisterController
{
    use StorefrontControllerMockTrait;
}
/** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();

    $this->keyValue = $this->createMock('Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface');
    $this->lock = $this->createMock('Drupal\Core\Lock\LockBackendInterface');
    $this->requestStack = new RequestStack();
    $request = Request::createFromGlobals();
    $session = $this->createMock(SessionInterface::class);
    $request->setSession($session);
    $this->requestStack->push($request);
    $current_user = $this->createMock(AccountProxyInterface::class);

    $this->tempStore = new SharedTempStore($this->keyValue, $this->lock, $this->owner, $this->requestStack, $current_user, 604800);

    $this->ownObject = (object) [
      'data' => 'test_data',
      'owner' => $this->owner,
      'updated' => (int) $request->server->get('REQUEST_TIME'),
    ];

    
$fs->mkdir($tmpDir);
        $fs->dumpFile($tmpDir . '/symfony.lock', json_encode([], \JSON_THROW_ON_ERROR));

        static::assertTrue($recoveryManager->isFlexProject($tmpDir));
    }

    public function testGetPHPBinary(): void
    {
        $recoveryManager = new RecoveryManager();

        $request = new Request();
        $request->setSession(new Session(new MockArraySessionStorage()));
        $request->getSession()->set('phpBinary', 'php');

        static::assertSame('php', $recoveryManager->getPHPBinary($request));
    }

    private function prepareShopware(Filesystem $fs, string $tmpDir, string $version = '6.4.10.0'): void
    {
        $fs->mkdir($tmpDir);
        $fs->mkdir($tmpDir . '/public');

        $_SERVER['SCRIPT_FILENAME'] = $tmpDir . '/public/shopware-installer.phar.php';
        
$this->requestStack = new RequestStack();
    $this->requestStack->push($this->request);

    $this->session = $this->getMockBuilder('\Symfony\Component\HttpFoundation\Session\SessionInterface')
      ->getMock();
  }

  /** * @covers ::getContext */
  public function testSameContextForSameSession() {
    $this->request->setSession($this->session);
    $cache_context = new SessionCacheContext($this->requestStack);

    $session_id = 'aSebeZ52bbM6SvADurQP89SFnEpxY6j8';
    $this->session->expects($this->exactly(2))
      ->method('getId')
      ->willReturn($session_id);

    $context1 = $cache_context->getContext();
    $context2 = $cache_context->getContext();
    $this->assertSame($context1$context2);
    $this->assertStringNotContainsString($session_id$context1, 'Session ID not contained in cache context');
  }

        }
    }

    /** * @param array<string, mixed> $params */
    private function createRequest(string $route, array $params = []): Request
    {
        $request = new Request();
        $request->query->add($params);
        $request->setSession($this->getSession());
        $request->attributes->add([
            '_route' => $route,
            SalesChannelRequest::ATTRIBUTE_IS_SALES_CHANNEL_REQUEST => true,
            PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID => $this->ids->get('sales-channel'),
            PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT => $this->salesChannelContext,
            RequestTransformer::STOREFRONT_URL => 'http://localhost',
        ]);

        return $request;
    }

    
$handler->setFirewallName('admin');
        }
        $this->assertSame('http://localhost'.$redirectedUrl$handler->onAuthenticationSuccess($request$token)->getTargetUrl());
    }

    public function testRequestRedirectionsWithTargetPathInSessions()
    {
        $session = $this->createMock(SessionInterface::class);
        $session->expects($this->once())->method('get')->with('_security.admin.target_path')->willReturn('/admin/dashboard');
        $session->expects($this->once())->method('remove')->with('_security.admin.target_path');
        $requestWithSession = Request::create('/');
        $requestWithSession->setSession($session);

        $urlGenerator = $this->createMock(UrlGeneratorInterface::class);
        $urlGenerator->expects($this->any())->method('generate')->willReturn('http://localhost/login');
        $httpUtils = new HttpUtils($urlGenerator);
        $token = $this->createMock(TokenInterface::class);
        $handler = new DefaultAuthenticationSuccessHandler($httpUtils);
        $handler->setFirewallName('admin');

        $this->assertSame('http://localhost/admin/dashboard', $handler->onAuthenticationSuccess($requestWithSession$token)->getTargetUrl());
    }

    
use Symfony\Contracts\Service\ServiceLocatorTrait;

class UsageTrackingTokenStorageTest extends TestCase
{
    public function testGetSetToken()
    {
        $sessionAccess = 0;
        $sessionLocator = new class(['request_stack' => function D) use (&$sessionAccess) {
            $session = $this->createMock(SessionInterface::class);

            $request = new Request();
            $request->setSession($session);
            $requestStack = $this->getMockBuilder(RequestStack::class)->onlyMethods(['getSession'])->getMock();
            $requestStack->push($request);
            $requestStack->expects($this->any())->method('getSession')->willReturnCallback(function D) use ($session, &$sessionAccess) {
                ++$sessionAccess;

                $session->expects($this->once())
                        ->method('getMetadataBag');

                return $session;
            });

            
$request = Request::create('/');
        $request->attributes->set('last', 'last');
        $controller = [new NullableController(), 'action'];

        $this->assertEquals([null, null, 'value', 'last'], self::getResolver()->getArguments($request$controller));
    }

    public function testGetSessionArguments()
    {
        $session = new Session(new MockArraySessionStorage());
        $request = Request::create('/');
        $request->setSession($session);
        $controller = $this->controllerWithSession(...);

        $this->assertEquals([$session], self::getResolver()->getArguments($request$controller));
    }

    public function testGetSessionArgumentsWithExtendedSession()
    {
        $session = new ExtendingSession(new MockArraySessionStorage());
        $request = Request::create('/');
        $request->setSession($session);
        $controller = $this->controllerWithExtendingSession(...);

        
public function testCreateRequestWithAbsoluteUrl()
    {
        $utils = new HttpUtils($this->createMock(UrlGeneratorInterface::class));
        $subRequest = $utils->createRequest($this->getRequest(), 'http://symfony.com/');

        $this->assertEquals('/', $subRequest->getPathInfo());
    }

    public function testCreateRequestPassesSessionToTheNewRequest()
    {
        $request = $this->getRequest();
        $request->setSession($session = $this->createMock(SessionInterface::class));

        $utils = new HttpUtils($this->getUrlGenerator());
        $subRequest = $utils->createRequest($request, '/foobar');

        $this->assertSame($session$subRequest->getSession());
    }

    /** * @dataProvider provideSecurityRequestAttributes */
    public function testCreateRequestPassesSecurityRequestAttributesToTheNewRequest($attribute)
    {
Home | Imprint | This part of the site doesn't use cookies.