Projet

Général

Profil

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

root / drupal7 / modules / system / system.test @ 4444412d

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
/**
871
 * Test execution of the cron queue.
872
 */
873
class CronQueueTestCase extends DrupalWebTestCase {
874
  /**
875
   * Implement getInfo().
876
   */
877
  public static function getInfo() {
878
    return array(
879
      'name' => 'Cron queue functionality',
880
      'description' => 'Tests the cron queue runner.',
881
      'group' => 'System'
882
    );
883
  }
884

    
885
  function setUp() {
886
    parent::setUp(array('common_test', 'common_test_cron_helper'));
887
  }
888

    
889
  /**
890
   * Tests that exceptions thrown by workers are handled properly.
891
   */
892
  function testExceptions() {
893
    $queue = DrupalQueue::get('cron_queue_test_exception');
894

    
895
    // Enqueue an item for processing.
896
    $queue->createItem(array($this->randomName() => $this->randomName()));
897

    
898
    // Run cron; the worker for this queue should throw an exception and handle
899
    // it.
900
    $this->cronRun();
901

    
902
    // The item should be left in the queue.
903
    $this->assertEqual($queue->numberOfItems(), 1, 'Failing item still in the queue after throwing an exception.');
904
  }
905

    
906
}
907

    
908
class AdminMetaTagTestCase extends DrupalWebTestCase {
909
  /**
910
   * Implement getInfo().
911
   */
912
  public static function getInfo() {
913
    return array(
914
      'name' => 'Fingerprinting meta tag',
915
      'description' => 'Confirm that the fingerprinting meta tag appears as expected.',
916
      'group' => 'System'
917
    );
918
  }
919

    
920
  /**
921
   * Verify that the meta tag HTML is generated correctly.
922
   */
923
  public function testMetaTag() {
924
    list($version, ) = explode('.', VERSION);
925
    $string = '<meta name="Generator" content="Drupal ' . $version . ' (http://drupal.org)" />';
926
    $this->drupalGet('node');
927
    $this->assertRaw($string, 'Fingerprinting meta tag generated correctly.', 'System');
928
  }
929
}
930

    
931
/**
932
 * Tests custom access denied functionality.
933
 */
934
class AccessDeniedTestCase extends DrupalWebTestCase {
935
  protected $admin_user;
936

    
937
  public static function getInfo() {
938
    return array(
939
      'name' => '403 functionality',
940
      'description' => 'Tests page access denied functionality, including custom 403 pages.',
941
      'group' => 'System'
942
    );
943
  }
944

    
945
  function setUp() {
946
    parent::setUp();
947

    
948
    // Create an administrative user.
949
    $this->admin_user = $this->drupalCreateUser(array('access administration pages', 'administer site configuration', 'administer blocks'));
950
  }
951

    
952
  function testAccessDenied() {
953
    $this->drupalGet('admin');
954
    $this->assertText(t('Access denied'), 'Found the default 403 page');
955
    $this->assertResponse(403);
956

    
957
    $this->drupalLogin($this->admin_user);
958
    $edit = array(
959
      'title' => $this->randomName(10),
960
      'body' => array(LANGUAGE_NONE => array(array('value' => $this->randomName(100)))),
961
    );
962
    $node = $this->drupalCreateNode($edit);
963

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

    
967
    $this->drupalLogout();
968
    $this->drupalGet('admin');
969
    $this->assertText($node->title, 'Found the custom 403 page');
970

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

    
974
    $this->drupalGet('admin');
975
    $this->assertText($node->title, 'Found the custom 403 page');
976
    $this->assertText(t('User login'), 'Blocks are shown on the custom 403 page');
977

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

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

    
985
    $this->drupalGet('admin');
986
    $this->assertText(t('Access denied'), 'Found the default 403 page');
987
    $this->assertResponse(403);
988
    $this->assertText(t('User login'), 'Blocks are shown on the default 403 page');
989

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

    
995
    // Check that we can log in from the 403 page.
996
    $this->drupalLogout();
997
    $edit = array(
998
      'name' => $this->admin_user->name,
999
      'pass' => $this->admin_user->pass_raw,
1000
    );
1001
    $this->drupalPost('admin/config/system/site-information', $edit, t('Log in'));
1002

    
1003
    // Check that we're still on the same page.
1004
    $this->assertText(t('Site information'));
1005
  }
1006
}
1007

    
1008
class PageNotFoundTestCase extends DrupalWebTestCase {
1009
  protected $admin_user;
1010

    
1011
  /**
1012
   * Implement getInfo().
1013
   */
1014
  public static function getInfo() {
1015
    return array(
1016
      'name' => '404 functionality',
1017
      'description' => "Tests page not found functionality, including custom 404 pages.",
1018
      'group' => 'System'
1019
    );
1020
  }
1021

    
1022
  /**
1023
   * Implement setUp().
1024
   */
1025
  function setUp() {
1026
    parent::setUp();
1027

    
1028
    // Create an administrative user.
1029
    $this->admin_user = $this->drupalCreateUser(array('administer site configuration'));
1030
    $this->drupalLogin($this->admin_user);
1031
  }
1032

    
1033
  function testPageNotFound() {
1034
    $this->drupalGet($this->randomName(10));
1035
    $this->assertText(t('Page not found'), 'Found the default 404 page');
1036

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

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

    
1046
    $this->drupalGet($this->randomName(10));
1047
    $this->assertText($node->title, 'Found the custom 404 page');
1048
  }
1049
}
1050

    
1051
/**
1052
 * Tests site maintenance functionality.
1053
 */
1054
class SiteMaintenanceTestCase extends DrupalWebTestCase {
1055
  protected $admin_user;
1056

    
1057
  public static function getInfo() {
1058
    return array(
1059
      'name' => 'Site maintenance mode functionality',
1060
      'description' => 'Test access to site while in maintenance mode.',
1061
      'group' => 'System',
1062
    );
1063
  }
1064

    
1065
  function setUp() {
1066
    parent::setUp();
1067

    
1068
    // Create a user allowed to access site in maintenance mode.
1069
    $this->user = $this->drupalCreateUser(array('access site in maintenance mode'));
1070
    // Create an administrative user.
1071
    $this->admin_user = $this->drupalCreateUser(array('administer site configuration', 'access site in maintenance mode'));
1072
    $this->drupalLogin($this->admin_user);
1073
  }
1074

    
1075
  /**
1076
   * Verify site maintenance mode functionality.
1077
   */
1078
  function testSiteMaintenance() {
1079
    // Turn on maintenance mode.
1080
    $edit = array(
1081
      'maintenance_mode' => 1,
1082
    );
1083
    $this->drupalPost('admin/config/development/maintenance', $edit, t('Save configuration'));
1084

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

    
1089
    $this->drupalGet('');
1090
    $this->assertRaw($admin_message, 'Found the site maintenance mode message.');
1091

    
1092
    // Logout and verify that offline message is displayed.
1093
    $this->drupalLogout();
1094
    $this->drupalGet('');
1095
    $this->assertText($offline_message);
1096
    $this->drupalGet('node');
1097
    $this->assertText($offline_message);
1098
    $this->drupalGet('user/register');
1099
    $this->assertText($offline_message);
1100

    
1101
    // Verify that user is able to log in.
1102
    $this->drupalGet('user');
1103
    $this->assertNoText($offline_message);
1104
    $this->drupalGet('user/login');
1105
    $this->assertNoText($offline_message);
1106

    
1107
    // Log in user and verify that maintenance mode message is displayed
1108
    // directly after login.
1109
    $edit = array(
1110
      'name' => $this->user->name,
1111
      'pass' => $this->user->pass_raw,
1112
    );
1113
    $this->drupalPost(NULL, $edit, t('Log in'));
1114
    $this->assertText($user_message);
1115

    
1116
    // Log in administrative user and configure a custom site offline message.
1117
    $this->drupalLogout();
1118
    $this->drupalLogin($this->admin_user);
1119
    $this->drupalGet('admin/config/development/maintenance');
1120
    $this->assertNoRaw($admin_message, 'Site maintenance mode message not displayed.');
1121

    
1122
    $offline_message = 'Sorry, not online.';
1123
    $edit = array(
1124
      'maintenance_mode_message' => $offline_message,
1125
    );
1126
    $this->drupalPost(NULL, $edit, t('Save configuration'));
1127

    
1128
    // Logout and verify that custom site offline message is displayed.
1129
    $this->drupalLogout();
1130
    $this->drupalGet('');
1131
    $this->assertRaw($offline_message, 'Found the site offline message.');
1132

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

    
1137
    // Submit password reset form.
1138
    $edit = array(
1139
      'name' => $this->user->name,
1140
    );
1141
    $this->drupalPost('user/password', $edit, t('E-mail new password'));
1142
    $mails = $this->drupalGetMails();
1143
    $start = strpos($mails[0]['body'], 'user/reset/'. $this->user->uid);
1144
    $path = substr($mails[0]['body'], $start, 66 + strlen($this->user->uid));
1145

    
1146
    // Log in with temporary login link.
1147
    $this->drupalPost($path, array(), t('Log in'));
1148
    $this->assertText($user_message);
1149
  }
1150
}
1151

    
1152
/**
1153
 * Tests generic date and time handling capabilities of Drupal.
1154
 */
