system.test 113 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899
  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. // Use a custom 404 page.
  940. $this->drupalPost('admin/config/system/site-information', array('site_404' => 'node/' . $node->nid), t('Save configuration'));
  941. $this->drupalGet($this->randomName(10));
  942. $this->assertText($node->title, 'Found the custom 404 page');
  943. }
  944. }
  945. /**
  946. * Tests site maintenance functionality.
  947. */
  948. class SiteMaintenanceTestCase extends DrupalWebTestCase {
  949. protected $admin_user;
  950. public static function getInfo() {
  951. return array(
  952. 'name' => 'Site maintenance mode functionality',
  953. 'description' => 'Test access to site while in maintenance mode.',
  954. 'group' => 'System',
  955. );
  956. }
  957. function setUp() {
  958. parent::setUp();
  959. // Create a user allowed to access site in maintenance mode.
  960. $this->user = $this->drupalCreateUser(array('access site in maintenance mode'));
  961. // Create an administrative user.
  962. $this->admin_user = $this->drupalCreateUser(array('administer site configuration', 'access site in maintenance mode'));
  963. $this->drupalLogin($this->admin_user);
  964. }
  965. /**
  966. * Verify site maintenance mode functionality.
  967. */
  968. function testSiteMaintenance() {
  969. // Turn on maintenance mode.
  970. $edit = array(
  971. 'maintenance_mode' => 1,
  972. );
  973. $this->drupalPost('admin/config/development/maintenance', $edit, t('Save configuration'));
  974. $admin_message = t('Operating in maintenance mode. <a href="@url">Go online.</a>', array('@url' => url('admin/config/development/maintenance')));
  975. $user_message = t('Operating in maintenance mode.');
  976. $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')));
  977. $this->drupalGet('');
  978. $this->assertRaw($admin_message, 'Found the site maintenance mode message.');
  979. // Logout and verify that offline message is displayed.
  980. $this->drupalLogout();
  981. $this->drupalGet('');
  982. $this->assertText($offline_message);
  983. $this->drupalGet('node');
  984. $this->assertText($offline_message);
  985. $this->drupalGet('user/register');
  986. $this->assertText($offline_message);
  987. // Verify that user is able to log in.
  988. $this->drupalGet('user');
  989. $this->assertNoText($offline_message);
  990. $this->drupalGet('user/login');
  991. $this->assertNoText($offline_message);
  992. // Log in user and verify that maintenance mode message is displayed
  993. // directly after login.
  994. $edit = array(
  995. 'name' => $this->user->name,
  996. 'pass' => $this->user->pass_raw,
  997. );
  998. $this->drupalPost(NULL, $edit, t('Log in'));
  999. $this->assertText($user_message);
  1000. // Log in administrative user and configure a custom site offline message.
  1001. $this->drupalLogout();
  1002. $this->drupalLogin($this->admin_user);
  1003. $this->drupalGet('admin/config/development/maintenance');
  1004. $this->assertNoRaw($admin_message, 'Site maintenance mode message not displayed.');
  1005. $offline_message = 'Sorry, not online.';
  1006. $edit = array(
  1007. 'maintenance_mode_message' => $offline_message,
  1008. );
  1009. $this->drupalPost(NULL, $edit, t('Save configuration'));
  1010. // Logout and verify that custom site offline message is displayed.
  1011. $this->drupalLogout();
  1012. $this->drupalGet('');
  1013. $this->assertRaw($offline_message, 'Found the site offline message.');
  1014. // Verify that custom site offline message is not displayed on user/password.
  1015. $this->drupalGet('user/password');
  1016. $this->assertText(t('Username or e-mail address'), 'Anonymous users can access user/password');
  1017. // Submit password reset form.
  1018. $edit = array(
  1019. 'name' => $this->user->name,
  1020. );
  1021. $this->drupalPost('user/password', $edit, t('E-mail new password'));
  1022. $mails = $this->drupalGetMails();
  1023. $start = strpos($mails[0]['body'], 'user/reset/'. $this->user->uid);
  1024. $path = substr($mails[0]['body'], $start, 66 + strlen($this->user->uid));
  1025. // Log in with temporary login link.
  1026. $this->drupalPost($path, array(), t('Log in'));
  1027. $this->assertText($user_message);
  1028. }
  1029. }
  1030. /**
  1031. * Tests generic date and time handling capabilities of Drupal.
  1032. */
  1033. class DateTimeFunctionalTest extends DrupalWebTestCase {
  1034. public static function getInfo() {
  1035. return array(
  1036. 'name' => 'Date and time',
  1037. 'description' => 'Configure date and time settings. Test date formatting and time zone handling, including daylight saving time.',
  1038. 'group' => 'System',
  1039. );
  1040. }
  1041. function setUp() {
  1042. parent::setUp(array('locale'));
  1043. // Create admin user and log in admin user.
  1044. $this->admin_user = $this->drupalCreateUser(array('administer site configuration'));
  1045. $this->drupalLogin($this->admin_user);
  1046. }
  1047. /**
  1048. * Test time zones and DST handling.
  1049. */
  1050. function testTimeZoneHandling() {
  1051. // Setup date/time settings for Honolulu time.
  1052. variable_set('date_default_timezone', 'Pacific/Honolulu');
  1053. variable_set('configurable_timezones', 0);
  1054. variable_set('date_format_medium', 'Y-m-d H:i:s O');
  1055. // Create some nodes with different authored-on dates.
  1056. $date1 = '2007-01-31 21:00:00 -1000';
  1057. $date2 = '2007-07-31 21:00:00 -1000';
  1058. $node1 = $this->drupalCreateNode(array('created' => strtotime($date1), 'type' => 'article'));
  1059. $node2 = $this->drupalCreateNode(array('created' => strtotime($date2), 'type' => 'article'));
  1060. // Confirm date format and time zone.
  1061. $this->drupalGet("node/$node1->nid");
  1062. $this->assertText('2007-01-31 21:00:00 -1000', 'Date should be identical, with GMT offset of -10 hours.');
  1063. $this->drupalGet("node/$node2->nid");
  1064. $this->assertText('2007-07-31 21:00:00 -1000', 'Date should be identical, with GMT offset of -10 hours.');
  1065. // Set time zone to Los Angeles time.
  1066. variable_set('date_default_timezone', 'America/Los_Angeles');
  1067. // Confirm date format and time zone.
  1068. $this->drupalGet("node/$node1->nid");
  1069. $this->assertText('2007-01-31 23:00:00 -0800', 'Date should be two hours ahead, with GMT offset of -8 hours.');
  1070. $this->drupalGet("node/$node2->nid");
  1071. $this->assertText('2007-08-01 00:00:00 -0700', 'Date should be three hours ahead, with GMT offset of -7 hours.');
  1072. }
  1073. /**
  1074. * Test date type configuration.
  1075. */
  1076. function testDateTypeConfiguration() {
  1077. // Confirm system date types appear.
  1078. $this->drupalGet('admin/config/regional/date-time');
  1079. $this->assertText(t('Medium'), 'System date types appear in date type list.');
  1080. $this->assertNoRaw('href="/admin/config/regional/date-time/types/medium/delete"', 'No delete link appear for system date types.');
  1081. // Add custom date type.
  1082. $this->clickLink(t('Add date type'));
  1083. $date_type = strtolower($this->randomName(8));
  1084. $machine_name = 'machine_' . $date_type;
  1085. $date_format = 'd.m.Y - H:i';
  1086. $edit = array(
  1087. 'date_type' => $date_type,
  1088. 'machine_name' => $machine_name,
  1089. 'date_format' => $date_format,
  1090. );
  1091. $this->drupalPost('admin/config/regional/date-time/types/add', $edit, t('Add date type'));
  1092. $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time', array('absolute' => TRUE)), 'Correct page redirection.');
  1093. $this->assertText(t('New date type added successfully.'), 'Date type added confirmation message appears.');
  1094. $this->assertText($date_type, 'Custom date type appears in the date type list.');
  1095. $this->assertText(t('delete'), 'Delete link for custom date type appears.');
  1096. // Delete custom date type.
  1097. $this->clickLink(t('delete'));
  1098. $this->drupalPost('admin/config/regional/date-time/types/' . $machine_name . '/delete', array(), t('Remove'));
  1099. $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time', array('absolute' => TRUE)), 'Correct page redirection.');
  1100. $this->assertText(t('Removed date type ' . $date_type), 'Custom date type removed.');
  1101. }
  1102. /**
  1103. * Test date format configuration.
  1104. */
  1105. function testDateFormatConfiguration() {
  1106. // Confirm 'no custom date formats available' message appears.
  1107. $this->drupalGet('admin/config/regional/date-time/formats');
  1108. $this->assertText(t('No custom date formats available.'), 'No custom date formats message appears.');
  1109. // Add custom date format.
  1110. $this->clickLink(t('Add format'));
  1111. $edit = array(
  1112. 'date_format' => 'Y',
  1113. );
  1114. $this->drupalPost('admin/config/regional/date-time/formats/add', $edit, t('Add format'));
  1115. $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE)), 'Correct page redirection.');
  1116. $this->assertNoText(t('No custom date formats available.'), 'No custom date formats message does not appear.');
  1117. $this->assertText(t('Custom date format added.'), 'Custom date format added.');
  1118. // Ensure custom date format appears in date type configuration options.
  1119. $this->drupalGet('admin/config/regional/date-time');
  1120. $this->assertRaw('<option value="Y">', 'Custom date format appears in options.');
  1121. // Edit custom date format.
  1122. $this->drupalGet('admin/config/regional/date-time/formats');
  1123. $this->clickLink(t('edit'));
  1124. $edit = array(
  1125. 'date_format' => 'Y m',
  1126. );
  1127. $this->drupalPost($this->getUrl(), $edit, t('Save format'));
  1128. $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE)), 'Correct page redirection.');
  1129. $this->assertText(t('Custom date format updated.'), 'Custom date format successfully updated.');
  1130. // Delete custom date format.
  1131. $this->clickLink(t('delete'));
  1132. $this->drupalPost($this->getUrl(), array(), t('Remove'));
  1133. $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE)), 'Correct page redirection.');
  1134. $this->assertText(t('Removed date format'), 'Custom date format removed successfully.');
  1135. }
  1136. /**
  1137. * Test if the date formats are stored properly.
  1138. */
  1139. function testDateFormatStorage() {
  1140. $date_format = array(
  1141. 'type' => 'short',
  1142. 'format' => 'dmYHis',
  1143. 'locked' => 0,
  1144. 'is_new' => 1,
  1145. );
  1146. system_date_format_save($date_format);
  1147. $format = db_select('date_formats', 'df')
  1148. ->fields('df', array('format'))
  1149. ->condition('type', 'short')
  1150. ->condition('format', 'dmYHis')
  1151. ->execute()
  1152. ->fetchField();
  1153. $this->verbose($format);
  1154. $this->assertEqual('dmYHis', $format, 'Unlocalized date format resides in general table.');
  1155. $format = db_select('date_format_locale', 'dfl')
  1156. ->fields('dfl', array('format'))
  1157. ->condition('type', 'short')
  1158. ->condition('format', 'dmYHis')
  1159. ->execute()
  1160. ->fetchField();
  1161. $this->assertFalse($format, 'Unlocalized date format resides not in localized table.');
  1162. // Enable German language
  1163. locale_add_language('de', NULL, NULL, LANGUAGE_LTR, '', '', TRUE, 'en');
  1164. $date_format = array(
  1165. 'type' => 'short',
  1166. 'format' => 'YMDHis',
  1167. 'locales' => array('de', 'tr'),
  1168. 'locked' => 0,
  1169. 'is_new' => 1,
  1170. );
  1171. system_date_format_save($date_format);
  1172. $format = db_select('date_format_locale', 'dfl')
  1173. ->fields('dfl', array('format'))
  1174. ->condition('type', 'short')
  1175. ->condition('format', 'YMDHis')
  1176. ->condition('language', 'de')
  1177. ->execute()
  1178. ->fetchField();
  1179. $this->assertEqual('YMDHis', $format, 'Localized date format resides in localized table.');
  1180. $format = db_select('date_formats', 'df')
  1181. ->fields('df', array('format'))
  1182. ->condition('type', 'short')
  1183. ->condition('format', 'YMDHis')
  1184. ->execute()
  1185. ->fetchField();
  1186. $this->assertEqual('YMDHis', $format, 'Localized date format resides in general table too.');
  1187. $format = db_select('date_format_locale', 'dfl')
  1188. ->fields('dfl', array('format'))
  1189. ->condition('type', 'short')
  1190. ->condition('format', 'YMDHis')
  1191. ->condition('language', 'tr')
  1192. ->execute()
  1193. ->fetchColumn();
  1194. $this->assertFalse($format, 'Localized date format for disabled language is ignored.');
  1195. }
  1196. }
  1197. class PageTitleFiltering extends DrupalWebTestCase {
  1198. protected $content_user;
  1199. protected $saved_title;
  1200. /**
  1201. * Implement getInfo().
  1202. */
  1203. public static function getInfo() {
  1204. return array(
  1205. 'name' => 'HTML in page titles',
  1206. 'description' => 'Tests correct handling or conversion by drupal_set_title() and drupal_get_title() and checks the correct escaping of site name and slogan.',
  1207. 'group' => 'System'
  1208. );
  1209. }
  1210. /**
  1211. * Implement setUp().
  1212. */
  1213. function setUp() {
  1214. parent::setUp();
  1215. $this->content_user = $this->drupalCreateUser(array('create page content', 'access content', 'administer themes', 'administer site configuration'));
  1216. $this->drupalLogin($this->content_user);
  1217. $this->saved_title = drupal_get_title();
  1218. }
  1219. /**
  1220. * Reset page title.
  1221. */
  1222. function tearDown() {
  1223. // Restore the page title.
  1224. drupal_set_title($this->saved_title, PASS_THROUGH);
  1225. parent::tearDown();
  1226. }
  1227. /**
  1228. * Tests the handling of HTML by drupal_set_title() and drupal_get_title()
  1229. */
  1230. function testTitleTags() {
  1231. $title = "string with <em>HTML</em>";
  1232. // drupal_set_title's $filter is CHECK_PLAIN by default, so the title should be
  1233. // returned with check_plain().
  1234. drupal_set_title($title, CHECK_PLAIN);
  1235. $this->assertTrue(strpos(drupal_get_title(), '<em>') === FALSE, 'Tags in title converted to entities when $output is CHECK_PLAIN.');
  1236. // drupal_set_title's $filter is passed as PASS_THROUGH, so the title should be
  1237. // returned with HTML.
  1238. drupal_set_title($title, PASS_THROUGH);
  1239. $this->assertTrue(strpos(drupal_get_title(), '<em>') !== FALSE, 'Tags in title are not converted to entities when $output is PASS_THROUGH.');
  1240. // Generate node content.
  1241. $langcode = LANGUAGE_NONE;
  1242. $edit = array(
  1243. "title" => '!SimpleTest! ' . $title . $this->randomName(20),
  1244. "body[$langcode][0][value]" => '!SimpleTest! test body' . $this->randomName(200),
  1245. );
  1246. // Create the node with HTML in the title.
  1247. $this->drupalPost('node/add/page', $edit, t('Save'));
  1248. $node = $this->drupalGetNodeByTitle($edit["title"]);
  1249. $this->assertNotNull($node, 'Node created and found in database');
  1250. $this->drupalGet("node/" . $node->nid);
  1251. $this->assertText(check_plain($edit["title"]), 'Check to make sure tags in the node title are converted.');
  1252. }
  1253. /**
  1254. * Test if the title of the site is XSS proof.
  1255. */
  1256. function testTitleXSS() {
  1257. // Set some title with JavaScript and HTML chars to escape.
  1258. $title = '</title><script type="text/javascript">alert("Title XSS!");</script> & < > " \' ';
  1259. $title_filtered = check_plain($title);
  1260. $slogan = '<script type="text/javascript">alert("Slogan XSS!");</script>';
  1261. $slogan_filtered = filter_xss_admin($slogan);
  1262. // Activate needed appearance settings.
  1263. $edit = array(
  1264. 'toggle_name' => TRUE,
  1265. 'toggle_slogan' => TRUE,
  1266. 'toggle_main_menu' => TRUE,
  1267. 'toggle_secondary_menu' => TRUE,
  1268. );
  1269. $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
  1270. // Set title and slogan.
  1271. $edit = array(
  1272. 'site_name' => $title,
  1273. 'site_slogan' => $slogan,
  1274. );
  1275. $this->drupalPost('admin/config/system/site-information', $edit, t('Save configuration'));
  1276. // Load frontpage.
  1277. $this->drupalGet('');
  1278. // Test the title.
  1279. $this->assertNoRaw($title, 'Check for the unfiltered version of the title.');
  1280. // Adding </title> so we do not test the escaped version from drupal_set_title().
  1281. $this->assertRaw($title_filtered . '</title>', 'Check for the filtered version of the title.');
  1282. // Test the slogan.
  1283. $this->assertNoRaw($slogan, 'Check for the unfiltered version of the slogan.');
  1284. $this->assertRaw($slogan_filtered, 'Check for the filtered version of the slogan.');
  1285. }
  1286. }
  1287. /**
  1288. * Test front page functionality and administration.
  1289. */
  1290. class FrontPageTestCase extends DrupalWebTestCase {
  1291. public static function getInfo() {
  1292. return array(
  1293. 'name' => 'Front page',
  1294. 'description' => 'Tests front page functionality and administration.',
  1295. 'group' => 'System',
  1296. );
  1297. }
  1298. function setUp() {
  1299. parent::setUp('system_test');
  1300. // Create admin user, log in admin user, and create one node.
  1301. $this->admin_user = $this->drupalCreateUser(array('access content', 'administer site configuration'));
  1302. $this->drupalLogin($this->admin_user);
  1303. $this->node_path = "node/" . $this->drupalCreateNode(array('promote' => 1))->nid;
  1304. // Enable front page logging in system_test.module.
  1305. variable_set('front_page_output', 1);
  1306. }
  1307. /**
  1308. * Test front page functionality.
  1309. */
  1310. function testDrupalIsFrontPage() {
  1311. $this->drupalGet('');
  1312. $this->assertText(t('On front page.'), 'Path is the front page.');
  1313. $this->drupalGet('node');
  1314. $this->assertText(t('On front page.'), 'Path is the front page.');
  1315. $this->drupalGet($this->node_path);
  1316. $this->assertNoText(t('On front page.'), 'Path is not the front page.');
  1317. // Change the front page to an invalid path.
  1318. $edit = array('site_frontpage' => 'kittens');
  1319. $this->drupalPost('admin/config/system/site-information', $edit, t('Save configuration'));
  1320. $this->assertText(t("The path '@path' is either invalid or you do not have access to it.", array('@path' => $edit['site_frontpage'])));
  1321. // Change the front page to a valid path.
  1322. $edit['site_frontpage'] = $this->node_path;
  1323. $this->drupalPost('admin/config/system/site-information', $edit, t('Save configuration'));
  1324. $this->assertText(t('The configuration options have been saved.'), 'The front page path has been saved.');
  1325. $this->drupalGet('');
  1326. $this->assertText(t('On front page.'), 'Path is the front page.');
  1327. $this->drupalGet('node');
  1328. $this->assertNoText(t('On front page.'), 'Path is not the front page.');
  1329. $this->drupalGet($this->node_path);
  1330. $this->assertText(t('On front page.'), 'Path is the front page.');
  1331. }
  1332. }
  1333. class SystemBlockTestCase extends DrupalWebTestCase {
  1334. protected $profile = 'testing';
  1335. public static function getInfo() {
  1336. return array(
  1337. 'name' => 'Block functionality',
  1338. 'description' => 'Configure and move powered-by block.',
  1339. 'group' => 'System',
  1340. );
  1341. }
  1342. function setUp() {
  1343. parent::setUp('block');
  1344. // Create and login user
  1345. $admin_user = $this->drupalCreateUser(array('administer blocks', 'access administration pages'));
  1346. $this->drupalLogin($admin_user);
  1347. }
  1348. /**
  1349. * Test displaying and hiding the powered-by and help blocks.
  1350. */
  1351. function testSystemBlocks() {
  1352. // Set block title and some settings to confirm that the interface is available.
  1353. $this->drupalPost('admin/structure/block/manage/system/powered-by/configure', array('title' => $this->randomName(8)), t('Save block'));
  1354. $this->assertText(t('The block configuration has been saved.'), t('Block configuration set.'));
  1355. // Set the powered-by block to the footer region.
  1356. $edit = array();
  1357. $edit['blocks[system_powered-by][region]'] = 'footer';
  1358. $edit['blocks[system_main][region]'] = 'content';
  1359. $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
  1360. $this->assertText(t('The block settings have been updated.'), t('Block successfully moved to footer region.'));
  1361. // Confirm that the block is being displayed.
  1362. $this->drupalGet('node');
  1363. $this->assertRaw('id="block-system-powered-by"', t('Block successfully being displayed on the page.'));
  1364. // Set the block to the disabled region.
  1365. $edit = array();
  1366. $edit['blocks[system_powered-by][region]'] = '-1';
  1367. $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
  1368. // Confirm that the block is hidden.
  1369. $this->assertNoRaw('id="block-system-powered-by"', t('Block no longer appears on page.'));
  1370. // For convenience of developers, set the block to its default settings.
  1371. $edit = array();
  1372. $edit['blocks[system_powered-by][region]'] = 'footer';
  1373. $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
  1374. $this->drupalPost('admin/structure/block/manage/system/powered-by/configure', array('title' => ''), t('Save block'));
  1375. // Set the help block to the help region.
  1376. $edit = array();
  1377. $edit['blocks[system_help][region]'] = 'help';
  1378. $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
  1379. // Test displaying the help block with block caching enabled.
  1380. variable_set('block_cache', TRUE);
  1381. $this->drupalGet('admin/structure/block/add');
  1382. $this->assertRaw(t('Use this page to create a new custom block.'));
  1383. $this->drupalGet('admin/index');
  1384. $this->assertRaw(t('This page shows you all available administration tasks for each module.'));
  1385. }
  1386. }
  1387. /**
  1388. * Test main content rendering fallback provided by system module.
  1389. */
  1390. class SystemMainContentFallback extends DrupalWebTestCase {
  1391. protected $admin_user;
  1392. protected $web_user;
  1393. public static function getInfo() {
  1394. return array(
  1395. 'name' => 'Main content rendering fallback',
  1396. 'description' => ' Test system module main content rendering fallback.',
  1397. 'group' => 'System',
  1398. );
  1399. }
  1400. function setUp() {
  1401. parent::setUp('system_test');
  1402. // Create and login admin user.
  1403. $this->admin_user = $this->drupalCreateUser(array(
  1404. 'access administration pages',
  1405. 'administer site configuration',
  1406. 'administer modules',
  1407. 'administer blocks',
  1408. 'administer nodes',
  1409. ));
  1410. $this->drupalLogin($this->admin_user);
  1411. // Create a web user.
  1412. $this->web_user = $this->drupalCreateUser(array('access user profiles', 'access content'));
  1413. }
  1414. /**
  1415. * Test availability of main content.
  1416. */
  1417. function testMainContentFallback() {
  1418. $edit = array();
  1419. // Disable the dashboard module, which depends on the block module.
  1420. $edit['modules[Core][dashboard][enable]'] = FALSE;
  1421. $this->drupalPost('admin/modules', $edit, t('Save configuration'));
  1422. $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
  1423. // Disable the block module.
  1424. $edit['modules[Core][block][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. module_list(TRUE);
  1428. $this->assertFalse(module_exists('block'), 'Block module disabled.');
  1429. // At this point, no region is filled and fallback should be triggered.
  1430. $this->drupalGet('admin/config/system/site-information');
  1431. $this->assertField('site_name', 'Admin interface still available.');
  1432. // Fallback should not trigger when another module is handling content.
  1433. $this->drupalGet('system-test/main-content-handling');
  1434. $this->assertRaw('id="system-test-content"', 'Content handled by another module');
  1435. $this->assertText(t('Content to test main content fallback'), 'Main content still displayed.');
  1436. // Fallback should trigger when another module
  1437. // indicates that it is not handling the content.
  1438. $this->drupalGet('system-test/main-content-fallback');
  1439. $this->assertText(t('Content to test main content fallback'), 'Main content fallback properly triggers.');
  1440. // Fallback should not trigger when another module is handling content.
  1441. // Note that this test ensures that no duplicate
  1442. // content gets created by the fallback.
  1443. $this->drupalGet('system-test/main-content-duplication');
  1444. $this->assertNoText(t('Content to test main content fallback'), 'Main content not duplicated.');
  1445. // Request a user* page and see if it is displayed.
  1446. $this->drupalLogin($this->web_user);
  1447. $this->drupalGet('user/' . $this->web_user->uid . '/edit');
  1448. $this->assertField('mail', 'User interface still available.');
  1449. // Enable the block module again.
  1450. $this->drupalLogin($this->admin_user);
  1451. $edit = array();
  1452. $edit['modules[Core][block][enable]'] = 'block';
  1453. $this->drupalPost('admin/modules', $edit, t('Save configuration'));
  1454. $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
  1455. module_list(TRUE);
  1456. $this->assertTrue(module_exists('block'), 'Block module re-enabled.');
  1457. }
  1458. }
  1459. /**
  1460. * Tests for the theme interface functionality.
  1461. */
  1462. class SystemThemeFunctionalTest extends DrupalWebTestCase {
  1463. public static function getInfo() {
  1464. return array(
  1465. 'name' => 'Theme interface functionality',
  1466. 'description' => 'Tests the theme interface functionality by enabling and switching themes, and using an administration theme.',
  1467. 'group' => 'System',
  1468. );
  1469. }
  1470. function setUp() {
  1471. parent::setUp();
  1472. $this->admin_user = $this->drupalCreateUser(array('access administration pages', 'view the administration theme', 'administer themes', 'bypass node access', 'administer blocks'));
  1473. $this->drupalLogin($this->admin_user);
  1474. $this->node = $this->drupalCreateNode();
  1475. }
  1476. /**
  1477. * Test the theme settings form.
  1478. */
  1479. function testThemeSettings() {
  1480. // Specify a filesystem path to be used for the logo.
  1481. $file = current($this->drupalGetTestFiles('image'));
  1482. $file_relative = strtr($file->uri, array('public:/' => variable_get('file_public_path', conf_path() . '/files')));
  1483. $default_theme_path = 'themes/stark';
  1484. $supported_paths = array(
  1485. // Raw stream wrapper URI.
  1486. $file->uri => array(
  1487. 'form' => file_uri_target($file->uri),
  1488. 'src' => file_create_url($file->uri),
  1489. ),
  1490. // Relative path within the public filesystem.
  1491. file_uri_target($file->uri) => array(
  1492. 'form' => file_uri_target($file->uri),
  1493. 'src' => file_create_url($file->uri),
  1494. ),
  1495. // Relative path to a public file.
  1496. $file_relative => array(
  1497. 'form' => $file_relative,
  1498. 'src' => file_create_url($file->uri),
  1499. ),
  1500. // Relative path to an arbitrary file.
  1501. 'misc/druplicon.png' => array(
  1502. 'form' => 'misc/druplicon.png',
  1503. 'src' => $GLOBALS['base_url'] . '/' . 'misc/druplicon.png',
  1504. ),
  1505. // Relative path to a file in a theme.
  1506. $default_theme_path . '/logo.png' => array(
  1507. 'form' => $default_theme_path . '/logo.png',
  1508. 'src' => $GLOBALS['base_url'] . '/' . $default_theme_path . '/logo.png',
  1509. ),
  1510. );
  1511. foreach ($supported_paths as $input => $expected) {
  1512. $edit = array(
  1513. 'default_logo' => FALSE,
  1514. 'logo_path' => $input,
  1515. );
  1516. $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
  1517. $this->assertNoText('The custom logo path is invalid.');
  1518. $this->assertFieldByName('logo_path', $expected['form']);
  1519. // Verify the actual 'src' attribute of the logo being output.
  1520. $this->drupalGet('');
  1521. $elements = $this->xpath('//*[@id=:id]/img', array(':id' => 'logo'));
  1522. $this->assertEqual((string) $elements[0]['src'], $expected['src']);
  1523. }
  1524. $unsupported_paths = array(
  1525. // Stream wrapper URI to non-existing file.
  1526. 'public://whatever.png',
  1527. 'private://whatever.png',
  1528. 'temporary://whatever.png',
  1529. // Bogus stream wrapper URIs.
  1530. 'public:/whatever.png',
  1531. '://whatever.png',
  1532. ':whatever.png',
  1533. 'public://',
  1534. // Relative path within the public filesystem to non-existing file.
  1535. 'whatever.png',
  1536. // Relative path to non-existing file in public filesystem.
  1537. variable_get('file_public_path', conf_path() . '/files') . '/whatever.png',
  1538. // Semi-absolute path to non-existing file in public filesystem.
  1539. '/' . variable_get('file_public_path', conf_path() . '/files') . '/whatever.png',
  1540. // Relative path to arbitrary non-existing file.
  1541. 'misc/whatever.png',
  1542. // Semi-absolute path to arbitrary non-existing file.
  1543. '/misc/whatever.png',
  1544. // Absolute paths to any local file (even if it exists).
  1545. drupal_realpath($file->uri),
  1546. );
  1547. $this->drupalGet('admin/appearance/settings');
  1548. foreach ($unsupported_paths as $path) {
  1549. $edit = array(
  1550. 'default_logo' => FALSE,
  1551. 'logo_path' => $path,
  1552. );
  1553. $this->drupalPost(NULL, $edit, t('Save configuration'));
  1554. $this->assertText('The custom logo path is invalid.');
  1555. }
  1556. // Upload a file to use for the logo.
  1557. $edit = array(
  1558. 'default_logo' => FALSE,
  1559. 'logo_path' => '',
  1560. 'files[logo_upload]' => drupal_realpath($file->uri),
  1561. );
  1562. $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
  1563. $fields = $this->xpath($this->constructFieldXpath('name', 'logo_path'));
  1564. $uploaded_filename = 'public://' . $fields[0]['value'];
  1565. $this->drupalGet('');
  1566. $elements = $this->xpath('//*[@id=:id]/img', array(':id' => 'logo'));
  1567. $this->assertEqual($elements[0]['src'], file_create_url($uploaded_filename));
  1568. }
  1569. /**
  1570. * Test the administration theme functionality.
  1571. */
  1572. function testAdministrationTheme() {
  1573. theme_enable(array('stark'));
  1574. variable_set('theme_default', 'stark');
  1575. // Enable an administration theme and show it on the node admin pages.
  1576. $edit = array(
  1577. 'admin_theme' => 'seven',
  1578. 'node_admin_theme' => TRUE,
  1579. );
  1580. $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
  1581. $this->drupalGet('admin/config');
  1582. $this->assertRaw('themes/seven', 'Administration theme used on an administration page.');
  1583. $this->drupalGet('node/' . $this->node->nid);
  1584. $this->assertRaw('themes/stark', 'Site default theme used on node page.');
  1585. $this->drupalGet('node/add');
  1586. $this->assertRaw('themes/seven', 'Administration theme used on the add content page.');
  1587. $this->drupalGet('node/' . $this->node->nid . '/edit');
  1588. $this->assertRaw('themes/seven', 'Administration theme used on the edit content page.');
  1589. // Disable the admin theme on the node admin pages.
  1590. $edit = array(
  1591. 'node_admin_theme' => FALSE,
  1592. );
  1593. $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
  1594. $this->drupalGet('admin/config');
  1595. $this->assertRaw('themes/seven', 'Administration theme used on an administration page.');
  1596. $this->drupalGet('node/add');
  1597. $this->assertRaw('themes/stark', 'Site default theme used on the add content page.');
  1598. // Reset to the default theme settings.
  1599. variable_set('theme_default', 'bartik');
  1600. $edit = array(
  1601. 'admin_theme' => '0',
  1602. 'node_admin_theme' => FALSE,
  1603. );
  1604. $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
  1605. $this->drupalGet('admin');
  1606. $this->assertRaw('themes/bartik', 'Site default theme used on administration page.');
  1607. $this->drupalGet('node/add');
  1608. $this->assertRaw('themes/bartik', 'Site default theme used on the add content page.');
  1609. }
  1610. /**
  1611. * Test switching the default theme.
  1612. */
  1613. function testSwitchDefaultTheme() {
  1614. // Enable "stark" and set it as the default theme.
  1615. theme_enable(array('stark'));
  1616. $this->drupalGet('admin/appearance');
  1617. $this->clickLink(t('Set default'), 1);
  1618. $this->assertTrue(variable_get('theme_default', '') == 'stark', 'Site default theme switched successfully.');
  1619. // Test the default theme on the secondary links (blocks admin page).
  1620. $this->drupalGet('admin/structure/block');
  1621. $this->assertText('Stark(' . t('active tab') . ')', 'Default local task on blocks admin page is the default theme.');
  1622. // Switch back to Bartik and test again to test that the menu cache is cleared.
  1623. $this->drupalGet('admin/appearance');
  1624. $this->clickLink(t('Set default'), 0);
  1625. $this->drupalGet('admin/structure/block');
  1626. $this->assertText('Bartik(' . t('active tab') . ')', 'Default local task on blocks admin page has changed.');
  1627. }
  1628. }
  1629. /**
  1630. * Test the basic queue functionality.
  1631. */
  1632. class QueueTestCase extends DrupalWebTestCase {
  1633. public static function getInfo() {
  1634. return array(
  1635. 'name' => 'Queue functionality',
  1636. 'description' => 'Queues and dequeues a set of items to check the basic queue functionality.',
  1637. 'group' => 'System',
  1638. );
  1639. }
  1640. /**
  1641. * Queues and dequeues a set of items to check the basic queue functionality.
  1642. */
  1643. function testQueue() {
  1644. // Create two queues.
  1645. $queue1 = DrupalQueue::get($this->randomName());
  1646. $queue1->createQueue();
  1647. $queue2 = DrupalQueue::get($this->randomName());
  1648. $queue2->createQueue();
  1649. // Create four items.
  1650. $data = array();
  1651. for ($i = 0; $i < 4; $i++) {
  1652. $data[] = array($this->randomName() => $this->randomName());
  1653. }
  1654. // Queue items 1 and 2 in the queue1.
  1655. $queue1->createItem($data[0]);
  1656. $queue1->createItem($data[1]);
  1657. // Retrieve two items from queue1.
  1658. $items = array();
  1659. $new_items = array();
  1660. $items[] = $item = $queue1->claimItem();
  1661. $new_items[] = $item->data;
  1662. $items[] = $item = $queue1->claimItem();
  1663. $new_items[] = $item->data;
  1664. // First two dequeued items should match the first two items we queued.
  1665. $this->assertEqual($this->queueScore($data, $new_items), 2, 'Two items matched');
  1666. // Add two more items.
  1667. $queue1->createItem($data[2]);
  1668. $queue1->createItem($data[3]);
  1669. $this->assertTrue($queue1->numberOfItems(), 'Queue 1 is not empty after adding items.');
  1670. $this->assertFalse($queue2->numberOfItems(), 'Queue 2 is empty while Queue 1 has items');
  1671. $items[] = $item = $queue1->claimItem();
  1672. $new_items[] = $item->data;
  1673. $items[] = $item = $queue1->claimItem();
  1674. $new_items[] = $item->data;
  1675. // All dequeued items should match the items we queued exactly once,
  1676. // therefore the score must be exactly 4.
  1677. $this->assertEqual($this->queueScore($data, $new_items), 4, 'Four items matched');
  1678. // There should be no duplicate items.
  1679. $this->assertEqual($this->queueScore($new_items, $new_items), 4, 'Four items matched');
  1680. // Delete all items from queue1.
  1681. foreach ($items as $item) {
  1682. $queue1->deleteItem($item);
  1683. }
  1684. // Check that both queues are empty.
  1685. $this->assertFalse($queue1->numberOfItems(), 'Queue 1 is empty');
  1686. $this->assertFalse($queue2->numberOfItems(), 'Queue 2 is empty');
  1687. }
  1688. /**
  1689. * This function returns the number of equal items in two arrays.
  1690. */
  1691. function queueScore($items, $new_items) {
  1692. $score = 0;
  1693. foreach ($items as $item) {
  1694. foreach ($new_items as $new_item) {
  1695. if ($item === $new_item) {
  1696. $score++;
  1697. }
  1698. }
  1699. }
  1700. return $score;
  1701. }
  1702. }
  1703. /**
  1704. * Test token replacement in strings.
  1705. */
  1706. class TokenReplaceTestCase extends DrupalWebTestCase {
  1707. public static function getInfo() {
  1708. return array(
  1709. 'name' => 'Token replacement',
  1710. 'description' => 'Generates text using placeholders for dummy content to check token replacement.',
  1711. 'group' => 'System',
  1712. );
  1713. }
  1714. /**
  1715. * Creates a user and a node, then tests the tokens generated from them.
  1716. */
  1717. function testTokenReplacement() {
  1718. // Create the initial objects.
  1719. $account = $this->drupalCreateUser();
  1720. $node = $this->drupalCreateNode(array('uid' => $account->uid));
  1721. $node->title = '<blink>Blinking Text</blink>';
  1722. global $user, $language;
  1723. $source = '[node:title]'; // Title of the node we passed in
  1724. $source .= '[node:author:name]'; // Node author's name
  1725. $source .= '[node:created:since]'; // Time since the node was created
  1726. $source .= '[current-user:name]'; // Current user's name
  1727. $source .= '[date:short]'; // Short date format of REQUEST_TIME
  1728. $source .= '[user:name]'; // No user passed in, should be untouched
  1729. $source .= '[bogus:token]'; // Non-existent token
  1730. $target = check_plain($node->title);
  1731. $target .= check_plain($account->name);
  1732. $target .= format_interval(REQUEST_TIME - $node->created, 2, $language->language);
  1733. $target .= check_plain($user->name);
  1734. $target .= format_date(REQUEST_TIME, 'short', '', NULL, $language->language);
  1735. // Test that the clear parameter cleans out non-existent tokens.
  1736. $result = token_replace($source, array('node' => $node), array('language' => $language, 'clear' => TRUE));
  1737. $result = $this->assertEqual($target, $result, 'Valid tokens replaced while invalid tokens cleared out.');
  1738. // Test without using the clear parameter (non-existent token untouched).
  1739. $target .= '[user:name]';
  1740. $target .= '[bogus:token]';
  1741. $result = token_replace($source, array('node' => $node), array('language' => $language));
  1742. $this->assertEqual($target, $result, 'Valid tokens replaced while invalid tokens ignored.');
  1743. // Check that the results of token_generate are sanitized properly. This does NOT
  1744. // test the cleanliness of every token -- just that the $sanitize flag is being
  1745. // passed properly through the call stack and being handled correctly by a 'known'
  1746. // token, [node:title].
  1747. $raw_tokens = array('title' => '[node:title]');
  1748. $generated = token_generate('node', $raw_tokens, array('node' => $node));
  1749. $this->assertEqual($generated['[node:title]'], check_plain($node->title), 'Token sanitized.');
  1750. $generated = token_generate('node', $raw_tokens, array('node' => $node), array('sanitize' => FALSE));
  1751. $this->assertEqual($generated['[node:title]'], $node->title, 'Unsanitized token generated properly.');
  1752. // Test token replacement when the string contains no tokens.
  1753. $this->assertEqual(token_replace('No tokens here.'), 'No tokens here.');
  1754. }
  1755. /**
  1756. * Test whether token-replacement works in various contexts.
  1757. */
  1758. function testSystemTokenRecognition() {
  1759. global $language;
  1760. // Generate prefixes and suffixes for the token context.
  1761. $tests = array(
  1762. array('prefix' => 'this is the ', 'suffix' => ' site'),
  1763. array('prefix' => 'this is the', 'suffix' => 'site'),
  1764. array('prefix' => '[', 'suffix' => ']'),
  1765. array('prefix' => '', 'suffix' => ']]]'),
  1766. array('prefix' => '[[[', 'suffix' => ''),
  1767. array('prefix' => ':[:', 'suffix' => '--]'),
  1768. array('prefix' => '-[-', 'suffix' => ':]:'),
  1769. array('prefix' => '[:', 'suffix' => ']'),
  1770. array('prefix' => '[site:', 'suffix' => ':name]'),
  1771. array('prefix' => '[site:', 'suffix' => ']'),
  1772. );
  1773. // Check if the token is recognized in each of the contexts.
  1774. foreach ($tests as $test) {
  1775. $input = $test['prefix'] . '[site:name]' . $test['suffix'];
  1776. $expected = $test['prefix'] . 'Drupal' . $test['suffix'];
  1777. $output = token_replace($input, array(), array('language' => $language));
  1778. $this->assertTrue($output == $expected, format_string('Token recognized in string %string', array('%string' => $input)));
  1779. }
  1780. }
  1781. /**
  1782. * Tests the generation of all system site information tokens.
  1783. */
  1784. function testSystemSiteTokenReplacement() {
  1785. global $language;
  1786. $url_options = array(
  1787. 'absolute' => TRUE,
  1788. 'language' => $language,
  1789. );
  1790. // Set a few site variables.
  1791. variable_set('site_name', '<strong>Drupal<strong>');
  1792. variable_set('site_slogan', '<blink>Slogan</blink>');
  1793. // Generate and test sanitized tokens.
  1794. $tests = array();
  1795. $tests['[site:name]'] = check_plain(variable_get('site_name', 'Drupal'));
  1796. $tests['[site:slogan]'] = check_plain(variable_get('site_slogan', ''));
  1797. $tests['[site:mail]'] = 'simpletest@example.com';
  1798. $tests['[site:url]'] = url('<front>', $url_options);
  1799. $tests['[site:url-brief]'] = preg_replace(array('!^https?://!', '!/$!'), '', url('<front>', $url_options));
  1800. $tests['[site:login-url]'] = url('user', $url_options);
  1801. // Test to make sure that we generated something for each token.
  1802. $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
  1803. foreach ($tests as $input => $expected) {
  1804. $output = token_replace($input, array(), array('language' => $language));
  1805. $this->assertEqual($output, $expected, format_string('Sanitized system site information token %token replaced.', array('%token' => $input)));
  1806. }
  1807. // Generate and test unsanitized tokens.
  1808. $tests['[site:name]'] = variable_get('site_name', 'Drupal');
  1809. $tests['[site:slogan]'] = variable_get('site_slogan', '');
  1810. foreach ($tests as $input => $expected) {
  1811. $output = token_replace($input, array(), array('language' => $language, 'sanitize' => FALSE));
  1812. $this->assertEqual($output, $expected, format_string('Unsanitized system site information token %token replaced.', array('%token' => $input)));
  1813. }
  1814. }
  1815. /**
  1816. * Tests the generation of all system date tokens.
  1817. */
  1818. function testSystemDateTokenReplacement() {
  1819. global $language;
  1820. // Set time to one hour before request.
  1821. $date = REQUEST_TIME - 3600;
  1822. // Generate and test tokens.
  1823. $tests = array();
  1824. $tests['[date:short]'] = format_date($date, 'short', '', NULL, $language->language);
  1825. $tests['[date:medium]'] = format_date($date, 'medium', '', NULL, $language->language);
  1826. $tests['[date:long]'] = format_date($date, 'long', '', NULL, $language->language);
  1827. $tests['[date:custom:m/j/Y]'] = format_date($date, 'custom', 'm/j/Y', NULL, $language->language);
  1828. $tests['[date:since]'] = format_interval((REQUEST_TIME - $date), 2, $language->language);
  1829. $tests['[date:raw]'] = filter_xss($date);
  1830. // Test to make sure that we generated something for each token.
  1831. $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
  1832. foreach ($tests as $input => $expected) {
  1833. $output = token_replace($input, array('date' => $date), array('language' => $language));
  1834. $this->assertEqual($output, $expected, format_string('Date token %token replaced.', array('%token' => $input)));
  1835. }
  1836. }
  1837. }
  1838. class InfoFileParserTestCase extends DrupalUnitTestCase {
  1839. public static function getInfo() {
  1840. return array(
  1841. 'name' => 'Info file format parser',
  1842. 'description' => 'Tests proper parsing of a .info file formatted string.',
  1843. 'group' => 'System',
  1844. );
  1845. }
  1846. /**
  1847. * Test drupal_parse_info_format().
  1848. */
  1849. function testDrupalParseInfoFormat() {
  1850. $config = '
  1851. simple = Value
  1852. quoted = " Value"
  1853. multiline = "Value
  1854. Value"
  1855. array[] = Value1
  1856. array[] = Value2
  1857. array_assoc[a] = Value1
  1858. array_assoc[b] = Value2
  1859. array_deep[][][] = Value
  1860. array_deep_assoc[a][b][c] = Value
  1861. array_space[a b] = Value';
  1862. $expected = array(
  1863. 'simple' => 'Value',
  1864. 'quoted' => ' Value',
  1865. 'multiline' => "Value\n Value",
  1866. 'array' => array(
  1867. 0 => 'Value1',
  1868. 1 => 'Value2',
  1869. ),
  1870. 'array_assoc' => array(
  1871. 'a' => 'Value1',
  1872. 'b' => 'Value2',
  1873. ),
  1874. 'array_deep' => array(
  1875. 0 => array(
  1876. 0 => array(
  1877. 0 => 'Value',
  1878. ),
  1879. ),
  1880. ),
  1881. 'array_deep_assoc' => array(
  1882. 'a' => array(
  1883. 'b' => array(
  1884. 'c' => 'Value',
  1885. ),
  1886. ),
  1887. ),
  1888. 'array_space' => array(
  1889. 'a b' => 'Value',
  1890. ),
  1891. );
  1892. $parsed = drupal_parse_info_format($config);
  1893. $this->assertEqual($parsed['simple'], $expected['simple'], 'Set a simple value.');
  1894. $this->assertEqual($parsed['quoted'], $expected['quoted'], 'Set a simple value in quotes.');
  1895. $this->assertEqual($parsed['multiline'], $expected['multiline'], 'Set a multiline value.');
  1896. $this->assertEqual($parsed['array'], $expected['array'], 'Set a simple array.');
  1897. $this->assertEqual($parsed['array_assoc'], $expected['array_assoc'], 'Set an associative array.');
  1898. $this->assertEqual($parsed['array_deep'], $expected['array_deep'], 'Set a nested array.');
  1899. $this->assertEqual($parsed['array_deep_assoc'], $expected['array_deep_assoc'], 'Set a nested associative array.');
  1900. $this->assertEqual($parsed['array_space'], $expected['array_space'], 'Set an array with a whitespace in the key.');
  1901. $this->assertEqual($parsed, $expected, 'Entire parsed .info string and expected array are identical.');
  1902. }
  1903. }
  1904. /**
  1905. * Tests the effectiveness of hook_system_info_alter().
  1906. */
  1907. class SystemInfoAlterTestCase extends DrupalWebTestCase {
  1908. public static function getInfo() {
  1909. return array(
  1910. 'name' => 'System info alter',
  1911. 'description' => 'Tests the effectiveness of hook_system_info_alter().',
  1912. 'group' => 'System',
  1913. );
  1914. }
  1915. /**
  1916. * Tests that {system}.info is rebuilt after a module that implements
  1917. * hook_system_info_alter() is enabled. Also tests if core *_list() functions
  1918. * return freshly altered info.
  1919. */
  1920. function testSystemInfoAlter() {
  1921. // Enable our test module. Flush all caches, which we assert is the only
  1922. // thing necessary to use the rebuilt {system}.info.
  1923. module_enable(array('module_test'), FALSE);
  1924. drupal_flush_all_caches();
  1925. $this->assertTrue(module_exists('module_test'), 'Test module is enabled.');
  1926. $info = $this->getSystemInfo('seven', 'theme');
  1927. $this->assertTrue(isset($info['regions']['test_region']), 'Altered theme info was added to {system}.info.');
  1928. $seven_regions = system_region_list('seven');
  1929. $this->assertTrue(isset($seven_regions['test_region']), 'Altered theme info was returned by system_region_list().');
  1930. $system_list_themes = system_list('theme');
  1931. $info = $system_list_themes['seven']->info;
  1932. $this->assertTrue(isset($info['regions']['test_region']), 'Altered theme info was returned by system_list().');
  1933. $list_themes = list_themes();
  1934. $this->assertTrue(isset($list_themes['seven']->info['regions']['test_region']), 'Altered theme info was returned by list_themes().');
  1935. // Disable the module and verify that {system}.info is rebuilt without it.
  1936. module_disable(array('module_test'), FALSE);
  1937. drupal_flush_all_caches();
  1938. $this->assertFalse(module_exists('module_test'), 'Test module is disabled.');
  1939. $info = $this->getSystemInfo('seven', 'theme');
  1940. $this->assertFalse(isset($info['regions']['test_region']), 'Altered theme info was removed from {system}.info.');
  1941. $seven_regions = system_region_list('seven');
  1942. $this->assertFalse(isset($seven_regions['test_region']), 'Altered theme info was not returned by system_region_list().');
  1943. $system_list_themes = system_list('theme');
  1944. $info = $system_list_themes['seven']->info;
  1945. $this->assertFalse(isset($info['regions']['test_region']), 'Altered theme info was not returned by system_list().');
  1946. $list_themes = list_themes();
  1947. $this->assertFalse(isset($list_themes['seven']->info['regions']['test_region']), 'Altered theme info was not returned by list_themes().');
  1948. }
  1949. /**
  1950. * Returns the info array as it is stored in {system}.
  1951. *
  1952. * @param $name
  1953. * The name of the record in {system}.
  1954. * @param $type
  1955. * The type of record in {system}.
  1956. *
  1957. * @return
  1958. * Array of info, or FALSE if the record is not found.
  1959. */
  1960. function getSystemInfo($name, $type) {
  1961. $raw_info = db_query("SELECT info FROM {system} WHERE name = :name AND type = :type", array(':name' => $name, ':type' => $type))->fetchField();
  1962. return $raw_info ? unserialize($raw_info) : FALSE;
  1963. }
  1964. }
  1965. /**
  1966. * Tests for the update system functionality.
  1967. */
  1968. class UpdateScriptFunctionalTest extends DrupalWebTestCase {
  1969. private $update_url;
  1970. private $update_user;
  1971. public static function getInfo() {
  1972. return array(
  1973. 'name' => 'Update functionality',
  1974. 'description' => 'Tests the update script access and functionality.',
  1975. 'group' => 'System',
  1976. );
  1977. }
  1978. function setUp() {
  1979. parent::setUp('update_script_test');
  1980. $this->update_url = $GLOBALS['base_url'] . '/update.php';
  1981. $this->update_user = $this->drupalCreateUser(array('administer software updates'));
  1982. }
  1983. /**
  1984. * Tests access to the update script.
  1985. */
  1986. function testUpdateAccess() {
  1987. // Try accessing update.php without the proper permission.
  1988. $regular_user = $this->drupalCreateUser();
  1989. $this->drupalLogin($regular_user);
  1990. $this->drupalGet($this->update_url, array('external' => TRUE));
  1991. $this->assertResponse(403);
  1992. // Try accessing update.php as an anonymous user.
  1993. $this->drupalLogout();
  1994. $this->drupalGet($this->update_url, array('external' => TRUE));
  1995. $this->assertResponse(403);
  1996. // Access the update page with the proper permission.
  1997. $this->drupalLogin($this->update_user);
  1998. $this->drupalGet($this->update_url, array('external' => TRUE));
  1999. $this->assertResponse(200);
  2000. // Access the update page as user 1.
  2001. $user1 = user_load(1);
  2002. $user1->pass_raw = user_password();
  2003. require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
  2004. $user1->pass = user_hash_password(trim($user1->pass_raw));
  2005. db_query("UPDATE {users} SET pass = :pass WHERE uid = :uid", array(':pass' => $user1->pass, ':uid' => $user1->uid));
  2006. $this->drupalLogin($user1);
  2007. $this->drupalGet($this->update_url, array('external' => TRUE));
  2008. $this->assertResponse(200);
  2009. }
  2010. /**
  2011. * Tests that requirements warnings and errors are correctly displayed.
  2012. */
  2013. function testRequirements() {
  2014. $this->drupalLogin($this->update_user);
  2015. // If there are no requirements warnings or errors, we expect to be able to
  2016. // go through the update process uninterrupted.
  2017. $this->drupalGet($this->update_url, array('external' => TRUE));
  2018. $this->drupalPost(NULL, array(), t('Continue'));
  2019. $this->assertText(t('No pending updates.'), 'End of update process was reached.');
  2020. // Confirm that all caches were cleared.
  2021. $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared when there were no requirements warnings or errors.');
  2022. // If there is a requirements warning, we expect it to be initially
  2023. // displayed, but clicking the link to proceed should allow us to go
  2024. // through the rest of the update process uninterrupted.
  2025. // First, run this test with pending updates to make sure they can be run
  2026. // successfully.
  2027. variable_set('update_script_test_requirement_type', REQUIREMENT_WARNING);
  2028. drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
  2029. $this->drupalGet($this->update_url, array('external' => TRUE));
  2030. $this->assertText('This is a requirements warning provided by the update_script_test module.');
  2031. $this->clickLink('try again');
  2032. $this->assertNoText('This is a requirements warning provided by the update_script_test module.');
  2033. $this->drupalPost(NULL, array(), t('Continue'));
  2034. $this->drupalPost(NULL, array(), t('Apply pending updates'));
  2035. $this->assertText(t('The update_script_test_update_7000() update was executed successfully.'), 'End of update process was reached.');
  2036. // Confirm that all caches were cleared.
  2037. $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared after resolving a requirements warning and applying updates.');
  2038. // Now try again without pending updates to make sure that works too.
  2039. $this->drupalGet($this->update_url, array('external' => TRUE));
  2040. $this->assertText('This is a requirements warning provided by the update_script_test module.');
  2041. $this->clickLink('try again');
  2042. $this->assertNoText('This is a requirements warning provided by the update_script_test module.');
  2043. $this->drupalPost(NULL, array(), t('Continue'));
  2044. $this->assertText(t('No pending updates.'), 'End of update process was reached.');
  2045. // Confirm that all caches were cleared.
  2046. $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared after applying updates and re-running the script.');
  2047. // If there is a requirements error, it should be displayed even after
  2048. // clicking the link to proceed (since the problem that triggered the error
  2049. // has not been fixed).
  2050. variable_set('update_script_test_requirement_type', REQUIREMENT_ERROR);
  2051. $this->drupalGet($this->update_url, array('external' => TRUE));
  2052. $this->assertText('This is a requirements error provided by the update_script_test module.');
  2053. $this->clickLink('try again');
  2054. $this->assertText('This is a requirements error provided by the update_script_test module.');
  2055. }
  2056. /**
  2057. * Tests the effect of using the update script on the theme system.
  2058. */
  2059. function testThemeSystem() {
  2060. // Since visiting update.php triggers a rebuild of the theme system from an
  2061. // unusual maintenance mode environment, we check that this rebuild did not
  2062. // put any incorrect information about the themes into the database.
  2063. $original_theme_data = db_query("SELECT * FROM {system} WHERE type = 'theme' ORDER BY name")->fetchAll();
  2064. $this->drupalLogin($this->update_user);
  2065. $this->drupalGet($this->update_url, array('external' => TRUE));
  2066. $final_theme_data = db_query("SELECT * FROM {system} WHERE type = 'theme' ORDER BY name")->fetchAll();
  2067. $this->assertEqual($original_theme_data, $final_theme_data, 'Visiting update.php does not alter the information about themes stored in the database.');
  2068. }
  2069. /**
  2070. * Tests update.php when there are no updates to apply.
  2071. */
  2072. function testNoUpdateFunctionality() {
  2073. // Click through update.php with 'administer software updates' permission.
  2074. $this->drupalLogin($this->update_user);
  2075. $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
  2076. $this->assertText(t('No pending updates.'));
  2077. $this->assertNoLink('Administration pages');
  2078. $this->clickLink('Front page');
  2079. $this->assertResponse(200);
  2080. // Click through update.php with 'access administration pages' permission.
  2081. $admin_user = $this->drupalCreateUser(array('administer software updates', 'access administration pages'));
  2082. $this->drupalLogin($admin_user);
  2083. $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
  2084. $this->assertText(t('No pending updates.'));
  2085. $this->clickLink('Administration pages');
  2086. $this->assertResponse(200);
  2087. }
  2088. /**
  2089. * Tests update.php after performing a successful update.
  2090. */
  2091. function testSuccessfulUpdateFunctionality() {
  2092. drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
  2093. // Click through update.php with 'administer software updates' permission.
  2094. $this->drupalLogin($this->update_user);
  2095. $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
  2096. $this->drupalPost(NULL, array(), t('Apply pending updates'));
  2097. $this->assertText('Updates were attempted.');
  2098. $this->assertLink('site');
  2099. $this->assertNoLink('Administration pages');
  2100. $this->assertNoLink('logged');
  2101. $this->clickLink('Front page');
  2102. $this->assertResponse(200);
  2103. drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
  2104. // Click through update.php with 'access administration pages' and
  2105. // 'access site reports' permissions.
  2106. $admin_user = $this->drupalCreateUser(array('administer software updates', 'access administration pages', 'access site reports'));
  2107. $this->drupalLogin($admin_user);
  2108. $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
  2109. $this->drupalPost(NULL, array(), t('Apply pending updates'));
  2110. $this->assertText('Updates were attempted.');
  2111. $this->assertLink('logged');
  2112. $this->clickLink('Administration pages');
  2113. $this->assertResponse(200);
  2114. }
  2115. }
  2116. /**
  2117. * Functional tests for the flood control mechanism.
  2118. */
  2119. class FloodFunctionalTest extends DrupalWebTestCase {
  2120. public static function getInfo() {
  2121. return array(
  2122. 'name' => 'Flood control mechanism',
  2123. 'description' => 'Functional tests for the flood control mechanism.',
  2124. 'group' => 'System',
  2125. );
  2126. }
  2127. /**
  2128. * Test flood control mechanism clean-up.
  2129. */
  2130. function testCleanUp() {
  2131. $threshold = 1;
  2132. $window_expired = -1;
  2133. $name = 'flood_test_cleanup';
  2134. // Register expired event.
  2135. flood_register_event($name, $window_expired);
  2136. // Verify event is not allowed.
  2137. $this->assertFalse(flood_is_allowed($name, $threshold));
  2138. // Run cron and verify event is now allowed.
  2139. $this->cronRun();
  2140. $this->assertTrue(flood_is_allowed($name, $threshold));
  2141. // Register unexpired event.
  2142. flood_register_event($name);
  2143. // Verify event is not allowed.
  2144. $this->assertFalse(flood_is_allowed($name, $threshold));
  2145. // Run cron and verify event is still not allowed.
  2146. $this->cronRun();
  2147. $this->assertFalse(flood_is_allowed($name, $threshold));
  2148. }
  2149. }
  2150. /**
  2151. * Test HTTP file downloading capability.
  2152. */
  2153. class RetrieveFileTestCase extends DrupalWebTestCase {
  2154. public static function getInfo() {
  2155. return array(
  2156. 'name' => 'HTTP file retrieval',
  2157. 'description' => 'Checks HTTP file fetching and error handling.',
  2158. 'group' => 'System',
  2159. );
  2160. }
  2161. /**
  2162. * Invokes system_retrieve_file() in several scenarios.
  2163. */
  2164. function testFileRetrieving() {
  2165. // Test 404 handling by trying to fetch a randomly named file.
  2166. drupal_mkdir($sourcedir = 'public://' . $this->randomName());
  2167. $filename = 'Файл для тестирования ' . $this->randomName();
  2168. $url = file_create_url($sourcedir . '/' . $filename);
  2169. $retrieved_file = system_retrieve_file($url);
  2170. $this->assertFalse($retrieved_file, 'Non-existent file not fetched.');
  2171. // Actually create that file, download it via HTTP and test the returned path.
  2172. file_put_contents($sourcedir . '/' . $filename, 'testing');
  2173. $retrieved_file = system_retrieve_file($url);
  2174. // URLs could not contains characters outside the ASCII set so $filename
  2175. // has to be encoded.
  2176. $encoded_filename = rawurlencode($filename);
  2177. $this->assertEqual($retrieved_file, 'public://' . $encoded_filename, 'Sane path for downloaded file returned (public:// scheme).');
  2178. $this->assertTrue(is_file($retrieved_file), 'Downloaded file does exist (public:// scheme).');
  2179. $this->assertEqual(filesize($retrieved_file), 7, 'File size of downloaded file is correct (public:// scheme).');
  2180. file_unmanaged_delete($retrieved_file);
  2181. // Test downloading file to a different location.
  2182. drupal_mkdir($targetdir = 'temporary://' . $this->randomName());
  2183. $retrieved_file = system_retrieve_file($url, $targetdir);
  2184. $this->assertEqual($retrieved_file, "$targetdir/$encoded_filename", 'Sane path for downloaded file returned (temporary:// scheme).');
  2185. $this->assertTrue(is_file($retrieved_file), 'Downloaded file does exist (temporary:// scheme).');
  2186. $this->assertEqual(filesize($retrieved_file), 7, 'File size of downloaded file is correct (temporary:// scheme).');
  2187. file_unmanaged_delete($retrieved_file);
  2188. file_unmanaged_delete_recursive($sourcedir);
  2189. file_unmanaged_delete_recursive($targetdir);
  2190. }
  2191. }
  2192. /**
  2193. * Functional tests shutdown functions.
  2194. */
  2195. class ShutdownFunctionsTest extends DrupalWebTestCase {
  2196. public static function getInfo() {
  2197. return array(
  2198. 'name' => 'Shutdown functions',
  2199. 'description' => 'Functional tests for shutdown functions',
  2200. 'group' => 'System',
  2201. );
  2202. }
  2203. function setUp() {
  2204. parent::setUp('system_test');
  2205. }
  2206. /**
  2207. * Test shutdown functions.
  2208. */
  2209. function testShutdownFunctions() {
  2210. $arg1 = $this->randomName();
  2211. $arg2 = $this->randomName();
  2212. $this->drupalGet('system-test/shutdown-functions/' . $arg1 . '/' . $arg2);
  2213. $this->assertText(t('First shutdown function, arg1 : @arg1, arg2: @arg2', array('@arg1' => $arg1, '@arg2' => $arg2)));
  2214. $this->assertText(t('Second shutdown function, arg1 : @arg1, arg2: @arg2', array('@arg1' => $arg1, '@arg2' => $arg2)));
  2215. // Make sure exceptions displayed through _drupal_render_exception_safe()
  2216. // are correctly escaped.
  2217. $this->assertRaw('Drupal is &amp;lt;blink&amp;gt;awesome&amp;lt;/blink&amp;gt;.');
  2218. }
  2219. }
  2220. /**
  2221. * Tests administrative overview pages.
  2222. */
  2223. class SystemAdminTestCase extends DrupalWebTestCase {
  2224. public static function getInfo() {
  2225. return array(
  2226. 'name' => 'Administrative pages',
  2227. 'description' => 'Tests output on administrative pages and compact mode functionality.',
  2228. 'group' => 'System',
  2229. );
  2230. }
  2231. function setUp() {
  2232. // testAdminPages() requires Locale module.
  2233. parent::setUp(array('locale'));
  2234. // Create an administrator with all permissions, as well as a regular user
  2235. // who can only access administration pages and perform some Locale module
  2236. // administrative tasks, but not all of them.
  2237. $this->admin_user = $this->drupalCreateUser(array_keys(module_invoke_all('permission')));
  2238. $this->web_user = $this->drupalCreateUser(array(
  2239. 'access administration pages',
  2240. 'translate interface',
  2241. ));
  2242. $this->drupalLogin($this->admin_user);
  2243. }
  2244. /**
  2245. * Tests output on administrative listing pages.
  2246. */
  2247. function testAdminPages() {
  2248. // Go to Administration.
  2249. $this->drupalGet('admin');
  2250. // Verify that all visible, top-level administration links are listed on
  2251. // the main administration page.
  2252. foreach (menu_get_router() as $path => $item) {
  2253. if (strpos($path, 'admin/') === 0 && ($item['type'] & MENU_VISIBLE_IN_TREE) && $item['_number_parts'] == 2) {
  2254. $this->assertLink($item['title']);
  2255. $this->assertLinkByHref($path);
  2256. $this->assertText($item['description']);
  2257. }
  2258. }
  2259. // For each administrative listing page on which the Locale module appears,
  2260. // verify that there are links to the module's primary configuration pages,
  2261. // but no links to its individual sub-configuration pages. Also verify that
  2262. // a user with access to only some Locale module administration pages only
  2263. // sees links to the pages they have access to.
  2264. $admin_list_pages = array(
  2265. 'admin/index',
  2266. 'admin/config',
  2267. 'admin/config/regional',
  2268. );
  2269. foreach ($admin_list_pages as $page) {
  2270. // For the administrator, verify that there are links to Locale's primary
  2271. // configuration pages, but no links to individual sub-configuration
  2272. // pages.
  2273. $this->drupalLogin($this->admin_user);
  2274. $this->drupalGet($page);
  2275. $this->assertLinkByHref('admin/config');
  2276. $this->assertLinkByHref('admin/config/regional/settings');
  2277. $this->assertLinkByHref('admin/config/regional/date-time');
  2278. $this->assertLinkByHref('admin/config/regional/language');
  2279. $this->assertNoLinkByHref('admin/config/regional/language/configure/session');
  2280. $this->assertNoLinkByHref('admin/config/regional/language/configure/url');
  2281. $this->assertLinkByHref('admin/config/regional/translate');
  2282. // On admin/index only, the administrator should also see a "Configure
  2283. // permissions" link for the Locale module.
  2284. if ($page == 'admin/index') {
  2285. $this->assertLinkByHref("admin/people/permissions#module-locale");
  2286. }
  2287. // For a less privileged user, verify that there are no links to Locale's
  2288. // primary configuration pages, but a link to the translate page exists.
  2289. $this->drupalLogin($this->web_user);
  2290. $this->drupalGet($page);
  2291. $this->assertLinkByHref('admin/config');
  2292. $this->assertNoLinkByHref('admin/config/regional/settings');
  2293. $this->assertNoLinkByHref('admin/config/regional/date-time');
  2294. $this->assertNoLinkByHref('admin/config/regional/language');
  2295. $this->assertNoLinkByHref('admin/config/regional/language/configure/session');
  2296. $this->assertNoLinkByHref('admin/config/regional/language/configure/url');
  2297. $this->assertLinkByHref('admin/config/regional/translate');
  2298. // This user cannot configure permissions, so even on admin/index should
  2299. // not see a "Configure permissions" link for the Locale module.
  2300. if ($page == 'admin/index') {
  2301. $this->assertNoLinkByHref("admin/people/permissions#module-locale");
  2302. }
  2303. }
  2304. }
  2305. /**
  2306. * Test compact mode.
  2307. */
  2308. function testCompactMode() {
  2309. $this->drupalGet('admin/compact/on');
  2310. $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode turns on.');
  2311. $this->drupalGet('admin/compact/on');
  2312. $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode remains on after a repeat call.');
  2313. $this->drupalGet('');
  2314. $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode persists on new requests.');
  2315. $this->drupalGet('admin/compact/off');
  2316. $this->assertEqual($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'deleted', 'Compact mode turns off.');
  2317. $this->drupalGet('admin/compact/off');
  2318. $this->assertEqual($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'deleted', 'Compact mode remains off after a repeat call.');
  2319. $this->drupalGet('');
  2320. $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode persists on new requests.');
  2321. }
  2322. }
  2323. /**
  2324. * Tests authorize.php and related hooks.
  2325. */
  2326. class SystemAuthorizeCase extends DrupalWebTestCase {
  2327. public static function getInfo() {
  2328. return array(
  2329. 'name' => 'Authorize API',
  2330. 'description' => 'Tests the authorize.php script and related API.',
  2331. 'group' => 'System',
  2332. );
  2333. }
  2334. function setUp() {
  2335. parent::setUp(array('system_test'));
  2336. variable_set('allow_authorize_operations', TRUE);
  2337. // Create an administrator user.
  2338. $this->admin_user = $this->drupalCreateUser(array('administer software updates'));
  2339. $this->drupalLogin($this->admin_user);
  2340. }
  2341. /**
  2342. * Helper function to initialize authorize.php and load it via drupalGet().
  2343. *
  2344. * Initializing authorize.php needs to happen in the child Drupal
  2345. * installation, not the parent. So, we visit a menu callback provided by
  2346. * system_test.module which calls system_authorized_init() to initialize the
  2347. * $_SESSION inside the test site, not the framework site. This callback
  2348. * redirects to authorize.php when it's done initializing.
  2349. *
  2350. * @see system_authorized_init().
  2351. */
  2352. function drupalGetAuthorizePHP($page_title = 'system-test-auth') {
  2353. $this->drupalGet('system-test/authorize-init/' . $page_title);
  2354. }
  2355. /**
  2356. * Tests the FileTransfer hooks
  2357. */
  2358. function testFileTransferHooks() {
  2359. $page_title = $this->randomName(16);
  2360. $this->drupalGetAuthorizePHP($page_title);
  2361. $this->assertTitle(strtr('@title | Drupal', array('@title' => $page_title)), 'authorize.php page title is correct.');
  2362. $this->assertNoText('It appears you have reached this page in error.');
  2363. $this->assertText('To continue, provide your server connection details');
  2364. // Make sure we see the new connection method added by system_test.
  2365. $this->assertRaw('System Test FileTransfer');
  2366. // Make sure the settings form callback works.
  2367. $this->assertText('System Test Username');
  2368. }
  2369. }
  2370. /**
  2371. * Test the handling of requests containing 'index.php'.
  2372. */
  2373. class SystemIndexPhpTest extends DrupalWebTestCase {
  2374. public static function getInfo() {
  2375. return array(
  2376. 'name' => 'Index.php handling',
  2377. 'description' => "Test the handling of requests containing 'index.php'.",
  2378. 'group' => 'System',
  2379. );
  2380. }
  2381. function setUp() {
  2382. parent::setUp();
  2383. }
  2384. /**
  2385. * Test index.php handling.
  2386. */
  2387. function testIndexPhpHandling() {
  2388. $index_php = $GLOBALS['base_url'] . '/index.php';
  2389. $this->drupalGet($index_php, array('external' => TRUE));
  2390. $this->assertResponse(200, 'Make sure index.php returns a valid page.');
  2391. $this->drupalGet($index_php, array('external' => TRUE, 'query' => array('q' => 'user')));
  2392. $this->assertResponse(200, 'Make sure index.php?q=user returns a valid page.');
  2393. $this->drupalGet($index_php .'/user', array('external' => TRUE));
  2394. $this->assertResponse(404, "Make sure index.php/user returns a 'page not found'.");
  2395. }
  2396. }
  2397. /**
  2398. * Test token replacement in strings.
  2399. */
  2400. class TokenScanTest extends DrupalWebTestCase {
  2401. public static function getInfo() {
  2402. return array(
  2403. 'name' => 'Token scanning',
  2404. 'description' => 'Scan token-like patterns in a dummy text to check token scanning.',
  2405. 'group' => 'System',
  2406. );
  2407. }
  2408. /**
  2409. * Scans dummy text, then tests the output.
  2410. */
  2411. function testTokenScan() {
  2412. // Define text with valid and not valid, fake and existing token-like
  2413. // strings.
  2414. $text = 'First a [valid:simple], but dummy token, and a dummy [valid:token with: spaces].';
  2415. $text .= 'Then a [not valid:token].';
  2416. $text .= 'Last an existing token: [node:author:name].';
  2417. $token_wannabes = token_scan($text);
  2418. $this->assertTrue(isset($token_wannabes['valid']['simple']), 'A simple valid token has been matched.');
  2419. $this->assertTrue(isset($token_wannabes['valid']['token with: spaces']), 'A valid token with space characters in the token name has been matched.');
  2420. $this->assertFalse(isset($token_wannabes['not valid']), 'An invalid token with spaces in the token type has not been matched.');
  2421. $this->assertTrue(isset($token_wannabes['node']), 'An existing valid token has been matched.');
  2422. }
  2423. }
  2424. /**
  2425. * Test case for drupal_valid_token().
  2426. */
  2427. class SystemValidTokenTest extends DrupalUnitTestCase {
  2428. /**
  2429. * Flag to indicate whether PHP error reportings should be asserted.
  2430. *
  2431. * @var bool
  2432. */
  2433. protected $assertErrors = TRUE;
  2434. public static function getInfo() {
  2435. return array(
  2436. 'name' => 'Token validation',
  2437. 'description' => 'Test the security token validation.',
  2438. 'group' => 'System',
  2439. );
  2440. }
  2441. /**
  2442. * Tests invalid invocations of drupal_valid_token() that must return FALSE.
  2443. */
  2444. public function testTokenValidation() {
  2445. // The following checks will throw PHP notices, so we disable error
  2446. // assertions.
  2447. $this->assertErrors = FALSE;
  2448. $this->assertFalse(drupal_valid_token(NULL, new stdClass()), 'Token NULL, value object returns FALSE.');
  2449. $this->assertFalse(drupal_valid_token(0, array()), 'Token 0, value array returns FALSE.');
  2450. $this->assertFalse(drupal_valid_token('', array()), "Token '', value array returns FALSE.");
  2451. $this->assertFalse('' === drupal_get_token(array()), 'Token generation does not return an empty string on invalid parameters.');
  2452. $this->assertErrors = TRUE;
  2453. $this->assertFalse(drupal_valid_token(TRUE, 'foo'), 'Token TRUE, value foo returns FALSE.');
  2454. $this->assertFalse(drupal_valid_token(0, 'foo'), 'Token 0, value foo returns FALSE.');
  2455. }
  2456. /**
  2457. * Overrides DrupalTestCase::errorHandler().
  2458. */
  2459. public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
  2460. if ($this->assertErrors) {
  2461. return parent::errorHandler($severity, $message, $file, $line);
  2462. }
  2463. return TRUE;
  2464. }
  2465. }
  2466. /**
  2467. * Tests drupal_set_message() and related functions.
  2468. */
  2469. class DrupalSetMessageTest extends DrupalWebTestCase {
  2470. public static function getInfo() {
  2471. return array(
  2472. 'name' => 'Messages',
  2473. 'description' => 'Tests that messages can be displayed using drupal_set_message().',
  2474. 'group' => 'System',
  2475. );
  2476. }
  2477. function setUp() {
  2478. parent::setUp('system_test');
  2479. }
  2480. /**
  2481. * Tests setting messages and removing one before it is displayed.
  2482. */
  2483. function testSetRemoveMessages() {
  2484. // The page at system-test/drupal-set-message sets two messages and then
  2485. // removes the first before it is displayed.
  2486. $this->drupalGet('system-test/drupal-set-message');
  2487. $this->assertNoText('First message (removed).');
  2488. $this->assertText('Second message (not removed).');
  2489. }
  2490. }
  2491. /**
  2492. * Tests confirm form destinations.
  2493. */
  2494. class ConfirmFormTest extends DrupalWebTestCase {
  2495. protected $admin_user;
  2496. public static function getInfo() {
  2497. return array(
  2498. 'name' => 'Confirm form',
  2499. 'description' => 'Tests that the confirm form does not use external destinations.',
  2500. 'group' => 'System',
  2501. );
  2502. }
  2503. function setUp() {
  2504. parent::setUp();
  2505. $this->admin_user = $this->drupalCreateUser(array('administer users'));
  2506. $this->drupalLogin($this->admin_user);
  2507. }
  2508. /**
  2509. * Tests that the confirm form does not use external destinations.
  2510. */
  2511. function testConfirmForm() {
  2512. $this->drupalGet('user/1/cancel');
  2513. $this->assertCancelLinkUrl(url('user/1'));
  2514. $this->drupalGet('user/1/cancel', array('query' => array('destination' => 'node')));
  2515. $this->assertCancelLinkUrl(url('node'));
  2516. $this->drupalGet('user/1/cancel', array('query' => array('destination' => 'http://example.com')));
  2517. $this->assertCancelLinkUrl(url('user/1'));
  2518. }
  2519. /**
  2520. * Asserts that a cancel link is present pointing to the provided URL.
  2521. */
  2522. function assertCancelLinkUrl($url, $message = '', $group = 'Other') {
  2523. $links = $this->xpath('//a[normalize-space(text())=:label and @href=:url]', array(':label' => t('Cancel'), ':url' => $url));
  2524. $message = ($message ? $message : format_string('Cancel link with url %url found.', array('%url' => $url)));
  2525. return $this->assertTrue(isset($links[0]), $message, $group);
  2526. }
  2527. }