You are here

public function FieldAccessTest::testFieldAccess in Drupal 9

Same name in this branch
  1. 9 core/tests/Drupal/KernelTests/Core/Field/FieldAccessTest.php \Drupal\KernelTests\Core\Field\FieldAccessTest::testFieldAccess()
  2. 9 core/modules/field/tests/src/Functional/FieldAccessTest.php \Drupal\Tests\field\Functional\FieldAccessTest::testFieldAccess()
Same name and namespace in other branches
  1. 8 core/tests/Drupal/KernelTests/Core/Field/FieldAccessTest.php \Drupal\KernelTests\Core\Field\FieldAccessTest::testFieldAccess()

Tests hook_entity_field_access() and hook_entity_field_access_alter().

See also

entity_test_entity_field_access()

entity_test_entity_field_access_alter()

File

core/tests/Drupal/KernelTests/Core/Field/FieldAccessTest.php, line 67

Class

FieldAccessTest
Tests Field level access hooks.

Namespace

Drupal\KernelTests\Core\Field

Code

public function testFieldAccess() {
  $values = [
    'name' => $this
      ->randomMachineName(),
    'user_id' => 1,
    'field_test_text' => [
      'value' => 'no access value',
      'format' => 'full_html',
    ],
  ];
  $entity = EntityTest::create($values);

  // Create a dummy user account for testing access with.
  $values = [
    'name' => 'test',
  ];
  $account = User::create($values);
  $this
    ->assertFalse($entity->field_test_text
    ->access('view', $account), 'Access to the field was denied.');
  $expected = AccessResult::forbidden()
    ->addCacheableDependency($entity);
  $this
    ->assertEquals($expected, $entity->field_test_text
    ->access('view', $account, TRUE), 'Access to the field was denied.');
  $entity->field_test_text = 'access alter value';
  $this
    ->assertFalse($entity->field_test_text
    ->access('view', $account), 'Access to the field was denied.');
  $this
    ->assertEquals($expected, $entity->field_test_text
    ->access('view', $account, TRUE), 'Access to the field was denied.');
  $entity->field_test_text = 'standard value';
  $this
    ->assertTrue($entity->field_test_text
    ->access('view', $account), 'Access to the field was granted.');
  $this
    ->assertEquals(AccessResult::allowed(), $entity->field_test_text
    ->access('view', $account, TRUE), 'Access to the field was granted.');
}