Projet

Général

Profil

Paste
Télécharger (116 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / system / system.test @ 134c7813

1
<?php
2

    
3
/**
4
 * @file
5
 * Tests for system.module.
6
 */
7

    
8
/**
9
 * Helper class for module test cases.
10
 */
11
class ModuleTestCase extends DrupalWebTestCase {
12
  protected $admin_user;
13

    
14
  function setUp() {
15
    parent::setUp('system_test');
16

    
17
    $this->admin_user = $this->drupalCreateUser(array('access administration pages', 'administer modules'));
18
    $this->drupalLogin($this->admin_user);
19
  }
20

    
21
  /**
22
   * Assert there are tables that begin with the specified base table name.
23
   *
24
   * @param $base_table
25
   *   Beginning of table name to look for.
26
   * @param $count
27
   *   (optional) Whether or not to assert that there are tables that match the
28
   *   specified base table. Defaults to TRUE.
29
   */
30
  function assertTableCount($base_table, $count = TRUE) {
31
    $tables = db_find_tables(Database::getConnection()->prefixTables('{' . $base_table . '}') . '%');
32

    
33
    if ($count) {
34
      return $this->assertTrue($tables, format_string('Tables matching "@base_table" found.', array('@base_table' => $base_table)));
35
    }
36
    return $this->assertFalse($tables, format_string('Tables matching "@base_table" not found.', array('@base_table' => $base_table)));
37
  }
38

    
39
  /**
40
   * Assert that all tables defined in a module's hook_schema() exist.
41
   *
42
   * @param $module
43
   *   The name of the module.
44
   */
45
  function assertModuleTablesExist($module) {
46
    $tables = array_keys(drupal_get_schema_unprocessed($module));
47
    $tables_exist = TRUE;
48
    foreach ($tables as $table) {
49
      if (!db_table_exists($table)) {
50
        $tables_exist = FALSE;
51
      }
52
    }
53
    return $this->assertTrue($tables_exist, format_string('All database tables defined by the @module module exist.', array('@module' => $module)));
54
  }
55

    
56
  /**
57
   * Assert that none of the tables defined in a module's hook_schema() exist.
58
   *
59
   * @param $module
60
   *   The name of the module.
61
   */
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)) {
67
        $tables_exist = TRUE;
68
      }
69
    }
70
    return $this->assertFalse($tables_exist, format_string('None of the database tables defined by the @module module exist.', array('@module' => $module)));
71
  }
72

    
73
  /**
74
   * Assert the list of modules are enabled or disabled.
75
   *
76
   * @param $modules
77
   *   Module list to check.
78
   * @param $enabled
79
   *   Expected module state.
80
   */
81
  function assertModules(array $modules, $enabled) {
82
    module_list(TRUE);
83
    foreach ($modules as $module) {
84
      if ($enabled) {
85
        $message = 'Module "@module" is enabled.';
86
      }
87
      else {
88
        $message = 'Module "@module" is not enabled.';
89
      }
90
      $this->assertEqual(module_exists($module), $enabled, format_string($message, array('@module' => $module)));
91
    }
92
  }
93

    
94
  /**
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.
97
   *
98
   * @param $type
99
   *   The category to which this message belongs.
100
   * @param $message
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.
106
   * @param $variables
107
   *   Array of variables to replace in the message on display or
108
   *   NULL if message is already translated or not possible to
109
   *   translate.
110
   * @param $severity
111
   *   The severity of the message, as per RFC 3164.
112
   * @param $link
113
   *   A link to associate with the message.
114
   */
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)
122
      ->countQuery()
123
      ->execute()
124
      ->fetchField();
125
    $this->assertTrue($count > 0, format_string('watchdog table contains @count rows for @message', array('@count' => $count, '@message' => $message)));
126
  }
127
}
128

    
129
/**
130
 * Test module enabling/disabling functionality.
131
 */
132
class EnableDisableTestCase extends ModuleTestCase {
133
  protected $profile = 'testing';
134

    
135
  public static function getInfo() {
136
    return array(
137
      'name' => 'Enable/disable modules',
138
      'description' => 'Enable/disable core module and confirm table creation/deletion.',
139
      'group' => 'Module',
140
    );
141
  }
142

    
143
  /**
144
   * Test that all core modules can be enabled, disabled and uninstalled.
145
   */
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]);
153
      }
154
    }
155
    $this->assertTrue(count($modules), format_string('Found @count core modules that we can try to enable in this test.', array('@count' => count($modules))));
156

    
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;
161
   }
162

    
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);
166

    
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
169
    // them separately.
170
    $automatically_enabled = array();
171

    
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);
178

    
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
181
        // enabled.
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;
186
          }
187
        }
188

    
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);
194
        }
195

    
196
        // Install and enable the module.
197
        $edit = array();
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'));
204
        }
205
        $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
206

    
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
210
        // the logs.
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);
218
        }
219

    
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);
227
        }
228
      }
229
    }
230

    
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);
243
        }
244
      }
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.'));
250
        break;
251
      }
252
    }
253

    
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');
258
    }
259

    
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
263
    //   uninstalled.
264
    // - That enabling more than one module at the same time does not lead to
265
    //   any errors.
266
    $edit = array();
267
    foreach (array_keys($modules) as $name) {
268
      $edit['modules[Core][' . $name . '][enable]'] = $name;
269
    }
270
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
271
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
272
  }
273

    
274
  /**
275
   * Ensures entity info cache is updated after changes.
276
   */
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.');
281

    
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.');
288

    
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.');
293
  }
294

    
295
  /**
296
   * Tests entity info cache after enabling a module with a dependency on an entity providing module.
297
   *
298
   * @see entity_cache_test_watchdog()
299
   */
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.');
305
  }
306

    
307
  /**
308
   * Disables and uninstalls a module and asserts that it was done correctly.
309
   *
310
   * @param $module
311
   *   The name of the module to disable and uninstall.
312
   */
313
  function assertSuccessfulDisableAndUninstall($module) {
314
    // Disable the module.
315
    $edit = array();
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.'), 'Modules status has been updated.');
319
    $this->assertModules(array($module), FALSE);
320

    
321
    // Check that the appropriate hook was fired and the appropriate log
322
    // message appears.
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);
325

    
326
    //  Check that the module's database tables still exist.
327
    $this->assertModuleTablesExist($module);
328

    
329
    // Uninstall the module.
330
    $edit = array();
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.'), 'Modules status has been updated.');
335
    $this->assertModules(array($module), FALSE);
336

    
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
340
    // anymore.)
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);
344
    }
345

    
346
    // Check that the module's database tables no longer exist.
347
    $this->assertModuleTablesDoNotExist($module);
348
  }
349
}
350

    
351
/**
352
 * Tests failure of hook_requirements('install').
353
 */
354
class HookRequirementsTestCase extends ModuleTestCase {
355
  public static function getInfo() {
356
    return array(
357
      'name' => 'Requirements hook failure',
358
      'description' => "Attempts enabling a module that fails hook_requirements('install').",
359
      'group' => 'Module',
360
    );
361
  }
362

    
363
  /**
364
   * Assert that a module cannot be installed if it fails hook_requirements().
365
   */
366
  function testHookRequirementsFailure() {
367
    $this->assertModules(array('requirements1_test'), FALSE);
368

    
369
    // Attempt to install the requirements1_test module.
370
    $edit = array();
371
    $edit['modules[Testing][requirements1_test][enable]'] = 'requirements1_test';
372
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
373

    
374
    // Makes sure the module was NOT installed.
375
    $this->assertText(t('Requirements 1 Test failed requirements'), 'Modules status has been updated.');
376
    $this->assertModules(array('requirements1_test'), FALSE);
377
  }
378
}
379

    
380
/**
381
 * Test module dependency functionality.
382
 */
383
class ModuleDependencyTestCase extends ModuleTestCase {
384
  public static function getInfo() {
385
    return array(
386
      'name' => 'Module dependencies',
387
      'description' => 'Enable module without dependency enabled.',
388
      'group' => 'Module',
389
    );
390
  }
391

    
392
  /**
393
   * Checks functionality of project namespaces for dependencies.
394
   */
395
  function testProjectNamespaceForDependencies() {
396
    // Enable module with project namespace to ensure nothing breaks.
397
    $edit = array(
398
      'modules[Testing][system_project_namespace_test][enable]' => TRUE,
399
    );
400
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
401
    $this->assertModules(array('system_project_namespace_test'), TRUE);
402
  }
403

    
404
  /**
405
   * Attempt to enable translation module without locale enabled.
406
   */
407
  function testEnableWithoutDependency() {
408
    // Attempt to enable content translation without locale enabled.
409
    $edit = array();
410
    $edit['modules[Core][translation][enable]'] = 'translation';
411
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
412
    $this->assertText(t('Some required modules must be enabled'), 'Dependency required.');
413

    
414
    $this->assertModules(array('translation', 'locale'), FALSE);
415

    
416
    // Assert that the locale tables weren't enabled.
417
    $this->assertTableCount('languages', FALSE);
418
    $this->assertTableCount('locale', FALSE);
419

    
420
    $this->drupalPost(NULL, NULL, t('Continue'));
421
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
422

    
423
    $this->assertModules(array('translation', 'locale'), TRUE);
424

    
425
    // Assert that the locale tables were enabled.
426
    $this->assertTableCount('languages', TRUE);
427
    $this->assertTableCount('locale', TRUE);
428
  }
429

    
430
  /**
431
   * Attempt to enable a module with a missing dependency.
432
   */
433
  function testMissingModules() {
434
    // Test that the system_dependencies_test module is marked
435
    // as missing a dependency.
436
    $this->drupalGet('admin/modules');
437
    $this->assertRaw(t('@module (<span class="admin-missing">missing</span>)', array('@module' => drupal_ucfirst('_missing_dependency'))), 'A module with missing dependencies is marked as such.');
438
    $checkbox = $this->xpath('//input[@type="checkbox" and @disabled="disabled" and @name="modules[Testing][system_dependencies_test][enable]"]');
439
    $this->assert(count($checkbox) == 1, 'Checkbox for the module is disabled.');
440

    
441
    // Force enable the system_dependencies_test module.
442
    module_enable(array('system_dependencies_test'), FALSE);
443

    
444
    // Verify that the module is forced to be disabled when submitting
445
    // the module page.
446
    $this->drupalPost('admin/modules', array(), t('Save configuration'));
447
    $this->assertText(t('The @module module is missing, so the following module will be disabled: @depends.', array('@module' => '_missing_dependency', '@depends' => 'system_dependencies_test')), 'The module missing dependencies will be disabled.');
448

    
449
    // Confirm.
450
    $this->drupalPost(NULL, NULL, t('Continue'));
451

    
452
    // Verify that the module has been disabled.
453
    $this->assertModules(array('system_dependencies_test'), FALSE);
454
  }
455

    
456
  /**
457
   * Tests enabling a module that depends on an incompatible version of a module.
458
   */
459
  function testIncompatibleModuleVersionDependency() {
460
    // Test that the system_incompatible_module_version_dependencies_test is
461
    // marked as having an incompatible dependency.
462
    $this->drupalGet('admin/modules');
463
    $this->assertRaw(t('@module (<span class="admin-missing">incompatible with</span> version @version)', array(
464
      '@module' => 'System incompatible module version test (>2.0)',
465
      '@version' => '1.0',
466
    )), 'A module that depends on an incompatible version of a module is marked as such.');
467
    $checkbox = $this->xpath('//input[@type="checkbox" and @disabled="disabled" and @name="modules[Testing][system_incompatible_module_version_dependencies_test][enable]"]');
468
    $this->assert(count($checkbox) == 1, 'Checkbox for the module is disabled.');
469
  }
470

    
471
  /**
472
   * Tests enabling a module that depends on a module with an incompatible core version.
473
   */
474
  function testIncompatibleCoreVersionDependency() {
475
    // Test that the system_incompatible_core_version_dependencies_test is
476
    // marked as having an incompatible dependency.
477
    $this->drupalGet('admin/modules');
478
    $this->assertRaw(t('@module (<span class="admin-missing">incompatible with</span> this version of Drupal core)', array(
479
      '@module' => 'System incompatible core version test',
480
    )), 'A module that depends on a module with an incompatible core version is marked as such.');
481
    $checkbox = $this->xpath('//input[@type="checkbox" and @disabled="disabled" and @name="modules[Testing][system_incompatible_core_version_dependencies_test][enable]"]');
482
    $this->assert(count($checkbox) == 1, 'Checkbox for the module is disabled.');
483
  }
484

    
485
  /**
486
   * Tests enabling a module that depends on a module which fails hook_requirements().
487
   */
488
  function testEnableRequirementsFailureDependency() {
489
    $this->assertModules(array('requirements1_test'), FALSE);
490
    $this->assertModules(array('requirements2_test'), FALSE);
491

    
492
    // Attempt to install both modules at the same time.
493
    $edit = array();
494
    $edit['modules[Testing][requirements1_test][enable]'] = 'requirements1_test';
495
    $edit['modules[Testing][requirements2_test][enable]'] = 'requirements2_test';
496
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
497

    
498
    // Makes sure the modules were NOT installed.
499
    $this->assertText(t('Requirements 1 Test failed requirements'), 'Modules status has been updated.');
500
    $this->assertModules(array('requirements1_test'), FALSE);
501
    $this->assertModules(array('requirements2_test'), FALSE);
502

    
503
    // Makes sure that already enabled modules the failing modules depend on
504
    // were not disabled.
505
    $this->assertModules(array('comment'), TRUE);
506

    
507
  }
508

    
509
  /**
510
   * Tests that module dependencies are enabled in the correct order via the
511
   * UI. Dependencies should be enabled before their dependents.
512
   */
513
  function testModuleEnableOrder() {
514
    module_enable(array('module_test'), FALSE);
515
    $this->resetAll();
516
    $this->assertModules(array('module_test'), TRUE);
517
    variable_set('dependency_test', 'dependency');
518
    // module_test creates a dependency chain: forum depends on poll, which
519
    // depends on php. The correct enable order is, php, poll, forum.
520
    $expected_order = array('php', 'poll', 'forum');
521

    
522
    // Enable the modules through the UI, verifying that the dependency chain
523
    // is correct.
524
    $edit = array();
525
    $edit['modules[Core][forum][enable]'] = 'forum';
526
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
527
    $this->assertModules(array('forum'), FALSE);
528
    $this->assertText(t('You must enable the Poll, PHP filter modules to install Forum.'), t('Dependency chain created.'));
529
    $edit['modules[Core][poll][enable]'] = 'poll';
530
    $edit['modules[Core][php][enable]'] = 'php';
531
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
532
    $this->assertModules(array('forum', 'poll', 'php'), TRUE);
533

    
534
    // Check the actual order which is saved by module_test_modules_enabled().
535
    $this->assertIdentical(variable_get('test_module_enable_order', FALSE), $expected_order, t('Modules enabled in the correct order.'));
536
  }
537

    
538
  /**
539
   * Tests attempting to uninstall a module that has installed dependents.
540
   */
541
  function testUninstallDependents() {
542
    // Enable the forum module.
543
    $edit = array('modules[Core][forum][enable]' => 'forum');
544
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
545
    $this->assertModules(array('forum'), TRUE);
546

    
547
    // Disable forum and comment. Both should now be installed but disabled.
548
    $edit = array('modules[Core][forum][enable]' => FALSE);
549
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
550
    $this->assertModules(array('forum'), FALSE);
551
    $edit = array('modules[Core][comment][enable]' => FALSE);
552
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
553
    $this->assertModules(array('comment'), FALSE);
554

    
555
    // Check that the taxonomy module cannot be uninstalled.
556
    $this->drupalGet('admin/modules/uninstall');
557
    $checkbox = $this->xpath('//input[@type="checkbox" and @disabled="disabled" and @name="uninstall[comment]"]');
558
    $this->assert(count($checkbox) == 1, 'Checkbox for uninstalling the comment module is disabled.');
559

    
560
    // Uninstall the forum module, and check that taxonomy now can also be
561
    // uninstalled.
562
    $edit = array('uninstall[forum]' => 'forum');
563
    $this->drupalPost('admin/modules/uninstall', $edit, t('Uninstall'));
564
    $this->drupalPost(NULL, NULL, t('Uninstall'));
565
    $this->assertText(t('The selected modules have been uninstalled.'), 'Modules status has been updated.');
566
    $edit = array('uninstall[comment]' => 'comment');
567
    $this->drupalPost('admin/modules/uninstall', $edit, t('Uninstall'));
568
    $this->drupalPost(NULL, NULL, t('Uninstall'));
569
    $this->assertText(t('The selected modules have been uninstalled.'), 'Modules status has been updated.');
570
  }
571

    
572
  /**
573
   * Tests whether the correct module metadata is returned.
574
   */
575
  function testModuleMetaData() {
576
    // Generate the list of available modules.
577
    $modules = system_rebuild_module_data();
578
    // Check that the mtime field exists for the system module.
579
    $this->assertTrue(!empty($modules['system']->info['mtime']), 'The system.info file modification time field is present.');
580
    // Use 0 if mtime isn't present, to avoid an array index notice.
581
    $test_mtime = !empty($modules['system']->info['mtime']) ? $modules['system']->info['mtime'] : 0;
582
    // Ensure the mtime field contains a number that is greater than zero.
583
    $this->assertTrue(is_numeric($test_mtime) && ($test_mtime > 0), 'The system.info file modification time field contains a timestamp.');
584
  }
585

    
586
  /**
587
   * Tests whether the correct theme metadata is returned.
588
   */
589
  function testThemeMetaData() {
590
    // Generate the list of available themes.
591
    $themes = system_rebuild_theme_data();
592
    // Check that the mtime field exists for the bartik theme.
593
    $this->assertTrue(!empty($themes['bartik']->info['mtime']), 'The bartik.info file modification time field is present.');
594
    // Use 0 if mtime isn't present, to avoid an array index notice.
595
    $test_mtime = !empty($themes['bartik']->info['mtime']) ? $themes['bartik']->info['mtime'] : 0;
596
    // Ensure the mtime field contains a number that is greater than zero.
597
    $this->assertTrue(is_numeric($test_mtime) && ($test_mtime > 0), 'The bartik.info file modification time field contains a timestamp.');
598
  }
599
}
600

    
601
/**
602
 * Test module dependency on specific versions.
603
 */
