summaryrefslogtreecommitdiff
path: root/modules/system/system.test
blob: 2c642adff50b58c15a4cf61e36ecf8876aa6a131 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
<?php
// $Id$

/**
 * Helper class for module test cases.
 */
class ModuleTestCase extends DrupalWebTestCase {
  protected $admin_user;

  function setUp() {
    parent::setUp('system_test');

    $this->admin_user = $this->drupalCreateUser(array('access administration pages', 'administer site configuration'));
    $this->drupalLogin($this->admin_user);
  }

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

    if ($count) {
      return $this->assertTrue($tables, t('Tables matching "@base_table" found.', array('@base_table' => $base_table)));
    }
    return $this->assertFalse($tables, t('Tables matching "@base_table" not found.', array('@base_table' => $base_table)));
  }

  /**
   * Assert the list of modules are enabled or disabled.
   *
   * @param $modules
   *   Module list to check.
   * @param $enabled
   *   Expected module state.
   */
  function assertModules(array $modules, $enabled) {
    module_list(TRUE);
    foreach ($modules as $module) {
      if ($enabled) {
        $message = 'Module "@module" is enabled.';
      }
      else {
        $message = 'Module "@module" is not enabled.';
      }
      $this->assertEqual(module_exists($module), $enabled, t($message, array('@module' => $module)));
    }
  }

  /**
   * Verify a log entry was entered for a module's status change.
   * Called in the same way of the expected original watchdog() execution.
   *
   * @param $type
   *   The category to which this message belongs.
   * @param $message
   *   The message to store in the log. Keep $message translatable
   *   by not concatenating dynamic values into it! Variables in the
   *   message should be added by using placeholder strings alongside
   *   the variables argument to declare the value of the placeholders.
   *   See t() for documentation on how $message and $variables interact.
   * @param $variables
   *   Array of variables to replace in the message on display or
   *   NULL if message is already translated or not possible to
   *   translate.
   * @param $severity
   *   The severity of the message, as per RFC 3164.
   * @param $link
   *   A link to associate with the message.
   */
  function assertLogMessage($type, $message, $variables = array(), $severity = WATCHDOG_NOTICE, $link = '') {
    $count = db_select('watchdog', 'w')
      ->condition('type', $type)
      ->condition('message', $message)
      ->condition('variables', serialize($variables))
      ->condition('severity', $severity)
      ->condition('link', $link)
      ->countQuery()
      ->execute()
      ->fetchField();
    $this->assertTrue($count > 0, t('watchdog table contains @count rows for @message', array('@count' => $count, '@message' => $message)));
  }
}

/**
 * Test module enabling/disabling functionality.
 */
