Project

General

Profile

Paste
Download (117 KB) Statistics
| Branch: | Revision:

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

1
<?php
2

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

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

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

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

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

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

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

    
56
  /**
57
   * Assert that none of the tables defined in a module's hook_schema() exist.
58
   *
59
   * @param $module
60
   *   The name of the module.
61
   */
62
  function assertModuleTablesDoNotExist($module) {
63
    $tables = array_keys(drupal_get_schema_unprocessed($module));
64
    $tables_exist = FALSE;
65
    foreach ($tables as $table) {
66
      if (db_table_exists($table)) {
67
        $tables_exist = TRUE;
68
      }
69
    }
70
    return $this->assertFalse($tables_exist, format_string('None of the database tables defined by the @module module exist.', array('@module' => $module)));
71
  }
72

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

    
94
  /**
95
   * Verify a log entry was entered for a module's status change.
96
   * Called in the same way of the expected original watchdog() execution.
97
   *
98
   * @param $type
99
   *   The category to which this message belongs.
100
   * @param $message
101
   *   The message to store in the log. Keep $message translatable
102
   *   by not concatenating dynamic values into it! Variables in the
103
   *   message should be added by using placeholder strings alongside
104
   *   the variables argument to declare the value of the placeholders.
105
   *   See t() for documentation on how $message and $variables interact.
106
   * @param $variables
107
   *   Array of variables to replace in the message on display or
108
   *   NULL if message is already translated or not possible to
109
   *   translate.
110
   * @param $severity
111
   *   The severity of the message, as per RFC 3164.
112
   * @param $link
113
   *   A link to associate with the message.
114
   */
115
  function assertLogMessage($type, $message, $variables = array(), $severity = WATCHDOG_NOTICE, $link = '') {
116
    $count = db_select('watchdog', 'w')
117
      ->condition('type', $type)
118
      ->condition('message', $message)
119
      ->condition('variables', serialize($variables))
120
      ->condition('severity', $severity)
121
      ->condition('link', $link)
122
      ->countQuery()
123
      ->execute()
124
      ->fetchField();
125
    $this->assertTrue($count > 0, format_string('watchdog table contains @count rows for @message', array('@count' => $count, '@message' => $message)));
126
  }
127
}
128

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

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

    
143
  /**
144
   * Test that all core modules can be enabled, disabled and uninstalled.
145
   */
146
  function testEnableDisable() {
147
    // Try to enable, disable and uninstall all core modules, unless they are
148
    // hidden or required.
149
    $modules = system_rebuild_module_data();
150
    foreach ($modules as $name => $module) {
151
      if ($module->info['package'] != 'Core' || !empty($module->info['hidden']) || !empty($module->info['required'])) {
152
        unset($modules[$name]);
153
      }
154
    }
155
    $this->assertTrue(count($modules), format_string('Found @count core modules that we can try to enable in this test.', array('@count' => count($modules))));
156

    
157
    // Enable the dblog module first, since we will be asserting the presence
158
    // of log messages throughout the test.
159
   if (isset($modules['dblog'])) {
160
     $modules = array('dblog' => $modules['dblog']) + $modules;
161
   }
162

    
163
   // Set a variable so that the hook implementations in system_test.module
164
   // will display messages via drupal_set_message().
165
   variable_set('test_verbose_module_hooks', TRUE);
166

    
167
    // Throughout this test, some modules may be automatically enabled (due to
168
    // dependencies). We'll keep track of them in an array, so we can handle
169
    // them separately.
170
    $automatically_enabled = array();
171

    
172
    // Go through each module in the list and try to enable it (unless it was
173
    // already enabled automatically due to a dependency).
174
    foreach ($modules as $name => $module) {
175
      if (empty($automatically_enabled[$name])) {
176
        // Start a list of modules that we expect to be enabled this time.
177
        $modules_to_enable = array($name);
178

    
179
        // Find out if the module has any dependencies that aren't enabled yet;
180
        // if so, add them to the list of modules we expect to be automatically
181
        // enabled.
182
        foreach (array_keys($module->requires) as $dependency) {
183
          if (isset($modules[$dependency]) && empty($automatically_enabled[$dependency])) {
184
            $modules_to_enable[] = $dependency;
185
            $automatically_enabled[$dependency] = TRUE;
186
          }
187
        }
188

    
189
        // Check that each module is not yet enabled and does not have any
190
        // database tables yet.
191
        foreach ($modules_to_enable as $module_to_enable) {
192
          $this->assertModules(array($module_to_enable), FALSE);
193
          $this->assertModuleTablesDoNotExist($module_to_enable);
194
        }
195

    
196
        // Install and enable the module.
197
        $edit = array();
198
        $edit['modules[Core][' . $name . '][enable]'] = $name;
199
        $this->drupalPost('admin/modules', $edit, t('Save configuration'));
200
        // Handle the case where modules were installed along with this one and
201
        // where we therefore hit a confirmation screen.
202
        if (count($modules_to_enable) > 1) {
203
          $this->drupalPost(NULL, array(), t('Continue'));
204
        }
205
        $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
206

    
207
        // Check that hook_modules_installed() and hook_modules_enabled() were
208
        // invoked with the expected list of modules, that each module's
209
        // database tables now exist, and that appropriate messages appear in
210
        // the logs.
211
        foreach ($modules_to_enable as $module_to_enable) {
212
          $this->assertText(t('hook_modules_installed fired for @module', array('@module' => $module_to_enable)));
213
          $this->assertText(t('hook_modules_enabled fired for @module', array('@module' => $module_to_enable)));
214
          $this->assertModules(array($module_to_enable), TRUE);
215
          $this->assertModuleTablesExist($module_to_enable);
216
          $this->assertLogMessage('system', "%module module installed.", array('%module' => $module_to_enable), WATCHDOG_INFO);
217
          $this->assertLogMessage('system', "%module module enabled.", array('%module' => $module_to_enable), WATCHDOG_INFO);
218
        }
219

    
220
        // Disable and uninstall the original module, and check appropriate
221
        // hooks, tables, and log messages. (Later, we'll go back and do the
222
        // same thing for modules that were enabled automatically.) Skip this
223
        // for the dblog module, because that is needed for the test; we'll go
224
        // back and do that one at the end also.
225
        if ($name != 'dblog') {
226
          $this->assertSuccessfulDisableAndUninstall($name);
227
        }
228
      }
229
    }
230

    
231
    // Go through all modules that were automatically enabled, and try to
232
    // disable and uninstall them one by one.
233
    while (!empty($automatically_enabled)) {
234
      $initial_count = count($automatically_enabled);
235
      foreach (array_keys($automatically_enabled) as $name) {
236
        // If the module can't be disabled due to dependencies, skip it and try
237
        // again the next time. Otherwise, try to disable it.
238
        $this->drupalGet('admin/modules');
239
        $disabled_checkbox = $this->xpath('//input[@type="checkbox" and @disabled="disabled" and @name="modules[Core][' . $name . '][enable]"]');
240
        if (empty($disabled_checkbox) && $name != 'dblog') {
241
          unset($automatically_enabled[$name]);
242
          $this->assertSuccessfulDisableAndUninstall($name);
243
        }
244
      }
245
      $final_count = count($automatically_enabled);
246
      // If all checkboxes were disabled, something is really wrong with the
247
      // test. Throw a failure and avoid an infinite loop.
248
      if ($initial_count == $final_count) {
249
        $this->fail(t('Remaining modules could not be disabled.'));
250
        break;
251
      }
252
    }
253

    
254
    // Disable and uninstall the dblog module last, since we needed it for
255
    // assertions in all the above tests.
256
    if (isset($modules['dblog'])) {
257
      $this->assertSuccessfulDisableAndUninstall('dblog');
258
    }
259

    
260
    // Now that all modules have been tested, go back and try to enable them
261
    // all again at once. This tests two things:
262
    // - That each module can be successfully enabled again after being
263
    //   uninstalled.
264
    // - That enabling more than one module at the same time does not lead to
265
    //   any errors.
266
    $edit = array();
267
    foreach (array_keys($modules) as $name) {
268
      $edit['modules[Core][' . $name . '][enable]'] = $name;
269
    }
270
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
271
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
272
  }
273

    
274
  /**
275
   * Ensures entity info cache is updated after changes.
276
   */
277
  function testEntityInfoChanges() {
278
    module_enable(array('entity_cache_test'));
279
    $entity_info = entity_get_info();
280
    $this->assertTrue(isset($entity_info['entity_cache_test']), 'Test entity type found.');
281

    
282
    // Change the label of the test entity type and make sure changes appear
283
    // after flushing caches.
284
    variable_set('entity_cache_test_label', 'New label.');
285
    drupal_flush_all_caches();
286
    $info = entity_get_info('entity_cache_test');
287
    $this->assertEqual($info['label'], 'New label.', 'New label appears in entity info.');
288

    
289
    // Disable the providing module and make sure the entity type is gone.
290
    module_disable(array('entity_cache_test', 'entity_cache_test_dependency'));
291
    $entity_info = entity_get_info();
292
    $this->assertFalse(isset($entity_info['entity_cache_test']), 'Entity type of the providing module is gone.');
293
  }
294

    
295
  /**
296
   * Tests entity info cache after enabling a module with a dependency on an entity providing module.
297
   *
298
   * @see entity_cache_test_watchdog()
299
   */
300
  function testEntityInfoCacheWatchdog() {
301
    module_enable(array('entity_cache_test'));
302
    $info = variable_get('entity_cache_test');
303
    $this->assertEqual($info['label'], 'Entity Cache Test', 'Entity info label is correct.');
304
    $this->assertEqual($info['controller class'], 'DrupalDefaultEntityController', 'Entity controller class info is correct.');
305
  }
306

    
307
  /**
308
   * Disables and uninstalls a module and asserts that it was done correctly.
309
   *
310
   * @param $module
311
   *   The name of the module to disable and uninstall.
312
   */
313
  function assertSuccessfulDisableAndUninstall($module) {
314
    // Disable the module.
315
    $edit = array();
316
    $edit['modules[Core][' . $module . '][enable]'] = FALSE;
317
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
318
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
319
    $this->assertModules(array($module), FALSE);
320

    
321
    // Check that the appropriate hook was fired and the appropriate log
322
    // message appears.
323
    $this->assertText(t('hook_modules_disabled fired for @module', array('@module' => $module)));
324
    $this->assertLogMessage('system', "%module module disabled.", array('%module' => $module), WATCHDOG_INFO);
325

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

    
329
    // Uninstall the module.
330
    $edit = array();
331
    $edit['uninstall[' . $module . ']'] = $module;
332
    $this->drupalPost('admin/modules/uninstall', $edit, t('Uninstall'));
333
    $this->drupalPost(NULL, NULL, t('Uninstall'));
334
    $this->assertText(t('The selected modules have been uninstalled.'), 'Modules status has been updated.');
335
    $this->assertModules(array($module), FALSE);
336

    
337
    // Check that the appropriate hook was fired and the appropriate log
338
    // message appears. (But don't check for the log message if the dblog
339
    // module was just uninstalled, since the {watchdog} table won't be there
340
    // anymore.)
341
    $this->assertText(t('hook_modules_uninstalled fired for @module', array('@module' => $module)));
342
    if ($module != 'dblog') {
343
      $this->assertLogMessage('system', "%module module uninstalled.", array('%module' => $module), WATCHDOG_INFO);
344
    }
345

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
507
  }
508

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
774
  /**
775
   * Test duplicate IP addresses are not present in the 'blocked_ips' table.
776
   */
777
  function testDuplicateIpAddress() {
778
    drupal_static_reset('ip_address');
779
    $submit_ip = $_SERVER['REMOTE_ADDR'] = '192.168.1.1';
780
    system_block_ip_action();
781
    system_block_ip_action();
782
    $ip_count = db_query("SELECT iid from {blocked_ips} WHERE ip = :ip", array(':ip' => $submit_ip))->rowCount();
783
    $this->assertEqual('1', $ip_count);
784
    drupal_static_reset('ip_address');
785
    $submit_ip = $_SERVER['REMOTE_ADDR'] = ' ';
786
    system_block_ip_action();
787
    system_block_ip_action();
788
    system_block_ip_action();
789
    $ip_count = db_query("SELECT iid from {blocked_ips} WHERE ip = :ip", array(':ip' => $submit_ip))->rowCount();
790
    $this->assertEqual('1', $ip_count);
791
  }
792
}
793

    
794
class CronRunTestCase extends DrupalWebTestCase {
795
  /**
796
   * Implement getInfo().
797
   */
798
  public static function getInfo() {
799
    return array(
800
      'name' => 'Cron run',
801
      'description' => 'Test cron run.',
802
      'group' => 'System'
803
    );
804
  }
805

    
806
  function setUp() {
807
    parent::setUp(array('common_test', 'common_test_cron_helper'));
808
  }
809

    
810
  /**
811
   * Test cron runs.
812
   */
813
  function testCronRun() {
814
    global $base_url;
815

    
816
    // Run cron anonymously without any cron key.
817
    $this->drupalGet($base_url . '/cron.php', array('external' => TRUE));
818
    $this->assertResponse(403);
819

    
820
    // Run cron anonymously with a random cron key.
821
    $key = $this->randomName(16);
822
    $this->drupalGet($base_url . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => $key)));