604
class ModuleVersionTestCase extends ModuleTestCase {
605
  public static function getInfo() {
606
    return array(
607
      'name' => 'Module versions',
608
      'description' => 'Check module version dependencies.',
609
      'group' => 'Module',
610
    );
611
  }
612

    
613
  function setUp() {
614
    parent::setUp('module_test');
615
  }
616

    
617
  /**
618
   * Test version dependencies.
619
   */
620
  function testModuleVersions() {
621
    $dependencies = array(
622
      // Alternating between being compatible and incompatible with 7.x-2.4-beta3.
623
      // The first is always a compatible.
624
      'common_test',
625
      // Branch incompatibility.
626
      'common_test (1.x)',
627
      // Branch compatibility.
628
      'common_test (2.x)',
629
      // Another branch incompatibility.
630
      'common_test (>2.x)',
631
      // Another branch compatibility.
632
      'common_test (<=2.x)',
633
      // Another branch incompatibility.
634
      'common_test (<2.x)',
635
      // Another branch compatibility.
636
      'common_test (>=2.x)',
637
      // Nonsense, misses a dash. Incompatible with everything.
638
      'common_test (=7.x2.x, >=2.4)',
639
      // Core version is optional. Compatible.
640
      'common_test (=7.x-2.x, >=2.4-alpha2)',
641
      // Test !=, explicitly incompatible.
642
      'common_test (=2.x, !=2.4-beta3)',
643
      // Three operations. Compatible.
644
      'common_test (=2.x, !=2.3, <2.5)',
645
      // Testing extra version. Incompatible.
646
      'common_test (<=2.4-beta2)',
647
      // Testing extra version. Compatible.
648
      'common_test (>2.4-beta2)',
649
      // Testing extra version. Incompatible.
650
      'common_test (>2.4-rc0)',
651
    );
652
    variable_set('dependencies', $dependencies);
653
    $n = count($dependencies);
654
    for ($i = 0; $i < $n; $i++) {
655
      $this->drupalGet('admin/modules');
656
      $checkbox = $this->xpath('//input[@id="edit-modules-testing-module-test-enable"]');
657
      $this->assertEqual(!empty($checkbox[0]['disabled']), $i % 2, $dependencies[$i]);
658
    }
659
  }
660
}
661

    
662
/**
663
 * Test required modules functionality.
664
 */
665
class ModuleRequiredTestCase extends ModuleTestCase {
666
  public static function getInfo() {
667
    return array(
668
      'name' => 'Required modules',
669
      'description' => 'Attempt disabling of required modules.',
670
      'group' => 'Module',
671
    );
672
  }
673

    
674
  /**
675
   * Assert that core required modules cannot be disabled.
676
   */
677
  function testDisableRequired() {
678
    $module_info = system_get_info('module');
679
    $this->drupalGet('admin/modules');
680
    foreach ($module_info as $module => $info) {
681
      // Check to make sure the checkbox for each required module is disabled
682
      // and checked (or absent from the page if the module is also hidden).
683
      if (!empty($info['required'])) {
684
        $field_name = "modules[{$info['package']}][$module][enable]";
685
        if (empty($info['hidden'])) {
686
          $this->assertFieldByXPath("//input[@name='$field_name' and @disabled='disabled' and @checked='checked']", '', format_string('Field @name was disabled and checked.', array('@name' => $field_name)));
687
        }
688
        else {
689
          $this->assertNoFieldByName($field_name);
690
        }
691
      }
692
    }
693
  }
694
}
695

    
696
class IPAddressBlockingTestCase extends DrupalWebTestCase {
697
  protected $blocking_user;
698

    
699
  /**
700
   * Implement getInfo().
701
   */
702
  public static function getInfo() {
703
    return array(
704
      'name' => 'IP address blocking',
705
      'description' => 'Test IP address blocking.',
706
      'group' => 'System'
707
    );
708
  }
709

    
710
  /**
711
   * Implement setUp().
712
   */
713
  function setUp() {
714
    parent::setUp();
715

    
716
    // Create user.
717
    $this->blocking_user = $this->drupalCreateUser(array('block IP addresses'));
718
    $this->drupalLogin($this->blocking_user);
719
  }
720

    
721
  /**
722
   * Test a variety of user input to confirm correct validation and saving of data.
723
   */
724
  function testIPAddressValidation() {
725
    $this->drupalGet('admin/config/people/ip-blocking');
726

    
727
    // Block a valid IP address.
728
    $edit = array();
729
    $edit['ip'] = '192.168.1.1';
730
    $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
731
    $ip = db_query("SELECT iid from {blocked_ips} WHERE ip = :ip", array(':ip' => $edit['ip']))->fetchField();
732
    $this->assertTrue($ip, t('IP address found in database.'));
733
    $this->assertRaw(t('The IP address %ip has been blocked.', array('%ip' => $edit['ip'])), t('IP address was blocked.'));
734

    
735
    // Try to block an IP address that's already blocked.
736
    $edit = array();
737
    $edit['ip'] = '192.168.1.1';
738
    $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
739
    $this->assertText(t('This IP address is already blocked.'));
740

    
741
    // Try to block a reserved IP address.
742
    $edit = array();
743
    $edit['ip'] = '255.255.255.255';
744
    $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
745
    $this->assertText(t('Enter a valid IP address.'));
746

    
747
    // Try to block a reserved IP address.
748
    $edit = array();
749
    $edit['ip'] = 'test.example.com';
750
    $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
751
    $this->assertText(t('Enter a valid IP address.'));
752

    
753
    // Submit an empty form.
754
    $edit = array();
755
    $edit['ip'] = '';
756
    $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
757
    $this->assertText(t('Enter a valid IP address.'));
758

    
759
    // Pass an IP address as a URL parameter and submit it.
760
    $submit_ip = '1.2.3.4';
761
    $this->drupalPost('admin/config/people/ip-blocking/' . $submit_ip, NULL, t('Add'));
762
    $ip = db_query("SELECT iid from {blocked_ips} WHERE ip = :ip", array(':ip' => $submit_ip))->fetchField();
763
    $this->assertTrue($ip, t('IP address found in database'));
764
    $this->assertRaw(t('The IP address %ip has been blocked.', array('%ip' => $submit_ip)), t('IP address was blocked.'));
765

    
766
    // Submit your own IP address. This fails, although it works when testing manually.
767
     // TODO: on some systems this test fails due to a bug or inconsistency in cURL.
768
     // $edit = array();
769
     // $edit['ip'] = ip_address();
770
     // $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Save'));
771
     // $this->assertText(t('You may not block your own IP address.'));
772
  }
773
}
774

    
775
class CronRunTestCase extends DrupalWebTestCase {
776
  /**
777
   * Implement getInfo().
778
   */
779
  public static function getInfo() {
780
    return array(
781
      'name' => 'Cron run',
782
      'description' => 'Test cron run.',
783
      'group' => 'System'
784
    );
785
  }
786

    
787
  function setUp() {
788
    parent::setUp(array('common_test', 'common_test_cron_helper'));
789
  }
790

    
791
  /**
792
   * Test cron runs.
793
   */
794
  function testCronRun() {
795
    global $base_url;
796

    
797
    // Run cron anonymously without any cron key.
798
    $this->drupalGet($base_url . '/cron.php', array('external' => TRUE));
799
    $this->assertResponse(403);
800

    
801
    // Run cron anonymously with a random cron key.
802
    $key = $this->randomName(16);
803
    $this->drupalGet($base_url . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => $key)));
804
    $this->assertResponse(403);
805

    
806
    // Run cron anonymously with the valid cron key.
807
    $key = variable_get('cron_key', 'drupal');
808
    $this->drupalGet($base_url . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => $key)));
809
    $this->assertResponse(200);
810
  }
811

    
812
  /**
813
   * Ensure that the automatic cron run feature is working.
814
   *
815
   * In these tests we do not use REQUEST_TIME to track start time, because we
816
   * need the exact time when cron is triggered.
817
   */
818
  function testAutomaticCron() {
819
    // Ensure cron does not run when the cron threshold is enabled and was
820
    // not passed.
821
    $cron_last = time();
822
    $cron_safe_threshold = 100;
823
    variable_set('cron_last', $cron_last);
824
    variable_set('cron_safe_threshold', $cron_safe_threshold);
825
    $this->drupalGet('');
826
    $this->assertTrue($cron_last == variable_get('cron_last', NULL), 'Cron does not run when the cron threshold is not passed.');
827

    
828
    // Test if cron runs when the cron threshold was passed.
829
    $cron_last = time() - 200;
830
    variable_set('cron_last', $cron_last);
831
    $this->drupalGet('');
832
    sleep(1);
833
    $this->assertTrue($cron_last < variable_get('cron_last', NULL), 'Cron runs when the cron threshold is passed.');
834

    
835
    // Disable the cron threshold through the interface.
836
    $admin_user = $this->drupalCreateUser(array('administer site configuration'));
837
    $this->drupalLogin($admin_user);
838
    $this->drupalPost('admin/config/system/cron', array('cron_safe_threshold' => 0), t('Save configuration'));
839
    $this->assertText(t('The configuration options have been saved.'));
840
    $this->drupalLogout();
841

    
842
    // Test if cron does not run when the cron threshold is disabled.
843
    $cron_last = time() - 200;
844
    variable_set('cron_last', $cron_last);
845
    $this->drupalGet('');
846
    $this->assertTrue($cron_last == variable_get('cron_last', NULL), 'Cron does not run when the cron threshold is disabled.');
847
  }
848

    
849
  /**
850
   * Ensure that temporary files are removed.
851
   *
852
   * Create files for all the possible combinations of age and status. We are
853
   * using UPDATE statements rather than file_save() because it would set the
854
   * timestamp.
855
   */
856
  function testTempFileCleanup() {
857
    // Temporary file that is older than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
858
    $temp_old = file_save_data('');
859
    db_update('file_managed')
860
      ->fields(array(
861
        'status' => 0,
862
        'timestamp' => 1,
863
      ))
864
      ->condition('fid', $temp_old->fid)
865
      ->execute();
866
    $this->assertTrue(file_exists($temp_old->uri), 'Old temp file was created correctly.');
867

    
868
    // Temporary file that is less than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
869
    $temp_new = file_save_data('');
870
    db_update('file_managed')
871
      ->fields(array('status' => 0))
872
      ->condition('fid', $temp_new->fid)
873
      ->execute();
874
    $this->assertTrue(file_exists($temp_new->uri), 'New temp file was created correctly.');
875

    
876
    // Permanent file that is older than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
877
    $perm_old = file_save_data('');
878
    db_update('file_managed')
879
      ->fields(array('timestamp' => 1))
880
      ->condition('fid', $temp_old->fid)
881
      ->execute();
882
    $this->assertTrue(file_exists($perm_old->uri), 'Old permanent file was created correctly.');
883

    
884
    // Permanent file that is newer than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
885
    $perm_new = file_save_data('');
886
    $this->assertTrue(file_exists($perm_new->uri), 'New permanent file was created correctly.');
887

    
888
    // Run cron and then ensure that only the old, temp file was deleted.
889
    $this->cronRun();
890
    $this->assertFalse(file_exists($temp_old->uri), 'Old temp file was correctly removed.');
891
    $this->assertTrue(file_exists($temp_new->uri), 'New temp file was correctly ignored.');
892
    $this->assertTrue(file_exists($perm_old->uri), 'Old permanent file was correctly ignored.');
893
    $this->assertTrue(file_exists($perm_new->uri), 'New permanent file was correctly ignored.');
894
  }
895

    
896
  /**
897
   * Make sure exceptions thrown on hook_cron() don't affect other modules.
898
   */
