user.test 45.3 KB
Newer Older
1
2
3
4
<?php
// $Id$

class UserRegistrationTestCase extends DrupalWebTestCase {
5
  public static function getInfo() {
6
7
    return array(
      'name' => t('User registration'),
8
      'description' => t('Registers a user, fails login, resets password, successfully logs in with the one time password, fails password change, changes password, logs out, successfully logs in with the new password, visits profile page.'),
9
10
11
12
13
14
15
16
17
18
19
20
21
22
      'group' => t('User')
    );
  }

  /**
   * Registers a user, fails login, resets password, successfully logs in with the one time password,
   * changes password, logs out, successfully logs in with the new password, visits profile page.
   *
   * Assumes that the profile module is disabled.
   */
  function testUserRegistration() {
    // Set user registration to "Visitors can create accounts and no administrator approval is required."
    variable_set('user_register', 1);

23
    // Enable user-configurable time zones, and set the default time zone to Brussels time.
24
    variable_set('configurable_timezones', 1);
25
    variable_set('date_default_timezone', 'Europe/Brussels');
26

27
28
    $edit = array();
    $edit['name'] = $name = $this->randomName();
29
    $edit['mail'] = $mail = $edit['name'] . '@example.com';
30
31
32
33
    $this->drupalPost('user/register', $edit, t('Create new account'));
    $this->assertText(t('Your password and further instructions have been sent to your e-mail address.'), t('User registered successfully.'));

    // Check database for created user.
34
35
    $users = user_load_multiple(array(), array('name' => $name, 'mail' => $mail));
    $user = reset($users);
36
37
38
39
40
41
42
43
    $this->assertTrue($user, t('User found in database.'));
    $this->assertTrue($user->uid > 0, t('User has valid user id.'));

    // Check user fields.
    $this->assertEqual($user->name, $name, t('Username matches.'));
    $this->assertEqual($user->mail, $mail, t('E-mail address matches.'));
    $this->assertEqual($user->theme, '', t('Correct theme field.'));
    $this->assertEqual($user->signature, '', t('Correct signature field.'));
44
    $this->assertTrue(($user->created > REQUEST_TIME - 20 ), t('Correct creation time.'));
45
    $this->assertEqual($user->status, variable_get('user_register', 1) == 1 ? 1 : 0, t('Correct status field.'));
46
    $this->assertEqual($user->timezone, variable_get('date_default_timezone'), t('Correct time zone field.'));
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
    $this->assertEqual($user->language, '', t('Correct language field.'));
    $this->assertEqual($user->picture, '', t('Correct picture field.'));
    $this->assertEqual($user->init, $mail, t('Correct init field.'));

    // Attempt to login with incorrect password.
    $edit = array();
    $edit['name'] = $name;
    $edit['pass'] = 'foo';
    $this->drupalPost('user', $edit, t('Log in'));
    $this->assertText(t('Sorry, unrecognized username or password. Have you forgotten your password?'), t('Invalid login attempt failed.'));

    // Login using password reset page.
    $url = user_pass_reset_url($user);
    sleep(1); // TODO Find better way.
    $this->drupalGet($url);
    $this->assertText(t('This login can be used only once.'), t('Login can be used only once.'));

    $this->drupalPost(NULL, NULL, t('Log in'));
    $this->assertText(t('You have just used your one-time login link. It is no longer necessary to use this link to login. Please change your password.'), t('This link is no longer valid.'));

67
68
69
70
71
72
73
74
    // Check password type validation
    $edit = array();
    $edit['pass[pass1]'] = '99999.0';
    $edit['pass[pass2]'] = '99999';
    $this->drupalPost(NULL, $edit, t('Save'));
    $this->assertText(t('The specified passwords do not match.'), t('Type mismatched passwords display an error message.'));    
    $this->assertNoText(t('The changes have been saved.'), t('Save user password with mismatched type in password confirm.'));
    
75
76
77
78
79
80
81
82
83
    // Change user password.
    $new_pass = user_password();
    $edit = array();
    $edit['pass[pass1]'] = $new_pass;
    $edit['pass[pass2]'] = $new_pass;
    $this->drupalPost(NULL, $edit, t('Save'));
    $this->assertText(t('The changes have been saved.'), t('Password changed to @password', array('@password' => $new_pass)));

    // Make sure password changes are present in database.
84
    require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
85

86
    $user = user_load($user->uid, TRUE);
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
    $this->assertTrue(user_check_password($new_pass, $user), t('Correct password in database.'));

    // Logout of user account.
    $this->clickLink(t('Log out'));
    $this->assertNoText($user->name, t('Logged out.'));

    // Login user.
    $edit = array();
    $edit['name'] = $user->name;
    $edit['pass'] = $new_pass;
    $this->drupalPost('user', $edit, t('Log in'));
    $this->assertText(t('Log out'), t('Logged in.'));

    $this->assertText($user->name, t('[logged in] Username found.'));
    $this->assertNoText(t('Sorry. Unrecognized username or password.'), t('[logged in] No message for unrecognized username or password.'));
    $this->assertNoText(t('User login'), t('[logged in] No user login form present.'));

    $this->drupalGet('user');
    $this->assertText($user->name, t('[user auth] Not login page.'));
    $this->assertText(t('View'), t('[user auth] Found view tab on the profile page.'));
    $this->assertText(t('Edit'), t('[user auth] Found edit tab on the profile page.'));
  }
}