1155
class DateTimeFunctionalTest extends DrupalWebTestCase {
1156
  public static function getInfo() {
1157
    return array(
1158
      'name' => 'Date and time',
1159
      'description' => 'Configure date and time settings. Test date formatting and time zone handling, including daylight saving time.',
1160
      'group' => 'System',
1161
    );
1162
  }
1163

    
1164
  function setUp() {
1165
    parent::setUp(array('locale'));
1166

    
1167
    // Create admin user and log in admin user.
1168
    $this->admin_user = $this->drupalCreateUser(array('administer site configuration'));
1169
    $this->drupalLogin($this->admin_user);
1170
  }
1171

    
1172

    
1173
  /**
1174
   * Test time zones and DST handling.
1175
   */
1176
  function testTimeZoneHandling() {
1177
    // Setup date/time settings for Honolulu time.
1178
    variable_set('date_default_timezone', 'Pacific/Honolulu');
1179
    variable_set('configurable_timezones', 0);
1180
    variable_set('date_format_medium', 'Y-m-d H:i:s O');
1181

    
1182
    // Create some nodes with different authored-on dates.
1183
    $date1 = '2007-01-31 21:00:00 -1000';
1184
    $date2 = '2007-07-31 21:00:00 -1000';
1185
    $node1 = $this->drupalCreateNode(array('created' => strtotime($date1), 'type' => 'article'));
1186
    $node2 = $this->drupalCreateNode(array('created' => strtotime($date2), 'type' => 'article'));
1187

    
1188
    // Confirm date format and time zone.
1189
    $this->drupalGet("node/$node1->nid");
1190
    $this->assertText('2007-01-31 21:00:00 -1000', 'Date should be identical, with GMT offset of -10 hours.');
1191
    $this->drupalGet("node/$node2->nid");
1192
    $this->assertText('2007-07-31 21:00:00 -1000', 'Date should be identical, with GMT offset of -10 hours.');
1193

    
1194
    // Set time zone to Los Angeles time.
1195
    variable_set('date_default_timezone', 'America/Los_Angeles');
1196

    
1197
    // Confirm date format and time zone.
1198
    $this->drupalGet("node/$node1->nid");
1199
    $this->assertText('2007-01-31 23:00:00 -0800', 'Date should be two hours ahead, with GMT offset of -8 hours.');
1200
    $this->drupalGet("node/$node2->nid");
1201
    $this->assertText('2007-08-01 00:00:00 -0700', 'Date should be three hours ahead, with GMT offset of -7 hours.');
1202
  }
1203

    
1204
  /**
1205
   * Test date type configuration.
1206
   */
1207
  function testDateTypeConfiguration() {
1208
    // Confirm system date types appear.
1209
    $this->drupalGet('admin/config/regional/date-time');
1210
    $this->assertText(t('Medium'), 'System date types appear in date type list.');
1211
    $this->assertNoRaw('href="/admin/config/regional/date-time/types/medium/delete"', 'No delete link appear for system date types.');
1212

    
1213
    // Add custom date type.
1214
    $this->clickLink(t('Add date type'));
1215
    $date_type = strtolower($this->randomName(8));
1216
    $machine_name = 'machine_' . $date_type;
1217
    $date_format = 'd.m.Y - H:i';
1218
    $edit = array(
1219
      'date_type' => $date_type,
1220
      'machine_name' => $machine_name,
1221
      'date_format' => $date_format,
1222
    );
1223
    $this->drupalPost('admin/config/regional/date-time/types/add', $edit, t('Add date type'));
1224
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time', array('absolute' => TRUE)), 'Correct page redirection.');
1225
    $this->assertText(t('New date type added successfully.'), 'Date type added confirmation message appears.');
1226
    $this->assertText($date_type, 'Custom date type appears in the date type list.');
1227
    $this->assertText(t('delete'), 'Delete link for custom date type appears.');
1228

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

    
1236
  /**
1237
   * Test date format configuration.
1238
   */
1239
  function testDateFormatConfiguration() {
1240
    // Confirm 'no custom date formats available' message appears.
1241
    $this->drupalGet('admin/config/regional/date-time/formats');
1242
    $this->assertText(t('No custom date formats available.'), 'No custom date formats message appears.');
1243

    
1244
    // Add custom date format.
1245
    $this->clickLink(t('Add format'));
1246
    $edit = array(
1247
      'date_format' => 'Y',
1248
    );
1249
    $this->drupalPost('admin/config/regional/date-time/formats/add', $edit, t('Add format'));
1250
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE)), 'Correct page redirection.');
1251
    $this->assertNoText(t('No custom date formats available.'), 'No custom date formats message does not appear.');
1252
    $this->assertText(t('Custom date format added.'), 'Custom date format added.');
1253

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

    
1258
    // Edit custom date format.
1259
    $this->drupalGet('admin/config/regional/date-time/formats');
1260
    $this->clickLink(t('edit'));
1261
    $edit = array(
1262
      'date_format' => 'Y m',
1263
    );
1264
    $this->drupalPost($this->getUrl(), $edit, t('Save format'));
1265
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE)), 'Correct page redirection.');
1266
    $this->assertText(t('Custom date format updated.'), 'Custom date format successfully updated.');
1267

    
1268
    // Delete custom date format.
1269
    $this->clickLink(t('delete'));
1270
    $this->drupalPost($this->getUrl(), array(), t('Remove'));
1271
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE)), 'Correct page redirection.');
1272
    $this->assertText(t('Removed date format'), 'Custom date format removed successfully.');
1273
  }
1274

    
1275
  /**
1276
   * Test if the date formats are stored properly.
1277
   */
1278
  function testDateFormatStorage() {
1279
    $date_format = array(
1280
      'type' => 'short',
1281
      'format' => 'dmYHis',
1282
      'locked' => 0,
1283
      'is_new' => 1,
1284
    );
1285
    system_date_format_save($date_format);
1286

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

    
1296
    $format = db_select('date_format_locale', 'dfl')
1297
      ->fields('dfl', array('format'))
1298
      ->condition('type', 'short')
1299
      ->condition('format', 'dmYHis')
1300
      ->execute()
1301
      ->fetchField();
1302
    $this->assertFalse($format, 'Unlocalized date format resides not in localized table.');
1303

    
1304
    // Enable German language
1305
    locale_add_language('de', NULL, NULL, LANGUAGE_LTR, '', '', TRUE, 'en');
1306

    
1307
    $date_format = array(
1308
      'type' => 'short',
1309
      'format' => 'YMDHis',
1310
      'locales' => array('de', 'tr'),
1311
      'locked' => 0,
1312
      'is_new' => 1,
1313
    );
1314
    system_date_format_save($date_format);
1315

    
1316
    $format = db_select('date_format_locale', 'dfl')
1317
      ->fields('dfl', array('format'))
1318
      ->condition('type', 'short')
1319
      ->condition('format', 'YMDHis')
1320
      ->condition('language', 'de')
1321
      ->execute()
1322
      ->fetchField();
1323
    $this->assertEqual('YMDHis', $format, 'Localized date format resides in localized table.');
1324

    
1325
    $format = db_select('date_formats', 'df')
1326
      ->fields('df', array('format'))
1327
      ->condition('type', 'short')
1328
      ->condition('format', 'YMDHis')
1329
      ->execute()
1330
      ->fetchField();
1331
    $this->assertEqual('YMDHis', $format, 'Localized date format resides in general table too.');
1332

    
1333
    $format = db_select('date_format_locale', 'dfl')
1334
      ->fields('dfl', array('format'))
1335
      ->condition('type', 'short')
1336
      ->condition('format', 'YMDHis')
1337
      ->condition('language', 'tr')
1338
      ->execute()
1339
      ->fetchColumn();
1340
    $this->assertFalse($format, 'Localized date format for disabled language is ignored.');
1341
  }