899
  function testCronExceptions() {
900
    variable_del('common_test_cron');
901
    // The common_test module throws an exception. If it isn't caught, the tests
902
    // won't finish successfully.
903
    // The common_test_cron_helper module sets the 'common_test_cron' variable.
904
    $this->cronRun();
905
    $result = variable_get('common_test_cron');
906
    $this->assertEqual($result, 'success', 'Cron correctly handles exceptions thrown during hook_cron() invocations.');
907
  }
908

    
909
  /**
910
   * Tests that hook_flush_caches() is not invoked on every single cron run.
911
   *
912
   * @see system_cron()
913
   */
914
  public function testCronCacheExpiration() {
915
    module_enable(array('system_cron_test'));
916
    variable_del('system_cron_test_flush_caches');
917

    
918
    // Invoke cron the first time: hook_flush_caches() should be called and then
919
    // get cached.
920
    drupal_cron_run();
921
    $this->assertEqual(variable_get('system_cron_test_flush_caches'), 1, 'hook_flush_caches() was invoked the first time.');
922
    $cache = cache_get('system_cache_tables');
923
    $this->assertEqual(empty($cache), FALSE, 'Cache is filled with cache table data.');
924

    
925
    // Run cron again and ensure that hook_flush_caches() is not called.
926
    variable_del('system_cron_test_flush_caches');
927
    drupal_cron_run();
928
    $this->assertNull(variable_get('system_cron_test_flush_caches'), 'hook_flush_caches() was not invoked the second time.');
929
  }
930

    
931
}
932

    
933
/**
934
 * Test execution of the cron queue.
935
 */
936
class CronQueueTestCase extends DrupalWebTestCase {
937
  /**
938
   * Implement getInfo().
939
   */
940
  public static function getInfo() {
941
    return array(
942
      'name' => 'Cron queue functionality',
943
      'description' => 'Tests the cron queue runner.',
944
      'group' => 'System'
945
    );
946
  }
947

    
948
  function setUp() {
949
    parent::setUp(array('common_test', 'common_test_cron_helper', 'cron_queue_test'));
950
  }
951

    
952
  /**
953
   * Tests that exceptions thrown by workers are handled properly.
954
   */
955
  function testExceptions() {
956
    $queue = DrupalQueue::get('cron_queue_test_exception');
957

    
958
    // Enqueue an item for processing.
959
    $queue->createItem(array($this->randomName() => $this->randomName()));
960

    
961
    // Run cron; the worker for this queue should throw an exception and handle
962
    // it.
963
    $this->cronRun();
964

    
965
    // The item should be left in the queue.
966
    $this->assertEqual($queue->numberOfItems(), 1, 'Failing item still in the queue after throwing an exception.');
967
  }
968

    
969
  /**
970
   * Tests worker defined as a class method callable.
971
   */
972
  function testCallable() {
973
    $queue = DrupalQueue::get('cron_queue_test_callback');
974

    
975
    // Enqueue an item for processing.
976
    $queue->createItem(array($this->randomName() => $this->randomName()));
977

    
978
    // Run cron; the worker should perform the task and delete the item from the
979
    // queue.
980
    $this->cronRun();
981

    
982
    // The queue should be empty.
983
    $this->assertEqual($queue->numberOfItems(), 0);
984
  }
985

    
986
}
987

    
988
class AdminMetaTagTestCase extends DrupalWebTestCase {
989
  /**
990
   * Implement getInfo().
991
   */
992
  public static function getInfo() {
993
    return array(
994
      'name' => 'Fingerprinting meta tag',
995
      'description' => 'Confirm that the fingerprinting meta tag appears as expected.',
996
      'group' => 'System'
997
    );
998
  }
999

    
1000
  /**
1001
   * Verify that the meta tag HTML is generated correctly.
1002
   */
1003
  public function testMetaTag() {
1004
    list($version, ) = explode('.', VERSION);
1005
    $string = '<meta name="Generator" content="Drupal ' . $version . ' (http://drupal.org)" />';
1006
    $this->drupalGet('node');
1007
    $this->assertRaw($string, 'Fingerprinting meta tag generated correctly.', 'System');
1008
  }
1009
}
1010

    
1011
/**
1012
 * Tests custom access denied functionality.
1013
 */
1014
class AccessDeniedTestCase extends DrupalWebTestCase {
1015
  protected $admin_user;
1016

    
1017
  public static function getInfo() {
1018
    return array(
1019
      'name' => '403 functionality',
1020
      'description' => 'Tests page access denied functionality, including custom 403 pages.',
1021
      'group' => 'System'
1022
    );
1023
  }
1024

    
1025
  function setUp() {
1026
    parent::setUp();
1027

    
1028
    // Create an administrative user.
1029
    $this->admin_user = $this->drupalCreateUser(array('access administration pages', 'administer site configuration', 'administer blocks'));
1030
  }
1031

    
1032
  function testAccessDenied() {
1033
    $this->drupalGet('admin');
1034
    $this->assertText(t('Access denied'), 'Found the default 403 page');
1035
    $this->assertResponse(403);
1036

    
1037
    $this->drupalLogin($this->admin_user);
1038
    $edit = array(
1039
      'title' => $this->randomName(10),
1040
      'body' => array(LANGUAGE_NONE => array(array('value' => $this->randomName(100)))),
1041
    );
1042
    $node = $this->drupalCreateNode($edit);
1043

    
1044
    // Use a custom 403 page.
1045
    $this->drupalPost('admin/config/system/site-information', array('site_403' => 'node/' . $node->nid), t('Save configuration'));
1046

    
1047
    $this->drupalLogout();
1048
    $this->drupalGet('admin');
1049
    $this->assertText($node->title, 'Found the custom 403 page');
1050

    
1051
    // Logout and check that the user login block is shown on custom 403 pages.
1052
    $this->drupalLogout();
1053

    
1054
    $this->drupalGet('admin');
1055
    $this->assertText($node->title, 'Found the custom 403 page');
1056
    $this->assertText(t('User login'), 'Blocks are shown on the custom 403 page');
1057

    
1058
    // Log back in and remove the custom 403 page.
1059
    $this->drupalLogin($this->admin_user);
1060
    $this->drupalPost('admin/config/system/site-information', array('site_403' => ''), t('Save configuration'));
1061

    
1062
    // Logout and check that the user login block is shown on default 403 pages.
1063
    $this->drupalLogout();
1064

    
1065
    $this->drupalGet('admin');
1066
    $this->assertText(t('Access denied'), 'Found the default 403 page');
1067
    $this->assertResponse(403);
1068
    $this->assertText(t('User login'), 'Blocks are shown on the default 403 page');
1069

    
1070
    // Log back in, set the custom 403 page to /user and remove the block
1071
    $this->drupalLogin($this->admin_user);
1072
    variable_set('site_403', 'user');
1073
    $this->drupalPost('admin/structure/block', array('blocks[user_login][region]' => '-1'), t('Save blocks'));
1074

    
1075
    // Check that we can log in from the 403 page.
1076
    $this->drupalLogout();
1077
    $edit = array(
1078
      'name' => $this->admin_user->name,
1079
      'pass' => $this->admin_user->pass_raw,
1080
    );
1081
    $this->drupalPost('admin/config/system/site-information', $edit, t('Log in'));
1082

    
1083
    // Check that we're still on the same page.
1084
    $this->assertText(t('Site information'));
1085
  }
1086
}
1087

    
1088
class PageNotFoundTestCase extends DrupalWebTestCase {
1089
  protected $admin_user;
1090

    
1091
  /**
1092
   * Implement getInfo().
1093
   */
1094
  public static function getInfo() {
1095
    return array(
1096
      'name' => '404 functionality',
1097
      'description' => "Tests page not found functionality, including custom 404 pages.",
1098
      'group' => 'System'
1099
    );
1100
  }
1101

    
1102
  /**
1103
   * Implement setUp().
1104
   */
1105
  function setUp() {
1106
    parent::setUp();
1107

    
1108
    // Create an administrative user.
1109
    $this->admin_user = $this->drupalCreateUser(array('administer site configuration'));
1110
    $this->drupalLogin($this->admin_user);
1111
  }
1112

    
1113
  function testPageNotFound() {
1114
    $this->drupalGet($this->randomName(10));
1115
    $this->assertText(t('Page not found'), 'Found the default 404 page');
1116

    
1117
    $edit = array(
1118
      'title' => $this->randomName(10),
1119
      'body' => array(LANGUAGE_NONE => array(array('value' => $this->randomName(100)))),
1120
    );
1121
    $node = $this->drupalCreateNode($edit);
1122

    
1123
    // As node IDs must be integers, make sure requests for non-integer IDs
1124
    // return a page not found error.
1125
    $this->drupalGet('node/invalid');
1126
    $this->assertResponse(404);
1127

    
1128
    // Use a custom 404 page.
1129
    $this->drupalPost('admin/config/system/site-information', array('site_404' => 'node/' . $node->nid), t('Save configuration'));
1130

    
1131
    $this->drupalGet($this->randomName(10));
1132
    $this->assertText($node->title, 'Found the custom 404 page');
1133
  }
1134
}
1135

    
1136
/**
1137
 * Tests site maintenance functionality.
1138
 */
1139
class SiteMaintenanceTestCase extends DrupalWebTestCase {
1140
  protected $admin_user;
1141

    
1142
  public static function getInfo() {
1143
    return array(
1144
      'name' => 'Site maintenance mode functionality',
1145
      'description' => 'Test access to site while in maintenance mode.',
1146
      'group' => 'System',
1147
    );
1148
  }
1149

    
1150
  function setUp() {
1151
    parent::setUp();
1152

    
1153
    // Create a user allowed to access site in maintenance mode.
1154
    $this->user = $this->drupalCreateUser(array('access site in maintenance mode'));
1155
    // Create an administrative user.
1156
    $this->admin_user = $this->drupalCreateUser(array('administer site configuration', 'access site in maintenance mode'));
1157
    $this->drupalLogin($this->admin_user);
1158
  }
1159

    
1160
  /**
1161
   * Verify site maintenance mode functionality.
1162
   */
1163
  function testSiteMaintenance() {
1164
    // Turn on maintenance mode.
1165
    $edit = array(
1166
      'maintenance_mode' => 1,
1167
    );
1168
    $this->drupalPost('admin/config/development/maintenance', $edit, t('Save configuration'));
1169

    
1170
    $admin_message = t('Operating in maintenance mode. <a href="@url">Go online.</a>', array('@url' => url('admin/config/development/maintenance')));
1171
    $user_message = t('Operating in maintenance mode.');
1172
    $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')));
1173

    
1174
    $this->drupalGet('');
1175
    $this->assertRaw($admin_message, 'Found the site maintenance mode message.');
1176

    
1177
    // Logout and verify that offline message is displayed.
1178
    $this->drupalLogout();
1179
    $this->drupalGet('');
1180
    $this->assertText($offline_message);
1181
    $this->drupalGet('node');
1182
    $this->assertText($offline_message);
1183
    $this->drupalGet('user/register');
1184
    $this->assertText($offline_message);
1185

    
1186
    // Verify that user is able to log in.
1187
    $this->drupalGet('user');
1188
    $this->assertNoText($offline_message);
1189
    $this->drupalGet('user/login');
1190
    $this->assertNoText($offline_message);
1191

    
1192
    // Log in user and verify that maintenance mode message is displayed
1193
    // directly after login.
1194
    $edit = array(
1195
      'name' => $this->user->name,
1196
      'pass' => $this->user->pass_raw,
1197
    );
1198
    $this->drupalPost(NULL, $edit, t('Log in'));
1199
    $this->assertText($user_message);
1200

    
1201
    // Log in administrative user and configure a custom site offline message.
1202
    $this->drupalLogout();
1203
    $this->drupalLogin($this->admin_user);
1204
    $this->drupalGet('admin/config/development/maintenance');
1205
    $this->assertNoRaw($admin_message, 'Site maintenance mode message not displayed.');
1206

    
1207
    $offline_message = 'Sorry, not online.';
1208
    $edit = array(
1209
      'maintenance_mode_message' => $offline_message,
1210
    );
1211
    $this->drupalPost(NULL, $edit, t('Save configuration'));
1212

    
1213
    // Logout and verify that custom site offline message is displayed.
1214
    $this->drupalLogout();
1215
    $this->drupalGet('');
1216
    $this->assertRaw($offline_message, 'Found the site offline message.');
1217

    
1218
    // Verify that custom site offline message is not displayed on user/password.
1219
    $this->drupalGet('user/password');
1220
    $this->assertText(t('Username or e-mail address'), 'Anonymous users can access user/password');
1221

    
1222
    // Submit password reset form.
1223
    $edit = array(
1224
      'name' => $this->user->name,
1225
    );
1226
    $this->drupalPost('user/password', $edit, t('E-mail new password'));
1227
    $mails = $this->drupalGetMails();
1228
    $start = strpos($mails[0]['body'], 'user/reset/'. $this->user->uid);
1229
    $path = substr($mails[0]['body'], $start, 66 + strlen($this->user->uid));
1230

    
1231
    // Log in with temporary login link.
1232
    $this->drupalPost($path, array(), t('Log in'));
1233
    $this->assertText($user_message);
1234
  }
1235
}
1236

    
1237
/**
1238
 * Tests generic date and time handling capabilities of Drupal.
1239
 */
