Projet

Général

Profil

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

root / drupal7 / modules / system / system.test @ db2d93dd

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
   * Attempt to enable translation module without locale enabled.
394
   */
395
  function testEnableWithoutDependency() {
396
    // Attempt to enable content translation without locale enabled.
397
    $edit = array();
398
    $edit['modules[Core][translation][enable]'] = 'translation';
399
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
400
    $this->assertText(t('Some required modules must be enabled'), 'Dependency required.');
401

    
402
    $this->assertModules(array('translation', 'locale'), FALSE);
403

    
404
    // Assert that the locale tables weren't enabled.
405
    $this->assertTableCount('languages', FALSE);
406
    $this->assertTableCount('locale', FALSE);
407

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

    
411
    $this->assertModules(array('translation', 'locale'), TRUE);
412

    
413
    // Assert that the locale tables were enabled.
414
    $this->assertTableCount('languages', TRUE);
415
    $this->assertTableCount('locale', TRUE);
416
  }
417

    
418
  /**
419
   * Attempt to enable a module with a missing dependency.
420
   */
421
  function testMissingModules() {
422
    // Test that the system_dependencies_test module is marked
423
    // as missing a dependency.
424
    $this->drupalGet('admin/modules');
425
    $this->assertRaw(t('@module (<span class="admin-missing">missing</span>)', array('@module' => drupal_ucfirst('_missing_dependency'))), 'A module with missing dependencies is marked as such.');
426
    $checkbox = $this->xpath('//input[@type="checkbox" and @disabled="disabled" and @name="modules[Testing][system_dependencies_test][enable]"]');
427
    $this->assert(count($checkbox) == 1, 'Checkbox for the module is disabled.');
428

    
429
    // Force enable the system_dependencies_test module.
430
    module_enable(array('system_dependencies_test'), FALSE);
431

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

    
437
    // Confirm.
438
    $this->drupalPost(NULL, NULL, t('Continue'));
439

    
440
    // Verify that the module has been disabled.
441
    $this->assertModules(array('system_dependencies_test'), FALSE);
442
  }
443

    
444
  /**
445
   * Tests enabling a module that depends on an incompatible version of a module.
446
   */
447
  function testIncompatibleModuleVersionDependency() {
448
    // Test that the system_incompatible_module_version_dependencies_test is
449
    // marked as having an incompatible dependency.
450
    $this->drupalGet('admin/modules');
451
    $this->assertRaw(t('@module (<span class="admin-missing">incompatible with</span> version @version)', array(
452
      '@module' => 'System incompatible module version test (>2.0)',
453
      '@version' => '1.0',
454
    )), 'A module that depends on an incompatible version of a module is marked as such.');
455
    $checkbox = $this->xpath('//input[@type="checkbox" and @disabled="disabled" and @name="modules[Testing][system_incompatible_module_version_dependencies_test][enable]"]');
456
    $this->assert(count($checkbox) == 1, 'Checkbox for the module is disabled.');
457
  }
458

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

    
473
  /**
474
   * Tests enabling a module that depends on a module which fails hook_requirements().
475
   */
476
  function testEnableRequirementsFailureDependency() {
477
    $this->assertModules(array('requirements1_test'), FALSE);
478
    $this->assertModules(array('requirements2_test'), FALSE);
479

    
480
    // Attempt to install both modules at the same time.
481
    $edit = array();
482
    $edit['modules[Testing][requirements1_test][enable]'] = 'requirements1_test';
483
    $edit['modules[Testing][requirements2_test][enable]'] = 'requirements2_test';
484
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
485

    
486
    // Makes sure the modules were NOT installed.
487
    $this->assertText(t('Requirements 1 Test failed requirements'), 'Modules status has been updated.');
488
    $this->assertModules(array('requirements1_test'), FALSE);
489
    $this->assertModules(array('requirements2_test'), FALSE);
490

    
491
    // Makes sure that already enabled modules the failing modules depend on
492
    // were not disabled.
493
    $this->assertModules(array('comment'), TRUE);
494

    
495
  }
496

    
497
  /**
498
   * Tests that module dependencies are enabled in the correct order via the
499
   * UI. Dependencies should be enabled before their dependents.
500
   */
501
  function testModuleEnableOrder() {
502
    module_enable(array('module_test'), FALSE);
503
    $this->resetAll();
504
    $this->assertModules(array('module_test'), TRUE);
505
    variable_set('dependency_test', 'dependency');
506
    // module_test creates a dependency chain: forum depends on poll, which
507
    // depends on php. The correct enable order is, php, poll, forum.
508
    $expected_order = array('php', 'poll', 'forum');
509

    
510
    // Enable the modules through the UI, verifying that the dependency chain
511
    // is correct.
512
    $edit = array();
513
    $edit['modules[Core][forum][enable]'] = 'forum';
514
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
515
    $this->assertModules(array('forum'), FALSE);
516
    $this->assertText(t('You must enable the Poll, PHP filter modules to install Forum.'), t('Dependency chain created.'));
517
    $edit['modules[Core][poll][enable]'] = 'poll';
518
    $edit['modules[Core][php][enable]'] = 'php';
519
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
520
    $this->assertModules(array('forum', 'poll', 'php'), TRUE);
521

    
522
    // Check the actual order which is saved by module_test_modules_enabled().
523
    $this->assertIdentical(variable_get('test_module_enable_order', FALSE), $expected_order, t('Modules enabled in the correct order.'));
524
  }
525

    
526
  /**
527
   * Tests attempting to uninstall a module that has installed dependents.
528
   */
529
  function testUninstallDependents() {
530
    // Enable the forum module.
531
    $edit = array('modules[Core][forum][enable]' => 'forum');
532
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
533
    $this->assertModules(array('forum'), TRUE);
534

    
535
    // Disable forum and comment. Both should now be installed but disabled.
536
    $edit = array('modules[Core][forum][enable]' => FALSE);
537
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
538
    $this->assertModules(array('forum'), FALSE);
539
    $edit = array('modules[Core][comment][enable]' => FALSE);
540
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
541
    $this->assertModules(array('comment'), FALSE);
542

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

    
548
    // Uninstall the forum module, and check that taxonomy now can also be
549
    // uninstalled.
550
    $edit = array('uninstall[forum]' => 'forum');
551
    $this->drupalPost('admin/modules/uninstall', $edit, t('Uninstall'));
552
    $this->drupalPost(NULL, NULL, t('Uninstall'));
553
    $this->assertText(t('The selected modules have been uninstalled.'), 'Modules status has been updated.');
554
    $edit = array('uninstall[comment]' => 'comment');
555
    $this->drupalPost('admin/modules/uninstall', $edit, t('Uninstall'));
556
    $this->drupalPost(NULL, NULL, t('Uninstall'));
557
    $this->assertText(t('The selected modules have been uninstalled.'), 'Modules status has been updated.');
558
  }
559

    
560
  /**
561
   * Tests whether the correct module metadata is returned.
562
   */
563
  function testModuleMetaData() {
564
    // Generate the list of available modules.
565
    $modules = system_rebuild_module_data();
566
    // Check that the mtime field exists for the system module.
567
    $this->assertTrue(!empty($modules['system']->info['mtime']), 'The system.info file modification time field is present.');
568
    // Use 0 if mtime isn't present, to avoid an array index notice.
569
    $test_mtime = !empty($modules['system']->info['mtime']) ? $modules['system']->info['mtime'] : 0;
570
    // Ensure the mtime field contains a number that is greater than zero.
571
    $this->assertTrue(is_numeric($test_mtime) && ($test_mtime > 0), 'The system.info file modification time field contains a timestamp.');
572
  }
573

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

    
589
/**
590
 * Test module dependency on specific versions.
591
 */
592
class ModuleVersionTestCase extends ModuleTestCase {
593
  public static function getInfo() {
594
    return array(
595
      'name' => 'Module versions',
596
      'description' => 'Check module version dependencies.',
597
      'group' => 'Module',
598
    );
599
  }
600

    
601
  function setUp() {
602
    parent::setUp('module_test');
603
  }
604

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

    
650
/**
651
 * Test required modules functionality.
652
 */
653
class ModuleRequiredTestCase extends ModuleTestCase {
654
  public static function getInfo() {
655
    return array(
656
      'name' => 'Required modules',
657
      'description' => 'Attempt disabling of required modules.',
658
      'group' => 'Module',
659
    );
660
  }
661

    
662
  /**
663
   * Assert that core required modules cannot be disabled.
664
   */
665
  function testDisableRequired() {
666
    $module_info = system_get_info('module');
667
    $this->drupalGet('admin/modules');
668
    foreach ($module_info as $module => $info) {
669
      // Check to make sure the checkbox for each required module is disabled
670
      // and checked (or absent from the page if the module is also hidden).
671
      if (!empty($info['required'])) {
672
        $field_name = "modules[{$info['package']}][$module][enable]";
673
        if (empty($info['hidden'])) {
674
          $this->assertFieldByXPath("//input[@name='$field_name' and @disabled='disabled' and @checked='checked']", '', format_string('Field @name was disabled and checked.', array('@name' => $field_name)));
675
        }
676
        else {
677
          $this->assertNoFieldByName($field_name);
678
        }
679
      }
680
    }
681
  }
682
}
683

    
684
class IPAddressBlockingTestCase extends DrupalWebTestCase {
685
  protected $blocking_user;
686

    
687
  /**
688
   * Implement getInfo().
689
   */
690
  public static function getInfo() {
691
    return array(
692
      'name' => 'IP address blocking',
693
      'description' => 'Test IP address blocking.',
694
      'group' => 'System'
695
    );
696
  }
697

    
698
  /**
699
   * Implement setUp().
700
   */
701
  function setUp() {
702
    parent::setUp();
703

    
704
    // Create user.
705
    $this->blocking_user = $this->drupalCreateUser(array('block IP addresses'));
706
    $this->drupalLogin($this->blocking_user);
707
  }
708

    
709
  /**
710
   * Test a variety of user input to confirm correct validation and saving of data.
711
   */
712
  function testIPAddressValidation() {
713
    $this->drupalGet('admin/config/people/ip-blocking');
714

    
715
    // Block a valid IP address.
716
    $edit = array();
717
    $edit['ip'] = '192.168.1.1';
718
    $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
719
    $ip = db_query("SELECT iid from {blocked_ips} WHERE ip = :ip", array(':ip' => $edit['ip']))->fetchField();
720
    $this->assertTrue($ip, t('IP address found in database.'));
721
    $this->assertRaw(t('The IP address %ip has been blocked.', array('%ip' => $edit['ip'])), t('IP address was blocked.'));
722

    
723
    // Try to block an IP address that's already blocked.
724
    $edit = array();
725
    $edit['ip'] = '192.168.1.1';
726
    $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
727
    $this->assertText(t('This IP address is already blocked.'));
728

    
729
    // Try to block a reserved IP address.
730
    $edit = array();
731
    $edit['ip'] = '255.255.255.255';
732
    $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
733
    $this->assertText(t('Enter a valid IP address.'));
734

    
735
    // Try to block a reserved IP address.
736
    $edit = array();
737
    $edit['ip'] = 'test.example.com';
738
    $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
739
    $this->assertText(t('Enter a valid IP address.'));
740

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

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

    
754
    // Submit your own IP address. This fails, although it works when testing manually.
755
     // TODO: on some systems this test fails due to a bug or inconsistency in cURL.
756
     // $edit = array();
757
     // $edit['ip'] = ip_address();
758
     // $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Save'));
759
     // $this->assertText(t('You may not block your own IP address.'));
760
  }
761
}
762

    
763
class CronRunTestCase extends DrupalWebTestCase {
764
  /**
765
   * Implement getInfo().
766
   */
767
  public static function getInfo() {
768
    return array(
769
      'name' => 'Cron run',
770
      'description' => 'Test cron run.',
771
      'group' => 'System'
772
    );
773
  }
774

    
775
  function setUp() {
776
    parent::setUp(array('common_test', 'common_test_cron_helper'));
777
  }
778

    
779
  /**
780
   * Test cron runs.
781
   */
782
  function testCronRun() {
783
    global $base_url;
784

    
785
    // Run cron anonymously without any cron key.
786
    $this->drupalGet($base_url . '/cron.php', array('external' => TRUE));
787
    $this->assertResponse(403);
788

    
789
    // Run cron anonymously with a random cron key.
790
    $key = $this->randomName(16);
791
    $this->drupalGet($base_url . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => $key)));
792
    $this->assertResponse(403);
793

    
794
    // Run cron anonymously with the valid cron key.
795
    $key = variable_get('cron_key', 'drupal');
796
    $this->drupalGet($base_url . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => $key)));
