Example #1
0
 /**
  * {@inheritdoc}
  */
 protected function setUp($import_test_views = TRUE)
 {
     parent::setUp($import_test_views);
     $this->installEntitySchema('user');
     $this->installEntitySchema('comment');
     // Create the anonymous role.
     $this->installConfig(['user']);
     // Create an anonymous user.
     $storage = \Drupal::entityManager()->getStorage('user');
     // Insert a row for the anonymous user.
     $storage->create(array('uid' => 0, 'name' => '', 'status' => 0))->save();
     $admin_role = Role::create(['id' => 'admin', 'permissions' => ['administer comments', 'access user profiles']]);
     $admin_role->save();
     /* @var \Drupal\user\RoleInterface $anonymous_role */
     $anonymous_role = Role::load(Role::ANONYMOUS_ID);
     $anonymous_role->grantPermission('access comments');
     $anonymous_role->save();
     $this->adminUser = User::create(['name' => $this->randomMachineName(), 'roles' => [$admin_role->id()]]);
     $this->adminUser->save();
     // Create some comments.
     $comment = Comment::create(['subject' => 'My comment title', 'uid' => $this->adminUser->id(), 'name' => $this->adminUser->label(), 'entity_type' => 'entity_test', 'comment_type' => 'entity_test', 'status' => 1]);
     $comment->save();
     $comment_anonymous = Comment::create(['subject' => 'Anonymous comment title', 'uid' => 0, 'name' => 'barry', 'mail' => '*****@*****.**', 'homepage' => 'https://example.com', 'entity_type' => 'entity_test', 'comment_type' => 'entity_test', 'created' => 123456, 'status' => 1]);
     $comment_anonymous->save();
 }
 /**
  * Performs setup tasks before each individual test method is run.
  */
 public function setUp()
 {
     parent::setUp('content_access');
     // The parent method already installs most needed node and comment schemas,
     // but here we also need the comment statistics.
     $this->installSchema('comment', array('comment_entity_statistics'));
     // Create a node type for testing.
     $type = NodeType::create(array('type' => 'page', 'name' => 'page'));
     $type->save();
     // Create anonymous user role.
     $role = Role::create(array('id' => 'anonymous', 'label' => 'anonymous'));
     $role->save();
     // Insert the anonymous user into the database, as the user table is inner
     // joined by \Drupal\comment\CommentStorage.
     User::create(array('uid' => 0, 'name' => ''))->save();
     // Create a node with attached comment.
     $this->nodes[0] = Node::create(array('status' => NODE_PUBLISHED, 'type' => 'page', 'title' => 'test title'));
     $this->nodes[0]->save();
     $comment_type = CommentType::create(array('id' => 'comment', 'target_entity_type_id' => 'node'));
     $comment_type->save();
     $this->installConfig(array('comment'));
     $this->addDefaultCommentField('node', 'page');
     $comment = Comment::create(array('entity_type' => 'node', 'entity_id' => $this->nodes[0]->id(), 'field_name' => 'comment', 'body' => 'test body', 'comment_type' => $comment_type->id()));
     $comment->save();
     $this->comments[] = $comment;
     $this->nodes[1] = Node::create(array('status' => NODE_PUBLISHED, 'type' => 'page', 'title' => 'some title'));
     $this->nodes[1]->save();
     $this->nodes[2] = Node::create(array('status' => NODE_NOT_PUBLISHED, 'type' => 'page', 'title' => 'other title'));
     $this->nodes[2]->save();
     // Also index users, to verify that they are unaffected by the processor.
     $this->index->set('datasources', array('entity:comment', 'entity:node', 'entity:user'));
     $this->index->save();
     $this->index = entity_load('search_api_index', $this->index->id(), TRUE);
 }