1240
class DateTimeFunctionalTest extends DrupalWebTestCase {
1241
  public static function getInfo() {
1242
    return array(
1243
      'name' => 'Date and time',
1244
      'description' => 'Configure date and time settings. Test date formatting and time zone handling, including daylight saving time.',
1245
      'group' => 'System',
1246
    );
1247
  }
1248

    
1249
  function setUp() {
1250
    parent::setUp(array('locale'));
1251

    
1252
    // Create admin user and log in admin user.
1253
    $this->admin_user = $this->drupalCreateUser(array('administer site configuration'));
1254
    $this->drupalLogin($this->admin_user);
1255
  }
1256

    
1257

    
1258
  /**
1259
   * Test time zones and DST handling.
1260
   */
1261
  function testTimeZoneHandling() {
1262
    // Setup date/time settings for Honolulu time.
1263
    variable_set('date_default_timezone', 'Pacific/Honolulu');
1264
    variable_set('configurable_timezones', 0);
1265
    variable_set('date_format_medium', 'Y-m-d H:i:s O');
1266

    
1267
    // Create some nodes with different authored-on dates.
1268
    $date1 = '2007-01-31 21:00:00 -1000';
1269
    $date2 = '2007-07-31 21:00:00 -1000';
1270
    $node1 = $this->drupalCreateNode(array('created' => strtotime($date1), 'type' => 'article'));
1271
    $node2 = $this->drupalCreateNode(array('created' => strtotime($date2), 'type' => 'article'));
1272

    
1273
    // Confirm date format and time zone.
1274
    $this->drupalGet("node/$node1->nid");
1275
    $this->assertText('2007-01-31 21:00:00 -1000', 'Date should be identical, with GMT offset of -10 hours.');
1276
    $this->drupalGet("node/$node2->nid");
1277
    $this->assertText('2007-07-31 21:00:00 -1000', 'Date should be identical, with GMT offset of -10 hours.');
1278

    
1279
    // Set time zone to Los Angeles time.
1280
    variable_set('date_default_timezone', 'America/Los_Angeles');
1281

    
1282
    // Confirm date format and time zone.
1283
    $this->drupalGet("node/$node1->nid");
1284
    $this->assertText('2007-01-31 23:00:00 -0800', 'Date should be two hours ahead, with GMT offset of -8 hours.');
1285
    $this->drupalGet("node/$node2->nid");
1286
    $this->assertText('2007-08-01 00:00:00 -0700', 'Date should be three hours ahead, with GMT offset of -7 hours.');
1287
  }
1288

    
1289
  /**
1290
   * Test date type configuration.
1291
   */
1292
  function testDateTypeConfiguration() {
1293
    // Confirm system date types appear.
1294
    $this->drupalGet('admin/config/regional/date-time');
1295
    $this->assertText(t('Medium'), 'System date types appear in date type list.');
1296
    $this->assertNoRaw('href="/admin/config/regional/date-time/types/medium/delete"', 'No delete link appear for system date types.');
1297

    
1298
    // Add custom date type.
1299
    $this->clickLink(t('Add date type'));
1300
    $date_type = strtolower($this->randomName(8));
1301
    $machine_name = 'machine_' . $date_type;
1302
    $date_format = 'd.m.Y - H:i';
1303
    $edit = array(
1304
      'date_type' => $date_type,
1305
      'machine_name' => $machine_name,
1306
      'date_format' => $date_format,
1307
    );
1308
    $this->drupalPost('admin/config/regional/date-time/types/add', $edit, t('Add date type'));
1309
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time', array('absolute' => TRUE)), 'Correct page redirection.');
1310
    $this->assertText(t('New date type added successfully.'), 'Date type added confirmation message appears.');
1311
    $this->assertText($date_type, 'Custom date type appears in the date type list.');
1312
    $this->assertText(t('delete'), 'Delete link for custom date type appears.');
1313

    
1314
    // Delete custom date type.
1315
    $this->clickLink(t('delete'));
1316
    $this->drupalPost('admin/config/regional/date-time/types/' . $machine_name . '/delete', array(), t('Remove'));
1317
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time', array('absolute' => TRUE)), 'Correct page redirection.');
1318
    $this->assertText(t('Removed date type ' . $date_type), 'Custom date type removed.');
1319
  }
1320

    
1321
  /**
1322
   * Test date format configuration.
1323
   */
1324
  function testDateFormatConfiguration() {
1325
    // Confirm 'no custom date formats available' message appears.
1326
    $this->drupalGet('admin/config/regional/date-time/formats');
1327
    $this->assertText(t('No custom date formats available.'), 'No custom date formats message appears.');
1328

    
1329
    // Add custom date format.
1330
    $this->clickLink(t('Add format'));
1331
    $edit = array(
1332
      'date_format' => 'Y',
1333
    );
1334
    $this->drupalPost('admin/config/regional/date-time/formats/add', $edit, t('Add format'));
1335
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE)), 'Correct page redirection.');
1336
    $this->assertNoText(t('No custom date formats available.'), 'No custom date formats message does not appear.');
1337
    $this->assertText(t('Custom date format added.'), 'Custom date format added.');
1338

    
1339
    // Ensure custom date format appears in date type configuration options.
1340
    $this->drupalGet('admin/config/regional/date-time');
1341
    $this->assertRaw('<option value="Y">', 'Custom date format appears in options.');
1342

    
1343
    // Edit custom date format.
1344
    $this->drupalGet('admin/config/regional/date-time/formats');
1345
    $this->clickLink(t('edit'));
1346
    $edit = array(
1347
      'date_format' => 'Y m',
1348
    );
1349
    $this->drupalPost($this->getUrl(), $edit, t('Save format'));
1350
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE)), 'Correct page redirection.');
1351
    $this->assertText(t('Custom date format updated.'), 'Custom date format successfully updated.');
1352

    
1353
    // Check that ajax callback is protected by CSRF token.
1354
    $this->drupalGet('admin/config/regional/date-time/formats/lookup', array('query' => array('format' => 'Y m d')));
1355
    $this->assertResponse(403, 'Access denied with no token');
1356
    $this->drupalGet('admin/config/regional/date-time/formats/lookup', array('query' => array('token' => 'invalid', 'format' => 'Y m d')));
1357
    $this->assertResponse(403, 'Access denied with invalid token');
1358
    $this->drupalGet('admin/config/regional/date-time/formats');
1359
    $this->clickLink(t('edit'));
1360
    $settings = $this->drupalGetSettings();
1361
    $lookup_url = $settings['dateTime']['date-format']['lookup'];
1362
    preg_match('/token=([^&]+)/', $lookup_url, $matches);
1363
    $this->assertFalse(empty($matches[1]), 'Found token value');
1364
    $this->drupalGet('admin/config/regional/date-time/formats/lookup', array('query' => array('token' => $matches[1], 'format' => 'Y m d')));
1365
    $this->assertResponse(200, 'Access allowed with valid token');
1366
    $this->assertText(format_date(time(), 'custom', 'Y m d'));
1367

    
1368
    // Delete custom date format.
1369
    $this->drupalGet('admin/config/regional/date-time/formats');
1370
    $this->clickLink(t('delete'));
1371
    $this->drupalPost($this->getUrl(), array(), t('Remove'));
1372
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE)), 'Correct page redirection.');
1373
    $this->assertText(t('Removed date format'), 'Custom date format removed successfully.');
1374
  }
1375

    
1376
  /**
1377
   * Test if the date formats are stored properly.
1378
   */
1379
  function testDateFormatStorage() {
1380
    $date_format = array(
1381
      'type' => 'short',
1382
      'format' => 'dmYHis',
1383
      'locked' => 0,
1384
      'is_new' => 1,
1385
    );
1386
    system_date_format_save($date_format);
1387

    
1388
    $format = db_select('date_formats', 'df')
1389
      ->fields('df', array('format'))
1390
      ->condition('type', 'short')
1391
      ->condition('format', 'dmYHis')
1392
      ->execute()
1393
      ->fetchField();
1394
    $this->verbose($format);
1395
    $this->assertEqual('dmYHis', $format, 'Unlocalized date format resides in general table.');
1396

    
1397
    $format = db_select('date_format_locale', 'dfl')
1398
      ->fields('dfl', array('format'))
1399
      ->condition('type', 'short')
1400
      ->condition('format', 'dmYHis')
1401
      ->execute()
1402
      ->fetchField();
1403
    $this->assertFalse($format, 'Unlocalized date format resides not in localized table.');
1404

    
1405
    // Enable German language
1406
    locale_add_language('de', NULL, NULL, LANGUAGE_LTR, '', '', TRUE, 'en');
1407

    
1408
    $date_format = array(
1409
      'type' => 'short',
1410
      'format' => 'YMDHis',
1411
      'locales' => array('de', 'tr'),
1412
      'locked' => 0,
1413
      'is_new' => 1,
1414
    );
1415
    system_date_format_save($date_format);
1416

    
1417
    $format = db_select('date_format_locale', 'dfl')
1418
      ->fields('dfl', array('format'))
1419
      ->condition('type', 'short')
1420
      ->condition('format', 'YMDHis')
1421
      ->condition('language', 'de')
1422
      ->execute()
1423
      ->fetchField();
1424
    $this->assertEqual('YMDHis', $format, 'Localized date format resides in localized table.');
1425

    
1426
    $format = db_select('date_formats', 'df')
1427
      ->fields('df', array('format'))
1428
      ->condition('type', 'short')
1429
      ->condition('format', 'YMDHis')
1430
      ->execute()
1431
      ->fetchField();
1432
    $this->assertEqual('YMDHis', $format, 'Localized date format resides in general table too.');
1433

    
1434
    $format = db_select('date_format_locale', 'dfl')
1435
      ->fields('dfl', array('format'))
1436
      ->condition('type', 'short')
1437
      ->condition('format', 'YMDHis')
1438
      ->condition('language', 'tr')
1439
      ->execute()
1440
      ->fetchColumn();
1441
    $this->assertFalse($format, 'Localized date format for disabled language is ignored.');
1442
  }
1443
}
1444

    
1445
class PageTitleFiltering extends DrupalWebTestCase {
1446
  protected $content_user;
1447
  protected $saved_title;
1448

    
1449
  /**
1450
   * Implement getInfo().
1451
   */
1452
  public static function getInfo() {
1453
    return array(
1454
      'name' => 'HTML in page titles',
1455
      'description' => 'Tests correct handling or conversion by drupal_set_title() and drupal_get_title() and checks the correct escaping of site name and slogan.',
1456
      'group' => 'System'
1457
    );
1458
  }
1459

    
1460
  /**
1461
   * Implement setUp().
1462
   */
1463
  function setUp() {
1464
    parent::setUp();
1465

    
1466
    $this->content_user = $this->drupalCreateUser(array('create page content', 'access content', 'administer themes', 'administer site configuration'));
1467
    $this->drupalLogin($this->content_user);
1468
    $this->saved_title = drupal_get_title();
1469
  }
1470

    
1471
  /**
1472
   * Reset page title.
1473
   */
1474
  function tearDown() {
1475
    // Restore the page title.
1476
    drupal_set_title($this->saved_title, PASS_THROUGH);
1477

    
1478
    parent::tearDown();
1479
  }
1480

    
1481
  /**
1482
   * Tests the handling of HTML by drupal_set_title() and drupal_get_title()
1483
   */
1484
  function testTitleTags() {
1485
    $title = "string with <em>HTML</em>";
1486
    // drupal_set_title's $filter is CHECK_PLAIN by default, so the title should be
1487
    // returned with check_plain().
1488
    drupal_set_title($title, CHECK_PLAIN);
1489
    $this->assertTrue(strpos(drupal_get_title(), '<em>') === FALSE, 'Tags in title converted to entities when $output is CHECK_PLAIN.');
1490
    // drupal_set_title's $filter is passed as PASS_THROUGH, so the title should be
1491
    // returned with HTML.
1492
    drupal_set_title($title, PASS_THROUGH);
1493
    $this->assertTrue(strpos(drupal_get_title(), '<em>') !== FALSE, 'Tags in title are not converted to entities when $output is PASS_THROUGH.');
1494
    // Generate node content.
1495
    $langcode = LANGUAGE_NONE;
1496
    $edit = array(
1497
      "title" => '!SimpleTest! ' . $title . $this->randomName(20),
1498
      "body[$langcode][0][value]" => '!SimpleTest! test body' . $this->randomName(200),
1499
    );
1500
    // Create the node with HTML in the title.
1501
    $this->drupalPost('node/add/page', $edit, t('Save'));
1502

    
1503
    $node = $this->drupalGetNodeByTitle($edit["title"]);
1504
    $this->assertNotNull($node, 'Node created and found in database');
1505
    $this->drupalGet("node/" . $node->nid);
1506
    $this->assertText(check_plain($edit["title"]), 'Check to make sure tags in the node title are converted.');
1507
  }
1508
  /**
1509
   * Test if the title of the site is XSS proof.
1510
   */
1511
  function testTitleXSS() {
1512
    // Set some title with JavaScript and HTML chars to escape.
1513
    $title = '</title><script type="text/javascript">alert("Title XSS!");</script> & < > " \' ';
1514
    $title_filtered = check_plain($title);
1515

    
1516
    $slogan = '<script type="text/javascript">alert("Slogan XSS!");</script>';
1517
    $slogan_filtered = filter_xss_admin($slogan);
1518

    
1519
    // Activate needed appearance settings.
1520
    $edit = array(
1521
      'toggle_name'           => TRUE,
1522
      'toggle_slogan'         => TRUE,
1523
      'toggle_main_menu'      => TRUE,
1524
      'toggle_secondary_menu' => TRUE,
1525
    );
1526
    $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
1527

    
1528
    // Set title and slogan.
1529
    $edit = array(
1530
      'site_name'    => $title,
1531
      'site_slogan'  => $slogan,
1532
    );
1533
    $this->drupalPost('admin/config/system/site-information', $edit, t('Save configuration'));
1534

    
1535
    // Load frontpage.
1536
    $this->drupalGet('');
1537

    
1538
    // Test the title.
1539
    $this->assertNoRaw($title, 'Check for the unfiltered version of the title.');
1540
    // Adding </title> so we do not test the escaped version from drupal_set_title().
1541
    $this->assertRaw($title_filtered . '</title>', 'Check for the filtered version of the title.');
1542

    
1543
    // Test the slogan.
1544
    $this->assertNoRaw($slogan, 'Check for the unfiltered version of the slogan.');
1545
    $this->assertRaw($slogan_filtered, 'Check for the filtered version of the slogan.');
1546
  }
1547
}
1548

    
1549
/**
1550
 * Test front page functionality and administration.
1551
 */