1342
}
1343

    
1344
class PageTitleFiltering extends DrupalWebTestCase {
1345
  protected $content_user;
1346
  protected $saved_title;
1347

    
1348
  /**
1349
   * Implement getInfo().
1350
   */
1351
  public static function getInfo() {
1352
    return array(
1353
      'name' => 'HTML in page titles',
1354
      'description' => 'Tests correct handling or conversion by drupal_set_title() and drupal_get_title() and checks the correct escaping of site name and slogan.',
1355
      'group' => 'System'
1356
    );
1357
  }
1358

    
1359
  /**
1360
   * Implement setUp().
1361
   */
1362
  function setUp() {
1363
    parent::setUp();
1364

    
1365
    $this->content_user = $this->drupalCreateUser(array('create page content', 'access content', 'administer themes', 'administer site configuration'));
1366
    $this->drupalLogin($this->content_user);
1367
    $this->saved_title = drupal_get_title();
1368
  }
1369

    
1370
  /**
1371
   * Reset page title.
1372
   */
1373
  function tearDown() {
1374
    // Restore the page title.
1375
    drupal_set_title($this->saved_title, PASS_THROUGH);
1376

    
1377
    parent::tearDown();
1378
  }
1379

    
1380
  /**
1381
   * Tests the handling of HTML by drupal_set_title() and drupal_get_title()
1382
   */
1383
  function testTitleTags() {
1384
    $title = "string with <em>HTML</em>";
1385
    // drupal_set_title's $filter is CHECK_PLAIN by default, so the title should be
1386
    // returned with check_plain().
1387
    drupal_set_title($title, CHECK_PLAIN);
1388
    $this->assertTrue(strpos(drupal_get_title(), '<em>') === FALSE, 'Tags in title converted to entities when $output is CHECK_PLAIN.');
1389
    // drupal_set_title's $filter is passed as PASS_THROUGH, so the title should be
1390
    // returned with HTML.
1391
    drupal_set_title($title, PASS_THROUGH);
1392
    $this->assertTrue(strpos(drupal_get_title(), '<em>') !== FALSE, 'Tags in title are not converted to entities when $output is PASS_THROUGH.');
1393
    // Generate node content.
1394
    $langcode = LANGUAGE_NONE;
1395
    $edit = array(
1396
      "title" => '!SimpleTest! ' . $title . $this->randomName(20),
1397
      "body[$langcode][0][value]" => '!SimpleTest! test body' . $this->randomName(200),
1398
    );
1399
    // Create the node with HTML in the title.
1400
    $this->drupalPost('node/add/page', $edit, t('Save'));
1401

    
1402
    $node = $this->drupalGetNodeByTitle($edit["title"]);
1403
    $this->assertNotNull($node, 'Node created and found in database');
1404
    $this->drupalGet("node/" . $node->nid);
1405
    $this->assertText(check_plain($edit["title"]), 'Check to make sure tags in the node title are converted.');
1406
  }
1407
  /**
1408
   * Test if the title of the site is XSS proof.
1409
   */
1410
  function testTitleXSS() {
1411
    // Set some title with JavaScript and HTML chars to escape.
1412
    $title = '</title><script type="text/javascript">alert("Title XSS!");</script> & < > " \' ';
1413
    $title_filtered = check_plain($title);
1414

    
1415
    $slogan = '<script type="text/javascript">alert("Slogan XSS!");</script>';
1416
    $slogan_filtered = filter_xss_admin($slogan);
1417

    
1418
    // Activate needed appearance settings.
1419
    $edit = array(
1420
      'toggle_name'           => TRUE,
1421
      'toggle_slogan'         => TRUE,
1422
      'toggle_main_menu'      => TRUE,
1423
      'toggle_secondary_menu' => TRUE,
1424
    );
1425
    $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
1426

    
1427
    // Set title and slogan.
1428
    $edit = array(
1429
      'site_name'    => $title,
1430
      'site_slogan'  => $slogan,
1431
    );
1432
    $this->drupalPost('admin/config/system/site-information', $edit, t('Save configuration'));
1433

    
1434
    // Load frontpage.
1435
    $this->drupalGet('');
1436

    
1437
    // Test the title.
1438
    $this->assertNoRaw($title, 'Check for the unfiltered version of the title.');
1439
    // Adding </title> so we do not test the escaped version from drupal_set_title().
1440
    $this->assertRaw($title_filtered . '</title>', 'Check for the filtered version of the title.');
1441

    
1442
    // Test the slogan.
1443
    $this->assertNoRaw($slogan, 'Check for the unfiltered version of the slogan.');
1444
    $this->assertRaw($slogan_filtered, 'Check for the filtered version of the slogan.');
1445
  }
1446
}
1447

    
1448
/**
1449
 * Test front page functionality and administration.
1450
 */
1451
class FrontPageTestCase extends DrupalWebTestCase {
1452

    
1453
  public static function getInfo() {
1454
    return array(
1455
      'name' => 'Front page',
1456
      'description' => 'Tests front page functionality and administration.',
1457
      'group' => 'System',
1458
    );
1459
  }
1460

    
1461
  function setUp() {
1462
    parent::setUp('system_test');
1463

    
1464
    // Create admin user, log in admin user, and create one node.
1465
    $this->admin_user = $this->drupalCreateUser(array('access content', 'administer site configuration'));
1466
    $this->drupalLogin($this->admin_user);
1467
    $this->node_path = "node/" . $this->drupalCreateNode(array('promote' => 1))->nid;
1468

    
1469
    // Enable front page logging in system_test.module.
1470
    variable_set('front_page_output', 1);
1471
  }
1472

    
1473
  /**
1474
   * Test front page functionality.
1475
   */
1476
  function testDrupalIsFrontPage() {
1477
    $this->drupalGet('');
1478
    $this->assertText(t('On front page.'), 'Path is the front page.');
1479
    $this->drupalGet('node');
1480
    $this->assertText(t('On front page.'), 'Path is the front page.');
1481
    $this->drupalGet($this->node_path);
1482
    $this->assertNoText(t('On front page.'), 'Path is not the front page.');
1483

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

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

    
1494
    $this->drupalGet('');
1495
    $this->assertText(t('On front page.'), 'Path is the front page.');
1496
    $this->drupalGet('node');
1497
    $this->assertNoText(t('On front page.'), 'Path is not the front page.');
1498
    $this->drupalGet($this->node_path);
1499
    $this->assertText(t('On front page.'), 'Path is the front page.');
1500
  }
1501
}
1502

    
1503
class SystemBlockTestCase extends DrupalWebTestCase {
1504
  protected $profile = 'testing';
1505

    
1506
  public static function getInfo() {
1507
    return array(
1508
      'name' => 'Block functionality',
1509
      'description' => 'Configure and move powered-by block.',
1510
      'group' => 'System',
1511
    );
1512
  }
1513

    
1514
  function setUp() {
1515
    parent::setUp('block');
1516

    
1517
    // Create and login user
1518
    $admin_user = $this->drupalCreateUser(array('administer blocks', 'access administration pages'));
1519
    $this->drupalLogin($admin_user);
1520
  }
1521

    
1522
  /**
1523
   * Test displaying and hiding the powered-by and help blocks.
1524
   */
1525
  function testSystemBlocks() {
1526
    // Set block title and some settings to confirm that the interface is available.
1527
    $this->drupalPost('admin/structure/block/manage/system/powered-by/configure', array('title' => $this->randomName(8)), t('Save block'));
1528
    $this->assertText(t('The block configuration has been saved.'), t('Block configuration set.'));
1529

    
1530
    // Set the powered-by block to the footer region.
1531
    $edit = array();
1532
    $edit['blocks[system_powered-by][region]'] = 'footer';
1533
    $edit['blocks[system_main][region]'] = 'content';
1534
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1535
    $this->assertText(t('The block settings have been updated.'), t('Block successfully moved to footer region.'));
1536

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

    
1541
    // Set the block to the disabled region.
1542
    $edit = array();
1543
    $edit['blocks[system_powered-by][region]'] = '-1';
1544
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1545

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

    
1549
    // For convenience of developers, set the block to its default settings.
1550
    $edit = array();
1551
    $edit['blocks[system_powered-by][region]'] = 'footer';
1552
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1553
    $this->drupalPost('admin/structure/block/manage/system/powered-by/configure', array('title' => ''), t('Save block'));
1554

    
1555
    // Set the help block to the help region.
1556
    $edit = array();
1557
    $edit['blocks[system_help][region]'] = 'help';
1558
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1559

    
1560
    // Test displaying the help block with block caching enabled.
1561
    variable_set('block_cache', TRUE);
1562
    $this->drupalGet('admin/structure/block/add');
1563
    $this->assertRaw(t('Use this page to create a new custom block.'));
1564
    $this->drupalGet('admin/index');
1565
    $this->assertRaw(t('This page shows you all available administration tasks for each module.'));
1566
  }
1567
}
1568

    
1569
/**
1570
 * Test main content rendering fallback provided by system module.
1571
 */
1572
class SystemMainContentFallback extends DrupalWebTestCase {
1573
  protected $admin_user;
1574
  protected $web_user;
1575

    
1576
  public static function getInfo() {
1577
    return array(
1578
      'name' => 'Main content rendering fallback',
1579
      'description' => ' Test system module main content rendering fallback.',
1580
      'group' => 'System',
1581
    );
1582
  }
1583

    
1584
  function setUp() {
1585
    parent::setUp('system_test');
1586

    
1587
    // Create and login admin user.
1588
    $this->admin_user = $this->drupalCreateUser(array(
1589
      'access administration pages',
1590
      'administer site configuration',
1591
      'administer modules',
1592
      'administer blocks',
1593
      'administer nodes',
1594
    ));
1595
    $this->drupalLogin($this->admin_user);
1596

    
1597
    // Create a web user.
1598
    $this->web_user = $this->drupalCreateUser(array('access user profiles', 'access content'));
1599
  }
1600

    
1601
  /**
1602
   * Test availability of main content.
1603
   */
1604
  function testMainContentFallback() {
1605
    $edit = array();
1606
    // Disable the dashboard module, which depends on the block module.
1607
    $edit['modules[Core][dashboard][enable]'] = FALSE;
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
    // Disable the block module.
1611
    $edit['modules[Core][block][enable]'] = FALSE;
1612
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
1613
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
1614
    module_list(TRUE);
1615
    $this->assertFalse(module_exists('block'), 'Block module disabled.');
1616

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

    
1621
    // Fallback should not trigger when another module is handling content.
1622
    $this->drupalGet('system-test/main-content-handling');
1623
    $this->assertRaw('id="system-test-content"', 'Content handled by another module');
1624
    $this->assertText(t('Content to test main content fallback'), 'Main content still displayed.');
1625

    
1626
    // Fallback should trigger when another module
1627
    // indicates that it is not handling the content.
1628
    $this->drupalGet('system-test/main-content-fallback');
1629
    $this->assertText(t('Content to test main content fallback'), 'Main content fallback properly triggers.');
1630

    
1631
    // Fallback should not trigger when another module is handling content.
1632
    // Note that this test ensures that no duplicate
1633
    // content gets created by the fallback.
1634
    $this->drupalGet('system-test/main-content-duplication');
1635
    $this->assertNoText(t('Content to test main content fallback'), 'Main content not duplicated.');
1636

    
1637
    // Request a user* page and see if it is displayed.
1638
    $this->drupalLogin($this->web_user);
1639
    $this->drupalGet('user/' . $this->web_user->uid . '/edit');
1640
    $this->assertField('mail', 'User interface still available.');
1641

    
1642
    // Enable the block module again.
1643
    $this->drupalLogin($this->admin_user);
1644
    $edit = array();
1645
    $edit['modules[Core][block][enable]'] = 'block';
1646
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
1647
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
1648
    module_list(TRUE);
1649
    $this->assertTrue(module_exists('block'), 'Block module re-enabled.');
1650
  }
1651
}
1652

    
1653
/**
1654
 * Tests for the theme interface functionality.
1655
 */
