You are here

class PathBasedBreadcrumbBuilderTest in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/system/tests/src/Unit/Breadcrumbs/PathBasedBreadcrumbBuilderTest.php \Drupal\Tests\system\Unit\Breadcrumbs\PathBasedBreadcrumbBuilderTest

@coversDefaultClass \Drupal\system\PathBasedBreadcrumbBuilder @group system

Hierarchy

Expanded class hierarchy of PathBasedBreadcrumbBuilderTest

File

core/modules/system/tests/src/Unit/Breadcrumbs/PathBasedBreadcrumbBuilderTest.php, line 29
Contains \Drupal\Tests\system\Unit\Breadcrumbs\PathBasedBreadcrumbBuilderTest.

Namespace

Drupal\Tests\system\Unit\Breadcrumbs
View source
class PathBasedBreadcrumbBuilderTest extends UnitTestCase {

  /**
   * The path based breadcrumb builder object to test.
   *
   * @var \Drupal\system\PathBasedBreadcrumbBuilder
   */
  protected $builder;

  /**
   * The mocked title resolver.
   *
   * @var \Drupal\Core\Controller\TitleResolverInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $titleResolver;

  /**
   * The mocked access manager.
   *
   * @var \Drupal\Core\Access\AccessManagerInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $accessManager;

  /**
   * The request matching mock object.
   *
   * @var \Symfony\Component\Routing\Matcher\RequestMatcherInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $requestMatcher;

  /**
   * The mocked route request context.
   *
   * @var \Drupal\Core\Routing\RequestContext|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $context;

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

  /**
   * The mocked path processor.
   *
   * @var \Drupal\Core\PathProcessor\InboundPathProcessorInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $pathProcessor;

  /**
   * The mocked current path.
   *
   * @var \Drupal\Core\Path\CurrentPathStack|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $currentPath;

  /**
   * {@inheritdoc}
   *
   * @covers ::__construct
   */
  protected function setUp() {
    parent::setUp();
    $this->requestMatcher = $this
      ->getMock('\\Symfony\\Component\\Routing\\Matcher\\RequestMatcherInterface');
    $config_factory = $this
      ->getConfigFactoryStub(array(
      'system.site' => array(
        'front' => 'test_frontpage',
      ),
    ));
    $this->pathProcessor = $this
      ->getMock('\\Drupal\\Core\\PathProcessor\\InboundPathProcessorInterface');
    $this->context = $this
      ->getMock('\\Drupal\\Core\\Routing\\RequestContext');
    $this->accessManager = $this
      ->getMock('\\Drupal\\Core\\Access\\AccessManagerInterface');
    $this->titleResolver = $this
      ->getMock('\\Drupal\\Core\\Controller\\TitleResolverInterface');
    $this->currentUser = $this
      ->getMock('Drupal\\Core\\Session\\AccountInterface');
    $this->currentPath = $this
      ->getMockBuilder('Drupal\\Core\\Path\\CurrentPathStack')
      ->disableOriginalConstructor()
      ->getMock();
    $this->builder = new TestPathBasedBreadcrumbBuilder($this->context, $this->accessManager, $this->requestMatcher, $this->pathProcessor, $config_factory, $this->titleResolver, $this->currentUser, $this->currentPath);
    $this->builder
      ->setStringTranslation($this
      ->getStringTranslationStub());
    $cache_contexts_manager = $this
      ->getMockBuilder('Drupal\\Core\\Cache\\Context\\CacheContextsManager')
      ->disableOriginalConstructor()
      ->getMock();
    $cache_contexts_manager
      ->method('assertValidTokens')
      ->willReturn(TRUE);
    $cache_contexts_manager
      ->expects($this
      ->any())
      ->method('validate_tokens');
    $container = new Container();
    $container
      ->set('cache_contexts_manager', $cache_contexts_manager);
    \Drupal::setContainer($container);
  }

  /**
   * Tests the build method on the frontpage.
   *
   * @covers ::build
   */
  public function testBuildOnFrontpage() {
    $this->context
      ->expects($this
      ->once())
      ->method('getPathInfo')
      ->will($this
      ->returnValue('/'));
    $breadcrumb = $this->builder
      ->build($this
      ->getMock('Drupal\\Core\\Routing\\RouteMatchInterface'));
    $this
      ->assertEquals([], $breadcrumb
      ->getLinks());
    $this
      ->assertEquals([
      'url.path',
    ], $breadcrumb
      ->getCacheContexts());
    $this
      ->assertEquals([], $breadcrumb
      ->getCacheTags());
    $this
      ->assertEquals(Cache::PERMANENT, $breadcrumb
      ->getCacheMaxAge());
  }

