Projet

Général

Profil

Paste
Télécharger (97,7 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / user / user.test @ b4adf10d

1
<?php
2

    
3
/**
4
 * @file
5
 * Tests for user.module.
6
 */
7

    
8
class UserRegistrationTestCase extends DrupalWebTestCase {
9
  public static function getInfo() {
10
    return array(
11
      'name' => 'User registration',
12
      'description' => 'Test registration of user under different configurations.',
13
      'group' => 'User'
14
    );
15
  }
16

    
17
  function setUp() {
18
    parent::setUp('field_test');
19
  }
20

    
21
  function testRegistrationWithEmailVerification() {
22
    // Require e-mail verification.
23
    variable_set('user_email_verification', TRUE);
24

    
25
    // Set registration to administrator only.
26
    variable_set('user_register', USER_REGISTER_ADMINISTRATORS_ONLY);
27
    $this->drupalGet('user/register');
28
    $this->assertResponse(403, 'Registration page is inaccessible when only administrators can create accounts.');
29

    
30
    // Allow registration by site visitors without administrator approval.
31
    variable_set('user_register', USER_REGISTER_VISITORS);
32
    $edit = array();
33
    $edit['name'] = $name = $this->randomName();
34
    $edit['mail'] = $mail = $edit['name'] . '@example.com';
35
    $this->drupalPost('user/register', $edit, t('Create new account'));
36
    $this->assertText(t('A welcome message with further instructions has been sent to your e-mail address.'), 'User registered successfully.');
37
    $accounts = user_load_multiple(array(), array('name' => $name, 'mail' => $mail));
38
    $new_user = reset($accounts);
39
    $this->assertTrue($new_user->status, 'New account is active after registration.');
40

    
41
    // Allow registration by site visitors, but require administrator approval.
42
    variable_set('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL);
43
    $edit = array();
44
    $edit['name'] = $name = $this->randomName();
45
    $edit['mail'] = $mail = $edit['name'] . '@example.com';
46
    $this->drupalPost('user/register', $edit, t('Create new account'));
47
    $accounts = user_load_multiple(array(), array('name' => $name, 'mail' => $mail));
48
    $new_user = reset($accounts);
49
    $this->assertFalse($new_user->status, 'New account is blocked until approved by an administrator.');
50
  }
51

    
52
  function testRegistrationWithoutEmailVerification() {
53
    // Don't require e-mail verification.
54
    variable_set('user_email_verification', FALSE);
55

    
56
    // Allow registration by site visitors without administrator approval.
57
    variable_set('user_register', USER_REGISTER_VISITORS);
58
    $edit = array();
59
    $edit['name'] = $name = $this->randomName();
60
    $edit['mail'] = $mail = $edit['name'] . '@example.com';
61

    
62
    // Try entering a mismatching password.
63
    $edit['pass[pass1]'] = '99999.0';
64
    $edit['pass[pass2]'] = '99999';
65
    $this->drupalPost('user/register', $edit, t('Create new account'));
66
    $this->assertText(t('The specified passwords do not match.'), 'Typing mismatched passwords displays an error message.');
67

    
68
    // Enter a correct password.
69
    $edit['pass[pass1]'] = $new_pass = $this->randomName();
70
    $edit['pass[pass2]'] = $new_pass;
71
    $this->drupalPost('user/register', $edit, t('Create new account'));
72
    $accounts = user_load_multiple(array(), array('name' => $name, 'mail' => $mail));
73
    $new_user = reset($accounts);
74
    $this->assertText(t('Registration successful. You are now logged in.'), 'Users are logged in after registering.');
75
    $this->drupalLogout();
76

    
77
    // Allow registration by site visitors, but require administrator approval.
78
    variable_set('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL);
79
    $edit = array();
80
    $edit['name'] = $name = $this->randomName();
81
    $edit['mail'] = $mail = $edit['name'] . '@example.com';
82
    $edit['pass[pass1]'] = $pass = $this->randomName();
83
    $edit['pass[pass2]'] = $pass;
84
    $this->drupalPost('user/register', $edit, t('Create new account'));
85
    $this->assertText(t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.'), 'Users are notified of pending approval');
86

    
87
    // Try to login before administrator approval.
88
    $auth = array(
89
      'name' => $name,
90
      'pass' => $pass,
91
    );
92
    $this->drupalPost('user/login', $auth, t('Log in'));
93
    $this->assertText(t('The username @name has not been activated or is blocked.', array('@name' => $name)), 'User cannot login yet.');
94

    
95
    // Activate the new account.
96
    $accounts = user_load_multiple(array(), array('name' => $name, 'mail' => $mail));
97
    $new_user = reset($accounts);
98
    $admin_user = $this->drupalCreateUser(array('administer users'));
99
    $this->drupalLogin($admin_user);
100
    $edit = array(
101
      'status' => 1,
102
    );
103
    $this->drupalPost('user/' . $new_user->uid . '/edit', $edit, t('Save'));
104
    $this->drupalLogout();
105

    
106
    // Login after administrator approval.
107
    $this->drupalPost('user/login', $auth, t('Log in'));
108
    $this->assertText(t('Member for'), 'User can log in after administrator approval.');
109
  }
110

    
111
  function testRegistrationEmailDuplicates() {
112
    // Don't require e-mail verification.
113
    variable_set('user_email_verification', FALSE);
114

    
115
    // Allow registration by site visitors without administrator approval.
116
    variable_set('user_register', USER_REGISTER_VISITORS);
117

    
118
    // Set up a user to check for duplicates.
119
    $duplicate_user = $this->drupalCreateUser();
120

    
121
    $edit = array();
122
    $edit['name'] = $this->randomName();
123
    $edit['mail'] = $duplicate_user->mail;
124

    
125
    // Attempt to create a new account using an existing e-mail address.
126
    $this->drupalPost('user/register', $edit, t('Create new account'));
127
    $this->assertText(t('The e-mail address @email is already registered.', array('@email' => $duplicate_user->mail)), 'Supplying an exact duplicate email address displays an error message');
128

    
129
    // Attempt to bypass duplicate email registration validation by adding spaces.
130
    $edit['mail'] = '   ' . $duplicate_user->mail . '   ';
131

    
132
    $this->drupalPost('user/register', $edit, t('Create new account'));
133
    $this->assertText(t('The e-mail address @email is already registered.', array('@email' => $duplicate_user->mail)), 'Supplying a duplicate email address with added whitespace displays an error message');
134
  }
135

    
136
  function testRegistrationDefaultValues() {
137
    // Allow registration by site visitors without administrator approval.
138
    variable_set('user_register', USER_REGISTER_VISITORS);
139

    
140
    // Don't require e-mail verification.
141
    variable_set('user_email_verification', FALSE);
142

    
143
    // Set the default timezone to Brussels.
144
    variable_set('configurable_timezones', 1);
145
    variable_set('date_default_timezone', 'Europe/Brussels');
146

    
147
    // Check that the account information fieldset's options are not displayed
148
    // is a fieldset if there is not more than one fieldset in the form.
149
    $this->drupalGet('user/register');
150
    $this->assertNoRaw('<fieldset id="edit-account"><legend>Account information</legend>', 'Account settings fieldset was hidden.');
151

    
152
    $edit = array();
153
    $edit['name'] = $name = $this->randomName();
154
    $edit['mail'] = $mail = $edit['name'] . '@example.com';
155
    $edit['pass[pass1]'] = $new_pass = $this->randomName();
156
    $edit['pass[pass2]'] = $new_pass;
157
    $this->drupalPost(NULL, $edit, t('Create new account'));
158

    
159
    // Check user fields.
160
    $accounts = user_load_multiple(array(), array('name' => $name, 'mail' => $mail));
161
    $new_user = reset($accounts);
162
    $this->assertEqual($new_user->name, $name, 'Username matches.');
163
    $this->assertEqual($new_user->mail, $mail, 'E-mail address matches.');
164
    $this->assertEqual($new_user->theme, '', 'Correct theme field.');
165
    $this->assertEqual($new_user->signature, '', 'Correct signature field.');
166
    $this->assertTrue(($new_user->created > REQUEST_TIME - 20 ), 'Correct creation time.');
167
    $this->assertEqual($new_user->status, variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) == USER_REGISTER_VISITORS ? 1 : 0, 'Correct status field.');
168
    $this->assertEqual($new_user->timezone, variable_get('date_default_timezone'), 'Correct time zone field.');
169
    $this->assertEqual($new_user->language, '', 'Correct language field.');
170
    $this->assertEqual($new_user->picture, '', 'Correct picture field.');
171
    $this->assertEqual($new_user->init, $mail, 'Correct init field.');
172
  }
173

    
174
  /**
175
   * Tests Field API fields on user registration forms.
176
   */
177
  function testRegistrationWithUserFields() {
178
    // Create a field, and an instance on 'user' entity type.
179
    $field = array(
180
      'type' => 'test_field',
181
      'field_name' => 'test_user_field',
182
      'cardinality' => 1,
183
    );
184
    field_create_field($field);
185
    $instance = array(
186
      'field_name' => 'test_user_field',
187
      'entity_type' => 'user',
188
      'label' => 'Some user field',
189
      'bundle' => 'user',
190
      'required' => TRUE,
191
      'settings' => array('user_register_form' => FALSE),
192
    );
193
    field_create_instance($instance);
194

    
195
    // Check that the field does not appear on the registration form.
196
    $this->drupalGet('user/register');
197
    $this->assertNoText($instance['label'], 'The field does not appear on user registration form');
198

    
199
    // Have the field appear on the registration form.
200
    $instance['settings']['user_register_form'] = TRUE;
201
    field_update_instance($instance);
202
    $this->drupalGet('user/register');
203
    $this->assertText($instance['label'], 'The field appears on user registration form');
204

    
205
    // Check that validation errors are correctly reported.
206
    $edit = array();
207
    $edit['name'] = $name = $this->randomName();
208
    $edit['mail'] = $mail = $edit['name'] . '@example.com';
209
    // Missing input in required field.
210
    $edit['test_user_field[und][0][value]'] = '';
211
    $this->drupalPost(NULL, $edit, t('Create new account'));
212
    $this->assertRaw(t('@name field is required.', array('@name' => $instance['label'])), 'Field validation error was correctly reported.');
213
    // Invalid input.
214
    $edit['test_user_field[und][0][value]'] = '-1';
215
    $this->drupalPost(NULL, $edit, t('Create new account'));
216
    $this->assertRaw(t('%name does not accept the value -1.', array('%name' => $instance['label'])), 'Field validation error was correctly reported.');
217

    
218
    // Submit with valid data.
219
    $value = rand(1, 255);
220
    $edit['test_user_field[und][0][value]'] = $value;
221
    $this->drupalPost(NULL, $edit, t('Create new account'));
222
    // Check user fields.
223
    $accounts = user_load_multiple(array(), array('name' => $name, 'mail' => $mail));
224
    $new_user = reset($accounts);
225
    $this->assertEqual($new_user->test_user_field[LANGUAGE_NONE][0]['value'], $value, 'The field value was correctly saved.');
226

    
227
    // Check that the 'add more' button works.
228
    $field['cardinality'] = FIELD_CARDINALITY_UNLIMITED;
229
    field_update_field($field);
230
    foreach (array('js', 'nojs') as $js) {
231
      $this->drupalGet('user/register');
232
      // Add two inputs.
233
      $value = rand(1, 255);
234
      $edit = array();
235
      $edit['test_user_field[und][0][value]'] = $value;
236
      if ($js == 'js') {
237
        $this->drupalPostAJAX(NULL, $edit, 'test_user_field_add_more');
238
        $this->drupalPostAJAX(NULL, $edit, 'test_user_field_add_more');
239
      }
240
      else {
241
        $this->drupalPost(NULL, $edit, t('Add another item'));
242
        $this->drupalPost(NULL, $edit, t('Add another item'));
243
      }
244
      // Submit with three values.
245
      $edit['test_user_field[und][1][value]'] = $value + 1;
246
      $edit['test_user_field[und][2][value]'] = $value + 2;
247
      $edit['name'] = $name = $this->randomName();
248
      $edit['mail'] = $mail = $edit['name'] . '@example.com';
249
      $this->drupalPost(NULL, $edit, t('Create new account'));
250
      // Check user fields.
251
      $accounts = user_load_multiple(array(), array('name' => $name, 'mail' => $mail));
252
      $new_user = reset($accounts);
253
      $this->assertEqual($new_user->test_user_field[LANGUAGE_NONE][0]['value'], $value, format_string('@js : The field value was correclty saved.', array('@js' => $js)));
254
      $this->assertEqual($new_user->test_user_field[LANGUAGE_NONE][1]['value'], $value + 1, format_string('@js : The field value was correclty saved.', array('@js' => $js)));
255
      $this->assertEqual($new_user->test_user_field[LANGUAGE_NONE][2]['value'], $value + 2, format_string('@js : The field value was correclty saved.', array('@js' => $js)));
256
    }
257
  }
258
}
259

    
260
class UserValidationTestCase extends DrupalWebTestCase {
261
  public static function getInfo() {
262
    return array(
263
      'name' => 'Username/e-mail validation',
264
      'description' => 'Verify that username/email validity checks behave as designed.',
265
      'group' => 'User'
266
    );
267
  }
268

    
269
  // Username validation.
270
  function testUsernames() {
271
    $test_cases = array( // '<username>' => array('<description>', 'assert<testName>'),
272
      'foo'                    => array('Valid username', 'assertNull'),
273
      'FOO'                    => array('Valid username', 'assertNull'),
274
      'Foo O\'Bar'             => array('Valid username', 'assertNull'),
275
      'foo@bar'                => array('Valid username', 'assertNull'),
276
      'foo@example.com'        => array('Valid username', 'assertNull'),
277
      'foo@-example.com'       => array('Valid username', 'assertNull'), // invalid domains are allowed in usernames
278
      'þòøÇߪř€'               => array('Valid username', 'assertNull'),
279
      'ᚠᛇᚻ᛫ᛒᛦᚦ'                => array('Valid UTF8 username', 'assertNull'), // runes
280
      ' foo'                   => array('Invalid username that starts with a space', 'assertNotNull'),
281
      'foo '                   => array('Invalid username that ends with a space', 'assertNotNull'),
282
      'foo  bar'               => array('Invalid username that contains 2 spaces \'&nbsp;&nbsp;\'', 'assertNotNull'),
283
      ''                       => array('Invalid empty username', 'assertNotNull'),
284
      'foo/'                   => array('Invalid username containing invalid chars', 'assertNotNull'),
285
      'foo' . chr(0) . 'bar'   => array('Invalid username containing chr(0)', 'assertNotNull'), // NULL
286
      'foo' . chr(13) . 'bar'  => array('Invalid username containing chr(13)', 'assertNotNull'), // CR
287
      str_repeat('x', USERNAME_MAX_LENGTH + 1) => array('Invalid excessively long username', 'assertNotNull'),
288
    );
289
    foreach ($test_cases as $name => $test_case) {
290
      list($description, $test) = $test_case;
291
      $result = user_validate_name($name);
292
      $this->$test($result, $description . ' (' . $name . ')');
293
    }
294
  }
295

    
296
  // Mail validation. More extensive tests can be found at common.test
297
  function testMailAddresses() {
298
    $test_cases = array( // '<username>' => array('<description>', 'assert<testName>'),
299
      ''                => array('Empty mail address', 'assertNotNull'),
300
      'foo'             => array('Invalid mail address', 'assertNotNull'),
301
      'foo@example.com' => array('Valid mail address', 'assertNull'),
302
    );
303
    foreach ($test_cases as $name => $test_case) {
304
      list($description, $test) = $test_case;
305
      $result = user_validate_mail($name);
306
      $this->$test($result, $description . ' (' . $name . ')');
307
    }
308
  }
309
}
310

    
311
/**
312
 * Functional tests for user logins, including rate limiting of login attempts.
313
 */
314
class UserLoginTestCase extends DrupalWebTestCase {
315
  public static function getInfo() {
316
    return array(
317
      'name' => 'User login',
318
      'description' => 'Ensure that login works as expected.',
319
      'group' => 'User',
320
    );
321
  }
322

    
323
  /**
324
   * Test the global login flood control.
325
   */
326
  function testGlobalLoginFloodControl() {
327
    // Set the global login limit.
328
    variable_set('user_failed_login_ip_limit', 10);
329
    // Set a high per-user limit out so that it is not relevant in the test.
330
    variable_set('user_failed_login_user_limit', 4000);
331

    
332
    $user1 = $this->drupalCreateUser(array());
333
    $incorrect_user1 = clone $user1;
334
    $incorrect_user1->pass_raw .= 'incorrect';
335

    
336
    // Try 2 failed logins.
337
    for ($i = 0; $i < 2; $i++) {
338
      $this->assertFailedLogin($incorrect_user1);
339
    }
340

    
341
    // A successful login will not reset the IP-based flood control count.
342
    $this->drupalLogin($user1);
343
    $this->drupalLogout();
344

    
345
    // Try 8 more failed logins, they should not trigger the flood control
346
    // mechanism.
347
    for ($i = 0; $i < 8; $i++) {
348
      $this->assertFailedLogin($incorrect_user1);
349
    }
350

    
351
    // The next login trial should result in an IP-based flood error message.
352
    $this->assertFailedLogin($incorrect_user1, 'ip');
353

    
354
    // A login with the correct password should also result in a flood error
355
    // message.
356
    $this->assertFailedLogin($user1, 'ip');
357
  }
358

    
359
  /**
360
   * Test the per-user login flood control.
361
   */
362
  function testPerUserLoginFloodControl() {
363
    // Set a high global limit out so that it is not relevant in the test.
364
    variable_set('user_failed_login_ip_limit', 4000);
365
    // Set the per-user login limit.
366
    variable_set('user_failed_login_user_limit', 3);
367

    
368
    $user1 = $this->drupalCreateUser(array());
369
    $incorrect_user1 = clone $user1;
370
    $incorrect_user1->pass_raw .= 'incorrect';
371

    
372
    $user2 = $this->drupalCreateUser(array());
373

    
374
    // Try 2 failed logins.
375
    for ($i = 0; $i < 2; $i++) {
376
      $this->assertFailedLogin($incorrect_user1);
377
    }
378

    
379
    // A successful login will reset the per-user flood control count.
380
    $this->drupalLogin($user1);
381
    $this->drupalLogout();
382

    
383
    // Try 3 failed logins for user 1, they will not trigger flood control.
384
    for ($i = 0; $i < 3; $i++) {
385
      $this->assertFailedLogin($incorrect_user1);
386
    }
387

    
388
    // Try one successful attempt for user 2, it should not trigger any
389
    // flood control.
390
    $this->drupalLogin($user2);
391
    $this->drupalLogout();
392

    
393
    // Try one more attempt for user 1, it should be rejected, even if the
394
    // correct password has been used.
395
    $this->assertFailedLogin($user1, 'user');
396
  }
397

    
398
  /**
399
   * Test that user password is re-hashed upon login after changing $count_log2.
400
   */
401
  function testPasswordRehashOnLogin() {
402
    // Load password hashing API.
403
    require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
404
    // Set initial $count_log2 to the default, DRUPAL_HASH_COUNT.
405
    variable_set('password_count_log2', DRUPAL_HASH_COUNT);
406
    // Create a new user and authenticate.
407
    $account = $this->drupalCreateUser(array());
408
    $password = $account->pass_raw;
409
    $this->drupalLogin($account);
410
    $this->drupalLogout();
411
    // Load the stored user. The password hash should reflect $count_log2.
412
    $account = user_load($account->uid);
413
    $this->assertIdentical(_password_get_count_log2($account->pass), DRUPAL_HASH_COUNT);
414
    // Change $count_log2 and log in again.
415
    variable_set('password_count_log2', DRUPAL_HASH_COUNT + 1);
416
    $account->pass_raw = $password;
417
    $this->drupalLogin($account);
418
    // Load the stored user, which should have a different password hash now.
419
    $account = user_load($account->uid, TRUE);
420
    $this->assertIdentical(_password_get_count_log2($account->pass), DRUPAL_HASH_COUNT + 1);
421
  }
422

    
423
  /**
424
   * Make an unsuccessful login attempt.
425
   *
426
   * @param $account
427
   *   A user object with name and pass_raw attributes for the login attempt.
428
   * @param $flood_trigger
429
   *   Whether or not to expect that the flood control mechanism will be
430
   *   triggered.
431
   */
432
  function assertFailedLogin($account, $flood_trigger = NULL) {
433
    $edit = array(
434
      'name' => $account->name,
435
      'pass' => $account->pass_raw,
436
    );
437
    $this->drupalPost('user', $edit, t('Log in'));
438
    $this->assertNoFieldByXPath("//input[@name='pass' and @value!='']", NULL, 'Password value attribute is blank.');
439
    if (isset($flood_trigger)) {
440
      if ($flood_trigger == 'user') {
441
        $this->assertRaw(format_plural(variable_get('user_failed_login_user_limit', 5), 'Sorry, there has been more than one failed login attempt for this account. It is temporarily blocked. Try again later or <a href="@url">request a new password</a>.', 'Sorry, there have been more than @count failed login attempts for this account. It is temporarily blocked. Try again later or <a href="@url">request a new password</a>.', array('@url' => url('user/password'))));
442
      }
443
      else {
444
        // No uid, so the limit is IP-based.
445
        $this->assertRaw(t('Sorry, too many failed login attempts from your IP address. This IP address is temporarily blocked. Try again later or <a href="@url">request a new password</a>.', array('@url' => url('user/password'))));
446
      }
447
    }
448
    else {
449
      $this->assertText(t('Sorry, unrecognized username or password. Have you forgotten your password?'));
450
    }
451
  }
452
}
453

    
454
/**
455
 * Tests resetting a user password.
456
 */
457
class UserPasswordResetTestCase extends DrupalWebTestCase {
458
  protected $profile = 'standard';
459

    
460
  public static function getInfo() {
461
    return array(
462
      'name' => 'Reset password',
463
      'description' => 'Ensure that password reset methods work as expected.',
464
      'group' => 'User',
465
    );
466
  }
467

    
468
  /**
469
   * Tests password reset functionality.
470
   */
471
  function testUserPasswordReset() {
472
    // Create a user.
473
    $account = $this->drupalCreateUser();
474
    $this->drupalLogin($account);
475
    $this->drupalLogout();
476
    // Attempt to reset password.
477
    $edit = array('name' => $account->name);
478
    $this->drupalPost('user/password', $edit, t('E-mail new password'));
479
    // Confirm the password reset.
480
    $this->assertText(t('Further instructions have been sent to your e-mail address.'), 'Password reset instructions mailed message displayed.');
481
  }
482

    
483
  /**
484
   * Attempts login using an expired password reset link.
485
   */
486
  function testUserPasswordResetExpired() {
487
    // Set password reset timeout variable to 43200 seconds = 12 hours.
488
    $timeout = 43200;
489
    variable_set('user_password_reset_timeout', $timeout);
490

    
491
    // Create a user.
492
    $account = $this->drupalCreateUser();
493
    $this->drupalLogin($account);
494
    // Load real user object.
495
    $account = user_load($account->uid, TRUE);
496
    $this->drupalLogout();
497

    
498
    // To attempt an expired password reset, create a password reset link as if
499
    // its request time was 60 seconds older than the allowed limit of timeout.
500
    $bogus_timestamp = REQUEST_TIME - variable_get('user_password_reset_timeout', 86400) - 60;
501
    $this->drupalGet("user/reset/$account->uid/$bogus_timestamp/" . user_pass_rehash($account->pass, $bogus_timestamp, $account->login));
502
    $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.');
503
  }
504

    
505
  /**
506
   * Prefill the text box on incorrect login via link to password reset page.
507
   */
508
  function testUserPasswordTextboxFilled() {
509
    $this->drupalGet('user/login');
510
    $edit = array(
511
      'name' => $this->randomName(),
512
      'pass' => $this->randomName(),
513
    );
514
    $this->drupalPost('user', $edit, t('Log in'));
515
    $this->assertRaw(t('Sorry, unrecognized username or password. <a href="@password">Have you forgotten your password?</a>',
516
      array('@password' => url('user/password', array('query' => array('name' => $edit['name']))))));
517
    unset($edit['pass']);
518
    $this->drupalGet('user/password', array('query' => array('name' => $edit['name'])));
519
    $this->assertFieldByName('name', $edit['name'], 'User name found.');
520
  }
521

    
522
}
523

    
524
/**
525
 * Test cancelling a user.
526
 */
527
class UserCancelTestCase extends DrupalWebTestCase {
528
  public static function getInfo() {
529
    return array(
530
      'name' => 'Cancel account',
531
      'description' => 'Ensure that account cancellation methods work as expected.',
532
      'group' => 'User',
533
    );
534
  }
535

    
536
  function setUp() {
537
    parent::setUp('comment');
538
  }
539

    
540
  /**
541
   * Attempt to cancel account without permission.
542
   */
543
  function testUserCancelWithoutPermission() {
544
    variable_set('user_cancel_method', 'user_cancel_reassign');
545

    
546
    // Create a user.
547
    $account = $this->drupalCreateUser(array());
548
    $this->drupalLogin($account);
549
    // Load real user object.
550
    $account = user_load($account->uid, TRUE);
551

    
552
    // Create a node.
553
    $node = $this->drupalCreateNode(array('uid' => $account->uid));
554

    
555
    // Attempt to cancel account.
556
    $this->drupalGet('user/' . $account->uid . '/edit');
557
    $this->assertNoRaw(t('Cancel account'), 'No cancel account button displayed.');
558

    
559
    // Attempt bogus account cancellation request confirmation.
560
    $timestamp = $account->login;
561
    $this->drupalGet("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login));
562
    $this->assertResponse(403, 'Bogus cancelling request rejected.');
563
    $account = user_load($account->uid);
564
    $this->assertTrue($account->status == 1, 'User account was not canceled.');
565

    
566
    // Confirm user's content has not been altered.
567
    $test_node = node_load($node->nid, NULL, TRUE);
568
    $this->assertTrue(($test_node->uid == $account->uid && $test_node->status == 1), 'Node of the user has not been altered.');
569
  }
570

    
571
  /**
572
   * Tests that user account for uid 1 cannot be cancelled.
573
   *
574
   * This should never be possible, or the site owner would become unable to
575
   * administer the site.
576
   */
577
  function testUserCancelUid1() {
578
    // Update uid 1's name and password to we know it.
579
    $password = user_password();
580
    require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
581
    $account = array(
582
      'name' => 'user1',
583
      'pass' => user_hash_password(trim($password)),
584
    );
585
    // We cannot use user_save() here or the password would be hashed again.
586
    db_update('users')
587
      ->fields($account)
588
      ->condition('uid', 1)
589
      ->execute();
590

    
591
    // Reload and log in uid 1.
592
    $user1 = user_load(1, TRUE);
593
    $user1->pass_raw = $password;
594

    
595
    // Try to cancel uid 1's account with a different user.
596
    $this->admin_user = $this->drupalCreateUser(array('administer users'));
597
    $this->drupalLogin($this->admin_user);
598
    $edit = array(
599
      'operation' => 'cancel',
600
      'accounts[1]' => TRUE,
601
    );
602
    $this->drupalPost('admin/people', $edit, t('Update'));
603

    
604
    // Verify that uid 1's account was not cancelled.
605
    $user1 = user_load(1, TRUE);
606
    $this->assertEqual($user1->status, 1, 'User #1 still exists and is not blocked.');
607
  }
608

    
609
  /**
610
   * Attempt invalid account cancellations.
611
   */
612
  function testUserCancelInvalid() {
613
    variable_set('user_cancel_method', 'user_cancel_reassign');
614

    
615
    // Create a user.
616
    $account = $this->drupalCreateUser(array('cancel account'));
617
    $this->drupalLogin($account);
618
    // Load real user object.
619
    $account = user_load($account->uid, TRUE);
620

    
621
    // Create a node.
622
    $node = $this->drupalCreateNode(array('uid' => $account->uid));
623

    
624
    // Attempt to cancel account.
625
    $this->drupalPost('user/' . $account->uid . '/edit', NULL, t('Cancel account'));
626

    
627
    // Confirm account cancellation.
628
    $timestamp = time();
629
    $this->drupalPost(NULL, NULL, t('Cancel account'));
630
    $this->assertText(t('A confirmation request to cancel your account has been sent to your e-mail address.'), 'Account cancellation request mailed message displayed.');
631

    
632
    // Attempt bogus account cancellation request confirmation.
633
    $bogus_timestamp = $timestamp + 60;
634
    $this->drupalGet("user/$account->uid/cancel/confirm/$bogus_timestamp/" . user_pass_rehash($account->pass, $bogus_timestamp, $account->login));
635
    $this->assertText(t('You have tried to use an account cancellation link that has expired. Please request a new one using the form below.'), 'Bogus cancelling request rejected.');
636
    $account = user_load($account->uid);
637
    $this->assertTrue($account->status == 1, 'User account was not canceled.');
638

    
639
    // Attempt expired account cancellation request confirmation.
640
    $bogus_timestamp = $timestamp - 86400 - 60;
641
    $this->drupalGet("user/$account->uid/cancel/confirm/$bogus_timestamp/" . user_pass_rehash($account->pass, $bogus_timestamp, $account->login));
642
    $this->assertText(t('You have tried to use an account cancellation link that has expired. Please request a new one using the form below.'), 'Expired cancel account request rejected.');
643
    $accounts = user_load_multiple(array($account->uid), array('status' => 1));
644
    $this->assertTrue(reset($accounts), 'User account was not canceled.');
645

    
646
    // Confirm user's content has not been altered.
647
    $test_node = node_load($node->nid, NULL, TRUE);
648
    $this->assertTrue(($test_node->uid == $account->uid && $test_node->status == 1), 'Node of the user has not been altered.');
649
  }
650

    
651
  /**
652
   * Disable account and keep all content.
653
   */
654
  function testUserBlock() {
655
    variable_set('user_cancel_method', 'user_cancel_block');
656

    
657
    // Create a user.
658
    $web_user = $this->drupalCreateUser(array('cancel account'));
659
    $this->drupalLogin($web_user);
660

    
661
    // Load real user object.
662
    $account = user_load($web_user->uid, TRUE);
663

    
664
    // Attempt to cancel account.
665
    $this->drupalGet('user/' . $account->uid . '/edit');
666
    $this->drupalPost(NULL, NULL, t('Cancel account'));
667
    $this->assertText(t('Are you sure you want to cancel your account?'), 'Confirmation form to cancel account displayed.');
668
    $this->assertText(t('Your account will be blocked and you will no longer be able to log in. All of your content will remain attributed to your user name.'), 'Informs that all content will be remain as is.');
669
    $this->assertNoText(t('Select the method to cancel the account above.'), 'Does not allow user to select account cancellation method.');
670

    
671
    // Confirm account cancellation.
672
    $timestamp = time();
673

    
674
    $this->drupalPost(NULL, NULL, t('Cancel account'));
675
    $this->assertText(t('A confirmation request to cancel your account has been sent to your e-mail address.'), 'Account cancellation request mailed message displayed.');
676

    
677
    // Confirm account cancellation request.
678
    $this->drupalGet("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login));
679
    $account = user_load($account->uid, TRUE);
680
    $this->assertTrue($account->status == 0, 'User has been blocked.');
681

    
682
    // Confirm that the confirmation message made it through to the end user.
683
    $this->assertRaw(t('%name has been disabled.', array('%name' => $account->name)), "Confirmation message displayed to user.");
684
  }
685

    
686
  /**
687
   * Disable account and unpublish all content.
688
   */
689
  function testUserBlockUnpublish() {
690
    variable_set('user_cancel_method', 'user_cancel_block_unpublish');
691

    
692
    // Create a user.
693
    $account = $this->drupalCreateUser(array('cancel account'));
694
    $this->drupalLogin($account);
695
    // Load real user object.
696
    $account = user_load($account->uid, TRUE);
697

    
698
    // Create a node with two revisions.
699
    $node = $this->drupalCreateNode(array('uid' => $account->uid));
700
    $settings = get_object_vars($node);
701
    $settings['revision'] = 1;
702
    $node = $this->drupalCreateNode($settings);
703

    
704
    // Attempt to cancel account.
705
    $this->drupalGet('user/' . $account->uid . '/edit');
706
    $this->drupalPost(NULL, NULL, t('Cancel account'));
707
    $this->assertText(t('Are you sure you want to cancel your account?'), 'Confirmation form to cancel account displayed.');
708
    $this->assertText(t('Your account will be blocked and you will no longer be able to log in. All of your content will be hidden from everyone but administrators.'), 'Informs that all content will be unpublished.');
709

    
710
    // Confirm account cancellation.
711
    $timestamp = time();
712
    $this->drupalPost(NULL, NULL, t('Cancel account'));
713
    $this->assertText(t('A confirmation request to cancel your account has been sent to your e-mail address.'), 'Account cancellation request mailed message displayed.');
714

    
715
    // Confirm account cancellation request.
716
    $this->drupalGet("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login));
717
    $account = user_load($account->uid, TRUE);
718
    $this->assertTrue($account->status == 0, 'User has been blocked.');
719

    
720
    // Confirm user's content has been unpublished.
721
    $test_node = node_load($node->nid, NULL, TRUE);
722
    $this->assertTrue($test_node->status == 0, 'Node of the user has been unpublished.');
723
    $test_node = node_load($node->nid, $node->vid, TRUE);
724
    $this->assertTrue($test_node->status == 0, 'Node revision of the user has been unpublished.');
725

    
726
    // Confirm that the confirmation message made it through to the end user.
727
    $this->assertRaw(t('%name has been disabled.', array('%name' => $account->name)), "Confirmation message displayed to user.");
728
  }
729

    
730
  /**
731
   * Delete account and anonymize all content.
732
   */
733
  function testUserAnonymize() {
734
    variable_set('user_cancel_method', 'user_cancel_reassign');
735

    
736
    // Create a user.
737
    $account = $this->drupalCreateUser(array('cancel account'));
738
    $this->drupalLogin($account);
739
    // Load real user object.
740
    $account = user_load($account->uid, TRUE);
741

    
742
    // Create a simple node.
743
    $node = $this->drupalCreateNode(array('uid' => $account->uid));
744

    
745
    // Create a node with two revisions, the initial one belonging to the
746
    // cancelling user.
747
    $revision_node = $this->drupalCreateNode(array('uid' => $account->uid));
748
    $revision = $revision_node->vid;
749
    $settings = get_object_vars($revision_node);
750
    $settings['revision'] = 1;
751
    $settings['uid'] = 1; // Set new/current revision to someone else.
752
    $revision_node = $this->drupalCreateNode($settings);
753

    
754
    // Attempt to cancel account.
755
    $this->drupalGet('user/' . $account->uid . '/edit');
756
    $this->drupalPost(NULL, NULL, t('Cancel account'));
757
    $this->assertText(t('Are you sure you want to cancel your account?'), 'Confirmation form to cancel account displayed.');
758
    $this->assertRaw(t('Your account will be removed and all account information deleted. All of your content will be assigned to the %anonymous-name user.', array('%anonymous-name' => variable_get('anonymous', t('Anonymous')))), 'Informs that all content will be attributed to anonymous account.');
759

    
760
    // Confirm account cancellation.
761
    $timestamp = time();
762
    $this->drupalPost(NULL, NULL, t('Cancel account'));
763
    $this->assertText(t('A confirmation request to cancel your account has been sent to your e-mail address.'), 'Account cancellation request mailed message displayed.');
764

    
765
    // Confirm account cancellation request.
766
    $this->drupalGet("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login));
767
    $this->assertFalse(user_load($account->uid, TRUE), 'User is not found in the database.');
768

    
769
    // Confirm that user's content has been attributed to anonymous user.
770
    $test_node = node_load($node->nid, NULL, TRUE);
771
    $this->assertTrue(($test_node->uid == 0 && $test_node->status == 1), 'Node of the user has been attributed to anonymous user.');
772
    $test_node = node_load($revision_node->nid, $revision, TRUE);
773
    $this->assertTrue(($test_node->revision_uid == 0 && $test_node->status == 1), 'Node revision of the user has been attributed to anonymous user.');
774
    $test_node = node_load($revision_node->nid, NULL, TRUE);
775
    $this->assertTrue(($test_node->uid != 0 && $test_node->status == 1), "Current revision of the user's node was not attributed to anonymous user.");
776

    
777
    // Confirm that the confirmation message made it through to the end user.
778
    $this->assertRaw(t('%name has been deleted.', array('%name' => $account->name)), "Confirmation message displayed to user.");
779
  }
780

    
781
  /**
782
   * Delete account and remove all content.
783
   */
784
  function testUserDelete() {
785
    variable_set('user_cancel_method', 'user_cancel_delete');
786

    
787
    // Create a user.
788
    $account = $this->drupalCreateUser(array('cancel account', 'post comments', 'skip comment approval'));
789
    $this->drupalLogin($account);
790
    // Load real user object.
791
    $account = user_load($account->uid, TRUE);
792

    
793
    // Create a simple node.
794
    $node = $this->drupalCreateNode(array('uid' => $account->uid));
795

    
796
    // Create comment.
797
    $langcode = LANGUAGE_NONE;
798
    $edit = array();
799
    $edit['subject'] = $this->randomName(8);
800
    $edit['comment_body[' . $langcode . '][0][value]'] = $this->randomName(16);
801

    
802
    $this->drupalPost('comment/reply/' . $node->nid, $edit, t('Preview'));
803
    $this->drupalPost(NULL, array(), t('Save'));
804
    $this->assertText(t('Your comment has been posted.'));
805
    $comments = comment_load_multiple(array(), array('subject' => $edit['subject']));
806
    $comment = reset($comments);
807
    $this->assertTrue($comment->cid, 'Comment found.');
808

    
809
    // Create a node with two revisions, the initial one belonging to the
810
    // cancelling user.
811
    $revision_node = $this->drupalCreateNode(array('uid' => $account->uid));
812
    $revision = $revision_node->vid;
813
    $settings = get_object_vars($revision_node);
814
    $settings['revision'] = 1;
815
    $settings['uid'] = 1; // Set new/current revision to someone else.
816
    $revision_node = $this->drupalCreateNode($settings);
817

    
818
    // Attempt to cancel account.
819
    $this->drupalGet('user/' . $account->uid . '/edit');
820
    $this->drupalPost(NULL, NULL, t('Cancel account'));
821
    $this->assertText(t('Are you sure you want to cancel your account?'), 'Confirmation form to cancel account displayed.');
822
    $this->assertText(t('Your account will be removed and all account information deleted. All of your content will also be deleted.'), 'Informs that all content will be deleted.');
823

    
824
    // Confirm account cancellation.
825
    $timestamp = time();
826
    $this->drupalPost(NULL, NULL, t('Cancel account'));
827
    $this->assertText(t('A confirmation request to cancel your account has been sent to your e-mail address.'), 'Account cancellation request mailed message displayed.');
828

    
829
    // Confirm account cancellation request.
830
    $this->drupalGet("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login));
831
    $this->assertFalse(user_load($account->uid, TRUE), 'User is not found in the database.');
832

    
833
    // Confirm that user's content has been deleted.
834
    $this->assertFalse(node_load($node->nid, NULL, TRUE), 'Node of the user has been deleted.');
835
    $this->assertFalse(node_load($node->nid, $revision, TRUE), 'Node revision of the user has been deleted.');
836
    $this->assertTrue(node_load($revision_node->nid, NULL, TRUE), "Current revision of the user's node was not deleted.");
837
    $this->assertFalse(comment_load($comment->cid), 'Comment of the user has been deleted.');
838

    
839
    // Confirm that the confirmation message made it through to the end user.
840
    $this->assertRaw(t('%name has been deleted.', array('%name' => $account->name)), "Confirmation message displayed to user.");
841
  }
842

    
843
  /**
844
   * Create an administrative user and delete another user.
845
   */
846
  function testUserCancelByAdmin() {
847
    variable_set('user_cancel_method', 'user_cancel_reassign');
848

    
849
    // Create a regular user.
850
    $account = $this->drupalCreateUser(array());
851

    
852
    // Create administrative user.
853
    $admin_user = $this->drupalCreateUser(array('administer users'));
854
    $this->drupalLogin($admin_user);
855

    
856
    // Delete regular user.
857
    $this->drupalGet('user/' . $account->uid . '/edit');
858
    $this->drupalPost(NULL, NULL, t('Cancel account'));
859
    $this->assertRaw(t('Are you sure you want to cancel the account %name?', array('%name' => $account->name)), 'Confirmation form to cancel account displayed.');
860
    $this->assertText(t('Select the method to cancel the account above.'), 'Allows to select account cancellation method.');
861

    
862
    // Confirm deletion.
863
    $this->drupalPost(NULL, NULL, t('Cancel account'));
864
    $this->assertRaw(t('%name has been deleted.', array('%name' => $account->name)), 'User deleted.');
865
    $this->assertFalse(user_load($account->uid), 'User is not found in the database.');
866
  }
867

    
868
  /**
869
   * Create an administrative user and mass-delete other users.
870
   */
871
  function testMassUserCancelByAdmin() {
872
    variable_set('user_cancel_method', 'user_cancel_reassign');
873
    // Enable account cancellation notification.
874
    variable_set('user_mail_status_canceled_notify', TRUE);
875

    
876
    // Create administrative user.
877
    $admin_user = $this->drupalCreateUser(array('administer users'));
878
    $this->drupalLogin($admin_user);
879

    
880
    // Create some users.
881
    $users = array();
882
    for ($i = 0; $i < 3; $i++) {
883
      $account = $this->drupalCreateUser(array());
884
      $users[$account->uid] = $account;
885
    }
886

    
887
    // Cancel user accounts, including own one.
888
    $edit = array();
889
    $edit['operation'] = 'cancel';
890
    foreach ($users as $uid => $account) {
891
      $edit['accounts[' . $uid . ']'] = TRUE;
892
    }
893
    $edit['accounts[' . $admin_user->uid . ']'] = TRUE;
894
    // Also try to cancel uid 1.
895
    $edit['accounts[1]'] = TRUE;
896
    $this->drupalPost('admin/people', $edit, t('Update'));
897
    $this->assertText(t('Are you sure you want to cancel these user accounts?'), 'Confirmation form to cancel accounts displayed.');
898
    $this->assertText(t('When cancelling these accounts'), 'Allows to select account cancellation method.');
899
    $this->assertText(t('Require e-mail confirmation to cancel account.'), 'Allows to send confirmation mail.');
900
    $this->assertText(t('Notify user when account is canceled.'), 'Allows to send notification mail.');
901

    
902
    // Confirm deletion.
903
    $this->drupalPost(NULL, NULL, t('Cancel accounts'));
904
    $status = TRUE;
905
    foreach ($users as $account) {
906
      $status = $status && (strpos($this->content, t('%name has been deleted.', array('%name' => $account->name))) !== FALSE);
907
      $status = $status && !user_load($account->uid, TRUE);
908
    }
909
    $this->assertTrue($status, 'Users deleted and not found in the database.');
910

    
911
    // Ensure that admin account was not cancelled.
912
    $this->assertText(t('A confirmation request to cancel your account has been sent to your e-mail address.'), 'Account cancellation request mailed message displayed.');
913
    $admin_user = user_load($admin_user->uid);
914
    $this->assertTrue($admin_user->status == 1, 'Administrative user is found in the database and enabled.');
915

    
916
    // Verify that uid 1's account was not cancelled.
917
    $user1 = user_load(1, TRUE);
918
    $this->assertEqual($user1->status, 1, 'User #1 still exists and is not blocked.');
919
  }
920
}
921

    
922
class UserPictureTestCase extends DrupalWebTestCase {
923
  protected $user;
924
  protected $_directory_test;
925

    
926
  public static function getInfo() {
927
    return array(
928
      'name' => 'Upload user picture',
929
      'description' => 'Assure that dimension check, extension check and image scaling work as designed.',
930
      'group' => 'User'
931
    );
932
  }
933

    
934
  function setUp() {
935
    parent::setUp();
936
    // Enable user pictures.
937
    variable_set('user_pictures', 1);
938

    
939
    $this->user = $this->drupalCreateUser();
940

    
941
    // Test if directories specified in settings exist in filesystem.
942
    $file_dir = 'public://';
943
    $file_check = file_prepare_directory($file_dir, FILE_CREATE_DIRECTORY);
944
    // TODO: Test public and private methods?
945

    
946
    $picture_dir = variable_get('user_picture_path', 'pictures');
947
    $picture_path = $file_dir . $picture_dir;
948

    
949
    $pic_check = file_prepare_directory($picture_path, FILE_CREATE_DIRECTORY);
950
    $this->_directory_test = is_writable($picture_path);
951
    $this->assertTrue($this->_directory_test, "The directory $picture_path doesn't exist or is not writable. Further tests won't be made.");
952
  }
953

    
954
  function testNoPicture() {
955
    $this->drupalLogin($this->user);
956

    
957
    // Try to upload a file that is not an image for the user picture.
958
    $not_an_image = current($this->drupalGetTestFiles('html'));
959
    $this->saveUserPicture($not_an_image);
960
    $this->assertRaw(t('Only JPEG, PNG and GIF images are allowed.'), 'Non-image files are not accepted.');
961
  }
962

    
963
  /**
964
   * Do the test:
965
   *  GD Toolkit is installed
966
   *  Picture has invalid dimension
967
   *
968
   * results: The image should be uploaded because ImageGDToolkit resizes the picture
969
   */
970
  function testWithGDinvalidDimension() {
971
    if ($this->_directory_test && image_get_toolkit()) {
972
      $this->drupalLogin($this->user);
973

    
974
      $image = current($this->drupalGetTestFiles('image'));
975
      $info = image_get_info($image->uri);
976

    
977
      // Set new variables: invalid dimensions, valid filesize (0 = no limit).
978
      $test_dim = ($info['width'] - 10) . 'x' . ($info['height'] - 10);
979
      variable_set('user_picture_dimensions', $test_dim);
980
      variable_set('user_picture_file_size', 0);
981

    
982
      $pic_path = $this->saveUserPicture($image);
983
      // Check that the image was resized and is being displayed on the
984
      // user's profile page.
985
      $text = t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels.', array('%dimensions' => $test_dim));
986
      $this->assertRaw($text, 'Image was resized.');
987
      $alt = t("@user's picture", array('@user' => format_username($this->user)));
988
      $style = variable_get('user_picture_style', '');
989
      $this->assertRaw(check_plain(image_style_url($style, $pic_path)), "Image is displayed in user's edit page");
990

    
991
      // Check if file is located in proper directory.
992
      $this->assertTrue(is_file($pic_path), "File is located in proper directory");
993
    }
994
  }
995

    
996
  /**
997
   * Do the test:
998
   *  GD Toolkit is installed
999
   *  Picture has invalid size
1000
   *
1001
   * results: The image should be uploaded because ImageGDToolkit resizes the picture
1002
   */
1003
  function testWithGDinvalidSize() {
1004
    if ($this->_directory_test && image_get_toolkit()) {
1005
      $this->drupalLogin($this->user);
1006

    
1007
      // Images are sorted first by size then by name. We need an image
1008
      // bigger than 1 KB so we'll grab the last one.
1009
      $files = $this->drupalGetTestFiles('image');
1010
      $image = end($files);
1011
      $info = image_get_info($image->uri);
1012

    
1013
      // Set new variables: valid dimensions, invalid filesize.
1014
      $test_dim = ($info['width'] + 10) . 'x' . ($info['height'] + 10);
1015
      $test_size = 1;
1016
      variable_set('user_picture_dimensions', $test_dim);
1017
      variable_set('user_picture_file_size', $test_size);
1018

    
1019
      $pic_path = $this->saveUserPicture($image);
1020

    
1021
      // Test that the upload failed and that the correct reason was cited.
1022
      $text = t('The specified file %filename could not be uploaded.', array('%filename' => $image->filename));
1023
      $this->assertRaw($text, 'Upload failed.');
1024
      $text = t('The file is %filesize exceeding the maximum file size of %maxsize.', array('%filesize' => format_size(filesize($image->uri)), '%maxsize' => format_size($test_size * 1024)));
1025
      $this->assertRaw($text, 'File size cited as reason for failure.');
1026

    
1027
      // Check if file is not uploaded.
1028
      $this->assertFalse(is_file($pic_path), 'File was not uploaded.');
1029
    }
1030
  }
1031

    
1032
  /**
1033
   * Do the test:
1034
   *  GD Toolkit is not installed
1035
   *  Picture has invalid size
1036
   *
1037
   * results: The image shouldn't be uploaded
1038
   */
1039
  function testWithoutGDinvalidDimension() {
1040
    if ($this->_directory_test && !image_get_toolkit()) {
1041
      $this->drupalLogin($this->user);
1042

    
1043
      $image = current($this->drupalGetTestFiles('image'));
1044
      $info = image_get_info($image->uri);
1045

    
1046
      // Set new variables: invalid dimensions, valid filesize (0 = no limit).
1047
      $test_dim = ($info['width'] - 10) . 'x' . ($info['height'] - 10);
1048
      variable_set('user_picture_dimensions', $test_dim);
1049
      variable_set('user_picture_file_size', 0);
1050

    
1051
      $pic_path = $this->saveUserPicture($image);
1052

    
1053
      // Test that the upload failed and that the correct reason was cited.
1054
      $text = t('The specified file %filename could not be uploaded.', array('%filename' => $image->filename));
1055
      $this->assertRaw($text, 'Upload failed.');
1056
      $text = t('The image is too large; the maximum dimensions are %dimensions pixels.', array('%dimensions' => $test_dim));
1057
      $this->assertRaw($text, 'Checking response on invalid image (dimensions).');
1058

    
1059
      // Check if file is not uploaded.
1060
      $this->assertFalse(is_file($pic_path), 'File was not uploaded.');
1061
    }
1062
  }
1063

    
1064
  /**
1065
   * Do the test:
1066
   *  GD Toolkit is not installed
1067
   *  Picture has invalid size
1068
   *
1069
   * results: The image shouldn't be uploaded
1070
   */
1071
  function testWithoutGDinvalidSize() {
1072
    if ($this->_directory_test && !image_get_toolkit()) {
1073
      $this->drupalLogin($this->user);
1074

    
1075
      $image = current($this->drupalGetTestFiles('image'));
1076
      $info = image_get_info($image->uri);
1077

    
1078
      // Set new variables: valid dimensions, invalid filesize.
1079
      $test_dim = ($info['width'] + 10) . 'x' . ($info['height'] + 10);
1080
      $test_size = 1;
1081
      variable_set('user_picture_dimensions', $test_dim);
1082
      variable_set('user_picture_file_size', $test_size);
1083

    
1084
      $pic_path = $this->saveUserPicture($image);
1085

    
1086
      // Test that the upload failed and that the correct reason was cited.
1087
      $text = t('The specified file %filename could not be uploaded.', array('%filename' => $image->filename));
1088
      $this->assertRaw($text, 'Upload failed.');
1089
      $text = t('The file is %filesize exceeding the maximum file size of %maxsize.', array('%filesize' => format_size(filesize($image->uri)), '%maxsize' => format_size($test_size * 1024)));
1090
      $this->assertRaw($text, 'File size cited as reason for failure.');
1091

    
1092
      // Check if file is not uploaded.
1093
      $this->assertFalse(is_file($pic_path), 'File was not uploaded.');
1094
    }
1095
  }
1096

    
1097
  /**
1098
   * Do the test:
1099
   *  Picture is valid (proper size and dimension)
1100
   *
1101
   * results: The image should be uploaded
1102
   */
1103
  function testPictureIsValid() {
1104
    if ($this->_directory_test) {
1105
      $this->drupalLogin($this->user);
1106

    
1107
      $image = current($this->drupalGetTestFiles('image'));
1108
      $info = image_get_info($image->uri);
1109

    
1110
      // Set new variables: valid dimensions, valid filesize (0 = no limit).
1111
      $test_dim = ($info['width'] + 10) . 'x' . ($info['height'] + 10);
1112
      variable_set('user_picture_dimensions', $test_dim);
1113
      variable_set('user_picture_file_size', 0);
1114

    
1115
      $pic_path = $this->saveUserPicture($image);
1116

    
1117
      // Check if image is displayed in user's profile page.
1118
      $this->drupalGet('user');
1119
      $this->assertRaw(file_uri_target($pic_path), "Image is displayed in user's profile page");
1120

    
1121
      // Check if file is located in proper directory.
1122
      $this->assertTrue(is_file($pic_path), 'File is located in proper directory');
1123

    
1124
      // Set new picture dimensions.
1125
      $test_dim = ($info['width'] + 5) . 'x' . ($info['height'] + 5);
1126
      variable_set('user_picture_dimensions', $test_dim);
1127

    
1128
      $pic_path2 = $this->saveUserPicture($image);
1129
      $this->assertNotEqual($pic_path, $pic_path2, 'Filename of second picture is different.');
1130

    
1131
      // Check if user picture has a valid file ID after saving the user.
1132
      $account = user_load($this->user->uid, TRUE);
1133
      $this->assertTrue(is_object($account->picture), 'User picture object is valid after user load.');
1134
      $this->assertNotNull($account->picture->fid, 'User picture object has a FID after user load.');
1135
      $this->assertTrue(is_file($account->picture->uri), 'File is located in proper directory after user load.');
1136
      user_save($account);
1137
      // Verify that the user save does not destroy the user picture object.
1138
      $this->assertTrue(is_object($account->picture), 'User picture object is valid after user save.');
1139
      $this->assertNotNull($account->picture->fid, 'User picture object has a FID after user save.');
1140
      $this->assertTrue(is_file($account->picture->uri), 'File is located in proper directory after user save.');
1141
    }
1142
  }
1143

    
1144
  /**
1145
   * Test HTTP schema working with user pictures.
1146
   */
1147
  function testExternalPicture() {
1148
    $this->drupalLogin($this->user);
1149
    // Set the default picture to an URI with a HTTP schema.
1150
    $images = $this->drupalGetTestFiles('image');
1151
    $image = $images[0];
1152
    $pic_path = file_create_url($image->uri);
1153
    variable_set('user_picture_default', $pic_path);
1154

    
1155
    // Check if image is displayed in user's profile page.
1156
    $this->drupalGet('user');
1157

    
1158
    // Get the user picture image via xpath.
1159
    $elements = $this->xpath('//div[@class="user-picture"]/img');
1160
    $this->assertEqual(count($elements), 1, "There is exactly one user picture on the user's profile page");
1161
    $this->assertEqual($pic_path, (string) $elements[0]['src'], "User picture source is correct.");
1162
  }
1163

    
1164
  /**
1165
   * Tests deletion of user pictures.
1166
   */
1167
  function testDeletePicture() {
1168
    $this->drupalLogin($this->user);
1169

    
1170
    $image = current($this->drupalGetTestFiles('image'));
1171
    $info = image_get_info($image->uri);
1172

    
1173
    // Set new variables: valid dimensions, valid filesize (0 = no limit).
1174
    $test_dim = ($info['width'] + 10) . 'x' . ($info['height'] + 10);
1175
    variable_set('user_picture_dimensions', $test_dim);
1176
    variable_set('user_picture_file_size', 0);
1177

    
1178
    // Save a new picture.
1179
    $edit = array('files[picture_upload]' => drupal_realpath($image->uri));
1180
    $this->drupalPost('user/' . $this->user->uid . '/edit', $edit, t('Save'));
1181

    
1182
    // Load actual user data from database.
1183
    $account = user_load($this->user->uid, TRUE);
1184
    $pic_path = isset($account->picture) ? $account->picture->uri : NULL;
1185

    
1186
    // Check if image is displayed in user's profile page.
1187
    $this->drupalGet('user');
1188
    $this->assertRaw(file_uri_target($pic_path), "Image is displayed in user's profile page");
1189

    
1190
    // Check if file is located in proper directory.
1191
    $this->assertTrue(is_file($pic_path), 'File is located in proper directory');
1192

    
1193
    $edit = array('picture_delete' => 1);
1194
    $this->drupalPost('user/' . $this->user->uid . '/edit', $edit, t('Save'));
1195

    
1196
    // Load actual user data from database.
1197
    $account1 = user_load($this->user->uid, TRUE);
1198
    $this->assertNull($account1->picture, 'User object has no picture');
1199

    
1200
    $file = file_load($account->picture->fid);
1201
    $this->assertFalse($file, 'File is removed from database');
1202

    
1203
    // Clear out PHP's file stat cache so we see the current value.
1204
    clearstatcache();
1205
    $this->assertFalse(is_file($pic_path), 'File is removed from file system');
1206
  }
1207

    
1208
  function saveUserPicture($image) {
1209
    $edit = array('files[picture_upload]' => drupal_realpath($image->uri));
1210
    $this->drupalPost('user/' . $this->user->uid . '/edit', $edit, t('Save'));
1211

    
1212
    // Load actual user data from database.
1213
    $account = user_load($this->user->uid, TRUE);
1214
    return isset($account->picture) ? $account->picture->uri : NULL;
1215
  }
1216

    
1217
  /**
1218
   * Tests the admin form validates user picture settings.
1219
   */
1220
  function testUserPictureAdminFormValidation() {
1221
    $this->drupalLogin($this->drupalCreateUser(array('administer users')));
1222

    
1223
    // The default values are valid.
1224
    $this->drupalPost('admin/config/people/accounts', array(), t('Save configuration'));
1225
    $this->assertText(t('The configuration options have been saved.'), 'The default values are valid.');
1226

    
1227
    // The form does not save with an invalid file size.
1228
    $edit = array(
1229
      'user_picture_file_size' => $this->randomName(),
1230
    );
1231
    $this->drupalPost('admin/config/people/accounts', $edit, t('Save configuration'));
1232
    $this->assertNoText(t('The configuration options have been saved.'), 'The form does not save with an invalid file size.');
1233
  }
1234
}
1235

    
1236

    
1237
class UserPermissionsTestCase extends DrupalWebTestCase {
1238
  protected $admin_user;
1239
  protected $rid;
1240

    
1241
  public static function getInfo() {
1242
    return array(
1243
      'name' => 'Role permissions',
1244
      'description' => 'Verify that role permissions can be added and removed via the permissions page.',
1245
      'group' => 'User'
1246
    );
1247
  }
1248

    
1249
  function setUp() {
1250
    parent::setUp();
1251

    
1252
    $this->admin_user = $this->drupalCreateUser(array('administer permissions', 'access user profiles', 'administer site configuration', 'administer modules', 'administer users'));
1253

    
1254
    // Find the new role ID - it must be the maximum.
1255
    $all_rids = array_keys($this->admin_user->roles);
1256
    sort($all_rids);
1257
    $this->rid = array_pop($all_rids);
1258
  }
1259

    
1260
  /**
1261
   * Change user permissions and check user_access().
1262
   */
1263
  function testUserPermissionChanges() {
1264
    $this->drupalLogin($this->admin_user);
1265
    $rid = $this->rid;
1266
    $account = $this->admin_user;
1267

    
1268
    // Add a permission.
1269
    $this->assertFalse(user_access('administer nodes', $account), 'User does not have "administer nodes" permission.');
1270
    $edit = array();
1271
    $edit[$rid . '[administer nodes]'] = TRUE;
1272
    $this->drupalPost('admin/people/permissions', $edit, t('Save permissions'));
1273
    $this->assertText(t('The changes have been saved.'), 'Successful save message displayed.');
1274
    drupal_static_reset('user_access');
1275
    drupal_static_reset('user_role_permissions');
1276
    $this->assertTrue(user_access('administer nodes', $account), 'User now has "administer nodes" permission.');
1277

    
1278
    // Remove a permission.
1279
    $this->assertTrue(user_access('access user profiles', $account), 'User has "access user profiles" permission.');
1280
    $edit = array();
1281
    $edit[$rid . '[access user profiles]'] = FALSE;
1282
    $this->drupalPost('admin/people/permissions', $edit, t('Save permissions'));
1283
    $this->assertText(t('The changes have been saved.'), 'Successful save message displayed.');
1284
    drupal_static_reset('user_access');
1285
    drupal_static_reset('user_role_permissions');
1286
    $this->assertFalse(user_access('access user profiles', $account), 'User no longer has "access user profiles" permission.');
1287
  }
1288

    
1289
  /**
1290
   * Test assigning of permissions for the administrator role.
1291
   */
1292
  function testAdministratorRole() {
1293
    $this->drupalLogin($this->admin_user);
1294
    $this->drupalGet('admin/config/people/accounts');
1295

    
1296
    // Set the user's role to be the administrator role.
1297
    $edit = array();
1298
    $edit['user_admin_role'] = $this->rid;
1299
    $this->drupalPost('admin/config/people/accounts', $edit, t('Save configuration'));
1300

    
1301
    // Enable aggregator module and ensure the 'administer news feeds'
1302
    // permission is assigned by default.
1303
    $edit = array();
1304
    $edit['modules[Core][aggregator][enable]'] = TRUE;
1305
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
1306
    $this->assertTrue(user_access('administer news feeds', $this->admin_user), 'The permission was automatically assigned to the administrator role');
1307
  }
1308

    
1309
  /**
1310
   * Verify proper permission changes by user_role_change_permissions().
1311
   */
1312
  function testUserRoleChangePermissions() {
1313
    $rid = $this->rid;
1314
    $account = $this->admin_user;
1315

    
1316
    // Verify current permissions.
1317
    $this->assertFalse(user_access('administer nodes', $account), 'User does not have "administer nodes" permission.');
1318
    $this->assertTrue(user_access('access user profiles', $account), 'User has "access user profiles" permission.');
1319
    $this->assertTrue(user_access('administer site configuration', $account), 'User has "administer site configuration" permission.');
1320

    
1321
    // Change permissions.
1322
    $permissions = array(
1323
      'administer nodes' => 1,
1324
      'access user profiles' => 0,
1325
    );
1326
    user_role_change_permissions($rid, $permissions);
1327

    
1328
    // Verify proper permission changes.
1329
    $this->assertTrue(user_access('administer nodes', $account), 'User now has "administer nodes" permission.');
1330
    $this->assertFalse(user_access('access user profiles', $account), 'User no longer has "access user profiles" permission.');
1331
    $this->assertTrue(user_access('administer site configuration', $account), 'User still has "administer site configuration" permission.');
1332
  }
1333
}
1334

    
1335
class UserAdminTestCase extends DrupalWebTestCase {
1336
  public static function getInfo() {
1337
    return array(
1338
      'name' => 'User administration',
1339
      'description' => 'Test user administration page functionality.',
1340
      'group' => 'User'
1341
    );
1342
  }
1343

    
1344
  /**
1345
   * Registers a user and deletes it.
1346
   */
1347
  function testUserAdmin() {
1348

    
1349
    $user_a = $this->drupalCreateUser(array());
1350
    $user_b = $this->drupalCreateUser(array('administer taxonomy'));
1351
    $user_c = $this->drupalCreateUser(array('administer taxonomy'));
1352

    
1353
    // Create admin user to delete registered user.
1354
    $admin_user = $this->drupalCreateUser(array('administer users'));
1355
    $this->drupalLogin($admin_user);
1356
    $this->drupalGet('admin/people');
1357
    $this->assertText($user_a->name, 'Found user A on admin users page');
1358
    $this->assertText($user_b->name, 'Found user B on admin users page');
1359
    $this->assertText($user_c->name, 'Found user C on admin users page');
1360
    $this->assertText($admin_user->name, 'Found Admin user on admin users page');
1361

    
1362
    // Test for existence of edit link in table.
1363
    $link = l(t('edit'), "user/$user_a->uid/edit", array('query' => array('destination' => 'admin/people')));
1364
    $this->assertRaw($link, 'Found user A edit link on admin users page');
1365

    
1366
    // Filter the users by permission 'administer taxonomy'.
1367
    $edit = array();
1368
    $edit['permission'] = 'administer taxonomy';
1369
    $this->drupalPost('admin/people', $edit, t('Filter'));
1370

    
1371
    // Check if the correct users show up.
1372
    $this->assertNoText($user_a->name, 'User A not on filtered by perm admin users page');
1373
    $this->assertText($user_b->name, 'Found user B on filtered by perm admin users page');
1374
    $this->assertText($user_c->name, 'Found user C on filtered by perm admin users page');
1375

    
1376
    // Filter the users by role. Grab the system-generated role name for User C.
1377
    $edit['role'] = max(array_flip($user_c->roles));
1378
    $this->drupalPost('admin/people', $edit, t('Refine'));
1379

    
1380
    // Check if the correct users show up when filtered by role.
1381
    $this->assertNoText($user_a->name, 'User A not on filtered by role on admin users page');
1382
    $this->assertNoText($user_b->name, 'User B not on filtered by role on admin users page');
1383
    $this->assertText($user_c->name, 'User C on filtered by role on admin users page');
1384

    
1385
    // Test blocking of a user.
1386
    $account = user_load($user_c->uid);
1387
    $this->assertEqual($account->status, 1, 'User C not blocked');
1388
    $edit = array();
1389
    $edit['operation'] = 'block';
1390
    $edit['accounts[' . $account->uid . ']'] = TRUE;
1391
    $this->drupalPost('admin/people', $edit, t('Update'));
1392
    $account = user_load($user_c->uid, TRUE);
1393
    $this->assertEqual($account->status, 0, 'User C blocked');
1394

    
1395
    // Test unblocking of a user from /admin/people page and sending of activation mail
1396
    $editunblock = array();
1397
    $editunblock['operation'] = 'unblock';
1398
    $editunblock['accounts[' . $account->uid . ']'] = TRUE;
1399
    $this->drupalPost('admin/people', $editunblock, t('Update'));
1400
    $account = user_load($user_c->uid, TRUE);
1401
    $this->assertEqual($account->status, 1, 'User C unblocked');
1402
    $this->assertMail("to", $account->mail, "Activation mail sent to user C");
1403

    
1404
    // Test blocking and unblocking another user from /user/[uid]/edit form and sending of activation mail
1405
    $user_d = $this->drupalCreateUser(array());
1406
    $account1 = user_load($user_d->uid, TRUE);
1407
    $this->drupalPost('user/' . $account1->uid . '/edit', array('status' => 0), t('Save'));
1408
    $account1 = user_load($user_d->uid, TRUE);
1409
    $this->assertEqual($account1->status, 0, 'User D blocked');
1410
    $this->drupalPost('user/' . $account1->uid . '/edit', array('status' => TRUE), t('Save'));
1411
    $account1 = user_load($user_d->uid, TRUE);
1412
    $this->assertEqual($account1->status, 1, 'User D unblocked');
1413
    $this->assertMail("to", $account1->mail, "Activation mail sent to user D");
1414
  }
1415
}
1416

    
1417
/**
1418
 * Tests for user-configurable time zones.
1419
 */
1420
class UserTimeZoneFunctionalTest extends DrupalWebTestCase {
1421
  public static function getInfo() {
1422
    return array(
1423
      'name' => 'User time zones',
1424
      'description' => 'Set a user time zone and verify that dates are displayed in local time.',
1425
      'group' => 'User',
1426
    );
1427
  }
1428

    
1429
  /**
1430
   * Tests the display of dates and time when user-configurable time zones are set.
1431
   */
1432
  function testUserTimeZone() {
1433
    // Setup date/time settings for Los Angeles time.
1434
    variable_set('date_default_timezone', 'America/Los_Angeles');
1435
    variable_set('configurable_timezones', 1);
1436
    variable_set('date_format_medium', 'Y-m-d H:i T');
1437

    
1438
    // Create a user account and login.
1439
    $web_user = $this->drupalCreateUser();
1440
    $this->drupalLogin($web_user);
1441

    
1442
    // Create some nodes with different authored-on dates.
1443
    // Two dates in PST (winter time):
1444
    $date1 = '2007-03-09 21:00:00 -0800';
1445
    $date2 = '2007-03-11 01:00:00 -0800';
1446
    // One date in PDT (summer time):
1447
    $date3 = '2007-03-20 21:00:00 -0700';
1448
    $node1 = $this->drupalCreateNode(array('created' => strtotime($date1), 'type' => 'article'));
1449
    $node2 = $this->drupalCreateNode(array('created' => strtotime($date2), 'type' => 'article'));
1450
    $node3 = $this->drupalCreateNode(array('created' => strtotime($date3), 'type' => 'article'));
1451

    
1452
    // Confirm date format and time zone.
1453
    $this->drupalGet("node/$node1->nid");
1454
    $this->assertText('2007-03-09 21:00 PST', 'Date should be PST.');
1455
    $this->drupalGet("node/$node2->nid");
1456
    $this->assertText('2007-03-11 01:00 PST', 'Date should be PST.');
1457
    $this->drupalGet("node/$node3->nid");
1458
    $this->assertText('2007-03-20 21:00 PDT', 'Date should be PDT.');
1459

    
1460
    // Change user time zone to Santiago time.
1461
    $edit = array();
1462
    $edit['mail'] = $web_user->mail;
1463
    $edit['timezone'] = 'America/Santiago';
1464
    $this->drupalPost("user/$web_user->uid/edit", $edit, t('Save'));
1465
    $this->assertText(t('The changes have been saved.'), 'Time zone changed to Santiago time.');
1466

    
1467
    // Confirm date format and time zone.
1468
    $this->drupalGet("node/$node1->nid");
1469
    $this->assertText('2007-03-10 02:00 CLST', 'Date should be Chile summer time; five hours ahead of PST.');
1470
    $this->drupalGet("node/$node2->nid");
1471
    $this->assertText('2007-03-11 05:00 CLT', 'Date should be Chile time; four hours ahead of PST');
1472
    $this->drupalGet("node/$node3->nid");
1473
    $this->assertText('2007-03-21 00:00 CLT', 'Date should be Chile time; three hours ahead of PDT.');
1474
  }
1475
}
1476

    
1477
/**
1478
 * Test user autocompletion.
1479
 */
1480
class UserAutocompleteTestCase extends DrupalWebTestCase {
1481
  public static function getInfo() {
1482
    return array(
1483
      'name' => 'User autocompletion',
1484
      'description' => 'Test user autocompletion functionality.',
1485
      'group' => 'User'
1486
    );
1487
  }
1488

    
1489
  function setUp() {
1490
    parent::setUp();
1491

    
1492
    // Set up two users with different permissions to test access.
1493
    $this->unprivileged_user = $this->drupalCreateUser();
1494
    $this->privileged_user = $this->drupalCreateUser(array('access user profiles'));
1495
  }
1496

    
1497
  /**
1498
   * Tests access to user autocompletion and verify the correct results.
1499
   */
1500
  function testUserAutocomplete() {
1501
    // Check access from unprivileged user, should be denied.
1502
    $this->drupalLogin($this->unprivileged_user);
1503
    $this->drupalGet('user/autocomplete/' . $this->unprivileged_user->name[0]);
1504
    $this->assertResponse(403, 'Autocompletion access denied to user without permission.');
1505

    
1506
    // Check access from privileged user.
1507
    $this->drupalLogout();
1508
    $this->drupalLogin($this->privileged_user);
1509
    $this->drupalGet('user/autocomplete/' . $this->unprivileged_user->name[0]);
1510
    $this->assertResponse(200, 'Autocompletion access allowed.');
1511

    
1512
    // Using first letter of the user's name, make sure the user's full name is in the results.
1513
    $this->assertRaw($this->unprivileged_user->name, 'User name found in autocompletion results.');
1514
  }
1515
}
1516

    
1517

    
1518
/**
1519
 * Tests user links in the secondary menu.
1520
 */
1521
class UserAccountLinksUnitTests extends DrupalWebTestCase {
1522
  public static function getInfo() {
1523
    return array(
1524
      'name' => 'User account links',
1525
      'description' => 'Test user-account links.',
1526
      'group' => 'User'
1527
    );
1528
  }
1529

    
1530
  function setUp() {
1531
    parent::setUp('menu');
1532
  }
1533

    
1534
  /**
1535
   * Tests the secondary menu.
1536
   */
1537
  function testSecondaryMenu() {
1538
    // Create a regular user.
1539
    $user = $this->drupalCreateUser(array());
1540

    
1541
    // Log in and get the homepage.
1542
    $this->drupalLogin($user);
1543
    $this->drupalGet('<front>');
1544

    
1545
    // For a logged-in user, expect the secondary menu to have links for "My
1546
    // account" and "Log out".
1547
    $link = $this->xpath('//ul[@id=:menu_id]/li/a[contains(@href, :href) and text()=:text]', array(
1548
      ':menu_id' => 'secondary-menu-links',
1549
      ':href' => 'user',
1550
      ':text' => 'My account',
1551
    ));
1552
    $this->assertEqual(count($link), 1, 'My account link is in secondary menu.');
1553

    
1554
    $link = $this->xpath('//ul[@id=:menu_id]/li/a[contains(@href, :href) and text()=:text]', array(
1555
      ':menu_id' => 'secondary-menu-links',
1556
      ':href' => 'user/logout',
1557
      ':text' => 'Log out',
1558
    ));
1559
    $this->assertEqual(count($link), 1, 'Log out link is in secondary menu.');
1560

    
1561
    // Log out and get the homepage.
1562
    $this->drupalLogout();
1563
    $this->drupalGet('<front>');
1564

    
1565
    // For a logged-out user, expect no secondary links.
1566
    $element = $this->xpath('//ul[@id=:menu_id]', array(':menu_id' => 'secondary-menu-links'));
1567
    $this->assertEqual(count($element), 0, 'No secondary-menu for logged-out users.');
1568
  }
1569

    
1570
  /**
1571
   * Tests disabling the 'My account' link.
1572
   */
1573
  function testDisabledAccountLink() {
1574
    // Create an admin user and log in.
1575
    $this->drupalLogin($this->drupalCreateUser(array('access administration pages', 'administer menu')));
1576

    
1577
    // Verify that the 'My account' link is enabled.
1578
    $this->drupalGet('admin/structure/menu/manage/user-menu');
1579
    $label = $this->xpath('//label[contains(.,:text)]/@for', array(':text' => 'Enable My account menu link'));
1580
    $this->assertFieldChecked((string) $label[0], "The 'My account' link is enabled by default.");
1581

    
1582
    // Disable the 'My account' link.
1583
    $input = $this->xpath('//input[@id=:field_id]/@name', array(':field_id' => (string)$label[0]));
1584
    $edit = array(
1585
      (string) $input[0] => FALSE,
1586
    );
1587
    $this->drupalPost('admin/structure/menu/manage/user-menu', $edit, t('Save configuration'));
1588

    
1589
    // Get the homepage.
1590
    $this->drupalGet('<front>');
1591

    
1592
    // Verify that the 'My account' link does not appear when disabled.
1593
    $link = $this->xpath('//ul[@id=:menu_id]/li/a[contains(@href, :href) and text()=:text]', array(
1594
      ':menu_id' => 'secondary-menu-links',
1595
      ':href' => 'user',
1596
      ':text' => 'My account',
1597
    ));
1598
    $this->assertEqual(count($link), 0, 'My account link is not in the secondary menu.');
1599
  }
1600

    
1601
}
1602

    
1603
/**
1604
 * Test user blocks.
1605
 */
1606
class UserBlocksUnitTests extends DrupalWebTestCase {
1607
  public static function getInfo() {
1608
    return array(
1609
      'name' => 'User blocks',
1610
      'description' => 'Test user blocks.',
1611
      'group' => 'User'
1612
    );
1613
  }
1614

    
1615
  /**
1616
   * Test the user login block.
1617
   */
1618
  function testUserLoginBlock() {
1619
    // Create a user with some permission that anonymous users lack.
1620
    $user = $this->drupalCreateUser(array('administer permissions'));
1621

    
1622
    // Log in using the block.
1623
    $edit = array();
1624
    $edit['name'] = $user->name;
1625
    $edit['pass'] = $user->pass_raw;
1626
    $this->drupalPost('admin/people/permissions', $edit, t('Log in'));
1627
    $this->assertNoText(t('User login'), 'Logged in.');
1628

    
1629
    // Check that we are still on the same page.
1630
    $this->assertEqual(url('admin/people/permissions', array('absolute' => TRUE)), $this->getUrl(), 'Still on the same page after login for access denied page');
1631

    
1632
    // Now, log out and repeat with a non-403 page.
1633
    $this->drupalLogout();
1634
    $this->drupalPost('filter/tips', $edit, t('Log in'));
1635
    $this->assertNoText(t('User login'), 'Logged in.');
1636
    $this->assertPattern('!<title.*?' . t('Compose tips') . '.*?</title>!', 'Still on the same page after login for allowed page');
1637

    
1638
    // Check that the user login block is not vulnerable to information
1639
    // disclosure to third party sites.
1640
    $this->drupalLogout();
1641
    $this->drupalPost('http://example.com/', $edit, t('Log in'), array('external' => FALSE));
1642
    // Check that we remain on the site after login.
1643
    $this->assertEqual(url('user/' . $user->uid, array('absolute' => TRUE)), $this->getUrl(), 'Redirected to user profile page after login from the frontpage');
1644
  }
1645

    
1646
  /**
1647
   * Test the Who's Online block.
1648
   */
1649
  function testWhosOnlineBlock() {
1650
    // Generate users and make sure there are no current user sessions.
1651
    $user1 = $this->drupalCreateUser(array());
1652
    $user2 = $this->drupalCreateUser(array());
1653
    $user3 = $this->drupalCreateUser(array());
1654
    $this->assertEqual(db_query("SELECT COUNT(*) FROM {sessions}")->fetchField(), 0, 'Sessions table is empty.');
1655

    
1656
    // Insert a user with two sessions.
1657
    $this->insertSession(array('uid' => $user1->uid));
1658
    $this->insertSession(array('uid' => $user1->uid));
1659
    $this->assertEqual(db_query("SELECT COUNT(*) FROM {sessions} WHERE uid = :uid", array(':uid' => $user1->uid))->fetchField(), 2, 'Duplicate user session has been inserted.');
1660

    
1661
    // Insert a user with only one session.
1662
    $this->insertSession(array('uid' => $user2->uid, 'timestamp' => REQUEST_TIME + 1));
1663

    
1664
    // Insert an inactive logged-in user who should not be seen in the block.
1665
    $this->insertSession(array('uid' => $user3->uid, 'timestamp' => (REQUEST_TIME - variable_get('user_block_seconds_online', 900) - 1)));
1666

    
1667
    // Insert two anonymous user sessions.
1668
    $this->insertSession();
1669
    $this->insertSession();
1670

    
1671
    // Test block output.
1672
    $block = user_block_view('online');
1673
    $this->drupalSetContent($block['content']);
1674
    $this->assertRaw(t('2 users'), 'Correct number of online users (2 users).');
1675
    $this->assertText($user1->name, 'Active user 1 found in online list.');
1676
    $this->assertText($user2->name, 'Active user 2 found in online list.');
1677
    $this->assertNoText($user3->name, "Inactive user not found in online list.");
1678
    $this->assertTrue(strpos($this->drupalGetContent(), $user1->name) > strpos($this->drupalGetContent(), $user2->name), 'Online users are ordered correctly.');
1679
  }
1680

    
1681
  /**
1682
   * Insert a user session into the {sessions} table. This function is used
1683
   * since we cannot log in more than one user at the same time in tests.
1684
   */
1685
  private function insertSession(array $fields = array()) {
1686
    $fields += array(
1687
      'uid' => 0,
1688
      'sid' => drupal_hash_base64(uniqid(mt_rand(), TRUE)),
1689
      'timestamp' => REQUEST_TIME,
1690
    );
1691
    db_insert('sessions')
1692
      ->fields($fields)
1693
      ->execute();
1694
    $this->assertEqual(db_query("SELECT COUNT(*) FROM {sessions} WHERE uid = :uid AND sid = :sid AND timestamp = :timestamp", array(':uid' => $fields['uid'], ':sid' => $fields['sid'], ':timestamp' => $fields['timestamp']))->fetchField(), 1, 'Session record inserted.');
1695
  }
1696
}
1697

    
1698
/**
1699
 * Tests saving a user account.
1700
 */
1701
class UserSaveTestCase extends DrupalWebTestCase {
1702

    
1703
  public static function getInfo() {
1704
    return array(
1705
      'name' => 'User save test',
1706
      'description' => 'Test user_save() for arbitrary new uid.',
1707
      'group' => 'User',
1708
    );
1709
  }
1710

    
1711
  /**
1712
   * Test creating a user with arbitrary uid.
1713
   */
1714
  function testUserImport() {
1715
    // User ID must be a number that is not in the database.
1716
    $max_uid = db_query('SELECT MAX(uid) FROM {users}')->fetchField();
1717
    $test_uid = $max_uid + mt_rand(1000, 1000000);
1718
    $test_name = $this->randomName();
1719

    
1720
    // Create the base user, based on drupalCreateUser().
1721
    $user = array(
1722
      'name' => $test_name,
1723
      'uid' => $test_uid,
1724
      'mail' => $test_name . '@example.com',
1725
      'is_new' => TRUE,
1726
      'pass' => user_password(),
1727
      'status' => 1,
1728
    );
1729
    $user_by_return = user_save(drupal_anonymous_user(), $user);
1730
    $this->assertTrue($user_by_return, 'Loading user by return of user_save().');
1731

    
1732
    // Test if created user exists.
1733
    $user_by_uid = user_load($test_uid);
1734
    $this->assertTrue($user_by_uid, 'Loading user by uid.');
1735

    
1736
    $user_by_name = user_load_by_name($test_name);
1737
    $this->assertTrue($user_by_name, 'Loading user by name.');
1738
  }
1739
}
1740

    
1741
/**
1742
 * Test the create user administration page.
1743
 */
1744
class UserCreateTestCase extends DrupalWebTestCase {
1745

    
1746
  public static function getInfo() {
1747
    return array(
1748
      'name' => 'User create',
1749
      'description' => 'Test the create user administration page.',
1750
      'group' => 'User',
1751
    );
1752
  }
1753

    
1754
  /**
1755
   * Create a user through the administration interface and ensure that it
1756
   * displays in the user list.
1757
   */
1758
  protected function testUserAdd() {
1759
    $user = $this->drupalCreateUser(array('administer users'));
1760
    $this->drupalLogin($user);
1761

    
1762
    foreach (array(FALSE, TRUE) as $notify) {
1763
      $edit = array(
1764
        'name' => $this->randomName(),
1765
        'mail' => $this->randomName() . '@example.com',
1766
        'pass[pass1]' => $pass = $this->randomString(),
1767
        'pass[pass2]' => $pass,
1768
        'notify' => $notify,
1769
      );
1770
      $this->drupalPost('admin/people/create', $edit, t('Create new account'));
1771

    
1772
      if ($notify) {
1773
        $this->assertText(t('A welcome message with further instructions has been e-mailed to the new user @name.', array('@name' => $edit['name'])), 'User created');
1774
        $this->assertEqual(count($this->drupalGetMails()), 1, 'Notification e-mail sent');
1775
      }
1776
      else {
1777
        $this->assertText(t('Created a new user account for @name. No e-mail has been sent.', array('@name' => $edit['name'])), 'User created');
1778
        $this->assertEqual(count($this->drupalGetMails()), 0, 'Notification e-mail not sent');
1779
      }
1780

    
1781
      $this->drupalGet('admin/people');
1782
      $this->assertText($edit['name'], 'User found in list of users');
1783
    }
1784
  }
1785
}
1786

    
1787
/**
1788
 * Tests editing a user account.
1789
 */
1790
class UserEditTestCase extends DrupalWebTestCase {
1791

    
1792
  public static function getInfo() {
1793
    return array(
1794
      'name' => 'User edit',
1795
      'description' => 'Test user edit page.',
1796
      'group' => 'User',
1797
    );
1798
  }
1799

    
1800
  /**
1801
   * Test user edit page.
1802
   */
1803
  function testUserEdit() {
1804
    // Test user edit functionality with user pictures disabled.
1805
    variable_set('user_pictures', 0);
1806
    $user1 = $this->drupalCreateUser(array('change own username'));
1807
    $user2 = $this->drupalCreateUser(array());
1808
    $this->drupalLogin($user1);
1809

    
1810
    // Test that error message appears when attempting to use a non-unique user name.
1811
    $edit['name'] = $user2->name;
1812
    $this->drupalPost("user/$user1->uid/edit", $edit, t('Save'));
1813
    $this->assertRaw(t('The name %name is already taken.', array('%name' => $edit['name'])));
1814

    
1815
    // Repeat the test with user pictures enabled, which modifies the form.
1816
    variable_set('user_pictures', 1);
1817
    $this->drupalPost("user/$user1->uid/edit", $edit, t('Save'));
1818
    $this->assertRaw(t('The name %name is already taken.', array('%name' => $edit['name'])));
1819

    
1820
    // Check that filling out a single password field does not validate.
1821
    $edit = array();
1822
    $edit['pass[pass1]'] = '';
1823
    $edit['pass[pass2]'] = $this->randomName();
1824
    $this->drupalPost("user/$user1->uid/edit", $edit, t('Save'));
1825
    $this->assertText(t("The specified passwords do not match."), 'Typing mismatched passwords displays an error message.');
1826

    
1827
    $edit['pass[pass1]'] = $this->randomName();
1828
    $edit['pass[pass2]'] = '';
1829
    $this->drupalPost("user/$user1->uid/edit", $edit, t('Save'));
1830
    $this->assertText(t("The specified passwords do not match."), 'Typing mismatched passwords displays an error message.');
1831

    
1832
    // Test that the error message appears when attempting to change the mail or
1833
    // pass without the current password.
1834
    $edit = array();
1835
    $edit['mail'] = $this->randomName() . '@new.example.com';
1836
    $this->drupalPost("user/$user1->uid/edit", $edit, t('Save'));
1837
    $this->assertRaw(t("Your current password is missing or incorrect; it's required to change the %name.", array('%name' => t('E-mail address'))));
1838

    
1839
    $edit['current_pass'] = $user1->pass_raw;
1840
    $this->drupalPost("user/$user1->uid/edit", $edit, t('Save'));
1841
    $this->assertRaw(t("The changes have been saved."));
1842

    
1843
    // Test that the user must enter current password before changing passwords.
1844
    $edit = array();
1845
    $edit['pass[pass1]'] = $new_pass = $this->randomName();
1846
    $edit['pass[pass2]'] = $new_pass;
1847
    $this->drupalPost("user/$user1->uid/edit", $edit, t('Save'));
1848
    $this->assertRaw(t("Your current password is missing or incorrect; it's required to change the %name.", array('%name' => t('Password'))));
1849

    
1850
    // Try again with the current password.
1851
    $edit['current_pass'] = $user1->pass_raw;
1852
    $this->drupalPost("user/$user1->uid/edit", $edit, t('Save'));
1853
    $this->assertRaw(t("The changes have been saved."));
1854

    
1855
    // Make sure the user can log in with their new password.
1856
    $this->drupalLogout();
1857
    $user1->pass_raw = $new_pass;
1858
    $this->drupalLogin($user1);
1859
    $this->drupalLogout();
1860
  }
1861
}
1862

    
1863
/**
1864
 * Test case for user signatures.
1865
 */
1866
class UserSignatureTestCase extends DrupalWebTestCase {
1867
  public static function getInfo() {
1868
    return array(
1869
      'name' => 'User signatures',
1870
      'description' => 'Test user signatures.',
1871
      'group' => 'User',
1872
    );
1873
  }
1874

    
1875
  function setUp() {
1876
    parent::setUp('comment');
1877

    
1878
    // Enable user signatures.
1879
    variable_set('user_signatures', 1);
1880

    
1881
    // Prefetch text formats.
1882
    $this->full_html_format = filter_format_load('full_html');
1883
    $this->plain_text_format = filter_format_load('plain_text');
1884

    
1885
    // Create regular and administrative users.
1886
    $this->web_user = $this->drupalCreateUser(array());
1887
    $admin_permissions = array('administer comments');
1888
    foreach (filter_formats() as $format) {
1889
      if ($permission = filter_permission_name($format)) {
1890
        $admin_permissions[] = $permission;
1891
      }
1892
    }
1893
    $this->admin_user = $this->drupalCreateUser($admin_permissions);
1894
  }
1895

    
1896
  /**
1897
   * Test that a user can change their signature format and that it is respected
1898
   * upon display.
1899
   */
1900
  function testUserSignature() {
1901
    // Create a new node with comments on.
1902
    $node = $this->drupalCreateNode(array('comment' => COMMENT_NODE_OPEN));
1903

    
1904
    // Verify that user signature field is not displayed on registration form.
1905
    $this->drupalGet('user/register');
1906
    $this->assertNoText(t('Signature'));
1907

    
1908
    // Log in as a regular user and create a signature.
1909
    $this->drupalLogin($this->web_user);
1910
    $signature_text = "<h1>" . $this->randomName() . "</h1>";
1911
    $edit = array(
1912
      'signature[value]' => $signature_text,
1913
      'signature[format]' => $this->plain_text_format->format,
1914
    );
1915
    $this->drupalPost('user/' . $this->web_user->uid . '/edit', $edit, t('Save'));
1916

    
1917
    // Verify that values were stored.
1918
    $this->assertFieldByName('signature[value]', $edit['signature[value]'], 'Submitted signature text found.');
1919
    $this->assertFieldByName('signature[format]', $edit['signature[format]'], 'Submitted signature format found.');
1920

    
1921
    // Create a comment.
1922
    $langcode = LANGUAGE_NONE;
1923
    $edit = array();
1924
    $edit['subject'] = $this->randomName(8);
1925
    $edit['comment_body[' . $langcode . '][0][value]'] = $this->randomName(16);
1926
    $this->drupalPost('comment/reply/' . $node->nid, $edit, t('Preview'));
1927
    $this->drupalPost(NULL, array(), t('Save'));
1928

    
1929
    // Get the comment ID. (This technique is the same one used in the Comment
1930
    // module's CommentHelperCase test case.)
1931
    preg_match('/#comment-([0-9]+)/', $this->getURL(), $match);
1932
    $comment_id = $match[1];
1933

    
1934
    // Log in as an administrator and edit the comment to use Full HTML, so
1935
    // that the comment text itself is not filtered at all.
1936
    $this->drupalLogin($this->admin_user);
1937
    $edit['comment_body[' . $langcode . '][0][format]'] = $this->full_html_format->format;
1938
    $this->drupalPost('comment/' . $comment_id . '/edit', $edit, t('Save'));
1939

    
1940
    // Assert that the signature did not make it through unfiltered.
1941
    $this->drupalGet('node/' . $node->nid);
1942
    $this->assertNoRaw($signature_text, 'Unfiltered signature text not found.');
1943
    $this->assertRaw(check_markup($signature_text, $this->plain_text_format->format), 'Filtered signature text found.');
1944
  }
1945
}
1946

    
1947
/*
1948
 * Test that a user, having editing their own account, can still log in.
1949
 */
1950
class UserEditedOwnAccountTestCase extends DrupalWebTestCase {
1951

    
1952
  public static function getInfo() {
1953
    return array(
1954
      'name' => 'User edited own account',
1955
      'description' => 'Test user edited own account can still log in.',
1956
      'group' => 'User',
1957
    );
1958
  }
1959

    
1960
  function testUserEditedOwnAccount() {
1961
    // Change account setting 'Who can register accounts?' to Administrators
1962
    // only.
1963
    variable_set('user_register', USER_REGISTER_ADMINISTRATORS_ONLY);
1964

    
1965
    // Create a new user account and log in.
1966
    $account = $this->drupalCreateUser(array('change own username'));
1967
    $this->drupalLogin($account);
1968

    
1969
    // Change own username.
1970
    $edit = array();
1971
    $edit['name'] = $this->randomName();
1972
    $this->drupalPost('user/' . $account->uid . '/edit', $edit, t('Save'));
1973

    
1974
    // Log out.
1975
    $this->drupalLogout();
1976

    
1977
    // Set the new name on the user account and attempt to log back in.
1978
    $account->name = $edit['name'];
1979
    $this->drupalLogin($account);
1980
  }
1981
}
1982

    
1983
/**
1984
 * Test case to test adding, editing and deleting roles.
1985
 */
1986
class UserRoleAdminTestCase extends DrupalWebTestCase {
1987

    
1988
  public static function getInfo() {
1989
    return array(
1990
      'name' => 'User role administration',
1991
      'description' => 'Test adding, editing and deleting user roles and changing role weights.',
1992
      'group' => 'User',
1993
    );
1994
  }
1995

    
1996
  function setUp() {
1997
    parent::setUp();
1998
    $this->admin_user = $this->drupalCreateUser(array('administer permissions', 'administer users'));
1999
  }
2000

    
2001
  /**
2002
   * Test adding, renaming and deleting roles.
2003
   */
2004
  function testRoleAdministration() {
2005
    $this->drupalLogin($this->admin_user);
2006

    
2007
    // Test adding a role. (In doing so, we use a role name that happens to
2008
    // correspond to an integer, to test that the role administration pages
2009
    // correctly distinguish between role names and IDs.)
2010
    $role_name = '123';
2011
    $edit = array('name' => $role_name);
2012
    $this->drupalPost('admin/people/permissions/roles', $edit, t('Add role'));
2013
    $this->assertText(t('The role has been added.'), 'The role has been added.');
2014
    $role = user_role_load_by_name($role_name);
2015
    $this->assertTrue(is_object($role), 'The role was successfully retrieved from the database.');
2016

    
2017
    // Try adding a duplicate role.
2018
    $this->drupalPost(NULL, $edit, t('Add role'));
2019
    $this->assertRaw(t('The role name %name already exists. Choose another role name.', array('%name' => $role_name)), 'Duplicate role warning displayed.');
2020

    
2021
    // Test renaming a role.
2022
    $old_name = $role_name;
2023
    $role_name = '456';
2024
    $edit = array('name' => $role_name);
2025
    $this->drupalPost("admin/people/permissions/roles/edit/{$role->rid}", $edit, t('Save role'));
2026
    $this->assertText(t('The role has been renamed.'), 'The role has been renamed.');
2027
    $this->assertFalse(user_role_load_by_name($old_name), 'The role can no longer be retrieved from the database using its old name.');
2028
    $this->assertTrue(is_object(user_role_load_by_name($role_name)), 'The role can be retrieved from the database using its new name.');
2029

    
2030
    // Test deleting a role.
2031
    $this->drupalPost("admin/people/permissions/roles/edit/{$role->rid}", NULL, t('Delete role'));
2032
    $this->drupalPost(NULL, NULL, t('Delete'));
2033
    $this->assertText(t('The role has been deleted.'), 'The role has been deleted');
2034
    $this->assertNoLinkByHref("admin/people/permissions/roles/edit/{$role->rid}", 'Role edit link removed.');
2035
    $this->assertFalse(user_role_load_by_name($role_name), 'A deleted role can no longer be loaded.');
2036

    
2037
    // Make sure that the system-defined roles cannot be edited via the user
2038
    // interface.
2039
    $this->drupalGet('admin/people/permissions/roles/edit/' . DRUPAL_ANONYMOUS_RID);
2040
    $this->assertResponse(403, 'Access denied when trying to edit the built-in anonymous role.');
2041
    $this->drupalGet('admin/people/permissions/roles/edit/' . DRUPAL_AUTHENTICATED_RID);
2042
    $this->assertResponse(403, 'Access denied when trying to edit the built-in authenticated role.');
2043
  }
2044

    
2045
  /**
2046
   * Test user role weight change operation.
2047
   */
2048
  function testRoleWeightChange() {
2049
    $this->drupalLogin($this->admin_user);
2050

    
2051
    // Pick up a random role and get its weight.
2052
    $rid = array_rand(user_roles());
2053
    $role = user_role_load($rid);
2054
    $old_weight = $role->weight;
2055

    
2056
    // Change the role weight and submit the form.
2057
    $edit = array('roles['. $rid .'][weight]' => $old_weight + 1);
2058
    $this->drupalPost('admin/people/permissions/roles', $edit, t('Save order'));
2059
    $this->assertText(t('The role settings have been updated.'), 'The role settings form submitted successfully.');
2060

    
2061
    // Retrieve the saved role and compare its weight.
2062
    $role = user_role_load($rid);
2063
    $new_weight = $role->weight;
2064
    $this->assertTrue(($old_weight + 1) == $new_weight, 'Role weight updated successfully.');
2065
  }
2066
}
2067

    
2068
/**
2069
 * Test user token replacement in strings.
2070
 */
2071
class UserTokenReplaceTestCase extends DrupalWebTestCase {
2072
  public static function getInfo() {
2073
    return array(
2074
      'name' => 'User token replacement',
2075
      'description' => 'Generates text using placeholders for dummy content to check user token replacement.',
2076
      'group' => 'User',
2077
    );
2078
  }
2079

    
2080
  /**
2081
   * Creates a user, then tests the tokens generated from it.
2082
   */
2083
  function testUserTokenReplacement() {
2084
    global $language;
2085
    $url_options = array(
2086
      'absolute' => TRUE,
2087
      'language' => $language,
2088
    );
2089

    
2090
    // Create two users and log them in one after another.
2091
    $user1 = $this->drupalCreateUser(array());
2092
    $user2 = $this->drupalCreateUser(array());
2093
    $this->drupalLogin($user1);
2094
    $this->drupalLogout();
2095
    $this->drupalLogin($user2);
2096

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

    
2100
    // Generate and test sanitized tokens.
2101
    $tests = array();
2102
    $tests['[user:uid]'] = $account->uid;
2103
    $tests['[user:name]'] = check_plain(format_username($account));
2104
    $tests['[user:mail]'] = check_plain($account->mail);
2105
    $tests['[user:url]'] = url("user/$account->uid", $url_options);
2106
    $tests['[user:edit-url]'] = url("user/$account->uid/edit", $url_options);
2107
    $tests['[user:last-login]'] = format_date($account->login, 'medium', '', NULL, $language->language);
2108
    $tests['[user:last-login:short]'] = format_date($account->login, 'short', '', NULL, $language->language);
2109
    $tests['[user:created]'] = format_date($account->created, 'medium', '', NULL, $language->language);
2110
    $tests['[user:created:short]'] = format_date($account->created, 'short', '', NULL, $language->language);
2111
    $tests['[current-user:name]'] = check_plain(format_username($global_account));
2112

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

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

    
2121
    // Generate and test unsanitized tokens.
2122
    $tests['[user:name]'] = format_username($account);
2123
    $tests['[user:mail]'] = $account->mail;
2124
    $tests['[current-user:name]'] = format_username($global_account);
2125

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

    
2133
/**
2134
 * Test user search.
2135
 */
2136
class UserUserSearchTestCase extends DrupalWebTestCase {
2137
  public static function getInfo() {
2138
    return array(
2139
      'name' => 'User search',
2140
      'description' => 'Tests the user search page and verifies that sensitive information is hidden from unauthorized users.',
2141
      'group' => 'User',
2142
    );
2143
  }
2144

    
2145
  function testUserSearch() {
2146
    $user1 = $this->drupalCreateUser(array('access user profiles', 'search content', 'use advanced search'));
2147
    $this->drupalLogin($user1);
2148
    $keys = $user1->mail;
2149
    $edit = array('keys' => $keys);
2150
    $this->drupalPost('search/user/', $edit, t('Search'));
2151
    $this->assertNoText($keys);
2152
    $this->drupalLogout();
2153

    
2154
    $user2 = $this->drupalCreateUser(array('administer users', 'access user profiles', 'search content', 'use advanced search'));
2155
    $this->drupalLogin($user2);
2156
    $keys = $user2->mail;
2157
    $edit = array('keys' => $keys);
2158
    $this->drupalPost('search/user/', $edit, t('Search'));
2159
    $this->assertText($keys);
2160

    
2161
    // Create a blocked user.
2162
    $blocked_user = $this->drupalCreateUser();
2163
    $edit = array('status' => 0);
2164
    $blocked_user = user_save($blocked_user, $edit);
2165

    
2166
    // Verify that users with "administer users" permissions can see blocked
2167
    // accounts in search results.
2168
    $edit = array('keys' => $blocked_user->name);
2169
    $this->drupalPost('search/user/', $edit, t('Search'));
2170
    $this->assertText($blocked_user->name, 'Blocked users are listed on the user search results for users with the "administer users" permission.');
2171

    
2172
    // Verify that users without "administer users" permissions do not see
2173
    // blocked accounts in search results.
2174
    $this->drupalLogin($user1);
2175
    $edit = array('keys' => $blocked_user->name);
2176
    $this->drupalPost('search/user/', $edit, t('Search'));
2177
    $this->assertNoText($blocked_user->name, 'Blocked users are hidden from the user search results.');
2178

    
2179
    $this->drupalLogout();
2180
  }
2181
}
2182

    
2183
/**
2184
 * Test role assignment.
2185
 */
2186
class UserRolesAssignmentTestCase extends DrupalWebTestCase {
2187
  protected $admin_user;
2188

    
2189
  public static function getInfo() {
2190
    return array(
2191
      'name' => 'Role assignment',
2192
      'description' => 'Tests that users can be assigned and unassigned roles.',
2193
      'group' => 'User'
2194
    );
2195
  }
2196

    
2197
  function setUp() {
2198
    parent::setUp();
2199
    $this->admin_user = $this->drupalCreateUser(array('administer permissions', 'administer users'));
2200
    $this->drupalLogin($this->admin_user);
2201
  }
2202

    
2203
  /**
2204
   * Tests that a user can be assigned a role and that the role can be removed
2205
   * again.
2206
   */
2207
  function testAssignAndRemoveRole()  {
2208
    $rid = $this->drupalCreateRole(array('administer content types'));
2209
    $account = $this->drupalCreateUser();
2210

    
2211
    // Assign the role to the user.
2212
    $this->drupalPost('user/' . $account->uid . '/edit', array("roles[$rid]" => $rid), t('Save'));
2213
    $this->assertText(t('The changes have been saved.'));
2214
    $this->assertFieldChecked('edit-roles-' . $rid, 'Role is assigned.');
2215
    $this->userLoadAndCheckRoleAssigned($account, $rid);
2216

    
2217
    // Remove the role from the user.
2218
    $this->drupalPost('user/' . $account->uid . '/edit', array("roles[$rid]" => FALSE), t('Save'));
2219
    $this->assertText(t('The changes have been saved.'));
2220
    $this->assertNoFieldChecked('edit-roles-' . $rid, 'Role is removed from user.');
2221
    $this->userLoadAndCheckRoleAssigned($account, $rid, FALSE);
2222
  }
2223

    
2224
  /**
2225
   * Tests that when creating a user the role can be assigned. And that it can
2226
   * be removed again.
2227
   */
2228
  function testCreateUserWithRole() {
2229
    $rid = $this->drupalCreateRole(array('administer content types'));
2230
    // Create a new user and add the role at the same time.
2231
    $edit = array(
2232
      'name' => $this->randomName(),
2233
      'mail' => $this->randomName() . '@example.com',
2234
      'pass[pass1]' => $pass = $this->randomString(),
2235
      'pass[pass2]' => $pass,
2236
      "roles[$rid]" => $rid,
2237
    );
2238
    $this->drupalPost('admin/people/create', $edit, t('Create new account'));
2239
    $this->assertText(t('Created a new user account for !name.', array('!name' => $edit['name'])));
2240
    // Get the newly added user.
2241
    $account = user_load_by_name($edit['name']);
2242

    
2243
    $this->drupalGet('user/' . $account->uid . '/edit');
2244
    $this->assertFieldChecked('edit-roles-' . $rid, 'Role is assigned.');
2245
    $this->userLoadAndCheckRoleAssigned($account, $rid);
2246

    
2247
    // Remove the role again.
2248
    $this->drupalPost('user/' . $account->uid . '/edit', array("roles[$rid]" => FALSE), t('Save'));
2249
    $this->assertText(t('The changes have been saved.'));
2250
    $this->assertNoFieldChecked('edit-roles-' . $rid, 'Role is removed from user.');
2251
    $this->userLoadAndCheckRoleAssigned($account, $rid, FALSE);
2252
  }
2253

    
2254
  /**
2255
   * Check role on user object.
2256
   *
2257
   * @param object $account
2258
   *   The user account to check.
2259
   * @param string $rid
2260
   *   The role ID to search for.
2261
   * @param bool $is_assigned
2262
   *   (optional) Whether to assert that $rid exists (TRUE) or not (FALSE).
2263
   *   Defaults to TRUE.
2264
   */
2265
  private function userLoadAndCheckRoleAssigned($account, $rid, $is_assigned = TRUE) {
2266
    $account = user_load($account->uid, TRUE);
2267
    if ($is_assigned) {
2268
      $this->assertTrue(array_key_exists($rid, $account->roles), 'The role is present in the user object.');
2269
    }
2270
    else {
2271
      $this->assertFalse(array_key_exists($rid, $account->roles), 'The role is not present in the user object.');
2272
    }
2273
  }
2274
}
2275

    
2276

    
2277
/**
2278
 * Unit test for authmap assignment.
2279
 */
2280
class UserAuthmapAssignmentTestCase extends DrupalWebTestCase {
2281
  public static function getInfo() {
2282
    return array(
2283
      'name' => 'Authmap assignment',
2284
      'description' => 'Tests that users can be assigned and unassigned authmaps.',
2285
      'group' => 'User'
2286
    );
2287
  }
2288

    
2289
  /**
2290
   * Test authmap assignment and retrieval.
2291
   */
2292
  function testAuthmapAssignment()  {
2293
    $account = $this->drupalCreateUser();
2294

    
2295
    // Assign authmaps to the user.
2296
    $authmaps = array(
2297
      'authname_poll' => 'external username one',
2298
      'authname_book' => 'external username two',
2299
    );
2300
    user_set_authmaps($account, $authmaps);
2301

    
2302
    // Test for expected authmaps.
2303
    $expected_authmaps = array(
2304
      'external username one' => array(
2305
        'poll' => 'external username one',
2306
      ),
2307
      'external username two' => array(
2308
        'book' => 'external username two',
2309
      ),
2310
    );
2311
    foreach ($expected_authmaps as $authname => $expected_output) {
2312
      $this->assertIdentical(user_get_authmaps($authname), $expected_output, format_string('Authmap for authname %authname was set correctly.', array('%authname' => $authname)));
2313
    }
2314

    
2315
    // Remove authmap for module poll, add authmap for module blog.
2316
    $authmaps = array(
2317
      'authname_poll' => NULL,
2318
      'authname_blog' => 'external username three',
2319
    );
2320
    user_set_authmaps($account, $authmaps);
2321

    
2322
    // Assert that external username one does not have authmaps.
2323
    $remove_username = 'external username one';
2324
    unset($expected_authmaps[$remove_username]);
2325
    $this->assertFalse(user_get_authmaps($remove_username), format_string('Authmap for %authname was removed.', array('%authname' => $remove_username)));
2326

    
2327
    // Assert that a new authmap was created for external username three, and
2328
    // existing authmaps for external username two were unchanged.
2329
    $expected_authmaps['external username three'] = array('blog' => 'external username three');
2330
    foreach ($expected_authmaps as $authname => $expected_output) {
2331
      $this->assertIdentical(user_get_authmaps($authname), $expected_output, format_string('Authmap for authname %authname was set correctly.', array('%authname' => $authname)));
2332
    }
2333
  }
2334
}
2335

    
2336
/**
2337
 * Tests user_validate_current_pass on a custom form.
2338
 */
2339
class UserValidateCurrentPassCustomForm extends DrupalWebTestCase {
2340

    
2341
  public static function getInfo() {
2342
    return array(
2343
      'name' => 'User validate current pass custom form',
2344
      'description' => 'Test that user_validate_current_pass is usable on a custom form.',
2345
      'group' => 'User',
2346
    );
2347
  }
2348

    
2349
  /**
2350
   * User with permission to view content.
2351
   */
2352
  protected $accessUser;
2353

    
2354
  /**
2355
   * User permission to administer users.
2356
   */
2357
  protected $adminUser;
2358

    
2359
  function setUp() {
2360
    parent::setUp('user_form_test');
2361
    // Create two users
2362
    $this->accessUser = $this->drupalCreateUser(array('access content'));
2363
    $this->adminUser = $this->drupalCreateUser(array('administer users'));
2364
  }
2365

    
2366
  /**
2367
   * Tests that user_validate_current_pass can be reused on a custom form.
2368
   */
2369
  function testUserValidateCurrentPassCustomForm() {
2370
    $this->drupalLogin($this->adminUser);
2371

    
2372
    // Submit the custom form with the admin user using the access user's password.
2373
    $edit = array();
2374
    $edit['user_form_test_field'] = $this->accessUser->name;
2375
    $edit['current_pass'] = $this->accessUser->pass_raw;
2376
    $this->drupalPost('user_form_test_current_password/' . $this->accessUser->uid, $edit, t('Test'));
2377
    $this->assertText(t('The password has been validated and the form submitted successfully.'));
2378
  }
2379
}