Projet

Général

Profil

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

root / drupal7 / modules / system / system.test @ 30d5b9c5

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
    // Delete custom date format.
1354
    $this->clickLink(t('delete'));
1355
    $this->drupalPost($this->getUrl(), array(), t('Remove'));
1356
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE)), 'Correct page redirection.');
1357
    $this->assertText(t('Removed date format'), 'Custom date format removed successfully.');
1358
  }
1359

    
1360
  /**
1361
   * Test if the date formats are stored properly.
1362
   */
1363
  function testDateFormatStorage() {
1364
    $date_format = array(
1365
      'type' => 'short',
1366
      'format' => 'dmYHis',
1367
      'locked' => 0,
1368
      'is_new' => 1,
1369
    );
1370
    system_date_format_save($date_format);
1371

    
1372
    $format = db_select('date_formats', 'df')
1373
      ->fields('df', array('format'))
1374
      ->condition('type', 'short')
1375
      ->condition('format', 'dmYHis')
1376
      ->execute()
1377
      ->fetchField();
1378
    $this->verbose($format);
1379
    $this->assertEqual('dmYHis', $format, 'Unlocalized date format resides in general table.');
1380

    
1381
    $format = db_select('date_format_locale', 'dfl')
1382
      ->fields('dfl', array('format'))
1383
      ->condition('type', 'short')
1384
      ->condition('format', 'dmYHis')
1385
      ->execute()
1386
      ->fetchField();
1387
    $this->assertFalse($format, 'Unlocalized date format resides not in localized table.');
1388

    
1389
    // Enable German language
1390
    locale_add_language('de', NULL, NULL, LANGUAGE_LTR, '', '', TRUE, 'en');
1391

    
1392
    $date_format = array(
1393
      'type' => 'short',
1394
      'format' => 'YMDHis',
1395
      'locales' => array('de', 'tr'),
1396
      'locked' => 0,
1397
      'is_new' => 1,
1398
    );
1399
    system_date_format_save($date_format);
1400

    
1401
    $format = db_select('date_format_locale', 'dfl')
1402
      ->fields('dfl', array('format'))
1403
      ->condition('type', 'short')
1404
      ->condition('format', 'YMDHis')
1405
      ->condition('language', 'de')
1406
      ->execute()
1407
      ->fetchField();
1408
    $this->assertEqual('YMDHis', $format, 'Localized date format resides in localized table.');
1409

    
1410
    $format = db_select('date_formats', 'df')
1411
      ->fields('df', array('format'))
1412
      ->condition('type', 'short')
1413
      ->condition('format', 'YMDHis')
1414
      ->execute()
1415
      ->fetchField();
1416
    $this->assertEqual('YMDHis', $format, 'Localized date format resides in general table too.');
1417

    
1418
    $format = db_select('date_format_locale', 'dfl')
1419
      ->fields('dfl', array('format'))
1420
      ->condition('type', 'short')
1421
      ->condition('format', 'YMDHis')
1422
      ->condition('language', 'tr')
1423
      ->execute()
1424
      ->fetchColumn();
1425
    $this->assertFalse($format, 'Localized date format for disabled language is ignored.');
1426
  }
1427
}
1428

    
1429
class PageTitleFiltering extends DrupalWebTestCase {
1430
  protected $content_user;
1431
  protected $saved_title;
1432

    
1433
  /**
1434
   * Implement getInfo().
1435
   */
1436
  public static function getInfo() {
1437
    return array(
1438
      'name' => 'HTML in page titles',
1439
      'description' => 'Tests correct handling or conversion by drupal_set_title() and drupal_get_title() and checks the correct escaping of site name and slogan.',
1440
      'group' => 'System'
1441
    );
1442
  }
1443

    
1444
  /**
1445
   * Implement setUp().
1446
   */
1447
  function setUp() {
1448
    parent::setUp();
1449

    
1450
    $this->content_user = $this->drupalCreateUser(array('create page content', 'access content', 'administer themes', 'administer site configuration'));
1451
    $this->drupalLogin($this->content_user);
1452
    $this->saved_title = drupal_get_title();
1453
  }
1454

    
1455
  /**
1456
   * Reset page title.
1457
   */
1458
  function tearDown() {
1459
    // Restore the page title.
1460
    drupal_set_title($this->saved_title, PASS_THROUGH);
1461

    
1462
    parent::tearDown();
1463
  }
1464

    
1465
  /**
1466
   * Tests the handling of HTML by drupal_set_title() and drupal_get_title()
1467
   */
1468
  function testTitleTags() {
1469
    $title = "string with <em>HTML</em>";
1470
    // drupal_set_title's $filter is CHECK_PLAIN by default, so the title should be
1471
    // returned with check_plain().
1472
    drupal_set_title($title, CHECK_PLAIN);
1473
    $this->assertTrue(strpos(drupal_get_title(), '<em>') === FALSE, 'Tags in title converted to entities when $output is CHECK_PLAIN.');
1474
    // drupal_set_title's $filter is passed as PASS_THROUGH, so the title should be
1475
    // returned with HTML.
1476
    drupal_set_title($title, PASS_THROUGH);
1477
    $this->assertTrue(strpos(drupal_get_title(), '<em>') !== FALSE, 'Tags in title are not converted to entities when $output is PASS_THROUGH.');
1478
    // Generate node content.
1479
    $langcode = LANGUAGE_NONE;
1480
    $edit = array(
1481
      "title" => '!SimpleTest! ' . $title . $this->randomName(20),
1482
      "body[$langcode][0][value]" => '!SimpleTest! test body' . $this->randomName(200),
1483
    );
1484
    // Create the node with HTML in the title.
1485
    $this->drupalPost('node/add/page', $edit, t('Save'));
1486

    
1487
    $node = $this->drupalGetNodeByTitle($edit["title"]);
1488
    $this->assertNotNull($node, 'Node created and found in database');
1489
    $this->drupalGet("node/" . $node->nid);
1490
    $this->assertText(check_plain($edit["title"]), 'Check to make sure tags in the node title are converted.');
1491
  }
1492
  /**
1493
   * Test if the title of the site is XSS proof.
1494
   */
1495
  function testTitleXSS() {
1496
    // Set some title with JavaScript and HTML chars to escape.
1497
    $title = '</title><script type="text/javascript">alert("Title XSS!");</script> & < > " \' ';
1498
    $title_filtered = check_plain($title);
1499

    
1500
    $slogan = '<script type="text/javascript">alert("Slogan XSS!");</script>';
1501
    $slogan_filtered = filter_xss_admin($slogan);
1502

    
1503
    // Activate needed appearance settings.
1504
    $edit = array(
1505
      'toggle_name'           => TRUE,
1506
      'toggle_slogan'         => TRUE,
1507
      'toggle_main_menu'      => TRUE,
1508
      'toggle_secondary_menu' => TRUE,
1509
    );
1510
    $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
1511

    
1512
    // Set title and slogan.
1513
    $edit = array(
1514
      'site_name'    => $title,
1515
      'site_slogan'  => $slogan,
1516
    );
1517
    $this->drupalPost('admin/config/system/site-information', $edit, t('Save configuration'));
1518

    
1519
    // Load frontpage.
1520
    $this->drupalGet('');
1521

    
1522
    // Test the title.
1523
    $this->assertNoRaw($title, 'Check for the unfiltered version of the title.');
1524
    // Adding </title> so we do not test the escaped version from drupal_set_title().
1525
    $this->assertRaw($title_filtered . '</title>', 'Check for the filtered version of the title.');
1526

    
1527
    // Test the slogan.
1528
    $this->assertNoRaw($slogan, 'Check for the unfiltered version of the slogan.');
1529
    $this->assertRaw($slogan_filtered, 'Check for the filtered version of the slogan.');
1530
  }
1531
}
1532

    
1533
/**
1534
 * Test front page functionality and administration.
1535
 */