class UserValidationTestCase extends DrupalWebTestCase {
113
  public static function getInfo() {
114
115
116
117
118
119
120
121
    return array(
      'name' => t('Username/e-mail validation'),
      'description' => t('Verify that username/email validity checks behave as designed.'),
      'group' => t('User')
    );
  }

  // Username validation.
122
123
124
125
126
127
128
129
130
131
  function testUsernames() {
    $test_cases = array( // '<username>' => array('<description>', 'assert<testName>'),
      'foo'                    => array('Valid username', 'assertNull'),
      'FOO'                    => array('Valid username', 'assertNull'),
      'Foo O\'Bar'             => array('Valid username', 'assertNull'),
      'foo@bar'                => array('Valid username', 'assertNull'),
      'foo@example.com'        => array('Valid username', 'assertNull'),
      'foo@-example.com'       => array('Valid username', 'assertNull'), // invalid domains are allowed in usernames
      'þòøÇߪř€'               => array('Valid username', 'assertNull'),
      'ᚠᛇᚻ᛫ᛒᛦᚦ'                => array('Valid UTF8 username', 'assertNull'), // runes
132
133
134
135
136
137
138
139
      ' foo'                   => array('Invalid username that starts with a space', 'assertNotNull'),
      'foo '                   => array('Invalid username that ends with a space', 'assertNotNull'),
      'foo  bar'               => array('Invalid username that contains 2 spaces \'&nbsp;&nbsp;\'', 'assertNotNull'),
      ''                       => array('Invalid empty username', 'assertNotNull'),
      'foo/'                   => array('Invalid username containing invalid chars', 'assertNotNull'),
      'foo' . chr(0) . 'bar'   => array('Invalid username containing chr(0)', 'assertNotNull'), // NULL
      'foo' . chr(13) . 'bar'  => array('Invalid username containing chr(13)', 'assertNotNull'), // CR
      str_repeat('x', USERNAME_MAX_LENGTH + 1) => array('Invalid excessively long username', 'assertNotNull'),
140
141
142
143
    );
    foreach ($test_cases as $name => $test_case) {
      list($description, $test) = $test_case;
      $result = user_validate_name($name);
144
      $this->$test($result, $description . ' (' . $name . ')');
145
    }
146
147
  }

148
149
150
151
152
153
154
155
156
157
  // Mail validation. More extensive tests can be found at common.test
  function testMailAddresses() {
    $test_cases = array( // '<username>' => array('<description>', 'assert<testName>'),
      ''                => array('Empty mail address', 'assertNotNull'),
      'foo'             => array('Invalid mail address', 'assertNotNull'),
      'foo@example.com' => array('Valid mail address', 'assertNull'),
    );
    foreach ($test_cases as $name => $test_case) {
      list($description, $test) = $test_case;
      $result = user_validate_mail($name);
158
      $this->$test($result, $description . ' (' . $name . ')');
159
    }
160
161
162
  }
}