class EnableDisableTestCase extends ModuleTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Enable/disable modules',
      'description' => 'Enable/disable core module and confirm table creation/deletion.',
      'group' => 'Module',
    );
  }

  /**
   * Enable a module, check the database for related tables, disable module,
   * check for related tables, uninstall module, check for related tables.
   * Also check for invocation of the hook_module_action hook.
   */
  function testEnableDisable() {
    // Enable aggregator, and check tables.
    $this->assertModules(array('aggregator'), FALSE);
    $this->assertTableCount('aggregator', FALSE);

    // Install (and enable) aggregator module.
    $edit = array();
    $edit['modules[Core][aggregator][enable]'] = 'aggregator';
    $edit['modules[Core][forum][enable]'] = 'forum';
    $this->drupalPost('admin/config/modules', $edit, t('Save configuration'));
    $this->assertText(t('The configuration options have been saved.'), t('Modules status has been updated.'));

    // Check that hook_modules_installed and hook_modules_enabled hooks were invoked and check tables.
    $this->assertText(t('hook_modules_installed fired for aggregator'), t('hook_modules_installed fired.'));
    $this->assertText(t('hook_modules_enabled fired for aggregator'), t('hook_modules_enabled fired.'));
    $this->assertModules(array('aggregator'), TRUE);
    $this->assertTableCount('aggregator', TRUE);
    $this->assertLogMessage('system', "%module module enabled.", array('%module' => 'aggregator'), WATCHDOG_INFO);

    // Disable aggregator, check tables, uninstall aggregator, check tables.
    $edit = array();
    $edit['modules[Core][aggregator][enable]'] = FALSE;
    $this->drupalPost('admin/config/modules', $edit, t('Save configuration'));
    $this->assertText(t('The configuration options have been saved.'), t('Modules status has been updated.'));

    // Check that hook_modules_disabled hook was invoked and check tables.
    $this->assertText(t('hook_modules_disabled fired for aggregator'), t('hook_modules_disabled fired.'));
    $this->assertModules(array('aggregator'), FALSE);
    $this->assertTableCount('aggregator', TRUE);
    $this->assertLogMessage('system', "%module module disabled.", array('%module' => 'aggregator'), WATCHDOG_INFO);

    // Uninstall the module.
    $edit = array();
    $edit['uninstall[aggregator]'] = 'aggregator';
    $this->drupalPost('admin/config/modules/uninstall', $edit, t('Uninstall'));

    $this->drupalPost(NULL, NULL, t('Uninstall'));
    $this->assertText(t('The selected modules have been uninstalled.'), t('Modules status has been updated.'));

    // Check that hook_modules_uninstalled hook was invoked and check tables.
    $this->assertText(t('hook_modules_uninstalled fired for aggregator'), t('hook_modules_uninstalled fired.'));
    $this->assertModules(array('aggregator'), FALSE);
    $this->assertTableCount('aggregator', FALSE);
    $this->assertLogMessage('system', "%module module uninstalled.", array('%module' => 'aggregator'), WATCHDOG_INFO);

    // Reinstall (and enable) aggregator module.
    $edit = array();
    $edit['modules[Core][aggregator][enable]'] = 'aggregator';
    $this->drupalPost('admin/config/modules', $edit, t('Save configuration'));
    $this->assertText(t('The configuration options have been saved.'), t('Modules status has been updated.'));
  }
}

/**
 * Test module dependency functionality.
 */
class ModuleDependencyTestCase extends ModuleTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Module dependencies',
      'description' => 'Enable module without dependency enabled.',
      'group' => 'Module',
    );
  }

  /**
   * Attempt to enable translation module without locale enabled.
   */
  function testEnableWithoutDependency() {
    // Attempt to enable content translation without locale enabled.
    $edit = array();
    $edit['modules[Core][translation][enable]'] = 'translation';
    $this->drupalPost('admin/config/modules', $edit, t('Save configuration'));
    $this->assertText(t('Some required modules must be enabled'), t('Dependecy required.'));

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

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

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

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

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

/**
 * Test module dependency on specific versions.
 */
class ModuleVersionTestCase extends ModuleTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Module versions',
      'description' => 'Check module version dependencies.',
      'group' => 'Module',
    );
  }

  function setup() {
    parent::setUp('module_test');
  }

  /**
   * Test version dependencies.
   */
  function testModuleVersions() {
    $dependencies = array(
      // Alternating between being compatible and incompatible with 7.x-2.4-beta3.
      // The first is always a compatible.
      'common_test',
      // Branch incompatibility.
      'common_test (1.x)',
      // Branch compatibility.
      'common_test (2.x)',
      // Another branch incompatibility.
      'common_test (>2.x)',
      // Another branch compatibility.
      'common_test (<=2.x)',
      // Another branch incompatibility.
      'common_test (<2.x)',
      // Another branch compatibility.
      'common_test (>=2.x)',
      // Nonsense, misses a dash. Incompatible with everything.
      'common_test (=7.x2.x, >=2.4)',
      // Core version is optional. Compatible.
      'common_test (=7.x-2.x, >=2.4-alpha2)',
      // Test !=, explicitly incompatible.
      'common_test (=2.x, !=2.4-beta3)',
      // Three operations. Compatible.
      'common_test (=2.x, !=2.3, <2.5)',
      // Testing extra version. Incompatible.
      'common_test (<=2.4-beta2)',
      // Testing extra version. Compatible.
      'common_test (>2.4-beta2)',
      // Testing extra version. Incompatible.
      'common_test (>2.4-rc0)',
    );
    variable_set('dependencies', $dependencies);
    $n = count($dependencies);
    for ($i = 0; $i < $n; $i++) {
      $this->drupalGet('admin/config/modules');
      $checkbox = $this->xpath('//input[@id="edit-modules-Testing-module-test-enable"]');
      $this->assertEqual(!empty($checkbox[0]['disabled']), $i % 2, $dependencies[$i]);
    }
  }
}

