summaryrefslogtreecommitdiff
path: root/modules/simpletest/tests/form.test
blob: f90b854c7d7c4a9a2ca94c3ef234c638a7e01641 (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
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
<?php

/**
 * @file
 * Unit tests for the Drupal Form API.
 */

class FormsTestCase extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Form element validation',
      'description' => 'Tests various form element validation mechanisms.',
      'group' => 'Form API',
    );
  }

  function setUp() {
    parent::setUp('form_test');
  }

  /**
   * Check several empty values for required forms elements.
   *
   * Carriage returns, tabs, spaces, and unchecked checkbox elements are not
   * valid content for a required field.
   *
   * If the form field is found in form_get_errors() then the test pass.
   */
  function testRequiredFields() {
    // Originates from http://drupal.org/node/117748
    // Sets of empty strings and arrays.
    $empty_strings = array('""' => "", '"\n"' => "\n", '" "' => " ", '"\t"' => "\t", '" \n\t "' => " \n\t ", '"\n\n\n\n\n"' => "\n\n\n\n\n");
    $empty_arrays = array('array()' => array());
    $empty_checkbox = array(NULL);

    $elements['textfield']['element'] = array('#title' => $this->randomName(), '#type' => 'textfield');
    $elements['textfield']['empty_values'] = $empty_strings;

    $elements['password']['element'] = array('#title' => $this->randomName(), '#type' => 'password');
    $elements['password']['empty_values'] = $empty_strings;

    $elements['password_confirm']['element'] = array('#title' => $this->randomName(), '#type' => 'password_confirm');
    // Provide empty values for both password fields.
    foreach ($empty_strings as $key => $value) {
      $elements['password_confirm']['empty_values'][$key] = array('pass1' => $value, 'pass2' => $value);
    }

    $elements['textarea']['element'] = array('#title' => $this->randomName(), '#type' => 'textarea');
    $elements['textarea']['empty_values'] = $empty_strings;

    $elements['radios']['element'] = array('#title' => $this->randomName(), '#type' => 'radios', '#options' => array('' => t('None'), $this->randomName(), $this->randomName(), $this->randomName()));
    $elements['radios']['empty_values'] = $empty_arrays;

    $elements['checkbox']['element'] = array('#title' => $this->randomName(), '#type' => 'checkbox', '#required' => TRUE);
    $elements['checkbox']['empty_values'] = $empty_checkbox;

    $elements['checkboxes']['element'] = array('#title' => $this->randomName(), '#type' => 'checkboxes', '#options' => array($this->randomName(), $this->randomName(), $this->randomName()));
    $elements['checkboxes']['empty_values'] = $empty_arrays;

    $elements['select']['element'] = array('#title' => $this->randomName(), '#type' => 'select', '#options' => array('' => t('None'), $this->randomName(), $this->randomName(), $this->randomName()));
    $elements['select']['empty_values'] = $empty_strings;

    $elements['file']['element'] = array('#title' => $this->randomName(), '#type' => 'file');
    $elements['file']['empty_values'] = $empty_strings;

    // Regular expression to find the expected marker on required elements.
    $required_marker_preg = '@<label.*<span class="form-required" title="This field is required\.">\*</span></label>@';

    // Go through all the elements and all the empty values for them.
    foreach ($elements as $type => $data) {
      foreach ($data['empty_values'] as $key => $empty) {
        foreach (array(TRUE, FALSE) as $required) {
          $form_id = $this->randomName();
          $form = array();
          $form_state = form_state_defaults();
          form_clear_error();
          $form['op'] = array('#type' => 'submit', '#value' => t('Submit'));
          $element = $data['element']['#title'];
          $form[$element] = $data['element'];
          $form[$element]['#required'] = $required;
          $form_state['input'][$element] = $empty;
          $form_state['input']['form_id'] = $form_id;
          $form_state['method'] = 'post';

          // The form token CSRF protection should not interfere with this test,
          // so we bypass it by marking this test form as programmed.
          $form_state['programmed'] = TRUE;
          drupal_prepare_form($form_id, $form, $form_state);
          drupal_process_form($form_id, $form, $form_state);
          $errors = form_get_errors();
          // Form elements of type 'radios' throw all sorts of PHP notices
          // when you try to render them like this, so we ignore those for
          // testing the required marker.
          // @todo Fix this work-around (http://drupal.org/node/588438).
          $form_output = ($type == 'radios') ? '' : drupal_render($form);
          if ($required) {
            // Make sure we have a form error for this element.
            $this->assertTrue(isset($errors[$element]), "Check empty($key) '$type' field '$element'");
            if (!empty($form_output)) {
              // Make sure the form element is marked as required.
              $this->assertTrue(preg_match($required_marker_preg, $form_output), "Required '$type' field is marked as required");
            }
          }
          else {
            if (!empty($form_output)) {
              // Make sure the form element is *not* marked as required.
              $this->assertFalse(preg_match($required_marker_preg, $form_output), "Optional '$type' field is not marked as required");
            }
            if ($type == 'select') {
              // Select elements are going to have validation errors with empty
              // input, since those are illegal choices. Just make sure the
              // error is not "field is required".
              $this->assertTrue((empty($errors[$element]) || strpos('field is required', $errors[$element]) === FALSE), "Optional '$type' field '$element' is not treated as a required element");
            }
            else {
              // Make sure there is *no* form error for this element.
              $this->assertTrue(empty($errors[$element]), "Optional '$type' field '$element' has no errors with empty input");
            }
          }
        }
      }
    }
    // Clear the expected form error messages so they don't appear as exceptions.
    drupal_get_messages();
  }

  /**
   * Tests validation for required checkbox, select, and radio elements.
   *
   * Submits a test form containing several types of form elements. The form
   * is submitted twice, first without values for required fields and then
   * with values. Each submission is checked for relevant error messages.
   *
   * @see form_test_validate_required_form()
   */
  function testRequiredCheckboxesRadio() {
    $form = $form_state = array();
    $form = form_test_validate_required_form($form, $form_state);

    // Attempt to submit the form with no required fields set.
    $edit = array();
    $this->drupalPost('form-test/validate-required', $edit, 'Submit');

    // The only error messages that should appear are the relevant 'required'
    // messages for each field.
    $expected = array();
    foreach (array('textfield', 'checkboxes', 'select', 'radios') as $key) {
      $expected[] = t('!name field is required.', array('!name' => $form[$key]['#title']));
    }

    // Check the page for error messages.
    $errors = $this->xpath('//div[contains(@class, "error")]//li');
    foreach ($errors as $error) {
      $expected_key = array_search($error[0], $expected);
      // If the error message is not one of the expected messages, fail.
      if ($expected_key === FALSE) {
        $this->fail(format_string("Unexpected error message: @error", array('@error' => $error[0])));
      }
      // Remove the expected message from the list once it is found.
      else {
        unset($expected[$expected_key]);
      }
    }

    // Fail if any expected messages were not found.
    foreach ($expected as $not_found) {
      $this->fail(format_string("Found error message: @error", array('@error' => $not_found)));
    }

    // Verify that input elements are still empty.
    $this->assertFieldByName('textfield', '');
    $this->assertNoFieldChecked('edit-checkboxes-foo');
    $this->assertNoFieldChecked('edit-checkboxes-bar');
    $this->assertOptionSelected('edit-select', '');
    $this->assertNoFieldChecked('edit-radios-foo');
    $this->assertNoFieldChecked('edit-radios-bar');
    $this->assertNoFieldChecked('edit-radios-optional-foo');
    $this->assertNoFieldChecked('edit-radios-optional-bar');
    $this->assertNoFieldChecked('edit-radios-optional-default-value-false-foo');
    $this->assertNoFieldChecked('edit-radios-optional-default-value-false-bar');

    // Submit again with required fields set and verify that there are no
    // error messages.
    $edit = array(
      'textfield' => $this->randomString(),
      'checkboxes[foo]' => TRUE,
      'select' => 'foo',
      'radios' => 'bar',
    );
    $this->drupalPost(NULL, $edit, 'Submit');
    $this->assertNoFieldByXpath('//div[contains(@class, "error")]', FALSE, 'No error message is displayed when all required fields are filled.');
    $this->assertRaw("The form_test_validate_required_form form was submitted successfully.", 'Validation form submitted successfully.');
  }

  /**
   * Tests validation for required textfield element without title.
   *
   * Submits a test form containing a textfield form elements without title.
   * The form is submitted twice, first without value for the required field
   * and then with value. Each submission is checked for relevant error
   * messages.
   *
   * @see form_test_validate_required_form_no_title()
   */
  function testRequiredTextfieldNoTitle() {
    $form = $form_state = array();
    $form = form_test_validate_required_form_no_title($form, $form_state);

    // Attempt to submit the form with no required field set.
    $edit = array();
    $this->drupalPost('form-test/validate-required-no-title', $edit, 'Submit');
    $this->assertNoRaw("The form_test_validate_required_form_no_title form was submitted successfully.", 'Validation form submitted successfully.');

    // Check the page for the error class on the textfield.
    $this->assertFieldByXPath('//input[contains(@class, "error")]', FALSE, 'Error input form element class found.');

    // Submit again with required fields set and verify that there are no
    // error messages.
    $edit = array(
      'textfield' => $this->randomString(),
    );
    $this->drupalPost(NULL, $edit, 'Submit');
    $this->assertNoFieldByXpath('//input[contains(@class, "error")]', FALSE, 'No error input form element class found.');
    $this->assertRaw("The form_test_validate_required_form_no_title form was submitted successfully.", 'Validation form submitted successfully.');
  }

  /**
   * Test default value handling for checkboxes.
   *
   * @see _form_test_checkbox()
   */
  function testCheckboxProcessing() {
    // First, try to submit without the required checkbox.
    $edit = array();
    $this->drupalPost('form-test/checkbox', $edit, t('Submit'));
    $this->assertRaw(t('!name field is required.', array('!name' => 'required_checkbox')), 'A required checkbox is actually mandatory');

    // Now try to submit the form correctly.
    $values = drupal_json_decode($this->drupalPost(NULL, array('required_checkbox' => 1), t('Submit')));
    $expected_values = array(
      'disabled_checkbox_on' => 'disabled_checkbox_on',
      'disabled_checkbox_off' => '',
      'checkbox_on' => 'checkbox_on',
      'checkbox_off' => '',
      'zero_checkbox_on' => '0',
      'zero_checkbox_off' => '',
    );
    foreach ($expected_values as $widget => $expected_value) {
      $this->assertEqual($values[$widget], $expected_value, format_string('Checkbox %widget returns expected value (expected: %expected, got: %value)', array(
        '%widget' => var_export($widget, TRUE),
        '%expected' => var_export($expected_value, TRUE),
        '%value' => var_export($values[$widget], TRUE),
      )));
    }
  }

  /**
   * Tests validation of #type 'select' elements.
   */
  function testSelect() {
    $form = $form_state = array();
    $form = form_test_select($form, $form_state);
    $error = '!name field is required.';
    $this->drupalGet('form-test/select');

    // Posting without any values should throw validation errors.
    $this->drupalPost(NULL, array(), 'Submit');
    $this->assertNoText(t($error, array('!name' => $form['select']['#title'])));
    $this->assertNoText(t($error, array('!name' => $form['select_required']['#title'])));
    $this->assertNoText(t($error, array('!name' => $form['select_optional']['#title'])));
    $this->assertNoText(t($error, array('!name' => $form['empty_value']['#title'])));
    $this->assertNoText(t($error, array('!name' => $form['empty_value_one']['#title'])));
    $this->assertText(t($error, array('!name' => $form['no_default']['#title'])));
    $this->assertNoText(t($error, array('!name' => $form['no_default_optional']['#title'])));
    $this->assertText(t($error, array('!name' => $form['no_default_empty_option']['#title'])));
    $this->assertNoText(t($error, array('!name' => $form['no_default_empty_option_optional']['#title'])));
    $this->assertText(t($error, array('!name' => $form['no_default_empty_value']['#title'])));
    $this->assertText(t($error, array('!name' => $form['no_default_empty_value_one']['#title'])));
    $this->assertNoText(t($error, array('!name' => $form['no_default_empty_value_optional']['#title'])));
    $this->assertNoText(t($error, array('!name' => $form['multiple']['#title'])));
    $this->assertNoText(t($error, array('!name' => $form['multiple_no_default']['#title'])));
    $this->assertText(t($error, array('!name' => $form['multiple_no_default_required']['#title'])));

    // Post values for required fields.
    $edit = array(
      'no_default' => 'three',
      'no_default_empty_option' => 'three',
      'no_default_empty_value' => 'three',
      'no_default_empty_value_one' => 'three',
      'multiple_no_default_required[]' => 'three',
    );
    $this->drupalPost(NULL, $edit, 'Submit');
    $values = drupal_json_decode($this->drupalGetContent());

    // Verify expected values.
    $expected = array(
      'select' => 'one',
      'empty_value' => 'one',
      'empty_value_one' => 'one',
      'no_default' => 'three',
      'no_default_optional' => 'one',
      'no_default_optional_empty_value' => '',
      'no_default_empty_option' => 'three',
      'no_default_empty_option_optional' => '',
      'no_default_empty_value' => 'three',
      'no_default_empty_value_one' => 'three',
      'no_default_empty_value_optional' => 0,
      'multiple' => array('two' => 'two'),
      'multiple_no_default' => array(),
      'multiple_no_default_required' => array('three' => 'three'),
    );
    foreach ($expected as $key => $value) {
      $this->assertIdentical($values[$key], $value, format_string('@name: @actual is equal to @expected.', array(
        '@name' => $key,
        '@actual' => var_export($values[$key], TRUE),
        '@expected' => var_export($value, TRUE),
      )));
    }
  }

  /**
   * Test handling of disabled elements.
   *
   * @see _form_test_disabled_elements()
   */
  function testDisabledElements() {
    // Get the raw form in its original state.
    $form_state = array();
    $form = _form_test_disabled_elements(array(), $form_state);

    // Build a submission that tries to hijack the form by submitting input for
    // elements that are disabled.
    $edit = array();
    foreach (element_children($form) as $key) {
      if (isset($form[$key]['#test_hijack_value'])) {
        if (is_array($form[$key]['#test_hijack_value'])) {
          foreach ($form[$key]['#test_hijack_value'] as $subkey => $value) {
            $edit[$key . '[' . $subkey . ']'] = $value;
          }
        }
        else {
          $edit[$key] = $form[$key]['#test_hijack_value'];
        }
      }
    }

    // Submit the form with no input, as the browser does for disabled elements,
    // and fetch the $form_state['values'] that is passed to the submit handler.
    $this->drupalPost('form-test/disabled-elements', array(), t('Submit'));
    $returned_values['normal'] = drupal_json_decode($this->content);

    // Do the same with input, as could happen if JavaScript un-disables an
    // element. drupalPost() emulates a browser by not submitting input for
    // disabled elements, so we need to un-disable those elements first.
    $this->drupalGet('form-test/disabled-elements');
    $disabled_elements = array();
    foreach ($this->xpath('//*[@disabled]') as $element) {
      $disabled_elements[] = (string) $element['name'];
      unset($element['disabled']);
    }

    // All the elements should be marked as disabled, including the ones below
    // the disabled container.
    $this->assertEqual(count($disabled_elements), 32, 'The correct elements have the disabled property in the HTML code.');

    $this->drupalPost(NULL, $edit, t('Submit'));
    $returned_values['hijacked'] = drupal_json_decode($this->content);

    // Ensure that the returned values match the form's default values in both
    // cases.
    foreach ($returned_values as $type => $values) {
      $this->assertFormValuesDefault($values, $form);
    }
  }

  /**
   * Assert that the values submitted to a form matches the default values of the elements.
   */
  function assertFormValuesDefault($values, $form) {
    foreach (element_children($form) as $key) {
      if (isset($form[$key]['#default_value'])) {
        if (isset($form[$key]['#expected_value'])) {
          $expected_value = $form[$key]['#expected_value'];
        }
        else {
          $expected_value = $form[$key]['#default_value'];
        }

        if ($key == 'checkboxes_multiple') {
          // Checkboxes values are not filtered out.
          $values[$key] = array_filter($values[$key]);
        }
        $this->assertIdentical($expected_value, $values[$key], format_string('Default value for %type: expected %expected, returned %returned.', array('%type' => $key, '%expected' => var_export($expected_value, TRUE), '%returned' => var_export($values[$key], TRUE))));
      }

      // Recurse children.
      $this->assertFormValuesDefault($values, $form[$key]);
    }
  }

  /**
   * Verify markup for disabled form elements.
   *
   * @see _form_test_disabled_elements()
   */
  function testDisabledMarkup() {
    $this->drupalGet('form-test/disabled-elements');
    $form_state = array();
    $form = _form_test_disabled_elements(array(), $form_state);
    $type_map = array(
      'textarea' => 'textarea',
      'select' => 'select',
      'weight' => 'select',
      'date' => 'select',
    );

    foreach ($form as $name => $item) {
      // Skip special #types.
      if (!isset($item['#type']) || in_array($item['#type'], array('hidden', 'text_format'))) {
        continue;
      }
      // Setup XPath and CSS class depending on #type.
      if (in_array($item['#type'], array('image_button', 'button', 'submit'))) {
        $path = "//!type[contains(@class, :div-class) and @value=:value]";
        $class = 'form-button-disabled';
      }
      else {
        // starts-with() required for checkboxes.
        $path = "//div[contains(@class, :div-class)]/descendant::!type[starts-with(@name, :name)]";
        $class = 'form-disabled';
      }
      // Replace DOM element name in $path according to #type.
      $type = 'input';
      if (isset($type_map[$item['#type']])) {
        $type = $type_map[$item['#type']];
      }
      $path = strtr($path, array('!type' => $type));
      // Verify that the element exists.
      $element = $this->xpath($path, array(
        ':name' => check_plain($name),
        ':div-class' => $class,
        ':value' => isset($item['#value']) ? $item['#value'] : '',
      ));
      $this->assertTrue(isset($element[0]), format_string('Disabled form element class found for #type %type.', array('%type' => $item['#type'])));
    }

    // Verify special element #type text-format.
    $element = $this->xpath('//div[contains(@class, :div-class)]/descendant::textarea[@name=:name]', array(
      ':name' => 'text_format[value]',
      ':div-class' => 'form-disabled',
    ));
    $this->assertTrue(isset($element[0]), format_string('Disabled form element class found for #type %type.', array('%type' => 'text_format[value]')));
    $element = $this->xpath('//div[contains(@class, :div-class)]/descendant::select[@name=:name]', array(
      ':name' => 'text_format[format]',
      ':div-class' => 'form-disabled',
    ));
    $this->assertTrue(isset($element[0]), format_string('Disabled form element class found for #type %type.', array('%type' => 'text_format[format]')));
  }

  /**
   * Test Form API protections against input forgery.
   *
   * @see _form_test_input_forgery()
   */
  function testInputForgery() {
    $this->drupalGet('form-test/input-forgery');
    $checkbox = $this->xpath('//input[@name="checkboxes[two]"]');
    $checkbox[0]['value'] = 'FORGERY';
    $this->drupalPost(NULL, array('checkboxes[one]' => TRUE, 'checkboxes[two]' => TRUE), t('Submit'));
    $this->assertText('An illegal choice has been detected.', 'Input forgery was detected.');
  }
}

