system.test

Tests for system.module.

File

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