class CustomAccessCheckTest

Same name in other branches
  1. 9 core/tests/Drupal/Tests/Core/Access/CustomAccessCheckTest.php \Drupal\Tests\Core\Access\CustomAccessCheckTest
  2. 8.9.x core/tests/Drupal/Tests/Core/Access/CustomAccessCheckTest.php \Drupal\Tests\Core\Access\CustomAccessCheckTest
  3. 11.x core/tests/Drupal/Tests/Core/Access/CustomAccessCheckTest.php \Drupal\Tests\Core\Access\CustomAccessCheckTest

@coversDefaultClass \Drupal\Core\Access\CustomAccessCheck @group Access

Hierarchy

Expanded class hierarchy of CustomAccessCheckTest

File

core/tests/Drupal/Tests/Core/Access/CustomAccessCheckTest.php, line 20

Namespace

Drupal\Tests\Core\Access
View source
class CustomAccessCheckTest extends UnitTestCase {
    
    /**
     * The access checker to test.
     *
     * @var \Drupal\Core\Access\CustomAccessCheck
     */
    protected $accessChecker;
    
    /**
     * The mocked callable resolver.
     *
     * @var \Drupal\Core\Utility\CallableResolver|\PHPUnit\Framework\MockObject\MockObject
     */
    protected $callableResolver;
    
    /**
     * The mocked arguments resolver.
     *
     * @var \Drupal\Core\Access\AccessArgumentsResolverFactoryInterface|\PHPUnit\Framework\MockObject\MockObject
     */
    protected $argumentsResolverFactory;
    
    /**
     * {@inheritdoc}
     */
    protected function setUp() : void {
        parent::setUp();
        $this->callableResolver = $this->createMock(CallableResolver::class);
        $this->argumentsResolverFactory = $this->createMock('Drupal\\Core\\Access\\AccessArgumentsResolverFactoryInterface');
        $this->accessChecker = new CustomAccessCheck($this->callableResolver, $this->argumentsResolverFactory);
    }
    
    /**
     * Tests the access method.
     */
    public function testAccess() : void {
        $route_match = $this->createMock('Drupal\\Core\\Routing\\RouteMatchInterface');
        $this->callableResolver
            ->expects($this->exactly(4))
            ->method('getCallableFromDefinition')
            ->willReturnMap([
            [
                '\\Drupal\\Tests\\Core\\Access\\TestController::accessDeny',
                [
                    new TestController(),
                    'accessDeny',
                ],
            ],
            [
                '\\Drupal\\Tests\\Core\\Access\\TestController::accessAllow',
                [
                    new TestController(),
                    'accessAllow',
                ],
            ],
            [
                '\\Drupal\\Tests\\Core\\Access\\TestController::accessParameter',
                [
                    new TestController(),
                    'accessParameter',
                ],
            ],
            [
                '\\Drupal\\Tests\\Core\\Access\\TestController::accessRequest',
                [
                    new TestController(),
                    'accessRequest',
                ],
            ],
        ]);
        $resolver0 = $this->createMock('Drupal\\Component\\Utility\\ArgumentsResolverInterface');
        $resolver0->expects($this->once())
            ->method('getArguments')
            ->willReturn([]);
        $resolver1 = $this->createMock('Drupal\\Component\\Utility\\ArgumentsResolverInterface');
        $resolver1->expects($this->once())
            ->method('getArguments')
            ->willReturn([]);
        $resolver2 = $this->createMock('Drupal\\Component\\Utility\\ArgumentsResolverInterface');
        $resolver2->expects($this->once())
            ->method('getArguments')
            ->willReturn([
            'parameter' => 'TRUE',
        ]);
        $request = Request::create('/foo?example=muh');
        $resolver3 = $this->createMock('Drupal\\Component\\Utility\\ArgumentsResolverInterface');
        $resolver3->expects($this->once())
            ->method('getArguments')
            ->willReturn([
            'request' => $request,
        ]);
        $this->argumentsResolverFactory
            ->expects($this->exactly(4))
            ->method('getArgumentsResolver')
            ->willReturnOnConsecutiveCalls($resolver0, $resolver1, $resolver2, $resolver3);
        $route = new Route('/test-route', [], [
            '_custom_access' => '\\Drupal\\Tests\\Core\\Access\\TestController::accessDeny',
        ]);
        $account = $this->createMock('Drupal\\Core\\Session\\AccountInterface');
        $this->assertEquals(AccessResult::neutral(), $this->accessChecker
            ->access($route, $route_match, $account, $request));
        $route = new Route('/test-route', [], [
            '_custom_access' => '\\Drupal\\Tests\\Core\\Access\\TestController::accessAllow',
        ]);
        $this->assertEquals(AccessResult::allowed(), $this->accessChecker
            ->access($route, $route_match, $account, $request));
        $route = new Route('/test-route', [
            'parameter' => 'TRUE',
        ], [
            '_custom_access' => '\\Drupal\\Tests\\Core\\Access\\TestController::accessParameter',
        ]);
        $this->assertEquals(AccessResult::allowed(), $this->accessChecker
            ->access($route, $route_match, $account, $request));
        $route = new Route('/test-route', [
            'parameter' => 'TRUE',
        ], [
            '_custom_access' => '\\Drupal\\Tests\\Core\\Access\\TestController::accessRequest',
        ]);
        $this->assertEquals(AccessResult::allowed(), $this->accessChecker
            ->access($route, $route_match, $account, $request));
    }
    