1552
class FrontPageTestCase extends DrupalWebTestCase {
1553

    
1554
  public static function getInfo() {
1555
    return array(
1556
      'name' => 'Front page',
1557
      'description' => 'Tests front page functionality and administration.',
1558
      'group' => 'System',
1559
    );
1560
  }
1561

    
1562
  function setUp() {
1563
    parent::setUp('system_test');
1564

    
1565
    // Create admin user, log in admin user, and create one node.
1566
    $this->admin_user = $this->drupalCreateUser(array('access content', 'administer site configuration'));
1567
    $this->drupalLogin($this->admin_user);
1568
    $this->node_path = "node/" . $this->drupalCreateNode(array('promote' => 1))->nid;
1569

    
1570
    // Enable front page logging in system_test.module.
1571
    variable_set('front_page_output', 1);
1572
  }
1573

    
1574
  /**
1575
   * Test front page functionality.
1576
   */
1577
  function testDrupalIsFrontPage() {
1578
    $this->drupalGet('');
1579
    $this->assertText(t('On front page.'), 'Path is the front page.');
1580
    $this->drupalGet('node');
1581
    $this->assertText(t('On front page.'), 'Path is the front page.');
1582
    $this->drupalGet($this->node_path);
1583
    $this->assertNoText(t('On front page.'), 'Path is not the front page.');
1584

    
1585
    // Change the front page to an invalid path.
1586
    $edit = array('site_frontpage' => 'kittens');
1587
    $this->drupalPost('admin/config/system/site-information', $edit, t('Save configuration'));
1588
    $this->assertText(t("The path '@path' is either invalid or you do not have access to it.", array('@path' => $edit['site_frontpage'])));
1589

    
1590
    // Change the front page to a valid path.
1591
    $edit['site_frontpage'] = $this->node_path;
1592
    $this->drupalPost('admin/config/system/site-information', $edit, t('Save configuration'));
1593
    $this->assertText(t('The configuration options have been saved.'), 'The front page path has been saved.');
1594

    
1595
    $this->drupalGet('');
1596
    $this->assertText(t('On front page.'), 'Path is the front page.');
1597
    $this->drupalGet('node');
1598
    $this->assertNoText(t('On front page.'), 'Path is not the front page.');
1599
    $this->drupalGet($this->node_path);
1600
    $this->assertText(t('On front page.'), 'Path is the front page.');
1601
  }
1602
}
1603

    
1604
class SystemBlockTestCase extends DrupalWebTestCase {
1605
  protected $profile = 'testing';
1606

    
1607
  public static function getInfo() {
1608
    return array(
1609
      'name' => 'Block functionality',
1610
      'description' => 'Configure and move powered-by block.',
1611
      'group' => 'System',
1612
    );
1613
  }
1614

    
1615
  function setUp() {
1616
    parent::setUp('block');
1617

    
1618
    // Create and login user
1619
    $admin_user = $this->drupalCreateUser(array('administer blocks', 'access administration pages'));
1620
    $this->drupalLogin($admin_user);
1621
  }
1622

    
1623
  /**
1624
   * Test displaying and hiding the powered-by and help blocks.
1625
   */
1626
  function testSystemBlocks() {
1627
    // Set block title and some settings to confirm that the interface is available.
1628
    $this->drupalPost('admin/structure/block/manage/system/powered-by/configure', array('title' => $this->randomName(8)), t('Save block'));
1629
    $this->assertText(t('The block configuration has been saved.'), t('Block configuration set.'));
1630

    
1631
    // Set the powered-by block to the footer region.
1632
    $edit = array();
1633
    $edit['blocks[system_powered-by][region]'] = 'footer';
1634
    $edit['blocks[system_main][region]'] = 'content';
1635
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1636
    $this->assertText(t('The block settings have been updated.'), t('Block successfully moved to footer region.'));
1637

    
1638
    // Confirm that the block is being displayed.
1639
    $this->drupalGet('node');
1640
    $this->assertRaw('id="block-system-powered-by"', t('Block successfully being displayed on the page.'));
1641

    
1642
    // Set the block to the disabled region.
1643
    $edit = array();
1644
    $edit['blocks[system_powered-by][region]'] = '-1';
1645
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1646

    
1647
    // Confirm that the block is hidden.
1648
    $this->assertNoRaw('id="block-system-powered-by"', t('Block no longer appears on page.'));
1649

    
1650
    // For convenience of developers, set the block to its default settings.
1651
    $edit = array();
1652
    $edit['blocks[system_powered-by][region]'] = 'footer';
1653
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1654
    $this->drupalPost('admin/structure/block/manage/system/powered-by/configure', array('title' => ''), t('Save block'));
1655

    
1656
    // Set the help block to the help region.
1657
    $edit = array();
1658
    $edit['blocks[system_help][region]'] = 'help';
1659
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1660

    
1661
    // Test displaying the help block with block caching enabled.
1662
    variable_set('block_cache', TRUE);
1663
    $this->drupalGet('admin/structure/block/add');
1664
    $this->assertRaw(t('Use this page to create a new custom block.'));
1665
    $this->drupalGet('admin/index');
1666
    $this->assertRaw(t('This page shows you all available administration tasks for each module.'));
1667
  }
1668
}
1669

    
1670
/**
1671
 * Test main content rendering fallback provided by system module.
1672
 */
1673
class SystemMainContentFallback extends DrupalWebTestCase {
1674
  protected $admin_user;
1675
  protected $web_user;
1676

    
1677
  public static function getInfo() {
1678
    return array(
1679
      'name' => 'Main content rendering fallback',
1680
      'description' => ' Test system module main content rendering fallback.',
1681
      'group' => 'System',
1682
    );
1683
  }
1684

    
1685
  function setUp() {
1686
    parent::setUp('system_test');
1687

    
1688
    // Create and login admin user.
1689
    $this->admin_user = $this->drupalCreateUser(array(
1690
      'access administration pages',
1691
      'administer site configuration',
1692
      'administer modules',
1693
      'administer blocks',
1694
      'administer nodes',
1695
    ));
1696
    $this->drupalLogin($this->admin_user);
1697

    
1698
    // Create a web user.
1699
    $this->web_user = $this->drupalCreateUser(array('access user profiles', 'access content'));
1700
  }
1701

    
1702
  /**
1703
   * Test availability of main content.
1704
   */
1705
  function testMainContentFallback() {
1706
    $edit = array();
1707
    // Disable the dashboard module, which depends on the block module.
1708
    $edit['modules[Core][dashboard][enable]'] = FALSE;
1709
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
1710
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
1711
    // Disable the block module.
1712
    $edit['modules[Core][block][enable]'] = FALSE;
1713
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
1714
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
1715
    module_list(TRUE);
1716
    $this->assertFalse(module_exists('block'), 'Block module disabled.');
1717

    
1718
    // At this point, no region is filled and fallback should be triggered.
1719
    $this->drupalGet('admin/config/system/site-information');
1720
    $this->assertField('site_name', 'Admin interface still available.');
1721

    
1722
    // Fallback should not trigger when another module is handling content.
1723
    $this->drupalGet('system-test/main-content-handling');
1724
    $this->assertRaw('id="system-test-content"', 'Content handled by another module');
1725
    $this->assertText(t('Content to test main content fallback'), 'Main content still displayed.');
1726

    
1727
    // Fallback should trigger when another module
1728
    // indicates that it is not handling the content.
1729
    $this->drupalGet('system-test/main-content-fallback');
1730
    $this->assertText(t('Content to test main content fallback'), 'Main content fallback properly triggers.');
1731

    
1732
    // Fallback should not trigger when another module is handling content.
1733
    // Note that this test ensures that no duplicate
1734
    // content gets created by the fallback.
1735
    $this->drupalGet('system-test/main-content-duplication');
1736
    $this->assertNoText(t('Content to test main content fallback'), 'Main content not duplicated.');
1737

    
1738
    // Request a user* page and see if it is displayed.
1739
    $this->drupalLogin($this->web_user);
1740
    $this->drupalGet('user/' . $this->web_user->uid . '/edit');
1741
    $this->assertField('mail', 'User interface still available.');
1742

    
1743
    // Enable the block module again.
1744
    $this->drupalLogin($this->admin_user);
1745
    $edit = array();
1746
    $edit['modules[Core][block][enable]'] = 'block';
1747
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
1748
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
1749
    module_list(TRUE);
1750
    $this->assertTrue(module_exists('block'), 'Block module re-enabled.');
1751
  }
1752
}
1753

    
1754
/**
1755
 * Tests for the theme interface functionality.
1756
 */
1757
class SystemThemeFunctionalTest extends DrupalWebTestCase {
1758
  public static function getInfo() {
1759
    return array(
1760
      'name' => 'Theme interface functionality',
1761
      'description' => 'Tests the theme interface functionality by enabling and switching themes, and using an administration theme.',
1762
      'group' => 'System',
1763
    );
1764
  }
1765

    
1766
  function setUp() {
1767
    parent::setUp();
1768

    
1769
    $this->admin_user = $this->drupalCreateUser(array('access administration pages', 'view the administration theme', 'administer themes', 'bypass node access', 'administer blocks'));
1770
    $this->drupalLogin($this->admin_user);
1771
    $this->node = $this->drupalCreateNode();
1772
  }
1773

    
1774
  /**
1775
   * Test the theme settings form.
1776
   */
1777
  function testThemeSettings() {
1778
    // Specify a filesystem path to be used for the logo.
1779
    $file = current($this->drupalGetTestFiles('image'));
1780
    $file_relative = strtr($file->uri, array('public:/' => variable_get('file_public_path', conf_path() . '/files')));
1781
    $default_theme_path = 'themes/stark';
1782

    
1783
    $supported_paths = array(
1784
      // Raw stream wrapper URI.
1785
      $file->uri => array(
1786
        'form' => file_uri_target($file->uri),
1787
        'src' => file_create_url($file->uri),
1788
      ),
1789
      // Relative path within the public filesystem.
1790
      file_uri_target($file->uri) => array(
1791
        'form' => file_uri_target($file->uri),
1792
        'src' => file_create_url($file->uri),
1793
      ),
1794
      // Relative path to a public file.
1795
      $file_relative => array(
1796
        'form' => $file_relative,
1797
        'src' => file_create_url($file->uri),
1798
      ),
1799
      // Relative path to an arbitrary file.
1800
      'misc/druplicon.png' => array(
1801
        'form' => 'misc/druplicon.png',
1802
        'src' => $GLOBALS['base_url'] . '/' . 'misc/druplicon.png',
1803
      ),
1804
      // Relative path to a file in a theme.
1805
      $default_theme_path . '/logo.png' => array(
1806
        'form' => $default_theme_path . '/logo.png',
1807
        'src' => $GLOBALS['base_url'] . '/' . $default_theme_path . '/logo.png',
1808
      ),
1809
    );
1810
    foreach ($supported_paths as $input => $expected) {
1811
      $edit = array(
1812
        'default_logo' => FALSE,
1813
        'logo_path' => $input,
1814
      );
1815
      $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
1816
      $this->assertNoText('The custom logo path is invalid.');
1817
      $this->assertFieldByName('logo_path', $expected['form']);
1818

    
1819
      // Verify the actual 'src' attribute of the logo being output.
1820
      $this->drupalGet('');
1821
      $elements = $this->xpath('//*[@id=:id]/img', array(':id' => 'logo'));
1822
      $this->assertEqual((string) $elements[0]['src'], $expected['src']);
1823
    }
1824

    
1825
    $unsupported_paths = array(
1826
      // Stream wrapper URI to non-existing file.
1827
      'public://whatever.png',
1828
      'private://whatever.png',
1829
      'temporary://whatever.png',
1830
      // Bogus stream wrapper URIs.
1831
      'public:/whatever.png',
1832
      '://whatever.png',
1833
      ':whatever.png',
1834
      'public://',
1835
      // Relative path within the public filesystem to non-existing file.
1836
      'whatever.png',
1837
      // Relative path to non-existing file in public filesystem.
1838
      variable_get('file_public_path', conf_path() . '/files') . '/whatever.png',
1839
      // Semi-absolute path to non-existing file in public filesystem.
1840
      '/' . variable_get('file_public_path', conf_path() . '/files') . '/whatever.png',
1841
      // Relative path to arbitrary non-existing file.
1842
      'misc/whatever.png',
1843
      // Semi-absolute path to arbitrary non-existing file.
1844
      '/misc/whatever.png',
1845
      // Absolute paths to any local file (even if it exists).
1846
      drupal_realpath($file->uri),
1847
    );
1848
    $this->drupalGet('admin/appearance/settings');
1849
    foreach ($unsupported_paths as $path) {
1850
      $edit = array(
1851
        'default_logo' => FALSE,
1852
        'logo_path' => $path,
1853
      );
1854
      $this->drupalPost(NULL, $edit, t('Save configuration'));
1855
      $this->assertText('The custom logo path is invalid.');
1856
    }
1857

    
1858
    // Upload a file to use for the logo.
1859
    $edit = array(
1860
      'default_logo' => FALSE,
1861
      'logo_path' => '',
1862
      'files[logo_upload]' => drupal_realpath($file->uri),
1863
    );
1864
    $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
1865

    
1866
    $fields = $this->xpath($this->constructFieldXpath('name', 'logo_path'));
1867
    $uploaded_filename = 'public://' . $fields[0]['value'];
1868

    
1869
    $this->drupalGet('');
1870
    $elements = $this->xpath('//*[@id=:id]/img', array(':id' => 'logo'));
1871
    $this->assertEqual($elements[0]['src'], file_create_url($uploaded_filename));
1872
  }
1873

    
1874
  /**
1875
   * Test the administration theme functionality.
1876
   */
1877
  function testAdministrationTheme() {
1878
    theme_enable(array('stark'));
1879
    variable_set('theme_default', 'stark');
1880
    // Enable an administration theme and show it on the node admin pages.
1881
    $edit = array(
1882
      'admin_theme' => 'seven',
1883
      'node_admin_theme' => TRUE,
1884
    );
1885
    $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
1886

    
1887
    $this->drupalGet('admin/config');
1888
    $this->assertRaw('themes/seven', 'Administration theme used on an administration page.');
1889

    
1890
    $this->drupalGet('node/' . $this->node->nid);
1891
    $this->assertRaw('themes/stark', 'Site default theme used on node page.');
1892

    
1893
    $this->drupalGet('node/add');
1894
    $this->assertRaw('themes/seven', 'Administration theme used on the add content page.');
1895

    
1896
    $this->drupalGet('node/' . $this->node->nid . '/edit');
1897
    $this->assertRaw('themes/seven', 'Administration theme used on the edit content page.');
1898

    
1899
    // Disable the admin theme on the node admin pages.
1900
    $edit = array(
1901
      'node_admin_theme' => FALSE,
1902
    );
1903
    $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
1904

    
1905
    $this->drupalGet('admin/config');
1906
    $this->assertRaw('themes/seven', 'Administration theme used on an administration page.');
1907

    
1908
    $this->drupalGet('node/add');
1909
    $this->assertRaw('themes/stark', 'Site default theme used on the add content page.');
1910

    
1911
    // Reset to the default theme settings.
1912
    variable_set('theme_default', 'bartik');
1913
    $edit = array(
1914
      'admin_theme' => '0',
1915
      'node_admin_theme' => FALSE,
1916
    );
1917
    $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
1918

    
1919
    $this->drupalGet('admin');
1920
    $this->assertRaw('themes/bartik', 'Site default theme used on administration page.');
1921

    
1922
    $this->drupalGet('node/add');
1923
    $this->assertRaw('themes/bartik', 'Site default theme used on the add content page.');
1924
  }
1925

    
1926
  /**
1927
   * Test switching the default theme.
1928
   */
1929
  function testSwitchDefaultTheme() {
1930
    // Enable "stark" and set it as the default theme.
1931
    theme_enable(array('stark'));
1932
    $this->drupalGet('admin/appearance');
1933
    $this->clickLink(t('Set default'), 1);
1934
    $this->assertTrue(variable_get('theme_default', '') == 'stark', 'Site default theme switched successfully.');
1935

    
1936
    // Test the default theme on the secondary links (blocks admin page).
1937
    $this->drupalGet('admin/structure/block');
1938
    $this->assertText('Stark(' . t('active tab') . ')', 'Default local task on blocks admin page is the default theme.');
1939
    // Switch back to Bartik and test again to test that the menu cache is cleared.
1940
    $this->drupalGet('admin/appearance');
1941
    $this->clickLink(t('Set default'), 0);
1942
    $this->drupalGet('admin/structure/block');
1943
    $this->assertText('Bartik(' . t('active tab') . ')', 'Default local task on blocks admin page has changed.');
1944
  }
1945
}
1946

    
1947

    
1948
/**
1949
 * Test the basic queue functionality.
1950
 */
