1 user.test UserTokenReplaceTestCase::testUserTokenReplacement()

Creates a user, then tests the tokens generated from it.

File

core/modules/user/tests/user.test, line 2533
Tests for user.module.

Class

UserTokenReplaceTestCase
Test user token replacement in strings.

Code

function testUserTokenReplacement() {
  global $language;
  $url_options = array(
    'absolute' => TRUE,
    'language' => $language,
  );

  // Create two users and log them in one after another.
  $user1 = $this->backdropCreateUser(array());
  $user2 = $this->backdropCreateUser(array());
  $this->backdropLogin($user1);
  $this->backdropLogout();
  $this->backdropLogin($user2);

  $account = user_load($user1->uid);
  $global_account = user_load($GLOBALS['user']->uid);

  // Generate and test sanitized tokens.
  $tests = array();
  $tests['[user:uid]'] = $account->uid;
  $tests['[user:name]'] = check_plain(user_format_name($account));
  $tests['[user:mail]'] = check_plain($account->mail);
  $tests['[user:url]'] = url("user/$account->uid", $url_options);
  $tests['[user:edit-url]'] = url("user/$account->uid/edit", $url_options);
  $tests['[user:last-login]'] = format_date($account->login, 'medium', '', NULL, $language->langcode);
  $tests['[user:last-login:short]'] = format_date($account->login, 'short', '', NULL, $language->langcode);
  $tests['[user:created]'] = format_date($account->created, 'medium', '', NULL, $language->langcode);
  $tests['[user:created:short]'] = format_date($account->created, 'short', '', NULL, $language->langcode);
  $tests['[user:changed]'] = format_date($account->changed, 'medium', '', NULL, $language->langcode);
  $tests['[user:changed:short]'] = format_date($account->changed, 'short', '', NULL, $language->langcode);
  $tests['[current-user:name]'] = check_plain(user_format_name($global_account));

  // Test to make sure that we generated something for each token.
  $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');

  foreach ($tests as $input => $expected) {
    $output = token_replace($input, array('user' => $account), array('language' => $language));
    $this->assertEqual($output, $expected, format_string('Sanitized user token %token replaced.', array('%token' => $input)));
  }

  // Generate and test unsanitized tokens.
  $tests['[user:name]'] = user_format_name($account);
  $tests['[user:mail]'] = $account->mail;
  $tests['[current-user:name]'] = user_format_name($global_account);

  foreach ($tests as $input => $expected) {
    $output = token_replace($input, array('user' => $account), array('language' => $language, 'sanitize' => FALSE));
    $this->assertEqual($output, $expected, format_string('Unsanitized user token %token replaced.', array('%token' => $input)));
  }
}