Example #3
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->installSchema('system', 'sequences');
     $this->installEntitySchema('user');
     $this->manager = $this->container->get('plugin.manager.condition');
     // Set up the authenticated and anonymous roles.
     Role::create(array('id' => RoleInterface::ANONYMOUS_ID, 'label' => 'Anonymous user'))->save();
     Role::create(array('id' => RoleInterface::AUTHENTICATED_ID, 'label' => 'Authenticated user'))->save();
     // Create new role.
     $rid = strtolower($this->randomMachineName(8));
     $label = $this->randomString(8);
     $role = Role::create(array('id' => $rid, 'label' => $label));
     $role->save();
     $this->role = $role;
     // Setup an anonymous user for our tests.
     $this->anonymous = User::create(array('name' => '', 'uid' => 0));
     $this->anonymous->save();
     // Loading the anonymous user adds the correct role.
     $this->anonymous = User::load($this->anonymous->id());
     // Setup an authenticated user for our tests.
     $this->authenticated = User::create(array('name' => $this->randomMachineName()));
     $this->authenticated->save();
     // Add the custom role.
     $this->authenticated->addRole($this->role->id());
 }
 public function testRevisionView()
 {
     $entity = EnhancedEntity::create(['name' => 'rev 1', 'type' => 'default']);
     $entity->save();
     $revision = clone $entity;
     $revision->name->value = 'rev 2';
     $revision->setNewRevision(TRUE);
     $revision->isDefaultRevision(FALSE);
     $revision->save();
     /** @var \Symfony\Component\HttpKernel\HttpKernelInterface $http_kernel */
     $http_kernel = \Drupal::service('http_kernel');
     $request = Request::create($revision->url('revision'));
     $response = $http_kernel->handle($request);
     $this->assertEquals(403, $response->getStatusCode());
     $role = Role::create(['id' => 'test_role']);
     $role->grantPermission('view all entity_test_enhanced revisions');
     $role->grantPermission('administer entity_test_enhanced');
     $role->save();
     $user = User::create(['name' => 'Test user']);
     $user->addRole($role->id());
     \Drupal::service('account_switcher')->switchTo($user);
     $request = Request::create($revision->url('revision'));
     $response = $http_kernel->handle($request);
     $this->assertEquals(200, $response->getStatusCode());
     $this->assertNotContains('rev 1', $response->getContent());
     $this->assertContains('rev 2', $response->getContent());
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->role1 = Role::create(array('id' => strtolower($this->randomMachineName(8)), 'label' => $this->randomMachineName(8)));
     $this->role1->save();
     $this->role2 = Role::create(array('id' => strtolower($this->randomMachineName(8)), 'label' => $this->randomMachineName(8)));
     $this->role2->save();
     $this->createEntityReferenceField('user', 'user', 'user_reference', 'User reference', 'user');
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->installEntitySchema('user');
     $this->installSchema('system', 'sequences');
     $devel_role = Role::create(['id' => 'admin', 'permissions' => ['access devel information']]);
     $devel_role->save();
     $this->develUser = User::create(['name' => $this->randomMachineName(), 'roles' => [$devel_role->id()]]);
     $this->develUser->save();
 }
 /**
  * Tests the plain formatter.
  */
 public function testAllFormatters()
 {
     // Tests the plain formatter.
     $this->assertFormatterRdfa(array('type' => 'taxonomy_term_reference_plain'), 'http://schema.org/about', array('value' => $this->term->getName(), 'type' => 'literal'));
     // Grant the access content permission to the anonymous user.
     Role::create(array('id' => DRUPAL_ANONYMOUS_RID))->grantPermission('access content')->save();
     // Tests the link formatter.
     $term_uri = $this->getAbsoluteUri($this->term);
     $this->assertFormatterRdfa(array('type' => 'taxonomy_term_reference_link'), 'http://schema.org/about', array('value' => $term_uri, 'type' => 'uri'));
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->installEntitySchema('user');
     $this->installEntitySchema('entity_test_mul');
     $this->installEntitySchema('entity_test_admin_routes');
     /** @var \Drupal\user\RoleInterface $role */
     $role = Role::create(['id' => RoleInterface::ANONYMOUS_ID]);
     $role->grantPermission('administer entity_test content')->grantPermission('view test entity');
     $role->save();
 }
 /**
  * @return \Drupal\user\UserInterface
  */
 protected function drupalCreateUser(array $permissions = [])
 {
     $role = Role::create(['id' => 'test_role__' . $this->randomMachineName()]);
     foreach ($permissions as $permission) {
         $role->grantPermission($permission);
     }
     $role->save();
     $user = User::create(['name' => 'test name  ' . $this->randomMachineName()]);
     $user->addRole($role->id());
     $user->save();
     return $user;
 }
 /**
  * Tests whether the user action config schema are valid.
  */
 function testValidUserActionConfigSchema()
 {
     $rid = strtolower($this->randomName(8));
     Role::create(array('id' => $rid))->save();
     // Test user_add_role_action configuration.
     $config = \Drupal::config('system.action.user_add_role_action.' . $rid);
     $this->assertEqual($config->get('id'), 'user_add_role_action.' . $rid);
     $this->assertConfigSchema(\Drupal::service('config.typed'), $config->getName(), $config->get());
     // Test user_remove_role_action configuration.
     $config = \Drupal::config('system.action.user_remove_role_action.' . $rid);
     $this->assertEqual($config->get('id'), 'user_remove_role_action.' . $rid);
     $this->assertConfigSchema(\Drupal::service('config.typed'), $config->getName(), $config->get());
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp($import_test_views = TRUE)
 {
     parent::setUp($import_test_views);
     $this->installEntitySchema('user');
     $role_with_access = Role::create(['id' => 'with_access', 'permissions' => ['view test entity field']]);
     $role_with_access->save();
     $role_without_access = Role::create(['id' => 'without_access', 'permissions' => []]);
     $role_without_access->save();
     $this->userWithAccess = User::create(['name' => $this->randomMachineName(), 'roles' => [$role_with_access->id()]]);
     $this->userWithAccess->save();
     $this->userWithoutAccess = User::create(['name' => $this->randomMachineName(), 'roles' => [$role_without_access->id()]]);
     $this->userWithoutAccess->save();
 }
 /**
  * Sets up the test.
  */
 protected function setUp()
 {
     parent::setUp();
     $this->installSchema('system', ['sequences', 'key_value_expire']);
     $this->installEntitySchema('user');
     \Drupal::service('router.builder')->rebuild();
     /** @var \Drupal\user\RoleInterface $role */
     $role = Role::create(array('id' => 'admin', 'label' => 'admin'));
     $role->grantPermission('link to any page');
     $role->save();
     $this->testUser = User::create(array('name' => 'foobar', 'mail' => '*****@*****.**'));
     $this->testUser->addRole($role->id());
     $this->testUser->save();
     \Drupal::service('current_user')->setAccount($this->testUser);
 }
Example #13
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->installEntitySchema('user');
     $this->installEntitySchema('entity_test_mul');
     $this->installEntitySchema('entity_test_admin_routes');
     $this->installSchema('system', 'router');
     $router_builder = \Drupal::service('router.builder');
     $router_builder->rebuild();
     /** @var \Drupal\Core\Routing\RouteBuilderInterface $router_builder */
     $router_builder = \Drupal::service('router.builder');
     $router_builder->rebuild();
     /** @var \Drupal\user\RoleInterface $role */
     $role = Role::create(['id' => RoleInterface::ANONYMOUS_ID]);
     $role->grantPermission('administer entity_test content')->grantPermission('view test entity');
     $role->save();
 }
 /**
  * Tests that role filter dependencies are calculated correctly.
  */
 public function testDependencies()
 {
     $role = Role::create(['id' => 'test_user_role']);
     $role->save();
     $view = View::load('test_user_name');
     $expected = ['module' => ['user']];
     $this->assertEqual($expected, $view->getDependencies());
     $display =& $view->getDisplay('default');
     $display['display_options']['filters']['roles_target_id'] = ['id' => 'roles_target_id', 'table' => 'user__roles', 'field' => 'roles_target_id', 'value' => ['test_user_role' => 'test_user_role'], 'plugin_id' => 'user_roles'];
     $view->save();
     $expected['config'][] = 'user.role.test_user_role';
     $this->assertEqual($expected, $view->getDependencies());
     $view = View::load('test_user_name');
     $display =& $view->getDisplay('default');
     $display['display_options']['filters']['roles_target_id'] = ['id' => 'roles_target_id', 'table' => 'user__roles', 'field' => 'roles_target_id', 'value' => [], 'plugin_id' => 'user_roles'];
     $view->save();
     unset($expected['config']);
     $this->assertEqual($expected, $view->getDependencies());
 }