1951
class QueueTestCase extends DrupalWebTestCase {
1952
  public static function getInfo() {
1953
    return array(
1954
      'name' => 'Queue functionality',
1955
      'description' => 'Queues and dequeues a set of items to check the basic queue functionality.',
1956
      'group' => 'System',
1957
    );
1958
  }
1959

    
1960
  /**
1961
   * Queues and dequeues a set of items to check the basic queue functionality.
1962
   */
1963
  function testQueue() {
1964
    // Create two queues.
1965
    $queue1 = DrupalQueue::get($this->randomName());
1966
    $queue1->createQueue();
1967
    $queue2 = DrupalQueue::get($this->randomName());
1968
    $queue2->createQueue();
1969

    
1970
    // Create four items.
1971
    $data = array();
1972
    for ($i = 0; $i < 4; $i++) {
1973
      $data[] = array($this->randomName() => $this->randomName());
1974
    }
1975

    
1976
    // Queue items 1 and 2 in the queue1.
1977
    $queue1->createItem($data[0]);
1978
    $queue1->createItem($data[1]);
1979

    
1980
    // Retrieve two items from queue1.
1981
    $items = array();
1982
    $new_items = array();
1983

    
1984
    $items[] = $item = $queue1->claimItem();
1985
    $new_items[] = $item->data;
1986

    
1987
    $items[] = $item = $queue1->claimItem();
1988
    $new_items[] = $item->data;
1989

    
1990
    // First two dequeued items should match the first two items we queued.
1991
    $this->assertEqual($this->queueScore($data, $new_items), 2, 'Two items matched');
1992

    
1993
    // Add two more items.
1994
    $queue1->createItem($data[2]);
1995
    $queue1->createItem($data[3]);
1996

    
1997
    $this->assertTrue($queue1->numberOfItems(), 'Queue 1 is not empty after adding items.');
1998
    $this->assertFalse($queue2->numberOfItems(), 'Queue 2 is empty while Queue 1 has items');
1999

    
2000
    $items[] = $item = $queue1->claimItem();
2001
    $new_items[] = $item->data;
2002

    
2003
    $items[] = $item = $queue1->claimItem();
2004
    $new_items[] = $item->data;
2005

    
2006
    // All dequeued items should match the items we queued exactly once,
2007
    // therefore the score must be exactly 4.
2008
    $this->assertEqual($this->queueScore($data, $new_items), 4, 'Four items matched');
2009

    
2010
    // There should be no duplicate items.
2011
    $this->assertEqual($this->queueScore($new_items, $new_items), 4, 'Four items matched');
2012

    
2013
    // Delete all items from queue1.
2014
    foreach ($items as $item) {
2015
      $queue1->deleteItem($item);
2016
    }
2017

    
2018
    // Check that both queues are empty.
2019
    $this->assertFalse($queue1->numberOfItems(), 'Queue 1 is empty');
2020
    $this->assertFalse($queue2->numberOfItems(), 'Queue 2 is empty');
2021
  }
2022

    
2023
  /**
2024
   * This function returns the number of equal items in two arrays.
2025
   */
2026
  function queueScore($items, $new_items) {
2027
    $score = 0;
2028
    foreach ($items as $item) {
2029
      foreach ($new_items as $new_item) {
2030
        if ($item === $new_item) {
2031
          $score++;
2032
        }
2033
      }
2034
    }
2035
    return $score;
2036
  }
2037
}
2038

    
2039
/**
2040
 * Test token replacement in strings.
2041
 */
2042
class TokenReplaceTestCase extends DrupalWebTestCase {
2043
  public static function getInfo() {
2044
    return array(
2045
      'name' => 'Token replacement',
2046
      'description' => 'Generates text using placeholders for dummy content to check token replacement.',
2047
      'group' => 'System',
2048
    );
2049
  }
2050

    
2051
  /**
2052
   * Creates a user and a node, then tests the tokens generated from them.
2053
   */
2054
  function testTokenReplacement() {
2055
    // Create the initial objects.
2056
    $account = $this->drupalCreateUser();
2057
    $node = $this->drupalCreateNode(array('uid' => $account->uid));
2058
    $node->title = '<blink>Blinking Text</blink>';
2059
    global $user, $language;
2060

    
2061
    $source  = '[node:title]';         // Title of the node we passed in
2062
    $source .= '[node:author:name]';   // Node author's name
2063
    $source .= '[node:created:since]'; // Time since the node was created
2064
    $source .= '[current-user:name]';  // Current user's name
2065
    $source .= '[date:short]';         // Short date format of REQUEST_TIME
2066
    $source .= '[user:name]';          // No user passed in, should be untouched
2067
    $source .= '[bogus:token]';        // Non-existent token
2068

    
2069
    $target  = check_plain($node->title);
2070
    $target .= check_plain($account->name);
2071
    $target .= format_interval(REQUEST_TIME - $node->created, 2, $language->language);
2072
    $target .= check_plain($user->name);
2073
    $target .= format_date(REQUEST_TIME, 'short', '', NULL, $language->language);
2074

    
2075
    // Test that the clear parameter cleans out non-existent tokens.
2076
    $result = token_replace($source, array('node' => $node), array('language' => $language, 'clear' => TRUE));
2077
    $result = $this->assertEqual($target, $result, 'Valid tokens replaced while invalid tokens cleared out.');
2078

    
2079
    // Test without using the clear parameter (non-existent token untouched).
2080
    $target .= '[user:name]';
2081
    $target .= '[bogus:token]';
2082
    $result = token_replace($source, array('node' => $node), array('language' => $language));
2083
    $this->assertEqual($target, $result, 'Valid tokens replaced while invalid tokens ignored.');
2084

    
2085
    // Check that the results of token_generate are sanitized properly. This does NOT
2086
    // test the cleanliness of every token -- just that the $sanitize flag is being
2087
    // passed properly through the call stack and being handled correctly by a 'known'
2088
    // token, [node:title].
2089
    $raw_tokens = array('title' => '[node:title]');
2090
    $generated = token_generate('node', $raw_tokens, array('node' => $node));
2091
    $this->assertEqual($generated['[node:title]'], check_plain($node->title), 'Token sanitized.');
2092

    
2093
    $generated = token_generate('node', $raw_tokens, array('node' => $node), array('sanitize' => FALSE));
2094
    $this->assertEqual($generated['[node:title]'], $node->title, 'Unsanitized token generated properly.');
2095

    
2096
    // Test token replacement when the string contains no tokens.
2097
    $this->assertEqual(token_replace('No tokens here.'), 'No tokens here.');
2098
  }
2099

    
2100
  /**
2101
   * Test whether token-replacement works in various contexts.
2102
   */
2103
  function testSystemTokenRecognition() {
2104
    global $language;
2105

    
2106
    // Generate prefixes and suffixes for the token context.
2107
    $tests = array(
2108
      array('prefix' => 'this is the ', 'suffix' => ' site'),
2109
      array('prefix' => 'this is the', 'suffix' => 'site'),
2110
      array('prefix' => '[', 'suffix' => ']'),
2111
      array('prefix' => '', 'suffix' => ']]]'),
2112
      array('prefix' => '[[[', 'suffix' => ''),
2113
      array('prefix' => ':[:', 'suffix' => '--]'),
2114
      array('prefix' => '-[-', 'suffix' => ':]:'),
2115
      array('prefix' => '[:', 'suffix' => ']'),
2116
      array('prefix' => '[site:', 'suffix' => ':name]'),
2117
      array('prefix' => '[site:', 'suffix' => ']'),
2118
    );
2119

    
2120
    // Check if the token is recognized in each of the contexts.
2121
    foreach ($tests as $test) {
2122
      $input = $test['prefix'] . '[site:name]' . $test['suffix'];
2123
      $expected = $test['prefix'] . 'Drupal' . $test['suffix'];
2124
      $output = token_replace($input, array(), array('language' => $language));
2125
      $this->assertTrue($output == $expected, format_string('Token recognized in string %string', array('%string' => $input)));
2126
    }
2127
  }
2128

    
2129
  /**
2130
   * Tests the generation of all system site information tokens.
2131
   */
2132
  function testSystemSiteTokenReplacement() {
2133
    global $language;
2134
    $url_options = array(
2135
      'absolute' => TRUE,
2136
      'language' => $language,
2137
    );
2138

    
2139
    // Set a few site variables.
2140
    variable_set('site_name', '<strong>Drupal<strong>');
2141
    variable_set('site_slogan', '<blink>Slogan</blink>');
2142

    
2143
    // Generate and test sanitized tokens.
2144
    $tests = array();
2145
    $tests['[site:name]'] = check_plain(variable_get('site_name', 'Drupal'));
2146
    $tests['[site:slogan]'] = check_plain(variable_get('site_slogan', ''));
2147
    $tests['[site:mail]'] = 'simpletest@example.com';
2148
    $tests['[site:url]'] = url('<front>', $url_options);
2149
    $tests['[site:url-brief]'] = preg_replace(array('!^https?://!', '!/$!'), '', url('<front>', $url_options));
2150
    $tests['[site:login-url]'] = url('user', $url_options);
2151

    
2152
    // Test to make sure that we generated something for each token.
2153
    $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
2154

    
2155
    foreach ($tests as $input => $expected) {
2156
      $output = token_replace($input, array(), array('language' => $language));
2157
      $this->assertEqual($output, $expected, format_string('Sanitized system site information token %token replaced.', array('%token' => $input)));
2158
    }
2159

    
2160
    // Generate and test unsanitized tokens.
2161
    $tests['[site:name]'] = variable_get('site_name', 'Drupal');
2162
    $tests['[site:slogan]'] = variable_get('site_slogan', '');
2163

    
2164
    foreach ($tests as $input => $expected) {
2165
      $output = token_replace($input, array(), array('language' => $language, 'sanitize' => FALSE));
2166
      $this->assertEqual($output, $expected, format_string('Unsanitized system site information token %token replaced.', array('%token' => $input)));
2167
    }
2168
  }
2169

    
2170
  /**
2171
   * Tests the generation of all system date tokens.
2172
   */
2173
  function testSystemDateTokenReplacement() {
2174
    global $language;
2175

    
2176
    // Set time to one hour before request.
2177
    $date = REQUEST_TIME - 3600;
2178

    
2179
    // Generate and test tokens.
2180
    $tests = array();
2181
    $tests['[date:short]'] = format_date($date, 'short', '', NULL, $language->language);
2182
    $tests['[date:medium]'] = format_date($date, 'medium', '', NULL, $language->language);
2183
    $tests['[date:long]'] = format_date($date, 'long', '', NULL, $language->language);
2184
    $tests['[date:custom:m/j/Y]'] = format_date($date, 'custom', 'm/j/Y', NULL, $language->language);
2185
    $tests['[date:since]'] = format_interval((REQUEST_TIME - $date), 2, $language->language);
2186
    $tests['[date:raw]'] = filter_xss($date);
2187

    
2188
    // Test to make sure that we generated something for each token.
2189
    $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
2190

    
2191
    foreach ($tests as $input => $expected) {
2192
      $output = token_replace($input, array('date' => $date), array('language' => $language));
2193
      $this->assertEqual($output, $expected, format_string('Date token %token replaced.', array('%token' => $input)));
2194
    }
2195
  }
2196
}
2197

    
2198
class InfoFileParserTestCase extends DrupalUnitTestCase {
2199
  public static function getInfo() {
2200
    return array(
2201
      'name' => 'Info file format parser',
2202
      'description' => 'Tests proper parsing of a .info file formatted string.',
2203
      'group' => 'System',
2204
    );
2205
  }
2206

    
2207
  /**
2208
   * Test drupal_parse_info_format().
2209
   */
2210
  function testDrupalParseInfoFormat() {
2211
    $config = '
2212
simple = Value
2213
quoted = " Value"
2214
multiline = "Value
2215
  Value"
2216
array[] = Value1
2217
array[] = Value2
2218
array_assoc[a] = Value1
2219
array_assoc[b] = Value2
2220
array_deep[][][] = Value
2221
array_deep_assoc[a][b][c] = Value
2222
array_space[a b] = Value';
2223

    
2224
    $expected = array(
2225
      'simple' => 'Value',
2226
      'quoted' => ' Value',
2227
      'multiline' => "Value\n  Value",
2228
      'array' => array(
2229
        0 => 'Value1',
2230
        1 => 'Value2',
2231
      ),
2232
      'array_assoc' => array(
2233
        'a' => 'Value1',
2234
        'b' => 'Value2',
2235
      ),
2236
      'array_deep' => array(
2237
        0 => array(
2238
          0 => array(
2239
            0 => 'Value',
2240
          ),
2241
        ),
2242
      ),
2243
      'array_deep_assoc' => array(
2244
        'a' => array(
2245
          'b' => array(
2246
            'c' => 'Value',
2247
          ),
2248
        ),
2249
      ),
2250
      'array_space' => array(
2251
        'a b' => 'Value',
2252
      ),
2253
    );
2254

    
2255
    $parsed = drupal_parse_info_format($config);
2256

    
2257
    $this->assertEqual($parsed['simple'], $expected['simple'], 'Set a simple value.');
2258
    $this->assertEqual($parsed['quoted'], $expected['quoted'], 'Set a simple value in quotes.');
2259
    $this->assertEqual($parsed['multiline'], $expected['multiline'], 'Set a multiline value.');
2260
    $this->assertEqual($parsed['array'], $expected['array'], 'Set a simple array.');
2261
    $this->assertEqual($parsed['array_assoc'], $expected['array_assoc'], 'Set an associative array.');
2262
    $this->assertEqual($parsed['array_deep'], $expected['array_deep'], 'Set a nested array.');
2263
    $this->assertEqual($parsed['array_deep_assoc'], $expected['array_deep_assoc'], 'Set a nested associative array.');
2264
    $this->assertEqual($parsed['array_space'], $expected['array_space'], 'Set an array with a whitespace in the key.');
2265
    $this->assertEqual($parsed, $expected, 'Entire parsed .info string and expected array are identical.');
2266
  }
2267
}
2268

    
2269
/**
2270
 * Tests the effectiveness of hook_system_info_alter().
2271
 */
