Projet

Général

Profil

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

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

1
<?php
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
495
  }
496

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

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

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

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

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

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

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

    
561
/**
562
 * Test module dependency on specific versions.
563
 */
564
class ModuleVersionTestCase extends ModuleTestCase {
565
  public static function getInfo() {
566
    return array(
567
      'name' => 'Module versions',
568
      'description' => 'Check module version dependencies.',
569
      'group' => 'Module',
570
    );
571
  }
572

    
573
  function setUp() {
574
    parent::setUp('module_test');
575
  }
576

    
577
  /**
578
   * Test version dependencies.
579
   */
580
  function testModuleVersions() {
581
    $dependencies = array(
582
      // Alternating between being compatible and incompatible with 7.x-2.4-beta3.
583
      // The first is always a compatible.
584
      'common_test',
585
      // Branch incompatibility.
586
      'common_test (1.x)',
587
      // Branch compatibility.
588
      'common_test (2.x)',
589
      // Another branch incompatibility.
590
      'common_test (>2.x)',
591
      // Another branch compatibility.
592
      'common_test (<=2.x)',
593
      // Another branch incompatibility.
594
      'common_test (<2.x)',
595
      // Another branch compatibility.
596
      'common_test (>=2.x)',
597
      // Nonsense, misses a dash. Incompatible with everything.
598
      'common_test (=7.x2.x, >=2.4)',
599
      // Core version is optional. Compatible.
600
      'common_test (=7.x-2.x, >=2.4-alpha2)',
601
      // Test !=, explicitly incompatible.
602
      'common_test (=2.x, !=2.4-beta3)',
603
      // Three operations. Compatible.
604
      'common_test (=2.x, !=2.3, <2.5)',
605
      // Testing extra version. Incompatible.
606
      'common_test (<=2.4-beta2)',
607
      // Testing extra version. Compatible.
608
      'common_test (>2.4-beta2)',
609
      // Testing extra version. Incompatible.
610
      'common_test (>2.4-rc0)',
611
    );
612
    variable_set('dependencies', $dependencies);
613
    $n = count($dependencies);
614
    for ($i = 0; $i < $n; $i++) {
615
      $this->drupalGet('admin/modules');
616
      $checkbox = $this->xpath('//input[@id="edit-modules-testing-module-test-enable"]');
617
      $this->assertEqual(!empty($checkbox[0]['disabled']), $i % 2, $dependencies[$i]);
618
    }
619
  }
620
}
621

    
622
/**
623
 * Test required modules functionality.
624
 */
625
class ModuleRequiredTestCase extends ModuleTestCase {
626
  public static function getInfo() {
627
    return array(
628
      'name' => 'Required modules',
629
      'description' => 'Attempt disabling of required modules.',
630
      'group' => 'Module',
631
    );
632
  }
633

    
634
  /**
635
   * Assert that core required modules cannot be disabled.
636
   */
637
  function testDisableRequired() {
638
    $module_info = system_get_info('module');
639
    $this->drupalGet('admin/modules');
640
    foreach ($module_info as $module => $info) {
641
      // Check to make sure the checkbox for each required module is disabled
642
      // and checked (or absent from the page if the module is also hidden).
643
      if (!empty($info['required'])) {
644
        $field_name = "modules[{$info['package']}][$module][enable]";
645
        if (empty($info['hidden'])) {
646
          $this->assertFieldByXPath("//input[@name='$field_name' and @disabled='disabled' and @checked='checked']", '', format_string('Field @name was disabled and checked.', array('@name' => $field_name)));
647
        }
648
        else {
649
          $this->assertNoFieldByName($field_name);
650
        }
651
      }
652
    }
653
  }
654
}
655

    
656
class IPAddressBlockingTestCase extends DrupalWebTestCase {
657
  protected $blocking_user;
658

    
659
  /**
660
   * Implement getInfo().
661
   */
662
  public static function getInfo() {
663
    return array(
664
      'name' => 'IP address blocking',
665
      'description' => 'Test IP address blocking.',
666
      'group' => 'System'
667
    );
668
  }
669

    
670
  /**
671
   * Implement setUp().
672
   */
673
  function setUp() {
674
    parent::setUp();
675

    
676
    // Create user.
677
    $this->blocking_user = $this->drupalCreateUser(array('block IP addresses'));
678
    $this->drupalLogin($this->blocking_user);
679
  }
680

    
681
  /**
682
   * Test a variety of user input to confirm correct validation and saving of data.
683
   */
684
  function testIPAddressValidation() {
685
    $this->drupalGet('admin/config/people/ip-blocking');
686

    
687
    // Block a valid IP address.
688
    $edit = array();
689
    $edit['ip'] = '192.168.1.1';
690
    $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
691
    $ip = db_query("SELECT iid from {blocked_ips} WHERE ip = :ip", array(':ip' => $edit['ip']))->fetchField();
692
    $this->assertTrue($ip, t('IP address found in database.'));
693
    $this->assertRaw(t('The IP address %ip has been blocked.', array('%ip' => $edit['ip'])), t('IP address was blocked.'));
694

    
695
    // Try to block an IP address that's already blocked.
696
    $edit = array();
697
    $edit['ip'] = '192.168.1.1';
698
    $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
699
    $this->assertText(t('This IP address is already blocked.'));
700

    
701
    // Try to block a reserved IP address.
702
    $edit = array();
703
    $edit['ip'] = '255.255.255.255';
704
    $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
705
    $this->assertText(t('Enter a valid IP address.'));
706

    
707
    // Try to block a reserved IP address.
708
    $edit = array();
709
    $edit['ip'] = 'test.example.com';
710
    $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
711
    $this->assertText(t('Enter a valid IP address.'));
712

    
713
    // Submit an empty form.
714
    $edit = array();
715
    $edit['ip'] = '';
716
    $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
717
    $this->assertText(t('Enter a valid IP address.'));
718

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

    
726
    // Submit your own IP address. This fails, although it works when testing manually.
727
     // TODO: on some systems this test fails due to a bug or inconsistency in cURL.
728
     // $edit = array();
729
     // $edit['ip'] = ip_address();
730
     // $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Save'));
731
     // $this->assertText(t('You may not block your own IP address.'));
732
  }
733
}
734

    
735
class CronRunTestCase extends DrupalWebTestCase {
736
  /**
737
   * Implement getInfo().
738
   */
739
  public static function getInfo() {
740
    return array(
741
      'name' => 'Cron run',
742
      'description' => 'Test cron run.',
743
      'group' => 'System'
744
    );
745
  }
746

    
747
  function setUp() {
748
    parent::setUp(array('common_test', 'common_test_cron_helper'));
749
  }
750

    
751
  /**
752
   * Test cron runs.
753
   */
754
  function testCronRun() {
755
    global $base_url;
756

    
757
    // Run cron anonymously without any cron key.
758
    $this->drupalGet($base_url . '/cron.php', array('external' => TRUE));
759
    $this->assertResponse(403);
760

    
761
    // Run cron anonymously with a random cron key.
762
    $key = $this->randomName(16);
763
    $this->drupalGet($base_url . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => $key)));
764
    $this->assertResponse(403);
765

    
766
    // Run cron anonymously with the valid cron key.
767
    $key = variable_get('cron_key', 'drupal');
768
    $this->drupalGet($base_url . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => $key)));
769
    $this->assertResponse(200);
770
  }
771

    
772
  /**
773
   * Ensure that the automatic cron run feature is working.
774
   *
775
   * In these tests we do not use REQUEST_TIME to track start time, because we
776
   * need the exact time when cron is triggered.
777
   */
778
  function testAutomaticCron() {
779
    // Ensure cron does not run when the cron threshold is enabled and was
780
    // not passed.
781
    $cron_last = time();
782
    $cron_safe_threshold = 100;
783
    variable_set('cron_last', $cron_last);
784
    variable_set('cron_safe_threshold', $cron_safe_threshold);
785
    $this->drupalGet('');
786
    $this->assertTrue($cron_last == variable_get('cron_last', NULL), 'Cron does not run when the cron threshold is not passed.');
787

    
788
    // Test if cron runs when the cron threshold was passed.
789
    $cron_last = time() - 200;
790
    variable_set('cron_last', $cron_last);
791
    $this->drupalGet('');
792
    sleep(1);
793
    $this->assertTrue($cron_last < variable_get('cron_last', NULL), 'Cron runs when the cron threshold is passed.');
794

    
795
    // Disable the cron threshold through the interface.
796
    $admin_user = $this->drupalCreateUser(array('administer site configuration'));
797
    $this->drupalLogin($admin_user);
798
    $this->drupalPost('admin/config/system/cron', array('cron_safe_threshold' => 0), t('Save configuration'));
799
    $this->assertText(t('The configuration options have been saved.'));
800
    $this->drupalLogout();
801

    
802
    // Test if cron does not run when the cron threshold is disabled.
803
    $cron_last = time() - 200;
804
    variable_set('cron_last', $cron_last);
805
    $this->drupalGet('');
806
    $this->assertTrue($cron_last == variable_get('cron_last', NULL), 'Cron does not run when the cron threshold is disabled.');
807
  }
808

    
809
  /**
810
   * Ensure that temporary files are removed.
811
   *
812
   * Create files for all the possible combinations of age and status. We are
813
   * using UPDATE statements rather than file_save() because it would set the
814
   * timestamp.
815
   */
816
  function testTempFileCleanup() {
817
    // Temporary file that is older than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
818
    $temp_old = file_save_data('');
819
    db_update('file_managed')
820
      ->fields(array(
821
        'status' => 0,
822
        'timestamp' => 1,
823
      ))
824
      ->condition('fid', $temp_old->fid)
825
      ->execute();
826
    $this->assertTrue(file_exists($temp_old->uri), 'Old temp file was created correctly.');
827

    
828
    // Temporary file that is less than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
829
    $temp_new = file_save_data('');
830
    db_update('file_managed')
831
      ->fields(array('status' => 0))
832
      ->condition('fid', $temp_new->fid)
833
      ->execute();
834
    $this->assertTrue(file_exists($temp_new->uri), 'New temp file was created correctly.');
835

    
836
    // Permanent file that is older than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
837
    $perm_old = file_save_data('');
838
    db_update('file_managed')
839
      ->fields(array('timestamp' => 1))
840
      ->condition('fid', $temp_old->fid)
841
      ->execute();
842
    $this->assertTrue(file_exists($perm_old->uri), 'Old permanent file was created correctly.');
843

    
844
    // Permanent file that is newer than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
845
    $perm_new = file_save_data('');
846
    $this->assertTrue(file_exists($perm_new->uri), 'New permanent file was created correctly.');
847

    
848
    // Run cron and then ensure that only the old, temp file was deleted.
849
    $this->cronRun();
850
    $this->assertFalse(file_exists($temp_old->uri), 'Old temp file was correctly removed.');
851
    $this->assertTrue(file_exists($temp_new->uri), 'New temp file was correctly ignored.');
852
    $this->assertTrue(file_exists($perm_old->uri), 'Old permanent file was correctly ignored.');
853
    $this->assertTrue(file_exists($perm_new->uri), 'New permanent file was correctly ignored.');
854
  }