797
    $this->assertResponse(200);
798
  }
799

    
800
  /**
801
   * Ensure that the automatic cron run feature is working.
802
   *
803
   * In these tests we do not use REQUEST_TIME to track start time, because we
804
   * need the exact time when cron is triggered.
805
   */
806
  function testAutomaticCron() {
807
    // Ensure cron does not run when the cron threshold is enabled and was
808
    // not passed.
809
    $cron_last = time();
810
    $cron_safe_threshold = 100;
811
    variable_set('cron_last', $cron_last);
812
    variable_set('cron_safe_threshold', $cron_safe_threshold);
813
    $this->drupalGet('');
814
    $this->assertTrue($cron_last == variable_get('cron_last', NULL), 'Cron does not run when the cron threshold is not passed.');
815

    
816
    // Test if cron runs when the cron threshold was passed.
817
    $cron_last = time() - 200;
818
    variable_set('cron_last', $cron_last);
819
    $this->drupalGet('');
820
    sleep(1);
821
    $this->assertTrue($cron_last < variable_get('cron_last', NULL), 'Cron runs when the cron threshold is passed.');
822

    
823
    // Disable the cron threshold through the interface.
824
    $admin_user = $this->drupalCreateUser(array('administer site configuration'));
825
    $this->drupalLogin($admin_user);
826
    $this->drupalPost('admin/config/system/cron', array('cron_safe_threshold' => 0), t('Save configuration'));
827
    $this->assertText(t('The configuration options have been saved.'));
828
    $this->drupalLogout();
829

    
830
    // Test if cron does not run when the cron threshold is disabled.
831
    $cron_last = time() - 200;
832
    variable_set('cron_last', $cron_last);
833
    $this->drupalGet('');
834
    $this->assertTrue($cron_last == variable_get('cron_last', NULL), 'Cron does not run when the cron threshold is disabled.');
835
  }
836

    
837
  /**
838
   * Ensure that temporary files are removed.
839
   *
840
   * Create files for all the possible combinations of age and status. We are
841
   * using UPDATE statements rather than file_save() because it would set the
842
   * timestamp.
843
   */
844
  function testTempFileCleanup() {
845
    // Temporary file that is older than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
846
    $temp_old = file_save_data('');
847
    db_update('file_managed')
848
      ->fields(array(
849
        'status' => 0,
850
        'timestamp' => 1,
851
      ))
852
      ->condition('fid', $temp_old->fid)
853
      ->execute();
854
    $this->assertTrue(file_exists($temp_old->uri), 'Old temp file was created correctly.');
855

    
856
    // Temporary file that is less than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
857
    $temp_new = file_save_data('');
858
    db_update('file_managed')
859
      ->fields(array('status' => 0))
860
      ->condition('fid', $temp_new->fid)
861
      ->execute();
862
    $this->assertTrue(file_exists($temp_new->uri), 'New temp file was created correctly.');
863

    
864
    // Permanent file that is older than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
865
    $perm_old = file_save_data('');
866
    db_update('file_managed')
867
      ->fields(array('timestamp' => 1))
868
      ->condition('fid', $temp_old->fid)
869
      ->execute();
870
    $this->assertTrue(file_exists($perm_old->uri), 'Old permanent file was created correctly.');
871

    
872
    // Permanent file that is newer than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
873
    $perm_new = file_save_data('');
874
    $this->assertTrue(file_exists($perm_new->uri), 'New permanent file was created correctly.');
875

    
876
    // Run cron and then ensure that only the old, temp file was deleted.
877
    $this->cronRun();
878
    $this->assertFalse(file_exists($temp_old->uri), 'Old temp file was correctly removed.');
879
    $this->assertTrue(file_exists($temp_new->uri), 'New temp file was correctly ignored.');
880
    $this->assertTrue(file_exists($perm_old->uri), 'Old permanent file was correctly ignored.');
881
    $this->assertTrue(file_exists($perm_new->uri), 'New permanent file was correctly ignored.');
882
  }
883

    
884
  /**
885
   * Make sure exceptions thrown on hook_cron() don't affect other modules.
886
   */
887
  function testCronExceptions() {
888
    variable_del('common_test_cron');
889
    // The common_test module throws an exception. If it isn't caught, the tests
890
    // won't finish successfully.
891
    // The common_test_cron_helper module sets the 'common_test_cron' variable.
892
    $this->cronRun();
893
    $result = variable_get('common_test_cron');
894
    $this->assertEqual($result, 'success', 'Cron correctly handles exceptions thrown during hook_cron() invocations.');
895
  }
896
}
897

    
898
/**
899
 * Test execution of the cron queue.
900
 */
901
class CronQueueTestCase extends DrupalWebTestCase {
902
  /**
903
   * Implement getInfo().
904
   */
905
  public static function getInfo() {
906
    return array(
907
      'name' => 'Cron queue functionality',
908
      'description' => 'Tests the cron queue runner.',
909
      'group' => 'System'
910
    );
911
  }
912

    
913
  function setUp() {
914
    parent::setUp(array('common_test', 'common_test_cron_helper'));
915
  }
916

    
917
  /**
918
   * Tests that exceptions thrown by workers are handled properly.
919
   */
920
  function testExceptions() {
921
    $queue = DrupalQueue::get('cron_queue_test_exception');
922

    
923
    // Enqueue an item for processing.
924
    $queue->createItem(array($this->randomName() => $this->randomName()));
925

    
926
    // Run cron; the worker for this queue should throw an exception and handle
927
    // it.
928
    $this->cronRun();
929

    
930
    // The item should be left in the queue.
931
    $this->assertEqual($queue->numberOfItems(), 1, 'Failing item still in the queue after throwing an exception.');
932
  }
933

    
934
}
935

    
936
class AdminMetaTagTestCase extends DrupalWebTestCase {
937
  /**
938
   * Implement getInfo().
939
   */
940
  public static function getInfo() {
941
    return array(
942
      'name' => 'Fingerprinting meta tag',
943
      'description' => 'Confirm that the fingerprinting meta tag appears as expected.',
944
      'group' => 'System'
945
    );
946
  }
947

    
948
  /**
949
   * Verify that the meta tag HTML is generated correctly.
950
   */
951
  public function testMetaTag() {
952
    list($version, ) = explode('.', VERSION);
953
    $string = '<meta name="Generator" content="Drupal ' . $version . ' (http://drupal.org)" />';
954
    $this->drupalGet('node');
955
    $this->assertRaw($string, 'Fingerprinting meta tag generated correctly.', 'System');
956
  }
957
}
958

    
959
/**
960
 * Tests custom access denied functionality.
961
 */
962
class AccessDeniedTestCase extends DrupalWebTestCase {
963
  protected $admin_user;
964

    
965
  public static function getInfo() {
966
    return array(
967
      'name' => '403 functionality',
968
      'description' => 'Tests page access denied functionality, including custom 403 pages.',
969
      'group' => 'System'
970
    );
971
  }
972

    
973
  function setUp() {
974
    parent::setUp();
975

    
976
    // Create an administrative user.
977
    $this->admin_user = $this->drupalCreateUser(array('access administration pages', 'administer site configuration', 'administer blocks'));
978
  }
979

    
980
  function testAccessDenied() {
981
    $this->drupalGet('admin');
982
    $this->assertText(t('Access denied'), 'Found the default 403 page');
983
    $this->assertResponse(403);
984

    
985
    $this->drupalLogin($this->admin_user);
986
    $edit = array(
987
      'title' => $this->randomName(10),
988
      'body' => array(LANGUAGE_NONE => array(array('value' => $this->randomName(100)))),
989
    );
990
    $node = $this->drupalCreateNode($edit);
991

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

    
995
    $this->drupalLogout();
996
    $this->drupalGet('admin');
997
    $this->assertText($node->title, 'Found the custom 403 page');
998

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

    
1002
    $this->drupalGet('admin');
1003
    $this->assertText($node->title, 'Found the custom 403 page');
1004
    $this->assertText(t('User login'), 'Blocks are shown on the custom 403 page');
1005

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

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

    
1013
    $this->drupalGet('admin');
1014
    $this->assertText(t('Access denied'), 'Found the default 403 page');
1015
    $this->assertResponse(403);
1016
    $this->assertText(t('User login'), 'Blocks are shown on the default 403 page');
1017

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

    
1023
    // Check that we can log in from the 403 page.
1024
    $this->drupalLogout();
1025
    $edit = array(
1026
      'name' => $this->admin_user->name,
1027
      'pass' => $this->admin_user->pass_raw,
1028
    );
1029
    $this->drupalPost('admin/config/system/site-information', $edit, t('Log in'));
1030

    
1031
    // Check that we're still on the same page.
1032
    $this->assertText(t('Site information'));
1033
  }
1034
}
1035

    
1036
class PageNotFoundTestCase extends DrupalWebTestCase {
1037
  protected $admin_user;
1038

    
1039
  /**
1040
   * Implement getInfo().
1041
   */
1042
  public static function getInfo() {
1043
    return array(
1044
      'name' => '404 functionality',
1045
      'description' => "Tests page not found functionality, including custom 404 pages.",
1046
      'group' => 'System'
1047
    );
1048
  }
1049

    
1050
  /**
1051
   * Implement setUp().
1052
   */
1053
  function setUp() {
1054
    parent::setUp();
1055

    
1056
    // Create an administrative user.
1057
    $this->admin_user = $this->drupalCreateUser(array('administer site configuration'));
1058
    $this->drupalLogin($this->admin_user);
1059
  }
1060

    
1061
  function testPageNotFound() {
1062
    $this->drupalGet($this->randomName(10));
1063
    $this->assertText(t('Page not found'), 'Found the default 404 page');
1064

    
1065
    $edit = array(
1066
      'title' => $this->randomName(10),
1067
      'body' => array(LANGUAGE_NONE => array(array('value' => $this->randomName(100)))),
1068
    );
1069
    $node = $this->drupalCreateNode($edit);
1070

    
1071
    // As node IDs must be integers, make sure requests for non-integer IDs
1072
    // return a page not found error.
1073
    $this->drupalGet('node/invalid');
1074
    $this->assertResponse(404);
1075

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

    
1079
    $this->drupalGet($this->randomName(10));
1080
    $this->assertText($node->title, 'Found the custom 404 page');
1081
  }
1082
}
1083

    
1084
/**
1085
 * Tests site maintenance functionality.
1086
 */