/**
 * Tests building and processing of core form elements.
 */
class FormElementTestCase extends DrupalWebTestCase {
  protected $profile = 'testing';

  public static function getInfo() {
    return array(
      'name' => 'Element processing',
      'description' => 'Tests building and processing of core form elements.',
      'group' => 'Form API',
    );
  }

  function setUp() {
    parent::setUp(array('form_test'));
  }

  /**
   * Tests expansion of #options for #type checkboxes and radios.
   */
  function testOptions() {
    $this->drupalGet('form-test/checkboxes-radios');

    // Verify that all options appear in their defined order.
    foreach (array('checkbox', 'radio') as $type) {
      $elements = $this->xpath('//input[@type=:type]', array(':type' => $type));
      $expected_values = array('0', 'foo', '1', 'bar', '>');
      foreach ($elements as $element) {
        $expected = array_shift($expected_values);
        $this->assertIdentical((string) $element['value'], $expected);
      }
    }

    // Enable customized option sub-elements.
    $this->drupalGet('form-test/checkboxes-radios/customize');

    // Verify that all options appear in their defined order, taking a custom
    // #weight into account.
    foreach (array('checkbox', 'radio') as $type) {
      $elements = $this->xpath('//input[@type=:type]', array(':type' => $type));
      $expected_values = array('0', 'foo', 'bar', '>', '1');
      foreach ($elements as $element) {
        $expected = array_shift($expected_values);
        $this->assertIdentical((string) $element['value'], $expected);
      }
    }
    // Verify that custom #description properties are output.
    foreach (array('checkboxes', 'radios') as $type) {
      $elements = $this->xpath('//input[@id=:id]/following-sibling::div[@class=:class]', array(
        ':id' => 'edit-' . $type . '-foo',
        ':class' => 'description',
      ));
      $this->assertTrue(count($elements), format_string('Custom %type option description found.', array(
        '%type' => $type,
      )));
    }
  }
}

