3 namespace Drupal\KernelTests\Core\Field;
5 use Drupal\Core\Access\AccessResult;
6 use Drupal\entity_test\Entity\EntityTest;
7 use Drupal\KernelTests\KernelTestBase;
8 use Drupal\user\Entity\User;
11 * Tests Field level access hooks.
15 class FieldAccessTest extends KernelTestBase {
18 * Modules to load code from.
22 public static $modules = ['entity_test', 'field', 'system', 'text', 'filter', 'user'];
25 * Holds the currently active global user ID that initiated the test run.
27 * The user ID gets replaced during the test and needs to be kept here so that
28 * it can be restored at the end of the test run.
34 protected function setUp() {
36 // Install field configuration.
37 $this->installConfig(['field']);
38 // The users table is needed for creating dummy user accounts.
39 $this->installEntitySchema('user');
40 // Register entity_test text field.
41 module_load_install('entity_test');
42 entity_test_install();
46 * Tests hook_entity_field_access() and hook_entity_field_access_alter().
48 * @see entity_test_entity_field_access()
49 * @see entity_test_entity_field_access_alter()
51 public function testFieldAccess() {
53 'name' => $this->randomMachineName(),
55 'field_test_text' => [
56 'value' => 'no access value',
57 'format' => 'full_html',
60 $entity = EntityTest::create($values);
62 // Create a dummy user account for testing access with.
63 $values = ['name' => 'test'];
64 $account = User::create($values);
66 $this->assertFalse($entity->field_test_text->access('view', $account), 'Access to the field was denied.');
67 $expected = AccessResult::forbidden()->addCacheableDependency($entity);
68 $this->assertEqual($expected, $entity->field_test_text->access('view', $account, TRUE), 'Access to the field was denied.');
70 $entity->field_test_text = 'access alter value';
71 $this->assertFalse($entity->field_test_text->access('view', $account), 'Access to the field was denied.');
72 $this->assertEqual($expected, $entity->field_test_text->access('view', $account, TRUE), 'Access to the field was denied.');
74 $entity->field_test_text = 'standard value';
75 $this->assertTrue($entity->field_test_text->access('view', $account), 'Access to the field was granted.');
76 $this->assertEqual(AccessResult::allowed(), $entity->field_test_text->access('view', $account, TRUE), 'Access to the field was granted.');