823
    $this->assertResponse(403);
824

    
825
    // Run cron anonymously with the valid cron key.
826
    $key = variable_get('cron_key', 'drupal');
827
    $this->drupalGet($base_url . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => $key)));
828
    $this->assertResponse(200);
829
  }
830

    
831
  /**
832
   * Ensure that the automatic cron run feature is working.
833
   *
834
   * In these tests we do not use REQUEST_TIME to track start time, because we
835
   * need the exact time when cron is triggered.
836
   */
837
  function testAutomaticCron() {
838
    // Ensure cron does not run when the cron threshold is enabled and was
839
    // not passed.
840
    $cron_last = time();
841
    $cron_safe_threshold = 100;
842
    variable_set('cron_last', $cron_last);
843
    variable_set('cron_safe_threshold', $cron_safe_threshold);
844
    $this->drupalGet('');
845
    $this->assertTrue($cron_last == variable_get('cron_last', NULL), 'Cron does not run when the cron threshold is not passed.');
846

    
847
    // Test if cron runs when the cron threshold was passed.
848
    $cron_last = time() - 200;
849
    variable_set('cron_last', $cron_last);
850
    $this->drupalGet('');
851
    sleep(1);
852
    $this->assertTrue($cron_last < variable_get('cron_last', NULL), 'Cron runs when the cron threshold is passed.');
853

    
854
    // Disable the cron threshold through the interface.
855
    $admin_user = $this->drupalCreateUser(array('administer site configuration'));
856
    $this->drupalLogin($admin_user);
857
    $this->drupalPost('admin/config/system/cron', array('cron_safe_threshold' => 0), t('Save configuration'));
858
    $this->assertText(t('The configuration options have been saved.'));
859
    $this->drupalLogout();
860

    
861
    // Test if cron does not run when the cron threshold is disabled.
862
    $cron_last = time() - 200;
863
    variable_set('cron_last', $cron_last);
864
    $this->drupalGet('');
865
    $this->assertTrue($cron_last == variable_get('cron_last', NULL), 'Cron does not run when the cron threshold is disabled.');
866
  }
867

    
868
  /**
869
   * Ensure that temporary files are removed.
870
   *
871
   * Create files for all the possible combinations of age and status. We are
872
   * using UPDATE statements rather than file_save() because it would set the
873
   * timestamp.
874
   */
875
  function testTempFileCleanup() {
876
    // Temporary file that is older than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
877
    $temp_old = file_save_data('');
878
    db_update('file_managed')
879
      ->fields(array(
880
        'status' => 0,
881
        'timestamp' => 1,
882
      ))
883
      ->condition('fid', $temp_old->fid)
884
      ->execute();
885
    $this->assertTrue(file_exists($temp_old->uri), 'Old temp file was created correctly.');
886

    
887
    // Temporary file that is less than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
888
    $temp_new = file_save_data('');
889
    db_update('file_managed')
890
      ->fields(array('status' => 0))
891
      ->condition('fid', $temp_new->fid)
892
      ->execute();
893
    $this->assertTrue(file_exists($temp_new->uri), 'New temp file was created correctly.');
894

    
895
    // Permanent file that is older than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
896
    $perm_old = file_save_data('');
897
    db_update('file_managed')
898
      ->fields(array('timestamp' => 1))
899
      ->condition('fid', $temp_old->fid)
900
      ->execute();
901
    $this->assertTrue(file_exists($perm_old->uri), 'Old permanent file was created correctly.');
902

    
903
    // Permanent file that is newer than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
904
    $perm_new = file_save_data('');
905
    $this->assertTrue(file_exists($perm_new->uri), 'New permanent file was created correctly.');
906

    
907
    // Run cron and then ensure that only the old, temp file was deleted.
908
    $this->cronRun();
909
    $this->assertFalse(file_exists($temp_old->uri), 'Old temp file was correctly removed.');
910
    $this->assertTrue(file_exists($temp_new->uri), 'New temp file was correctly ignored.');
911
    $this->assertTrue(file_exists($perm_old->uri), 'Old permanent file was correctly ignored.');
912
    $this->assertTrue(file_exists($perm_new->uri), 'New permanent file was correctly ignored.');
913
  }
914

    
915
  /**
916
   * Make sure exceptions thrown on hook_cron() don't affect other modules.
917
   */
918
  function testCronExceptions() {
919
    variable_del('common_test_cron');
920
    // The common_test module throws an exception. If it isn't caught, the tests
921
    // won't finish successfully.
922
    // The common_test_cron_helper module sets the 'common_test_cron' variable.
923
    $this->cronRun();
924
    $result = variable_get('common_test_cron');
925
    $this->assertEqual($result, 'success', 'Cron correctly handles exceptions thrown during hook_cron() invocations.');
926
  }
927

    
928
  /**
929
   * Tests that hook_flush_caches() is not invoked on every single cron run.
930
   *
931
   * @see system_cron()
932
   */
933
  public function testCronCacheExpiration() {
934
    module_enable(array('system_cron_test'));
935
    variable_del('system_cron_test_flush_caches');
936

    
937
    // Invoke cron the first time: hook_flush_caches() should be called and then
938
    // get cached.
939
    drupal_cron_run();
940
    $this->assertEqual(variable_get('system_cron_test_flush_caches'), 1, 'hook_flush_caches() was invoked the first time.');
941
    $cache = cache_get('system_cache_tables');
942
    $this->assertEqual(empty($cache), FALSE, 'Cache is filled with cache table data.');
943

    
944
    // Run cron again and ensure that hook_flush_caches() is not called.
945
    variable_del('system_cron_test_flush_caches');
946
    drupal_cron_run();
947
    $this->assertNull(variable_get('system_cron_test_flush_caches'), 'hook_flush_caches() was not invoked the second time.');
948
  }
949

    
950
}
951

    
952
/**
953
 * Test execution of the cron queue.
954
 */
955
class CronQueueTestCase extends DrupalWebTestCase {
956
  /**
957
   * Implement getInfo().
958
   */
959
  public static function getInfo() {
960
    return array(
961
      'name' => 'Cron queue functionality',
962
      'description' => 'Tests the cron queue runner.',
963
      'group' => 'System'
964
    );
965
  }
966

    
967
  function setUp() {
968
    parent::setUp(array('common_test', 'common_test_cron_helper', 'cron_queue_test'));
969
  }
970

    
971
  /**
972
   * Tests that exceptions thrown by workers are handled properly.
973
   */
974
  function testExceptions() {
975
    $queue = DrupalQueue::get('cron_queue_test_exception');
976

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

    
980
    // Run cron; the worker for this queue should throw an exception and handle
981
    // it.
982
    $this->cronRun();
983

    
984
    // The item should be left in the queue.
985
    $this->assertEqual($queue->numberOfItems(), 1, 'Failing item still in the queue after throwing an exception.');
986
  }
987

    
988
  /**
989
   * Tests worker defined as a class method callable.
990
   */
991
  function testCallable() {
992
    $queue = DrupalQueue::get('cron_queue_test_callback');
993

    
994
    // Enqueue an item for processing.
995
    $queue->createItem(array($this->randomName() => $this->randomName()));
996

    
997
    // Run cron; the worker should perform the task and delete the item from the
998
    // queue.
999
    $this->cronRun();
1000

    
1001
    // The queue should be empty.
1002
    $this->assertEqual($queue->numberOfItems(), 0);
1003
  }
1004

    
1005
}
1006

    
1007
class AdminMetaTagTestCase extends DrupalWebTestCase {
1008
  /**
1009
   * Implement getInfo().
1010
   */
1011
  public static function getInfo() {
1012
    return array(
1013
      'name' => 'Fingerprinting meta tag',
1014
      'description' => 'Confirm that the fingerprinting meta tag appears as expected.',
1015
      'group' => 'System'
1016
    );
1017
  }
1018

    
1019
  /**
1020
   * Verify that the meta tag HTML is generated correctly.
1021
   */
1022
  public function testMetaTag() {
1023
    list($version, ) = explode('.', VERSION);
1024
    $string = '<meta name="Generator" content="Drupal ' . $version . ' (http://drupal.org)" />';
1025
    $this->drupalGet('node');
1026
    $this->assertRaw($string, 'Fingerprinting meta tag generated correctly.', 'System');
1027
  }
1028
}
1029

    
1030
/**
1031
 * Tests custom access denied functionality.
1032
 */
1033
class AccessDeniedTestCase extends DrupalWebTestCase {
1034
  protected $admin_user;
1035

    
1036
  public static function getInfo() {
1037
    return array(
1038
      'name' => '403 functionality',
1039
      'description' => 'Tests page access denied functionality, including custom 403 pages.',
1040
      'group' => 'System'
1041
    );
1042
  }
1043

    
1044
  function setUp() {
1045
    parent::setUp();
1046

    
1047
    // Create an administrative user.
1048
    $this->admin_user = $this->drupalCreateUser(array('access administration pages', 'administer site configuration', 'administer blocks'));
1049
  }
1050

    
1051
  function testAccessDenied() {
1052
    $this->drupalGet('admin');
1053
    $this->assertText(t('Access denied'), 'Found the default 403 page');
1054
    $this->assertResponse(403);
1055

    
1056
    $this->drupalLogin($this->admin_user);
1057
    $edit = array(
1058
      'title' => $this->randomName(10),
1059
      'body' => array(LANGUAGE_NONE => array(array('value' => $this->randomName(100)))),
1060
    );
1061
    $node = $this->drupalCreateNode($edit);
1062

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

    
1066
    $this->drupalLogout();
1067
    $this->drupalGet('admin');
1068
    $this->assertText($node->title, 'Found the custom 403 page');
1069

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

    
1073
    $this->drupalGet('admin');
1074
    $this->assertText($node->title, 'Found the custom 403 page');
1075
    $this->assertText(t('User login'), 'Blocks are shown on the custom 403 page');
1076

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

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

    
1084
    $this->drupalGet('admin');
1085
    $this->assertText(t('Access denied'), 'Found the default 403 page');
1086
    $this->assertResponse(403);
1087
    $this->assertText(t('User login'), 'Blocks are shown on the default 403 page');
1088

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

    
1094
    // Check that we can log in from the 403 page.
1095
    $this->drupalLogout();
1096
    $edit = array(
1097
      'name' => $this->admin_user->name,
1098
      'pass' => $this->admin_user->pass_raw,
1099
    );
1100
    $this->drupalPost('admin/config/system/site-information', $edit, t('Log in'));
1101

    
1102
    // Check that we're still on the same page.
1103
    $this->assertText(t('Site information'));
1104
  }
1105
}
1106

    
1107
class PageNotFoundTestCase extends DrupalWebTestCase {
1108
  protected $admin_user;
1109

    
1110
  /**
1111
   * Implement getInfo().
1112
   */
1113
  public static function getInfo() {
1114
    return array(
1115
      'name' => '404 functionality',
1116
      'description' => "Tests page not found functionality, including custom 404 pages.",
1117
      'group' => 'System'
1118
    );
1119
  }
1120

    
1121
  /**
1122
   * Implement setUp().
1123
   */
1124
  function setUp() {
1125
    parent::setUp();
1126

    
1127
    // Create an administrative user.
1128
    $this->admin_user = $this->drupalCreateUser(array('administer site configuration'));
1129
    $this->drupalLogin($this->admin_user);
1130
  }
1131

    
1132
  function testPageNotFound() {
1133
    $this->drupalGet($this->randomName(10));
1134
    $this->assertText(t('Page not found'), 'Found the default 404 page');
1135

    
1136
    $edit = array(
1137
      'title' => $this->randomName(10),
1138
      'body' => array(LANGUAGE_NONE => array(array('value' => $this->randomName(100)))),
1139
    );
1140
    $node = $this->drupalCreateNode($edit);
1141

    
1142
    // As node IDs must be integers, make sure requests for non-integer IDs
1143
    // return a page not found error.
1144
    $this->drupalGet('node/invalid');
1145
    $this->assertResponse(404);
1146

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

    
1150
    $this->drupalGet($this->randomName(10));
1151
    $this->assertText($node->title, 'Found the custom 404 page');
1152
  }
1153
}
1154

    
1155
/**
1156
 * Tests site maintenance functionality.
1157
 */
