system.test 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904
  1. <?php
  2. /**
  3. * @file
  4. * Tests for system.module.
  5. */
  6. /**
  7. * Helper class for module test cases.
  8. */
  9. class ModuleTestCase extends DrupalWebTestCase {
  10. protected $admin_user;
  11. function setUp() {
  12. parent::setUp('system_test');
  13. $this->admin_user = $this->drupalCreateUser(array('access administration pages', 'administer modules'));
  14. $this->drupalLogin($this->admin_user);
  15. }
  16. /**
  17. * Assert there are tables that begin with the specified base table name.
  18. *
  19. * @param $base_table
  20. * Beginning of table name to look for.
  21. * @param $count
  22. * (optional) Whether or not to assert that there are tables that match the
  23. * specified base table. Defaults to TRUE.
  24. */
  25. function assertTableCount($base_table, $count = TRUE) {
  26. $tables = db_find_tables(Database::getConnection()->prefixTables('{' . $base_table . '}') . '%');
  27. if ($count) {
  28. return $this->assertTrue($tables, format_string('Tables matching "@base_table" found.', array('@base_table' => $base_table)));
  29. }
  30. return $this->assertFalse($tables, format_string('Tables matching "@base_table" not found.', array('@base_table' => $base_table)));
  31. }
  32. /**
  33. * Assert that all tables defined in a module's hook_schema() exist.
  34. *
  35. * @param $module
  36. * The name of the module.
  37. */
  38. function assertModuleTablesExist($module) {
  39. $tables = array_keys(drupal_get_schema_unprocessed($module));
  40. $tables_exist = TRUE;
  41. foreach ($tables as $table) {
  42. if (!db_table_exists($table)) {
  43. $tables_exist = FALSE;
  44. }
  45. }
  46. return $this->assertTrue($tables_exist, format_string('All database tables defined by the @module module exist.', array('@module' => $module)));
  47. }
  48. /**
  49. * Assert that none of the tables defined in a module's hook_schema() exist.
  50. *
  51. * @param $module
  52. * The name of the module.
  53. */
  54. function assertModuleTablesDoNotExist($module) {
  55. $tables = array_keys(drupal_get_schema_unprocessed($module));
  56. $tables_exist = FALSE;
  57. foreach ($tables as $table) {
  58. if (db_table_exists($table)) {
  59. $tables_exist = TRUE;
  60. }
  61. }
  62. return $this->assertFalse($tables_exist, format_string('None of the database tables defined by the @module module exist.', array('@module' => $module)));
  63. }
  64. /**
  65. * Assert the list of modules are enabled or disabled.
  66. *
  67. * @param $modules
  68. * Module list to check.
  69. * @param $enabled
  70. * Expected module state.
  71. */
  72. function assertModules(array $modules, $enabled) {
  73. module_list(TRUE);
  74. foreach ($modules as $module) {
  75. if ($enabled) {
  76. $message = 'Module "@module" is enabled.';
  77. }
  78. else {
  79. $message = 'Module "@module" is not enabled.';
  80. }
  81. $this->assertEqual(module_exists($module), $enabled, format_string($message, array('@module' => $module)));
  82. }
  83. }
  84. /**
  85. * Verify a log entry was entered for a module's status change.
  86. * Called in the same way of the expected original watchdog() execution.
  87. *
  88. * @param $type
  89. * The category to which this message belongs.
  90. * @param $message
  91. * The message to store in the log. Keep $message translatable
  92. * by not concatenating dynamic values into it! Variables in the
  93. * message should be added by using placeholder strings alongside
  94. * the variables argument to declare the value of the placeholders.
  95. * See t() for documentation on how $message and $variables interact.
  96. * @param $variables
  97. * Array of variables to replace in the message on display or
  98. * NULL if message is already translated or not possible to
  99. * translate.
  100. * @param $severity
  101. * The severity of the message, as per RFC 3164.
  102. * @param $link
  103. * A link to associate with the message.
  104. */
  105. function assertLogMessage($type, $message, $variables = array(), $severity = WATCHDOG_NOTICE, $link = '') {
  106. $count = db_select('watchdog', 'w')
  107. ->condition('type', $type)
  108. ->condition('message', $message)
  109. ->condition('variables', serialize($variables))
  110. ->condition('severity', $severity)
  111. ->condition('link', $link)
  112. ->countQuery()
  113. ->execute()
  114. ->fetchField();
  115. $this->assertTrue($count > 0, format_string('watchdog table contains @count rows for @message', array('@count' => $count, '@message' => $message)));
  116. }
  117. }
  118. /**
  119. * Test module enabling/disabling functionality.
  120. */
  121. class EnableDisableTestCase extends ModuleTestCase {
  122. protected $profile = 'testing';
  123. public static function getInfo() {
  124. return array(
  125. 'name' => 'Enable/disable modules',
  126. 'description' => 'Enable/disable core module and confirm table creation/deletion.',
  127. 'group' => 'Module',
  128. );
  129. }
  130. /**
  131. * Test that all core modules can be enabled, disabled and uninstalled.
  132. */
  133. function testEnableDisable() {
  134. // Try to enable, disable and uninstall all core modules, unless they are
  135. // hidden or required.
  136. $modules = system_rebuild_module_data();
  137. foreach ($modules as $name => $module) {
  138. if ($module->info['package'] != 'Core' || !empty($module->info['hidden']) || !empty($module->info['required'])) {
  139. unset($modules[$name]);
  140. }
  141. }
  142. $this->assertTrue(count($modules), format_string('Found @count core modules that we can try to enable in this test.', array('@count' => count($modules))));
  143. // Enable the dblog module first, since we will be asserting the presence
  144. // of log messages throughout the test.
  145. if (isset($modules['dblog'])) {
  146. $modules = array('dblog' => $modules['dblog']) + $modules;
  147. }
  148. // Set a variable so that the hook implementations in system_test.module
  149. // will display messages via drupal_set_message().
  150. variable_set('test_verbose_module_hooks', TRUE);
  151. // Throughout this test, some modules may be automatically enabled (due to
  152. // dependencies). We'll keep track of them in an array, so we can handle
  153. // them separately.
  154. $automatically_enabled = array();
  155. // Go through each module in the list and try to enable it (unless it was
  156. // already enabled automatically due to a dependency).
  157. foreach ($modules as $name => $module) {
  158. if (empty($automatically_enabled[$name])) {
  159. // Start a list of modules that we expect to be enabled this time.
  160. $modules_to_enable = array($name);
  161. // Find out if the module has any dependencies that aren't enabled yet;
  162. // if so, add them to the list of modules we expect to be automatically
  163. // enabled.
  164. foreach (array_keys($module->requires) as $dependency) {
  165. if (isset($modules[$dependency]) && empty($automatically_enabled[$dependency])) {
  166. $modules_to_enable[] = $dependency;
  167. $automatically_enabled[$dependency] = TRUE;
  168. }
  169. }
  170. // Check that each module is not yet enabled and does not have any
  171. // database tables yet.
  172. foreach ($modules_to_enable as $module_to_enable) {
  173. $this->assertModules(array($module_to_enable), FALSE);
  174. $this->assertModuleTablesDoNotExist($module_to_enable);
  175. }
  176. // Install and enable the module.
  177. $edit = array();
  178. $edit['modules[Core][' . $name . '][enable]'] = $name;
  179. $this->drupalPost('admin/modules', $edit, t('Save configuration'));
  180. // Handle the case where modules were installed along with this one and
  181. // where we therefore hit a confirmation screen.
  182. if (count($modules_to_enable) > 1) {
  183. $this->drupalPost(NULL, array(), t('Continue'));
  184. }
  185. $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
  186. // Check that hook_modules_installed() and hook_modules_enabled() were
  187. // invoked with the expected list of modules, that each module's
  188. // database tables now exist, and that appropriate messages appear in
  189. // the logs.
  190. foreach ($modules_to_enable as $module_to_enable) {
  191. $this->assertText(t('hook_modules_installed fired for @module', array('@module' => $module_to_enable)));
  192. $this->assertText(t('hook_modules_enabled fired for @module', array('@module' => $module_to_enable)));
  193. $this->assertModules(array($module_to_enable), TRUE);
  194. $this->assertModuleTablesExist($module_to_enable);
  195. $this->assertLogMessage('system', "%module module installed.", array('%module' => $module_to_enable), WATCHDOG_INFO);
  196. $this->assertLogMessage('system', "%module module enabled.", array('%module' => $module_to_enable), WATCHDOG_INFO);
  197. }
  198. // Disable and uninstall the original module, and check appropriate
  199. // hooks, tables, and log messages. (Later, we'll go back and do the
  200. // same thing for modules that were enabled automatically.) Skip this
  201. // for the dblog module, because that is needed for the test; we'll go
  202. // back and do that one at the end also.
  203. if ($name != 'dblog') {
  204. $this->assertSuccessfulDisableAndUninstall($name);
  205. }
  206. }
  207. }
  208. // Go through all modules that were automatically enabled, and try to
  209. // disable and uninstall them one by one.
  210. while (!empty($automatically_enabled)) {
  211. $initial_count = count($automatically_enabled);
  212. foreach (array_keys($automatically_enabled) as $name) {
  213. // If the module can't be disabled due to dependencies, skip it and try
  214. // again the next time. Otherwise, try to disable it.
  215. $this->drupalGet('admin/modules');
  216. $disabled_checkbox = $this->xpath('//input[@type="checkbox" and @disabled="disabled" and @name="modules[Core][' . $name . '][enable]"]');
  217. if (empty($disabled_checkbox) && $name != 'dblog') {
  218. unset($automatically_enabled[$name]);
  219. $this->assertSuccessfulDisableAndUninstall($name);
  220. }
  221. }
  222. $final_count = count($automatically_enabled);
  223. // If all checkboxes were disabled, something is really wrong with the
  224. // test. Throw a failure and avoid an infinite loop.
  225. if ($initial_count == $final_count) {
  226. $this->fail(t('Remaining modules could not be disabled.'));
  227. break;
  228. }
  229. }
  230. // Disable and uninstall the dblog module last, since we needed it for
  231. // assertions in all the above tests.
  232. if (isset($modules['dblog'])) {
  233. $this->assertSuccessfulDisableAndUninstall('dblog');
  234. }
  235. // Now that all modules have been tested, go back and try to enable them
  236. // all again at once. This tests two things:
  237. // - That each module can be successfully enabled again after being
  238. // uninstalled.
  239. // - That enabling more than one module at the same time does not lead to
  240. // any errors.
  241. $edit = array();
  242. foreach (array_keys($modules) as $name) {
  243. $edit['modules[Core][' . $name . '][enable]'] = $name;
  244. }
  245. $this->drupalPost('admin/modules', $edit, t('Save configuration'));
  246. $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
  247. }
  248. /**
  249. * Ensures entity info cache is updated after changes.
  250. */
  251. function testEntityInfoChanges() {
  252. module_enable(array('entity_cache_test'));
  253. $entity_info = entity_get_info();
  254. $this->assertTrue(isset($entity_info['entity_cache_test']), 'Test entity type found.');
  255. // Change the label of the test entity type and make sure changes appear
  256. // after flushing caches.
  257. variable_set('entity_cache_test_label', 'New label.');
  258. drupal_flush_all_caches();
  259. $info = entity_get_info('entity_cache_test');
  260. $this->assertEqual($info['label'], 'New label.', 'New label appears in entity info.');
  261. // Disable the providing module and make sure the entity type is gone.
  262. module_disable(array('entity_cache_test', 'entity_cache_test_dependency'));
  263. $entity_info = entity_get_info();
  264. $this->assertFalse(isset($entity_info['entity_cache_test']), 'Entity type of the providing module is gone.');
  265. }
  266. /**
  267. * Tests entity info cache after enabling a module with a dependency on an entity providing module.
  268. *
  269. * @see entity_cache_test_watchdog()
  270. */
  271. function testEntityInfoCacheWatchdog() {
  272. module_enable(array('entity_cache_test'));
  273. $info = variable_get('entity_cache_test');
  274. $this->assertEqual($info['label'], 'Entity Cache Test', 'Entity info label is correct.');
  275. $this->assertEqual($info['controller class'], 'DrupalDefaultEntityController', 'Entity controller class info is correct.');
  276. }
  277. /**
  278. * Disables and uninstalls a module and asserts that it was done correctly.
  279. *
  280. * @param $module
  281. * The name of the module to disable and uninstall.
  282. */
  283. function assertSuccessfulDisableAndUninstall($module) {
  284. // Disable the module.
  285. $edit = array();
  286. $edit['modules[Core][' . $module . '][enable]'] = FALSE;
  287. $this->drupalPost('admin/modules', $edit, t('Save configuration'));
  288. $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
  289. $this->assertModules(array($module), FALSE);
  290. // Check that the appropriate hook was fired and the appropriate log
  291. // message appears.
  292. $this->assertText(t('hook_modules_disabled fired for @module', array('@module' => $module)));
  293. $this->assertLogMessage('system', "%module module disabled.", array('%module' => $module), WATCHDOG_INFO);
  294. // Check that the module's database tables still exist.
  295. $this->assertModuleTablesExist($module);
  296. // Uninstall the module.
  297. $edit = array();
  298. $edit['uninstall[' . $module . ']'] = $module;
  299. $this->drupalPost('admin/modules/uninstall', $edit, t('Uninstall'));
  300. $this->drupalPost(NULL, NULL, t('Uninstall'));
  301. $this->assertText(t('The selected modules have been uninstalled.'), 'Modules status has been updated.');
  302. $this->assertModules(array($module), FALSE);
  303. // Check that the appropriate hook was fired and the appropriate log
  304. // message appears. (But don't check for the log message if the dblog
  305. // module was just uninstalled, since the {watchdog} table won't be there
  306. // anymore.)
  307. $this->assertText(t('hook_modules_uninstalled fired for @module', array('@module' => $module)));
  308. if ($module != 'dblog') {
  309. $this->assertLogMessage('system', "%module module uninstalled.", array('%module' => $module), WATCHDOG_INFO);
  310. }
  311. // Check that the module's database tables no longer exist.
  312. $this->assertModuleTablesDoNotExist($module);
  313. }
  314. }
  315. /**
  316. * Tests failure of hook_requirements('install').
  317. */
  318. class HookRequirementsTestCase extends ModuleTestCase {
  319. public static function getInfo() {
  320. return array(
  321. 'name' => 'Requirements hook failure',
  322. 'description' => "Attempts enabling a module that fails hook_requirements('install').",
  323. 'group' => 'Module',
  324. );
  325. }
  326. /**
  327. * Assert that a module cannot be installed if it fails hook_requirements().
  328. */
  329. function testHookRequirementsFailure() {
  330. $this->assertModules(array('requirements1_test'), FALSE);
  331. // Attempt to install the requirements1_test module.
  332. $edit = array();
  333. $edit['modules[Testing][requirements1_test][enable]'] = 'requirements1_test';
  334. $this->drupalPost('admin/modules', $edit, t('Save configuration'));
  335. // Makes sure the module was NOT installed.
  336. $this->assertText(t('Requirements 1 Test failed requirements'), 'Modules status has been updated.');
  337. $this->assertModules(array('requirements1_test'), FALSE);
  338. }
  339. }
  340. /**
  341. * Test module dependency functionality.
  342. */
  343. class ModuleDependencyTestCase extends ModuleTestCase {
  344. public static function getInfo() {
  345. return array(
  346. 'name' => 'Module dependencies',
  347. 'description' => 'Enable module without dependency enabled.',
  348. 'group' => 'Module',
  349. );
  350. }
  351. /**
  352. * Attempt to enable translation module without locale enabled.
  353. */
  354. function testEnableWithoutDependency() {
  355. // Attempt to enable content translation without locale enabled.
  356. $edit = array();
  357. $edit['modules[Core][translation][enable]'] = 'translation';
  358. $this->drupalPost('admin/modules', $edit, t('Save configuration'));
  359. $this->assertText(t('Some required modules must be enabled'), 'Dependency required.');
  360. $this->assertModules(array('translation', 'locale'), FALSE);
  361. // Assert that the locale tables weren't enabled.
  362. $this->assertTableCount('languages', FALSE);
  363. $this->assertTableCount('locale', FALSE);
  364. $this->drupalPost(NULL, NULL, t('Continue'));
  365. $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
  366. $this->assertModules(array('translation', 'locale'), TRUE);
  367. // Assert that the locale tables were enabled.
  368. $this->assertTableCount('languages', TRUE);
  369. $this->assertTableCount('locale', TRUE);
  370. }
  371. /**
  372. * Attempt to enable a module with a missing dependency.
  373. */
  374. function testMissingModules() {
  375. // Test that the system_dependencies_test module is marked
  376. // as missing a dependency.
  377. $this->drupalGet('admin/modules');
  378. $this->assertRaw(t('@module (<span class="admin-missing">missing</span>)', array('@module' => drupal_ucfirst('_missing_dependency'))), 'A module with missing dependencies is marked as such.');
  379. $checkbox = $this->xpath('//input[@type="checkbox" and @disabled="disabled" and @name="modules[Testing][system_dependencies_test][enable]"]');
  380. $this->assert(count($checkbox) == 1, 'Checkbox for the module is disabled.');
  381. // Force enable the system_dependencies_test module.
  382. module_enable(array('system_dependencies_test'), FALSE);
  383. // Verify that the module is forced to be disabled when submitting
  384. // the module page.
  385. $this->drupalPost('admin/modules', array(), t('Save configuration'));
  386. $this->assertText(t('The @module module is missing, so the following module will be disabled: @depends.', array('@module' => '_missing_dependency', '@depends' => 'system_dependencies_test')), 'The module missing dependencies will be disabled.');
  387. // Confirm.
  388. $this->drupalPost(NULL, NULL, t('Continue'));
  389. // Verify that the module has been disabled.
  390. $this->assertModules(array('system_dependencies_test'), FALSE);
  391. }
  392. /**
  393. * Tests enabling a module that depends on an incompatible version of a module.
  394. */
  395. function testIncompatibleModuleVersionDependency() {
  396. // Test that the system_incompatible_module_version_dependencies_test is
  397. // marked as having an incompatible dependency.
  398. $this->drupalGet('admin/modules');
  399. $this->assertRaw(t('@module (<span class="admin-missing">incompatible with</span> version @version)', array(
  400. '@module' => 'System incompatible module version test (>2.0)',
  401. '@version' => '1.0',
  402. )), 'A module that depends on an incompatible version of a module is marked as such.');
  403. $checkbox = $this->xpath('//input[@type="checkbox" and @disabled="disabled" and @name="modules[Testing][system_incompatible_module_version_dependencies_test][enable]"]');
  404. $this->assert(count($checkbox) == 1, 'Checkbox for the module is disabled.');
  405. }
  406. /**
  407. * Tests enabling a module that depends on a module with an incompatible core version.
  408. */
  409. function testIncompatibleCoreVersionDependency() {
  410. // Test that the system_incompatible_core_version_dependencies_test is
  411. // marked as having an incompatible dependency.
  412. $this->drupalGet('admin/modules');
  413. $this->assertRaw(t('@module (<span class="admin-missing">incompatible with</span> this version of Drupal core)', array(
  414. '@module' => 'System incompatible core version test',
  415. )), 'A module that depends on a module with an incompatible core version is marked as such.');
  416. $checkbox = $this->xpath('//input[@type="checkbox" and @disabled="disabled" and @name="modules[Testing][system_incompatible_core_version_dependencies_test][enable]"]');
  417. $this->assert(count($checkbox) == 1, 'Checkbox for the module is disabled.');
  418. }
  419. /**
  420. * Tests enabling a module that depends on a module which fails hook_requirements().
  421. */
  422. function testEnableRequirementsFailureDependency() {
  423. $this->assertModules(array('requirements1_test'), FALSE);
  424. $this->assertModules(array('requirements2_test'), FALSE);
  425. // Attempt to install both modules at the same time.
  426. $edit = array();
  427. $edit['modules[Testing][requirements1_test][enable]'] = 'requirements1_test';
  428. $edit['modules[Testing][requirements2_test][enable]'] = 'requirements2_test';
  429. $this->drupalPost('admin/modules', $edit, t('Save configuration'));
  430. // Makes sure the modules were NOT installed.
  431. $this->assertText(t('Requirements 1 Test failed requirements'), 'Modules status has been updated.');
  432. $this->assertModules(array('requirements1_test'), FALSE);
  433. $this->assertModules(array('requirements2_test'), FALSE);
  434. // Makes sure that already enabled modules the failing modules depend on
  435. // were not disabled.
  436. $this->assertModules(array('comment'), TRUE);
  437. }
  438. /**
  439. * Tests that module dependencies are enabled in the correct order via the
  440. * UI. Dependencies should be enabled before their dependents.
  441. */
  442. function testModuleEnableOrder() {
  443. module_enable(array('module_test'), FALSE);
  444. $this->resetAll();
  445. $this->assertModules(array('module_test'), TRUE);
  446. variable_set('dependency_test', 'dependency');
  447. // module_test creates a dependency chain: forum depends on poll, which
  448. // depends on php. The correct enable order is, php, poll, forum.
  449. $expected_order = array('php', 'poll', 'forum');
  450. // Enable the modules through the UI, verifying that the dependency chain
  451. // is correct.
  452. $edit = array();
  453. $edit['modules[Core][forum][enable]'] = 'forum';
  454. $this->drupalPost('admin/modules', $edit, t('Save configuration'));
  455. $this->assertModules(array('forum'), FALSE);
  456. $this->assertText(t('You must enable the Poll, PHP filter modules to install Forum.'), t('Dependency chain created.'));
  457. $edit['modules[Core][poll][enable]'] = 'poll';
  458. $edit['modules[Core][php][enable]'] = 'php';
  459. $this->drupalPost('admin/modules', $edit, t('Save configuration'));
  460. $this->assertModules(array('forum', 'poll', 'php'), TRUE);
  461. // Check the actual order which is saved by module_test_modules_enabled().
  462. $this->assertIdentical(variable_get('test_module_enable_order', FALSE), $expected_order, t('Modules enabled in the correct order.'));
  463. }
  464. /**
  465. * Tests attempting to uninstall a module that has installed dependents.
  466. */
  467. function testUninstallDependents() {
  468. // Enable the forum module.
  469. $edit = array('modules[Core][forum][enable]' => 'forum');
  470. $this->drupalPost('admin/modules', $edit, t('Save configuration'));
  471. $this->assertModules(array('forum'), TRUE);
  472. // Disable forum and comment. Both should now be installed but disabled.
  473. $edit = array('modules[Core][forum][enable]' => FALSE);
  474. $this->drupalPost('admin/modules', $edit, t('Save configuration'));
  475. $this->assertModules(array('forum'), FALSE);
  476. $edit = array('modules[Core][comment][enable]' => FALSE);
  477. $this->drupalPost('admin/modules', $edit, t('Save configuration'));
  478. $this->assertModules(array('comment'), FALSE);
  479. // Check that the taxonomy module cannot be uninstalled.
  480. $this->drupalGet('admin/modules/uninstall');
  481. $checkbox = $this->xpath('//input[@type="checkbox" and @disabled="disabled" and @name="uninstall[comment]"]');
  482. $this->assert(count($checkbox) == 1, 'Checkbox for uninstalling the comment module is disabled.');
  483. // Uninstall the forum module, and check that taxonomy now can also be
  484. // uninstalled.
  485. $edit = array('uninstall[forum]' => 'forum');
  486. $this->drupalPost('admin/modules/uninstall', $edit, t('Uninstall'));
  487. $this->drupalPost(NULL, NULL, t('Uninstall'));
  488. $this->assertText(t('The selected modules have been uninstalled.'), 'Modules status has been updated.');
  489. $edit = array('uninstall[comment]' => 'comment');
  490. $this->drupalPost('admin/modules/uninstall', $edit, t('Uninstall'));
  491. $this->drupalPost(NULL, NULL, t('Uninstall'));
  492. $this->assertText(t('The selected modules have been uninstalled.'), 'Modules status has been updated.');
  493. }
  494. /**
  495. * Tests whether the correct module metadata is returned.
  496. */
  497. function testModuleMetaData() {
  498. // Generate the list of available modules.
  499. $modules = system_rebuild_module_data();
  500. // Check that the mtime field exists for the system module.
  501. $this->assertTrue(!empty($modules['system']->info['mtime']), 'The system.info file modification time field is present.');
  502. // Use 0 if mtime isn't present, to avoid an array index notice.
  503. $test_mtime = !empty($modules['system']->info['mtime']) ? $modules['system']->info['mtime'] : 0;
  504. // Ensure the mtime field contains a number that is greater than zero.
  505. $this->assertTrue(is_numeric($test_mtime) && ($test_mtime > 0), 'The system.info file modification time field contains a timestamp.');
  506. }
  507. /**
  508. * Tests whether the correct theme metadata is returned.
  509. */
  510. function testThemeMetaData() {
  511. // Generate the list of available themes.
  512. $themes = system_rebuild_theme_data();
  513. // Check that the mtime field exists for the bartik theme.
  514. $this->assertTrue(!empty($themes['bartik']->info['mtime']), 'The bartik.info file modification time field is present.');
  515. // Use 0 if mtime isn't present, to avoid an array index notice.
  516. $test_mtime = !empty($themes['bartik']->info['mtime']) ? $themes['bartik']->info['mtime'] : 0;
  517. // Ensure the mtime field contains a number that is greater than zero.
  518. $this->assertTrue(is_numeric($test_mtime) && ($test_mtime > 0), 'The bartik.info file modification time field contains a timestamp.');
  519. }
  520. }
  521. /**
  522. * Test module dependency on specific versions.
  523. */
  524. class ModuleVersionTestCase extends ModuleTestCase {
  525. public static function getInfo() {
  526. return array(
  527. 'name' => 'Module versions',
  528. 'description' => 'Check module version dependencies.',
  529. 'group' => 'Module',
  530. );
  531. }
  532. function setUp() {
  533. parent::setUp('module_test');
  534. }
  535. /**
  536. * Test version dependencies.
  537. */
  538. function testModuleVersions() {
  539. $dependencies = array(
  540. // Alternating between being compatible and incompatible with 7.x-2.4-beta3.
  541. // The first is always a compatible.
  542. 'common_test',
  543. // Branch incompatibility.
  544. 'common_test (1.x)',
  545. // Branch compatibility.
  546. 'common_test (2.x)',
  547. // Another branch incompatibility.
  548. 'common_test (>2.x)',
  549. // Another branch compatibility.
  550. 'common_test (<=2.x)',
  551. // Another branch incompatibility.
  552. 'common_test (<2.x)',
  553. // Another branch compatibility.
  554. 'common_test (>=2.x)',
  555. // Nonsense, misses a dash. Incompatible with everything.
  556. 'common_test (=7.x2.x, >=2.4)',
  557. // Core version is optional. Compatible.
  558. 'common_test (=7.x-2.x, >=2.4-alpha2)',
  559. // Test !=, explicitly incompatible.
  560. 'common_test (=2.x, !=2.4-beta3)',
  561. // Three operations. Compatible.
  562. 'common_test (=2.x, !=2.3, <2.5)',
  563. // Testing extra version. Incompatible.
  564. 'common_test (<=2.4-beta2)',
  565. // Testing extra version. Compatible.
  566. 'common_test (>2.4-beta2)',
  567. // Testing extra version. Incompatible.
  568. 'common_test (>2.4-rc0)',
  569. );
  570. variable_set('dependencies', $dependencies);
  571. $n = count($dependencies);
  572. for ($i = 0; $i < $n; $i++) {
  573. $this->drupalGet('admin/modules');
  574. $checkbox = $this->xpath('//input[@id="edit-modules-testing-module-test-enable"]');
  575. $this->assertEqual(!empty($checkbox[0]['disabled']), $i % 2, $dependencies[$i]);
  576. }
  577. }
  578. }
  579. /**
  580. * Test required modules functionality.
  581. */
  582. class ModuleRequiredTestCase extends ModuleTestCase {
  583. public static function getInfo() {
  584. return array(
  585. 'name' => 'Required modules',
  586. 'description' => 'Attempt disabling of required modules.',
  587. 'group' => 'Module',
  588. );
  589. }
  590. /**
  591. * Assert that core required modules cannot be disabled.
  592. */
  593. function testDisableRequired() {
  594. $module_info = system_get_info('module');
  595. $this->drupalGet('admin/modules');
  596. foreach ($module_info as $module => $info) {
  597. // Check to make sure the checkbox for each required module is disabled
  598. // and checked (or absent from the page if the module is also hidden).
  599. if (!empty($info['required'])) {
  600. $field_name = "modules[{$info['package']}][$module][enable]";
  601. if (empty($info['hidden'])) {
  602. $this->assertFieldByXPath("//input[@name='$field_name' and @disabled='disabled' and @checked='checked']", '', format_string('Field @name was disabled and checked.', array('@name' => $field_name)));
  603. }
  604. else {
  605. $this->assertNoFieldByName($field_name);
  606. }
  607. }
  608. }
  609. }
  610. }
  611. class IPAddressBlockingTestCase extends DrupalWebTestCase {
  612. protected $blocking_user;
  613. /**
  614. * Implement getInfo().
  615. */
  616. public static function getInfo() {
  617. return array(
  618. 'name' => 'IP address blocking',
  619. 'description' => 'Test IP address blocking.',
  620. 'group' => 'System'
  621. );
  622. }
  623. /**
  624. * Implement setUp().
  625. */
  626. function setUp() {
  627. parent::setUp();
  628. // Create user.
  629. $this->blocking_user = $this->drupalCreateUser(array('block IP addresses'));
  630. $this->drupalLogin($this->blocking_user);
  631. }
  632. /**
  633. * Test a variety of user input to confirm correct validation and saving of data.
  634. */
  635. function testIPAddressValidation() {
  636. $this->drupalGet('admin/config/people/ip-blocking');
  637. // Block a valid IP address.
  638. $edit = array();
  639. $edit['ip'] = '192.168.1.1';
  640. $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
  641. $ip = db_query("SELECT iid from {blocked_ips} WHERE ip = :ip", array(':ip' => $edit['ip']))->fetchField();
  642. $this->assertTrue($ip, t('IP address found in database.'));
  643. $this->assertRaw(t('The IP address %ip has been blocked.', array('%ip' => $edit['ip'])), t('IP address was blocked.'));
  644. // Try to block an IP address that's already blocked.
  645. $edit = array();
  646. $edit['ip'] = '192.168.1.1';
  647. $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
  648. $this->assertText(t('This IP address is already blocked.'));
  649. // Try to block a reserved IP address.
  650. $edit = array();
  651. $edit['ip'] = '255.255.255.255';
  652. $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
  653. $this->assertText(t('Enter a valid IP address.'));
  654. // Try to block a reserved IP address.
  655. $edit = array();
  656. $edit['ip'] = 'test.example.com';
  657. $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
  658. $this->assertText(t('Enter a valid IP address.'));
  659. // Submit an empty form.
  660. $edit = array();
  661. $edit['ip'] = '';
  662. $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
  663. $this->assertText(t('Enter a valid IP address.'));
  664. // Pass an IP address as a URL parameter and submit it.
  665. $submit_ip = '1.2.3.4';
  666. $this->drupalPost('admin/config/people/ip-blocking/' . $submit_ip, NULL, t('Add'));
  667. $ip = db_query("SELECT iid from {blocked_ips} WHERE ip = :ip", array(':ip' => $submit_ip))->fetchField();
  668. $this->assertTrue($ip, t('IP address found in database'));
  669. $this->assertRaw(t('The IP address %ip has been blocked.', array('%ip' => $submit_ip)), t('IP address was blocked.'));
  670. // Submit your own IP address. This fails, although it works when testing manually.
  671. // TODO: on some systems this test fails due to a bug or inconsistency in cURL.
  672. // $edit = array();
  673. // $edit['ip'] = ip_address();
  674. // $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Save'));
  675. // $this->assertText(t('You may not block your own IP address.'));
  676. }
  677. }
  678. class CronRunTestCase extends DrupalWebTestCase {
  679. /**
  680. * Implement getInfo().
  681. */
  682. public static function getInfo() {
  683. return array(
  684. 'name' => 'Cron run',
  685. 'description' => 'Test cron run.',
  686. 'group' => 'System'
  687. );
  688. }
  689. function setUp() {
  690. parent::setUp(array('common_test', 'common_test_cron_helper'));
  691. }
  692. /**
  693. * Test cron runs.
  694. */
  695. function testCronRun() {
  696. global $base_url;
  697. // Run cron anonymously without any cron key.
  698. $this->drupalGet($base_url . '/cron.php', array('external' => TRUE));
  699. $this->assertResponse(403);
  700. // Run cron anonymously with a random cron key.
  701. $key = $this->randomName(16);
  702. $this->drupalGet($base_url . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => $key)));
  703. $this->assertResponse(403);
  704. // Run cron anonymously with the valid cron key.
  705. $key = variable_get('cron_key', 'drupal');
  706. $this->drupalGet($base_url . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => $key)));
  707. $this->assertResponse(200);
  708. }
  709. /**
  710. * Ensure that the automatic cron run feature is working.
  711. *
  712. * In these tests we do not use REQUEST_TIME to track start time, because we
  713. * need the exact time when cron is triggered.
  714. */
  715. function testAutomaticCron() {
  716. // Ensure cron does not run when the cron threshold is enabled and was
  717. // not passed.
  718. $cron_last = time();
  719. $cron_safe_threshold = 100;
  720. variable_set('cron_last', $cron_last);
  721. variable_set('cron_safe_threshold', $cron_safe_threshold);
  722. $this->drupalGet('');
  723. $this->assertTrue($cron_last == variable_get('cron_last', NULL), 'Cron does not run when the cron threshold is not passed.');
  724. // Test if cron runs when the cron threshold was passed.
  725. $cron_last = time() - 200;
  726. variable_set('cron_last', $cron_last);
  727. $this->drupalGet('');
  728. sleep(1);
  729. $this->assertTrue($cron_last < variable_get('cron_last', NULL), 'Cron runs when the cron threshold is passed.');
  730. // Disable the cron threshold through the interface.
  731. $admin_user = $this->drupalCreateUser(array('administer site configuration'));
  732. $this->drupalLogin($admin_user);
  733. $this->drupalPost('admin/config/system/cron', array('cron_safe_threshold' => 0), t('Save configuration'));
  734. $this->assertText(t('The configuration options have been saved.'));
  735. $this->drupalLogout();
  736. // Test if cron does not run when the cron threshold is disabled.
  737. $cron_last = time() - 200;
  738. variable_set('cron_last', $cron_last);
  739. $this->drupalGet('');
  740. $this->assertTrue($cron_last == variable_get('cron_last', NULL), 'Cron does not run when the cron threshold is disabled.');
  741. }
  742. /**
  743. * Ensure that temporary files are removed.
  744. *
  745. * Create files for all the possible combinations of age and status. We are
  746. * using UPDATE statements rather than file_save() because it would set the
  747. * timestamp.
  748. */
  749. function testTempFileCleanup() {
  750. // Temporary file that is older than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
  751. $temp_old = file_save_data('');
  752. db_update('file_managed')
  753. ->fields(array(
  754. 'status' => 0,
  755. 'timestamp' => 1,
  756. ))
  757. ->condition('fid', $temp_old->fid)
  758. ->execute();
  759. $this->assertTrue(file_exists($temp_old->uri), 'Old temp file was created correctly.');
  760. // Temporary file that is less than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
  761. $temp_new = file_save_data('');
  762. db_update('file_managed')
  763. ->fields(array('status' => 0))
  764. ->condition('fid', $temp_new->fid)
  765. ->execute();
  766. $this->assertTrue(file_exists($temp_new->uri), 'New temp file was created correctly.');
  767. // Permanent file that is older than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
  768. $perm_old = file_save_data('');
  769. db_update('file_managed')
  770. ->fields(array('timestamp' => 1))
  771. ->condition('fid', $temp_old->fid)
  772. ->execute();
  773. $this->assertTrue(file_exists($perm_old->uri), 'Old permanent file was created correctly.');
  774. // Permanent file that is newer than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
  775. $perm_new = file_save_data('');
  776. $this->assertTrue(file_exists($perm_new->uri), 'New permanent file was created correctly.');
  777. // Run cron and then ensure that only the old, temp file was deleted.
  778. $this->cronRun();
  779. $this->assertFalse(file_exists($temp_old->uri), 'Old temp file was correctly removed.');
  780. $this->assertTrue(file_exists($temp_new->uri), 'New temp file was correctly ignored.');
  781. $this->assertTrue(file_exists($perm_old->uri), 'Old permanent file was correctly ignored.');
  782. $this->assertTrue(file_exists($perm_new->uri), 'New permanent file was correctly ignored.');
  783. }
  784. /**
  785. * Make sure exceptions thrown on hook_cron() don't affect other modules.
  786. */
  787. function testCronExceptions() {
  788. variable_del('common_test_cron');
  789. // The common_test module throws an exception. If it isn't caught, the tests
  790. // won't finish successfully.
  791. // The common_test_cron_helper module sets the 'common_test_cron' variable.
  792. $this->cronRun();
  793. $result = variable_get('common_test_cron');
  794. $this->assertEqual($result, 'success', 'Cron correctly handles exceptions thrown during hook_cron() invocations.');
  795. }
  796. }
  797. /**
  798. * Test execution of the cron queue.
  799. */
  800. class CronQueueTestCase extends DrupalWebTestCase {
  801. /**
  802. * Implement getInfo().
  803. */
  804. public static function getInfo() {
  805. return array(
  806. 'name' => 'Cron queue functionality',
  807. 'description' => 'Tests the cron queue runner.',
  808. 'group' => 'System'
  809. );
  810. }
  811. function setUp() {
  812. parent::setUp(array('common_test', 'common_test_cron_helper'));
  813. }
  814. /**
  815. * Tests that exceptions thrown by workers are handled properly.
  816. */
  817. function testExceptions() {
  818. $queue = DrupalQueue::get('cron_queue_test_exception');
  819. // Enqueue an item for processing.
  820. $queue->createItem(array($this->randomName() => $this->randomName()));
  821. // Run cron; the worker for this queue should throw an exception and handle
  822. // it.
  823. $this->cronRun();
  824. // The item should be left in the queue.
  825. $this->assertEqual($queue->numberOfItems(), 1, 'Failing item still in the queue after throwing an exception.');
  826. }
  827. }
  828. class AdminMetaTagTestCase extends DrupalWebTestCase {
  829. /**
  830. * Implement getInfo().
  831. */
  832. public static function getInfo() {
  833. return array(
  834. 'name' => 'Fingerprinting meta tag',
  835. 'description' => 'Confirm that the fingerprinting meta tag appears as expected.',
  836. 'group' => 'System'
  837. );
  838. }
  839. /**
  840. * Verify that the meta tag HTML is generated correctly.
  841. */
  842. public function testMetaTag() {
  843. list($version, ) = explode('.', VERSION);
  844. $string = '<meta name="Generator" content="Drupal ' . $version . ' (http://drupal.org)" />';
  845. $this->drupalGet('node');
  846. $this->assertRaw($string, 'Fingerprinting meta tag generated correctly.', 'System');
  847. }
  848. }
  849. /**
  850. * Tests custom access denied functionality.
  851. */
  852. class AccessDeniedTestCase extends DrupalWebTestCase {
  853. protected $admin_user;
  854. public static function getInfo() {
  855. return array(
  856. 'name' => '403 functionality',
  857. 'description' => 'Tests page access denied functionality, including custom 403 pages.',
  858. 'group' => 'System'
  859. );
  860. }
  861. function setUp() {
  862. parent::setUp();
  863. // Create an administrative user.
  864. $this->admin_user = $this->drupalCreateUser(array('access administration pages', 'administer site configuration', 'administer blocks'));
  865. }
  866. function testAccessDenied() {
  867. $this->drupalGet('admin');
  868. $this->assertText(t('Access denied'), 'Found the default 403 page');
  869. $this->assertResponse(403);
  870. $this->drupalLogin($this->admin_user);
  871. $edit = array(
  872. 'title' => $this->randomName(10),
  873. 'body' => array(LANGUAGE_NONE => array(array('value' => $this->randomName(100)))),
  874. );
  875. $node = $this->drupalCreateNode($edit);
  876. // Use a custom 403 page.
  877. $this->drupalPost('admin/config/system/site-information', array('site_403' => 'node/' . $node->nid), t('Save configuration'));
  878. $this->drupalLogout();
  879. $this->drupalGet('admin');
  880. $this->assertText($node->title, 'Found the custom 403 page');
  881. // Logout and check that the user login block is shown on custom 403 pages.
  882. $this->drupalLogout();
  883. $this->drupalGet('admin');
  884. $this->assertText($node->title, 'Found the custom 403 page');
  885. $this->assertText(t('User login'), 'Blocks are shown on the custom 403 page');
  886. // Log back in and remove the custom 403 page.
  887. $this->drupalLogin($this->admin_user);
  888. $this->drupalPost('admin/config/system/site-information', array('site_403' => ''), t('Save configuration'));
  889. // Logout and check that the user login block is shown on default 403 pages.
  890. $this->drupalLogout();
  891. $this->drupalGet('admin');
  892. $this->assertText(t('Access denied'), 'Found the default 403 page');
  893. $this->assertResponse(403);
  894. $this->assertText(t('User login'), 'Blocks are shown on the default 403 page');
  895. // Log back in, set the custom 403 page to /user and remove the block
  896. $this->drupalLogin($this->admin_user);
  897. variable_set('site_403', 'user');
  898. $this->drupalPost('admin/structure/block', array('blocks[user_login][region]' => '-1'), t('Save blocks'));
  899. // Check that we can log in from the 403 page.
  900. $this->drupalLogout();
  901. $edit = array(
  902. 'name' => $this->admin_user->name,
  903. 'pass' => $this->admin_user->pass_raw,
  904. );
  905. $this->drupalPost('admin/config/system/site-information', $edit, t('Log in'));
  906. // Check that we're still on the same page.
  907. $this->assertText(t('Site information'));
  908. }
  909. }
  910. class PageNotFoundTestCase extends DrupalWebTestCase {
  911. protected $admin_user;
  912. /**
  913. * Implement getInfo().
  914. */
  915. public static function getInfo() {
  916. return array(
  917. 'name' => '404 functionality',
  918. 'description' => "Tests page not found functionality, including custom 404 pages.",
  919. 'group' => 'System'
  920. );
  921. }
  922. /**
  923. * Implement setUp().
  924. */
  925. function setUp() {
  926. parent::setUp();
  927. // Create an administrative user.
  928. $this->admin_user = $this->drupalCreateUser(array('administer site configuration'));
  929. $this->drupalLogin($this->admin_user);
  930. }
  931. function testPageNotFound() {
  932. $this->drupalGet($this->randomName(10));
  933. $this->assertText(t('Page not found'), 'Found the default 404 page');
  934. $edit = array(
  935. 'title' => $this->randomName(10),
  936. 'body' => array(LANGUAGE_NONE => array(array('value' => $this->randomName(100)))),
  937. );
  938. $node = $this->drupalCreateNode($edit);
  939. // As node IDs must be integers, make sure requests for non-integer IDs
  940. // return a page not found error.
  941. $this->drupalGet('node/invalid');
  942. $this->assertResponse(404);
  943. // Use a custom 404 page.
  944. $this->drupalPost('admin/config/system/site-information', array('site_404' => 'node/' . $node->nid), t('Save configuration'));
  945. $this->drupalGet($this->randomName(10));
  946. $this->assertText($node->title, 'Found the custom 404 page');
  947. }
  948. }
  949. /**
  950. * Tests site maintenance functionality.
  951. */
  952. class SiteMaintenanceTestCase extends DrupalWebTestCase {
  953. protected $admin_user;
  954. public static function getInfo() {
  955. return array(
  956. 'name' => 'Site maintenance mode functionality',
  957. 'description' => 'Test access to site while in maintenance mode.',
  958. 'group' => 'System',
  959. );
  960. }
  961. function setUp() {
  962. parent::setUp();
  963. // Create a user allowed to access site in maintenance mode.
  964. $this->user = $this->drupalCreateUser(array('access site in maintenance mode'));
  965. // Create an administrative user.
  966. $this->admin_user = $this->drupalCreateUser(array('administer site configuration', 'access site in maintenance mode'));
  967. $this->drupalLogin($this->admin_user);
  968. }
  969. /**
  970. * Verify site maintenance mode functionality.
  971. */
  972. function testSiteMaintenance() {
  973. // Turn on maintenance mode.
  974. $edit = array(
  975. 'maintenance_mode' => 1,
  976. );
  977. $this->drupalPost('admin/config/development/maintenance', $edit, t('Save configuration'));
  978. $admin_message = t('Operating in maintenance mode. <a href="@url">Go online.</a>', array('@url' => url('admin/config/development/maintenance')));
  979. $user_message = t('Operating in maintenance mode.');
  980. $offline_message = t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal')));
  981. $this->drupalGet('');
  982. $this->assertRaw($admin_message, 'Found the site maintenance mode message.');
  983. // Logout and verify that offline message is displayed.
  984. $this->drupalLogout();
  985. $this->drupalGet('');
  986. $this->assertText($offline_message);
  987. $this->drupalGet('node');
  988. $this->assertText($offline_message);
  989. $this->drupalGet('user/register');
  990. $this->assertText($offline_message);
  991. // Verify that user is able to log in.
  992. $this->drupalGet('user');
  993. $this->assertNoText($offline_message);
  994. $this->drupalGet('user/login');
  995. $this->assertNoText($offline_message);
  996. // Log in user and verify that maintenance mode message is displayed
  997. // directly after login.
  998. $edit = array(
  999. 'name' => $this->user->name,
  1000. 'pass' => $this->user->pass_raw,
  1001. );
  1002. $this->drupalPost(NULL, $edit, t('Log in'));
  1003. $this->assertText($user_message);
  1004. // Log in administrative user and configure a custom site offline message.
  1005. $this->drupalLogout();
  1006. $this->drupalLogin($this->admin_user);
  1007. $this->drupalGet('admin/config/development/maintenance');
  1008. $this->assertNoRaw($admin_message, 'Site maintenance mode message not displayed.');
  1009. $offline_message = 'Sorry, not online.';
  1010. $edit = array(
  1011. 'maintenance_mode_message' => $offline_message,
  1012. );
  1013. $this->drupalPost(NULL, $edit, t('Save configuration'));
  1014. // Logout and verify that custom site offline message is displayed.
  1015. $this->drupalLogout();
  1016. $this->drupalGet('');
  1017. $this->assertRaw($offline_message, 'Found the site offline message.');
  1018. // Verify that custom site offline message is not displayed on user/password.
  1019. $this->drupalGet('user/password');
  1020. $this->assertText(t('Username or e-mail address'), 'Anonymous users can access user/password');
  1021. // Submit password reset form.
  1022. $edit = array(
  1023. 'name' => $this->user->name,
  1024. );
  1025. $this->drupalPost('user/password', $edit, t('E-mail new password'));
  1026. $mails = $this->drupalGetMails();
  1027. $start = strpos($mails[0]['body'], 'user/reset/'. $this->user->uid);
  1028. $path = substr($mails[0]['body'], $start, 66 + strlen($this->user->uid));
  1029. // Log in with temporary login link.
  1030. $this->drupalPost($path, array(), t('Log in'));
  1031. $this->assertText($user_message);
  1032. }
  1033. }
  1034. /**
  1035. * Tests generic date and time handling capabilities of Drupal.
  1036. */
  1037. class DateTimeFunctionalTest extends DrupalWebTestCase {
  1038. public static function getInfo() {
  1039. return array(
  1040. 'name' => 'Date and time',
  1041. 'description' => 'Configure date and time settings. Test date formatting and time zone handling, including daylight saving time.',
  1042. 'group' => 'System',
  1043. );
  1044. }
  1045. function setUp() {
  1046. parent::setUp(array('locale'));
  1047. // Create admin user and log in admin user.
  1048. $this->admin_user = $this->drupalCreateUser(array('administer site configuration'));
  1049. $this->drupalLogin($this->admin_user);
  1050. }
  1051. /**
  1052. * Test time zones and DST handling.
  1053. */
  1054. function testTimeZoneHandling() {
  1055. // Setup date/time settings for Honolulu time.
  1056. variable_set('date_default_timezone', 'Pacific/Honolulu');
  1057. variable_set('configurable_timezones', 0);
  1058. variable_set('date_format_medium', 'Y-m-d H:i:s O');
  1059. // Create some nodes with different authored-on dates.
  1060. $date1 = '2007-01-31 21:00:00 -1000';
  1061. $date2 = '2007-07-31 21:00:00 -1000';
  1062. $node1 = $this->drupalCreateNode(array('created' => strtotime($date1), 'type' => 'article'));
  1063. $node2 = $this->drupalCreateNode(array('created' => strtotime($date2), 'type' => 'article'));
  1064. // Confirm date format and time zone.
  1065. $this->drupalGet("node/$node1->nid");
  1066. $this->assertText('2007-01-31 21:00:00 -1000', 'Date should be identical, with GMT offset of -10 hours.');
  1067. $this->drupalGet("node/$node2->nid");
  1068. $this->assertText('2007-07-31 21:00:00 -1000', 'Date should be identical, with GMT offset of -10 hours.');
  1069. // Set time zone to Los Angeles time.
  1070. variable_set('date_default_timezone', 'America/Los_Angeles');
  1071. // Confirm date format and time zone.
  1072. $this->drupalGet("node/$node1->nid");
  1073. $this->assertText('2007-01-31 23:00:00 -0800', 'Date should be two hours ahead, with GMT offset of -8 hours.');
  1074. $this->drupalGet("node/$node2->nid");
  1075. $this->assertText('2007-08-01 00:00:00 -0700', 'Date should be three hours ahead, with GMT offset of -7 hours.');
  1076. }
  1077. /**
  1078. * Test date type configuration.
  1079. */
  1080. function testDateTypeConfiguration() {
  1081. // Confirm system date types appear.
  1082. $this->drupalGet('admin/config/regional/date-time');
  1083. $this->assertText(t('Medium'), 'System date types appear in date type list.');
  1084. $this->assertNoRaw('href="/admin/config/regional/date-time/types/medium/delete"', 'No delete link appear for system date types.');
  1085. // Add custom date type.
  1086. $this->clickLink(t('Add date type'));
  1087. $date_type = strtolower($this->randomName(8));
  1088. $machine_name = 'machine_' . $date_type;
  1089. $date_format = 'd.m.Y - H:i';
  1090. $edit = array(
  1091. 'date_type' => $date_type,
  1092. 'machine_name' => $machine_name,
  1093. 'date_format' => $date_format,
  1094. );
  1095. $this->drupalPost('admin/config/regional/date-time/types/add', $edit, t('Add date type'));
  1096. $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time', array('absolute' => TRUE)), 'Correct page redirection.');
  1097. $this->assertText(t('New date type added successfully.'), 'Date type added confirmation message appears.');
  1098. $this->assertText($date_type, 'Custom date type appears in the date type list.');
  1099. $this->assertText(t('delete'), 'Delete link for custom date type appears.');
  1100. // Delete custom date type.
  1101. $this->clickLink(t('delete'));
  1102. $this->drupalPost('admin/config/regional/date-time/types/' . $machine_name . '/delete', array(), t('Remove'));
  1103. $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time', array('absolute' => TRUE)), 'Correct page redirection.');
  1104. $this->assertText(t('Removed date type ' . $date_type), 'Custom date type removed.');
  1105. }
  1106. /**
  1107. * Test date format configuration.
  1108. */
  1109. function testDateFormatConfiguration() {
  1110. // Confirm 'no custom date formats available' message appears.
  1111. $this->drupalGet('admin/config/regional/date-time/formats');
  1112. $this->assertText(t('No custom date formats available.'), 'No custom date formats message appears.');
  1113. // Add custom date format.
  1114. $this->clickLink(t('Add format'));
  1115. $edit = array(
  1116. 'date_format' => 'Y',
  1117. );
  1118. $this->drupalPost('admin/config/regional/date-time/formats/add', $edit, t('Add format'));
  1119. $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE)), 'Correct page redirection.');
  1120. $this->assertNoText(t('No custom date formats available.'), 'No custom date formats message does not appear.');
  1121. $this->assertText(t('Custom date format added.'), 'Custom date format added.');
  1122. // Ensure custom date format appears in date type configuration options.
  1123. $this->drupalGet('admin/config/regional/date-time');
  1124. $this->assertRaw('<option value="Y">', 'Custom date format appears in options.');
  1125. // Edit custom date format.
  1126. $this->drupalGet('admin/config/regional/date-time/formats');
  1127. $this->clickLink(t('edit'));
  1128. $edit = array(
  1129. 'date_format' => 'Y m',
  1130. );
  1131. $this->drupalPost($this->getUrl(), $edit, t('Save format'));
  1132. $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE)), 'Correct page redirection.');
  1133. $this->assertText(t('Custom date format updated.'), 'Custom date format successfully updated.');
  1134. // Delete custom date format.
  1135. $this->clickLink(t('delete'));
  1136. $this->drupalPost($this->getUrl(), array(), t('Remove'));
  1137. $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE)), 'Correct page redirection.');
  1138. $this->assertText(t('Removed date format'), 'Custom date format removed successfully.');
  1139. }
  1140. /**
  1141. * Test if the date formats are stored properly.
  1142. */
  1143. function testDateFormatStorage() {
  1144. $date_format = array(
  1145. 'type' => 'short',
  1146. 'format' => 'dmYHis',
  1147. 'locked' => 0,
  1148. 'is_new' => 1,
  1149. );
  1150. system_date_format_save($date_format);
  1151. $format = db_select('date_formats', 'df')
  1152. ->fields('df', array('format'))
  1153. ->condition('type', 'short')
  1154. ->condition('format', 'dmYHis')
  1155. ->execute()
  1156. ->fetchField();
  1157. $this->verbose($format);
  1158. $this->assertEqual('dmYHis', $format, 'Unlocalized date format resides in general table.');
  1159. $format = db_select('date_format_locale', 'dfl')
  1160. ->fields('dfl', array('format'))
  1161. ->condition('type', 'short')
  1162. ->condition('format', 'dmYHis')
  1163. ->execute()
  1164. ->fetchField();
  1165. $this->assertFalse($format, 'Unlocalized date format resides not in localized table.');
  1166. // Enable German language
  1167. locale_add_language('de', NULL, NULL, LANGUAGE_LTR, '', '', TRUE, 'en');
  1168. $date_format = array(
  1169. 'type' => 'short',
  1170. 'format' => 'YMDHis',
  1171. 'locales' => array('de', 'tr'),
  1172. 'locked' => 0,
  1173. 'is_new' => 1,
  1174. );
  1175. system_date_format_save($date_format);
  1176. $format = db_select('date_format_locale', 'dfl')
  1177. ->fields('dfl', array('format'))
  1178. ->condition('type', 'short')
  1179. ->condition('format', 'YMDHis')
  1180. ->condition('language', 'de')
  1181. ->execute()
  1182. ->fetchField();
  1183. $this->assertEqual('YMDHis', $format, 'Localized date format resides in localized table.');
  1184. $format = db_select('date_formats', 'df')
  1185. ->fields('df', array('format'))
  1186. ->condition('type', 'short')
  1187. ->condition('format', 'YMDHis')
  1188. ->execute()
  1189. ->fetchField();
  1190. $this->assertEqual('YMDHis', $format, 'Localized date format resides in general table too.');
  1191. $format = db_select('date_format_locale', 'dfl')
  1192. ->fields('dfl', array('format'))
  1193. ->condition('type', 'short')
  1194. ->condition('format', 'YMDHis')
  1195. ->condition('language', 'tr')
  1196. ->execute()
  1197. ->fetchColumn();
  1198. $this->assertFalse($format, 'Localized date format for disabled language is ignored.');
  1199. }
  1200. }
  1201. class PageTitleFiltering extends DrupalWebTestCase {
  1202. protected $content_user;
  1203. protected $saved_title;
  1204. /**
  1205. * Implement getInfo().
  1206. */
  1207. public static function getInfo() {
  1208. return array(
  1209. 'name' => 'HTML in page titles',
  1210. 'description' => 'Tests correct handling or conversion by drupal_set_title() and drupal_get_title() and checks the correct escaping of site name and slogan.',
  1211. 'group' => 'System'
  1212. );
  1213. }
  1214. /**
  1215. * Implement setUp().
  1216. */
  1217. function setUp() {
  1218. parent::setUp();
  1219. $this->content_user = $this->drupalCreateUser(array('create page content', 'access content', 'administer themes', 'administer site configuration'));
  1220. $this->drupalLogin($this->content_user);
  1221. $this->saved_title = drupal_get_title();
  1222. }
  1223. /**
  1224. * Reset page title.
  1225. */
  1226. function tearDown() {
  1227. // Restore the page title.
  1228. drupal_set_title($this->saved_title, PASS_THROUGH);
  1229. parent::tearDown();
  1230. }
  1231. /**
  1232. * Tests the handling of HTML by drupal_set_title() and drupal_get_title()
  1233. */
  1234. function testTitleTags() {
  1235. $title = "string with <em>HTML</em>";
  1236. // drupal_set_title's $filter is CHECK_PLAIN by default, so the title should be
  1237. // returned with check_plain().
  1238. drupal_set_title($title, CHECK_PLAIN);
  1239. $this->assertTrue(strpos(drupal_get_title(), '<em>') === FALSE, 'Tags in title converted to entities when $output is CHECK_PLAIN.');
  1240. // drupal_set_title's $filter is passed as PASS_THROUGH, so the title should be
  1241. // returned with HTML.
  1242. drupal_set_title($title, PASS_THROUGH);
  1243. $this->assertTrue(strpos(drupal_get_title(), '<em>') !== FALSE, 'Tags in title are not converted to entities when $output is PASS_THROUGH.');
  1244. // Generate node content.
  1245. $langcode = LANGUAGE_NONE;
  1246. $edit = array(
  1247. "title" => '!SimpleTest! ' . $title . $this->randomName(20),
  1248. "body[$langcode][0][value]" => '!SimpleTest! test body' . $this->randomName(200),
  1249. );
  1250. // Create the node with HTML in the title.
  1251. $this->drupalPost('node/add/page', $edit, t('Save'));
  1252. $node = $this->drupalGetNodeByTitle($edit["title"]);
  1253. $this->assertNotNull($node, 'Node created and found in database');
  1254. $this->drupalGet("node/" . $node->nid);
  1255. $this->assertText(check_plain($edit["title"]), 'Check to make sure tags in the node title are converted.');
  1256. }
  1257. /**
  1258. * Test if the title of the site is XSS proof.
  1259. */
  1260. function testTitleXSS() {
  1261. // Set some title with JavaScript and HTML chars to escape.
  1262. $title = '</title><script type="text/javascript">alert("Title XSS!");</script> & < > " \' ';
  1263. $title_filtered = check_plain($title);
  1264. $slogan = '<script type="text/javascript">alert("Slogan XSS!");</script>';
  1265. $slogan_filtered = filter_xss_admin($slogan);
  1266. // Activate needed appearance settings.
  1267. $edit = array(
  1268. 'toggle_name' => TRUE,
  1269. 'toggle_slogan' => TRUE,
  1270. 'toggle_main_menu' => TRUE,
  1271. 'toggle_secondary_menu' => TRUE,
  1272. );
  1273. $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
  1274. // Set title and slogan.
  1275. $edit = array(
  1276. 'site_name' => $title,
  1277. 'site_slogan' => $slogan,
  1278. );
  1279. $this->drupalPost('admin/config/system/site-information', $edit, t('Save configuration'));
  1280. // Load frontpage.
  1281. $this->drupalGet('');
  1282. // Test the title.
  1283. $this->assertNoRaw($title, 'Check for the unfiltered version of the title.');
  1284. // Adding </title> so we do not test the escaped version from drupal_set_title().
  1285. $this->assertRaw($title_filtered . '</title>', 'Check for the filtered version of the title.');
  1286. // Test the slogan.
  1287. $this->assertNoRaw($slogan, 'Check for the unfiltered version of the slogan.');
  1288. $this->assertRaw($slogan_filtered, 'Check for the filtered version of the slogan.');
  1289. }
  1290. }
  1291. /**
  1292. * Test front page functionality and administration.
  1293. */
  1294. class FrontPageTestCase extends DrupalWebTestCase {
  1295. public static function getInfo() {
  1296. return array(
  1297. 'name' => 'Front page',
  1298. 'description' => 'Tests front page functionality and administration.',
  1299. 'group' => 'System',
  1300. );
  1301. }
  1302. function setUp() {
  1303. parent::setUp('system_test');
  1304. // Create admin user, log in admin user, and create one node.
  1305. $this->admin_user = $this->drupalCreateUser(array('access content', 'administer site configuration'));
  1306. $this->drupalLogin($this->admin_user);
  1307. $this->node_path = "node/" . $this->drupalCreateNode(array('promote' => 1))->nid;
  1308. // Enable front page logging in system_test.module.
  1309. variable_set('front_page_output', 1);
  1310. }
  1311. /**
  1312. * Test front page functionality.
  1313. */
  1314. function testDrupalIsFrontPage() {
  1315. $this->drupalGet('');
  1316. $this->assertText(t('On front page.'), 'Path is the front page.');
  1317. $this->drupalGet('node');
  1318. $this->assertText(t('On front page.'), 'Path is the front page.');
  1319. $this->drupalGet($this->node_path);
  1320. $this->assertNoText(t('On front page.'), 'Path is not the front page.');
  1321. // Change the front page to an invalid path.
  1322. $edit = array('site_frontpage' => 'kittens');
  1323. $this->drupalPost('admin/config/system/site-information', $edit, t('Save configuration'));
  1324. $this->assertText(t("The path '@path' is either invalid or you do not have access to it.", array('@path' => $edit['site_frontpage'])));
  1325. // Change the front page to a valid path.
  1326. $edit['site_frontpage'] = $this->node_path;
  1327. $this->drupalPost('admin/config/system/site-information', $edit, t('Save configuration'));
  1328. $this->assertText(t('The configuration options have been saved.'), 'The front page path has been saved.');
  1329. $this->drupalGet('');
  1330. $this->assertText(t('On front page.'), 'Path is the front page.');
  1331. $this->drupalGet('node');
  1332. $this->assertNoText(t('On front page.'), 'Path is not the front page.');
  1333. $this->drupalGet($this->node_path);
  1334. $this->assertText(t('On front page.'), 'Path is the front page.');
  1335. }
  1336. }
  1337. class SystemBlockTestCase extends DrupalWebTestCase {
  1338. protected $profile = 'testing';
  1339. public static function getInfo() {
  1340. return array(
  1341. 'name' => 'Block functionality',
  1342. 'description' => 'Configure and move powered-by block.',
  1343. 'group' => 'System',
  1344. );
  1345. }
  1346. function setUp() {
  1347. parent::setUp('block');
  1348. // Create and login user
  1349. $admin_user = $this->drupalCreateUser(array('administer blocks', 'access administration pages'));
  1350. $this->drupalLogin($admin_user);
  1351. }
  1352. /**
  1353. * Test displaying and hiding the powered-by and help blocks.
  1354. */
  1355. function testSystemBlocks() {
  1356. // Set block title and some settings to confirm that the interface is available.
  1357. $this->drupalPost('admin/structure/block/manage/system/powered-by/configure', array('title' => $this->randomName(8)), t('Save block'));
  1358. $this->assertText(t('The block configuration has been saved.'), t('Block configuration set.'));
  1359. // Set the powered-by block to the footer region.
  1360. $edit = array();
  1361. $edit['blocks[system_powered-by][region]'] = 'footer';
  1362. $edit['blocks[system_main][region]'] = 'content';
  1363. $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
  1364. $this->assertText(t('The block settings have been updated.'), t('Block successfully moved to footer region.'));
  1365. // Confirm that the block is being displayed.
  1366. $this->drupalGet('node');
  1367. $this->assertRaw('id="block-system-powered-by"', t('Block successfully being displayed on the page.'));
  1368. // Set the block to the disabled region.
  1369. $edit = array();
  1370. $edit['blocks[system_powered-by][region]'] = '-1';
  1371. $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
  1372. // Confirm that the block is hidden.
  1373. $this->assertNoRaw('id="block-system-powered-by"', t('Block no longer appears on page.'));
  1374. // For convenience of developers, set the block to its default settings.
  1375. $edit = array();
  1376. $edit['blocks[system_powered-by][region]'] = 'footer';
  1377. $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
  1378. $this->drupalPost('admin/structure/block/manage/system/powered-by/configure', array('title' => ''), t('Save block'));
  1379. // Set the help block to the help region.
  1380. $edit = array();
  1381. $edit['blocks[system_help][region]'] = 'help';
  1382. $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
  1383. // Test displaying the help block with block caching enabled.
  1384. variable_set('block_cache', TRUE);
  1385. $this->drupalGet('admin/structure/block/add');
  1386. $this->assertRaw(t('Use this page to create a new custom block.'));
  1387. $this->drupalGet('admin/index');
  1388. $this->assertRaw(t('This page shows you all available administration tasks for each module.'));
  1389. }
  1390. }
  1391. /**
  1392. * Test main content rendering fallback provided by system module.
  1393. */
  1394. class SystemMainContentFallback extends DrupalWebTestCase {
  1395. protected $admin_user;
  1396. protected $web_user;
  1397. public static function getInfo() {
  1398. return array(
  1399. 'name' => 'Main content rendering fallback',
  1400. 'description' => ' Test system module main content rendering fallback.',
  1401. 'group' => 'System',
  1402. );
  1403. }
  1404. function setUp() {
  1405. parent::setUp('system_test');
  1406. // Create and login admin user.
  1407. $this->admin_user = $this->drupalCreateUser(array(
  1408. 'access administration pages',
  1409. 'administer site configuration',
  1410. 'administer modules',
  1411. 'administer blocks',
  1412. 'administer nodes',
  1413. ));
  1414. $this->drupalLogin($this->admin_user);
  1415. // Create a web user.
  1416. $this->web_user = $this->drupalCreateUser(array('access user profiles', 'access content'));
  1417. }
  1418. /**
  1419. * Test availability of main content.
  1420. */
  1421. function testMainContentFallback() {
  1422. $edit = array();
  1423. // Disable the dashboard module, which depends on the block module.
  1424. $edit['modules[Core][dashboard][enable]'] = FALSE;
  1425. $this->drupalPost('admin/modules', $edit, t('Save configuration'));
  1426. $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
  1427. // Disable the block module.
  1428. $edit['modules[Core][block][enable]'] = FALSE;
  1429. $this->drupalPost('admin/modules', $edit, t('Save configuration'));
  1430. $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
  1431. module_list(TRUE);
  1432. $this->assertFalse(module_exists('block'), 'Block module disabled.');
  1433. // At this point, no region is filled and fallback should be triggered.
  1434. $this->drupalGet('admin/config/system/site-information');
  1435. $this->assertField('site_name', 'Admin interface still available.');
  1436. // Fallback should not trigger when another module is handling content.
  1437. $this->drupalGet('system-test/main-content-handling');
  1438. $this->assertRaw('id="system-test-content"', 'Content handled by another module');
  1439. $this->assertText(t('Content to test main content fallback'), 'Main content still displayed.');
  1440. // Fallback should trigger when another module
  1441. // indicates that it is not handling the content.
  1442. $this->drupalGet('system-test/main-content-fallback');
  1443. $this->assertText(t('Content to test main content fallback'), 'Main content fallback properly triggers.');
  1444. // Fallback should not trigger when another module is handling content.
  1445. // Note that this test ensures that no duplicate
  1446. // content gets created by the fallback.
  1447. $this->drupalGet('system-test/main-content-duplication');
  1448. $this->assertNoText(t('Content to test main content fallback'), 'Main content not duplicated.');
  1449. // Request a user* page and see if it is displayed.
  1450. $this->drupalLogin($this->web_user);
  1451. $this->drupalGet('user/' . $this->web_user->uid . '/edit');
  1452. $this->assertField('mail', 'User interface still available.');
  1453. // Enable the block module again.
  1454. $this->drupalLogin($this->admin_user);
  1455. $edit = array();
  1456. $edit['modules[Core][block][enable]'] = 'block';
  1457. $this->drupalPost('admin/modules', $edit, t('Save configuration'));
  1458. $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
  1459. module_list(TRUE);
  1460. $this->assertTrue(module_exists('block'), 'Block module re-enabled.');
  1461. }
  1462. }
  1463. /**
  1464. * Tests for the theme interface functionality.
  1465. */
  1466. class SystemThemeFunctionalTest extends DrupalWebTestCase {
  1467. public static function getInfo() {
  1468. return array(
  1469. 'name' => 'Theme interface functionality',
  1470. 'description' => 'Tests the theme interface functionality by enabling and switching themes, and using an administration theme.',
  1471. 'group' => 'System',
  1472. );
  1473. }
  1474. function setUp() {
  1475. parent::setUp();
  1476. $this->admin_user = $this->drupalCreateUser(array('access administration pages', 'view the administration theme', 'administer themes', 'bypass node access', 'administer blocks'));
  1477. $this->drupalLogin($this->admin_user);
  1478. $this->node = $this->drupalCreateNode();
  1479. }
  1480. /**
  1481. * Test the theme settings form.
  1482. */
  1483. function testThemeSettings() {
  1484. // Specify a filesystem path to be used for the logo.
  1485. $file = current($this->drupalGetTestFiles('image'));
  1486. $file_relative = strtr($file->uri, array('public:/' => variable_get('file_public_path', conf_path() . '/files')));
  1487. $default_theme_path = 'themes/stark';
  1488. $supported_paths = array(
  1489. // Raw stream wrapper URI.
  1490. $file->uri => array(
  1491. 'form' => file_uri_target($file->uri),
  1492. 'src' => file_create_url($file->uri),
  1493. ),
  1494. // Relative path within the public filesystem.
  1495. file_uri_target($file->uri) => array(
  1496. 'form' => file_uri_target($file->uri),
  1497. 'src' => file_create_url($file->uri),
  1498. ),
  1499. // Relative path to a public file.
  1500. $file_relative => array(
  1501. 'form' => $file_relative,
  1502. 'src' => file_create_url($file->uri),
  1503. ),
  1504. // Relative path to an arbitrary file.
  1505. 'misc/druplicon.png' => array(
  1506. 'form' => 'misc/druplicon.png',
  1507. 'src' => $GLOBALS['base_url'] . '/' . 'misc/druplicon.png',
  1508. ),
  1509. // Relative path to a file in a theme.
  1510. $default_theme_path . '/logo.png' => array(
  1511. 'form' => $default_theme_path . '/logo.png',
  1512. 'src' => $GLOBALS['base_url'] . '/' . $default_theme_path . '/logo.png',
  1513. ),
  1514. );
  1515. foreach ($supported_paths as $input => $expected) {
  1516. $edit = array(
  1517. 'default_logo' => FALSE,
  1518. 'logo_path' => $input,
  1519. );
  1520. $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
  1521. $this->assertNoText('The custom logo path is invalid.');
  1522. $this->assertFieldByName('logo_path', $expected['form']);
  1523. // Verify the actual 'src' attribute of the logo being output.
  1524. $this->drupalGet('');
  1525. $elements = $this->xpath('//*[@id=:id]/img', array(':id' => 'logo'));
  1526. $this->assertEqual((string) $elements[0]['src'], $expected['src']);
  1527. }
  1528. $unsupported_paths = array(
  1529. // Stream wrapper URI to non-existing file.
  1530. 'public://whatever.png',
  1531. 'private://whatever.png',
  1532. 'temporary://whatever.png',
  1533. // Bogus stream wrapper URIs.
  1534. 'public:/whatever.png',
  1535. '://whatever.png',
  1536. ':whatever.png',
  1537. 'public://',
  1538. // Relative path within the public filesystem to non-existing file.
  1539. 'whatever.png',
  1540. // Relative path to non-existing file in public filesystem.
  1541. variable_get('file_public_path', conf_path() . '/files') . '/whatever.png',
  1542. // Semi-absolute path to non-existing file in public filesystem.
  1543. '/' . variable_get('file_public_path', conf_path() . '/files') . '/whatever.png',
  1544. // Relative path to arbitrary non-existing file.
  1545. 'misc/whatever.png',
  1546. // Semi-absolute path to arbitrary non-existing file.
  1547. '/misc/whatever.png',
  1548. // Absolute paths to any local file (even if it exists).
  1549. drupal_realpath($file->uri),
  1550. );
  1551. $this->drupalGet('admin/appearance/settings');
  1552. foreach ($unsupported_paths as $path) {
  1553. $edit = array(
  1554. 'default_logo' => FALSE,
  1555. 'logo_path' => $path,
  1556. );
  1557. $this->drupalPost(NULL, $edit, t('Save configuration'));
  1558. $this->assertText('The custom logo path is invalid.');
  1559. }
  1560. // Upload a file to use for the logo.
  1561. $edit = array(
  1562. 'default_logo' => FALSE,
  1563. 'logo_path' => '',
  1564. 'files[logo_upload]' => drupal_realpath($file->uri),
  1565. );
  1566. $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
  1567. $fields = $this->xpath($this->constructFieldXpath('name', 'logo_path'));
  1568. $uploaded_filename = 'public://' . $fields[0]['value'];
  1569. $this->drupalGet('');
  1570. $elements = $this->xpath('//*[@id=:id]/img', array(':id' => 'logo'));
  1571. $this->assertEqual($elements[0]['src'], file_create_url($uploaded_filename));
  1572. }
  1573. /**
  1574. * Test the administration theme functionality.
  1575. */
  1576. function testAdministrationTheme() {
  1577. theme_enable(array('stark'));
  1578. variable_set('theme_default', 'stark');
  1579. // Enable an administration theme and show it on the node admin pages.
  1580. $edit = array(
  1581. 'admin_theme' => 'seven',
  1582. 'node_admin_theme' => TRUE,
  1583. );
  1584. $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
  1585. $this->drupalGet('admin/config');
  1586. $this->assertRaw('themes/seven', 'Administration theme used on an administration page.');
  1587. $this->drupalGet('node/' . $this->node->nid);
  1588. $this->assertRaw('themes/stark', 'Site default theme used on node page.');
  1589. $this->drupalGet('node/add');
  1590. $this->assertRaw('themes/seven', 'Administration theme used on the add content page.');
  1591. $this->drupalGet('node/' . $this->node->nid . '/edit');
  1592. $this->assertRaw('themes/seven', 'Administration theme used on the edit content page.');
  1593. // Disable the admin theme on the node admin pages.
  1594. $edit = array(
  1595. 'node_admin_theme' => FALSE,
  1596. );
  1597. $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
  1598. $this->drupalGet('admin/config');
  1599. $this->assertRaw('themes/seven', 'Administration theme used on an administration page.');
  1600. $this->drupalGet('node/add');
  1601. $this->assertRaw('themes/stark', 'Site default theme used on the add content page.');
  1602. // Reset to the default theme settings.
  1603. variable_set('theme_default', 'bartik');
  1604. $edit = array(
  1605. 'admin_theme' => '0',
  1606. 'node_admin_theme' => FALSE,
  1607. );
  1608. $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
  1609. $this->drupalGet('admin');
  1610. $this->assertRaw('themes/bartik', 'Site default theme used on administration page.');
  1611. $this->drupalGet('node/add');
  1612. $this->assertRaw('themes/bartik', 'Site default theme used on the add content page.');
  1613. }
  1614. /**
  1615. * Test switching the default theme.
  1616. */
  1617. function testSwitchDefaultTheme() {
  1618. // Enable "stark" and set it as the default theme.
  1619. theme_enable(array('stark'));
  1620. $this->drupalGet('admin/appearance');
  1621. $this->clickLink(t('Set default'), 1);
  1622. $this->assertTrue(variable_get('theme_default', '') == 'stark', 'Site default theme switched successfully.');
  1623. // Test the default theme on the secondary links (blocks admin page).
  1624. $this->drupalGet('admin/structure/block');
  1625. $this->assertText('Stark(' . t('active tab') . ')', 'Default local task on blocks admin page is the default theme.');
  1626. // Switch back to Bartik and test again to test that the menu cache is cleared.
  1627. $this->drupalGet('admin/appearance');
  1628. $this->clickLink(t('Set default'), 0);
  1629. $this->drupalGet('admin/structure/block');
  1630. $this->assertText('Bartik(' . t('active tab') . ')', 'Default local task on blocks admin page has changed.');
  1631. }
  1632. }
  1633. /**
  1634. * Test the basic queue functionality.
  1635. */
  1636. class QueueTestCase extends DrupalWebTestCase {
  1637. public static function getInfo() {
  1638. return array(
  1639. 'name' => 'Queue functionality',
  1640. 'description' => 'Queues and dequeues a set of items to check the basic queue functionality.',
  1641. 'group' => 'System',
  1642. );
  1643. }
  1644. /**
  1645. * Queues and dequeues a set of items to check the basic queue functionality.
  1646. */
  1647. function testQueue() {
  1648. // Create two queues.
  1649. $queue1 = DrupalQueue::get($this->randomName());
  1650. $queue1->createQueue();
  1651. $queue2 = DrupalQueue::get($this->randomName());
  1652. $queue2->createQueue();
  1653. // Create four items.
  1654. $data = array();
  1655. for ($i = 0; $i < 4; $i++) {
  1656. $data[] = array($this->randomName() => $this->randomName());
  1657. }
  1658. // Queue items 1 and 2 in the queue1.
  1659. $queue1->createItem($data[0]);
  1660. $queue1->createItem($data[1]);
  1661. // Retrieve two items from queue1.
  1662. $items = array();
  1663. $new_items = array();
  1664. $items[] = $item = $queue1->claimItem();
  1665. $new_items[] = $item->data;
  1666. $items[] = $item = $queue1->claimItem();
  1667. $new_items[] = $item->data;
  1668. // First two dequeued items should match the first two items we queued.
  1669. $this->assertEqual($this->queueScore($data, $new_items), 2, 'Two items matched');
  1670. // Add two more items.
  1671. $queue1->createItem($data[2]);
  1672. $queue1->createItem($data[3]);
  1673. $this->assertTrue($queue1->numberOfItems(), 'Queue 1 is not empty after adding items.');
  1674. $this->assertFalse($queue2->numberOfItems(), 'Queue 2 is empty while Queue 1 has items');
  1675. $items[] = $item = $queue1->claimItem();
  1676. $new_items[] = $item->data;
  1677. $items[] = $item = $queue1->claimItem();
  1678. $new_items[] = $item->data;
  1679. // All dequeued items should match the items we queued exactly once,
  1680. // therefore the score must be exactly 4.
  1681. $this->assertEqual($this->queueScore($data, $new_items), 4, 'Four items matched');
  1682. // There should be no duplicate items.
  1683. $this->assertEqual($this->queueScore($new_items, $new_items), 4, 'Four items matched');
  1684. // Delete all items from queue1.
  1685. foreach ($items as $item) {
  1686. $queue1->deleteItem($item);
  1687. }
  1688. // Check that both queues are empty.
  1689. $this->assertFalse($queue1->numberOfItems(), 'Queue 1 is empty');
  1690. $this->assertFalse($queue2->numberOfItems(), 'Queue 2 is empty');
  1691. }
  1692. /**
  1693. * This function returns the number of equal items in two arrays.
  1694. */
  1695. function queueScore($items, $new_items) {
  1696. $score = 0;
  1697. foreach ($items as $item) {
  1698. foreach ($new_items as $new_item) {
  1699. if ($item === $new_item) {
  1700. $score++;
  1701. }
  1702. }
  1703. }
  1704. return $score;
  1705. }
  1706. }
  1707. /**
  1708. * Test token replacement in strings.
  1709. */
  1710. class TokenReplaceTestCase extends DrupalWebTestCase {
  1711. public static function getInfo() {
  1712. return array(
  1713. 'name' => 'Token replacement',
  1714. 'description' => 'Generates text using placeholders for dummy content to check token replacement.',
  1715. 'group' => 'System',
  1716. );
  1717. }
  1718. /**
  1719. * Creates a user and a node, then tests the tokens generated from them.
  1720. */
  1721. function testTokenReplacement() {
  1722. // Create the initial objects.
  1723. $account = $this->drupalCreateUser();
  1724. $node = $this->drupalCreateNode(array('uid' => $account->uid));
  1725. $node->title = '<blink>Blinking Text</blink>';
  1726. global $user, $language;
  1727. $source = '[node:title]'; // Title of the node we passed in
  1728. $source .= '[node:author:name]'; // Node author's name
  1729. $source .= '[node:created:since]'; // Time since the node was created
  1730. $source .= '[current-user:name]'; // Current user's name
  1731. $source .= '[date:short]'; // Short date format of REQUEST_TIME
  1732. $source .= '[user:name]'; // No user passed in, should be untouched
  1733. $source .= '[bogus:token]'; // Non-existent token
  1734. $target = check_plain($node->title);
  1735. $target .= check_plain($account->name);
  1736. $target .= format_interval(REQUEST_TIME - $node->created, 2, $language->language);
  1737. $target .= check_plain($user->name);
  1738. $target .= format_date(REQUEST_TIME, 'short', '', NULL, $language->language);
  1739. // Test that the clear parameter cleans out non-existent tokens.
  1740. $result = token_replace($source, array('node' => $node), array('language' => $language, 'clear' => TRUE));
  1741. $result = $this->assertEqual($target, $result, 'Valid tokens replaced while invalid tokens cleared out.');
  1742. // Test without using the clear parameter (non-existent token untouched).
  1743. $target .= '[user:name]';
  1744. $target .= '[bogus:token]';
  1745. $result = token_replace($source, array('node' => $node), array('language' => $language));
  1746. $this->assertEqual($target, $result, 'Valid tokens replaced while invalid tokens ignored.');
  1747. // Check that the results of token_generate are sanitized properly. This does NOT
  1748. // test the cleanliness of every token -- just that the $sanitize flag is being
  1749. // passed properly through the call stack and being handled correctly by a 'known'
  1750. // token, [node:title].
  1751. $raw_tokens = array('title' => '[node:title]');
  1752. $generated = token_generate('node', $raw_tokens, array('node' => $node));
  1753. $this->assertEqual($generated['[node:title]'], check_plain($node->title), 'Token sanitized.');
  1754. $generated = token_generate('node', $raw_tokens, array('node' => $node), array('sanitize' => FALSE));
  1755. $this->assertEqual($generated['[node:title]'], $node->title, 'Unsanitized token generated properly.');
  1756. // Test token replacement when the string contains no tokens.
  1757. $this->assertEqual(token_replace('No tokens here.'), 'No tokens here.');
  1758. }
  1759. /**
  1760. * Test whether token-replacement works in various contexts.
  1761. */
  1762. function testSystemTokenRecognition() {
  1763. global $language;
  1764. // Generate prefixes and suffixes for the token context.
  1765. $tests = array(
  1766. array('prefix' => 'this is the ', 'suffix' => ' site'),
  1767. array('prefix' => 'this is the', 'suffix' => 'site'),
  1768. array('prefix' => '[', 'suffix' => ']'),
  1769. array('prefix' => '', 'suffix' => ']]]'),
  1770. array('prefix' => '[[[', 'suffix' => ''),
  1771. array('prefix' => ':[:', 'suffix' => '--]'),
  1772. array('prefix' => '-[-', 'suffix' => ':]:'),
  1773. array('prefix' => '[:', 'suffix' => ']'),
  1774. array('prefix' => '[site:', 'suffix' => ':name]'),
  1775. array('prefix' => '[site:', 'suffix' => ']'),
  1776. );
  1777. // Check if the token is recognized in each of the contexts.
  1778. foreach ($tests as $test) {
  1779. $input = $test['prefix'] . '[site:name]' . $test['suffix'];
  1780. $expected = $test['prefix'] . 'Drupal' . $test['suffix'];
  1781. $output = token_replace($input, array(), array('language' => $language));
  1782. $this->assertTrue($output == $expected, format_string('Token recognized in string %string', array('%string' => $input)));
  1783. }
  1784. }
  1785. /**
  1786. * Tests the generation of all system site information tokens.
  1787. */
  1788. function testSystemSiteTokenReplacement() {
  1789. global $language;
  1790. $url_options = array(
  1791. 'absolute' => TRUE,
  1792. 'language' => $language,
  1793. );
  1794. // Set a few site variables.
  1795. variable_set('site_name', '<strong>Drupal<strong>');
  1796. variable_set('site_slogan', '<blink>Slogan</blink>');
  1797. // Generate and test sanitized tokens.
  1798. $tests = array();
  1799. $tests['[site:name]'] = check_plain(variable_get('site_name', 'Drupal'));
  1800. $tests['[site:slogan]'] = check_plain(variable_get('site_slogan', ''));
  1801. $tests['[site:mail]'] = 'simpletest@example.com';
  1802. $tests['[site:url]'] = url('<front>', $url_options);
  1803. $tests['[site:url-brief]'] = preg_replace(array('!^https?://!', '!/$!'), '', url('<front>', $url_options));
  1804. $tests['[site:login-url]'] = url('user', $url_options);
  1805. // Test to make sure that we generated something for each token.
  1806. $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
  1807. foreach ($tests as $input => $expected) {
  1808. $output = token_replace($input, array(), array('language' => $language));
  1809. $this->assertEqual($output, $expected, format_string('Sanitized system site information token %token replaced.', array('%token' => $input)));
  1810. }
  1811. // Generate and test unsanitized tokens.
  1812. $tests['[site:name]'] = variable_get('site_name', 'Drupal');
  1813. $tests['[site:slogan]'] = variable_get('site_slogan', '');
  1814. foreach ($tests as $input => $expected) {
  1815. $output = token_replace($input, array(), array('language' => $language, 'sanitize' => FALSE));
  1816. $this->assertEqual($output, $expected, format_string('Unsanitized system site information token %token replaced.', array('%token' => $input)));
  1817. }
  1818. }
  1819. /**
  1820. * Tests the generation of all system date tokens.
  1821. */
  1822. function testSystemDateTokenReplacement() {
  1823. global $language;
  1824. // Set time to one hour before request.
  1825. $date = REQUEST_TIME - 3600;
  1826. // Generate and test tokens.
  1827. $tests = array();
  1828. $tests['[date:short]'] = format_date($date, 'short', '', NULL, $language->language);
  1829. $tests['[date:medium]'] = format_date($date, 'medium', '', NULL, $language->language);
  1830. $tests['[date:long]'] = format_date($date, 'long', '', NULL, $language->language);
  1831. $tests['[date:custom:m/j/Y]'] = format_date($date, 'custom', 'm/j/Y', NULL, $language->language);
  1832. $tests['[date:since]'] = format_interval((REQUEST_TIME - $date), 2, $language->language);
  1833. $tests['[date:raw]'] = filter_xss($date);
  1834. // Test to make sure that we generated something for each token.
  1835. $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
  1836. foreach ($tests as $input => $expected) {
  1837. $output = token_replace($input, array('date' => $date), array('language' => $language));
  1838. $this->assertEqual($output, $expected, format_string('Date token %token replaced.', array('%token' => $input)));
  1839. }
  1840. }
  1841. }
  1842. class InfoFileParserTestCase extends DrupalUnitTestCase {
  1843. public static function getInfo() {
  1844. return array(
  1845. 'name' => 'Info file format parser',
  1846. 'description' => 'Tests proper parsing of a .info file formatted string.',
  1847. 'group' => 'System',
  1848. );
  1849. }
  1850. /**
  1851. * Test drupal_parse_info_format().
  1852. */
  1853. function testDrupalParseInfoFormat() {
  1854. $config = '
  1855. simple = Value
  1856. quoted = " Value"
  1857. multiline = "Value
  1858. Value"
  1859. array[] = Value1
  1860. array[] = Value2
  1861. array_assoc[a] = Value1
  1862. array_assoc[b] = Value2
  1863. array_deep[][][] = Value
  1864. array_deep_assoc[a][b][c] = Value
  1865. array_space[a b] = Value';
  1866. $expected = array(
  1867. 'simple' => 'Value',
  1868. 'quoted' => ' Value',
  1869. 'multiline' => "Value\n Value",
  1870. 'array' => array(
  1871. 0 => 'Value1',
  1872. 1 => 'Value2',
  1873. ),
  1874. 'array_assoc' => array(
  1875. 'a' => 'Value1',
  1876. 'b' => 'Value2',
  1877. ),
  1878. 'array_deep' => array(
  1879. 0 => array(
  1880. 0 => array(
  1881. 0 => 'Value',
  1882. ),
  1883. ),
  1884. ),
  1885. 'array_deep_assoc' => array(
  1886. 'a' => array(
  1887. 'b' => array(
  1888. 'c' => 'Value',
  1889. ),
  1890. ),
  1891. ),
  1892. 'array_space' => array(
  1893. 'a b' => 'Value',
  1894. ),
  1895. );
  1896. $parsed = drupal_parse_info_format($config);
  1897. $this->assertEqual($parsed['simple'], $expected['simple'], 'Set a simple value.');
  1898. $this->assertEqual($parsed['quoted'], $expected['quoted'], 'Set a simple value in quotes.');
  1899. $this->assertEqual($parsed['multiline'], $expected['multiline'], 'Set a multiline value.');
  1900. $this->assertEqual($parsed['array'], $expected['array'], 'Set a simple array.');
  1901. $this->assertEqual($parsed['array_assoc'], $expected['array_assoc'], 'Set an associative array.');
  1902. $this->assertEqual($parsed['array_deep'], $expected['array_deep'], 'Set a nested array.');
  1903. $this->assertEqual($parsed['array_deep_assoc'], $expected['array_deep_assoc'], 'Set a nested associative array.');
  1904. $this->assertEqual($parsed['array_space'], $expected['array_space'], 'Set an array with a whitespace in the key.');
  1905. $this->assertEqual($parsed, $expected, 'Entire parsed .info string and expected array are identical.');
  1906. }
  1907. }
  1908. /**
  1909. * Tests the effectiveness of hook_system_info_alter().
  1910. */
  1911. class SystemInfoAlterTestCase extends DrupalWebTestCase {
  1912. public static function getInfo() {
  1913. return array(
  1914. 'name' => 'System info alter',
  1915. 'description' => 'Tests the effectiveness of hook_system_info_alter().',
  1916. 'group' => 'System',
  1917. );
  1918. }
  1919. /**
  1920. * Tests that {system}.info is rebuilt after a module that implements
  1921. * hook_system_info_alter() is enabled. Also tests if core *_list() functions
  1922. * return freshly altered info.
  1923. */
  1924. function testSystemInfoAlter() {
  1925. // Enable our test module. Flush all caches, which we assert is the only
  1926. // thing necessary to use the rebuilt {system}.info.
  1927. module_enable(array('module_test'), FALSE);
  1928. drupal_flush_all_caches();
  1929. $this->assertTrue(module_exists('module_test'), 'Test module is enabled.');
  1930. $info = $this->getSystemInfo('seven', 'theme');
  1931. $this->assertTrue(isset($info['regions']['test_region']), 'Altered theme info was added to {system}.info.');
  1932. $seven_regions = system_region_list('seven');
  1933. $this->assertTrue(isset($seven_regions['test_region']), 'Altered theme info was returned by system_region_list().');
  1934. $system_list_themes = system_list('theme');
  1935. $info = $system_list_themes['seven']->info;
  1936. $this->assertTrue(isset($info['regions']['test_region']), 'Altered theme info was returned by system_list().');
  1937. $list_themes = list_themes();
  1938. $this->assertTrue(isset($list_themes['seven']->info['regions']['test_region']), 'Altered theme info was returned by list_themes().');
  1939. // Disable the module and verify that {system}.info is rebuilt without it.
  1940. module_disable(array('module_test'), FALSE);
  1941. drupal_flush_all_caches();
  1942. $this->assertFalse(module_exists('module_test'), 'Test module is disabled.');
  1943. $info = $this->getSystemInfo('seven', 'theme');
  1944. $this->assertFalse(isset($info['regions']['test_region']), 'Altered theme info was removed from {system}.info.');
  1945. $seven_regions = system_region_list('seven');
  1946. $this->assertFalse(isset($seven_regions['test_region']), 'Altered theme info was not returned by system_region_list().');
  1947. $system_list_themes = system_list('theme');
  1948. $info = $system_list_themes['seven']->info;
  1949. $this->assertFalse(isset($info['regions']['test_region']), 'Altered theme info was not returned by system_list().');
  1950. $list_themes = list_themes();
  1951. $this->assertFalse(isset($list_themes['seven']->info['regions']['test_region']), 'Altered theme info was not returned by list_themes().');
  1952. }
  1953. /**
  1954. * Returns the info array as it is stored in {system}.
  1955. *
  1956. * @param $name
  1957. * The name of the record in {system}.
  1958. * @param $type
  1959. * The type of record in {system}.
  1960. *
  1961. * @return
  1962. * Array of info, or FALSE if the record is not found.
  1963. */
  1964. function getSystemInfo($name, $type) {
  1965. $raw_info = db_query("SELECT info FROM {system} WHERE name = :name AND type = :type", array(':name' => $name, ':type' => $type))->fetchField();
  1966. return $raw_info ? unserialize($raw_info) : FALSE;
  1967. }
  1968. }
  1969. /**
  1970. * Tests for the update system functionality.
  1971. */
  1972. class UpdateScriptFunctionalTest extends DrupalWebTestCase {
  1973. private $update_url;
  1974. private $update_user;
  1975. public static function getInfo() {
  1976. return array(
  1977. 'name' => 'Update functionality',
  1978. 'description' => 'Tests the update script access and functionality.',
  1979. 'group' => 'System',
  1980. );
  1981. }
  1982. function setUp() {
  1983. parent::setUp('update_script_test');
  1984. $this->update_url = $GLOBALS['base_url'] . '/update.php';
  1985. $this->update_user = $this->drupalCreateUser(array('administer software updates'));
  1986. }
  1987. /**
  1988. * Tests access to the update script.
  1989. */
  1990. function testUpdateAccess() {
  1991. // Try accessing update.php without the proper permission.
  1992. $regular_user = $this->drupalCreateUser();
  1993. $this->drupalLogin($regular_user);
  1994. $this->drupalGet($this->update_url, array('external' => TRUE));
  1995. $this->assertResponse(403);
  1996. // Try accessing update.php as an anonymous user.
  1997. $this->drupalLogout();
  1998. $this->drupalGet($this->update_url, array('external' => TRUE));
  1999. $this->assertResponse(403);
  2000. // Access the update page with the proper permission.
  2001. $this->drupalLogin($this->update_user);
  2002. $this->drupalGet($this->update_url, array('external' => TRUE));
  2003. $this->assertResponse(200);
  2004. // Access the update page as user 1.
  2005. $user1 = user_load(1);
  2006. $user1->pass_raw = user_password();
  2007. require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
  2008. $user1->pass = user_hash_password(trim($user1->pass_raw));
  2009. db_query("UPDATE {users} SET pass = :pass WHERE uid = :uid", array(':pass' => $user1->pass, ':uid' => $user1->uid));
  2010. $this->drupalLogin($user1);
  2011. $this->drupalGet($this->update_url, array('external' => TRUE));
  2012. $this->assertResponse(200);
  2013. }
  2014. /**
  2015. * Tests that requirements warnings and errors are correctly displayed.
  2016. */
  2017. function testRequirements() {
  2018. $this->drupalLogin($this->update_user);
  2019. // If there are no requirements warnings or errors, we expect to be able to
  2020. // go through the update process uninterrupted.
  2021. $this->drupalGet($this->update_url, array('external' => TRUE));
  2022. $this->drupalPost(NULL, array(), t('Continue'));
  2023. $this->assertText(t('No pending updates.'), 'End of update process was reached.');
  2024. // Confirm that all caches were cleared.
  2025. $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared when there were no requirements warnings or errors.');
  2026. // If there is a requirements warning, we expect it to be initially
  2027. // displayed, but clicking the link to proceed should allow us to go
  2028. // through the rest of the update process uninterrupted.
  2029. // First, run this test with pending updates to make sure they can be run
  2030. // successfully.
  2031. variable_set('update_script_test_requirement_type', REQUIREMENT_WARNING);
  2032. drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
  2033. $this->drupalGet($this->update_url, array('external' => TRUE));
  2034. $this->assertText('This is a requirements warning provided by the update_script_test module.');
  2035. $this->clickLink('try again');
  2036. $this->assertNoText('This is a requirements warning provided by the update_script_test module.');
  2037. $this->drupalPost(NULL, array(), t('Continue'));
  2038. $this->drupalPost(NULL, array(), t('Apply pending updates'));
  2039. $this->assertText(t('The update_script_test_update_7000() update was executed successfully.'), 'End of update process was reached.');
  2040. // Confirm that all caches were cleared.
  2041. $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared after resolving a requirements warning and applying updates.');
  2042. // Now try again without pending updates to make sure that works too.
  2043. $this->drupalGet($this->update_url, array('external' => TRUE));
  2044. $this->assertText('This is a requirements warning provided by the update_script_test module.');
  2045. $this->clickLink('try again');
  2046. $this->assertNoText('This is a requirements warning provided by the update_script_test module.');
  2047. $this->drupalPost(NULL, array(), t('Continue'));
  2048. $this->assertText(t('No pending updates.'), 'End of update process was reached.');
  2049. // Confirm that all caches were cleared.
  2050. $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared after applying updates and re-running the script.');
  2051. // If there is a requirements error, it should be displayed even after
  2052. // clicking the link to proceed (since the problem that triggered the error
  2053. // has not been fixed).
  2054. variable_set('update_script_test_requirement_type', REQUIREMENT_ERROR);
  2055. $this->drupalGet($this->update_url, array('external' => TRUE));
  2056. $this->assertText('This is a requirements error provided by the update_script_test module.');
  2057. $this->clickLink('try again');
  2058. $this->assertText('This is a requirements error provided by the update_script_test module.');
  2059. }
  2060. /**
  2061. * Tests the effect of using the update script on the theme system.
  2062. */
  2063. function testThemeSystem() {
  2064. // Since visiting update.php triggers a rebuild of the theme system from an
  2065. // unusual maintenance mode environment, we check that this rebuild did not
  2066. // put any incorrect information about the themes into the database.
  2067. $original_theme_data = db_query("SELECT * FROM {system} WHERE type = 'theme' ORDER BY name")->fetchAll();
  2068. $this->drupalLogin($this->update_user);
  2069. $this->drupalGet($this->update_url, array('external' => TRUE));
  2070. $final_theme_data = db_query("SELECT * FROM {system} WHERE type = 'theme' ORDER BY name")->fetchAll();
  2071. $this->assertEqual($original_theme_data, $final_theme_data, 'Visiting update.php does not alter the information about themes stored in the database.');
  2072. }
  2073. /**
  2074. * Tests update.php when there are no updates to apply.
  2075. */
  2076. function testNoUpdateFunctionality() {
  2077. // Click through update.php with 'administer software updates' permission.
  2078. $this->drupalLogin($this->update_user);
  2079. $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
  2080. $this->assertText(t('No pending updates.'));
  2081. $this->assertNoLink('Administration pages');
  2082. $this->clickLink('Front page');
  2083. $this->assertResponse(200);
  2084. // Click through update.php with 'access administration pages' permission.
  2085. $admin_user = $this->drupalCreateUser(array('administer software updates', 'access administration pages'));
  2086. $this->drupalLogin($admin_user);
  2087. $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
  2088. $this->assertText(t('No pending updates.'));
  2089. $this->clickLink('Administration pages');
  2090. $this->assertResponse(200);
  2091. }
  2092. /**
  2093. * Tests update.php after performing a successful update.
  2094. */
  2095. function testSuccessfulUpdateFunctionality() {
  2096. drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
  2097. // Click through update.php with 'administer software updates' permission.
  2098. $this->drupalLogin($this->update_user);
  2099. $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
  2100. $this->drupalPost(NULL, array(), t('Apply pending updates'));
  2101. $this->assertText('Updates were attempted.');
  2102. $this->assertLink('site');
  2103. $this->assertNoLink('Administration pages');
  2104. $this->assertNoLink('logged');
  2105. $this->clickLink('Front page');
  2106. $this->assertResponse(200);
  2107. drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
  2108. // Click through update.php with 'access administration pages' and
  2109. // 'access site reports' permissions.
  2110. $admin_user = $this->drupalCreateUser(array('administer software updates', 'access administration pages', 'access site reports'));
  2111. $this->drupalLogin($admin_user);
  2112. $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
  2113. $this->drupalPost(NULL, array(), t('Apply pending updates'));
  2114. $this->assertText('Updates were attempted.');
  2115. $this->assertLink('logged');
  2116. $this->clickLink('Administration pages');
  2117. $this->assertResponse(200);
  2118. }
  2119. }
  2120. /**
  2121. * Functional tests for the flood control mechanism.
  2122. */
  2123. class FloodFunctionalTest extends DrupalWebTestCase {
  2124. public static function getInfo() {
  2125. return array(
  2126. 'name' => 'Flood control mechanism',
  2127. 'description' => 'Functional tests for the flood control mechanism.',
  2128. 'group' => 'System',
  2129. );
  2130. }
  2131. /**
  2132. * Test flood control mechanism clean-up.
  2133. */
  2134. function testCleanUp() {
  2135. $threshold = 1;
  2136. $window_expired = -1;
  2137. $name = 'flood_test_cleanup';
  2138. // Register expired event.
  2139. flood_register_event($name, $window_expired);
  2140. // Verify event is not allowed.
  2141. $this->assertFalse(flood_is_allowed($name, $threshold));
  2142. // Run cron and verify event is now allowed.
  2143. $this->cronRun();
  2144. $this->assertTrue(flood_is_allowed($name, $threshold));
  2145. // Register unexpired event.
  2146. flood_register_event($name);
  2147. // Verify event is not allowed.
  2148. $this->assertFalse(flood_is_allowed($name, $threshold));
  2149. // Run cron and verify event is still not allowed.
  2150. $this->cronRun();
  2151. $this->assertFalse(flood_is_allowed($name, $threshold));
  2152. }
  2153. }
  2154. /**
  2155. * Test HTTP file downloading capability.
  2156. */
  2157. class RetrieveFileTestCase extends DrupalWebTestCase {
  2158. public static function getInfo() {
  2159. return array(
  2160. 'name' => 'HTTP file retrieval',
  2161. 'description' => 'Checks HTTP file fetching and error handling.',
  2162. 'group' => 'System',
  2163. );
  2164. }
  2165. /**
  2166. * Invokes system_retrieve_file() in several scenarios.
  2167. */
  2168. function testFileRetrieving() {
  2169. // Test 404 handling by trying to fetch a randomly named file.
  2170. drupal_mkdir($sourcedir = 'public://' . $this->randomName());
  2171. $filename = 'Файл для тестирования ' . $this->randomName();
  2172. $url = file_create_url($sourcedir . '/' . $filename);
  2173. $retrieved_file = system_retrieve_file($url);
  2174. $this->assertFalse($retrieved_file, 'Non-existent file not fetched.');
  2175. // Actually create that file, download it via HTTP and test the returned path.
  2176. file_put_contents($sourcedir . '/' . $filename, 'testing');
  2177. $retrieved_file = system_retrieve_file($url);
  2178. // URLs could not contains characters outside the ASCII set so $filename
  2179. // has to be encoded.
  2180. $encoded_filename = rawurlencode($filename);
  2181. $this->assertEqual($retrieved_file, 'public://' . $encoded_filename, 'Sane path for downloaded file returned (public:// scheme).');
  2182. $this->assertTrue(is_file($retrieved_file), 'Downloaded file does exist (public:// scheme).');
  2183. $this->assertEqual(filesize($retrieved_file), 7, 'File size of downloaded file is correct (public:// scheme).');
  2184. file_unmanaged_delete($retrieved_file);
  2185. // Test downloading file to a different location.
  2186. drupal_mkdir($targetdir = 'temporary://' . $this->randomName());
  2187. $retrieved_file = system_retrieve_file($url, $targetdir);
  2188. $this->assertEqual($retrieved_file, "$targetdir/$encoded_filename", 'Sane path for downloaded file returned (temporary:// scheme).');
  2189. $this->assertTrue(is_file($retrieved_file), 'Downloaded file does exist (temporary:// scheme).');
  2190. $this->assertEqual(filesize($retrieved_file), 7, 'File size of downloaded file is correct (temporary:// scheme).');
  2191. file_unmanaged_delete($retrieved_file);
  2192. file_unmanaged_delete_recursive($sourcedir);
  2193. file_unmanaged_delete_recursive($targetdir);
  2194. }
  2195. }
  2196. /**
  2197. * Functional tests shutdown functions.
  2198. */
  2199. class ShutdownFunctionsTest extends DrupalWebTestCase {
  2200. public static function getInfo() {
  2201. return array(
  2202. 'name' => 'Shutdown functions',
  2203. 'description' => 'Functional tests for shutdown functions',
  2204. 'group' => 'System',
  2205. );
  2206. }
  2207. function setUp() {
  2208. parent::setUp('system_test');
  2209. }
  2210. /**
  2211. * Test shutdown functions.
  2212. */
  2213. function testShutdownFunctions() {
  2214. $arg1 = $this->randomName();
  2215. $arg2 = $this->randomName();
  2216. $this->drupalGet('system-test/shutdown-functions/' . $arg1 . '/' . $arg2);
  2217. $this->assertText(t('First shutdown function, arg1 : @arg1, arg2: @arg2', array('@arg1' => $arg1, '@arg2' => $arg2)));
  2218. $this->assertText(t('Second shutdown function, arg1 : @arg1, arg2: @arg2', array('@arg1' => $arg1, '@arg2' => $arg2)));
  2219. // Make sure exceptions displayed through _drupal_render_exception_safe()
  2220. // are correctly escaped.
  2221. $this->assertRaw('Drupal is &amp;lt;blink&amp;gt;awesome&amp;lt;/blink&amp;gt;.');
  2222. }
  2223. }
  2224. /**
  2225. * Tests administrative overview pages.
  2226. */
  2227. class SystemAdminTestCase extends DrupalWebTestCase {
  2228. public static function getInfo() {
  2229. return array(
  2230. 'name' => 'Administrative pages',
  2231. 'description' => 'Tests output on administrative pages and compact mode functionality.',
  2232. 'group' => 'System',
  2233. );
  2234. }
  2235. function setUp() {
  2236. // testAdminPages() requires Locale module.
  2237. parent::setUp(array('locale'));
  2238. // Create an administrator with all permissions, as well as a regular user
  2239. // who can only access administration pages and perform some Locale module
  2240. // administrative tasks, but not all of them.
  2241. $this->admin_user = $this->drupalCreateUser(array_keys(module_invoke_all('permission')));
  2242. $this->web_user = $this->drupalCreateUser(array(
  2243. 'access administration pages',
  2244. 'translate interface',
  2245. ));
  2246. $this->drupalLogin($this->admin_user);
  2247. }
  2248. /**
  2249. * Tests output on administrative listing pages.
  2250. */
  2251. function testAdminPages() {
  2252. // Go to Administration.
  2253. $this->drupalGet('admin');
  2254. // Verify that all visible, top-level administration links are listed on
  2255. // the main administration page.
  2256. foreach (menu_get_router() as $path => $item) {
  2257. if (strpos($path, 'admin/') === 0 && ($item['type'] & MENU_VISIBLE_IN_TREE) && $item['_number_parts'] == 2) {
  2258. $this->assertLink($item['title']);
  2259. $this->assertLinkByHref($path);
  2260. $this->assertText($item['description']);
  2261. }
  2262. }
  2263. // For each administrative listing page on which the Locale module appears,
  2264. // verify that there are links to the module's primary configuration pages,
  2265. // but no links to its individual sub-configuration pages. Also verify that
  2266. // a user with access to only some Locale module administration pages only
  2267. // sees links to the pages they have access to.
  2268. $admin_list_pages = array(
  2269. 'admin/index',
  2270. 'admin/config',
  2271. 'admin/config/regional',
  2272. );
  2273. foreach ($admin_list_pages as $page) {
  2274. // For the administrator, verify that there are links to Locale's primary
  2275. // configuration pages, but no links to individual sub-configuration
  2276. // pages.
  2277. $this->drupalLogin($this->admin_user);
  2278. $this->drupalGet($page);
  2279. $this->assertLinkByHref('admin/config');
  2280. $this->assertLinkByHref('admin/config/regional/settings');
  2281. $this->assertLinkByHref('admin/config/regional/date-time');
  2282. $this->assertLinkByHref('admin/config/regional/language');
  2283. $this->assertNoLinkByHref('admin/config/regional/language/configure/session');
  2284. $this->assertNoLinkByHref('admin/config/regional/language/configure/url');
  2285. $this->assertLinkByHref('admin/config/regional/translate');
  2286. // On admin/index only, the administrator should also see a "Configure
  2287. // permissions" link for the Locale module.
  2288. if ($page == 'admin/index') {
  2289. $this->assertLinkByHref("admin/people/permissions#module-locale");
  2290. }
  2291. // For a less privileged user, verify that there are no links to Locale's
  2292. // primary configuration pages, but a link to the translate page exists.
  2293. $this->drupalLogin($this->web_user);
  2294. $this->drupalGet($page);
  2295. $this->assertLinkByHref('admin/config');
  2296. $this->assertNoLinkByHref('admin/config/regional/settings');
  2297. $this->assertNoLinkByHref('admin/config/regional/date-time');
  2298. $this->assertNoLinkByHref('admin/config/regional/language');
  2299. $this->assertNoLinkByHref('admin/config/regional/language/configure/session');
  2300. $this->assertNoLinkByHref('admin/config/regional/language/configure/url');
  2301. $this->assertLinkByHref('admin/config/regional/translate');
  2302. // This user cannot configure permissions, so even on admin/index should
  2303. // not see a "Configure permissions" link for the Locale module.
  2304. if ($page == 'admin/index') {
  2305. $this->assertNoLinkByHref("admin/people/permissions#module-locale");
  2306. }
  2307. }
  2308. }
  2309. /**
  2310. * Test compact mode.
  2311. */
  2312. function testCompactMode() {
  2313. $this->drupalGet('admin/compact/on');
  2314. $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode turns on.');
  2315. $this->drupalGet('admin/compact/on');
  2316. $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode remains on after a repeat call.');
  2317. $this->drupalGet('');
  2318. $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode persists on new requests.');
  2319. $this->drupalGet('admin/compact/off');
  2320. $this->assertEqual($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'deleted', 'Compact mode turns off.');
  2321. $this->drupalGet('admin/compact/off');
  2322. $this->assertEqual($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'deleted', 'Compact mode remains off after a repeat call.');
  2323. $this->drupalGet('');
  2324. $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode persists on new requests.');
  2325. }
  2326. }
  2327. /**
  2328. * Tests authorize.php and related hooks.
  2329. */
  2330. class SystemAuthorizeCase extends DrupalWebTestCase {
  2331. public static function getInfo() {
  2332. return array(
  2333. 'name' => 'Authorize API',
  2334. 'description' => 'Tests the authorize.php script and related API.',
  2335. 'group' => 'System',
  2336. );
  2337. }
  2338. function setUp() {
  2339. parent::setUp(array('system_test'));
  2340. variable_set('allow_authorize_operations', TRUE);
  2341. // Create an administrator user.
  2342. $this->admin_user = $this->drupalCreateUser(array('administer software updates'));
  2343. $this->drupalLogin($this->admin_user);
  2344. }
  2345. /**
  2346. * Helper function to initialize authorize.php and load it via drupalGet().
  2347. *
  2348. * Initializing authorize.php needs to happen in the child Drupal
  2349. * installation, not the parent. So, we visit a menu callback provided by
  2350. * system_test.module which calls system_authorized_init() to initialize the
  2351. * $_SESSION inside the test site, not the framework site. This callback
  2352. * redirects to authorize.php when it's done initializing.
  2353. *
  2354. * @see system_authorized_init().
  2355. */
  2356. function drupalGetAuthorizePHP($page_title = 'system-test-auth') {
  2357. $this->drupalGet('system-test/authorize-init/' . $page_title);
  2358. }
  2359. /**
  2360. * Tests the FileTransfer hooks
  2361. */
  2362. function testFileTransferHooks() {
  2363. $page_title = $this->randomName(16);
  2364. $this->drupalGetAuthorizePHP($page_title);
  2365. $this->assertTitle(strtr('@title | Drupal', array('@title' => $page_title)), 'authorize.php page title is correct.');
  2366. $this->assertNoText('It appears you have reached this page in error.');
  2367. $this->assertText('To continue, provide your server connection details');
  2368. // Make sure we see the new connection method added by system_test.
  2369. $this->assertRaw('System Test FileTransfer');
  2370. // Make sure the settings form callback works.
  2371. $this->assertText('System Test Username');
  2372. }
  2373. }
  2374. /**
  2375. * Test the handling of requests containing 'index.php'.
  2376. */
  2377. class SystemIndexPhpTest extends DrupalWebTestCase {
  2378. public static function getInfo() {
  2379. return array(
  2380. 'name' => 'Index.php handling',
  2381. 'description' => "Test the handling of requests containing 'index.php'.",
  2382. 'group' => 'System',
  2383. );
  2384. }
  2385. function setUp() {
  2386. parent::setUp();
  2387. }
  2388. /**
  2389. * Test index.php handling.
  2390. */
  2391. function testIndexPhpHandling() {
  2392. $index_php = $GLOBALS['base_url'] . '/index.php';
  2393. $this->drupalGet($index_php, array('external' => TRUE));
  2394. $this->assertResponse(200, 'Make sure index.php returns a valid page.');
  2395. $this->drupalGet($index_php, array('external' => TRUE, 'query' => array('q' => 'user')));
  2396. $this->assertResponse(200, 'Make sure index.php?q=user returns a valid page.');
  2397. $this->drupalGet($index_php .'/user', array('external' => TRUE));
  2398. $this->assertResponse(404, "Make sure index.php/user returns a 'page not found'.");
  2399. }
  2400. }
  2401. /**
  2402. * Test token replacement in strings.
  2403. */
  2404. class TokenScanTest extends DrupalWebTestCase {
  2405. public static function getInfo() {
  2406. return array(
  2407. 'name' => 'Token scanning',
  2408. 'description' => 'Scan token-like patterns in a dummy text to check token scanning.',
  2409. 'group' => 'System',
  2410. );
  2411. }
  2412. /**
  2413. * Scans dummy text, then tests the output.
  2414. */
  2415. function testTokenScan() {
  2416. // Define text with valid and not valid, fake and existing token-like
  2417. // strings.
  2418. $text = 'First a [valid:simple], but dummy token, and a dummy [valid:token with: spaces].';
  2419. $text .= 'Then a [not valid:token].';
  2420. $text .= 'Last an existing token: [node:author:name].';
  2421. $token_wannabes = token_scan($text);
  2422. $this->assertTrue(isset($token_wannabes['valid']['simple']), 'A simple valid token has been matched.');
  2423. $this->assertTrue(isset($token_wannabes['valid']['token with: spaces']), 'A valid token with space characters in the token name has been matched.');
  2424. $this->assertFalse(isset($token_wannabes['not valid']), 'An invalid token with spaces in the token type has not been matched.');
  2425. $this->assertTrue(isset($token_wannabes['node']), 'An existing valid token has been matched.');
  2426. }
  2427. }
  2428. /**
  2429. * Test case for drupal_valid_token().
  2430. */
  2431. class SystemValidTokenTest extends DrupalUnitTestCase {
  2432. /**
  2433. * Flag to indicate whether PHP error reportings should be asserted.
  2434. *
  2435. * @var bool
  2436. */
  2437. protected $assertErrors = TRUE;
  2438. public static function getInfo() {
  2439. return array(
  2440. 'name' => 'Token validation',
  2441. 'description' => 'Test the security token validation.',
  2442. 'group' => 'System',
  2443. );
  2444. }
  2445. /**
  2446. * Tests invalid invocations of drupal_valid_token() that must return FALSE.
  2447. */
  2448. public function testTokenValidation() {
  2449. // The following checks will throw PHP notices, so we disable error
  2450. // assertions.
  2451. $this->assertErrors = FALSE;
  2452. $this->assertFalse(drupal_valid_token(NULL, new stdClass()), 'Token NULL, value object returns FALSE.');
  2453. $this->assertFalse(drupal_valid_token(0, array()), 'Token 0, value array returns FALSE.');
  2454. $this->assertFalse(drupal_valid_token('', array()), "Token '', value array returns FALSE.");
  2455. $this->assertFalse('' === drupal_get_token(array()), 'Token generation does not return an empty string on invalid parameters.');
  2456. $this->assertErrors = TRUE;
  2457. $this->assertFalse(drupal_valid_token(TRUE, 'foo'), 'Token TRUE, value foo returns FALSE.');
  2458. $this->assertFalse(drupal_valid_token(0, 'foo'), 'Token 0, value foo returns FALSE.');
  2459. }
  2460. /**
  2461. * Overrides DrupalTestCase::errorHandler().
  2462. */
  2463. public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
  2464. if ($this->assertErrors) {
  2465. return parent::errorHandler($severity, $message, $file, $line);
  2466. }
  2467. return TRUE;
  2468. }
  2469. }
  2470. /**
  2471. * Tests drupal_set_message() and related functions.
  2472. */
  2473. class DrupalSetMessageTest extends DrupalWebTestCase {
  2474. public static function getInfo() {
  2475. return array(
  2476. 'name' => 'Messages',
  2477. 'description' => 'Tests that messages can be displayed using drupal_set_message().',
  2478. 'group' => 'System',
  2479. );
  2480. }
  2481. function setUp() {
  2482. parent::setUp('system_test');
  2483. }
  2484. /**
  2485. * Tests setting messages and removing one before it is displayed.
  2486. */
  2487. function testSetRemoveMessages() {
  2488. // The page at system-test/drupal-set-message sets two messages and then
  2489. // removes the first before it is displayed.
  2490. $this->drupalGet('system-test/drupal-set-message');
  2491. $this->assertNoText('First message (removed).');
  2492. $this->assertText('Second message (not removed).');
  2493. }
  2494. }
  2495. /**
  2496. * Tests confirm form destinations.
  2497. */
  2498. class ConfirmFormTest extends DrupalWebTestCase {
  2499. protected $admin_user;
  2500. public static function getInfo() {
  2501. return array(
  2502. 'name' => 'Confirm form',
  2503. 'description' => 'Tests that the confirm form does not use external destinations.',
  2504. 'group' => 'System',
  2505. );
  2506. }
  2507. function setUp() {
  2508. parent::setUp();
  2509. $this->admin_user = $this->drupalCreateUser(array('administer users'));
  2510. $this->drupalLogin($this->admin_user);
  2511. }
  2512. /**
  2513. * Tests that the confirm form does not use external destinations.
  2514. */
  2515. function testConfirmForm() {
  2516. $this->drupalGet('user/1/cancel');
  2517. $this->assertCancelLinkUrl(url('user/1'));
  2518. $this->drupalGet('user/1/cancel', array('query' => array('destination' => 'node')));
  2519. $this->assertCancelLinkUrl(url('node'));
  2520. $this->drupalGet('user/1/cancel', array('query' => array('destination' => 'http://example.com')));
  2521. $this->assertCancelLinkUrl(url('user/1'));
  2522. }
  2523. /**
  2524. * Asserts that a cancel link is present pointing to the provided URL.
  2525. */
  2526. function assertCancelLinkUrl($url, $message = '', $group = 'Other') {
  2527. $links = $this->xpath('//a[normalize-space(text())=:label and @href=:url]', array(':label' => t('Cancel'), ':url' => $url));
  2528. $message = ($message ? $message : format_string('Cancel link with url %url found.', array('%url' => $url)));
  2529. return $this->assertTrue(isset($links[0]), $message, $group);
  2530. }
  2531. }