1656
class SystemThemeFunctionalTest extends DrupalWebTestCase {
1657
  public static function getInfo() {
1658
    return array(
1659
      'name' => 'Theme interface functionality',
1660
      'description' => 'Tests the theme interface functionality by enabling and switching themes, and using an administration theme.',
1661
      'group' => 'System',
1662
    );
1663
  }
1664

    
1665
  function setUp() {
1666
    parent::setUp();
1667

    
1668
    $this->admin_user = $this->drupalCreateUser(array('access administration pages', 'view the administration theme', 'administer themes', 'bypass node access', 'administer blocks'));
1669
    $this->drupalLogin($this->admin_user);
1670
    $this->node = $this->drupalCreateNode();
1671
  }
1672

    
1673
  /**
1674
   * Test the theme settings form.
1675
   */
1676
  function testThemeSettings() {
1677
    // Specify a filesystem path to be used for the logo.
1678
    $file = current($this->drupalGetTestFiles('image'));
1679
    $file_relative = strtr($file->uri, array('public:/' => variable_get('file_public_path', conf_path() . '/files')));
1680
    $default_theme_path = 'themes/stark';
1681

    
1682
    $supported_paths = array(
1683
      // Raw stream wrapper URI.
1684
      $file->uri => array(
1685
        'form' => file_uri_target($file->uri),
1686
        'src' => file_create_url($file->uri),
1687
      ),
1688
      // Relative path within the public filesystem.
1689
      file_uri_target($file->uri) => array(
1690
        'form' => file_uri_target($file->uri),
1691
        'src' => file_create_url($file->uri),
1692
      ),
1693
      // Relative path to a public file.
1694
      $file_relative => array(
1695
        'form' => $file_relative,
1696
        'src' => file_create_url($file->uri),
1697
      ),
1698
      // Relative path to an arbitrary file.
1699
      'misc/druplicon.png' => array(
1700
        'form' => 'misc/druplicon.png',
1701
        'src' => $GLOBALS['base_url'] . '/' . 'misc/druplicon.png',
1702
      ),
1703
      // Relative path to a file in a theme.
1704
      $default_theme_path . '/logo.png' => array(
1705
        'form' => $default_theme_path . '/logo.png',
1706
        'src' => $GLOBALS['base_url'] . '/' . $default_theme_path . '/logo.png',
1707
      ),
1708
    );
1709
    foreach ($supported_paths as $input => $expected) {
1710
      $edit = array(
1711
        'default_logo' => FALSE,
1712
        'logo_path' => $input,
1713
      );
1714
      $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
1715
      $this->assertNoText('The custom logo path is invalid.');
1716
      $this->assertFieldByName('logo_path', $expected['form']);
1717

    
1718
      // Verify the actual 'src' attribute of the logo being output.
1719
      $this->drupalGet('');
1720
      $elements = $this->xpath('//*[@id=:id]/img', array(':id' => 'logo'));
1721
      $this->assertEqual((string) $elements[0]['src'], $expected['src']);
1722
    }
1723

    
1724
    $unsupported_paths = array(
1725
      // Stream wrapper URI to non-existing file.
1726
      'public://whatever.png',
1727
      'private://whatever.png',
1728
      'temporary://whatever.png',
1729
      // Bogus stream wrapper URIs.
1730
      'public:/whatever.png',
1731
      '://whatever.png',
1732
      ':whatever.png',
1733
      'public://',
1734
      // Relative path within the public filesystem to non-existing file.
1735
      'whatever.png',
1736
      // Relative path to non-existing file in public filesystem.
1737
      variable_get('file_public_path', conf_path() . '/files') . '/whatever.png',
1738
      // Semi-absolute path to non-existing file in public filesystem.
1739
      '/' . variable_get('file_public_path', conf_path() . '/files') . '/whatever.png',
1740
      // Relative path to arbitrary non-existing file.
1741
      'misc/whatever.png',
1742
      // Semi-absolute path to arbitrary non-existing file.
1743
      '/misc/whatever.png',
1744
      // Absolute paths to any local file (even if it exists).
1745
      drupal_realpath($file->uri),
1746
    );
1747
    $this->drupalGet('admin/appearance/settings');
1748
    foreach ($unsupported_paths as $path) {
1749
      $edit = array(
1750
        'default_logo' => FALSE,
1751
        'logo_path' => $path,
1752
      );
1753
      $this->drupalPost(NULL, $edit, t('Save configuration'));
1754
      $this->assertText('The custom logo path is invalid.');
1755
    }
1756

    
1757
    // Upload a file to use for the logo.
1758
    $edit = array(
1759
      'default_logo' => FALSE,
1760
      'logo_path' => '',
1761
      'files[logo_upload]' => drupal_realpath($file->uri),
1762
    );
1763
    $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
1764

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

    
1768
    $this->drupalGet('');
1769
    $elements = $this->xpath('//*[@id=:id]/img', array(':id' => 'logo'));
1770
    $this->assertEqual($elements[0]['src'], file_create_url($uploaded_filename));
1771
  }
1772

    
1773
  /**
1774
   * Test the administration theme functionality.
1775
   */
1776
  function testAdministrationTheme() {
1777
    theme_enable(array('stark'));
1778
    variable_set('theme_default', 'stark');
1779
    // Enable an administration theme and show it on the node admin pages.
1780
    $edit = array(
1781
      'admin_theme' => 'seven',
1782
      'node_admin_theme' => TRUE,
1783
    );
1784
    $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
1785

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

    
1789
    $this->drupalGet('node/' . $this->node->nid);
1790
    $this->assertRaw('themes/stark', 'Site default theme used on node page.');
1791

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

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

    
1798
    // Disable the admin theme on the node admin pages.
1799
    $edit = array(
1800
      'node_admin_theme' => FALSE,
1801
    );
1802
    $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
1803

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

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

    
1810
    // Reset to the default theme settings.
1811
    variable_set('theme_default', 'bartik');
1812
    $edit = array(
1813
      'admin_theme' => '0',
1814
      'node_admin_theme' => FALSE,
1815
    );
1816
    $this->drupalPost('admin/appearance', $edit, t('Save configuration'));
1817

    
1818
    $this->drupalGet('admin');
1819
    $this->assertRaw('themes/bartik', 'Site default theme used on administration page.');
1820

    
1821
    $this->drupalGet('node/add');
1822
    $this->assertRaw('themes/bartik', 'Site default theme used on the add content page.');
1823
  }
1824

    
1825
  /**
1826
   * Test switching the default theme.
1827
   */
1828
  function testSwitchDefaultTheme() {
1829
    // Enable "stark" and set it as the default theme.
1830
    theme_enable(array('stark'));
1831
    $this->drupalGet('admin/appearance');
1832
    $this->clickLink(t('Set default'), 1);
1833
    $this->assertTrue(variable_get('theme_default', '') == 'stark', 'Site default theme switched successfully.');
1834

    
1835
    // Test the default theme on the secondary links (blocks admin page).
1836
    $this->drupalGet('admin/structure/block');
1837
    $this->assertText('Stark(' . t('active tab') . ')', 'Default local task on blocks admin page is the default theme.');
1838
    // Switch back to Bartik and test again to test that the menu cache is cleared.
1839
    $this->drupalGet('admin/appearance');
1840
    $this->clickLink(t('Set default'), 0);
1841
    $this->drupalGet('admin/structure/block');
1842
    $this->assertText('Bartik(' . t('active tab') . ')', 'Default local task on blocks admin page has changed.');
1843
  }
1844
}
1845

    
1846

    
1847
/**
1848
 * Test the basic queue functionality.
1849
 */
1850
class QueueTestCase extends DrupalWebTestCase {
1851
  public static function getInfo() {
1852
    return array(
1853
      'name' => 'Queue functionality',
1854
      'description' => 'Queues and dequeues a set of items to check the basic queue functionality.',
1855
      'group' => 'System',
1856
    );
1857
  }
1858

    
1859
  /**
1860
   * Queues and dequeues a set of items to check the basic queue functionality.
1861
   */
1862
  function testQueue() {
1863
    // Create two queues.
1864
    $queue1 = DrupalQueue::get($this->randomName());
1865
    $queue1->createQueue();
1866
    $queue2 = DrupalQueue::get($this->randomName());
1867
    $queue2->createQueue();
1868

    
1869
    // Create four items.
1870
    $data = array();
1871
    for ($i = 0; $i < 4; $i++) {
1872
      $data[] = array($this->randomName() => $this->randomName());
1873
    }
1874

    
1875
    // Queue items 1 and 2 in the queue1.
1876
    $queue1->createItem($data[0]);
1877
    $queue1->createItem($data[1]);
1878

    
1879
    // Retrieve two items from queue1.
1880
    $items = array();
1881
    $new_items = array();
1882

    
1883
    $items[] = $item = $queue1->claimItem();
1884
    $new_items[] = $item->data;
1885

    
1886
    $items[] = $item = $queue1->claimItem();
1887
    $new_items[] = $item->data;
1888

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

    
1892
    // Add two more items.
1893
    $queue1->createItem($data[2]);
1894
    $queue1->createItem($data[3]);
1895

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

    
1899
    $items[] = $item = $queue1->claimItem();
1900
    $new_items[] = $item->data;
1901

    
1902
    $items[] = $item = $queue1->claimItem();
1903
    $new_items[] = $item->data;
1904

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

    
1909
    // There should be no duplicate items.
1910
    $this->assertEqual($this->queueScore($new_items, $new_items), 4, 'Four items matched');
1911

    
1912
    // Delete all items from queue1.
1913
    foreach ($items as $item) {
1914
      $queue1->deleteItem($item);
1915
    }
1916

    
1917
    // Check that both queues are empty.
1918
    $this->assertFalse($queue1->numberOfItems(), 'Queue 1 is empty');
1919
    $this->assertFalse($queue2->numberOfItems(), 'Queue 2 is empty');
1920
  }
1921

    
1922
  /**
1923
   * This function returns the number of equal items in two arrays.
1924
   */
1925
  function queueScore($items, $new_items) {
1926
    $score = 0;
1927
    foreach ($items as $item) {
1928
      foreach ($new_items as $new_item) {
1929
        if ($item === $new_item) {
1930
          $score++;
1931
        }
1932
      }
1933
    }
1934
    return $score;
1935
  }
1936
}
1937

    
1938
/**
1939
 * Test token replacement in strings.
1940
 */