1158
class SiteMaintenanceTestCase extends DrupalWebTestCase {
1159
  protected $admin_user;
1160

    
1161
  public static function getInfo() {
1162
    return array(
1163
      'name' => 'Site maintenance mode functionality',
1164
      'description' => 'Test access to site while in maintenance mode.',
1165
      'group' => 'System',
1166
    );
1167
  }
1168

    
1169
  function setUp() {
1170
    parent::setUp();
1171

    
1172
    // Create a user allowed to access site in maintenance mode.
1173
    $this->user = $this->drupalCreateUser(array('access site in maintenance mode'));
1174
    // Create an administrative user.
1175
    $this->admin_user = $this->drupalCreateUser(array('administer site configuration', 'access site in maintenance mode'));
1176
    $this->drupalLogin($this->admin_user);
1177
  }
1178

    
1179
  /**
1180
   * Verify site maintenance mode functionality.
1181
   */
1182
  function testSiteMaintenance() {
1183
    // Turn on maintenance mode.
1184
    $edit = array(
1185
      'maintenance_mode' => 1,
1186
    );
1187
    $this->drupalPost('admin/config/development/maintenance', $edit, t('Save configuration'));
1188

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

    
1193
    $this->drupalGet('');
1194
    $this->assertRaw($admin_message, 'Found the site maintenance mode message.');
1195

    
1196
    // Logout and verify that offline message is displayed.
1197
    $this->drupalLogout();
1198
    $this->drupalGet('');
1199
    $this->assertText($offline_message);
1200
    $this->drupalGet('node');
1201
    $this->assertText($offline_message);
1202
    $this->drupalGet('user/register');
1203
    $this->assertText($offline_message);
1204

    
1205
    // Verify that user is able to log in.
1206
    $this->drupalGet('user');
1207
    $this->assertNoText($offline_message);
1208
    $this->drupalGet('user/login');
1209
    $this->assertNoText($offline_message);
1210

    
1211
    // Log in user and verify that maintenance mode message is displayed
1212
    // directly after login.
1213
    $edit = array(
1214
      'name' => $this->user->name,
1215
      'pass' => $this->user->pass_raw,
1216
    );
1217
    $this->drupalPost(NULL, $edit, t('Log in'));
1218
    $this->assertText($user_message);
1219

    
1220
    // Log in administrative user and configure a custom site offline message.
1221
    $this->drupalLogout();
1222
    $this->drupalLogin($this->admin_user);
1223
    $this->drupalGet('admin/config/development/maintenance');
1224
    $this->assertNoRaw($admin_message, 'Site maintenance mode message not displayed.');
1225

    
1226
    $offline_message = 'Sorry, not online.';
1227
    $edit = array(
1228
      'maintenance_mode_message' => $offline_message,
1229
    );
1230
    $this->drupalPost(NULL, $edit, t('Save configuration'));
1231

    
1232
    // Logout and verify that custom site offline message is displayed.
1233
    $this->drupalLogout();
1234
    $this->drupalGet('');
1235
    $this->assertRaw($offline_message, 'Found the site offline message.');
1236

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

    
1241
    // Submit password reset form.
1242
    $edit = array(
1243
      'name' => $this->user->name,
1244
    );
1245
    $this->drupalPost('user/password', $edit, t('E-mail new password'));
1246
    $mails = $this->drupalGetMails();
1247
    $start = strpos($mails[0]['body'], 'user/reset/'. $this->user->uid);
1248
    $path = substr($mails[0]['body'], $start, 66 + strlen($this->user->uid));
1249

    
1250
    // Log in with temporary login link.
1251
    $this->drupalPost($path, array(), t('Log in'));
1252
    $this->assertText($user_message);
1253
  }
1254
}
1255

    
1256
/**
1257
 * Tests generic date and time handling capabilities of Drupal.
1258
 */
1259
class DateTimeFunctionalTest extends DrupalWebTestCase {
1260
  public static function getInfo() {
1261
    return array(
1262
      'name' => 'Date and time',
1263
      'description' => 'Configure date and time settings. Test date formatting and time zone handling, including daylight saving time.',
1264
      'group' => 'System',
1265
    );
1266
  }
1267

    
1268
  function setUp() {
1269
    parent::setUp(array('locale'));
1270

    
1271
    // Create admin user and log in admin user.
1272
    $this->admin_user = $this->drupalCreateUser(array('administer site configuration'));
1273
    $this->drupalLogin($this->admin_user);
1274
  }
1275

    
1276

    
1277
  /**
1278
   * Test time zones and DST handling.
1279
   */
1280
  function testTimeZoneHandling() {
1281
    // Setup date/time settings for Honolulu time.
1282
    variable_set('date_default_timezone', 'Pacific/Honolulu');
1283
    variable_set('configurable_timezones', 0);
1284
    variable_set('date_format_medium', 'Y-m-d H:i:s O');
1285

    
1286
    // Create some nodes with different authored-on dates.
1287
    $date1 = '2007-01-31 21:00:00 -1000';
1288
    $date2 = '2007-07-31 21:00:00 -1000';
1289
    $node1 = $this->drupalCreateNode(array('created' => strtotime($date1), 'type' => 'article'));
1290
    $node2 = $this->drupalCreateNode(array('created' => strtotime($date2), 'type' => 'article'));
1291

    
1292
    // Confirm date format and time zone.
1293
    $this->drupalGet("node/$node1->nid");
1294
    $this->assertText('2007-01-31 21:00:00 -1000', 'Date should be identical, with GMT offset of -10 hours.');
1295
    $this->drupalGet("node/$node2->nid");
1296
    $this->assertText('2007-07-31 21:00:00 -1000', 'Date should be identical, with GMT offset of -10 hours.');
1297

    
1298
    // Set time zone to Los Angeles time.
1299
    variable_set('date_default_timezone', 'America/Los_Angeles');
1300

    
1301
    // Confirm date format and time zone.
1302
    $this->drupalGet("node/$node1->nid");
1303
    $this->assertText('2007-01-31 23:00:00 -0800', 'Date should be two hours ahead, with GMT offset of -8 hours.');
1304
    $this->drupalGet("node/$node2->nid");
1305
    $this->assertText('2007-08-01 00:00:00 -0700', 'Date should be three hours ahead, with GMT offset of -7 hours.');
1306
  }
1307

    
1308
  /**
1309
   * Test date type configuration.
1310
   */
1311
  function testDateTypeConfiguration() {
1312
    // Confirm system date types appear.
1313
    $this->drupalGet('admin/config/regional/date-time');
1314
    $this->assertText(t('Medium'), 'System date types appear in date type list.');
1315
    $this->assertNoRaw('href="/admin/config/regional/date-time/types/medium/delete"', 'No delete link appear for system date types.');
1316

    
1317
    // Add custom date type.
1318
    $this->clickLink(t('Add date type'));
1319
    $date_type = strtolower($this->randomName(8));
1320
    $machine_name = 'machine_' . $date_type;
1321
    $date_format = 'd.m.Y - H:i';
1322
    $edit = array(
1323
      'date_type' => $date_type,
1324
      'machine_name' => $machine_name,
1325
      'date_format' => $date_format,
1326
    );
1327
    $this->drupalPost('admin/config/regional/date-time/types/add', $edit, t('Add date type'));
1328
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time', array('absolute' => TRUE)), 'Correct page redirection.');
1329
    $this->assertText(t('New date type added successfully.'), 'Date type added confirmation message appears.');
1330
    $this->assertText($date_type, 'Custom date type appears in the date type list.');
1331
    $this->assertText(t('delete'), 'Delete link for custom date type appears.');
1332

    
1333
    // Delete custom date type.
1334
    $this->clickLink(t('delete'));
1335
    $this->drupalPost('admin/config/regional/date-time/types/' . $machine_name . '/delete', array(), t('Remove'));
1336
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time', array('absolute' => TRUE)), 'Correct page redirection.');
1337
    $this->assertText(t('Removed date type ' . $date_type), 'Custom date type removed.');
1338
  }
1339

    
1340
  /**
1341
   * Test date format configuration.
1342
   */
1343
  function testDateFormatConfiguration() {
1344
    // Confirm 'no custom date formats available' message appears.
1345
    $this->drupalGet('admin/config/regional/date-time/formats');
1346
    $this->assertText(t('No custom date formats available.'), 'No custom date formats message appears.');
1347

    
1348
    // Add custom date format.
1349
    $this->clickLink(t('Add format'));
1350
    $edit = array(
1351
      'date_format' => 'Y',
1352
    );
1353
    $this->drupalPost('admin/config/regional/date-time/formats/add', $edit, t('Add format'));
1354
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE)), 'Correct page redirection.');
1355
    $this->assertNoText(t('No custom date formats available.'), 'No custom date formats message does not appear.');
1356
    $this->assertText(t('Custom date format added.'), 'Custom date format added.');
1357

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

    
1362
    // Edit custom date format.
1363
    $this->drupalGet('admin/config/regional/date-time/formats');
1364
    $this->clickLink(t('edit'));
1365
    $edit = array(
1366
      'date_format' => 'Y m',
1367
    );
1368
    $this->drupalPost($this->getUrl(), $edit, t('Save format'));
1369
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE)), 'Correct page redirection.');
1370
    $this->assertText(t('Custom date format updated.'), 'Custom date format successfully updated.');
1371

    
1372
    // Check that ajax callback is protected by CSRF token.
1373
    $this->drupalGet('admin/config/regional/date-time/formats/lookup', array('query' => array('format' => 'Y m d')));
1374
    $this->assertResponse(403, 'Access denied with no token');
1375
    $this->drupalGet('admin/config/regional/date-time/formats/lookup', array('query' => array('token' => 'invalid', 'format' => 'Y m d')));
1376
    $this->assertResponse(403, 'Access denied with invalid token');
1377
    $this->drupalGet('admin/config/regional/date-time/formats');
1378
    $this->clickLink(t('edit'));
1379
    $settings = $this->drupalGetSettings();
1380
    $lookup_url = $settings['dateTime']['date-format']['lookup'];
1381
    preg_match('/token=([^&]+)/', $lookup_url, $matches);
1382
    $this->assertFalse(empty($matches[1]), 'Found token value');
1383
    $this->drupalGet('admin/config/regional/date-time/formats/lookup', array('query' => array('token' => $matches[1], 'format' => 'Y m d')));
1384
    $this->assertResponse(200, 'Access allowed with valid token');
1385
    $this->assertText(format_date(time(), 'custom', 'Y m d'));
1386

    
1387
    // Delete custom date format.
1388
    $this->drupalGet('admin/config/regional/date-time/formats');
1389
    $this->clickLink(t('delete'));
1390
    $this->drupalPost($this->getUrl(), array(), t('Remove'));
1391
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE)), 'Correct page redirection.');
1392
    $this->assertText(t('Removed date format'), 'Custom date format removed successfully.');
1393
  }
1394

    
1395
  /**
1396
   * Test if the date formats are stored properly.
1397
   */
1398
  function testDateFormatStorage() {
1399
    $date_format = array(
1400
      'type' => 'short',
1401
      'format' => 'dmYHis',
1402
      'locked' => 0,
1403
      'is_new' => 1,
1404
    );
1405
    system_date_format_save($date_format);
1406

    
1407
    $format = db_select('date_formats', 'df')
1408
      ->fields('df', array('format'))
1409
      ->condition('type', 'short')
1410
      ->condition('format', 'dmYHis')
1411
      ->execute()
1412
      ->fetchField();
1413
    $this->verbose($format);
1414
    $this->assertEqual('dmYHis', $format, 'Unlocalized date format resides in general table.');
1415

    
1416
    $format = db_select('date_format_locale', 'dfl')
1417
      ->fields('dfl', array('format'))
1418
      ->condition('type', 'short')
1419
      ->condition('format', 'dmYHis')
1420
      ->execute()
1421
      ->fetchField();
1422
    $this->assertFalse($format, 'Unlocalized date format resides not in localized table.');
1423

    
1424
    // Enable German language
1425
    locale_add_language('de', NULL, NULL, LANGUAGE_LTR, '', '', TRUE, 'en');
1426

    
1427
    $date_format = array(
1428
      'type' => 'short',
1429
      'format' => 'YMDHis',
1430
      'locales' => array('de', 'tr'),
1431
      'locked' => 0,
1432
      'is_new' => 1,
1433
    );
1434
    system_date_format_save($date_format);
1435

    
1436
    $format = db_select('date_format_locale', 'dfl')
1437
      ->fields('dfl', array('format'))
1438
      ->condition('type', 'short')
1439
      ->condition('format', 'YMDHis')
1440
      ->condition('language', 'de')
1441
      ->execute()
1442
      ->fetchField();
1443
    $this->assertEqual('YMDHis', $format, 'Localized date format resides in localized table.');
1444

    
1445
    $format = db_select('date_formats', 'df')
1446
      ->fields('df', array('format'))
1447
      ->condition('type', 'short')
1448
      ->condition('format', 'YMDHis')
1449
      ->execute()
1450
      ->fetchField();
1451
    $this->assertEqual('YMDHis', $format, 'Localized date format resides in general table too.');
1452

    
1453
    $format = db_select('date_format_locale', 'dfl')
1454
      ->fields('dfl', array('format'))
1455
      ->condition('type', 'short')
1456
      ->condition('format', 'YMDHis')
1457
      ->condition('language', 'tr')
1458
      ->execute()
1459
      ->fetchColumn();
1460
    $this->assertFalse($format, 'Localized date format for disabled language is ignored.');
1461
  }