/**
 * Test form alter hooks.
 */
class FormAlterTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Form alter hooks',
      'description' => 'Tests hook_form_alter() and hook_form_FORM_ID_alter().',
      'group' => 'Form API',
    );
  }

  function setUp() {
    parent::setUp('form_test');
  }

  /**
   * Tests execution order of hook_form_alter() and hook_form_FORM_ID_alter().
   */
  function testExecutionOrder() {
    $this->drupalGet('form-test/alter');
    // Ensure that the order is first by module, then for a given module, the
    // id-specific one after the generic one.
    $expected = array(
      'block_form_form_test_alter_form_alter() executed.',
      'form_test_form_alter() executed.',
      'form_test_form_form_test_alter_form_alter() executed.',
      'system_form_form_test_alter_form_alter() executed.',
    );
    $content = preg_replace('/\s+/', ' ', filter_xss($this->content, array()));
    $this->assert(strpos($content, implode(' ', $expected)) !== FALSE, 'Form alter hooks executed in the expected order.');
  }
}

/**
 * Test form validation handlers.
 */
class FormValidationTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Form validation handlers',
      'description' => 'Tests form processing and alteration via form validation handlers.',
      'group' => 'Form API',
    );
  }

  function setUp() {
    parent::setUp('form_test');
  }

  /**
   * Tests form alterations by #element_validate, #validate, and form_set_value().
   */
  function testValidate() {
    $this->drupalGet('form-test/validate');
    // Verify that #element_validate handlers can alter the form and submitted
    // form values.
    $edit = array(
      'name' => 'element_validate',
    );
    $this->drupalPost(NULL, $edit, 'Save');
    $this->assertFieldByName('name', '#value changed by #element_validate', 'Form element #value was altered.');
    $this->assertText('Name value: value changed by form_set_value() in #element_validate', 'Form element value in $form_state was altered.');

    // Verify that #validate handlers can alter the form and submitted
    // form values.
    $edit = array(
      'name' => 'validate',
    );
    $this->drupalPost(NULL, $edit, 'Save');
    $this->assertFieldByName('name', '#value changed by #validate', 'Form element #value was altered.');
    $this->assertText('Name value: value changed by form_set_value() in #validate', 'Form element value in $form_state was altered.');

    // Verify that #element_validate handlers can make form elements
    // inaccessible, but values persist.
    $edit = array(
      'name' => 'element_validate_access',
    );
    $this->drupalPost(NULL, $edit, 'Save');
    $this->assertNoFieldByName('name', 'Form element was hidden.');
    $this->assertText('Name value: element_validate_access', 'Value for inaccessible form element exists.');

    // Verify that value for inaccessible form element persists.
    $this->drupalPost(NULL, array(), 'Save');
    $this->assertNoFieldByName('name', 'Form element was hidden.');
    $this->assertText('Name value: element_validate_access', 'Value for inaccessible form element exists.');

    // Verify that #validate handlers don't run if the CSRF token is invalid.
    $this->drupalLogin($this->drupalCreateUser());
    $this->drupalGet('form-test/validate');
    $edit = array(
      'name' => 'validate',
      'form_token' => 'invalid token'
    );
    $this->drupalPost(NULL, $edit, 'Save');
    $this->assertNoFieldByName('name', '#value changed by #validate', 'Form element #value was not altered.');
    $this->assertNoText('Name value: value changed by form_set_value() in #validate', 'Form element value in $form_state was not altered.');
    $this->assertText('The form has become outdated. Copy any unsaved work in the form below');
  }

  /**
   * Tests partial form validation through #limit_validation_errors.
   */
  function testValidateLimitErrors() {
    $edit = array(
      'test' => 'invalid',
      'test_numeric_index[0]' => 'invalid',
      'test_substring[foo]' => 'invalid',
    );
    $path = 'form-test/limit-validation-errors';

    // Submit the form by pressing the 'Partial validate' button (uses
    // #limit_validation_errors) and ensure that the title field is not
    // validated, but the #element_validate handler for the 'test' field
    // is triggered.
    $this->drupalPost($path, $edit, t('Partial validate'));
    $this->assertNoText(t('!name field is required.', array('!name' => 'Title')));
    $this->assertText('Test element is invalid');

    // Edge case of #limit_validation_errors containing numeric indexes: same
    // thing with the 'Partial validate (numeric index)' button and the
    // 'test_numeric_index' field.
    $this->drupalPost($path, $edit, t('Partial validate (numeric index)'));
    $this->assertNoText(t('!name field is required.', array('!name' => 'Title')));
    $this->assertText('Test (numeric index) element is invalid');

    // Ensure something like 'foobar' isn't considered "inside" 'foo'.
    $this->drupalPost($path, $edit, t('Partial validate (substring)'));
    $this->assertNoText(t('!name field is required.', array('!name' => 'Title')));
    $this->assertText('Test (substring) foo element is invalid');

    // Ensure not validated values are not available to submit handlers.
    $this->drupalPost($path, array('title' => '', 'test' => 'valid'), t('Partial validate'));
    $this->assertText('Only validated values appear in the form values.');

    // Now test full form validation and ensure that the #element_validate
    // handler is still triggered.
    $this->drupalPost($path, $edit, t('Full validate'));
    $this->assertText(t('!name field is required.', array('!name' => 'Title')));
    $this->assertText('Test element is invalid');
  }

  /**
   *  Tests error border of multiple fields with same name in a page.
   */
  function testMultiFormSameNameErrorClass() {
    $this->drupalGet('form-test/double-form');
    $edit = array();
    $this->drupalPost(NULL, $edit, t('Save'));
    $this->assertFieldByXpath('//input[@id="edit-name" and contains(@class, "error")]', NULL, 'Error input form element class found for first element.');
    $this->assertNoFieldByXpath('//input[@id="edit-name--2" and contains(@class, "error")]', NULL, 'No error input form element class found for second element.');
  }
}

/**
 * Test form element labels, required markers and associated output.
 */
class FormsElementsLabelsTestCase extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Form element and label output test',
      'description' => 'Test form element labels, required markers and associated output.',
      'group' => 'Form API',
    );
  }

  function setUp() {
    parent::setUp('form_test');
  }

  /**
   * Test form elements, labels, title attibutes and required marks output
   * correctly and have the correct label option class if needed.
   */
  function testFormLabels() {
    $this->drupalGet('form_test/form-labels');

    // Check that the checkbox/radio processing is not interfering with
    // basic placement.
    $elements = $this->xpath('//input[@id="edit-form-checkboxes-test-third-checkbox"]/following-sibling::label[@for="edit-form-checkboxes-test-third-checkbox" and @class="option"]');
    $this->assertTrue(isset($elements[0]), "Label follows field and label option class correct for regular checkboxes.");

    // Make sure the label is rendered for checkboxes.
    $elements = $this->xpath('//input[@id="edit-form-checkboxes-test-0"]/following-sibling::label[@for="edit-form-checkboxes-test-0" and @class="option"]');
    $this->assertTrue(isset($elements[0]), "Label 0 found checkbox.");

    $elements = $this->xpath('//input[@id="edit-form-radios-test-second-radio"]/following-sibling::label[@for="edit-form-radios-test-second-radio" and @class="option"]');
    $this->assertTrue(isset($elements[0]), "Label follows field and label option class correct for regular radios.");

    // Make sure the label is rendered for radios.
    $elements = $this->xpath('//input[@id="edit-form-radios-test-0"]/following-sibling::label[@for="edit-form-radios-test-0" and @class="option"]');
    $this->assertTrue(isset($elements[0]), "Label 0 found radios.");

    // Exercise various defaults for checkboxes and modifications to ensure
    // appropriate override and correct behavior.
    $elements = $this->xpath('//input[@id="edit-form-checkbox-test"]/following-sibling::label[@for="edit-form-checkbox-test" and @class="option"]');
    $this->assertTrue(isset($elements[0]), "Label follows field and label option class correct for a checkbox by default.");

    // Exercise various defaults for textboxes and modifications to ensure
    // appropriate override and correct behavior.
    $elements = $this->xpath('//label[@for="edit-form-textfield-test-title-and-required"]/child::span[@class="form-required"]/parent::*/following-sibling::input[@id="edit-form-textfield-test-title-and-required"]');
    $this->assertTrue(isset($elements[0]), "Label precedes textfield, with required marker inside label.");

    $elements = $this->xpath('//input[@id="edit-form-textfield-test-no-title-required"]/preceding-sibling::label[@for="edit-form-textfield-test-no-title-required"]/span[@class="form-required"]');
    $this->assertTrue(isset($elements[0]), "Label tag with required marker precedes required textfield with no title.");

    $elements = $this->xpath('//input[@id="edit-form-textfield-test-title-invisible"]/preceding-sibling::label[@for="edit-form-textfield-test-title-invisible" and @class="element-invisible"]');
    $this->assertTrue(isset($elements[0]), "Label preceding field and label class is element-invisible.");

    $elements = $this->xpath('//input[@id="edit-form-textfield-test-title"]/preceding-sibling::span[@class="form-required"]');
    $this->assertFalse(isset($elements[0]), "No required marker on non-required field.");

    $elements = $this->xpath('//input[@id="edit-form-textfield-test-title-after"]/following-sibling::label[@for="edit-form-textfield-test-title-after" and @class="option"]');
    $this->assertTrue(isset($elements[0]), "Label after field and label option class correct for text field.");

    $elements = $this->xpath('//label[@for="edit-form-textfield-test-title-no-show"]');
    $this->assertFalse(isset($elements[0]), "No label tag when title set not to display.");

    // Check #field_prefix and #field_suffix placement.
    $elements = $this->xpath('//span[@class="field-prefix"]/following-sibling::div[@id="edit-form-radios-test"]');
    $this->assertTrue(isset($elements[0]), "Properly placed the #field_prefix element after the label and before the field.");

    $elements = $this->xpath('//span[@class="field-suffix"]/preceding-sibling::div[@id="edit-form-radios-test"]');
    $this->assertTrue(isset($elements[0]), "Properly places the #field_suffix element immediately after the form field.");

    // Check #prefix and #suffix placement.
    $elements = $this->xpath('//div[@id="form-test-textfield-title-prefix"]/following-sibling::div[contains(@class, \'form-item-form-textfield-test-title\')]');
    $this->assertTrue(isset($elements[0]), "Properly places the #prefix element before the form item.");

    $elements = $this->xpath('//div[@id="form-test-textfield-title-suffix"]/preceding-sibling::div[contains(@class, \'form-item-form-textfield-test-title\')]');
    $this->assertTrue(isset($elements[0]), "Properly places the #suffix element before the form item.");

    // Check title attribute for radios and checkboxes.
    $elements = $this->xpath('//div[@id="edit-form-checkboxes-title-attribute"]');
    $this->assertEqual($elements[0]['title'], 'Checkboxes test' . ' (' . t('Required') . ')', 'Title attribute found.');
    $elements = $this->xpath('//div[@id="edit-form-radios-title-attribute"]');
    $this->assertEqual($elements[0]['title'], 'Radios test' . ' (' . t('Required') . ')', 'Title attribute found.');
  }
}

