system.test

Tests for system.module.

Classes

Namesort descending Description
AccessDeniedTestCase Tests custom access denied functionality.
AdminMetaTagTestCase
ConfirmFormTest Tests confirm form destinations.
CronQueueTestCase Test execution of the cron queue.
CronRunTestCase
DateTimeFunctionalTest Tests generic date and time handling capabilities of Drupal.
DrupalSetMessageTest Tests drupal_set_message() and related functions.
EnableDisableTestCase Test module enabling/disabling functionality.
FloodFunctionalTest Functional tests for the flood control mechanism.
FrontPageTestCase Test front page functionality and administration.
HookRequirementsTestCase Tests failure of hook_requirements('install').
InfoFileParserTestCase
IPAddressBlockingTestCase
ModuleDependencyTestCase Test module dependency functionality.
ModuleRequiredTestCase Test required modules functionality.
ModuleTestCase Helper class for module test cases.
ModuleVersionTestCase Test module dependency on specific versions.
PageNotFoundTestCase
PageTitleFiltering
QueueTestCase Test the basic queue functionality.
RetrieveFileTestCase Test HTTP file downloading capability.
ShutdownFunctionsTest Functional tests shutdown functions.
SiteMaintenanceTestCase Tests site maintenance functionality.
SystemAdminTestCase Tests administrative overview pages.
SystemAuthorizeCase Tests authorize.php and related hooks.
SystemBlockTestCase
SystemIndexPhpTest Test the handling of requests containing 'index.php'.
SystemInfoAlterTestCase Tests the effectiveness of hook_system_info_alter().
SystemMainContentFallback Test main content rendering fallback provided by system module.
SystemThemeFunctionalTest Tests for the theme interface functionality.
SystemValidTokenTest Test case for drupal_valid_token().
TokenReplaceTestCase Test token replacement in strings.
TokenScanTest Test token replacement in strings.
UpdateScriptFunctionalTest Tests for the update system functionality.

File

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