1462
}
1463

    
1464
class PageTitleFiltering extends DrupalWebTestCase {
1465
  protected $content_user;
1466
  protected $saved_title;
1467

    
1468
  /**
1469
   * Implement getInfo().
1470
   */
1471
  public static function getInfo() {
1472
    return array(
1473
      'name' => 'HTML in page titles',
1474
      'description' => 'Tests correct handling or conversion by drupal_set_title() and drupal_get_title() and checks the correct escaping of site name and slogan.',
1475
      'group' => 'System'
1476
    );
1477
  }
1478

    
1479
  /**
1480
   * Implement setUp().
1481
   */
1482
  function setUp() {
1483
    parent::setUp();
1484

    
1485
    $this->content_user = $this->drupalCreateUser(array('create page content', 'access content', 'administer themes', 'administer site configuration'));
1486
    $this->drupalLogin($this->content_user);
1487
    $this->saved_title = drupal_get_title();
1488
  }
1489

    
1490
  /**
1491
   * Reset page title.
1492
   */
1493
  function tearDown() {
1494
    // Restore the page title.
1495
    drupal_set_title($this->saved_title, PASS_THROUGH);
1496

    
1497
    parent::tearDown();
1498
  }
1499

    
1500
  /**
1501
   * Tests the handling of HTML by drupal_set_title() and drupal_get_title()
1502
   */
1503
  function testTitleTags() {
1504
    $title = "string with <em>HTML</em>";
1505
    // drupal_set_title's $filter is CHECK_PLAIN by default, so the title should be
1506
    // returned with check_plain().
1507
    drupal_set_title($title, CHECK_PLAIN);
1508
    $this->assertTrue(strpos(drupal_get_title(), '<em>') === FALSE, 'Tags in title converted to entities when $output is CHECK_PLAIN.');
1509
    // drupal_set_title's $filter is passed as PASS_THROUGH, so the title should be
1510
    // returned with HTML.
1511
    drupal_set_title($title, PASS_THROUGH);
1512
    $this->assertTrue(strpos(drupal_get_title(), '<em>') !== FALSE, 'Tags in title are not converted to entities when $output is PASS_THROUGH.');
1513
    // Generate node content.
1514
    $langcode = LANGUAGE_NONE;
1515
    $edit = array(
1516
      "title" => '!SimpleTest! ' . $title . $this->randomName(20),
1517
      "body[$langcode][0][value]" => '!SimpleTest! test body' . $this->randomName(200),
1518
    );
1519
    // Create the node with HTML in the title.
1520
    $this->drupalPost('node/add/page', $edit, t('Save'));
1521

    
1522
    $node = $this->drupalGetNodeByTitle($edit["title"]);
1523
    $this->assertNotNull($node, 'Node created and found in database');
1524
    $this->drupalGet("node/" . $node->nid);
1525
    $this->assertText(check_plain($edit["title"]), 'Check to make sure tags in the node title are converted.');
1526
  }
1527
  /**
1528
   * Test if the title of the site is XSS proof.
1529
   */
1530
  function testTitleXSS() {
1531
    // Set some title with JavaScript and HTML chars to escape.
1532
    $title = '</title><script type="text/javascript">alert("Title XSS!");</script> & < > " \' ';
1533
    $title_filtered = check_plain($title);
1534

    
1535
    $slogan = '<script type="text/javascript">alert("Slogan XSS!");</script>';
1536
    $slogan_filtered = filter_xss_admin($slogan);
1537

    
1538
    // Activate needed appearance settings.
1539
    $edit = array(
1540
      'toggle_name'           => TRUE,
1541
      'toggle_slogan'         => TRUE,
1542
      'toggle_main_menu'      => TRUE,
1543
      'toggle_secondary_menu' => TRUE,
1544
    );
1545
    $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
1546

    
1547
    // Set title and slogan.
1548
    $edit = array(
1549
      'site_name'    => $title,
1550
      'site_slogan'  => $slogan,
1551
    );
1552
    $this->drupalPost('admin/config/system/site-information', $edit, t('Save configuration'));
1553

    
1554
    // Load frontpage.
1555
    $this->drupalGet('');
1556

    
1557
    // Test the title.
1558
    $this->assertNoRaw($title, 'Check for the unfiltered version of the title.');
1559
    // Adding </title> so we do not test the escaped version from drupal_set_title().
1560
    $this->assertRaw($title_filtered . '</title>', 'Check for the filtered version of the title.');
1561

    
1562
    // Test the slogan.
1563
    $this->assertNoRaw($slogan, 'Check for the unfiltered version of the slogan.');
1564
    $this->assertRaw($slogan_filtered, 'Check for the filtered version of the slogan.');
1565
  }
1566
}
1567

    
1568
/**
1569
 * Test front page functionality and administration.
1570
 */
1571
class FrontPageTestCase extends DrupalWebTestCase {
1572

    
1573
  public static function getInfo() {
1574
    return array(
1575
      'name' => 'Front page',
1576
      'description' => 'Tests front page functionality and administration.',
1577
      'group' => 'System',
1578
    );
1579
  }
1580

    
1581
  function setUp() {
1582
    parent::setUp('system_test');
1583

    
1584
    // Create admin user, log in admin user, and create one node.
1585
    $this->admin_user = $this->drupalCreateUser(array('access content', 'administer site configuration'));
1586
    $this->drupalLogin($this->admin_user);
1587
    $this->node_path = "node/" . $this->drupalCreateNode(array('promote' => 1))->nid;
1588

    
1589
    // Enable front page logging in system_test.module.
1590
    variable_set('front_page_output', 1);
1591
  }
1592

    
1593
  /**
1594
   * Test front page functionality.
1595
   */
1596
  function testDrupalIsFrontPage() {
1597
    $this->drupalGet('');
1598
    $this->assertText(t('On front page.'), 'Path is the front page.');
1599
    $this->drupalGet('node');
1600
    $this->assertText(t('On front page.'), 'Path is the front page.');
1601
    $this->drupalGet($this->node_path);
1602
    $this->assertNoText(t('On front page.'), 'Path is not the front page.');
1603

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

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

    
1614
    $this->drupalGet('');
1615
    $this->assertText(t('On front page.'), 'Path is the front page.');
1616
    $this->drupalGet('node');
1617
    $this->assertNoText(t('On front page.'), 'Path is not the front page.');
1618
    $this->drupalGet($this->node_path);
1619
    $this->assertText(t('On front page.'), 'Path is the front page.');
1620
  }
1621
}
1622

    
1623
class SystemBlockTestCase extends DrupalWebTestCase {
1624
  protected $profile = 'testing';
1625

    
1626
  public static function getInfo() {
1627
    return array(
1628
      'name' => 'Block functionality',
1629
      'description' => 'Configure and move powered-by block.',
1630
      'group' => 'System',
1631
    );
1632
  }
1633

    
1634
  function setUp() {
1635
    parent::setUp('block');
1636

    
1637
    // Create and login user
1638
    $admin_user = $this->drupalCreateUser(array('administer blocks', 'access administration pages'));
1639
    $this->drupalLogin($admin_user);
1640
  }
1641

    
1642
  /**
1643
   * Test displaying and hiding the powered-by and help blocks.
1644
   */
1645
  function testSystemBlocks() {
1646
    // Set block title and some settings to confirm that the interface is available.
1647
    $this->drupalPost('admin/structure/block/manage/system/powered-by/configure', array('title' => $this->randomName(8)), t('Save block'));
1648
    $this->assertText(t('The block configuration has been saved.'), t('Block configuration set.'));
1649

    
1650
    // Set the powered-by block to the footer region.
1651
    $edit = array();
1652
    $edit['blocks[system_powered-by][region]'] = 'footer';
1653
    $edit['blocks[system_main][region]'] = 'content';
1654
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1655
    $this->assertText(t('The block settings have been updated.'), t('Block successfully moved to footer region.'));
1656

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

    
1661
    // Set the block to the disabled region.
1662
    $edit = array();
1663
    $edit['blocks[system_powered-by][region]'] = '-1';
1664
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1665

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

    
1669
    // For convenience of developers, set the block to its default settings.
1670
    $edit = array();
1671
    $edit['blocks[system_powered-by][region]'] = 'footer';
1672
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1673
    $this->drupalPost('admin/structure/block/manage/system/powered-by/configure', array('title' => ''), t('Save block'));
1674

    
1675
    // Set the help block to the help region.
1676
    $edit = array();
1677
    $edit['blocks[system_help][region]'] = 'help';
1678
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1679

    
1680
    // Test displaying the help block with block caching enabled.
1681
    variable_set('block_cache', TRUE);
1682
    $this->drupalGet('admin/structure/block/add');
1683
    $this->assertRaw(t('Use this page to create a new custom block.'));
1684
    $this->drupalGet('admin/index');
1685
    $this->assertRaw(t('This page shows you all available administration tasks for each module.'));
1686
  }
1687
}
1688

    
1689
/**
1690
 * Test main content rendering fallback provided by system module.
1691
 */
1692
class SystemMainContentFallback extends DrupalWebTestCase {
1693
  protected $admin_user;
1694
  protected $web_user;
1695

    
1696
  public static function getInfo() {
1697
    return array(
1698
      'name' => 'Main content rendering fallback',
1699
      'description' => ' Test system module main content rendering fallback.',
1700
      'group' => 'System',
1701
    );
1702
  }
1703

    
1704
  function setUp() {
1705
    parent::setUp('system_test');
1706

    
1707
    // Create and login admin user.
1708
    $this->admin_user = $this->drupalCreateUser(array(
1709
      'access administration pages',
1710
      'administer site configuration',
1711
      'administer modules',
1712
      'administer blocks',
1713
      'administer nodes',
1714
    ));
1715
    $this->drupalLogin($this->admin_user);
1716

    
1717
    // Create a web user.
1718
    $this->web_user = $this->drupalCreateUser(array('access user profiles', 'access content'));
1719
  }
1720

    
1721
  /**
1722
   * Test availability of main content.
1723
   */
1724
  function testMainContentFallback() {
1725
    $edit = array();
1726
    // Disable the dashboard module, which depends on the block module.
1727
    $edit['modules[Core][dashboard][enable]'] = FALSE;
1728
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
1729
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
1730
    // Disable the block module.
1731
    $edit['modules[Core][block][enable]'] = FALSE;
1732
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
1733
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
1734
    module_list(TRUE);
1735
    $this->assertFalse(module_exists('block'), 'Block module disabled.');
1736

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

    
1741
    // Fallback should not trigger when another module is handling content.
1742
    $this->drupalGet('system-test/main-content-handling');
1743
    $this->assertRaw('id="system-test-content"', 'Content handled by another module');
1744
    $this->assertText(t('Content to test main content fallback'), 'Main content still displayed.');
1745

    
1746
    // Fallback should trigger when another module
1747
    // indicates that it is not handling the content.
1748
    $this->drupalGet('system-test/main-content-fallback');
1749
    $this->assertText(t('Content to test main content fallback'), 'Main content fallback properly triggers.');
1750

    
1751
    // Fallback should not trigger when another module is handling content.
1752
    // Note that this test ensures that no duplicate
1753
    // content gets created by the fallback.
1754
    $this->drupalGet('system-test/main-content-duplication');
1755
    $this->assertNoText(t('Content to test main content fallback'), 'Main content not duplicated.');
1756

    
1757
    // Request a user* page and see if it is displayed.
1758
    $this->drupalLogin($this->web_user);
1759
    $this->drupalGet('user/' . $this->web_user->uid . '/edit');
1760
    $this->assertField('mail', 'User interface still available.');
1761

    
1762
    // Enable the block module again.
1763
    $this->drupalLogin($this->admin_user);
1764
    $edit = array();
1765
    $edit['modules[Core][block][enable]'] = 'block';
1766
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
1767
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
1768
    module_list(TRUE);
1769
    $this->assertTrue(module_exists('block'), 'Block module re-enabled.');
1770
  }
1771
}
1772

    
1773
/**
1774
 * Tests for the theme interface functionality.
1775
 */