1087
class SiteMaintenanceTestCase extends DrupalWebTestCase {
1088
  protected $admin_user;
1089

    
1090
  public static function getInfo() {
1091
    return array(
1092
      'name' => 'Site maintenance mode functionality',
1093
      'description' => 'Test access to site while in maintenance mode.',
1094
      'group' => 'System',
1095
    );
1096
  }
1097

    
1098
  function setUp() {
1099
    parent::setUp();
1100

    
1101
    // Create a user allowed to access site in maintenance mode.
1102
    $this->user = $this->drupalCreateUser(array('access site in maintenance mode'));
1103
    // Create an administrative user.
1104
    $this->admin_user = $this->drupalCreateUser(array('administer site configuration', 'access site in maintenance mode'));
1105
    $this->drupalLogin($this->admin_user);
1106
  }
1107

    
1108
  /**
1109
   * Verify site maintenance mode functionality.
1110
   */
1111
  function testSiteMaintenance() {
1112
    // Turn on maintenance mode.
1113
    $edit = array(
1114
      'maintenance_mode' => 1,
1115
    );
1116
    $this->drupalPost('admin/config/development/maintenance', $edit, t('Save configuration'));
1117

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

    
1122
    $this->drupalGet('');
1123
    $this->assertRaw($admin_message, 'Found the site maintenance mode message.');
1124

    
1125
    // Logout and verify that offline message is displayed.
1126
    $this->drupalLogout();
1127
    $this->drupalGet('');
1128
    $this->assertText($offline_message);
1129
    $this->drupalGet('node');
1130
    $this->assertText($offline_message);
1131
    $this->drupalGet('user/register');
1132
    $this->assertText($offline_message);
1133

    
1134
    // Verify that user is able to log in.
1135
    $this->drupalGet('user');
1136
    $this->assertNoText($offline_message);
1137
    $this->drupalGet('user/login');
1138
    $this->assertNoText($offline_message);
1139

    
1140
    // Log in user and verify that maintenance mode message is displayed
1141
    // directly after login.
1142
    $edit = array(
1143
      'name' => $this->user->name,
1144
      'pass' => $this->user->pass_raw,
1145
    );
1146
    $this->drupalPost(NULL, $edit, t('Log in'));
1147
    $this->assertText($user_message);
1148

    
1149
    // Log in administrative user and configure a custom site offline message.
1150
    $this->drupalLogout();
1151
    $this->drupalLogin($this->admin_user);
1152
    $this->drupalGet('admin/config/development/maintenance');
1153
    $this->assertNoRaw($admin_message, 'Site maintenance mode message not displayed.');
1154

    
1155
    $offline_message = 'Sorry, not online.';
1156
    $edit = array(
1157
      'maintenance_mode_message' => $offline_message,
1158
    );
1159
    $this->drupalPost(NULL, $edit, t('Save configuration'));
1160

    
1161
    // Logout and verify that custom site offline message is displayed.
1162
    $this->drupalLogout();
1163
    $this->drupalGet('');
1164
    $this->assertRaw($offline_message, 'Found the site offline message.');
1165

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

    
1170
    // Submit password reset form.
1171
    $edit = array(
1172
      'name' => $this->user->name,
1173
    );
1174
    $this->drupalPost('user/password', $edit, t('E-mail new password'));
1175
    $mails = $this->drupalGetMails();
1176
    $start = strpos($mails[0]['body'], 'user/reset/'. $this->user->uid);
1177
    $path = substr($mails[0]['body'], $start, 66 + strlen($this->user->uid));
1178

    
1179
    // Log in with temporary login link.
1180
    $this->drupalPost($path, array(), t('Log in'));
1181
    $this->assertText($user_message);
1182
  }
1183
}
1184

    
1185
/**
1186
 * Tests generic date and time handling capabilities of Drupal.
1187
 */
1188
class DateTimeFunctionalTest extends DrupalWebTestCase {
1189
  public static function getInfo() {
1190
    return array(
1191
      'name' => 'Date and time',
1192
      'description' => 'Configure date and time settings. Test date formatting and time zone handling, including daylight saving time.',
1193
      'group' => 'System',
1194
    );
1195
  }
1196

    
1197
  function setUp() {
1198
    parent::setUp(array('locale'));
1199

    
1200
    // Create admin user and log in admin user.
1201
    $this->admin_user = $this->drupalCreateUser(array('administer site configuration'));
1202
    $this->drupalLogin($this->admin_user);
1203
  }
1204

    
1205

    
1206
  /**
1207
   * Test time zones and DST handling.
1208
   */
1209
  function testTimeZoneHandling() {
1210
    // Setup date/time settings for Honolulu time.
1211
    variable_set('date_default_timezone', 'Pacific/Honolulu');
1212
    variable_set('configurable_timezones', 0);
1213
    variable_set('date_format_medium', 'Y-m-d H:i:s O');
1214

    
1215
    // Create some nodes with different authored-on dates.
1216
    $date1 = '2007-01-31 21:00:00 -1000';
1217
    $date2 = '2007-07-31 21:00:00 -1000';
1218
    $node1 = $this->drupalCreateNode(array('created' => strtotime($date1), 'type' => 'article'));
1219
    $node2 = $this->drupalCreateNode(array('created' => strtotime($date2), 'type' => 'article'));
1220

    
1221
    // Confirm date format and time zone.
1222
    $this->drupalGet("node/$node1->nid");
1223
    $this->assertText('2007-01-31 21:00:00 -1000', 'Date should be identical, with GMT offset of -10 hours.');
1224
    $this->drupalGet("node/$node2->nid");
1225
    $this->assertText('2007-07-31 21:00:00 -1000', 'Date should be identical, with GMT offset of -10 hours.');
1226

    
1227
    // Set time zone to Los Angeles time.
1228
    variable_set('date_default_timezone', 'America/Los_Angeles');
1229

    
1230
    // Confirm date format and time zone.
1231
    $this->drupalGet("node/$node1->nid");
1232
    $this->assertText('2007-01-31 23:00:00 -0800', 'Date should be two hours ahead, with GMT offset of -8 hours.');
1233
    $this->drupalGet("node/$node2->nid");
1234
    $this->assertText('2007-08-01 00:00:00 -0700', 'Date should be three hours ahead, with GMT offset of -7 hours.');
1235
  }
1236

    
1237
  /**
1238
   * Test date type configuration.
1239
   */
1240
  function testDateTypeConfiguration() {
1241
    // Confirm system date types appear.
1242
    $this->drupalGet('admin/config/regional/date-time');
1243
    $this->assertText(t('Medium'), 'System date types appear in date type list.');
1244
    $this->assertNoRaw('href="/admin/config/regional/date-time/types/medium/delete"', 'No delete link appear for system date types.');
1245

    
1246
    // Add custom date type.
1247
    $this->clickLink(t('Add date type'));
1248
    $date_type = strtolower($this->randomName(8));
1249
    $machine_name = 'machine_' . $date_type;
1250
    $date_format = 'd.m.Y - H:i';
1251
    $edit = array(
1252
      'date_type' => $date_type,
1253
      'machine_name' => $machine_name,
1254
      'date_format' => $date_format,
1255
    );
1256
    $this->drupalPost('admin/config/regional/date-time/types/add', $edit, t('Add date type'));
1257
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time', array('absolute' => TRUE)), 'Correct page redirection.');
1258
    $this->assertText(t('New date type added successfully.'), 'Date type added confirmation message appears.');
1259
    $this->assertText($date_type, 'Custom date type appears in the date type list.');
1260
    $this->assertText(t('delete'), 'Delete link for custom date type appears.');
1261

    
1262
    // Delete custom date type.
1263
    $this->clickLink(t('delete'));
1264
    $this->drupalPost('admin/config/regional/date-time/types/' . $machine_name . '/delete', array(), t('Remove'));
1265
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time', array('absolute' => TRUE)), 'Correct page redirection.');
1266
    $this->assertText(t('Removed date type ' . $date_type), 'Custom date type removed.');
1267
  }
1268

    
1269
  /**
1270
   * Test date format configuration.
1271
   */
1272
  function testDateFormatConfiguration() {
1273
    // Confirm 'no custom date formats available' message appears.
1274
    $this->drupalGet('admin/config/regional/date-time/formats');
1275
    $this->assertText(t('No custom date formats available.'), 'No custom date formats message appears.');
1276

    
1277
    // Add custom date format.
1278
    $this->clickLink(t('Add format'));
1279
    $edit = array(
1280
      'date_format' => 'Y',
1281
    );
1282
    $this->drupalPost('admin/config/regional/date-time/formats/add', $edit, t('Add format'));
1283
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE)), 'Correct page redirection.');
1284
    $this->assertNoText(t('No custom date formats available.'), 'No custom date formats message does not appear.');
1285
    $this->assertText(t('Custom date format added.'), 'Custom date format added.');
1286

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

    
1291
    // Edit custom date format.
1292
    $this->drupalGet('admin/config/regional/date-time/formats');
1293
    $this->clickLink(t('edit'));
1294
    $edit = array(
1295
      'date_format' => 'Y m',
1296
    );
1297
    $this->drupalPost($this->getUrl(), $edit, t('Save format'));
1298
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE)), 'Correct page redirection.');
1299
    $this->assertText(t('Custom date format updated.'), 'Custom date format successfully updated.');
1300

    
1301
    // Delete custom date format.
1302
    $this->clickLink(t('delete'));
1303
    $this->drupalPost($this->getUrl(), array(), t('Remove'));
1304
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE)), 'Correct page redirection.');
1305
    $this->assertText(t('Removed date format'), 'Custom date format removed successfully.');
1306
  }
1307

    
1308
  /**
1309
   * Test if the date formats are stored properly.
1310
   */
1311
  function testDateFormatStorage() {
1312
    $date_format = array(
1313
      'type' => 'short',
1314
      'format' => 'dmYHis',
1315
      'locked' => 0,
1316
      'is_new' => 1,
1317
    );
1318
    system_date_format_save($date_format);
1319

    
1320
    $format = db_select('date_formats', 'df')
1321
      ->fields('df', array('format'))
1322
      ->condition('type', 'short')
1323
      ->condition('format', 'dmYHis')
1324
      ->execute()
1325
      ->fetchField();
1326
    $this->verbose($format);
1327
    $this->assertEqual('dmYHis', $format, 'Unlocalized date format resides in general table.');
1328

    
1329
    $format = db_select('date_format_locale', 'dfl')
1330
      ->fields('dfl', array('format'))
1331
      ->condition('type', 'short')
1332
      ->condition('format', 'dmYHis')
1333
      ->execute()
1334
      ->fetchField();
1335
    $this->assertFalse($format, 'Unlocalized date format resides not in localized table.');
1336

    
1337
    // Enable German language
1338
    locale_add_language('de', NULL, NULL, LANGUAGE_LTR, '', '', TRUE, 'en');
1339

    
1340
    $date_format = array(
1341
      'type' => 'short',
1342
      'format' => 'YMDHis',
1343
      'locales' => array('de', 'tr'),
1344
      'locked' => 0,
1345
      'is_new' => 1,
1346
    );
1347
    system_date_format_save($date_format);
1348

    
1349
    $format = db_select('date_format_locale', 'dfl')
1350
      ->fields('dfl', array('format'))
1351
      ->condition('type', 'short')
1352
      ->condition('format', 'YMDHis')
1353
      ->condition('language', 'de')
1354
      ->execute()
1355
      ->fetchField();
1356
    $this->assertEqual('YMDHis', $format, 'Localized date format resides in localized table.');
1357

    
1358
    $format = db_select('date_formats', 'df')
1359
      ->fields('df', array('format'))
1360
      ->condition('type', 'short')
1361
      ->condition('format', 'YMDHis')
1362
      ->execute()
1363
      ->fetchField();
1364
    $this->assertEqual('YMDHis', $format, 'Localized date format resides in general table too.');
1365

    
1366
    $format = db_select('date_format_locale', 'dfl')
1367
      ->fields('dfl', array('format'))
1368
      ->condition('type', 'short')
1369
      ->condition('format', 'YMDHis')
1370
      ->condition('language', 'tr')
1371
      ->execute()
1372
      ->fetchColumn();
1373
    $this->assertFalse($format, 'Localized date format for disabled language is ignored.');
1374
  }