163
class UserCancelTestCase extends DrupalWebTestCase {
164
  public static function getInfo() {
165
    return array(
166
167
168
      'name' => t('Cancel account'),
      'description' => t('Ensure that account cancellation methods work as expected.'),
      'group' => t('User'),
169
170
171
172
    );
  }

  /**
173
   * Attempt to cancel account without permission.
174
   */
175
176
177
178
179
180
181
  function testUserCancelWithoutPermission() {
    variable_set('user_cancel_method', 'user_cancel_reassign');

    // Create a user.
    $account = $this->drupalCreateUser(array());
    $this->drupalLogin($account);
    // Load real user object.
182
    $account = user_load($account->uid, TRUE);
183
184
185
186
187
188
189
190
191
192
193
194

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

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

    // Attempt bogus account cancellation request confirmation.
    $timestamp = $account->login;
    $this->drupalGet("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login));
    $this->assertResponse(403, t('Bogus cancelling request rejected.'));
195
196
    $account = user_load($account->uid);
    $this->assertTrue($account->status == 1, t('User account was not canceled.'));
197
198
199
200
201

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

203
204
205
206
207
208
209
210
211
212
  /**
   * Attempt invalid account cancellations.
   */
  function testUserCancelInvalid() {
    variable_set('user_cancel_method', 'user_cancel_reassign');

    // Create a user.
    $account = $this->drupalCreateUser(array('cancel account'));
    $this->drupalLogin($account);
    // Load real user object.
213
    $account = user_load($account->uid, TRUE);
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229

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

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

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

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

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

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

244
245
246
247
248
249
250
  /**
   * Disable account and keep all content.
   */
  function testUserBlock() {
    variable_set('user_cancel_method', 'user_cancel_block');

    // Create a user.
251
252
253
    $web_user = $this->drupalCreateUser(array('cancel account'));
    $this->drupalLogin($web_user);

254
    // Load real user object.
255
    $account = user_load($web_user->uid, TRUE);
256
257
258
259
260
261
262
263
264
265

    // Attempt to cancel account.
    $this->drupalGet('user/' . $account->uid . '/edit');
    $this->drupalPost(NULL, NULL, t('Cancel account'));
    $this->assertText(t('Are you sure you want to cancel your account?'), t('Confirmation form to cancel account displayed.'));
    $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.'), t('Informs that all content will be remain as is.'));
    $this->assertNoText(t('Select the method to cancel the account above.'), t('Does not allow user to select account cancellation method.'));

    // Confirm account cancellation.
    $timestamp = time();
266

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

    // Confirm account cancellation request.
    $this->drupalGet("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login));
272
273
    $account = user_load($account->uid, TRUE);
    $this->assertTrue($account->status == 0, t('User has been blocked.'));
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288

    // Confirm user is logged out.
    $this->assertNoText($account->name, t('Logged out.'));
  }

  /**
   * Disable account and unpublish all content.
   */
  function testUserBlockUnpublish() {
    variable_set('user_cancel_method', 'user_cancel_block_unpublish');

    // Create a user.
    $account = $this->drupalCreateUser(array('cancel account'));
    $this->drupalLogin($account);
    // Load real user object.
289
    $account = user_load($account->uid, TRUE);
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309

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

    // Attempt to cancel account.
    $this->drupalGet('user/' . $account->uid . '/edit');
    $this->drupalPost(NULL, NULL, t('Cancel account'));
    $this->assertText(t('Are you sure you want to cancel your account?'), t('Confirmation form to cancel account displayed.'));
    $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.'), t('Informs that all content will be unpublished.'));

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

    // Confirm account cancellation request.
    $this->drupalGet("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login));
310
311
    $account = user_load($account->uid, TRUE);
    $this->assertTrue($account->status == 0, t('User has been blocked.'));
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332

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

    // Confirm user is logged out.
    $this->assertNoText($account->name, t('Logged out.'));
  }

  /**
   * Delete account and anonymize all content.
   */
  function testUserAnonymize() {
    variable_set('user_cancel_method', 'user_cancel_reassign');

    // Create a user.
    $account = $this->drupalCreateUser(array('cancel account'));
    $this->drupalLogin($account);
    // Load real user object.
333
    $account = user_load($account->uid, TRUE);
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359

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

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

    // Attempt to cancel account.
    $this->drupalGet('user/' . $account->uid . '/edit');
    $this->drupalPost(NULL, NULL, t('Cancel account'));
    $this->assertText(t('Are you sure you want to cancel your account?'), t('Confirmation form to cancel account displayed.'));
    $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')))), t('Informs that all content will be attributed to anonymous account.'));

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

    // Confirm account cancellation request.
    $this->drupalGet("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login));
360
    $this->assertFalse(user_load($account->uid, TRUE), t('User is not found in the database.'));
361
362
363
364
365
366
367
368
369
370
371
372

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

    // Confirm that user is logged out.
    $this->assertNoText($account->name, t('Logged out.'));
  }
373

374
375
376
377
378
379
380
381
382
383
  /**
   * Delete account and remove all content.
   */
  function testUserDelete() {
    variable_set('user_cancel_method', 'user_cancel_delete');

    // Create a user.
    $account = $this->drupalCreateUser(array('cancel account'));
    $this->drupalLogin($account);
    // Load real user object.
384
    $account = user_load($account->uid, TRUE);
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415

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

    // Create comment.
    module_load_include('test', 'comment');
    $comment = CommentHelperCase::postComment($node, '', $this->randomName(32), TRUE, TRUE);
    $this->assertTrue(comment_load($comment->id), t('Comment found.'));

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

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

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

    // Confirm account cancellation request.
    $this->drupalGet("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login));
416
    $this->assertFalse(user_load($account->uid, TRUE), t('User is not found in the database.'));
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435

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

    // Confirm that user is logged out.
    $this->assertNoText($account->name, t('Logged out.'));
  }

  /**
   * Create an administrative user and delete another user.
   */
  function testUserCancelByAdmin() {
    variable_set('user_cancel_method', 'user_cancel_reassign');

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

437
    // Create administrative user.
438
439
440
    $admin_user = $this->drupalCreateUser(array('administer users'));
    $this->drupalLogin($admin_user);

441
442
443
444
445
    // Delete regular user.
    $this->drupalGet('user/' . $account->uid . '/edit');
    $this->drupalPost(NULL, NULL, t('Cancel account'));
    $this->assertRaw(t('Are you sure you want to cancel the account %name?', array('%name' => $account->name)), t('Confirmation form to cancel account displayed.'));
    $this->assertText(t('Select the method to cancel the account above.'), t('Allows to select account cancellation method.'));
446
447

    // Confirm deletion.
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
    $this->drupalPost(NULL, NULL, t('Cancel account'));
    $this->assertRaw(t('%name has been deleted.', array('%name' => $account->name)), t('User deleted.'));
    $this->assertFalse(user_load($account->uid), t('User is not found in the database.'));
  }

  /**
   * Create an administrative user and mass-delete other users.
   */
  function testMassUserCancelByAdmin() {
    variable_set('user_cancel_method', 'user_cancel_reassign');
    // Enable account cancellation notification.
    variable_set('user_mail_status_canceled_notify', TRUE);

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

    // Create some users.
    $users = array();
    for ($i = 0; $i < 3; $i++) {
      $account = $this->drupalCreateUser(array());
      $users[$account->uid] = $account;
    }

    // Cancel user accounts, including own one.
    $edit = array();
    $edit['operation'] = 'cancel';
    foreach ($users as $uid => $account) {
476
      $edit['accounts[' . $uid . ']'] = TRUE;
477
    }
478
    $edit['accounts[' . $admin_user->uid . ']'] = TRUE;
479
480
481
482
483
484
485
486
487
488
489
    $this->drupalPost('admin/user/user', $edit, t('Update'));
    $this->assertText(t('Are you sure you want to cancel these user accounts?'), t('Confirmation form to cancel accounts displayed.'));
    $this->assertText(t('When cancelling these accounts'), t('Allows to select account cancellation method.'));
    $this->assertText(t('Require e-mail confirmation to cancel account.'), t('Allows to send confirmation mail.'));
    $this->assertText(t('Notify user when account is canceled.'), t('Allows to send notification mail.'));

    // Confirm deletion.
    $this->drupalPost(NULL, NULL, t('Cancel accounts'));
    $status = TRUE;
    foreach ($users as $account) {
      $status = $status && (strpos($this->content, t('%name has been deleted.', array('%name' => $account->name))) !== FALSE);
490
      $status = $status && !user_load($account->uid, TRUE);
491
492
493
494
495
    }
    $this->assertTrue($status, t('Users deleted and not found in the database.'));

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

501
502
503
class UserPictureTestCase extends DrupalWebTestCase {
  protected $user;
  protected $_directory_test;
504

505
  public static function getInfo() {
506
507
508
509
510
511
    return array(
      'name' => t('Upload user picture'),
      'description' => t('Assure that dimension check, extension check and image scaling work as designed.'),
      'group' => t('User')
    );
  }
512

513
514
515
516
  function setUp() {
    parent::setUp();
    // Enable user pictures.
    variable_set('user_pictures', 1);
517

518
    $this->user = $this->drupalCreateUser();
519

520
521
522
    // Test if directories specified in settings exist in filesystem.
    $file_dir = file_directory_path();
    $file_check = file_check_directory($file_dir, FILE_CREATE_DIRECTORY, 'file_directory_path');
523

524
    $picture_dir = variable_get('user_picture_path', 'pictures');
525
    $picture_path = $file_dir . '/' .$picture_dir;
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553

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

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

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

  /**
   * Do the test:
   *  GD Toolkit is installed
   *  Picture has invalid dimension
   *
   * results: The image should be uploaded because ImageGDToolkit resizes the picture
   */
  function testWithGDinvalidDimension() {
    if ($this->_directory_test)
      if (image_get_toolkit()) {
        $this->drupalLogin($this->user);

        $image = current($this->drupalGetTestFiles('image'));
554
        $info = image_get_info($image->filepath);
555

556
        // Set new variables: invalid dimensions, valid filesize (0 = no limit).
557
558
        $test_dim = ($info['width'] - 10) . 'x' . ($info['height'] - 10);
        variable_set('user_picture_dimensions', $test_dim);
559
        variable_set('user_picture_file_size', 0);
560
561

        $pic_path = $this->saveUserPicture($image);
562
563
564
565
        // Check that the image was resized and is being displayed on the
        // user's profile page.
        $text = t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels.', array('%dimensions' => $test_dim));
        $this->assertRaw($text, t('Image was resized.'));
566
        $alt = t("@user's picture", array('@user' => $this->user->name));
567
        $this->assertRaw(theme('image', $pic_path, $alt, $alt, '', FALSE), t("Image is displayed in user's edit page"));
568

569
570
        // Check if file is located in proper directory.
        $this->assertTrue(is_file($pic_path), t("File is located in proper directory"));
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
      }
  }

  /**
   * Do the test:
   *  GD Toolkit is installed
   *  Picture has invalid size
   *
   * results: The image should be uploaded because ImageGDToolkit resizes the picture
   */
  function testWithGDinvalidSize() {
    if ($this->_directory_test)
      if (image_get_toolkit()) {

        $this->drupalLogin($this->user);

587
588
589
        // Images are sorted first by size then by name. We need an image
        // bigger than 1 KB so we'll grab the last one.
        $image = end($this->drupalGetTestFiles('image'));
590
        $info = image_get_info($image->filepath);
591

592
        // Set new variables: valid dimensions, invalid filesize.
593
        $test_dim = ($info['width'] + 10) . 'x' . ($info['height'] + 10);
594
        $test_size = 1;
595
596
597
        variable_set('user_picture_dimensions', $test_dim);
        variable_set('user_picture_file_size', $test_size);

598
        $pic_path = $this->saveUserPicture($image);
599

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

606
607
        // Check if file is not uploaded.
        $this->assertFalse(is_file($pic_path), t('File was not uploaded.'));
608
609
610
611
612
613
614
615
616
617
      }
  }

  /**
   * Do the test:
   *  GD Toolkit is not installed
   *  Picture has invalid size
   *
   * results: The image shouldn't be uploaded
   */
618
  function testWithoutGDinvalidDimension() {
619
620
621
622
623
624
    if ($this->_directory_test)
      if (!image_get_toolkit()) {

        $this->drupalLogin($this->user);

        $image = current($this->drupalGetTestFiles('image'));
625
        $info = image_get_info($image->filepath);
626

627
        // Set new variables: invalid dimensions, valid filesize (0 = no limit).
628
629
        $test_dim = ($info['width'] - 10) . 'x' . ($info['height'] - 10);
        variable_set('user_picture_dimensions', $test_dim);
630
        variable_set('user_picture_file_size', 0);
631
632
633

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

634
        // Test that the upload failed and that the correct reason was cited.
635
        $text = t('The specified file %filename could not be uploaded.', array('%filename' => $image->filename));
636
637
638
639
640
641
        $this->assertRaw($text, t('Upload failed.'));
        $text = t('The image is too large; the maximum dimensions are %dimensions pixels.', array('%dimensions' => $test_dim));
        $this->assertRaw($text, t('Checking response on invalid image (dimensions).'));

        // Check if file is not uploaded.
        $this->assertFalse(is_file($pic_path), t('File was not uploaded.'));
642
      }
643
  }
644
645
646
647
648
649
650
651

  /**
   * Do the test:
   *  GD Toolkit is not installed
   *  Picture has invalid size
   *
   * results: The image shouldn't be uploaded
   */
652
  function testWithoutGDinvalidSize() {
653
654
655
656
657
    if ($this->_directory_test)
      if (!image_get_toolkit()) {
        $this->drupalLogin($this->user);

        $image = current($this->drupalGetTestFiles('image'));
658
        $info = image_get_info($image->filepath);
659
660

        // Set new variables: valid dimensions, invalid filesize.
661
        $test_dim = ($info['width'] + 10) . 'x' . ($info['height'] + 10);
662
        $test_size = 1;
663
664
665
666
667
        variable_set('user_picture_dimensions', $test_dim);
        variable_set('user_picture_file_size', $test_size);

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

668
        // Test that the upload failed and that the correct reason was cited.
669
        $text = t('The specified file %filename could not be uploaded.', array('%filename' => $image->filename));
670
        $this->assertRaw($text, t('Upload failed.'));
671
        $text = t('The file is %filesize exceeding the maximum file size of %maxsize.', array('%filesize' => format_size(filesize($image->filepath)), '%maxsize' => format_size($test_size * 1024)));
672
673
674
675
        $this->assertRaw($text, t('File size cited as reason for failure.'));

        // Check if file is not uploaded.
        $this->assertFalse(is_file($pic_path), t('File was not uploaded.'));
676
677
678
679
680
681
682
683
684
685
686
687
      }
  }

  /**
   * Do the test:
   *  Picture is valid (proper size and dimension)
   *
   * results: The image should be uploaded
   */
  function testPictureIsValid() {
    if ($this->_directory_test) {
      $this->drupalLogin($this->user);
688

689
      $image = current($this->drupalGetTestFiles('image'));
690
      $info = image_get_info($image->filepath);
691

692
      // Set new variables: valid dimensions, valid filesize (0 = no limit).
693
694
      $test_dim = ($info['width'] + 10) . 'x' . ($info['height'] + 10);
      variable_set('user_picture_dimensions', $test_dim);
695
      variable_set('user_picture_file_size', 0);
696
697
698

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

699
700
      // Check if image is displayed in user's profile page.
      $this->drupalGet('user');
701
702
      $this->assertRaw($pic_path, t("Image is displayed in user's profile page"));

703
      // Check if file is located in proper directory.
704
705
706
      $this->assertTrue(is_file($pic_path), t('File is located in proper directory'));
    }
  }
707

708
  function saveUserPicture($image) {
709
    $edit = array('files[picture_upload]' => realpath($image->filepath));
710
    $this->drupalPost('user/' . $this->user->uid . '/edit', $edit, t('Save'));
711

712
    $img_info = image_get_info($image->filepath);
713
    $picture_dir = variable_get('user_picture_path', 'pictures');
714
    $pic_path = file_directory_path() . '/' . $picture_dir . '/picture-' . $this->user->uid . '.' . $img_info['extension'];
715
716
717
718
719

    return $pic_path;
  }
}

720
721
722
723
724

class UserPermissionsTestCase extends DrupalWebTestCase {
  protected $admin_user;
  protected $rid;

725
  public static function getInfo() {
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
    return array(
      'name' => t('Role permissions'),
      'description' => t('Verify that role permissions can be added and removed via the permissions page.'),
      'group' => t('User')
    );
  }

  function setUp() {
    parent::setUp();

    $this->admin_user = $this->drupalCreateUser(array('administer permissions', 'access user profiles'));

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

  /**
   * Change user permissions and check user_access().
   */
  function testUserPermissionChanges() {
    $this->drupalLogin($this->admin_user);
    $rid = $this->rid;
    $account = $this->admin_user;

    // Add a permission.
    $this->assertFalse(user_access('administer nodes', $account, TRUE), t('User does not have "administer nodes" permission.'));
    $edit = array();
    $edit[$rid . '[administer nodes]'] = TRUE;
    $this->drupalPost('admin/user/permissions', $edit, t('Save permissions'));
    $this->assertText(t('The changes have been saved.'), t('Successful save message displayed.'));
    $this->assertTrue(user_access('administer nodes', $account, TRUE), t('User now has "administer nodes" permission.'));

    // Remove a permission.
    $this->assertTrue(user_access('access user profiles', $account, TRUE), t('User has "access user profiles" permission.'));
    $edit = array();
    $edit[$rid . '[access user profiles]'] = FALSE;
    $this->drupalPost('admin/user/permissions', $edit, t('Save permissions'));
    $this->assertText(t('The changes have been saved.'), t('Successful save message displayed.'));
    $this->assertFalse(user_access('access user profiles', $account, TRUE), t('User no longer has "access user profiles" permission.'));
  }

}
770
771

class UserAdminTestCase extends DrupalWebTestCase {
772
  public static function getInfo() {
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
    return array(
      'name' => t('User admininstration'),
      'description' => t('Test user admininstration page functionality.'),
      'group' => t('User')
    );
  }

  /**
   * Registers a user and deletes it.
   */
  function testUserAdmin() {

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

    // Create admin user to delete registered user.
    $admin_user = $this->drupalCreateUser(array('administer users'));
    $this->drupalLogin($admin_user);
    $this->drupalGet('admin/user/user');
    $this->assertText($user_a->name, t('Found user A on admin users page'));
    $this->assertText($user_b->name, t('Found user B on admin users page'));
    $this->assertText($user_c->name, t('Found user C on admin users page'));
    $this->assertText($admin_user->name, t('Found Admin user on admin users page'));

798
    // Filter the users by permission 'administer taxonomy'.
799
800
801
802
803
804
805
806
807
808
809
    $edit = array();
    $edit['filter'] = 'permission';
    $edit['permission'] = 'administer taxonomy';
    $this->drupalPost('admin/user/user', $edit, t('Filter'));

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

    // Test blocking of a user.
810
    $account = user_load($user_b->uid);
811
812
813
    $this->assertEqual($account->status, 1, 'User B not blocked');
    $edit = array();
    $edit['operation'] = 'block';
814
    $edit['accounts[' . $account->uid . ']'] = TRUE;
815
    $this->drupalPost('admin/user/user', $edit, t('Update'));
816
    $account = user_load($user_b->uid, TRUE);
817
818
819
    $this->assertEqual($account->status, 0, 'User B blocked');
  }
}
820

821
822
823
824
/**
 * Tests for user-configurable time zones.
 */
class UserTimeZoneFunctionalTest extends DrupalWebTestCase {
825
  public static function getInfo() {
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
    return array(
      'name' => t('User time zones'),
      'description' => t('Set a user time zone and verify that dates are displayed in local time.'),
      'group' => t('User'),
    );
  }

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

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

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

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

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

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

881
882
883
884
/**
 * Test user autocompletion.
 */
class UserAutocompleteTestCase extends DrupalWebTestCase {
885
  public static function getInfo() {
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
    return array(
      'name' => t('User autocompletion'),
      'description' => t('Test user autocompletion functionality.'),
      'group' => t('User')
    );
  }

  function setUp() {
    parent::setUp();

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

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

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

    // Using first letter of the user's name, make sure the user's full name is in the results.
    $this->assertRaw($this->unprivileged_user->name, t('User name found in autocompletion results.'));
  }
}
920
921
922
923
924

/**
 * Test user blocks.
 */
class UserBlocksUnitTests extends DrupalWebTestCase {
925
  public static function getInfo() {
926
927
928
929
930
931
932
    return array(
      'name' => t('User blocks'),
      'description' => t('Test user blocks.'),
      'group' => t('User')
    );
  }

933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
  /**
   * Test the user login block.
   */
  function testUserLoginBlock() {
    // Create a user with some permission that anonymous users lack.
    $user = $this->drupalCreateUser(array('administer permissions'));

    // Log in using the block.
    $edit = array();
    $edit['name'] = $user->name;
    $edit['pass'] = $user->pass_raw;
    $this->drupalPost('admin/user/permissions', $edit, t('Log in'));
    $this->assertText(t('Log out'), t('Logged in.'));

    // Check that we are still on the same page.
    $this->assertPattern('!<title.*?' . t('Permissions') . '.*?</title>!', t('Still on the same page after login for access denied page'));

    // Now, log out and repeat with a non-403 page.
    $this->clickLink(t('Log out'));
    $this->drupalPost('filter/tips', $edit, t('Log in'));
    $this->assertText(t('Log out'), t('Logged in.'));
    $this->assertPattern('!<title.*?' . t('Compose tips') . '.*?</title>!', t('Still on the same page after login for allowed page'));
  }

957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
  /**
   * Test the Who's Online block.
   */
  function testWhosOnlineBlock() {
    // Generate users and make sure there are no current user sessions.
    $user1 = $this->drupalCreateUser(array());
    $user2 = $this->drupalCreateUser(array());
    $user3 = $this->drupalCreateUser(array());
    $this->assertEqual(db_query("SELECT COUNT(*) FROM {sessions}")->fetchField(), 0, t('Sessions table is empty.'));

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

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

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

    // Insert two anonymous user sessions.
    $this->insertSession();
    $this->insertSession();

    // Test block output.
983
    $block = user_block_view('online');
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
    $this->drupalSetContent($block['content']);
    $this->assertRaw(t('%members and %visitors', array('%members' => '2 users', '%visitors' => '2 guests')), t('Correct number of online users (2 users and 2 guests).'));
    $this->assertText($user1->name, t('Active user 1 found in online list.'));
    $this->assertText($user2->name, t('Active user 2 found in online list.'));
    $this->assertNoText($user3->name, t("Inactive user not found in online list."));
    $this->assertTrue(strpos($this->drupalGetContent(), $user1->name) > strpos($this->drupalGetContent(), $user2->name), t('Online users are ordered correctly.'));
  }

  /**
   * Insert a user session into the {sessions} table. This function is used
   * since we cannot log in more than one user at the same time in tests.
   */
  private function insertSession(array $fields = array()) {
    $fields += array(
      'uid' => 0,
      'sid' => md5(microtime()),
      'timestamp' => REQUEST_TIME,
    );
    db_insert('sessions')
      ->fields($fields)
      ->execute();
    $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, t('Session record inserted.'));
  }
}
1008
1009
1010
1011
1012
1013

/**
 * Test case to test user_save() behaviour.
 */
class UserSaveTestCase extends DrupalWebTestCase {

1014
  public static function getInfo() {
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
    return array(
      'name' => t('User save test'),
      'description' => t('Test user_save() for arbitrary new uid.'),
      'group' => t('User'),
    );
  }

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

    // Create the base user, based on drupalCreateUser().
    $user = array(
      'name' => $test_name,
      'uid' => $test_uid,
      'mail' => $test_name . '@example.com',
      'is_new' => TRUE,
      'pass' => user_password(),
      'status' => 1,
    );
    $user_by_return = user_save('', $user);
    $this->assertTrue($user_by_return, t('Loading user by return of user_save().'));

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

    $user_by_name = user_load_by_name($test_name);
    $this->assertTrue($user_by_name, t('Loading user by name.'));
  }
}