You are here

public function DownloadTest::testMediaDownloadByOwner in Media Entity Download 8.2

Tests download of media entity files by it's owner.

File

tests/src/Functional/DownloadTest.php, line 138

Class

DownloadTest
Simple test to ensure that main page loads with module enabled.

Namespace

Drupal\Tests\media_entity_download\Functional

Code

public function testMediaDownloadByOwner() {
  $media_owner = $this
    ->createUser([
    'download media',
    'view media',
  ]);
  $media_owner_role = Role::load(current($media_owner
    ->getRoles(TRUE)));
  $no_media_owner = $this
    ->createUser([
    'download media',
    'view media',
    'view own unpublished media',
  ]);
  $no_media_owner_role = Role::load(current($no_media_owner
    ->getRoles(TRUE)));
  $this
    ->assertNotEqual($media_owner_role, $no_media_owner_role);
  $media = $this
    ->createMediaEntity(TRUE, $media_owner);
  $unpublished_media = $this
    ->createMediaEntity(FALSE, $media_owner);
  $this
    ->drupalLogin($media_owner);
  $this
    ->drupalGet(Url::fromRoute('media_entity_download.download', [
    'media' => $media
      ->id(),
  ]));
  $this
    ->assertEquals(Response::HTTP_OK, $this
    ->getSession()
    ->getStatusCode());
  $this
    ->drupalGet(Url::fromRoute('media_entity_download.download', [
    'media' => $unpublished_media
      ->id(),
  ]));
  $this
    ->assertEquals(Response::HTTP_FORBIDDEN, $this
    ->getSession()
    ->getStatusCode());
  $media_owner_role
    ->grantPermission('view own unpublished media');
  $media_owner_role
    ->save();
  $this
    ->drupalGet(Url::fromRoute('media_entity_download.download', [
    'media' => $unpublished_media
      ->id(),
  ]));
  $this
    ->assertEquals(Response::HTTP_OK, $this
    ->getSession()
    ->getStatusCode());

  // Assert file headers.
  $unpublished_media_file_id = $unpublished_media
    ->getSource()
    ->getSourceFieldValue($unpublished_media);

  /** @var \Drupal\file\FileInterface $unpublished_media_file */
  $unpublished_media_file = File::load($unpublished_media_file_id);
  $this
    ->assertEquals('attachment; filename="' . $unpublished_media_file
    ->getFilename() . '"', $this
    ->drupalGetHeader('Content-Disposition'));
  $this
    ->assertEquals('public', $this
    ->drupalGetHeader('Cache-Control'));
  $this
    ->assertEquals($unpublished_media_file
    ->getSize(), $this
    ->drupalGetHeader('Content-Length'));
  $this
    ->drupalLogin($no_media_owner);
  $this
    ->drupalGet(Url::fromRoute('media_entity_download.download', [
    'media' => $media
      ->id(),
  ]));
  $this
    ->assertEquals(Response::HTTP_OK, $this
    ->getSession()
    ->getStatusCode());
  $this
    ->drupalGet(Url::fromRoute('media_entity_download.download', [
    'media' => $unpublished_media
      ->id(),
  ]));
  $this
    ->assertEquals(Response::HTTP_FORBIDDEN, $this
    ->getSession()
    ->getStatusCode());
}