/**
 * Test the tableselect form element for expected behavior.
 */
class FormsElementsTableSelectFunctionalTest extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Tableselect form element type test',
      'description' => 'Test the tableselect element for expected behavior',
      'group' => 'Form API',
    );
  }

  function setUp() {
    parent::setUp('form_test');
  }


  /**
   * Test the display of checkboxes when #multiple is TRUE.
   */
  function testMultipleTrue() {

    $this->drupalGet('form_test/tableselect/multiple-true');

    $this->assertNoText(t('Empty text.'), 'Empty text should not be displayed.');

    // Test for the presence of the Select all rows tableheader.
    $this->assertFieldByXPath('//th[@class="select-all"]', NULL, 'Presence of the "Select all" checkbox.');

    $rows = array('row1', 'row2', 'row3');
    foreach ($rows as $row) {
      $this->assertFieldByXPath('//input[@type="checkbox"]', $row, format_string('Checkbox for value @row.', array('@row' => $row)));
    }
  }

  /**
   * Test the display of radios when #multiple is FALSE.
   */
  function testMultipleFalse() {
    $this->drupalGet('form_test/tableselect/multiple-false');

    $this->assertNoText(t('Empty text.'), 'Empty text should not be displayed.');

    // Test for the absence of the Select all rows tableheader.
    $this->assertNoFieldByXPath('//th[@class="select-all"]', '', 'Absence of the "Select all" checkbox.');

    $rows = array('row1', 'row2', 'row3');
    foreach ($rows as $row) {
      $this->assertFieldByXPath('//input[@type="radio"]', $row, format_string('Radio button for value @row.', array('@row' => $row)));
    }
  }

  /**
   * Test the display of the #empty text when #options is an empty array.
   */
  function testEmptyText() {
    $this->drupalGet('form_test/tableselect/empty-text');
    $this->assertText(t('Empty text.'), 'Empty text should be displayed.');
  }

  /**
   * Test the submission of single and multiple values when #multiple is TRUE.
   */
  function testMultipleTrueSubmit() {

    // Test a submission with one checkbox checked.
    $edit = array();
    $edit['tableselect[row1]'] = TRUE;
    $this->drupalPost('form_test/tableselect/multiple-true', $edit, 'Submit');

    $this->assertText(t('Submitted: row1 = row1'), 'Checked checkbox row1');
    $this->assertText(t('Submitted: row2 = 0'), 'Unchecked checkbox row2.');
    $this->assertText(t('Submitted: row3 = 0'), 'Unchecked checkbox row3.');

    // Test a submission with multiple checkboxes checked.
    $edit['tableselect[row1]'] = TRUE;
    $edit['tableselect[row3]'] = TRUE;
    $this->drupalPost('form_test/tableselect/multiple-true', $edit, 'Submit');

    $this->assertText(t('Submitted: row1 = row1'), 'Checked checkbox row1.');
    $this->assertText(t('Submitted: row2 = 0'), 'Unchecked checkbox row2.');
    $this->assertText(t('Submitted: row3 = row3'), 'Checked checkbox row3.');

  }

  /**
   * Test submission of values when #multiple is FALSE.
   */
  function testMultipleFalseSubmit() {
    $edit['tableselect'] = 'row1';
    $this->drupalPost('form_test/tableselect/multiple-false', $edit, 'Submit');
    $this->assertText(t('Submitted: row1'), 'Selected radio button');
  }

  /**
   * Test the #js_select property.
   */
  function testAdvancedSelect() {
    // When #multiple = TRUE a Select all checkbox should be displayed by default.
    $this->drupalGet('form_test/tableselect/advanced-select/multiple-true-default');
    $this->assertFieldByXPath('//th[@class="select-all"]', NULL, 'Display a "Select all" checkbox by default when #multiple is TRUE.');

    // When #js_select is set to FALSE, a "Select all" checkbox should not be displayed.
    $this->drupalGet('form_test/tableselect/advanced-select/multiple-true-no-advanced-select');
    $this->assertNoFieldByXPath('//th[@class="select-all"]', NULL, 'Do not display a "Select all" checkbox when #js_select is FALSE.');

    // A "Select all" checkbox never makes sense when #multiple = FALSE, regardless of the value of #js_select.
    $this->drupalGet('form_test/tableselect/advanced-select/multiple-false-default');
    $this->assertNoFieldByXPath('//th[@class="select-all"]', NULL, 'Do not display a "Select all" checkbox when #multiple is FALSE.');

    $this->drupalGet('form_test/tableselect/advanced-select/multiple-false-advanced-select');
    $this->assertNoFieldByXPath('//th[@class="select-all"]', NULL, 'Do not display a "Select all" checkbox when #multiple is FALSE, even when #js_select is TRUE.');
  }


  /**
   * Test the whether the option checker gives an error on invalid tableselect values for checkboxes.
   */
  function testMultipleTrueOptionchecker() {

    list($header, $options) = _form_test_tableselect_get_data();

    $form['tableselect'] = array(
      '#type' => 'tableselect',
      '#header' => $header,
      '#options' => $options,
    );

    // Test with a valid value.
    list($processed_form, $form_state, $errors) = $this->formSubmitHelper($form, array('tableselect' => array('row1' => 'row1')));
    $this->assertFalse(isset($errors['tableselect']), 'Option checker allows valid values for checkboxes.');

    // Test with an invalid value.
    list($processed_form, $form_state, $errors) = $this->formSubmitHelper($form, array('tableselect' => array('non_existing_value' => 'non_existing_value')));
    $this->assertTrue(isset($errors['tableselect']), 'Option checker disallows invalid values for checkboxes.');

  }


  /**
   * Test the whether the option checker gives an error on invalid tableselect values for radios.
   */
  function testMultipleFalseOptionchecker() {

    list($header, $options) = _form_test_tableselect_get_data();

    $form['tableselect'] = array(
      '#type' => 'tableselect',
      '#header' => $header,
      '#options' => $options,
      '#multiple' => FALSE,
    );

    // Test with a valid value.
    list($processed_form, $form_state, $errors) = $this->formSubmitHelper($form, array('tableselect' => 'row1'));
    $this->assertFalse(isset($errors['tableselect']), 'Option checker allows valid values for radio buttons.');

    // Test with an invalid value.
    list($processed_form, $form_state, $errors) = $this->formSubmitHelper($form, array('tableselect' => 'non_existing_value'));
    $this->assertTrue(isset($errors['tableselect']), 'Option checker disallows invalid values for radio buttons.');
  }


  /**
   * Helper function for the option check test to submit a form while collecting errors.
   *
   * @param $form_element
   *   A form element to test.
   * @param $edit
   *   An array containing post data.
   *
   * @return
   *   An array containing the processed form, the form_state and any errors.
   */
  private function formSubmitHelper($form, $edit) {
    $form_id = $this->randomName();
    $form_state = form_state_defaults();

    $form['op'] = array('#type' => 'submit', '#value' => t('Submit'));

    $form_state['input'] = $edit;
    $form_state['input']['form_id'] = $form_id;

    // The form token CSRF protection should not interfere with this test,
    // so we bypass it by marking this test form as programmed.
    $form_state['programmed'] = TRUE;

    drupal_prepare_form($form_id, $form, $form_state);

    drupal_process_form($form_id, $form, $form_state);

    $errors = form_get_errors();

    // Clear errors and messages.
    drupal_get_messages();
    form_clear_error();

    // Return the processed form together with form_state and errors
    // to allow the caller lowlevel access to the form.
    return array($form, $form_state, $errors);
  }

}

/**
 * Test the vertical_tabs form element for expected behavior.
 */