1536
class FrontPageTestCase extends DrupalWebTestCase {
1537

    
1538
  public static function getInfo() {
1539
    return array(
1540
      'name' => 'Front page',
1541
      'description' => 'Tests front page functionality and administration.',
1542
      'group' => 'System',
1543
    );
1544
  }
1545

    
1546
  function setUp() {
1547
    parent::setUp('system_test');
1548

    
1549
    // Create admin user, log in admin user, and create one node.
1550
    $this->admin_user = $this->drupalCreateUser(array('access content', 'administer site configuration'));
1551
    $this->drupalLogin($this->admin_user);
1552
    $this->node_path = "node/" . $this->drupalCreateNode(array('promote' => 1))->nid;
1553

    
1554
    // Enable front page logging in system_test.module.
1555
    variable_set('front_page_output', 1);
1556
  }
1557

    
1558
  /**
1559
   * Test front page functionality.
1560
   */
1561
  function testDrupalIsFrontPage() {
1562
    $this->drupalGet('');
1563
    $this->assertText(t('On front page.'), 'Path is the front page.');
1564
    $this->drupalGet('node');
1565
    $this->assertText(t('On front page.'), 'Path is the front page.');
1566
    $this->drupalGet($this->node_path);
1567
    $this->assertNoText(t('On front page.'), 'Path is not the front page.');
1568

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

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

    
1579
    $this->drupalGet('');
1580
    $this->assertText(t('On front page.'), 'Path is the front page.');
1581
    $this->drupalGet('node');
1582
    $this->assertNoText(t('On front page.'), 'Path is not the front page.');
1583
    $this->drupalGet($this->node_path);
1584
    $this->assertText(t('On front page.'), 'Path is the front page.');
1585
  }
1586
}
1587

    
1588
class SystemBlockTestCase extends DrupalWebTestCase {
1589
  protected $profile = 'testing';
1590

    
1591
  public static function getInfo() {
1592
    return array(
1593
      'name' => 'Block functionality',
1594
      'description' => 'Configure and move powered-by block.',
1595
      'group' => 'System',
1596
    );
1597
  }
1598

    
1599
  function setUp() {
1600
    parent::setUp('block');
1601

    
1602
    // Create and login user
1603
    $admin_user = $this->drupalCreateUser(array('administer blocks', 'access administration pages'));
1604
    $this->drupalLogin($admin_user);
1605
  }
1606

    
1607
  /**
1608
   * Test displaying and hiding the powered-by and help blocks.
1609
   */
1610
  function testSystemBlocks() {
1611
    // Set block title and some settings to confirm that the interface is available.
1612
    $this->drupalPost('admin/structure/block/manage/system/powered-by/configure', array('title' => $this->randomName(8)), t('Save block'));
1613
    $this->assertText(t('The block configuration has been saved.'), t('Block configuration set.'));
1614

    
1615
    // Set the powered-by block to the footer region.
1616
    $edit = array();
1617
    $edit['blocks[system_powered-by][region]'] = 'footer';
1618
    $edit['blocks[system_main][region]'] = 'content';
1619
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1620
    $this->assertText(t('The block settings have been updated.'), t('Block successfully moved to footer region.'));
1621

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

    
1626
    // Set the block to the disabled region.
1627
    $edit = array();
1628
    $edit['blocks[system_powered-by][region]'] = '-1';
1629
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1630

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

    
1634
    // For convenience of developers, set the block to its default settings.
1635
    $edit = array();
1636
    $edit['blocks[system_powered-by][region]'] = 'footer';
1637
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1638
    $this->drupalPost('admin/structure/block/manage/system/powered-by/configure', array('title' => ''), t('Save block'));
1639

    
1640
    // Set the help block to the help region.
1641
    $edit = array();
1642
    $edit['blocks[system_help][region]'] = 'help';
1643
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1644

    
1645
    // Test displaying the help block with block caching enabled.
1646
    variable_set('block_cache', TRUE);
1647
    $this->drupalGet('admin/structure/block/add');
1648
    $this->assertRaw(t('Use this page to create a new custom block.'));
1649
    $this->drupalGet('admin/index');
1650
    $this->assertRaw(t('This page shows you all available administration tasks for each module.'));
1651
  }
1652
}
1653

    
1654
/**
1655
 * Test main content rendering fallback provided by system module.
1656
 */
1657
class SystemMainContentFallback extends DrupalWebTestCase {
1658
  protected $admin_user;
1659
  protected $web_user;
1660

    
1661
  public static function getInfo() {
1662
    return array(
1663
      'name' => 'Main content rendering fallback',
1664
      'description' => ' Test system module main content rendering fallback.',
1665
      'group' => 'System',
1666
    );
1667
  }
1668

    
1669
  function setUp() {
1670
    parent::setUp('system_test');
1671

    
1672
    // Create and login admin user.
1673
    $this->admin_user = $this->drupalCreateUser(array(
1674
      'access administration pages',
1675
      'administer site configuration',
1676
      'administer modules',
1677
      'administer blocks',
1678
      'administer nodes',
1679
    ));
1680
    $this->drupalLogin($this->admin_user);
1681

    
1682
    // Create a web user.
1683
    $this->web_user = $this->drupalCreateUser(array('access user profiles', 'access content'));
1684
  }
1685

    
1686
  /**
1687
   * Test availability of main content.
1688
   */
1689
  function testMainContentFallback() {
1690
    $edit = array();
1691
    // Disable the dashboard module, which depends on the block module.
1692
    $edit['modules[Core][dashboard][enable]'] = FALSE;
1693
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
1694
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
1695
    // Disable the block module.
1696
    $edit['modules[Core][block][enable]'] = FALSE;
1697
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
1698
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
1699
    module_list(TRUE);
1700
    $this->assertFalse(module_exists('block'), 'Block module disabled.');
1701

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

    
1706
    // Fallback should not trigger when another module is handling content.
1707
    $this->drupalGet('system-test/main-content-handling');
1708
    $this->assertRaw('id="system-test-content"', 'Content handled by another module');
1709
    $this->assertText(t('Content to test main content fallback'), 'Main content still displayed.');
1710

    
1711
    // Fallback should trigger when another module
1712
    // indicates that it is not handling the content.
1713
    $this->drupalGet('system-test/main-content-fallback');
1714
    $this->assertText(t('Content to test main content fallback'), 'Main content fallback properly triggers.');
1715

    
1716
    // Fallback should not trigger when another module is handling content.
1717
    // Note that this test ensures that no duplicate
1718
    // content gets created by the fallback.
1719
    $this->drupalGet('system-test/main-content-duplication');
1720
    $this->assertNoText(t('Content to test main content fallback'), 'Main content not duplicated.');
1721

    
1722
    // Request a user* page and see if it is displayed.
1723
    $this->drupalLogin($this->web_user);
1724
    $this->drupalGet('user/' . $this->web_user->uid . '/edit');
1725
    $this->assertField('mail', 'User interface still available.');
1726

    
1727
    // Enable the block module again.
1728
    $this->drupalLogin($this->admin_user);
1729
    $edit = array();
1730
    $edit['modules[Core][block][enable]'] = 'block';
1731
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
1732
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
1733
    module_list(TRUE);
1734
    $this->assertTrue(module_exists('block'), 'Block module re-enabled.');
1735
  }
1736
}
1737

    
1738
/**
1739
 * Tests for the theme interface functionality.
1740
 */