    /**
     * Tests the access method exception for invalid access callbacks.
     */
    public function testAccessException() : void {
        // Create callableResolver mock to return InvalidArgumentException.
        $this->callableResolver = $this->getMockBuilder(CallableResolver::class)
            ->disableOriginalConstructor()
            ->getMock();
        $this->callableResolver
            ->expects($this->any())
            ->method('getCallableFromDefinition')
            ->willThrowException(new \InvalidArgumentException());
        // Overwrite the access checker using the newly mocked callable resolve.
        $this->accessChecker = new CustomAccessCheck($this->callableResolver, $this->argumentsResolverFactory);
        // Add a route with a _custom_access route that doesn't exist.
        $route = new Route('/test-route', [], [
            '_custom_access' => '\\Drupal\\Tests\\Core\\Access\\NonExistentController::nonExistentMethod',
        ]);
        $route_match = $this->createMock(RouteMatchInterface::class);
        $account = $this->createMock(AccountInterface::class);
        $request = Request::create('/foo?example=muh');
        $this->expectException(\BadMethodCallException::class);
        $this->expectExceptionMessage('The "\\Drupal\\Tests\\Core\\Access\\NonExistentController::nonExistentMethod" method is not callable as a _custom_access callback in route "/test-route"');
        // Run the access check.
        $this->accessChecker
            ->access($route, $route_match, $account, $request);
    }

}

Members

Title Sort descending Deprecated Modifiers Object type Summary Overriden Title Overrides
CustomAccessCheckTest::$accessChecker protected property The access checker to test.
CustomAccessCheckTest::$argumentsResolverFactory protected property The mocked arguments resolver.
CustomAccessCheckTest::$callableResolver protected property The mocked callable resolver.
CustomAccessCheckTest::setUp protected function Overrides UnitTestCase::setUp
CustomAccessCheckTest::testAccess public function Tests the access method.
CustomAccessCheckTest::testAccessException public function Tests the access method exception for invalid access callbacks.
PhpUnitWarnings::$deprecationWarnings private static property Deprecation warnings from PHPUnit to raise with @trigger_error().
PhpUnitWarnings::addWarning public function Converts PHPUnit deprecation warnings to E_USER_DEPRECATED.
RandomGeneratorTrait::getRandomGenerator protected function Gets the random generator for the utility methods.
RandomGeneratorTrait::randomMachineName protected function Generates a unique random string containing letters and numbers.
RandomGeneratorTrait::randomObject public function Generates a random PHP object.
RandomGeneratorTrait::randomString public function Generates a pseudo-random string of ASCII characters of codes 32 to 126.
RandomGeneratorTrait::randomStringValidate Deprecated public function Callback for random string validation.
UnitTestCase::$root protected property The app root. 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::getStringTranslationStub public function Returns a stub translation manager that just returns the passed string.
UnitTestCase::setUpBeforeClass public static function
UnitTestCase::__get public function

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.