1375
}
1376

    
1377
class PageTitleFiltering extends DrupalWebTestCase {
1378
  protected $content_user;
1379
  protected $saved_title;
1380

    
1381
  /**
1382
   * Implement getInfo().
1383
   */
1384
  public static function getInfo() {
1385
    return array(
1386
      'name' => 'HTML in page titles',
1387
      'description' => 'Tests correct handling or conversion by drupal_set_title() and drupal_get_title() and checks the correct escaping of site name and slogan.',
1388
      'group' => 'System'
1389
    );
1390
  }
1391

    
1392
  /**
1393
   * Implement setUp().
1394
   */
1395
  function setUp() {
1396
    parent::setUp();
1397

    
1398
    $this->content_user = $this->drupalCreateUser(array('create page content', 'access content', 'administer themes', 'administer site configuration'));
1399
    $this->drupalLogin($this->content_user);
1400
    $this->saved_title = drupal_get_title();
1401
  }
1402

    
1403
  /**
1404
   * Reset page title.
1405
   */
1406
  function tearDown() {
1407
    // Restore the page title.
1408
    drupal_set_title($this->saved_title, PASS_THROUGH);
1409

    
1410
    parent::tearDown();
1411
  }
1412

    
1413
  /**
1414
   * Tests the handling of HTML by drupal_set_title() and drupal_get_title()
1415
   */
1416
  function testTitleTags() {
1417
    $title = "string with <em>HTML</em>";
1418
    // drupal_set_title's $filter is CHECK_PLAIN by default, so the title should be
1419
    // returned with check_plain().
1420
    drupal_set_title($title, CHECK_PLAIN);
1421
    $this->assertTrue(strpos(drupal_get_title(), '<em>') === FALSE, 'Tags in title converted to entities when $output is CHECK_PLAIN.');
1422
    // drupal_set_title's $filter is passed as PASS_THROUGH, so the title should be
1423
    // returned with HTML.
1424
    drupal_set_title($title, PASS_THROUGH);
1425
    $this->assertTrue(strpos(drupal_get_title(), '<em>') !== FALSE, 'Tags in title are not converted to entities when $output is PASS_THROUGH.');
1426
    // Generate node content.
1427
    $langcode = LANGUAGE_NONE;
1428
    $edit = array(
1429
      "title" => '!SimpleTest! ' . $title . $this->randomName(20),
1430
      "body[$langcode][0][value]" => '!SimpleTest! test body' . $this->randomName(200),
1431
    );
1432
    // Create the node with HTML in the title.
1433
    $this->drupalPost('node/add/page', $edit, t('Save'));
1434

    
1435
    $node = $this->drupalGetNodeByTitle($edit["title"]);
1436
    $this->assertNotNull($node, 'Node created and found in database');
1437
    $this->drupalGet("node/" . $node->nid);
1438
    $this->assertText(check_plain($edit["title"]), 'Check to make sure tags in the node title are converted.');
1439
  }
1440
  /**
1441
   * Test if the title of the site is XSS proof.
1442
   */
1443
  function testTitleXSS() {
1444
    // Set some title with JavaScript and HTML chars to escape.
1445
    $title = '</title><script type="text/javascript">alert("Title XSS!");</script> & < > " \' ';
1446
    $title_filtered = check_plain($title);
1447

    
1448
    $slogan = '<script type="text/javascript">alert("Slogan XSS!");</script>';
1449
    $slogan_filtered = filter_xss_admin($slogan);
1450

    
1451
    // Activate needed appearance settings.
1452
    $edit = array(
1453
      'toggle_name'           => TRUE,
1454
      'toggle_slogan'         => TRUE,
1455
      'toggle_main_menu'      => TRUE,
1456
      'toggle_secondary_menu' => TRUE,
1457
    );
1458
    $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
1459

    
1460
    // Set title and slogan.
1461
    $edit = array(
1462
      'site_name'    => $title,
1463
      'site_slogan'  => $slogan,
1464
    );
1465
    $this->drupalPost('admin/config/system/site-information', $edit, t('Save configuration'));
1466

    
1467
    // Load frontpage.
1468
    $this->drupalGet('');
1469

    
1470
    // Test the title.
1471
    $this->assertNoRaw($title, 'Check for the unfiltered version of the title.');
1472
    // Adding </title> so we do not test the escaped version from drupal_set_title().
1473
    $this->assertRaw($title_filtered . '</title>', 'Check for the filtered version of the title.');
1474

    
1475
    // Test the slogan.
1476
    $this->assertNoRaw($slogan, 'Check for the unfiltered version of the slogan.');
1477
    $this->assertRaw($slogan_filtered, 'Check for the filtered version of the slogan.');
1478
  }
1479
}
1480

    
1481
/**
1482
 * Test front page functionality and administration.
1483
 */
1484
class FrontPageTestCase extends DrupalWebTestCase {
1485

    
1486
  public static function getInfo() {
1487
    return array(
1488
      'name' => 'Front page',
1489
      'description' => 'Tests front page functionality and administration.',
1490
      'group' => 'System',
1491
    );
1492
  }
1493

    
1494
  function setUp() {
1495
    parent::setUp('system_test');
1496

    
1497
    // Create admin user, log in admin user, and create one node.
1498
    $this->admin_user = $this->drupalCreateUser(array('access content', 'administer site configuration'));
1499
    $this->drupalLogin($this->admin_user);
1500
    $this->node_path = "node/" . $this->drupalCreateNode(array('promote' => 1))->nid;
1501

    
1502
    // Enable front page logging in system_test.module.
1503
    variable_set('front_page_output', 1);
1504
  }
1505

    
1506
  /**
1507
   * Test front page functionality.
1508
   */
1509
  function testDrupalIsFrontPage() {
1510
    $this->drupalGet('');
1511
    $this->assertText(t('On front page.'), 'Path is the front page.');
1512
    $this->drupalGet('node');
1513
    $this->assertText(t('On front page.'), 'Path is the front page.');
1514
    $this->drupalGet($this->node_path);
1515
    $this->assertNoText(t('On front page.'), 'Path is not the front page.');
1516

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

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

    
1527
    $this->drupalGet('');
1528
    $this->assertText(t('On front page.'), 'Path is the front page.');
1529
    $this->drupalGet('node');
1530
    $this->assertNoText(t('On front page.'), 'Path is not the front page.');
1531
    $this->drupalGet($this->node_path);
1532
    $this->assertText(t('On front page.'), 'Path is the front page.');
1533
  }
1534
}
1535

    
1536
class SystemBlockTestCase extends DrupalWebTestCase {
1537
  protected $profile = 'testing';
1538

    
1539
  public static function getInfo() {
1540
    return array(
1541
      'name' => 'Block functionality',
1542
      'description' => 'Configure and move powered-by block.',
1543
      'group' => 'System',
1544
    );
1545
  }
1546

    
1547
  function setUp() {
1548
    parent::setUp('block');
1549

    
1550
    // Create and login user
1551
    $admin_user = $this->drupalCreateUser(array('administer blocks', 'access administration pages'));
1552
    $this->drupalLogin($admin_user);
1553
  }
1554

    
1555
  /**
1556
   * Test displaying and hiding the powered-by and help blocks.
1557
   */
1558
  function testSystemBlocks() {
1559
    // Set block title and some settings to confirm that the interface is available.
1560
    $this->drupalPost('admin/structure/block/manage/system/powered-by/configure', array('title' => $this->randomName(8)), t('Save block'));
1561
    $this->assertText(t('The block configuration has been saved.'), t('Block configuration set.'));
1562

    
1563
    // Set the powered-by block to the footer region.
1564
    $edit = array();
1565
    $edit['blocks[system_powered-by][region]'] = 'footer';
1566
    $edit['blocks[system_main][region]'] = 'content';
1567
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1568
    $this->assertText(t('The block settings have been updated.'), t('Block successfully moved to footer region.'));
1569

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

    
1574
    // Set the block to the disabled region.
1575
    $edit = array();
1576
    $edit['blocks[system_powered-by][region]'] = '-1';
1577
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1578

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

    
1582
    // For convenience of developers, set the block to its default settings.
1583
    $edit = array();
1584
    $edit['blocks[system_powered-by][region]'] = 'footer';
1585
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1586
    $this->drupalPost('admin/structure/block/manage/system/powered-by/configure', array('title' => ''), t('Save block'));
1587

    
1588
    // Set the help block to the help region.
1589
    $edit = array();
1590
    $edit['blocks[system_help][region]'] = 'help';
1591
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1592

    
1593
    // Test displaying the help block with block caching enabled.
1594
    variable_set('block_cache', TRUE);
1595
    $this->drupalGet('admin/structure/block/add');
1596
    $this->assertRaw(t('Use this page to create a new custom block.'));
1597
    $this->drupalGet('admin/index');
1598
    $this->assertRaw(t('This page shows you all available administration tasks for each module.'));
1599
  }
1600
}
1601

    
1602
/**
1603
 * Test main content rendering fallback provided by system module.
1604
 */
1605
class SystemMainContentFallback extends DrupalWebTestCase {
1606
  protected $admin_user;
1607
  protected $web_user;
1608

    
1609
  public static function getInfo() {
1610
    return array(
1611
      'name' => 'Main content rendering fallback',
1612
      'description' => ' Test system module main content rendering fallback.',
1613
      'group' => 'System',
1614
    );
1615
  }
1616

    
1617
  function setUp() {
1618
    parent::setUp('system_test');
1619

    
1620
    // Create and login admin user.
1621
    $this->admin_user = $this->drupalCreateUser(array(
1622
      'access administration pages',
1623
      'administer site configuration',
1624
      'administer modules',
1625
      'administer blocks',
1626
      'administer nodes',
1627
    ));
1628
    $this->drupalLogin($this->admin_user);
1629

    
1630
    // Create a web user.
1631
    $this->web_user = $this->drupalCreateUser(array('access user profiles', 'access content'));
1632
  }
1633

    
1634
  /**
1635
   * Test availability of main content.
1636
   */
1637
  function testMainContentFallback() {
1638
    $edit = array();
1639
    // Disable the dashboard module, which depends on the block module.
1640
    $edit['modules[Core][dashboard][enable]'] = FALSE;
1641
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
1642
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
1643
    // Disable the block module.
1644
    $edit['modules[Core][block][enable]'] = FALSE;
1645
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
1646
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
1647
    module_list(TRUE);
1648
    $this->assertFalse(module_exists('block'), 'Block module disabled.');
1649

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

    
1654
    // Fallback should not trigger when another module is handling content.
1655
    $this->drupalGet('system-test/main-content-handling');
1656
    $this->assertRaw('id="system-test-content"', 'Content handled by another module');
1657
    $this->assertText(t('Content to test main content fallback'), 'Main content still displayed.');
1658

    
1659
    // Fallback should trigger when another module
1660
    // indicates that it is not handling the content.
1661
    $this->drupalGet('system-test/main-content-fallback');
1662
    $this->assertText(t('Content to test main content fallback'), 'Main content fallback properly triggers.');
1663

    
1664
    // Fallback should not trigger when another module is handling content.
1665
    // Note that this test ensures that no duplicate
1666
    // content gets created by the fallback.
1667
    $this->drupalGet('system-test/main-content-duplication');
1668
    $this->assertNoText(t('Content to test main content fallback'), 'Main content not duplicated.');
1669

    
1670
    // Request a user* page and see if it is displayed.
1671
    $this->drupalLogin($this->web_user);
1672
    $this->drupalGet('user/' . $this->web_user->uid . '/edit');
1673
    $this->assertField('mail', 'User interface still available.');
1674

    
1675
    // Enable the block module again.
1676
    $this->drupalLogin($this->admin_user);
1677
    $edit = array();
1678
    $edit['modules[Core][block][enable]'] = 'block';
1679
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
1680
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
1681
    module_list(TRUE);
1682
    $this->assertTrue(module_exists('block'), 'Block module re-enabled.');
1683
  }
1684
}
1685

    
1686
/**
1687
 * Tests for the theme interface functionality.
1688
 */