1776
class SystemThemeFunctionalTest extends DrupalWebTestCase {
1777
  public static function getInfo() {
1778
    return array(
1779
      'name' => 'Theme interface functionality',
1780
      'description' => 'Tests the theme interface functionality by enabling and switching themes, and using an administration theme.',
1781
      'group' => 'System',
1782
    );
1783
  }
1784

    
1785
  function setUp() {
1786
    parent::setUp();
1787

    
1788
    $this->admin_user = $this->drupalCreateUser(array('access administration pages', 'view the administration theme', 'administer themes', 'bypass node access', 'administer blocks'));
1789
    $this->drupalLogin($this->admin_user);
1790
    $this->node = $this->drupalCreateNode();
1791
  }
1792

    
1793
  /**
1794
   * Test the theme settings form.
1795
   */
1796
  function testThemeSettings() {
1797
    // Specify a filesystem path to be used for the logo.
1798
    $file = current($this->drupalGetTestFiles('image'));
1799
    $file_relative = strtr($file->uri, array('public:/' => variable_get('file_public_path', conf_path() . '/files')));
1800
    $default_theme_path = 'themes/stark';
1801

    
1802
    $supported_paths = array(
1803
      // Raw stream wrapper URI.
1804
      $file->uri => array(
1805
        'form' => file_uri_target($file->uri),
1806
        'src' => file_create_url($file->uri),
1807
      ),
1808
      // Relative path within the public filesystem.
1809
      file_uri_target($file->uri) => array(
1810
        'form' => file_uri_target($file->uri),
1811
        'src' => file_create_url($file->uri),
1812
      ),
1813
      // Relative path to a public file.
1814
      $file_relative => array(
1815
        'form' => $file_relative,
1816
        'src' => file_create_url($file->uri),
1817
      ),
1818
      // Relative path to an arbitrary file.
1819
      'misc/druplicon.png' => array(
1820
        'form' => 'misc/druplicon.png',
1821
        'src' => $GLOBALS['base_url'] . '/' . 'misc/druplicon.png',
1822
      ),
1823
      // Relative path to a file in a theme.
1824
      $default_theme_path . '/logo.png' => array(
1825
        'form' => $default_theme_path . '/logo.png',
1826
        'src' => $GLOBALS['base_url'] . '/' . $default_theme_path . '/logo.png',
1827
      ),
1828
    );
1829
    foreach ($supported_paths as $input => $expected) {
1830
      $edit = array(
1831
        'default_logo' => FALSE,
1832
        'logo_path' => $input,
1833
      );
1834
      $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
1835
      $this->assertNoText('The custom logo path is invalid.');
1836
      $this->assertFieldByName('logo_path', $expected['form']);
1837

    
1838
      // Verify the actual 'src' attribute of the logo being output.
1839
      $this->drupalGet('');
1840
      $elements = $this->xpath('//*[@id=:id]/img', array(':id' => 'logo'));
1841
      $this->assertEqual((string) $elements[0]['src'], $expected['src']);
1842
    }
1843

    
1844
    $unsupported_paths = array(
1845
      // Stream wrapper URI to non-existing file.
1846
      'public://whatever.png',
1847
      'private://whatever.png',
1848
      'temporary://whatever.png',
1849
      // Bogus stream wrapper URIs.
1850
      'public:/whatever.png',
1851
      '://whatever.png',
1852
      ':whatever.png',
1853
      'public://',
1854
      // Relative path within the public filesystem to non-existing file.
1855
      'whatever.png',
1856
      // Relative path to non-existing file in public filesystem.
1857
      variable_get('file_public_path', conf_path() . '/files') . '/whatever.png',
1858
      // Semi-absolute path to non-existing file in public filesystem.
1859
      '/' . variable_get('file_public_path', conf_path() . '/files') . '/whatever.png',
1860
      // Relative path to arbitrary non-existing file.
1861
      'misc/whatever.png',
1862
      // Semi-absolute path to arbitrary non-existing file.
1863
      '/misc/whatever.png',
1864
      // Absolute paths to any local file (even if it exists).
1865
      drupal_realpath($file->uri),
1866
    );
1867
    $this->drupalGet('admin/appearance/settings');
1868
    foreach ($unsupported_paths as $path) {
1869
      $edit = array(
1870
        'default_logo' => FALSE,
1871
        'logo_path' => $path,
1872
      );
1873
      $this->drupalPost(NULL, $edit, t('Save configuration'));
1874
      $this->assertText('The custom logo path is invalid.');
1875
    }
1876

    
1877
    // Upload a file to use for the logo.
1878
    $edit = array(
1879
      'default_logo' => FALSE,
1880
      'logo_path' => '',
1881
      'files[logo_upload]' => drupal_realpath($file->uri),
1882
    );
1883
    $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
1884

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

    
1888
    $this->drupalGet('');
1889
    $elements = $this->xpath('//*[@id=:id]/img', array(':id' => 'logo'));
1890
    $this->assertEqual($elements[0]['src'], file_create_url($uploaded_filename));
1891
  }
1892

    
1893
  /**
1894
   * Test the administration theme functionality.
1895
   */
1896
  function testAdministrationTheme() {
1897
    theme_enable(array('stark'));
1898
    variable_set('theme_default', 'stark');
1899
    // Enable an administration theme and show it on the node admin pages.
1900
    $edit = array(
1901
      'admin_theme' => 'seven',
1902
      'node_admin_theme' => TRUE,
1903
    );
1904
    $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
1905

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

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

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

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

    
1918
    // Disable the admin theme on the node admin pages.
1919
    $edit = array(
1920
      'node_admin_theme' => FALSE,
1921
    );
1922
    $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
1923

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

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

    
1930
    // Reset to the default theme settings.
1931
    variable_set('theme_default', 'bartik');
1932
    $edit = array(
1933
      'admin_theme' => '0',
1934
      'node_admin_theme' => FALSE,
1935
    );
1936
    $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
1937

    
1938
    $this->drupalGet('admin');
1939
    $this->assertRaw('themes/bartik', 'Site default theme used on administration page.');
1940

    
1941
    $this->drupalGet('node/add');
1942
    $this->assertRaw('themes/bartik', 'Site default theme used on the add content page.');
1943
  }
1944

    
1945
  /**
1946
   * Test switching the default theme.
1947
   */
1948
  function testSwitchDefaultTheme() {
1949
    // Enable "stark" and set it as the default theme.
1950
    theme_enable(array('stark'));
1951
    $this->drupalGet('admin/appearance');
1952
    $this->clickLink(t('Set default'), 1);
1953
    $this->assertTrue(variable_get('theme_default', '') == 'stark', 'Site default theme switched successfully.');
1954

    
1955
    // Test the default theme on the secondary links (blocks admin page).
1956
    $this->drupalGet('admin/structure/block');
1957
    $this->assertText('Stark(' . t('active tab') . ')', 'Default local task on blocks admin page is the default theme.');
1958
    // Switch back to Bartik and test again to test that the menu cache is cleared.
1959
    $this->drupalGet('admin/appearance');
1960
    $this->clickLink(t('Set default'), 0);
1961
    $this->drupalGet('admin/structure/block');
1962
    $this->assertText('Bartik(' . t('active tab') . ')', 'Default local task on blocks admin page has changed.');
1963
  }
1964
}
1965

    
1966

    
1967
/**
1968
 * Test the basic queue functionality.
1969
 */
1970
class QueueTestCase extends DrupalWebTestCase {
1971
  public static function getInfo() {
1972
    return array(
1973
      'name' => 'Queue functionality',
1974
      'description' => 'Queues and dequeues a set of items to check the basic queue functionality.',
1975
      'group' => 'System',
1976
    );
1977
  }
1978

    
1979
  /**
1980
   * Queues and dequeues a set of items to check the basic queue functionality.
1981
   */
1982
  function testQueue() {
1983
    // Create two queues.
1984
    $queue1 = DrupalQueue::get($this->randomName());
1985
    $queue1->createQueue();
1986
    $queue2 = DrupalQueue::get($this->randomName());
1987
    $queue2->createQueue();
1988

    
1989
    // Create four items.
1990
    $data = array();
1991
    for ($i = 0; $i < 4; $i++) {
1992
      $data[] = array($this->randomName() => $this->randomName());
1993
    }
1994

    
1995
    // Queue items 1 and 2 in the queue1.
1996
    $queue1->createItem($data[0]);
1997
    $queue1->createItem($data[1]);
1998

    
1999
    // Retrieve two items from queue1.
2000
    $items = array();
2001
    $new_items = array();
2002

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

    
2006
    $items[] = $item = $queue1->claimItem();
2007
    $new_items[] = $item->data;
2008

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

    
2012
    // Add two more items.
2013
    $queue1->createItem($data[2]);
2014
    $queue1->createItem($data[3]);
2015

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

    
2019
    $items[] = $item = $queue1->claimItem();
2020
    $new_items[] = $item->data;
2021

    
2022
    $items[] = $item = $queue1->claimItem();
2023
    $new_items[] = $item->data;
2024

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

    
2029
    // There should be no duplicate items.
2030
    $this->assertEqual($this->queueScore($new_items, $new_items), 4, 'Four items matched');
2031

    
2032
    // Delete all items from queue1.
2033
    foreach ($items as $item) {
2034
      $queue1->deleteItem($item);
2035
    }
2036

    
2037
    // Check that both queues are empty.
2038
    $this->assertFalse($queue1->numberOfItems(), 'Queue 1 is empty');
2039
    $this->assertFalse($queue2->numberOfItems(), 'Queue 2 is empty');
2040
  }
2041

    
2042
  /**
2043
   * This function returns the number of equal items in two arrays.
2044
   */
2045
  function queueScore($items, $new_items) {
2046
    $score = 0;
2047
    foreach ($items as $item) {
2048
      foreach ($new_items as $new_item) {
2049
        if ($item === $new_item) {
2050
          $score++;
2051
        }
2052
      }
2053
    }
2054
    return $score;
2055
  }
2056
}
2057

    
2058
/**
2059
 * Test token replacement in strings.
2060
 */