Example #15
0
 /**
  * {@inheritdoc}
  */
 public function setUp($processor = NULL)
 {
     parent::setUp('rendered_item');
     // Load configuration and needed schemas. (The necessary schemas for using
     // nodes are already installed by the parent method.)
     $this->installConfig(array('system', 'filter', 'node', 'comment'));
     $this->installSchema('system', array('router'));
     \Drupal::service('router.builder')->rebuild();
     // Create a node type for testing.
     $type = NodeType::create(array('type' => 'page', 'name' => 'page'));
     $type->save();
     node_add_body_field($type);
     // Create anonymous user role.
     $role = Role::create(array('id' => 'anonymous', 'label' => 'anonymous'));
     $role->save();
     // Insert the anonymous user into the database.
     $anonymous_user = User::create(array('uid' => 0, 'name' => ''));
     $anonymous_user->save();
     // Default node values for all nodes we create below.
     $node_data = array('status' => NODE_PUBLISHED, 'type' => 'page', 'title' => '', 'body' => array('value' => '', 'summary' => '', 'format' => 'plain_text'), 'uid' => $anonymous_user->id());
     // Create some test nodes with valid user on it for rendering a picture.
     $node_data['title'] = 'Title for node 1';
     $node_data['body']['value'] = 'value for node 1';
     $node_data['body']['summary'] = 'summary for node 1';
     $this->nodes[1] = Node::create($node_data);
     $this->nodes[1]->save();
     $node_data['title'] = 'Title for node 2';
     $node_data['body']['value'] = 'value for node 2';
     $node_data['body']['summary'] = 'summary for node 2';
     $this->nodes[2] = Node::create($node_data);
     $this->nodes[2]->save();
     // Set proper configuration for the tested processor.
     $config = $this->processor->getConfiguration();
     $config['view_mode'] = array('entity:node' => ['page' => 'full', 'article' => 'teaser'], 'entity:user' => 'compact', 'entity:comment' => 'teaser');
     $config['roles'] = array($role->id());
     $this->processor->setConfiguration($config);
     $this->index->save();
     $this->index->getDatasources();
     // Enable the classy theme as the tests rely on markup from that.
     \Drupal::service('theme_handler')->install(array('classy'));
     \Drupal::theme()->setActiveTheme(\Drupal::service('theme.initialization')->initTheme('classy'));
 }
 /**
  * {@inheritdoc}
  */
 function setUp()
 {
     parent::setUp();
     // Create and configure User module's admin role.
     $this->admin_role = Role::create(['id' => 'administrator', 'label' => 'Administrator']);
     // Users in this role get all permissions assigned by default.
     $this->admin_role->set('is_admin', TRUE)->save();
     // Create a 'masquerade' role to masquerade as users without roles.
     $this->masquerade_role = Role::create(['id' => 'masquerade', 'label' => 'Masquerade']);
     $this->masquerade_role->grantPermission('masquerade as authenticated')->save();
     // Create an additional 'editor' role to masquerade as basic users.
     $this->editor_role = Role::create(['id' => 'editor', 'label' => 'Editor']);
     $this->editor_role->grantPermission('masquerade as masquerade')->grantPermission('masquerade as authenticated')->save();
     // Create an additional 'moderator' role to check 'masquerade as any user'.
     $this->moderator_role = Role::create(['id' => 'moderator', 'label' => 'Moderator']);
     $this->moderator_role->grantPermission('masquerade as any user')->save();
     // Create test users with varying privilege levels.
     // Administrative user with User module's admin role *only*.
     $this->admin_user = $this->drupalCreateUser();
     $this->admin_user->setUsername('admin_user');
     $this->admin_user->addRole($this->admin_role->id());
     $this->admin_user->save();
     // Moderator user.
     $this->moderator_user = $this->drupalCreateUser();
     $this->moderator_user->setUsername('moderator_user');
     $this->moderator_user->addRole($this->moderator_role->id());
     $this->moderator_user->save();
     // Editor user.
     $this->editor_user = $this->drupalCreateUser();
     $this->editor_user->setUsername('editor_user');
     $this->editor_user->addRole($this->editor_role->id());
     $this->editor_user->save();
     // Masquerade user.
     $this->masquerade_user = $this->drupalCreateUser();
     $this->masquerade_user->setUsername('masquerade_user');
     $this->masquerade_user->addRole($this->masquerade_role->id());
     $this->masquerade_user->save();
     // Authenticated user.
     $this->auth_user = $this->drupalCreateUser();
     // Place block to allow unmasquerade link accessible.
     $this->drupalPlaceBlock('system_menu_block:account');
 }