1689
class SystemThemeFunctionalTest extends DrupalWebTestCase {
1690
  public static function getInfo() {
1691
    return array(
1692
      'name' => 'Theme interface functionality',
1693
      'description' => 'Tests the theme interface functionality by enabling and switching themes, and using an administration theme.',
1694
      'group' => 'System',
1695
    );
1696
  }
1697

    
1698
  function setUp() {
1699
    parent::setUp();
1700

    
1701
    $this->admin_user = $this->drupalCreateUser(array('access administration pages', 'view the administration theme', 'administer themes', 'bypass node access', 'administer blocks'));
1702
    $this->drupalLogin($this->admin_user);
1703
    $this->node = $this->drupalCreateNode();
1704
  }
1705

    
1706
  /**
1707
   * Test the theme settings form.
1708
   */
1709
  function testThemeSettings() {
1710
    // Specify a filesystem path to be used for the logo.
1711
    $file = current($this->drupalGetTestFiles('image'));
1712
    $file_relative = strtr($file->uri, array('public:/' => variable_get('file_public_path', conf_path() . '/files')));
1713
    $default_theme_path = 'themes/stark';
1714

    
1715
    $supported_paths = array(
1716
      // Raw stream wrapper URI.
1717
      $file->uri => array(
1718
        'form' => file_uri_target($file->uri),
1719
        'src' => file_create_url($file->uri),
1720
      ),
1721
      // Relative path within the public filesystem.
1722
      file_uri_target($file->uri) => array(
1723
        'form' => file_uri_target($file->uri),
1724
        'src' => file_create_url($file->uri),
1725
      ),
1726
      // Relative path to a public file.
1727
      $file_relative => array(
1728
        'form' => $file_relative,
1729
        'src' => file_create_url($file->uri),
1730
      ),
1731
      // Relative path to an arbitrary file.
1732
      'misc/druplicon.png' => array(
1733
        'form' => 'misc/druplicon.png',
1734
        'src' => $GLOBALS['base_url'] . '/' . 'misc/druplicon.png',
1735
      ),
1736
      // Relative path to a file in a theme.
1737
      $default_theme_path . '/logo.png' => array(
1738
        'form' => $default_theme_path . '/logo.png',
1739
        'src' => $GLOBALS['base_url'] . '/' . $default_theme_path . '/logo.png',
1740
      ),
1741
    );
1742
    foreach ($supported_paths as $input => $expected) {
1743
      $edit = array(
1744
        'default_logo' => FALSE,
1745
        'logo_path' => $input,
1746
      );
1747
      $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
1748
      $this->assertNoText('The custom logo path is invalid.');
1749
      $this->assertFieldByName('logo_path', $expected['form']);
1750

    
1751
      // Verify the actual 'src' attribute of the logo being output.
1752
      $this->drupalGet('');
1753
      $elements = $this->xpath('//*[@id=:id]/img', array(':id' => 'logo'));
1754
      $this->assertEqual((string) $elements[0]['src'], $expected['src']);
1755
    }
1756

    
1757
    $unsupported_paths = array(
1758
      // Stream wrapper URI to non-existing file.
1759
      'public://whatever.png',
1760
      'private://whatever.png',
1761
      'temporary://whatever.png',
1762
      // Bogus stream wrapper URIs.
1763
      'public:/whatever.png',
1764
      '://whatever.png',
1765
      ':whatever.png',
1766
      'public://',
1767
      // Relative path within the public filesystem to non-existing file.
1768
      'whatever.png',
1769
      // Relative path to non-existing file in public filesystem.
1770
      variable_get('file_public_path', conf_path() . '/files') . '/whatever.png',
1771
      // Semi-absolute path to non-existing file in public filesystem.
1772
      '/' . variable_get('file_public_path', conf_path() . '/files') . '/whatever.png',
1773
      // Relative path to arbitrary non-existing file.
1774
      'misc/whatever.png',
1775
      // Semi-absolute path to arbitrary non-existing file.
1776
      '/misc/whatever.png',
1777
      // Absolute paths to any local file (even if it exists).
1778
      drupal_realpath($file->uri),
1779
    );
1780
    $this->drupalGet('admin/appearance/settings');
1781
    foreach ($unsupported_paths as $path) {
1782
      $edit = array(
1783
        'default_logo' => FALSE,
1784
        'logo_path' => $path,
1785
      );
1786
      $this->drupalPost(NULL, $edit, t('Save configuration'));
1787
      $this->assertText('The custom logo path is invalid.');
1788
    }
1789

    
1790
    // Upload a file to use for the logo.
1791
    $edit = array(
1792
      'default_logo' => FALSE,
1793
      'logo_path' => '',
1794
      'files[logo_upload]' => drupal_realpath($file->uri),
1795
    );
1796
    $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
1797

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

    
1801
    $this->drupalGet('');
1802
    $elements = $this->xpath('//*[@id=:id]/img', array(':id' => 'logo'));
1803
    $this->assertEqual($elements[0]['src'], file_create_url($uploaded_filename));
1804
  }
1805

    
1806
  /**
1807
   * Test the administration theme functionality.
1808
   */
1809
  function testAdministrationTheme() {
1810
    theme_enable(array('stark'));
1811
    variable_set('theme_default', 'stark');
1812
    // Enable an administration theme and show it on the node admin pages.
1813
    $edit = array(
1814
      'admin_theme' => 'seven',
1815
      'node_admin_theme' => TRUE,
1816
    );
1817
    $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
1818

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

    
1822
    $this->drupalGet('node/' . $this->node->nid);
1823
    $this->assertRaw('themes/stark', 'Site default theme used on node page.');
1824

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

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

    
1831
    // Disable the admin theme on the node admin pages.
1832
    $edit = array(
1833
      'node_admin_theme' => FALSE,
1834
    );
1835
    $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
1836

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

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

    
1843
    // Reset to the default theme settings.
1844
    variable_set('theme_default', 'bartik');
1845
    $edit = array(
1846
      'admin_theme' => '0',
1847
      'node_admin_theme' => FALSE,
1848
    );
1849
    $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
1850

    
1851
    $this->drupalGet('admin');
1852
    $this->assertRaw('themes/bartik', 'Site default theme used on administration page.');
1853

    
1854
    $this->drupalGet('node/add');
1855
    $this->assertRaw('themes/bartik', 'Site default theme used on the add content page.');
1856
  }
1857

    
1858
  /**
1859
   * Test switching the default theme.
1860
   */
1861
  function testSwitchDefaultTheme() {
1862
    // Enable "stark" and set it as the default theme.
1863
    theme_enable(array('stark'));
1864
    $this->drupalGet('admin/appearance');
1865
    $this->clickLink(t('Set default'), 1);
1866
    $this->assertTrue(variable_get('theme_default', '') == 'stark', 'Site default theme switched successfully.');
1867

    
1868
    // Test the default theme on the secondary links (blocks admin page).
1869
    $this->drupalGet('admin/structure/block');
1870
    $this->assertText('Stark(' . t('active tab') . ')', 'Default local task on blocks admin page is the default theme.');
1871
    // Switch back to Bartik and test again to test that the menu cache is cleared.
1872
    $this->drupalGet('admin/appearance');
1873
    $this->clickLink(t('Set default'), 0);
1874
    $this->drupalGet('admin/structure/block');
1875
    $this->assertText('Bartik(' . t('active tab') . ')', 'Default local task on blocks admin page has changed.');
1876
  }
1877
}
1878

    
1879

    
1880
/**
1881
 * Test the basic queue functionality.
1882
 */
1883
class QueueTestCase extends DrupalWebTestCase {
1884
  public static function getInfo() {
1885
    return array(
1886
      'name' => 'Queue functionality',
1887
      'description' => 'Queues and dequeues a set of items to check the basic queue functionality.',
1888
      'group' => 'System',
1889
    );
1890
  }
1891

    
1892
  /**
1893
   * Queues and dequeues a set of items to check the basic queue functionality.
1894
   */
1895
  function testQueue() {
1896
    // Create two queues.
1897
    $queue1 = DrupalQueue::get($this->randomName());
1898
    $queue1->createQueue();
1899
    $queue2 = DrupalQueue::get($this->randomName());
1900
    $queue2->createQueue();
1901

    
1902
    // Create four items.
1903
    $data = array();
1904
    for ($i = 0; $i < 4; $i++) {
1905
      $data[] = array($this->randomName() => $this->randomName());
1906
    }
1907

    
1908
    // Queue items 1 and 2 in the queue1.
1909
    $queue1->createItem($data[0]);
1910
    $queue1->createItem($data[1]);
1911

    
1912
    // Retrieve two items from queue1.
1913
    $items = array();
1914
    $new_items = array();
1915

    
1916
    $items[] = $item = $queue1->claimItem();
1917
    $new_items[] = $item->data;
1918

    
1919
    $items[] = $item = $queue1->claimItem();
1920
    $new_items[] = $item->data;
1921

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

    
1925
    // Add two more items.
1926
    $queue1->createItem($data[2]);
1927
    $queue1->createItem($data[3]);
1928

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

    
1932
    $items[] = $item = $queue1->claimItem();
1933
    $new_items[] = $item->data;
1934

    
1935
    $items[] = $item = $queue1->claimItem();
1936
    $new_items[] = $item->data;
1937

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

    
1942
    // There should be no duplicate items.
1943
    $this->assertEqual($this->queueScore($new_items, $new_items), 4, 'Four items matched');
1944

    
1945
    // Delete all items from queue1.
1946
    foreach ($items as $item) {
1947
      $queue1->deleteItem($item);
1948
    }
1949

    
1950
    // Check that both queues are empty.
1951
    $this->assertFalse($queue1->numberOfItems(), 'Queue 1 is empty');
1952
    $this->assertFalse($queue2->numberOfItems(), 'Queue 2 is empty');
1953
  }
1954

    
1955
  /**
1956
   * This function returns the number of equal items in two arrays.
1957
   */
1958
  function queueScore($items, $new_items) {
1959
    $score = 0;
1960
    foreach ($items as $item) {
1961
      foreach ($new_items as $new_item) {
1962
        if ($item === $new_item) {
1963
          $score++;
1964
        }
1965
      }
1966
    }
1967
    return $score;
1968
  }
1969
}
1970

    
1971
/**
1972
 * Test token replacement in strings.
1973
 */