class FormsElementsVerticalTabsFunctionalTest extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Vertical tabs form element type test',
      'description' => 'Test the vertical_tabs element for expected behavior',
      'group' => 'Form API',
    );
  }

  function setUp() {
    parent::setUp('form_test');
  }

  /**
   * Ensures that vertical-tabs.js is included before collapse.js.
   *
   * Otherwise, collapse.js adds "SHOW" or "HIDE" labels to the tabs.
   */
  function testJavaScriptOrdering() {
    $this->drupalGet('form_test/vertical-tabs');
    $position1 = strpos($this->content, 'misc/vertical-tabs.js');
    $position2 = strpos($this->content, 'misc/collapse.js');
    $this->assertTrue($position1 !== FALSE && $position2 !== FALSE && $position1 < $position2, 'vertical-tabs.js is included before collapse.js');
  }
}

/**
 * Test the form storage on a multistep form.
 *
 * The tested form puts data into the storage during the initial form
 * construction. These tests verify that there are no duplicate form
 * constructions, with and without manual form caching activiated. Furthermore
 * when a validation error occurs, it makes sure that changed form element
 * values aren't lost due to a wrong form rebuild.
 */
class FormsFormStorageTestCase extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name'  => 'Multistep form using form storage',
      'description'  => 'Tests a multistep form using form storage and makes sure validation and caching works right.',
      'group' => 'Form API',
    );
  }

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

    $this->web_user = $this->drupalCreateUser(array('access content'));
    $this->drupalLogin($this->web_user);
  }

  /**
   * Tests using the form in a usual way.
   */
  function testForm() {
    $this->drupalGet('form_test/form-storage');
    $this->assertText('Form constructions: 1');

    $edit = array('title' => 'new', 'value' => 'value_is_set');

    // Use form rebuilding triggered by a submit button.
    $this->drupalPost(NULL, $edit, 'Continue submit');
    $this->assertText('Form constructions: 2');
    $this->assertText('Form constructions: 3');

    // Reset the form to the values of the storage, using a form rebuild
    // triggered by button of type button.
    $this->drupalPost(NULL, array('title' => 'changed'), 'Reset');
    $this->assertFieldByName('title', 'new', 'Values have been resetted.');
    // After rebuilding, the form has been cached.
    $this->assertText('Form constructions: 4');

    $this->drupalPost(NULL, $edit, 'Save');
    $this->assertText('Form constructions: 4');
    $this->assertText('Title: new', 'The form storage has stored the values.');
  }

  /**
   * Tests using the form with an activated $form_state['cache'] property.
   */
  function testFormCached() {
    $this->drupalGet('form_test/form-storage', array('query' => array('cache' => 1)));
    $this->assertText('Form constructions: 1');

    $edit = array('title' => 'new', 'value' => 'value_is_set');

    // Use form rebuilding triggered by a submit button.
    $this->drupalPost(NULL, $edit, 'Continue submit');
    $this->assertText('Form constructions: 2');

    // Reset the form to the values of the storage, using a form rebuild
    // triggered by button of type button.
    $this->drupalPost(NULL, array('title' => 'changed'), 'Reset');
    $this->assertFieldByName('title', 'new', 'Values have been resetted.');
    $this->assertText('Form constructions: 3');

    $this->drupalPost(NULL, $edit, 'Save');
    $this->assertText('Form constructions: 3');
    $this->assertText('Title: new', 'The form storage has stored the values.');
  }

  /**
   * Tests validation when form storage is used.
   */
  function testValidation() {
    $this->drupalPost('form_test/form-storage', array('title' => '', 'value' => 'value_is_set'), 'Continue submit');
    $this->assertPattern('/value_is_set/', 'The input values have been kept.');
  }

  /**
   * Tests updating cached form storage during form validation.
   *
   * If form caching is enabled and a form stores data in the form storage, then
   * the form storage also has to be updated in case of a validation error in
   * the form. This test re-uses the existing form for multi-step tests, but
   * triggers a special #element_validate handler to update the form storage
   * during form validation, while another, required element in the form
   * triggers a form validation error.
   */
  function testCachedFormStorageValidation() {
    // Request the form with 'cache' query parameter to enable form caching.
    $this->drupalGet('form_test/form-storage', array('query' => array('cache' => 1)));

    // Skip step 1 of the multi-step form, since the first step copies over
    // 'title' into form storage, but we want to verify that changes in the form
    // storage are updated in the cache during form validation.
    $edit = array('title' => 'foo');
    $this->drupalPost(NULL, $edit, 'Continue submit');

    // In step 2, trigger a validation error for the required 'title' field, and
    // post the special 'change_title' value for the 'value' field, which
    // conditionally invokes the #element_validate handler to update the form
    // storage.
    $edit = array('title' => '', 'value' => 'change_title');
    $this->drupalPost(NULL, $edit, 'Save');

    // At this point, the form storage should contain updated values, but we do
    // not see them, because the form has not been rebuilt yet due to the
    // validation error. Post again and verify that the rebuilt form contains
    // the values of the updated form storage.
    $this->drupalPost(NULL, array('title' => 'foo', 'value' => 'bar'), 'Save');
    $this->assertText("The thing has been changed.", 'The altered form storage value was updated in cache and taken over.');
  }

  /**
   * Tests a form using form state without using 'storage' to pass data from the
   * constructor to a submit handler. The data has to persist even when caching
   * gets activated, what may happen when a modules alter the form and adds
   * #ajax properties.
   */
  function testFormStatePersist() {
    // Test the form one time with caching activated and one time without.
    $run_options = array(
      array(),
      array('query' => array('cache' => 1)),
    );
    foreach ($run_options as $options) {
      $this->drupalPost('form-test/state-persist', array(), t('Submit'), $options);
      // The submit handler outputs the value in $form_state, assert it's there.
      $this->assertText('State persisted.');

      // Test it again, but first trigger a validation error, then test.
      $this->drupalPost('form-test/state-persist', array('title' => ''), t('Submit'), $options);
      $this->assertText(t('!name field is required.', array('!name' => 'title')));
      // Submit the form again triggering no validation error.
      $this->drupalPost(NULL, array('title' => 'foo'), t('Submit'), $options);
      $this->assertText('State persisted.');

      // Now post to the rebuilt form and verify it's still there afterwards.
      $this->drupalPost(NULL, array('title' => 'bar'), t('Submit'), $options);
      $this->assertText('State persisted.');
    }
  }

  /**
   * Verify that the form build-id remains the same when validation errors
   * occur on a mutable form.
   */
  function testMutableForm() {
    // Request the form with 'cache' query parameter to enable form caching.
    $this->drupalGet('form_test/form-storage', array('query' => array('cache' => 1)));
    $buildIdFields = $this->xpath('//input[@name="form_build_id"]');
    $this->assertEqual(count($buildIdFields), 1, 'One form build id field on the page');
    $buildId = (string) $buildIdFields[0]['value'];

    // Trigger validation error by submitting an empty title.
    $edit = array('title' => '');
    $this->drupalPost(NULL, $edit, 'Continue submit');

    // Verify that the build-id did not change.
    $this->assertFieldByName('form_build_id', $buildId, 'Build id remains the same when form validation fails');
  }

  /**
   * Verifies that form build-id is regenerated when loading an immutable form
   * from the cache.
   */
  function testImmutableForm() {
    // Request the form with 'cache' query parameter to enable form caching.
    $this->drupalGet('form_test/form-storage', array('query' => array('cache' => 1, 'immutable' => 1)));
    $buildIdFields = $this->xpath('//input[@name="form_build_id"]');
    $this->assertEqual(count($buildIdFields), 1, 'One form build id field on the page');
    $buildId = (string) $buildIdFields[0]['value'];

    // Trigger validation error by submitting an empty title.
    $edit = array('title' => '');
    $this->drupalPost(NULL, $edit, 'Continue submit');

    // Verify that the build-id did change.
    $this->assertNoFieldByName('form_build_id', $buildId, 'Build id changes when form validation fails');

    // Retrieve the new build-id.
    $buildIdFields = $this->xpath('//input[@name="form_build_id"]');
    $this->assertEqual(count($buildIdFields), 1, 'One form build id field on the page');
    $buildId = (string) $buildIdFields[0]['value'];

    // Trigger validation error by again submitting an empty title.
    $edit = array('title' => '');
    $this->drupalPost(NULL, $edit, 'Continue submit');

    // Verify that the build-id does not change the second time.
    $this->assertFieldByName('form_build_id', $buildId, 'Build id remains the same when form validation fails subsequently');
  }

  /**
   * Verify that existing contrib code cannot overwrite immutable form state.
   */
  public function testImmutableFormLegacyProtection() {
    $this->drupalGet('form_test/form-storage', array('query' => array('cache' => 1, 'immutable' => 1)));
    $build_id_fields = $this->xpath('//input[@name="form_build_id"]');
    $this->assertEqual(count($build_id_fields), 1, 'One form build id field on the page');
    $build_id = (string) $build_id_fields[0]['value'];

    // Try to poison the form cache.
    $original = $this->drupalGetAJAX('form_test/form-storage-legacy/' . $build_id);
    $this->assertEqual($original['form']['#build_id_old'], $build_id, 'Original build_id was recorded');
    $this->assertNotEqual($original['form']['#build_id'], $build_id, 'New build_id was generated');

    // Assert that a watchdog message was logged by form_set_cache.
    $status = (bool) db_query_range('SELECT 1 FROM {watchdog} WHERE message = :message', 0, 1, array(':message' => 'Form build-id mismatch detected while attempting to store a form in the cache.'));
    $this->assert($status, 'A watchdog message was logged by form_set_cache');

    // Ensure that the form state was not poisoned by the preceeding call.
    $original = $this->drupalGetAJAX('form_test/form-storage-legacy/' . $build_id);
    $this->assertEqual($original['form']['#build_id_old'], $build_id, 'Original build_id was recorded');
    $this->assertNotEqual($original['form']['#build_id'], $build_id, 'New build_id was generated');
    $this->assert(empty($original['form']['#poisoned']), 'Original form structure was preserved');
    $this->assert(empty($original['form_state']['poisoned']), 'Original form state was preserved');
  }
}

/**
 * Test the form storage when page caching for anonymous users is turned on.
 */
