Request example

private MockObject&UserCheckerInterface $userChecker;
    private MockObject&AccessDecisionManagerInterface $accessDecisionManager;
    private Request $request;
    private RequestEvent $event;

    protected function setUp(): void
    {
        $this->tokenStorage = new TokenStorage();
        $this->userProvider = new InMemoryUserProvider(['kuba' => []]);
        $this->userChecker = $this->createMock(UserCheckerInterface::class);
        $this->accessDecisionManager = $this->createMock(AccessDecisionManagerInterface::class);
        $this->request = new Request();
        $this->event = new RequestEvent($this->createMock(HttpKernelInterface::class)$this->request, HttpKernelInterface::MAIN_REQUEST);
    }

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

    public function testEventIsIgnoredIfUsernameIsNotPassedWithTheRequest()
    {
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DataCollector\MemoryDataCollector;

class MemoryDataCollectorTest extends TestCase
{
    public function testCollect()
    {
        $collector = new MemoryDataCollector();
        $collector->collect(new Request()new Response());

        $this->assertIsInt($collector->getMemory());
        $this->assertIsInt($collector->getMemoryLimit());
        $this->assertSame('memory', $collector->getName());
    }

    /** @dataProvider getBytesConversionTestData */
    public function testBytesConversion($limit$bytes)
    {
        $collector = new MemoryDataCollector();
        $method = new \ReflectionMethod($collector, 'convertToBytes');
        
// Use the provided config for system.mail.interface settings.     $this->configFactory = $this->getConfigFactoryStub([
      'system.mail' => [
        'interface' => [],
      ],
      'system.site' => [
        'mail' => 'test@example.com',
      ],
    ]);

    $this->request = new Request();

    $this->requestStack = $this->prophesize(RequestStack::class);
    $this->requestStack->getCurrentRequest()
      ->willReturn($this->request);

    $container = new ContainerBuilder();
    $container->set('config.factory', $this->configFactory);
    $container->set('request_stack', $this->requestStack->reveal());
    \Drupal::setContainer($container);
  }

  
