/** * Tests that fields are synchronized using the Subscriber form. */ public function testSubscriberFormFieldSync() { // Create a subscriber for the user. $subscriber = Subscriber::create(array('uid' => $this->user->id(), 'mail' => '*****@*****.**')); $subscriber->save(); // Edit subscriber field and assert user field is changed accordingly. $this->drupalLogin($this->user); $this->drupalGet('admin/people/simplenews/edit/' . $subscriber->id()); $this->assertField('field_shared[0][value]'); $this->assertRaw($this->user->field_shared->value); $new_value = $this->randomMachineName(); $this->drupalPostForm(NULL, array('field_shared[0][value]' => $new_value), t('Save')); $this->drupalGet('admin/people/simplenews/edit/' . $subscriber->id()); $this->assertRaw($new_value); $this->user = User::load($this->user->id()); $this->assertEqual($this->user->field_shared->value, $new_value); // Unset the sync setting and assert field is not synced. $this->drupalPostForm('admin/config/people/simplenews/settings/subscriber', array('simplenews_sync_fields' => FALSE), t('Save configuration')); $unsynced_value = $this->randomMachineName(); $this->drupalPostForm('admin/people/simplenews/edit/' . $subscriber->id(), array('field_shared[0][value]' => $unsynced_value), t('Save')); $this->drupalGet('admin/people/simplenews/edit/' . $subscriber->id()); $this->assertRaw($unsynced_value); $this->user = User::load($this->user->id()); $this->assertEqual($this->user->field_shared->value, $new_value); $this->assertNotEqual($this->user->field_shared->value, $unsynced_value); }
/** * Tests the node comment statistics. */ function testCommentNodeCommentStatistics() { $node_storage = $this->container->get('entity.manager')->getStorage('node'); // Set comments to have subject and preview disabled. $this->drupalLogin($this->adminUser); $this->setCommentPreview(DRUPAL_DISABLED); $this->setCommentForm(TRUE); $this->setCommentSubject(FALSE); $this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Comment paging changed.'); $this->drupalLogout(); // Checks the initial values of node comment statistics with no comment. $node = $node_storage->load($this->node->id()); $this->assertEqual($node->get('comment')->last_comment_timestamp, $this->node->getCreatedTime(), 'The initial value of node last_comment_timestamp is the node created date.'); $this->assertEqual($node->get('comment')->last_comment_name, NULL, 'The initial value of node last_comment_name is NULL.'); $this->assertEqual($node->get('comment')->last_comment_uid, $this->webUser->id(), 'The initial value of node last_comment_uid is the node uid.'); $this->assertEqual($node->get('comment')->comment_count, 0, 'The initial value of node comment_count is zero.'); // Post comment #1 as web_user2. $this->drupalLogin($this->webUser2); $comment_text = $this->randomMachineName(); $this->postComment($this->node, $comment_text); // Checks the new values of node comment statistics with comment #1. // The node cache needs to be reset before reload. $node_storage->resetCache(array($this->node->id())); $node = $node_storage->load($this->node->id()); $this->assertEqual($node->get('comment')->last_comment_name, NULL, 'The value of node last_comment_name is NULL.'); $this->assertEqual($node->get('comment')->last_comment_uid, $this->webUser2->id(), 'The value of node last_comment_uid is the comment #1 uid.'); $this->assertEqual($node->get('comment')->comment_count, 1, 'The value of node comment_count is 1.'); // Prepare for anonymous comment submission (comment approval enabled). $this->drupalLogin($this->adminUser); user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array('access comments' => TRUE, 'post comments' => TRUE, 'skip comment approval' => FALSE)); // Ensure that the poster can leave some contact info. $this->setCommentAnonymous('1'); $this->drupalLogout(); // Post comment #2 as anonymous (comment approval enabled). $this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment'); $anonymous_comment = $this->postComment($this->node, $this->randomMachineName(), '', TRUE); // Checks the new values of node comment statistics with comment #2 and // ensure they haven't changed since the comment has not been moderated. // The node needs to be reloaded with the cache reset. $node_storage->resetCache(array($this->node->id())); $node = $node_storage->load($this->node->id()); $this->assertEqual($node->get('comment')->last_comment_name, NULL, 'The value of node last_comment_name is still NULL.'); $this->assertEqual($node->get('comment')->last_comment_uid, $this->webUser2->id(), 'The value of node last_comment_uid is still the comment #1 uid.'); $this->assertEqual($node->get('comment')->comment_count, 1, 'The value of node comment_count is still 1.'); // Prepare for anonymous comment submission (no approval required). $this->drupalLogin($this->adminUser); user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array('access comments' => TRUE, 'post comments' => TRUE, 'skip comment approval' => TRUE)); $this->drupalLogout(); // Post comment #3 as anonymous. $this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment'); $anonymous_comment = $this->postComment($this->node, $this->randomMachineName(), '', array('name' => $this->randomMachineName())); $comment_loaded = Comment::load($anonymous_comment->id()); // Checks the new values of node comment statistics with comment #3. // The node needs to be reloaded with the cache reset. $node_storage->resetCache(array($this->node->id())); $node = $node_storage->load($this->node->id()); $this->assertEqual($node->get('comment')->last_comment_name, $comment_loaded->getAuthorName(), 'The value of node last_comment_name is the name of the anonymous user.'); $this->assertEqual($node->get('comment')->last_comment_uid, 0, 'The value of node last_comment_uid is zero.'); $this->assertEqual($node->get('comment')->comment_count, 2, 'The value of node comment_count is 2.'); }
/** * Tests tabs in profile UI. */ public function testProfileTabs() { $types_data = ['profile_type_0' => ['label' => $this->randomMachineName()], 'profile_type_1' => ['label' => $this->randomMachineName()]]; /** @var ProfileType[] $types */ $types = []; foreach ($types_data as $id => $values) { $types[$id] = ProfileType::create(['id' => $id] + $values); $types[$id]->save(); } $this->container->get('router.builder')->rebuild(); $this->user1 = User::create(['name' => $this->randomMachineName(), 'mail' => $this->randomMachineName() . '@example.com']); $this->user1->save(); $this->user2 = User::create(['name' => $this->randomMachineName(), 'mail' => $this->randomMachineName() . '@example.com']); $this->user2->save(); // Create new profiles. $profile1 = Profile::create($expected = ['type' => $types['profile_type_0']->id(), 'uid' => $this->user1->id()]); $profile1->save(); $profile2 = Profile::create($expected = ['type' => $types['profile_type_1']->id(), 'uid' => $this->user2->id()]); $profile2->save(); $this->drupalLogin($this->adminUser); $this->drupalGet('admin/config'); $this->clickLink('User profiles'); $this->assertResponse(200); $this->assertUrl('admin/config/people/profiles'); $this->assertLink($profile1->label()); $this->assertLinkByHref($profile2->toUrl('canonical')->toString()); $tasks = [['entity.profile.collection', []], ['entity.profile_type.collection', []]]; $this->assertLocalTasks($tasks, 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()); }
/** * {@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(); }
/** * Test the Who's Online block. */ function testWhosOnlineBlock() { $block = $this->drupalPlaceBlock('views_block:who_s_online-who_s_online_block'); // Generate users. $user1 = $this->drupalCreateUser(array('access user profiles')); $user2 = $this->drupalCreateUser(array()); $user3 = $this->drupalCreateUser(array()); // Update access of two users to be within the active timespan. $this->updateAccess($user1->id()); $this->updateAccess($user2->id(), REQUEST_TIME + 1); // Insert an inactive user who should not be seen in the block, and ensure // that the admin user used in setUp() does not appear. $inactive_time = REQUEST_TIME - 15 * 60 - 1; $this->updateAccess($user3->id(), $inactive_time); $this->updateAccess($this->adminUser->id(), $inactive_time); // Test block output. \Drupal::currentUser()->setAccount($user1); $content = entity_view($block, 'block'); $this->drupalSetContent(render($content)); $this->assertRaw(t('2 users'), 'Correct number of online users (2 users).'); $this->assertText($user1->getUsername(), 'Active user 1 found in online list.'); $this->assertText($user2->getUsername(), 'Active user 2 found in online list.'); $this->assertNoText($user3->getUsername(), 'Inactive user not found in online list.'); $this->assertTrue(strpos($this->drupalGetContent(), $user1->getUsername()) > strpos($this->drupalGetContent(), $user2->getUsername()), 'Online users are ordered correctly.'); }
public function userProfileForm(RouteMatchInterface $route_match, UserInterface $user, ProfileTypeInterface $profile_type) { $profile = $this->entityManager()->getStorage('profile')->create([ 'uid' => $user->id(), 'type' => $profile_type->id(), ]); return $this->entityFormBuilder()->getForm($profile, 'add', ['uid' => $user->id(), 'created' => REQUEST_TIME]); }
/** * Tests password reset functionality. */ function testUserPasswordReset() { // Try to reset the password for an invalid account. $this->drupalGet('user/password'); $edit = array('name' => $this->randomName(32)); $this->drupalPostForm(NULL, $edit, t('Email new password')); $this->assertText(t('Sorry, @name is not recognized as a username or an email address.', array('@name' => $edit['name'])), 'Validation error message shown when trying to request password for invalid account.'); $this->assertEqual(count($this->drupalGetMails(array('id' => 'user_password_reset'))), 0, 'No email was sent when requesting a password for an invalid account.'); // Reset the password by username via the password reset page. $edit['name'] = $this->account->getUsername(); $this->drupalPostForm(NULL, $edit, t('Email new password')); // Verify that the user was sent an email. $this->assertMail('to', $this->account->getEmail(), 'Password email sent to user.'); $subject = t('Replacement login information for @username at @site', array('@username' => $this->account->getUsername(), '@site' => \Drupal::config('system.site')->get('name'))); $this->assertMail('subject', $subject, 'Password reset email subject is correct.'); $resetURL = $this->getResetURL(); $this->drupalGet($resetURL); // Check the one-time login page. $this->assertText($this->account->getUsername(), 'One-time login page contains the correct username.'); $this->assertText(t('This login can be used only once.'), 'Found warning about one-time login.'); // Check successful login. $this->drupalPostForm(NULL, NULL, t('Log in')); $this->assertLink(t('Log out')); $this->assertTitle(t('@name | @site', array('@name' => $this->account->getUsername(), '@site' => \Drupal::config('system.site')->get('name'))), 'Logged in using password reset link.'); // Change the forgotten password. $password = user_password(); $edit = array('pass[pass1]' => $password, 'pass[pass2]' => $password); $this->drupalPostForm(NULL, $edit, t('Save')); $this->assertText(t('The changes have been saved.'), 'Forgotten password changed.'); // Verify that the password reset session has been destroyed. $this->drupalPostForm(NULL, $edit, t('Save')); $this->assertText(t('Your current password is missing or incorrect; it\'s required to change the Password.'), 'Password needed to make profile changes.'); // Log out, and try to log in again using the same one-time link. $this->drupalLogout(); $this->drupalGet($resetURL); $this->assertText(t('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.'), 'One-time link is no longer valid.'); // Request a new password again, this time using the email address. $this->drupalGet('user/password'); // Count email messages before to compare with after. $before = count($this->drupalGetMails(array('id' => 'user_password_reset'))); $edit = array('name' => $this->account->getEmail()); $this->drupalPostForm(NULL, $edit, t('Email new password')); $this->assertTrue(count($this->drupalGetMails(array('id' => 'user_password_reset'))) === $before + 1, 'Email sent when requesting password reset using email address.'); // Create a password reset link as if the request time was 60 seconds older than the allowed limit. $timeout = \Drupal::config('user.settings')->get('password_reset_timeout'); $bogus_timestamp = REQUEST_TIME - $timeout - 60; $_uid = $this->account->id(); $this->drupalGet("user/reset/{$_uid}/{$bogus_timestamp}/" . user_pass_rehash($this->account->getPassword(), $bogus_timestamp, $this->account->getLastLoginTime())); $this->assertText(t('You have tried to use a one-time login link that has expired. Please request a new one using the form below.'), 'Expired password reset request rejected.'); // Create a user, block the account, and verify that a login link is denied. $timestamp = REQUEST_TIME - 1; $blocked_account = $this->drupalCreateUser()->block(); $blocked_account->save(); $this->drupalGet("user/reset/" . $blocked_account->id() . "/{$timestamp}/" . user_pass_rehash($blocked_account->getPassword(), $timestamp, $blocked_account->getLastLoginTime())); $this->assertResponse(403); }
public function flickr_photos_access(\Drupal\user\UserInterface $user, Drupal\Core\Session\AccountInterface $account) { $view_access = FALSE; if (!empty($user) && $user->id()) { if (isset($user->flickr['nsid'])) { $view_access = \Drupal::currentUser()->hasPermission('administer flickr') || $user->status && (\Drupal::currentUser()->hasPermission('view all flickr photos') || \Drupal::currentUser()->hasPermission('view own flickr photos') && \Drupal::currentUser()->uid == $user->id()); } } return $view_access; }
public function testUserEntityClone() { $this->drupalPostForm('entity_clone/user/' . $this->adminUser->id(), [], t('Clone')); $users = \Drupal::entityTypeManager() ->getStorage('user') ->loadByProperties([ 'name' => 'test_user_cloned', ]); $user = reset($users); $this->assertTrue($user, 'Test user cloned found in database.'); }
/** * Tests customer overview. */ public function testCustomerAdminPages() { $this->drupalLogin($this->adminUser); $country = Country::load('US'); Order::create(array('uid' => $this->customer->id(), 'billing_country' => $country->id(), 'billing_zone' => 'AK'))->save(); $this->drupalGet('admin/store/customers/view'); $this->assertResponse(200); $this->assertLinkByHref('user/' . $this->customer->id()); $this->assertText($country->getZones()['AK']); $this->assertText($country->label()); }
protected function setUp() { parent::setUp(); // Create Basic page node type. if ($this->profile != 'standard') { $this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page')); } $this->privilegedUser = $this->drupalCreateUser(array('administer statistics', 'view post access counter', 'create page content')); $this->drupalLogin($this->privilegedUser); $this->testNode = $this->drupalCreateNode(array('type' => 'page', 'uid' => $this->privilegedUser->id())); $this->client = \Drupal::service('http_client_factory')->fromOptions(['config/curl' => [CURLOPT_TIMEOUT => 10]]); }
/** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->installEntitySchema('file'); $this->installEntitySchema('user'); $this->installSchema('file', array('file_usage')); $this->installSchema('system', 'sequences'); $this->user1 = User::create(['name' => 'user1', 'status' => 1]); $this->user1->save(); $this->user2 = User::create(['name' => 'user2', 'status' => 1]); $this->user2->save(); $this->file = File::create(array('uid' => $this->user1->id(), 'filename' => 'druplicon.txt', 'filemime' => 'text/plain')); }
/** * Test label callback. */ function testLabelCallback() { $this->assertEqual($this->account->label(), $this->account->getUsername(), 'The username should be used as label'); // Setup a random anonymous name to be sure the name is used. $name = $this->randomMachineName(); $this->config('user.settings')->set('anonymous', $name)->save(); $this->assertEqual($this->anonymous->label(), $name, 'The variable anonymous should be used for name of uid 0'); $this->assertEqual($this->anonymous->getDisplayName(), $name, 'The variable anonymous should be used for display name of uid 0'); $this->assertEqual($this->anonymous->getUserName(), '', 'The raw anonymous user name should be empty string'); // Set to test the altered username. \Drupal::state()->set('user_hooks_test_user_format_name_alter', TRUE); $this->assertEqual($this->account->getDisplayName(), '<em>' . $this->account->id() . '</em>', 'The user display name should be altered.'); $this->assertEqual($this->account->getUsername(), $this->account->name->value, 'The user name should not be altered.'); }
/** * Tests that existing nodes are indexed by cron. */ function testTrackerCronIndexing() { $this->drupalLogin($this->user); // Create 3 nodes. $edits = array(); $nodes = array(); for ($i = 1; $i <= 3; $i++) { $edits[$i] = array('title' => $this->randomMachineName()); $nodes[$i] = $this->drupalCreateNode($edits[$i]); } // Add a comment to the last node as other user. $this->drupalLogin($this->otherUser); $comment = array('subject[0][value]' => $this->randomMachineName(), 'comment_body[0][value]' => $this->randomMachineName(20)); $this->drupalPostForm('comment/reply/node/' . $nodes[3]->id() . '/comment', $comment, t('Save')); // Start indexing backwards from node 3. \Drupal::state()->set('tracker.index_nid', 3); // Clear the current tracker tables and rebuild them. db_delete('tracker_node')->execute(); db_delete('tracker_user')->execute(); tracker_cron(); $this->drupalLogin($this->user); // Fetch the user's tracker. $this->drupalGet('activity/' . $this->user->id()); // Assert that all node titles are displayed. foreach ($nodes as $i => $node) { $this->assertText($node->label(), format_string('Node @i is displayed on the tracker listing pages.', array('@i' => $i))); } // Fetch the site-wide tracker. $this->drupalGet('activity'); // Assert that all node titles are displayed. foreach ($nodes as $i => $node) { $this->assertText($node->label(), format_string('Node @i is displayed on the tracker listing pages.', array('@i' => $i))); } }
/** * Tests that an admin user with "administer permissions" can add all roles. */ function testRoleAssignAdminUser() { // Login as admin user $this->drupalLogin($this->admin_user); // Load account edit page $this->drupalGet('user/' . $this->testaccount->id() . '/edit'); // Check that Drupal default roles checkboxes are shown. $this->assertText(t('Roles')); $this->assertNoFieldChecked('edit-roles-editor'); $this->assertNoFieldChecked('edit-roles-webmaster'); $this->assertNoFieldChecked('edit-roles-siteadmin'); // Assign the role "SiteAdmin" to the account. $this->drupalPostForm('user/' . $this->testaccount->id() . '/edit', array("roles[siteadmin]" => "siteadmin"), t('Save')); $this->assertText(t('The changes have been saved.')); $this->assertFieldChecked('edit-roles-siteadmin', 'Role siteadmin is assigned.'); $this->userLoadAndCheckRoleAssigned($this->testaccount, 'siteadmin'); $this->userLoadAndCheckRoleAssigned($this->testaccount, RoleInterface::AUTHENTICATED_ID); // Now log in as restricted user again $this->drupalLogin($this->restricted_user); // Assign the role "editor" to the account, and test that the assigned // "siteadmin" role doesn't get lost. $this->drupalPostForm('user/' . $this->testaccount->id() . '/edit', array("roles[editor]" => "editor"), t('Save')); $this->assertText(t('The changes have been saved.')); $this->assertFieldChecked('edit-roles-editor', 'Role editor is assigned.'); $this->assertNoField('edit-roles-siteadmin'); $this->userLoadAndCheckRoleAssigned($this->testaccount, 'editor'); $this->userLoadAndCheckRoleAssigned($this->testaccount, RoleInterface::AUTHENTICATED_ID); $this->userLoadAndCheckRoleAssigned($this->testaccount, 'siteadmin'); }
/** * Returns the list of consumers for a user. * * @param \Drupal\user\UserInterface $user * A user account object. * * @return string * A HTML-formatted string with the list of OAuth consumers. */ public function consumers(UserInterface $user) { $list = array(); $list['#cache']['tags'] = array('oauth:' => $user->id()); $list['heading']['#markup'] = $this->linkGenerator->generate($this->t('Add consumer'), Url::fromRoute('oauth.user_consumer_add', array('user' => $user->id()))); // Get the list of consumers. $result = $this->user_data->get('oauth', $user->id()); // Define table headers. $list['table'] = array('#theme' => 'table', '#header' => array('consumer_key' => array('data' => $this->t('Consumer key')), 'consumer_secret' => array('data' => $this->t('Consumer secret')), 'operations' => array('data' => $this->t('Operations'))), '#rows' => array()); // Add existing consumers to the table. foreach ($result as $key => $consumer) { $list['table']['#rows'][] = array('data' => array('consumer_key' => $key, 'consumer_secret' => $consumer['consumer_secret'], 'operations' => array('data' => array('#type' => 'operations', '#links' => array('delete' => array('title' => $this->t('Delete'), 'url' => Url::fromRoute('oauth.user_consumer_delete', array('user' => $user->id(), 'key' => $key)))))))); } $list['table']['#empty'] = $this->t('There are no OAuth consumers.'); return $list; }
/** * Tests that default handlers are added even if custom are specified. */ public function testPathElement() { $form_state = (new FormState())->setValues(['required_validate' => 'user/' . $this->testUser->id(), 'required_non_validate' => 'magic-ponies', 'required_validate_route' => 'user/' . $this->testUser->id(), 'required_validate_url' => 'user/' . $this->testUser->id()]); $form_builder = $this->container->get('form_builder'); $form_builder->submitForm($this, $form_state); // Valid form state. $this->assertEqual(count($form_state->getErrors()), 0); $this->assertEqual($form_state->getValue('required_validate_route'), array('route_name' => 'entity.user.canonical', 'route_parameters' => array('user' => $this->testUser->id()))); /** @var \Drupal\Core\Url $url */ $url = $form_state->getValue('required_validate_url'); $this->assertTrue($url instanceof Url); $this->assertEqual($url->getRouteName(), 'entity.user.canonical'); $this->assertEqual($url->getRouteParameters(), array('user' => $this->testUser->id())); // Test #required. $form_state = (new FormState())->setValues(['required_non_validate' => 'magic-ponies', 'required_validate_route' => 'user/' . $this->testUser->id(), 'required_validate_url' => 'user/' . $this->testUser->id()]); $form_builder->submitForm($this, $form_state); $errors = $form_state->getErrors(); // Should be missing 'required_validate' field. $this->assertEqual(count($errors), 1); $this->assertEqual($errors, array('required_validate' => t('@name field is required.', array('@name' => 'required_validate')))); // Test invalid parameters. $form_state = (new FormState())->setValues(['required_validate' => 'user/74', 'required_non_validate' => 'magic-ponies', 'required_validate_route' => 'user/74', 'required_validate_url' => 'user/74']); $form_builder = $this->container->get('form_builder'); $form_builder->submitForm($this, $form_state); // Valid form state. $errors = $form_state->getErrors(); $this->assertEqual(count($errors), 3); $this->assertEqual($errors, array('required_validate' => t('This path does not exist or you do not have permission to link to %path.', array('%path' => 'user/74')), 'required_validate_route' => t('This path does not exist or you do not have permission to link to %path.', array('%path' => 'user/74')), 'required_validate_url' => t('This path does not exist or you do not have permission to link to %path.', array('%path' => 'user/74')))); }
/** * @inheritdoc */ public function save(UserInterface $account, $provider, $authname, $data = NULL) { if (!is_scalar($data)) { $data = serialize($data); } $this->connection->merge('authmap')->keys(array('uid' => $account->id(), 'provider' => $provider))->fields(array('authname' => $authname, 'data' => $data))->execute(); }
/** * Tests CRUD operations for profile types through the UI. */ public function testCRUDUI() { $types_data = ['profile_type_0' => ['label' => $this->randomMachineName()], 'profile_type_1' => ['label' => $this->randomMachineName()]]; /** @var ProfileType[] $types */ $types = []; foreach ($types_data as $id => $values) { $types[$id] = $this->createProfileType($id, $values['label']); } $this->user1 = User::create(['name' => $this->randomMachineName(), 'mail' => $this->randomMachineName() . '@example.com']); $this->user1->save(); $this->user2 = User::create(['name' => $this->randomMachineName(), 'mail' => $this->randomMachineName() . '@example.com']); $this->user2->save(); // Create new profiles. $profile1 = Profile::create($expected = ['type' => $types['profile_type_0']->id(), 'uid' => $this->user1->id()]); $profile1->save(); $profile2 = Profile::create($expected = ['type' => $types['profile_type_1']->id(), 'uid' => $this->user2->id()]); $profile2->save(); $this->drupalLogin($this->adminUser); $this->drupalGet('admin/config'); $this->clickLink('User profiles'); $this->assertResponse(200); $this->assertUrl('admin/config/people/profiles'); $this->assertLink($profile1->label()); $this->assertLinkByHref($profile2->toUrl('canonical')->toString()); }
/** * Tests the views wizards provided by the media module. */ public function testMediaViewsWizard() { $data = ['name' => $this->randomMachineName(), 'bundle' => $this->testBundle->id(), 'type' => 'Unknown', 'uid' => $this->adminUser->id(), 'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(), 'status' => Media::PUBLISHED]; $media = Media::create($data); $media->save(); // Test the Media wizard. $this->drupalPostForm('admin/structure/views/add', ['label' => 'media view', 'id' => 'media_test', 'show[wizard_key]' => 'media', 'page[create]' => 1, 'page[title]' => 'media_test', 'page[path]' => 'media_test'], t('Save and edit')); $this->drupalGet('media_test'); $this->assertText($data['name']); user_role_revoke_permissions('anonymous', ['access content']); $this->drupalLogout(); $this->drupalGet('media_test'); $this->assertResponse(403); $this->drupalLogin($this->adminUser); // Test the MediaRevision wizard. $this->drupalPostForm('admin/structure/views/add', ['label' => 'media revision view', 'id' => 'media_revision', 'show[wizard_key]' => 'media_revision', 'page[create]' => 1, 'page[title]' => 'media_revision', 'page[path]' => 'media_revision'], t('Save and edit')); $this->drupalGet('media_revision'); // Check only for the label of the changed field as we want to only test // if the field is present and not its value. $this->assertText($data['name']); user_role_revoke_permissions('anonymous', ['view revisions']); $this->drupalLogout(); $this->drupalGet('media_revision'); $this->assertResponse(403); }
/** * Checks that the "authored by" works correctly with various values. * * @param \Drupal\node\NodeInterface $node * A node object. * @param string $form_element_name * The name of the form element to populate. */ protected function checkVariousAuthoredByValues(NodeInterface $node, $form_element_name) { // Try to change the 'authored by' field to an invalid user name. $edit = array($form_element_name => 'invalid-name'); $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save and keep published')); $this->assertRaw(t('There are no entities matching "%name".', array('%name' => 'invalid-name'))); // Change the authored by field to an empty string, which should assign // authorship to the anonymous user (uid 0). $edit[$form_element_name] = ''; $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save and keep published')); $this->nodeStorage->resetCache(array($node->id())); $node = $this->nodeStorage->load($node->id()); $uid = $node->getOwnerId(); // Most SQL database drivers stringify fetches but entities are not // necessarily stored in a SQL database. At the same time, NULL/FALSE/"" // won't do. $this->assertTrue($uid === 0 || $uid === '0', 'Node authored by anonymous user.'); // Change the authored by field to another user's name (that is not // logged in). $edit[$form_element_name] = $this->webUser->getUsername(); $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save and keep published')); $this->nodeStorage->resetCache(array($node->id())); $node = $this->nodeStorage->load($node->id()); $this->assertIdentical($node->getOwnerId(), $this->webUser->id(), 'Node authored by normal user.'); }
/** * Tests loading default from storage handler. */ public function testLoadDefaultProfile() { $profile_type = $this->createProfileType('test_defaults', 'test_defaults'); // Create new profiles. $profile1 = Profile::create($expected = ['type' => $profile_type->id(), 'uid' => $this->user1->id()]); $profile1->setActive(TRUE); $profile1->save(); $profile2 = Profile::create($expected = ['type' => $profile_type->id(), 'uid' => $this->user1->id()]); $profile2->setActive(TRUE); $profile2->setDefault(TRUE); $profile2->save(); /** @var \Drupal\profile\ProfileStorageInterface $storage */ $storage = \Drupal::entityTypeManager()->getStorage('profile'); $default_profile = $storage->loadDefaultByUser($this->user1, $profile_type->id()); $this->assertEqual($profile2->id(), $default_profile->id()); }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $account = $this->currentUser(); $account_is_user = $this->user->id() == $account->id(); if ($form_state->getValue('set') == 'new') { // Save a new shortcut set with links copied from the user's default set. /* @var \Drupal\shortcut\Entity\ShortcutSet $set */ $set = $this->shortcutSetStorage->create(array('id' => $form_state->getValue('id'), 'label' => $form_state->getValue('label'))); $set->save(); $replacements = array('%user' => $this->user->label(), '%set_name' => $set->label(), ':switch-url' => $this->url('<current>')); if ($account_is_user) { // Only administrators can create new shortcut sets, so we know they have // access to switch back. drupal_set_message($this->t('You are now using the new %set_name shortcut set. You can edit it from this page or <a href=":switch-url">switch back to a different one.</a>', $replacements)); } else { drupal_set_message($this->t('%user is now using a new shortcut set called %set_name. You can edit it from this page.', $replacements)); } $form_state->setRedirect('entity.shortcut_set.customize_form', array('shortcut_set' => $set->id())); } else { // Switch to a different shortcut set. /* @var \Drupal\shortcut\Entity\ShortcutSet $set */ $set = $this->shortcutSetStorage->load($form_state->getValue('set')); $replacements = array('%user' => $this->user->getDisplayName(), '%set_name' => $set->label()); drupal_set_message($account_is_user ? $this->t('You are now using the %set_name shortcut set.', $replacements) : $this->t('%user is now using the %set_name shortcut set.', $replacements)); } // Assign the shortcut set to the provided user account. $this->shortcutSetStorage->assignUser($set, $this->user); }
protected function setUp() { parent::setUp(); // Create Basic page node type. if ($this->profile != 'standard') { $this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page')); } $this->authUser = $this->drupalCreateUser(array('access content', 'create page content', 'edit own page content')); // Ensure we have a node page to access. $this->node = $this->drupalCreateNode(array('title' => $this->randomMachineName(255), 'uid' => $this->authUser->id())); // Enable access logging. $this->config('statistics.settings')->set('count_content_views', 1)->save(); // Clear the logs. db_truncate('node_counter'); $this->client = \Drupal::service('http_client_factory')->fromOptions(['config/curl' => [CURLOPT_TIMEOUT => 10]]); }
/** * Tests that changes to a user account by another user clears the changed * account's toolbar cached, not the user's who took the action. */ function testNonCurrentUserAccountUpdates() { $admin_user_id = $this->adminUser->id(); $this->hash = $this->getSubtreesHash(); // adminUser2 will add a role to adminUser. $this->drupalLogin($this->adminUser2); $rid = $this->drupalCreateRole(array('administer content types')); // Get the subtree hash for adminUser2 to check later that it has not // changed. Request a new page to refresh the drupalSettings object. $this->drupalGet('test-page'); $this->assertResponse(200); $admin_user_2_hash = $this->getSubtreesHash(); // Assign the role to the user. $this->drupalPostForm('user/' . $admin_user_id . '/edit', array("roles[{$rid}]" => $rid), t('Save')); $this->assertText(t('The changes have been saved.')); // Log in adminUser and assert that the subtrees hash has changed. $this->drupalLogin($this->adminUser); $this->assertDifferentHash(); // Log in adminUser2 to check that its subtrees hash has not changed. $this->drupalLogin($this->adminUser2); $new_subtree_hash = $this->getSubtreesHash(); // Assert that the old adminUser subtree hash and the new adminUser // subtree hash are the same. $this->assertTrue($new_subtree_hash, 'A valid hash value for the admin menu subtrees was created.'); $this->assertEqual($admin_user_2_hash, $new_subtree_hash, 'The user-specific subtree menu hash has not been updated.'); }
/** * Creates an order for the specified user, and redirects to the edit page. * * @param \Drupal\user\UserInterface $user * The user to create the order for. */ public function createForUser(UserInterface $user) { $order = Order::create(['uid' => $user->id(), 'order_status' => uc_order_state_default('post_checkout')]); $order->save(); uc_order_comment_save($order->id(), \Drupal::currentUser()->id(), $this->t('Order created by the administration.'), 'admin'); return $this->redirect('entity.uc_order.edit_form', ['uc_order' => $order->id()]); }
/** * Edits the user picture for the test user. */ function saveUserPicture($image) { $edit = array('files[user_picture_0]' => drupal_realpath($image->uri)); $this->drupalPostForm('user/' . $this->webUser->id() . '/edit', $edit, t('Save')); // Load actual user data from database. $account = user_load($this->webUser->id(), TRUE); return file_load($account->user_picture->target_id, TRUE); }
protected function setUp() { parent::setUp(); ViewTestData::createTestViews(get_class($this), array('comment_test_views')); // Add two users, create a node with the user1 as author and another node // with user2 as author. For the second node add a comment from user1. $this->account = $this->drupalCreateUser(array('skip comment approval')); $this->account2 = $this->drupalCreateUser(); $this->drupalLogin($this->account); $this->drupalCreateContentType(array('type' => 'page', 'name' => t('Basic page'))); $this->addDefaultCommentField('node', 'page'); $this->nodeUserPosted = $this->drupalCreateNode(); $this->nodeUserCommented = $this->drupalCreateNode(array('uid' => $this->account2->id())); $comment = array('uid' => $this->loggedInUser->id(), 'entity_id' => $this->nodeUserCommented->id(), 'entity_type' => 'node', 'field_name' => 'comment', 'subject' => 'How much wood would a woodchuck chuck', 'cid' => '', 'pid' => '', 'mail' => '*****@*****.**'); $this->comment = Comment::create($comment); $this->comment->save(); }
protected function setUp() { parent::setUp(); // Create an article content type only if it does not yet exist, so that // child classes may specify the standard profile. $types = node_type_get_types(); if (empty($types['article'])) { $this->drupalCreateContentType(array('type' => 'article', 'name' => t('Article'))); } // Create two test users. $this->admin_user = $this->drupalCreateUser(array('administer content types', 'administer comments', 'administer comment types', 'administer comment fields', 'administer comment display', 'skip comment approval', 'post comments', 'access comments', 'access content')); $this->web_user = $this->drupalCreateUser(array('access comments', 'post comments', 'create article content', 'edit own comments', 'skip comment approval', 'access content')); // Create comment field on article. $this->container->get('comment.manager')->addDefaultField('node', 'article'); // Create a test node authored by the web user. $this->node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1, 'uid' => $this->web_user->id())); }