system.test 116 KB

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