1941
class TokenReplaceTestCase extends DrupalWebTestCase {
1942
  public static function getInfo() {
1943
    return array(
1944
      'name' => 'Token replacement',
1945
      'description' => 'Generates text using placeholders for dummy content to check token replacement.',
1946
      'group' => 'System',
1947
    );
1948
  }
1949

    
1950
  /**
1951
   * Creates a user and a node, then tests the tokens generated from them.
1952
   */
1953
  function testTokenReplacement() {
1954
    // Create the initial objects.
1955
    $account = $this->drupalCreateUser();
1956
    $node = $this->drupalCreateNode(array('uid' => $account->uid));
1957
    $node->title = '<blink>Blinking Text</blink>';
1958
    global $user, $language;
1959

    
1960
    $source  = '[node:title]';         // Title of the node we passed in
1961
    $source .= '[node:author:name]';   // Node author's name
1962
    $source .= '[node:created:since]'; // Time since the node was created
1963
    $source .= '[current-user:name]';  // Current user's name
1964
    $source .= '[date:short]';         // Short date format of REQUEST_TIME
1965
    $source .= '[user:name]';          // No user passed in, should be untouched
1966
    $source .= '[bogus:token]';        // Non-existent token
1967

    
1968
    $target  = check_plain($node->title);
1969
    $target .= check_plain($account->name);
1970
    $target .= format_interval(REQUEST_TIME - $node->created, 2, $language->language);
1971
    $target .= check_plain($user->name);
1972
    $target .= format_date(REQUEST_TIME, 'short', '', NULL, $language->language);
1973

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

    
1978
    // Test without using the clear parameter (non-existent token untouched).
1979
    $target .= '[user:name]';
1980
    $target .= '[bogus:token]';
1981
    $result = token_replace($source, array('node' => $node), array('language' => $language));
1982
    $this->assertEqual($target, $result, 'Valid tokens replaced while invalid tokens ignored.');
1983

    
1984
    // Check that the results of token_generate are sanitized properly. This does NOT
1985
    // test the cleanliness of every token -- just that the $sanitize flag is being
1986
    // passed properly through the call stack and being handled correctly by a 'known'
1987
    // token, [node:title].
1988
    $raw_tokens = array('title' => '[node:title]');
1989
    $generated = token_generate('node', $raw_tokens, array('node' => $node));
1990
    $this->assertEqual($generated['[node:title]'], check_plain($node->title), 'Token sanitized.');
1991

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

    
1995
    // Test token replacement when the string contains no tokens.
1996
    $this->assertEqual(token_replace('No tokens here.'), 'No tokens here.');
1997
  }
1998

    
1999
  /**
2000
   * Test whether token-replacement works in various contexts.
2001
   */
2002
  function testSystemTokenRecognition() {
2003
    global $language;
2004

    
2005
    // Generate prefixes and suffixes for the token context.
2006
    $tests = array(
2007
      array('prefix' => 'this is the ', 'suffix' => ' site'),
2008
      array('prefix' => 'this is the', 'suffix' => 'site'),
2009
      array('prefix' => '[', 'suffix' => ']'),
2010
      array('prefix' => '', 'suffix' => ']]]'),
2011
      array('prefix' => '[[[', 'suffix' => ''),
2012
      array('prefix' => ':[:', 'suffix' => '--]'),
2013
      array('prefix' => '-[-', 'suffix' => ':]:'),
2014
      array('prefix' => '[:', 'suffix' => ']'),
2015
      array('prefix' => '[site:', 'suffix' => ':name]'),
2016
      array('prefix' => '[site:', 'suffix' => ']'),
2017
    );
2018

    
2019
    // Check if the token is recognized in each of the contexts.
2020
    foreach ($tests as $test) {
2021
      $input = $test['prefix'] . '[site:name]' . $test['suffix'];
2022
      $expected = $test['prefix'] . 'Drupal' . $test['suffix'];
2023
      $output = token_replace($input, array(), array('language' => $language));
2024
      $this->assertTrue($output == $expected, format_string('Token recognized in string %string', array('%string' => $input)));
2025
    }
2026
  }
2027

    
2028
  /**
2029
   * Tests the generation of all system site information tokens.
2030
   */
2031
  function testSystemSiteTokenReplacement() {
2032
    global $language;
2033
    $url_options = array(
2034
      'absolute' => TRUE,
2035
      'language' => $language,
2036
    );
2037

    
2038
    // Set a few site variables.
2039
    variable_set('site_name', '<strong>Drupal<strong>');
2040
    variable_set('site_slogan', '<blink>Slogan</blink>');
2041

    
2042
    // Generate and test sanitized tokens.
2043
    $tests = array();
2044
    $tests['[site:name]'] = check_plain(variable_get('site_name', 'Drupal'));
2045
    $tests['[site:slogan]'] = check_plain(variable_get('site_slogan', ''));
2046
    $tests['[site:mail]'] = 'simpletest@example.com';
2047
    $tests['[site:url]'] = url('<front>', $url_options);
2048
    $tests['[site:url-brief]'] = preg_replace(array('!^https?://!', '!/$!'), '', url('<front>', $url_options));
2049
    $tests['[site:login-url]'] = url('user', $url_options);
2050

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

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

    
2059
    // Generate and test unsanitized tokens.
2060
    $tests['[site:name]'] = variable_get('site_name', 'Drupal');
2061
    $tests['[site:slogan]'] = variable_get('site_slogan', '');
2062

    
2063
    foreach ($tests as $input => $expected) {
2064
      $output = token_replace($input, array(), array('language' => $language, 'sanitize' => FALSE));
2065
      $this->assertEqual($output, $expected, format_string('Unsanitized system site information token %token replaced.', array('%token' => $input)));
2066
    }
2067
  }
2068

    
2069
  /**
2070
   * Tests the generation of all system date tokens.
2071
   */
2072
  function testSystemDateTokenReplacement() {
2073
    global $language;
2074

    
2075
    // Set time to one hour before request.
2076
    $date = REQUEST_TIME - 3600;
2077

    
2078
    // Generate and test tokens.
2079
    $tests = array();
2080
    $tests['[date:short]'] = format_date($date, 'short', '', NULL, $language->language);
2081
    $tests['[date:medium]'] = format_date($date, 'medium', '', NULL, $language->language);
2082
    $tests['[date:long]'] = format_date($date, 'long', '', NULL, $language->language);
2083
    $tests['[date:custom:m/j/Y]'] = format_date($date, 'custom', 'm/j/Y', NULL, $language->language);
2084
    $tests['[date:since]'] = format_interval((REQUEST_TIME - $date), 2, $language->language);
2085
    $tests['[date:raw]'] = filter_xss($date);
2086

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

    
2090
    foreach ($tests as $input => $expected) {
2091
      $output = token_replace($input, array('date' => $date), array('language' => $language));
2092
      $this->assertEqual($output, $expected, format_string('Date token %token replaced.', array('%token' => $input)));
2093
    }
2094
  }
2095
}
2096

    
2097
class InfoFileParserTestCase extends DrupalUnitTestCase {
2098
  public static function getInfo() {
2099
    return array(
2100
      'name' => 'Info file format parser',
2101
      'description' => 'Tests proper parsing of a .info file formatted string.',
2102
      'group' => 'System',
2103
    );
2104
  }
2105

    
2106
  /**
2107
   * Test drupal_parse_info_format().
2108
   */
2109
  function testDrupalParseInfoFormat() {
2110
    $config = '
2111
simple = Value
2112
quoted = " Value"
2113
multiline = "Value
2114
  Value"
2115
array[] = Value1
2116
array[] = Value2
2117
array_assoc[a] = Value1
2118
array_assoc[b] = Value2
2119
array_deep[][][] = Value
2120
array_deep_assoc[a][b][c] = Value
2121
array_space[a b] = Value';
2122

    
2123
    $expected = array(
2124
      'simple' => 'Value',
2125
      'quoted' => ' Value',
2126
      'multiline' => "Value\n  Value",
2127
      'array' => array(
2128
        0 => 'Value1',
2129
        1 => 'Value2',
2130
      ),
2131
      'array_assoc' => array(
2132
        'a' => 'Value1',
2133
        'b' => 'Value2',
2134
      ),
2135
      'array_deep' => array(
2136
        0 => array(
2137
          0 => array(
2138
            0 => 'Value',
2139
          ),
2140
        ),
2141
      ),
2142
      'array_deep_assoc' => array(
2143
        'a' => array(
2144
          'b' => array(
2145
            'c' => 'Value',
2146
          ),
2147
        ),
2148
      ),
2149
      'array_space' => array(
2150
        'a b' => 'Value',
2151
      ),
2152
    );
2153

    
2154
    $parsed = drupal_parse_info_format($config);
2155

    
2156
    $this->assertEqual($parsed['simple'], $expected['simple'], 'Set a simple value.');
2157
    $this->assertEqual($parsed['quoted'], $expected['quoted'], 'Set a simple value in quotes.');
2158
    $this->assertEqual($parsed['multiline'], $expected['multiline'], 'Set a multiline value.');
2159
    $this->assertEqual($parsed['array'], $expected['array'], 'Set a simple array.');
2160
    $this->assertEqual($parsed['array_assoc'], $expected['array_assoc'], 'Set an associative array.');
2161
    $this->assertEqual($parsed['array_deep'], $expected['array_deep'], 'Set a nested array.');
2162
    $this->assertEqual($parsed['array_deep_assoc'], $expected['array_deep_assoc'], 'Set a nested associative array.');
2163
    $this->assertEqual($parsed['array_space'], $expected['array_space'], 'Set an array with a whitespace in the key.');
2164
    $this->assertEqual($parsed, $expected, 'Entire parsed .info string and expected array are identical.');
2165
  }
2166
}
2167

    
2168
/**
2169
 * Tests the effectiveness of hook_system_info_alter().
2170
 */
