function MediaAccessTest::testCanonicalMediaAccess

Same name in other branches
  1. 8.9.x core/modules/media/tests/src/Functional/MediaAccessTest.php \Drupal\Tests\media\Functional\MediaAccessTest::testCanonicalMediaAccess()
  2. 10 core/modules/media/tests/src/Functional/MediaAccessTest.php \Drupal\Tests\media\Functional\MediaAccessTest::testCanonicalMediaAccess()
  3. 11.x core/modules/media/tests/src/Functional/MediaAccessTest.php \Drupal\Tests\media\Functional\MediaAccessTest::testCanonicalMediaAccess()

Tests view access control on the canonical page.

File

core/modules/media/tests/src/Functional/MediaAccessTest.php, line 200

Class

MediaAccessTest
Basic access tests for Media.

Namespace

Drupal\Tests\media\Functional

Code

public function testCanonicalMediaAccess() {
    $media_type = $this->createMediaType('test');
    $assert_session = $this->assertSession();
    \Drupal::configFactory()->getEditable('media.settings')
        ->set('standalone_url', TRUE)
        ->save(TRUE);
    $this->container
        ->get('router.builder')
        ->rebuild();
    // Create media.
    $media = Media::create([
        'bundle' => $media_type->id(),
        'name' => 'Unnamed',
    ]);
    $media->save();
    $user_media = Media::create([
        'bundle' => $media_type->id(),
        'name' => 'Unnamed',
        'uid' => $this->nonAdminUser
            ->id(),
    ]);
    $user_media->save();
    $this->drupalLogin($this->nonAdminUser);
    
    /** @var \Drupal\user\RoleInterface $role */
    $role = Role::load(RoleInterface::AUTHENTICATED_ID);
    user_role_revoke_permissions($role->id(), [
        'view media',
    ]);
    $this->drupalGet('media/' . $media->id());
    $this->assertCacheContext('user.permissions');
    $assert_session->statusCodeEquals(403);
    $access_result = $media->access('view', NULL, TRUE);
    $this->assertSame("The 'view media' permission is required when the media item is published.", $access_result->getReason());
    $this->grantPermissions($role, [
        'view media',
    ]);
    $this->drupalGet('media/' . $media->id());
    $this->assertCacheContext('user.permissions');
    $assert_session->statusCodeEquals(200);
}

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