system.test 120 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098
  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_d8($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 COUNT(*) from {blocked_ips} WHERE ip = :ip", array(':ip' => $submit_ip))->fetchColumn();
  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 COUNT(*) from {blocked_ips} WHERE ip = :ip", array(':ip' => $submit_ip))->fetchColumn();
  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 individual per-theme settings form.
  1698. */
  1699. function testPerThemeSettings() {
  1700. // Enable the test theme and the module that controls it. Clear caches in
  1701. // between so that the module's hook_system_theme_info() implementation is
  1702. // correctly registered.
  1703. module_enable(array('theme_test'));
  1704. drupal_flush_all_caches();
  1705. theme_enable(array('test_theme'));
  1706. // Test that the theme-specific settings form can be saved and that the
  1707. // theme-specific checkbox is checked and unchecked as appropriate.
  1708. $this->drupalGet('admin/appearance/settings/test_theme');
  1709. $this->assertNoFieldChecked('edit-test-theme-checkbox', 'The test_theme_checkbox setting is unchecked.');
  1710. $this->drupalPost(NULL, array('test_theme_checkbox' => TRUE), t('Save configuration'));
  1711. $this->assertText('The test theme setting was saved.');
  1712. $this->assertFieldChecked('edit-test-theme-checkbox', 'The test_theme_checkbox setting is checked.');
  1713. $this->drupalPost(NULL, array('test_theme_checkbox' => FALSE), t('Save configuration'));
  1714. $this->assertText('The test theme setting was saved.');
  1715. $this->assertNoFieldChecked('edit-test-theme-checkbox', 'The test_theme_checkbox setting is unchecked.');
  1716. }
  1717. /**
  1718. * Test the administration theme functionality.
  1719. */
  1720. function testAdministrationTheme() {
  1721. theme_enable(array('stark'));
  1722. variable_set('theme_default', 'stark');
  1723. // Enable an administration theme and show it on the node admin pages.
  1724. $edit = array(
  1725. 'admin_theme' => 'seven',
  1726. 'node_admin_theme' => TRUE,
  1727. );
  1728. $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
  1729. $this->drupalGet('admin/config');
  1730. $this->assertRaw('themes/seven', 'Administration theme used on an administration page.');
  1731. $this->drupalGet('node/' . $this->node->nid);
  1732. $this->assertRaw('themes/stark', 'Site default theme used on node page.');
  1733. $this->drupalGet('node/add');
  1734. $this->assertRaw('themes/seven', 'Administration theme used on the add content page.');
  1735. $this->drupalGet('node/' . $this->node->nid . '/edit');
  1736. $this->assertRaw('themes/seven', 'Administration theme used on the edit content page.');
  1737. // Disable the admin theme on the node admin pages.
  1738. $edit = array(
  1739. 'node_admin_theme' => FALSE,
  1740. );
  1741. $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
  1742. $this->drupalGet('admin/config');
  1743. $this->assertRaw('themes/seven', 'Administration theme used on an administration page.');
  1744. $this->drupalGet('node/add');
  1745. $this->assertRaw('themes/stark', 'Site default theme used on the add content page.');
  1746. // Reset to the default theme settings.
  1747. variable_set('theme_default', 'bartik');
  1748. $edit = array(
  1749. 'admin_theme' => '0',
  1750. 'node_admin_theme' => FALSE,
  1751. );
  1752. $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
  1753. $this->drupalGet('admin');
  1754. $this->assertRaw('themes/bartik', 'Site default theme used on administration page.');
  1755. $this->drupalGet('node/add');
  1756. $this->assertRaw('themes/bartik', 'Site default theme used on the add content page.');
  1757. }
  1758. /**
  1759. * Test switching the default theme.
  1760. */
  1761. function testSwitchDefaultTheme() {
  1762. // Enable "stark" and set it as the default theme.
  1763. theme_enable(array('stark'));
  1764. $this->drupalGet('admin/appearance');
  1765. $this->clickLink(t('Set default'), 1);
  1766. $this->assertTrue(variable_get('theme_default', '') == 'stark', 'Site default theme switched successfully.');
  1767. // Test the default theme on the secondary links (blocks admin page).
  1768. $this->drupalGet('admin/structure/block');
  1769. $this->assertText('Stark(' . t('active tab') . ')', 'Default local task on blocks admin page is the default theme.');
  1770. // Switch back to Bartik and test again to test that the menu cache is cleared.
  1771. $this->drupalGet('admin/appearance');
  1772. $this->clickLink(t('Set default'), 0);
  1773. $this->drupalGet('admin/structure/block');
  1774. $this->assertText('Bartik(' . t('active tab') . ')', 'Default local task on blocks admin page has changed.');
  1775. }
  1776. }
  1777. /**
  1778. * Test the basic queue functionality.
  1779. */
  1780. class QueueTestCase extends DrupalWebTestCase {
  1781. public static function getInfo() {
  1782. return array(
  1783. 'name' => 'Queue functionality',
  1784. 'description' => 'Queues and dequeues a set of items to check the basic queue functionality.',
  1785. 'group' => 'System',
  1786. );
  1787. }
  1788. /**
  1789. * Queues and dequeues a set of items to check the basic queue functionality.
  1790. */
  1791. function testQueue() {
  1792. // Create two queues.
  1793. $queue1 = DrupalQueue::get($this->randomName());
  1794. $queue1->createQueue();
  1795. $queue2 = DrupalQueue::get($this->randomName());
  1796. $queue2->createQueue();
  1797. // Create four items.
  1798. $data = array();
  1799. for ($i = 0; $i < 4; $i++) {
  1800. $data[] = array($this->randomName() => $this->randomName());
  1801. }
  1802. // Queue items 1 and 2 in the queue1.
  1803. $queue1->createItem($data[0]);
  1804. $queue1->createItem($data[1]);
  1805. // Retrieve two items from queue1.
  1806. $items = array();
  1807. $new_items = array();
  1808. $items[] = $item = $queue1->claimItem();
  1809. $new_items[] = $item->data;
  1810. $items[] = $item = $queue1->claimItem();
  1811. $new_items[] = $item->data;
  1812. // First two dequeued items should match the first two items we queued.
  1813. $this->assertEqual($this->queueScore($data, $new_items), 2, 'Two items matched');
  1814. // Add two more items.
  1815. $queue1->createItem($data[2]);
  1816. $queue1->createItem($data[3]);
  1817. $this->assertTrue($queue1->numberOfItems(), 'Queue 1 is not empty after adding items.');
  1818. $this->assertFalse($queue2->numberOfItems(), 'Queue 2 is empty while Queue 1 has items');
  1819. $items[] = $item = $queue1->claimItem();
  1820. $new_items[] = $item->data;
  1821. $items[] = $item = $queue1->claimItem();
  1822. $new_items[] = $item->data;
  1823. // All dequeued items should match the items we queued exactly once,
  1824. // therefore the score must be exactly 4.
  1825. $this->assertEqual($this->queueScore($data, $new_items), 4, 'Four items matched');
  1826. // There should be no duplicate items.
  1827. $this->assertEqual($this->queueScore($new_items, $new_items), 4, 'Four items matched');
  1828. // Delete all items from queue1.
  1829. foreach ($items as $item) {
  1830. $queue1->deleteItem($item);
  1831. }
  1832. // Check that both queues are empty.
  1833. $this->assertFalse($queue1->numberOfItems(), 'Queue 1 is empty');
  1834. $this->assertFalse($queue2->numberOfItems(), 'Queue 2 is empty');
  1835. }
  1836. /**
  1837. * This function returns the number of equal items in two arrays.
  1838. */
  1839. function queueScore($items, $new_items) {
  1840. $score = 0;
  1841. foreach ($items as $item) {
  1842. foreach ($new_items as $new_item) {
  1843. if ($item === $new_item) {
  1844. $score++;
  1845. }
  1846. }
  1847. }
  1848. return $score;
  1849. }
  1850. }
  1851. /**
  1852. * Test token replacement in strings.
  1853. */
  1854. class TokenReplaceTestCase extends DrupalWebTestCase {
  1855. public static function getInfo() {
  1856. return array(
  1857. 'name' => 'Token replacement',
  1858. 'description' => 'Generates text using placeholders for dummy content to check token replacement.',
  1859. 'group' => 'System',
  1860. );
  1861. }
  1862. /**
  1863. * Creates a user and a node, then tests the tokens generated from them.
  1864. */
  1865. function testTokenReplacement() {
  1866. // Create the initial objects.
  1867. $account = $this->drupalCreateUser();
  1868. $node = $this->drupalCreateNode(array('uid' => $account->uid));
  1869. $node->title = '<blink>Blinking Text</blink>';
  1870. global $user, $language;
  1871. $source = '[node:title]'; // Title of the node we passed in
  1872. $source .= '[node:author:name]'; // Node author's name
  1873. $source .= '[node:created:since]'; // Time since the node was created
  1874. $source .= '[current-user:name]'; // Current user's name
  1875. $source .= '[date:short]'; // Short date format of REQUEST_TIME
  1876. $source .= '[user:name]'; // No user passed in, should be untouched
  1877. $source .= '[bogus:token]'; // Non-existent token
  1878. $target = check_plain($node->title);
  1879. $target .= check_plain($account->name);
  1880. $target .= format_interval(REQUEST_TIME - $node->created, 2, $language->language);
  1881. $target .= check_plain($user->name);
  1882. $target .= format_date(REQUEST_TIME, 'short', '', NULL, $language->language);
  1883. // Test that the clear parameter cleans out non-existent tokens.
  1884. $result = token_replace($source, array('node' => $node), array('language' => $language, 'clear' => TRUE));
  1885. $result = $this->assertEqual($target, $result, 'Valid tokens replaced while invalid tokens cleared out.');
  1886. // Test without using the clear parameter (non-existent token untouched).
  1887. $target .= '[user:name]';
  1888. $target .= '[bogus:token]';
  1889. $result = token_replace($source, array('node' => $node), array('language' => $language));
  1890. $this->assertEqual($target, $result, 'Valid tokens replaced while invalid tokens ignored.');
  1891. // Check that the results of token_generate are sanitized properly. This does NOT
  1892. // test the cleanliness of every token -- just that the $sanitize flag is being
  1893. // passed properly through the call stack and being handled correctly by a 'known'
  1894. // token, [node:title].
  1895. $raw_tokens = array('title' => '[node:title]');
  1896. $generated = token_generate('node', $raw_tokens, array('node' => $node));
  1897. $this->assertEqual($generated['[node:title]'], check_plain($node->title), 'Token sanitized.');
  1898. $generated = token_generate('node', $raw_tokens, array('node' => $node), array('sanitize' => FALSE));
  1899. $this->assertEqual($generated['[node:title]'], $node->title, 'Unsanitized token generated properly.');
  1900. // Test token replacement when the string contains no tokens.
  1901. $this->assertEqual(token_replace('No tokens here.'), 'No tokens here.');
  1902. }
  1903. /**
  1904. * Test whether token-replacement works in various contexts.
  1905. */
  1906. function testSystemTokenRecognition() {
  1907. global $language;
  1908. // Generate prefixes and suffixes for the token context.
  1909. $tests = array(
  1910. array('prefix' => 'this is the ', 'suffix' => ' site'),
  1911. array('prefix' => 'this is the', 'suffix' => 'site'),
  1912. array('prefix' => '[', 'suffix' => ']'),
  1913. array('prefix' => '', 'suffix' => ']]]'),
  1914. array('prefix' => '[[[', 'suffix' => ''),
  1915. array('prefix' => ':[:', 'suffix' => '--]'),
  1916. array('prefix' => '-[-', 'suffix' => ':]:'),
  1917. array('prefix' => '[:', 'suffix' => ']'),
  1918. array('prefix' => '[site:', 'suffix' => ':name]'),
  1919. array('prefix' => '[site:', 'suffix' => ']'),
  1920. );
  1921. // Check if the token is recognized in each of the contexts.
  1922. foreach ($tests as $test) {
  1923. $input = $test['prefix'] . '[site:name]' . $test['suffix'];
  1924. $expected = $test['prefix'] . 'Drupal' . $test['suffix'];
  1925. $output = token_replace($input, array(), array('language' => $language));
  1926. $this->assertTrue($output == $expected, format_string('Token recognized in string %string', array('%string' => $input)));
  1927. }
  1928. }
  1929. /**
  1930. * Tests the generation of all system site information tokens.
  1931. */
  1932. function testSystemSiteTokenReplacement() {
  1933. global $language;
  1934. $url_options = array(
  1935. 'absolute' => TRUE,
  1936. 'language' => $language,
  1937. );
  1938. // Set a few site variables.
  1939. variable_set('site_name', '<strong>Drupal<strong>');
  1940. variable_set('site_slogan', '<blink>Slogan</blink>');
  1941. // Generate and test sanitized tokens.
  1942. $tests = array();
  1943. $tests['[site:name]'] = check_plain(variable_get('site_name', 'Drupal'));
  1944. $tests['[site:slogan]'] = check_plain(variable_get('site_slogan', ''));
  1945. $tests['[site:mail]'] = 'simpletest@example.com';
  1946. $tests['[site:url]'] = url('<front>', $url_options);
  1947. $tests['[site:url-brief]'] = preg_replace(array('!^https?://!', '!/$!'), '', url('<front>', $url_options));
  1948. $tests['[site:login-url]'] = url('user', $url_options);
  1949. // Test to make sure that we generated something for each token.
  1950. $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
  1951. foreach ($tests as $input => $expected) {
  1952. $output = token_replace($input, array(), array('language' => $language));
  1953. $this->assertEqual($output, $expected, format_string('Sanitized system site information token %token replaced.', array('%token' => $input)));
  1954. }
  1955. // Generate and test unsanitized tokens.
  1956. $tests['[site:name]'] = variable_get('site_name', 'Drupal');
  1957. $tests['[site:slogan]'] = variable_get('site_slogan', '');
  1958. foreach ($tests as $input => $expected) {
  1959. $output = token_replace($input, array(), array('language' => $language, 'sanitize' => FALSE));
  1960. $this->assertEqual($output, $expected, format_string('Unsanitized system site information token %token replaced.', array('%token' => $input)));
  1961. }
  1962. }
  1963. /**
  1964. * Tests the generation of all system date tokens.
  1965. */
  1966. function testSystemDateTokenReplacement() {
  1967. global $language;
  1968. // Set time to one hour before request.
  1969. $date = REQUEST_TIME - 3600;
  1970. // Generate and test tokens.
  1971. $tests = array();
  1972. $tests['[date:short]'] = format_date($date, 'short', '', NULL, $language->language);
  1973. $tests['[date:medium]'] = format_date($date, 'medium', '', NULL, $language->language);
  1974. $tests['[date:long]'] = format_date($date, 'long', '', NULL, $language->language);
  1975. $tests['[date:custom:m/j/Y]'] = format_date($date, 'custom', 'm/j/Y', NULL, $language->language);
  1976. $tests['[date:since]'] = format_interval((REQUEST_TIME - $date), 2, $language->language);
  1977. $tests['[date:raw]'] = filter_xss($date);
  1978. // Test to make sure that we generated something for each token.
  1979. $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
  1980. foreach ($tests as $input => $expected) {
  1981. $output = token_replace($input, array('date' => $date), array('language' => $language));
  1982. $this->assertEqual($output, $expected, format_string('Date token %token replaced.', array('%token' => $input)));
  1983. }
  1984. }
  1985. }
  1986. class InfoFileParserTestCase extends DrupalUnitTestCase {
  1987. public static function getInfo() {
  1988. return array(
  1989. 'name' => 'Info file format parser',
  1990. 'description' => 'Tests proper parsing of a .info file formatted string.',
  1991. 'group' => 'System',
  1992. );
  1993. }
  1994. /**
  1995. * Test drupal_parse_info_format().
  1996. */
  1997. function testDrupalParseInfoFormat() {
  1998. $config = '
  1999. simple = Value
  2000. quoted = " Value"
  2001. multiline = "Value
  2002. Value"
  2003. array[] = Value1
  2004. array[] = Value2
  2005. array_assoc[a] = Value1
  2006. array_assoc[b] = Value2
  2007. array_deep[][][] = Value
  2008. array_deep_assoc[a][b][c] = Value
  2009. array_space[a b] = Value';
  2010. $expected = array(
  2011. 'simple' => 'Value',
  2012. 'quoted' => ' Value',
  2013. 'multiline' => "Value\n Value",
  2014. 'array' => array(
  2015. 0 => 'Value1',
  2016. 1 => 'Value2',
  2017. ),
  2018. 'array_assoc' => array(
  2019. 'a' => 'Value1',
  2020. 'b' => 'Value2',
  2021. ),
  2022. 'array_deep' => array(
  2023. 0 => array(
  2024. 0 => array(
  2025. 0 => 'Value',
  2026. ),
  2027. ),
  2028. ),
  2029. 'array_deep_assoc' => array(
  2030. 'a' => array(
  2031. 'b' => array(
  2032. 'c' => 'Value',
  2033. ),
  2034. ),
  2035. ),
  2036. 'array_space' => array(
  2037. 'a b' => 'Value',
  2038. ),
  2039. );
  2040. $parsed = drupal_parse_info_format($config);
  2041. $this->assertEqual($parsed['simple'], $expected['simple'], 'Set a simple value.');
  2042. $this->assertEqual($parsed['quoted'], $expected['quoted'], 'Set a simple value in quotes.');
  2043. $this->assertEqual($parsed['multiline'], $expected['multiline'], 'Set a multiline value.');
  2044. $this->assertEqual($parsed['array'], $expected['array'], 'Set a simple array.');
  2045. $this->assertEqual($parsed['array_assoc'], $expected['array_assoc'], 'Set an associative array.');
  2046. $this->assertEqual($parsed['array_deep'], $expected['array_deep'], 'Set a nested array.');
  2047. $this->assertEqual($parsed['array_deep_assoc'], $expected['array_deep_assoc'], 'Set a nested associative array.');
  2048. $this->assertEqual($parsed['array_space'], $expected['array_space'], 'Set an array with a whitespace in the key.');
  2049. $this->assertEqual($parsed, $expected, 'Entire parsed .info string and expected array are identical.');
  2050. }
  2051. }
  2052. /**
  2053. * Tests the effectiveness of hook_system_info_alter().
  2054. */
  2055. class SystemInfoAlterTestCase extends DrupalWebTestCase {
  2056. public static function getInfo() {
  2057. return array(
  2058. 'name' => 'System info alter',
  2059. 'description' => 'Tests the effectiveness of hook_system_info_alter().',
  2060. 'group' => 'System',
  2061. );
  2062. }
  2063. /**
  2064. * Tests that {system}.info is rebuilt after a module that implements
  2065. * hook_system_info_alter() is enabled. Also tests if core *_list() functions
  2066. * return freshly altered info.
  2067. */
  2068. function testSystemInfoAlter() {
  2069. // Enable our test module. Flush all caches, which we assert is the only
  2070. // thing necessary to use the rebuilt {system}.info.
  2071. module_enable(array('module_test'), FALSE);
  2072. drupal_flush_all_caches();
  2073. $this->assertTrue(module_exists('module_test'), 'Test module is enabled.');
  2074. $info = $this->getSystemInfo('seven', 'theme');
  2075. $this->assertTrue(isset($info['regions']['test_region']), 'Altered theme info was added to {system}.info.');
  2076. $seven_regions = system_region_list('seven');
  2077. $this->assertTrue(isset($seven_regions['test_region']), 'Altered theme info was returned by system_region_list().');
  2078. $system_list_themes = system_list('theme');
  2079. $info = $system_list_themes['seven']->info;
  2080. $this->assertTrue(isset($info['regions']['test_region']), 'Altered theme info was returned by system_list().');
  2081. $list_themes = list_themes();
  2082. $this->assertTrue(isset($list_themes['seven']->info['regions']['test_region']), 'Altered theme info was returned by list_themes().');
  2083. // Disable the module and verify that {system}.info is rebuilt without it.
  2084. module_disable(array('module_test'), FALSE);
  2085. drupal_flush_all_caches();
  2086. $this->assertFalse(module_exists('module_test'), 'Test module is disabled.');
  2087. $info = $this->getSystemInfo('seven', 'theme');
  2088. $this->assertFalse(isset($info['regions']['test_region']), 'Altered theme info was removed from {system}.info.');
  2089. $seven_regions = system_region_list('seven');
  2090. $this->assertFalse(isset($seven_regions['test_region']), 'Altered theme info was not returned by system_region_list().');
  2091. $system_list_themes = system_list('theme');
  2092. $info = $system_list_themes['seven']->info;
  2093. $this->assertFalse(isset($info['regions']['test_region']), 'Altered theme info was not returned by system_list().');
  2094. $list_themes = list_themes();
  2095. $this->assertFalse(isset($list_themes['seven']->info['regions']['test_region']), 'Altered theme info was not returned by list_themes().');
  2096. }
  2097. /**
  2098. * Returns the info array as it is stored in {system}.
  2099. *
  2100. * @param $name
  2101. * The name of the record in {system}.
  2102. * @param $type
  2103. * The type of record in {system}.
  2104. *
  2105. * @return
  2106. * Array of info, or FALSE if the record is not found.
  2107. */
  2108. function getSystemInfo($name, $type) {
  2109. $raw_info = db_query("SELECT info FROM {system} WHERE name = :name AND type = :type", array(':name' => $name, ':type' => $type))->fetchField();
  2110. return $raw_info ? unserialize($raw_info) : FALSE;
  2111. }
  2112. }
  2113. /**
  2114. * Tests for the update system functionality.
  2115. */
  2116. class UpdateScriptFunctionalTest extends DrupalWebTestCase {
  2117. private $update_url;
  2118. private $update_user;
  2119. public static function getInfo() {
  2120. return array(
  2121. 'name' => 'Update functionality',
  2122. 'description' => 'Tests the update script access and functionality.',
  2123. 'group' => 'System',
  2124. );
  2125. }
  2126. function setUp() {
  2127. parent::setUp('update_script_test');
  2128. $this->update_url = $GLOBALS['base_url'] . '/update.php';
  2129. $this->update_user = $this->drupalCreateUser(array('administer software updates'));
  2130. }
  2131. /**
  2132. * Tests that there are no pending updates for the first test method.
  2133. */
  2134. function testNoPendingUpdates() {
  2135. // Ensure that for the first test method in a class, there are no pending
  2136. // updates. This tests a drupal_get_schema_versions() bug that previously
  2137. // led to the wrong schema version being recorded for the initial install
  2138. // of a child site during automated testing.
  2139. $this->drupalLogin($this->update_user);
  2140. $this->drupalGet($this->update_url, array('external' => TRUE));
  2141. $this->drupalPost(NULL, array(), t('Continue'));
  2142. $this->assertText(t('No pending updates.'), 'End of update process was reached.');
  2143. }
  2144. /**
  2145. * Tests access to the update script.
  2146. */
  2147. function testUpdateAccess() {
  2148. // Try accessing update.php without the proper permission.
  2149. $regular_user = $this->drupalCreateUser();
  2150. $this->drupalLogin($regular_user);
  2151. $this->drupalGet($this->update_url, array('external' => TRUE));
  2152. $this->assertResponse(403);
  2153. // Try accessing update.php as an anonymous user.
  2154. $this->drupalLogout();
  2155. $this->drupalGet($this->update_url, array('external' => TRUE));
  2156. $this->assertResponse(403);
  2157. // Access the update page with the proper permission.
  2158. $this->drupalLogin($this->update_user);
  2159. $this->drupalGet($this->update_url, array('external' => TRUE));
  2160. $this->assertResponse(200);
  2161. // Access the update page as user 1.
  2162. $user1 = user_load(1);
  2163. $user1->pass_raw = user_password();
  2164. require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
  2165. $user1->pass = user_hash_password(trim($user1->pass_raw));
  2166. db_query("UPDATE {users} SET pass = :pass WHERE uid = :uid", array(':pass' => $user1->pass, ':uid' => $user1->uid));
  2167. $this->drupalLogin($user1);
  2168. $this->drupalGet($this->update_url, array('external' => TRUE));
  2169. $this->assertResponse(200);
  2170. }
  2171. /**
  2172. * Tests that requirements warnings and errors are correctly displayed.
  2173. */
  2174. function testRequirements() {
  2175. $this->drupalLogin($this->update_user);
  2176. // If there are no requirements warnings or errors, we expect to be able to
  2177. // go through the update process uninterrupted.
  2178. $this->drupalGet($this->update_url, array('external' => TRUE));
  2179. $this->drupalPost(NULL, array(), t('Continue'));
  2180. $this->assertText(t('No pending updates.'), 'End of update process was reached.');
  2181. // Confirm that all caches were cleared.
  2182. $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared when there were no requirements warnings or errors.');
  2183. // If there is a requirements warning, we expect it to be initially
  2184. // displayed, but clicking the link to proceed should allow us to go
  2185. // through the rest of the update process uninterrupted.
  2186. // First, run this test with pending updates to make sure they can be run
  2187. // successfully.
  2188. variable_set('update_script_test_requirement_type', REQUIREMENT_WARNING);
  2189. drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
  2190. $this->drupalGet($this->update_url, array('external' => TRUE));
  2191. $this->assertText('This is a requirements warning provided by the update_script_test module.');
  2192. $this->clickLink('try again');
  2193. $this->assertNoText('This is a requirements warning provided by the update_script_test module.');
  2194. $this->drupalPost(NULL, array(), t('Continue'));
  2195. $this->drupalPost(NULL, array(), t('Apply pending updates'));
  2196. $this->assertText(t('The update_script_test_update_7000() update was executed successfully.'), 'End of update process was reached.');
  2197. // Confirm that all caches were cleared.
  2198. $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared after resolving a requirements warning and applying updates.');
  2199. // Now try again without pending updates to make sure that works too.
  2200. $this->drupalGet($this->update_url, array('external' => TRUE));
  2201. $this->assertText('This is a requirements warning provided by the update_script_test module.');
  2202. $this->clickLink('try again');
  2203. $this->assertNoText('This is a requirements warning provided by the update_script_test module.');
  2204. $this->drupalPost(NULL, array(), t('Continue'));
  2205. $this->assertText(t('No pending updates.'), 'End of update process was reached.');
  2206. // Confirm that all caches were cleared.
  2207. $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared after applying updates and re-running the script.');
  2208. // If there is a requirements error, it should be displayed even after
  2209. // clicking the link to proceed (since the problem that triggered the error
  2210. // has not been fixed).
  2211. variable_set('update_script_test_requirement_type', REQUIREMENT_ERROR);
  2212. $this->drupalGet($this->update_url, array('external' => TRUE));
  2213. $this->assertText('This is a requirements error provided by the update_script_test module.');
  2214. $this->clickLink('try again');
  2215. $this->assertText('This is a requirements error provided by the update_script_test module.');
  2216. // Check if the optional 'value' key displays without a notice.
  2217. variable_set('update_script_test_requirement_type', REQUIREMENT_INFO);
  2218. $this->drupalGet($this->update_url, array('external' => TRUE));
  2219. $this->assertText('This is a requirements info provided by the update_script_test module.');
  2220. $this->assertNoText('Notice: Undefined index: value in theme_status_report()');
  2221. }
  2222. /**
  2223. * Tests the effect of using the update script on the theme system.
  2224. */
  2225. function testThemeSystem() {
  2226. // Since visiting update.php triggers a rebuild of the theme system from an
  2227. // unusual maintenance mode environment, we check that this rebuild did not
  2228. // put any incorrect information about the themes into the database.
  2229. $original_theme_data = db_query("SELECT * FROM {system} WHERE type = 'theme' ORDER BY name")->fetchAll();
  2230. $this->drupalLogin($this->update_user);
  2231. $this->drupalGet($this->update_url, array('external' => TRUE));
  2232. $final_theme_data = db_query("SELECT * FROM {system} WHERE type = 'theme' ORDER BY name")->fetchAll();
  2233. $this->assertEqual($original_theme_data, $final_theme_data, 'Visiting update.php does not alter the information about themes stored in the database.');
  2234. }
  2235. /**
  2236. * Tests update.php when there are no updates to apply.
  2237. */
  2238. function testNoUpdateFunctionality() {
  2239. // Click through update.php with 'administer software updates' permission.
  2240. $this->drupalLogin($this->update_user);
  2241. $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
  2242. $this->assertText(t('No pending updates.'));
  2243. $this->assertNoLink('Administration pages');
  2244. $this->clickLink('Front page');
  2245. $this->assertResponse(200);
  2246. // Click through update.php with 'access administration pages' permission.
  2247. $admin_user = $this->drupalCreateUser(array('administer software updates', 'access administration pages'));
  2248. $this->drupalLogin($admin_user);
  2249. $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
  2250. $this->assertText(t('No pending updates.'));
  2251. $this->clickLink('Administration pages');
  2252. $this->assertResponse(200);
  2253. }
  2254. /**
  2255. * Tests update.php after performing a successful update.
  2256. */
  2257. function testSuccessfulUpdateFunctionality() {
  2258. drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
  2259. // Click through update.php with 'administer software updates' permission.
  2260. $this->drupalLogin($this->update_user);
  2261. $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
  2262. $this->drupalPost(NULL, array(), t('Apply pending updates'));
  2263. $this->assertText('Updates were attempted.');
  2264. $this->assertLink('site');
  2265. $this->assertNoLink('Administration pages');
  2266. $this->assertNoLink('logged');
  2267. $this->clickLink('Front page');
  2268. $this->assertResponse(200);
  2269. drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
  2270. // Click through update.php with 'access administration pages' and
  2271. // 'access site reports' permissions.
  2272. $admin_user = $this->drupalCreateUser(array('administer software updates', 'access administration pages', 'access site reports'));
  2273. $this->drupalLogin($admin_user);
  2274. $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
  2275. $this->drupalPost(NULL, array(), t('Apply pending updates'));
  2276. $this->assertText('Updates were attempted.');
  2277. $this->assertLink('logged');
  2278. $this->clickLink('Administration pages');
  2279. $this->assertResponse(200);
  2280. }
  2281. }
  2282. /**
  2283. * Functional tests for the flood control mechanism.
  2284. */
  2285. class FloodFunctionalTest extends DrupalWebTestCase {
  2286. public static function getInfo() {
  2287. return array(
  2288. 'name' => 'Flood control mechanism',
  2289. 'description' => 'Functional tests for the flood control mechanism.',
  2290. 'group' => 'System',
  2291. );
  2292. }
  2293. /**
  2294. * Test flood control mechanism clean-up.
  2295. */
  2296. function testCleanUp() {
  2297. $threshold = 1;
  2298. $window_expired = -1;
  2299. $name = 'flood_test_cleanup';
  2300. // Register expired event.
  2301. flood_register_event($name, $window_expired);
  2302. // Verify event is not allowed.
  2303. $this->assertFalse(flood_is_allowed($name, $threshold));
  2304. // Run cron and verify event is now allowed.
  2305. $this->cronRun();
  2306. $this->assertTrue(flood_is_allowed($name, $threshold));
  2307. // Register unexpired event.
  2308. flood_register_event($name);
  2309. // Verify event is not allowed.
  2310. $this->assertFalse(flood_is_allowed($name, $threshold));
  2311. // Run cron and verify event is still not allowed.
  2312. $this->cronRun();
  2313. $this->assertFalse(flood_is_allowed($name, $threshold));
  2314. }
  2315. }
  2316. /**
  2317. * Test HTTP file downloading capability.
  2318. */
  2319. class RetrieveFileTestCase extends DrupalWebTestCase {
  2320. public static function getInfo() {
  2321. return array(
  2322. 'name' => 'HTTP file retrieval',
  2323. 'description' => 'Checks HTTP file fetching and error handling.',
  2324. 'group' => 'System',
  2325. );
  2326. }
  2327. /**
  2328. * Invokes system_retrieve_file() in several scenarios.
  2329. */
  2330. function testFileRetrieving() {
  2331. // Test 404 handling by trying to fetch a randomly named file.
  2332. drupal_mkdir($sourcedir = 'public://' . $this->randomName());
  2333. $filename = 'Файл для тестирования ' . $this->randomName();
  2334. $url = file_create_url($sourcedir . '/' . $filename);
  2335. $retrieved_file = system_retrieve_file($url);
  2336. $this->assertFalse($retrieved_file, 'Non-existent file not fetched.');
  2337. // Actually create that file, download it via HTTP and test the returned path.
  2338. file_put_contents($sourcedir . '/' . $filename, 'testing');
  2339. $retrieved_file = system_retrieve_file($url);
  2340. // URLs could not contains characters outside the ASCII set so $filename
  2341. // has to be encoded.
  2342. $encoded_filename = rawurlencode($filename);
  2343. $this->assertEqual($retrieved_file, 'public://' . $encoded_filename, 'Sane path for downloaded file returned (public:// scheme).');
  2344. $this->assertTrue(is_file($retrieved_file), 'Downloaded file does exist (public:// scheme).');
  2345. $this->assertEqual(filesize($retrieved_file), 7, 'File size of downloaded file is correct (public:// scheme).');
  2346. file_unmanaged_delete($retrieved_file);
  2347. // Test downloading file to a different location.
  2348. drupal_mkdir($targetdir = 'temporary://' . $this->randomName());
  2349. $retrieved_file = system_retrieve_file($url, $targetdir);
  2350. $this->assertEqual($retrieved_file, "$targetdir/$encoded_filename", 'Sane path for downloaded file returned (temporary:// scheme).');
  2351. $this->assertTrue(is_file($retrieved_file), 'Downloaded file does exist (temporary:// scheme).');
  2352. $this->assertEqual(filesize($retrieved_file), 7, 'File size of downloaded file is correct (temporary:// scheme).');
  2353. file_unmanaged_delete($retrieved_file);
  2354. file_unmanaged_delete_recursive($sourcedir);
  2355. file_unmanaged_delete_recursive($targetdir);
  2356. }
  2357. }
  2358. /**
  2359. * Functional tests shutdown functions.
  2360. */
  2361. class ShutdownFunctionsTest extends DrupalWebTestCase {
  2362. public static function getInfo() {
  2363. return array(
  2364. 'name' => 'Shutdown functions',
  2365. 'description' => 'Functional tests for shutdown functions',
  2366. 'group' => 'System',
  2367. );
  2368. }
  2369. function setUp() {
  2370. parent::setUp('system_test');
  2371. }
  2372. /**
  2373. * Test shutdown functions.
  2374. */
  2375. function testShutdownFunctions() {
  2376. $arg1 = $this->randomName();
  2377. $arg2 = $this->randomName();
  2378. $this->drupalGet('system-test/shutdown-functions/' . $arg1 . '/' . $arg2);
  2379. $this->assertText(t('First shutdown function, arg1 : @arg1, arg2: @arg2', array('@arg1' => $arg1, '@arg2' => $arg2)));
  2380. $this->assertText(t('Second shutdown function, arg1 : @arg1, arg2: @arg2', array('@arg1' => $arg1, '@arg2' => $arg2)));
  2381. // Make sure exceptions displayed through _drupal_render_exception_safe()
  2382. // are correctly escaped.
  2383. $this->assertRaw('Drupal is &amp;lt;blink&amp;gt;awesome&amp;lt;/blink&amp;gt;.');
  2384. }
  2385. }
  2386. /**
  2387. * Tests administrative overview pages.
  2388. */
  2389. class SystemAdminTestCase extends DrupalWebTestCase {
  2390. public static function getInfo() {
  2391. return array(
  2392. 'name' => 'Administrative pages',
  2393. 'description' => 'Tests output on administrative pages and compact mode functionality.',
  2394. 'group' => 'System',
  2395. );
  2396. }
  2397. function setUp() {
  2398. // testAdminPages() requires Locale module.
  2399. parent::setUp(array('locale'));
  2400. // Create an administrator with all permissions, as well as a regular user
  2401. // who can only access administration pages and perform some Locale module
  2402. // administrative tasks, but not all of them.
  2403. $this->admin_user = $this->drupalCreateUser(array_keys(module_invoke_all('permission')));
  2404. $this->web_user = $this->drupalCreateUser(array(
  2405. 'access administration pages',
  2406. 'translate interface',
  2407. ));
  2408. $this->drupalLogin($this->admin_user);
  2409. }
  2410. /**
  2411. * Tests output on administrative listing pages.
  2412. */
  2413. function testAdminPages() {
  2414. // Go to Administration.
  2415. $this->drupalGet('admin');
  2416. // Verify that all visible, top-level administration links are listed on
  2417. // the main administration page.
  2418. foreach (menu_get_router() as $path => $item) {
  2419. if (strpos($path, 'admin/') === 0 && ($item['type'] & MENU_VISIBLE_IN_TREE) && $item['_number_parts'] == 2) {
  2420. $this->assertLink($item['title']);
  2421. $this->assertLinkByHref($path);
  2422. $this->assertText($item['description']);
  2423. }
  2424. }
  2425. // For each administrative listing page on which the Locale module appears,
  2426. // verify that there are links to the module's primary configuration pages,
  2427. // but no links to its individual sub-configuration pages. Also verify that
  2428. // a user with access to only some Locale module administration pages only
  2429. // sees links to the pages they have access to.
  2430. $admin_list_pages = array(
  2431. 'admin/index',
  2432. 'admin/config',
  2433. 'admin/config/regional',
  2434. );
  2435. foreach ($admin_list_pages as $page) {
  2436. // For the administrator, verify that there are links to Locale's primary
  2437. // configuration pages, but no links to individual sub-configuration
  2438. // pages.
  2439. $this->drupalLogin($this->admin_user);
  2440. $this->drupalGet($page);
  2441. $this->assertLinkByHref('admin/config');
  2442. $this->assertLinkByHref('admin/config/regional/settings');
  2443. $this->assertLinkByHref('admin/config/regional/date-time');
  2444. $this->assertLinkByHref('admin/config/regional/language');
  2445. $this->assertNoLinkByHref('admin/config/regional/language/configure/session');
  2446. $this->assertNoLinkByHref('admin/config/regional/language/configure/url');
  2447. $this->assertLinkByHref('admin/config/regional/translate');
  2448. // On admin/index only, the administrator should also see a "Configure
  2449. // permissions" link for the Locale module.
  2450. if ($page == 'admin/index') {
  2451. $this->assertLinkByHref("admin/people/permissions#module-locale");
  2452. }
  2453. // For a less privileged user, verify that there are no links to Locale's
  2454. // primary configuration pages, but a link to the translate page exists.
  2455. $this->drupalLogin($this->web_user);
  2456. $this->drupalGet($page);
  2457. $this->assertLinkByHref('admin/config');
  2458. $this->assertNoLinkByHref('admin/config/regional/settings');
  2459. $this->assertNoLinkByHref('admin/config/regional/date-time');
  2460. $this->assertNoLinkByHref('admin/config/regional/language');
  2461. $this->assertNoLinkByHref('admin/config/regional/language/configure/session');
  2462. $this->assertNoLinkByHref('admin/config/regional/language/configure/url');
  2463. $this->assertLinkByHref('admin/config/regional/translate');
  2464. // This user cannot configure permissions, so even on admin/index should
  2465. // not see a "Configure permissions" link for the Locale module.
  2466. if ($page == 'admin/index') {
  2467. $this->assertNoLinkByHref("admin/people/permissions#module-locale");
  2468. }
  2469. }
  2470. }
  2471. /**
  2472. * Test compact mode.
  2473. */
  2474. function testCompactMode() {
  2475. $this->drupalGet('admin/compact/on');
  2476. $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode turns on.');
  2477. $this->drupalGet('admin/compact/on');
  2478. $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode remains on after a repeat call.');
  2479. $this->drupalGet('');
  2480. $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode persists on new requests.');
  2481. $this->drupalGet('admin/compact/off');
  2482. $this->assertEqual($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'deleted', 'Compact mode turns off.');
  2483. $this->drupalGet('admin/compact/off');
  2484. $this->assertEqual($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'deleted', 'Compact mode remains off after a repeat call.');
  2485. $this->drupalGet('');
  2486. $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode persists on new requests.');
  2487. }
  2488. }
  2489. /**
  2490. * Tests authorize.php and related hooks.
  2491. */
  2492. class SystemAuthorizeCase extends DrupalWebTestCase {
  2493. public static function getInfo() {
  2494. return array(
  2495. 'name' => 'Authorize API',
  2496. 'description' => 'Tests the authorize.php script and related API.',
  2497. 'group' => 'System',
  2498. );
  2499. }
  2500. function setUp() {
  2501. parent::setUp(array('system_test'));
  2502. variable_set('allow_authorize_operations', TRUE);
  2503. // Create an administrator user.
  2504. $this->admin_user = $this->drupalCreateUser(array('administer software updates'));
  2505. $this->drupalLogin($this->admin_user);
  2506. }
  2507. /**
  2508. * Helper function to initialize authorize.php and load it via drupalGet().
  2509. *
  2510. * Initializing authorize.php needs to happen in the child Drupal
  2511. * installation, not the parent. So, we visit a menu callback provided by
  2512. * system_test.module which calls system_authorized_init() to initialize the
  2513. * $_SESSION inside the test site, not the framework site. This callback
  2514. * redirects to authorize.php when it's done initializing.
  2515. *
  2516. * @see system_authorized_init().
  2517. */
  2518. function drupalGetAuthorizePHP($page_title = 'system-test-auth') {
  2519. $this->drupalGet('system-test/authorize-init/' . $page_title);
  2520. }
  2521. /**
  2522. * Tests the FileTransfer hooks
  2523. */
  2524. function testFileTransferHooks() {
  2525. $page_title = $this->randomName(16);
  2526. $this->drupalGetAuthorizePHP($page_title);
  2527. $this->assertTitle(strtr('@title | Drupal', array('@title' => $page_title)), 'authorize.php page title is correct.');
  2528. $this->assertNoText('It appears you have reached this page in error.');
  2529. $this->assertText('To continue, provide your server connection details');
  2530. // Make sure we see the new connection method added by system_test.
  2531. $this->assertRaw('System Test FileTransfer');
  2532. // Make sure the settings form callback works.
  2533. $this->assertText('System Test Username');
  2534. }
  2535. }
  2536. /**
  2537. * Test the handling of requests containing 'index.php'.
  2538. */
  2539. class SystemIndexPhpTest extends DrupalWebTestCase {
  2540. public static function getInfo() {
  2541. return array(
  2542. 'name' => 'Index.php handling',
  2543. 'description' => "Test the handling of requests containing 'index.php'.",
  2544. 'group' => 'System',
  2545. );
  2546. }
  2547. function setUp() {
  2548. parent::setUp();
  2549. }
  2550. /**
  2551. * Test index.php handling.
  2552. */
  2553. function testIndexPhpHandling() {
  2554. $index_php = $GLOBALS['base_url'] . '/index.php';
  2555. $this->drupalGet($index_php, array('external' => TRUE));
  2556. $this->assertResponse(200, 'Make sure index.php returns a valid page.');
  2557. $this->drupalGet($index_php, array('external' => TRUE, 'query' => array('q' => 'user')));
  2558. $this->assertResponse(200, 'Make sure index.php?q=user returns a valid page.');
  2559. $this->drupalGet($index_php .'/user', array('external' => TRUE));
  2560. $this->assertResponse(404, "Make sure index.php/user returns a 'page not found'.");
  2561. }
  2562. }
  2563. /**
  2564. * Test token replacement in strings.
  2565. */
  2566. class TokenScanTest extends DrupalWebTestCase {
  2567. public static function getInfo() {
  2568. return array(
  2569. 'name' => 'Token scanning',
  2570. 'description' => 'Scan token-like patterns in a dummy text to check token scanning.',
  2571. 'group' => 'System',
  2572. );
  2573. }
  2574. /**
  2575. * Scans dummy text, then tests the output.
  2576. */
  2577. function testTokenScan() {
  2578. // Define text with valid and not valid, fake and existing token-like
  2579. // strings.
  2580. $text = 'First a [valid:simple], but dummy token, and a dummy [valid:token with: spaces].';
  2581. $text .= 'Then a [not valid:token].';
  2582. $text .= 'Last an existing token: [node:author:name].';
  2583. $token_wannabes = token_scan($text);
  2584. $this->assertTrue(isset($token_wannabes['valid']['simple']), 'A simple valid token has been matched.');
  2585. $this->assertTrue(isset($token_wannabes['valid']['token with: spaces']), 'A valid token with space characters in the token name has been matched.');
  2586. $this->assertFalse(isset($token_wannabes['not valid']), 'An invalid token with spaces in the token type has not been matched.');
  2587. $this->assertTrue(isset($token_wannabes['node']), 'An existing valid token has been matched.');
  2588. }
  2589. }
  2590. /**
  2591. * Test case for drupal_valid_token().
  2592. */
  2593. class SystemValidTokenTest extends DrupalUnitTestCase {
  2594. /**
  2595. * Flag to indicate whether PHP error reportings should be asserted.
  2596. *
  2597. * @var bool
  2598. */
  2599. protected $assertErrors = TRUE;
  2600. public static function getInfo() {
  2601. return array(
  2602. 'name' => 'Token validation',
  2603. 'description' => 'Test the security token validation.',
  2604. 'group' => 'System',
  2605. );
  2606. }
  2607. /**
  2608. * Tests invalid invocations of drupal_valid_token() that must return FALSE.
  2609. */
  2610. public function testTokenValidation() {
  2611. // The following checks will throw PHP notices, so we disable error
  2612. // assertions.
  2613. $this->assertErrors = FALSE;
  2614. try {
  2615. $this->assertFalse(drupal_valid_token(NULL, new stdClass()), 'Token NULL, value object returns FALSE.');
  2616. }
  2617. // PHP 7.4 compatibility: the stdClass string conversion throws an exception
  2618. // which is also an acceptable outcome of this test.
  2619. catch (Error $e) {
  2620. $this->pass('Token NULL, value object throws error exception which is ok.');
  2621. }
  2622. $this->assertFalse(drupal_valid_token(0, array()), 'Token 0, value array returns FALSE.');
  2623. $this->assertFalse(drupal_valid_token('', array()), "Token '', value array returns FALSE.");
  2624. $this->assertFalse('' === drupal_get_token(array()), 'Token generation does not return an empty string on invalid parameters.');
  2625. $this->assertErrors = TRUE;
  2626. $this->assertFalse(drupal_valid_token(TRUE, 'foo'), 'Token TRUE, value foo returns FALSE.');
  2627. $this->assertFalse(drupal_valid_token(0, 'foo'), 'Token 0, value foo returns FALSE.');
  2628. }
  2629. /**
  2630. * Overrides DrupalTestCase::errorHandler().
  2631. */
  2632. public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
  2633. if ($this->assertErrors) {
  2634. return parent::errorHandler($severity, $message, $file, $line);
  2635. }
  2636. return TRUE;
  2637. }
  2638. }
  2639. /**
  2640. * Tests drupal_set_message() and related functions.
  2641. */
  2642. class DrupalSetMessageTest extends DrupalWebTestCase {
  2643. public static function getInfo() {
  2644. return array(
  2645. 'name' => 'Messages',
  2646. 'description' => 'Tests that messages can be displayed using drupal_set_message().',
  2647. 'group' => 'System',
  2648. );
  2649. }
  2650. function setUp() {
  2651. parent::setUp('system_test');
  2652. }
  2653. /**
  2654. * Tests setting messages and removing one before it is displayed.
  2655. */
  2656. function testSetRemoveMessages() {
  2657. // The page at system-test/drupal-set-message sets two messages and then
  2658. // removes the first before it is displayed.
  2659. $this->drupalGet('system-test/drupal-set-message');
  2660. $this->assertNoText('First message (removed).');
  2661. $this->assertText('Second message (not removed).');
  2662. }
  2663. }
  2664. /**
  2665. * Tests confirm form destinations.
  2666. */
  2667. class ConfirmFormTest extends DrupalWebTestCase {
  2668. protected $admin_user;
  2669. public static function getInfo() {
  2670. return array(
  2671. 'name' => 'Confirm form',
  2672. 'description' => 'Tests that the confirm form does not use external destinations.',
  2673. 'group' => 'System',
  2674. );
  2675. }
  2676. function setUp() {
  2677. parent::setUp();
  2678. $this->admin_user = $this->drupalCreateUser(array('administer users'));
  2679. $this->drupalLogin($this->admin_user);
  2680. }
  2681. /**
  2682. * Tests that the confirm form does not use external destinations.
  2683. */
  2684. function testConfirmForm() {
  2685. $this->drupalGet('user/1/cancel');
  2686. $this->assertCancelLinkUrl(url('user/1'));
  2687. $this->drupalGet('user/1/cancel', array('query' => array('destination' => 'node')));
  2688. $this->assertCancelLinkUrl(url('node'));
  2689. $this->drupalGet('user/1/cancel', array('query' => array('destination' => 'http://example.com')));
  2690. $this->assertCancelLinkUrl(url('user/1'));
  2691. }
  2692. /**
  2693. * Asserts that a cancel link is present pointing to the provided URL.
  2694. */
  2695. function assertCancelLinkUrl($url, $message = '', $group = 'Other') {
  2696. $links = $this->xpath('//a[normalize-space(text())=:label and @href=:url]', array(':label' => t('Cancel'), ':url' => $url));
  2697. $message = ($message ? $message : format_string('Cancel link with url %url found.', array('%url' => $url)));
  2698. return $this->assertTrue(isset($links[0]), $message, $group);
  2699. }
  2700. }