2171
class SystemInfoAlterTestCase extends DrupalWebTestCase {
2172
  public static function getInfo() {
2173
    return array(
2174
      'name' => 'System info alter',
2175
      'description' => 'Tests the effectiveness of hook_system_info_alter().',
2176
      'group' => 'System',
2177
    );
2178
  }
2179

    
2180
  /**
2181
   * Tests that {system}.info is rebuilt after a module that implements
2182
   * hook_system_info_alter() is enabled. Also tests if core *_list() functions
2183
   * return freshly altered info.
2184
   */
2185
  function testSystemInfoAlter() {
2186
    // Enable our test module. Flush all caches, which we assert is the only
2187
    // thing necessary to use the rebuilt {system}.info.
2188
    module_enable(array('module_test'), FALSE);
2189
    drupal_flush_all_caches();
2190
    $this->assertTrue(module_exists('module_test'), 'Test module is enabled.');
2191

    
2192
    $info = $this->getSystemInfo('seven', 'theme');
2193
    $this->assertTrue(isset($info['regions']['test_region']), 'Altered theme info was added to {system}.info.');
2194
    $seven_regions = system_region_list('seven');
2195
    $this->assertTrue(isset($seven_regions['test_region']), 'Altered theme info was returned by system_region_list().');
2196
    $system_list_themes = system_list('theme');
2197
    $info = $system_list_themes['seven']->info;
2198
    $this->assertTrue(isset($info['regions']['test_region']), 'Altered theme info was returned by system_list().');
2199
    $list_themes = list_themes();
2200
    $this->assertTrue(isset($list_themes['seven']->info['regions']['test_region']), 'Altered theme info was returned by list_themes().');
2201

    
2202
    // Disable the module and verify that {system}.info is rebuilt without it.
2203
    module_disable(array('module_test'), FALSE);
2204
    drupal_flush_all_caches();
2205
    $this->assertFalse(module_exists('module_test'), 'Test module is disabled.');
2206

    
2207
    $info = $this->getSystemInfo('seven', 'theme');
2208
    $this->assertFalse(isset($info['regions']['test_region']), 'Altered theme info was removed from {system}.info.');
2209
    $seven_regions = system_region_list('seven');
2210
    $this->assertFalse(isset($seven_regions['test_region']), 'Altered theme info was not returned by system_region_list().');
2211
    $system_list_themes = system_list('theme');
2212
    $info = $system_list_themes['seven']->info;
2213
    $this->assertFalse(isset($info['regions']['test_region']), 'Altered theme info was not returned by system_list().');
2214
    $list_themes = list_themes();
2215
    $this->assertFalse(isset($list_themes['seven']->info['regions']['test_region']), 'Altered theme info was not returned by list_themes().');
2216
  }
2217

    
2218
  /**
2219
   * Returns the info array as it is stored in {system}.
2220
   *
2221
   * @param $name
2222
   *   The name of the record in {system}.
2223
   * @param $type
2224
   *   The type of record in {system}.
2225
   *
2226
   * @return
2227
   *   Array of info, or FALSE if the record is not found.
2228
   */
2229
  function getSystemInfo($name, $type) {
2230
    $raw_info = db_query("SELECT info FROM {system} WHERE name = :name AND type = :type", array(':name' => $name, ':type' => $type))->fetchField();
2231
    return $raw_info ? unserialize($raw_info) : FALSE;
2232
  }
2233
}
2234

    
2235
/**
2236
 * Tests for the update system functionality.
2237
 */
2238
class UpdateScriptFunctionalTest extends DrupalWebTestCase {
2239
  private $update_url;
2240
  private $update_user;
2241

    
2242
  public static function getInfo() {
2243
    return array(
2244
      'name' => 'Update functionality',
2245
      'description' => 'Tests the update script access and functionality.',
2246
      'group' => 'System',
2247
    );
2248
  }
2249

    
2250
  function setUp() {
2251
    parent::setUp('update_script_test');
2252
    $this->update_url = $GLOBALS['base_url'] . '/update.php';
2253
    $this->update_user = $this->drupalCreateUser(array('administer software updates'));
2254
  }
2255

    
2256
  /**
2257
   * Tests access to the update script.
2258
   */
2259
  function testUpdateAccess() {
2260
    // Try accessing update.php without the proper permission.
2261
    $regular_user = $this->drupalCreateUser();
2262
    $this->drupalLogin($regular_user);
2263
    $this->drupalGet($this->update_url, array('external' => TRUE));
2264
    $this->assertResponse(403);
2265

    
2266
    // Try accessing update.php as an anonymous user.
2267
    $this->drupalLogout();
2268
    $this->drupalGet($this->update_url, array('external' => TRUE));
2269
    $this->assertResponse(403);
2270

    
2271
    // Access the update page with the proper permission.
2272
    $this->drupalLogin($this->update_user);
2273
    $this->drupalGet($this->update_url, array('external' => TRUE));
2274
    $this->assertResponse(200);
2275

    
2276
    // Access the update page as user 1.
2277
    $user1 = user_load(1);
2278
    $user1->pass_raw = user_password();
2279
    require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
2280
    $user1->pass = user_hash_password(trim($user1->pass_raw));
2281
    db_query("UPDATE {users} SET pass = :pass WHERE uid = :uid", array(':pass' => $user1->pass, ':uid' => $user1->uid));
2282
    $this->drupalLogin($user1);
2283
    $this->drupalGet($this->update_url, array('external' => TRUE));
2284
    $this->assertResponse(200);
2285
  }
2286

    
2287
  /**
2288
   * Tests that requirements warnings and errors are correctly displayed.
2289
   */
2290
  function testRequirements() {
2291
    $this->drupalLogin($this->update_user);
2292

    
2293
    // If there are no requirements warnings or errors, we expect to be able to
2294
    // go through the update process uninterrupted.
2295
    $this->drupalGet($this->update_url, array('external' => TRUE));
2296
    $this->drupalPost(NULL, array(), t('Continue'));
2297
    $this->assertText(t('No pending updates.'), 'End of update process was reached.');
2298
    // Confirm that all caches were cleared.
2299
    $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared when there were no requirements warnings or errors.');
2300

    
2301
    // If there is a requirements warning, we expect it to be initially
2302
    // displayed, but clicking the link to proceed should allow us to go
2303
    // through the rest of the update process uninterrupted.
2304

    
2305
    // First, run this test with pending updates to make sure they can be run
2306
    // successfully.
2307
    variable_set('update_script_test_requirement_type', REQUIREMENT_WARNING);
2308
    drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
2309
    $this->drupalGet($this->update_url, array('external' => TRUE));
2310
    $this->assertText('This is a requirements warning provided by the update_script_test module.');
2311
    $this->clickLink('try again');
2312
    $this->assertNoText('This is a requirements warning provided by the update_script_test module.');
2313
    $this->drupalPost(NULL, array(), t('Continue'));
2314
    $this->drupalPost(NULL, array(), t('Apply pending updates'));
2315
    $this->assertText(t('The update_script_test_update_7000() update was executed successfully.'), 'End of update process was reached.');
2316
    // Confirm that all caches were cleared.
2317
    $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared after resolving a requirements warning and applying updates.');
2318

    
2319
    // Now try again without pending updates to make sure that works too.
2320
    $this->drupalGet($this->update_url, array('external' => TRUE));
2321
    $this->assertText('This is a requirements warning provided by the update_script_test module.');
2322
    $this->clickLink('try again');
2323
    $this->assertNoText('This is a requirements warning provided by the update_script_test module.');
2324
    $this->drupalPost(NULL, array(), t('Continue'));
2325
    $this->assertText(t('No pending updates.'), 'End of update process was reached.');
2326
    // Confirm that all caches were cleared.
2327
    $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared after applying updates and re-running the script.');
2328

    
2329
    // If there is a requirements error, it should be displayed even after
2330
    // clicking the link to proceed (since the problem that triggered the error
2331
    // has not been fixed).
2332
    variable_set('update_script_test_requirement_type', REQUIREMENT_ERROR);
2333
    $this->drupalGet($this->update_url, array('external' => TRUE));
2334
    $this->assertText('This is a requirements error provided by the update_script_test module.');
2335
    $this->clickLink('try again');
2336
    $this->assertText('This is a requirements error provided by the update_script_test module.');
2337
  }
2338

    
2339
  /**
2340
   * Tests the effect of using the update script on the theme system.
2341
   */
2342
  function testThemeSystem() {
2343
    // Since visiting update.php triggers a rebuild of the theme system from an
2344
    // unusual maintenance mode environment, we check that this rebuild did not
2345
    // put any incorrect information about the themes into the database.
2346
    $original_theme_data = db_query("SELECT * FROM {system} WHERE type = 'theme' ORDER BY name")->fetchAll();
2347
    $this->drupalLogin($this->update_user);
2348
    $this->drupalGet($this->update_url, array('external' => TRUE));
2349
    $final_theme_data = db_query("SELECT * FROM {system} WHERE type = 'theme' ORDER BY name")->fetchAll();
2350
    $this->assertEqual($original_theme_data, $final_theme_data, 'Visiting update.php does not alter the information about themes stored in the database.');
2351
  }
2352

    
2353
  /**
2354
   * Tests update.php when there are no updates to apply.
2355
   */
2356
  function testNoUpdateFunctionality() {
2357
    // Click through update.php with 'administer software updates' permission.
2358
    $this->drupalLogin($this->update_user);
2359
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
2360
    $this->assertText(t('No pending updates.'));
2361
    $this->assertNoLink('Administration pages');
2362
    $this->clickLink('Front page');
2363
    $this->assertResponse(200);
2364

    
2365
    // Click through update.php with 'access administration pages' permission.
2366
    $admin_user = $this->drupalCreateUser(array('administer software updates', 'access administration pages'));
2367
    $this->drupalLogin($admin_user);
2368
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
2369
    $this->assertText(t('No pending updates.'));
2370
    $this->clickLink('Administration pages');
2371
    $this->assertResponse(200);
2372
  }
2373

    
2374
  /**
2375
   * Tests update.php after performing a successful update.
2376
   */
2377
  function testSuccessfulUpdateFunctionality() {
2378
    drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
2379
    // Click through update.php with 'administer software updates' permission.
2380
    $this->drupalLogin($this->update_user);
2381
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
2382
    $this->drupalPost(NULL, array(), t('Apply pending updates'));
2383
    $this->assertText('Updates were attempted.');
2384
    $this->assertLink('site');
2385
    $this->assertNoLink('Administration pages');
2386
    $this->assertNoLink('logged');
2387
    $this->clickLink('Front page');
2388
    $this->assertResponse(200);
2389

    
2390
    drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
2391
    // Click through update.php with 'access administration pages' and
2392
    // 'access site reports' permissions.
2393
    $admin_user = $this->drupalCreateUser(array('administer software updates', 'access administration pages', 'access site reports'));
2394
    $this->drupalLogin($admin_user);
2395
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
2396
    $this->drupalPost(NULL, array(), t('Apply pending updates'));
2397
    $this->assertText('Updates were attempted.');
2398
    $this->assertLink('logged');
2399
    $this->clickLink('Administration pages');
2400
    $this->assertResponse(200);
2401
  }
2402
}
2403

    
2404
/**
2405
 * Functional tests for the flood control mechanism.
2406
 */