Example #17
0
 /**
  * Ensures that the access() method on \Drupal\Core\Url objects works.
  */
 public function testAccess()
 {
     /** @var \Drupal\user\RoleInterface $role_with_access */
     $role_with_access = Role::create(['id' => 'role_with_access']);
     $role_with_access->grantPermission('administer users');
     $role_with_access->save();
     /** @var \Drupal\user\RoleInterface $role_without_access */
     $role_without_access = Role::create(['id' => 'role_without_access']);
     $role_without_access->save();
     $user_with_access = User::create(['roles' => ['role_with_access']]);
     $user_without_access = User::create(['roles' => ['role_without_access']]);
     $url_always_access = new Url('router_test.1');
     $this->assertTrue($url_always_access->access($user_with_access));
     $this->assertTrue($url_always_access->access($user_without_access));
     $url_none_access = new Url('router_test.15');
     $this->assertFalse($url_none_access->access($user_with_access));
     $this->assertFalse($url_none_access->access($user_without_access));
     $url_access = new Url('router_test.16');
     $this->assertTrue($url_access->access($user_with_access));
     $this->assertFalse($url_access->access($user_without_access));
 }
 /**
  * Sets up the test.
  */
 protected function setUp()
 {
     parent::setUp();
     $this->installEntitySchema('user');
     $this->installSchema('system', ['sequences']);
     $this->installConfig(['filter', 'filter_test']);
     // Filter tips link to the full-page.
     \Drupal::service('router.builder')->rebuild();
     /* @var \Drupal\Core\Render\ElementInfoManager $manager */
     $manager = \Drupal::service('plugin.manager.element_info');
     $manager->clearCachedDefinitions();
     $manager->getDefinitions();
     /* @var \Drupal\filter\FilterFormatInterface $filter_test_format */
     $filter_test_format = FilterFormat::load('filter_test');
     /* @var \Drupal\user\RoleInterface $role */
     $role = Role::create(['id' => 'admin', 'label' => 'admin']);
     $role->grantPermission($filter_test_format->getPermissionName());
     $role->save();
     $this->testUser = User::create(['name' => 'foobar', 'mail' => '*****@*****.**']);
     $this->testUser->addRole($role->id());
     $this->testUser->save();
     \Drupal::service('current_user')->setAccount($this->testUser);
 }
 protected function setUp($import_test_views = TRUE)
 {
     parent::setUp($import_test_views);
     ViewTestData::createTestViews(get_class($this), ['comment_test_views']);
     $this->installEntitySchema('user');
     $this->installEntitySchema('comment');
     $this->installConfig(['user']);
     $entity_manager = $this->container->get('entity.manager');
     $this->commentStorage = $entity_manager->getStorage('comment');
     $this->userStorage = $entity_manager->getStorage('user');
     // Insert a row for the anonymous user.
     $this->userStorage->create(['uid' => 0, 'name' => '', 'status' => 0])->save();
     $admin_role = Role::create(['id' => 'admin']);
     $admin_role->grantPermission('administer comments');
     $admin_role->save();
     /* @var \Drupal\user\RoleInterface $anonymous_role */
     $anonymous_role = Role::load(Role::ANONYMOUS_ID);
     $anonymous_role->grantPermission('access comments');
     $anonymous_role->save();
     $this->adminUser = $this->userStorage->create(['name' => $this->randomMachineName()]);
     $this->adminUser->addRole('admin');
     $this->adminUser->save();
 }
 /**
  * {@inheritdoc}
  */
 protected function setUpFixtures()
 {
     $this->installEntitySchema('user');
     $this->installEntitySchema('entity_test');
     $this->installConfig(['entity_test']);
     EntityViewMode::create(['id' => 'entity_test.foobar', 'targetEntityType' => 'entity_test', 'status' => TRUE, 'enabled' => TRUE, 'label' => 'My view mode'])->save();
     $display = EntityViewDisplay::create(['targetEntityType' => 'entity_test', 'bundle' => 'entity_test', 'mode' => 'foobar', 'label' => 'My view mode', 'status' => TRUE]);
     $display->save();
     $field_storage = FieldStorageConfig::create(['field_name' => 'test_field', 'entity_type' => 'entity_test', 'type' => 'string']);
     $field_storage->save();
     $field_config = FieldConfig::create(['field_name' => 'test_field', 'entity_type' => 'entity_test', 'bundle' => 'entity_test']);
     $field_config->save();
     // Create some test entities.
     for ($i = 1; $i <= 3; $i++) {
         EntityTest::create(['name' => "Article title {$i}", 'test_field' => "Test {$i}"])->save();
     }
     $role = Role::create(['id' => 'test_role']);
     $role->grantPermission('bypass node access');
     $role->save();
     $this->user = User::create(['name' => 'test user']);
     $this->user->addRole($role->id());
     $this->user->save();
     parent::setUpFixtures();
 }
Example #21
0
 /**
  * Creates a role with specified permissions.
  *
  * @param array $permissions
  *   Array of permission names to assign to role.
  * @param string $rid
  *   (optional) The role ID (machine name). Defaults to a random name.
  * @param string $name
  *   (optional) The label for the role. Defaults to a random string.
  * @param int $weight
  *   (optional) The weight for the role. Defaults NULL so that entity_create()
  *   sets the weight to maximum + 1.
  *
  * @return string
  *   Role ID of newly created role, or FALSE if role creation failed.
  */
 protected function createRole(array $permissions, $rid = NULL, $name = NULL, $weight = NULL)
 {
     // Generate a random, lowercase machine name if none was passed.
     if (!isset($rid)) {
         $rid = strtolower($this->randomMachineName(8));
     }
     // Generate a random label.
     if (!isset($name)) {
         // In the role UI role names are trimmed and random string can start or
         // end with a space.
         $name = trim($this->randomString(8));
     }
     // Check the all the permissions strings are valid.
     if (!$this->checkPermissions($permissions)) {
         return FALSE;
     }
     // Create new role.
     $role = Role::create(array('id' => $rid, 'label' => $name));
     if (isset($weight)) {
         $role->set('weight', $weight);
     }
     $result = $role->save();
     $this->assertIdentical($result, SAVED_NEW, SafeMarkup::format('Created role ID @rid with name @name.', array('@name' => var_export($role->label(), TRUE), '@rid' => var_export($role->id(), TRUE))), 'Role');
     if ($result === SAVED_NEW) {
         // Grant the specified permissions to the role, if any.
         if (!empty($permissions)) {
             $this->grantPermissions($role, $permissions);
             $assigned_permissions = Role::load($role->id())->getPermissions();
             $missing_permissions = array_diff($permissions, $assigned_permissions);
             if (!$missing_permissions) {
                 $this->pass(SafeMarkup::format('Created permissions: @perms', array('@perms' => implode(', ', $permissions))), 'Role');
             } else {
                 $this->fail(SafeMarkup::format('Failed to create permissions: @perms', array('@perms' => implode(', ', $missing_permissions))), 'Role');
             }
         }
         return $role->id();
     } else {
         return FALSE;
     }
 }
 /**
  * Creates a new user account.
  *
  * @param string[] $permissions
  *   The permissions to set for the user.
  *
  * @return \Drupal\user\UserInterface
  *   The new user object.
  */
 protected function createUser($permissions)
 {
     $role = Role::create(array('id' => 'role', 'name' => 'Role test'));
     $role->save();
     user_role_grant_permissions($role->id(), $permissions);
     $values = array('uid' => 2, 'name' => 'Test', 'roles' => array($role->id()));
     $authenticated_user = User::create($values);
     $authenticated_user->enforceIsNew();
     $authenticated_user->save();
     return $authenticated_user;
 }
