You are here

class R4032LoginSubscriberTest in Redirect 403 to User Login 8

Same name and namespace in other branches
  1. 2.x tests/src/Unit/R4032LoginSubscriberTest.php \Drupal\Tests\r4032login\Unit\R4032LoginSubscriberTest

@coversDefaultClass \Drupal\r4032login\EventSubscriber\R4032LoginSubscriber @group r4032login

Hierarchy

Expanded class hierarchy of R4032LoginSubscriberTest

File

tests/src/Unit/R4032LoginSubscriberTest.php, line 21

Namespace

Drupal\Tests\r4032login\Unit
View source
class R4032LoginSubscriberTest extends UnitTestCase {

  /**
   * The mocked HTTP kernel.
   *
   * @var \Symfony\Component\HttpKernel\HttpKernelInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $kernel;

  /**
   * The mocked configuration factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $configFactory;

  /**
   * The mocked current user.
   *
   * @var \Drupal\Core\Session\AccountInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $currentUser;

  /**
   * The mocked request stack service.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $requestStack;

  /**
   * The path matcher.
   *
   * @var \Drupal\Core\Path\PathMatcherInterface
   */
  protected $pathMatcher;

  /**
   * An event dispatcher instance to use for map events.
   *
   * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
   */
  protected $eventDispatcher;

  /**
   * The mocked unrouted URL assembler.
   *
   * @var \Drupal\Core\Utility\UnroutedUrlAssemblerInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $urlAssembler;

  /**
   * The mocked router.
   *
   * @var \Drupal\Tests\Core\Routing\TestRouterInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $router;

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    $this->kernel = $this
      ->getMock('Symfony\\Component\\HttpKernel\\HttpKernelInterface');
    $this->configFactory = $this
      ->getConfigFactoryStub([
      'r4032login.settings' => [
        'display_denied_message' => TRUE,
        'access_denied_message' => 'Access denied. You must log in to view this page.',
        'access_denied_message_type' => 'error',
        'redirect_authenticated_users_to' => '',
        'user_login_path' => '/user/login',
        'default_redirect_code' => 302,
        'match_noredirect_pages' => '',
      ],
    ]);
    $this->currentUser = $this
      ->getMock('Drupal\\Core\\Session\\AccountInterface');
    $this->requestStack = new RequestStack();
    $this->requestStack
      ->push(new Request());
    $this->pathMatcher = $this
      ->getMock('\\Drupal\\Core\\Path\\PathMatcherInterface');
    $this->eventDispatcher = $this
      ->getMock('\\Symfony\\Component\\EventDispatcher\\EventDispatcherInterface');
    $this->urlAssembler = $this
      ->getMock('Drupal\\Core\\Utility\\UnroutedUrlAssemblerInterface');
    $this->urlAssembler
      ->expects($this
      ->any())
      ->method('assemble')
      ->will($this
      ->returnArgument(0));
    $this->router = $this
      ->getMock('Drupal\\Tests\\Core\\Routing\\TestRouterInterface');
    $container = new ContainerBuilder();
    $container
      ->set('path.validator', $this
      ->getMock('Drupal\\Core\\Path\\PathValidatorInterface'));
    $container
      ->set('router.no_access_checks', $this->router);
    $container
      ->set('unrouted_url_assembler', $this->urlAssembler);
    \Drupal::setContainer($container);
  }

  /**
   * Tests constructor for the R4032LoginSubscriber instance.
   *
   * @covers ::__construct
   */
  public function testConstruct() {
    $r4032login = new R4032LoginSubscriber($this->configFactory, $this->currentUser, $this->requestStack, $this->pathMatcher, $this->eventDispatcher);
    $this
      ->assertInstanceOf('\\Drupal\\r4032login\\EventSubscriber\\R4032LoginSubscriber', $r4032login);
  }