1974
class TokenReplaceTestCase extends DrupalWebTestCase {
1975
  public static function getInfo() {
1976
    return array(
1977
      'name' => 'Token replacement',
1978
      'description' => 'Generates text using placeholders for dummy content to check token replacement.',
1979
      'group' => 'System',
1980
    );
1981
  }
1982

    
1983
  /**
1984
   * Creates a user and a node, then tests the tokens generated from them.
1985
   */
1986
  function testTokenReplacement() {
1987
    // Create the initial objects.
1988
    $account = $this->drupalCreateUser();
1989
    $node = $this->drupalCreateNode(array('uid' => $account->uid));
1990
    $node->title = '<blink>Blinking Text</blink>';
1991
    global $user, $language;
1992

    
1993
    $source  = '[node:title]';         // Title of the node we passed in
1994
    $source .= '[node:author:name]';   // Node author's name
1995
    $source .= '[node:created:since]'; // Time since the node was created
1996
    $source .= '[current-user:name]';  // Current user's name
1997
    $source .= '[date:short]';         // Short date format of REQUEST_TIME
1998
    $source .= '[user:name]';          // No user passed in, should be untouched
1999
    $source .= '[bogus:token]';        // Non-existent token
2000

    
2001
    $target  = check_plain($node->title);
2002
    $target .= check_plain($account->name);
2003
    $target .= format_interval(REQUEST_TIME - $node->created, 2, $language->language);
2004
    $target .= check_plain($user->name);
2005
    $target .= format_date(REQUEST_TIME, 'short', '', NULL, $language->language);
2006

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

    
2011
    // Test without using the clear parameter (non-existent token untouched).
2012
    $target .= '[user:name]';
2013
    $target .= '[bogus:token]';
2014
    $result = token_replace($source, array('node' => $node), array('language' => $language));
2015
    $this->assertEqual($target, $result, 'Valid tokens replaced while invalid tokens ignored.');
2016

    
2017
    // Check that the results of token_generate are sanitized properly. This does NOT
2018
    // test the cleanliness of every token -- just that the $sanitize flag is being
2019
    // passed properly through the call stack and being handled correctly by a 'known'
2020
    // token, [node:title].
2021
    $raw_tokens = array('title' => '[node:title]');
2022
    $generated = token_generate('node', $raw_tokens, array('node' => $node));
2023
    $this->assertEqual($generated['[node:title]'], check_plain($node->title), 'Token sanitized.');
2024

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

    
2028
    // Test token replacement when the string contains no tokens.
2029
    $this->assertEqual(token_replace('No tokens here.'), 'No tokens here.');
2030
  }
2031

    
2032
  /**
2033
   * Test whether token-replacement works in various contexts.
2034
   */
2035
  function testSystemTokenRecognition() {
2036
    global $language;
2037

    
2038
    // Generate prefixes and suffixes for the token context.
2039
    $tests = array(
2040
      array('prefix' => 'this is the ', 'suffix' => ' site'),
2041
      array('prefix' => 'this is the', 'suffix' => 'site'),
2042
      array('prefix' => '[', 'suffix' => ']'),
2043
      array('prefix' => '', 'suffix' => ']]]'),
2044
      array('prefix' => '[[[', 'suffix' => ''),
2045
      array('prefix' => ':[:', 'suffix' => '--]'),
2046
      array('prefix' => '-[-', 'suffix' => ':]:'),
2047
      array('prefix' => '[:', 'suffix' => ']'),
2048
      array('prefix' => '[site:', 'suffix' => ':name]'),
2049
      array('prefix' => '[site:', 'suffix' => ']'),
2050
    );
2051

    
2052
    // Check if the token is recognized in each of the contexts.
2053
    foreach ($tests as $test) {
2054
      $input = $test['prefix'] . '[site:name]' . $test['suffix'];
2055
      $expected = $test['prefix'] . 'Drupal' . $test['suffix'];
2056
      $output = token_replace($input, array(), array('language' => $language));
2057
      $this->assertTrue($output == $expected, format_string('Token recognized in string %string', array('%string' => $input)));
2058
    }
2059
  }
2060

    
2061
  /**
2062
   * Tests the generation of all system site information tokens.
2063
   */
2064
  function testSystemSiteTokenReplacement() {
2065
    global $language;
2066
    $url_options = array(
2067
      'absolute' => TRUE,
2068
      'language' => $language,
2069
    );
2070

    
2071
    // Set a few site variables.
2072
    variable_set('site_name', '<strong>Drupal<strong>');
2073
    variable_set('site_slogan', '<blink>Slogan</blink>');
2074

    
2075
    // Generate and test sanitized tokens.
2076
    $tests = array();
2077
    $tests['[site:name]'] = check_plain(variable_get('site_name', 'Drupal'));
2078
    $tests['[site:slogan]'] = check_plain(variable_get('site_slogan', ''));
2079
    $tests['[site:mail]'] = 'simpletest@example.com';
2080
    $tests['[site:url]'] = url('<front>', $url_options);
2081
    $tests['[site:url-brief]'] = preg_replace(array('!^https?://!', '!/$!'), '', url('<front>', $url_options));
2082
    $tests['[site:login-url]'] = url('user', $url_options);
2083

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

    
2087
    foreach ($tests as $input => $expected) {
2088
      $output = token_replace($input, array(), array('language' => $language));
2089
      $this->assertEqual($output, $expected, format_string('Sanitized system site information token %token replaced.', array('%token' => $input)));
2090
    }
2091

    
2092
    // Generate and test unsanitized tokens.
2093
    $tests['[site:name]'] = variable_get('site_name', 'Drupal');
2094
    $tests['[site:slogan]'] = variable_get('site_slogan', '');
2095

    
2096
    foreach ($tests as $input => $expected) {
2097
      $output = token_replace($input, array(), array('language' => $language, 'sanitize' => FALSE));
2098
      $this->assertEqual($output, $expected, format_string('Unsanitized system site information token %token replaced.', array('%token' => $input)));
2099
    }
2100
  }
2101

    
2102
  /**
2103
   * Tests the generation of all system date tokens.
2104
   */
2105
  function testSystemDateTokenReplacement() {
2106
    global $language;
2107

    
2108
    // Set time to one hour before request.
2109
    $date = REQUEST_TIME - 3600;
2110

    
2111
    // Generate and test tokens.
2112
    $tests = array();
2113
    $tests['[date:short]'] = format_date($date, 'short', '', NULL, $language->language);
2114
    $tests['[date:medium]'] = format_date($date, 'medium', '', NULL, $language->language);
2115
    $tests['[date:long]'] = format_date($date, 'long', '', NULL, $language->language);
2116
    $tests['[date:custom:m/j/Y]'] = format_date($date, 'custom', 'm/j/Y', NULL, $language->language);
2117
    $tests['[date:since]'] = format_interval((REQUEST_TIME - $date), 2, $language->language);
2118
    $tests['[date:raw]'] = filter_xss($date);
2119

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

    
2123
    foreach ($tests as $input => $expected) {
2124
      $output = token_replace($input, array('date' => $date), array('language' => $language));
2125
      $this->assertEqual($output, $expected, format_string('Date token %token replaced.', array('%token' => $input)));
2126
    }
2127
  }
2128
}
2129

    
2130
class InfoFileParserTestCase extends DrupalUnitTestCase {
2131
  public static function getInfo() {
2132
    return array(
2133
      'name' => 'Info file format parser',
2134
      'description' => 'Tests proper parsing of a .info file formatted string.',
2135
      'group' => 'System',
2136
    );
2137
  }
2138

    
2139
  /**
2140
   * Test drupal_parse_info_format().
2141
   */
2142
  function testDrupalParseInfoFormat() {
2143
    $config = '
2144
simple = Value
2145
quoted = " Value"
2146
multiline = "Value
2147
  Value"
2148
array[] = Value1
2149
array[] = Value2
2150
array_assoc[a] = Value1
2151
array_assoc[b] = Value2
2152
array_deep[][][] = Value
2153
array_deep_assoc[a][b][c] = Value
2154
array_space[a b] = Value';
2155

    
2156
    $expected = array(
2157
      'simple' => 'Value',
2158
      'quoted' => ' Value',
2159
      'multiline' => "Value\n  Value",
2160
      'array' => array(
2161
        0 => 'Value1',
2162
        1 => 'Value2',
2163
      ),
2164
      'array_assoc' => array(
2165
        'a' => 'Value1',
2166
        'b' => 'Value2',
2167
      ),
2168
      'array_deep' => array(
2169
        0 => array(
2170
          0 => array(
2171
            0 => 'Value',
2172
          ),
2173
        ),
2174
      ),
2175
      'array_deep_assoc' => array(
2176
        'a' => array(
2177
          'b' => array(
2178
            'c' => 'Value',
2179
          ),
2180
        ),
2181
      ),
2182
      'array_space' => array(
2183
        'a b' => 'Value',
2184
      ),
2185
    );
2186

    
2187
    $parsed = drupal_parse_info_format($config);
2188

    
2189
    $this->assertEqual($parsed['simple'], $expected['simple'], 'Set a simple value.');
2190
    $this->assertEqual($parsed['quoted'], $expected['quoted'], 'Set a simple value in quotes.');
2191
    $this->assertEqual($parsed['multiline'], $expected['multiline'], 'Set a multiline value.');
2192
    $this->assertEqual($parsed['array'], $expected['array'], 'Set a simple array.');
2193
    $this->assertEqual($parsed['array_assoc'], $expected['array_assoc'], 'Set an associative array.');
2194
    $this->assertEqual($parsed['array_deep'], $expected['array_deep'], 'Set a nested array.');
2195
    $this->assertEqual($parsed['array_deep_assoc'], $expected['array_deep_assoc'], 'Set a nested associative array.');
2196
    $this->assertEqual($parsed['array_space'], $expected['array_space'], 'Set an array with a whitespace in the key.');
2197
    $this->assertEqual($parsed, $expected, 'Entire parsed .info string and expected array are identical.');
2198
  }
2199
}
2200

    
2201
/**
2202
 * Tests the effectiveness of hook_system_info_alter().
2203
 */
2204
class SystemInfoAlterTestCase extends DrupalWebTestCase {
2205
  public static function getInfo() {
2206
    return array(
2207
      'name' => 'System info alter',
2208
      'description' => 'Tests the effectiveness of hook_system_info_alter().',
2209
      'group' => 'System',
2210
    );
2211
  }
2212

    
2213
  /**
2214
   * Tests that {system}.info is rebuilt after a module that implements
2215
   * hook_system_info_alter() is enabled. Also tests if core *_list() functions
2216
   * return freshly altered info.
2217
   */
2218
  function testSystemInfoAlter() {
2219
    // Enable our test module. Flush all caches, which we assert is the only
2220
    // thing necessary to use the rebuilt {system}.info.
2221
    module_enable(array('module_test'), FALSE);
2222
    drupal_flush_all_caches();
2223
    $this->assertTrue(module_exists('module_test'), 'Test module is enabled.');
2224

    
2225
    $info = $this->getSystemInfo('seven', 'theme');
2226
    $this->assertTrue(isset($info['regions']['test_region']), 'Altered theme info was added to {system}.info.');
2227
    $seven_regions = system_region_list('seven');
2228
    $this->assertTrue(isset($seven_regions['test_region']), 'Altered theme info was returned by system_region_list().');
2229
    $system_list_themes = system_list('theme');
2230
    $info = $system_list_themes['seven']->info;
2231
    $this->assertTrue(isset($info['regions']['test_region']), 'Altered theme info was returned by system_list().');
2232
    $list_themes = list_themes();
2233
    $this->assertTrue(isset($list_themes['seven']->info['regions']['test_region']), 'Altered theme info was returned by list_themes().');
2234

    
2235
    // Disable the module and verify that {system}.info is rebuilt without it.
2236
    module_disable(array('module_test'), FALSE);
2237
    drupal_flush_all_caches();
2238
    $this->assertFalse(module_exists('module_test'), 'Test module is disabled.');
2239

    
2240
    $info = $this->getSystemInfo('seven', 'theme');
2241
    $this->assertFalse(isset($info['regions']['test_region']), 'Altered theme info was removed from {system}.info.');
2242
    $seven_regions = system_region_list('seven');
2243
    $this->assertFalse(isset($seven_regions['test_region']), 'Altered theme info was not returned by system_region_list().');
2244
    $system_list_themes = system_list('theme');
2245
    $info = $system_list_themes['seven']->info;
2246
    $this->assertFalse(isset($info['regions']['test_region']), 'Altered theme info was not returned by system_list().');
2247
    $list_themes = list_themes();
2248
    $this->assertFalse(isset($list_themes['seven']->info['regions']['test_region']), 'Altered theme info was not returned by list_themes().');
2249
  }
2250

    
2251
  /**
2252
   * Returns the info array as it is stored in {system}.
2253
   *
2254
   * @param $name
2255
   *   The name of the record in {system}.
2256
   * @param $type
2257
   *   The type of record in {system}.
2258
   *
2259
   * @return
2260
   *   Array of info, or FALSE if the record is not found.
2261
   */
2262
  function getSystemInfo($name, $type) {
2263
    $raw_info = db_query("SELECT info FROM {system} WHERE name = :name AND type = :type", array(':name' => $name, ':type' => $type))->fetchField();
2264
    return $raw_info ? unserialize($raw_info) : FALSE;
2265
  }
2266
}
2267

    
2268
/**
2269
 * Tests for the update system functionality.
2270
 */