855

    
856
  /**
857
   * Make sure exceptions thrown on hook_cron() don't affect other modules.
858
   */
859
  function testCronExceptions() {
860
    variable_del('common_test_cron');
861
    // The common_test module throws an exception. If it isn't caught, the tests
862
    // won't finish successfully.
863
    // The common_test_cron_helper module sets the 'common_test_cron' variable.
864
    $this->cronRun();
865
    $result = variable_get('common_test_cron');
866
    $this->assertEqual($result, 'success', 'Cron correctly handles exceptions thrown during hook_cron() invocations.');
867
  }
868
}
869

    
870
class AdminMetaTagTestCase extends DrupalWebTestCase {
871
  /**
872
   * Implement getInfo().
873
   */
874
  public static function getInfo() {
875
    return array(
876
      'name' => 'Fingerprinting meta tag',
877
      'description' => 'Confirm that the fingerprinting meta tag appears as expected.',
878
      'group' => 'System'
879
    );
880
  }
881

    
882
  /**
883
   * Verify that the meta tag HTML is generated correctly.
884
   */
885
  public function testMetaTag() {
886
    list($version, ) = explode('.', VERSION);
887
    $string = '<meta name="Generator" content="Drupal ' . $version . ' (http://drupal.org)" />';
888
    $this->drupalGet('node');
889
    $this->assertRaw($string, 'Fingerprinting meta tag generated correctly.', 'System');
890
  }
891
}
892

    
893
/**
894
 * Tests custom access denied functionality.
895
 */
896
class AccessDeniedTestCase extends DrupalWebTestCase {
897
  protected $admin_user;
898

    
899
  public static function getInfo() {
900
    return array(
901
      'name' => '403 functionality',
902
      'description' => 'Tests page access denied functionality, including custom 403 pages.',
903
      'group' => 'System'
904
    );
905
  }
906

    
907
  function setUp() {
908
    parent::setUp();
909

    
910
    // Create an administrative user.
911
    $this->admin_user = $this->drupalCreateUser(array('access administration pages', 'administer site configuration', 'administer blocks'));
912
  }
913

    
914
  function testAccessDenied() {
915
    $this->drupalGet('admin');
916
    $this->assertText(t('Access denied'), 'Found the default 403 page');
917
    $this->assertResponse(403);
918

    
919
    $this->drupalLogin($this->admin_user);
920
    $edit = array(
921
      'title' => $this->randomName(10),
922
      'body' => array(LANGUAGE_NONE => array(array('value' => $this->randomName(100)))),
923
    );
924
    $node = $this->drupalCreateNode($edit);
925

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

    
929
    $this->drupalLogout();
930
    $this->drupalGet('admin');
931
    $this->assertText($node->title, 'Found the custom 403 page');
932

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

    
936
    $this->drupalGet('admin');
937
    $this->assertText($node->title, 'Found the custom 403 page');
938
    $this->assertText(t('User login'), 'Blocks are shown on the custom 403 page');
939

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

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

    
947
    $this->drupalGet('admin');
948
    $this->assertText(t('Access denied'), 'Found the default 403 page');
949
    $this->assertResponse(403);
950
    $this->assertText(t('User login'), 'Blocks are shown on the default 403 page');
951

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

    
957
    // Check that we can log in from the 403 page.
958
    $this->drupalLogout();
959
    $edit = array(
960
      'name' => $this->admin_user->name,
961
      'pass' => $this->admin_user->pass_raw,
962
    );
963
    $this->drupalPost('admin/config/system/site-information', $edit, t('Log in'));
964

    
965
    // Check that we're still on the same page.
966
    $this->assertText(t('Site information'));
967
  }
968
}
969

    
970
class PageNotFoundTestCase extends DrupalWebTestCase {
971
  protected $admin_user;
972

    
973
  /**
974
   * Implement getInfo().
975
   */
976
  public static function getInfo() {
977
    return array(
978
      'name' => '404 functionality',
979
      'description' => "Tests page not found functionality, including custom 404 pages.",
980
      'group' => 'System'
981
    );
982
  }
983

    
984
  /**
985
   * Implement setUp().
986
   */
987
  function setUp() {
988
    parent::setUp();
989

    
990
    // Create an administrative user.
991
    $this->admin_user = $this->drupalCreateUser(array('administer site configuration'));
992
    $this->drupalLogin($this->admin_user);
993
  }
994

    
995
  function testPageNotFound() {
996
    $this->drupalGet($this->randomName(10));
997
    $this->assertText(t('Page not found'), 'Found the default 404 page');
998

    
999
    $edit = array(
1000
      'title' => $this->randomName(10),
1001
      'body' => array(LANGUAGE_NONE => array(array('value' => $this->randomName(100)))),
1002
    );
1003
    $node = $this->drupalCreateNode($edit);
1004

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

    
1008
    $this->drupalGet($this->randomName(10));
1009
    $this->assertText($node->title, 'Found the custom 404 page');
1010
  }
1011
}
1012

    
1013
/**
1014
 * Tests site maintenance functionality.
1015
 */
1016
class SiteMaintenanceTestCase extends DrupalWebTestCase {
1017
  protected $admin_user;
1018

    
1019
  public static function getInfo() {
1020
    return array(
1021
      'name' => 'Site maintenance mode functionality',
1022
      'description' => 'Test access to site while in maintenance mode.',
1023
      'group' => 'System',
1024
    );
1025
  }
1026

    
1027
  function setUp() {
1028
    parent::setUp();
1029

    
1030
    // Create a user allowed to access site in maintenance mode.
1031
    $this->user = $this->drupalCreateUser(array('access site in maintenance mode'));
1032
    // Create an administrative user.
1033
    $this->admin_user = $this->drupalCreateUser(array('administer site configuration', 'access site in maintenance mode'));
1034
    $this->drupalLogin($this->admin_user);
1035
  }
1036

    
1037
  /**
1038
   * Verify site maintenance mode functionality.
1039
   */
1040
  function testSiteMaintenance() {
1041
    // Turn on maintenance mode.
1042
    $edit = array(
1043
      'maintenance_mode' => 1,
1044
    );
1045
    $this->drupalPost('admin/config/development/maintenance', $edit, t('Save configuration'));
1046

    
1047
    $admin_message = t('Operating in maintenance mode. <a href="@url">Go online.</a>', array('@url' => url('admin/config/development/maintenance')));
1048
    $user_message = t('Operating in maintenance mode.');
1049
    $offline_message = t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal')));
1050

    
1051
    $this->drupalGet('');
1052
    $this->assertRaw($admin_message, 'Found the site maintenance mode message.');
1053

    
1054
    // Logout and verify that offline message is displayed.
1055
    $this->drupalLogout();
1056
    $this->drupalGet('');
1057
    $this->assertText($offline_message);
1058
    $this->drupalGet('node');
1059
    $this->assertText($offline_message);
1060
    $this->drupalGet('user/register');
1061
    $this->assertText($offline_message);
1062

    
1063
    // Verify that user is able to log in.
1064
    $this->drupalGet('user');
1065
    $this->assertNoText($offline_message);
1066
    $this->drupalGet('user/login');
1067
    $this->assertNoText($offline_message);
1068

    
1069
    // Log in user and verify that maintenance mode message is displayed
1070
    // directly after login.
1071
    $edit = array(
1072
      'name' => $this->user->name,
1073
      'pass' => $this->user->pass_raw,
1074
    );
1075
    $this->drupalPost(NULL, $edit, t('Log in'));
1076
    $this->assertText($user_message);
1077

    
1078
    // Log in administrative user and configure a custom site offline message.
1079
    $this->drupalLogout();
1080
    $this->drupalLogin($this->admin_user);
1081
    $this->drupalGet('admin/config/development/maintenance');
1082
    $this->assertNoRaw($admin_message, 'Site maintenance mode message not displayed.');
1083

    
1084
    $offline_message = 'Sorry, not online.';
1085
    $edit = array(
1086
      'maintenance_mode_message' => $offline_message,
1087
    );
1088
    $this->drupalPost(NULL, $edit, t('Save configuration'));
1089

    
1090
    // Logout and verify that custom site offline message is displayed.
1091
    $this->drupalLogout();
1092
    $this->drupalGet('');
1093
    $this->assertRaw($offline_message, 'Found the site offline message.');
1094

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

    
1099
    // Submit password reset form.
1100
    $edit = array(
1101
      'name' => $this->user->name,
1102
    );
1103
    $this->drupalPost('user/password', $edit, t('E-mail new password'));
1104
    $mails = $this->drupalGetMails();
1105
    $start = strpos($mails[0]['body'], 'user/reset/'. $this->user->uid);
1106
    $path = substr($mails[0]['body'], $start, 66 + strlen($this->user->uid));
1107

    
1108
    // Log in with temporary login link.
1109
    $this->drupalPost($path, array(), t('Log in'));
1110
    $this->assertText($user_message);
1111
  }
1112
}
1113

    
1114
/**
1115
 * Tests generic date and time handling capabilities of Drupal.
1116
 */