  /**
   * Tests the build method with one path element.
   *
   * @covers ::build
   */
  public function testBuildWithOnePathElement() {
    $this->context
      ->expects($this
      ->once())
      ->method('getPathInfo')
      ->will($this
      ->returnValue('/example'));
    $breadcrumb = $this->builder
      ->build($this
      ->getMock('Drupal\\Core\\Routing\\RouteMatchInterface'));
    $this
      ->assertEquals([
      0 => new Link('Home', new Url('<front>')),
    ], $breadcrumb
      ->getLinks());
    $this
      ->assertEquals([
      'url.path',
    ], $breadcrumb
      ->getCacheContexts());
    $this
      ->assertEquals([], $breadcrumb
      ->getCacheTags());
    $this
      ->assertEquals(Cache::PERMANENT, $breadcrumb
      ->getCacheMaxAge());
  }

  /**
   * Tests the build method with two path elements.
   *
   * @covers ::build
   * @covers ::getRequestForPath
   */
  public function testBuildWithTwoPathElements() {
    $this->context
      ->expects($this
      ->once())
      ->method('getPathInfo')
      ->will($this
      ->returnValue('/example/baz'));
    $this
      ->setupStubPathProcessor();
    $route_1 = new Route('/example');
    $this->requestMatcher
      ->expects($this
      ->exactly(1))
      ->method('matchRequest')
      ->will($this
      ->returnCallback(function (Request $request) use ($route_1) {
      if ($request
        ->getPathInfo() == '/example') {
        return array(
          RouteObjectInterface::ROUTE_NAME => 'example',
          RouteObjectInterface::ROUTE_OBJECT => $route_1,
          '_raw_variables' => new ParameterBag(array()),
        );
      }
    }));
    $this
      ->setupAccessManagerToAllow();
    $breadcrumb = $this->builder
      ->build($this
      ->getMock('Drupal\\Core\\Routing\\RouteMatchInterface'));
    $this
      ->assertEquals([
      0 => new Link('Home', new Url('<front>')),
      1 => new Link('Example', new Url('example')),
    ], $breadcrumb
      ->getLinks());
    $this
      ->assertEquals([
      'url.path',
      'user.permissions',
    ], $breadcrumb
      ->getCacheContexts());
    $this
      ->assertEquals([], $breadcrumb
      ->getCacheTags());
    $this
      ->assertEquals(Cache::PERMANENT, $breadcrumb
      ->getCacheMaxAge());
  }

  /**
   * Tests the build method with three path elements.
   *
   * @covers ::build
   * @covers ::getRequestForPath
   */
  public function testBuildWithThreePathElements() {
    $this->context
      ->expects($this
      ->once())
      ->method('getPathInfo')
      ->will($this
      ->returnValue('/example/bar/baz'));
    $this
      ->setupStubPathProcessor();
    $route_1 = new Route('/example/bar');
    $route_2 = new Route('/example');
    $this->requestMatcher
      ->expects($this
      ->exactly(2))
      ->method('matchRequest')
      ->will($this
      ->returnCallback(function (Request $request) use ($route_1, $route_2) {
      if ($request
        ->getPathInfo() == '/example/bar') {
        return array(
          RouteObjectInterface::ROUTE_NAME => 'example_bar',
          RouteObjectInterface::ROUTE_OBJECT => $route_1,
          '_raw_variables' => new ParameterBag(array()),
        );
      }
      elseif ($request
        ->getPathInfo() == '/example') {
        return array(
          RouteObjectInterface::ROUTE_NAME => 'example',
          RouteObjectInterface::ROUTE_OBJECT => $route_2,
          '_raw_variables' => new ParameterBag(array()),
        );
      }
    }));
    $this->accessManager
      ->expects($this
      ->any())
      ->method('check')
      ->willReturnOnConsecutiveCalls(AccessResult::allowed()
      ->cachePerPermissions(), AccessResult::allowed()
      ->addCacheContexts([
      'bar',
    ])
      ->addCacheTags([
      'example',
    ]));
    $breadcrumb = $this->builder
      ->build($this
      ->getMock('Drupal\\Core\\Routing\\RouteMatchInterface'));
    $this
      ->assertEquals([
      new Link('Home', new Url('<front>')),
      new Link('Example', new Url('example')),
      new Link('Bar', new Url('example_bar')),
    ], $breadcrumb
      ->getLinks());
    $this
      ->assertEquals([
      'bar',
      'url.path',
      'user.permissions',
    ], $breadcrumb
      ->getCacheContexts());
    $this
      ->assertEquals([
      'example',
    ], $breadcrumb
      ->getCacheTags());
    $this
      ->assertEquals(Cache::PERMANENT, $breadcrumb
      ->getCacheMaxAge());
  }

