function AccessTest::testFileCacheability

Same name in other branches
  1. 8.9.x core/modules/file/tests/src/Kernel/AccessTest.php \Drupal\Tests\file\Kernel\AccessTest::testFileCacheability()
  2. 10 core/modules/file/tests/src/Kernel/AccessTest.php \Drupal\Tests\file\Kernel\AccessTest::testFileCacheability()
  3. 11.x core/modules/file/tests/src/Kernel/AccessTest.php \Drupal\Tests\file\Kernel\AccessTest::testFileCacheability()

Tests cacheability metadata.

File

core/modules/file/tests/src/Kernel/AccessTest.php, line 129

Class

AccessTest
Tests for the File access control.

Namespace

Drupal\Tests\file\Kernel

Code

public function testFileCacheability() {
    $file = File::create([
        'filename' => 'green-scarf',
        'uri' => 'private://green-scarf',
        'filemime' => 'text/plain',
    ]);
    $file->setPermanent();
    $file->save();
    \Drupal::service('session')->set('anonymous_allowed_file_ids', [
        $file->id() => $file->id(),
    ]);
    $account = User::getAnonymousUser();
    $file->setOwnerId($account->id())
        ->save();
    $this->assertSame([
        'session',
        'user',
    ], $file->access('view', $account, TRUE)
        ->getCacheContexts());
    $this->assertSame([
        'session',
        'user',
    ], $file->access('download', $account, TRUE)
        ->getCacheContexts());
    $account = $this->user1;
    $file->setOwnerId($account->id())
        ->save();
    $this->assertSame([
        'user',
    ], $file->access('view', $account, TRUE)
        ->getCacheContexts());
    $this->assertSame([
        'user',
    ], $file->access('download', $account, TRUE)
        ->getCacheContexts());
}

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