1117
class DateTimeFunctionalTest extends DrupalWebTestCase {
1118
  public static function getInfo() {
1119
    return array(
1120
      'name' => 'Date and time',
1121
      'description' => 'Configure date and time settings. Test date formatting and time zone handling, including daylight saving time.',
1122
      'group' => 'System',
1123
    );
1124
  }
1125

    
1126
  function setUp() {
1127
    parent::setUp(array('locale'));
1128

    
1129
    // Create admin user and log in admin user.
1130
    $this->admin_user = $this->drupalCreateUser(array('administer site configuration'));
1131
    $this->drupalLogin($this->admin_user);
1132
  }
1133

    
1134

    
1135
  /**
1136
   * Test time zones and DST handling.
1137
   */
1138
  function testTimeZoneHandling() {
1139
    // Setup date/time settings for Honolulu time.
1140
    variable_set('date_default_timezone', 'Pacific/Honolulu');
1141
    variable_set('configurable_timezones', 0);
1142
    variable_set('date_format_medium', 'Y-m-d H:i:s O');
1143

    
1144
    // Create some nodes with different authored-on dates.
1145
    $date1 = '2007-01-31 21:00:00 -1000';
1146
    $date2 = '2007-07-31 21:00:00 -1000';
1147
    $node1 = $this->drupalCreateNode(array('created' => strtotime($date1), 'type' => 'article'));
1148
    $node2 = $this->drupalCreateNode(array('created' => strtotime($date2), 'type' => 'article'));
1149

    
1150
    // Confirm date format and time zone.
1151
    $this->drupalGet("node/$node1->nid");
1152
    $this->assertText('2007-01-31 21:00:00 -1000', 'Date should be identical, with GMT offset of -10 hours.');
1153
    $this->drupalGet("node/$node2->nid");
1154
    $this->assertText('2007-07-31 21:00:00 -1000', 'Date should be identical, with GMT offset of -10 hours.');
1155

    
1156
    // Set time zone to Los Angeles time.
1157
    variable_set('date_default_timezone', 'America/Los_Angeles');
1158

    
1159
    // Confirm date format and time zone.
1160
    $this->drupalGet("node/$node1->nid");
1161
    $this->assertText('2007-01-31 23:00:00 -0800', 'Date should be two hours ahead, with GMT offset of -8 hours.');
1162
    $this->drupalGet("node/$node2->nid");
1163
    $this->assertText('2007-08-01 00:00:00 -0700', 'Date should be three hours ahead, with GMT offset of -7 hours.');
1164
  }
1165

    
1166
  /**
1167
   * Test date type configuration.
1168
   */
1169
  function testDateTypeConfiguration() {
1170
    // Confirm system date types appear.
1171
    $this->drupalGet('admin/config/regional/date-time');
1172
    $this->assertText(t('Medium'), 'System date types appear in date type list.');
1173
    $this->assertNoRaw('href="/admin/config/regional/date-time/types/medium/delete"', 'No delete link appear for system date types.');
1174

    
1175
    // Add custom date type.
1176
    $this->clickLink(t('Add date type'));
1177
    $date_type = strtolower($this->randomName(8));
1178
    $machine_name = 'machine_' . $date_type;
1179
    $date_format = 'd.m.Y - H:i';
1180
    $edit = array(
1181
      'date_type' => $date_type,
1182
      'machine_name' => $machine_name,
1183
      'date_format' => $date_format,
1184
    );
1185
    $this->drupalPost('admin/config/regional/date-time/types/add', $edit, t('Add date type'));
1186
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time', array('absolute' => TRUE)), 'Correct page redirection.');
1187
    $this->assertText(t('New date type added successfully.'), 'Date type added confirmation message appears.');
1188
    $this->assertText($date_type, 'Custom date type appears in the date type list.');
1189
    $this->assertText(t('delete'), 'Delete link for custom date type appears.');
1190

    
1191
    // Delete custom date type.
1192
    $this->clickLink(t('delete'));
1193
    $this->drupalPost('admin/config/regional/date-time/types/' . $machine_name . '/delete', array(), t('Remove'));
1194
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time', array('absolute' => TRUE)), 'Correct page redirection.');
1195
    $this->assertText(t('Removed date type ' . $date_type), 'Custom date type removed.');
1196
  }
1197

    
1198
  /**
1199
   * Test date format configuration.
1200
   */
1201
  function testDateFormatConfiguration() {
1202
    // Confirm 'no custom date formats available' message appears.
1203
    $this->drupalGet('admin/config/regional/date-time/formats');
1204
    $this->assertText(t('No custom date formats available.'), 'No custom date formats message appears.');
1205

    
1206
    // Add custom date format.
1207
    $this->clickLink(t('Add format'));
1208
    $edit = array(
1209
      'date_format' => 'Y',
1210
    );
1211
    $this->drupalPost('admin/config/regional/date-time/formats/add', $edit, t('Add format'));
1212
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE)), 'Correct page redirection.');
1213
    $this->assertNoText(t('No custom date formats available.'), 'No custom date formats message does not appear.');
1214
    $this->assertText(t('Custom date format added.'), 'Custom date format added.');
1215

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

    
1220
    // Edit custom date format.
1221
    $this->drupalGet('admin/config/regional/date-time/formats');
1222
    $this->clickLink(t('edit'));
1223
    $edit = array(
1224
      'date_format' => 'Y m',
1225
    );
1226
    $this->drupalPost($this->getUrl(), $edit, t('Save format'));
1227
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE)), 'Correct page redirection.');
1228
    $this->assertText(t('Custom date format updated.'), 'Custom date format successfully updated.');
1229

    
1230
    // Delete custom date format.
1231
    $this->clickLink(t('delete'));
1232
    $this->drupalPost($this->getUrl(), array(), t('Remove'));
1233
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE)), 'Correct page redirection.');
1234
    $this->assertText(t('Removed date format'), 'Custom date format removed successfully.');
1235
  }
1236

    
1237
  /**
1238
   * Test if the date formats are stored properly.
1239
   */
1240
  function testDateFormatStorage() {
1241
    $date_format = array(
1242
      'type' => 'short',
1243
      'format' => 'dmYHis',
1244
      'locked' => 0,
1245
      'is_new' => 1,
1246
    );
1247
    system_date_format_save($date_format);
1248

    
1249
    $format = db_select('date_formats', 'df')
1250
      ->fields('df', array('format'))
1251
      ->condition('type', 'short')
1252
      ->condition('format', 'dmYHis')
1253
      ->execute()
1254
      ->fetchField();
1255
    $this->verbose($format);
1256
    $this->assertEqual('dmYHis', $format, 'Unlocalized date format resides in general table.');
1257

    
1258
    $format = db_select('date_format_locale', 'dfl')
1259
      ->fields('dfl', array('format'))
1260
      ->condition('type', 'short')
1261
      ->condition('format', 'dmYHis')
1262
      ->execute()
1263
      ->fetchField();
1264
    $this->assertFalse($format, 'Unlocalized date format resides not in localized table.');
1265

    
1266
    // Enable German language
1267
    locale_add_language('de', NULL, NULL, LANGUAGE_LTR, '', '', TRUE, 'en');
1268

    
1269
    $date_format = array(
1270
      'type' => 'short',
1271
      'format' => 'YMDHis',
1272
      'locales' => array('de', 'tr'),
1273
      'locked' => 0,
1274
      'is_new' => 1,
1275
    );
1276
    system_date_format_save($date_format);
1277

    
1278
    $format = db_select('date_format_locale', 'dfl')
1279
      ->fields('dfl', array('format'))
1280
      ->condition('type', 'short')
1281
      ->condition('format', 'YMDHis')
1282
      ->condition('language', 'de')
1283
      ->execute()
1284
      ->fetchField();
1285
    $this->assertEqual('YMDHis', $format, 'Localized date format resides in localized table.');
1286

    
1287
    $format = db_select('date_formats', 'df')
1288
      ->fields('df', array('format'))
1289
      ->condition('type', 'short')
1290
      ->condition('format', 'YMDHis')
1291
      ->execute()
1292
      ->fetchField();
1293
    $this->assertEqual('YMDHis', $format, 'Localized date format resides in general table too.');
1294

    
1295
    $format = db_select('date_format_locale', 'dfl')
1296
      ->fields('dfl', array('format'))
1297
      ->condition('type', 'short')
1298
      ->condition('format', 'YMDHis')
1299
      ->condition('language', 'tr')
1300
      ->execute()
1301
      ->fetchColumn();
1302
    $this->assertFalse($format, 'Localized date format for disabled language is ignored.');
1303
  }
1304
}
1305

    
1306
class PageTitleFiltering extends DrupalWebTestCase {
1307
  protected $content_user;
1308
  protected $saved_title;
1309

    
1310
  /**
1311
   * Implement getInfo().
1312
   */
1313
  public static function getInfo() {
1314
    return array(
1315
      'name' => 'HTML in page titles',
1316
      'description' => 'Tests correct handling or conversion by drupal_set_title() and drupal_get_title() and checks the correct escaping of site name and slogan.',
1317
      'group' => 'System'
1318
    );
1319
  }
1320

    
1321
  /**
1322
   * Implement setUp().
1323
   */
1324
  function setUp() {
1325
    parent::setUp();
1326

    
1327
    $this->content_user = $this->drupalCreateUser(array('create page content', 'access content', 'administer themes', 'administer site configuration'));
1328
    $this->drupalLogin($this->content_user);
1329
    $this->saved_title = drupal_get_title();
1330
  }
1331

    
1332
  /**
1333
   * Reset page title.
1334
   */
1335
  function tearDown() {
1336
    // Restore the page title.
1337
    drupal_set_title($this->saved_title, PASS_THROUGH);
1338

    
1339
    parent::tearDown();
1340
  }
1341

    
1342
  /**
1343
   * Tests the handling of HTML by drupal_set_title() and drupal_get_title()
1344
   */
1345
  function testTitleTags() {
1346
    $title = "string with <em>HTML</em>";
1347
    // drupal_set_title's $filter is CHECK_PLAIN by default, so the title should be
1348
    // returned with check_plain().
1349
    drupal_set_title($title, CHECK_PLAIN);
1350
    $this->assertTrue(strpos(drupal_get_title(), '<em>') === FALSE, 'Tags in title converted to entities when $output is CHECK_PLAIN.');
1351
    // drupal_set_title's $filter is passed as PASS_THROUGH, so the title should be
1352
    // returned with HTML.
1353
    drupal_set_title($title, PASS_THROUGH);
1354
    $this->assertTrue(strpos(drupal_get_title(), '<em>') !== FALSE, 'Tags in title are not converted to entities when $output is PASS_THROUGH.');
1355
    // Generate node content.
1356
    $langcode = LANGUAGE_NONE;
1357
    $edit = array(
1358
      "title" => '!SimpleTest! ' . $title . $this->randomName(20),
1359
      "body[$langcode][0][value]" => '!SimpleTest! test body' . $this->randomName(200),
1360
    );
1361
    // Create the node with HTML in the title.
1362
    $this->drupalPost('node/add/page', $edit, t('Save'));
1363

    
1364
    $node = $this->drupalGetNodeByTitle($edit["title"]);
1365
    $this->assertNotNull($node, 'Node created and found in database');
1366
    $this->drupalGet("node/" . $node->nid);
1367
    $this->assertText(check_plain($edit["title"]), 'Check to make sure tags in the node title are converted.');
1368
  }
1369
  /**
1370
   * Test if the title of the site is XSS proof.
1371
   */
1372
  function testTitleXSS() {
1373
    // Set some title with JavaScript and HTML chars to escape.
1374
    $title = '</title><script type="text/javascript">alert("Title XSS!");</script> & < > " \' ';
1375
    $title_filtered = check_plain($title);
1376

    
1377
    $slogan = '<script type="text/javascript">alert("Slogan XSS!");</script>';
1378
    $slogan_filtered = filter_xss_admin($slogan);
1379

    
1380
    // Activate needed appearance settings.
1381
    $edit = array(
1382
      'toggle_name'           => TRUE,
1383
      'toggle_slogan'         => TRUE,
1384
      'toggle_main_menu'      => TRUE,
1385
      'toggle_secondary_menu' => TRUE,
1386
    );
1387
    $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
1388

    
1389
    // Set title and slogan.
1390
    $edit = array(
1391
      'site_name'    => $title,
1392
      'site_slogan'  => $slogan,
1393
    );
1394
    $this->drupalPost('admin/config/system/site-information', $edit, t('Save configuration'));
1395

    
1396
    // Load frontpage.
1397
    $this->drupalGet('');
1398

    
1399
    // Test the title.
1400
    $this->assertNoRaw($title, 'Check for the unfiltered version of the title.');
1401
    // Adding </title> so we do not test the escaped version from drupal_set_title().
1402
    $this->assertRaw($title_filtered . '</title>', 'Check for the filtered version of the title.');
1403

    
1404
    // Test the slogan.
1405
    $this->assertNoRaw($slogan, 'Check for the unfiltered version of the slogan.');
1406
    $this->assertRaw($slogan_filtered, 'Check for the filtered version of the slogan.');
1407
  }
1408
}
1409

    
1410
/**
1411
 * Test front page functionality and administration.
1412
 */
