You are here

function FileEntityAccessTest::testFileEntityPrivateDownloadAccess in File Entity (fieldable files) 8.2

Test to see if we have access to download private files when granted the permissions.

File

tests/src/Functional/FileEntityAccessTest.php, line 194

Class

FileEntityAccessTest
Tests the access aspects of file entity.

Namespace

Drupal\Tests\file_entity\Functional

Code

function testFileEntityPrivateDownloadAccess() {
  $original_file = next($this->files['text']);
  foreach ($this
    ->getPrivateDownloadAccessCases() as $case) {

    /** @var FileInterface $file */
    $file = file_copy($original_file, 'private://');
    $user_name = 'anonymous';

    // Create users and login only if non-anonymous.
    $authenticated_user = !is_null($case['permissions']);
    if ($authenticated_user) {
      $account = $this
        ->drupalCreateUser($case['permissions']);
      $this
        ->drupalLogin($account);
      $user_name = $account
        ->getAccountName();
      if (!empty($case['owner'])) {
        $file
          ->setOwner($account)
          ->save();
      }
    }

    // Check if the physical file is there.
    $arguments = array(
      '%name' => $file
        ->getFilename(),
      '%username' => $user_name,
      '%uri' => $file
        ->getFileUri(),
    );
    $this
      ->assertTrue(is_file($file
      ->getFileUri()), new FormattableMarkup('File %name owned by %username successfully created at %uri.', $arguments));
    $url = file_create_url($file
      ->getFileUri());
    $message_file_info = ' ' . new FormattableMarkup('File %uri was checked.', array(
      '%uri' => $file
        ->getFileUri(),
    ));

    // Try to download the file.
    $this
      ->drupalGet($url);
    $this
      ->assertResponse($case['expect'], $case['message'] . $message_file_info);

    // Logout authenticated users.
    if ($authenticated_user) {
      $this
        ->drupalLogout();
    }
  }
}