2061
class TokenReplaceTestCase extends DrupalWebTestCase {
2062
  public static function getInfo() {
2063
    return array(
2064
      'name' => 'Token replacement',
2065
      'description' => 'Generates text using placeholders for dummy content to check token replacement.',
2066
      'group' => 'System',
2067
    );
2068
  }
2069

    
2070
  /**
2071
   * Creates a user and a node, then tests the tokens generated from them.
2072
   */
2073
  function testTokenReplacement() {
2074
    // Create the initial objects.
2075
    $account = $this->drupalCreateUser();
2076
    $node = $this->drupalCreateNode(array('uid' => $account->uid));
2077
    $node->title = '<blink>Blinking Text</blink>';
2078
    global $user, $language;
2079

    
2080
    $source  = '[node:title]';         // Title of the node we passed in
2081
    $source .= '[node:author:name]';   // Node author's name
2082
    $source .= '[node:created:since]'; // Time since the node was created
2083
    $source .= '[current-user:name]';  // Current user's name
2084
    $source .= '[date:short]';         // Short date format of REQUEST_TIME
2085
    $source .= '[user:name]';          // No user passed in, should be untouched
2086
    $source .= '[bogus:token]';        // Non-existent token
2087

    
2088
    $target  = check_plain($node->title);
2089
    $target .= check_plain($account->name);
2090
    $target .= format_interval(REQUEST_TIME - $node->created, 2, $language->language);
2091
    $target .= check_plain($user->name);
2092
    $target .= format_date(REQUEST_TIME, 'short', '', NULL, $language->language);
2093

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

    
2098
    // Test without using the clear parameter (non-existent token untouched).
2099
    $target .= '[user:name]';
2100
    $target .= '[bogus:token]';
2101
    $result = token_replace($source, array('node' => $node), array('language' => $language));
2102
    $this->assertEqual($target, $result, 'Valid tokens replaced while invalid tokens ignored.');
2103

    
2104
    // Check that the results of token_generate are sanitized properly. This does NOT
2105
    // test the cleanliness of every token -- just that the $sanitize flag is being
2106
    // passed properly through the call stack and being handled correctly by a 'known'
2107
    // token, [node:title].
2108
    $raw_tokens = array('title' => '[node:title]');
2109
    $generated = token_generate('node', $raw_tokens, array('node' => $node));
2110
    $this->assertEqual($generated['[node:title]'], check_plain($node->title), 'Token sanitized.');
2111

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

    
2115
    // Test token replacement when the string contains no tokens.
2116
    $this->assertEqual(token_replace('No tokens here.'), 'No tokens here.');
2117
  }
2118

    
2119
  /**
2120
   * Test whether token-replacement works in various contexts.
2121
   */
2122
  function testSystemTokenRecognition() {
2123
    global $language;
2124

    
2125
    // Generate prefixes and suffixes for the token context.
2126
    $tests = array(
2127
      array('prefix' => 'this is the ', 'suffix' => ' site'),
2128
      array('prefix' => 'this is the', 'suffix' => 'site'),
2129
      array('prefix' => '[', 'suffix' => ']'),
2130
      array('prefix' => '', 'suffix' => ']]]'),
2131
      array('prefix' => '[[[', 'suffix' => ''),
2132
      array('prefix' => ':[:', 'suffix' => '--]'),
2133
      array('prefix' => '-[-', 'suffix' => ':]:'),
2134
      array('prefix' => '[:', 'suffix' => ']'),
2135
      array('prefix' => '[site:', 'suffix' => ':name]'),
2136
      array('prefix' => '[site:', 'suffix' => ']'),
2137
    );
2138

    
2139
    // Check if the token is recognized in each of the contexts.
2140
    foreach ($tests as $test) {
2141
      $input = $test['prefix'] . '[site:name]' . $test['suffix'];
2142
      $expected = $test['prefix'] . 'Drupal' . $test['suffix'];
2143
      $output = token_replace($input, array(), array('language' => $language));
2144
      $this->assertTrue($output == $expected, format_string('Token recognized in string %string', array('%string' => $input)));
2145
    }
2146
  }
2147

    
2148
  /**
2149
   * Tests the generation of all system site information tokens.
2150
   */
2151
  function testSystemSiteTokenReplacement() {
2152
    global $language;
2153
    $url_options = array(
2154
      'absolute' => TRUE,
2155
      'language' => $language,
2156
    );
2157

    
2158
    // Set a few site variables.
2159
    variable_set('site_name', '<strong>Drupal<strong>');
2160
    variable_set('site_slogan', '<blink>Slogan</blink>');
2161

    
2162
    // Generate and test sanitized tokens.
2163
    $tests = array();
2164
    $tests['[site:name]'] = check_plain(variable_get('site_name', 'Drupal'));
2165
    $tests['[site:slogan]'] = check_plain(variable_get('site_slogan', ''));
2166
    $tests['[site:mail]'] = 'simpletest@example.com';
2167
    $tests['[site:url]'] = url('<front>', $url_options);
2168
    $tests['[site:url-brief]'] = preg_replace(array('!^https?://!', '!/$!'), '', url('<front>', $url_options));
2169
    $tests['[site:login-url]'] = url('user', $url_options);
2170

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

    
2174
    foreach ($tests as $input => $expected) {
2175
      $output = token_replace($input, array(), array('language' => $language));
2176
      $this->assertEqual($output, $expected, format_string('Sanitized system site information token %token replaced.', array('%token' => $input)));
2177
    }
2178

    
2179
    // Generate and test unsanitized tokens.
2180
    $tests['[site:name]'] = variable_get('site_name', 'Drupal');
2181
    $tests['[site:slogan]'] = variable_get('site_slogan', '');
2182

    
2183
    foreach ($tests as $input => $expected) {
2184
      $output = token_replace($input, array(), array('language' => $language, 'sanitize' => FALSE));
2185
      $this->assertEqual($output, $expected, format_string('Unsanitized system site information token %token replaced.', array('%token' => $input)));
2186
    }
2187
  }
2188

    
2189
  /**
2190
   * Tests the generation of all system date tokens.
2191
   */
2192
  function testSystemDateTokenReplacement() {
2193
    global $language;
2194

    
2195
    // Set time to one hour before request.
2196
    $date = REQUEST_TIME - 3600;
2197

    
2198
    // Generate and test tokens.
2199
    $tests = array();
2200
    $tests['[date:short]'] = format_date($date, 'short', '', NULL, $language->language);
2201
    $tests['[date:medium]'] = format_date($date, 'medium', '', NULL, $language->language);
2202
    $tests['[date:long]'] = format_date($date, 'long', '', NULL, $language->language);
2203
    $tests['[date:custom:m/j/Y]'] = format_date($date, 'custom', 'm/j/Y', NULL, $language->language);
2204
    $tests['[date:since]'] = format_interval((REQUEST_TIME - $date), 2, $language->language);
2205
    $tests['[date:raw]'] = filter_xss($date);
2206

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

    
2210
    foreach ($tests as $input => $expected) {
2211
      $output = token_replace($input, array('date' => $date), array('language' => $language));
2212
      $this->assertEqual($output, $expected, format_string('Date token %token replaced.', array('%token' => $input)));
2213
    }
2214
  }
2215
}
2216

    
2217
class InfoFileParserTestCase extends DrupalUnitTestCase {
2218
  public static function getInfo() {
2219
    return array(
2220
      'name' => 'Info file format parser',
2221
      'description' => 'Tests proper parsing of a .info file formatted string.',
2222
      'group' => 'System',
2223
    );
2224
  }
2225

    
2226
  /**
2227
   * Test drupal_parse_info_format().
2228
   */
2229
  function testDrupalParseInfoFormat() {
2230
    $config = '
2231
simple = Value
2232
quoted = " Value"
2233
multiline = "Value
2234
  Value"
2235
array[] = Value1
2236
array[] = Value2
2237
array_assoc[a] = Value1
2238
array_assoc[b] = Value2
2239
array_deep[][][] = Value
2240
array_deep_assoc[a][b][c] = Value
2241
array_space[a b] = Value';
2242

    
2243
    $expected = array(
2244
      'simple' => 'Value',
2245
      'quoted' => ' Value',
2246
      'multiline' => "Value\n  Value",
2247
      'array' => array(
2248
        0 => 'Value1',
2249
        1 => 'Value2',
2250
      ),
2251
      'array_assoc' => array(
2252
        'a' => 'Value1',
2253
        'b' => 'Value2',
2254
      ),
2255
      'array_deep' => array(
2256
        0 => array(
2257
          0 => array(
2258
            0 => 'Value',
2259
          ),
2260
        ),
2261
      ),
2262
      'array_deep_assoc' => array(
2263
        'a' => array(
2264
          'b' => array(
2265
            'c' => 'Value',
2266
          ),
2267
        ),
2268
      ),
2269
      'array_space' => array(
2270
        'a b' => 'Value',
2271
      ),
2272
    );
2273

    
2274
    $parsed = drupal_parse_info_format($config);
2275

    
2276
    $this->assertEqual($parsed['simple'], $expected['simple'], 'Set a simple value.');
2277
    $this->assertEqual($parsed['quoted'], $expected['quoted'], 'Set a simple value in quotes.');
2278
    $this->assertEqual($parsed['multiline'], $expected['multiline'], 'Set a multiline value.');
2279
    $this->assertEqual($parsed['array'], $expected['array'], 'Set a simple array.');
2280
    $this->assertEqual($parsed['array_assoc'], $expected['array_assoc'], 'Set an associative array.');
2281
    $this->assertEqual($parsed['array_deep'], $expected['array_deep'], 'Set a nested array.');
2282
    $this->assertEqual($parsed['array_deep_assoc'], $expected['array_deep_assoc'], 'Set a nested associative array.');
2283
    $this->assertEqual($parsed['array_space'], $expected['array_space'], 'Set an array with a whitespace in the key.');
2284
    $this->assertEqual($parsed, $expected, 'Entire parsed .info string and expected array are identical.');
2285
  }
2286
}
2287

    
2288
/**
2289
 * Tests the effectiveness of hook_system_info_alter().
2290
 */
2291
class SystemInfoAlterTestCase extends DrupalWebTestCase {
2292
  public static function getInfo() {
2293
    return array(
2294
      'name' => 'System info alter',
2295
      'description' => 'Tests the effectiveness of hook_system_info_alter().',
2296
      'group' => 'System',
2297
    );
2298
  }
2299

    
2300
  /**
2301
   * Tests that {system}.info is rebuilt after a module that implements
2302
   * hook_system_info_alter() is enabled. Also tests if core *_list() functions
2303
   * return freshly altered info.
2304
   */
2305
  function testSystemInfoAlter() {
2306
    // Enable our test module. Flush all caches, which we assert is the only
2307
    // thing necessary to use the rebuilt {system}.info.
2308
    module_enable(array('module_test'), FALSE);
2309
    drupal_flush_all_caches();
2310
    $this->assertTrue(module_exists('module_test'), 'Test module is enabled.');
2311

    
2312
    $info = $this->getSystemInfo('seven', 'theme');
2313
    $this->assertTrue(isset($info['regions']['test_region']), 'Altered theme info was added to {system}.info.');
2314
    $seven_regions = system_region_list('seven');
2315
    $this->assertTrue(isset($seven_regions['test_region']), 'Altered theme info was returned by system_region_list().');
2316
    $system_list_themes = system_list('theme');
2317
    $info = $system_list_themes['seven']->info;
2318
    $this->assertTrue(isset($info['regions']['test_region']), 'Altered theme info was returned by system_list().');
2319
    $list_themes = list_themes();
2320
    $this->assertTrue(isset($list_themes['seven']->info['regions']['test_region']), 'Altered theme info was returned by list_themes().');
2321

    
2322
    // Disable the module and verify that {system}.info is rebuilt without it.
2323
    module_disable(array('module_test'), FALSE);
2324
    drupal_flush_all_caches();
2325
    $this->assertFalse(module_exists('module_test'), 'Test module is disabled.');
2326

    
2327
    $info = $this->getSystemInfo('seven', 'theme');
2328
    $this->assertFalse(isset($info['regions']['test_region']), 'Altered theme info was removed from {system}.info.');
2329
    $seven_regions = system_region_list('seven');
2330
    $this->assertFalse(isset($seven_regions['test_region']), 'Altered theme info was not returned by system_region_list().');
2331
    $system_list_themes = system_list('theme');
2332
    $info = $system_list_themes['seven']->info;
2333
    $this->assertFalse(isset($info['regions']['test_region']), 'Altered theme info was not returned by system_list().');
2334
    $list_themes = list_themes();
2335
    $this->assertFalse(isset($list_themes['seven']->info['regions']['test_region']), 'Altered theme info was not returned by list_themes().');
2336
  }
2337

    
2338
  /**
2339
   * Returns the info array as it is stored in {system}.
2340
   *
2341
   * @param $name
2342
   *   The name of the record in {system}.
2343
   * @param $type
2344
   *   The type of record in {system}.
2345
   *
2346
   * @return
2347
   *   Array of info, or FALSE if the record is not found.
2348
   */
2349
  function getSystemInfo($name, $type) {
2350
    $raw_info = db_query("SELECT info FROM {system} WHERE name = :name AND type = :type", array(':name' => $name, ':type' => $type))->fetchField();
2351
    return $raw_info ? unserialize($raw_info) : FALSE;
2352
  }
2353
}
2354

    
2355
/**
2356
 * Tests for the update system functionality.
2357
 */