1413
class FrontPageTestCase extends DrupalWebTestCase {
1414

    
1415
  public static function getInfo() {
1416
    return array(
1417
      'name' => 'Front page',
1418
      'description' => 'Tests front page functionality and administration.',
1419
      'group' => 'System',
1420
    );
1421
  }
1422

    
1423
  function setUp() {
1424
    parent::setUp('system_test');
1425

    
1426
    // Create admin user, log in admin user, and create one node.
1427
    $this->admin_user = $this->drupalCreateUser(array('access content', 'administer site configuration'));
1428
    $this->drupalLogin($this->admin_user);
1429
    $this->node_path = "node/" . $this->drupalCreateNode(array('promote' => 1))->nid;
1430

    
1431
    // Enable front page logging in system_test.module.
1432
    variable_set('front_page_output', 1);
1433
  }
1434

    
1435
  /**
1436
   * Test front page functionality.
1437
   */
1438
  function testDrupalIsFrontPage() {
1439
    $this->drupalGet('');
1440
    $this->assertText(t('On front page.'), 'Path is the front page.');
1441
    $this->drupalGet('node');
1442
    $this->assertText(t('On front page.'), 'Path is the front page.');
1443
    $this->drupalGet($this->node_path);
1444
    $this->assertNoText(t('On front page.'), 'Path is not the front page.');
1445

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

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

    
1456
    $this->drupalGet('');
1457
    $this->assertText(t('On front page.'), 'Path is the front page.');
1458
    $this->drupalGet('node');
1459
    $this->assertNoText(t('On front page.'), 'Path is not the front page.');
1460
    $this->drupalGet($this->node_path);
1461
    $this->assertText(t('On front page.'), 'Path is the front page.');
1462
  }
1463
}
1464

    
1465
class SystemBlockTestCase extends DrupalWebTestCase {
1466
  protected $profile = 'testing';
1467

    
1468
  public static function getInfo() {
1469
    return array(
1470
      'name' => 'Block functionality',
1471
      'description' => 'Configure and move powered-by block.',
1472
      'group' => 'System',
1473
    );
1474
  }
1475

    
1476
  function setUp() {
1477
    parent::setUp('block');
1478

    
1479
    // Create and login user
1480
    $admin_user = $this->drupalCreateUser(array('administer blocks', 'access administration pages'));
1481
    $this->drupalLogin($admin_user);
1482
  }
1483

    
1484
  /**
1485
   * Test displaying and hiding the powered-by and help blocks.
1486
   */
1487
  function testSystemBlocks() {
1488
    // Set block title and some settings to confirm that the interface is available.
1489
    $this->drupalPost('admin/structure/block/manage/system/powered-by/configure', array('title' => $this->randomName(8)), t('Save block'));
1490
    $this->assertText(t('The block configuration has been saved.'), t('Block configuration set.'));
1491

    
1492
    // Set the powered-by block to the footer region.
1493
    $edit = array();
1494
    $edit['blocks[system_powered-by][region]'] = 'footer';
1495
    $edit['blocks[system_main][region]'] = 'content';
1496
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1497
    $this->assertText(t('The block settings have been updated.'), t('Block successfully moved to footer region.'));
1498

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

    
1503
    // Set the block to the disabled region.
1504
    $edit = array();
1505
    $edit['blocks[system_powered-by][region]'] = '-1';
1506
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1507

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

    
1511
    // For convenience of developers, set the block to its default settings.
1512
    $edit = array();
1513
    $edit['blocks[system_powered-by][region]'] = 'footer';
1514
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1515
    $this->drupalPost('admin/structure/block/manage/system/powered-by/configure', array('title' => ''), t('Save block'));
1516

    
1517
    // Set the help block to the help region.
1518
    $edit = array();
1519
    $edit['blocks[system_help][region]'] = 'help';
1520
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1521

    
1522
    // Test displaying the help block with block caching enabled.
1523
    variable_set('block_cache', TRUE);
1524
    $this->drupalGet('admin/structure/block/add');
1525
    $this->assertRaw(t('Use this page to create a new custom block.'));
1526
    $this->drupalGet('admin/index');
1527
    $this->assertRaw(t('This page shows you all available administration tasks for each module.'));
1528
  }
1529
}
1530

    
1531
/**
1532
 * Test main content rendering fallback provided by system module.
1533
 */
1534
class SystemMainContentFallback extends DrupalWebTestCase {
1535
  protected $admin_user;
1536
  protected $web_user;
1537

    
1538
  public static function getInfo() {
1539
    return array(
1540
      'name' => 'Main content rendering fallback',
1541
      'description' => ' Test system module main content rendering fallback.',
1542
      'group' => 'System',
1543
    );
1544
  }
1545

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

    
1549
    // Create and login admin user.
1550
    $this->admin_user = $this->drupalCreateUser(array(
1551
      'access administration pages',
1552
      'administer site configuration',
1553
      'administer modules',
1554
      'administer blocks',
1555
      'administer nodes',
1556
    ));
1557
    $this->drupalLogin($this->admin_user);
1558

    
1559
    // Create a web user.
1560
    $this->web_user = $this->drupalCreateUser(array('access user profiles', 'access content'));
1561
  }
1562

    
1563
  /**
1564
   * Test availability of main content.
1565
   */
1566
  function testMainContentFallback() {
1567
    $edit = array();
1568
    // Disable the dashboard module, which depends on the block module.
1569
    $edit['modules[Core][dashboard][enable]'] = FALSE;
1570
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
1571
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
1572
    // Disable the block module.
1573
    $edit['modules[Core][block][enable]'] = FALSE;
1574
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
1575
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
1576
    module_list(TRUE);
1577
    $this->assertFalse(module_exists('block'), 'Block module disabled.');
1578

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

    
1583
    // Fallback should not trigger when another module is handling content.
1584
    $this->drupalGet('system-test/main-content-handling');
1585
    $this->assertRaw('id="system-test-content"', 'Content handled by another module');
1586
    $this->assertText(t('Content to test main content fallback'), 'Main content still displayed.');
1587

    
1588
    // Fallback should trigger when another module
1589
    // indicates that it is not handling the content.
1590
    $this->drupalGet('system-test/main-content-fallback');
1591
    $this->assertText(t('Content to test main content fallback'), 'Main content fallback properly triggers.');
1592

    
1593
    // Fallback should not trigger when another module is handling content.
1594
    // Note that this test ensures that no duplicate
1595
    // content gets created by the fallback.
1596
    $this->drupalGet('system-test/main-content-duplication');
1597
    $this->assertNoText(t('Content to test main content fallback'), 'Main content not duplicated.');
1598

    
1599
    // Request a user* page and see if it is displayed.
1600
    $this->drupalLogin($this->web_user);
1601
    $this->drupalGet('user/' . $this->web_user->uid . '/edit');
1602
    $this->assertField('mail', 'User interface still available.');
1603

    
1604
    // Enable the block module again.
1605
    $this->drupalLogin($this->admin_user);
1606
    $edit = array();
1607
    $edit['modules[Core][block][enable]'] = 'block';
1608
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
1609
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
1610
    module_list(TRUE);
1611
    $this->assertTrue(module_exists('block'), 'Block module re-enabled.');
1612
  }
1613
}
1614

    
1615
/**
1616
 * Tests for the theme interface functionality.
1617
 */
1618
class SystemThemeFunctionalTest extends DrupalWebTestCase {
1619
  public static function getInfo() {
1620
    return array(
1621
      'name' => 'Theme interface functionality',
1622
      'description' => 'Tests the theme interface functionality by enabling and switching themes, and using an administration theme.',
1623
      'group' => 'System',
1624
    );
1625
  }
1626

    
1627
  function setUp() {
1628
    parent::setUp();
1629

    
1630
    $this->admin_user = $this->drupalCreateUser(array('access administration pages', 'view the administration theme', 'administer themes', 'bypass node access', 'administer blocks'));
1631
    $this->drupalLogin($this->admin_user);
1632
    $this->node = $this->drupalCreateNode();
1633
  }
1634

    
1635
  /**
1636
   * Test the theme settings form.
1637
   */
1638
  function testThemeSettings() {
1639
    // Specify a filesystem path to be used for the logo.
1640
    $file = current($this->drupalGetTestFiles('image'));
1641
    $file_relative = strtr($file->uri, array('public:/' => variable_get('file_public_path', conf_path() . '/files')));
1642
    $default_theme_path = 'themes/stark';
1643

    
1644
    $supported_paths = array(
1645
      // Raw stream wrapper URI.
1646
      $file->uri => array(
1647
        'form' => file_uri_target($file->uri),
1648
        'src' => file_create_url($file->uri),
1649
      ),
1650
      // Relative path within the public filesystem.
1651
      file_uri_target($file->uri) => array(
1652
        'form' => file_uri_target($file->uri),
1653
        'src' => file_create_url($file->uri),
1654
      ),
1655
      // Relative path to a public file.
1656
      $file_relative => array(
1657
        'form' => $file_relative,
1658
        'src' => file_create_url($file->uri),
1659
      ),
1660
      // Relative path to an arbitrary file.
1661
      'misc/druplicon.png' => array(
1662
        'form' => 'misc/druplicon.png',
1663
        'src' => $GLOBALS['base_url'] . '/' . 'misc/druplicon.png',
1664
      ),
1665
      // Relative path to a file in a theme.
1666
      $default_theme_path . '/logo.png' => array(
1667
        'form' => $default_theme_path . '/logo.png',
1668
        'src' => $GLOBALS['base_url'] . '/' . $default_theme_path . '/logo.png',
1669
      ),
1670
    );
1671
    foreach ($supported_paths as $input => $expected) {
1672
      $edit = array(
1673
        'default_logo' => FALSE,
1674
        'logo_path' => $input,
1675
      );
1676
      $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
1677
      $this->assertNoText('The custom logo path is invalid.');
1678
      $this->assertFieldByName('logo_path', $expected['form']);
1679

    
1680
      // Verify the actual 'src' attribute of the logo being output.
1681
      $this->drupalGet('');
1682
      $elements = $this->xpath('//*[@id=:id]/img', array(':id' => 'logo'));
1683
      $this->assertEqual((string) $elements[0]['src'], $expected['src']);
1684
    }
1685

    
1686
    $unsupported_paths = array(
1687
      // Stream wrapper URI to non-existing file.
1688
      'public://whatever.png',
1689
      'private://whatever.png',
1690
      'temporary://whatever.png',
1691
      // Bogus stream wrapper URIs.
1692
      'public:/whatever.png',
1693
      '://whatever.png',
1694
      ':whatever.png',
1695
      'public://',
1696
      // Relative path within the public filesystem to non-existing file.
1697
      'whatever.png',
1698
      // Relative path to non-existing file in public filesystem.
1699
      variable_get('file_public_path', conf_path() . '/files') . '/whatever.png',
1700
      // Semi-absolute path to non-existing file in public filesystem.
1701
      '/' . variable_get('file_public_path', conf_path() . '/files') . '/whatever.png',
1702
      // Relative path to arbitrary non-existing file.
1703
      'misc/whatever.png',
1704
      // Semi-absolute path to arbitrary non-existing file.
1705
      '/misc/whatever.png',
1706
      // Absolute paths to any local file (even if it exists).
1707
      drupal_realpath($file->uri),
1708
    );
1709
    $this->drupalGet('admin/appearance/settings');
1710
    foreach ($unsupported_paths as $path) {
1711
      $edit = array(
1712
        'default_logo' => FALSE,
1713
        'logo_path' => $path,
1714
      );
1715
      $this->drupalPost(NULL, $edit, t('Save configuration'));
1716
      $this->assertText('The custom logo path is invalid.');
1717
    }
1718

    
1719
    // Upload a file to use for the logo.
1720
    $edit = array(
1721
      'default_logo' => FALSE,
1722
      'logo_path' => '',
1723
      'files[logo_upload]' => drupal_realpath($file->uri),
1724
    );
1725
    $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
1726

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

    
1730
    $this->drupalGet('');
1731
    $elements = $this->xpath('//*[@id=:id]/img', array(':id' => 'logo'));
1732
    $this->assertEqual($elements[0]['src'], file_create_url($uploaded_filename));
1733
  }
1734

    
1735
  /**
1736
   * Test the administration theme functionality.
1737
   */
1738
  function testAdministrationTheme() {
1739
    theme_enable(array('stark'));
1740
    variable_set('theme_default', 'stark');
1741
    // Enable an administration theme and show it on the node admin pages.
1742
    $edit = array(
1743
      'admin_theme' => 'seven',
1744
      'node_admin_theme' => TRUE,
1745
    );
1746
    $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
1747

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

    
1751
    $this->drupalGet('node/' . $this->node->nid);
1752
    $this->assertRaw('themes/stark', 'Site default theme used on node page.');
1753

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

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

    
1760
    // Disable the admin theme on the node admin pages.
1761
    $edit = array(
1762
      'node_admin_theme' => FALSE,
1763
    );
1764
    $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
1765

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

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

    
1772
    // Reset to the default theme settings.
1773
    variable_set('theme_default', 'bartik');
1774
    $edit = array(
1775
      'admin_theme' => '0',
1776
      'node_admin_theme' => FALSE,
1777
    );
1778
    $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
1779

    
1780
    $this->drupalGet('admin');
1781
    $this->assertRaw('themes/bartik', 'Site default theme used on administration page.');
1782

    
1783
    $this->drupalGet('node/add');
1784
    $this->assertRaw('themes/bartik', 'Site default theme used on the add content page.');
1785
  }
1786

    
1787
  /**
1788
   * Test switching the default theme.
1789
   */
1790
  function testSwitchDefaultTheme() {
1791
    // Enable "stark" and set it as the default theme.
1792
    theme_enable(array('stark'));
1793
    $this->drupalGet('admin/appearance');
1794
    $this->clickLink(t('Set default'), 1);
1795
    $this->assertTrue(variable_get('theme_default', '') == 'stark', 'Site default theme switched successfully.');
1796

    
1797
    // Test the default theme on the secondary links (blocks admin page).
1798
    $this->drupalGet('admin/structure/block');
1799
    $this->assertText('Stark(' . t('active tab') . ')', 'Default local task on blocks admin page is the default theme.');
1800
    // Switch back to Bartik and test again to test that the menu cache is cleared.
1801
    $this->drupalGet('admin/appearance');
1802
    $this->clickLink(t('Set default'), 0);
1803
    $this->drupalGet('admin/structure/block');
1804
    $this->assertText('Bartik(' . t('active tab') . ')', 'Default local task on blocks admin page has changed.');
1805
  }
1806
}
1807

    
1808

    
1809
/**
1810
 * Test the basic queue functionality.
1811
 */
