5 * Tests for system.module.
9 * Helper class for module test cases.
11 class ModuleTestCase
extends DrupalWebTestCase
{
12 protected
$admin_user;
15 parent
::setUp('system_test');
17 $this->admin_user
= $this->drupalCreateUser(array('access administration pages', 'administer modules'));
18 $this->drupalLogin($this->admin_user
);
22 * Assert there are tables that begin with the specified base table name.
25 * Beginning of table name to look for.
27 * (optional) Whether or not to assert that there are tables that match the
28 * specified base table. Defaults to TRUE.
30 function assertTableCount($base_table, $count = TRUE
) {
31 $tables = db_find_tables(Database
::getConnection()->prefixTables('{' .
$base_table .
'}') .
'%');
34 return $this->assertTrue($tables, t('Tables matching "@base_table" found.', array('@base_table' => $base_table)));
36 return $this->assertFalse($tables, t('Tables matching "@base_table" not found.', array('@base_table' => $base_table)));
40 * Assert that all tables defined in a module's hook_schema() exist.
43 * The name of the module.
45 function assertModuleTablesExist($module) {
46 $tables = array_keys(drupal_get_schema_unprocessed($module));
48 foreach ($tables as
$table) {
49 if (!db_table_exists($table)) {
50 $tables_exist = FALSE
;
53 return $this->assertTrue($tables_exist, t('All database tables defined by the @module module exist.', array('@module' => $module)));
57 * Assert that none of the tables defined in a module's hook_schema() exist.
60 * The name of the module.
62 function assertModuleTablesDoNotExist($module) {
63 $tables = array_keys(drupal_get_schema_unprocessed($module));
64 $tables_exist = FALSE
;
65 foreach ($tables as
$table) {
66 if (db_table_exists($table)) {
70 return $this->assertFalse($tables_exist, t('None of the database tables defined by the @module module exist.', array('@module' => $module)));
74 * Assert the list of modules are enabled or disabled.
77 * Module list to check.
79 * Expected module state.
81 function assertModules(array $modules, $enabled) {
83 foreach ($modules as
$module) {
85 $message = 'Module "@module" is enabled.';
88 $message = 'Module "@module" is not enabled.';
90 $this->assertEqual(module_exists($module), $enabled, t($message, array('@module' => $module)));
95 * Verify a log entry was entered for a module's status change.
96 * Called in the same way of the expected original watchdog() execution.
99 * The category to which this message belongs.
101 * The message to store in the log. Keep $message translatable
102 * by not concatenating dynamic values into it! Variables in the
103 * message should be added by using placeholder strings alongside
104 * the variables argument to declare the value of the placeholders.
105 * See t() for documentation on how $message and $variables interact.
107 * Array of variables to replace in the message on display or
108 * NULL if message is already translated or not possible to
111 * The severity of the message, as per RFC 3164.
113 * A link to associate with the message.
115 function assertLogMessage($type, $message, $variables = array(), $severity = WATCHDOG_NOTICE
, $link = '') {
116 $count = db_select('watchdog', 'w')
117 ->condition('type', $type)
118 ->condition('message', $message)
119 ->condition('variables', serialize($variables))
120 ->condition('severity', $severity)
121 ->condition('link', $link)
125 $this->assertTrue($count > 0, t('watchdog table contains @count rows for @message', array('@count' => $count, '@message' => $message)));
130 * Test module enabling/disabling functionality.
132 class EnableDisableTestCase
extends ModuleTestCase
{
133 protected
$profile = 'testing';
135 public static
function getInfo() {
137 'name' => 'Enable/disable modules',
138 'description' => 'Enable/disable core module and confirm table creation/deletion.',
144 * Test that all core modules can be enabled, disabled and uninstalled.
146 function testEnableDisable() {
147 // Try to enable, disable and uninstall all core modules, unless they are
148 // hidden or required.
149 $modules = system_rebuild_module_data();
150 foreach ($modules as
$name => $module) {
151 if ($module->info
['package'] != 'Core' || !empty($module->info
['hidden']) || !empty($module->info
['required'])) {
152 unset($modules[$name]);
155 $this->assertTrue(count($modules), t('Found @count core modules that we can try to enable in this test.', array('@count' => count($modules))));
157 // Enable the dblog module first, since we will be asserting the presence
158 // of log messages throughout the test.
159 if (isset($modules['dblog'])) {
160 $modules = array('dblog' => $modules['dblog']) + $modules;
163 // Set a variable so that the hook implementations in system_test.module
164 // will display messages via drupal_set_message().
165 variable_set('test_verbose_module_hooks', TRUE
);
167 // Throughout this test, some modules may be automatically enabled (due to
168 // dependencies). We'll keep track of them in an array, so we can handle
170 $automatically_enabled = array();
172 // Go through each module in the list and try to enable it (unless it was
173 // already enabled automatically due to a dependency).
174 foreach ($modules as
$name => $module) {
175 if (empty($automatically_enabled[$name])) {
176 // Start a list of modules that we expect to be enabled this time.
177 $modules_to_enable = array($name);
179 // Find out if the module has any dependencies that aren't enabled yet;
180 // if so, add them to the list of modules we expect to be automatically
182 foreach (array_keys($module->requires
) as
$dependency) {
183 if (isset($modules[$dependency]) && empty($automatically_enabled[$dependency])) {
184 $modules_to_enable[] = $dependency;
185 $automatically_enabled[$dependency] = TRUE
;
189 // Check that each module is not yet enabled and does not have any
190 // database tables yet.
191 foreach ($modules_to_enable as
$module_to_enable) {
192 $this->assertModules(array($module_to_enable), FALSE
);
193 $this->assertModuleTablesDoNotExist($module_to_enable);
196 // Install and enable the module.
198 $edit['modules[Core][' .
$name .
'][enable]'] = $name;
199 $this->drupalPost('admin/modules', $edit, t('Save configuration'));
200 // Handle the case where modules were installed along with this one and
201 // where we therefore hit a confirmation screen.
202 if (count($modules_to_enable) > 1) {
203 $this->drupalPost(NULL
, array(), t('Continue'));
205 $this->assertText(t('The configuration options have been saved.'), t('Modules status has been updated.'));
207 // Check that hook_modules_installed() and hook_modules_enabled() were
208 // invoked with the expected list of modules, that each module's
209 // database tables now exist, and that appropriate messages appear in
211 foreach ($modules_to_enable as
$module_to_enable) {
212 $this->assertText(t('hook_modules_installed fired for @module', array('@module' => $module_to_enable)));
213 $this->assertText(t('hook_modules_enabled fired for @module', array('@module' => $module_to_enable)));
214 $this->assertModules(array($module_to_enable), TRUE
);
215 $this->assertModuleTablesExist($module_to_enable);
216 $this->assertLogMessage('system', "%module module installed.", array('%module' => $module_to_enable), WATCHDOG_INFO
);
217 $this->assertLogMessage('system', "%module module enabled.", array('%module' => $module_to_enable), WATCHDOG_INFO
);
220 // Disable and uninstall the original module, and check appropriate
221 // hooks, tables, and log messages. (Later, we'll go back and do the
222 // same thing for modules that were enabled automatically.) Skip this
223 // for the dblog module, because that is needed for the test; we'll go
224 // back and do that one at the end also.
225 if ($name != 'dblog') {
226 $this->assertSuccessfulDisableAndUninstall($name);
231 // Go through all modules that were automatically enabled, and try to
232 // disable and uninstall them one by one.
233 while (!empty($automatically_enabled)) {
234 $initial_count = count($automatically_enabled);
235 foreach (array_keys($automatically_enabled) as
$name) {
236 // If the module can't be disabled due to dependencies, skip it and try
237 // again the next time. Otherwise, try to disable it.
238 $this->drupalGet('admin/modules');
239 $disabled_checkbox = $this->xpath('//input[@type="checkbox" and @disabled="disabled" and @name="modules[Core][' .
$name .
'][enable]"]');
240 if (empty($disabled_checkbox) && $name != 'dblog') {
241 unset($automatically_enabled[$name]);
242 $this->assertSuccessfulDisableAndUninstall($name);
245 $final_count = count($automatically_enabled);
246 // If all checkboxes were disabled, something is really wrong with the
247 // test. Throw a failure and avoid an infinite loop.
248 if ($initial_count == $final_count) {
249 $this->fail(t('Remaining modules could not be disabled.'));
254 // Disable and uninstall the dblog module last, since we needed it for
255 // assertions in all the above tests.
256 if (isset($modules['dblog'])) {
257 $this->assertSuccessfulDisableAndUninstall('dblog');
260 // Now that all modules have been tested, go back and try to enable them
261 // all again at once. This tests two things:
262 // - That each module can be successfully enabled again after being
264 // - That enabling more than one module at the same time does not lead to
267 foreach (array_keys($modules) as
$name) {
268 $edit['modules[Core][' .
$name .
'][enable]'] = $name;
270 $this->drupalPost('admin/modules', $edit, t('Save configuration'));
271 $this->assertText(t('The configuration options have been saved.'), t('Modules status has been updated.'));
275 * Ensures entity info cache is updated after changes.
277 function testEntityInfoChanges() {
278 module_enable(array('entity_cache_test'));
279 $entity_info = entity_get_info();
280 $this->assertTrue(isset($entity_info['entity_cache_test']), 'Test entity type found.');
282 // Change the label of the test entity type and make sure changes appear
283 // after flushing caches.
284 variable_set('entity_cache_test_label', 'New label.');
285 drupal_flush_all_caches();
286 $info = entity_get_info('entity_cache_test');
287 $this->assertEqual($info['label'], 'New label.', 'New label appears in entity info.');
289 // Disable the providing module and make sure the entity type is gone.
290 module_disable(array('entity_cache_test', 'entity_cache_test_dependency'));
291 $entity_info = entity_get_info();
292 $this->assertFalse(isset($entity_info['entity_cache_test']), 'Entity type of the providing module is gone.');
296 * Tests entity info cache after enabling a module with a dependency on an entity providing module.
298 * @see entity_cache_test_watchdog()
300 function testEntityInfoCacheWatchdog() {
301 module_enable(array('entity_cache_test'));
302 $info = variable_get('entity_cache_test');
303 $this->assertEqual($info['label'], 'Entity Cache Test', 'Entity info label is correct.');
304 $this->assertEqual($info['controller class'], 'DrupalDefaultEntityController', 'Entity controller class info is correct.');
308 * Disables and uninstalls a module and asserts that it was done correctly.
311 * The name of the module to disable and uninstall.
313 function assertSuccessfulDisableAndUninstall($module) {
314 // Disable the module.
316 $edit['modules[Core][' .
$module .
'][enable]'] = FALSE
;
317 $this->drupalPost('admin/modules', $edit, t('Save configuration'));
318 $this->assertText(t('The configuration options have been saved.'), t('Modules status has been updated.'));
319 $this->assertModules(array($module), FALSE
);
321 // Check that the appropriate hook was fired and the appropriate log
323 $this->assertText(t('hook_modules_disabled fired for @module', array('@module' => $module)));
324 $this->assertLogMessage('system', "%module module disabled.", array('%module' => $module), WATCHDOG_INFO
);
326 // Check that the module's database tables still exist.
327 $this->assertModuleTablesExist($module);
329 // Uninstall the module.
331 $edit['uninstall[' .
$module .
']'] = $module;
332 $this->drupalPost('admin/modules/uninstall', $edit, t('Uninstall'));
333 $this->drupalPost(NULL
, NULL
, t('Uninstall'));
334 $this->assertText(t('The selected modules have been uninstalled.'), t('Modules status has been updated.'));
335 $this->assertModules(array($module), FALSE
);
337 // Check that the appropriate hook was fired and the appropriate log
338 // message appears. (But don't check for the log message if the dblog
339 // module was just uninstalled, since the {watchdog} table won't be there
341 $this->assertText(t('hook_modules_uninstalled fired for @module', array('@module' => $module)));
342 if ($module != 'dblog') {
343 $this->assertLogMessage('system', "%module module uninstalled.", array('%module' => $module), WATCHDOG_INFO
);
346 // Check that the module's database tables no longer exist.
347 $this->assertModuleTablesDoNotExist($module);
352 * Tests failure of hook_requirements('install').
354 class HookRequirementsTestCase
extends ModuleTestCase
{
355 public static
function getInfo() {
357 'name' => 'Requirements hook failure',
358 'description' => "Attempts enabling a module that fails hook_requirements('install').",
364 * Assert that a module cannot be installed if it fails hook_requirements().
366 function testHookRequirementsFailure() {
367 $this->assertModules(array('requirements1_test'), FALSE
);
369 // Attempt to install the requirements1_test module.
371 $edit['modules[Testing][requirements1_test][enable]'] = 'requirements1_test';
372 $this->drupalPost('admin/modules', $edit, t('Save configuration'));
374 // Makes sure the module was NOT installed.
375 $this->assertText(t('Requirements 1 Test failed requirements'), t('Modules status has been updated.'));
376 $this->assertModules(array('requirements1_test'), FALSE
);
381 * Test module dependency functionality.
383 class ModuleDependencyTestCase
extends ModuleTestCase
{
384 public static
function getInfo() {
386 'name' => 'Module dependencies',
387 'description' => 'Enable module without dependency enabled.',
393 * Attempt to enable translation module without locale enabled.
395 function testEnableWithoutDependency() {
396 // Attempt to enable content translation without locale enabled.
398 $edit['modules[Core][translation][enable]'] = 'translation';
399 $this->drupalPost('admin/modules', $edit, t('Save configuration'));
400 $this->assertText(t('Some required modules must be enabled'), t('Dependency required.'));
402 $this->assertModules(array('translation', 'locale'), FALSE
);
404 // Assert that the locale tables weren't enabled.
405 $this->assertTableCount('languages', FALSE
);
406 $this->assertTableCount('locale', FALSE
);
408 $this->drupalPost(NULL
, NULL
, t('Continue'));
409 $this->assertText(t('The configuration options have been saved.'), t('Modules status has been updated.'));
411 $this->assertModules(array('translation', 'locale'), TRUE
);
413 // Assert that the locale tables were enabled.
414 $this->assertTableCount('languages', TRUE
);
415 $this->assertTableCount('locale', TRUE
);
419 * Attempt to enable a module with a missing dependency.
421 function testMissingModules() {
422 // Test that the system_dependencies_test module is marked
423 // as missing a dependency.
424 $this->drupalGet('admin/modules');
425 $this->assertRaw(t('@module (<span class="admin-missing">missing</span>)', array('@module' => drupal_ucfirst('_missing_dependency'))), t('A module with missing dependencies is marked as such.'));
426 $checkbox = $this->xpath('//input[@type="checkbox" and @disabled="disabled" and @name="modules[Testing][system_dependencies_test][enable]"]');
427 $this->assert(count($checkbox) == 1, t('Checkbox for the module is disabled.'));
429 // Force enable the system_dependencies_test module.
430 module_enable(array('system_dependencies_test'), FALSE
);
432 // Verify that the module is forced to be disabled when submitting
434 $this->drupalPost('admin/modules', array(), t('Save configuration'));
435 $this->assertText(t('The @module module is missing, so the following module will be disabled: @depends.', array('@module' => '_missing_dependency', '@depends' => 'system_dependencies_test')), t('The module missing dependencies will be disabled.'));
438 $this->drupalPost(NULL
, NULL
, t('Continue'));
440 // Verify that the module has been disabled.
441 $this->assertModules(array('system_dependencies_test'), FALSE
);
445 * Tests enabling a module that depends on an incompatible version of a module.
447 function testIncompatibleModuleVersionDependency() {
448 // Test that the system_incompatible_module_version_dependencies_test is
449 // marked as having an incompatible dependency.
450 $this->drupalGet('admin/modules');
451 $this->assertRaw(t('@module (<span class="admin-missing">incompatible with</span> version @version)', array(
452 '@module' => 'System incompatible module version test (>2.0)',
454 )), 'A module that depends on an incompatible version of a module is marked as such.');
455 $checkbox = $this->xpath('//input[@type="checkbox" and @disabled="disabled" and @name="modules[Testing][system_incompatible_module_version_dependencies_test][enable]"]');
456 $this->assert(count($checkbox) == 1, t('Checkbox for the module is disabled.'));
460 * Tests enabling a module that depends on a module with an incompatible core version.
462 function testIncompatibleCoreVersionDependency() {
463 // Test that the system_incompatible_core_version_dependencies_test is
464 // marked as having an incompatible dependency.
465 $this->drupalGet('admin/modules');
466 $this->assertRaw(t('@module (<span class="admin-missing">incompatible with</span> this version of Drupal core)', array(
467 '@module' => 'System incompatible core version test',
468 )), 'A module that depends on a module with an incompatible core version is marked as such.');
469 $checkbox = $this->xpath('//input[@type="checkbox" and @disabled="disabled" and @name="modules[Testing][system_incompatible_core_version_dependencies_test][enable]"]');
470 $this->assert(count($checkbox) == 1, t('Checkbox for the module is disabled.'));
474 * Tests enabling a module that depends on a module which fails hook_requirements().
476 function testEnableRequirementsFailureDependency() {
477 $this->assertModules(array('requirements1_test'), FALSE
);
478 $this->assertModules(array('requirements2_test'), FALSE
);
480 // Attempt to install both modules at the same time.
482 $edit['modules[Testing][requirements1_test][enable]'] = 'requirements1_test';
483 $edit['modules[Testing][requirements2_test][enable]'] = 'requirements2_test';
484 $this->drupalPost('admin/modules', $edit, t('Save configuration'));
486 // Makes sure the modules were NOT installed.
487 $this->assertText(t('Requirements 1 Test failed requirements'), t('Modules status has been updated.'));
488 $this->assertModules(array('requirements1_test'), FALSE
);
489 $this->assertModules(array('requirements2_test'), FALSE
);
491 // Makes sure that already enabled modules the failing modules depend on
492 // were not disabled.
493 $this->assertModules(array('comment'), TRUE
);
498 * Tests that module dependencies are enabled in the correct order via the
499 * UI. Dependencies should be enabled before their dependents.
501 function testModuleEnableOrder() {
502 module_enable(array('module_test'), FALSE
);
504 $this->assertModules(array('module_test'), TRUE
);
505 variable_set('dependency_test', 'dependency');
506 // module_test creates a dependency chain: forum depends on poll, which
507 // depends on php. The correct enable order is, php, poll, forum.
508 $expected_order = array('php', 'poll', 'forum');
510 // Enable the modules through the UI, verifying that the dependency chain
513 $edit['modules[Core][forum][enable]'] = 'forum';
514 $this->drupalPost('admin/modules', $edit, t('Save configuration'));
515 $this->assertModules(array('forum'), FALSE
);
516 $this->assertText(t('You must enable the Poll, PHP filter modules to install Forum.'), t('Dependency chain created.'));
517 $edit['modules[Core][poll][enable]'] = 'poll';
518 $edit['modules[Core][php][enable]'] = 'php';
519 $this->drupalPost('admin/modules', $edit, t('Save configuration'));
520 $this->assertModules(array('forum', 'poll', 'php'), TRUE
);
522 // Check the actual order which is saved by module_test_modules_enabled().
523 $this->assertIdentical(variable_get('test_module_enable_order', FALSE
), $expected_order, t('Modules enabled in the correct order.'));
527 * Tests attempting to uninstall a module that has installed dependents.
529 function testUninstallDependents() {
530 // Enable the forum module.
531 $edit = array('modules[Core][forum][enable]' => 'forum');
532 $this->drupalPost('admin/modules', $edit, t('Save configuration'));
533 $this->assertModules(array('forum'), TRUE
);
535 // Disable forum and comment. Both should now be installed but disabled.
536 $edit = array('modules[Core][forum][enable]' => FALSE
);
537 $this->drupalPost('admin/modules', $edit, t('Save configuration'));
538 $this->assertModules(array('forum'), FALSE
);
539 $edit = array('modules[Core][comment][enable]' => FALSE
);
540 $this->drupalPost('admin/modules', $edit, t('Save configuration'));
541 $this->assertModules(array('comment'), FALSE
);
543 // Check that the taxonomy module cannot be uninstalled.
544 $this->drupalGet('admin/modules/uninstall');
545 $checkbox = $this->xpath('//input[@type="checkbox" and @disabled="disabled" and @name="uninstall[comment]"]');
546 $this->assert(count($checkbox) == 1, t('Checkbox for uninstalling the comment module is disabled.'));
548 // Uninstall the forum module, and check that taxonomy now can also be
550 $edit = array('uninstall[forum]' => 'forum');
551 $this->drupalPost('admin/modules/uninstall', $edit, t('Uninstall'));
552 $this->drupalPost(NULL
, NULL
, t('Uninstall'));
553 $this->assertText(t('The selected modules have been uninstalled.'), t('Modules status has been updated.'));
554 $edit = array('uninstall[comment]' => 'comment');
555 $this->drupalPost('admin/modules/uninstall', $edit, t('Uninstall'));
556 $this->drupalPost(NULL
, NULL
, t('Uninstall'));
557 $this->assertText(t('The selected modules have been uninstalled.'), t('Modules status has been updated.'));
562 * Test module dependency on specific versions.
564 class ModuleVersionTestCase
extends ModuleTestCase
{
565 public static
function getInfo() {
567 'name' => 'Module versions',
568 'description' => 'Check module version dependencies.',
574 parent
::setUp('module_test');
578 * Test version dependencies.
580 function testModuleVersions() {
581 $dependencies = array(
582 // Alternating between being compatible and incompatible with 7.x-2.4-beta3.
583 // The first is always a compatible.
585 // Branch incompatibility.
587 // Branch compatibility.
589 // Another branch incompatibility.
590 'common_test (>2.x)',
591 // Another branch compatibility.
592 'common_test (<=2.x)',
593 // Another branch incompatibility.
594 'common_test (<2.x)',
595 // Another branch compatibility.
596 'common_test (>=2.x)',
597 // Nonsense, misses a dash. Incompatible with everything.
598 'common_test (=7.x2.x, >=2.4)',
599 // Core version is optional. Compatible.
600 'common_test (=7.x-2.x, >=2.4-alpha2)',
601 // Test !=, explicitly incompatible.
602 'common_test (=2.x, !=2.4-beta3)',
603 // Three operations. Compatible.
604 'common_test (=2.x, !=2.3, <2.5)',
605 // Testing extra version. Incompatible.
606 'common_test (<=2.4-beta2)',
607 // Testing extra version. Compatible.
608 'common_test (>2.4-beta2)',
609 // Testing extra version. Incompatible.
610 'common_test (>2.4-rc0)',
612 variable_set('dependencies', $dependencies);
613 $n = count($dependencies);
614 for ($i = 0; $i < $n; $i++) {
615 $this->drupalGet('admin/modules');
616 $checkbox = $this->xpath('//input[@id="edit-modules-testing-module-test-enable"]');
617 $this->assertEqual(!empty($checkbox[0]['disabled']), $i %
2, $dependencies[$i]);
623 * Test required modules functionality.
625 class ModuleRequiredTestCase
extends ModuleTestCase
{
626 public static
function getInfo() {
628 'name' => 'Required modules',
629 'description' => 'Attempt disabling of required modules.',
635 * Assert that core required modules cannot be disabled.
637 function testDisableRequired() {
638 $module_info = system_get_info('module');
639 $this->drupalGet('admin/modules');
640 foreach ($module_info as
$module => $info) {
641 // Check to make sure the checkbox for each required module is disabled
642 // and checked (or absent from the page if the module is also hidden).
643 if (!empty($info['required'])) {
644 $field_name = "modules[{$info['package']}][$module][enable]";
645 if (empty($info['hidden'])) {
646 $this->assertFieldByXPath("//input[@name='$field_name' and @disabled='disabled' and @checked='checked']", '', t('Field @name was disabled and checked.', array('@name' => $field_name)));
649 $this->assertNoFieldByName($field_name);
656 class IPAddressBlockingTestCase
extends DrupalWebTestCase
{
657 protected
$blocking_user;
660 * Implement getInfo().
662 public static
function getInfo() {
664 'name' => 'IP address blocking',
665 'description' => 'Test IP address blocking.',
677 $this->blocking_user
= $this->drupalCreateUser(array('block IP addresses'));
678 $this->drupalLogin($this->blocking_user
);
682 * Test a variety of user input to confirm correct validation and saving of data.
684 function testIPAddressValidation() {
685 $this->drupalGet('admin/config/people/ip-blocking');
687 // Block a valid IP address.
689 $edit['ip'] = '192.168.1.1';
690 $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
691 $ip = db_query("SELECT iid from {blocked_ips} WHERE ip = :ip", array(':ip' => $edit['ip']))->fetchField();
692 $this->assertTrue($ip, t('IP address found in database.'));
693 $this->assertRaw(t('The IP address %ip has been blocked.', array('%ip' => $edit['ip'])), t('IP address was blocked.'));
695 // Try to block an IP address that's already blocked.
697 $edit['ip'] = '192.168.1.1';
698 $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
699 $this->assertText(t('This IP address is already blocked.'));
701 // Try to block a reserved IP address.
703 $edit['ip'] = '255.255.255.255';
704 $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
705 $this->assertText(t('Enter a valid IP address.'));
707 // Try to block a reserved IP address.
709 $edit['ip'] = 'test.example.com';
710 $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
711 $this->assertText(t('Enter a valid IP address.'));
713 // Submit an empty form.
716 $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
717 $this->assertText(t('Enter a valid IP address.'));
719 // Pass an IP address as a URL parameter and submit it.
720 $submit_ip = '1.2.3.4';
721 $this->drupalPost('admin/config/people/ip-blocking/' .
$submit_ip, NULL
, t('Add'));
722 $ip = db_query("SELECT iid from {blocked_ips} WHERE ip = :ip", array(':ip' => $submit_ip))->fetchField();
723 $this->assertTrue($ip, t('IP address found in database'));
724 $this->assertRaw(t('The IP address %ip has been blocked.', array('%ip' => $submit_ip)), t('IP address was blocked.'));
726 // Submit your own IP address. This fails, although it works when testing manually.
727 // TODO: on some systems this test fails due to a bug or inconsistency in cURL.
729 // $edit['ip'] = ip_address();
730 // $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Save'));
731 // $this->assertText(t('You may not block your own IP address.'));
735 class CronRunTestCase
extends DrupalWebTestCase
{
737 * Implement getInfo().
739 public static
function getInfo() {
741 'name' => 'Cron run',
742 'description' => 'Test cron run.',
748 parent
::setUp(array('common_test', 'common_test_cron_helper'));
754 function testCronRun() {
757 // Run cron anonymously without any cron key.
758 $this->drupalGet($base_url .
'/cron.php', array('external' => TRUE
));
759 $this->assertResponse(403);
761 // Run cron anonymously with a random cron key.
762 $key = $this->randomName(16);
763 $this->drupalGet($base_url .
'/cron.php', array('external' => TRUE
, 'query' => array('cron_key' => $key)));
764 $this->assertResponse(403);
766 // Run cron anonymously with the valid cron key.
767 $key = variable_get('cron_key', 'drupal');
768 $this->drupalGet($base_url .
'/cron.php', array('external' => TRUE
, 'query' => array('cron_key' => $key)));
769 $this->assertResponse(200);
773 * Ensure that the automatic cron run feature is working.
775 * In these tests we do not use REQUEST_TIME to track start time, because we
776 * need the exact time when cron is triggered.
778 function testAutomaticCron() {
779 // Ensure cron does not run when the cron threshold is enabled and was
782 $cron_safe_threshold = 100;
783 variable_set('cron_last', $cron_last);
784 variable_set('cron_safe_threshold', $cron_safe_threshold);
785 $this->drupalGet('');
786 $this->assertTrue($cron_last == variable_get('cron_last', NULL
), t('Cron does not run when the cron threshold is not passed.'));
788 // Test if cron runs when the cron threshold was passed.
789 $cron_last = time() - 200;
790 variable_set('cron_last', $cron_last);
791 $this->drupalGet('');
793 $this->assertTrue($cron_last < variable_get('cron_last', NULL
), t('Cron runs when the cron threshold is passed.'));
795 // Disable the cron threshold through the interface.
796 $admin_user = $this->drupalCreateUser(array('administer site configuration'));
797 $this->drupalLogin($admin_user);
798 $this->drupalPost('admin/config/system/cron', array('cron_safe_threshold' => 0), t('Save configuration'));
799 $this->assertText(t('The configuration options have been saved.'));
800 $this->drupalLogout();
802 // Test if cron does not run when the cron threshold is disabled.
803 $cron_last = time() - 200;
804 variable_set('cron_last', $cron_last);
805 $this->drupalGet('');
806 $this->assertTrue($cron_last == variable_get('cron_last', NULL
), t('Cron does not run when the cron threshold is disabled.'));
810 * Ensure that temporary files are removed.
812 * Create files for all the possible combinations of age and status. We are
813 * using UPDATE statements rather than file_save() because it would set the
816 function testTempFileCleanup() {
817 // Temporary file that is older than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
818 $temp_old = file_save_data('');
819 db_update('file_managed')
824 ->condition('fid', $temp_old->fid
)
826 $this->assertTrue(file_exists($temp_old->uri
), t('Old temp file was created correctly.'));
828 // Temporary file that is less than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
829 $temp_new = file_save_data('');
830 db_update('file_managed')
831 ->fields(array('status' => 0))
832 ->condition('fid', $temp_new->fid
)
834 $this->assertTrue(file_exists($temp_new->uri
), t('New temp file was created correctly.'));
836 // Permanent file that is older than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
837 $perm_old = file_save_data('');
838 db_update('file_managed')
839 ->fields(array('timestamp' => 1))
840 ->condition('fid', $temp_old->fid
)
842 $this->assertTrue(file_exists($perm_old->uri
), t('Old permanent file was created correctly.'));
844 // Permanent file that is newer than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
845 $perm_new = file_save_data('');
846 $this->assertTrue(file_exists($perm_new->uri
), t('New permanent file was created correctly.'));
848 // Run cron and then ensure that only the old, temp file was deleted.
850 $this->assertFalse(file_exists($temp_old->uri
), t('Old temp file was correctly removed.'));
851 $this->assertTrue(file_exists($temp_new->uri
), t('New temp file was correctly ignored.'));
852 $this->assertTrue(file_exists($perm_old->uri
), t('Old permanent file was correctly ignored.'));
853 $this->assertTrue(file_exists($perm_new->uri
), t('New permanent file was correctly ignored.'));
857 * Make sure exceptions thrown on hook_cron() don't affect other modules.
859 function testCronExceptions() {
860 variable_del('common_test_cron');
861 // The common_test module throws an exception. If it isn't caught, the tests
862 // won't finish successfully.
863 // The common_test_cron_helper module sets the 'common_test_cron' variable.
865 $result = variable_get('common_test_cron');
866 $this->assertEqual($result, 'success', t('Cron correctly handles exceptions thrown during hook_cron() invocations.'));
870 class AdminMetaTagTestCase
extends DrupalWebTestCase
{
872 * Implement getInfo().
874 public static
function getInfo() {
876 'name' => 'Fingerprinting meta tag',
877 'description' => 'Confirm that the fingerprinting meta tag appears as expected.',
883 * Verify that the meta tag HTML is generated correctly.
885 public
function testMetaTag() {
886 list($version, ) = explode('.', VERSION
);
887 $string = '<meta name="Generator" content="Drupal ' .
$version .
' (http://drupal.org)" />';
888 $this->drupalGet('node');
889 $this->assertRaw($string, t('Fingerprinting meta tag generated correctly.'), t('System'));
894 * Tests custom access denied functionality.
896 class AccessDeniedTestCase
extends DrupalWebTestCase
{
897 protected
$admin_user;
899 public static
function getInfo() {
901 'name' => '403 functionality',
902 'description' => 'Tests page access denied functionality, including custom 403 pages.',
910 // Create an administrative user.
911 $this->admin_user
= $this->drupalCreateUser(array('access administration pages', 'administer site configuration', 'administer blocks'));
914 function testAccessDenied() {
915 $this->drupalGet('admin');
916 $this->assertText(t('Access denied'), t('Found the default 403 page'));
917 $this->assertResponse(403);
919 $this->drupalLogin($this->admin_user
);
921 'title' => $this->randomName(10),
922 'body' => array(LANGUAGE_NONE
=> array(array('value' => $this->randomName(100)))),
924 $node = $this->drupalCreateNode($edit);
926 // Use a custom 403 page.
927 $this->drupalPost('admin/config/system/site-information', array('site_403' => 'node/' .
$node->nid
), t('Save configuration'));
929 $this->drupalLogout();
930 $this->drupalGet('admin');
931 $this->assertText($node->title
, t('Found the custom 403 page'));
933 // Logout and check that the user login block is shown on custom 403 pages.
934 $this->drupalLogout();
936 $this->drupalGet('admin');
937 $this->assertText($node->title
, t('Found the custom 403 page'));
938 $this->assertText(t('User login'), t('Blocks are shown on the custom 403 page'));
940 // Log back in and remove the custom 403 page.
941 $this->drupalLogin($this->admin_user
);
942 $this->drupalPost('admin/config/system/site-information', array('site_403' => ''), t('Save configuration'));
944 // Logout and check that the user login block is shown on default 403 pages.
945 $this->drupalLogout();
947 $this->drupalGet('admin');
948 $this->assertText(t('Access denied'), t('Found the default 403 page'));
949 $this->assertResponse(403);
950 $this->assertText(t('User login'), t('Blocks are shown on the default 403 page'));
952 // Log back in, set the custom 403 page to /user and remove the block
953 $this->drupalLogin($this->admin_user
);
954 variable_set('site_403', 'user');
955 $this->drupalPost('admin/structure/block', array('blocks[user_login][region]' => '-1'), t('Save blocks'));
957 // Check that we can log in from the 403 page.
958 $this->drupalLogout();
960 'name' => $this->admin_user
->name
,
961 'pass' => $this->admin_user
->pass_raw
,
963 $this->drupalPost('admin/config/system/site-information', $edit, t('Log in'));
965 // Check that we're still on the same page.
966 $this->assertText(t('Site information'));
970 class PageNotFoundTestCase
extends DrupalWebTestCase
{
971 protected
$admin_user;
974 * Implement getInfo().
976 public static
function getInfo() {
978 'name' => '404 functionality',
979 'description' => "Tests page not found functionality, including custom 404 pages.",
990 // Create an administrative user.
991 $this->admin_user
= $this->drupalCreateUser(array('administer site configuration'));
992 $this->drupalLogin($this->admin_user
);
995 function testPageNotFound() {
996 $this->drupalGet($this->randomName(10));
997 $this->assertText(t('Page not found'), t('Found the default 404 page'));
1000 'title' => $this->randomName(10),
1001 'body' => array(LANGUAGE_NONE
=> array(array('value' => $this->randomName(100)))),
1003 $node = $this->drupalCreateNode($edit);
1005 // Use a custom 404 page.
1006 $this->drupalPost('admin/config/system/site-information', array('site_404' => 'node/' .
$node->nid
), t('Save configuration'));
1008 $this->drupalGet($this->randomName(10));
1009 $this->assertText($node->title
, t('Found the custom 404 page'));
1014 * Tests site maintenance functionality.
1016 class SiteMaintenanceTestCase
extends DrupalWebTestCase
{
1017 protected
$admin_user;
1019 public static
function getInfo() {
1021 'name' => 'Site maintenance mode functionality',
1022 'description' => 'Test access to site while in maintenance mode.',
1023 'group' => 'System',
1030 // Create a user allowed to access site in maintenance mode.
1031 $this->user
= $this->drupalCreateUser(array('access site in maintenance mode'));
1032 // Create an administrative user.
1033 $this->admin_user
= $this->drupalCreateUser(array('administer site configuration', 'access site in maintenance mode'));
1034 $this->drupalLogin($this->admin_user
);
1038 * Verify site maintenance mode functionality.
1040 function testSiteMaintenance() {
1041 // Turn on maintenance mode.
1043 'maintenance_mode' => 1,
1045 $this->drupalPost('admin/config/development/maintenance', $edit, t('Save configuration'));
1047 $admin_message = t('Operating in maintenance mode. <a href="@url">Go online.</a>', array('@url' => url('admin/config/development/maintenance')));
1048 $user_message = t('Operating in maintenance mode.');
1049 $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')));
1051 $this->drupalGet('');
1052 $this->assertRaw($admin_message, t('Found the site maintenance mode message.'));
1054 // Logout and verify that offline message is displayed.
1055 $this->drupalLogout();
1056 $this->drupalGet('');
1057 $this->assertText($offline_message);
1058 $this->drupalGet('node');
1059 $this->assertText($offline_message);
1060 $this->drupalGet('user/register');
1061 $this->assertText($offline_message);
1063 // Verify that user is able to log in.
1064 $this->drupalGet('user');
1065 $this->assertNoText($offline_message);
1066 $this->drupalGet('user/login');
1067 $this->assertNoText($offline_message);
1069 // Log in user and verify that maintenance mode message is displayed
1070 // directly after login.
1072 'name' => $this->user
->name
,
1073 'pass' => $this->user
->pass_raw
,
1075 $this->drupalPost(NULL
, $edit, t('Log in'));
1076 $this->assertText($user_message);
1078 // Log in administrative user and configure a custom site offline message.
1079 $this->drupalLogout();
1080 $this->drupalLogin($this->admin_user
);
1081 $this->drupalGet('admin/config/development/maintenance');
1082 $this->assertNoRaw($admin_message, t('Site maintenance mode message not displayed.'));
1084 $offline_message = 'Sorry, not online.';
1086 'maintenance_mode_message' => $offline_message,
1088 $this->drupalPost(NULL
, $edit, t('Save configuration'));
1090 // Logout and verify that custom site offline message is displayed.
1091 $this->drupalLogout();
1092 $this->drupalGet('');
1093 $this->assertRaw($offline_message, t('Found the site offline message.'));
1095 // Verify that custom site offline message is not displayed on user/password.
1096 $this->drupalGet('user/password');
1097 $this->assertText(t('Username or e-mail address'), t('Anonymous users can access user/password'));
1099 // Submit password reset form.
1101 'name' => $this->user
->name
,
1103 $this->drupalPost('user/password', $edit, t('E-mail new password'));
1104 $mails = $this->drupalGetMails();
1105 $start = strpos($mails[0]['body'], 'user/reset/'.
$this->user
->uid
);
1106 $path = substr($mails[0]['body'], $start, 66 + strlen($this->user
->uid
));
1108 // Log in with temporary login link.
1109 $this->drupalPost($path, array(), t('Log in'));
1110 $this->assertText($user_message);
1115 * Tests generic date and time handling capabilities of Drupal.
1117 class DateTimeFunctionalTest
extends DrupalWebTestCase
{
1118 public static
function getInfo() {
1120 'name' => 'Date and time',
1121 'description' => 'Configure date and time settings. Test date formatting and time zone handling, including daylight saving time.',
1122 'group' => 'System',
1127 parent
::setUp(array('locale'));
1129 // Create admin user and log in admin user.
1130 $this->admin_user
= $this->drupalCreateUser(array('administer site configuration'));
1131 $this->drupalLogin($this->admin_user
);
1136 * Test time zones and DST handling.
1138 function testTimeZoneHandling() {
1139 // Setup date/time settings for Honolulu time.
1140 variable_set('date_default_timezone', 'Pacific/Honolulu');
1141 variable_set('configurable_timezones', 0);
1142 variable_set('date_format_medium', 'Y-m-d H:i:s O');
1144 // Create some nodes with different authored-on dates.
1145 $date1 = '2007-01-31 21:00:00 -1000';
1146 $date2 = '2007-07-31 21:00:00 -1000';
1147 $node1 = $this->drupalCreateNode(array('created' => strtotime($date1), 'type' => 'article'));
1148 $node2 = $this->drupalCreateNode(array('created' => strtotime($date2), 'type' => 'article'));
1150 // Confirm date format and time zone.
1151 $this->drupalGet("node/$node1->nid");
1152 $this->assertText('2007-01-31 21:00:00 -1000', t('Date should be identical, with GMT offset of -10 hours.'));
1153 $this->drupalGet("node/$node2->nid");
1154 $this->assertText('2007-07-31 21:00:00 -1000', t('Date should be identical, with GMT offset of -10 hours.'));
1156 // Set time zone to Los Angeles time.
1157 variable_set('date_default_timezone', 'America/Los_Angeles');
1159 // Confirm date format and time zone.
1160 $this->drupalGet("node/$node1->nid");
1161 $this->assertText('2007-01-31 23:00:00 -0800', t('Date should be two hours ahead, with GMT offset of -8 hours.'));
1162 $this->drupalGet("node/$node2->nid");
1163 $this->assertText('2007-08-01 00:00:00 -0700', t('Date should be three hours ahead, with GMT offset of -7 hours.'));
1167 * Test date type configuration.
1169 function testDateTypeConfiguration() {
1170 // Confirm system date types appear.
1171 $this->drupalGet('admin/config/regional/date-time');
1172 $this->assertText(t('Medium'), 'System date types appear in date type list.');
1173 $this->assertNoRaw('href="/admin/config/regional/date-time/types/medium/delete"', 'No delete link appear for system date types.');
1175 // Add custom date type.
1176 $this->clickLink(t('Add date type'));
1177 $date_type = strtolower($this->randomName(8));
1178 $machine_name = 'machine_' .
$date_type;
1179 $date_format = 'd.m.Y - H:i';
1181 'date_type' => $date_type,
1182 'machine_name' => $machine_name,
1183 'date_format' => $date_format,
1185 $this->drupalPost('admin/config/regional/date-time/types/add', $edit, t('Add date type'));
1186 $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time', array('absolute' => TRUE
)), t('Correct page redirection.'));
1187 $this->assertText(t('New date type added successfully.'), 'Date type added confirmation message appears.');
1188 $this->assertText($date_type, 'Custom date type appears in the date type list.');
1189 $this->assertText(t('delete'), 'Delete link for custom date type appears.');
1191 // Delete custom date type.
1192 $this->clickLink(t('delete'));
1193 $this->drupalPost('admin/config/regional/date-time/types/' .
$machine_name .
'/delete', array(), t('Remove'));
1194 $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time', array('absolute' => TRUE
)), t('Correct page redirection.'));
1195 $this->assertText(t('Removed date type ' .
$date_type), 'Custom date type removed.');
1199 * Test date format configuration.
1201 function testDateFormatConfiguration() {
1202 // Confirm 'no custom date formats available' message appears.
1203 $this->drupalGet('admin/config/regional/date-time/formats');
1204 $this->assertText(t('No custom date formats available.'), 'No custom date formats message appears.');
1206 // Add custom date format.
1207 $this->clickLink(t('Add format'));
1209 'date_format' => 'Y',
1211 $this->drupalPost('admin/config/regional/date-time/formats/add', $edit, t('Add format'));
1212 $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE
)), t('Correct page redirection.'));
1213 $this->assertNoText(t('No custom date formats available.'), 'No custom date formats message does not appear.');
1214 $this->assertText(t('Custom date format added.'), 'Custom date format added.');
1216 // Ensure custom date format appears in date type configuration options.
1217 $this->drupalGet('admin/config/regional/date-time');
1218 $this->assertRaw('<option value="Y">', 'Custom date format appears in options.');
1220 // Edit custom date format.
1221 $this->drupalGet('admin/config/regional/date-time/formats');
1222 $this->clickLink(t('edit'));
1224 'date_format' => 'Y m',
1226 $this->drupalPost($this->getUrl(), $edit, t('Save format'));
1227 $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE
)), t('Correct page redirection.'));
1228 $this->assertText(t('Custom date format updated.'), 'Custom date format successfully updated.');
1230 // Delete custom date format.
1231 $this->clickLink(t('delete'));
1232 $this->drupalPost($this->getUrl(), array(), t('Remove'));
1233 $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE
)), t('Correct page redirection.'));
1234 $this->assertText(t('Removed date format'), 'Custom date format removed successfully.');
1238 * Test if the date formats are stored properly.
1240 function testDateFormatStorage() {
1241 $date_format = array(
1243 'format' => 'dmYHis',
1247 system_date_format_save($date_format);
1249 $format = db_select('date_formats', 'df')
1250 ->fields('df', array('format'))
1251 ->condition('type', 'short')
1252 ->condition('format', 'dmYHis')
1255 $this->verbose($format);
1256 $this->assertEqual('dmYHis', $format, 'Unlocalized date format resides in general table.');
1258 $format = db_select('date_format_locale', 'dfl')
1259 ->fields('dfl', array('format'))
1260 ->condition('type', 'short')
1261 ->condition('format', 'dmYHis')
1264 $this->assertFalse($format, 'Unlocalized date format resides not in localized table.');
1266 // Enable German language
1267 locale_add_language('de', NULL
, NULL
, LANGUAGE_LTR
, '', '', TRUE
, 'en');
1269 $date_format = array(
1271 'format' => 'YMDHis',
1272 'locales' => array('de', 'tr'),
1276 system_date_format_save($date_format);
1278 $format = db_select('date_format_locale', 'dfl')
1279 ->fields('dfl', array('format'))
1280 ->condition('type', 'short')
1281 ->condition('format', 'YMDHis')
1282 ->condition('language', 'de')
1285 $this->assertEqual('YMDHis', $format, 'Localized date format resides in localized table.');
1287 $format = db_select('date_formats', 'df')
1288 ->fields('df', array('format'))
1289 ->condition('type', 'short')
1290 ->condition('format', 'YMDHis')
1293 $this->assertEqual('YMDHis', $format, 'Localized date format resides in general table too.');
1295 $format = db_select('date_format_locale', 'dfl')
1296 ->fields('dfl', array('format'))
1297 ->condition('type', 'short')
1298 ->condition('format', 'YMDHis')
1299 ->condition('language', 'tr')
1302 $this->assertFalse($format, 'Localized date format for disabled language is ignored.');
1306 class PageTitleFiltering
extends DrupalWebTestCase
{
1307 protected
$content_user;
1308 protected
$saved_title;
1311 * Implement getInfo().
1313 public static
function getInfo() {
1315 'name' => 'HTML in page titles',
1316 'description' => 'Tests correct handling or conversion by drupal_set_title() and drupal_get_title() and checks the correct escaping of site name and slogan.',
1322 * Implement setUp().
1327 $this->content_user
= $this->drupalCreateUser(array('create page content', 'access content', 'administer themes', 'administer site configuration'));
1328 $this->drupalLogin($this->content_user
);
1329 $this->saved_title
= drupal_get_title();
1335 function tearDown() {
1336 // Restore the page title.
1337 drupal_set_title($this->saved_title
, PASS_THROUGH
);
1343 * Tests the handling of HTML by drupal_set_title() and drupal_get_title()
1345 function testTitleTags() {
1346 $title = "string with <em>HTML</em>";
1347 // drupal_set_title's $filter is CHECK_PLAIN by default, so the title should be
1348 // returned with check_plain().
1349 drupal_set_title($title, CHECK_PLAIN
);
1350 $this->assertTrue(strpos(drupal_get_title(), '<em>') === FALSE
, t('Tags in title converted to entities when $output is CHECK_PLAIN.'));
1351 // drupal_set_title's $filter is passed as PASS_THROUGH, so the title should be
1352 // returned with HTML.
1353 drupal_set_title($title, PASS_THROUGH
);
1354 $this->assertTrue(strpos(drupal_get_title(), '<em>') !== FALSE
, t('Tags in title are not converted to entities when $output is PASS_THROUGH.'));
1355 // Generate node content.
1356 $langcode = LANGUAGE_NONE
;
1358 "title" => '!SimpleTest! ' .
$title .
$this->randomName(20),
1359 "body[$langcode][0][value]" => '!SimpleTest! test body' .
$this->randomName(200),
1361 // Create the node with HTML in the title.
1362 $this->drupalPost('node/add/page', $edit, t('Save'));
1364 $node = $this->drupalGetNodeByTitle($edit["title"]);
1365 $this->assertNotNull($node, 'Node created and found in database');
1366 $this->drupalGet("node/" .
$node->nid
);
1367 $this->assertText(check_plain($edit["title"]), 'Check to make sure tags in the node title are converted.');
1370 * Test if the title of the site is XSS proof.
1372 function testTitleXSS() {
1373 // Set some title with JavaScript and HTML chars to escape.
1374 $title = '</title><script type="text/javascript">alert("Title XSS!");</script> & < > " \' ';
1375 $title_filtered = check_plain($title);
1377 $slogan = '<script type="text/javascript">alert("Slogan XSS!");</script>';
1378 $slogan_filtered = filter_xss_admin($slogan);
1380 // Activate needed appearance settings.
1382 'toggle_name' => TRUE
,
1383 'toggle_slogan' => TRUE
,
1384 'toggle_main_menu' => TRUE
,
1385 'toggle_secondary_menu' => TRUE
,
1387 $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
1389 // Set title and slogan.
1391 'site_name' => $title,
1392 'site_slogan' => $slogan,
1394 $this->drupalPost('admin/config/system/site-information', $edit, t('Save configuration'));
1397 $this->drupalGet('');
1400 $this->assertNoRaw($title, 'Check for the unfiltered version of the title.');
1401 // Adding </title> so we do not test the escaped version from drupal_set_title().
1402 $this->assertRaw($title_filtered .
'</title>', 'Check for the filtered version of the title.');
1405 $this->assertNoRaw($slogan, 'Check for the unfiltered version of the slogan.');
1406 $this->assertRaw($slogan_filtered, 'Check for the filtered version of the slogan.');
1411 * Test front page functionality and administration.
1413 class FrontPageTestCase
extends DrupalWebTestCase
{
1415 public static
function getInfo() {
1417 'name' => 'Front page',
1418 'description' => 'Tests front page functionality and administration.',
1419 'group' => 'System',
1424 parent
::setUp('system_test');
1426 // Create admin user, log in admin user, and create one node.
1427 $this->admin_user
= $this->drupalCreateUser(array('access content', 'administer site configuration'));
1428 $this->drupalLogin($this->admin_user
);
1429 $this->node_path
= "node/" .
$this->drupalCreateNode(array('promote' => 1))->nid
;
1431 // Enable front page logging in system_test.module.
1432 variable_set('front_page_output', 1);
1436 * Test front page functionality.
1438 function testDrupalIsFrontPage() {
1439 $this->drupalGet('');
1440 $this->assertText(t('On front page.'), t('Path is the front page.'));
1441 $this->drupalGet('node');
1442 $this->assertText(t('On front page.'), t('Path is the front page.'));
1443 $this->drupalGet($this->node_path
);
1444 $this->assertNoText(t('On front page.'), t('Path is not the front page.'));
1446 // Change the front page to an invalid path.
1447 $edit = array('site_frontpage' => 'kittens');
1448 $this->drupalPost('admin/config/system/site-information', $edit, t('Save configuration'));
1449 $this->assertText(t("The path '@path' is either invalid or you do not have access to it.", array('@path' => $edit['site_frontpage'])));
1451 // Change the front page to a valid path.
1452 $edit['site_frontpage'] = $this->node_path
;
1453 $this->drupalPost('admin/config/system/site-information', $edit, t('Save configuration'));
1454 $this->assertText(t('The configuration options have been saved.'), t('The front page path has been saved.'));
1456 $this->drupalGet('');
1457 $this->assertText(t('On front page.'), t('Path is the front page.'));
1458 $this->drupalGet('node');
1459 $this->assertNoText(t('On front page.'), t('Path is not the front page.'));
1460 $this->drupalGet($this->node_path
);
1461 $this->assertText(t('On front page.'), t('Path is the front page.'));
1465 class SystemBlockTestCase
extends DrupalWebTestCase
{
1466 protected
$profile = 'testing';
1468 public static
function getInfo() {
1470 'name' => 'Block functionality',
1471 'description' => 'Configure and move powered-by block.',
1472 'group' => 'System',
1477 parent
::setUp('block');
1479 // Create and login user
1480 $admin_user = $this->drupalCreateUser(array('administer blocks', 'access administration pages'));
1481 $this->drupalLogin($admin_user);
1485 * Test displaying and hiding the powered-by and help blocks.
1487 function testSystemBlocks() {
1488 // Set block title and some settings to confirm that the interface is available.
1489 $this->drupalPost('admin/structure/block/manage/system/powered-by/configure', array('title' => $this->randomName(8)), t('Save block'));
1490 $this->assertText(t('The block configuration has been saved.'), t('Block configuration set.'));
1492 // Set the powered-by block to the footer region.
1494 $edit['blocks[system_powered-by][region]'] = 'footer';
1495 $edit['blocks[system_main][region]'] = 'content';
1496 $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1497 $this->assertText(t('The block settings have been updated.'), t('Block successfully moved to footer region.'));
1499 // Confirm that the block is being displayed.
1500 $this->drupalGet('node');
1501 $this->assertRaw('id="block-system-powered-by"', t('Block successfully being displayed on the page.'));
1503 // Set the block to the disabled region.
1505 $edit['blocks[system_powered-by][region]'] = '-1';
1506 $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1508 // Confirm that the block is hidden.
1509 $this->assertNoRaw('id="block-system-powered-by"', t('Block no longer appears on page.'));
1511 // For convenience of developers, set the block to its default settings.
1513 $edit['blocks[system_powered-by][region]'] = 'footer';
1514 $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1515 $this->drupalPost('admin/structure/block/manage/system/powered-by/configure', array('title' => ''), t('Save block'));
1517 // Set the help block to the help region.
1519 $edit['blocks[system_help][region]'] = 'help';
1520 $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1522 // Test displaying the help block with block caching enabled.
1523 variable_set('block_cache', TRUE
);
1524 $this->drupalGet('admin/structure/block/add');
1525 $this->assertRaw(t('Use this page to create a new custom block.'));
1526 $this->drupalGet('admin/index');
1527 $this->assertRaw(t('This page shows you all available administration tasks for each module.'));
1532 * Test main content rendering fallback provided by system module.
1534 class SystemMainContentFallback
extends DrupalWebTestCase
{
1535 protected
$admin_user;
1536 protected
$web_user;
1538 public static
function getInfo() {
1540 'name' => 'Main content rendering fallback',
1541 'description' => ' Test system module main content rendering fallback.',
1542 'group' => 'System',
1547 parent
::setUp('system_test');
1549 // Create and login admin user.
1550 $this->admin_user
= $this->drupalCreateUser(array(
1551 'access administration pages',
1552 'administer site configuration',
1553 'administer modules',
1554 'administer blocks',
1557 $this->drupalLogin($this->admin_user
);
1559 // Create a web user.
1560 $this->web_user
= $this->drupalCreateUser(array('access user profiles', 'access content'));
1564 * Test availability of main content.
1566 function testMainContentFallback() {
1568 // Disable the dashboard module, which depends on the block module.
1569 $edit['modules[Core][dashboard][enable]'] = FALSE
;
1570 $this->drupalPost('admin/modules', $edit, t('Save configuration'));
1571 $this->assertText(t('The configuration options have been saved.'), t('Modules status has been updated.'));
1572 // Disable the block module.
1573 $edit['modules[Core][block][enable]'] = FALSE
;
1574 $this->drupalPost('admin/modules', $edit, t('Save configuration'));
1575 $this->assertText(t('The configuration options have been saved.'), t('Modules status has been updated.'));
1577 $this->assertFalse(module_exists('block'), t('Block module disabled.'));
1579 // At this point, no region is filled and fallback should be triggered.
1580 $this->drupalGet('admin/config/system/site-information');
1581 $this->assertField('site_name', t('Admin interface still available.'));
1583 // Fallback should not trigger when another module is handling content.
1584 $this->drupalGet('system-test/main-content-handling');
1585 $this->assertRaw('id="system-test-content"', t('Content handled by another module'));
1586 $this->assertText(t('Content to test main content fallback'), t('Main content still displayed.'));
1588 // Fallback should trigger when another module
1589 // indicates that it is not handling the content.
1590 $this->drupalGet('system-test/main-content-fallback');
1591 $this->assertText(t('Content to test main content fallback'), t('Main content fallback properly triggers.'));
1593 // Fallback should not trigger when another module is handling content.
1594 // Note that this test ensures that no duplicate
1595 // content gets created by the fallback.
1596 $this->drupalGet('system-test/main-content-duplication');
1597 $this->assertNoText(t('Content to test main content fallback'), t('Main content not duplicated.'));
1599 // Request a user* page and see if it is displayed.
1600 $this->drupalLogin($this->web_user
);
1601 $this->drupalGet('user/' .
$this->web_user
->uid .
'/edit');
1602 $this->assertField('mail', t('User interface still available.'));
1604 // Enable the block module again.
1605 $this->drupalLogin($this->admin_user
);
1607 $edit['modules[Core][block][enable]'] = 'block';
1608 $this->drupalPost('admin/modules', $edit, t('Save configuration'));
1609 $this->assertText(t('The configuration options have been saved.'), t('Modules status has been updated.'));
1611 $this->assertTrue(module_exists('block'), t('Block module re-enabled.'));
1616 * Tests for the theme interface functionality.
1618 class SystemThemeFunctionalTest
extends DrupalWebTestCase
{
1619 public static
function getInfo() {
1621 'name' => 'Theme interface functionality',
1622 'description' => 'Tests the theme interface functionality by enabling and switching themes, and using an administration theme.',
1623 'group' => 'System',
1630 $this->admin_user
= $this->drupalCreateUser(array('access administration pages', 'view the administration theme', 'administer themes', 'bypass node access', 'administer blocks'));
1631 $this->drupalLogin($this->admin_user
);
1632 $this->node
= $this->drupalCreateNode();
1636 * Test the theme settings form.
1638 function testThemeSettings() {
1639 // Specify a filesystem path to be used for the logo.
1640 $file = current($this->drupalGetTestFiles('image'));
1641 $fullpath = drupal_realpath($file->uri
);
1643 'default_logo' => FALSE
,
1644 'logo_path' => $fullpath,
1646 $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
1647 $this->drupalGet('node');
1648 $this->assertRaw($fullpath, t('Logo path successfully changed.'));
1650 // Upload a file to use for the logo.
1651 $file = current($this->drupalGetTestFiles('image'));
1653 'default_logo' => FALSE
,
1655 'files[logo_upload]' => drupal_realpath($file->uri
),
1658 $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'), $options);
1659 $this->drupalGet('node');
1660 $this->assertRaw($file->name
, t('Logo file successfully uploaded.'));
1664 * Test the administration theme functionality.
1666 function testAdministrationTheme() {
1667 theme_enable(array('stark'));
1668 variable_set('theme_default', 'stark');
1669 // Enable an administration theme and show it on the node admin pages.
1671 'admin_theme' => 'seven',
1672 'node_admin_theme' => TRUE
,
1674 $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
1676 $this->drupalGet('admin/config');
1677 $this->assertRaw('themes/seven', t('Administration theme used on an administration page.'));
1679 $this->drupalGet('node/' .
$this->node
->nid
);
1680 $this->assertRaw('themes/stark', t('Site default theme used on node page.'));
1682 $this->drupalGet('node/add');
1683 $this->assertRaw('themes/seven', t('Administration theme used on the add content page.'));
1685 $this->drupalGet('node/' .
$this->node
->nid .
'/edit');
1686 $this->assertRaw('themes/seven', t('Administration theme used on the edit content page.'));
1688 // Disable the admin theme on the node admin pages.
1690 'node_admin_theme' => FALSE
,
1692 $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
1694 $this->drupalGet('admin/config');
1695 $this->assertRaw('themes/seven', t('Administration theme used on an administration page.'));
1697 $this->drupalGet('node/add');
1698 $this->assertRaw('themes/stark', t('Site default theme used on the add content page.'));
1700 // Reset to the default theme settings.
1701 variable_set('theme_default', 'bartik');
1703 'admin_theme' => '0',
1704 'node_admin_theme' => FALSE
,
1706 $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
1708 $this->drupalGet('admin');
1709 $this->assertRaw('themes/bartik', t('Site default theme used on administration page.'));
1711 $this->drupalGet('node/add');
1712 $this->assertRaw('themes/bartik', t('Site default theme used on the add content page.'));
1716 * Test switching the default theme.
1718 function testSwitchDefaultTheme() {
1719 // Enable "stark" and set it as the default theme.
1720 theme_enable(array('stark'));
1721 $this->drupalGet('admin/appearance');
1722 $this->clickLink(t('Set default'), 1);
1723 $this->assertTrue(variable_get('theme_default', '') == 'stark', t('Site default theme switched successfully.'));
1725 // Test the default theme on the secondary links (blocks admin page).
1726 $this->drupalGet('admin/structure/block');
1727 $this->assertText('Stark(' .
t('active tab') .
')', t('Default local task on blocks admin page is the default theme.'));
1728 // Switch back to Bartik and test again to test that the menu cache is cleared.
1729 $this->drupalGet('admin/appearance');
1730 $this->clickLink(t('Set default'), 0);
1731 $this->drupalGet('admin/structure/block');
1732 $this->assertText('Bartik(' .
t('active tab') .
')', t('Default local task on blocks admin page has changed.'));
1738 * Test the basic queue functionality.
1740 class QueueTestCase
extends DrupalWebTestCase
{
1741 public static
function getInfo() {
1743 'name' => 'Queue functionality',
1744 'description' => 'Queues and dequeues a set of items to check the basic queue functionality.',
1745 'group' => 'System',
1750 * Queues and dequeues a set of items to check the basic queue functionality.
1752 function testQueue() {
1753 // Create two queues.
1754 $queue1 = DrupalQueue
::get($this->randomName());
1755 $queue1->createQueue();
1756 $queue2 = DrupalQueue
::get($this->randomName());
1757 $queue2->createQueue();
1759 // Create four items.
1761 for ($i = 0; $i < 4; $i++) {
1762 $data[] = array($this->randomName() => $this->randomName());
1765 // Queue items 1 and 2 in the queue1.
1766 $queue1->createItem($data[0]);
1767 $queue1->createItem($data[1]);
1769 // Retrieve two items from queue1.
1771 $new_items = array();
1773 $items[] = $item = $queue1->claimItem();
1774 $new_items[] = $item->data
;
1776 $items[] = $item = $queue1->claimItem();
1777 $new_items[] = $item->data
;
1779 // First two dequeued items should match the first two items we queued.
1780 $this->assertEqual($this->queueScore($data, $new_items), 2, t('Two items matched'));
1782 // Add two more items.
1783 $queue1->createItem($data[2]);
1784 $queue1->createItem($data[3]);
1786 $this->assertTrue($queue1->numberOfItems(), t('Queue 1 is not empty after adding items.'));
1787 $this->assertFalse($queue2->numberOfItems(), t('Queue 2 is empty while Queue 1 has items'));
1789 $items[] = $item = $queue1->claimItem();
1790 $new_items[] = $item->data
;
1792 $items[] = $item = $queue1->claimItem();
1793 $new_items[] = $item->data
;
1795 // All dequeued items should match the items we queued exactly once,
1796 // therefore the score must be exactly 4.
1797 $this->assertEqual($this->queueScore($data, $new_items), 4, t('Four items matched'));
1799 // There should be no duplicate items.
1800 $this->assertEqual($this->queueScore($new_items, $new_items), 4, t('Four items matched'));
1802 // Delete all items from queue1.
1803 foreach ($items as
$item) {
1804 $queue1->deleteItem($item);
1807 // Check that both queues are empty.
1808 $this->assertFalse($queue1->numberOfItems(), t('Queue 1 is empty'));
1809 $this->assertFalse($queue2->numberOfItems(), t('Queue 2 is empty'));
1813 * This function returns the number of equal items in two arrays.
1815 function queueScore($items, $new_items) {
1817 foreach ($items as
$item) {
1818 foreach ($new_items as
$new_item) {
1819 if ($item === $new_item) {
1829 * Test token replacement in strings.
1831 class TokenReplaceTestCase
extends DrupalWebTestCase
{
1832 public static
function getInfo() {
1834 'name' => 'Token replacement',
1835 'description' => 'Generates text using placeholders for dummy content to check token replacement.',
1836 'group' => 'System',
1841 * Creates a user and a node, then tests the tokens generated from them.
1843 function testTokenReplacement() {
1844 // Create the initial objects.
1845 $account = $this->drupalCreateUser();
1846 $node = $this->drupalCreateNode(array('uid' => $account->uid
));
1847 $node->title
= '<blink>Blinking Text</blink>';
1848 global $user, $language;
1850 $source = '[node:title]'; // Title of the node we passed in
1851 $source .
= '[node:author:name]'; // Node author's name
1852 $source .
= '[node:created:since]'; // Time since the node was created
1853 $source .
= '[current-user:name]'; // Current user's name
1854 $source .
= '[date:short]'; // Short date format of REQUEST_TIME
1855 $source .
= '[user:name]'; // No user passed in, should be untouched
1856 $source .
= '[bogus:token]'; // Non-existent token
1858 $target = check_plain($node->title
);
1859 $target .
= check_plain($account->name
);
1860 $target .
= format_interval(REQUEST_TIME
- $node->created
, 2, $language->language
);
1861 $target .
= check_plain($user->name
);
1862 $target .
= format_date(REQUEST_TIME
, 'short', '', NULL
, $language->language
);
1864 // Test that the clear parameter cleans out non-existent tokens.
1865 $result = token_replace($source, array('node' => $node), array('language' => $language, 'clear' => TRUE
));
1866 $result = $this->assertEqual($target, $result, 'Valid tokens replaced while invalid tokens cleared out.');
1868 // Test without using the clear parameter (non-existent token untouched).
1869 $target .
= '[user:name]';
1870 $target .
= '[bogus:token]';
1871 $result = token_replace($source, array('node' => $node), array('language' => $language));
1872 $this->assertEqual($target, $result, 'Valid tokens replaced while invalid tokens ignored.');
1874 // Check that the results of token_generate are sanitized properly. This does NOT
1875 // test the cleanliness of every token -- just that the $sanitize flag is being
1876 // passed properly through the call stack and being handled correctly by a 'known'
1877 // token, [node:title].
1878 $raw_tokens = array('title' => '[node:title]');
1879 $generated = token_generate('node', $raw_tokens, array('node' => $node));
1880 $this->assertEqual($generated['[node:title]'], check_plain($node->title
), t('Token sanitized.'));
1882 $generated = token_generate('node', $raw_tokens, array('node' => $node), array('sanitize' => FALSE
));
1883 $this->assertEqual($generated['[node:title]'], $node->title
, t('Unsanitized token generated properly.'));
1885 // Test token replacement when the string contains no tokens.
1886 $this->assertEqual(token_replace('No tokens here.'), 'No tokens here.');
1890 * Test whether token-replacement works in various contexts.
1892 function testSystemTokenRecognition() {
1895 // Generate prefixes and suffixes for the token context.
1897 array('prefix' => 'this is the ', 'suffix' => ' site'),
1898 array('prefix' => 'this is the', 'suffix' => 'site'),
1899 array('prefix' => '[', 'suffix' => ']'),
1900 array('prefix' => '', 'suffix' => ']]]'),
1901 array('prefix' => '[[[', 'suffix' => ''),
1902 array('prefix' => ':[:', 'suffix' => '--]'),
1903 array('prefix' => '-[-', 'suffix' => ':]:'),
1904 array('prefix' => '[:', 'suffix' => ']'),
1905 array('prefix' => '[site:', 'suffix' => ':name]'),
1906 array('prefix' => '[site:', 'suffix' => ']'),
1909 // Check if the token is recognized in each of the contexts.
1910 foreach ($tests as
$test) {
1911 $input = $test['prefix'] .
'[site:name]' .
$test['suffix'];
1912 $expected = $test['prefix'] .
'Drupal' .
$test['suffix'];
1913 $output = token_replace($input, array(), array('language' => $language));
1914 $this->assertTrue($output == $expected, t('Token recognized in string %string', array('%string' => $input)));
1919 * Tests the generation of all system site information tokens.
1921 function testSystemSiteTokenReplacement() {
1923 $url_options = array(
1925 'language' => $language,
1928 // Set a few site variables.
1929 variable_set('site_name', '<strong>Drupal<strong>');
1930 variable_set('site_slogan', '<blink>Slogan</blink>');
1932 // Generate and test sanitized tokens.
1934 $tests['[site:name]'] = check_plain(variable_get('site_name', 'Drupal'));
1935 $tests['[site:slogan]'] = check_plain(variable_get('site_slogan', ''));
1936 $tests['[site:mail]'] = 'simpletest@example.com';
1937 $tests['[site:url]'] = url('<front>', $url_options);
1938 $tests['[site:url-brief]'] = preg_replace(array('!^https?://!', '!/$!'), '', url('<front>', $url_options));
1939 $tests['[site:login-url]'] = url('user', $url_options);
1941 // Test to make sure that we generated something for each token.
1942 $this->assertFalse(in_array(0, array_map('strlen', $tests)), t('No empty tokens generated.'));
1944 foreach ($tests as
$input => $expected) {
1945 $output = token_replace($input, array(), array('language' => $language));
1946 $this->assertEqual($output, $expected, t('Sanitized system site information token %token replaced.', array('%token' => $input)));
1949 // Generate and test unsanitized tokens.
1950 $tests['[site:name]'] = variable_get('site_name', 'Drupal');
1951 $tests['[site:slogan]'] = variable_get('site_slogan', '');
1953 foreach ($tests as
$input => $expected) {
1954 $output = token_replace($input, array(), array('language' => $language, 'sanitize' => FALSE
));
1955 $this->assertEqual($output, $expected, t('Unsanitized system site information token %token replaced.', array('%token' => $input)));
1960 * Tests the generation of all system date tokens.
1962 function testSystemDateTokenReplacement() {
1965 // Set time to one hour before request.
1966 $date = REQUEST_TIME
- 3600;
1968 // Generate and test tokens.
1970 $tests['[date:short]'] = format_date($date, 'short', '', NULL
, $language->language
);
1971 $tests['[date:medium]'] = format_date($date, 'medium', '', NULL
, $language->language
);
1972 $tests['[date:long]'] = format_date($date, 'long', '', NULL
, $language->language
);
1973 $tests['[date:custom:m/j/Y]'] = format_date($date, 'custom', 'm/j/Y', NULL
, $language->language
);
1974 $tests['[date:since]'] = format_interval((REQUEST_TIME
- $date), 2, $language->language
);
1975 $tests['[date:raw]'] = filter_xss($date);
1977 // Test to make sure that we generated something for each token.
1978 $this->assertFalse(in_array(0, array_map('strlen', $tests)), t('No empty tokens generated.'));
1980 foreach ($tests as
$input => $expected) {
1981 $output = token_replace($input, array('date' => $date), array('language' => $language));
1982 $this->assertEqual($output, $expected, t('Date token %token replaced.', array('%token' => $input)));
1987 class InfoFileParserTestCase
extends DrupalUnitTestCase
{
1988 public static
function getInfo() {
1990 'name' => 'Info file format parser',
1991 'description' => 'Tests proper parsing of a .info file formatted string.',
1992 'group' => 'System',
1997 * Test drupal_parse_info_format().
1999 function testDrupalParseInfoFormat() {
2007 array_assoc[a] = Value1
2008 array_assoc[b] = Value2
2009 array_deep[][][] = Value
2010 array_deep_assoc[a][b][c] = Value
2011 array_space[a b] = Value';
2014 'simple' => 'Value',
2015 'quoted' => ' Value',
2016 'multiline' => "Value\n Value",
2021 'array_assoc' => array(
2025 'array_deep' => array(
2032 'array_deep_assoc' => array(
2039 'array_space' => array(
2044 $parsed = drupal_parse_info_format($config);
2046 $this->assertEqual($parsed['simple'], $expected['simple'], t('Set a simple value.'));
2047 $this->assertEqual($parsed['quoted'], $expected['quoted'], t('Set a simple value in quotes.'));
2048 $this->assertEqual($parsed['multiline'], $expected['multiline'], t('Set a multiline value.'));
2049 $this->assertEqual($parsed['array'], $expected['array'], t('Set a simple array.'));
2050 $this->assertEqual($parsed['array_assoc'], $expected['array_assoc'], t('Set an associative array.'));
2051 $this->assertEqual($parsed['array_deep'], $expected['array_deep'], t('Set a nested array.'));
2052 $this->assertEqual($parsed['array_deep_assoc'], $expected['array_deep_assoc'], t('Set a nested associative array.'));
2053 $this->assertEqual($parsed['array_space'], $expected['array_space'], t('Set an array with a whitespace in the key.'));
2054 $this->assertEqual($parsed, $expected, t('Entire parsed .info string and expected array are identical.'));
2059 * Tests the effectiveness of hook_system_info_alter().
2061 class SystemInfoAlterTestCase
extends DrupalWebTestCase
{
2062 public static
function getInfo() {
2064 'name' => 'System info alter',
2065 'description' => 'Tests the effectiveness of hook_system_info_alter().',
2066 'group' => 'System',
2071 * Tests that {system}.info is rebuilt after a module that implements
2072 * hook_system_info_alter() is enabled. Also tests if core *_list() functions
2073 * return freshly altered info.
2075 function testSystemInfoAlter() {
2076 // Enable our test module. Flush all caches, which we assert is the only
2077 // thing necessary to use the rebuilt {system}.info.
2078 module_enable(array('module_test'), FALSE
);
2079 drupal_flush_all_caches();
2080 $this->assertTrue(module_exists('module_test'), t('Test module is enabled.'));
2082 $info = $this->getSystemInfo('seven', 'theme');
2083 $this->assertTrue(isset($info['regions']['test_region']), t('Altered theme info was added to {system}.info.'));
2084 $seven_regions = system_region_list('seven');
2085 $this->assertTrue(isset($seven_regions['test_region']), t('Altered theme info was returned by system_region_list().'));
2086 $system_list_themes = system_list('theme');
2087 $info = $system_list_themes['seven']->info
;
2088 $this->assertTrue(isset($info['regions']['test_region']), t('Altered theme info was returned by system_list().'));
2089 $list_themes = list_themes();
2090 $this->assertTrue(isset($list_themes['seven']->info
['regions']['test_region']), t('Altered theme info was returned by list_themes().'));
2092 // Disable the module and verify that {system}.info is rebuilt without it.
2093 module_disable(array('module_test'), FALSE
);
2094 drupal_flush_all_caches();
2095 $this->assertFalse(module_exists('module_test'), t('Test module is disabled.'));
2097 $info = $this->getSystemInfo('seven', 'theme');
2098 $this->assertFalse(isset($info['regions']['test_region']), t('Altered theme info was removed from {system}.info.'));
2099 $seven_regions = system_region_list('seven');
2100 $this->assertFalse(isset($seven_regions['test_region']), t('Altered theme info was not returned by system_region_list().'));
2101 $system_list_themes = system_list('theme');
2102 $info = $system_list_themes['seven']->info
;
2103 $this->assertFalse(isset($info['regions']['test_region']), t('Altered theme info was not returned by system_list().'));
2104 $list_themes = list_themes();
2105 $this->assertFalse(isset($list_themes['seven']->info
['regions']['test_region']), t('Altered theme info was not returned by list_themes().'));
2109 * Returns the info array as it is stored in {system}.
2112 * The name of the record in {system}.
2114 * The type of record in {system}.
2117 * Array of info, or FALSE if the record is not found.
2119 function getSystemInfo($name, $type) {
2120 $raw_info = db_query("SELECT info FROM {system} WHERE name = :name AND type = :type", array(':name' => $name, ':type' => $type))->fetchField();
2121 return $raw_info ?
unserialize($raw_info) : FALSE
;
2126 * Tests for the update system functionality.
2128 class UpdateScriptFunctionalTest
extends DrupalWebTestCase
{
2129 private
$update_url;
2130 private
$update_user;
2132 public static
function getInfo() {
2134 'name' => 'Update functionality',
2135 'description' => 'Tests the update script access and functionality.',
2136 'group' => 'System',
2141 parent
::setUp('update_script_test');
2142 $this->update_url
= $GLOBALS['base_url'] .
'/update.php';
2143 $this->update_user
= $this->drupalCreateUser(array('administer software updates'));
2147 * Tests access to the update script.
2149 function testUpdateAccess() {
2150 // Try accessing update.php without the proper permission.
2151 $regular_user = $this->drupalCreateUser();
2152 $this->drupalLogin($regular_user);
2153 $this->drupalGet($this->update_url
, array('external' => TRUE
));
2154 $this->assertResponse(403);
2156 // Try accessing update.php as an anonymous user.
2157 $this->drupalLogout();
2158 $this->drupalGet($this->update_url
, array('external' => TRUE
));
2159 $this->assertResponse(403);
2161 // Access the update page with the proper permission.
2162 $this->drupalLogin($this->update_user
);
2163 $this->drupalGet($this->update_url
, array('external' => TRUE
));
2164 $this->assertResponse(200);
2166 // Access the update page as user 1.
2167 $user1 = user_load(1);
2168 $user1->pass_raw
= user_password();
2169 require_once DRUPAL_ROOT .
'/' .
variable_get('password_inc', 'includes/password.inc');
2170 $user1->pass
= user_hash_password(trim($user1->pass_raw
));
2171 db_query("UPDATE {users} SET pass = :pass WHERE uid = :uid", array(':pass' => $user1->pass
, ':uid' => $user1->uid
));
2172 $this->drupalLogin($user1);
2173 $this->drupalGet($this->update_url
, array('external' => TRUE
));
2174 $this->assertResponse(200);
2178 * Tests that requirements warnings and errors are correctly displayed.
2180 function testRequirements() {
2181 $this->drupalLogin($this->update_user
);
2183 // If there are no requirements warnings or errors, we expect to be able to
2184 // go through the update process uninterrupted.
2185 $this->drupalGet($this->update_url
, array('external' => TRUE
));
2186 $this->drupalPost(NULL
, array(), t('Continue'));
2187 $this->assertText(t('No pending updates.'), t('End of update process was reached.'));
2188 // Confirm that all caches were cleared.
2189 $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared when there were no requirements warnings or errors.');
2191 // If there is a requirements warning, we expect it to be initially
2192 // displayed, but clicking the link to proceed should allow us to go
2193 // through the rest of the update process uninterrupted.
2195 // First, run this test with pending updates to make sure they can be run
2197 variable_set('update_script_test_requirement_type', REQUIREMENT_WARNING
);
2198 drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
2199 $this->drupalGet($this->update_url
, array('external' => TRUE
));
2200 $this->assertText('This is a requirements warning provided by the update_script_test module.');
2201 $this->clickLink('try again');
2202 $this->assertNoText('This is a requirements warning provided by the update_script_test module.');
2203 $this->drupalPost(NULL
, array(), t('Continue'));
2204 $this->drupalPost(NULL
, array(), t('Apply pending updates'));
2205 $this->assertText(t('The update_script_test_update_7000() update was executed successfully.'), t('End of update process was reached.'));
2206 // Confirm that all caches were cleared.
2207 $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared after resolving a requirements warning and applying updates.');
2209 // Now try again without pending updates to make sure that works too.
2210 $this->drupalGet($this->update_url
, array('external' => TRUE
));
2211 $this->assertText('This is a requirements warning provided by the update_script_test module.');
2212 $this->clickLink('try again');
2213 $this->assertNoText('This is a requirements warning provided by the update_script_test module.');
2214 $this->drupalPost(NULL
, array(), t('Continue'));
2215 $this->assertText(t('No pending updates.'), t('End of update process was reached.'));
2216 // Confirm that all caches were cleared.
2217 $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared after applying updates and re-running the script.');
2219 // If there is a requirements error, it should be displayed even after
2220 // clicking the link to proceed (since the problem that triggered the error
2221 // has not been fixed).
2222 variable_set('update_script_test_requirement_type', REQUIREMENT_ERROR
);
2223 $this->drupalGet($this->update_url
, array('external' => TRUE
));
2224 $this->assertText('This is a requirements error provided by the update_script_test module.');
2225 $this->clickLink('try again');
2226 $this->assertText('This is a requirements error provided by the update_script_test module.');
2230 * Tests the effect of using the update script on the theme system.
2232 function testThemeSystem() {
2233 // Since visiting update.php triggers a rebuild of the theme system from an
2234 // unusual maintenance mode environment, we check that this rebuild did not
2235 // put any incorrect information about the themes into the database.
2236 $original_theme_data = db_query("SELECT * FROM {system} WHERE type = 'theme' ORDER BY name")->fetchAll();
2237 $this->drupalLogin($this->update_user
);
2238 $this->drupalGet($this->update_url
, array('external' => TRUE
));
2239 $final_theme_data = db_query("SELECT * FROM {system} WHERE type = 'theme' ORDER BY name")->fetchAll();
2240 $this->assertEqual($original_theme_data, $final_theme_data, t('Visiting update.php does not alter the information about themes stored in the database.'));
2244 * Tests update.php when there are no updates to apply.
2246 function testNoUpdateFunctionality() {
2247 // Click through update.php with 'administer software updates' permission.
2248 $this->drupalLogin($this->update_user
);
2249 $this->drupalPost($this->update_url
, array(), t('Continue'), array('external' => TRUE
));
2250 $this->assertText(t('No pending updates.'));
2251 $this->assertNoLink('Administration pages');
2252 $this->clickLink('Front page');
2253 $this->assertResponse(200);
2255 // Click through update.php with 'access administration pages' permission.
2256 $admin_user = $this->drupalCreateUser(array('administer software updates', 'access administration pages'));
2257 $this->drupalLogin($admin_user);
2258 $this->drupalPost($this->update_url
, array(), t('Continue'), array('external' => TRUE
));
2259 $this->assertText(t('No pending updates.'));
2260 $this->clickLink('Administration pages');
2261 $this->assertResponse(200);
2265 * Tests update.php after performing a successful update.
2267 function testSuccessfulUpdateFunctionality() {
2268 drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
2269 // Click through update.php with 'administer software updates' permission.
2270 $this->drupalLogin($this->update_user
);
2271 $this->drupalPost($this->update_url
, array(), t('Continue'), array('external' => TRUE
));
2272 $this->drupalPost(NULL
, array(), t('Apply pending updates'));
2273 $this->assertText('Updates were attempted.');
2274 $this->assertLink('site');
2275 $this->assertNoLink('Administration pages');
2276 $this->assertNoLink('logged');
2277 $this->clickLink('Front page');
2278 $this->assertResponse(200);
2280 drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
2281 // Click through update.php with 'access administration pages' and
2282 // 'access site reports' permissions.
2283 $admin_user = $this->drupalCreateUser(array('administer software updates', 'access administration pages', 'access site reports'));
2284 $this->drupalLogin($admin_user);
2285 $this->drupalPost($this->update_url
, array(), t('Continue'), array('external' => TRUE
));
2286 $this->drupalPost(NULL
, array(), t('Apply pending updates'));
2287 $this->assertText('Updates were attempted.');
2288 $this->assertLink('logged');
2289 $this->clickLink('Administration pages');
2290 $this->assertResponse(200);
2295 * Functional tests for the flood control mechanism.
2297 class FloodFunctionalTest
extends DrupalWebTestCase
{
2298 public static
function getInfo() {
2300 'name' => 'Flood control mechanism',
2301 'description' => 'Functional tests for the flood control mechanism.',
2302 'group' => 'System',
2307 * Test flood control mechanism clean-up.
2309 function testCleanUp() {
2311 $window_expired = -1;
2312 $name = 'flood_test_cleanup';
2314 // Register expired event.
2315 flood_register_event($name, $window_expired);
2316 // Verify event is not allowed.
2317 $this->assertFalse(flood_is_allowed($name, $threshold));
2318 // Run cron and verify event is now allowed.
2320 $this->assertTrue(flood_is_allowed($name, $threshold));
2322 // Register unexpired event.
2323 flood_register_event($name);
2324 // Verify event is not allowed.
2325 $this->assertFalse(flood_is_allowed($name, $threshold));
2326 // Run cron and verify event is still not allowed.
2328 $this->assertFalse(flood_is_allowed($name, $threshold));
2333 * Test HTTP file downloading capability.
2335 class RetrieveFileTestCase
extends DrupalWebTestCase
{
2336 public static
function getInfo() {
2338 'name' => 'HTTP file retrieval',
2339 'description' => 'Checks HTTP file fetching and error handling.',
2340 'group' => 'System',
2345 * Invokes system_retrieve_file() in several scenarios.
2347 function testFileRetrieving() {
2348 // Test 404 handling by trying to fetch a randomly named file.
2349 drupal_mkdir($sourcedir = 'public://' .
$this->randomName());
2350 $filename = 'Файл для тестирования ' .
$this->randomName();
2351 $url = file_create_url($sourcedir .
'/' .
$filename);
2352 $retrieved_file = system_retrieve_file($url);
2353 $this->assertFalse($retrieved_file, t('Non-existent file not fetched.'));
2355 // Actually create that file, download it via HTTP and test the returned path.
2356 file_put_contents($sourcedir .
'/' .
$filename, 'testing');
2357 $retrieved_file = system_retrieve_file($url);
2359 // URLs could not contains characters outside the ASCII set so $filename
2360 // has to be encoded.
2361 $encoded_filename = rawurlencode($filename);
2363 $this->assertEqual($retrieved_file, 'public://' .
$encoded_filename, t('Sane path for downloaded file returned (public:// scheme).'));
2364 $this->assertTrue(is_file($retrieved_file), t('Downloaded file does exist (public:// scheme).'));
2365 $this->assertEqual(filesize($retrieved_file), 7, t('File size of downloaded file is correct (public:// scheme).'));
2366 file_unmanaged_delete($retrieved_file);
2368 // Test downloading file to a different location.
2369 drupal_mkdir($targetdir = 'temporary://' .
$this->randomName());
2370 $retrieved_file = system_retrieve_file($url, $targetdir);
2371 $this->assertEqual($retrieved_file, "$targetdir/$encoded_filename", t('Sane path for downloaded file returned (temporary:// scheme).'));
2372 $this->assertTrue(is_file($retrieved_file), t('Downloaded file does exist (temporary:// scheme).'));
2373 $this->assertEqual(filesize($retrieved_file), 7, t('File size of downloaded file is correct (temporary:// scheme).'));
2374 file_unmanaged_delete($retrieved_file);
2376 file_unmanaged_delete_recursive($sourcedir);
2377 file_unmanaged_delete_recursive($targetdir);
2382 * Functional tests shutdown functions.
2384 class ShutdownFunctionsTest
extends DrupalWebTestCase
{
2385 public static
function getInfo() {
2387 'name' => 'Shutdown functions',
2388 'description' => 'Functional tests for shutdown functions',
2389 'group' => 'System',
2394 parent
::setUp('system_test');
2398 * Test shutdown functions.
2400 function testShutdownFunctions() {
2401 $arg1 = $this->randomName();
2402 $arg2 = $this->randomName();
2403 $this->drupalGet('system-test/shutdown-functions/' .
$arg1 .
'/' .
$arg2);
2404 $this->assertText(t('First shutdown function, arg1 : @arg1, arg2: @arg2', array('@arg1' => $arg1, '@arg2' => $arg2)));
2405 $this->assertText(t('Second shutdown function, arg1 : @arg1, arg2: @arg2', array('@arg1' => $arg1, '@arg2' => $arg2)));
2407 // Make sure exceptions displayed through _drupal_render_exception_safe()
2408 // are correctly escaped.
2409 $this->assertRaw('Drupal is &lt;blink&gt;awesome&lt;/blink&gt;.');
2414 * Tests administrative overview pages.
2416 class SystemAdminTestCase
extends DrupalWebTestCase
{
2417 public static
function getInfo() {
2419 'name' => 'Administrative pages',
2420 'description' => 'Tests output on administrative pages and compact mode functionality.',
2421 'group' => 'System',
2426 // testAdminPages() requires Locale module.
2427 parent
::setUp(array('locale'));
2429 // Create an administrator with all permissions, as well as a regular user
2430 // who can only access administration pages and perform some Locale module
2431 // administrative tasks, but not all of them.
2432 $this->admin_user
= $this->drupalCreateUser(array_keys(module_invoke_all('permission')));
2433 $this->web_user
= $this->drupalCreateUser(array(
2434 'access administration pages',
2435 'translate interface',
2437 $this->drupalLogin($this->admin_user
);
2441 * Tests output on administrative listing pages.
2443 function testAdminPages() {
2444 // Go to Administration.
2445 $this->drupalGet('admin');
2447 // Verify that all visible, top-level administration links are listed on
2448 // the main administration page.
2449 foreach (menu_get_router() as
$path => $item) {
2450 if (strpos($path, 'admin/') === 0 && ($item['type'] & MENU_VISIBLE_IN_TREE
) && $item['_number_parts'] == 2) {
2451 $this->assertLink($item['title']);
2452 $this->assertLinkByHref($path);
2453 $this->assertText($item['description']);
2457 // For each administrative listing page on which the Locale module appears,
2458 // verify that there are links to the module's primary configuration pages,
2459 // but no links to its individual sub-configuration pages. Also verify that
2460 // a user with access to only some Locale module administration pages only
2461 // sees links to the pages they have access to.
2462 $admin_list_pages = array(
2465 'admin/config/regional',
2468 foreach ($admin_list_pages as
$page) {
2469 // For the administrator, verify that there are links to Locale's primary
2470 // configuration pages, but no links to individual sub-configuration
2472 $this->drupalLogin($this->admin_user
);
2473 $this->drupalGet($page);
2474 $this->assertLinkByHref('admin/config');
2475 $this->assertLinkByHref('admin/config/regional/settings');
2476 $this->assertLinkByHref('admin/config/regional/date-time');
2477 $this->assertLinkByHref('admin/config/regional/language');
2478 $this->assertNoLinkByHref('admin/config/regional/language/configure/session');
2479 $this->assertNoLinkByHref('admin/config/regional/language/configure/url');
2480 $this->assertLinkByHref('admin/config/regional/translate');
2481 // On admin/index only, the administrator should also see a "Configure
2482 // permissions" link for the Locale module.
2483 if ($page == 'admin/index') {
2484 $this->assertLinkByHref("admin/people/permissions#module-locale");
2487 // For a less privileged user, verify that there are no links to Locale's
2488 // primary configuration pages, but a link to the translate page exists.
2489 $this->drupalLogin($this->web_user
);
2490 $this->drupalGet($page);
2491 $this->assertLinkByHref('admin/config');
2492 $this->assertNoLinkByHref('admin/config/regional/settings');
2493 $this->assertNoLinkByHref('admin/config/regional/date-time');
2494 $this->assertNoLinkByHref('admin/config/regional/language');
2495 $this->assertNoLinkByHref('admin/config/regional/language/configure/session');
2496 $this->assertNoLinkByHref('admin/config/regional/language/configure/url');
2497 $this->assertLinkByHref('admin/config/regional/translate');
2498 // This user cannot configure permissions, so even on admin/index should
2499 // not see a "Configure permissions" link for the Locale module.
2500 if ($page == 'admin/index') {
2501 $this->assertNoLinkByHref("admin/people/permissions#module-locale");
2507 * Test compact mode.
2509 function testCompactMode() {
2510 $this->drupalGet('admin/compact/on');
2511 $this->assertTrue($this->cookies
['Drupal.visitor.admin_compact_mode']['value'], t('Compact mode turns on.'));
2512 $this->drupalGet('admin/compact/on');
2513 $this->assertTrue($this->cookies
['Drupal.visitor.admin_compact_mode']['value'], t('Compact mode remains on after a repeat call.'));
2514 $this->drupalGet('');
2515 $this->assertTrue($this->cookies
['Drupal.visitor.admin_compact_mode']['value'], t('Compact mode persists on new requests.'));
2517 $this->drupalGet('admin/compact/off');
2518 $this->assertEqual($this->cookies
['Drupal.visitor.admin_compact_mode']['value'], 'deleted', t('Compact mode turns off.'));
2519 $this->drupalGet('admin/compact/off');
2520 $this->assertEqual($this->cookies
['Drupal.visitor.admin_compact_mode']['value'], 'deleted', t('Compact mode remains off after a repeat call.'));
2521 $this->drupalGet('');
2522 $this->assertTrue($this->cookies
['Drupal.visitor.admin_compact_mode']['value'], t('Compact mode persists on new requests.'));
2527 * Tests authorize.php and related hooks.
2529 class SystemAuthorizeCase
extends DrupalWebTestCase
{
2530 public static
function getInfo() {
2532 'name' => 'Authorize API',
2533 'description' => 'Tests the authorize.php script and related API.',
2534 'group' => 'System',
2539 parent
::setUp(array('system_test'));
2541 variable_set('allow_authorize_operations', TRUE
);
2543 // Create an administrator user.
2544 $this->admin_user
= $this->drupalCreateUser(array('administer software updates'));
2545 $this->drupalLogin($this->admin_user
);
2549 * Helper function to initialize authorize.php and load it via drupalGet().
2551 * Initializing authorize.php needs to happen in the child Drupal
2552 * installation, not the parent. So, we visit a menu callback provided by
2553 * system_test.module which calls system_authorized_init() to initialize the
2554 * $_SESSION inside the test site, not the framework site. This callback
2555 * redirects to authorize.php when it's done initializing.
2557 * @see system_authorized_init().
2559 function drupalGetAuthorizePHP($page_title = 'system-test-auth') {
2560 $this->drupalGet('system-test/authorize-init/' .
$page_title);
2564 * Tests the FileTransfer hooks
2566 function testFileTransferHooks() {
2567 $page_title = $this->randomName(16);
2568 $this->drupalGetAuthorizePHP($page_title);
2569 $this->assertTitle(strtr('@title | Drupal', array('@title' => $page_title)), 'authorize.php page title is correct.');
2570 $this->assertNoText('It appears you have reached this page in error.');
2571 $this->assertText('To continue, provide your server connection details');
2572 // Make sure we see the new connection method added by system_test.
2573 $this->assertRaw('System Test FileTransfer');
2574 // Make sure the settings form callback works.
2575 $this->assertText('System Test Username');
2580 * Test the handling of requests containing 'index.php'.
2582 class SystemIndexPhpTest
extends DrupalWebTestCase
{
2583 public static
function getInfo() {
2585 'name' => 'Index.php handling',
2586 'description' => "Test the handling of requests containing 'index.php'.",
2587 'group' => 'System',
2596 * Test index.php handling.
2598 function testIndexPhpHandling() {
2599 $index_php = $GLOBALS['base_url'] .
'/index.php';
2601 $this->drupalGet($index_php, array('external' => TRUE
));
2602 $this->assertResponse(200, t('Make sure index.php returns a valid page.'));
2604 $this->drupalGet($index_php, array('external' => TRUE
, 'query' => array('q' => 'user')));
2605 $this->assertResponse(200, t('Make sure index.php?q=user returns a valid page.'));
2607 $this->drupalGet($index_php .
'/user', array('external' => TRUE
));
2608 $this->assertResponse(404, t("Make sure index.php/user returns a 'page not found'."));