1741
class SystemThemeFunctionalTest extends DrupalWebTestCase {
1742
  public static function getInfo() {
1743
    return array(
1744
      'name' => 'Theme interface functionality',
1745
      'description' => 'Tests the theme interface functionality by enabling and switching themes, and using an administration theme.',
1746
      'group' => 'System',
1747
    );
1748
  }
1749

    
1750
  function setUp() {
1751
    parent::setUp();
1752

    
1753
    $this->admin_user = $this->drupalCreateUser(array('access administration pages', 'view the administration theme', 'administer themes', 'bypass node access', 'administer blocks'));
1754
    $this->drupalLogin($this->admin_user);
1755
    $this->node = $this->drupalCreateNode();
1756
  }
1757

    
1758
  /**
1759
   * Test the theme settings form.
1760
   */
1761
  function testThemeSettings() {
1762
    // Specify a filesystem path to be used for the logo.
1763
    $file = current($this->drupalGetTestFiles('image'));
1764
    $file_relative = strtr($file->uri, array('public:/' => variable_get('file_public_path', conf_path() . '/files')));
1765
    $default_theme_path = 'themes/stark';
1766

    
1767
    $supported_paths = array(
1768
      // Raw stream wrapper URI.
1769
      $file->uri => array(
1770
        'form' => file_uri_target($file->uri),
1771
        'src' => file_create_url($file->uri),
1772
      ),
1773
      // Relative path within the public filesystem.
1774
      file_uri_target($file->uri) => array(
1775
        'form' => file_uri_target($file->uri),
1776
        'src' => file_create_url($file->uri),
1777
      ),
1778
      // Relative path to a public file.
1779
      $file_relative => array(
1780
        'form' => $file_relative,
1781
        'src' => file_create_url($file->uri),
1782
      ),
1783
      // Relative path to an arbitrary file.
1784
      'misc/druplicon.png' => array(
1785
        'form' => 'misc/druplicon.png',
1786
        'src' => $GLOBALS['base_url'] . '/' . 'misc/druplicon.png',
1787
      ),
1788
      // Relative path to a file in a theme.
1789
      $default_theme_path . '/logo.png' => array(
1790
        'form' => $default_theme_path . '/logo.png',
1791
        'src' => $GLOBALS['base_url'] . '/' . $default_theme_path . '/logo.png',
1792
      ),
1793
    );
1794
    foreach ($supported_paths as $input => $expected) {
1795
      $edit = array(
1796
        'default_logo' => FALSE,
1797
        'logo_path' => $input,
1798
      );
1799
      $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
1800
      $this->assertNoText('The custom logo path is invalid.');
1801
      $this->assertFieldByName('logo_path', $expected['form']);
1802

    
1803
      // Verify the actual 'src' attribute of the logo being output.
1804
      $this->drupalGet('');
1805
      $elements = $this->xpath('//*[@id=:id]/img', array(':id' => 'logo'));
1806
      $this->assertEqual((string) $elements[0]['src'], $expected['src']);
1807
    }
1808

    
1809
    $unsupported_paths = array(
1810
      // Stream wrapper URI to non-existing file.
1811
      'public://whatever.png',
1812
      'private://whatever.png',
1813
      'temporary://whatever.png',
1814
      // Bogus stream wrapper URIs.
1815
      'public:/whatever.png',
1816
      '://whatever.png',
1817
      ':whatever.png',
1818
      'public://',
1819
      // Relative path within the public filesystem to non-existing file.
1820
      'whatever.png',
1821
      // Relative path to non-existing file in public filesystem.
1822
      variable_get('file_public_path', conf_path() . '/files') . '/whatever.png',
1823
      // Semi-absolute path to non-existing file in public filesystem.
1824
      '/' . variable_get('file_public_path', conf_path() . '/files') . '/whatever.png',
1825
      // Relative path to arbitrary non-existing file.
1826
      'misc/whatever.png',
1827
      // Semi-absolute path to arbitrary non-existing file.
1828
      '/misc/whatever.png',
1829
      // Absolute paths to any local file (even if it exists).
1830
      drupal_realpath($file->uri),
1831
    );
1832
    $this->drupalGet('admin/appearance/settings');
1833
    foreach ($unsupported_paths as $path) {
1834
      $edit = array(
1835
        'default_logo' => FALSE,
1836
        'logo_path' => $path,
1837
      );
1838
      $this->drupalPost(NULL, $edit, t('Save configuration'));
1839
      $this->assertText('The custom logo path is invalid.');
1840
    }
1841

    
1842
    // Upload a file to use for the logo.
1843
    $edit = array(
1844
      'default_logo' => FALSE,
1845
      'logo_path' => '',
1846
      'files[logo_upload]' => drupal_realpath($file->uri),
1847
    );
1848
    $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
1849

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

    
1853
    $this->drupalGet('');
1854
    $elements = $this->xpath('//*[@id=:id]/img', array(':id' => 'logo'));
1855
    $this->assertEqual($elements[0]['src'], file_create_url($uploaded_filename));
1856
  }
1857

    
1858
  /**
1859
   * Test the administration theme functionality.
1860
   */
1861
  function testAdministrationTheme() {
1862
    theme_enable(array('stark'));
1863
    variable_set('theme_default', 'stark');
1864
    // Enable an administration theme and show it on the node admin pages.
1865
    $edit = array(
1866
      'admin_theme' => 'seven',
1867
      'node_admin_theme' => TRUE,
1868
    );
1869
    $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
1870

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

    
1874
    $this->drupalGet('node/' . $this->node->nid);
1875
    $this->assertRaw('themes/stark', 'Site default theme used on node page.');
1876

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

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

    
1883
    // Disable the admin theme on the node admin pages.
1884
    $edit = array(
1885
      'node_admin_theme' => FALSE,
1886
    );
1887
    $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
1888

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

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

    
1895
    // Reset to the default theme settings.
1896
    variable_set('theme_default', 'bartik');
1897
    $edit = array(
1898
      'admin_theme' => '0',
1899
      'node_admin_theme' => FALSE,
1900
    );
1901
    $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
1902

    
1903
    $this->drupalGet('admin');
1904
    $this->assertRaw('themes/bartik', 'Site default theme used on administration page.');
1905

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

    
1910
  /**
1911
   * Test switching the default theme.
1912
   */
1913
  function testSwitchDefaultTheme() {
1914
    // Enable "stark" and set it as the default theme.
1915
    theme_enable(array('stark'));
1916
    $this->drupalGet('admin/appearance');
1917
    $this->clickLink(t('Set default'), 1);
1918
    $this->assertTrue(variable_get('theme_default', '') == 'stark', 'Site default theme switched successfully.');
1919

    
1920
    // Test the default theme on the secondary links (blocks admin page).
1921
    $this->drupalGet('admin/structure/block');
1922
    $this->assertText('Stark(' . t('active tab') . ')', 'Default local task on blocks admin page is the default theme.');
1923
    // Switch back to Bartik and test again to test that the menu cache is cleared.
1924
    $this->drupalGet('admin/appearance');
1925
    $this->clickLink(t('Set default'), 0);
1926
    $this->drupalGet('admin/structure/block');
1927
    $this->assertText('Bartik(' . t('active tab') . ')', 'Default local task on blocks admin page has changed.');
1928
  }
1929
}
1930

    
1931

    
1932
/**
1933
 * Test the basic queue functionality.
1934
 */
1935
class QueueTestCase extends DrupalWebTestCase {
1936
  public static function getInfo() {
1937
    return array(
1938
      'name' => 'Queue functionality',
1939
      'description' => 'Queues and dequeues a set of items to check the basic queue functionality.',
1940
      'group' => 'System',
1941
    );
1942
  }
1943

    
1944
  /**
1945
   * Queues and dequeues a set of items to check the basic queue functionality.
1946
   */
1947
  function testQueue() {
1948
    // Create two queues.
1949
    $queue1 = DrupalQueue::get($this->randomName());
1950
    $queue1->createQueue();
1951
    $queue2 = DrupalQueue::get($this->randomName());
1952
    $queue2->createQueue();
1953

    
1954
    // Create four items.
1955
    $data = array();
1956
    for ($i = 0; $i < 4; $i++) {
1957
      $data[] = array($this->randomName() => $this->randomName());
1958
    }
1959

    
1960
    // Queue items 1 and 2 in the queue1.
1961
    $queue1->createItem($data[0]);
1962
    $queue1->createItem($data[1]);
1963

    
1964
    // Retrieve two items from queue1.
1965
    $items = array();
1966
    $new_items = array();
1967

    
1968
    $items[] = $item = $queue1->claimItem();
1969
    $new_items[] = $item->data;
1970

    
1971
    $items[] = $item = $queue1->claimItem();
1972
    $new_items[] = $item->data;
1973

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

    
1977
    // Add two more items.
1978
    $queue1->createItem($data[2]);
1979
    $queue1->createItem($data[3]);
1980

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

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

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

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

    
1994
    // There should be no duplicate items.
1995
    $this->assertEqual($this->queueScore($new_items, $new_items), 4, 'Four items matched');
1996

    
1997
    // Delete all items from queue1.
1998
    foreach ($items as $item) {
1999
      $queue1->deleteItem($item);
2000
    }
2001

    
2002
    // Check that both queues are empty.
2003
    $this->assertFalse($queue1->numberOfItems(), 'Queue 1 is empty');
2004
    $this->assertFalse($queue2->numberOfItems(), 'Queue 2 is empty');
2005
  }
2006

    
2007
  /**
2008
   * This function returns the number of equal items in two arrays.
2009
   */
2010
  function queueScore($items, $new_items) {
2011
    $score = 0;
2012
    foreach ($items as $item) {
2013
      foreach ($new_items as $new_item) {
2014
        if ($item === $new_item) {
2015
          $score++;
2016
        }
2017
      }
2018
    }
2019
    return $score;
2020
  }
2021
}
2022

    
2023
/**
2024
 * Test token replacement in strings.
2025
 */
2026
class TokenReplaceTestCase extends DrupalWebTestCase {
2027
  public static function getInfo() {
2028
    return array(
2029
      'name' => 'Token replacement',
2030
      'description' => 'Generates text using placeholders for dummy content to check token replacement.',
2031
      'group' => 'System',
2032
    );
2033
  }
2034

    
2035
  /**
2036
   * Creates a user and a node, then tests the tokens generated from them.
2037
   */
2038
  function testTokenReplacement() {
2039
    // Create the initial objects.
2040
    $account = $this->drupalCreateUser();
2041
    $node = $this->drupalCreateNode(array('uid' => $account->uid));
2042
    $node->title = '<blink>Blinking Text</blink>';
2043
    global $user, $language;
2044

    
2045
    $source  = '[node:title]';         // Title of the node we passed in
2046
    $source .= '[node:author:name]';   // Node author's name
2047
    $source .= '[node:created:since]'; // Time since the node was created
2048
    $source .= '[current-user:name]';  // Current user's name
2049
    $source .= '[date:short]';         // Short date format of REQUEST_TIME
2050
    $source .= '[user:name]';          // No user passed in, should be untouched
2051
    $source .= '[bogus:token]';        // Non-existent token
2052

    
2053
    $target  = check_plain($node->title);
2054
    $target .= check_plain($account->name);
2055
    $target .= format_interval(REQUEST_TIME - $node->created, 2, $language->language);
2056
    $target .= check_plain($user->name);
2057
    $target .= format_date(REQUEST_TIME, 'short', '', NULL, $language->language);
2058

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

    
2063
    // Test without using the clear parameter (non-existent token untouched).
2064
    $target .= '[user:name]';
2065
    $target .= '[bogus:token]';
2066
    $result = token_replace($source, array('node' => $node), array('language' => $language));
2067
    $this->assertEqual($target, $result, 'Valid tokens replaced while invalid tokens ignored.');
2068

    
2069
    // Check that the results of token_generate are sanitized properly. This does NOT
2070
    // test the cleanliness of every token -- just that the $sanitize flag is being
2071
    // passed properly through the call stack and being handled correctly by a 'known'
2072
    // token, [node:title].
2073
    $raw_tokens = array('title' => '[node:title]');
2074
    $generated = token_generate('node', $raw_tokens, array('node' => $node));
2075
    $this->assertEqual($generated['[node:title]'], check_plain($node->title), 'Token sanitized.');
2076

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

    
2080
    // Test token replacement when the string contains no tokens.
2081
    $this->assertEqual(token_replace('No tokens here.'), 'No tokens here.');
2082
  }
2083

    
2084
  /**
2085
   * Test whether token-replacement works in various contexts.
2086
   */
2087
  function testSystemTokenRecognition() {
2088
    global $language;
2089

    
2090
    // Generate prefixes and suffixes for the token context.
2091
    $tests = array(
2092
      array('prefix' => 'this is the ', 'suffix' => ' site'),
2093
      array('prefix' => 'this is the', 'suffix' => 'site'),
2094
      array('prefix' => '[', 'suffix' => ']'),
2095
      array('prefix' => '', 'suffix' => ']]]'),
2096
      array('prefix' => '[[[', 'suffix' => ''),
2097
      array('prefix' => ':[:', 'suffix' => '--]'),
2098
      array('prefix' => '-[-', 'suffix' => ':]:'),
2099
      array('prefix' => '[:', 'suffix' => ']'),
2100
      array('prefix' => '[site:', 'suffix' => ':name]'),
2101
      array('prefix' => '[site:', 'suffix' => ']'),
2102
    );
2103

    
2104
    // Check if the token is recognized in each of the contexts.
2105
    foreach ($tests as $test) {
2106
      $input = $test['prefix'] . '[site:name]' . $test['suffix'];
2107
      $expected = $test['prefix'] . 'Drupal' . $test['suffix'];
2108
      $output = token_replace($input, array(), array('language' => $language));
2109
      $this->assertTrue($output == $expected, format_string('Token recognized in string %string', array('%string' => $input)));
2110
    }
2111
  }
2112

    
2113
  /**
2114
   * Tests the generation of all system site information tokens.
2115
   */
2116
  function testSystemSiteTokenReplacement() {
2117
    global $language;
2118
    $url_options = array(
2119
      'absolute' => TRUE,
2120
      'language' => $language,
2121
    );
2122

    
2123
    // Set a few site variables.
2124
    variable_set('site_name', '<strong>Drupal<strong>');
2125
    variable_set('site_slogan', '<blink>Slogan</blink>');
2126

    
2127
    // Generate and test sanitized tokens.
2128
    $tests = array();
2129
    $tests['[site:name]'] = check_plain(variable_get('site_name', 'Drupal'));
2130
    $tests['[site:slogan]'] = check_plain(variable_get('site_slogan', ''));
2131
    $tests['[site:mail]'] = 'simpletest@example.com';
2132
    $tests['[site:url]'] = url('<front>', $url_options);
2133
    $tests['[site:url-brief]'] = preg_replace(array('!^https?://!', '!/$!'), '', url('<front>', $url_options));
2134
    $tests['[site:login-url]'] = url('user', $url_options);
2135

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

    
2139
    foreach ($tests as $input => $expected) {
2140
      $output = token_replace($input, array(), array('language' => $language));
2141
      $this->assertEqual($output, $expected, format_string('Sanitized system site information token %token replaced.', array('%token' => $input)));
2142
    }
2143

    
2144
    // Generate and test unsanitized tokens.
2145
    $tests['[site:name]'] = variable_get('site_name', 'Drupal');
2146
    $tests['[site:slogan]'] = variable_get('site_slogan', '');
2147

    
2148
    foreach ($tests as $input => $expected) {
2149
      $output = token_replace($input, array(), array('language' => $language, 'sanitize' => FALSE));
2150
      $this->assertEqual($output, $expected, format_string('Unsanitized system site information token %token replaced.', array('%token' => $input)));
2151
    }
2152
  }
2153

    
2154
  /**
2155
   * Tests the generation of all system date tokens.
2156
   */
2157
  function testSystemDateTokenReplacement() {
2158
    global $language;
2159

    
2160
    // Set time to one hour before request.
2161
    $date = REQUEST_TIME - 3600;
2162

    
2163
    // Generate and test tokens.
2164
    $tests = array();
2165
    $tests['[date:short]'] = format_date($date, 'short', '', NULL, $language->language);
2166
    $tests['[date:medium]'] = format_date($date, 'medium', '', NULL, $language->language);
2167
    $tests['[date:long]'] = format_date($date, 'long', '', NULL, $language->language);
2168
    $tests['[date:custom:m/j/Y]'] = format_date($date, 'custom', 'm/j/Y', NULL, $language->language);
2169
    $tests['[date:since]'] = format_interval((REQUEST_TIME - $date), 2, $language->language);
2170
    $tests['[date:raw]'] = filter_xss($date);
2171

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

    
2175
    foreach ($tests as $input => $expected) {
2176
      $output = token_replace($input, array('date' => $date), array('language' => $language));
2177
      $this->assertEqual($output, $expected, format_string('Date token %token replaced.', array('%token' => $input)));
2178
    }
2179
  }
2180
}
2181

    
2182
class InfoFileParserTestCase extends DrupalUnitTestCase {
2183
  public static function getInfo() {
2184
    return array(
2185
      'name' => 'Info file format parser',
2186
      'description' => 'Tests proper parsing of a .info file formatted string.',
2187
      'group' => 'System',
2188
    );
2189
  }
2190

    
2191
  /**
2192
   * Test drupal_parse_info_format().
2193
   */
2194
  function testDrupalParseInfoFormat() {
2195
    $config = '
2196
simple = Value
2197
quoted = " Value"
2198
multiline = "Value
2199
  Value"
2200
array[] = Value1
2201
array[] = Value2
2202
array_assoc[a] = Value1
2203
array_assoc[b] = Value2
2204
array_deep[][][] = Value
2205
array_deep_assoc[a][b][c] = Value
2206
array_space[a b] = Value';
2207

    
2208
    $expected = array(
2209
      'simple' => 'Value',
2210
      'quoted' => ' Value',
2211
      'multiline' => "Value\n  Value",
2212
      'array' => array(
2213
        0 => 'Value1',
2214
        1 => 'Value2',
2215
      ),
2216
      'array_assoc' => array(
2217
        'a' => 'Value1',
2218
        'b' => 'Value2',
2219
      ),
2220
      'array_deep' => array(
2221
        0 => array(
2222
          0 => array(
2223
            0 => 'Value',
2224
          ),
2225
        ),
2226
      ),
2227
      'array_deep_assoc' => array(
2228
        'a' => array(
2229
          'b' => array(
2230
            'c' => 'Value',
2231
          ),
2232
        ),
2233
      ),
2234
      'array_space' => array(
2235
        'a b' => 'Value',
2236
      ),
2237
    );
2238

    
2239
    $parsed = drupal_parse_info_format($config);
2240

    
2241
    $this->assertEqual($parsed['simple'], $expected['simple'], 'Set a simple value.');
2242
    $this->assertEqual($parsed['quoted'], $expected['quoted'], 'Set a simple value in quotes.');
2243
    $this->assertEqual($parsed['multiline'], $expected['multiline'], 'Set a multiline value.');
2244
    $this->assertEqual($parsed['array'], $expected['array'], 'Set a simple array.');
2245
    $this->assertEqual($parsed['array_assoc'], $expected['array_assoc'], 'Set an associative array.');
2246
    $this->assertEqual($parsed['array_deep'], $expected['array_deep'], 'Set a nested array.');
2247
    $this->assertEqual($parsed['array_deep_assoc'], $expected['array_deep_assoc'], 'Set a nested associative array.');
2248
    $this->assertEqual($parsed['array_space'], $expected['array_space'], 'Set an array with a whitespace in the key.');
2249
    $this->assertEqual($parsed, $expected, 'Entire parsed .info string and expected array are identical.');
2250
  }
2251
}
2252

    
2253
/**
2254
 * Tests the effectiveness of hook_system_info_alter().
2255
 */
2256
class SystemInfoAlterTestCase extends DrupalWebTestCase {
2257
  public static function getInfo() {
2258
    return array(
2259
      'name' => 'System info alter',
2260
      'description' => 'Tests the effectiveness of hook_system_info_alter().',
2261
      'group' => 'System',
2262
    );
2263
  }
2264

    
2265
  /**
2266
   * Tests that {system}.info is rebuilt after a module that implements
2267
   * hook_system_info_alter() is enabled. Also tests if core *_list() functions
2268
   * return freshly altered info.
2269
   */
2270
  function testSystemInfoAlter() {
2271
    // Enable our test module. Flush all caches, which we assert is the only
2272
    // thing necessary to use the rebuilt {system}.info.
2273
    module_enable(array('module_test'), FALSE);
2274
    drupal_flush_all_caches();
2275
    $this->assertTrue(module_exists('module_test'), 'Test module is enabled.');
2276

    
2277
    $info = $this->getSystemInfo('seven', 'theme');
2278
    $this->assertTrue(isset($info['regions']['test_region']), 'Altered theme info was added to {system}.info.');
2279
    $seven_regions = system_region_list('seven');
2280
    $this->assertTrue(isset($seven_regions['test_region']), 'Altered theme info was returned by system_region_list().');
2281
    $system_list_themes = system_list('theme');
2282
    $info = $system_list_themes['seven']->info;
2283
    $this->assertTrue(isset($info['regions']['test_region']), 'Altered theme info was returned by system_list().');
2284
    $list_themes = list_themes();
2285
    $this->assertTrue(isset($list_themes['seven']->info['regions']['test_region']), 'Altered theme info was returned by list_themes().');
2286

    
2287
    // Disable the module and verify that {system}.info is rebuilt without it.
2288
    module_disable(array('module_test'), FALSE);
2289
    drupal_flush_all_caches();
2290
    $this->assertFalse(module_exists('module_test'), 'Test module is disabled.');
2291

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

    
2303
  /**
2304
   * Returns the info array as it is stored in {system}.
2305
   *
2306
   * @param $name
2307
   *   The name of the record in {system}.
2308
   * @param $type
2309
   *   The type of record in {system}.
2310
   *
2311
   * @return
2312
   *   Array of info, or FALSE if the record is not found.
2313
   */
2314
  function getSystemInfo($name, $type) {
2315
    $raw_info = db_query("SELECT info FROM {system} WHERE name = :name AND type = :type", array(':name' => $name, ':type' => $type))->fetchField();
2316
    return $raw_info ? unserialize($raw_info) : FALSE;
2317
  }
2318
}
2319

    
2320
/**
2321
 * Tests for the update system functionality.
2322
 */
2323
class UpdateScriptFunctionalTest extends DrupalWebTestCase {
2324
  private $update_url;
2325
  private $update_user;
2326

    
2327
  public static function getInfo() {
2328
    return array(
2329
      'name' => 'Update functionality',
2330
      'description' => 'Tests the update script access and functionality.',
2331
      'group' => 'System',
2332
    );
2333
  }
2334

    
2335
  function setUp() {
2336
    parent::setUp('update_script_test');
2337
    $this->update_url = $GLOBALS['base_url'] . '/update.php';
2338
    $this->update_user = $this->drupalCreateUser(array('administer software updates'));
2339
  }
2340

    
2341
  /**
2342
   * Tests access to the update script.
2343
   */
2344
  function testUpdateAccess() {
2345
    // Try accessing update.php without the proper permission.
2346
    $regular_user = $this->drupalCreateUser();
2347
    $this->drupalLogin($regular_user);
2348
    $this->drupalGet($this->update_url, array('external' => TRUE));
2349
    $this->assertResponse(403);
2350

    
2351
    // Try accessing update.php as an anonymous user.
2352
    $this->drupalLogout();
2353
    $this->drupalGet($this->update_url, array('external' => TRUE));
2354
    $this->assertResponse(403);
2355

    
2356
    // Access the update page with the proper permission.
2357
    $this->drupalLogin($this->update_user);
2358
    $this->drupalGet($this->update_url, array('external' => TRUE));
2359
    $this->assertResponse(200);
2360

    
2361
    // Access the update page as user 1.
2362
    $user1 = user_load(1);
2363
    $user1->pass_raw = user_password();
2364
    require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
2365
    $user1->pass = user_hash_password(trim($user1->pass_raw));
2366
    db_query("UPDATE {users} SET pass = :pass WHERE uid = :uid", array(':pass' => $user1->pass, ':uid' => $user1->uid));
2367
    $this->drupalLogin($user1);
2368
    $this->drupalGet($this->update_url, array('external' => TRUE));
2369
    $this->assertResponse(200);
2370
  }
2371

    
2372
  /**
2373
   * Tests that requirements warnings and errors are correctly displayed.
2374
   */
2375
  function testRequirements() {
2376
    $this->drupalLogin($this->update_user);
2377

    
2378
    // If there are no requirements warnings or errors, we expect to be able to
2379
    // go through the update process uninterrupted.
2380
    $this->drupalGet($this->update_url, array('external' => TRUE));
2381
    $this->drupalPost(NULL, array(), t('Continue'));
2382
    $this->assertText(t('No pending updates.'), 'End of update process was reached.');
2383
    // Confirm that all caches were cleared.
2384
    $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared when there were no requirements warnings or errors.');
2385

    
2386
    // If there is a requirements warning, we expect it to be initially
2387
    // displayed, but clicking the link to proceed should allow us to go
2388
    // through the rest of the update process uninterrupted.
2389

    
2390
    // First, run this test with pending updates to make sure they can be run
2391
    // successfully.
2392
    variable_set('update_script_test_requirement_type', REQUIREMENT_WARNING);
2393
    drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
2394
    $this->drupalGet($this->update_url, array('external' => TRUE));
2395
    $this->assertText('This is a requirements warning provided by the update_script_test module.');
2396
    $this->clickLink('try again');
2397
    $this->assertNoText('This is a requirements warning provided by the update_script_test module.');
2398
    $this->drupalPost(NULL, array(), t('Continue'));
2399
    $this->drupalPost(NULL, array(), t('Apply pending updates'));
2400
    $this->assertText(t('The update_script_test_update_7000() update was executed successfully.'), 'End of update process was reached.');
2401
    // Confirm that all caches were cleared.
2402
    $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared after resolving a requirements warning and applying updates.');
2403

    
2404
    // Now try again without pending updates to make sure that works too.
2405
    $this->drupalGet($this->update_url, array('external' => TRUE));
2406
    $this->assertText('This is a requirements warning provided by the update_script_test module.');
2407
    $this->clickLink('try again');
2408
    $this->assertNoText('This is a requirements warning provided by the update_script_test module.');
2409
    $this->drupalPost(NULL, array(), t('Continue'));
2410
    $this->assertText(t('No pending updates.'), 'End of update process was reached.');
2411
    // Confirm that all caches were cleared.
2412
    $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared after applying updates and re-running the script.');
2413

    
2414
    // If there is a requirements error, it should be displayed even after
2415
    // clicking the link to proceed (since the problem that triggered the error
2416
    // has not been fixed).
2417
    variable_set('update_script_test_requirement_type', REQUIREMENT_ERROR);
2418
    $this->drupalGet($this->update_url, array('external' => TRUE));
2419
    $this->assertText('This is a requirements error provided by the update_script_test module.');
2420
    $this->clickLink('try again');
2421
    $this->assertText('This is a requirements error provided by the update_script_test module.');
2422
  }
2423

    
2424
  /**
2425
   * Tests the effect of using the update script on the theme system.
2426
   */
2427
  function testThemeSystem() {
2428
    // Since visiting update.php triggers a rebuild of the theme system from an
2429
    // unusual maintenance mode environment, we check that this rebuild did not
2430
    // put any incorrect information about the themes into the database.
2431
    $original_theme_data = db_query("SELECT * FROM {system} WHERE type = 'theme' ORDER BY name")->fetchAll();
2432
    $this->drupalLogin($this->update_user);
2433
    $this->drupalGet($this->update_url, array('external' => TRUE));
2434
    $final_theme_data = db_query("SELECT * FROM {system} WHERE type = 'theme' ORDER BY name")->fetchAll();
2435
    $this->assertEqual($original_theme_data, $final_theme_data, 'Visiting update.php does not alter the information about themes stored in the database.');
2436
  }
2437

    
2438
  /**
2439
   * Tests update.php when there are no updates to apply.
2440
   */
2441
  function testNoUpdateFunctionality() {
2442
    // Click through update.php with 'administer software updates' permission.
2443
    $this->drupalLogin($this->update_user);
2444
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
2445
    $this->assertText(t('No pending updates.'));
2446
    $this->assertNoLink('Administration pages');
2447
    $this->clickLink('Front page');
2448
    $this->assertResponse(200);
2449

    
2450
    // Click through update.php with 'access administration pages' permission.
2451
    $admin_user = $this->drupalCreateUser(array('administer software updates', 'access administration pages'));
2452
    $this->drupalLogin($admin_user);
2453
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
2454
    $this->assertText(t('No pending updates.'));
2455
    $this->clickLink('Administration pages');
2456
    $this->assertResponse(200);
2457
  }
2458

    
2459
  /**
2460
   * Tests update.php after performing a successful update.
2461
   */
2462
  function testSuccessfulUpdateFunctionality() {
2463
    drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
2464
    // Click through update.php with 'administer software updates' permission.
2465
    $this->drupalLogin($this->update_user);
2466
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
2467
    $this->drupalPost(NULL, array(), t('Apply pending updates'));
2468
    $this->assertText('Updates were attempted.');
2469
    $this->assertLink('site');
2470
    $this->assertNoLink('Administration pages');
2471
    $this->assertNoLink('logged');
2472
    $this->clickLink('Front page');
2473
    $this->assertResponse(200);
2474

    
2475
    drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
2476
    // Click through update.php with 'access administration pages' and
2477
    // 'access site reports' permissions.
2478
    $admin_user = $this->drupalCreateUser(array('administer software updates', 'access administration pages', 'access site reports'));
2479
    $this->drupalLogin($admin_user);
2480
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
2481
    $this->drupalPost(NULL, array(), t('Apply pending updates'));
2482
    $this->assertText('Updates were attempted.');
2483
    $this->assertLink('logged');
2484
    $this->clickLink('Administration pages');
2485
    $this->assertResponse(200);
2486
  }
2487
}
2488

    
2489
/**
2490
 * Functional tests for the flood control mechanism.
2491
 */
2492
class FloodFunctionalTest extends DrupalWebTestCase {
2493
  public static function getInfo() {
2494
    return array(
2495
      'name' => 'Flood control mechanism',
2496
      'description' => 'Functional tests for the flood control mechanism.',
2497
      'group' => 'System',
2498
    );
2499
  }
2500

    
2501
  /**
2502
   * Test flood control mechanism clean-up.
2503
   */
2504
  function testCleanUp() {
2505
    $threshold = 1;
2506
    $window_expired = -1;
2507
    $name = 'flood_test_cleanup';
2508

    
2509
    // Register expired event.
2510
    flood_register_event($name, $window_expired);
2511
    // Verify event is not allowed.
2512
    $this->assertFalse(flood_is_allowed($name, $threshold));
2513
    // Run cron and verify event is now allowed.
2514
    $this->cronRun();
2515
    $this->assertTrue(flood_is_allowed($name, $threshold));
2516

    
2517
    // Register unexpired event.
2518
    flood_register_event($name);
2519
    // Verify event is not allowed.
2520
    $this->assertFalse(flood_is_allowed($name, $threshold));
2521
    // Run cron and verify event is still not allowed.
2522
    $this->cronRun();
2523
    $this->assertFalse(flood_is_allowed($name, $threshold));
2524
  }
2525
}
2526

    
2527
/**
2528
 * Test HTTP file downloading capability.
2529
 */
2530
class RetrieveFileTestCase extends DrupalWebTestCase {
2531
  public static function getInfo() {
2532
    return array(
2533
      'name' => 'HTTP file retrieval',
2534
      'description' => 'Checks HTTP file fetching and error handling.',
2535
      'group' => 'System',
2536
    );
2537
  }
2538

    
2539
  /**
2540
   * Invokes system_retrieve_file() in several scenarios.
2541
   */
2542
  function testFileRetrieving() {
2543
    // Test 404 handling by trying to fetch a randomly named file.
2544
    drupal_mkdir($sourcedir = 'public://' . $this->randomName());
2545
    $filename = 'Файл для тестирования ' . $this->randomName();
2546
    $url = file_create_url($sourcedir . '/' . $filename);
2547
    $retrieved_file = system_retrieve_file($url);
2548
    $this->assertFalse($retrieved_file, 'Non-existent file not fetched.');
2549

    
2550
    // Actually create that file, download it via HTTP and test the returned path.
2551
    file_put_contents($sourcedir . '/' . $filename, 'testing');
2552
    $retrieved_file = system_retrieve_file($url);
2553

    
2554
    // URLs could not contains characters outside the ASCII set so $filename
2555
    // has to be encoded.
2556
    $encoded_filename = rawurlencode($filename);
2557

    
2558
    $this->assertEqual($retrieved_file, 'public://' . $encoded_filename, 'Sane path for downloaded file returned (public:// scheme).');
2559
    $this->assertTrue(is_file($retrieved_file), 'Downloaded file does exist (public:// scheme).');
2560
    $this->assertEqual(filesize($retrieved_file), 7, 'File size of downloaded file is correct (public:// scheme).');
2561
    file_unmanaged_delete($retrieved_file);
2562

    
2563
    // Test downloading file to a different location.
2564
    drupal_mkdir($targetdir = 'temporary://' . $this->randomName());
2565
    $retrieved_file = system_retrieve_file($url, $targetdir);
2566
    $this->assertEqual($retrieved_file, "$targetdir/$encoded_filename", 'Sane path for downloaded file returned (temporary:// scheme).');
2567
    $this->assertTrue(is_file($retrieved_file), 'Downloaded file does exist (temporary:// scheme).');
2568
    $this->assertEqual(filesize($retrieved_file), 7, 'File size of downloaded file is correct (temporary:// scheme).');
2569
    file_unmanaged_delete($retrieved_file);
2570

    
2571
    file_unmanaged_delete_recursive($sourcedir);
2572
    file_unmanaged_delete_recursive($targetdir);
2573
  }
2574
}
2575

    
2576
/**
2577
 * Functional tests shutdown functions.
2578
 */
2579
class ShutdownFunctionsTest extends DrupalWebTestCase {
2580
  public static function getInfo() {
2581
    return array(
2582
      'name' => 'Shutdown functions',
2583
      'description' => 'Functional tests for shutdown functions',
2584
      'group' => 'System',
2585
    );
2586
  }
2587

    
2588
  function setUp() {
2589
    parent::setUp('system_test');
2590
  }
2591

    
2592
  /**
2593
   * Test shutdown functions.
2594
   */
2595
  function testShutdownFunctions() {
2596
    $arg1 = $this->randomName();
2597
    $arg2 = $this->randomName();
2598
    $this->drupalGet('system-test/shutdown-functions/' . $arg1 . '/' . $arg2);
2599
    $this->assertText(t('First shutdown function, arg1 : @arg1, arg2: @arg2', array('@arg1' => $arg1, '@arg2' => $arg2)));
2600
    $this->assertText(t('Second shutdown function, arg1 : @arg1, arg2: @arg2', array('@arg1' => $arg1, '@arg2' => $arg2)));
2601

    
2602
    // Make sure exceptions displayed through _drupal_render_exception_safe()
2603
    // are correctly escaped.
2604
    $this->assertRaw('Drupal is &amp;lt;blink&amp;gt;awesome&amp;lt;/blink&amp;gt;.');
2605
  }
2606
}
2607

    
2608
/**
2609
 * Tests administrative overview pages.
2610
 */
2611
class SystemAdminTestCase extends DrupalWebTestCase {
2612
  public static function getInfo() {
2613
    return array(
2614
      'name' => 'Administrative pages',
2615
      'description' => 'Tests output on administrative pages and compact mode functionality.',
2616
      'group' => 'System',
2617
    );
2618
  }
2619

    
2620
  function setUp() {
2621
    // testAdminPages() requires Locale module.
2622
    parent::setUp(array('locale'));
2623

    
2624
    // Create an administrator with all permissions, as well as a regular user
2625
    // who can only access administration pages and perform some Locale module
2626
    // administrative tasks, but not all of them.
2627
    $this->admin_user = $this->drupalCreateUser(array_keys(module_invoke_all('permission')));
2628
    $this->web_user = $this->drupalCreateUser(array(
2629
      'access administration pages',
2630
      'translate interface',
2631
    ));
2632
    $this->drupalLogin($this->admin_user);
2633
  }
2634

    
2635
  /**
2636
   * Tests output on administrative listing pages.
2637
   */
2638
  function testAdminPages() {
2639
    // Go to Administration.
2640
    $this->drupalGet('admin');
2641

    
2642
    // Verify that all visible, top-level administration links are listed on
2643
    // the main administration page.
2644
    foreach (menu_get_router() as $path => $item) {
2645
      if (strpos($path, 'admin/') === 0 && ($item['type'] & MENU_VISIBLE_IN_TREE) && $item['_number_parts'] == 2) {
2646
        $this->assertLink($item['title']);
2647
        $this->assertLinkByHref($path);
2648
        $this->assertText($item['description']);
2649
      }
2650
    }
2651

    
2652
    // For each administrative listing page on which the Locale module appears,
2653
    // verify that there are links to the module's primary configuration pages,
2654
    // but no links to its individual sub-configuration pages. Also verify that
2655
    // a user with access to only some Locale module administration pages only
2656
    // sees links to the pages they have access to.
2657
    $admin_list_pages = array(
2658
      'admin/index',
2659
      'admin/config',
2660
      'admin/config/regional',
2661
    );
2662

    
2663
    foreach ($admin_list_pages as $page) {
2664
      // For the administrator, verify that there are links to Locale's primary
2665
      // configuration pages, but no links to individual sub-configuration
2666
      // pages.
2667
      $this->drupalLogin($this->admin_user);
2668
      $this->drupalGet($page);
2669
      $this->assertLinkByHref('admin/config');
2670
      $this->assertLinkByHref('admin/config/regional/settings');
2671
      $this->assertLinkByHref('admin/config/regional/date-time');
2672
      $this->assertLinkByHref('admin/config/regional/language');
2673
      $this->assertNoLinkByHref('admin/config/regional/language/configure/session');
2674
      $this->assertNoLinkByHref('admin/config/regional/language/configure/url');
2675
      $this->assertLinkByHref('admin/config/regional/translate');
2676
      // On admin/index only, the administrator should also see a "Configure
2677
      // permissions" link for the Locale module.
2678
      if ($page == 'admin/index') {
2679
        $this->assertLinkByHref("admin/people/permissions#module-locale");
2680
      }
2681

    
2682
      // For a less privileged user, verify that there are no links to Locale's
2683
      // primary configuration pages, but a link to the translate page exists.
2684
      $this->drupalLogin($this->web_user);
2685
      $this->drupalGet($page);
2686
      $this->assertLinkByHref('admin/config');
2687
      $this->assertNoLinkByHref('admin/config/regional/settings');
2688
      $this->assertNoLinkByHref('admin/config/regional/date-time');
2689
      $this->assertNoLinkByHref('admin/config/regional/language');
2690
      $this->assertNoLinkByHref('admin/config/regional/language/configure/session');
2691
      $this->assertNoLinkByHref('admin/config/regional/language/configure/url');
2692
      $this->assertLinkByHref('admin/config/regional/translate');
2693
      // This user cannot configure permissions, so even on admin/index should
2694
      // not see a "Configure permissions" link for the Locale module.
2695
      if ($page == 'admin/index') {
2696
        $this->assertNoLinkByHref("admin/people/permissions#module-locale");
2697
      }
2698
    }
2699
  }
2700

    
2701
  /**
2702
   * Test compact mode.
2703
   */
2704
  function testCompactMode() {
2705
    $this->drupalGet('admin/compact/on');
2706
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode turns on.');
2707
    $this->drupalGet('admin/compact/on');
2708
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode remains on after a repeat call.');
2709
    $this->drupalGet('');
2710
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode persists on new requests.');
2711

    
2712
    $this->drupalGet('admin/compact/off');
2713
    $this->assertEqual($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'deleted', 'Compact mode turns off.');
2714
    $this->drupalGet('admin/compact/off');
2715
    $this->assertEqual($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'deleted', 'Compact mode remains off after a repeat call.');
2716
    $this->drupalGet('');
2717
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode persists on new requests.');
2718
  }
2719
}
2720

    
2721
/**
2722
 * Tests authorize.php and related hooks.
2723
 */
2724
class SystemAuthorizeCase extends DrupalWebTestCase {
2725
  public static function getInfo() {
2726
    return array(
2727
      'name' => 'Authorize API',
2728
      'description' => 'Tests the authorize.php script and related API.',
2729
      'group' => 'System',
2730
    );
2731
  }
2732

    
2733
  function setUp() {
2734
    parent::setUp(array('system_test'));
2735

    
2736
    variable_set('allow_authorize_operations', TRUE);
2737

    
2738
    // Create an administrator user.
2739
    $this->admin_user = $this->drupalCreateUser(array('administer software updates'));
2740
    $this->drupalLogin($this->admin_user);
2741
  }
2742

    
2743
  /**
2744
   * Helper function to initialize authorize.php and load it via drupalGet().
2745
   *
2746
   * Initializing authorize.php needs to happen in the child Drupal
2747
   * installation, not the parent. So, we visit a menu callback provided by
2748
   * system_test.module which calls system_authorized_init() to initialize the
2749
   * $_SESSION inside the test site, not the framework site. This callback
2750
   * redirects to authorize.php when it's done initializing.
2751
   *
2752
   * @see system_authorized_init().
2753
   */
2754
  function drupalGetAuthorizePHP($page_title = 'system-test-auth') {
2755
    $this->drupalGet('system-test/authorize-init/' . $page_title);
2756
  }
2757

    
2758
  /**
2759
   * Tests the FileTransfer hooks
2760
   */
2761
  function testFileTransferHooks() {
2762
    $page_title = $this->randomName(16);
2763
    $this->drupalGetAuthorizePHP($page_title);
2764
    $this->assertTitle(strtr('@title | Drupal', array('@title' => $page_title)), 'authorize.php page title is correct.');
2765
    $this->assertNoText('It appears you have reached this page in error.');
2766
    $this->assertText('To continue, provide your server connection details');
2767
    // Make sure we see the new connection method added by system_test.
2768
    $this->assertRaw('System Test FileTransfer');
2769
    // Make sure the settings form callback works.
2770
    $this->assertText('System Test Username');
2771
  }
2772
}
2773

    
2774
/**
2775
 * Test the handling of requests containing 'index.php'.
2776
 */
2777
class SystemIndexPhpTest extends DrupalWebTestCase {
2778
  public static function getInfo() {
2779
    return array(
2780
      'name' => 'Index.php handling',
2781
      'description' => "Test the handling of requests containing 'index.php'.",
2782
      'group' => 'System',
2783
    );
2784
  }
2785

    
2786
  function setUp() {
2787
    parent::setUp();
2788
  }
2789

    
2790
  /**
2791
   * Test index.php handling.
2792
   */
2793
  function testIndexPhpHandling() {
2794
    $index_php = $GLOBALS['base_url'] . '/index.php';
2795

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

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

    
2802
    $this->drupalGet($index_php .'/user', array('external' => TRUE));
2803
    $this->assertResponse(404, "Make sure index.php/user returns a 'page not found'.");
2804
  }
2805
}
2806

    
2807
/**
2808
 * Test token replacement in strings.
2809
 */
2810
class TokenScanTest extends DrupalWebTestCase {
2811

    
2812
  public static function getInfo() {
2813
    return array(
2814
      'name' => 'Token scanning',
2815
      'description' => 'Scan token-like patterns in a dummy text to check token scanning.',
2816
      'group' => 'System',
2817
    );
2818
  }
2819

    
2820
  /**
2821
   * Scans dummy text, then tests the output.
2822
   */
2823
  function testTokenScan() {
2824
    // Define text with valid and not valid, fake and existing token-like
2825
    // strings.
2826
    $text = 'First a [valid:simple], but dummy token, and a dummy [valid:token with: spaces].';
2827
    $text .= 'Then a [not valid:token].';
2828
    $text .= 'Last an existing token: [node:author:name].';
2829
    $token_wannabes = token_scan($text);
2830

    
2831
    $this->assertTrue(isset($token_wannabes['valid']['simple']), 'A simple valid token has been matched.');
2832
    $this->assertTrue(isset($token_wannabes['valid']['token with: spaces']), 'A valid token with space characters in the token name has been matched.');
2833
    $this->assertFalse(isset($token_wannabes['not valid']), 'An invalid token with spaces in the token type has not been matched.');
2834
    $this->assertTrue(isset($token_wannabes['node']), 'An existing valid token has been matched.');
2835
  }
2836
}
2837

    
2838
/**
2839
 * Test case for drupal_valid_token().
2840
 */
2841
class SystemValidTokenTest extends DrupalUnitTestCase {
2842

    
2843
  /**
2844
   * Flag to indicate whether PHP error reportings should be asserted.
2845
   *
2846
   * @var bool
2847
   */
2848
  protected $assertErrors = TRUE;
2849

    
2850
  public static function getInfo() {
2851
    return array(
2852
      'name' => 'Token validation',
2853
      'description' => 'Test the security token validation.',
2854
      'group' => 'System',
2855
    );
2856
  }
2857

    
2858
  /**
2859
   * Tests invalid invocations of drupal_valid_token() that must return FALSE.
2860
   */
2861
  public function testTokenValidation() {
2862
    // The following checks will throw PHP notices, so we disable error
2863
    // assertions.
2864
    $this->assertErrors = FALSE;
2865
    $this->assertFalse(drupal_valid_token(NULL, new stdClass()), 'Token NULL, value object returns FALSE.');
2866
    $this->assertFalse(drupal_valid_token(0, array()), 'Token 0, value array returns FALSE.');
2867
    $this->assertFalse(drupal_valid_token('', array()), "Token '', value array returns FALSE.");
2868
    $this->assertFalse('' === drupal_get_token(array()), 'Token generation does not return an empty string on invalid parameters.');
2869
    $this->assertErrors = TRUE;
2870

    
2871
    $this->assertFalse(drupal_valid_token(TRUE, 'foo'), 'Token TRUE, value foo returns FALSE.');
2872
    $this->assertFalse(drupal_valid_token(0, 'foo'), 'Token 0, value foo returns FALSE.');
2873
  }
2874

    
2875
  /**
2876
   * Overrides DrupalTestCase::errorHandler().
2877
   */
2878
  public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
2879
    if ($this->assertErrors) {
2880
      return parent::errorHandler($severity, $message, $file, $line);
2881
    }
2882
    return TRUE;
2883
  }
2884
}
2885

    
2886
/**
2887
 * Tests drupal_set_message() and related functions.
2888
 */
2889
class DrupalSetMessageTest extends DrupalWebTestCase {
2890

    
2891
  public static function getInfo() {
2892
    return array(
2893
      'name' => 'Messages',
2894
      'description' => 'Tests that messages can be displayed using drupal_set_message().',
2895
      'group' => 'System',
2896
    );
2897
  }
2898

    
2899
  function setUp() {
2900
    parent::setUp('system_test');
2901
  }
2902

    
2903
  /**
2904
   * Tests setting messages and removing one before it is displayed.
2905
   */
2906
  function testSetRemoveMessages() {
2907
    // The page at system-test/drupal-set-message sets two messages and then
2908
    // removes the first before it is displayed.
2909
    $this->drupalGet('system-test/drupal-set-message');
2910
    $this->assertNoText('First message (removed).');
2911
    $this->assertText('Second message (not removed).');
2912
  }
2913
}
2914

    
2915
/**
2916
 * Tests confirm form destinations.
2917
 */
2918
class ConfirmFormTest extends DrupalWebTestCase {
2919
  protected $admin_user;
2920

    
2921
  public static function getInfo() {
2922
    return array(
2923
      'name' => 'Confirm form',
2924
      'description' => 'Tests that the confirm form does not use external destinations.',
2925
      'group' => 'System',
2926
    );
2927
  }
2928

    
2929
  function setUp() {
2930
    parent::setUp();
2931

    
2932
    $this->admin_user = $this->drupalCreateUser(array('administer users'));
2933
    $this->drupalLogin($this->admin_user);
2934
  }
2935

    
2936
  /**
2937
   * Tests that the confirm form does not use external destinations.
2938
   */
2939
  function testConfirmForm() {
2940
    $this->drupalGet('user/1/cancel');
2941
    $this->assertCancelLinkUrl(url('user/1'));
2942
    $this->drupalGet('user/1/cancel', array('query' => array('destination' => 'node')));
2943
    $this->assertCancelLinkUrl(url('node'));
2944
    $this->drupalGet('user/1/cancel', array('query' => array('destination' => 'http://example.com')));
2945
    $this->assertCancelLinkUrl(url('user/1'));
2946
  }
2947

    
2948
  /**
2949
   * Asserts that a cancel link is present pointing to the provided URL.
2950
   */
2951
  function assertCancelLinkUrl($url, $message = '', $group = 'Other') {
2952
    $links = $this->xpath('//a[normalize-space(text())=:label and @href=:url]', array(':label' => t('Cancel'), ':url' => $url));
2953
    $message = ($message ? $message : format_string('Cancel link with url %url found.', array('%url' => $url)));
2954
    return $this->assertTrue(isset($links[0]), $message, $group);
2955
  }
2956
}