1812
class QueueTestCase extends DrupalWebTestCase {
1813
  public static function getInfo() {
1814
    return array(
1815
      'name' => 'Queue functionality',
1816
      'description' => 'Queues and dequeues a set of items to check the basic queue functionality.',
1817
      'group' => 'System',
1818
    );
1819
  }
1820

    
1821
  /**
1822
   * Queues and dequeues a set of items to check the basic queue functionality.
1823
   */
1824
  function testQueue() {
1825
    // Create two queues.
1826
    $queue1 = DrupalQueue::get($this->randomName());
1827
    $queue1->createQueue();
1828
    $queue2 = DrupalQueue::get($this->randomName());
1829
    $queue2->createQueue();
1830

    
1831
    // Create four items.
1832
    $data = array();
1833
    for ($i = 0; $i < 4; $i++) {
1834
      $data[] = array($this->randomName() => $this->randomName());
1835
    }
1836

    
1837
    // Queue items 1 and 2 in the queue1.
1838
    $queue1->createItem($data[0]);
1839
    $queue1->createItem($data[1]);
1840

    
1841
    // Retrieve two items from queue1.
1842
    $items = array();
1843
    $new_items = array();
1844

    
1845
    $items[] = $item = $queue1->claimItem();
1846
    $new_items[] = $item->data;
1847

    
1848
    $items[] = $item = $queue1->claimItem();
1849
    $new_items[] = $item->data;
1850

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

    
1854
    // Add two more items.
1855
    $queue1->createItem($data[2]);
1856
    $queue1->createItem($data[3]);
1857

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

    
1861
    $items[] = $item = $queue1->claimItem();
1862
    $new_items[] = $item->data;
1863

    
1864
    $items[] = $item = $queue1->claimItem();
1865
    $new_items[] = $item->data;
1866

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

    
1871
    // There should be no duplicate items.
1872
    $this->assertEqual($this->queueScore($new_items, $new_items), 4, 'Four items matched');
1873

    
1874
    // Delete all items from queue1.
1875
    foreach ($items as $item) {
1876
      $queue1->deleteItem($item);
1877
    }
1878

    
1879
    // Check that both queues are empty.
1880
    $this->assertFalse($queue1->numberOfItems(), 'Queue 1 is empty');
1881
    $this->assertFalse($queue2->numberOfItems(), 'Queue 2 is empty');
1882
  }
1883

    
1884
  /**
1885
   * This function returns the number of equal items in two arrays.
1886
   */
1887
  function queueScore($items, $new_items) {
1888
    $score = 0;
1889
    foreach ($items as $item) {
1890
      foreach ($new_items as $new_item) {
1891
        if ($item === $new_item) {
1892
          $score++;
1893
        }
1894
      }
1895
    }
1896
    return $score;
1897
  }
1898
}
1899

    
1900
/**
1901
 * Test token replacement in strings.
1902
 */