  /**
   * Tests that exceptions during request matching are caught.
   *
   * @covers ::build
   * @covers ::getRequestForPath
   *
   * @dataProvider providerTestBuildWithException
   */
  public function testBuildWithException($exception_class, $exception_argument) {
    $this->context
      ->expects($this
      ->once())
      ->method('getPathInfo')
      ->will($this
      ->returnValue('/example/bar'));
    $this
      ->setupStubPathProcessor();
    $this->requestMatcher
      ->expects($this
      ->any())
      ->method('matchRequest')
      ->will($this
      ->throwException(new $exception_class($exception_argument)));
    $breadcrumb = $this->builder
      ->build($this
      ->getMock('Drupal\\Core\\Routing\\RouteMatchInterface'));

    // No path matched, though at least the frontpage is displayed.
    $this
      ->assertEquals([
      0 => new Link('Home', new Url('<front>')),
    ], $breadcrumb
      ->getLinks());
    $this
      ->assertEquals([
      'url.path',
    ], $breadcrumb
      ->getCacheContexts());
    $this
      ->assertEquals([], $breadcrumb
      ->getCacheTags());
    $this
      ->assertEquals(Cache::PERMANENT, $breadcrumb
      ->getCacheMaxAge());
  }

  /**
   * Provides exception types for testBuildWithException.
   *
   * @return array
   *   The list of exception test cases.
   *
   * @see \Drupal\Tests\system\Unit\Breadcrumbs\PathBasedBreadcrumbBuilderTest::testBuildWithException()
   */
  public function providerTestBuildWithException() {
    return array(
      array(
        'Drupal\\Core\\ParamConverter\\ParamNotConvertedException',
        '',
      ),
      array(
        'Symfony\\Component\\Routing\\Exception\\MethodNotAllowedException',
        array(),
      ),
      array(
        'Symfony\\Component\\Routing\\Exception\\ResourceNotFoundException',
        '',
      ),
    );
  }

  /**
   * Tests the build method with a non processed path.
   *
   * @covers ::build
   * @covers ::getRequestForPath
   */
  public function testBuildWithNonProcessedPath() {
    $this->context
      ->expects($this
      ->once())
      ->method('getPathInfo')
      ->will($this
      ->returnValue('/example/bar'));
    $this->pathProcessor
      ->expects($this
      ->once())
      ->method('processInbound')
      ->will($this
      ->returnValue(FALSE));
    $this->requestMatcher
      ->expects($this
      ->any())
      ->method('matchRequest')
      ->will($this
      ->returnValue(array()));
    $breadcrumb = $this->builder
      ->build($this
      ->getMock('Drupal\\Core\\Routing\\RouteMatchInterface'));

    // No path matched, though at least the frontpage is displayed.
    $this
      ->assertEquals([
      0 => new Link('Home', new Url('<front>')),
    ], $breadcrumb
      ->getLinks());
    $this
      ->assertEquals([
      'url.path',
    ], $breadcrumb
      ->getCacheContexts());
    $this
      ->assertEquals([], $breadcrumb
      ->getCacheTags());
    $this
      ->assertEquals(Cache::PERMANENT, $breadcrumb
      ->getCacheMaxAge());
  }

  /**
   * Tests the applied method.
   *
   * @covers ::applies
   */
  public function testApplies() {
    $this
      ->assertTrue($this->builder
      ->applies($this
      ->getMock('Drupal\\Core\\Routing\\RouteMatchInterface')));
  }