/**
 * Test required modules functionality.
 */
class ModuleRequiredTestCase extends ModuleTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Required modules',
      'description' => 'Attempt disabling of required modules.',
      'group' => 'Module',
    );
  }

  /**
   * Assert that core required modules cannot be disabled.
   */
  function testDisableRequired() {
    $required_modules = drupal_required_modules();
    $this->drupalGet('admin/config/modules');
    foreach ($required_modules as $module) {
      // Check to make sure the checkbox for required module is not found.
      $this->assertNoFieldByName('modules[Core][' . $module . '][enable]');
    }
  }
}

class IPAddressBlockingTestCase extends DrupalWebTestCase {
  protected $blocking_user;

  /**
   * Implement getInfo().
   */
  public static function getInfo() {
    return array(
      'name' => 'IP address blocking',
      'description' => 'Test IP address blocking.',
      'group' => 'System'
    );
  }

  /**
   * Implement setUp().
   */
  function setUp() {
    parent::setUp();

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

  /**
   * Test a variety of user input to confirm correct validation and saving of data.
   */
  function testIPAddressValidation() {
    $this->drupalGet('admin/settings/ip-blocking');

    // Block a valid IP address.
    $edit = array();
    $edit['ip'] = '192.168.1.1';
    $this->drupalPost('admin/settings/ip-blocking', $edit, t('Save'));
    $ip = db_query("SELECT iid from {blocked_ips} WHERE ip = :ip", array(':ip' => $edit['ip']))->fetchField();
    $this->assertNotNull($ip, t('IP address found in database'));
    $this->assertRaw(t('The IP address %ip has been blocked.', array('%ip' => $edit['ip'])), t('IP address was blocked.'));

    // Try to block an IP address that's already blocked.
    $edit = array();
    $edit['ip'] = '192.168.1.1';
    $this->drupalPost('admin/settings/ip-blocking', $edit, t('Save'));
    $this->assertText(t('This IP address is already blocked.'));

    // Try to block a reserved IP address.
    $edit = array();
    $edit['ip'] = '255.255.255.255';
    $this->drupalPost('admin/settings/ip-blocking', $edit, t('Save'));
    $this->assertText(t('Please enter a valid IP address.'));

    // Try to block a reserved IP address.
    $edit = array();
    $edit['ip'] = 'test.example.com';
    $this->drupalPost('admin/settings/ip-blocking', $edit, t('Save'));
    $this->assertText(t('Please enter a valid IP address.'));

    // Submit an empty form.
    $edit = array();
    $edit['ip'] = '';
    $this->drupalPost('admin/settings/ip-blocking', $edit, t('Save'));
    $this->assertText(t('Please enter a valid IP address.'));

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

class CronRunTestCase extends DrupalWebTestCase {
  /**
   * Implement getInfo().
   */
  public static function getInfo() {
    return array(
      'name' => 'Cron run',
      'description' => 'Test cron run.',
      'group' => 'System'
    );
  }

  /**
   * Test cron runs.
   */
  function testCronRun() {
    global $base_url;
    // Run cron anonymously without any cron key.
    $this->drupalGet($base_url . '/cron.php', array('external' => TRUE));
    $this->assertResponse(403);

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

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

    // Execute cron directly.
    $this->assertTrue(drupal_cron_run(), t('Cron ran successfully.'));
  }

  /**
   * Ensure that temporary files are removed.
   */
  function testTempFileCleanup() {
    // Create files for all the possible combinations of age and status. We're
    // using UPDATE statments rather than file_save() because it would set the
    // timestamp.

    // Temporary file that is older than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
    $temp_old = file_save_data('');
    db_update('file')
      ->fields(array(
        'status' => 0,
        'timestamp' => 1,
      ))
      ->condition('fid', $temp_old->fid)
      ->execute();
    $this->assertTrue(file_exists($temp_old->uri), t('Old temp file was created correctly.'));

    // Temporary file that is less than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
    $temp_new = file_save_data('');
    db_update('file')
      ->fields(array('status' => 0))
      ->condition('fid', $temp_new->fid)
      ->execute();
    $this->assertTrue(file_exists($temp_new->uri), t('New temp file was created correctly.'));

    // Permanent file that is older than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
    $perm_old = file_save_data('');
    db_update('file')
      ->fields(array('timestamp' => 1))
      ->condition('fid', $temp_old->fid)
      ->execute();
    $this->assertTrue(file_exists($perm_old->uri), t('Old permanent file was created correctly.'));

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

    // Run cron and then ensure that only the old, temp file was deleted.
    $this->assertTrue(drupal_cron_run(), t('Cron ran successfully.'));
    $this->assertFalse(file_exists($temp_old->uri), t('Old temp file was correctly removed.'));
    $this->assertTrue(file_exists($temp_new->uri), t('New temp file was correctly ignored.'));
    $this->assertTrue(file_exists($perm_old->uri), t('Old permanent file was correctly ignored.'));
    $this->assertTrue(file_exists($perm_new->uri), t('New permanent file was correctly ignored.'));
  }
}

class AdminMetaTagTestCase extends DrupalWebTestCase {
  /**
   * Implement getInfo().
   */
  public static function getInfo() {
    return array(
      'name' => 'Fingerprinting meta tag',
      'description' => 'Confirm that the fingerprinting meta tag appears as expected.',
      'group' => 'System'
    );
  }

  /**
   * Verify that the meta tag HTML is generated correctly.
   */
  public function testMetaTag() {
    list($version, ) = explode('.', VERSION);
    $string = '<meta name="Generator" content="Drupal ' . $version . ' (http://drupal.org)" />';
    $this->drupalGet('node');
    $this->assertRaw($string, t('Fingerprinting meta tag generated correctly.'), t('System'));
  }
}

/**
 * Tests custom access denied functionality.
 */
class AccessDeniedTestCase extends DrupalWebTestCase {
  protected $admin_user;

  /**
   * Implement getInfo().
   */
  public static function getInfo() {
    return array(
      'name' => '403 functionality',
      'description' => "Tests page access denied functionality, including custom 403 pages.",
      'group' => 'System'
    );
  }

  /**
   * Implement setUp().
   */
  function setUp() {
    parent::setUp();

    // Create an administrative user.
    $this->admin_user = $this->drupalCreateUser(array('administer site configuration', 'administer blocks'));
    $this->drupalLogin($this->admin_user);
  }

  function testAccessDenied() {
    $this->drupalGet('admin');
    $this->assertText(t('Access denied'), t('Found the default 403 page'));

    $edit = array(
      'title' => $this->randomName(10),
      'body' => array(FIELD_LANGUAGE_NONE => array(array('value' => $this->randomName(100)))),
    );
    $node = $this->drupalCreateNode($edit);

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

    $this->drupalGet('admin');
    $this->assertText($node->title, t('Found the custom 403 page'));

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

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

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

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

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

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

    // Check that we can log in from the 403 page.
    $this->drupalLogout();
    $edit = array(
      'name' => $this->admin_user->name,
      'pass' => $this->admin_user->pass_raw,
    );
    $this->drupalPost('admin/settings/site-information', $edit, t('Log in'));

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

class PageNotFoundTestCase extends DrupalWebTestCase {
  protected $admin_user;

  /**
   * Implement getInfo().
   */
  public static function getInfo() {
    return array(
      'name' => '404 functionality',
      'description' => "Tests page not found functionality, including custom 404 pages.",
      'group' => 'System'
    );
  }

  /**
   * Implement setUp().
   */
  function setUp() {
    parent::setUp();

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

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

    $edit = array(
      'title' => $this->randomName(10),
      'body' => array(FIELD_LANGUAGE_NONE => array(array('value' => $this->randomName(100)))),
    );
    $node = $this->drupalCreateNode($edit);

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

    $this->drupalGet($this->randomName(10));
    $this->assertText($node->title, t('Found the custom 404 page'));

    // Logout and check that the user login block is not shown on custom 404 pages.
    $this->drupalLogout();

    $this->drupalGet($this->randomName(10));
    $this->assertText($node->title, t('Found the custom 404 page'));
    $this->assertNoText(t('User login'), t('Blocks are not shown on the custom 404 page'));

    // Log back in and remove the custom 404 page.
    $this->drupalLogin($this->admin_user);
    $this->drupalPost('admin/settings/site-information', array('site_404' => ''), t('Save configuration'));

    // Logout and check that the user login block is not shown on default 404 pages.
    $this->drupalLogout();

    $this->drupalGet($this->randomName(10));
    $this->assertText(t('Page not found'), t('Found the default 404 page'));
    $this->assertNoText(t('User login'), t('Blocks are not shown on the default 404 page'));
  }
}

/**
 * Tests generic date and time handling capabilities of Drupal.
 */
class DateTimeFunctionalTest extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Date and time',
      'description' => 'Configure date and time settings. Test date formatting and time zone handling, including daylight saving time.',
      'group' => 'System',
    );
  }

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

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

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

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

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

class PageTitleFiltering extends DrupalWebTestCase {
  protected $content_user;
  protected $saved_title;

  /**
   * Implement getInfo().
   */
  public static function getInfo() {
    return array(
      'name' => 'HTML in page titles',
      'description' => 'Tests correct handling or conversion by drupal_set_title() and drupal_get_title().',
      'group' => 'System'
    );
  }

  /**
   * Implement setUp().
   */
  function setUp() {
    parent::setUp();

    $this->content_user = $this->drupalCreateUser(array('create page content', 'access content'));
    $this->drupalLogin($this->content_user);
    $this->saved_title = drupal_get_title();
  }

  /**
   * Reset page title.
   */
  function tearDown() {
    // Restore the page title.
    drupal_set_title($this->saved_title, PASS_THROUGH);

    parent::tearDown();
  }

  /**
   * Tests the handling of HTML by drupal_set_title() and drupal_get_title()
   */
  function testTitleTags() {
    $title = "string with <em>HTML</em>";
    // drupal_set_title's $filter is CHECK_PLAIN by default, so the title should be
    // returned with check_plain().
    drupal_set_title($title, CHECK_PLAIN);
    $this->assertTrue(strpos(drupal_get_title(), '<em>') === FALSE, t('Tags in title converted to entities when $output is CHECK_PLAIN.'));
    // drupal_set_title's $filter is passed as PASS_THROUGH, so the title should be
    // returned with HTML.
    drupal_set_title($title, PASS_THROUGH);
    $this->assertTrue(strpos(drupal_get_title(), '<em>') !== FALSE, t('Tags in title are not converted to entities when $output is PASS_THROUGH.'));
    // Generate node content.
    $langcode = FIELD_LANGUAGE_NONE;
    $edit = array(
     'title' => '!SimpleTest! ' . $title . $this->randomName(20),
     "body[$langcode][0][value]" => '!SimpleTest! test body' . $this->randomName(200),
    );
    // Create the node with HTML in the title.
    $this->drupalPost('node/add/page', $edit, t('Save'));

    $node = $this->drupalGetNodeByTitle($edit['title']);
    $this->assertNotNull($node, 'Node created and found in database');
    $this->drupalGet("node/" . $node->nid);
    $this->assertText(check_plain($edit['title']), 'Check to make sure tags in the node title are converted.');
  }
}

/**
 * Test front page functionality and administration.
 */
class FrontPageTestCase extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Front page',
      'description' => 'Tests front page functionality and administration.',
      'group' => 'System',
    );
  }