2358
class UpdateScriptFunctionalTest extends DrupalWebTestCase {
2359
  private $update_url;
2360
  private $update_user;
2361

    
2362
  public static function getInfo() {
2363
    return array(
2364
      'name' => 'Update functionality',
2365
      'description' => 'Tests the update script access and functionality.',
2366
      'group' => 'System',
2367
    );
2368
  }
2369

    
2370
  function setUp() {
2371
    parent::setUp('update_script_test');
2372
    $this->update_url = $GLOBALS['base_url'] . '/update.php';
2373
    $this->update_user = $this->drupalCreateUser(array('administer software updates'));
2374
  }
2375

    
2376
  /**
2377
   * Tests that there are no pending updates for the first test method.
2378
   */
2379
  function testNoPendingUpdates() {
2380
    // Ensure that for the first test method in a class, there are no pending
2381
    // updates. This tests a drupal_get_schema_versions() bug that previously
2382
    // led to the wrong schema version being recorded for the initial install
2383
    // of a child site during automated testing.
2384
    $this->drupalLogin($this->update_user);
2385
    $this->drupalGet($this->update_url, array('external' => TRUE));
2386
    $this->drupalPost(NULL, array(), t('Continue'));
2387
    $this->assertText(t('No pending updates.'), 'End of update process was reached.');
2388
  }
2389

    
2390
  /**
2391
   * Tests access to the update script.
2392
   */
2393
  function testUpdateAccess() {
2394
    // Try accessing update.php without the proper permission.
2395
    $regular_user = $this->drupalCreateUser();
2396
    $this->drupalLogin($regular_user);
2397
    $this->drupalGet($this->update_url, array('external' => TRUE));
2398
    $this->assertResponse(403);
2399

    
2400
    // Try accessing update.php as an anonymous user.
2401
    $this->drupalLogout();
2402
    $this->drupalGet($this->update_url, array('external' => TRUE));
2403
    $this->assertResponse(403);
2404

    
2405
    // Access the update page with the proper permission.
2406
    $this->drupalLogin($this->update_user);
2407
    $this->drupalGet($this->update_url, array('external' => TRUE));
2408
    $this->assertResponse(200);
2409

    
2410
    // Access the update page as user 1.
2411
    $user1 = user_load(1);
2412
    $user1->pass_raw = user_password();
2413
    require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
2414
    $user1->pass = user_hash_password(trim($user1->pass_raw));
2415
    db_query("UPDATE {users} SET pass = :pass WHERE uid = :uid", array(':pass' => $user1->pass, ':uid' => $user1->uid));
2416
    $this->drupalLogin($user1);
2417
    $this->drupalGet($this->update_url, array('external' => TRUE));
2418
    $this->assertResponse(200);
2419
  }
2420

    
2421
  /**
2422
   * Tests that requirements warnings and errors are correctly displayed.
2423
   */
2424
  function testRequirements() {
2425
    $this->drupalLogin($this->update_user);
2426

    
2427
    // If there are no requirements warnings or errors, we expect to be able to
2428
    // go through the update process uninterrupted.
2429
    $this->drupalGet($this->update_url, array('external' => TRUE));
2430
    $this->drupalPost(NULL, array(), t('Continue'));
2431
    $this->assertText(t('No pending updates.'), 'End of update process was reached.');
2432
    // Confirm that all caches were cleared.
2433
    $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared when there were no requirements warnings or errors.');
2434

    
2435
    // If there is a requirements warning, we expect it to be initially
2436
    // displayed, but clicking the link to proceed should allow us to go
2437
    // through the rest of the update process uninterrupted.
2438

    
2439
    // First, run this test with pending updates to make sure they can be run
2440
    // successfully.
2441
    variable_set('update_script_test_requirement_type', REQUIREMENT_WARNING);
2442
    drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
2443
    $this->drupalGet($this->update_url, array('external' => TRUE));
2444
    $this->assertText('This is a requirements warning provided by the update_script_test module.');
2445
    $this->clickLink('try again');
2446
    $this->assertNoText('This is a requirements warning provided by the update_script_test module.');
2447
    $this->drupalPost(NULL, array(), t('Continue'));
2448
    $this->drupalPost(NULL, array(), t('Apply pending updates'));
2449
    $this->assertText(t('The update_script_test_update_7000() update was executed successfully.'), 'End of update process was reached.');
2450
    // Confirm that all caches were cleared.
2451
    $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared after resolving a requirements warning and applying updates.');
2452

    
2453
    // Now try again without pending updates to make sure that works too.
2454
    $this->drupalGet($this->update_url, array('external' => TRUE));
2455
    $this->assertText('This is a requirements warning provided by the update_script_test module.');
2456
    $this->clickLink('try again');
2457
    $this->assertNoText('This is a requirements warning provided by the update_script_test module.');
2458
    $this->drupalPost(NULL, array(), t('Continue'));
2459
    $this->assertText(t('No pending updates.'), 'End of update process was reached.');
2460
    // Confirm that all caches were cleared.
2461
    $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared after applying updates and re-running the script.');
2462

    
2463
    // If there is a requirements error, it should be displayed even after
2464
    // clicking the link to proceed (since the problem that triggered the error
2465
    // has not been fixed).
2466
    variable_set('update_script_test_requirement_type', REQUIREMENT_ERROR);
2467
    $this->drupalGet($this->update_url, array('external' => TRUE));
2468
    $this->assertText('This is a requirements error provided by the update_script_test module.');
2469
    $this->clickLink('try again');
2470
    $this->assertText('This is a requirements error provided by the update_script_test module.');
2471

    
2472
    // Check if the optional 'value' key displays without a notice.
2473
    variable_set('update_script_test_requirement_type', REQUIREMENT_INFO);
2474
    $this->drupalGet($this->update_url, array('external' => TRUE));
2475
    $this->assertText('This is a requirements info provided by the update_script_test module.');
2476
    $this->assertNoText('Notice: Undefined index: value in theme_status_report()');
2477
  }
2478

    
2479
  /**
2480
   * Tests the effect of using the update script on the theme system.
2481
   */
2482
  function testThemeSystem() {
2483
    // Since visiting update.php triggers a rebuild of the theme system from an
2484
    // unusual maintenance mode environment, we check that this rebuild did not
2485
    // put any incorrect information about the themes into the database.
2486
    $original_theme_data = db_query("SELECT * FROM {system} WHERE type = 'theme' ORDER BY name")->fetchAll();
2487
    $this->drupalLogin($this->update_user);
2488
    $this->drupalGet($this->update_url, array('external' => TRUE));
2489
    $final_theme_data = db_query("SELECT * FROM {system} WHERE type = 'theme' ORDER BY name")->fetchAll();
2490
    $this->assertEqual($original_theme_data, $final_theme_data, 'Visiting update.php does not alter the information about themes stored in the database.');
2491
  }
2492

    
2493
  /**
2494
   * Tests update.php when there are no updates to apply.
2495
   */
2496
  function testNoUpdateFunctionality() {
2497
    // Click through update.php with 'administer software updates' permission.
2498
    $this->drupalLogin($this->update_user);
2499
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
2500
    $this->assertText(t('No pending updates.'));
2501
    $this->assertNoLink('Administration pages');
2502
    $this->clickLink('Front page');
2503
    $this->assertResponse(200);
2504

    
2505
    // Click through update.php with 'access administration pages' permission.
2506
    $admin_user = $this->drupalCreateUser(array('administer software updates', 'access administration pages'));
2507
    $this->drupalLogin($admin_user);
2508
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
2509
    $this->assertText(t('No pending updates.'));
2510
    $this->clickLink('Administration pages');
2511
    $this->assertResponse(200);
2512
  }
2513

    
2514
  /**
2515
   * Tests update.php after performing a successful update.
2516
   */
2517
  function testSuccessfulUpdateFunctionality() {
2518
    drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
2519
    // Click through update.php with 'administer software updates' permission.
2520
    $this->drupalLogin($this->update_user);
2521
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
2522
    $this->drupalPost(NULL, array(), t('Apply pending updates'));
2523
    $this->assertText('Updates were attempted.');
2524
    $this->assertLink('site');
2525
    $this->assertNoLink('Administration pages');
2526
    $this->assertNoLink('logged');
2527
    $this->clickLink('Front page');
2528
    $this->assertResponse(200);
2529

    
2530
    drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
2531
    // Click through update.php with 'access administration pages' and
2532
    // 'access site reports' permissions.
2533
    $admin_user = $this->drupalCreateUser(array('administer software updates', 'access administration pages', 'access site reports'));
2534
    $this->drupalLogin($admin_user);
2535
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
2536
    $this->drupalPost(NULL, array(), t('Apply pending updates'));
2537
    $this->assertText('Updates were attempted.');
2538
    $this->assertLink('logged');
2539
    $this->clickLink('Administration pages');
2540
    $this->assertResponse(200);
2541
  }
2542
}
2543

    
2544
/**
2545
 * Functional tests for the flood control mechanism.
2546
 */
2547
class FloodFunctionalTest extends DrupalWebTestCase {
2548
  public static function getInfo() {
2549
    return array(
2550
      'name' => 'Flood control mechanism',
2551
      'description' => 'Functional tests for the flood control mechanism.',
2552
      'group' => 'System',
2553
    );
2554
  }
2555

    
2556
  /**
2557
   * Test flood control mechanism clean-up.
2558
   */
2559
  function testCleanUp() {
2560
    $threshold = 1;
2561
    $window_expired = -1;
2562
    $name = 'flood_test_cleanup';
2563

    
2564
    // Register expired event.
2565
    flood_register_event($name, $window_expired);
2566
    // Verify event is not allowed.
2567
    $this->assertFalse(flood_is_allowed($name, $threshold));
2568
    // Run cron and verify event is now allowed.
2569
    $this->cronRun();
2570
    $this->assertTrue(flood_is_allowed($name, $threshold));
2571

    
2572
    // Register unexpired event.
2573
    flood_register_event($name);
2574
    // Verify event is not allowed.
2575
    $this->assertFalse(flood_is_allowed($name, $threshold));
2576
    // Run cron and verify event is still not allowed.
2577
    $this->cronRun();
2578
    $this->assertFalse(flood_is_allowed($name, $threshold));
2579
  }
2580
}
2581

    
2582
/**
2583
 * Test HTTP file downloading capability.
2584
 */
2585
class RetrieveFileTestCase extends DrupalWebTestCase {
2586
  public static function getInfo() {
2587
    return array(
2588
      'name' => 'HTTP file retrieval',
2589
      'description' => 'Checks HTTP file fetching and error handling.',
2590
      'group' => 'System',
2591
    );
2592
  }
2593

    
2594
  /**
2595
   * Invokes system_retrieve_file() in several scenarios.
2596
   */
2597
  function testFileRetrieving() {
2598
    // Test 404 handling by trying to fetch a randomly named file.
2599
    drupal_mkdir($sourcedir = 'public://' . $this->randomName());
2600
    $filename = 'Файл для тестирования ' . $this->randomName();
2601
    $url = file_create_url($sourcedir . '/' . $filename);
2602
    $retrieved_file = system_retrieve_file($url);
2603
    $this->assertFalse($retrieved_file, 'Non-existent file not fetched.');
2604

    
2605
    // Actually create that file, download it via HTTP and test the returned path.
2606
    file_put_contents($sourcedir . '/' . $filename, 'testing');
2607
    $retrieved_file = system_retrieve_file($url);
2608

    
2609
    // URLs could not contains characters outside the ASCII set so $filename
2610
    // has to be encoded.
2611
    $encoded_filename = rawurlencode($filename);
2612

    
2613
    $this->assertEqual($retrieved_file, 'public://' . $encoded_filename, 'Sane path for downloaded file returned (public:// scheme).');
2614
    $this->assertTrue(is_file($retrieved_file), 'Downloaded file does exist (public:// scheme).');
2615
    $this->assertEqual(filesize($retrieved_file), 7, 'File size of downloaded file is correct (public:// scheme).');
2616
    file_unmanaged_delete($retrieved_file);
2617

    
2618
    // Test downloading file to a different location.
2619
    drupal_mkdir($targetdir = 'temporary://' . $this->randomName());
2620
    $retrieved_file = system_retrieve_file($url, $targetdir);
2621
    $this->assertEqual($retrieved_file, "$targetdir/$encoded_filename", 'Sane path for downloaded file returned (temporary:// scheme).');
2622
    $this->assertTrue(is_file($retrieved_file), 'Downloaded file does exist (temporary:// scheme).');
2623
    $this->assertEqual(filesize($retrieved_file), 7, 'File size of downloaded file is correct (temporary:// scheme).');
2624
    file_unmanaged_delete($retrieved_file);
2625

    
2626
    file_unmanaged_delete_recursive($sourcedir);
2627
    file_unmanaged_delete_recursive($targetdir);
2628
  }
2629
}
2630

    
2631
/**
2632
 * Functional tests shutdown functions.
2633
 */
2634
class ShutdownFunctionsTest extends DrupalWebTestCase {
2635
  public static function getInfo() {
2636
    return array(
2637
      'name' => 'Shutdown functions',
2638
      'description' => 'Functional tests for shutdown functions',
2639
      'group' => 'System',
2640
    );
2641
  }
2642

    
2643
  function setUp() {
2644
    parent::setUp('system_test');
2645
  }
2646

    
2647
  /**
2648
   * Test shutdown functions.
2649
   */
2650
  function testShutdownFunctions() {
2651
    $arg1 = $this->randomName();
2652
    $arg2 = $this->randomName();
2653
    $this->drupalGet('system-test/shutdown-functions/' . $arg1 . '/' . $arg2);
2654
    $this->assertText(t('First shutdown function, arg1 : @arg1, arg2: @arg2', array('@arg1' => $arg1, '@arg2' => $arg2)));
2655
    $this->assertText(t('Second shutdown function, arg1 : @arg1, arg2: @arg2', array('@arg1' => $arg1, '@arg2' => $arg2)));
2656

    
2657
    // Make sure exceptions displayed through _drupal_render_exception_safe()
2658
    // are correctly escaped.
2659
    $this->assertRaw('Drupal is &amp;lt;blink&amp;gt;awesome&amp;lt;/blink&amp;gt;.');
2660
  }
2661
}
2662

    
2663
/**
2664
 * Tests administrative overview pages.
2665
 */