Example #23
0
 /**
  * Tests Standard installation profile.
  */
 function testStandard()
 {
     $this->drupalGet('');
     $this->assertLink(t('Contact'));
     $this->clickLink(t('Contact'));
     $this->assertResponse(200);
     // Test anonymous user can access 'Main navigation' block.
     $this->adminUser = $this->drupalCreateUser(array('administer blocks', 'post comments', 'skip comment approval', 'create article content', 'create page content'));
     $this->drupalLogin($this->adminUser);
     // Configure the block.
     $this->drupalGet('admin/structure/block/add/system_menu_block:main/bartik');
     $this->drupalPostForm(NULL, array('region' => 'sidebar_first', 'id' => 'main_navigation'), t('Save block'));
     // Verify admin user can see the block.
     $this->drupalGet('');
     $this->assertText('Main navigation');
     // Verify we have role = aria on system_powered_by and help_block
     // blocks.
     $this->drupalGet('admin/structure/block');
     $elements = $this->xpath('//div[@role=:role and @id=:id]', array(':role' => 'complementary', ':id' => 'block-bartik-help'));
     $this->assertEqual(count($elements), 1, 'Found complementary role on help block.');
     $this->drupalGet('');
     $elements = $this->xpath('//div[@role=:role and @id=:id]', array(':role' => 'complementary', ':id' => 'block-bartik-powered'));
     $this->assertEqual(count($elements), 1, 'Found complementary role on powered by block.');
     // Verify anonymous user can see the block.
     $this->drupalLogout();
     $this->assertText('Main navigation');
     // Ensure comments don't show in the front page RSS feed.
     // Create an article.
     $this->drupalCreateNode(array('type' => 'article', 'title' => 'Foobar', 'promote' => 1, 'status' => 1, 'body' => array(array('value' => 'Then she picked out two somebodies,<br />Sally and me', 'format' => 'basic_html'))));
     // Add a comment.
     $this->drupalLogin($this->adminUser);
     $this->drupalGet('node/1');
     $this->assertRaw('Then she picked out two somebodies,<br />Sally and me', 'Found a line break.');
     $this->drupalPostForm(NULL, array('subject[0][value]' => 'Barfoo', 'comment_body[0][value]' => 'Then she picked out two somebodies, Sally and me'), t('Save'));
     // Fetch the feed.
     $this->drupalGet('rss.xml');
     $this->assertText('Foobar');
     $this->assertNoText('Then she picked out two somebodies, Sally and me');
     // Ensure block body exists.
     $this->drupalGet('block/add');
     $this->assertFieldByName('body[0][value]');
     // Now we have all configuration imported, test all of them for schema
     // conformance. Ensures all imported default configuration is valid when
     // standard profile modules are enabled.
     $names = $this->container->get('config.storage')->listAll();
     /** @var \Drupal\Core\Config\TypedConfigManagerInterface $typed_config */
     $typed_config = $this->container->get('config.typed');
     foreach ($names as $name) {
         $config = $this->config($name);
         $this->assertConfigSchema($typed_config, $name, $config->get());
     }
     // Ensure that configuration from the Standard profile is not reused when
     // enabling a module again since it contains configuration that can not be
     // installed. For example, editor.editor.basic_html is editor configuration
     // that depends on the ckeditor module. The ckeditor module can not be
     // installed before the editor module since it depends on the editor module.
     // The installer does not have this limitation since it ensures that all of
     // the install profiles dependencies are installed before creating the
     // editor configuration.
     \Drupal::service('module_installer')->uninstall(array('editor', 'ckeditor'));
     $this->rebuildContainer();
     \Drupal::service('module_installer')->install(array('editor'));
     /** @var \Drupal\contact\ContactFormInterface $contact_form */
     $contact_form = ContactForm::load('feedback');
     $recipients = $contact_form->getRecipients();
     $this->assertEqual(['*****@*****.**'], $recipients);
     $role = Role::create(['id' => 'admin_theme', 'label' => 'Admin theme']);
     $role->grantPermission('view the administration theme');
     $role->save();
     $this->adminUser->addRole($role->id());
     $this->adminUser->save();
     $this->drupalGet('node/add');
     $this->assertResponse(200);
 }
 /**
  * Runs entity validation checks.
  */
 function testValidation()
 {
     $user = User::create(array('name' => 'test', 'mail' => '*****@*****.**'));
     $violations = $user->validate();
     $this->assertEqual(count($violations), 0, 'No violations when validating a default user.');
     // Only test one example invalid name here, the rest is already covered in
     // the testUsernames() method in this class.
     $name = $this->randomMachineName(61);
     $user->set('name', $name);
     $violations = $user->validate();
     $this->assertEqual(count($violations), 1, 'Violation found when name is too long.');
     $this->assertEqual($violations[0]->getPropertyPath(), 'name');
     $this->assertEqual($violations[0]->getMessage(), t('The username %name is too long: it must be %max characters or less.', array('%name' => $name, '%max' => 60)));
     // Create a second test user to provoke a name collision.
     $user2 = User::create(['name' => 'existing', 'mail' => '*****@*****.**']);
     $user2->save();
     $user->set('name', 'existing');
     $violations = $user->validate();
     $this->assertEqual(count($violations), 1, 'Violation found on name collision.');
     $this->assertEqual($violations[0]->getPropertyPath(), 'name');
     $this->assertEqual($violations[0]->getMessage(), t('The username %name is already taken.', array('%name' => 'existing')));
     // Make the name valid.
     $user->set('name', $this->randomMachineName());
     $user->set('mail', 'invalid');
     $violations = $user->validate();
     $this->assertEqual(count($violations), 1, 'Violation found when email is invalid');
     $this->assertEqual($violations[0]->getPropertyPath(), 'mail.0.value');
     $this->assertEqual($violations[0]->getMessage(), t('This value is not a valid email address.'));
     $mail = $this->randomMachineName(Email::EMAIL_MAX_LENGTH - 11) . '@example.com';
     $user->set('mail', $mail);
     $violations = $user->validate();
     // @todo There are two violations because EmailItem::getConstraints()
     //   overlaps with the implicit constraint of the 'email' property type used
     //   in EmailItem::propertyDefinitions(). Resolve this in
     //   https://www.drupal.org/node/2023465.
     $this->assertEqual(count($violations), 2, 'Violations found when email is too long');
     $this->assertEqual($violations[0]->getPropertyPath(), 'mail.0.value');
     $this->assertEqual($violations[0]->getMessage(), t('%name: the email address can not be longer than @max characters.', array('%name' => $user->get('mail')->getFieldDefinition()->getLabel(), '@max' => Email::EMAIL_MAX_LENGTH)));
     $this->assertEqual($violations[1]->getPropertyPath(), 'mail.0.value');
     $this->assertEqual($violations[1]->getMessage(), t('This value is not a valid email address.'));
     // Provoke an email collision with an existing user.
     $user->set('mail', '*****@*****.**');
     $violations = $user->validate();
     $this->assertEqual(count($violations), 1, 'Violation found when email already exists.');
     $this->assertEqual($violations[0]->getPropertyPath(), 'mail');
     $this->assertEqual($violations[0]->getMessage(), t('The email address %mail is already taken.', array('%mail' => '*****@*****.**')));
     $user->set('mail', NULL);
     $violations = $user->validate();
     $this->assertEqual(count($violations), 1, 'Email addresses may not be removed');
     $this->assertEqual($violations[0]->getPropertyPath(), 'mail');
     $this->assertEqual($violations[0]->getMessage(), t('@name field is required.', array('@name' => $user->getFieldDefinition('mail')->getLabel())));
     $user->set('mail', '*****@*****.**');
     $user->set('timezone', $this->randomString(33));
     $this->assertLengthViolation($user, 'timezone', 32, 2, 1);
     $user->set('timezone', 'invalid zone');
     $this->assertAllowedValuesViolation($user, 'timezone');
     $user->set('timezone', NULL);
     $user->set('init', 'invalid');
     $violations = $user->validate();
     $this->assertEqual(count($violations), 1, 'Violation found when init email is invalid');
     $user->set('init', NULL);
     $user->set('langcode', 'invalid');
     $this->assertAllowedValuesViolation($user, 'langcode');
     $user->set('langcode', NULL);
     // Only configurable langcodes are allowed for preferred languages.
     $user->set('preferred_langcode', Language::LANGCODE_NOT_SPECIFIED);
     $this->assertAllowedValuesViolation($user, 'preferred_langcode');
     $user->set('preferred_langcode', NULL);
     $user->set('preferred_admin_langcode', Language::LANGCODE_NOT_SPECIFIED);
     $this->assertAllowedValuesViolation($user, 'preferred_admin_langcode');
     $user->set('preferred_admin_langcode', NULL);
     Role::create(array('id' => 'role1'))->save();
     Role::create(array('id' => 'role2'))->save();
     // Test cardinality of user roles.
     $user = User::create(['name' => 'role_test', 'mail' => '*****@*****.**', 'roles' => array('role1', 'role2')]);
     $violations = $user->validate();
     $this->assertEqual(count($violations), 0);
     $user->roles[1]->target_id = 'unknown_role';
     $violations = $user->validate();
     $this->assertEqual(count($violations), 1);
     $this->assertEqual($violations[0]->getPropertyPath(), 'roles.1.target_id');
     $this->assertEqual($violations[0]->getMessage(), t('The referenced entity (%entity_type: %name) does not exist.', array('%entity_type' => 'user_role', '%name' => 'unknown_role')));
 }