  function setUp() {
    parent::setUp('system_test');

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

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

  /**
   * Test front page functionality.
   */
  function testDrupalIsFrontPage() {
    $this->drupalGet('');
    $this->assertText(t('On front page.'), t('Path is the front page.'));
    $this->drupalGet('node');
    $this->assertText(t('On front page.'), t('Path is the front page.'));
    $this->drupalGet($this->node_path);
    $this->assertNoText(t('On front page.'), t('Path is not the front page.'));

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

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

    $this->drupalGet('');
    $this->assertText(t('On front page.'), t('Path is the front page.'));
    $this->drupalGet('node');
    $this->assertNoText(t('On front page.'), t('Path is not the front page.'));
    $this->drupalGet($this->node_path);
    $this->assertText(t('On front page.'), t('Path is the front page.'));
  }
}

class SystemBlockTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Block functionality',
      'description' => 'Configure and move powered-by block.',
      'group' => 'System',
    );
  }

  function setUp() {
    parent::setUp();

    // Create and login user
    $admin_user = $this->drupalCreateUser(array('administer blocks'));
    $this->drupalLogin($admin_user);
  }

  /**
   * Test displaying and hiding the powered-by block.
   */
  function testPoweredByBlock() {
    // Set block title and some settings to confirm that the interface is availble.
    $this->drupalPost('admin/structure/block/configure/system/powered-by', array('title' => $this->randomName(8), 'color' => 'powered-black', 'size' => '135x42'), t('Save block'));
    $this->assertText(t('The block configuration has been saved.'), t('Block configuration set.'));

    // Set the powered-by block to the footer region.
    $edit = array();
    $edit['system_powered-by[region]'] = 'footer';
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
    $this->assertText(t('The block settings have been updated.'), t('Block successfully move to footer region.'));

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

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

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

    // For convenience of developers, set the block to it's default settings.
    $edit = array();
    $edit['system_powered-by[region]'] = 'footer';
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
    $this->drupalPost('admin/structure/block/configure/system/powered-by', array('title' => '', 'color' => 'powered-blue', 'size' => '80x15'), t('Save block'));
  }

}