class FormsFormStoragePageCacheTestCase extends DrupalWebTestCase {
  protected $profile = 'testing';

  public static function getInfo() {
    return array(
      'name'  => 'Forms using form storage on cached pages',
      'description'  => 'Tests a form using form storage and makes sure validation and caching works when page caching for anonymous users is turned on.',
      'group' => 'Form API',
    );
  }

  public function setUp() {
    parent::setUp('form_test');

    variable_set('cache', TRUE);
  }

  /**
   * Return the build id of the current form.
   */
  protected function getFormBuildId() {
    $build_id_fields = $this->xpath('//input[@name="form_build_id"]');
    $this->assertEqual(count($build_id_fields), 1, 'One form build id field on the page');
    return (string) $build_id_fields[0]['value'];
  }

  /**
   * Build-id is regenerated when validating cached form.
   */
  public function testValidateFormStorageOnCachedPage() {
    $this->drupalGet('form_test/form-storage-page-cache');
    $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Page was not cached.');
    $this->assertText('No old build id', 'No old build id on the page');
    $build_id_initial = $this->getFormBuildId();

    // Trigger validation error by submitting an empty title.
    $edit = array('title' => '');
    $this->drupalPost(NULL, $edit, 'Save');
    $this->assertText($build_id_initial, 'Old build id on the page');
    $build_id_first_validation = $this->getFormBuildId();
    $this->assertNotEqual($build_id_initial, $build_id_first_validation, 'Build id changes when form validation fails');

    // Trigger validation error by again submitting an empty title.
    $edit = array('title' => '');
    $this->drupalPost(NULL, $edit, 'Save');
    $this->assertText('No old build id', 'No old build id on the page');
    $build_id_second_validation = $this->getFormBuildId();
    $this->assertEqual($build_id_first_validation, $build_id_second_validation, 'Build id remains the same when form validation fails subsequently');

    // Repeat the test sequence but this time with a page loaded from the cache.
    $this->drupalGet('form_test/form-storage-page-cache');
    $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
    $this->assertText('No old build id', 'No old build id on the page');
    $build_id_from_cache_initial = $this->getFormBuildId();
    $this->assertEqual($build_id_initial, $build_id_from_cache_initial, 'Build id is the same as on the first request');

    // Trigger validation error by submitting an empty title.
    $edit = array('title' => '');
    $this->drupalPost(NULL, $edit, 'Save');
    $this->assertText($build_id_initial, 'Old build id is initial build id');
    $build_id_from_cache_first_validation = $this->getFormBuildId();
    $this->assertNotEqual($build_id_initial, $build_id_from_cache_first_validation, 'Build id changes when form validation fails');
    $this->assertNotEqual($build_id_first_validation, $build_id_from_cache_first_validation, 'Build id from first user is not reused');

    // Trigger validation error by again submitting an empty title.
    $edit = array('title' => '');
    $this->drupalPost(NULL, $edit, 'Save');
    $this->assertText('No old build id', 'No old build id on the page');
    $build_id_from_cache_second_validation = $this->getFormBuildId();
    $this->assertEqual($build_id_from_cache_first_validation, $build_id_from_cache_second_validation, 'Build id remains the same when form validation fails subsequently');
  }

  /**
   * Build-id is regenerated when rebuilding cached form.
   */
  public function testRebuildFormStorageOnCachedPage() {
    $this->drupalGet('form_test/form-storage-page-cache');
    $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Page was not cached.');
    $this->assertText('No old build id', 'No old build id on the page');
    $build_id_initial = $this->getFormBuildId();

    // Trigger rebuild, should regenerate build id.
    $edit = array('title' => 'something');
    $this->drupalPost(NULL, $edit, 'Rebuild');
    $this->assertText($build_id_initial, 'Initial build id as old build id on the page');
    $build_id_first_rebuild = $this->getFormBuildId();
    $this->assertNotEqual($build_id_initial, $build_id_first_rebuild, 'Build id changes on first rebuild.');

    // Trigger subsequent rebuild, should regenerate the build id again.
    $edit = array('title' => 'something');
    $this->drupalPost(NULL, $edit, 'Rebuild');
    $this->assertText($build_id_first_rebuild, 'First build id as old build id on the page');
    $build_id_second_rebuild = $this->getFormBuildId();
    $this->assertNotEqual($build_id_first_rebuild, $build_id_second_rebuild, 'Build id changes on second rebuild.');
  }
}

/**
 * Test wrapper form callbacks.
 */
class FormsFormWrapperTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Form wrapper callback',
      'description' => 'Tests form wrapper callbacks to pass a prebuilt form to form builder functions.',
      'group' => 'Form API',
    );
  }

  function setUp() {
    parent::setUp('form_test');
  }

  /**
   * Tests using the form in a usual way.
   */
  function testWrapperCallback() {
    $this->drupalGet('form_test/wrapper-callback');
    $this->assertText('Form wrapper callback element output.', 'The form contains form wrapper elements.');
    $this->assertText('Form builder element output.', 'The form contains form builder elements.');
  }
}

/**
 * Test $form_state clearance.
 */
class FormStateValuesCleanTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Form state values clearance',
      'description' => 'Test proper removal of submitted form values using form_state_values_clean().',
      'group' => 'Form API',
    );
  }

  function setUp() {
    parent::setUp('form_test');
  }

  /**
   * Tests form_state_values_clean().
   */
  function testFormStateValuesClean() {
    $values = drupal_json_decode($this->drupalPost('form_test/form-state-values-clean', array(), t('Submit')));

    // Setup the expected result.
    $result = array(
      'beer' => 1000,
      'baz' => array('beer' => 2000),
    );

    // Verify that all internal Form API elements were removed.
    $this->assertFalse(isset($values['form_id']), format_string('%element was removed.', array('%element' => 'form_id')));
    $this->assertFalse(isset($values['form_token']), format_string('%element was removed.', array('%element' => 'form_token')));
    $this->assertFalse(isset($values['form_build_id']), format_string('%element was removed.', array('%element' => 'form_build_id')));
    $this->assertFalse(isset($values['op']), format_string('%element was removed.', array('%element' => 'op')));

    // Verify that all buttons were removed.
    $this->assertFalse(isset($values['foo']), format_string('%element was removed.', array('%element' => 'foo')));
    $this->assertFalse(isset($values['bar']), format_string('%element was removed.', array('%element' => 'bar')));
    $this->assertFalse(isset($values['baz']['foo']), format_string('%element was removed.', array('%element' => 'foo')));
    $this->assertFalse(isset($values['baz']['baz']), format_string('%element was removed.', array('%element' => 'baz')));

    // Verify that nested form value still exists.
    $this->assertTrue(isset($values['baz']['beer']), 'Nested form value still exists.');

    // Verify that actual form values equal resulting form values.
    $this->assertEqual($values, $result, 'Expected form values equal actual form values.');
  }
}

/**
 * Tests $form_state clearance with form elements having buttons.
 */
class FormStateValuesCleanAdvancedTestCase extends DrupalWebTestCase {
  /**
   * An image file path for uploading.
   */
  protected $image;

  public static function getInfo() {
    return array(
      'name' => 'Form state values clearance (advanced)',
      'description' => 'Test proper removal of submitted form values using form_state_values_clean() when having forms with elements containing buttons like "managed_file".',
      'group' => 'Form API',
    );
  }

  function setUp() {
    parent::setUp('form_test');
  }

  /**
   * Tests form_state_values_clean().
   */
  function testFormStateValuesCleanAdvanced() {

    // Get an image for uploading.
    $image_files = $this->drupalGetTestFiles('image');
    $this->image = current($image_files);

    // Check if the physical file is there.
    $this->assertTrue(is_file($this->image->uri), "The image file we're going to upload exists.");

    // "Browse" for the desired file.
    $edit = array('files[image]' => drupal_realpath($this->image->uri));

    // Post the form.
    $this->drupalPost('form_test/form-state-values-clean-advanced', $edit, t('Submit'));

    // Expecting a 200 HTTP code.
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
  }
}

/**
 * Tests form rebuilding.
 *
 * @todo Add tests for other aspects of form rebuilding.
 */
class FormsRebuildTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Form rebuilding',
      'description' => 'Tests functionality of drupal_rebuild_form().',
      'group' => 'Form API',
    );
  }

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

    $this->web_user = $this->drupalCreateUser(array('access content'));
    $this->drupalLogin($this->web_user);
  }

  /**
   * Tests preservation of values.
   */
  function testRebuildPreservesValues() {
    $edit = array(
      'checkbox_1_default_off' => TRUE,
      'checkbox_1_default_on' => FALSE,
      'text_1' => 'foo',
    );
    $this->drupalPost('form-test/form-rebuild-preserve-values', $edit, 'Add more');

    // Verify that initial elements retained their submitted values.
    $this->assertFieldChecked('edit-checkbox-1-default-off', 'A submitted checked checkbox retained its checked state during a rebuild.');
    $this->assertNoFieldChecked('edit-checkbox-1-default-on', 'A submitted unchecked checkbox retained its unchecked state during a rebuild.');
    $this->assertFieldById('edit-text-1', 'foo', 'A textfield retained its submitted value during a rebuild.');

    // Verify that newly added elements were initialized with their default values.
    $this->assertFieldChecked('edit-checkbox-2-default-on', 'A newly added checkbox was initialized with a default checked state.');
    $this->assertNoFieldChecked('edit-checkbox-2-default-off', 'A newly added checkbox was initialized with a default unchecked state.');
    $this->assertFieldById('edit-text-2', 'DEFAULT 2', 'A newly added textfield was initialized with its default value.');
  }

  /**
   * Tests that a form's action is retained after an Ajax submission.
   *
   * The 'action' attribute of a form should not change after an Ajax submission
   * followed by a non-Ajax submission, which triggers a validation error.
   */
  function testPreserveFormActionAfterAJAX() {
    // Create a multi-valued field for 'page' nodes to use for Ajax testing.
    $field_name = 'field_ajax_test';
    $field = array(
      'field_name' => $field_name,
      'type' => 'text',
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
    );
    field_create_field($field);
    $instance = array(
      'field_name' => $field_name,
      'entity_type' => 'node',
      'bundle' => 'page',
    );
    field_create_instance($instance);

    // Log in a user who can create 'page' nodes.
    $this->web_user = $this->drupalCreateUser(array('create page content'));
    $this->drupalLogin($this->web_user);

    // Get the form for adding a 'page' node. Submit an "add another item" Ajax
    // submission and verify it worked by ensuring the updated page has two text
    // field items in the field for which we just added an item.
    $this->drupalGet('node/add/page');
    $this->drupalPostAJAX(NULL, array(), array('field_ajax_test_add_more' => t('Add another item')), 'system/ajax', array(), array(), 'page-node-form');
    $this->assert(count($this->xpath('//div[contains(@class, "field-name-field-ajax-test")]//input[@type="text"]')) == 2, 'AJAX submission succeeded.');

    // Submit the form with the non-Ajax "Save" button, leaving the title field
    // blank to trigger a validation error, and ensure that a validation error
    // occurred, because this test is for testing what happens when a form is
    // re-rendered without being re-built, which is what happens when there's
    // a validation error.
    $this->drupalPost(NULL, array(), t('Save'));
    $this->assertText('Title field is required.', 'Non-AJAX submission correctly triggered a validation error.');

    // Ensure that the form contains two items in the multi-valued field, so we
    // know we're testing a form that was correctly retrieved from cache.
    $this->assert(count($this->xpath('//form[contains(@id, "page-node-form")]//div[contains(@class, "form-item-field-ajax-test")]//input[@type="text"]')) == 2, 'Form retained its state from cache.');

    // Ensure that the form's action is correct.
    $forms = $this->xpath('//form[contains(@class, "node-page-form")]');
    $this->assert(count($forms) == 1 && $forms[0]['action'] == url('node/add/page'), 'Re-rendered form contains the correct action value.');
  }
}

