You are here

class CasRedirectorTest in CAS 8

Same name and namespace in other branches
  1. 2.x tests/src/Unit/Service/CasRedirectorTest.php \Drupal\Tests\cas\Unit\Service\CasRedirectorTest

Cas Redirector Unit Tests.

@group cas

@coversDefaultClass \Drupal\cas\Service\CasRedirector

Hierarchy

Expanded class hierarchy of CasRedirectorTest

File

tests/src/Unit/Service/CasRedirectorTest.php, line 22

Namespace

Drupal\Tests\cas\Unit\Service
View source
class CasRedirectorTest extends UnitTestCase {

  /**
   * Mock Cas Helper.
   *
   * @var \Drupal\cas\Service\CasHelper|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $casHelper;

  /**
   * Mock URL Generator.
   *
   * @var \Drupal\Core\Routing\UrlGeneratorInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $urlGenerator;

  /**
   * The mocked event dispatcher.
   *
   * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $eventDispatcher;

  /**
   * The mocked config factory service.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface|\PHPUnit\Framework\MockObject\MockBuilder
   */
  protected $configFactory;

  /**
   * Storage for events during tests.
   *
   * @var array
   */
  protected $events;

  /**
   * {@inheritdoc}
   */
  public function setUp() {
    parent::setUp();
    $this->configFactory = $this
      ->getConfigFactoryStub([
      'cas.settings' => [
        'server.hostname' => 'example-server.com',
        'server.protocol' => 'https',
        'server.port' => 443,
        'server.path' => '/cas',
        'server.version' => '2.0',
        'server.verify' => CasHelper::CA_DEFAULT,
        'server.cert' => 'foo',
        'advanced.connection_timeout' => 30,
      ],
    ]);
    $this->casHelper = $this
      ->getMockBuilder('\\Drupal\\cas\\Service\\CasHelper')
      ->disableOriginalConstructor()
      ->getMock();
    $this->urlGenerator = $this
      ->createMock('\\Drupal\\Core\\Routing\\UrlGeneratorInterface');
    $this->urlGenerator
      ->method('generate')
      ->willReturnCallback([
      $this,
      'getServiceUrl',
    ]);

    // Mock event dispatcher to dispatch events.
    $this->eventDispatcher = $this
      ->getMockBuilder('\\Symfony\\Component\\EventDispatcher\\EventDispatcherInterface')
      ->disableOriginalConstructor()
      ->getMock();

    // We have to mock the cache context manager which is called when we
    // add cache contexts to a cacheable metadata.
    $cache_contexts_manager = $this
      ->getMockBuilder('Drupal\\Core\\Cache\\Context\\CacheContextsManager')
      ->disableOriginalConstructor()
      ->getMock();
    $cache_contexts_manager
      ->method('assertValidTokens')
      ->willReturn(TRUE);
    $container = new Container();
    $container
      ->set('cache_contexts_manager', $cache_contexts_manager);
    \Drupal::setContainer($container);
  }

  /**
   * Get a service URL.
   *
   * @param string $route
   *   The route name.
   * @param array $parameters
   *   The service URL parameters.
   *
   * @return string
   *   The constructed service URL.
   */
  public function getServiceUrl($route, array $parameters = NULL) {
    if ($parameters) {
      return 'http://example.com/casservice?' . UrlHelper::buildQuery($parameters);
    }
    else {
      return 'http://example.com/casservice';
    }
  }

  /**
   * Dispatch an event.
   *
   * @param string $event_name
   *   Name of event fired.
   * @param \Drupal\cas\Event\CasPreRedirectEvent $event
   *   Event fired.
   */
  public function dispatchEvent($event_name, CasPreRedirectEvent $event) {
    $this->events[$event_name] = $event;
    $data = $event
      ->getCasRedirectData();
    $data
      ->setParameter('strong_auth', 'true');
    $data
      ->forceRedirection();
  }