2271
class UpdateScriptFunctionalTest extends DrupalWebTestCase {
2272
  private $update_url;
2273
  private $update_user;
2274

    
2275
  public static function getInfo() {
2276
    return array(
2277
      'name' => 'Update functionality',
2278
      'description' => 'Tests the update script access and functionality.',
2279
      'group' => 'System',
2280
    );
2281
  }
2282

    
2283
  function setUp() {
2284
    parent::setUp('update_script_test');
2285
    $this->update_url = $GLOBALS['base_url'] . '/update.php';
2286
    $this->update_user = $this->drupalCreateUser(array('administer software updates'));
2287
  }
2288

    
2289
  /**
2290
   * Tests access to the update script.
2291
   */
2292
  function testUpdateAccess() {
2293
    // Try accessing update.php without the proper permission.
2294
    $regular_user = $this->drupalCreateUser();
2295
    $this->drupalLogin($regular_user);
2296
    $this->drupalGet($this->update_url, array('external' => TRUE));
2297
    $this->assertResponse(403);
2298

    
2299
    // Try accessing update.php as an anonymous user.
2300
    $this->drupalLogout();
2301
    $this->drupalGet($this->update_url, array('external' => TRUE));
2302
    $this->assertResponse(403);
2303

    
2304
    // Access the update page with the proper permission.
2305
    $this->drupalLogin($this->update_user);
2306
    $this->drupalGet($this->update_url, array('external' => TRUE));
2307
    $this->assertResponse(200);
2308

    
2309
    // Access the update page as user 1.
2310
    $user1 = user_load(1);
2311
    $user1->pass_raw = user_password();
2312
    require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
2313
    $user1->pass = user_hash_password(trim($user1->pass_raw));
2314
    db_query("UPDATE {users} SET pass = :pass WHERE uid = :uid", array(':pass' => $user1->pass, ':uid' => $user1->uid));
2315
    $this->drupalLogin($user1);
2316
    $this->drupalGet($this->update_url, array('external' => TRUE));
2317
    $this->assertResponse(200);
2318
  }
2319

    
2320
  /**
2321
   * Tests that requirements warnings and errors are correctly displayed.
2322
   */
2323
  function testRequirements() {
2324
    $this->drupalLogin($this->update_user);
2325

    
2326
    // If there are no requirements warnings or errors, we expect to be able to
2327
    // go through the update process uninterrupted.
2328
    $this->drupalGet($this->update_url, array('external' => TRUE));
2329
    $this->drupalPost(NULL, array(), t('Continue'));
2330
    $this->assertText(t('No pending updates.'), 'End of update process was reached.');
2331
    // Confirm that all caches were cleared.
2332
    $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared when there were no requirements warnings or errors.');
2333

    
2334
    // If there is a requirements warning, we expect it to be initially
2335
    // displayed, but clicking the link to proceed should allow us to go
2336
    // through the rest of the update process uninterrupted.
2337

    
2338
    // First, run this test with pending updates to make sure they can be run
2339
    // successfully.
2340
    variable_set('update_script_test_requirement_type', REQUIREMENT_WARNING);
2341
    drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
2342
    $this->drupalGet($this->update_url, array('external' => TRUE));
2343
    $this->assertText('This is a requirements warning provided by the update_script_test module.');
2344
    $this->clickLink('try again');
2345
    $this->assertNoText('This is a requirements warning provided by the update_script_test module.');
2346
    $this->drupalPost(NULL, array(), t('Continue'));
2347
    $this->drupalPost(NULL, array(), t('Apply pending updates'));
2348
    $this->assertText(t('The update_script_test_update_7000() update was executed successfully.'), 'End of update process was reached.');
2349
    // Confirm that all caches were cleared.
2350
    $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared after resolving a requirements warning and applying updates.');
2351

    
2352
    // Now try again without pending updates to make sure that works too.
2353
    $this->drupalGet($this->update_url, array('external' => TRUE));
2354
    $this->assertText('This is a requirements warning provided by the update_script_test module.');
2355
    $this->clickLink('try again');
2356
    $this->assertNoText('This is a requirements warning provided by the update_script_test module.');
2357
    $this->drupalPost(NULL, array(), t('Continue'));
2358
    $this->assertText(t('No pending updates.'), 'End of update process was reached.');
2359
    // Confirm that all caches were cleared.
2360
    $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared after applying updates and re-running the script.');
2361

    
2362
    // If there is a requirements error, it should be displayed even after
2363
    // clicking the link to proceed (since the problem that triggered the error
2364
    // has not been fixed).
2365
    variable_set('update_script_test_requirement_type', REQUIREMENT_ERROR);
2366
    $this->drupalGet($this->update_url, array('external' => TRUE));
2367
    $this->assertText('This is a requirements error provided by the update_script_test module.');
2368
    $this->clickLink('try again');
2369
    $this->assertText('This is a requirements error provided by the update_script_test module.');
2370
  }
2371

    
2372
  /**
2373
   * Tests the effect of using the update script on the theme system.
2374
   */
2375
  function testThemeSystem() {
2376
    // Since visiting update.php triggers a rebuild of the theme system from an
2377
    // unusual maintenance mode environment, we check that this rebuild did not
2378
    // put any incorrect information about the themes into the database.
2379
    $original_theme_data = db_query("SELECT * FROM {system} WHERE type = 'theme' ORDER BY name")->fetchAll();
2380
    $this->drupalLogin($this->update_user);
2381
    $this->drupalGet($this->update_url, array('external' => TRUE));
2382
    $final_theme_data = db_query("SELECT * FROM {system} WHERE type = 'theme' ORDER BY name")->fetchAll();
2383
    $this->assertEqual($original_theme_data, $final_theme_data, 'Visiting update.php does not alter the information about themes stored in the database.');
2384
  }
2385

    
2386
  /**
2387
   * Tests update.php when there are no updates to apply.
2388
   */
2389
  function testNoUpdateFunctionality() {
2390
    // Click through update.php with 'administer software updates' permission.
2391
    $this->drupalLogin($this->update_user);
2392
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
2393
    $this->assertText(t('No pending updates.'));
2394
    $this->assertNoLink('Administration pages');
2395
    $this->clickLink('Front page');
2396
    $this->assertResponse(200);
2397

    
2398
    // Click through update.php with 'access administration pages' permission.
2399
    $admin_user = $this->drupalCreateUser(array('administer software updates', 'access administration pages'));
2400
    $this->drupalLogin($admin_user);
2401
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
2402
    $this->assertText(t('No pending updates.'));
2403
    $this->clickLink('Administration pages');
2404
    $this->assertResponse(200);
2405
  }
2406

    
2407
  /**
2408
   * Tests update.php after performing a successful update.
2409
   */
2410
  function testSuccessfulUpdateFunctionality() {
2411
    drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
2412
    // Click through update.php with 'administer software updates' permission.
2413
    $this->drupalLogin($this->update_user);
2414
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
2415
    $this->drupalPost(NULL, array(), t('Apply pending updates'));
2416
    $this->assertText('Updates were attempted.');
2417
    $this->assertLink('site');
2418
    $this->assertNoLink('Administration pages');
2419
    $this->assertNoLink('logged');
2420
    $this->clickLink('Front page');
2421
    $this->assertResponse(200);
2422

    
2423
    drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
2424
    // Click through update.php with 'access administration pages' and
2425
    // 'access site reports' permissions.
2426
    $admin_user = $this->drupalCreateUser(array('administer software updates', 'access administration pages', 'access site reports'));
2427
    $this->drupalLogin($admin_user);
2428
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
2429
    $this->drupalPost(NULL, array(), t('Apply pending updates'));
2430
    $this->assertText('Updates were attempted.');
2431
    $this->assertLink('logged');
2432
    $this->clickLink('Administration pages');
2433
    $this->assertResponse(200);
2434
  }
2435
}
2436

    
2437
/**
2438
 * Functional tests for the flood control mechanism.
2439
 */
2440
class FloodFunctionalTest extends DrupalWebTestCase {
2441
  public static function getInfo() {
2442
    return array(
2443
      'name' => 'Flood control mechanism',
2444
      'description' => 'Functional tests for the flood control mechanism.',
2445
      'group' => 'System',
2446
    );
2447
  }
2448

    
2449
  /**
2450
   * Test flood control mechanism clean-up.
2451
   */
2452
  function testCleanUp() {
2453
    $threshold = 1;
2454
    $window_expired = -1;
2455
    $name = 'flood_test_cleanup';
2456

    
2457
    // Register expired event.
2458
    flood_register_event($name, $window_expired);
2459
    // Verify event is not allowed.
2460
    $this->assertFalse(flood_is_allowed($name, $threshold));
2461
    // Run cron and verify event is now allowed.
2462
    $this->cronRun();
2463
    $this->assertTrue(flood_is_allowed($name, $threshold));
2464

    
2465
    // Register unexpired event.
2466
    flood_register_event($name);
2467
    // Verify event is not allowed.
2468
    $this->assertFalse(flood_is_allowed($name, $threshold));
2469
    // Run cron and verify event is still not allowed.
2470
    $this->cronRun();
2471
    $this->assertFalse(flood_is_allowed($name, $threshold));
2472
  }
2473
}
2474

    
2475
/**
2476
 * Test HTTP file downloading capability.
2477
 */
2478
class RetrieveFileTestCase extends DrupalWebTestCase {
2479
  public static function getInfo() {
2480
    return array(
2481
      'name' => 'HTTP file retrieval',
2482
      'description' => 'Checks HTTP file fetching and error handling.',
2483
      'group' => 'System',
2484
    );
2485
  }
2486

    
2487
  /**
2488
   * Invokes system_retrieve_file() in several scenarios.
2489
   */
2490
  function testFileRetrieving() {
2491
    // Test 404 handling by trying to fetch a randomly named file.
2492
    drupal_mkdir($sourcedir = 'public://' . $this->randomName());
2493
    $filename = 'Файл для тестирования ' . $this->randomName();
2494
    $url = file_create_url($sourcedir . '/' . $filename);
2495
    $retrieved_file = system_retrieve_file($url);
2496
    $this->assertFalse($retrieved_file, 'Non-existent file not fetched.');
2497

    
2498
    // Actually create that file, download it via HTTP and test the returned path.
2499
    file_put_contents($sourcedir . '/' . $filename, 'testing');
2500
    $retrieved_file = system_retrieve_file($url);
2501

    
2502
    // URLs could not contains characters outside the ASCII set so $filename
2503
    // has to be encoded.
2504
    $encoded_filename = rawurlencode($filename);
2505

    
2506
    $this->assertEqual($retrieved_file, 'public://' . $encoded_filename, 'Sane path for downloaded file returned (public:// scheme).');
2507
    $this->assertTrue(is_file($retrieved_file), 'Downloaded file does exist (public:// scheme).');
2508
    $this->assertEqual(filesize($retrieved_file), 7, 'File size of downloaded file is correct (public:// scheme).');
2509
    file_unmanaged_delete($retrieved_file);
2510

    
2511
    // Test downloading file to a different location.
2512
    drupal_mkdir($targetdir = 'temporary://' . $this->randomName());
2513
    $retrieved_file = system_retrieve_file($url, $targetdir);
2514
    $this->assertEqual($retrieved_file, "$targetdir/$encoded_filename", 'Sane path for downloaded file returned (temporary:// scheme).');
2515
    $this->assertTrue(is_file($retrieved_file), 'Downloaded file does exist (temporary:// scheme).');
2516
    $this->assertEqual(filesize($retrieved_file), 7, 'File size of downloaded file is correct (temporary:// scheme).');
2517
    file_unmanaged_delete($retrieved_file);
2518

    
2519
    file_unmanaged_delete_recursive($sourcedir);
2520
    file_unmanaged_delete_recursive($targetdir);
2521
  }
2522
}
2523

    
2524
/**
2525
 * Functional tests shutdown functions.
2526
 */
2527
class ShutdownFunctionsTest extends DrupalWebTestCase {
2528
  public static function getInfo() {
2529
    return array(
2530
      'name' => 'Shutdown functions',
2531
      'description' => 'Functional tests for shutdown functions',
2532
      'group' => 'System',
2533
    );
2534
  }
2535

    
2536
  function setUp() {
2537
    parent::setUp('system_test');
2538
  }
2539

    
2540
  /**
2541
   * Test shutdown functions.
2542
   */
2543
  function testShutdownFunctions() {
2544
    $arg1 = $this->randomName();
2545
    $arg2 = $this->randomName();
2546
    $this->drupalGet('system-test/shutdown-functions/' . $arg1 . '/' . $arg2);
2547
    $this->assertText(t('First shutdown function, arg1 : @arg1, arg2: @arg2', array('@arg1' => $arg1, '@arg2' => $arg2)));
2548
    $this->assertText(t('Second shutdown function, arg1 : @arg1, arg2: @arg2', array('@arg1' => $arg1, '@arg2' => $arg2)));
2549

    
2550
    // Make sure exceptions displayed through _drupal_render_exception_safe()
2551
    // are correctly escaped.
2552
    $this->assertRaw('Drupal is &amp;lt;blink&amp;gt;awesome&amp;lt;/blink&amp;gt;.');
2553
  }
2554
}
2555

    
2556
/**
2557
 * Tests administrative overview pages.
2558
 */