/**
 * Tests form redirection.
 */
class FormsRedirectTestCase extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Form redirecting',
      'description' => 'Tests functionality of drupal_redirect_form().',
      'group' => 'Form API',
    );
  }

  function setUp() {
    parent::setUp(array('form_test'));
  }

  /**
   * Tests form redirection.
   */
  function testRedirect() {
    $path = 'form-test/redirect';
    $options = array('query' => array('foo' => 'bar'));
    $options['absolute'] = TRUE;

    // Test basic redirection.
    $edit = array(
      'redirection' => TRUE,
      'destination' => $this->randomName(),
    );
    $this->drupalPost($path, $edit, t('Submit'));
    $this->assertUrl($edit['destination'], array(), 'Basic redirection works.');


    // Test without redirection.
    $edit = array(
      'redirection' => FALSE,
    );
    $this->drupalPost($path, $edit, t('Submit'));
    $this->assertUrl($path, array(), 'When redirect is set to FALSE, there should be no redirection.');

    // Test redirection with query parameters.
    $edit = array(
      'redirection' => TRUE,
      'destination' => $this->randomName(),
    );
    $this->drupalPost($path, $edit, t('Submit'), $options);
    $this->assertUrl($edit['destination'], array(), 'Redirection with query parameters works.');

    // Test without redirection but with query parameters.
    $edit = array(
      'redirection' => FALSE,
    );
    $this->drupalPost($path, $edit, t('Submit'), $options);
    $this->assertUrl($path, $options, 'When redirect is set to FALSE, there should be no redirection, and the query parameters should be passed along.');

    // Test redirection back to the original path.
    $edit = array(
      'redirection' => TRUE,
      'destination' => '',
    );
    $this->drupalPost($path, $edit, t('Submit'));
    $this->assertUrl($path, array(), 'When using an empty redirection string, there should be no redirection.');

    // Test redirection back to the original path with query parameters.
    $edit = array(
      'redirection' => TRUE,
      'destination' => '',
    );
    $this->drupalPost($path, $edit, t('Submit'), $options);
    $this->assertUrl($path, $options, 'When using an empty redirection string, there should be no redirection, and the query parameters should be passed along.');
  }

}

/**
 * Test the programmatic form submission behavior.
 */
class FormsProgrammaticTestCase extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Programmatic form submissions',
      'description' => 'Test the programmatic form submission behavior.',
      'group' => 'Form API',
    );
  }

  function setUp() {
    parent::setUp('form_test');
  }

  /**
   * Test the programmatic form submission workflow.
   */
  function testSubmissionWorkflow() {
    // Backup the current batch status and reset it to avoid conflicts while
    // processing the dummy form submit handler.
    $current_batch = $batch =& batch_get();
    $batch = array();

    // Test that a programmatic form submission is rejected when a required
    // textfield is omitted and correctly processed when it is provided.
    $this->submitForm(array(), FALSE);
    $this->submitForm(array('textfield' => 'test 1'), TRUE);
    $this->submitForm(array(), FALSE);
    $this->submitForm(array('textfield' => 'test 2'), TRUE);

    // Test that a programmatic form submission can turn on and off checkboxes
    // which are, by default, checked.
    $this->submitForm(array('textfield' => 'dummy value', 'checkboxes' => array(1 => 1, 2 => 2)), TRUE);
    $this->submitForm(array('textfield' => 'dummy value', 'checkboxes' => array(1 => 1, 2 => NULL)), TRUE);
    $this->submitForm(array('textfield' => 'dummy value', 'checkboxes' => array(1 => NULL, 2 => 2)), TRUE);
    $this->submitForm(array('textfield' => 'dummy value', 'checkboxes' => array(1 => NULL, 2 => NULL)), TRUE);

    // Test that a programmatic form submission can successfully submit values
    // even for fields where the #access property is FALSE.
    $this->submitForm(array('textfield' => 'dummy value', 'textfield_no_access' => 'test value'), TRUE);
    // Test that #access is respected for programmatic form submissions when
    // requested to do so.
    $submitted_values = array('textfield' => 'dummy value', 'textfield_no_access' => 'test value');
    $expected_values = array('textfield' => 'dummy value', 'textfield_no_access' => 'default value');
    $form_state = array('programmed_bypass_access_check' => FALSE);
    $this->submitForm($submitted_values, TRUE, $expected_values, $form_state);

    // Test that a programmatic form submission can correctly click a button
    // that limits validation errors based on user input. Since we do not
    // submit any values for "textfield" here and the textfield is required, we
    // only expect form validation to pass when validation is limited to a
    // different field.
    $this->submitForm(array('op' => 'Submit with limited validation', 'field_to_validate' => 'all'), FALSE);
    $this->submitForm(array('op' => 'Submit with limited validation', 'field_to_validate' => 'textfield'), FALSE);
    $this->submitForm(array('op' => 'Submit with limited validation', 'field_to_validate' => 'field_to_validate'), TRUE);

    // Restore the current batch status.
    $batch = $current_batch;
  }

  /**
   * Helper function used to programmatically submit the form defined in
   * form_test.module with the given values.
   *
   * @param $values
   *   An array of field values to be submitted.
   * @param $valid_input
   *   A boolean indicating whether or not the form submission is expected to
   *   be valid.
   * @param $expected_values
   *   (Optional) An array of field values that are expected to be stored by
   *   the form submit handler. If not set, the submitted $values are assumed
   *   to also be the expected stored values.
   * @param $form_state
   *   (Optional) A keyed array containing the state of the form, to be sent in
   *   the call to drupal_form_submit(). The $values parameter is added to
   *   $form_state['values'] by default, if it is not already set.
   */
  private function submitForm($values, $valid_input, $expected_values = NULL, $form_state = array()) {
    // Programmatically submit the given values.
    $form_state += array('values' => $values);
    drupal_form_submit('form_test_programmatic_form', $form_state);

    // Check that the form returns an error when expected, and vice versa.
    $errors = form_get_errors();
    $valid_form = empty($errors);
    $args = array(
      '%values' => print_r($values, TRUE),
      '%errors' => $valid_form ? t('None') : implode(' ', $errors),
    );
    $this->assertTrue($valid_input == $valid_form, format_string('Input values: %values<br/>Validation handler errors: %errors', $args));

    // We check submitted values only if we have a valid input.
    if ($valid_input) {
      // By fetching the values from $form_state['storage'] we ensure that the
      // submission handler was properly executed.
      $stored_values = $form_state['storage']['programmatic_form_submit'];
      if (!isset($expected_values)) {
        $expected_values = $values;
      }
      foreach ($expected_values as $key => $value) {
        $this->assertTrue(isset($stored_values[$key]) && $stored_values[$key] == $value, format_string('Submission handler correctly executed: %stored_key is %stored_value', array('%stored_key' => $key, '%stored_value' => print_r($value, TRUE))));
      }
    }
  }
}

/**
 * Test that FAPI correctly determines $form_state['triggering_element'].
 */