2272
class SystemInfoAlterTestCase extends DrupalWebTestCase {
2273
  public static function getInfo() {
2274
    return array(
2275
      'name' => 'System info alter',
2276
      'description' => 'Tests the effectiveness of hook_system_info_alter().',
2277
      'group' => 'System',
2278
    );
2279
  }
2280

    
2281
  /**
2282
   * Tests that {system}.info is rebuilt after a module that implements
2283
   * hook_system_info_alter() is enabled. Also tests if core *_list() functions
2284
   * return freshly altered info.
2285
   */
2286
  function testSystemInfoAlter() {
2287
    // Enable our test module. Flush all caches, which we assert is the only
2288
    // thing necessary to use the rebuilt {system}.info.
2289
    module_enable(array('module_test'), FALSE);
2290
    drupal_flush_all_caches();
2291
    $this->assertTrue(module_exists('module_test'), 'Test module is enabled.');
2292

    
2293
    $info = $this->getSystemInfo('seven', 'theme');
2294
    $this->assertTrue(isset($info['regions']['test_region']), 'Altered theme info was added to {system}.info.');
2295
    $seven_regions = system_region_list('seven');
2296
    $this->assertTrue(isset($seven_regions['test_region']), 'Altered theme info was returned by system_region_list().');
2297
    $system_list_themes = system_list('theme');
2298
    $info = $system_list_themes['seven']->info;
2299
    $this->assertTrue(isset($info['regions']['test_region']), 'Altered theme info was returned by system_list().');
2300
    $list_themes = list_themes();
2301
    $this->assertTrue(isset($list_themes['seven']->info['regions']['test_region']), 'Altered theme info was returned by list_themes().');
2302

    
2303
    // Disable the module and verify that {system}.info is rebuilt without it.
2304
    module_disable(array('module_test'), FALSE);
2305
    drupal_flush_all_caches();
2306
    $this->assertFalse(module_exists('module_test'), 'Test module is disabled.');
2307

    
2308
    $info = $this->getSystemInfo('seven', 'theme');
2309
    $this->assertFalse(isset($info['regions']['test_region']), 'Altered theme info was removed from {system}.info.');
2310
    $seven_regions = system_region_list('seven');
2311
    $this->assertFalse(isset($seven_regions['test_region']), 'Altered theme info was not returned by system_region_list().');
2312
    $system_list_themes = system_list('theme');
2313
    $info = $system_list_themes['seven']->info;
2314
    $this->assertFalse(isset($info['regions']['test_region']), 'Altered theme info was not returned by system_list().');
2315
    $list_themes = list_themes();
2316
    $this->assertFalse(isset($list_themes['seven']->info['regions']['test_region']), 'Altered theme info was not returned by list_themes().');
2317
  }
2318

    
2319
  /**
2320
   * Returns the info array as it is stored in {system}.
2321
   *
2322
   * @param $name
2323
   *   The name of the record in {system}.
2324
   * @param $type
2325
   *   The type of record in {system}.
2326
   *
2327
   * @return
2328
   *   Array of info, or FALSE if the record is not found.
2329
   */
2330
  function getSystemInfo($name, $type) {
2331
    $raw_info = db_query("SELECT info FROM {system} WHERE name = :name AND type = :type", array(':name' => $name, ':type' => $type))->fetchField();
2332
    return $raw_info ? unserialize($raw_info) : FALSE;
2333
  }
2334
}
2335

    
2336
/**
2337
 * Tests for the update system functionality.
2338
 */
2339
class UpdateScriptFunctionalTest extends DrupalWebTestCase {
2340
  private $update_url;
2341
  private $update_user;
2342

    
2343
  public static function getInfo() {
2344
    return array(
2345
      'name' => 'Update functionality',
2346
      'description' => 'Tests the update script access and functionality.',
2347
      'group' => 'System',
2348
    );
2349
  }
2350

    
2351
  function setUp() {
2352
    parent::setUp('update_script_test');
2353
    $this->update_url = $GLOBALS['base_url'] . '/update.php';
2354
    $this->update_user = $this->drupalCreateUser(array('administer software updates'));
2355
  }
2356

    
2357
  /**
2358
   * Tests access to the update script.
2359
   */
2360
  function testUpdateAccess() {
2361
    // Try accessing update.php without the proper permission.
2362
    $regular_user = $this->drupalCreateUser();
2363
    $this->drupalLogin($regular_user);
2364
    $this->drupalGet($this->update_url, array('external' => TRUE));
2365
    $this->assertResponse(403);
2366

    
2367
    // Try accessing update.php as an anonymous user.
2368
    $this->drupalLogout();
2369
    $this->drupalGet($this->update_url, array('external' => TRUE));
2370
    $this->assertResponse(403);
2371

    
2372
    // Access the update page with the proper permission.
2373
    $this->drupalLogin($this->update_user);
2374
    $this->drupalGet($this->update_url, array('external' => TRUE));
2375
    $this->assertResponse(200);
2376

    
2377
    // Access the update page as user 1.
2378
    $user1 = user_load(1);
2379
    $user1->pass_raw = user_password();
2380
    require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
2381
    $user1->pass = user_hash_password(trim($user1->pass_raw));
2382
    db_query("UPDATE {users} SET pass = :pass WHERE uid = :uid", array(':pass' => $user1->pass, ':uid' => $user1->uid));
2383
    $this->drupalLogin($user1);
2384
    $this->drupalGet($this->update_url, array('external' => TRUE));
2385
    $this->assertResponse(200);
2386
  }
2387

    
2388
  /**
2389
   * Tests that requirements warnings and errors are correctly displayed.
2390
   */
2391
  function testRequirements() {
2392
    $this->drupalLogin($this->update_user);
2393

    
2394
    // If there are no requirements warnings or errors, we expect to be able to
2395
    // go through the update process uninterrupted.
2396
    $this->drupalGet($this->update_url, array('external' => TRUE));
2397
    $this->drupalPost(NULL, array(), t('Continue'));
2398
    $this->assertText(t('No pending updates.'), 'End of update process was reached.');
2399
    // Confirm that all caches were cleared.
2400
    $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared when there were no requirements warnings or errors.');
2401

    
2402
    // If there is a requirements warning, we expect it to be initially
2403
    // displayed, but clicking the link to proceed should allow us to go
2404
    // through the rest of the update process uninterrupted.
2405

    
2406
    // First, run this test with pending updates to make sure they can be run
2407
    // successfully.
2408
    variable_set('update_script_test_requirement_type', REQUIREMENT_WARNING);
2409
    drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
2410
    $this->drupalGet($this->update_url, array('external' => TRUE));
2411
    $this->assertText('This is a requirements warning provided by the update_script_test module.');
2412
    $this->clickLink('try again');
2413
    $this->assertNoText('This is a requirements warning provided by the update_script_test module.');
2414
    $this->drupalPost(NULL, array(), t('Continue'));
2415
    $this->drupalPost(NULL, array(), t('Apply pending updates'));
2416
    $this->assertText(t('The update_script_test_update_7000() update was executed successfully.'), 'End of update process was reached.');
2417
    // Confirm that all caches were cleared.
2418
    $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared after resolving a requirements warning and applying updates.');
2419

    
2420
    // Now try again without pending updates to make sure that works too.
2421
    $this->drupalGet($this->update_url, array('external' => TRUE));
2422
    $this->assertText('This is a requirements warning provided by the update_script_test module.');
2423
    $this->clickLink('try again');
2424
    $this->assertNoText('This is a requirements warning provided by the update_script_test module.');
2425
    $this->drupalPost(NULL, array(), t('Continue'));
2426
    $this->assertText(t('No pending updates.'), 'End of update process was reached.');
2427
    // Confirm that all caches were cleared.
2428
    $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared after applying updates and re-running the script.');
2429

    
2430
    // If there is a requirements error, it should be displayed even after
2431
    // clicking the link to proceed (since the problem that triggered the error
2432
    // has not been fixed).
2433
    variable_set('update_script_test_requirement_type', REQUIREMENT_ERROR);
2434
    $this->drupalGet($this->update_url, array('external' => TRUE));
2435
    $this->assertText('This is a requirements error provided by the update_script_test module.');
2436
    $this->clickLink('try again');
2437
    $this->assertText('This is a requirements error provided by the update_script_test module.');
2438
  }
2439

    
2440
  /**
2441
   * Tests the effect of using the update script on the theme system.
2442
   */
2443
  function testThemeSystem() {
2444
    // Since visiting update.php triggers a rebuild of the theme system from an
2445
    // unusual maintenance mode environment, we check that this rebuild did not
2446
    // put any incorrect information about the themes into the database.
2447
    $original_theme_data = db_query("SELECT * FROM {system} WHERE type = 'theme' ORDER BY name")->fetchAll();
2448
    $this->drupalLogin($this->update_user);
2449
    $this->drupalGet($this->update_url, array('external' => TRUE));
2450
    $final_theme_data = db_query("SELECT * FROM {system} WHERE type = 'theme' ORDER BY name")->fetchAll();
2451
    $this->assertEqual($original_theme_data, $final_theme_data, 'Visiting update.php does not alter the information about themes stored in the database.');
2452
  }
2453

    
2454
  /**
2455
   * Tests update.php when there are no updates to apply.
2456
   */
2457
  function testNoUpdateFunctionality() {
2458
    // Click through update.php with 'administer software updates' permission.
2459
    $this->drupalLogin($this->update_user);
2460
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
2461
    $this->assertText(t('No pending updates.'));
2462
    $this->assertNoLink('Administration pages');
2463
    $this->clickLink('Front page');
2464
    $this->assertResponse(200);
2465

    
2466
    // Click through update.php with 'access administration pages' permission.
2467
    $admin_user = $this->drupalCreateUser(array('administer software updates', 'access administration pages'));
2468
    $this->drupalLogin($admin_user);
2469
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
2470
    $this->assertText(t('No pending updates.'));
2471
    $this->clickLink('Administration pages');
2472
    $this->assertResponse(200);
2473
  }
2474

    
2475
  /**
2476
   * Tests update.php after performing a successful update.
2477
   */
2478
  function testSuccessfulUpdateFunctionality() {
2479
    drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
2480
    // Click through update.php with 'administer software updates' permission.
2481
    $this->drupalLogin($this->update_user);
2482
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
2483
    $this->drupalPost(NULL, array(), t('Apply pending updates'));
2484
    $this->assertText('Updates were attempted.');
2485
    $this->assertLink('site');
2486
    $this->assertNoLink('Administration pages');
2487
    $this->assertNoLink('logged');
2488
    $this->clickLink('Front page');
2489
    $this->assertResponse(200);
2490

    
2491
    drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
2492
    // Click through update.php with 'access administration pages' and
2493
    // 'access site reports' permissions.
2494
    $admin_user = $this->drupalCreateUser(array('administer software updates', 'access administration pages', 'access site reports'));
2495
    $this->drupalLogin($admin_user);
2496
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
2497
    $this->drupalPost(NULL, array(), t('Apply pending updates'));
2498
    $this->assertText('Updates were attempted.');
2499
    $this->assertLink('logged');
2500
    $this->clickLink('Administration pages');
2501
    $this->assertResponse(200);
2502
  }
2503
}
2504

    
2505
/**
2506
 * Functional tests for the flood control mechanism.
2507
 */
2508
class FloodFunctionalTest extends DrupalWebTestCase {
2509
  public static function getInfo() {
2510
    return array(
2511
      'name' => 'Flood control mechanism',
2512
      'description' => 'Functional tests for the flood control mechanism.',
2513
      'group' => 'System',
2514
    );
2515
  }
2516

    
2517
  /**
2518
   * Test flood control mechanism clean-up.
2519
   */
2520
  function testCleanUp() {
2521
    $threshold = 1;
2522
    $window_expired = -1;
2523
    $name = 'flood_test_cleanup';
2524

    
2525
    // Register expired event.
2526
    flood_register_event($name, $window_expired);
2527
    // Verify event is not allowed.
2528
    $this->assertFalse(flood_is_allowed($name, $threshold));
2529
    // Run cron and verify event is now allowed.
2530
    $this->cronRun();
2531
    $this->assertTrue(flood_is_allowed($name, $threshold));
2532

    
2533
    // Register unexpired event.
2534
    flood_register_event($name);
2535
    // Verify event is not allowed.
2536
    $this->assertFalse(flood_is_allowed($name, $threshold));
2537
    // Run cron and verify event is still not allowed.
2538
    $this->cronRun();
2539
    $this->assertFalse(flood_is_allowed($name, $threshold));
2540
  }
2541
}
2542

    
2543
/**
2544
 * Test HTTP file downloading capability.
2545
 */
2546
class RetrieveFileTestCase extends DrupalWebTestCase {
2547
  public static function getInfo() {
2548
    return array(
2549
      'name' => 'HTTP file retrieval',
2550
      'description' => 'Checks HTTP file fetching and error handling.',
2551
      'group' => 'System',
2552
    );
2553
  }
2554

    
2555
  /**
2556
   * Invokes system_retrieve_file() in several scenarios.
2557
   */
2558
  function testFileRetrieving() {
2559
    // Test 404 handling by trying to fetch a randomly named file.
2560
    drupal_mkdir($sourcedir = 'public://' . $this->randomName());
2561
    $filename = 'Файл для тестирования ' . $this->randomName();
2562
    $url = file_create_url($sourcedir . '/' . $filename);
2563
    $retrieved_file = system_retrieve_file($url);
2564
    $this->assertFalse($retrieved_file, 'Non-existent file not fetched.');
2565

    
2566
    // Actually create that file, download it via HTTP and test the returned path.
2567
    file_put_contents($sourcedir . '/' . $filename, 'testing');
2568
    $retrieved_file = system_retrieve_file($url);
2569

    
2570
    // URLs could not contains characters outside the ASCII set so $filename
2571
    // has to be encoded.
2572
    $encoded_filename = rawurlencode($filename);
2573

    
2574
    $this->assertEqual($retrieved_file, 'public://' . $encoded_filename, 'Sane path for downloaded file returned (public:// scheme).');
2575
    $this->assertTrue(is_file($retrieved_file), 'Downloaded file does exist (public:// scheme).');
2576
    $this->assertEqual(filesize($retrieved_file), 7, 'File size of downloaded file is correct (public:// scheme).');
2577
    file_unmanaged_delete($retrieved_file);
2578

    
2579
    // Test downloading file to a different location.
2580
    drupal_mkdir($targetdir = 'temporary://' . $this->randomName());
2581
    $retrieved_file = system_retrieve_file($url, $targetdir);
2582
    $this->assertEqual($retrieved_file, "$targetdir/$encoded_filename", 'Sane path for downloaded file returned (temporary:// scheme).');
2583
    $this->assertTrue(is_file($retrieved_file), 'Downloaded file does exist (temporary:// scheme).');
2584
    $this->assertEqual(filesize($retrieved_file), 7, 'File size of downloaded file is correct (temporary:// scheme).');
2585
    file_unmanaged_delete($retrieved_file);
2586

    
2587
    file_unmanaged_delete_recursive($sourcedir);
2588
    file_unmanaged_delete_recursive($targetdir);
2589
  }
2590
}
2591

    
2592
/**
2593
 * Functional tests shutdown functions.
2594
 */
2595
class ShutdownFunctionsTest extends DrupalWebTestCase {
2596
  public static function getInfo() {
2597
    return array(
2598
      'name' => 'Shutdown functions',
2599
      'description' => 'Functional tests for shutdown functions',
2600
      'group' => 'System',
2601
    );
2602
  }
2603

    
2604
  function setUp() {
2605
    parent::setUp('system_test');
2606
  }
2607

    
2608
  /**
2609
   * Test shutdown functions.
2610
   */
2611
  function testShutdownFunctions() {
2612
    $arg1 = $this->randomName();
2613
    $arg2 = $this->randomName();
2614
    $this->drupalGet('system-test/shutdown-functions/' . $arg1 . '/' . $arg2);
2615
    $this->assertText(t('First shutdown function, arg1 : @arg1, arg2: @arg2', array('@arg1' => $arg1, '@arg2' => $arg2)));
2616
    $this->assertText(t('Second shutdown function, arg1 : @arg1, arg2: @arg2', array('@arg1' => $arg1, '@arg2' => $arg2)));
2617

    
2618
    // Make sure exceptions displayed through _drupal_render_exception_safe()
2619
    // are correctly escaped.
2620
    $this->assertRaw('Drupal is &amp;lt;blink&amp;gt;awesome&amp;lt;/blink&amp;gt;.');
2621
  }
2622
}
2623

    
2624
/**
2625
 * Tests administrative overview pages.
2626
 */
