user.test.orig 110 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658
  1. <?php
  2. /**
  3. * @file
  4. * Tests for user.module.
  5. */
  6. class UserRegistrationTestCase extends DrupalWebTestCase {
  7. public static function getInfo() {
  8. return array(
  9. 'name' => 'User registration',
  10. 'description' => 'Test registration of user under different configurations.',
  11. 'group' => 'User'
  12. );
  13. }
  14. function setUp() {
  15. parent::setUp('field_test');
  16. }
  17. function testRegistrationWithEmailVerification() {
  18. // Require e-mail verification.
  19. variable_set('user_email_verification', TRUE);
  20. // Set registration to administrator only.
  21. variable_set('user_register', USER_REGISTER_ADMINISTRATORS_ONLY);
  22. $this->drupalGet('user/register');
  23. $this->assertResponse(403, 'Registration page is inaccessible when only administrators can create accounts.');
  24. // Allow registration by site visitors without administrator approval.
  25. variable_set('user_register', USER_REGISTER_VISITORS);
  26. $edit = array();
  27. $edit['name'] = $name = $this->randomName();
  28. $edit['mail'] = $mail = $edit['name'] . '@example.com';
  29. $this->drupalPost('user/register', $edit, t('Create new account'));
  30. $this->assertText(t('A welcome message with further instructions has been sent to your e-mail address.'), 'User registered successfully.');
  31. $accounts = user_load_multiple(array(), array('name' => $name, 'mail' => $mail));
  32. $new_user = reset($accounts);
  33. $this->assertTrue($new_user->status, 'New account is active after registration.');
  34. // Allow registration by site visitors, but require administrator approval.
  35. variable_set('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL);
  36. $edit = array();
  37. $edit['name'] = $name = $this->randomName();
  38. $edit['mail'] = $mail = $edit['name'] . '@example.com';
  39. $this->drupalPost('user/register', $edit, t('Create new account'));
  40. $accounts = user_load_multiple(array(), array('name' => $name, 'mail' => $mail));
  41. $new_user = reset($accounts);
  42. $this->assertFalse($new_user->status, 'New account is blocked until approved by an administrator.');
  43. }
  44. function testRegistrationWithoutEmailVerification() {
  45. // Don't require e-mail verification.
  46. variable_set('user_email_verification', FALSE);
  47. // Allow registration by site visitors without administrator approval.
  48. variable_set('user_register', USER_REGISTER_VISITORS);
  49. $edit = array();
  50. $edit['name'] = $name = $this->randomName();
  51. $edit['mail'] = $mail = $edit['name'] . '@example.com';
  52. // Try entering a mismatching password.
  53. $edit['pass[pass1]'] = '99999.0';
  54. $edit['pass[pass2]'] = '99999';
  55. $this->drupalPost('user/register', $edit, t('Create new account'));
  56. $this->assertText(t('The specified passwords do not match.'), 'Typing mismatched passwords displays an error message.');
  57. // Enter a correct password.
  58. $edit['pass[pass1]'] = $new_pass = $this->randomName();
  59. $edit['pass[pass2]'] = $new_pass;
  60. $this->drupalPost('user/register', $edit, t('Create new account'));
  61. $accounts = user_load_multiple(array(), array('name' => $name, 'mail' => $mail));
  62. $new_user = reset($accounts);
  63. $this->assertText(t('Registration successful. You are now logged in.'), 'Users are logged in after registering.');
  64. $this->drupalLogout();
  65. // Allow registration by site visitors, but require administrator approval.
  66. variable_set('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL);
  67. $edit = array();
  68. $edit['name'] = $name = $this->randomName();
  69. $edit['mail'] = $mail = $edit['name'] . '@example.com';
  70. $edit['pass[pass1]'] = $pass = $this->randomName();
  71. $edit['pass[pass2]'] = $pass;
  72. $this->drupalPost('user/register', $edit, t('Create new account'));
  73. $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');
  74. // Try to login before administrator approval.
  75. $auth = array(
  76. 'name' => $name,
  77. 'pass' => $pass,
  78. );
  79. $this->drupalPost('user/login', $auth, t('Log in'));
  80. $this->assertText(t('The username @name has not been activated or is blocked.', array('@name' => $name)), 'User cannot login yet.');
  81. // Activate the new account.
  82. $accounts = user_load_multiple(array(), array('name' => $name, 'mail' => $mail));
  83. $new_user = reset($accounts);
  84. $admin_user = $this->drupalCreateUser(array('administer users'));
  85. $this->drupalLogin($admin_user);
  86. $edit = array(
  87. 'status' => 1,
  88. );
  89. $this->drupalPost('user/' . $new_user->uid . '/edit', $edit, t('Save'));
  90. $this->drupalLogout();
  91. // Login after administrator approval.
  92. $this->drupalPost('user/login', $auth, t('Log in'));
  93. $this->assertText(t('Member for'), 'User can log in after administrator approval.');
  94. }
  95. function testRegistrationEmailDuplicates() {
  96. // Don't require e-mail verification.
  97. variable_set('user_email_verification', FALSE);
  98. // Allow registration by site visitors without administrator approval.
  99. variable_set('user_register', USER_REGISTER_VISITORS);
  100. // Set up a user to check for duplicates.
  101. $duplicate_user = $this->drupalCreateUser();
  102. $edit = array();
  103. $edit['name'] = $this->randomName();
  104. $edit['mail'] = $duplicate_user->mail;
  105. // Attempt to create a new account using an existing e-mail address.
  106. $this->drupalPost('user/register', $edit, t('Create new account'));
  107. $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');
  108. // Attempt to bypass duplicate email registration validation by adding spaces.
  109. $edit['mail'] = ' ' . $duplicate_user->mail . ' ';
  110. $this->drupalPost('user/register', $edit, t('Create new account'));
  111. $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');
  112. }
  113. function testRegistrationDefaultValues() {
  114. // Allow registration by site visitors without administrator approval.
  115. variable_set('user_register', USER_REGISTER_VISITORS);
  116. // Don't require e-mail verification.
  117. variable_set('user_email_verification', FALSE);
  118. // Set the default timezone to Brussels.
  119. variable_set('configurable_timezones', 1);
  120. variable_set('date_default_timezone', 'Europe/Brussels');
  121. // Check that the account information fieldset's options are not displayed
  122. // is a fieldset if there is not more than one fieldset in the form.
  123. $this->drupalGet('user/register');
  124. $this->assertNoRaw('<fieldset id="edit-account"><legend>Account information</legend>', 'Account settings fieldset was hidden.');
  125. $edit = array();
  126. $edit['name'] = $name = $this->randomName();
  127. $edit['mail'] = $mail = $edit['name'] . '@example.com';
  128. $edit['pass[pass1]'] = $new_pass = $this->randomName();
  129. $edit['pass[pass2]'] = $new_pass;
  130. $this->drupalPost(NULL, $edit, t('Create new account'));
  131. // Check user fields.
  132. $accounts = user_load_multiple(array(), array('name' => $name, 'mail' => $mail));
  133. $new_user = reset($accounts);
  134. $this->assertEqual($new_user->name, $name, 'Username matches.');
  135. $this->assertEqual($new_user->mail, $mail, 'E-mail address matches.');
  136. $this->assertEqual($new_user->theme, '', 'Correct theme field.');
  137. $this->assertEqual($new_user->signature, '', 'Correct signature field.');
  138. $this->assertTrue(($new_user->created > REQUEST_TIME - 20 ), 'Correct creation time.');
  139. $this->assertEqual($new_user->status, variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) == USER_REGISTER_VISITORS ? 1 : 0, 'Correct status field.');
  140. $this->assertEqual($new_user->timezone, variable_get('date_default_timezone'), 'Correct time zone field.');
  141. $this->assertEqual($new_user->language, '', 'Correct language field.');
  142. $this->assertEqual($new_user->picture, '', 'Correct picture field.');
  143. $this->assertEqual($new_user->init, $mail, 'Correct init field.');
  144. }
  145. /**
  146. * Tests Field API fields on user registration forms.
  147. */
  148. function testRegistrationWithUserFields() {
  149. // Create a field, and an instance on 'user' entity type.
  150. $field = array(
  151. 'type' => 'test_field',
  152. 'field_name' => 'test_user_field',
  153. 'cardinality' => 1,
  154. );
  155. field_create_field($field);
  156. $instance = array(
  157. 'field_name' => 'test_user_field',
  158. 'entity_type' => 'user',
  159. 'label' => 'Some user field',
  160. 'bundle' => 'user',
  161. 'required' => TRUE,
  162. 'settings' => array('user_register_form' => FALSE),
  163. );
  164. field_create_instance($instance);
  165. // Check that the field does not appear on the registration form.
  166. $this->drupalGet('user/register');
  167. $this->assertNoText($instance['label'], 'The field does not appear on user registration form');
  168. // Have the field appear on the registration form.
  169. $instance['settings']['user_register_form'] = TRUE;
  170. field_update_instance($instance);
  171. $this->drupalGet('user/register');
  172. $this->assertText($instance['label'], 'The field appears on user registration form');
  173. // Check that validation errors are correctly reported.
  174. $edit = array();
  175. $edit['name'] = $name = $this->randomName();
  176. $edit['mail'] = $mail = $edit['name'] . '@example.com';
  177. // Missing input in required field.
  178. $edit['test_user_field[und][0][value]'] = '';
  179. $this->drupalPost(NULL, $edit, t('Create new account'));
  180. $this->assertRaw(t('@name field is required.', array('@name' => $instance['label'])), 'Field validation error was correctly reported.');
  181. // Invalid input.
  182. $edit['test_user_field[und][0][value]'] = '-1';
  183. $this->drupalPost(NULL, $edit, t('Create new account'));
  184. $this->assertRaw(t('%name does not accept the value -1.', array('%name' => $instance['label'])), 'Field validation error was correctly reported.');
  185. // Submit with valid data.
  186. $value = rand(1, 255);
  187. $edit['test_user_field[und][0][value]'] = $value;
  188. $this->drupalPost(NULL, $edit, t('Create new account'));
  189. // Check user fields.
  190. $accounts = user_load_multiple(array(), array('name' => $name, 'mail' => $mail));
  191. $new_user = reset($accounts);
  192. $this->assertEqual($new_user->test_user_field[LANGUAGE_NONE][0]['value'], $value, 'The field value was correctly saved.');
  193. // Check that the 'add more' button works.
  194. $field['cardinality'] = FIELD_CARDINALITY_UNLIMITED;
  195. field_update_field($field);
  196. foreach (array('js', 'nojs') as $js) {
  197. $this->drupalGet('user/register');
  198. // Add two inputs.
  199. $value = rand(1, 255);
  200. $edit = array();
  201. $edit['test_user_field[und][0][value]'] = $value;
  202. if ($js == 'js') {
  203. $this->drupalPostAJAX(NULL, $edit, 'test_user_field_add_more');
  204. $this->drupalPostAJAX(NULL, $edit, 'test_user_field_add_more');
  205. }
  206. else {
  207. $this->drupalPost(NULL, $edit, t('Add another item'));
  208. $this->drupalPost(NULL, $edit, t('Add another item'));
  209. }
  210. // Submit with three values.
  211. $edit['test_user_field[und][1][value]'] = $value + 1;
  212. $edit['test_user_field[und][2][value]'] = $value + 2;
  213. $edit['name'] = $name = $this->randomName();
  214. $edit['mail'] = $mail = $edit['name'] . '@example.com';
  215. $this->drupalPost(NULL, $edit, t('Create new account'));
  216. // Check user fields.
  217. $accounts = user_load_multiple(array(), array('name' => $name, 'mail' => $mail));
  218. $new_user = reset($accounts);
  219. $this->assertEqual($new_user->test_user_field[LANGUAGE_NONE][0]['value'], $value, format_string('@js : The field value was correclty saved.', array('@js' => $js)));
  220. $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)));
  221. $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)));
  222. }
  223. }
  224. }
  225. class UserValidationTestCase extends DrupalWebTestCase {
  226. public static function getInfo() {
  227. return array(
  228. 'name' => 'Username/e-mail validation',
  229. 'description' => 'Verify that username/email validity checks behave as designed.',
  230. 'group' => 'User'
  231. );
  232. }
  233. // Username validation.
  234. function testUsernames() {
  235. $test_cases = array( // '<username>' => array('<description>', 'assert<testName>'),
  236. 'foo' => array('Valid username', 'assertNull'),
  237. 'FOO' => array('Valid username', 'assertNull'),
  238. 'Foo O\'Bar' => array('Valid username', 'assertNull'),
  239. 'foo@bar' => array('Valid username', 'assertNull'),
  240. 'foo@example.com' => array('Valid username', 'assertNull'),
  241. 'foo@-example.com' => array('Valid username', 'assertNull'), // invalid domains are allowed in usernames
  242. 'þòøÇߪř€' => array('Valid username', 'assertNull'),
  243. 'foo+bar' => array('Valid username', 'assertNull'), // '+' symbol is allowed
  244. 'ᚠᛇᚻ᛫ᛒᛦᚦ' => array('Valid UTF8 username', 'assertNull'), // runes
  245. ' foo' => array('Invalid username that starts with a space', 'assertNotNull'),
  246. 'foo ' => array('Invalid username that ends with a space', 'assertNotNull'),
  247. 'foo bar' => array('Invalid username that contains 2 spaces \'&nbsp;&nbsp;\'', 'assertNotNull'),
  248. '' => array('Invalid empty username', 'assertNotNull'),
  249. 'foo/' => array('Invalid username containing invalid chars', 'assertNotNull'),
  250. 'foo' . chr(0) . 'bar' => array('Invalid username containing chr(0)', 'assertNotNull'), // NULL
  251. 'foo' . chr(13) . 'bar' => array('Invalid username containing chr(13)', 'assertNotNull'), // CR
  252. str_repeat('x', USERNAME_MAX_LENGTH + 1) => array('Invalid excessively long username', 'assertNotNull'),
  253. );
  254. foreach ($test_cases as $name => $test_case) {
  255. list($description, $test) = $test_case;
  256. $result = user_validate_name($name);
  257. $this->$test($result, $description . ' (' . $name . ')');
  258. }
  259. }
  260. // Mail validation. More extensive tests can be found at common.test
  261. function testMailAddresses() {
  262. $test_cases = array( // '<username>' => array('<description>', 'assert<testName>'),
  263. '' => array('Empty mail address', 'assertNotNull'),
  264. 'foo' => array('Invalid mail address', 'assertNotNull'),
  265. 'foo@example.com' => array('Valid mail address', 'assertNull'),
  266. );
  267. foreach ($test_cases as $name => $test_case) {
  268. list($description, $test) = $test_case;
  269. $result = user_validate_mail($name);
  270. $this->$test($result, $description . ' (' . $name . ')');
  271. }
  272. }
  273. }
  274. /**
  275. * Functional tests for user logins, including rate limiting of login attempts.
  276. */
  277. class UserLoginTestCase extends DrupalWebTestCase {
  278. public static function getInfo() {
  279. return array(
  280. 'name' => 'User login',
  281. 'description' => 'Ensure that login works as expected.',
  282. 'group' => 'User',
  283. );
  284. }
  285. function setUp() {
  286. parent::setUp('user_session_test');
  287. }
  288. /**
  289. * Test the global login flood control.
  290. */
  291. function testGlobalLoginFloodControl() {
  292. // Set the global login limit.
  293. variable_set('user_failed_login_ip_limit', 10);
  294. // Set a high per-user limit out so that it is not relevant in the test.
  295. variable_set('user_failed_login_user_limit', 4000);
  296. $user1 = $this->drupalCreateUser(array());
  297. $incorrect_user1 = clone $user1;
  298. $incorrect_user1->pass_raw .= 'incorrect';
  299. // Try 2 failed logins.
  300. for ($i = 0; $i < 2; $i++) {
  301. $this->assertFailedLogin($incorrect_user1);
  302. }
  303. // A successful login will not reset the IP-based flood control count.
  304. $this->drupalLogin($user1);
  305. $this->drupalLogout();
  306. // Try 8 more failed logins, they should not trigger the flood control
  307. // mechanism.
  308. for ($i = 0; $i < 8; $i++) {
  309. $this->assertFailedLogin($incorrect_user1);
  310. }
  311. // The next login trial should result in an IP-based flood error message.
  312. $this->assertFailedLogin($incorrect_user1, 'ip');
  313. // A login with the correct password should also result in a flood error
  314. // message.
  315. $this->assertFailedLogin($user1, 'ip');
  316. }
  317. /**
  318. * Test the per-user login flood control.
  319. */
  320. function testPerUserLoginFloodControl() {
  321. // Set a high global limit out so that it is not relevant in the test.
  322. variable_set('user_failed_login_ip_limit', 4000);
  323. // Set the per-user login limit.
  324. variable_set('user_failed_login_user_limit', 3);
  325. $user1 = $this->drupalCreateUser(array());
  326. $incorrect_user1 = clone $user1;
  327. $incorrect_user1->pass_raw .= 'incorrect';
  328. $user2 = $this->drupalCreateUser(array());
  329. // Try 2 failed logins.
  330. for ($i = 0; $i < 2; $i++) {
  331. $this->assertFailedLogin($incorrect_user1);
  332. }
  333. // A successful login will reset the per-user flood control count.
  334. $this->drupalLogin($user1);
  335. $this->drupalLogout();
  336. // Try 3 failed logins for user 1, they will not trigger flood control.
  337. for ($i = 0; $i < 3; $i++) {
  338. $this->assertFailedLogin($incorrect_user1);
  339. }
  340. // Try one successful attempt for user 2, it should not trigger any
  341. // flood control.
  342. $this->drupalLogin($user2);
  343. $this->drupalLogout();
  344. // Try one more attempt for user 1, it should be rejected, even if the
  345. // correct password has been used.
  346. $this->assertFailedLogin($user1, 'user');
  347. }
  348. /**
  349. * Test that user password is re-hashed upon login after changing $count_log2.
  350. */
  351. function testPasswordRehashOnLogin() {
  352. // Load password hashing API.
  353. require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
  354. // Set initial $count_log2 to the default, DRUPAL_HASH_COUNT.
  355. variable_set('password_count_log2', DRUPAL_HASH_COUNT);
  356. // Create a new user and authenticate.
  357. $account = $this->drupalCreateUser(array());
  358. $password = $account->pass_raw;
  359. $this->drupalLogin($account);
  360. $this->drupalLogout();
  361. // Load the stored user. The password hash should reflect $count_log2.
  362. $account = user_load($account->uid);
  363. $this->assertIdentical(_password_get_count_log2($account->pass), DRUPAL_HASH_COUNT);
  364. // Change $count_log2 and log in again.
  365. variable_set('password_count_log2', DRUPAL_HASH_COUNT + 1);
  366. $account->pass_raw = $password;
  367. $this->drupalLogin($account);
  368. // Load the stored user, which should have a different password hash now.
  369. $account = user_load($account->uid, TRUE);
  370. $this->assertIdentical(_password_get_count_log2($account->pass), DRUPAL_HASH_COUNT + 1);
  371. }
  372. /**
  373. * Test logging in when an anon session already exists.
  374. */
  375. function testLoginWithAnonSession() {
  376. // Visit the callback to generate a session for this anon user.
  377. $this->drupalGet('user_session_test_anon_session');
  378. // Now login.
  379. $account = $this->drupalCreateUser(array());
  380. $this->drupalLogin($account);
  381. }
  382. /**
  383. * Make an unsuccessful login attempt.
  384. *
  385. * @param $account
  386. * A user object with name and pass_raw attributes for the login attempt.
  387. * @param $flood_trigger
  388. * Whether or not to expect that the flood control mechanism will be
  389. * triggered.
  390. */
  391. function assertFailedLogin($account, $flood_trigger = NULL) {
  392. $edit = array(
  393. 'name' => $account->name,
  394. 'pass' => $account->pass_raw,
  395. );
  396. $this->drupalPost('user', $edit, t('Log in'));
  397. $this->assertNoFieldByXPath("//input[@name='pass' and @value!='']", NULL, 'Password value attribute is blank.');
  398. if (isset($flood_trigger)) {
  399. if ($flood_trigger == 'user') {
  400. $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'))));
  401. }
  402. else {
  403. // No uid, so the limit is IP-based.
  404. $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'))));
  405. }
  406. }
  407. else {
  408. $this->assertText(t('Sorry, unrecognized username or password. Have you forgotten your password?'));
  409. }
  410. }
  411. }
  412. /**
  413. * Tests resetting a user password.
  414. */
  415. class UserPasswordResetTestCase extends DrupalWebTestCase {
  416. protected $profile = 'standard';
  417. public static function getInfo() {
  418. return array(
  419. 'name' => 'Reset password',
  420. 'description' => 'Ensure that password reset methods work as expected.',
  421. 'group' => 'User',
  422. );
  423. }
  424. /**
  425. * Retrieves password reset email and extracts the login link.
  426. */
  427. public function getResetURL() {
  428. // Assume the most recent email.
  429. $_emails = $this->drupalGetMails();
  430. $email = end($_emails);
  431. $urls = array();
  432. preg_match('#.+user/reset/.+#', $email['body'], $urls);
  433. return $urls[0];
  434. }
  435. /**
  436. * Tests password reset functionality.
  437. */
  438. function testUserPasswordReset() {
  439. // Create a user.
  440. $account = $this->drupalCreateUser();
  441. $this->drupalLogin($account);
  442. $this->drupalLogout();
  443. // Attempt to reset password.
  444. $edit = array('name' => $account->name);
  445. $this->drupalPost('user/password', $edit, t('E-mail new password'));
  446. // Confirm the password reset.
  447. $this->assertText(t('Further instructions have been sent to your e-mail address.'), 'Password reset instructions mailed message displayed.');
  448. // Create an image field to enable an Ajax request on the user profile page.
  449. $field = array(
  450. 'field_name' => 'field_avatar',
  451. 'type' => 'image',
  452. 'settings' => array(),
  453. 'cardinality' => 1,
  454. );
  455. field_create_field($field);
  456. $instance = array(
  457. 'field_name' => $field['field_name'],
  458. 'entity_type' => 'user',
  459. 'label' => 'Avatar',
  460. 'bundle' => 'user',
  461. 'required' => FALSE,
  462. 'settings' => array(),
  463. 'widget' => array(
  464. 'type' => 'image_image',
  465. 'settings' => array(),
  466. ),
  467. );
  468. field_create_instance($instance);
  469. $resetURL = $this->getResetURL();
  470. $this->drupalGet($resetURL);
  471. // Check successful login.
  472. $this->drupalPost(NULL, NULL, t('Log in'));
  473. // Make sure the Ajax request from uploading a file does not invalidate the
  474. // reset token.
  475. $image = current($this->drupalGetTestFiles('image'));
  476. $edit = array(
  477. 'files[field_avatar_und_0]' => drupal_realpath($image->uri),
  478. );
  479. $this->drupalPostAJAX(NULL, $edit, 'field_avatar_und_0_upload_button');
  480. // Change the forgotten password.
  481. $password = user_password();
  482. $edit = array('pass[pass1]' => $password, 'pass[pass2]' => $password);
  483. $this->drupalPost(NULL, $edit, t('Save'));
  484. $this->assertText(t('The changes have been saved.'), 'Forgotten password changed.');
  485. }
  486. /**
  487. * Test user password reset while logged in.
  488. */
  489. function testUserPasswordResetLoggedIn() {
  490. $account = $this->drupalCreateUser();
  491. $this->drupalLogin($account);
  492. // Make sure the test account has a valid password.
  493. user_save($account, array('pass' => user_password()));
  494. // Generate one time login link.
  495. $reset_url = user_pass_reset_url($account);
  496. $this->drupalGet($reset_url);
  497. $this->assertText('Reset password');
  498. $this->drupalPost(NULL, NULL, t('Log in'));
  499. $this->assertText('You have just used your one-time login link. It is no longer necessary to use this link to log in. Please change your password.');
  500. $pass = user_password();
  501. $edit = array(
  502. 'pass[pass1]' => $pass,
  503. 'pass[pass2]' => $pass,
  504. );
  505. $this->drupalPost(NULL, $edit, t('Save'));
  506. $this->assertText('The changes have been saved.');
  507. }
  508. /**
  509. * Attempts login using an expired password reset link.
  510. */
  511. function testUserPasswordResetExpired() {
  512. // Set password reset timeout variable to 43200 seconds = 12 hours.
  513. $timeout = 43200;
  514. variable_set('user_password_reset_timeout', $timeout);
  515. // Create a user.
  516. $account = $this->drupalCreateUser();
  517. $this->drupalLogin($account);
  518. // Load real user object.
  519. $account = user_load($account->uid, TRUE);
  520. $this->drupalLogout();
  521. // To attempt an expired password reset, create a password reset link as if
  522. // its request time was 60 seconds older than the allowed limit of timeout.
  523. $bogus_timestamp = REQUEST_TIME - variable_get('user_password_reset_timeout', 86400) - 60;
  524. $this->drupalGet("user/reset/$account->uid/$bogus_timestamp/" . user_pass_rehash($account->pass, $bogus_timestamp, $account->login, $account->uid));
  525. $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.');
  526. }
  527. /**
  528. * Prefill the text box on incorrect login via link to password reset page.
  529. */
  530. function testUserPasswordTextboxFilled() {
  531. $this->drupalGet('user/login');
  532. $edit = array(
  533. 'name' => $this->randomName(),
  534. 'pass' => $this->randomName(),
  535. );
  536. $this->drupalPost('user', $edit, t('Log in'));
  537. $this->assertRaw(t('Sorry, unrecognized username or password. <a href="@password">Have you forgotten your password?</a>',
  538. array('@password' => url('user/password', array('query' => array('name' => $edit['name']))))));
  539. unset($edit['pass']);
  540. $this->drupalGet('user/password', array('query' => array('name' => $edit['name'])));
  541. $this->assertFieldByName('name', $edit['name'], 'User name found.');
  542. }
  543. /**
  544. * Make sure that users cannot forge password reset URLs of other users.
  545. */
  546. function testResetImpersonation() {
  547. // Make sure user 1 has a valid password, so it does not interfere with the
  548. // test user accounts that are created below.
  549. $account = user_load(1);
  550. user_save($account, array('pass' => user_password()));
  551. // Create two identical user accounts except for the user name. They must
  552. // have the same empty password, so we can't use $this->drupalCreateUser().
  553. $edit = array();
  554. $edit['name'] = $this->randomName();
  555. $edit['mail'] = $edit['name'] . '@example.com';
  556. $edit['status'] = 1;
  557. $user1 = user_save(drupal_anonymous_user(), $edit);
  558. $edit['name'] = $this->randomName();
  559. $user2 = user_save(drupal_anonymous_user(), $edit);
  560. // The password reset URL must not be valid for the second user when only
  561. // the user ID is changed in the URL.
  562. $reset_url = user_pass_reset_url($user1);
  563. $attack_reset_url = str_replace("user/reset/$user1->uid", "user/reset/$user2->uid", $reset_url);
  564. $this->drupalGet($attack_reset_url);
  565. $this->assertNoText($user2->name, 'The invalid password reset page does not show the user name.');
  566. $this->assertUrl('user/password', array(), 'The user is redirected to the password reset request page.');
  567. $this->assertText('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.');
  568. // When legacy code calls user_pass_rehash() without providing the $uid
  569. // parameter, neither password reset URL should be valid since it is
  570. // impossible for the system to determine which user account the token was
  571. // intended for.
  572. $timestamp = REQUEST_TIME;
  573. // Pass an explicit NULL for the $uid parameter of user_pass_rehash()
  574. // rather than not passing it at all, to avoid triggering PHP warnings in
  575. // the test.
  576. $reset_url_token = user_pass_rehash($user1->pass, $timestamp, $user1->login, NULL);
  577. $reset_url = url("user/reset/$user1->uid/$timestamp/$reset_url_token", array('absolute' => TRUE));
  578. $this->drupalGet($reset_url);
  579. $this->assertNoText($user1->name, 'The invalid password reset page does not show the user name.');
  580. $this->assertUrl('user/password', array(), 'The user is redirected to the password reset request page.');
  581. $this->assertText('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.');
  582. $attack_reset_url = str_replace("user/reset/$user1->uid", "user/reset/$user2->uid", $reset_url);
  583. $this->drupalGet($attack_reset_url);
  584. $this->assertNoText($user2->name, 'The invalid password reset page does not show the user name.');
  585. $this->assertUrl('user/password', array(), 'The user is redirected to the password reset request page.');
  586. $this->assertText('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.');
  587. // To verify that user_pass_rehash() never returns a valid result in the
  588. // above situation (even if legacy code also called it to attempt to
  589. // validate the token, rather than just to generate the URL), check that a
  590. // second call with the same parameters produces a different result.
  591. $new_reset_url_token = user_pass_rehash($user1->pass, $timestamp, $user1->login, NULL);
  592. $this->assertNotEqual($reset_url_token, $new_reset_url_token);
  593. // However, when the duplicate account is removed, the password reset URL
  594. // should be valid.
  595. user_delete($user2->uid);
  596. $reset_url_token = user_pass_rehash($user1->pass, $timestamp, $user1->login, NULL);
  597. $reset_url = url("user/reset/$user1->uid/$timestamp/$reset_url_token", array('absolute' => TRUE));
  598. $this->drupalGet($reset_url);
  599. $this->assertText($user1->name, 'The valid password reset page shows the user name.');
  600. $this->assertUrl($reset_url, array(), 'The user remains on the password reset login page.');
  601. $this->assertNoText('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.');
  602. }
  603. }
  604. /**
  605. * Test cancelling a user.
  606. */
  607. class UserCancelTestCase extends DrupalWebTestCase {
  608. public static function getInfo() {
  609. return array(
  610. 'name' => 'Cancel account',
  611. 'description' => 'Ensure that account cancellation methods work as expected.',
  612. 'group' => 'User',
  613. );
  614. }
  615. function setUp() {
  616. parent::setUp('comment');
  617. }
  618. /**
  619. * Attempt to cancel account without permission.
  620. */
  621. function testUserCancelWithoutPermission() {
  622. variable_set('user_cancel_method', 'user_cancel_reassign');
  623. // Create a user.
  624. $account = $this->drupalCreateUser(array());
  625. $this->drupalLogin($account);
  626. // Load real user object.
  627. $account = user_load($account->uid, TRUE);
  628. // Create a node.
  629. $node = $this->drupalCreateNode(array('uid' => $account->uid));
  630. // Attempt to cancel account.
  631. $this->drupalGet('user/' . $account->uid . '/edit');
  632. $this->assertNoRaw(t('Cancel account'), 'No cancel account button displayed.');
  633. // Attempt bogus account cancellation request confirmation.
  634. $timestamp = $account->login;
  635. $this->drupalGet("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login, $account->uid));
  636. $this->assertResponse(403, 'Bogus cancelling request rejected.');
  637. $account = user_load($account->uid);
  638. $this->assertTrue($account->status == 1, 'User account was not canceled.');
  639. // Confirm user's content has not been altered.
  640. $test_node = node_load($node->nid, NULL, TRUE);
  641. $this->assertTrue(($test_node->uid == $account->uid && $test_node->status == 1), 'Node of the user has not been altered.');
  642. }
  643. /**
  644. * Tests that user account for uid 1 cannot be cancelled.
  645. *
  646. * This should never be possible, or the site owner would become unable to
  647. * administer the site.
  648. */
  649. function testUserCancelUid1() {
  650. // Update uid 1's name and password to we know it.
  651. $password = user_password();
  652. require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
  653. $account = array(
  654. 'name' => 'user1',
  655. 'pass' => user_hash_password(trim($password)),
  656. );
  657. // We cannot use user_save() here or the password would be hashed again.
  658. db_update('users')
  659. ->fields($account)
  660. ->condition('uid', 1)
  661. ->execute();
  662. // Reload and log in uid 1.
  663. $user1 = user_load(1, TRUE);
  664. $user1->pass_raw = $password;
  665. // Try to cancel uid 1's account with a different user.
  666. $this->admin_user = $this->drupalCreateUser(array('administer users'));
  667. $this->drupalLogin($this->admin_user);
  668. $edit = array(
  669. 'operation' => 'cancel',
  670. 'accounts[1]' => TRUE,
  671. );
  672. $this->drupalPost('admin/people', $edit, t('Update'));
  673. // Verify that uid 1's account was not cancelled.
  674. $user1 = user_load(1, TRUE);
  675. $this->assertEqual($user1->status, 1, 'User #1 still exists and is not blocked.');
  676. }
  677. /**
  678. * Attempt invalid account cancellations.
  679. */
  680. function testUserCancelInvalid() {
  681. variable_set('user_cancel_method', 'user_cancel_reassign');
  682. // Create a user.
  683. $account = $this->drupalCreateUser(array('cancel account'));
  684. $this->drupalLogin($account);
  685. // Load real user object.
  686. $account = user_load($account->uid, TRUE);
  687. // Create a node.
  688. $node = $this->drupalCreateNode(array('uid' => $account->uid));
  689. // Attempt to cancel account.
  690. $this->drupalPost('user/' . $account->uid . '/edit', NULL, t('Cancel account'));
  691. // Confirm account cancellation.
  692. $timestamp = time();
  693. $this->drupalPost(NULL, NULL, t('Cancel account'));
  694. $this->assertText(t('A confirmation request to cancel your account has been sent to your e-mail address.'), 'Account cancellation request mailed message displayed.');
  695. // Attempt bogus account cancellation request confirmation.
  696. $bogus_timestamp = $timestamp + 60;
  697. $this->drupalGet("user/$account->uid/cancel/confirm/$bogus_timestamp/" . user_pass_rehash($account->pass, $bogus_timestamp, $account->login, $account->uid));
  698. $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.');
  699. $account = user_load($account->uid);
  700. $this->assertTrue($account->status == 1, 'User account was not canceled.');
  701. // Attempt expired account cancellation request confirmation.
  702. $bogus_timestamp = $timestamp - 86400 - 60;
  703. $this->drupalGet("user/$account->uid/cancel/confirm/$bogus_timestamp/" . user_pass_rehash($account->pass, $bogus_timestamp, $account->login, $account->uid));
  704. $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.');
  705. $accounts = user_load_multiple(array($account->uid), array('status' => 1));
  706. $this->assertTrue(reset($accounts), 'User account was not canceled.');
  707. // Confirm user's content has not been altered.
  708. $test_node = node_load($node->nid, NULL, TRUE);
  709. $this->assertTrue(($test_node->uid == $account->uid && $test_node->status == 1), 'Node of the user has not been altered.');
  710. }
  711. /**
  712. * Disable account and keep all content.
  713. */
  714. function testUserBlock() {
  715. variable_set('user_cancel_method', 'user_cancel_block');
  716. // Create a user.
  717. $web_user = $this->drupalCreateUser(array('cancel account'));
  718. $this->drupalLogin($web_user);
  719. // Load real user object.
  720. $account = user_load($web_user->uid, TRUE);
  721. // Attempt to cancel account.
  722. $this->drupalGet('user/' . $account->uid . '/edit');
  723. $this->drupalPost(NULL, NULL, t('Cancel account'));
  724. $this->assertText(t('Are you sure you want to cancel your account?'), 'Confirmation form to cancel account displayed.');
  725. $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.');
  726. $this->assertNoText(t('Select the method to cancel the account above.'), 'Does not allow user to select account cancellation method.');
  727. // Confirm account cancellation.
  728. $timestamp = time();
  729. $this->drupalPost(NULL, NULL, t('Cancel account'));
  730. $this->assertText(t('A confirmation request to cancel your account has been sent to your e-mail address.'), 'Account cancellation request mailed message displayed.');
  731. // Confirm account cancellation request.
  732. $this->drupalGet("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login, $account->uid));
  733. $account = user_load($account->uid, TRUE);
  734. $this->assertTrue($account->status == 0, 'User has been blocked.');
  735. // Confirm that the confirmation message made it through to the end user.
  736. $this->assertRaw(t('%name has been disabled.', array('%name' => $account->name)), "Confirmation message displayed to user.");
  737. }
  738. /**
  739. * Disable account and unpublish all content.
  740. */
  741. function testUserBlockUnpublish() {
  742. variable_set('user_cancel_method', 'user_cancel_block_unpublish');
  743. // Create a user.
  744. $account = $this->drupalCreateUser(array('cancel account'));
  745. $this->drupalLogin($account);
  746. // Load real user object.
  747. $account = user_load($account->uid, TRUE);
  748. // Create a node with two revisions.
  749. $node = $this->drupalCreateNode(array('uid' => $account->uid));
  750. $settings = get_object_vars($node);
  751. $settings['revision'] = 1;
  752. $node = $this->drupalCreateNode($settings);
  753. // Attempt to cancel account.
  754. $this->drupalGet('user/' . $account->uid . '/edit');
  755. $this->drupalPost(NULL, NULL, t('Cancel account'));
  756. $this->assertText(t('Are you sure you want to cancel your account?'), 'Confirmation form to cancel account displayed.');
  757. $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.');
  758. // Confirm account cancellation.
  759. $timestamp = time();
  760. $this->drupalPost(NULL, NULL, t('Cancel account'));
  761. $this->assertText(t('A confirmation request to cancel your account has been sent to your e-mail address.'), 'Account cancellation request mailed message displayed.');
  762. // Confirm account cancellation request.
  763. $this->drupalGet("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login, $account->uid));
  764. $account = user_load($account->uid, TRUE);
  765. $this->assertTrue($account->status == 0, 'User has been blocked.');
  766. // Confirm user's content has been unpublished.
  767. $test_node = node_load($node->nid, NULL, TRUE);
  768. $this->assertTrue($test_node->status == 0, 'Node of the user has been unpublished.');
  769. $test_node = node_load($node->nid, $node->vid, TRUE);
  770. $this->assertTrue($test_node->status == 0, 'Node revision of the user has been unpublished.');
  771. // Confirm that the confirmation message made it through to the end user.
  772. $this->assertRaw(t('%name has been disabled.', array('%name' => $account->name)), "Confirmation message displayed to user.");
  773. }
  774. /**
  775. * Delete account and anonymize all content.
  776. */
  777. function testUserAnonymize() {
  778. variable_set('user_cancel_method', 'user_cancel_reassign');
  779. // Create a user.
  780. $account = $this->drupalCreateUser(array('cancel account'));
  781. $this->drupalLogin($account);
  782. // Load real user object.
  783. $account = user_load($account->uid, TRUE);
  784. // Create a simple node.
  785. $node = $this->drupalCreateNode(array('uid' => $account->uid));
  786. // Create a node with two revisions, the initial one belonging to the
  787. // cancelling user.
  788. $revision_node = $this->drupalCreateNode(array('uid' => $account->uid));
  789. $revision = $revision_node->vid;
  790. $settings = get_object_vars($revision_node);
  791. $settings['revision'] = 1;
  792. $settings['uid'] = 1; // Set new/current revision to someone else.
  793. $revision_node = $this->drupalCreateNode($settings);
  794. // Attempt to cancel account.
  795. $this->drupalGet('user/' . $account->uid . '/edit');
  796. $this->drupalPost(NULL, NULL, t('Cancel account'));
  797. $this->assertText(t('Are you sure you want to cancel your account?'), 'Confirmation form to cancel account displayed.');
  798. $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.');
  799. // Confirm account cancellation.
  800. $timestamp = time();
  801. $this->drupalPost(NULL, NULL, t('Cancel account'));
  802. $this->assertText(t('A confirmation request to cancel your account has been sent to your e-mail address.'), 'Account cancellation request mailed message displayed.');
  803. // Confirm account cancellation request.
  804. $this->drupalGet("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login, $account->uid));
  805. $this->assertFalse(user_load($account->uid, TRUE), 'User is not found in the database.');
  806. // Confirm that user's content has been attributed to anonymous user.
  807. $test_node = node_load($node->nid, NULL, TRUE);
  808. $this->assertTrue(($test_node->uid == 0 && $test_node->status == 1), 'Node of the user has been attributed to anonymous user.');
  809. $test_node = node_load($revision_node->nid, $revision, TRUE);
  810. $this->assertTrue(($test_node->revision_uid == 0 && $test_node->status == 1), 'Node revision of the user has been attributed to anonymous user.');
  811. $test_node = node_load($revision_node->nid, NULL, TRUE);
  812. $this->assertTrue(($test_node->uid != 0 && $test_node->status == 1), "Current revision of the user's node was not attributed to anonymous user.");
  813. // Confirm that the confirmation message made it through to the end user.
  814. $this->assertRaw(t('%name has been deleted.', array('%name' => $account->name)), "Confirmation message displayed to user.");
  815. }
  816. /**
  817. * Delete account and remove all content.
  818. */
  819. function testUserDelete() {
  820. variable_set('user_cancel_method', 'user_cancel_delete');
  821. // Create a user.
  822. $account = $this->drupalCreateUser(array('cancel account', 'post comments', 'skip comment approval'));
  823. $this->drupalLogin($account);
  824. // Load real user object.
  825. $account = user_load($account->uid, TRUE);
  826. // Create a simple node.
  827. $node = $this->drupalCreateNode(array('uid' => $account->uid));
  828. // Create comment.
  829. $langcode = LANGUAGE_NONE;
  830. $edit = array();
  831. $edit['subject'] = $this->randomName(8);
  832. $edit['comment_body[' . $langcode . '][0][value]'] = $this->randomName(16);
  833. $this->drupalPost('comment/reply/' . $node->nid, $edit, t('Preview'));
  834. $this->drupalPost(NULL, array(), t('Save'));
  835. $this->assertText(t('Your comment has been posted.'));
  836. $comments = comment_load_multiple(array(), array('subject' => $edit['subject']));
  837. $comment = reset($comments);
  838. $this->assertTrue($comment->cid, 'Comment found.');
  839. // Create a node with two revisions, the initial one belonging to the
  840. // cancelling user.
  841. $revision_node = $this->drupalCreateNode(array('uid' => $account->uid));
  842. $revision = $revision_node->vid;
  843. $settings = get_object_vars($revision_node);
  844. $settings['revision'] = 1;
  845. $settings['uid'] = 1; // Set new/current revision to someone else.
  846. $revision_node = $this->drupalCreateNode($settings);
  847. // Attempt to cancel account.
  848. $this->drupalGet('user/' . $account->uid . '/edit');
  849. $this->drupalPost(NULL, NULL, t('Cancel account'));
  850. $this->assertText(t('Are you sure you want to cancel your account?'), 'Confirmation form to cancel account displayed.');
  851. $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.');
  852. // Confirm account cancellation.
  853. $timestamp = time();
  854. $this->drupalPost(NULL, NULL, t('Cancel account'));
  855. $this->assertText(t('A confirmation request to cancel your account has been sent to your e-mail address.'), 'Account cancellation request mailed message displayed.');
  856. // Confirm account cancellation request.
  857. $this->drupalGet("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login, $account->uid));
  858. $this->assertFalse(user_load($account->uid, TRUE), 'User is not found in the database.');
  859. // Confirm that user's content has been deleted.
  860. $this->assertFalse(node_load($node->nid, NULL, TRUE), 'Node of the user has been deleted.');
  861. $this->assertFalse(node_load($node->nid, $revision, TRUE), 'Node revision of the user has been deleted.');
  862. $this->assertTrue(node_load($revision_node->nid, NULL, TRUE), "Current revision of the user's node was not deleted.");
  863. $this->assertFalse(comment_load($comment->cid), 'Comment of the user has been deleted.');
  864. // Confirm that the confirmation message made it through to the end user.
  865. $this->assertRaw(t('%name has been deleted.', array('%name' => $account->name)), "Confirmation message displayed to user.");
  866. }
  867. /**
  868. * Create an administrative user and delete another user.
  869. */
  870. function testUserCancelByAdmin() {
  871. variable_set('user_cancel_method', 'user_cancel_reassign');
  872. // Create a regular user.
  873. $account = $this->drupalCreateUser(array());
  874. // Create administrative user.
  875. $admin_user = $this->drupalCreateUser(array('administer users'));
  876. $this->drupalLogin($admin_user);
  877. // Delete regular user.
  878. $this->drupalGet('user/' . $account->uid . '/edit');
  879. $this->drupalPost(NULL, NULL, t('Cancel account'));
  880. $this->assertRaw(t('Are you sure you want to cancel the account %name?', array('%name' => $account->name)), 'Confirmation form to cancel account displayed.');
  881. $this->assertText(t('Select the method to cancel the account above.'), 'Allows to select account cancellation method.');
  882. // Confirm deletion.
  883. $this->drupalPost(NULL, NULL, t('Cancel account'));
  884. $this->assertRaw(t('%name has been deleted.', array('%name' => $account->name)), 'User deleted.');
  885. $this->assertFalse(user_load($account->uid), 'User is not found in the database.');
  886. }
  887. /**
  888. * Create an administrative user and mass-delete other users.
  889. */
  890. function testMassUserCancelByAdmin() {
  891. variable_set('user_cancel_method', 'user_cancel_reassign');
  892. // Enable account cancellation notification.
  893. variable_set('user_mail_status_canceled_notify', TRUE);
  894. // Create administrative user.
  895. $admin_user = $this->drupalCreateUser(array('administer users'));
  896. $this->drupalLogin($admin_user);
  897. // Create some users.
  898. $users = array();
  899. for ($i = 0; $i < 3; $i++) {
  900. $account = $this->drupalCreateUser(array());
  901. $users[$account->uid] = $account;
  902. }
  903. // Cancel user accounts, including own one.
  904. $edit = array();
  905. $edit['operation'] = 'cancel';
  906. foreach ($users as $uid => $account) {
  907. $edit['accounts[' . $uid . ']'] = TRUE;
  908. }
  909. $edit['accounts[' . $admin_user->uid . ']'] = TRUE;
  910. // Also try to cancel uid 1.
  911. $edit['accounts[1]'] = TRUE;
  912. $this->drupalPost('admin/people', $edit, t('Update'));
  913. $this->assertText(t('Are you sure you want to cancel these user accounts?'), 'Confirmation form to cancel accounts displayed.');
  914. $this->assertText(t('When cancelling these accounts'), 'Allows to select account cancellation method.');
  915. $this->assertText(t('Require e-mail confirmation to cancel account.'), 'Allows to send confirmation mail.');
  916. $this->assertText(t('Notify user when account is canceled.'), 'Allows to send notification mail.');
  917. // Confirm deletion.
  918. $this->drupalPost(NULL, NULL, t('Cancel accounts'));
  919. $status = TRUE;
  920. foreach ($users as $account) {
  921. $status = $status && (strpos($this->content, t('%name has been deleted.', array('%name' => $account->name))) !== FALSE);
  922. $status = $status && !user_load($account->uid, TRUE);
  923. }
  924. $this->assertTrue($status, 'Users deleted and not found in the database.');
  925. // Ensure that admin account was not cancelled.
  926. $this->assertText(t('A confirmation request to cancel your account has been sent to your e-mail address.'), 'Account cancellation request mailed message displayed.');
  927. $admin_user = user_load($admin_user->uid);
  928. $this->assertTrue($admin_user->status == 1, 'Administrative user is found in the database and enabled.');
  929. // Verify that uid 1's account was not cancelled.
  930. $user1 = user_load(1, TRUE);
  931. $this->assertEqual($user1->status, 1, 'User #1 still exists and is not blocked.');
  932. }
  933. }
  934. class UserPictureTestCase extends DrupalWebTestCase {
  935. protected $user;
  936. protected $_directory_test;
  937. public static function getInfo() {
  938. return array(
  939. 'name' => 'Upload user picture',
  940. 'description' => 'Assure that dimension check, extension check and image scaling work as designed.',
  941. 'group' => 'User'
  942. );
  943. }
  944. function setUp() {
  945. parent::setUp();
  946. // Enable user pictures.
  947. variable_set('user_pictures', 1);
  948. $this->user = $this->drupalCreateUser();
  949. // Test if directories specified in settings exist in filesystem.
  950. $file_dir = 'public://';
  951. $file_check = file_prepare_directory($file_dir, FILE_CREATE_DIRECTORY);
  952. // TODO: Test public and private methods?
  953. $picture_dir = variable_get('user_picture_path', 'pictures');
  954. $picture_path = $file_dir . $picture_dir;
  955. $pic_check = file_prepare_directory($picture_path, FILE_CREATE_DIRECTORY);
  956. $this->_directory_test = is_writable($picture_path);
  957. $this->assertTrue($this->_directory_test, "The directory $picture_path doesn't exist or is not writable. Further tests won't be made.");
  958. }
  959. function testNoPicture() {
  960. $this->drupalLogin($this->user);
  961. // Try to upload a file that is not an image for the user picture.
  962. $not_an_image = current($this->drupalGetTestFiles('html'));
  963. $this->saveUserPicture($not_an_image);
  964. $this->assertRaw(t('Only JPEG, PNG and GIF images are allowed.'), 'Non-image files are not accepted.');
  965. }
  966. /**
  967. * Do the test:
  968. * GD Toolkit is installed
  969. * Picture has invalid dimension
  970. *
  971. * results: The image should be uploaded because ImageGDToolkit resizes the picture
  972. */
  973. function testWithGDinvalidDimension() {
  974. if ($this->_directory_test && image_get_toolkit()) {
  975. $this->drupalLogin($this->user);
  976. $image = current($this->drupalGetTestFiles('image'));
  977. $info = image_get_info($image->uri);
  978. // Set new variables: invalid dimensions, valid filesize (0 = no limit).
  979. $test_dim = ($info['width'] - 10) . 'x' . ($info['height'] - 10);
  980. variable_set('user_picture_dimensions', $test_dim);
  981. variable_set('user_picture_file_size', 0);
  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. // Check if file is located in proper directory.
  991. $this->assertTrue(is_file($pic_path), "File is located in proper directory");
  992. }
  993. }
  994. /**
  995. * Do the test:
  996. * GD Toolkit is installed
  997. * Picture has invalid size
  998. *
  999. * results: The image should be uploaded because ImageGDToolkit resizes the picture
  1000. */
  1001. function testWithGDinvalidSize() {
  1002. if ($this->_directory_test && image_get_toolkit()) {
  1003. $this->drupalLogin($this->user);
  1004. // Images are sorted first by size then by name. We need an image
  1005. // bigger than 1 KB so we'll grab the last one.
  1006. $files = $this->drupalGetTestFiles('image');
  1007. $image = end($files);
  1008. $info = image_get_info($image->uri);
  1009. // Set new variables: valid dimensions, invalid filesize.
  1010. $test_dim = ($info['width'] + 10) . 'x' . ($info['height'] + 10);
  1011. $test_size = 1;
  1012. variable_set('user_picture_dimensions', $test_dim);
  1013. variable_set('user_picture_file_size', $test_size);
  1014. $pic_path = $this->saveUserPicture($image);
  1015. // Test that the upload failed and that the correct reason was cited.
  1016. $text = t('The specified file %filename could not be uploaded.', array('%filename' => $image->filename));
  1017. $this->assertRaw($text, 'Upload failed.');
  1018. $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)));
  1019. $this->assertRaw($text, 'File size cited as reason for failure.');
  1020. // Check if file is not uploaded.
  1021. $this->assertFalse(is_file($pic_path), 'File was not uploaded.');
  1022. }
  1023. }
  1024. /**
  1025. * Do the test:
  1026. * GD Toolkit is not installed
  1027. * Picture has invalid size
  1028. *
  1029. * results: The image shouldn't be uploaded
  1030. */
  1031. function testWithoutGDinvalidDimension() {
  1032. if ($this->_directory_test && !image_get_toolkit()) {
  1033. $this->drupalLogin($this->user);
  1034. $image = current($this->drupalGetTestFiles('image'));
  1035. $info = image_get_info($image->uri);
  1036. // Set new variables: invalid dimensions, valid filesize (0 = no limit).
  1037. $test_dim = ($info['width'] - 10) . 'x' . ($info['height'] - 10);
  1038. variable_set('user_picture_dimensions', $test_dim);
  1039. variable_set('user_picture_file_size', 0);
  1040. $pic_path = $this->saveUserPicture($image);
  1041. // Test that the upload failed and that the correct reason was cited.
  1042. $text = t('The specified file %filename could not be uploaded.', array('%filename' => $image->filename));
  1043. $this->assertRaw($text, 'Upload failed.');
  1044. $text = t('The image is too large; the maximum dimensions are %dimensions pixels.', array('%dimensions' => $test_dim));
  1045. $this->assertRaw($text, 'Checking response on invalid image (dimensions).');
  1046. // Check if file is not uploaded.
  1047. $this->assertFalse(is_file($pic_path), 'File was not uploaded.');
  1048. }
  1049. }
  1050. /**
  1051. * Do the test:
  1052. * GD Toolkit is not installed
  1053. * Picture has invalid size
  1054. *
  1055. * results: The image shouldn't be uploaded
  1056. */
  1057. function testWithoutGDinvalidSize() {
  1058. if ($this->_directory_test && !image_get_toolkit()) {
  1059. $this->drupalLogin($this->user);
  1060. $image = current($this->drupalGetTestFiles('image'));
  1061. $info = image_get_info($image->uri);
  1062. // Set new variables: valid dimensions, invalid filesize.
  1063. $test_dim = ($info['width'] + 10) . 'x' . ($info['height'] + 10);
  1064. $test_size = 1;
  1065. variable_set('user_picture_dimensions', $test_dim);
  1066. variable_set('user_picture_file_size', $test_size);
  1067. $pic_path = $this->saveUserPicture($image);
  1068. // Test that the upload failed and that the correct reason was cited.
  1069. $text = t('The specified file %filename could not be uploaded.', array('%filename' => $image->filename));
  1070. $this->assertRaw($text, 'Upload failed.');
  1071. $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)));
  1072. $this->assertRaw($text, 'File size cited as reason for failure.');
  1073. // Check if file is not uploaded.
  1074. $this->assertFalse(is_file($pic_path), 'File was not uploaded.');
  1075. }
  1076. }
  1077. /**
  1078. * Do the test:
  1079. * Picture is valid (proper size and dimension)
  1080. *
  1081. * results: The image should be uploaded
  1082. */
  1083. function testPictureIsValid() {
  1084. if ($this->_directory_test) {
  1085. $this->drupalLogin($this->user);
  1086. $image = current($this->drupalGetTestFiles('image'));
  1087. $info = image_get_info($image->uri);
  1088. // Set new variables: valid dimensions, valid filesize (0 = no limit).
  1089. $test_dim = ($info['width'] + 10) . 'x' . ($info['height'] + 10);
  1090. variable_set('user_picture_dimensions', $test_dim);
  1091. variable_set('user_picture_file_size', 0);
  1092. $pic_path = $this->saveUserPicture($image);
  1093. // Check if image is displayed in user's profile page.
  1094. $this->drupalGet('user');
  1095. $this->assertRaw(file_uri_target($pic_path), "Image is displayed in user's profile page");
  1096. // Check if file is located in proper directory.
  1097. $this->assertTrue(is_file($pic_path), 'File is located in proper directory');
  1098. // Set new picture dimensions.
  1099. $test_dim = ($info['width'] + 5) . 'x' . ($info['height'] + 5);
  1100. variable_set('user_picture_dimensions', $test_dim);
  1101. $pic_path2 = $this->saveUserPicture($image);
  1102. $this->assertNotEqual($pic_path, $pic_path2, 'Filename of second picture is different.');
  1103. // Check if user picture has a valid file ID after saving the user.
  1104. $account = user_load($this->user->uid, TRUE);
  1105. $this->assertTrue(is_object($account->picture), 'User picture object is valid after user load.');
  1106. $this->assertNotNull($account->picture->fid, 'User picture object has a FID after user load.');
  1107. $this->assertTrue(is_file($account->picture->uri), 'File is located in proper directory after user load.');
  1108. user_save($account);
  1109. // Verify that the user save does not destroy the user picture object.
  1110. $this->assertTrue(is_object($account->picture), 'User picture object is valid after user save.');
  1111. $this->assertNotNull($account->picture->fid, 'User picture object has a FID after user save.');
  1112. $this->assertTrue(is_file($account->picture->uri), 'File is located in proper directory after user save.');
  1113. }
  1114. }
  1115. /**
  1116. * Test HTTP schema working with user pictures.
  1117. */
  1118. function testExternalPicture() {
  1119. $this->drupalLogin($this->user);
  1120. // Set the default picture to an URI with a HTTP schema.
  1121. $images = $this->drupalGetTestFiles('image');
  1122. $image = $images[0];
  1123. $pic_path = file_create_url($image->uri);
  1124. variable_set('user_picture_default', $pic_path);
  1125. // Check if image is displayed in user's profile page.
  1126. $this->drupalGet('user');
  1127. // Get the user picture image via xpath.
  1128. $elements = $this->xpath('//div[@class="user-picture"]/img');
  1129. $this->assertEqual(count($elements), 1, "There is exactly one user picture on the user's profile page");
  1130. $this->assertEqual($pic_path, (string) $elements[0]['src'], "User picture source is correct.");
  1131. }
  1132. /**
  1133. * Tests deletion of user pictures.
  1134. */
  1135. function testDeletePicture() {
  1136. $this->drupalLogin($this->user);
  1137. $image = current($this->drupalGetTestFiles('image'));
  1138. $info = image_get_info($image->uri);
  1139. // Set new variables: valid dimensions, valid filesize (0 = no limit).
  1140. $test_dim = ($info['width'] + 10) . 'x' . ($info['height'] + 10);
  1141. variable_set('user_picture_dimensions', $test_dim);
  1142. variable_set('user_picture_file_size', 0);
  1143. // Save a new picture.
  1144. $edit = array('files[picture_upload]' => drupal_realpath($image->uri));
  1145. $this->drupalPost('user/' . $this->user->uid . '/edit', $edit, t('Save'));
  1146. // Load actual user data from database.
  1147. $account = user_load($this->user->uid, TRUE);
  1148. $pic_path = isset($account->picture) ? $account->picture->uri : NULL;
  1149. // Check if image is displayed in user's profile page.
  1150. $this->drupalGet('user');
  1151. $this->assertRaw(file_uri_target($pic_path), "Image is displayed in user's profile page");
  1152. // Check if file is located in proper directory.
  1153. $this->assertTrue(is_file($pic_path), 'File is located in proper directory');
  1154. $edit = array('picture_delete' => 1);
  1155. $this->drupalPost('user/' . $this->user->uid . '/edit', $edit, t('Save'));
  1156. // Load actual user data from database.
  1157. $account1 = user_load($this->user->uid, TRUE);
  1158. $this->assertNull($account1->picture, 'User object has no picture');
  1159. $file = file_load($account->picture->fid);
  1160. $this->assertFalse($file, 'File is removed from database');
  1161. // Clear out PHP's file stat cache so we see the current value.
  1162. clearstatcache();
  1163. $this->assertFalse(is_file($pic_path), 'File is removed from file system');
  1164. }
  1165. function saveUserPicture($image) {
  1166. $edit = array('files[picture_upload]' => drupal_realpath($image->uri));
  1167. $this->drupalPost('user/' . $this->user->uid . '/edit', $edit, t('Save'));
  1168. // Load actual user data from database.
  1169. $account = user_load($this->user->uid, TRUE);
  1170. return isset($account->picture) ? $account->picture->uri : NULL;
  1171. }
  1172. /**
  1173. * Tests the admin form validates user picture settings.
  1174. */
  1175. function testUserPictureAdminFormValidation() {
  1176. $this->drupalLogin($this->drupalCreateUser(array('administer users')));
  1177. // The default values are valid.
  1178. $this->drupalPost('admin/config/people/accounts', array(), t('Save configuration'));
  1179. $this->assertText(t('The configuration options have been saved.'), 'The default values are valid.');
  1180. // The form does not save with an invalid file size.
  1181. $edit = array(
  1182. 'user_picture_file_size' => $this->randomName(),
  1183. );
  1184. $this->drupalPost('admin/config/people/accounts', $edit, t('Save configuration'));
  1185. $this->assertNoText(t('The configuration options have been saved.'), 'The form does not save with an invalid file size.');
  1186. }
  1187. }
  1188. class UserPermissionsTestCase extends DrupalWebTestCase {
  1189. protected $admin_user;
  1190. protected $rid;
  1191. public static function getInfo() {
  1192. return array(
  1193. 'name' => 'Role permissions',
  1194. 'description' => 'Verify that role permissions can be added and removed via the permissions page.',
  1195. 'group' => 'User'
  1196. );
  1197. }
  1198. function setUp() {
  1199. parent::setUp();
  1200. $this->admin_user = $this->drupalCreateUser(array('administer permissions', 'access user profiles', 'administer site configuration', 'administer modules', 'administer users'));
  1201. // Find the new role ID - it must be the maximum.
  1202. $all_rids = array_keys($this->admin_user->roles);
  1203. sort($all_rids);
  1204. $this->rid = array_pop($all_rids);
  1205. }
  1206. /**
  1207. * Change user permissions and check user_access().
  1208. */
  1209. function testUserPermissionChanges() {
  1210. $this->drupalLogin($this->admin_user);
  1211. $rid = $this->rid;
  1212. $account = $this->admin_user;
  1213. // Add a permission.
  1214. $this->assertFalse(user_access('administer nodes', $account), 'User does not have "administer nodes" permission.');
  1215. $edit = array();
  1216. $edit[$rid . '[administer nodes]'] = TRUE;
  1217. $this->drupalPost('admin/people/permissions', $edit, t('Save permissions'));
  1218. $this->assertText(t('The changes have been saved.'), 'Successful save message displayed.');
  1219. drupal_static_reset('user_access');
  1220. drupal_static_reset('user_role_permissions');
  1221. $this->assertTrue(user_access('administer nodes', $account), 'User now has "administer nodes" permission.');
  1222. // Remove a permission.
  1223. $this->assertTrue(user_access('access user profiles', $account), 'User has "access user profiles" permission.');
  1224. $edit = array();
  1225. $edit[$rid . '[access user profiles]'] = FALSE;
  1226. $this->drupalPost('admin/people/permissions', $edit, t('Save permissions'));
  1227. $this->assertText(t('The changes have been saved.'), 'Successful save message displayed.');
  1228. drupal_static_reset('user_access');
  1229. drupal_static_reset('user_role_permissions');
  1230. $this->assertFalse(user_access('access user profiles', $account), 'User no longer has "access user profiles" permission.');
  1231. }
  1232. /**
  1233. * Test assigning of permissions for the administrator role.
  1234. */
  1235. function testAdministratorRole() {
  1236. $this->drupalLogin($this->admin_user);
  1237. $this->drupalGet('admin/config/people/accounts');
  1238. // Set the user's role to be the administrator role.
  1239. $edit = array();
  1240. $edit['user_admin_role'] = $this->rid;
  1241. $this->drupalPost('admin/config/people/accounts', $edit, t('Save configuration'));
  1242. // Enable aggregator module and ensure the 'administer news feeds'
  1243. // permission is assigned by default.
  1244. $edit = array();
  1245. $edit['modules[Core][aggregator][enable]'] = TRUE;
  1246. $this->drupalPost('admin/modules', $edit, t('Save configuration'));
  1247. $this->assertTrue(user_access('administer news feeds', $this->admin_user), 'The permission was automatically assigned to the administrator role');
  1248. }
  1249. /**
  1250. * Verify proper permission changes by user_role_change_permissions().
  1251. */
  1252. function testUserRoleChangePermissions() {
  1253. $rid = $this->rid;
  1254. $account = $this->admin_user;
  1255. // Verify current permissions.
  1256. $this->assertFalse(user_access('administer nodes', $account), 'User does not have "administer nodes" permission.');
  1257. $this->assertTrue(user_access('access user profiles', $account), 'User has "access user profiles" permission.');
  1258. $this->assertTrue(user_access('administer site configuration', $account), 'User has "administer site configuration" permission.');
  1259. // Change permissions.
  1260. $permissions = array(
  1261. 'administer nodes' => 1,
  1262. 'access user profiles' => 0,
  1263. );
  1264. user_role_change_permissions($rid, $permissions);
  1265. // Verify proper permission changes.
  1266. $this->assertTrue(user_access('administer nodes', $account), 'User now has "administer nodes" permission.');
  1267. $this->assertFalse(user_access('access user profiles', $account), 'User no longer has "access user profiles" permission.');
  1268. $this->assertTrue(user_access('administer site configuration', $account), 'User still has "administer site configuration" permission.');
  1269. }
  1270. }
  1271. class UserAdminTestCase extends DrupalWebTestCase {
  1272. public static function getInfo() {
  1273. return array(
  1274. 'name' => 'User administration',
  1275. 'description' => 'Test user administration page functionality.',
  1276. 'group' => 'User'
  1277. );
  1278. }
  1279. /**
  1280. * Registers a user and deletes it.
  1281. */
  1282. function testUserAdmin() {
  1283. $user_a = $this->drupalCreateUser(array());
  1284. $user_b = $this->drupalCreateUser(array('administer taxonomy'));
  1285. $user_c = $this->drupalCreateUser(array('administer taxonomy'));
  1286. // Create admin user to delete registered user.
  1287. $admin_user = $this->drupalCreateUser(array('administer users'));
  1288. $this->drupalLogin($admin_user);
  1289. $this->drupalGet('admin/people');
  1290. $this->assertText($user_a->name, 'Found user A on admin users page');
  1291. $this->assertText($user_b->name, 'Found user B on admin users page');
  1292. $this->assertText($user_c->name, 'Found user C on admin users page');
  1293. $this->assertText($admin_user->name, 'Found Admin user on admin users page');
  1294. // Test for existence of edit link in table.
  1295. $link = l(t('edit'), "user/$user_a->uid/edit", array('query' => array('destination' => 'admin/people')));
  1296. $this->assertRaw($link, 'Found user A edit link on admin users page');
  1297. // Filter the users by permission 'administer taxonomy'.
  1298. $edit = array();
  1299. $edit['permission'] = 'administer taxonomy';
  1300. $this->drupalPost('admin/people', $edit, t('Filter'));
  1301. // Check if the correct users show up.
  1302. $this->assertNoText($user_a->name, 'User A not on filtered by perm admin users page');
  1303. $this->assertText($user_b->name, 'Found user B on filtered by perm admin users page');
  1304. $this->assertText($user_c->name, 'Found user C on filtered by perm admin users page');
  1305. // Filter the users by role. Grab the system-generated role name for User C.
  1306. $edit['role'] = max(array_flip($user_c->roles));
  1307. $this->drupalPost('admin/people', $edit, t('Refine'));
  1308. // Check if the correct users show up when filtered by role.
  1309. $this->assertNoText($user_a->name, 'User A not on filtered by role on admin users page');
  1310. $this->assertNoText($user_b->name, 'User B not on filtered by role on admin users page');
  1311. $this->assertText($user_c->name, 'User C on filtered by role on admin users page');
  1312. // Test blocking of a user.
  1313. $account = user_load($user_c->uid);
  1314. $this->assertEqual($account->status, 1, 'User C not blocked');
  1315. $edit = array();
  1316. $edit['operation'] = 'block';
  1317. $edit['accounts[' . $account->uid . ']'] = TRUE;
  1318. $this->drupalPost('admin/people', $edit, t('Update'));
  1319. $account = user_load($user_c->uid, TRUE);
  1320. $this->assertEqual($account->status, 0, 'User C blocked');
  1321. // Test unblocking of a user from /admin/people page and sending of activation mail
  1322. $editunblock = array();
  1323. $editunblock['operation'] = 'unblock';
  1324. $editunblock['accounts[' . $account->uid . ']'] = TRUE;
  1325. $this->drupalPost('admin/people', $editunblock, t('Update'));
  1326. $account = user_load($user_c->uid, TRUE);
  1327. $this->assertEqual($account->status, 1, 'User C unblocked');
  1328. $this->assertMail("to", $account->mail, "Activation mail sent to user C");
  1329. // Test blocking and unblocking another user from /user/[uid]/edit form and sending of activation mail
  1330. $user_d = $this->drupalCreateUser(array());
  1331. $account1 = user_load($user_d->uid, TRUE);
  1332. $this->drupalPost('user/' . $account1->uid . '/edit', array('status' => 0), t('Save'));
  1333. $account1 = user_load($user_d->uid, TRUE);
  1334. $this->assertEqual($account1->status, 0, 'User D blocked');
  1335. $this->drupalPost('user/' . $account1->uid . '/edit', array('status' => TRUE), t('Save'));
  1336. $account1 = user_load($user_d->uid, TRUE);
  1337. $this->assertEqual($account1->status, 1, 'User D unblocked');
  1338. $this->assertMail("to", $account1->mail, "Activation mail sent to user D");
  1339. }
  1340. }
  1341. /**
  1342. * Tests for user-configurable time zones.
  1343. */
  1344. class UserTimeZoneFunctionalTest extends DrupalWebTestCase {
  1345. public static function getInfo() {
  1346. return array(
  1347. 'name' => 'User time zones',
  1348. 'description' => 'Set a user time zone and verify that dates are displayed in local time.',
  1349. 'group' => 'User',
  1350. );
  1351. }
  1352. /**
  1353. * Tests the display of dates and time when user-configurable time zones are set.
  1354. */
  1355. function testUserTimeZone() {
  1356. // Setup date/time settings for Los Angeles time.
  1357. variable_set('date_default_timezone', 'America/Los_Angeles');
  1358. variable_set('configurable_timezones', 1);
  1359. // Override the 'medium' date format, which is the default for node
  1360. // creation time. Since we are testing time zones with Daylight Saving
  1361. // Time, and need to future proof against changes to the zoneinfo database,
  1362. // we choose the 'I' format placeholder instead of a human-readable zone
  1363. // name. With 'I', a 1 means the date is in DST, and 0 if not.
  1364. variable_set('date_format_medium', 'Y-m-d H:i I');
  1365. // Create a user account and login.
  1366. $web_user = $this->drupalCreateUser();
  1367. $this->drupalLogin($web_user);
  1368. // Create some nodes with different authored-on dates.
  1369. // Two dates in PST (winter time):
  1370. $date1 = '2007-03-09 21:00:00 -0800';
  1371. $date2 = '2007-03-11 01:00:00 -0800';
  1372. // One date in PDT (summer time):
  1373. $date3 = '2007-03-20 21:00:00 -0700';
  1374. $node1 = $this->drupalCreateNode(array('created' => strtotime($date1), 'type' => 'article'));
  1375. $node2 = $this->drupalCreateNode(array('created' => strtotime($date2), 'type' => 'article'));
  1376. $node3 = $this->drupalCreateNode(array('created' => strtotime($date3), 'type' => 'article'));
  1377. // Confirm date format and time zone.
  1378. $this->drupalGet("node/$node1->nid");
  1379. $this->assertText('2007-03-09 21:00 0', 'Date should be PST.');
  1380. $this->drupalGet("node/$node2->nid");
  1381. $this->assertText('2007-03-11 01:00 0', 'Date should be PST.');
  1382. $this->drupalGet("node/$node3->nid");
  1383. $this->assertText('2007-03-20 21:00 1', 'Date should be PDT.');
  1384. // Change user time zone to Santiago time.
  1385. $edit = array();
  1386. $edit['mail'] = $web_user->mail;
  1387. $edit['timezone'] = 'America/Santiago';
  1388. $this->drupalPost("user/$web_user->uid/edit", $edit, t('Save'));
  1389. $this->assertText(t('The changes have been saved.'), 'Time zone changed to Santiago time.');
  1390. // Confirm date format and time zone.
  1391. $this->drupalGet("node/$node1->nid");
  1392. $this->assertText('2007-03-10 02:00 1', 'Date should be Chile summer time; five hours ahead of PST.');
  1393. $this->drupalGet("node/$node2->nid");
  1394. $this->assertText('2007-03-11 05:00 0', 'Date should be Chile time; four hours ahead of PST');
  1395. $this->drupalGet("node/$node3->nid");
  1396. $this->assertText('2007-03-21 00:00 0', 'Date should be Chile time; three hours ahead of PDT.');
  1397. }
  1398. }
  1399. /**
  1400. * Test user autocompletion.
  1401. */
  1402. class UserAutocompleteTestCase extends DrupalWebTestCase {
  1403. public static function getInfo() {
  1404. return array(
  1405. 'name' => 'User autocompletion',
  1406. 'description' => 'Test user autocompletion functionality.',
  1407. 'group' => 'User'
  1408. );
  1409. }
  1410. function setUp() {
  1411. parent::setUp();
  1412. // Set up two users with different permissions to test access.
  1413. $this->unprivileged_user = $this->drupalCreateUser();
  1414. $this->privileged_user = $this->drupalCreateUser(array('access user profiles'));
  1415. }
  1416. /**
  1417. * Tests access to user autocompletion and verify the correct results.
  1418. */
  1419. function testUserAutocomplete() {
  1420. // Check access from unprivileged user, should be denied.
  1421. $this->drupalLogin($this->unprivileged_user);
  1422. $this->drupalGet('user/autocomplete/' . $this->unprivileged_user->name[0]);
  1423. $this->assertResponse(403, 'Autocompletion access denied to user without permission.');
  1424. // Check access from privileged user.
  1425. $this->drupalLogout();
  1426. $this->drupalLogin($this->privileged_user);
  1427. $this->drupalGet('user/autocomplete/' . $this->unprivileged_user->name[0]);
  1428. $this->assertResponse(200, 'Autocompletion access allowed.');
  1429. // Using first letter of the user's name, make sure the user's full name is in the results.
  1430. $this->assertRaw($this->unprivileged_user->name, 'User name found in autocompletion results.');
  1431. }
  1432. }
  1433. /**
  1434. * Tests user links in the secondary menu.
  1435. */
  1436. class UserAccountLinksUnitTests extends DrupalWebTestCase {
  1437. public static function getInfo() {
  1438. return array(
  1439. 'name' => 'User account links',
  1440. 'description' => 'Test user-account links.',
  1441. 'group' => 'User'
  1442. );
  1443. }
  1444. function setUp() {
  1445. parent::setUp('menu');
  1446. }
  1447. /**
  1448. * Tests the secondary menu.
  1449. */
  1450. function testSecondaryMenu() {
  1451. // Create a regular user.
  1452. $user = $this->drupalCreateUser(array());
  1453. // Log in and get the homepage.
  1454. $this->drupalLogin($user);
  1455. $this->drupalGet('<front>');
  1456. // For a logged-in user, expect the secondary menu to have links for "My
  1457. // account" and "Log out".
  1458. $link = $this->xpath('//ul[@id=:menu_id]/li/a[contains(@href, :href) and text()=:text]', array(
  1459. ':menu_id' => 'secondary-menu-links',
  1460. ':href' => 'user',
  1461. ':text' => 'My account',
  1462. ));
  1463. $this->assertEqual(count($link), 1, 'My account link is in secondary menu.');
  1464. $link = $this->xpath('//ul[@id=:menu_id]/li/a[contains(@href, :href) and text()=:text]', array(
  1465. ':menu_id' => 'secondary-menu-links',
  1466. ':href' => 'user/logout',
  1467. ':text' => 'Log out',
  1468. ));
  1469. $this->assertEqual(count($link), 1, 'Log out link is in secondary menu.');
  1470. // Log out and get the homepage.
  1471. $this->drupalLogout();
  1472. $this->drupalGet('<front>');
  1473. // For a logged-out user, expect no secondary links.
  1474. $element = $this->xpath('//ul[@id=:menu_id]', array(':menu_id' => 'secondary-menu-links'));
  1475. $this->assertEqual(count($element), 0, 'No secondary-menu for logged-out users.');
  1476. }
  1477. /**
  1478. * Tests disabling the 'My account' link.
  1479. */
  1480. function testDisabledAccountLink() {
  1481. // Create an admin user and log in.
  1482. $this->drupalLogin($this->drupalCreateUser(array('access administration pages', 'administer menu')));
  1483. // Verify that the 'My account' link is enabled.
  1484. $this->drupalGet('admin/structure/menu/manage/user-menu');
  1485. $label = $this->xpath('//label[contains(.,:text)]/@for', array(':text' => 'Enable My account menu link'));
  1486. $this->assertFieldChecked((string) $label[0], "The 'My account' link is enabled by default.");
  1487. // Disable the 'My account' link.
  1488. $input = $this->xpath('//input[@id=:field_id]/@name', array(':field_id' => (string)$label[0]));
  1489. $edit = array(
  1490. (string) $input[0] => FALSE,
  1491. );
  1492. $this->drupalPost('admin/structure/menu/manage/user-menu', $edit, t('Save configuration'));
  1493. // Get the homepage.
  1494. $this->drupalGet('<front>');
  1495. // Verify that the 'My account' link does not appear when disabled.
  1496. $link = $this->xpath('//ul[@id=:menu_id]/li/a[contains(@href, :href) and text()=:text]', array(
  1497. ':menu_id' => 'secondary-menu-links',
  1498. ':href' => 'user',
  1499. ':text' => 'My account',
  1500. ));
  1501. $this->assertEqual(count($link), 0, 'My account link is not in the secondary menu.');
  1502. }
  1503. }
  1504. /**
  1505. * Test user blocks.
  1506. */
  1507. class UserBlocksUnitTests extends DrupalWebTestCase {
  1508. public static function getInfo() {
  1509. return array(
  1510. 'name' => 'User blocks',
  1511. 'description' => 'Test user blocks.',
  1512. 'group' => 'User'
  1513. );
  1514. }
  1515. /**
  1516. * Test the user login block.
  1517. */
  1518. function testUserLoginBlock() {
  1519. // Create a user with some permission that anonymous users lack.
  1520. $user = $this->drupalCreateUser(array('administer permissions'));
  1521. // Log in using the block.
  1522. $edit = array();
  1523. $edit['name'] = $user->name;
  1524. $edit['pass'] = $user->pass_raw;
  1525. $this->drupalPost('admin/people/permissions', $edit, t('Log in'));
  1526. $this->assertNoText(t('User login'), 'Logged in.');
  1527. // Check that we are still on the same page.
  1528. $this->assertEqual(url('admin/people/permissions', array('absolute' => TRUE)), $this->getUrl(), 'Still on the same page after login for access denied page');
  1529. // Now, log out and repeat with a non-403 page.
  1530. $this->drupalLogout();
  1531. $this->drupalPost('filter/tips', $edit, t('Log in'));
  1532. $this->assertNoText(t('User login'), 'Logged in.');
  1533. $this->assertPattern('!<title.*?' . t('Compose tips') . '.*?</title>!', 'Still on the same page after login for allowed page');
  1534. // Check that the user login block is not vulnerable to information
  1535. // disclosure to third party sites.
  1536. $this->drupalLogout();
  1537. $this->drupalPost('http://example.com/', $edit, t('Log in'), array('external' => FALSE));
  1538. // Check that we remain on the site after login.
  1539. $this->assertEqual(url('user/' . $user->uid, array('absolute' => TRUE)), $this->getUrl(), 'Redirected to user profile page after login from the frontpage');
  1540. }
  1541. /**
  1542. * Test the Who's Online block.
  1543. */
  1544. function testWhosOnlineBlock() {
  1545. // Generate users and make sure there are no current user sessions.
  1546. $user1 = $this->drupalCreateUser(array());
  1547. $user2 = $this->drupalCreateUser(array());
  1548. $user3 = $this->drupalCreateUser(array());
  1549. $this->assertEqual(db_query("SELECT COUNT(*) FROM {sessions}")->fetchField(), 0, 'Sessions table is empty.');
  1550. // Insert a user with two sessions.
  1551. $this->insertSession(array('uid' => $user1->uid));
  1552. $this->insertSession(array('uid' => $user1->uid));
  1553. $this->assertEqual(db_query("SELECT COUNT(*) FROM {sessions} WHERE uid = :uid", array(':uid' => $user1->uid))->fetchField(), 2, 'Duplicate user session has been inserted.');
  1554. // Insert a user with only one session.
  1555. $this->insertSession(array('uid' => $user2->uid, 'timestamp' => REQUEST_TIME + 1));
  1556. // Insert an inactive logged-in user who should not be seen in the block.
  1557. $this->insertSession(array('uid' => $user3->uid, 'timestamp' => (REQUEST_TIME - variable_get('user_block_seconds_online', 900) - 1)));
  1558. // Insert two anonymous user sessions.
  1559. $this->insertSession();
  1560. $this->insertSession();
  1561. // Test block output.
  1562. $block = user_block_view('online');
  1563. $this->drupalSetContent($block['content']);
  1564. $this->assertRaw(t('2 users'), 'Correct number of online users (2 users).');
  1565. $this->assertText($user1->name, 'Active user 1 found in online list.');
  1566. $this->assertText($user2->name, 'Active user 2 found in online list.');
  1567. $this->assertNoText($user3->name, "Inactive user not found in online list.");
  1568. $this->assertTrue(strpos($this->drupalGetContent(), $user1->name) > strpos($this->drupalGetContent(), $user2->name), 'Online users are ordered correctly.');
  1569. }
  1570. /**
  1571. * Insert a user session into the {sessions} table. This function is used
  1572. * since we cannot log in more than one user at the same time in tests.
  1573. */
  1574. private function insertSession(array $fields = array()) {
  1575. $fields += array(
  1576. 'uid' => 0,
  1577. 'sid' => drupal_hash_base64(uniqid(mt_rand(), TRUE)),
  1578. 'timestamp' => REQUEST_TIME,
  1579. );
  1580. db_insert('sessions')
  1581. ->fields($fields)
  1582. ->execute();
  1583. $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.');
  1584. }
  1585. }
  1586. /**
  1587. * Tests saving a user account.
  1588. */
  1589. class UserSaveTestCase extends DrupalWebTestCase {
  1590. public static function getInfo() {
  1591. return array(
  1592. 'name' => 'User save test',
  1593. 'description' => 'Test user_save() for arbitrary new uid.',
  1594. 'group' => 'User',
  1595. );
  1596. }
  1597. /**
  1598. * Test creating a user with arbitrary uid.
  1599. */
  1600. function testUserImport() {
  1601. // User ID must be a number that is not in the database.
  1602. $max_uid = db_query('SELECT MAX(uid) FROM {users}')->fetchField();
  1603. $test_uid = $max_uid + mt_rand(1000, 1000000);
  1604. $test_name = $this->randomName();
  1605. // Create the base user, based on drupalCreateUser().
  1606. $user = array(
  1607. 'name' => $test_name,
  1608. 'uid' => $test_uid,
  1609. 'mail' => $test_name . '@example.com',
  1610. 'is_new' => TRUE,
  1611. 'pass' => user_password(),
  1612. 'status' => 1,
  1613. );
  1614. $user_by_return = user_save(drupal_anonymous_user(), $user);
  1615. $this->assertTrue($user_by_return, 'Loading user by return of user_save().');
  1616. // Test if created user exists.
  1617. $user_by_uid = user_load($test_uid);
  1618. $this->assertTrue($user_by_uid, 'Loading user by uid.');
  1619. $user_by_name = user_load_by_name($test_name);
  1620. $this->assertTrue($user_by_name, 'Loading user by name.');
  1621. }
  1622. }
  1623. /**
  1624. * Test the create user administration page.
  1625. */
  1626. class UserCreateTestCase extends DrupalWebTestCase {
  1627. public static function getInfo() {
  1628. return array(
  1629. 'name' => 'User create',
  1630. 'description' => 'Test the create user administration page.',
  1631. 'group' => 'User',
  1632. );
  1633. }
  1634. /**
  1635. * Create a user through the administration interface and ensure that it
  1636. * displays in the user list.
  1637. */
  1638. protected function testUserAdd() {
  1639. $user = $this->drupalCreateUser(array('administer users'));
  1640. $this->drupalLogin($user);
  1641. foreach (array(FALSE, TRUE) as $notify) {
  1642. $edit = array(
  1643. 'name' => $this->randomName(),
  1644. 'mail' => $this->randomName() . '@example.com',
  1645. 'pass[pass1]' => $pass = $this->randomString(),
  1646. 'pass[pass2]' => $pass,
  1647. 'notify' => $notify,
  1648. );
  1649. $this->drupalPost('admin/people/create', $edit, t('Create new account'));
  1650. if ($notify) {
  1651. $this->assertText(t('A welcome message with further instructions has been e-mailed to the new user @name.', array('@name' => $edit['name'])), 'User created');
  1652. $this->assertEqual(count($this->drupalGetMails()), 1, 'Notification e-mail sent');
  1653. }
  1654. else {
  1655. $this->assertText(t('Created a new user account for @name. No e-mail has been sent.', array('@name' => $edit['name'])), 'User created');
  1656. $this->assertEqual(count($this->drupalGetMails()), 0, 'Notification e-mail not sent');
  1657. }
  1658. $this->drupalGet('admin/people');
  1659. $this->assertText($edit['name'], 'User found in list of users');
  1660. }
  1661. // Test that the password '0' is considered a password.
  1662. $name = $this->randomName();
  1663. $edit = array(
  1664. 'name' => $name,
  1665. 'mail' => $name . '@example.com',
  1666. 'pass[pass1]' => 0,
  1667. 'pass[pass2]' => 0,
  1668. 'notify' => FALSE,
  1669. );
  1670. $this->drupalPost('admin/people/create', $edit, t('Create new account'));
  1671. $this->assertText(t('Created a new user account for @name. No e-mail has been sent.', array('@name' => $edit['name'])), 'User created with password 0');
  1672. $this->assertNoText('Password field is required');
  1673. }
  1674. }
  1675. /**
  1676. * Tests editing a user account.
  1677. */
  1678. class UserEditTestCase extends DrupalWebTestCase {
  1679. public static function getInfo() {
  1680. return array(
  1681. 'name' => 'User edit',
  1682. 'description' => 'Test user edit page.',
  1683. 'group' => 'User',
  1684. );
  1685. }
  1686. /**
  1687. * Test user edit page.
  1688. */
  1689. function testUserEdit() {
  1690. // Test user edit functionality with user pictures disabled.
  1691. variable_set('user_pictures', 0);
  1692. $user1 = $this->drupalCreateUser(array('change own username'));
  1693. $user2 = $this->drupalCreateUser(array());
  1694. $this->drupalLogin($user1);
  1695. // Test that error message appears when attempting to use a non-unique user name.
  1696. $edit['name'] = $user2->name;
  1697. $this->drupalPost("user/$user1->uid/edit", $edit, t('Save'));
  1698. $this->assertRaw(t('The name %name is already taken.', array('%name' => $edit['name'])));
  1699. // Repeat the test with user pictures enabled, which modifies the form.
  1700. variable_set('user_pictures', 1);
  1701. $this->drupalPost("user/$user1->uid/edit", $edit, t('Save'));
  1702. $this->assertRaw(t('The name %name is already taken.', array('%name' => $edit['name'])));
  1703. // Check that filling out a single password field does not validate.
  1704. $edit = array();
  1705. $edit['pass[pass1]'] = '';
  1706. $edit['pass[pass2]'] = $this->randomName();
  1707. $this->drupalPost("user/$user1->uid/edit", $edit, t('Save'));
  1708. $this->assertText(t("The specified passwords do not match."), 'Typing mismatched passwords displays an error message.');
  1709. $edit['pass[pass1]'] = $this->randomName();
  1710. $edit['pass[pass2]'] = '';
  1711. $this->drupalPost("user/$user1->uid/edit", $edit, t('Save'));
  1712. $this->assertText(t("The specified passwords do not match."), 'Typing mismatched passwords displays an error message.');
  1713. // Test that the error message appears when attempting to change the mail or
  1714. // pass without the current password.
  1715. $edit = array();
  1716. $edit['mail'] = $this->randomName() . '@new.example.com';
  1717. $this->drupalPost("user/$user1->uid/edit", $edit, t('Save'));
  1718. $this->assertRaw(t("Your current password is missing or incorrect; it's required to change the %name.", array('%name' => t('E-mail address'))));
  1719. $edit['current_pass'] = $user1->pass_raw;
  1720. $this->drupalPost("user/$user1->uid/edit", $edit, t('Save'));
  1721. $this->assertRaw(t("The changes have been saved."));
  1722. // Test that the user must enter current password before changing passwords.
  1723. $edit = array();
  1724. $edit['pass[pass1]'] = $new_pass = $this->randomName();
  1725. $edit['pass[pass2]'] = $new_pass;
  1726. $this->drupalPost("user/$user1->uid/edit", $edit, t('Save'));
  1727. $this->assertRaw(t("Your current password is missing or incorrect; it's required to change the %name.", array('%name' => t('Password'))));
  1728. // Try again with the current password.
  1729. $edit['current_pass'] = $user1->pass_raw;
  1730. $this->drupalPost("user/$user1->uid/edit", $edit, t('Save'));
  1731. $this->assertRaw(t("The changes have been saved."));
  1732. // Make sure the user can log in with their new password.
  1733. $this->drupalLogout();
  1734. $user1->pass_raw = $new_pass;
  1735. $this->drupalLogin($user1);
  1736. $this->drupalLogout();
  1737. }
  1738. /**
  1739. * Tests setting the password to "0".
  1740. */
  1741. public function testUserWith0Password() {
  1742. $admin = $this->drupalCreateUser(array('administer users'));
  1743. $this->drupalLogin($admin);
  1744. // Create a regular user.
  1745. $user1 = $this->drupalCreateUser(array());
  1746. $edit = array('pass[pass1]' => '0', 'pass[pass2]' => '0');
  1747. $this->drupalPost("user/" . $user1->uid . "/edit", $edit, t('Save'));
  1748. $this->assertRaw(t("The changes have been saved."));
  1749. $this->drupalLogout();
  1750. $user1->pass_raw = '0';
  1751. $this->drupalLogin($user1);
  1752. $this->drupalLogout();
  1753. }
  1754. }
  1755. /**
  1756. * Tests editing a user account with and without a form rebuild.
  1757. */
  1758. class UserEditRebuildTestCase extends DrupalWebTestCase {
  1759. public static function getInfo() {
  1760. return array(
  1761. 'name' => 'User edit with form rebuild',
  1762. 'description' => 'Test user edit page when a form rebuild is triggered.',
  1763. 'group' => 'User',
  1764. );
  1765. }
  1766. function setUp() {
  1767. parent::setUp('user_form_test');
  1768. }
  1769. /**
  1770. * Test user edit page when the form is set to rebuild.
  1771. */
  1772. function testUserEditFormRebuild() {
  1773. $user1 = $this->drupalCreateUser(array('change own username'));
  1774. $this->drupalLogin($user1);
  1775. $roles = array_keys($user1->roles);
  1776. // Save the user form twice.
  1777. $edit = array();
  1778. $edit['current_pass'] = $user1->pass_raw;
  1779. $this->drupalPost("user/$user1->uid/edit", $edit, t('Save'));
  1780. $this->assertRaw(t("The changes have been saved."));
  1781. $this->drupalPost(NULL, $edit, t('Save'));
  1782. $this->assertRaw(t("The changes have been saved."));
  1783. $saved_user1 = entity_load_unchanged('user', $user1->uid);
  1784. $this->assertEqual(count($roles), count($saved_user1->roles), 'Count of user roles in database matches original count.');
  1785. $diff = array_diff(array_keys($saved_user1->roles), $roles);
  1786. $this->assertTrue(empty($diff), format_string('User roles in database match original: @roles', array('@roles' => implode(', ', $saved_user1->roles))));
  1787. // Set variable that causes the form to be rebuilt in user_form_test.module.
  1788. variable_set('user_form_test_user_profile_form_rebuild', TRUE);
  1789. $this->drupalPost("user/$user1->uid/edit", $edit, t('Save'));
  1790. $this->assertRaw(t("The changes have been saved."));
  1791. $this->drupalPost(NULL, $edit, t('Save'));
  1792. $this->assertRaw(t("The changes have been saved."));
  1793. $saved_user1 = entity_load_unchanged('user', $user1->uid);
  1794. $this->assertEqual(count($roles), count($saved_user1->roles), 'Count of user roles in database matches original count.');
  1795. $diff = array_diff(array_keys($saved_user1->roles), $roles);
  1796. $this->assertTrue(empty($diff), format_string('User roles in database match original: @roles', array('@roles' => implode(', ', $saved_user1->roles))));
  1797. }
  1798. }
  1799. /**
  1800. * Test case for user signatures.
  1801. */
  1802. class UserSignatureTestCase extends DrupalWebTestCase {
  1803. public static function getInfo() {
  1804. return array(
  1805. 'name' => 'User signatures',
  1806. 'description' => 'Test user signatures.',
  1807. 'group' => 'User',
  1808. );
  1809. }
  1810. function setUp() {
  1811. parent::setUp('comment');
  1812. // Enable user signatures.
  1813. variable_set('user_signatures', 1);
  1814. // Prefetch text formats.
  1815. $this->full_html_format = filter_format_load('full_html');
  1816. $this->plain_text_format = filter_format_load('plain_text');
  1817. // Create regular and administrative users.
  1818. $this->web_user = $this->drupalCreateUser(array());
  1819. $admin_permissions = array('administer comments');
  1820. foreach (filter_formats() as $format) {
  1821. if ($permission = filter_permission_name($format)) {
  1822. $admin_permissions[] = $permission;
  1823. }
  1824. }
  1825. $this->admin_user = $this->drupalCreateUser($admin_permissions);
  1826. }
  1827. /**
  1828. * Test that a user can change their signature format and that it is respected
  1829. * upon display.
  1830. */
  1831. function testUserSignature() {
  1832. // Create a new node with comments on.
  1833. $node = $this->drupalCreateNode(array('comment' => COMMENT_NODE_OPEN));
  1834. // Verify that user signature field is not displayed on registration form.
  1835. $this->drupalGet('user/register');
  1836. $this->assertNoText(t('Signature'));
  1837. // Log in as a regular user and create a signature.
  1838. $this->drupalLogin($this->web_user);
  1839. $signature_text = "<h1>" . $this->randomName() . "</h1>";
  1840. $edit = array(
  1841. 'signature[value]' => $signature_text,
  1842. 'signature[format]' => $this->plain_text_format->format,
  1843. );
  1844. $this->drupalPost('user/' . $this->web_user->uid . '/edit', $edit, t('Save'));
  1845. // Verify that values were stored.
  1846. $this->assertFieldByName('signature[value]', $edit['signature[value]'], 'Submitted signature text found.');
  1847. $this->assertFieldByName('signature[format]', $edit['signature[format]'], 'Submitted signature format found.');
  1848. // Create a comment.
  1849. $langcode = LANGUAGE_NONE;
  1850. $edit = array();
  1851. $edit['subject'] = $this->randomName(8);
  1852. $edit['comment_body[' . $langcode . '][0][value]'] = $this->randomName(16);
  1853. $this->drupalPost('comment/reply/' . $node->nid, $edit, t('Preview'));
  1854. $this->drupalPost(NULL, array(), t('Save'));
  1855. // Get the comment ID. (This technique is the same one used in the Comment
  1856. // module's CommentHelperCase test case.)
  1857. preg_match('/#comment-([0-9]+)/', $this->getURL(), $match);
  1858. $comment_id = $match[1];
  1859. // Log in as an administrator and edit the comment to use Full HTML, so
  1860. // that the comment text itself is not filtered at all.
  1861. $this->drupalLogin($this->admin_user);
  1862. $edit['comment_body[' . $langcode . '][0][format]'] = $this->full_html_format->format;
  1863. $this->drupalPost('comment/' . $comment_id . '/edit', $edit, t('Save'));
  1864. // Assert that the signature did not make it through unfiltered.
  1865. $this->drupalGet('node/' . $node->nid);
  1866. $this->assertNoRaw($signature_text, 'Unfiltered signature text not found.');
  1867. $this->assertRaw(check_markup($signature_text, $this->plain_text_format->format), 'Filtered signature text found.');
  1868. }
  1869. }
  1870. /*
  1871. * Test that a user, having editing their own account, can still log in.
  1872. */
  1873. class UserEditedOwnAccountTestCase extends DrupalWebTestCase {
  1874. public static function getInfo() {
  1875. return array(
  1876. 'name' => 'User edited own account',
  1877. 'description' => 'Test user edited own account can still log in.',
  1878. 'group' => 'User',
  1879. );
  1880. }
  1881. function testUserEditedOwnAccount() {
  1882. // Change account setting 'Who can register accounts?' to Administrators
  1883. // only.
  1884. variable_set('user_register', USER_REGISTER_ADMINISTRATORS_ONLY);
  1885. // Create a new user account and log in.
  1886. $account = $this->drupalCreateUser(array('change own username'));
  1887. $this->drupalLogin($account);
  1888. // Change own username.
  1889. $edit = array();
  1890. $edit['name'] = $this->randomName();
  1891. $this->drupalPost('user/' . $account->uid . '/edit', $edit, t('Save'));
  1892. // Log out.
  1893. $this->drupalLogout();
  1894. // Set the new name on the user account and attempt to log back in.
  1895. $account->name = $edit['name'];
  1896. $this->drupalLogin($account);
  1897. }
  1898. }
  1899. /**
  1900. * Test case to test adding, editing and deleting roles.
  1901. */
  1902. class UserRoleAdminTestCase extends DrupalWebTestCase {
  1903. public static function getInfo() {
  1904. return array(
  1905. 'name' => 'User role administration',
  1906. 'description' => 'Test adding, editing and deleting user roles and changing role weights.',
  1907. 'group' => 'User',
  1908. );
  1909. }
  1910. function setUp() {
  1911. parent::setUp();
  1912. $this->admin_user = $this->drupalCreateUser(array('administer permissions', 'administer users'));
  1913. }
  1914. /**
  1915. * Test adding, renaming and deleting roles.
  1916. */
  1917. function testRoleAdministration() {
  1918. $this->drupalLogin($this->admin_user);
  1919. // Test adding a role. (In doing so, we use a role name that happens to
  1920. // correspond to an integer, to test that the role administration pages
  1921. // correctly distinguish between role names and IDs.)
  1922. $role_name = '123';
  1923. $edit = array('name' => $role_name);
  1924. $this->drupalPost('admin/people/permissions/roles', $edit, t('Add role'));
  1925. $this->assertText(t('The role has been added.'), 'The role has been added.');
  1926. $role = user_role_load_by_name($role_name);
  1927. $this->assertTrue(is_object($role), 'The role was successfully retrieved from the database.');
  1928. // Try adding a duplicate role.
  1929. $this->drupalPost(NULL, $edit, t('Add role'));
  1930. $this->assertRaw(t('The role name %name already exists. Choose another role name.', array('%name' => $role_name)), 'Duplicate role warning displayed.');
  1931. // Test renaming a role.
  1932. $old_name = $role_name;
  1933. $role_name = '456';
  1934. $edit = array('name' => $role_name);
  1935. $this->drupalPost("admin/people/permissions/roles/edit/{$role->rid}", $edit, t('Save role'));
  1936. $this->assertText(t('The role has been renamed.'), 'The role has been renamed.');
  1937. $this->assertFalse(user_role_load_by_name($old_name), 'The role can no longer be retrieved from the database using its old name.');
  1938. $this->assertTrue(is_object(user_role_load_by_name($role_name)), 'The role can be retrieved from the database using its new name.');
  1939. // Test deleting the default administrator role.
  1940. $role_name = 'administrator';
  1941. $role = user_role_load_by_name($role_name);
  1942. $this->drupalPost("admin/people/permissions/roles/edit/{$role->rid}", NULL, t('Delete role'));
  1943. $this->drupalPost(NULL, NULL, t('Delete'));
  1944. $this->assertText(t('The role has been deleted.'), 'The role has been deleted');
  1945. $this->assertNoLinkByHref("admin/people/permissions/roles/edit/{$role->rid}", 'Role edit link removed.');
  1946. $this->assertFalse(user_role_load_by_name($role_name), 'A deleted role can no longer be loaded.');
  1947. // Make sure this role is no longer configured as the administrator role.
  1948. $this->assertNull(variable_get('user_admin_role'), 'The administrator role is no longer configured as the administrator role.');
  1949. // Make sure that the system-defined roles cannot be edited via the user
  1950. // interface.
  1951. $this->drupalGet('admin/people/permissions/roles/edit/' . DRUPAL_ANONYMOUS_RID);
  1952. $this->assertResponse(403, 'Access denied when trying to edit the built-in anonymous role.');
  1953. $this->drupalGet('admin/people/permissions/roles/edit/' . DRUPAL_AUTHENTICATED_RID);
  1954. $this->assertResponse(403, 'Access denied when trying to edit the built-in authenticated role.');
  1955. }
  1956. /**
  1957. * Test user role weight change operation.
  1958. */
  1959. function testRoleWeightChange() {
  1960. $this->drupalLogin($this->admin_user);
  1961. // Pick up a random role and get its weight.
  1962. $rid = array_rand(user_roles());
  1963. $role = user_role_load($rid);
  1964. $old_weight = $role->weight;
  1965. // Change the role weight and submit the form.
  1966. $edit = array('roles['. $rid .'][weight]' => $old_weight + 1);
  1967. $this->drupalPost('admin/people/permissions/roles', $edit, t('Save order'));
  1968. $this->assertText(t('The role settings have been updated.'), 'The role settings form submitted successfully.');
  1969. // Retrieve the saved role and compare its weight.
  1970. $role = user_role_load($rid);
  1971. $new_weight = $role->weight;
  1972. $this->assertTrue(($old_weight + 1) == $new_weight, 'Role weight updated successfully.');
  1973. }
  1974. }
  1975. /**
  1976. * Test user token replacement in strings.
  1977. */
  1978. class UserTokenReplaceTestCase extends DrupalWebTestCase {
  1979. public static function getInfo() {
  1980. return array(
  1981. 'name' => 'User token replacement',
  1982. 'description' => 'Generates text using placeholders for dummy content to check user token replacement.',
  1983. 'group' => 'User',
  1984. );
  1985. }
  1986. /**
  1987. * Creates a user, then tests the tokens generated from it.
  1988. */
  1989. function testUserTokenReplacement() {
  1990. global $language;
  1991. $url_options = array(
  1992. 'absolute' => TRUE,
  1993. 'language' => $language,
  1994. );
  1995. // Create two users and log them in one after another.
  1996. $user1 = $this->drupalCreateUser(array());
  1997. $user2 = $this->drupalCreateUser(array());
  1998. $this->drupalLogin($user1);
  1999. $this->drupalLogout();
  2000. $this->drupalLogin($user2);
  2001. $account = user_load($user1->uid);
  2002. $global_account = user_load($GLOBALS['user']->uid);
  2003. // Generate and test sanitized tokens.
  2004. $tests = array();
  2005. $tests['[user:uid]'] = $account->uid;
  2006. $tests['[user:name]'] = check_plain(format_username($account));
  2007. $tests['[user:mail]'] = check_plain($account->mail);
  2008. $tests['[user:url]'] = url("user/$account->uid", $url_options);
  2009. $tests['[user:edit-url]'] = url("user/$account->uid/edit", $url_options);
  2010. $tests['[user:last-login]'] = format_date($account->login, 'medium', '', NULL, $language->language);
  2011. $tests['[user:last-login:short]'] = format_date($account->login, 'short', '', NULL, $language->language);
  2012. $tests['[user:created]'] = format_date($account->created, 'medium', '', NULL, $language->language);
  2013. $tests['[user:created:short]'] = format_date($account->created, 'short', '', NULL, $language->language);
  2014. $tests['[current-user:name]'] = check_plain(format_username($global_account));
  2015. // Test to make sure that we generated something for each token.
  2016. $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
  2017. foreach ($tests as $input => $expected) {
  2018. $output = token_replace($input, array('user' => $account), array('language' => $language));
  2019. $this->assertEqual($output, $expected, format_string('Sanitized user token %token replaced.', array('%token' => $input)));
  2020. }
  2021. // Generate and test unsanitized tokens.
  2022. $tests['[user:name]'] = format_username($account);
  2023. $tests['[user:mail]'] = $account->mail;
  2024. $tests['[current-user:name]'] = format_username($global_account);
  2025. foreach ($tests as $input => $expected) {
  2026. $output = token_replace($input, array('user' => $account), array('language' => $language, 'sanitize' => FALSE));
  2027. $this->assertEqual($output, $expected, format_string('Unsanitized user token %token replaced.', array('%token' => $input)));
  2028. }
  2029. }
  2030. }
  2031. /**
  2032. * Test user search.
  2033. */
  2034. class UserUserSearchTestCase extends DrupalWebTestCase {
  2035. public static function getInfo() {
  2036. return array(
  2037. 'name' => 'User search',
  2038. 'description' => 'Tests the user search page and verifies that sensitive information is hidden from unauthorized users.',
  2039. 'group' => 'User',
  2040. );
  2041. }
  2042. function testUserSearch() {
  2043. // Verify that a user without 'administer users' permission cannot search
  2044. // for users by email address. Additionally, ensure that the username has a
  2045. // plus sign to ensure searching works with that.
  2046. $user1 = $this->drupalCreateUser(array('access user profiles', 'search content', 'use advanced search'));
  2047. $edit['name'] = 'foo+bar';
  2048. $edit['mail'] = $edit['name'] . '@example.com';
  2049. user_save($user1, $edit);
  2050. $this->drupalLogin($user1);
  2051. $keys = $user1->mail;
  2052. $edit = array('keys' => $keys);
  2053. $this->drupalPost('search/user/', $edit, t('Search'));
  2054. $this->assertNoText($keys);
  2055. $this->drupalLogout();
  2056. $user2 = $this->drupalCreateUser(array('administer users', 'access user profiles', 'search content', 'use advanced search'));
  2057. $this->drupalLogin($user2);
  2058. $keys = $user2->mail;
  2059. $edit = array('keys' => $keys);
  2060. $this->drupalPost('search/user/', $edit, t('Search'));
  2061. $this->assertText($keys);
  2062. // Verify that wildcard search works.
  2063. $keys = $user1->name;
  2064. $keys = substr($keys, 0, 2) . '*' . substr($keys, 4, 2);
  2065. $edit = array('keys' => $keys);
  2066. $this->drupalPost('search/user/', $edit, t('Search'));
  2067. $this->assertText($user1->name, 'Search for username wildcard resulted in user name on page for administrative user.');
  2068. // Verify that wildcard search works for email.
  2069. $keys = $user1->mail;
  2070. $keys = substr($keys, 0, 2) . '*' . substr($keys, 4, 2);
  2071. $edit = array('keys' => $keys);
  2072. $this->drupalPost('search/user/', $edit, t('Search'));
  2073. $this->assertText($user1->name, 'Search for email wildcard resulted in user name on page for administrative user.');
  2074. // Create a blocked user.
  2075. $blocked_user = $this->drupalCreateUser();
  2076. $edit = array('status' => 0);
  2077. $blocked_user = user_save($blocked_user, $edit);
  2078. // Verify that users with "administer users" permissions can see blocked
  2079. // accounts in search results.
  2080. $edit = array('keys' => $blocked_user->name);
  2081. $this->drupalPost('search/user/', $edit, t('Search'));
  2082. $this->assertText($blocked_user->name, 'Blocked users are listed on the user search results for users with the "administer users" permission.');
  2083. // Verify that users without "administer users" permissions do not see
  2084. // blocked accounts in search results.
  2085. $this->drupalLogin($user1);
  2086. $edit = array('keys' => $blocked_user->name);
  2087. $this->drupalPost('search/user/', $edit, t('Search'));
  2088. $this->assertNoText($blocked_user->name, 'Blocked users are hidden from the user search results.');
  2089. $this->drupalLogout();
  2090. }
  2091. }
  2092. /**
  2093. * Test role assignment.
  2094. */
  2095. class UserRolesAssignmentTestCase extends DrupalWebTestCase {
  2096. protected $admin_user;
  2097. public static function getInfo() {
  2098. return array(
  2099. 'name' => 'Role assignment',
  2100. 'description' => 'Tests that users can be assigned and unassigned roles.',
  2101. 'group' => 'User'
  2102. );
  2103. }
  2104. function setUp() {
  2105. parent::setUp();
  2106. $this->admin_user = $this->drupalCreateUser(array('administer permissions', 'administer users'));
  2107. $this->drupalLogin($this->admin_user);
  2108. }
  2109. /**
  2110. * Tests that a user can be assigned a role and that the role can be removed
  2111. * again.
  2112. */
  2113. function testAssignAndRemoveRole() {
  2114. $rid = $this->drupalCreateRole(array('administer content types'));
  2115. $account = $this->drupalCreateUser();
  2116. // Assign the role to the user.
  2117. $this->drupalPost('user/' . $account->uid . '/edit', array("roles[$rid]" => $rid), t('Save'));
  2118. $this->assertText(t('The changes have been saved.'));
  2119. $this->assertFieldChecked('edit-roles-' . $rid, 'Role is assigned.');
  2120. $this->userLoadAndCheckRoleAssigned($account, $rid);
  2121. // Remove the role from the user.
  2122. $this->drupalPost('user/' . $account->uid . '/edit', array("roles[$rid]" => FALSE), t('Save'));
  2123. $this->assertText(t('The changes have been saved.'));
  2124. $this->assertNoFieldChecked('edit-roles-' . $rid, 'Role is removed from user.');
  2125. $this->userLoadAndCheckRoleAssigned($account, $rid, FALSE);
  2126. }
  2127. /**
  2128. * Tests that when creating a user the role can be assigned. And that it can
  2129. * be removed again.
  2130. */
  2131. function testCreateUserWithRole() {
  2132. $rid = $this->drupalCreateRole(array('administer content types'));
  2133. // Create a new user and add the role at the same time.
  2134. $edit = array(
  2135. 'name' => $this->randomName(),
  2136. 'mail' => $this->randomName() . '@example.com',
  2137. 'pass[pass1]' => $pass = $this->randomString(),
  2138. 'pass[pass2]' => $pass,
  2139. "roles[$rid]" => $rid,
  2140. );
  2141. $this->drupalPost('admin/people/create', $edit, t('Create new account'));
  2142. $this->assertText(t('Created a new user account for !name.', array('!name' => $edit['name'])));
  2143. // Get the newly added user.
  2144. $account = user_load_by_name($edit['name']);
  2145. $this->drupalGet('user/' . $account->uid . '/edit');
  2146. $this->assertFieldChecked('edit-roles-' . $rid, 'Role is assigned.');
  2147. $this->userLoadAndCheckRoleAssigned($account, $rid);
  2148. // Remove the role again.
  2149. $this->drupalPost('user/' . $account->uid . '/edit', array("roles[$rid]" => FALSE), t('Save'));
  2150. $this->assertText(t('The changes have been saved.'));
  2151. $this->assertNoFieldChecked('edit-roles-' . $rid, 'Role is removed from user.');
  2152. $this->userLoadAndCheckRoleAssigned($account, $rid, FALSE);
  2153. }
  2154. /**
  2155. * Check role on user object.
  2156. *
  2157. * @param object $account
  2158. * The user account to check.
  2159. * @param string $rid
  2160. * The role ID to search for.
  2161. * @param bool $is_assigned
  2162. * (optional) Whether to assert that $rid exists (TRUE) or not (FALSE).
  2163. * Defaults to TRUE.
  2164. */
  2165. private function userLoadAndCheckRoleAssigned($account, $rid, $is_assigned = TRUE) {
  2166. $account = user_load($account->uid, TRUE);
  2167. if ($is_assigned) {
  2168. $this->assertTrue(array_key_exists($rid, $account->roles), 'The role is present in the user object.');
  2169. }
  2170. else {
  2171. $this->assertFalse(array_key_exists($rid, $account->roles), 'The role is not present in the user object.');
  2172. }
  2173. }
  2174. }
  2175. /**
  2176. * Unit test for authmap assignment.
  2177. */
  2178. class UserAuthmapAssignmentTestCase extends DrupalWebTestCase {
  2179. public static function getInfo() {
  2180. return array(
  2181. 'name' => 'Authmap assignment',
  2182. 'description' => 'Tests that users can be assigned and unassigned authmaps.',
  2183. 'group' => 'User'
  2184. );
  2185. }
  2186. /**
  2187. * Test authmap assignment and retrieval.
  2188. */
  2189. function testAuthmapAssignment() {
  2190. $account = $this->drupalCreateUser();
  2191. // Assign authmaps to the user.
  2192. $authmaps = array(
  2193. 'authname_poll' => 'external username one',
  2194. 'authname_book' => 'external username two',
  2195. );
  2196. user_set_authmaps($account, $authmaps);
  2197. // Test for expected authmaps.
  2198. $expected_authmaps = array(
  2199. 'external username one' => array(
  2200. 'poll' => 'external username one',
  2201. ),
  2202. 'external username two' => array(
  2203. 'book' => 'external username two',
  2204. ),
  2205. );
  2206. foreach ($expected_authmaps as $authname => $expected_output) {
  2207. $this->assertIdentical(user_get_authmaps($authname), $expected_output, format_string('Authmap for authname %authname was set correctly.', array('%authname' => $authname)));
  2208. }
  2209. // Remove authmap for module poll, add authmap for module blog.
  2210. $authmaps = array(
  2211. 'authname_poll' => NULL,
  2212. 'authname_blog' => 'external username three',
  2213. );
  2214. user_set_authmaps($account, $authmaps);
  2215. // Assert that external username one does not have authmaps.
  2216. $remove_username = 'external username one';
  2217. unset($expected_authmaps[$remove_username]);
  2218. $this->assertFalse(user_get_authmaps($remove_username), format_string('Authmap for %authname was removed.', array('%authname' => $remove_username)));
  2219. // Assert that a new authmap was created for external username three, and
  2220. // existing authmaps for external username two were unchanged.
  2221. $expected_authmaps['external username three'] = array('blog' => 'external username three');
  2222. foreach ($expected_authmaps as $authname => $expected_output) {
  2223. $this->assertIdentical(user_get_authmaps($authname), $expected_output, format_string('Authmap for authname %authname was set correctly.', array('%authname' => $authname)));
  2224. }
  2225. }
  2226. }
  2227. /**
  2228. * Tests user_validate_current_pass on a custom form.
  2229. */
  2230. class UserValidateCurrentPassCustomForm extends DrupalWebTestCase {
  2231. public static function getInfo() {
  2232. return array(
  2233. 'name' => 'User validate current pass custom form',
  2234. 'description' => 'Test that user_validate_current_pass is usable on a custom form.',
  2235. 'group' => 'User',
  2236. );
  2237. }
  2238. /**
  2239. * User with permission to view content.
  2240. */
  2241. protected $accessUser;
  2242. /**
  2243. * User permission to administer users.
  2244. */
  2245. protected $adminUser;
  2246. function setUp() {
  2247. parent::setUp('user_form_test');
  2248. // Create two users
  2249. $this->accessUser = $this->drupalCreateUser(array('access content'));
  2250. $this->adminUser = $this->drupalCreateUser(array('administer users'));
  2251. }
  2252. /**
  2253. * Tests that user_validate_current_pass can be reused on a custom form.
  2254. */
  2255. function testUserValidateCurrentPassCustomForm() {
  2256. $this->drupalLogin($this->adminUser);
  2257. // Submit the custom form with the admin user using the access user's password.
  2258. $edit = array();
  2259. $edit['user_form_test_field'] = $this->accessUser->name;
  2260. $edit['current_pass'] = $this->accessUser->pass_raw;
  2261. $this->drupalPost('user_form_test_current_password/' . $this->accessUser->uid, $edit, t('Test'));
  2262. $this->assertText(t('The password has been validated and the form submitted successfully.'));
  2263. }
  2264. }