1903
class TokenReplaceTestCase extends DrupalWebTestCase {
1904
  public static function getInfo() {
1905
    return array(
1906
      'name' => 'Token replacement',
1907
      'description' => 'Generates text using placeholders for dummy content to check token replacement.',
1908
      'group' => 'System',
1909
    );
1910
  }
1911

    
1912
  /**
1913
   * Creates a user and a node, then tests the tokens generated from them.
1914
   */
1915
  function testTokenReplacement() {
1916
    // Create the initial objects.
1917
    $account = $this->drupalCreateUser();
1918
    $node = $this->drupalCreateNode(array('uid' => $account->uid));
1919
    $node->title = '<blink>Blinking Text</blink>';
1920
    global $user, $language;
1921

    
1922
    $source  = '[node:title]';         // Title of the node we passed in
1923
    $source .= '[node:author:name]';   // Node author's name
1924
    $source .= '[node:created:since]'; // Time since the node was created
1925
    $source .= '[current-user:name]';  // Current user's name
1926
    $source .= '[date:short]';         // Short date format of REQUEST_TIME
1927
    $source .= '[user:name]';          // No user passed in, should be untouched
1928
    $source .= '[bogus:token]';        // Non-existent token
1929

    
1930
    $target  = check_plain($node->title);
1931
    $target .= check_plain($account->name);
1932
    $target .= format_interval(REQUEST_TIME - $node->created, 2, $language->language);
1933
    $target .= check_plain($user->name);
1934
    $target .= format_date(REQUEST_TIME, 'short', '', NULL, $language->language);
1935

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

    
1940
    // Test without using the clear parameter (non-existent token untouched).
1941
    $target .= '[user:name]';
1942
    $target .= '[bogus:token]';
1943
    $result = token_replace($source, array('node' => $node), array('language' => $language));
1944
    $this->assertEqual($target, $result, 'Valid tokens replaced while invalid tokens ignored.');
1945

    
1946
    // Check that the results of token_generate are sanitized properly. This does NOT
1947
    // test the cleanliness of every token -- just that the $sanitize flag is being
1948
    // passed properly through the call stack and being handled correctly by a 'known'
1949
    // token, [node:title].
1950
    $raw_tokens = array('title' => '[node:title]');
1951
    $generated = token_generate('node', $raw_tokens, array('node' => $node));
1952
    $this->assertEqual($generated['[node:title]'], check_plain($node->title), 'Token sanitized.');
1953

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

    
1957
    // Test token replacement when the string contains no tokens.
1958
    $this->assertEqual(token_replace('No tokens here.'), 'No tokens here.');
1959
  }
1960

    
1961
  /**
1962
   * Test whether token-replacement works in various contexts.
1963
   */
1964
  function testSystemTokenRecognition() {
1965
    global $language;
1966

    
1967
    // Generate prefixes and suffixes for the token context.
1968
    $tests = array(
1969
      array('prefix' => 'this is the ', 'suffix' => ' site'),
1970
      array('prefix' => 'this is the', 'suffix' => 'site'),
1971
      array('prefix' => '[', 'suffix' => ']'),
1972
      array('prefix' => '', 'suffix' => ']]]'),
1973
      array('prefix' => '[[[', 'suffix' => ''),
1974
      array('prefix' => ':[:', 'suffix' => '--]'),
1975
      array('prefix' => '-[-', 'suffix' => ':]:'),
1976
      array('prefix' => '[:', 'suffix' => ']'),
1977
      array('prefix' => '[site:', 'suffix' => ':name]'),
1978
      array('prefix' => '[site:', 'suffix' => ']'),
1979
    );
1980

    
1981
    // Check if the token is recognized in each of the contexts.
1982
    foreach ($tests as $test) {
1983
      $input = $test['prefix'] . '[site:name]' . $test['suffix'];
1984
      $expected = $test['prefix'] . 'Drupal' . $test['suffix'];
1985
      $output = token_replace($input, array(), array('language' => $language));
1986
      $this->assertTrue($output == $expected, format_string('Token recognized in string %string', array('%string' => $input)));
1987
    }
1988
  }
1989

    
1990
  /**
1991
   * Tests the generation of all system site information tokens.
1992
   */
1993
  function testSystemSiteTokenReplacement() {
1994
    global $language;
1995
    $url_options = array(
1996
      'absolute' => TRUE,
1997
      'language' => $language,
1998
    );
1999

    
2000
    // Set a few site variables.
2001
    variable_set('site_name', '<strong>Drupal<strong>');
2002
    variable_set('site_slogan', '<blink>Slogan</blink>');
2003

    
2004
    // Generate and test sanitized tokens.
2005
    $tests = array();
2006
    $tests['[site:name]'] = check_plain(variable_get('site_name', 'Drupal'));
2007
    $tests['[site:slogan]'] = check_plain(variable_get('site_slogan', ''));
2008
    $tests['[site:mail]'] = 'simpletest@example.com';
2009
    $tests['[site:url]'] = url('<front>', $url_options);
2010
    $tests['[site:url-brief]'] = preg_replace(array('!^https?://!', '!/$!'), '', url('<front>', $url_options));
2011
    $tests['[site:login-url]'] = url('user', $url_options);
2012

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

    
2016
    foreach ($tests as $input => $expected) {
2017
      $output = token_replace($input, array(), array('language' => $language));
2018
      $this->assertEqual($output, $expected, format_string('Sanitized system site information token %token replaced.', array('%token' => $input)));
2019
    }
2020

    
2021
    // Generate and test unsanitized tokens.
2022
    $tests['[site:name]'] = variable_get('site_name', 'Drupal');
2023
    $tests['[site:slogan]'] = variable_get('site_slogan', '');
2024

    
2025
    foreach ($tests as $input => $expected) {
2026
      $output = token_replace($input, array(), array('language' => $language, 'sanitize' => FALSE));
2027
      $this->assertEqual($output, $expected, format_string('Unsanitized system site information token %token replaced.', array('%token' => $input)));
2028
    }
2029
  }
2030

    
2031
  /**
2032
   * Tests the generation of all system date tokens.
2033
   */
2034
  function testSystemDateTokenReplacement() {
2035
    global $language;
2036

    
2037
    // Set time to one hour before request.
2038
    $date = REQUEST_TIME - 3600;
2039

    
2040
    // Generate and test tokens.
2041
    $tests = array();
2042
    $tests['[date:short]'] = format_date($date, 'short', '', NULL, $language->language);
2043
    $tests['[date:medium]'] = format_date($date, 'medium', '', NULL, $language->language);
2044
    $tests['[date:long]'] = format_date($date, 'long', '', NULL, $language->language);
2045
    $tests['[date:custom:m/j/Y]'] = format_date($date, 'custom', 'm/j/Y', NULL, $language->language);
2046
    $tests['[date:since]'] = format_interval((REQUEST_TIME - $date), 2, $language->language);
2047
    $tests['[date:raw]'] = filter_xss($date);
2048

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

    
2052
    foreach ($tests as $input => $expected) {
2053
      $output = token_replace($input, array('date' => $date), array('language' => $language));
2054
      $this->assertEqual($output, $expected, format_string('Date token %token replaced.', array('%token' => $input)));
2055
    }
2056
  }
2057
}
2058

    
2059
class InfoFileParserTestCase extends DrupalUnitTestCase {
2060
  public static function getInfo() {
2061
    return array(
2062
      'name' => 'Info file format parser',
2063
      'description' => 'Tests proper parsing of a .info file formatted string.',
2064
      'group' => 'System',
2065
    );
2066
  }
2067

    
2068
  /**
2069
   * Test drupal_parse_info_format().
2070
   */
2071
  function testDrupalParseInfoFormat() {
2072
    $config = '
2073
simple = Value
2074
quoted = " Value"
2075
multiline = "Value
2076
  Value"
2077
array[] = Value1
2078
array[] = Value2
2079
array_assoc[a] = Value1
2080
array_assoc[b] = Value2
2081
array_deep[][][] = Value
2082
array_deep_assoc[a][b][c] = Value
2083
array_space[a b] = Value';
2084

    
2085
    $expected = array(
2086
      'simple' => 'Value',
2087
      'quoted' => ' Value',
2088
      'multiline' => "Value\n  Value",
2089
      'array' => array(
2090
        0 => 'Value1',
2091
        1 => 'Value2',
2092
      ),
2093
      'array_assoc' => array(
2094
        'a' => 'Value1',
2095
        'b' => 'Value2',
2096
      ),
2097
      'array_deep' => array(
2098
        0 => array(
2099
          0 => array(
2100
            0 => 'Value',
2101
          ),
2102
        ),
2103
      ),
2104
      'array_deep_assoc' => array(
2105
        'a' => array(
2106
          'b' => array(
2107
            'c' => 'Value',
2108
          ),
2109
        ),
2110
      ),
2111
      'array_space' => array(
2112
        'a b' => 'Value',
2113
      ),
2114
    );
2115

    
2116
    $parsed = drupal_parse_info_format($config);
2117

    
2118
    $this->assertEqual($parsed['simple'], $expected['simple'], 'Set a simple value.');
2119
    $this->assertEqual($parsed['quoted'], $expected['quoted'], 'Set a simple value in quotes.');
2120
    $this->assertEqual($parsed['multiline'], $expected['multiline'], 'Set a multiline value.');
2121
    $this->assertEqual($parsed['array'], $expected['array'], 'Set a simple array.');
2122
    $this->assertEqual($parsed['array_assoc'], $expected['array_assoc'], 'Set an associative array.');
2123
    $this->assertEqual($parsed['array_deep'], $expected['array_deep'], 'Set a nested array.');
2124
    $this->assertEqual($parsed['array_deep_assoc'], $expected['array_deep_assoc'], 'Set a nested associative array.');
2125
    $this->assertEqual($parsed['array_space'], $expected['array_space'], 'Set an array with a whitespace in the key.');
2126
    $this->assertEqual($parsed, $expected, 'Entire parsed .info string and expected array are identical.');
2127
  }
2128
}
2129

    
2130
/**
2131
 * Tests the effectiveness of hook_system_info_alter().
2132
 */
2133
class SystemInfoAlterTestCase extends DrupalWebTestCase {
2134
  public static function getInfo() {
2135
    return array(
2136
      'name' => 'System info alter',
2137
      'description' => 'Tests the effectiveness of hook_system_info_alter().',
2138
      'group' => 'System',
2139
    );
2140
  }
2141

    
2142
  /**
2143
   * Tests that {system}.info is rebuilt after a module that implements
2144
   * hook_system_info_alter() is enabled. Also tests if core *_list() functions
2145
   * return freshly altered info.
2146
   */
2147
  function testSystemInfoAlter() {
2148
    // Enable our test module. Flush all caches, which we assert is the only
2149
    // thing necessary to use the rebuilt {system}.info.
2150
    module_enable(array('module_test'), FALSE);
2151
    drupal_flush_all_caches();
2152
    $this->assertTrue(module_exists('module_test'), 'Test module is enabled.');
2153

    
2154
    $info = $this->getSystemInfo('seven', 'theme');
2155
    $this->assertTrue(isset($info['regions']['test_region']), 'Altered theme info was added to {system}.info.');
2156
    $seven_regions = system_region_list('seven');
2157
    $this->assertTrue(isset($seven_regions['test_region']), 'Altered theme info was returned by system_region_list().');
2158
    $system_list_themes = system_list('theme');
2159
    $info = $system_list_themes['seven']->info;
2160
    $this->assertTrue(isset($info['regions']['test_region']), 'Altered theme info was returned by system_list().');
2161
    $list_themes = list_themes();
2162
    $this->assertTrue(isset($list_themes['seven']->info['regions']['test_region']), 'Altered theme info was returned by list_themes().');
2163

    
2164
    // Disable the module and verify that {system}.info is rebuilt without it.
2165
    module_disable(array('module_test'), FALSE);
2166
    drupal_flush_all_caches();
2167
    $this->assertFalse(module_exists('module_test'), 'Test module is disabled.');
2168

    
2169
    $info = $this->getSystemInfo('seven', 'theme');
2170
    $this->assertFalse(isset($info['regions']['test_region']), 'Altered theme info was removed from {system}.info.');
2171
    $seven_regions = system_region_list('seven');
2172
    $this->assertFalse(isset($seven_regions['test_region']), 'Altered theme info was not returned by system_region_list().');
2173
    $system_list_themes = system_list('theme');
2174
    $info = $system_list_themes['seven']->info;
2175
    $this->assertFalse(isset($info['regions']['test_region']), 'Altered theme info was not returned by system_list().');
2176
    $list_themes = list_themes();
2177
    $this->assertFalse(isset($list_themes['seven']->info['regions']['test_region']), 'Altered theme info was not returned by list_themes().');
2178
  }
2179

    
2180
  /**
2181
   * Returns the info array as it is stored in {system}.
2182
   *
2183
   * @param $name
2184
   *   The name of the record in {system}.
2185
   * @param $type
2186
   *   The type of record in {system}.
2187
   *
2188
   * @return
2189
   *   Array of info, or FALSE if the record is not found.
2190
   */
2191
  function getSystemInfo($name, $type) {
2192
    $raw_info = db_query("SELECT info FROM {system} WHERE name = :name AND type = :type", array(':name' => $name, ':type' => $type))->fetchField();
2193
    return $raw_info ? unserialize($raw_info) : FALSE;
2194
  }
2195
}
2196

    
2197
/**
2198
 * Tests for the update system functionality.
2199
 */
