system.test 109 KB

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