Example #25
0
 /**
  * Tests components dependencies additions.
  */
 public function testComponentDependencies()
 {
     $this->enableModules(['dblog', 'color']);
     $this->installSchema('dblog', ['watchdog']);
     $this->installEntitySchema('user');
     /** @var \Drupal\user\RoleInterface[] $roles */
     $roles = [];
     // Create two arbitrary user roles.
     for ($i = 0; $i < 2; $i++) {
         $roles[$i] = Role::create(['id' => Unicode::strtolower($this->randomMachineName()), 'label' => $this->randomString()]);
         $roles[$i]->save();
     }
     // Create a field of type 'test_field' attached to 'entity_test'.
     $field_name = Unicode::strtolower($this->randomMachineName());
     FieldStorageConfig::create(['field_name' => $field_name, 'entity_type' => 'entity_test', 'type' => 'test_field'])->save();
     FieldConfig::create(['field_name' => $field_name, 'entity_type' => 'entity_test', 'bundle' => 'entity_test'])->save();
     // Create a new form display without components.
     /** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
     $form_display = EntityFormDisplay::create(['targetEntityType' => 'entity_test', 'bundle' => 'entity_test', 'mode' => 'default']);
     $form_display->save();
     $dependencies = ['user.role.' . $roles[0]->id(), 'user.role.' . $roles[1]->id()];
     // The config object should not depend on none of the two $roles.
     $this->assertNoDependency('config', $dependencies[0], $form_display);
     $this->assertNoDependency('config', $dependencies[1], $form_display);
     // Add a widget of type 'test_field_widget'.
     $component = ['type' => 'test_field_widget', 'settings' => ['test_widget_setting' => $this->randomString(), 'role' => $roles[0]->id(), 'role2' => $roles[1]->id()], 'third_party_settings' => ['color' => ['foo' => 'bar']]];
     $form_display->setComponent($field_name, $component);
     $form_display->save();
     // Now, the form display should depend on both user roles $roles.
     $this->assertDependency('config', $dependencies[0], $form_display);
     $this->assertDependency('config', $dependencies[1], $form_display);
     // The form display should depend on 'color' module.
     $this->assertDependency('module', 'color', $form_display);
     // Delete the first user role entity.
     $roles[0]->delete();
     // Reload the form display.
     $form_display = EntityFormDisplay::load($form_display->id());
     // The display exists.
     $this->assertFalse(empty($form_display));
     // The form display should not depend on $role[0] anymore.
     $this->assertNoDependency('config', $dependencies[0], $form_display);
     // The form display should depend on 'anonymous' user role.
     $this->assertDependency('config', 'user.role.anonymous', $form_display);
     // The form display should depend on 'color' module.
     $this->assertDependency('module', 'color', $form_display);
     // Manually trigger the removal of configuration belonging to the module
     // because KernelTestBase::disableModules() is not aware of this.
     $this->container->get('config.manager')->uninstall('module', 'color');
     // Uninstall 'color' module.
     $this->disableModules(['color']);
     // Reload the form display.
     $form_display = EntityFormDisplay::load($form_display->id());
     // The display exists.
     $this->assertFalse(empty($form_display));
     // The component is still enabled.
     $this->assertNotNull($form_display->getComponent($field_name));
     // The form display should not depend on 'color' module anymore.
     $this->assertNoDependency('module', 'color', $form_display);
     // Delete the 2nd user role entity.
     $roles[1]->delete();
     // Reload the form display.
     $form_display = EntityFormDisplay::load($form_display->id());
     // The display exists.
     $this->assertFalse(empty($form_display));
     // The component has been disabled.
     $this->assertNull($form_display->getComponent($field_name));
     $this->assertTrue($form_display->get('hidden')[$field_name]);
     // The correct warning message has been logged.
     $arguments = ['@display' => (string) t('Entity form display'), '@id' => $form_display->id(), '@name' => $field_name];
     $logged = (bool) Database::getConnection()->select('watchdog', 'w')->fields('w', ['wid'])->condition('type', 'system')->condition('message', "@display '@id': Component '@name' was disabled because its settings depend on removed dependencies.")->condition('variables', serialize($arguments))->execute()->fetchAll();
     $this->assertTrue($logged);
 }
 /**
  * Creates a user.
  *
  * @param array $values
  *   (optional) The values used to create the entity.
  * @param array $permissions
  *   (optional) Array of permission names to assign to user.
  *
  * @return \Drupal\user\Entity\User
  *   The created user entity.
  */
 protected function createUser($values = array(), $permissions = array())
 {
     if ($permissions) {
         // Create a new role and apply permissions to it.
         $role = Role::create(array('id' => strtolower($this->randomMachineName(8)), 'label' => $this->randomMachineName(8)));
         $role->save();
         user_role_grant_permissions($role->id(), $permissions);
         $values['roles'][] = $role->id();
     }
     $account = User::create($values + ['name' => $this->randomMachineName(), 'status' => 1]);
     $account->enforceIsNew();
     $account->save();
     return $account;
 }
 /**
  * Test assigning of permissions for the administrator role.
  */
 function testAdministratorRole()
 {
     $this->drupalLogin($this->adminUser);
     $this->drupalGet('admin/config/people/accounts');
     // Verify that the administration role is none by default.
     $this->assertOptionSelected('edit-user-admin-role', '', 'Administration role defaults to none.');
     $this->assertFalse(Role::load($this->rid)->isAdmin());
     // Set the user's role to be the administrator role.
     $edit = array();
     $edit['user_admin_role'] = $this->rid;
     $this->drupalPostForm('admin/config/people/accounts', $edit, t('Save configuration'));
     \Drupal::entityManager()->getStorage('user_role')->resetCache();
     $this->assertTrue(Role::load($this->rid)->isAdmin());
     // Enable aggregator module and ensure the 'administer news feeds'
     // permission is assigned by default.
     \Drupal::service('module_installer')->install(array('aggregator'));
     $this->assertTrue($this->adminUser->hasPermission('administer news feeds'), 'The permission was automatically assigned to the administrator role');
     // Ensure that selecting '- None -' removes the admin role.
     $edit = array();
     $edit['user_admin_role'] = '';
     $this->drupalPostForm('admin/config/people/accounts', $edit, t('Save configuration'));
     \Drupal::entityManager()->getStorage('user_role')->resetCache();
     \Drupal::configFactory()->reset();
     $this->assertFalse(Role::load($this->rid)->isAdmin());
     // Manually create two admin roles, in that case the single select should be
     // hidden.
     Role::create(['id' => 'admin_role_0', 'is_admin' => TRUE, 'label' => 'Admin role 0'])->save();
     Role::create(['id' => 'admin_role_1', 'is_admin' => TRUE, 'label' => 'Admin role 1'])->save();
     $this->drupalGet('admin/config/people/accounts');
     $this->assertNoFieldByName('user_admin_role');
 }
Example #28
0
 /**
  * Tests block_user_role_delete.
  */
 public function testBlockUserRoleDelete()
 {
     $role1 = Role::create(['id' => 'test_role1', 'name' => $this->randomString()]);
     $role1->save();
     $role2 = Role::create(['id' => 'test_role2', 'name' => $this->randomString()]);
     $role2->save();
     $block = Block::create(['id' => $this->randomMachineName(), 'plugin' => 'system_powered_by_block']);
     $block->setVisibilityConfig('user_role', ['roles' => [$role1->id() => $role1->id(), $role2->id() => $role2->id()]]);
     $block->save();
     $this->assertEqual($block->getVisibility()['user_role']['roles'], [$role1->id() => $role1->id(), $role2->id() => $role2->id()]);
     $role1->delete();
     $block = Block::load($block->id());
     $this->assertEqual($block->getVisibility()['user_role']['roles'], [$role2->id() => $role2->id()]);
 }
Example #29
0
 /**
  * Tests Standard installation profile.
  */
 function testStandard()
 {
     $this->drupalGet('');
     $this->assertLink(t('Contact'));
     $this->clickLink(t('Contact'));
     $this->assertResponse(200);
     // Test anonymous user can access 'Main navigation' block.
     $this->adminUser = $this->drupalCreateUser(array('administer blocks', 'post comments', 'skip comment approval', 'create article content', 'create page content'));
     $this->drupalLogin($this->adminUser);
     // Configure the block.
     $this->drupalGet('admin/structure/block/add/system_menu_block:main/bartik');
     $this->drupalPostForm(NULL, array('region' => 'sidebar_first', 'id' => 'main_navigation'), t('Save block'));
     // Verify admin user can see the block.
     $this->drupalGet('');
     $this->assertText('Main navigation');
     // Verify we have role = aria on system_powered_by and help_block
     // blocks.
     $this->drupalGet('admin/structure/block');
     $elements = $this->xpath('//div[@role=:role and @id=:id]', array(':role' => 'complementary', ':id' => 'block-bartik-help'));
     $this->assertEqual(count($elements), 1, 'Found complementary role on help block.');
     $this->drupalGet('');
     $elements = $this->xpath('//div[@role=:role and @id=:id]', array(':role' => 'complementary', ':id' => 'block-bartik-powered'));
     $this->assertEqual(count($elements), 1, 'Found complementary role on powered by block.');
     // Verify anonymous user can see the block.
     $this->drupalLogout();
     $this->assertText('Main navigation');
     // Ensure comments don't show in the front page RSS feed.
     // Create an article.
     $this->drupalCreateNode(array('type' => 'article', 'title' => 'Foobar', 'promote' => 1, 'status' => 1, 'body' => array(array('value' => 'Then she picked out two somebodies,<br />Sally and me', 'format' => 'basic_html'))));
     // Add a comment.
     $this->drupalLogin($this->adminUser);
     $this->drupalGet('node/1');
     $this->assertRaw('Then she picked out two somebodies,<br />Sally and me', 'Found a line break.');
     $this->drupalPostForm(NULL, array('subject[0][value]' => 'Barfoo', 'comment_body[0][value]' => 'Then she picked out two somebodies, Sally and me'), t('Save'));
     // Fetch the feed.
     $this->drupalGet('rss.xml');
     $this->assertText('Foobar');
     $this->assertNoText('Then she picked out two somebodies, Sally and me');
     // Ensure block body exists.
     $this->drupalGet('block/add');
     $this->assertFieldByName('body[0][value]');
     // Now we have all configuration imported, test all of them for schema
     // conformance. Ensures all imported default configuration is valid when
     // standard profile modules are enabled.
     $names = $this->container->get('config.storage')->listAll();
     /** @var \Drupal\Core\Config\TypedConfigManagerInterface $typed_config */
     $typed_config = $this->container->get('config.typed');
     foreach ($names as $name) {
         $config = $this->config($name);
         $this->assertConfigSchema($typed_config, $name, $config->get());
     }
     // Ensure that configuration from the Standard profile is not reused when
     // enabling a module again since it contains configuration that can not be
     // installed. For example, editor.editor.basic_html is editor configuration
     // that depends on the ckeditor module. The ckeditor module can not be
     // installed before the editor module since it depends on the editor module.
     // The installer does not have this limitation since it ensures that all of
     // the install profiles dependencies are installed before creating the
     // editor configuration.
     foreach (FilterFormat::loadMultiple() as $filter) {
         // Ensure that editor can be uninstalled by removing use in filter
         // formats. It is necessary to prime the filter collection before removing
         // the filter.
         $filter->filters();
         $filter->removeFilter('editor_file_reference');
         $filter->save();
     }
     \Drupal::service('module_installer')->uninstall(array('editor', 'ckeditor'));
     $this->rebuildContainer();
     \Drupal::service('module_installer')->install(array('editor'));
     /** @var \Drupal\contact\ContactFormInterface $contact_form */
     $contact_form = ContactForm::load('feedback');
     $recipients = $contact_form->getRecipients();
     $this->assertEqual(['*****@*****.**'], $recipients);
     $role = Role::create(['id' => 'admin_theme', 'label' => 'Admin theme']);
     $role->grantPermission('view the administration theme');
     $role->save();
     $this->adminUser->addRole($role->id());
     $this->adminUser->save();
     $this->drupalGet('node/add');
     $this->assertResponse(200);
     // Ensure that there are no pending updates after installation.
     $this->drupalLogin($this->rootUser);
     $this->drupalGet('update.php/selection');
     $this->assertText('No pending updates.');
     // Ensure that there are no pending entity updates after installation.
     $this->assertFalse($this->container->get('entity.definition_update_manager')->needsUpdates(), 'After installation, entity schema is up to date.');
     // Make sure the optional image styles are not installed.
     $this->drupalGet('admin/config/media/image-styles');
     $this->assertNoText('Max 325x325');
     $this->assertNoText('Max 650x650');
     $this->assertNoText('Max 1300x1300');
     $this->assertNoText('Max 2600x2600');
     // Make sure the optional image styles are installed after enabling
     // the responsive_image module.
     \Drupal::service('module_installer')->install(array('responsive_image'));
     $this->rebuildContainer();
     $this->drupalGet('admin/config/media/image-styles');
     $this->assertText('Max 325x325');
     $this->assertText('Max 650x650');
     $this->assertText('Max 1300x1300');
     $this->assertText('Max 2600x2600');
     // Verify certain routes' responses are cacheable by Dynamic Page Cache, to
     // ensure these responses are very fast for authenticated users.
     $this->dumpHeaders = TRUE;
     $this->drupalLogin($this->adminUser);
     $url = Url::fromRoute('contact.site_page');
     $this->drupalGet($url);
     $this->assertEqual('UNCACHEABLE', $this->drupalGetHeader(DynamicPageCacheSubscriber::HEADER), 'Site-wide contact page cannot be cached by Dynamic Page Cache.');
     $url = Url::fromRoute('<front>');
     $this->drupalGet($url);
     $this->drupalGet($url);
     $this->assertEqual('HIT', $this->drupalGetHeader(DynamicPageCacheSubscriber::HEADER), 'Frontpage is cached by Dynamic Page Cache.');
     // @todo uncomment after https://www.drupal.org/node/2543334 has landed.
     //url = Url::fromRoute('entity.node.canonical', ['node' => 1]);
     //$this->drupalGet($url);
     //$this->drupalGet($url);
     //$this->assertEqual('HIT', $this->drupalGetHeader(DynamicPageCacheSubscriber::HEADER), 'Full node page is cached by Dynamic Page Cache.');
     $url = Url::fromRoute('entity.user.canonical', ['user' => 1]);
     $this->drupalGet($url);
     $this->drupalGet($url);
     $this->assertEqual('HIT', $this->drupalGetHeader(DynamicPageCacheSubscriber::HEADER), 'User profile page is cached by Dynamic Page Cache.');
 }