2200
class UpdateScriptFunctionalTest extends DrupalWebTestCase {
2201
  private $update_url;
2202
  private $update_user;
2203

    
2204
  public static function getInfo() {
2205
    return array(
2206
      'name' => 'Update functionality',
2207
      'description' => 'Tests the update script access and functionality.',
2208
      'group' => 'System',
2209
    );
2210
  }
2211

    
2212
  function setUp() {
2213
    parent::setUp('update_script_test');
2214
    $this->update_url = $GLOBALS['base_url'] . '/update.php';
2215
    $this->update_user = $this->drupalCreateUser(array('administer software updates'));
2216
  }
2217

    
2218
  /**
2219
   * Tests access to the update script.
2220
   */
2221
  function testUpdateAccess() {
2222
    // Try accessing update.php without the proper permission.
2223
    $regular_user = $this->drupalCreateUser();
2224
    $this->drupalLogin($regular_user);
2225
    $this->drupalGet($this->update_url, array('external' => TRUE));
2226
    $this->assertResponse(403);
2227

    
2228
    // Try accessing update.php as an anonymous user.
2229
    $this->drupalLogout();
2230
    $this->drupalGet($this->update_url, array('external' => TRUE));
2231
    $this->assertResponse(403);
2232

    
2233
    // Access the update page with the proper permission.
2234
    $this->drupalLogin($this->update_user);
2235
    $this->drupalGet($this->update_url, array('external' => TRUE));
2236
    $this->assertResponse(200);
2237

    
2238
    // Access the update page as user 1.
2239
    $user1 = user_load(1);
2240
    $user1->pass_raw = user_password();
2241
    require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
2242
    $user1->pass = user_hash_password(trim($user1->pass_raw));
2243
    db_query("UPDATE {users} SET pass = :pass WHERE uid = :uid", array(':pass' => $user1->pass, ':uid' => $user1->uid));
2244
    $this->drupalLogin($user1);
2245
    $this->drupalGet($this->update_url, array('external' => TRUE));
2246
    $this->assertResponse(200);
2247
  }
2248

    
2249
  /**
2250
   * Tests that requirements warnings and errors are correctly displayed.
2251
   */
2252
  function testRequirements() {
2253
    $this->drupalLogin($this->update_user);
2254

    
2255
    // If there are no requirements warnings or errors, we expect to be able to
2256
    // go through the update process uninterrupted.
2257
    $this->drupalGet($this->update_url, array('external' => TRUE));
2258
    $this->drupalPost(NULL, array(), t('Continue'));
2259
    $this->assertText(t('No pending updates.'), 'End of update process was reached.');
2260
    // Confirm that all caches were cleared.
2261
    $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared when there were no requirements warnings or errors.');
2262

    
2263
    // If there is a requirements warning, we expect it to be initially
2264
    // displayed, but clicking the link to proceed should allow us to go
2265
    // through the rest of the update process uninterrupted.
2266

    
2267
    // First, run this test with pending updates to make sure they can be run
2268
    // successfully.
2269
    variable_set('update_script_test_requirement_type', REQUIREMENT_WARNING);
2270
    drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
2271
    $this->drupalGet($this->update_url, array('external' => TRUE));
2272
    $this->assertText('This is a requirements warning provided by the update_script_test module.');
2273
    $this->clickLink('try again');
2274
    $this->assertNoText('This is a requirements warning provided by the update_script_test module.');
2275
    $this->drupalPost(NULL, array(), t('Continue'));
2276
    $this->drupalPost(NULL, array(), t('Apply pending updates'));
2277
    $this->assertText(t('The update_script_test_update_7000() update was executed successfully.'), 'End of update process was reached.');
2278
    // Confirm that all caches were cleared.
2279
    $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared after resolving a requirements warning and applying updates.');
2280

    
2281
    // Now try again without pending updates to make sure that works too.
2282
    $this->drupalGet($this->update_url, array('external' => TRUE));
2283
    $this->assertText('This is a requirements warning provided by the update_script_test module.');
2284
    $this->clickLink('try again');
2285
    $this->assertNoText('This is a requirements warning provided by the update_script_test module.');
2286
    $this->drupalPost(NULL, array(), t('Continue'));
2287
    $this->assertText(t('No pending updates.'), 'End of update process was reached.');
2288
    // Confirm that all caches were cleared.
2289
    $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared after applying updates and re-running the script.');
2290

    
2291
    // If there is a requirements error, it should be displayed even after
2292
    // clicking the link to proceed (since the problem that triggered the error
2293
    // has not been fixed).
2294
    variable_set('update_script_test_requirement_type', REQUIREMENT_ERROR);
2295
    $this->drupalGet($this->update_url, array('external' => TRUE));
2296
    $this->assertText('This is a requirements error provided by the update_script_test module.');
2297
    $this->clickLink('try again');
2298
    $this->assertText('This is a requirements error provided by the update_script_test module.');
2299
  }
2300

    
2301
  /**
2302
   * Tests the effect of using the update script on the theme system.
2303
   */
2304
  function testThemeSystem() {
2305
    // Since visiting update.php triggers a rebuild of the theme system from an
2306
    // unusual maintenance mode environment, we check that this rebuild did not
2307
    // put any incorrect information about the themes into the database.
2308
    $original_theme_data = db_query("SELECT * FROM {system} WHERE type = 'theme' ORDER BY name")->fetchAll();
2309
    $this->drupalLogin($this->update_user);
2310
    $this->drupalGet($this->update_url, array('external' => TRUE));
2311
    $final_theme_data = db_query("SELECT * FROM {system} WHERE type = 'theme' ORDER BY name")->fetchAll();
2312
    $this->assertEqual($original_theme_data, $final_theme_data, 'Visiting update.php does not alter the information about themes stored in the database.');
2313
  }
2314

    
2315
  /**
2316
   * Tests update.php when there are no updates to apply.
2317
   */
2318
  function testNoUpdateFunctionality() {
2319
    // Click through update.php with 'administer software updates' permission.
2320
    $this->drupalLogin($this->update_user);
2321
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
2322
    $this->assertText(t('No pending updates.'));
2323
    $this->assertNoLink('Administration pages');
2324
    $this->clickLink('Front page');
2325
    $this->assertResponse(200);
2326

    
2327
    // Click through update.php with 'access administration pages' permission.
2328
    $admin_user = $this->drupalCreateUser(array('administer software updates', 'access administration pages'));
2329
    $this->drupalLogin($admin_user);
2330
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
2331
    $this->assertText(t('No pending updates.'));
2332
    $this->clickLink('Administration pages');
2333
    $this->assertResponse(200);
2334
  }
2335

    
2336
  /**
2337
   * Tests update.php after performing a successful update.
2338
   */
2339
  function testSuccessfulUpdateFunctionality() {
2340
    drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
2341
    // Click through update.php with 'administer software updates' permission.
2342
    $this->drupalLogin($this->update_user);
2343
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
2344
    $this->drupalPost(NULL, array(), t('Apply pending updates'));
2345
    $this->assertText('Updates were attempted.');
2346
    $this->assertLink('site');
2347
    $this->assertNoLink('Administration pages');
2348
    $this->assertNoLink('logged');
2349
    $this->clickLink('Front page');
2350
    $this->assertResponse(200);
2351

    
2352
    drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
2353
    // Click through update.php with 'access administration pages' and
2354
    // 'access site reports' permissions.
2355
    $admin_user = $this->drupalCreateUser(array('administer software updates', 'access administration pages', 'access site reports'));
2356
    $this->drupalLogin($admin_user);
2357
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
2358
    $this->drupalPost(NULL, array(), t('Apply pending updates'));
2359
    $this->assertText('Updates were attempted.');
2360
    $this->assertLink('logged');
2361
    $this->clickLink('Administration pages');
2362
    $this->assertResponse(200);
2363
  }
2364
}
2365

    
2366
/**
2367
 * Functional tests for the flood control mechanism.
2368
 */
2369
class FloodFunctionalTest extends DrupalWebTestCase {
2370
  public static function getInfo() {
2371
    return array(
2372
      'name' => 'Flood control mechanism',
2373
      'description' => 'Functional tests for the flood control mechanism.',
2374
      'group' => 'System',
2375
    );
2376
  }
2377

    
2378
  /**
2379
   * Test flood control mechanism clean-up.
2380
   */
2381
  function testCleanUp() {
2382
    $threshold = 1;
2383
    $window_expired = -1;
2384
    $name = 'flood_test_cleanup';
2385

    
2386
    // Register expired event.
2387
    flood_register_event($name, $window_expired);
2388
    // Verify event is not allowed.
2389
    $this->assertFalse(flood_is_allowed($name, $threshold));
2390
    // Run cron and verify event is now allowed.
2391
    $this->cronRun();
2392
    $this->assertTrue(flood_is_allowed($name, $threshold));
2393

    
2394
    // Register unexpired event.
2395
    flood_register_event($name);
2396
    // Verify event is not allowed.
2397
    $this->assertFalse(flood_is_allowed($name, $threshold));
2398
    // Run cron and verify event is still not allowed.
2399
    $this->cronRun();
2400
    $this->assertFalse(flood_is_allowed($name, $threshold));
2401
  }
2402
}
2403

    
2404
/**
2405
 * Test HTTP file downloading capability.
2406
 */
2407
class RetrieveFileTestCase extends DrupalWebTestCase {
2408
  public static function getInfo() {
2409
    return array(
2410
      'name' => 'HTTP file retrieval',
2411
      'description' => 'Checks HTTP file fetching and error handling.',
2412
      'group' => 'System',
2413
    );
2414
  }
2415

    
2416
  /**
2417
   * Invokes system_retrieve_file() in several scenarios.
2418
   */
2419
  function testFileRetrieving() {
2420
    // Test 404 handling by trying to fetch a randomly named file.
2421
    drupal_mkdir($sourcedir = 'public://' . $this->randomName());
2422
    $filename = 'Файл для тестирования ' . $this->randomName();
2423
    $url = file_create_url($sourcedir . '/' . $filename);
2424
    $retrieved_file = system_retrieve_file($url);
2425
    $this->assertFalse($retrieved_file, 'Non-existent file not fetched.');
2426

    
2427
    // Actually create that file, download it via HTTP and test the returned path.
2428
    file_put_contents($sourcedir . '/' . $filename, 'testing');
2429
    $retrieved_file = system_retrieve_file($url);
2430

    
2431
    // URLs could not contains characters outside the ASCII set so $filename
2432
    // has to be encoded.
2433
    $encoded_filename = rawurlencode($filename);
2434

    
2435
    $this->assertEqual($retrieved_file, 'public://' . $encoded_filename, 'Sane path for downloaded file returned (public:// scheme).');
2436
    $this->assertTrue(is_file($retrieved_file), 'Downloaded file does exist (public:// scheme).');
2437
    $this->assertEqual(filesize($retrieved_file), 7, 'File size of downloaded file is correct (public:// scheme).');
2438
    file_unmanaged_delete($retrieved_file);
2439

    
2440
    // Test downloading file to a different location.
2441
    drupal_mkdir($targetdir = 'temporary://' . $this->randomName());
2442
    $retrieved_file = system_retrieve_file($url, $targetdir);
2443
    $this->assertEqual($retrieved_file, "$targetdir/$encoded_filename", 'Sane path for downloaded file returned (temporary:// scheme).');
2444
    $this->assertTrue(is_file($retrieved_file), 'Downloaded file does exist (temporary:// scheme).');
2445
    $this->assertEqual(filesize($retrieved_file), 7, 'File size of downloaded file is correct (temporary:// scheme).');
2446
    file_unmanaged_delete($retrieved_file);
2447

    
2448
    file_unmanaged_delete_recursive($sourcedir);
2449
    file_unmanaged_delete_recursive($targetdir);
2450
  }
2451
}
2452

    
2453
/**
2454
 * Functional tests shutdown functions.
2455
 */
2456
class ShutdownFunctionsTest extends DrupalWebTestCase {
2457
  public static function getInfo() {
2458
    return array(
2459
      'name' => 'Shutdown functions',
2460
      'description' => 'Functional tests for shutdown functions',
2461
      'group' => 'System',
2462
    );
2463
  }
2464

    
2465
  function setUp() {
2466
    parent::setUp('system_test');
2467
  }
2468

    
2469
  /**
2470
   * Test shutdown functions.
2471
   */
2472
  function testShutdownFunctions() {
2473
    $arg1 = $this->randomName();
2474
    $arg2 = $this->randomName();
2475
    $this->drupalGet('system-test/shutdown-functions/' . $arg1 . '/' . $arg2);
2476
    $this->assertText(t('First shutdown function, arg1 : @arg1, arg2: @arg2', array('@arg1' => $arg1, '@arg2' => $arg2)));
2477
    $this->assertText(t('Second shutdown function, arg1 : @arg1, arg2: @arg2', array('@arg1' => $arg1, '@arg2' => $arg2)));
2478

    
2479
    // Make sure exceptions displayed through _drupal_render_exception_safe()
2480
    // are correctly escaped.
2481
    $this->assertRaw('Drupal is &amp;lt;blink&amp;gt;awesome&amp;lt;/blink&amp;gt;.');
2482
  }
2483
}
2484

    
2485
/**
2486
 * Tests administrative overview pages.
2487
 */
