system.test 119 KB

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