2627
class SystemAdminTestCase extends DrupalWebTestCase {
2628
  public static function getInfo() {
2629
    return array(
2630
      'name' => 'Administrative pages',
2631
      'description' => 'Tests output on administrative pages and compact mode functionality.',
2632
      'group' => 'System',
2633
    );
2634
  }
2635

    
2636
  function setUp() {
2637
    // testAdminPages() requires Locale module.
2638
    parent::setUp(array('locale'));
2639

    
2640
    // Create an administrator with all permissions, as well as a regular user
2641
    // who can only access administration pages and perform some Locale module
2642
    // administrative tasks, but not all of them.
2643
    $this->admin_user = $this->drupalCreateUser(array_keys(module_invoke_all('permission')));
2644
    $this->web_user = $this->drupalCreateUser(array(
2645
      'access administration pages',
2646
      'translate interface',
2647
    ));
2648
    $this->drupalLogin($this->admin_user);
2649
  }
2650

    
2651
  /**
2652
   * Tests output on administrative listing pages.
2653
   */
2654
  function testAdminPages() {
2655
    // Go to Administration.
2656
    $this->drupalGet('admin');
2657

    
2658
    // Verify that all visible, top-level administration links are listed on
2659
    // the main administration page.
2660
    foreach (menu_get_router() as $path => $item) {
2661
      if (strpos($path, 'admin/') === 0 && ($item['type'] & MENU_VISIBLE_IN_TREE) && $item['_number_parts'] == 2) {
2662
        $this->assertLink($item['title']);
2663
        $this->assertLinkByHref($path);
2664
        $this->assertText($item['description']);
2665
      }
2666
    }
2667

    
2668
    // For each administrative listing page on which the Locale module appears,
2669
    // verify that there are links to the module's primary configuration pages,
2670
    // but no links to its individual sub-configuration pages. Also verify that
2671
    // a user with access to only some Locale module administration pages only
2672
    // sees links to the pages they have access to.
2673
    $admin_list_pages = array(
2674
      'admin/index',
2675
      'admin/config',
2676
      'admin/config/regional',
2677
    );
2678

    
2679
    foreach ($admin_list_pages as $page) {
2680
      // For the administrator, verify that there are links to Locale's primary
2681
      // configuration pages, but no links to individual sub-configuration
2682
      // pages.
2683
      $this->drupalLogin($this->admin_user);
2684
      $this->drupalGet($page);
2685
      $this->assertLinkByHref('admin/config');
2686
      $this->assertLinkByHref('admin/config/regional/settings');
2687
      $this->assertLinkByHref('admin/config/regional/date-time');
2688
      $this->assertLinkByHref('admin/config/regional/language');
2689
      $this->assertNoLinkByHref('admin/config/regional/language/configure/session');
2690
      $this->assertNoLinkByHref('admin/config/regional/language/configure/url');
2691
      $this->assertLinkByHref('admin/config/regional/translate');
2692
      // On admin/index only, the administrator should also see a "Configure
2693
      // permissions" link for the Locale module.
2694
      if ($page == 'admin/index') {
2695
        $this->assertLinkByHref("admin/people/permissions#module-locale");
2696
      }
2697

    
2698
      // For a less privileged user, verify that there are no links to Locale's
2699
      // primary configuration pages, but a link to the translate page exists.
2700
      $this->drupalLogin($this->web_user);
2701
      $this->drupalGet($page);
2702
      $this->assertLinkByHref('admin/config');
2703
      $this->assertNoLinkByHref('admin/config/regional/settings');
2704
      $this->assertNoLinkByHref('admin/config/regional/date-time');
2705
      $this->assertNoLinkByHref('admin/config/regional/language');
2706
      $this->assertNoLinkByHref('admin/config/regional/language/configure/session');
2707
      $this->assertNoLinkByHref('admin/config/regional/language/configure/url');
2708
      $this->assertLinkByHref('admin/config/regional/translate');
2709
      // This user cannot configure permissions, so even on admin/index should
2710
      // not see a "Configure permissions" link for the Locale module.
2711
      if ($page == 'admin/index') {
2712
        $this->assertNoLinkByHref("admin/people/permissions#module-locale");
2713
      }
2714
    }
2715
  }
2716

    
2717
  /**
2718
   * Test compact mode.
2719
   */
2720
  function testCompactMode() {
2721
    $this->drupalGet('admin/compact/on');
2722
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode turns on.');
2723
    $this->drupalGet('admin/compact/on');
2724
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode remains on after a repeat call.');
2725
    $this->drupalGet('');
2726
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode persists on new requests.');
2727

    
2728
    $this->drupalGet('admin/compact/off');
2729
    $this->assertEqual($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'deleted', 'Compact mode turns off.');
2730
    $this->drupalGet('admin/compact/off');
2731
    $this->assertEqual($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'deleted', 'Compact mode remains off after a repeat call.');
2732
    $this->drupalGet('');
2733
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode persists on new requests.');
2734
  }
2735
}
2736

    
2737
/**
2738
 * Tests authorize.php and related hooks.
2739
 */
2740
class SystemAuthorizeCase extends DrupalWebTestCase {
2741
  public static function getInfo() {
2742
    return array(
2743
      'name' => 'Authorize API',
2744
      'description' => 'Tests the authorize.php script and related API.',
2745
      'group' => 'System',
2746
    );
2747
  }
2748

    
2749
  function setUp() {
2750
    parent::setUp(array('system_test'));
2751

    
2752
    variable_set('allow_authorize_operations', TRUE);
2753

    
2754
    // Create an administrator user.
2755
    $this->admin_user = $this->drupalCreateUser(array('administer software updates'));
2756
    $this->drupalLogin($this->admin_user);
2757
  }
2758

    
2759
  /**
2760
   * Helper function to initialize authorize.php and load it via drupalGet().
2761
   *
2762
   * Initializing authorize.php needs to happen in the child Drupal
2763
   * installation, not the parent. So, we visit a menu callback provided by
2764
   * system_test.module which calls system_authorized_init() to initialize the
2765
   * $_SESSION inside the test site, not the framework site. This callback
2766
   * redirects to authorize.php when it's done initializing.
2767
   *
2768
   * @see system_authorized_init().
2769
   */
2770
  function drupalGetAuthorizePHP($page_title = 'system-test-auth') {
2771
    $this->drupalGet('system-test/authorize-init/' . $page_title);
2772
  }
2773

    
2774
  /**
2775
   * Tests the FileTransfer hooks
2776
   */
2777
  function testFileTransferHooks() {
2778
    $page_title = $this->randomName(16);
2779
    $this->drupalGetAuthorizePHP($page_title);
2780
    $this->assertTitle(strtr('@title | Drupal', array('@title' => $page_title)), 'authorize.php page title is correct.');
2781
    $this->assertNoText('It appears you have reached this page in error.');
2782
    $this->assertText('To continue, provide your server connection details');
2783
    // Make sure we see the new connection method added by system_test.
2784
    $this->assertRaw('System Test FileTransfer');
2785
    // Make sure the settings form callback works.
2786
    $this->assertText('System Test Username');
2787
  }
2788
}
2789

    
2790
/**
2791
 * Test the handling of requests containing 'index.php'.
2792
 */
2793
class SystemIndexPhpTest extends DrupalWebTestCase {
2794
  public static function getInfo() {
2795
    return array(
2796
      'name' => 'Index.php handling',
2797
      'description' => "Test the handling of requests containing 'index.php'.",
2798
      'group' => 'System',
2799
    );
2800
  }
2801

    
2802
  function setUp() {
2803
    parent::setUp();
2804
  }
2805

    
2806
  /**
2807
   * Test index.php handling.
2808
   */
2809
  function testIndexPhpHandling() {
2810
    $index_php = $GLOBALS['base_url'] . '/index.php';
2811

    
2812
    $this->drupalGet($index_php, array('external' => TRUE));
2813
    $this->assertResponse(200, 'Make sure index.php returns a valid page.');
2814

    
2815
    $this->drupalGet($index_php, array('external' => TRUE, 'query' => array('q' => 'user')));
2816
    $this->assertResponse(200, 'Make sure index.php?q=user returns a valid page.');
2817

    
2818
    $this->drupalGet($index_php .'/user', array('external' => TRUE));
2819
    $this->assertResponse(404, "Make sure index.php/user returns a 'page not found'.");
2820
  }
2821
}
2822

    
2823
/**
2824
 * Test token replacement in strings.
2825
 */
2826
class TokenScanTest extends DrupalWebTestCase {
2827

    
2828
  public static function getInfo() {
2829
    return array(
2830
      'name' => 'Token scanning',
2831
      'description' => 'Scan token-like patterns in a dummy text to check token scanning.',
2832
      'group' => 'System',
2833
    );
2834
  }
2835

    
2836
  /**
2837
   * Scans dummy text, then tests the output.
2838
   */
2839
  function testTokenScan() {
2840
    // Define text with valid and not valid, fake and existing token-like
2841
    // strings.
2842
    $text = 'First a [valid:simple], but dummy token, and a dummy [valid:token with: spaces].';
2843
    $text .= 'Then a [not valid:token].';
2844
    $text .= 'Last an existing token: [node:author:name].';
2845
    $token_wannabes = token_scan($text);
2846

    
2847
    $this->assertTrue(isset($token_wannabes['valid']['simple']), 'A simple valid token has been matched.');
2848
    $this->assertTrue(isset($token_wannabes['valid']['token with: spaces']), 'A valid token with space characters in the token name has been matched.');
2849
    $this->assertFalse(isset($token_wannabes['not valid']), 'An invalid token with spaces in the token type has not been matched.');
2850
    $this->assertTrue(isset($token_wannabes['node']), 'An existing valid token has been matched.');
2851
  }
2852
}
2853

    
2854
/**
2855
 * Test case for drupal_valid_token().
2856
 */
2857
class SystemValidTokenTest extends DrupalUnitTestCase {
2858

    
2859
  /**
2860
   * Flag to indicate whether PHP error reportings should be asserted.
2861
   *
2862
   * @var bool
2863
   */
2864
  protected $assertErrors = TRUE;
2865

    
2866
  public static function getInfo() {
2867
    return array(
2868
      'name' => 'Token validation',
2869
      'description' => 'Test the security token validation.',
2870
      'group' => 'System',
2871
    );
2872
  }
2873

    
2874
  /**
2875
   * Tests invalid invocations of drupal_valid_token() that must return FALSE.
2876
   */
2877
  public function testTokenValidation() {
2878
    // The following checks will throw PHP notices, so we disable error
2879
    // assertions.
2880
    $this->assertErrors = FALSE;
2881
    $this->assertFalse(drupal_valid_token(NULL, new stdClass()), 'Token NULL, value object returns FALSE.');
2882
    $this->assertFalse(drupal_valid_token(0, array()), 'Token 0, value array returns FALSE.');
2883
    $this->assertFalse(drupal_valid_token('', array()), "Token '', value array returns FALSE.");
2884
    $this->assertFalse('' === drupal_get_token(array()), 'Token generation does not return an empty string on invalid parameters.');
2885
    $this->assertErrors = TRUE;
2886

    
2887
    $this->assertFalse(drupal_valid_token(TRUE, 'foo'), 'Token TRUE, value foo returns FALSE.');
2888
    $this->assertFalse(drupal_valid_token(0, 'foo'), 'Token 0, value foo returns FALSE.');
2889
  }
2890

    
2891
  /**
2892
   * Overrides DrupalTestCase::errorHandler().
2893
   */
2894
  public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
2895
    if ($this->assertErrors) {
2896
      return parent::errorHandler($severity, $message, $file, $line);
2897
    }
2898
    return TRUE;
2899
  }
2900
}
2901

    
2902
/**
2903
 * Tests drupal_set_message() and related functions.
2904
 */
2905
class DrupalSetMessageTest extends DrupalWebTestCase {
2906

    
2907
  public static function getInfo() {
2908
    return array(
2909
      'name' => 'Messages',
2910
      'description' => 'Tests that messages can be displayed using drupal_set_message().',
2911
      'group' => 'System',
2912
    );
2913
  }
2914

    
2915
  function setUp() {
2916
    parent::setUp('system_test');
2917
  }
2918

    
2919
  /**
2920
   * Tests setting messages and removing one before it is displayed.
2921
   */
2922
  function testSetRemoveMessages() {
2923
    // The page at system-test/drupal-set-message sets two messages and then
2924
    // removes the first before it is displayed.
2925
    $this->drupalGet('system-test/drupal-set-message');
2926
    $this->assertNoText('First message (removed).');
2927
    $this->assertText('Second message (not removed).');
2928
  }
2929
}
2930

    
2931
/**
2932
 * Tests confirm form destinations.
2933
 */
2934
class ConfirmFormTest extends DrupalWebTestCase {
2935
  protected $admin_user;
2936

    
2937
  public static function getInfo() {
2938
    return array(
2939
      'name' => 'Confirm form',
2940
      'description' => 'Tests that the confirm form does not use external destinations.',
2941
      'group' => 'System',
2942
    );
2943
  }
2944

    
2945
  function setUp() {
2946
    parent::setUp();
2947

    
2948
    $this->admin_user = $this->drupalCreateUser(array('administer users'));
2949
    $this->drupalLogin($this->admin_user);
2950
  }
2951

    
2952
  /**
2953
   * Tests that the confirm form does not use external destinations.
2954
   */
2955
  function testConfirmForm() {
2956
    $this->drupalGet('user/1/cancel');
2957
    $this->assertCancelLinkUrl(url('user/1'));
2958
    $this->drupalGet('user/1/cancel', array('query' => array('destination' => 'node')));
2959
    $this->assertCancelLinkUrl(url('node'));
2960
    $this->drupalGet('user/1/cancel', array('query' => array('destination' => 'http://example.com')));
2961
    $this->assertCancelLinkUrl(url('user/1'));
2962
  }
2963

    
2964
  /**
2965
   * Asserts that a cancel link is present pointing to the provided URL.
2966
   */
2967
  function assertCancelLinkUrl($url, $message = '', $group = 'Other') {
2968
    $links = $this->xpath('//a[normalize-space(text())=:label and @href=:url]', array(':label' => t('Cancel'), ':url' => $url));
2969
    $message = ($message ? $message : format_string('Cancel link with url %url found.', array('%url' => $url)));
2970
    return $this->assertTrue(isset($links[0]), $message, $group);
2971
  }
2972
}