2488
class SystemAdminTestCase extends DrupalWebTestCase {
2489
  public static function getInfo() {
2490
    return array(
2491
      'name' => 'Administrative pages',
2492
      'description' => 'Tests output on administrative pages and compact mode functionality.',
2493
      'group' => 'System',
2494
    );
2495
  }
2496

    
2497
  function setUp() {
2498
    // testAdminPages() requires Locale module.
2499
    parent::setUp(array('locale'));
2500

    
2501
    // Create an administrator with all permissions, as well as a regular user
2502
    // who can only access administration pages and perform some Locale module
2503
    // administrative tasks, but not all of them.
2504
    $this->admin_user = $this->drupalCreateUser(array_keys(module_invoke_all('permission')));
2505
    $this->web_user = $this->drupalCreateUser(array(
2506
      'access administration pages',
2507
      'translate interface',
2508
    ));
2509
    $this->drupalLogin($this->admin_user);
2510
  }
2511

    
2512
  /**
2513
   * Tests output on administrative listing pages.
2514
   */
2515
  function testAdminPages() {
2516
    // Go to Administration.
2517
    $this->drupalGet('admin');
2518

    
2519
    // Verify that all visible, top-level administration links are listed on
2520
    // the main administration page.
2521
    foreach (menu_get_router() as $path => $item) {
2522
      if (strpos($path, 'admin/') === 0 && ($item['type'] & MENU_VISIBLE_IN_TREE) && $item['_number_parts'] == 2) {
2523
        $this->assertLink($item['title']);
2524
        $this->assertLinkByHref($path);
2525
        $this->assertText($item['description']);
2526
      }
2527
    }
2528

    
2529
    // For each administrative listing page on which the Locale module appears,
2530
    // verify that there are links to the module's primary configuration pages,
2531
    // but no links to its individual sub-configuration pages. Also verify that
2532
    // a user with access to only some Locale module administration pages only
2533
    // sees links to the pages they have access to.
2534
    $admin_list_pages = array(
2535
      'admin/index',
2536
      'admin/config',
2537
      'admin/config/regional',
2538
    );
2539

    
2540
    foreach ($admin_list_pages as $page) {
2541
      // For the administrator, verify that there are links to Locale's primary
2542
      // configuration pages, but no links to individual sub-configuration
2543
      // pages.
2544
      $this->drupalLogin($this->admin_user);
2545
      $this->drupalGet($page);
2546
      $this->assertLinkByHref('admin/config');
2547
      $this->assertLinkByHref('admin/config/regional/settings');
2548
      $this->assertLinkByHref('admin/config/regional/date-time');
2549
      $this->assertLinkByHref('admin/config/regional/language');
2550
      $this->assertNoLinkByHref('admin/config/regional/language/configure/session');
2551
      $this->assertNoLinkByHref('admin/config/regional/language/configure/url');
2552
      $this->assertLinkByHref('admin/config/regional/translate');
2553
      // On admin/index only, the administrator should also see a "Configure
2554
      // permissions" link for the Locale module.
2555
      if ($page == 'admin/index') {
2556
        $this->assertLinkByHref("admin/people/permissions#module-locale");
2557
      }
2558

    
2559
      // For a less privileged user, verify that there are no links to Locale's
2560
      // primary configuration pages, but a link to the translate page exists.
2561
      $this->drupalLogin($this->web_user);
2562
      $this->drupalGet($page);
2563
      $this->assertLinkByHref('admin/config');
2564
      $this->assertNoLinkByHref('admin/config/regional/settings');
2565
      $this->assertNoLinkByHref('admin/config/regional/date-time');
2566
      $this->assertNoLinkByHref('admin/config/regional/language');
2567
      $this->assertNoLinkByHref('admin/config/regional/language/configure/session');
2568
      $this->assertNoLinkByHref('admin/config/regional/language/configure/url');
2569
      $this->assertLinkByHref('admin/config/regional/translate');
2570
      // This user cannot configure permissions, so even on admin/index should
2571
      // not see a "Configure permissions" link for the Locale module.
2572
      if ($page == 'admin/index') {
2573
        $this->assertNoLinkByHref("admin/people/permissions#module-locale");
2574
      }
2575
    }
2576
  }
2577

    
2578
  /**
2579
   * Test compact mode.
2580
   */
2581
  function testCompactMode() {
2582
    $this->drupalGet('admin/compact/on');
2583
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode turns on.');
2584
    $this->drupalGet('admin/compact/on');
2585
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode remains on after a repeat call.');
2586
    $this->drupalGet('');
2587
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode persists on new requests.');
2588

    
2589
    $this->drupalGet('admin/compact/off');
2590
    $this->assertEqual($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'deleted', 'Compact mode turns off.');
2591
    $this->drupalGet('admin/compact/off');
2592
    $this->assertEqual($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'deleted', 'Compact mode remains off after a repeat call.');
2593
    $this->drupalGet('');
2594
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode persists on new requests.');
2595
  }
2596
}
2597

    
2598
/**
2599
 * Tests authorize.php and related hooks.
2600
 */
2601
class SystemAuthorizeCase extends DrupalWebTestCase {
2602
  public static function getInfo() {
2603
    return array(
2604
      'name' => 'Authorize API',
2605
      'description' => 'Tests the authorize.php script and related API.',
2606
      'group' => 'System',
2607
    );
2608
  }
2609

    
2610
  function setUp() {
2611
    parent::setUp(array('system_test'));
2612

    
2613
    variable_set('allow_authorize_operations', TRUE);
2614

    
2615
    // Create an administrator user.
2616
    $this->admin_user = $this->drupalCreateUser(array('administer software updates'));
2617
    $this->drupalLogin($this->admin_user);
2618
  }
2619

    
2620
  /**
2621
   * Helper function to initialize authorize.php and load it via drupalGet().
2622
   *
2623
   * Initializing authorize.php needs to happen in the child Drupal
2624
   * installation, not the parent. So, we visit a menu callback provided by
2625
   * system_test.module which calls system_authorized_init() to initialize the
2626
   * $_SESSION inside the test site, not the framework site. This callback
2627
   * redirects to authorize.php when it's done initializing.
2628
   *
2629
   * @see system_authorized_init().
2630
   */
2631
  function drupalGetAuthorizePHP($page_title = 'system-test-auth') {
2632
    $this->drupalGet('system-test/authorize-init/' . $page_title);
2633
  }
2634

    
2635
  /**
2636
   * Tests the FileTransfer hooks
2637
   */
2638
  function testFileTransferHooks() {
2639
    $page_title = $this->randomName(16);
2640
    $this->drupalGetAuthorizePHP($page_title);
2641
    $this->assertTitle(strtr('@title | Drupal', array('@title' => $page_title)), 'authorize.php page title is correct.');
2642
    $this->assertNoText('It appears you have reached this page in error.');
2643
    $this->assertText('To continue, provide your server connection details');
2644
    // Make sure we see the new connection method added by system_test.
2645
    $this->assertRaw('System Test FileTransfer');
2646
    // Make sure the settings form callback works.
2647
    $this->assertText('System Test Username');
2648
  }
2649
}
2650

    
2651
/**
2652
 * Test the handling of requests containing 'index.php'.
2653
 */
2654
class SystemIndexPhpTest extends DrupalWebTestCase {
2655
  public static function getInfo() {
2656
    return array(
2657
      'name' => 'Index.php handling',
2658
      'description' => "Test the handling of requests containing 'index.php'.",
2659
      'group' => 'System',
2660
    );
2661
  }
2662

    
2663
  function setUp() {
2664
    parent::setUp();
2665
  }
2666

    
2667
  /**
2668
   * Test index.php handling.
2669
   */
2670
  function testIndexPhpHandling() {
2671
    $index_php = $GLOBALS['base_url'] . '/index.php';
2672

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

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

    
2679
    $this->drupalGet($index_php .'/user', array('external' => TRUE));
2680
    $this->assertResponse(404, "Make sure index.php/user returns a 'page not found'.");
2681
  }
2682
}
2683

    
2684
/**
2685
 * Test token replacement in strings.
2686
 */
2687
class TokenScanTest extends DrupalWebTestCase {
2688

    
2689
  public static function getInfo() {
2690
    return array(
2691
      'name' => 'Token scanning',
2692
      'description' => 'Scan token-like patterns in a dummy text to check token scanning.',
2693
      'group' => 'System',
2694
    );
2695
  }
2696

    
2697
  /**
2698
   * Scans dummy text, then tests the output.
2699
   */
2700
  function testTokenScan() {
2701
    // Define text with valid and not valid, fake and existing token-like
2702
    // strings.
2703
    $text = 'First a [valid:simple], but dummy token, and a dummy [valid:token with: spaces].';
2704
    $text .= 'Then a [not valid:token].';
2705
    $text .= 'Last an existing token: [node:author:name].';
2706
    $token_wannabes = token_scan($text);
2707

    
2708
    $this->assertTrue(isset($token_wannabes['valid']['simple']), 'A simple valid token has been matched.');
2709
    $this->assertTrue(isset($token_wannabes['valid']['token with: spaces']), 'A valid token with space characters in the token name has been matched.');
2710
    $this->assertFalse(isset($token_wannabes['not valid']), 'An invalid token with spaces in the token type has not been matched.');
2711
    $this->assertTrue(isset($token_wannabes['node']), 'An existing valid token has been matched.');
2712
  }
2713
}
2714

    
2715
/**
2716
 * Test case for drupal_valid_token().
2717
 */
2718
class SystemValidTokenTest extends DrupalUnitTestCase {
2719

    
2720
  /**
2721
   * Flag to indicate whether PHP error reportings should be asserted.
2722
   *
2723
   * @var bool
2724
   */
2725
  protected $assertErrors = TRUE;
2726

    
2727
  public static function getInfo() {
2728
    return array(
2729
      'name' => 'Token validation',
2730
      'description' => 'Test the security token validation.',
2731
      'group' => 'System',
2732
    );
2733
  }
2734

    
2735
  /**
2736
   * Tests invalid invocations of drupal_valid_token() that must return FALSE.
2737
   */
2738
  public function testTokenValidation() {
2739
    // The following checks will throw PHP notices, so we disable error
2740
    // assertions.
2741
    $this->assertErrors = FALSE;
2742
    $this->assertFalse(drupal_valid_token(NULL, new stdClass()), 'Token NULL, value object returns FALSE.');
2743
    $this->assertFalse(drupal_valid_token(0, array()), 'Token 0, value array returns FALSE.');
2744
    $this->assertFalse(drupal_valid_token('', array()), "Token '', value array returns FALSE.");
2745
    $this->assertFalse('' === drupal_get_token(array()), 'Token generation does not return an empty string on invalid parameters.');
2746
    $this->assertErrors = TRUE;
2747

    
2748
    $this->assertFalse(drupal_valid_token(TRUE, 'foo'), 'Token TRUE, value foo returns FALSE.');
2749
    $this->assertFalse(drupal_valid_token(0, 'foo'), 'Token 0, value foo returns FALSE.');
2750
  }
2751

    
2752
  /**
2753
   * Overrides DrupalTestCase::errorHandler().
2754
   */
2755
  public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
2756
    if ($this->assertErrors) {
2757
      return parent::errorHandler($severity, $message, $file, $line);
2758
    }
2759
    return TRUE;
2760
  }
2761
}