class SystemSettingsForm extends DrupalWebTestCase {
  /**
   * Implement getInfo().
   */
  public static function getInfo() {
    return array(
      'name' => 'System setting forms',
      'description' => 'Tests correctness of system_settings_form() processing.',
      'group' => 'System'
    );
  }

  /**
   * Implement setUp().
   */
  function setUp() {
    parent::setUp();

    variable_set('system_settings_form_test', TRUE);
    variable_set('system_settings_form_test_4', TRUE);
  }

  /**
   * Reset page title.
   */
  function tearDown() {
    variable_del('system_settings_form_test');
    variable_del('system_settings_form_test_4');

    parent::tearDown();
  }

  /**
   * Tests the handling of automatic defaults in systems_settings_form().
   */
  function testAutomaticDefaults() {
    $form = array();

    $form['system_settings_form_test'] = array(
      '#type' => 'checkbox',
      '#default_value' => FALSE,
    );

    $form['system_settings_form_test_2'] = array(
      '#type' => 'checkbox',
      '#default_value' => FALSE,
    );

    $form['system_settings_form_test_3'] = array(
      '#type' => 'checkbox',
      '#default_value' => TRUE,
    );

    $form['has_children']['system_settings_form_test_4'] = array(
      '#type' => 'checkbox',
      '#default_value' => FALSE,
    );

    $form['has_children']['system_settings_form_test_5'] = array(
      '#type' => 'checkbox',
      '#default_value' => TRUE,
    );

    $automatic = system_settings_form($form, FALSE);
    $this->assertFalse($automatic['system_settings_form_test']['#default_value']);
    $this->assertFalse($automatic['system_settings_form_test_2']['#default_value']);
    $this->assertTrue($automatic['system_settings_form_test_3']['#default_value']);
    $this->assertFalse($automatic['has_children']['system_settings_form_test_4']['#default_value']);
    $this->assertTrue($automatic['has_children']['system_settings_form_test_5']['#default_value']);

    $no_automatic = system_settings_form($form);
    $this->assertTrue($no_automatic['system_settings_form_test']['#default_value']);
    $this->assertFalse($no_automatic['system_settings_form_test_2']['#default_value']);
    $this->assertTrue($no_automatic['system_settings_form_test_3']['#default_value']);
    $this->assertTrue($no_automatic['has_children']['system_settings_form_test_4']['#default_value']);
    $this->assertTrue($no_automatic['has_children']['system_settings_form_test_5']['#default_value']);
  }
}