class FormsTriggeringElementTestCase extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Form triggering element determination',
      'description' => 'Test the determination of $form_state[\'triggering_element\'].',
      'group' => 'Form API',
    );
  }

  function setUp() {
    parent::setUp('form_test');
  }

  /**
   * Test the determination of $form_state['triggering_element'] when no button
   * information is included in the POST data, as is sometimes the case when
   * the ENTER key is pressed in a textfield in Internet Explorer.
   */
  function testNoButtonInfoInPost() {
    $path = 'form-test/clicked-button';
    $edit = array();
    $form_html_id = 'form-test-clicked-button';

    // Ensure submitting a form with no buttons results in no
    // $form_state['triggering_element'] and the form submit handler not
    // running.
    $this->drupalPost($path, $edit, NULL, array(), array(), $form_html_id);
    $this->assertText('There is no clicked button.', '$form_state[\'triggering_element\'] set to NULL.');
    $this->assertNoText('Submit handler for form_test_clicked_button executed.', 'Form submit handler did not execute.');

    // Ensure submitting a form with one or more submit buttons results in
    // $form_state['triggering_element'] being set to the first one the user has
    // access to. An argument with 'r' in it indicates a restricted
    // (#access=FALSE) button.
    $this->drupalPost($path . '/s', $edit, NULL, array(), array(), $form_html_id);
    $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to only button.');
    $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');

    $this->drupalPost($path . '/s/s', $edit, NULL, array(), array(), $form_html_id);
    $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to first button.');
    $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');

    $this->drupalPost($path . '/rs/s', $edit, NULL, array(), array(), $form_html_id);
    $this->assertText('The clicked button is button2.', '$form_state[\'triggering_element\'] set to first available button.');
    $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');

    // Ensure submitting a form with buttons of different types results in
    // $form_state['triggering_element'] being set to the first button,
    // regardless of type. For the FAPI 'button' type, this should result in the
    // submit handler not executing. The types are 's'(ubmit), 'b'(utton), and
    // 'i'(mage_button).
    $this->drupalPost($path . '/s/b/i', $edit, NULL, array(), array(), $form_html_id);
    $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to first button.');
    $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');

    $this->drupalPost($path . '/b/s/i', $edit, NULL, array(), array(), $form_html_id);
    $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to first button.');
    $this->assertNoText('Submit handler for form_test_clicked_button executed.', 'Form submit handler did not execute.');

    $this->drupalPost($path . '/i/s/b', $edit, NULL, array(), array(), $form_html_id);
    $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to first button.');
    $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');
  }

  /**
   * Test that $form_state['triggering_element'] does not get set to a button
   * with #access=FALSE.
   */
  function testAttemptAccessControlBypass() {
    $path = 'form-test/clicked-button';
    $form_html_id = 'form-test-clicked-button';

    // Retrieve a form where 'button1' has #access=FALSE and 'button2' doesn't.
    $this->drupalGet($path . '/rs/s');

    // Submit the form with 'button1=button1' in the POST data, which someone
    // trying to get around security safeguards could easily do. We have to do
    // a little trickery here, to work around the safeguards in drupalPost(): by
    // renaming the text field that is in the form to 'button1', we can get the
    // data we want into $_POST.
    $elements = $this->xpath('//form[@id="' . $form_html_id . '"]//input[@name="text"]');
    $elements[0]['name'] = 'button1';
    $this->drupalPost(NULL, array('button1' => 'button1'), NULL, array(), array(), $form_html_id);

    // Ensure that $form_state['triggering_element'] was not set to the
    // restricted button. Do this with both a negative and positive assertion,
    // because negative assertions alone can be brittle. See
    // testNoButtonInfoInPost() for why the triggering element gets set to
    // 'button2'.
    $this->assertNoText('The clicked button is button1.', '$form_state[\'triggering_element\'] not set to a restricted button.');
    $this->assertText('The clicked button is button2.', '$form_state[\'triggering_element\'] not set to a restricted button.');
  }
}

/**
 * Tests rebuilding of arbitrary forms by altering them.
 */
class FormsArbitraryRebuildTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Rebuild arbitrary forms',
      'description' => 'Tests altering forms to be rebuilt so there are multiple steps.',
      'group' => 'Form API',
    );
  }

  function setUp() {
    parent::setUp('form_test');
    // Auto-create a field for testing.
    $field = array(
      'field_name' => 'test_multiple',
      'type' => 'text',
      'cardinality' => -1,
      'translatable' => FALSE,
    );
    field_create_field($field);

    $instance = array(
      'entity_type' => 'node',
      'field_name' => 'test_multiple',
      'bundle' => 'page',
      'label' => 'Test a multiple valued field',
      'widget' => array(
        'type' => 'text_textfield',
        'weight' => 0,
      ),
    );
    field_create_instance($instance);
    variable_set('user_register', USER_REGISTER_VISITORS);
  }

  /**
   * Tests a basic rebuild with the user registration form.
   */
  function testUserRegistrationRebuild() {
    $edit = array(
      'name' => 'foo',
      'mail' => 'bar@example.com',
    );
    $this->drupalPost('user/register', $edit, 'Rebuild');
    $this->assertText('Form rebuilt.');
    $this->assertFieldByName('name', 'foo', 'Entered user name has been kept.');
    $this->assertFieldByName('mail', 'bar@example.com', 'Entered mail address has been kept.');
  }

  /**
   * Tests a rebuild caused by a multiple value field.
   */
  function testUserRegistrationMultipleField() {
    $edit = array(
      'name' => 'foo',
      'mail' => 'bar@example.com',
    );
    $this->drupalPost('user/register', $edit, t('Add another item'), array('query' => array('field' => TRUE)));
    $this->assertText('Test a multiple valued field', 'Form has been rebuilt.');
    $this->assertFieldByName('name', 'foo', 'Entered user name has been kept.');
    $this->assertFieldByName('mail', 'bar@example.com', 'Entered mail address has been kept.');
  }
}

/**
 * Tests form API file inclusion.
 */
class FormsFileInclusionTestCase extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Form API file inclusion',
      'description' => 'Tests form API file inclusion.',
      'group' => 'Form API',
    );
  }

  function setUp() {
    parent::setUp('form_test');
  }

  /**
   * Tests loading an include specified in hook_menu().
   */
  function testLoadMenuInclude() {
    $this->drupalPostAJAX('form-test/load-include-menu', array(), array('op' => t('Save')), 'system/ajax', array(), array(), 'form-test-load-include-menu');
    $this->assertText('Submit callback called.');
  }

  /**
   * Tests loading a custom specified inlcude.
   */
  function testLoadCustomInclude() {
    $this->drupalPost('form-test/load-include-custom', array(), t('Save'));
    $this->assertText('Submit callback called.');
  }
}

/**
 * Tests checkbox element.
 */
class FormCheckboxTestCase extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Form API checkbox',
      'description' => 'Tests form API checkbox handling of various combinations of #default_value and #return_value.',
      'group' => 'Form API',
    );
  }

  function setUp() {
    parent::setUp('form_test');
  }

  function testFormCheckbox() {
    // Ensure that the checked state is determined and rendered correctly for
    // tricky combinations of default and return values.
    foreach (array(FALSE, NULL, TRUE, 0, '0', '', 1, '1', 'foobar', '1foobar') as $default_value) {
      // Only values that can be used for array indeces are supported for
      // #return_value, with the exception of integer 0, which is not supported.
      // @see form_process_checkbox().
      foreach (array('0', '', 1, '1', 'foobar', '1foobar') as $return_value) {
        $form_array = drupal_get_form('form_test_checkbox_type_juggling', $default_value, $return_value);
        $form = drupal_render($form_array);
        if ($default_value === TRUE) {
          $checked = TRUE;
        }
        elseif ($return_value === '0') {
          $checked = ($default_value === '0');
        }
        elseif ($return_value === '') {
          $checked = ($default_value === '');
        }
        elseif ($return_value === 1 || $return_value === '1') {
          $checked = ($default_value === 1 || $default_value === '1');
        }
        elseif ($return_value === 'foobar') {
          $checked = ($default_value === 'foobar');
        }
        elseif ($return_value === '1foobar') {
          $checked = ($default_value === '1foobar');
        }
        $checked_in_html = strpos($form, 'checked') !== FALSE;
        $message = format_string('#default_value is %default_value #return_value is %return_value.', array('%default_value' => var_export($default_value, TRUE), '%return_value' => var_export($return_value, TRUE)));
        $this->assertIdentical($checked, $checked_in_html, $message);
      }
    }

    // Ensure that $form_state['values'] is populated correctly for a checkboxes
    // group that includes a 0-indexed array of options.
    $results = json_decode($this->drupalPost('form-test/checkboxes-zero', array(), 'Save'));
    $this->assertIdentical($results->checkbox_off, array(0, 0, 0), 'All three in checkbox_off are zeroes: off.');
    $this->assertIdentical($results->checkbox_zero_default, array('0', 0, 0), 'The first choice is on in checkbox_zero_default');
    $this->assertIdentical($results->checkbox_string_zero_default, array('0', 0, 0), 'The first choice is on in checkbox_string_zero_default');
    $edit = array('checkbox_off[0]' => '0');
    $results = json_decode($this->drupalPost('form-test/checkboxes-zero', $edit, 'Save'));
    $this->assertIdentical($results->checkbox_off, array('0', 0, 0), 'The first choice is on in checkbox_off but the rest is not');

    // Ensure that each checkbox is rendered correctly for a checkboxes group
    // that includes a 0-indexed array of options.
    $this->drupalPost('form-test/checkboxes-zero/0', array(), 'Save');
    $checkboxes = $this->xpath('//input[@type="checkbox"]');
    foreach ($checkboxes as $checkbox) {
      $checked = isset($checkbox['checked']);
      $name = (string) $checkbox['name'];
      $this->assertIdentical($checked, $name == 'checkbox_zero_default[0]' || $name == 'checkbox_string_zero_default[0]', format_string('Checkbox %name correctly checked', array('%name' => $name)));
    }
    $edit = array('checkbox_off[0]' => '0');
    $this->drupalPost('form-test/checkboxes-zero/0', $edit, 'Save');
    $checkboxes = $this->xpath('//input[@type="checkbox"]');
    foreach ($checkboxes as $checkbox) {
      $checked = isset($checkbox['checked']);
      $name = (string) $checkbox['name'];
      $this->assertIdentical($checked, $name == 'checkbox_off[0]' || $name == 'checkbox_zero_default[0]' || $name == 'checkbox_string_zero_default[0]', format_string('Checkbox %name correctly checked', array('%name' => $name)));
    }
  }
}

/**
 * Tests uniqueness of generated HTML IDs.
 */
class HTMLIdTestCase extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Unique HTML IDs',
      'description' => 'Tests functionality of drupal_html_id().',
      'group' => 'Form API',
    );
  }

  function setUp() {
    parent::setUp('form_test');
  }

  /**
   * Tests that HTML IDs do not get duplicated when form validation fails.
   */
  function testHTMLId() {
    $this->drupalGet('form-test/double-form');
    $this->assertNoDuplicateIds('There are no duplicate IDs');

    // Submit second form with empty title.
    $edit = array();
    $this->drupalPost(NULL, $edit, 'Save', array(), array(), 'form-test-html-id--2');
    $this->assertNoDuplicateIds('There are no duplicate IDs');
  }
}