2407
class FloodFunctionalTest extends DrupalWebTestCase {
2408
  public static function getInfo() {
2409
    return array(
2410
      'name' => 'Flood control mechanism',
2411
      'description' => 'Functional tests for the flood control mechanism.',
2412
      'group' => 'System',
2413
    );
2414
  }
2415

    
2416
  /**
2417
   * Test flood control mechanism clean-up.
2418
   */
2419
  function testCleanUp() {
2420
    $threshold = 1;
2421
    $window_expired = -1;
2422
    $name = 'flood_test_cleanup';
2423

    
2424
    // Register expired event.
2425
    flood_register_event($name, $window_expired);
2426
    // Verify event is not allowed.
2427
    $this->assertFalse(flood_is_allowed($name, $threshold));
2428
    // Run cron and verify event is now allowed.
2429
    $this->cronRun();
2430
    $this->assertTrue(flood_is_allowed($name, $threshold));
2431

    
2432
    // Register unexpired event.
2433
    flood_register_event($name);
2434
    // Verify event is not allowed.
2435
    $this->assertFalse(flood_is_allowed($name, $threshold));
2436
    // Run cron and verify event is still not allowed.
2437
    $this->cronRun();
2438
    $this->assertFalse(flood_is_allowed($name, $threshold));
2439
  }
2440
}
2441

    
2442
/**
2443
 * Test HTTP file downloading capability.
2444
 */
2445
class RetrieveFileTestCase extends DrupalWebTestCase {
2446
  public static function getInfo() {
2447
    return array(
2448
      'name' => 'HTTP file retrieval',
2449
      'description' => 'Checks HTTP file fetching and error handling.',
2450
      'group' => 'System',
2451
    );
2452
  }
2453

    
2454
  /**
2455
   * Invokes system_retrieve_file() in several scenarios.
2456
   */
2457
  function testFileRetrieving() {
2458
    // Test 404 handling by trying to fetch a randomly named file.
2459
    drupal_mkdir($sourcedir = 'public://' . $this->randomName());
2460
    $filename = 'Файл для тестирования ' . $this->randomName();
2461
    $url = file_create_url($sourcedir . '/' . $filename);
2462
    $retrieved_file = system_retrieve_file($url);
2463
    $this->assertFalse($retrieved_file, 'Non-existent file not fetched.');
2464

    
2465
    // Actually create that file, download it via HTTP and test the returned path.
2466
    file_put_contents($sourcedir . '/' . $filename, 'testing');
2467
    $retrieved_file = system_retrieve_file($url);
2468

    
2469
    // URLs could not contains characters outside the ASCII set so $filename
2470
    // has to be encoded.
2471
    $encoded_filename = rawurlencode($filename);
2472

    
2473
    $this->assertEqual($retrieved_file, 'public://' . $encoded_filename, 'Sane path for downloaded file returned (public:// scheme).');
2474
    $this->assertTrue(is_file($retrieved_file), 'Downloaded file does exist (public:// scheme).');
2475
    $this->assertEqual(filesize($retrieved_file), 7, 'File size of downloaded file is correct (public:// scheme).');
2476
    file_unmanaged_delete($retrieved_file);
2477

    
2478
    // Test downloading file to a different location.
2479
    drupal_mkdir($targetdir = 'temporary://' . $this->randomName());
2480
    $retrieved_file = system_retrieve_file($url, $targetdir);
2481
    $this->assertEqual($retrieved_file, "$targetdir/$encoded_filename", 'Sane path for downloaded file returned (temporary:// scheme).');
2482
    $this->assertTrue(is_file($retrieved_file), 'Downloaded file does exist (temporary:// scheme).');
2483
    $this->assertEqual(filesize($retrieved_file), 7, 'File size of downloaded file is correct (temporary:// scheme).');
2484
    file_unmanaged_delete($retrieved_file);
2485

    
2486
    file_unmanaged_delete_recursive($sourcedir);
2487
    file_unmanaged_delete_recursive($targetdir);
2488
  }
2489
}
2490

    
2491
/**
2492
 * Functional tests shutdown functions.
2493
 */
2494
class ShutdownFunctionsTest extends DrupalWebTestCase {
2495
  public static function getInfo() {
2496
    return array(
2497
      'name' => 'Shutdown functions',
2498
      'description' => 'Functional tests for shutdown functions',
2499
      'group' => 'System',
2500
    );
2501
  }
2502

    
2503
  function setUp() {
2504
    parent::setUp('system_test');
2505
  }
2506

    
2507
  /**
2508
   * Test shutdown functions.
2509
   */
2510
  function testShutdownFunctions() {
2511
    $arg1 = $this->randomName();
2512
    $arg2 = $this->randomName();
2513
    $this->drupalGet('system-test/shutdown-functions/' . $arg1 . '/' . $arg2);
2514
    $this->assertText(t('First shutdown function, arg1 : @arg1, arg2: @arg2', array('@arg1' => $arg1, '@arg2' => $arg2)));
2515
    $this->assertText(t('Second shutdown function, arg1 : @arg1, arg2: @arg2', array('@arg1' => $arg1, '@arg2' => $arg2)));
2516

    
2517
    // Make sure exceptions displayed through _drupal_render_exception_safe()
2518
    // are correctly escaped.
2519
    $this->assertRaw('Drupal is &amp;lt;blink&amp;gt;awesome&amp;lt;/blink&amp;gt;.');
2520
  }
2521
}
2522

    
2523
/**
2524
 * Tests administrative overview pages.
2525
 */