  /**
   * Tests the breadcrumb for a user path.
   *
   * @covers ::build
   * @covers ::getRequestForPath
   */
  public function testBuildWithUserPath() {
    $this->context
      ->expects($this
      ->once())
      ->method('getPathInfo')
      ->will($this
      ->returnValue('/user/1/edit'));
    $this
      ->setupStubPathProcessor();
    $route_1 = new Route('/user/1');
    $this->requestMatcher
      ->expects($this
      ->exactly(1))
      ->method('matchRequest')
      ->will($this
      ->returnCallback(function (Request $request) use ($route_1) {
      if ($request
        ->getPathInfo() == '/user/1') {
        return array(
          RouteObjectInterface::ROUTE_NAME => 'user_page',
          RouteObjectInterface::ROUTE_OBJECT => $route_1,
          '_raw_variables' => new ParameterBag(array()),
        );
      }
    }));
    $this
      ->setupAccessManagerToAllow();
    $this->titleResolver
      ->expects($this
      ->once())
      ->method('getTitle')
      ->with($this
      ->anything(), $route_1)
      ->will($this
      ->returnValue('Admin'));
    $breadcrumb = $this->builder
      ->build($this
      ->getMock('Drupal\\Core\\Routing\\RouteMatchInterface'));
    $this
      ->assertEquals([
      0 => new Link('Home', new Url('<front>')),
      1 => new Link('Admin', new Url('user_page')),
    ], $breadcrumb
      ->getLinks());
    $this
      ->assertEquals([
      'url.path',
      'user.permissions',
    ], $breadcrumb
      ->getCacheContexts());
    $this
      ->assertEquals([], $breadcrumb
      ->getCacheTags());
    $this
      ->assertEquals(Cache::PERMANENT, $breadcrumb
      ->getCacheMaxAge());
  }

  /**
   * Setup the access manager to always allow access to routes.
   */
  public function setupAccessManagerToAllow() {
    $this->accessManager
      ->expects($this
      ->any())
      ->method('check')
      ->willReturn((new AccessResultAllowed())
      ->cachePerPermissions());
  }
  protected function setupStubPathProcessor() {
    $this->pathProcessor
      ->expects($this
      ->any())
      ->method('processInbound')
      ->will($this
      ->returnArgument(0));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
PathBasedBreadcrumbBuilderTest::$accessManager protected property The mocked access manager.
PathBasedBreadcrumbBuilderTest::$builder protected property The path based breadcrumb builder object to test.
PathBasedBreadcrumbBuilderTest::$context protected property The mocked route request context.
PathBasedBreadcrumbBuilderTest::$currentPath protected property The mocked current path.
PathBasedBreadcrumbBuilderTest::$currentUser protected property The mocked current user.
PathBasedBreadcrumbBuilderTest::$pathProcessor protected property The mocked path processor.
PathBasedBreadcrumbBuilderTest::$requestMatcher protected property The request matching mock object.
PathBasedBreadcrumbBuilderTest::$titleResolver protected property The mocked title resolver.
PathBasedBreadcrumbBuilderTest::providerTestBuildWithException public function Provides exception types for testBuildWithException.
PathBasedBreadcrumbBuilderTest::setUp protected function @covers ::__construct Overrides UnitTestCase::setUp
PathBasedBreadcrumbBuilderTest::setupAccessManagerToAllow public function Setup the access manager to always allow access to routes.
PathBasedBreadcrumbBuilderTest::setupStubPathProcessor protected function
PathBasedBreadcrumbBuilderTest::testApplies public function Tests the applied method.
PathBasedBreadcrumbBuilderTest::testBuildOnFrontpage public function Tests the build method on the frontpage.
PathBasedBreadcrumbBuilderTest::testBuildWithException public function Tests that exceptions during request matching are caught.
PathBasedBreadcrumbBuilderTest::testBuildWithNonProcessedPath public function Tests the build method with a non processed path.
PathBasedBreadcrumbBuilderTest::testBuildWithOnePathElement public function Tests the build method with one path element.
PathBasedBreadcrumbBuilderTest::testBuildWithThreePathElements public function Tests the build method with three path elements.
PathBasedBreadcrumbBuilderTest::testBuildWithTwoPathElements public function Tests the build method with two path elements.
PathBasedBreadcrumbBuilderTest::testBuildWithUserPath public function Tests the breadcrumb for a user path.
UnitTestCase::$randomGenerator protected property The random generator.
UnitTestCase::$root protected property The app root.
UnitTestCase::assertArrayEquals protected function Asserts if two arrays are equal by sorting them first.
UnitTestCase::getBlockMockWithMachineName protected function Mocks a block with a block plugin.
UnitTestCase::getClassResolverStub protected function Returns a stub class resolver.
UnitTestCase::getConfigFactoryStub public function Returns a stub config factory that behaves according to the passed in 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.