/**
 * Tests for the theme interface functionality.
 */
class SystemThemeFunctionalTest extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Theme interface functionality',
      'description' => 'Tests the theme interface functionality by enabling and switching themes, and using an administration theme.',
      'group' => 'System',
    );
  }

  function setUp() {
    parent::setUp();

    $this->admin_user = $this->drupalCreateUser(array('access administration pages', 'administer site configuration', 'bypass node access'));
    $this->drupalLogin($this->admin_user);
    $this->node = $this->drupalCreateNode();
  }

  /**
   * Test the administration theme functionality.
   */
  function testAdministrationTheme() {
    // Enable an administration theme and show it on the node admin pages.
    $edit = array(
      'theme_default' => 'stark',
      'admin_theme' => 'garland',
      'node_admin_theme' => TRUE,
    );
    $this->drupalPost('admin/appearance', $edit, t('Save configuration'));

    $this->drupalGet('admin');
    $this->assertRaw('themes/garland', t('Administration theme used on an administration page.'));

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

    $this->drupalGet('node/add');
    $this->assertRaw('themes/garland', t('Administration theme used on the add content page.'));

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

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

    $this->drupalGet('admin');
    $this->assertRaw('themes/garland', t('Administration theme used on an administration page.'));

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

    // Reset to the default theme settings.
    $edit = array(
      'theme_default' => 'garland',
      'admin_theme' => '0',
      'node_admin_theme' => FALSE,
    );
    $this->drupalPost('admin/appearance', $edit, t('Save configuration'));

    $this->drupalGet('admin');
    $this->assertRaw('themes/garland', t('Site default theme used on administration page.'));

    $this->drupalGet('node/add');
    $this->assertRaw('themes/garland', t('Site default theme used on the add content page.'));
  }
}