2526
class SystemAdminTestCase extends DrupalWebTestCase {
2527
  public static function getInfo() {
2528
    return array(
2529
      'name' => 'Administrative pages',
2530
      'description' => 'Tests output on administrative pages and compact mode functionality.',
2531
      'group' => 'System',
2532
    );
2533
  }
2534

    
2535
  function setUp() {
2536
    // testAdminPages() requires Locale module.
2537
    parent::setUp(array('locale'));
2538

    
2539
    // Create an administrator with all permissions, as well as a regular user
2540
    // who can only access administration pages and perform some Locale module
2541
    // administrative tasks, but not all of them.
2542
    $this->admin_user = $this->drupalCreateUser(array_keys(module_invoke_all('permission')));
2543
    $this->web_user = $this->drupalCreateUser(array(
2544
      'access administration pages',
2545
      'translate interface',
2546
    ));
2547
    $this->drupalLogin($this->admin_user);
2548
  }
2549

    
2550
  /**
2551
   * Tests output on administrative listing pages.
2552
   */
2553
  function testAdminPages() {
2554
    // Go to Administration.
2555
    $this->drupalGet('admin');
2556

    
2557
    // Verify that all visible, top-level administration links are listed on
2558
    // the main administration page.
2559
    foreach (menu_get_router() as $path => $item) {
2560
      if (strpos($path, 'admin/') === 0 && ($item['type'] & MENU_VISIBLE_IN_TREE) && $item['_number_parts'] == 2) {
2561
        $this->assertLink($item['title']);
2562
        $this->assertLinkByHref($path);
2563
        $this->assertText($item['description']);
2564
      }
2565
    }
2566

    
2567
    // For each administrative listing page on which the Locale module appears,
2568
    // verify that there are links to the module's primary configuration pages,
2569
    // but no links to its individual sub-configuration pages. Also verify that
2570
    // a user with access to only some Locale module administration pages only
2571
    // sees links to the pages they have access to.
2572
    $admin_list_pages = array(
2573
      'admin/index',
2574
      'admin/config',
2575
      'admin/config/regional',
2576
    );
2577

    
2578
    foreach ($admin_list_pages as $page) {
2579
      // For the administrator, verify that there are links to Locale's primary
2580
      // configuration pages, but no links to individual sub-configuration
2581
      // pages.
2582
      $this->drupalLogin($this->admin_user);
2583
      $this->drupalGet($page);
2584
      $this->assertLinkByHref('admin/config');
2585
      $this->assertLinkByHref('admin/config/regional/settings');
2586
      $this->assertLinkByHref('admin/config/regional/date-time');
2587
      $this->assertLinkByHref('admin/config/regional/language');
2588
      $this->assertNoLinkByHref('admin/config/regional/language/configure/session');
2589
      $this->assertNoLinkByHref('admin/config/regional/language/configure/url');
2590
      $this->assertLinkByHref('admin/config/regional/translate');
2591
      // On admin/index only, the administrator should also see a "Configure
2592
      // permissions" link for the Locale module.
2593
      if ($page == 'admin/index') {
2594
        $this->assertLinkByHref("admin/people/permissions#module-locale");
2595
      }
2596

    
2597
      // For a less privileged user, verify that there are no links to Locale's
2598
      // primary configuration pages, but a link to the translate page exists.
2599
      $this->drupalLogin($this->web_user);
2600
      $this->drupalGet($page);
2601
      $this->assertLinkByHref('admin/config');
2602
      $this->assertNoLinkByHref('admin/config/regional/settings');
2603
      $this->assertNoLinkByHref('admin/config/regional/date-time');
2604
      $this->assertNoLinkByHref('admin/config/regional/language');
2605
      $this->assertNoLinkByHref('admin/config/regional/language/configure/session');
2606
      $this->assertNoLinkByHref('admin/config/regional/language/configure/url');
2607
      $this->assertLinkByHref('admin/config/regional/translate');
2608
      // This user cannot configure permissions, so even on admin/index should
2609
      // not see a "Configure permissions" link for the Locale module.
2610
      if ($page == 'admin/index') {
2611
        $this->assertNoLinkByHref("admin/people/permissions#module-locale");
2612
      }
2613
    }
2614
  }
2615

    
2616
  /**
2617
   * Test compact mode.
2618
   */
2619
  function testCompactMode() {
2620
    $this->drupalGet('admin/compact/on');
2621
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode turns on.');
2622
    $this->drupalGet('admin/compact/on');
2623
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode remains on after a repeat call.');
2624
    $this->drupalGet('');
2625
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode persists on new requests.');
2626

    
2627
    $this->drupalGet('admin/compact/off');
2628
    $this->assertEqual($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'deleted', 'Compact mode turns off.');
2629
    $this->drupalGet('admin/compact/off');
2630
    $this->assertEqual($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'deleted', 'Compact mode remains off after a repeat call.');
2631
    $this->drupalGet('');
2632
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode persists on new requests.');
2633
  }
2634
}
2635

    
2636
/**
2637
 * Tests authorize.php and related hooks.
2638
 */
2639
class SystemAuthorizeCase extends DrupalWebTestCase {
2640
  public static function getInfo() {
2641
    return array(
2642
      'name' => 'Authorize API',
2643
      'description' => 'Tests the authorize.php script and related API.',
2644
      'group' => 'System',
2645
    );
2646
  }
2647

    
2648
  function setUp() {
2649
    parent::setUp(array('system_test'));
2650

    
2651
    variable_set('allow_authorize_operations', TRUE);
2652

    
2653
    // Create an administrator user.
2654
    $this->admin_user = $this->drupalCreateUser(array('administer software updates'));
2655
    $this->drupalLogin($this->admin_user);
2656
  }
2657

    
2658
  /**
2659
   * Helper function to initialize authorize.php and load it via drupalGet().
2660
   *
2661
   * Initializing authorize.php needs to happen in the child Drupal
2662
   * installation, not the parent. So, we visit a menu callback provided by
2663
   * system_test.module which calls system_authorized_init() to initialize the
2664
   * $_SESSION inside the test site, not the framework site. This callback
2665
   * redirects to authorize.php when it's done initializing.
2666
   *
2667
   * @see system_authorized_init().
2668
   */
2669
  function drupalGetAuthorizePHP($page_title = 'system-test-auth') {
2670
    $this->drupalGet('system-test/authorize-init/' . $page_title);
2671
  }
2672

    
2673
  /**
2674
   * Tests the FileTransfer hooks
2675
   */
2676
  function testFileTransferHooks() {
2677
    $page_title = $this->randomName(16);
2678
    $this->drupalGetAuthorizePHP($page_title);
2679
    $this->assertTitle(strtr('@title | Drupal', array('@title' => $page_title)), 'authorize.php page title is correct.');
2680
    $this->assertNoText('It appears you have reached this page in error.');
2681
    $this->assertText('To continue, provide your server connection details');
2682
    // Make sure we see the new connection method added by system_test.
2683
    $this->assertRaw('System Test FileTransfer');
2684
    // Make sure the settings form callback works.
2685
    $this->assertText('System Test Username');
2686
  }
2687
}
2688

    
2689
/**
2690
 * Test the handling of requests containing 'index.php'.
2691
 */
2692
class SystemIndexPhpTest extends DrupalWebTestCase {
2693
  public static function getInfo() {
2694
    return array(
2695
      'name' => 'Index.php handling',
2696
      'description' => "Test the handling of requests containing 'index.php'.",
2697
      'group' => 'System',
2698
    );
2699
  }
2700

    
2701
  function setUp() {
2702
    parent::setUp();
2703
  }
2704

    
2705
  /**
2706
   * Test index.php handling.
2707
   */
2708
  function testIndexPhpHandling() {
2709
    $index_php = $GLOBALS['base_url'] . '/index.php';
2710

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

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

    
2717
    $this->drupalGet($index_php .'/user', array('external' => TRUE));
2718
    $this->assertResponse(404, "Make sure index.php/user returns a 'page not found'.");
2719
  }
2720
}
2721

    
2722
/**
2723
 * Test token replacement in strings.
2724
 */
2725
class TokenScanTest extends DrupalWebTestCase {
2726

    
2727
  public static function getInfo() {
2728
    return array(
2729
      'name' => 'Token scanning',
2730
      'description' => 'Scan token-like patterns in a dummy text to check token scanning.',
2731
      'group' => 'System',
2732
    );
2733
  }
2734

    
2735
  /**
2736
   * Scans dummy text, then tests the output.
2737
   */
2738
  function testTokenScan() {
2739
    // Define text with valid and not valid, fake and existing token-like
2740
    // strings.
2741
    $text = 'First a [valid:simple], but dummy token, and a dummy [valid:token with: spaces].';
2742
    $text .= 'Then a [not valid:token].';
2743
    $text .= 'Last an existing token: [node:author:name].';
2744
    $token_wannabes = token_scan($text);
2745

    
2746
    $this->assertTrue(isset($token_wannabes['valid']['simple']), 'A simple valid token has been matched.');
2747
    $this->assertTrue(isset($token_wannabes['valid']['token with: spaces']), 'A valid token with space characters in the token name has been matched.');
2748
    $this->assertFalse(isset($token_wannabes['not valid']), 'An invalid token with spaces in the token type has not been matched.');
2749
    $this->assertTrue(isset($token_wannabes['node']), 'An existing valid token has been matched.');
2750
  }
2751
}
2752

    
2753
/**
2754
 * Test case for drupal_valid_token().
2755
 */
2756
class SystemValidTokenTest extends DrupalUnitTestCase {
2757

    
2758
  /**
2759
   * Flag to indicate whether PHP error reportings should be asserted.
2760
   *
2761
   * @var bool
2762
   */
2763
  protected $assertErrors = TRUE;
2764

    
2765
  public static function getInfo() {
2766
    return array(
2767
      'name' => 'Token validation',
2768
      'description' => 'Test the security token validation.',
2769
      'group' => 'System',
2770
    );
2771
  }
2772

    
2773
  /**
2774
   * Tests invalid invocations of drupal_valid_token() that must return FALSE.
2775
   */
2776
  public function testTokenValidation() {
2777
    // The following checks will throw PHP notices, so we disable error
2778
    // assertions.
2779
    $this->assertErrors = FALSE;
2780
    $this->assertFalse(drupal_valid_token(NULL, new stdClass()), 'Token NULL, value object returns FALSE.');
2781
    $this->assertFalse(drupal_valid_token(0, array()), 'Token 0, value array returns FALSE.');
2782
    $this->assertFalse(drupal_valid_token('', array()), "Token '', value array returns FALSE.");
2783
    $this->assertFalse('' === drupal_get_token(array()), 'Token generation does not return an empty string on invalid parameters.');
2784
    $this->assertErrors = TRUE;
2785

    
2786
    $this->assertFalse(drupal_valid_token(TRUE, 'foo'), 'Token TRUE, value foo returns FALSE.');
2787
    $this->assertFalse(drupal_valid_token(0, 'foo'), 'Token 0, value foo returns FALSE.');
2788
  }
2789

    
2790
  /**
2791
   * Overrides DrupalTestCase::errorHandler().
2792
   */
2793
  public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
2794
    if ($this->assertErrors) {
2795
      return parent::errorHandler($severity, $message, $file, $line);
2796
    }
2797
    return TRUE;
2798
  }
2799
}