$this->app = $this->prophesize(HttpKernelInterface::class);
    $this->contentNegotiation = new StubNegotiationMiddleware($this->app->reveal());
  }

  /** * Tests the getContentType() method with AJAX iframe upload. * * @covers ::getContentType */
  public function testAjaxIframeUpload() {
    $request = new Request();
    $request->request->set('ajax_iframe_upload', '1');

    $this->assertSame('iframeupload', $this->contentNegotiation->getContentType($request));
  }

  /** * Tests the specifying a format via query parameters gets used. * * @covers ::getContentType */
  public function testFormatViaQueryParameter() {
    
$this->assertEquals($processedLogs[0]['priorityName'], 'DEBUG');
        $this->assertNull($processedLogs[0]['channel']);

        $this->assertInstanceOf(Data::class$processedLogs[0]['message']);
        $this->assertInstanceOf(Data::class$processedLogs[0]['context']);

        @unlink($path);
    }

    public function testWithMainRequest()
    {
        $mainRequest = new Request();
        $stack = new RequestStack();
        $stack->push($mainRequest);

        $logger = $this
            ->getMockBuilder(DebugLoggerInterface::class)
            ->onlyMethods(['countErrors', 'getLogs', 'clear'])
            ->getMock();
        $logger->expects($this->once())->method('countErrors')->with(null);
        $logger->expects($this->exactly(2))->method('getLogs')->with(null)->willReturn([]);

        $c = new LoggerDataCollector($logger, __DIR__.'/', $stack);

        
$session->method('save');
        $session->method('isStarted')->willReturn(true);

        if (isset($phpSessionOptions['samesite'])) {
            ini_set('session.cookie_samesite', $phpSessionOptions['samesite']);
        }
        session_set_cookie_params(0, $phpSessionOptions['path'] ?? null, $phpSessionOptions['domain'] ?? null, $phpSessionOptions['secure'] ?? null, $phpSessionOptions['httponly'] ?? null);

        $listener = new SessionListener(new Container(), false, $sessionOptions);
        $kernel = $this->createMock(HttpKernelInterface::class);

        $request = new Request();
        $listener->onKernelRequest(new RequestEvent($kernel$request, HttpKernelInterface::MAIN_REQUEST));

        $request->setSession($session);
        $response = new Response();
        $listener->onKernelResponse(new ResponseEvent($kernel$request, HttpKernelInterface::MAIN_REQUEST, $response));

        $cookies = $response->headers->getCookies();

        if ($sessionOptions['use_cookies'] ?? true) {
            $this->assertCount(1, $cookies);
            $this->assertSame('PHPSESSID', $cookies[0]->getName());
            
->getMock();
    $this->redirectDestination = $this->createMock('\Drupal\Core\Routing\RedirectDestinationInterface');

    $this->viewAjaxController = new ViewAjaxController($this->viewStorage, $this->executableFactory, $this->renderer, $this->currentPath, $this->redirectDestination);

    $element_info_manager = $this->createMock('\Drupal\Core\Render\ElementInfoManagerInterface');
    $element_info_manager->expects($this->any())
      ->method('getInfo')
      ->with('status_messages')
      ->willReturn([]);
    $request_stack = new RequestStack();
    $request_stack->push(new Request());
    $this->renderer = new Renderer(
      $this->createMock('\Drupal\Core\Controller\ControllerResolverInterface'),
      $this->createMock('\Drupal\Core\Theme\ThemeManagerInterface'),
      $element_info_manager,
      $this->createMock('\Drupal\Core\Render\PlaceholderGeneratorInterface'),
      $this->createMock('\Drupal\Core\Render\RenderCacheInterface'),
      $request_stack,
      [
        'required_cache_contexts' => [
          'languages:language_interface',
          'theme',
        ],


    public function testIsSuccessful()
    {
        $response = new Response();
        $this->assertTrue($response->isSuccessful());
    }

    public function testIsNotModified()
    {
        $response = new Response();
        $modified = $response->isNotModified(new Request());
        $this->assertFalse($modified);
    }

    public function testIsNotModifiedNotSafe()
    {
        $request = Request::create('/homepage', 'POST');

        $response = new Response();
        $this->assertFalse($response->isNotModified($request));
    }

    
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpClientKernel;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;

class HttpClientKernelTest extends TestCase
{
    public function testHandlePassesMaxRedirectsHttpClientOption()
    {
        $request = new Request();
        $request->attributes->set('http_client_options', ['max_redirects' => 50]);

        $response = $this->createMock(ResponseInterface::class);
        $response->expects($this->once())->method('getStatusCode')->willReturn(200);

        $client = $this->createMock(HttpClientInterface::class);
        $client
            ->expects($this->once())
            ->method('request')
            ->willReturnCallback(function Dstring $method, string $uri, array $options) use ($request$response) {
                $this->assertSame($request->getMethod()$method);
                
namespace Symfony\Component\HttpFoundation\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;

abstract class ResponseTestCase extends TestCase
{
    public function testNoCacheControlHeaderOnAttachmentUsingHTTPSAndMSIE()
    {
        // Check for HTTPS and IE 8         $request = new Request();
        $request->server->set('HTTPS', true);
        $request->server->set('HTTP_USER_AGENT', 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)');

        $response = $this->provideResponse();
        $response->headers->set('Content-Disposition', 'attachment; filename="fname.ext"');
        $response->prepare($request);

        $this->assertFalse($response->headers->has('Cache-Control'));

        // Check for IE 10 and HTTPS         $request->server->set('HTTP_USER_AGENT', 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)');

        
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Tests\Fixtures\Attribute\Bar;
use Symfony\Component\HttpKernel\Tests\Fixtures\Attribute\Baz;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\AttributeController;
use Symfony\Component\HttpKernel\Tests\TestHttpKernel;

class ControllerArgumentsEventTest extends TestCase
{
    public function testControllerArgumentsEvent()
    {
        $event = new ControllerArgumentsEvent(new TestHttpKernel()function D) {}['test']new Request(), HttpKernelInterface::MAIN_REQUEST);
        $this->assertEquals($event->getArguments()['test']);
    }

    public function testSetAttributes()
    {
        $controller = function D) {};
        $event = new ControllerArgumentsEvent(new TestHttpKernel()$controller['test']new Request(), HttpKernelInterface::MAIN_REQUEST);
        $event->setController($controller[]);

        $this->assertSame([]$event->getAttributes());
    }

    

        return new LoginFailureEvent($this->createMock(AuthenticationException::class)$this->createMock(AuthenticatorInterface::class)$this->requestStack->getCurrentRequest(), null, 'main', $passport);
    }

    private function createCheckPassportEvent($passport)
    {
        return new CheckPassportEvent($this->createMock(AuthenticatorInterface::class)$passport);
    }

    private function createRequest($ip = '192.168.1.0')
    {
        $request = new Request();
        $request->server->set('REMOTE_ADDR', $ip);

        return $request;
    }
}
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestFailure;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Test\Constraint\RequestAttributeValueSame;

class RequestAttributeValueSameTest extends TestCase
{
    public function testConstraint()
    {
        $request = new Request();
        $request->attributes->set('foo', 'bar');
        $constraint = new RequestAttributeValueSame('foo', 'bar');
        $this->assertTrue($constraint->evaluate($request, '', true));
        $constraint = new RequestAttributeValueSame('bar', 'foo');
        $this->assertFalse($constraint->evaluate($request, '', true));

        try {
            $constraint->evaluate($request);
        } catch (ExpectationFailedException $e) {
            $this->assertEquals("Failed asserting that the Request has attribute \"bar\" with value \"foo\".\n", TestFailure::exceptionToString($e));

            
$listener->onKernelView($event);
        self::assertFalse($event->hasResponse());

        $event = $this->createEventMock(null);

        $listener->onKernelView($event);
        self::assertFalse($event->hasResponse());
    }

    private function createEventMock(mixed $controllerResult): ViewEvent
    {
        return new ViewEvent($this->createMock(HttpKernelInterface::class)new Request(), HttpKernelInterface::MAIN_REQUEST, $controllerResult);
    }
}
/** * @covers ::onException */
  public function testOnException() {
    $form = ['#type' => 'form', '#build_id' => 'the_build_id'];
    $expected_form = $form + [
      '#build_id_old' => 'the_build_id',
    ];
    $form_state = new FormState();
    $exception = new FormAjaxException($form$form_state);

    $request = new Request([]['form_build_id' => 'the_build_id']);
    $commands = [];
    $response = new Response('');

    $this->formAjaxResponseBuilder->expects($this->once())
      ->method('buildResponse')
      ->with($request$expected_form$form_state$commands)
      ->willReturn($response);

    $this->assertResponseFromException($request$exception$response);
    $this->assertTrue($this->event->isAllowingCustomResponseCode());
    $this->assertSame(200, $this->event->getResponse()->getStatusCode());
  }
Home | Imprint | This part of the site doesn't use cookies.