2559
class SystemAdminTestCase extends DrupalWebTestCase {
2560
  public static function getInfo() {
2561
    return array(
2562
      'name' => 'Administrative pages',
2563
      'description' => 'Tests output on administrative pages and compact mode functionality.',
2564
      'group' => 'System',
2565
    );
2566
  }
2567

    
2568
  function setUp() {
2569
    // testAdminPages() requires Locale module.
2570
    parent::setUp(array('locale'));
2571

    
2572
    // Create an administrator with all permissions, as well as a regular user
2573
    // who can only access administration pages and perform some Locale module
2574
    // administrative tasks, but not all of them.
2575
    $this->admin_user = $this->drupalCreateUser(array_keys(module_invoke_all('permission')));
2576
    $this->web_user = $this->drupalCreateUser(array(
2577
      'access administration pages',
2578
      'translate interface',
2579
    ));
2580
    $this->drupalLogin($this->admin_user);
2581
  }
2582

    
2583
  /**
2584
   * Tests output on administrative listing pages.
2585
   */
2586
  function testAdminPages() {
2587
    // Go to Administration.
2588
    $this->drupalGet('admin');
2589

    
2590
    // Verify that all visible, top-level administration links are listed on
2591
    // the main administration page.
2592
    foreach (menu_get_router() as $path => $item) {
2593
      if (strpos($path, 'admin/') === 0 && ($item['type'] & MENU_VISIBLE_IN_TREE) && $item['_number_parts'] == 2) {
2594
        $this->assertLink($item['title']);
2595
        $this->assertLinkByHref($path);
2596
        $this->assertText($item['description']);
2597
      }
2598
    }
2599

    
2600
    // For each administrative listing page on which the Locale module appears,
2601
    // verify that there are links to the module's primary configuration pages,
2602
    // but no links to its individual sub-configuration pages. Also verify that
2603
    // a user with access to only some Locale module administration pages only
2604
    // sees links to the pages they have access to.
2605
    $admin_list_pages = array(
2606
      'admin/index',
2607
      'admin/config',
2608
      'admin/config/regional',
2609
    );
2610

    
2611
    foreach ($admin_list_pages as $page) {
2612
      // For the administrator, verify that there are links to Locale's primary
2613
      // configuration pages, but no links to individual sub-configuration
2614
      // pages.
2615
      $this->drupalLogin($this->admin_user);
2616
      $this->drupalGet($page);
2617
      $this->assertLinkByHref('admin/config');
2618
      $this->assertLinkByHref('admin/config/regional/settings');
2619
      $this->assertLinkByHref('admin/config/regional/date-time');
2620
      $this->assertLinkByHref('admin/config/regional/language');
2621
      $this->assertNoLinkByHref('admin/config/regional/language/configure/session');
2622
      $this->assertNoLinkByHref('admin/config/regional/language/configure/url');
2623
      $this->assertLinkByHref('admin/config/regional/translate');
2624
      // On admin/index only, the administrator should also see a "Configure
2625
      // permissions" link for the Locale module.
2626
      if ($page == 'admin/index') {
2627
        $this->assertLinkByHref("admin/people/permissions#module-locale");
2628
      }
2629

    
2630
      // For a less privileged user, verify that there are no links to Locale's
2631
      // primary configuration pages, but a link to the translate page exists.
2632
      $this->drupalLogin($this->web_user);
2633
      $this->drupalGet($page);
2634
      $this->assertLinkByHref('admin/config');
2635
      $this->assertNoLinkByHref('admin/config/regional/settings');
2636
      $this->assertNoLinkByHref('admin/config/regional/date-time');
2637
      $this->assertNoLinkByHref('admin/config/regional/language');
2638
      $this->assertNoLinkByHref('admin/config/regional/language/configure/session');
2639
      $this->assertNoLinkByHref('admin/config/regional/language/configure/url');
2640
      $this->assertLinkByHref('admin/config/regional/translate');
2641
      // This user cannot configure permissions, so even on admin/index should
2642
      // not see a "Configure permissions" link for the Locale module.
2643
      if ($page == 'admin/index') {
2644
        $this->assertNoLinkByHref("admin/people/permissions#module-locale");
2645
      }
2646
    }
2647
  }
2648

    
2649
  /**
2650
   * Test compact mode.
2651
   */
2652
  function testCompactMode() {
2653
    $this->drupalGet('admin/compact/on');
2654
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode turns on.');
2655
    $this->drupalGet('admin/compact/on');
2656
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode remains on after a repeat call.');
2657
    $this->drupalGet('');
2658
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode persists on new requests.');
2659

    
2660
    $this->drupalGet('admin/compact/off');
2661
    $this->assertEqual($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'deleted', 'Compact mode turns off.');
2662
    $this->drupalGet('admin/compact/off');
2663
    $this->assertEqual($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'deleted', 'Compact mode remains off after a repeat call.');
2664
    $this->drupalGet('');
2665
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode persists on new requests.');
2666
  }
2667
}
2668

    
2669
/**
2670
 * Tests authorize.php and related hooks.
2671
 */
2672
class SystemAuthorizeCase extends DrupalWebTestCase {
2673
  public static function getInfo() {
2674
    return array(
2675
      'name' => 'Authorize API',
2676
      'description' => 'Tests the authorize.php script and related API.',
2677
      'group' => 'System',
2678
    );
2679
  }
2680

    
2681
  function setUp() {
2682
    parent::setUp(array('system_test'));
2683

    
2684
    variable_set('allow_authorize_operations', TRUE);
2685

    
2686
    // Create an administrator user.
2687
    $this->admin_user = $this->drupalCreateUser(array('administer software updates'));
2688
    $this->drupalLogin($this->admin_user);
2689
  }
2690

    
2691
  /**
2692
   * Helper function to initialize authorize.php and load it via drupalGet().
2693
   *
2694
   * Initializing authorize.php needs to happen in the child Drupal
2695
   * installation, not the parent. So, we visit a menu callback provided by
2696
   * system_test.module which calls system_authorized_init() to initialize the
2697
   * $_SESSION inside the test site, not the framework site. This callback
2698
   * redirects to authorize.php when it's done initializing.
2699
   *
2700
   * @see system_authorized_init().
2701
   */
2702
  function drupalGetAuthorizePHP($page_title = 'system-test-auth') {
2703
    $this->drupalGet('system-test/authorize-init/' . $page_title);
2704
  }
2705

    
2706
  /**
2707
   * Tests the FileTransfer hooks
2708
   */
2709
  function testFileTransferHooks() {
2710
    $page_title = $this->randomName(16);
2711
    $this->drupalGetAuthorizePHP($page_title);
2712
    $this->assertTitle(strtr('@title | Drupal', array('@title' => $page_title)), 'authorize.php page title is correct.');
2713
    $this->assertNoText('It appears you have reached this page in error.');
2714
    $this->assertText('To continue, provide your server connection details');
2715
    // Make sure we see the new connection method added by system_test.
2716
    $this->assertRaw('System Test FileTransfer');
2717
    // Make sure the settings form callback works.
2718
    $this->assertText('System Test Username');
2719
  }
2720
}
2721

    
2722
/**
2723
 * Test the handling of requests containing 'index.php'.
2724
 */
2725
class SystemIndexPhpTest extends DrupalWebTestCase {
2726
  public static function getInfo() {
2727
    return array(
2728
      'name' => 'Index.php handling',
2729
      'description' => "Test the handling of requests containing 'index.php'.",
2730
      'group' => 'System',
2731
    );
2732
  }
2733

    
2734
  function setUp() {
2735
    parent::setUp();
2736
  }
2737

    
2738
  /**
2739
   * Test index.php handling.
2740
   */
2741
  function testIndexPhpHandling() {
2742
    $index_php = $GLOBALS['base_url'] . '/index.php';
2743

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

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

    
2750
    $this->drupalGet($index_php .'/user', array('external' => TRUE));
2751
    $this->assertResponse(404, "Make sure index.php/user returns a 'page not found'.");
2752
  }
2753
}
2754

    
2755
/**
2756
 * Test token replacement in strings.
2757
 */
2758
class TokenScanTest extends DrupalWebTestCase {
2759

    
2760
  public static function getInfo() {
2761
    return array(
2762
      'name' => 'Token scanning',
2763
      'description' => 'Scan token-like patterns in a dummy text to check token scanning.',
2764
      'group' => 'System',
2765
    );
2766
  }
2767

    
2768
  /**
2769
   * Scans dummy text, then tests the output.
2770
   */
2771
  function testTokenScan() {
2772
    // Define text with valid and not valid, fake and existing token-like
2773
    // strings.
2774
    $text = 'First a [valid:simple], but dummy token, and a dummy [valid:token with: spaces].';
2775
    $text .= 'Then a [not valid:token].';
2776
    $text .= 'Last an existing token: [node:author:name].';
2777
    $token_wannabes = token_scan($text);
2778

    
2779
    $this->assertTrue(isset($token_wannabes['valid']['simple']), 'A simple valid token has been matched.');
2780
    $this->assertTrue(isset($token_wannabes['valid']['token with: spaces']), 'A valid token with space characters in the token name has been matched.');
2781
    $this->assertFalse(isset($token_wannabes['not valid']), 'An invalid token with spaces in the token type has not been matched.');
2782
    $this->assertTrue(isset($token_wannabes['node']), 'An existing valid token has been matched.');
2783
  }
2784
}
2785

    
2786
/**
2787
 * Test case for drupal_valid_token().
2788
 */
2789
class SystemValidTokenTest extends DrupalUnitTestCase {
2790

    
2791
  /**
2792
   * Flag to indicate whether PHP error reportings should be asserted.
2793
   *
2794
   * @var bool
2795
   */
2796
  protected $assertErrors = TRUE;
2797

    
2798
  public static function getInfo() {
2799
    return array(
2800
      'name' => 'Token validation',
2801
      'description' => 'Test the security token validation.',
2802
      'group' => 'System',
2803
    );
2804
  }
2805

    
2806
  /**
2807
   * Tests invalid invocations of drupal_valid_token() that must return FALSE.
2808
   */
2809
  public function testTokenValidation() {
2810
    // The following checks will throw PHP notices, so we disable error
2811
    // assertions.
2812
    $this->assertErrors = FALSE;
2813
    $this->assertFalse(drupal_valid_token(NULL, new stdClass()), 'Token NULL, value object returns FALSE.');
2814
    $this->assertFalse(drupal_valid_token(0, array()), 'Token 0, value array returns FALSE.');
2815
    $this->assertFalse(drupal_valid_token('', array()), "Token '', value array returns FALSE.");
2816
    $this->assertFalse('' === drupal_get_token(array()), 'Token generation does not return an empty string on invalid parameters.');
2817
    $this->assertErrors = TRUE;
2818

    
2819
    $this->assertFalse(drupal_valid_token(TRUE, 'foo'), 'Token TRUE, value foo returns FALSE.');
2820
    $this->assertFalse(drupal_valid_token(0, 'foo'), 'Token 0, value foo returns FALSE.');
2821
  }
2822

    
2823
  /**
2824
   * Overrides DrupalTestCase::errorHandler().
2825
   */
2826
  public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
2827
    if ($this->assertErrors) {
2828
      return parent::errorHandler($severity, $message, $file, $line);
2829
    }
2830
    return TRUE;
2831
  }
2832
}
2833

    
2834
/**
2835
 * Tests drupal_set_message() and related functions.
2836
 */
2837
class DrupalSetMessageTest extends DrupalWebTestCase {
2838

    
2839
  public static function getInfo() {
2840
    return array(
2841
      'name' => 'Messages',
2842
      'description' => 'Tests that messages can be displayed using drupal_set_message().',
2843
      'group' => 'System',
2844
    );
2845
  }
2846

    
2847
  function setUp() {
2848
    parent::setUp('system_test');
2849
  }
2850

    
2851
  /**
2852
   * Tests setting messages and removing one before it is displayed.
2853
   */
2854
  function testSetRemoveMessages() {
2855
    // The page at system-test/drupal-set-message sets two messages and then
2856
    // removes the first before it is displayed.
2857
    $this->drupalGet('system-test/drupal-set-message');
2858
    $this->assertNoText('First message (removed).');
2859
    $this->assertText('Second message (not removed).');
2860
  }
2861
}
2862

    
2863
/**
2864
 * Tests confirm form destinations.
2865
 */
2866
class ConfirmFormTest extends DrupalWebTestCase {
2867
  protected $admin_user;
2868

    
2869
  public static function getInfo() {
2870
    return array(
2871
      'name' => 'Confirm form',
2872
      'description' => 'Tests that the confirm form does not use external destinations.',
2873
      'group' => 'System',
2874
    );
2875
  }
2876

    
2877
  function setUp() {
2878
    parent::setUp();
2879

    
2880
    $this->admin_user = $this->drupalCreateUser(array('administer users'));
2881
    $this->drupalLogin($this->admin_user);
2882
  }
2883

    
2884
  /**
2885
   * Tests that the confirm form does not use external destinations.
2886
   */
2887
  function testConfirmForm() {
2888
    $this->drupalGet('user/1/cancel');
2889
    $this->assertCancelLinkUrl(url('user/1'));
2890
    $this->drupalGet('user/1/cancel', array('query' => array('destination' => 'node')));
2891
    $this->assertCancelLinkUrl(url('node'));
2892
    $this->drupalGet('user/1/cancel', array('query' => array('destination' => 'http://example.com')));
2893
    $this->assertCancelLinkUrl(url('user/1'));
2894
  }
2895

    
2896
  /**
2897
   * Asserts that a cancel link is present pointing to the provided URL.
2898
   */
2899
  function assertCancelLinkUrl($url, $message = '', $group = 'Other') {
2900
    $links = $this->xpath('//a[normalize-space(text())=:label and @href=:url]', array(':label' => t('Cancel'), ':url' => $url));
2901
    $message = ($message ? $message : format_string('Cancel link with url %url found.', array('%url' => $url)));
2902
    return $this->assertTrue(isset($links[0]), $message, $group);
2903
  }
2904
}