3 namespace Drupal\Tests\file\Functional;
5 use Drupal\file\Entity\File;
8 * Tests access to managed files.
12 class FileManagedAccessTest extends FileManagedTestBase {
15 * Tests if public file is always accessible.
17 public function testFileAccess() {
18 // Create a new file entity.
19 $file = File::create([
21 'filename' => 'drupal.txt',
22 'uri' => 'public://drupal.txt',
23 'filemime' => 'text/plain',
24 'status' => FILE_STATUS_PERMANENT,
26 file_put_contents($file->getFileUri(), 'hello world');
28 // Save it, inserting a new record.
31 // Create authenticated user to check file access.
32 $account = $this->createUser(['access site reports']);
34 $this->assertTrue($file->access('view', $account), 'Public file is viewable to authenticated user');
35 $this->assertTrue($file->access('download', $account), 'Public file is downloadable to authenticated user');
37 // Create anonymous user to check file access.
38 $account = $this->createUser()->getAnonymousUser();
40 $this->assertTrue($file->access('view', $account), 'Public file is viewable to anonymous user');
41 $this->assertTrue($file->access('download', $account), 'Public file is downloadable to anonymous user');
43 // Create a new file entity.
44 $file = File::create([
46 'filename' => 'drupal.txt',
47 'uri' => 'private://drupal.txt',
48 'filemime' => 'text/plain',
49 'status' => FILE_STATUS_PERMANENT,
51 file_put_contents($file->getFileUri(), 'hello world');
53 // Save it, inserting a new record.
56 // Create authenticated user to check file access.
57 $account = $this->createUser(['access site reports']);
59 $this->assertFalse($file->access('view', $account), 'Private file is not viewable to authenticated user');
60 $this->assertFalse($file->access('download', $account), 'Private file is not downloadable to authenticated user');
62 // Create anonymous user to check file access.
63 $account = $this->createUser()->getAnonymousUser();
65 $this->assertFalse($file->access('view', $account), 'Private file is not viewable to anonymous user');
66 $this->assertFalse($file->access('download', $account), 'Private file is not downloadable to anonymous user');