  /**
   * Tests RedirectResponse for anonymous users.
   *
   * @param Request $request
   *   The request object.
   * @param array $config_values
   *   The configuration values.
   * @param string $expected_url
   *   The expected target URL.
   *
   * @covers ::on403
   *
   * @dataProvider providerRequests
   */
  public function testAnonymousRedirect(Request $request, array $config_values, $expected_url) {
    $config = $this
      ->getConfigFactoryStub([
      'r4032login.settings' => $config_values,
    ]);
    $this->currentUser
      ->expects($this
      ->any())
      ->method('isAnonymous')
      ->willReturn(TRUE);
    $r4032login = new R4032LoginSubscriber($config, $this->currentUser, $this->requestStack, $this->pathMatcher, $this->eventDispatcher);
    $event = new GetResponseForExceptionEvent($this->kernel, $request, HttpKernelInterface::MASTER_REQUEST, new AccessDeniedHttpException());
    $dispatcher = new EventDispatcher();
    $dispatcher
      ->addListener(KernelEvents::EXCEPTION, [
      $r4032login,
      'on403',
    ]);
    $dispatcher
      ->dispatch(KernelEvents::EXCEPTION, $event);
    $response = $event
      ->getResponse();
    $this
      ->assertInstanceOf('\\Symfony\\Component\\HttpFoundation\\RedirectResponse', $response);
    $this
      ->assertEquals($config_values['default_redirect_code'], $response
      ->getStatusCode());
    $this
      ->assertEquals(Url::fromUserInput($config_values['user_login_path'])
      ->toString(), $response
      ->getTargetUrl());
  }

  /**
   * Tests RedirectResponse for authenticated users.
   *
   * @param Request $request
   *   The request object.
   * @param array $config_values
   *   The configuration values.
   * @param string $expected_url
   *   The expected target URL.
   *
   * @covers ::on403
   *
   * @dataProvider providerRequests
   */
  public function testAuthenticatedRedirect(Request $request, array $config_values, $expected_url) {
    $config = $this
      ->getConfigFactoryStub([
      'r4032login.settings' => $config_values,
    ]);
    $this->currentUser
      ->expects($this
      ->any())
      ->method('isAuthenticated')
      ->willReturn(TRUE);
    $r4032login = new R4032LoginSubscriber($config, $this->currentUser, $this->requestStack, $this->pathMatcher, $this->eventDispatcher);
    $event = new GetResponseForExceptionEvent($this->kernel, $request, HttpKernelInterface::MASTER_REQUEST, new AccessDeniedHttpException());
    $dispatcher = new EventDispatcher();
    $dispatcher
      ->addListener(KernelEvents::EXCEPTION, [
      $r4032login,
      'on403',
    ]);
    $dispatcher
      ->dispatch(KernelEvents::EXCEPTION, $event);
    $response = $event
      ->getResponse();
    $this
      ->assertInstanceOf('\\Symfony\\Component\\HttpFoundation\\RedirectResponse', $response);
    $this
      ->assertEquals($config_values['default_redirect_code'], $response
      ->getStatusCode());
    $this
      ->assertEquals($expected_url, $response
      ->getTargetUrl());
  }

  /**
   * Tests the listener type for event subscriber exception events.
   *
   * @covers ::getSubscribedEvents
   */
  public function testGetSubscribedEvents() {
    $expected = [
      KernelEvents::EXCEPTION => [
        [
          'onException',
          0,
        ],
      ],
    ];
    $actual = R4032LoginSubscriber::getSubscribedEvents();
    $this
      ->assertSame($expected, $actual);
  }

  /**
   * Provides requests, config, and expected paths to ::on403().
   *
   * @return array
   *   An array of Request objects, configuration values, and expected paths.
   */
  public function providerRequests() {
    return [
      [
        new Request([
          'destination' => 'test',
        ]),
        [
          'display_denied_message' => TRUE,
          'access_denied_message' => 'Access denied. You must log in to view this page.',
          'access_denied_message_type' => 'error',
          'redirect_authenticated_users_to' => '/user/login',
          'user_login_path' => '/user/login',
          'default_redirect_code' => 302,
          'match_noredirect_pages' => '',
        ],
        'base:user/login',
      ],
      [
        new Request([
          'destination' => 'test',
        ]),
        [
          'display_denied_message' => TRUE,
          'access_denied_message' => 'Access denied. You must log in to view this page.',
          'access_denied_message_type' => 'error',
          'redirect_authenticated_users_to' => '/admin',
          'user_login_path' => '/user/login',
          'default_redirect_code' => 302,
          'match_noredirect_pages' => '',
        ],
        'base:admin',
      ],
    ];
  }