2666
class SystemAdminTestCase extends DrupalWebTestCase {
2667
  public static function getInfo() {
2668
    return array(
2669
      'name' => 'Administrative pages',
2670
      'description' => 'Tests output on administrative pages and compact mode functionality.',
2671
      'group' => 'System',
2672
    );
2673
  }
2674

    
2675
  function setUp() {
2676
    // testAdminPages() requires Locale module.
2677
    parent::setUp(array('locale'));
2678

    
2679
    // Create an administrator with all permissions, as well as a regular user
2680
    // who can only access administration pages and perform some Locale module
2681
    // administrative tasks, but not all of them.
2682
    $this->admin_user = $this->drupalCreateUser(array_keys(module_invoke_all('permission')));
2683
    $this->web_user = $this->drupalCreateUser(array(
2684
      'access administration pages',
2685
      'translate interface',
2686
    ));
2687
    $this->drupalLogin($this->admin_user);
2688
  }
2689

    
2690
  /**
2691
   * Tests output on administrative listing pages.
2692
   */
2693
  function testAdminPages() {
2694
    // Go to Administration.
2695
    $this->drupalGet('admin');
2696

    
2697
    // Verify that all visible, top-level administration links are listed on
2698
    // the main administration page.
2699
    foreach (menu_get_router() as $path => $item) {
2700
      if (strpos($path, 'admin/') === 0 && ($item['type'] & MENU_VISIBLE_IN_TREE) && $item['_number_parts'] == 2) {
2701
        $this->assertLink($item['title']);
2702
        $this->assertLinkByHref($path);
2703
        $this->assertText($item['description']);
2704
      }
2705
    }
2706

    
2707
    // For each administrative listing page on which the Locale module appears,
2708
    // verify that there are links to the module's primary configuration pages,
2709
    // but no links to its individual sub-configuration pages. Also verify that
2710
    // a user with access to only some Locale module administration pages only
2711
    // sees links to the pages they have access to.
2712
    $admin_list_pages = array(
2713
      'admin/index',
2714
      'admin/config',
2715
      'admin/config/regional',
2716
    );
2717

    
2718
    foreach ($admin_list_pages as $page) {
2719
      // For the administrator, verify that there are links to Locale's primary
2720
      // configuration pages, but no links to individual sub-configuration
2721
      // pages.
2722
      $this->drupalLogin($this->admin_user);
2723
      $this->drupalGet($page);
2724
      $this->assertLinkByHref('admin/config');
2725
      $this->assertLinkByHref('admin/config/regional/settings');
2726
      $this->assertLinkByHref('admin/config/regional/date-time');
2727
      $this->assertLinkByHref('admin/config/regional/language');
2728
      $this->assertNoLinkByHref('admin/config/regional/language/configure/session');
2729
      $this->assertNoLinkByHref('admin/config/regional/language/configure/url');
2730
      $this->assertLinkByHref('admin/config/regional/translate');
2731
      // On admin/index only, the administrator should also see a "Configure
2732
      // permissions" link for the Locale module.
2733
      if ($page == 'admin/index') {
2734
        $this->assertLinkByHref("admin/people/permissions#module-locale");
2735
      }
2736

    
2737
      // For a less privileged user, verify that there are no links to Locale's
2738
      // primary configuration pages, but a link to the translate page exists.
2739
      $this->drupalLogin($this->web_user);
2740
      $this->drupalGet($page);
2741
      $this->assertLinkByHref('admin/config');
2742
      $this->assertNoLinkByHref('admin/config/regional/settings');
2743
      $this->assertNoLinkByHref('admin/config/regional/date-time');
2744
      $this->assertNoLinkByHref('admin/config/regional/language');
2745
      $this->assertNoLinkByHref('admin/config/regional/language/configure/session');
2746
      $this->assertNoLinkByHref('admin/config/regional/language/configure/url');
2747
      $this->assertLinkByHref('admin/config/regional/translate');
2748
      // This user cannot configure permissions, so even on admin/index should
2749
      // not see a "Configure permissions" link for the Locale module.
2750
      if ($page == 'admin/index') {
2751
        $this->assertNoLinkByHref("admin/people/permissions#module-locale");
2752
      }
2753
    }
2754
  }
2755

    
2756
  /**
2757
   * Test compact mode.
2758
   */
2759
  function testCompactMode() {
2760
    $this->drupalGet('admin/compact/on');
2761
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode turns on.');
2762
    $this->drupalGet('admin/compact/on');
2763
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode remains on after a repeat call.');
2764
    $this->drupalGet('');
2765
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode persists on new requests.');
2766

    
2767
    $this->drupalGet('admin/compact/off');
2768
    $this->assertEqual($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'deleted', 'Compact mode turns off.');
2769
    $this->drupalGet('admin/compact/off');
2770
    $this->assertEqual($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'deleted', 'Compact mode remains off after a repeat call.');
2771
    $this->drupalGet('');
2772
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode persists on new requests.');
2773
  }
2774
}
2775

    
2776
/**
2777
 * Tests authorize.php and related hooks.
2778
 */
2779
class SystemAuthorizeCase extends DrupalWebTestCase {
2780
  public static function getInfo() {
2781
    return array(
2782
      'name' => 'Authorize API',
2783
      'description' => 'Tests the authorize.php script and related API.',
2784
      'group' => 'System',
2785
    );
2786
  }
2787

    
2788
  function setUp() {
2789
    parent::setUp(array('system_test'));
2790

    
2791
    variable_set('allow_authorize_operations', TRUE);
2792

    
2793
    // Create an administrator user.
2794
    $this->admin_user = $this->drupalCreateUser(array('administer software updates'));
2795
    $this->drupalLogin($this->admin_user);
2796
  }
2797

    
2798
  /**
2799
   * Helper function to initialize authorize.php and load it via drupalGet().
2800
   *
2801
   * Initializing authorize.php needs to happen in the child Drupal
2802
   * installation, not the parent. So, we visit a menu callback provided by
2803
   * system_test.module which calls system_authorized_init() to initialize the
2804
   * $_SESSION inside the test site, not the framework site. This callback
2805
   * redirects to authorize.php when it's done initializing.
2806
   *
2807
   * @see system_authorized_init().
2808
   */
2809
  function drupalGetAuthorizePHP($page_title = 'system-test-auth') {
2810
    $this->drupalGet('system-test/authorize-init/' . $page_title);
2811
  }
2812

    
2813
  /**
2814
   * Tests the FileTransfer hooks
2815
   */
2816
  function testFileTransferHooks() {
2817
    $page_title = $this->randomName(16);
2818
    $this->drupalGetAuthorizePHP($page_title);
2819
    $this->assertTitle(strtr('@title | Drupal', array('@title' => $page_title)), 'authorize.php page title is correct.');
2820
    $this->assertNoText('It appears you have reached this page in error.');
2821
    $this->assertText('To continue, provide your server connection details');
2822
    // Make sure we see the new connection method added by system_test.
2823
    $this->assertRaw('System Test FileTransfer');
2824
    // Make sure the settings form callback works.
2825
    $this->assertText('System Test Username');
2826
  }
2827
}
2828

    
2829
/**
2830
 * Test the handling of requests containing 'index.php'.
2831
 */
2832
class SystemIndexPhpTest extends DrupalWebTestCase {
2833
  public static function getInfo() {
2834
    return array(
2835
      'name' => 'Index.php handling',
2836
      'description' => "Test the handling of requests containing 'index.php'.",
2837
      'group' => 'System',
2838
    );
2839
  }
2840

    
2841
  function setUp() {
2842
    parent::setUp();
2843
  }
2844

    
2845
  /**
2846
   * Test index.php handling.
2847
   */
2848
  function testIndexPhpHandling() {
2849
    $index_php = $GLOBALS['base_url'] . '/index.php';
2850

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

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

    
2857
    $this->drupalGet($index_php .'/user', array('external' => TRUE));
2858
    $this->assertResponse(404, "Make sure index.php/user returns a 'page not found'.");
2859
  }
2860
}
2861

    
2862
/**
2863
 * Test token replacement in strings.
2864
 */
2865
class TokenScanTest extends DrupalWebTestCase {
2866

    
2867
  public static function getInfo() {
2868
    return array(
2869
      'name' => 'Token scanning',
2870
      'description' => 'Scan token-like patterns in a dummy text to check token scanning.',
2871
      'group' => 'System',
2872
    );
2873
  }
2874

    
2875
  /**
2876
   * Scans dummy text, then tests the output.
2877
   */
2878
  function testTokenScan() {
2879
    // Define text with valid and not valid, fake and existing token-like
2880
    // strings.
2881
    $text = 'First a [valid:simple], but dummy token, and a dummy [valid:token with: spaces].';
2882
    $text .= 'Then a [not valid:token].';
2883
    $text .= 'Last an existing token: [node:author:name].';
2884
    $token_wannabes = token_scan($text);
2885

    
2886
    $this->assertTrue(isset($token_wannabes['valid']['simple']), 'A simple valid token has been matched.');
2887
    $this->assertTrue(isset($token_wannabes['valid']['token with: spaces']), 'A valid token with space characters in the token name has been matched.');
2888
    $this->assertFalse(isset($token_wannabes['not valid']), 'An invalid token with spaces in the token type has not been matched.');
2889
    $this->assertTrue(isset($token_wannabes['node']), 'An existing valid token has been matched.');
2890
  }
2891
}
2892

    
2893
/**
2894
 * Test case for drupal_valid_token().
2895
 */
2896
class SystemValidTokenTest extends DrupalUnitTestCase {
2897

    
2898
  /**
2899
   * Flag to indicate whether PHP error reportings should be asserted.
2900
   *
2901
   * @var bool
2902
   */
2903
  protected $assertErrors = TRUE;
2904

    
2905
  public static function getInfo() {
2906
    return array(
2907
      'name' => 'Token validation',
2908
      'description' => 'Test the security token validation.',
2909
      'group' => 'System',
2910
    );
2911
  }
2912

    
2913
  /**
2914
   * Tests invalid invocations of drupal_valid_token() that must return FALSE.
2915
   */
2916
  public function testTokenValidation() {
2917
    // The following checks will throw PHP notices, so we disable error
2918
    // assertions.
2919
    $this->assertErrors = FALSE;
2920
    $this->assertFalse(drupal_valid_token(NULL, new stdClass()), 'Token NULL, value object returns FALSE.');
2921
    $this->assertFalse(drupal_valid_token(0, array()), 'Token 0, value array returns FALSE.');
2922
    $this->assertFalse(drupal_valid_token('', array()), "Token '', value array returns FALSE.");
2923
    $this->assertFalse('' === drupal_get_token(array()), 'Token generation does not return an empty string on invalid parameters.');
2924
    $this->assertErrors = TRUE;
2925

    
2926
    $this->assertFalse(drupal_valid_token(TRUE, 'foo'), 'Token TRUE, value foo returns FALSE.');
2927
    $this->assertFalse(drupal_valid_token(0, 'foo'), 'Token 0, value foo returns FALSE.');
2928
  }
2929

    
2930
  /**
2931
   * Overrides DrupalTestCase::errorHandler().
2932
   */
2933
  public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
2934
    if ($this->assertErrors) {
2935
      return parent::errorHandler($severity, $message, $file, $line);
2936
    }
2937
    return TRUE;
2938
  }
2939
}
2940

    
2941
/**
2942
 * Tests drupal_set_message() and related functions.
2943
 */
2944
class DrupalSetMessageTest extends DrupalWebTestCase {
2945

    
2946
  public static function getInfo() {
2947
    return array(
2948
      'name' => 'Messages',
2949
      'description' => 'Tests that messages can be displayed using drupal_set_message().',
2950
      'group' => 'System',
2951
    );
2952
  }
2953

    
2954
  function setUp() {
2955
    parent::setUp('system_test');
2956
  }
2957

    
2958
  /**
2959
   * Tests setting messages and removing one before it is displayed.
2960
   */
2961
  function testSetRemoveMessages() {
2962
    // The page at system-test/drupal-set-message sets two messages and then
2963
    // removes the first before it is displayed.
2964
    $this->drupalGet('system-test/drupal-set-message');
2965
    $this->assertNoText('First message (removed).');
2966
    $this->assertText('Second message (not removed).');
2967
  }
2968
}
2969

    
2970
/**
2971
 * Tests confirm form destinations.
2972
 */
2973
class ConfirmFormTest extends DrupalWebTestCase {
2974
  protected $admin_user;
2975

    
2976
  public static function getInfo() {
2977
    return array(
2978
      'name' => 'Confirm form',
2979
      'description' => 'Tests that the confirm form does not use external destinations.',
2980
      'group' => 'System',
2981
    );
2982
  }
2983

    
2984
  function setUp() {
2985
    parent::setUp();
2986

    
2987
    $this->admin_user = $this->drupalCreateUser(array('administer users'));
2988
    $this->drupalLogin($this->admin_user);
2989
  }
2990

    
2991
  /**
2992
   * Tests that the confirm form does not use external destinations.
2993
   */
2994
  function testConfirmForm() {
2995
    $this->drupalGet('user/1/cancel');
2996
    $this->assertCancelLinkUrl(url('user/1'));
2997
    $this->drupalGet('user/1/cancel', array('query' => array('destination' => 'node')));
2998
    $this->assertCancelLinkUrl(url('node'));
2999
    $this->drupalGet('user/1/cancel', array('query' => array('destination' => 'http://example.com')));
3000
    $this->assertCancelLinkUrl(url('user/1'));
3001
  }
3002

    
3003
  /**
3004
   * Asserts that a cancel link is present pointing to the provided URL.
3005
   */
3006
  function assertCancelLinkUrl($url, $message = '', $group = 'Other') {
3007
    $links = $this->xpath('//a[normalize-space(text())=:label and @href=:url]', array(':label' => t('Cancel'), ':url' => $url));
3008
    $message = ($message ? $message : format_string('Cancel link with url %url found.', array('%url' => $url)));
3009
    return $this->assertTrue(isset($links[0]), $message, $group);
3010
  }
3011
}