/**
 * Test the basic queue functionality.
 */
class QueueTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Queue functionality',
      'description' => 'Queues and dequeues a set of items to check the basic queue functionality.',
      'group' => 'System',
    );
  }

  /**
   * Queues and dequeues a set of items to check the basic queue functionality.
   */
  function testQueue() {
    // Create two queues.
    $queue1 = DrupalQueue::get($this->randomName());
    $queue1->createQueue();
    $queue2 = DrupalQueue::get($this->randomName());
    $queue2->createQueue();

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

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

    // Retrieve two items from queue1.
    $items = array();
    $new_items = array();

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

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

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

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

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

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

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

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

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

    // Delete all items from queue1.
    foreach ($items as $item) {
      $queue1->deleteItem($item);
    }

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

  /**
   * This function returns the number of equal items in two arrays.
   */
  function queueScore($items, $new_items) {
    $score = 0;
    foreach ($items as $item) {
      foreach ($new_items as $new_item) {
        if ($item === $new_item) {
          $score++;
        }
      }
    }
    return $score;
  }
}

/**
 * Test token replacement in strings.
 */
class TokenReplaceTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Token replacement',
      'description' => 'Generates text using placeholders for dummy content to check token replacement.',
      'group' => 'System',
    );
  }

  /**
   * Creates a user and a node, then tests the tokens generated from them.
   */
  function testTokenReplacement() {
    // Create the initial objects.
    $account = $this->drupalCreateUser();
    $node = $this->drupalCreateNode(array('uid' => $account->uid));
    $node->title = '<blink>Blinking Text</blink>';
    global $user;

    $source  = '[node:title]';         // Title of the node we passed in
    $source .= '[node:author:name]';   // Node author's name
    $source .= '[node:created:since]'; // Time since the node was created
    $source .= '[current-user:name]';  // Current user's name
    $source .= '[user:name]';          // No user passed in, should be untouched
    $source .= '[date:small]';         // Small date format of REQUEST_TIME
    $source .= '[bogus:token]';        // Nonexistent token, should be untouched

    $target  = check_plain($node->title);
    $target .= check_plain($account->name);
    $target .= format_interval(REQUEST_TIME - $node->created, 2);
    $target .= check_plain($user->name);
    $target .= '[user:name]';
    $target .= format_date(REQUEST_TIME, 'small');
    $target .= '[bogus:token]';

    $result = token_replace($source, array('node' => $node));

    // Check that the results of token_generate are sanitized properly. This does NOT
    // test the cleanliness of every token -- just that the $sanitize flag is being
    // passed properly through the call stack and being handled correctly by a 'known'
    // token, [node:title].
    $this->assertFalse(strcmp($target, $result), t('Basic placeholder tokens replaced.'));
    
    $raw_tokens = array(
      'node' => array('title' => '[node:title]'),
    );
    $generated = token_generate($raw_tokens, array('node' => $node));
    $this->assertFalse(strcmp($generated['[node:title]'], check_plain($node->title)), t('Token sanitized.'));

    $generated = token_generate($raw_tokens, array('node' => $node), array('sanitize' => FALSE));
    $this->assertFalse(strcmp($generated['[node:title]'], $node->title), t('Unsanitized token generated properly.'));
  }
}