  /**
   * Test buildRedirectResponse.
   */
  public function testBuildRedirectResponse() {
    $cas_redirector = new CasRedirector($this->casHelper, $this->eventDispatcher, $this->urlGenerator, $this->configFactory);
    $cas_data = new CasRedirectData();
    $cas_data
      ->forceRedirection();
    $response = $cas_redirector
      ->buildRedirectResponse($cas_data, TRUE);

    // Make sure that are url begins with the login redirection.
    $this
      ->assertEquals('https://example-server.com/cas/login?service=http%3A//example.com/casservice', $response
      ->getTargetUrl());
    $this
      ->assertInstanceOf('\\Drupal\\core\\Routing\\TrustedRedirectResponse', $response);

    // Validate redirection control.
    $cas_data
      ->preventRedirection();
    $response = $cas_redirector
      ->buildRedirectResponse($cas_data);
    $this
      ->assertNull($response, 'Return null for no response');
    $cas_data
      ->forceRedirection();
    $response = $cas_redirector
      ->buildRedirectResponse($cas_data);
    $this
      ->assertNotNull($response, 'Found response for redirect data');

    // Make sure setting of normal parameters works.
    $cas_data
      ->setParameter('strong_auth', 'true');
    $response = $cas_redirector
      ->buildRedirectResponse($cas_data);
    $this
      ->assertEquals('https://example-server.com/cas/login?strong_auth=true&service=http%3A//example.com/casservice', $response
      ->getTargetUrl(), 'Target URL with parameters');
    $cas_data
      ->setParameter('strong_auth', NULL);

    // Verfiy setting of gateway parameters.
    $cas_data
      ->setServiceParameter('returnto', 'node/1');
    $response = $cas_redirector
      ->buildRedirectResponse($cas_data);
    $this
      ->assertEquals('https://example-server.com/cas/login?service=http%3A//example.com/casservice%3Freturnto%3Dnode/1', $response
      ->getTargetUrl(), 'Service parameters present');

    // Verify proper redirector type.
    $cas_data
      ->setIsCacheable(TRUE);

    /** @var \Drupal\Core\Routing\TrustedRedirectResponse $response */
    $response = $cas_redirector
      ->buildRedirectResponse($cas_data);
    $this
      ->assertInstanceOf('\\Drupal\\core\\Routing\\TrustedRedirectResponse', $response);
    $data = $response
      ->getCacheableMetadata();
    $tags = $data
      ->getCacheTags();
    $this
      ->assertContains('config:cas.settings', $tags, 'Cache Tags set');

    // Verify proper redirector type.
    $cas_data
      ->setIsCacheable(FALSE);
    $response = $cas_redirector
      ->buildRedirectResponse($cas_data);
    $this
      ->assertInstanceOf('\\Drupal\\cas\\CasRedirectResponse', $response, 'Non-cacheable response');
  }

  /**
   * Tests the events dispatched by the listener.
   *
   * @covers ::buildRedirectResponse
   */
  public function testEventsDispatched() {

    // Mock up listener on dispatched event.
    $this->eventDispatcher
      ->method('dispatch')
      ->willReturnCallback([
      $this,
      'dispatchEvent',
    ]);
    $this->events = [];

    // Fire the redirection event.
    $cas_redirector = new CasRedirector($this->casHelper, $this->eventDispatcher, $this->urlGenerator, $this->configFactory);
    $cas_data = new CasRedirectData();
    $response = $cas_redirector
      ->buildRedirectResponse($cas_data);

    // Verfiy that the event fired and the redirector was appropriately altered.
    $this
      ->assertEquals(1, count($this->events), 'One Event was fired');
    $this
      ->assertEquals('https://example-server.com/cas/login?strong_auth=true&service=http%3A//example.com/casservice', $response
      ->getTargetUrl(), 'Altered parameters');
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CasRedirectorTest::$casHelper protected property Mock Cas Helper.
CasRedirectorTest::$configFactory protected property The mocked config factory service.
CasRedirectorTest::$eventDispatcher protected property The mocked event dispatcher.
CasRedirectorTest::$events protected property Storage for events during tests.
CasRedirectorTest::$urlGenerator protected property Mock URL Generator.
CasRedirectorTest::dispatchEvent public function Dispatch an event.
CasRedirectorTest::getServiceUrl public function Get a service URL.
CasRedirectorTest::setUp public function Overrides UnitTestCase::setUp
CasRedirectorTest::testBuildRedirectResponse public function Test buildRedirectResponse.
CasRedirectorTest::testEventsDispatched public function Tests the events dispatched by the listener.
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.
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.