  /**
   * Provides predefined and SPL exception events to ::on403().
   *
   * @return array
   *   An array of GetResponseForExceptionEvent exception events.
   */
  public function providerInvalidExceptions() {
    $kernel = $this
      ->getMock('Symfony\\Component\\HttpKernel\\HttpKernelInterface');
    $exceptions = [];
    foreach (get_declared_classes() as $name) {
      $class = new \ReflectionClass($name);
      if ($class
        ->isSubclassOf('Exception')) {
        $exceptions[] = [
          new GetResponseForExceptionEvent($kernel, new Request(), HttpKernelInterface::MASTER_REQUEST, $this
            ->getMockBuilder($name)
            ->disableOriginalConstructor()
            ->getMock()),
        ];
      }
    }
    return $exceptions;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
PhpunitCompatibilityTrait::getMock Deprecated public function Returns a mock object for the specified class using the available method.
PhpunitCompatibilityTrait::setExpectedException Deprecated public function Compatibility layer for PHPUnit 6 to support PHPUnit 4 code.
R4032LoginSubscriberTest::$configFactory protected property The mocked configuration factory.
R4032LoginSubscriberTest::$currentUser protected property The mocked current user.
R4032LoginSubscriberTest::$eventDispatcher protected property An event dispatcher instance to use for map events.
R4032LoginSubscriberTest::$kernel protected property The mocked HTTP kernel.
R4032LoginSubscriberTest::$pathMatcher protected property The path matcher.
R4032LoginSubscriberTest::$requestStack protected property The mocked request stack service.
R4032LoginSubscriberTest::$router protected property The mocked router.
R4032LoginSubscriberTest::$urlAssembler protected property The mocked unrouted URL assembler.
R4032LoginSubscriberTest::providerInvalidExceptions public function Provides predefined and SPL exception events to ::on403().
R4032LoginSubscriberTest::providerRequests public function Provides requests, config, and expected paths to ::on403().
R4032LoginSubscriberTest::setUp protected function Overrides UnitTestCase::setUp
R4032LoginSubscriberTest::testAnonymousRedirect public function Tests RedirectResponse for anonymous users.
R4032LoginSubscriberTest::testAuthenticatedRedirect public function Tests RedirectResponse for authenticated users.
R4032LoginSubscriberTest::testConstruct public function Tests constructor for the R4032LoginSubscriber instance.
R4032LoginSubscriberTest::testGetSubscribedEvents public function Tests the listener type for event subscriber exception events.
UnitTestCase::$randomGenerator protected property The random generator.
UnitTestCase::$root protected property The app root. 1
UnitTestCase::assertArrayEquals protected function Asserts if two arrays are equal by sorting them first.
UnitTestCase::getBlockMockWithMachineName Deprecated protected function Mocks a block with a block plugin. 1
UnitTestCase::getClassResolverStub protected function Returns a stub class resolver.
UnitTestCase::getConfigFactoryStub public function Returns a stub config factory that behaves according to the passed array.
UnitTestCase::getConfigStorageStub public function Returns a stub config storage that returns the supplied configuration.
UnitTestCase::getContainerWithCacheTagsInvalidator protected function Sets up a container with a cache tags invalidator.
UnitTestCase::getRandomGenerator protected function Gets the random generator for the utility methods.
UnitTestCase::getStringTranslationStub public function Returns a stub translation manager that just returns the passed string.
UnitTestCase::randomMachineName public function Generates a unique random string containing letters and numbers.