form.test 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101
  1. <?php
  2. /**
  3. * @file
  4. * Unit tests for the Drupal Form API.
  5. */
  6. class FormsTestCase extends DrupalWebTestCase {
  7. public static function getInfo() {
  8. return array(
  9. 'name' => 'Form element validation',
  10. 'description' => 'Tests various form element validation mechanisms.',
  11. 'group' => 'Form API',
  12. );
  13. }
  14. function setUp() {
  15. parent::setUp('form_test');
  16. }
  17. /**
  18. * Check several empty values for required forms elements.
  19. *
  20. * Carriage returns, tabs, spaces, and unchecked checkbox elements are not
  21. * valid content for a required field.
  22. *
  23. * If the form field is found in form_get_errors() then the test pass.
  24. */
  25. function testRequiredFields() {
  26. // Originates from http://drupal.org/node/117748
  27. // Sets of empty strings and arrays.
  28. $empty_strings = array('""' => "", '"\n"' => "\n", '" "' => " ", '"\t"' => "\t", '" \n\t "' => " \n\t ", '"\n\n\n\n\n"' => "\n\n\n\n\n");
  29. $empty_arrays = array('array()' => array());
  30. $empty_checkbox = array(NULL);
  31. $elements['textfield']['element'] = array('#title' => $this->randomName(), '#type' => 'textfield');
  32. $elements['textfield']['empty_values'] = $empty_strings;
  33. $elements['password']['element'] = array('#title' => $this->randomName(), '#type' => 'password');
  34. $elements['password']['empty_values'] = $empty_strings;
  35. $elements['password_confirm']['element'] = array('#title' => $this->randomName(), '#type' => 'password_confirm');
  36. // Provide empty values for both password fields.
  37. foreach ($empty_strings as $key => $value) {
  38. $elements['password_confirm']['empty_values'][$key] = array('pass1' => $value, 'pass2' => $value);
  39. }
  40. $elements['textarea']['element'] = array('#title' => $this->randomName(), '#type' => 'textarea');
  41. $elements['textarea']['empty_values'] = $empty_strings;
  42. $elements['radios']['element'] = array('#title' => $this->randomName(), '#type' => 'radios', '#options' => array('' => t('None'), $this->randomName(), $this->randomName(), $this->randomName()));
  43. $elements['radios']['empty_values'] = $empty_arrays;
  44. $elements['checkbox']['element'] = array('#title' => $this->randomName(), '#type' => 'checkbox', '#required' => TRUE);
  45. $elements['checkbox']['empty_values'] = $empty_checkbox;
  46. $elements['checkboxes']['element'] = array('#title' => $this->randomName(), '#type' => 'checkboxes', '#options' => array($this->randomName(), $this->randomName(), $this->randomName()));
  47. $elements['checkboxes']['empty_values'] = $empty_arrays;
  48. $elements['select']['element'] = array('#title' => $this->randomName(), '#type' => 'select', '#options' => array('' => t('None'), $this->randomName(), $this->randomName(), $this->randomName()));
  49. $elements['select']['empty_values'] = $empty_strings;
  50. $elements['file']['element'] = array('#title' => $this->randomName(), '#type' => 'file');
  51. $elements['file']['empty_values'] = $empty_strings;
  52. // Regular expression to find the expected marker on required elements.
  53. $required_marker_preg = '@<label.*<span class="form-required" title="This field is required\.">\*</span></label>@';
  54. // Go through all the elements and all the empty values for them.
  55. foreach ($elements as $type => $data) {
  56. foreach ($data['empty_values'] as $key => $empty) {
  57. foreach (array(TRUE, FALSE) as $required) {
  58. $form_id = $this->randomName();
  59. $form = array();
  60. $form_state = form_state_defaults();
  61. form_clear_error();
  62. $form['op'] = array('#type' => 'submit', '#value' => t('Submit'));
  63. $element = $data['element']['#title'];
  64. $form[$element] = $data['element'];
  65. $form[$element]['#required'] = $required;
  66. $form_state['input'][$element] = $empty;
  67. $form_state['input']['form_id'] = $form_id;
  68. $form_state['method'] = 'post';
  69. // The form token CSRF protection should not interfere with this test,
  70. // so we bypass it by marking this test form as programmed.
  71. $form_state['programmed'] = TRUE;
  72. drupal_prepare_form($form_id, $form, $form_state);
  73. drupal_process_form($form_id, $form, $form_state);
  74. $errors = form_get_errors();
  75. // Form elements of type 'radios' throw all sorts of PHP notices
  76. // when you try to render them like this, so we ignore those for
  77. // testing the required marker.
  78. // @todo Fix this work-around (http://drupal.org/node/588438).
  79. $form_output = ($type == 'radios') ? '' : drupal_render($form);
  80. if ($required) {
  81. // Make sure we have a form error for this element.
  82. $this->assertTrue(isset($errors[$element]), "Check empty($key) '$type' field '$element'");
  83. if (!empty($form_output)) {
  84. // Make sure the form element is marked as required.
  85. $this->assertTrue(preg_match($required_marker_preg, $form_output), "Required '$type' field is marked as required");
  86. }
  87. }
  88. else {
  89. if (!empty($form_output)) {
  90. // Make sure the form element is *not* marked as required.
  91. $this->assertFalse(preg_match($required_marker_preg, $form_output), "Optional '$type' field is not marked as required");
  92. }
  93. if ($type == 'select') {
  94. // Select elements are going to have validation errors with empty
  95. // input, since those are illegal choices. Just make sure the
  96. // error is not "field is required".
  97. $this->assertTrue((empty($errors[$element]) || strpos('field is required', $errors[$element]) === FALSE), "Optional '$type' field '$element' is not treated as a required element");
  98. }
  99. else {
  100. // Make sure there is *no* form error for this element.
  101. $this->assertTrue(empty($errors[$element]), "Optional '$type' field '$element' has no errors with empty input");
  102. }
  103. }
  104. }
  105. }
  106. }
  107. // Clear the expected form error messages so they don't appear as exceptions.
  108. drupal_get_messages();
  109. }
  110. /**
  111. * Tests validation for required checkbox, select, and radio elements.
  112. *
  113. * Submits a test form containing several types of form elements. The form
  114. * is submitted twice, first without values for required fields and then
  115. * with values. Each submission is checked for relevant error messages.
  116. *
  117. * @see form_test_validate_required_form()
  118. */
  119. function testRequiredCheckboxesRadio() {
  120. $form = $form_state = array();
  121. $form = form_test_validate_required_form($form, $form_state);
  122. // Attempt to submit the form with no required fields set.
  123. $edit = array();
  124. $this->drupalPost('form-test/validate-required', $edit, 'Submit');
  125. // The only error messages that should appear are the relevant 'required'
  126. // messages for each field.
  127. $expected = array();
  128. foreach (array('textfield', 'checkboxes', 'select', 'radios') as $key) {
  129. $expected[] = t('!name field is required.', array('!name' => $form[$key]['#title']));
  130. }
  131. // Check the page for error messages.
  132. $errors = $this->xpath('//div[contains(@class, "error")]//li');
  133. foreach ($errors as $error) {
  134. $expected_key = array_search($error[0], $expected);
  135. // If the error message is not one of the expected messages, fail.
  136. if ($expected_key === FALSE) {
  137. $this->fail(format_string("Unexpected error message: @error", array('@error' => $error[0])));
  138. }
  139. // Remove the expected message from the list once it is found.
  140. else {
  141. unset($expected[$expected_key]);
  142. }
  143. }
  144. // Fail if any expected messages were not found.
  145. foreach ($expected as $not_found) {
  146. $this->fail(format_string("Found error message: @error", array('@error' => $not_found)));
  147. }
  148. // Verify that input elements are still empty.
  149. $this->assertFieldByName('textfield', '');
  150. $this->assertNoFieldChecked('edit-checkboxes-foo');
  151. $this->assertNoFieldChecked('edit-checkboxes-bar');
  152. $this->assertOptionSelected('edit-select', '');
  153. $this->assertNoFieldChecked('edit-radios-foo');
  154. $this->assertNoFieldChecked('edit-radios-bar');
  155. $this->assertNoFieldChecked('edit-radios-optional-foo');
  156. $this->assertNoFieldChecked('edit-radios-optional-bar');
  157. $this->assertNoFieldChecked('edit-radios-optional-default-value-false-foo');
  158. $this->assertNoFieldChecked('edit-radios-optional-default-value-false-bar');
  159. // Submit again with required fields set and verify that there are no
  160. // error messages.
  161. $edit = array(
  162. 'textfield' => $this->randomString(),
  163. 'checkboxes[foo]' => TRUE,
  164. 'select' => 'foo',
  165. 'radios' => 'bar',
  166. );
  167. $this->drupalPost(NULL, $edit, 'Submit');
  168. $this->assertNoFieldByXpath('//div[contains(@class, "error")]', FALSE, 'No error message is displayed when all required fields are filled.');
  169. $this->assertRaw("The form_test_validate_required_form form was submitted successfully.", 'Validation form submitted successfully.');
  170. }
  171. /**
  172. * Tests validation for required textfield element without title.
  173. *
  174. * Submits a test form containing a textfield form elements without title.
  175. * The form is submitted twice, first without value for the required field
  176. * and then with value. Each submission is checked for relevant error
  177. * messages.
  178. *
  179. * @see form_test_validate_required_form_no_title()
  180. */
  181. function testRequiredTextfieldNoTitle() {
  182. $form = $form_state = array();
  183. $form = form_test_validate_required_form_no_title($form, $form_state);
  184. // Attempt to submit the form with no required field set.
  185. $edit = array();
  186. $this->drupalPost('form-test/validate-required-no-title', $edit, 'Submit');
  187. $this->assertNoRaw("The form_test_validate_required_form_no_title form was submitted successfully.", 'Validation form submitted successfully.');
  188. // Check the page for the error class on the textfield.
  189. $this->assertFieldByXPath('//input[contains(@class, "error")]', FALSE, 'Error input form element class found.');
  190. // Submit again with required fields set and verify that there are no
  191. // error messages.
  192. $edit = array(
  193. 'textfield' => $this->randomString(),
  194. );
  195. $this->drupalPost(NULL, $edit, 'Submit');
  196. $this->assertNoFieldByXpath('//input[contains(@class, "error")]', FALSE, 'No error input form element class found.');
  197. $this->assertRaw("The form_test_validate_required_form_no_title form was submitted successfully.", 'Validation form submitted successfully.');
  198. }
  199. /**
  200. * Test default value handling for checkboxes.
  201. *
  202. * @see _form_test_checkbox()
  203. */
  204. function testCheckboxProcessing() {
  205. // First, try to submit without the required checkbox.
  206. $edit = array();
  207. $this->drupalPost('form-test/checkbox', $edit, t('Submit'));
  208. $this->assertRaw(t('!name field is required.', array('!name' => 'required_checkbox')), 'A required checkbox is actually mandatory');
  209. // Now try to submit the form correctly.
  210. $values = drupal_json_decode($this->drupalPost(NULL, array('required_checkbox' => 1), t('Submit')));
  211. $expected_values = array(
  212. 'disabled_checkbox_on' => 'disabled_checkbox_on',
  213. 'disabled_checkbox_off' => '',
  214. 'checkbox_on' => 'checkbox_on',
  215. 'checkbox_off' => '',
  216. 'zero_checkbox_on' => '0',
  217. 'zero_checkbox_off' => '',
  218. );
  219. foreach ($expected_values as $widget => $expected_value) {
  220. $this->assertEqual($values[$widget], $expected_value, format_string('Checkbox %widget returns expected value (expected: %expected, got: %value)', array(
  221. '%widget' => var_export($widget, TRUE),
  222. '%expected' => var_export($expected_value, TRUE),
  223. '%value' => var_export($values[$widget], TRUE),
  224. )));
  225. }
  226. }
  227. /**
  228. * Tests validation of #type 'select' elements.
  229. */
  230. function testSelect() {
  231. $form = $form_state = array();
  232. $form = form_test_select($form, $form_state);
  233. $error = '!name field is required.';
  234. $this->drupalGet('form-test/select');
  235. // Posting without any values should throw validation errors.
  236. $this->drupalPost(NULL, array(), 'Submit');
  237. $this->assertNoText(t($error, array('!name' => $form['select']['#title'])));
  238. $this->assertNoText(t($error, array('!name' => $form['select_required']['#title'])));
  239. $this->assertNoText(t($error, array('!name' => $form['select_optional']['#title'])));
  240. $this->assertNoText(t($error, array('!name' => $form['empty_value']['#title'])));
  241. $this->assertNoText(t($error, array('!name' => $form['empty_value_one']['#title'])));
  242. $this->assertText(t($error, array('!name' => $form['no_default']['#title'])));
  243. $this->assertNoText(t($error, array('!name' => $form['no_default_optional']['#title'])));
  244. $this->assertText(t($error, array('!name' => $form['no_default_empty_option']['#title'])));
  245. $this->assertNoText(t($error, array('!name' => $form['no_default_empty_option_optional']['#title'])));
  246. $this->assertText(t($error, array('!name' => $form['no_default_empty_value']['#title'])));
  247. $this->assertText(t($error, array('!name' => $form['no_default_empty_value_one']['#title'])));
  248. $this->assertNoText(t($error, array('!name' => $form['no_default_empty_value_optional']['#title'])));
  249. $this->assertNoText(t($error, array('!name' => $form['multiple']['#title'])));
  250. $this->assertNoText(t($error, array('!name' => $form['multiple_no_default']['#title'])));
  251. $this->assertText(t($error, array('!name' => $form['multiple_no_default_required']['#title'])));
  252. // Post values for required fields.
  253. $edit = array(
  254. 'no_default' => 'three',
  255. 'no_default_empty_option' => 'three',
  256. 'no_default_empty_value' => 'three',
  257. 'no_default_empty_value_one' => 'three',
  258. 'multiple_no_default_required[]' => 'three',
  259. );
  260. $this->drupalPost(NULL, $edit, 'Submit');
  261. $values = drupal_json_decode($this->drupalGetContent());
  262. // Verify expected values.
  263. $expected = array(
  264. 'select' => 'one',
  265. 'empty_value' => 'one',
  266. 'empty_value_one' => 'one',
  267. 'no_default' => 'three',
  268. 'no_default_optional' => 'one',
  269. 'no_default_optional_empty_value' => '',
  270. 'no_default_empty_option' => 'three',
  271. 'no_default_empty_option_optional' => '',
  272. 'no_default_empty_value' => 'three',
  273. 'no_default_empty_value_one' => 'three',
  274. 'no_default_empty_value_optional' => 0,
  275. 'multiple' => array('two' => 'two'),
  276. 'multiple_no_default' => array(),
  277. 'multiple_no_default_required' => array('three' => 'three'),
  278. );
  279. foreach ($expected as $key => $value) {
  280. $this->assertIdentical($values[$key], $value, format_string('@name: @actual is equal to @expected.', array(
  281. '@name' => $key,
  282. '@actual' => var_export($values[$key], TRUE),
  283. '@expected' => var_export($value, TRUE),
  284. )));
  285. }
  286. }
  287. /**
  288. * Test handling of disabled elements.
  289. *
  290. * @see _form_test_disabled_elements()
  291. */
  292. function testDisabledElements() {
  293. // Get the raw form in its original state.
  294. $form_state = array();
  295. $form = _form_test_disabled_elements(array(), $form_state);
  296. // Build a submission that tries to hijack the form by submitting input for
  297. // elements that are disabled.
  298. $edit = array();
  299. foreach (element_children($form) as $key) {
  300. if (isset($form[$key]['#test_hijack_value'])) {
  301. if (is_array($form[$key]['#test_hijack_value'])) {
  302. foreach ($form[$key]['#test_hijack_value'] as $subkey => $value) {
  303. $edit[$key . '[' . $subkey . ']'] = $value;
  304. }
  305. }
  306. else {
  307. $edit[$key] = $form[$key]['#test_hijack_value'];
  308. }
  309. }
  310. }
  311. // Submit the form with no input, as the browser does for disabled elements,
  312. // and fetch the $form_state['values'] that is passed to the submit handler.
  313. $this->drupalPost('form-test/disabled-elements', array(), t('Submit'));
  314. $returned_values['normal'] = drupal_json_decode($this->content);
  315. // Do the same with input, as could happen if JavaScript un-disables an
  316. // element. drupalPost() emulates a browser by not submitting input for
  317. // disabled elements, so we need to un-disable those elements first.
  318. $this->drupalGet('form-test/disabled-elements');
  319. $disabled_elements = array();
  320. foreach ($this->xpath('//*[@disabled]') as $element) {
  321. $disabled_elements[] = (string) $element['name'];
  322. unset($element['disabled']);
  323. }
  324. // All the elements should be marked as disabled, including the ones below
  325. // the disabled container.
  326. $this->assertEqual(count($disabled_elements), 32, 'The correct elements have the disabled property in the HTML code.');
  327. $this->drupalPost(NULL, $edit, t('Submit'));
  328. $returned_values['hijacked'] = drupal_json_decode($this->content);
  329. // Ensure that the returned values match the form's default values in both
  330. // cases.
  331. foreach ($returned_values as $type => $values) {
  332. $this->assertFormValuesDefault($values, $form);
  333. }
  334. }
  335. /**
  336. * Assert that the values submitted to a form matches the default values of the elements.
  337. */
  338. function assertFormValuesDefault($values, $form) {
  339. foreach (element_children($form) as $key) {
  340. if (isset($form[$key]['#default_value'])) {
  341. if (isset($form[$key]['#expected_value'])) {
  342. $expected_value = $form[$key]['#expected_value'];
  343. }
  344. else {
  345. $expected_value = $form[$key]['#default_value'];
  346. }
  347. if ($key == 'checkboxes_multiple') {
  348. // Checkboxes values are not filtered out.
  349. $values[$key] = array_filter($values[$key]);
  350. }
  351. $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))));
  352. }
  353. // Recurse children.
  354. $this->assertFormValuesDefault($values, $form[$key]);
  355. }
  356. }
  357. /**
  358. * Verify markup for disabled form elements.
  359. *
  360. * @see _form_test_disabled_elements()
  361. */
  362. function testDisabledMarkup() {
  363. $this->drupalGet('form-test/disabled-elements');
  364. $form_state = array();
  365. $form = _form_test_disabled_elements(array(), $form_state);
  366. $type_map = array(
  367. 'textarea' => 'textarea',
  368. 'select' => 'select',
  369. 'weight' => 'select',
  370. 'date' => 'select',
  371. );
  372. foreach ($form as $name => $item) {
  373. // Skip special #types.
  374. if (!isset($item['#type']) || in_array($item['#type'], array('hidden', 'text_format'))) {
  375. continue;
  376. }
  377. // Setup XPath and CSS class depending on #type.
  378. if (in_array($item['#type'], array('image_button', 'button', 'submit'))) {
  379. $path = "//!type[contains(@class, :div-class) and @value=:value]";
  380. $class = 'form-button-disabled';
  381. }
  382. else {
  383. // starts-with() required for checkboxes.
  384. $path = "//div[contains(@class, :div-class)]/descendant::!type[starts-with(@name, :name)]";
  385. $class = 'form-disabled';
  386. }
  387. // Replace DOM element name in $path according to #type.
  388. $type = 'input';
  389. if (isset($type_map[$item['#type']])) {
  390. $type = $type_map[$item['#type']];
  391. }
  392. $path = strtr($path, array('!type' => $type));
  393. // Verify that the element exists.
  394. $element = $this->xpath($path, array(
  395. ':name' => check_plain($name),
  396. ':div-class' => $class,
  397. ':value' => isset($item['#value']) ? $item['#value'] : '',
  398. ));
  399. $this->assertTrue(isset($element[0]), format_string('Disabled form element class found for #type %type.', array('%type' => $item['#type'])));
  400. }
  401. // Verify special element #type text-format.
  402. $element = $this->xpath('//div[contains(@class, :div-class)]/descendant::textarea[@name=:name]', array(
  403. ':name' => 'text_format[value]',
  404. ':div-class' => 'form-disabled',
  405. ));
  406. $this->assertTrue(isset($element[0]), format_string('Disabled form element class found for #type %type.', array('%type' => 'text_format[value]')));
  407. $element = $this->xpath('//div[contains(@class, :div-class)]/descendant::select[@name=:name]', array(
  408. ':name' => 'text_format[format]',
  409. ':div-class' => 'form-disabled',
  410. ));
  411. $this->assertTrue(isset($element[0]), format_string('Disabled form element class found for #type %type.', array('%type' => 'text_format[format]')));
  412. }
  413. /**
  414. * Test Form API protections against input forgery.
  415. *
  416. * @see _form_test_input_forgery()
  417. */
  418. function testInputForgery() {
  419. $this->drupalGet('form-test/input-forgery');
  420. $checkbox = $this->xpath('//input[@name="checkboxes[two]"]');
  421. $checkbox[0]['value'] = 'FORGERY';
  422. $this->drupalPost(NULL, array('checkboxes[one]' => TRUE, 'checkboxes[two]' => TRUE), t('Submit'));
  423. $this->assertText('An illegal choice has been detected.', 'Input forgery was detected.');
  424. }
  425. /**
  426. * Tests that submitted values are converted to scalar strings for textfields.
  427. */
  428. public function testTextfieldStringValue() {
  429. // Check multivalued submissions.
  430. $multivalue = array('evil' => 'multivalue', 'not so' => 'good');
  431. $this->checkFormValue('textfield', $multivalue, '');
  432. $this->checkFormValue('password', $multivalue, '');
  433. $this->checkFormValue('textarea', $multivalue, '');
  434. $this->checkFormValue('machine_name', $multivalue, '');
  435. $this->checkFormValue('password_confirm', $multivalue, array('pass1' => '', 'pass2' => ''));
  436. // Check integer submissions.
  437. $integer = 5;
  438. $string = '5';
  439. $this->checkFormValue('textfield', $integer, $string);
  440. $this->checkFormValue('password', $integer, $string);
  441. $this->checkFormValue('textarea', $integer, $string);
  442. $this->checkFormValue('machine_name', $integer, $string);
  443. $this->checkFormValue('password_confirm', array('pass1' => $integer, 'pass2' => $integer), array('pass1' => $string, 'pass2' => $string));
  444. // Check that invalid array keys are ignored for password confirm elements.
  445. $this->checkFormValue('password_confirm', array('pass1' => 'test', 'pass2' => 'test', 'extra' => 'invalid'), array('pass1' => 'test', 'pass2' => 'test'));
  446. }
  447. /**
  448. * Checks that a given form input value is sanitized to the expected result.
  449. *
  450. * @param string $element_type
  451. * The form element type. Example: textfield.
  452. * @param mixed $input_value
  453. * The submitted user input value for the form element.
  454. * @param mixed $expected_value
  455. * The sanitized result value in the form state after calling
  456. * form_builder().
  457. */
  458. protected function checkFormValue($element_type, $input_value, $expected_value) {
  459. $form_id = $this->randomName();
  460. $form = array();
  461. $form_state = form_state_defaults();
  462. $form['op'] = array('#type' => 'submit', '#value' => t('Submit'));
  463. $form[$element_type] = array(
  464. '#type' => $element_type,
  465. '#title' => 'test',
  466. );
  467. $form_state['input'][$element_type] = $input_value;
  468. $form_state['input']['form_id'] = $form_id;
  469. $form_state['method'] = 'post';
  470. $form_state['values'] = array();
  471. drupal_prepare_form($form_id, $form, $form_state);
  472. // This is the main function we want to test: it is responsible for
  473. // populating user supplied $form_state['input'] to sanitized
  474. // $form_state['values'].
  475. form_builder($form_id, $form, $form_state);
  476. $this->assertIdentical($form_state['values'][$element_type], $expected_value, format_string('Form submission for the "@element_type" element type has been correctly sanitized.', array('@element_type' => $element_type)));
  477. }
  478. }
  479. /**
  480. * Tests building and processing of core form elements.
  481. */
  482. class FormElementTestCase extends DrupalWebTestCase {
  483. protected $profile = 'testing';
  484. public static function getInfo() {
  485. return array(
  486. 'name' => 'Element processing',
  487. 'description' => 'Tests building and processing of core form elements.',
  488. 'group' => 'Form API',
  489. );
  490. }
  491. function setUp() {
  492. parent::setUp(array('form_test'));
  493. }
  494. /**
  495. * Tests expansion of #options for #type checkboxes and radios.
  496. */
  497. function testOptions() {
  498. $this->drupalGet('form-test/checkboxes-radios');
  499. // Verify that all options appear in their defined order.
  500. foreach (array('checkbox', 'radio') as $type) {
  501. $elements = $this->xpath('//input[@type=:type]', array(':type' => $type));
  502. $expected_values = array('0', 'foo', '1', 'bar', '>');
  503. foreach ($elements as $element) {
  504. $expected = array_shift($expected_values);
  505. $this->assertIdentical((string) $element['value'], $expected);
  506. }
  507. }
  508. // Enable customized option sub-elements.
  509. $this->drupalGet('form-test/checkboxes-radios/customize');
  510. // Verify that all options appear in their defined order, taking a custom
  511. // #weight into account.
  512. foreach (array('checkbox', 'radio') as $type) {
  513. $elements = $this->xpath('//input[@type=:type]', array(':type' => $type));
  514. $expected_values = array('0', 'foo', 'bar', '>', '1');
  515. foreach ($elements as $element) {
  516. $expected = array_shift($expected_values);
  517. $this->assertIdentical((string) $element['value'], $expected);
  518. }
  519. }
  520. // Verify that custom #description properties are output.
  521. foreach (array('checkboxes', 'radios') as $type) {
  522. $elements = $this->xpath('//input[@id=:id]/following-sibling::div[@class=:class]', array(
  523. ':id' => 'edit-' . $type . '-foo',
  524. ':class' => 'description',
  525. ));
  526. $this->assertTrue(count($elements), format_string('Custom %type option description found.', array(
  527. '%type' => $type,
  528. )));
  529. }
  530. }
  531. }
  532. /**
  533. * Test form alter hooks.
  534. */
  535. class FormAlterTestCase extends DrupalWebTestCase {
  536. public static function getInfo() {
  537. return array(
  538. 'name' => 'Form alter hooks',
  539. 'description' => 'Tests hook_form_alter() and hook_form_FORM_ID_alter().',
  540. 'group' => 'Form API',
  541. );
  542. }
  543. function setUp() {
  544. parent::setUp('form_test');
  545. }
  546. /**
  547. * Tests execution order of hook_form_alter() and hook_form_FORM_ID_alter().
  548. */
  549. function testExecutionOrder() {
  550. $this->drupalGet('form-test/alter');
  551. // Ensure that the order is first by module, then for a given module, the
  552. // id-specific one after the generic one.
  553. $expected = array(
  554. 'block_form_form_test_alter_form_alter() executed.',
  555. 'form_test_form_alter() executed.',
  556. 'form_test_form_form_test_alter_form_alter() executed.',
  557. 'system_form_form_test_alter_form_alter() executed.',
  558. );
  559. $content = preg_replace('/\s+/', ' ', filter_xss($this->content, array()));
  560. $this->assert(strpos($content, implode(' ', $expected)) !== FALSE, 'Form alter hooks executed in the expected order.');
  561. }
  562. }
  563. /**
  564. * Test form validation handlers.
  565. */
  566. class FormValidationTestCase extends DrupalWebTestCase {
  567. public static function getInfo() {
  568. return array(
  569. 'name' => 'Form validation handlers',
  570. 'description' => 'Tests form processing and alteration via form validation handlers.',
  571. 'group' => 'Form API',
  572. );
  573. }
  574. function setUp() {
  575. parent::setUp('form_test');
  576. }
  577. /**
  578. * Tests form alterations by #element_validate, #validate, and form_set_value().
  579. */
  580. function testValidate() {
  581. $this->drupalGet('form-test/validate');
  582. // Verify that #element_validate handlers can alter the form and submitted
  583. // form values.
  584. $edit = array(
  585. 'name' => 'element_validate',
  586. );
  587. $this->drupalPost(NULL, $edit, 'Save');
  588. $this->assertFieldByName('name', '#value changed by #element_validate', 'Form element #value was altered.');
  589. $this->assertText('Name value: value changed by form_set_value() in #element_validate', 'Form element value in $form_state was altered.');
  590. // Verify that #validate handlers can alter the form and submitted
  591. // form values.
  592. $edit = array(
  593. 'name' => 'validate',
  594. );
  595. $this->drupalPost(NULL, $edit, 'Save');
  596. $this->assertFieldByName('name', '#value changed by #validate', 'Form element #value was altered.');
  597. $this->assertText('Name value: value changed by form_set_value() in #validate', 'Form element value in $form_state was altered.');
  598. // Verify that #element_validate handlers can make form elements
  599. // inaccessible, but values persist.
  600. $edit = array(
  601. 'name' => 'element_validate_access',
  602. );
  603. $this->drupalPost(NULL, $edit, 'Save');
  604. $this->assertNoFieldByName('name', 'Form element was hidden.');
  605. $this->assertText('Name value: element_validate_access', 'Value for inaccessible form element exists.');
  606. // Verify that value for inaccessible form element persists.
  607. $this->drupalPost(NULL, array(), 'Save');
  608. $this->assertNoFieldByName('name', 'Form element was hidden.');
  609. $this->assertText('Name value: element_validate_access', 'Value for inaccessible form element exists.');
  610. // Verify that #validate handlers don't run if the CSRF token is invalid.
  611. $this->drupalLogin($this->drupalCreateUser());
  612. $this->drupalGet('form-test/validate');
  613. $edit = array(
  614. 'name' => 'validate',
  615. 'form_token' => 'invalid token'
  616. );
  617. $this->drupalPost(NULL, $edit, 'Save');
  618. $this->assertNoFieldByName('name', '#value changed by #validate', 'Form element #value was not altered.');
  619. $this->assertNoText('Name value: value changed by form_set_value() in #validate', 'Form element value in $form_state was not altered.');
  620. $this->assertText('The form has become outdated. Copy any unsaved work in the form below');
  621. }
  622. /**
  623. * Tests partial form validation through #limit_validation_errors.
  624. */
  625. function testValidateLimitErrors() {
  626. $edit = array(
  627. 'test' => 'invalid',
  628. 'test_numeric_index[0]' => 'invalid',
  629. 'test_substring[foo]' => 'invalid',
  630. );
  631. $path = 'form-test/limit-validation-errors';
  632. // Submit the form by pressing the 'Partial validate' button (uses
  633. // #limit_validation_errors) and ensure that the title field is not
  634. // validated, but the #element_validate handler for the 'test' field
  635. // is triggered.
  636. $this->drupalPost($path, $edit, t('Partial validate'));
  637. $this->assertNoText(t('!name field is required.', array('!name' => 'Title')));
  638. $this->assertText('Test element is invalid');
  639. // Edge case of #limit_validation_errors containing numeric indexes: same
  640. // thing with the 'Partial validate (numeric index)' button and the
  641. // 'test_numeric_index' field.
  642. $this->drupalPost($path, $edit, t('Partial validate (numeric index)'));
  643. $this->assertNoText(t('!name field is required.', array('!name' => 'Title')));
  644. $this->assertText('Test (numeric index) element is invalid');
  645. // Ensure something like 'foobar' isn't considered "inside" 'foo'.
  646. $this->drupalPost($path, $edit, t('Partial validate (substring)'));
  647. $this->assertNoText(t('!name field is required.', array('!name' => 'Title')));
  648. $this->assertText('Test (substring) foo element is invalid');
  649. // Ensure not validated values are not available to submit handlers.
  650. $this->drupalPost($path, array('title' => '', 'test' => 'valid'), t('Partial validate'));
  651. $this->assertText('Only validated values appear in the form values.');
  652. // Now test full form validation and ensure that the #element_validate
  653. // handler is still triggered.
  654. $this->drupalPost($path, $edit, t('Full validate'));
  655. $this->assertText(t('!name field is required.', array('!name' => 'Title')));
  656. $this->assertText('Test element is invalid');
  657. }
  658. /**
  659. * Tests error border of multiple fields with same name in a page.
  660. */
  661. function testMultiFormSameNameErrorClass() {
  662. $this->drupalGet('form-test/double-form');
  663. $edit = array();
  664. $this->drupalPost(NULL, $edit, t('Save'));
  665. $this->assertFieldByXpath('//input[@id="edit-name" and contains(@class, "error")]', NULL, 'Error input form element class found for first element.');
  666. $this->assertNoFieldByXpath('//input[@id="edit-name--2" and contains(@class, "error")]', NULL, 'No error input form element class found for second element.');
  667. }
  668. }
  669. /**
  670. * Test form element labels, required markers and associated output.
  671. */
  672. class FormsElementsLabelsTestCase extends DrupalWebTestCase {
  673. public static function getInfo() {
  674. return array(
  675. 'name' => 'Form element and label output test',
  676. 'description' => 'Test form element labels, required markers and associated output.',
  677. 'group' => 'Form API',
  678. );
  679. }
  680. function setUp() {
  681. parent::setUp('form_test');
  682. }
  683. /**
  684. * Test form elements, labels, title attibutes and required marks output
  685. * correctly and have the correct label option class if needed.
  686. */
  687. function testFormLabels() {
  688. $this->drupalGet('form_test/form-labels');
  689. // Check that the checkbox/radio processing is not interfering with
  690. // basic placement.
  691. $elements = $this->xpath('//input[@id="edit-form-checkboxes-test-third-checkbox"]/following-sibling::label[@for="edit-form-checkboxes-test-third-checkbox" and @class="option"]');
  692. $this->assertTrue(isset($elements[0]), "Label follows field and label option class correct for regular checkboxes.");
  693. // Make sure the label is rendered for checkboxes.
  694. $elements = $this->xpath('//input[@id="edit-form-checkboxes-test-0"]/following-sibling::label[@for="edit-form-checkboxes-test-0" and @class="option"]');
  695. $this->assertTrue(isset($elements[0]), "Label 0 found checkbox.");
  696. $elements = $this->xpath('//input[@id="edit-form-radios-test-second-radio"]/following-sibling::label[@for="edit-form-radios-test-second-radio" and @class="option"]');
  697. $this->assertTrue(isset($elements[0]), "Label follows field and label option class correct for regular radios.");
  698. // Make sure the label is rendered for radios.
  699. $elements = $this->xpath('//input[@id="edit-form-radios-test-0"]/following-sibling::label[@for="edit-form-radios-test-0" and @class="option"]');
  700. $this->assertTrue(isset($elements[0]), "Label 0 found radios.");
  701. // Exercise various defaults for checkboxes and modifications to ensure
  702. // appropriate override and correct behavior.
  703. $elements = $this->xpath('//input[@id="edit-form-checkbox-test"]/following-sibling::label[@for="edit-form-checkbox-test" and @class="option"]');
  704. $this->assertTrue(isset($elements[0]), "Label follows field and label option class correct for a checkbox by default.");
  705. // Exercise various defaults for textboxes and modifications to ensure
  706. // appropriate override and correct behavior.
  707. $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"]');
  708. $this->assertTrue(isset($elements[0]), "Label precedes textfield, with required marker inside label.");
  709. $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"]');
  710. $this->assertTrue(isset($elements[0]), "Label tag with required marker precedes required textfield with no title.");
  711. $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"]');
  712. $this->assertTrue(isset($elements[0]), "Label preceding field and label class is element-invisible.");
  713. $elements = $this->xpath('//input[@id="edit-form-textfield-test-title"]/preceding-sibling::span[@class="form-required"]');
  714. $this->assertFalse(isset($elements[0]), "No required marker on non-required field.");
  715. $elements = $this->xpath('//input[@id="edit-form-textfield-test-title-after"]/following-sibling::label[@for="edit-form-textfield-test-title-after" and @class="option"]');
  716. $this->assertTrue(isset($elements[0]), "Label after field and label option class correct for text field.");
  717. $elements = $this->xpath('//label[@for="edit-form-textfield-test-title-no-show"]');
  718. $this->assertFalse(isset($elements[0]), "No label tag when title set not to display.");
  719. // Check #field_prefix and #field_suffix placement.
  720. $elements = $this->xpath('//span[@class="field-prefix"]/following-sibling::div[@id="edit-form-radios-test"]');
  721. $this->assertTrue(isset($elements[0]), "Properly placed the #field_prefix element after the label and before the field.");
  722. $elements = $this->xpath('//span[@class="field-suffix"]/preceding-sibling::div[@id="edit-form-radios-test"]');
  723. $this->assertTrue(isset($elements[0]), "Properly places the #field_suffix element immediately after the form field.");
  724. // Check #prefix and #suffix placement.
  725. $elements = $this->xpath('//div[@id="form-test-textfield-title-prefix"]/following-sibling::div[contains(@class, \'form-item-form-textfield-test-title\')]');
  726. $this->assertTrue(isset($elements[0]), "Properly places the #prefix element before the form item.");
  727. $elements = $this->xpath('//div[@id="form-test-textfield-title-suffix"]/preceding-sibling::div[contains(@class, \'form-item-form-textfield-test-title\')]');
  728. $this->assertTrue(isset($elements[0]), "Properly places the #suffix element before the form item.");
  729. // Check title attribute for radios and checkboxes.
  730. $elements = $this->xpath('//div[@id="edit-form-checkboxes-title-attribute"]');
  731. $this->assertEqual($elements[0]['title'], 'Checkboxes test' . ' (' . t('Required') . ')', 'Title attribute found.');
  732. $elements = $this->xpath('//div[@id="edit-form-radios-title-attribute"]');
  733. $this->assertEqual($elements[0]['title'], 'Radios test' . ' (' . t('Required') . ')', 'Title attribute found.');
  734. }
  735. }
  736. /**
  737. * Test the tableselect form element for expected behavior.
  738. */
  739. class FormsElementsTableSelectFunctionalTest extends DrupalWebTestCase {
  740. public static function getInfo() {
  741. return array(
  742. 'name' => 'Tableselect form element type test',
  743. 'description' => 'Test the tableselect element for expected behavior',
  744. 'group' => 'Form API',
  745. );
  746. }
  747. function setUp() {
  748. parent::setUp('form_test');
  749. }
  750. /**
  751. * Test the display of checkboxes when #multiple is TRUE.
  752. */
  753. function testMultipleTrue() {
  754. $this->drupalGet('form_test/tableselect/multiple-true');
  755. $this->assertNoText(t('Empty text.'), 'Empty text should not be displayed.');
  756. // Test for the presence of the Select all rows tableheader.
  757. $this->assertFieldByXPath('//th[@class="select-all"]', NULL, 'Presence of the "Select all" checkbox.');
  758. $rows = array('row1', 'row2', 'row3');
  759. foreach ($rows as $row) {
  760. $this->assertFieldByXPath('//input[@type="checkbox"]', $row, format_string('Checkbox for value @row.', array('@row' => $row)));
  761. }
  762. }
  763. /**
  764. * Test the display of radios when #multiple is FALSE.
  765. */
  766. function testMultipleFalse() {
  767. $this->drupalGet('form_test/tableselect/multiple-false');
  768. $this->assertNoText(t('Empty text.'), 'Empty text should not be displayed.');
  769. // Test for the absence of the Select all rows tableheader.
  770. $this->assertNoFieldByXPath('//th[@class="select-all"]', '', 'Absence of the "Select all" checkbox.');
  771. $rows = array('row1', 'row2', 'row3');
  772. foreach ($rows as $row) {
  773. $this->assertFieldByXPath('//input[@type="radio"]', $row, format_string('Radio button for value @row.', array('@row' => $row)));
  774. }
  775. }
  776. /**
  777. * Test the display of the #empty text when #options is an empty array.
  778. */
  779. function testEmptyText() {
  780. $this->drupalGet('form_test/tableselect/empty-text');
  781. $this->assertText(t('Empty text.'), 'Empty text should be displayed.');
  782. }
  783. /**
  784. * Test the submission of single and multiple values when #multiple is TRUE.
  785. */
  786. function testMultipleTrueSubmit() {
  787. // Test a submission with one checkbox checked.
  788. $edit = array();
  789. $edit['tableselect[row1]'] = TRUE;
  790. $this->drupalPost('form_test/tableselect/multiple-true', $edit, 'Submit');
  791. $this->assertText(t('Submitted: row1 = row1'), 'Checked checkbox row1');
  792. $this->assertText(t('Submitted: row2 = 0'), 'Unchecked checkbox row2.');
  793. $this->assertText(t('Submitted: row3 = 0'), 'Unchecked checkbox row3.');
  794. // Test a submission with multiple checkboxes checked.
  795. $edit['tableselect[row1]'] = TRUE;
  796. $edit['tableselect[row3]'] = TRUE;
  797. $this->drupalPost('form_test/tableselect/multiple-true', $edit, 'Submit');
  798. $this->assertText(t('Submitted: row1 = row1'), 'Checked checkbox row1.');
  799. $this->assertText(t('Submitted: row2 = 0'), 'Unchecked checkbox row2.');
  800. $this->assertText(t('Submitted: row3 = row3'), 'Checked checkbox row3.');
  801. }
  802. /**
  803. * Test submission of values when #multiple is FALSE.
  804. */
  805. function testMultipleFalseSubmit() {
  806. $edit['tableselect'] = 'row1';
  807. $this->drupalPost('form_test/tableselect/multiple-false', $edit, 'Submit');
  808. $this->assertText(t('Submitted: row1'), 'Selected radio button');
  809. }
  810. /**
  811. * Test the #js_select property.
  812. */
  813. function testAdvancedSelect() {
  814. // When #multiple = TRUE a Select all checkbox should be displayed by default.
  815. $this->drupalGet('form_test/tableselect/advanced-select/multiple-true-default');
  816. $this->assertFieldByXPath('//th[@class="select-all"]', NULL, 'Display a "Select all" checkbox by default when #multiple is TRUE.');
  817. // When #js_select is set to FALSE, a "Select all" checkbox should not be displayed.
  818. $this->drupalGet('form_test/tableselect/advanced-select/multiple-true-no-advanced-select');
  819. $this->assertNoFieldByXPath('//th[@class="select-all"]', NULL, 'Do not display a "Select all" checkbox when #js_select is FALSE.');
  820. // A "Select all" checkbox never makes sense when #multiple = FALSE, regardless of the value of #js_select.
  821. $this->drupalGet('form_test/tableselect/advanced-select/multiple-false-default');
  822. $this->assertNoFieldByXPath('//th[@class="select-all"]', NULL, 'Do not display a "Select all" checkbox when #multiple is FALSE.');
  823. $this->drupalGet('form_test/tableselect/advanced-select/multiple-false-advanced-select');
  824. $this->assertNoFieldByXPath('//th[@class="select-all"]', NULL, 'Do not display a "Select all" checkbox when #multiple is FALSE, even when #js_select is TRUE.');
  825. }
  826. /**
  827. * Test the whether the option checker gives an error on invalid tableselect values for checkboxes.
  828. */
  829. function testMultipleTrueOptionchecker() {
  830. list($header, $options) = _form_test_tableselect_get_data();
  831. $form['tableselect'] = array(
  832. '#type' => 'tableselect',
  833. '#header' => $header,
  834. '#options' => $options,
  835. );
  836. // Test with a valid value.
  837. list($processed_form, $form_state, $errors) = $this->formSubmitHelper($form, array('tableselect' => array('row1' => 'row1')));
  838. $this->assertFalse(isset($errors['tableselect']), 'Option checker allows valid values for checkboxes.');
  839. // Test with an invalid value.
  840. list($processed_form, $form_state, $errors) = $this->formSubmitHelper($form, array('tableselect' => array('non_existing_value' => 'non_existing_value')));
  841. $this->assertTrue(isset($errors['tableselect']), 'Option checker disallows invalid values for checkboxes.');
  842. }
  843. /**
  844. * Test the whether the option checker gives an error on invalid tableselect values for radios.
  845. */
  846. function testMultipleFalseOptionchecker() {
  847. list($header, $options) = _form_test_tableselect_get_data();
  848. $form['tableselect'] = array(
  849. '#type' => 'tableselect',
  850. '#header' => $header,
  851. '#options' => $options,
  852. '#multiple' => FALSE,
  853. );
  854. // Test with a valid value.
  855. list($processed_form, $form_state, $errors) = $this->formSubmitHelper($form, array('tableselect' => 'row1'));
  856. $this->assertFalse(isset($errors['tableselect']), 'Option checker allows valid values for radio buttons.');
  857. // Test with an invalid value.
  858. list($processed_form, $form_state, $errors) = $this->formSubmitHelper($form, array('tableselect' => 'non_existing_value'));
  859. $this->assertTrue(isset($errors['tableselect']), 'Option checker disallows invalid values for radio buttons.');
  860. }
  861. /**
  862. * Helper function for the option check test to submit a form while collecting errors.
  863. *
  864. * @param $form_element
  865. * A form element to test.
  866. * @param $edit
  867. * An array containing post data.
  868. *
  869. * @return
  870. * An array containing the processed form, the form_state and any errors.
  871. */
  872. private function formSubmitHelper($form, $edit) {
  873. $form_id = $this->randomName();
  874. $form_state = form_state_defaults();
  875. $form['op'] = array('#type' => 'submit', '#value' => t('Submit'));
  876. $form_state['input'] = $edit;
  877. $form_state['input']['form_id'] = $form_id;
  878. // The form token CSRF protection should not interfere with this test,
  879. // so we bypass it by marking this test form as programmed.
  880. $form_state['programmed'] = TRUE;
  881. drupal_prepare_form($form_id, $form, $form_state);
  882. drupal_process_form($form_id, $form, $form_state);
  883. $errors = form_get_errors();
  884. // Clear errors and messages.
  885. drupal_get_messages();
  886. form_clear_error();
  887. // Return the processed form together with form_state and errors
  888. // to allow the caller lowlevel access to the form.
  889. return array($form, $form_state, $errors);
  890. }
  891. }
  892. /**
  893. * Test the vertical_tabs form element for expected behavior.
  894. */
  895. class FormsElementsVerticalTabsFunctionalTest extends DrupalWebTestCase {
  896. public static function getInfo() {
  897. return array(
  898. 'name' => 'Vertical tabs form element type test',
  899. 'description' => 'Test the vertical_tabs element for expected behavior',
  900. 'group' => 'Form API',
  901. );
  902. }
  903. function setUp() {
  904. parent::setUp('form_test');
  905. }
  906. /**
  907. * Ensures that vertical-tabs.js is included before collapse.js.
  908. *
  909. * Otherwise, collapse.js adds "SHOW" or "HIDE" labels to the tabs.
  910. */
  911. function testJavaScriptOrdering() {
  912. $this->drupalGet('form_test/vertical-tabs');
  913. $position1 = strpos($this->content, 'misc/vertical-tabs.js');
  914. $position2 = strpos($this->content, 'misc/collapse.js');
  915. $this->assertTrue($position1 !== FALSE && $position2 !== FALSE && $position1 < $position2, 'vertical-tabs.js is included before collapse.js');
  916. }
  917. }
  918. /**
  919. * Test the form storage on a multistep form.
  920. *
  921. * The tested form puts data into the storage during the initial form
  922. * construction. These tests verify that there are no duplicate form
  923. * constructions, with and without manual form caching activiated. Furthermore
  924. * when a validation error occurs, it makes sure that changed form element
  925. * values aren't lost due to a wrong form rebuild.
  926. */
  927. class FormsFormStorageTestCase extends DrupalWebTestCase {
  928. public static function getInfo() {
  929. return array(
  930. 'name' => 'Multistep form using form storage',
  931. 'description' => 'Tests a multistep form using form storage and makes sure validation and caching works right.',
  932. 'group' => 'Form API',
  933. );
  934. }
  935. function setUp() {
  936. parent::setUp('form_test');
  937. $this->web_user = $this->drupalCreateUser(array('access content'));
  938. $this->drupalLogin($this->web_user);
  939. }
  940. /**
  941. * Tests using the form in a usual way.
  942. */
  943. function testForm() {
  944. $this->drupalGet('form_test/form-storage');
  945. $this->assertText('Form constructions: 1');
  946. $edit = array('title' => 'new', 'value' => 'value_is_set');
  947. // Use form rebuilding triggered by a submit button.
  948. $this->drupalPost(NULL, $edit, 'Continue submit');
  949. $this->assertText('Form constructions: 2');
  950. $this->assertText('Form constructions: 3');
  951. // Reset the form to the values of the storage, using a form rebuild
  952. // triggered by button of type button.
  953. $this->drupalPost(NULL, array('title' => 'changed'), 'Reset');
  954. $this->assertFieldByName('title', 'new', 'Values have been resetted.');
  955. // After rebuilding, the form has been cached.
  956. $this->assertText('Form constructions: 4');
  957. $this->drupalPost(NULL, $edit, 'Save');
  958. $this->assertText('Form constructions: 4');
  959. $this->assertText('Title: new', 'The form storage has stored the values.');
  960. }
  961. /**
  962. * Tests using the form with an activated $form_state['cache'] property.
  963. */
  964. function testFormCached() {
  965. $this->drupalGet('form_test/form-storage', array('query' => array('cache' => 1)));
  966. $this->assertText('Form constructions: 1');
  967. $edit = array('title' => 'new', 'value' => 'value_is_set');
  968. // Use form rebuilding triggered by a submit button.
  969. $this->drupalPost(NULL, $edit, 'Continue submit');
  970. $this->assertText('Form constructions: 2');
  971. // Reset the form to the values of the storage, using a form rebuild
  972. // triggered by button of type button.
  973. $this->drupalPost(NULL, array('title' => 'changed'), 'Reset');
  974. $this->assertFieldByName('title', 'new', 'Values have been resetted.');
  975. $this->assertText('Form constructions: 3');
  976. $this->drupalPost(NULL, $edit, 'Save');
  977. $this->assertText('Form constructions: 3');
  978. $this->assertText('Title: new', 'The form storage has stored the values.');
  979. }
  980. /**
  981. * Tests validation when form storage is used.
  982. */
  983. function testValidation() {
  984. $this->drupalPost('form_test/form-storage', array('title' => '', 'value' => 'value_is_set'), 'Continue submit');
  985. $this->assertPattern('/value_is_set/', 'The input values have been kept.');
  986. }
  987. /**
  988. * Tests updating cached form storage during form validation.
  989. *
  990. * If form caching is enabled and a form stores data in the form storage, then
  991. * the form storage also has to be updated in case of a validation error in
  992. * the form. This test re-uses the existing form for multi-step tests, but
  993. * triggers a special #element_validate handler to update the form storage
  994. * during form validation, while another, required element in the form
  995. * triggers a form validation error.
  996. */
  997. function testCachedFormStorageValidation() {
  998. // Request the form with 'cache' query parameter to enable form caching.
  999. $this->drupalGet('form_test/form-storage', array('query' => array('cache' => 1)));
  1000. // Skip step 1 of the multi-step form, since the first step copies over
  1001. // 'title' into form storage, but we want to verify that changes in the form
  1002. // storage are updated in the cache during form validation.
  1003. $edit = array('title' => 'foo');
  1004. $this->drupalPost(NULL, $edit, 'Continue submit');
  1005. // In step 2, trigger a validation error for the required 'title' field, and
  1006. // post the special 'change_title' value for the 'value' field, which
  1007. // conditionally invokes the #element_validate handler to update the form
  1008. // storage.
  1009. $edit = array('title' => '', 'value' => 'change_title');
  1010. $this->drupalPost(NULL, $edit, 'Save');
  1011. // At this point, the form storage should contain updated values, but we do
  1012. // not see them, because the form has not been rebuilt yet due to the
  1013. // validation error. Post again and verify that the rebuilt form contains
  1014. // the values of the updated form storage.
  1015. $this->drupalPost(NULL, array('title' => 'foo', 'value' => 'bar'), 'Save');
  1016. $this->assertText("The thing has been changed.", 'The altered form storage value was updated in cache and taken over.');
  1017. }
  1018. /**
  1019. * Tests a form using form state without using 'storage' to pass data from the
  1020. * constructor to a submit handler. The data has to persist even when caching
  1021. * gets activated, what may happen when a modules alter the form and adds
  1022. * #ajax properties.
  1023. */
  1024. function testFormStatePersist() {
  1025. // Test the form one time with caching activated and one time without.
  1026. $run_options = array(
  1027. array(),
  1028. array('query' => array('cache' => 1)),
  1029. );
  1030. foreach ($run_options as $options) {
  1031. $this->drupalPost('form-test/state-persist', array(), t('Submit'), $options);
  1032. // The submit handler outputs the value in $form_state, assert it's there.
  1033. $this->assertText('State persisted.');
  1034. // Test it again, but first trigger a validation error, then test.
  1035. $this->drupalPost('form-test/state-persist', array('title' => ''), t('Submit'), $options);
  1036. $this->assertText(t('!name field is required.', array('!name' => 'title')));
  1037. // Submit the form again triggering no validation error.
  1038. $this->drupalPost(NULL, array('title' => 'foo'), t('Submit'), $options);
  1039. $this->assertText('State persisted.');
  1040. // Now post to the rebuilt form and verify it's still there afterwards.
  1041. $this->drupalPost(NULL, array('title' => 'bar'), t('Submit'), $options);
  1042. $this->assertText('State persisted.');
  1043. }
  1044. }
  1045. /**
  1046. * Verify that the form build-id remains the same when validation errors
  1047. * occur on a mutable form.
  1048. */
  1049. function testMutableForm() {
  1050. // Request the form with 'cache' query parameter to enable form caching.
  1051. $this->drupalGet('form_test/form-storage', array('query' => array('cache' => 1)));
  1052. $buildIdFields = $this->xpath('//input[@name="form_build_id"]');
  1053. $this->assertEqual(count($buildIdFields), 1, 'One form build id field on the page');
  1054. $buildId = (string) $buildIdFields[0]['value'];
  1055. // Trigger validation error by submitting an empty title.
  1056. $edit = array('title' => '');
  1057. $this->drupalPost(NULL, $edit, 'Continue submit');
  1058. // Verify that the build-id did not change.
  1059. $this->assertFieldByName('form_build_id', $buildId, 'Build id remains the same when form validation fails');
  1060. }
  1061. /**
  1062. * Verifies that form build-id is regenerated when loading an immutable form
  1063. * from the cache.
  1064. */
  1065. function testImmutableForm() {
  1066. // Request the form with 'cache' query parameter to enable form caching.
  1067. $this->drupalGet('form_test/form-storage', array('query' => array('cache' => 1, 'immutable' => 1)));
  1068. $buildIdFields = $this->xpath('//input[@name="form_build_id"]');
  1069. $this->assertEqual(count($buildIdFields), 1, 'One form build id field on the page');
  1070. $buildId = (string) $buildIdFields[0]['value'];
  1071. // Trigger validation error by submitting an empty title.
  1072. $edit = array('title' => '');
  1073. $this->drupalPost(NULL, $edit, 'Continue submit');
  1074. // Verify that the build-id did change.
  1075. $this->assertNoFieldByName('form_build_id', $buildId, 'Build id changes when form validation fails');
  1076. // Retrieve the new build-id.
  1077. $buildIdFields = $this->xpath('//input[@name="form_build_id"]');
  1078. $this->assertEqual(count($buildIdFields), 1, 'One form build id field on the page');
  1079. $buildId = (string) $buildIdFields[0]['value'];
  1080. // Trigger validation error by again submitting an empty title.
  1081. $edit = array('title' => '');
  1082. $this->drupalPost(NULL, $edit, 'Continue submit');
  1083. // Verify that the build-id does not change the second time.
  1084. $this->assertFieldByName('form_build_id', $buildId, 'Build id remains the same when form validation fails subsequently');
  1085. }
  1086. /**
  1087. * Verify that existing contrib code cannot overwrite immutable form state.
  1088. */
  1089. public function testImmutableFormLegacyProtection() {
  1090. $this->drupalGet('form_test/form-storage', array('query' => array('cache' => 1, 'immutable' => 1)));
  1091. $build_id_fields = $this->xpath('//input[@name="form_build_id"]');
  1092. $this->assertEqual(count($build_id_fields), 1, 'One form build id field on the page');
  1093. $build_id = (string) $build_id_fields[0]['value'];
  1094. // Try to poison the form cache.
  1095. $original = $this->drupalGetAJAX('form_test/form-storage-legacy/' . $build_id);
  1096. $this->assertEqual($original['form']['#build_id_old'], $build_id, 'Original build_id was recorded');
  1097. $this->assertNotEqual($original['form']['#build_id'], $build_id, 'New build_id was generated');
  1098. // Assert that a watchdog message was logged by form_set_cache.
  1099. $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.'));
  1100. $this->assert($status, 'A watchdog message was logged by form_set_cache');
  1101. // Ensure that the form state was not poisoned by the preceeding call.
  1102. $original = $this->drupalGetAJAX('form_test/form-storage-legacy/' . $build_id);
  1103. $this->assertEqual($original['form']['#build_id_old'], $build_id, 'Original build_id was recorded');
  1104. $this->assertNotEqual($original['form']['#build_id'], $build_id, 'New build_id was generated');
  1105. $this->assert(empty($original['form']['#poisoned']), 'Original form structure was preserved');
  1106. $this->assert(empty($original['form_state']['poisoned']), 'Original form state was preserved');
  1107. }
  1108. }
  1109. /**
  1110. * Test the form storage when page caching for anonymous users is turned on.
  1111. */
  1112. class FormsFormStoragePageCacheTestCase extends DrupalWebTestCase {
  1113. protected $profile = 'testing';
  1114. public static function getInfo() {
  1115. return array(
  1116. 'name' => 'Forms using form storage on cached pages',
  1117. 'description' => 'Tests a form using form storage and makes sure validation and caching works when page caching for anonymous users is turned on.',
  1118. 'group' => 'Form API',
  1119. );
  1120. }
  1121. public function setUp() {
  1122. parent::setUp('form_test');
  1123. variable_set('cache', TRUE);
  1124. }
  1125. /**
  1126. * Return the build id of the current form.
  1127. */
  1128. protected function getFormBuildId() {
  1129. $build_id_fields = $this->xpath('//input[@name="form_build_id"]');
  1130. $this->assertEqual(count($build_id_fields), 1, 'One form build id field on the page');
  1131. return (string) $build_id_fields[0]['value'];
  1132. }
  1133. /**
  1134. * Build-id is regenerated when validating cached form.
  1135. */
  1136. public function testValidateFormStorageOnCachedPage() {
  1137. $this->drupalGet('form_test/form-storage-page-cache');
  1138. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Page was not cached.');
  1139. $this->assertText('No old build id', 'No old build id on the page');
  1140. $build_id_initial = $this->getFormBuildId();
  1141. // Trigger validation error by submitting an empty title.
  1142. $edit = array('title' => '');
  1143. $this->drupalPost(NULL, $edit, 'Save');
  1144. $this->assertText($build_id_initial, 'Old build id on the page');
  1145. $build_id_first_validation = $this->getFormBuildId();
  1146. $this->assertNotEqual($build_id_initial, $build_id_first_validation, 'Build id changes when form validation fails');
  1147. // Trigger validation error by again submitting an empty title.
  1148. $edit = array('title' => '');
  1149. $this->drupalPost(NULL, $edit, 'Save');
  1150. $this->assertText('No old build id', 'No old build id on the page');
  1151. $build_id_second_validation = $this->getFormBuildId();
  1152. $this->assertEqual($build_id_first_validation, $build_id_second_validation, 'Build id remains the same when form validation fails subsequently');
  1153. // Repeat the test sequence but this time with a page loaded from the cache.
  1154. $this->drupalGet('form_test/form-storage-page-cache');
  1155. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
  1156. $this->assertText('No old build id', 'No old build id on the page');
  1157. $build_id_from_cache_initial = $this->getFormBuildId();
  1158. $this->assertEqual($build_id_initial, $build_id_from_cache_initial, 'Build id is the same as on the first request');
  1159. // Trigger validation error by submitting an empty title.
  1160. $edit = array('title' => '');
  1161. $this->drupalPost(NULL, $edit, 'Save');
  1162. $this->assertText($build_id_initial, 'Old build id is initial build id');
  1163. $build_id_from_cache_first_validation = $this->getFormBuildId();
  1164. $this->assertNotEqual($build_id_initial, $build_id_from_cache_first_validation, 'Build id changes when form validation fails');
  1165. $this->assertNotEqual($build_id_first_validation, $build_id_from_cache_first_validation, 'Build id from first user is not reused');
  1166. // Trigger validation error by again submitting an empty title.
  1167. $edit = array('title' => '');
  1168. $this->drupalPost(NULL, $edit, 'Save');
  1169. $this->assertText('No old build id', 'No old build id on the page');
  1170. $build_id_from_cache_second_validation = $this->getFormBuildId();
  1171. $this->assertEqual($build_id_from_cache_first_validation, $build_id_from_cache_second_validation, 'Build id remains the same when form validation fails subsequently');
  1172. }
  1173. /**
  1174. * Build-id is regenerated when rebuilding cached form.
  1175. */
  1176. public function testRebuildFormStorageOnCachedPage() {
  1177. $this->drupalGet('form_test/form-storage-page-cache');
  1178. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Page was not cached.');
  1179. $this->assertText('No old build id', 'No old build id on the page');
  1180. $build_id_initial = $this->getFormBuildId();
  1181. // Trigger rebuild, should regenerate build id.
  1182. $edit = array('title' => 'something');
  1183. $this->drupalPost(NULL, $edit, 'Rebuild');
  1184. $this->assertText($build_id_initial, 'Initial build id as old build id on the page');
  1185. $build_id_first_rebuild = $this->getFormBuildId();
  1186. $this->assertNotEqual($build_id_initial, $build_id_first_rebuild, 'Build id changes on first rebuild.');
  1187. // Trigger subsequent rebuild, should regenerate the build id again.
  1188. $edit = array('title' => 'something');
  1189. $this->drupalPost(NULL, $edit, 'Rebuild');
  1190. $this->assertText($build_id_first_rebuild, 'First build id as old build id on the page');
  1191. $build_id_second_rebuild = $this->getFormBuildId();
  1192. $this->assertNotEqual($build_id_first_rebuild, $build_id_second_rebuild, 'Build id changes on second rebuild.');
  1193. }
  1194. }
  1195. /**
  1196. * Test wrapper form callbacks.
  1197. */
  1198. class FormsFormWrapperTestCase extends DrupalWebTestCase {
  1199. public static function getInfo() {
  1200. return array(
  1201. 'name' => 'Form wrapper callback',
  1202. 'description' => 'Tests form wrapper callbacks to pass a prebuilt form to form builder functions.',
  1203. 'group' => 'Form API',
  1204. );
  1205. }
  1206. function setUp() {
  1207. parent::setUp('form_test');
  1208. }
  1209. /**
  1210. * Tests using the form in a usual way.
  1211. */
  1212. function testWrapperCallback() {
  1213. $this->drupalGet('form_test/wrapper-callback');
  1214. $this->assertText('Form wrapper callback element output.', 'The form contains form wrapper elements.');
  1215. $this->assertText('Form builder element output.', 'The form contains form builder elements.');
  1216. }
  1217. }
  1218. /**
  1219. * Test $form_state clearance.
  1220. */
  1221. class FormStateValuesCleanTestCase extends DrupalWebTestCase {
  1222. public static function getInfo() {
  1223. return array(
  1224. 'name' => 'Form state values clearance',
  1225. 'description' => 'Test proper removal of submitted form values using form_state_values_clean().',
  1226. 'group' => 'Form API',
  1227. );
  1228. }
  1229. function setUp() {
  1230. parent::setUp('form_test');
  1231. }
  1232. /**
  1233. * Tests form_state_values_clean().
  1234. */
  1235. function testFormStateValuesClean() {
  1236. $values = drupal_json_decode($this->drupalPost('form_test/form-state-values-clean', array(), t('Submit')));
  1237. // Setup the expected result.
  1238. $result = array(
  1239. 'beer' => 1000,
  1240. 'baz' => array('beer' => 2000),
  1241. );
  1242. // Verify that all internal Form API elements were removed.
  1243. $this->assertFalse(isset($values['form_id']), format_string('%element was removed.', array('%element' => 'form_id')));
  1244. $this->assertFalse(isset($values['form_token']), format_string('%element was removed.', array('%element' => 'form_token')));
  1245. $this->assertFalse(isset($values['form_build_id']), format_string('%element was removed.', array('%element' => 'form_build_id')));
  1246. $this->assertFalse(isset($values['op']), format_string('%element was removed.', array('%element' => 'op')));
  1247. // Verify that all buttons were removed.
  1248. $this->assertFalse(isset($values['foo']), format_string('%element was removed.', array('%element' => 'foo')));
  1249. $this->assertFalse(isset($values['bar']), format_string('%element was removed.', array('%element' => 'bar')));
  1250. $this->assertFalse(isset($values['baz']['foo']), format_string('%element was removed.', array('%element' => 'foo')));
  1251. $this->assertFalse(isset($values['baz']['baz']), format_string('%element was removed.', array('%element' => 'baz')));
  1252. // Verify that nested form value still exists.
  1253. $this->assertTrue(isset($values['baz']['beer']), 'Nested form value still exists.');
  1254. // Verify that actual form values equal resulting form values.
  1255. $this->assertEqual($values, $result, 'Expected form values equal actual form values.');
  1256. }
  1257. }
  1258. /**
  1259. * Tests $form_state clearance with form elements having buttons.
  1260. */
  1261. class FormStateValuesCleanAdvancedTestCase extends DrupalWebTestCase {
  1262. /**
  1263. * An image file path for uploading.
  1264. */
  1265. protected $image;
  1266. public static function getInfo() {
  1267. return array(
  1268. 'name' => 'Form state values clearance (advanced)',
  1269. 'description' => 'Test proper removal of submitted form values using form_state_values_clean() when having forms with elements containing buttons like "managed_file".',
  1270. 'group' => 'Form API',
  1271. );
  1272. }
  1273. function setUp() {
  1274. parent::setUp('form_test');
  1275. }
  1276. /**
  1277. * Tests form_state_values_clean().
  1278. */
  1279. function testFormStateValuesCleanAdvanced() {
  1280. // Get an image for uploading.
  1281. $image_files = $this->drupalGetTestFiles('image');
  1282. $this->image = current($image_files);
  1283. // Check if the physical file is there.
  1284. $this->assertTrue(is_file($this->image->uri), "The image file we're going to upload exists.");
  1285. // "Browse" for the desired file.
  1286. $edit = array('files[image]' => drupal_realpath($this->image->uri));
  1287. // Post the form.
  1288. $this->drupalPost('form_test/form-state-values-clean-advanced', $edit, t('Submit'));
  1289. // Expecting a 200 HTTP code.
  1290. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  1291. $this->assertRaw(t('You WIN!'), 'Found the success message.');
  1292. }
  1293. }
  1294. /**
  1295. * Tests form rebuilding.
  1296. *
  1297. * @todo Add tests for other aspects of form rebuilding.
  1298. */
  1299. class FormsRebuildTestCase extends DrupalWebTestCase {
  1300. public static function getInfo() {
  1301. return array(
  1302. 'name' => 'Form rebuilding',
  1303. 'description' => 'Tests functionality of drupal_rebuild_form().',
  1304. 'group' => 'Form API',
  1305. );
  1306. }
  1307. function setUp() {
  1308. parent::setUp('form_test');
  1309. $this->web_user = $this->drupalCreateUser(array('access content'));
  1310. $this->drupalLogin($this->web_user);
  1311. }
  1312. /**
  1313. * Tests preservation of values.
  1314. */
  1315. function testRebuildPreservesValues() {
  1316. $edit = array(
  1317. 'checkbox_1_default_off' => TRUE,
  1318. 'checkbox_1_default_on' => FALSE,
  1319. 'text_1' => 'foo',
  1320. );
  1321. $this->drupalPost('form-test/form-rebuild-preserve-values', $edit, 'Add more');
  1322. // Verify that initial elements retained their submitted values.
  1323. $this->assertFieldChecked('edit-checkbox-1-default-off', 'A submitted checked checkbox retained its checked state during a rebuild.');
  1324. $this->assertNoFieldChecked('edit-checkbox-1-default-on', 'A submitted unchecked checkbox retained its unchecked state during a rebuild.');
  1325. $this->assertFieldById('edit-text-1', 'foo', 'A textfield retained its submitted value during a rebuild.');
  1326. // Verify that newly added elements were initialized with their default values.
  1327. $this->assertFieldChecked('edit-checkbox-2-default-on', 'A newly added checkbox was initialized with a default checked state.');
  1328. $this->assertNoFieldChecked('edit-checkbox-2-default-off', 'A newly added checkbox was initialized with a default unchecked state.');
  1329. $this->assertFieldById('edit-text-2', 'DEFAULT 2', 'A newly added textfield was initialized with its default value.');
  1330. }
  1331. /**
  1332. * Tests that a form's action is retained after an Ajax submission.
  1333. *
  1334. * The 'action' attribute of a form should not change after an Ajax submission
  1335. * followed by a non-Ajax submission, which triggers a validation error.
  1336. */
  1337. function testPreserveFormActionAfterAJAX() {
  1338. // Create a multi-valued field for 'page' nodes to use for Ajax testing.
  1339. $field_name = 'field_ajax_test';
  1340. $field = array(
  1341. 'field_name' => $field_name,
  1342. 'type' => 'text',
  1343. 'cardinality' => FIELD_CARDINALITY_UNLIMITED,
  1344. );
  1345. field_create_field($field);
  1346. $instance = array(
  1347. 'field_name' => $field_name,
  1348. 'entity_type' => 'node',
  1349. 'bundle' => 'page',
  1350. );
  1351. field_create_instance($instance);
  1352. // Log in a user who can create 'page' nodes.
  1353. $this->web_user = $this->drupalCreateUser(array('create page content'));
  1354. $this->drupalLogin($this->web_user);
  1355. // Get the form for adding a 'page' node. Submit an "add another item" Ajax
  1356. // submission and verify it worked by ensuring the updated page has two text
  1357. // field items in the field for which we just added an item.
  1358. $this->drupalGet('node/add/page');
  1359. $this->drupalPostAJAX(NULL, array(), array('field_ajax_test_add_more' => t('Add another item')), 'system/ajax', array(), array(), 'page-node-form');
  1360. $this->assert(count($this->xpath('//div[contains(@class, "field-name-field-ajax-test")]//input[@type="text"]')) == 2, 'AJAX submission succeeded.');
  1361. // Submit the form with the non-Ajax "Save" button, leaving the title field
  1362. // blank to trigger a validation error, and ensure that a validation error
  1363. // occurred, because this test is for testing what happens when a form is
  1364. // re-rendered without being re-built, which is what happens when there's
  1365. // a validation error.
  1366. $this->drupalPost(NULL, array(), t('Save'));
  1367. $this->assertText('Title field is required.', 'Non-AJAX submission correctly triggered a validation error.');
  1368. // Ensure that the form contains two items in the multi-valued field, so we
  1369. // know we're testing a form that was correctly retrieved from cache.
  1370. $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.');
  1371. // Ensure that the form's action is correct.
  1372. $forms = $this->xpath('//form[contains(@class, "node-page-form")]');
  1373. $this->assert(count($forms) == 1 && $forms[0]['action'] == url('node/add/page'), 'Re-rendered form contains the correct action value.');
  1374. }
  1375. }
  1376. /**
  1377. * Tests form redirection.
  1378. */
  1379. class FormsRedirectTestCase extends DrupalWebTestCase {
  1380. public static function getInfo() {
  1381. return array(
  1382. 'name' => 'Form redirecting',
  1383. 'description' => 'Tests functionality of drupal_redirect_form().',
  1384. 'group' => 'Form API',
  1385. );
  1386. }
  1387. function setUp() {
  1388. parent::setUp(array('form_test'));
  1389. }
  1390. /**
  1391. * Tests form redirection.
  1392. */
  1393. function testRedirect() {
  1394. $path = 'form-test/redirect';
  1395. $options = array('query' => array('foo' => 'bar'));
  1396. $options['absolute'] = TRUE;
  1397. // Test basic redirection.
  1398. $edit = array(
  1399. 'redirection' => TRUE,
  1400. 'destination' => $this->randomName(),
  1401. );
  1402. $this->drupalPost($path, $edit, t('Submit'));
  1403. $this->assertUrl($edit['destination'], array(), 'Basic redirection works.');
  1404. // Test without redirection.
  1405. $edit = array(
  1406. 'redirection' => FALSE,
  1407. );
  1408. $this->drupalPost($path, $edit, t('Submit'));
  1409. $this->assertUrl($path, array(), 'When redirect is set to FALSE, there should be no redirection.');
  1410. // Test redirection with query parameters.
  1411. $edit = array(
  1412. 'redirection' => TRUE,
  1413. 'destination' => $this->randomName(),
  1414. );
  1415. $this->drupalPost($path, $edit, t('Submit'), $options);
  1416. $this->assertUrl($edit['destination'], array(), 'Redirection with query parameters works.');
  1417. // Test without redirection but with query parameters.
  1418. $edit = array(
  1419. 'redirection' => FALSE,
  1420. );
  1421. $this->drupalPost($path, $edit, t('Submit'), $options);
  1422. $this->assertUrl($path, $options, 'When redirect is set to FALSE, there should be no redirection, and the query parameters should be passed along.');
  1423. // Test redirection back to the original path.
  1424. $edit = array(
  1425. 'redirection' => TRUE,
  1426. 'destination' => '',
  1427. );
  1428. $this->drupalPost($path, $edit, t('Submit'));
  1429. $this->assertUrl($path, array(), 'When using an empty redirection string, there should be no redirection.');
  1430. // Test redirection back to the original path with query parameters.
  1431. $edit = array(
  1432. 'redirection' => TRUE,
  1433. 'destination' => '',
  1434. );
  1435. $this->drupalPost($path, $edit, t('Submit'), $options);
  1436. $this->assertUrl($path, $options, 'When using an empty redirection string, there should be no redirection, and the query parameters should be passed along.');
  1437. }
  1438. }
  1439. /**
  1440. * Test the programmatic form submission behavior.
  1441. */
  1442. class FormsProgrammaticTestCase extends DrupalWebTestCase {
  1443. public static function getInfo() {
  1444. return array(
  1445. 'name' => 'Programmatic form submissions',
  1446. 'description' => 'Test the programmatic form submission behavior.',
  1447. 'group' => 'Form API',
  1448. );
  1449. }
  1450. function setUp() {
  1451. parent::setUp('form_test');
  1452. }
  1453. /**
  1454. * Test the programmatic form submission workflow.
  1455. */
  1456. function testSubmissionWorkflow() {
  1457. // Backup the current batch status and reset it to avoid conflicts while
  1458. // processing the dummy form submit handler.
  1459. $current_batch = $batch =& batch_get();
  1460. $batch = array();
  1461. // Test that a programmatic form submission is rejected when a required
  1462. // textfield is omitted and correctly processed when it is provided.
  1463. $this->submitForm(array(), FALSE);
  1464. $this->submitForm(array('textfield' => 'test 1'), TRUE);
  1465. $this->submitForm(array(), FALSE);
  1466. $this->submitForm(array('textfield' => 'test 2'), TRUE);
  1467. // Test that a programmatic form submission can turn on and off checkboxes
  1468. // which are, by default, checked.
  1469. $this->submitForm(array('textfield' => 'dummy value', 'checkboxes' => array(1 => 1, 2 => 2)), TRUE);
  1470. $this->submitForm(array('textfield' => 'dummy value', 'checkboxes' => array(1 => 1, 2 => NULL)), TRUE);
  1471. $this->submitForm(array('textfield' => 'dummy value', 'checkboxes' => array(1 => NULL, 2 => 2)), TRUE);
  1472. $this->submitForm(array('textfield' => 'dummy value', 'checkboxes' => array(1 => NULL, 2 => NULL)), TRUE);
  1473. // Test that a programmatic form submission can successfully submit values
  1474. // even for fields where the #access property is FALSE.
  1475. $this->submitForm(array('textfield' => 'dummy value', 'textfield_no_access' => 'test value'), TRUE);
  1476. // Test that #access is respected for programmatic form submissions when
  1477. // requested to do so.
  1478. $submitted_values = array('textfield' => 'dummy value', 'textfield_no_access' => 'test value');
  1479. $expected_values = array('textfield' => 'dummy value', 'textfield_no_access' => 'default value');
  1480. $form_state = array('programmed_bypass_access_check' => FALSE);
  1481. $this->submitForm($submitted_values, TRUE, $expected_values, $form_state);
  1482. // Test that a programmatic form submission can correctly click a button
  1483. // that limits validation errors based on user input. Since we do not
  1484. // submit any values for "textfield" here and the textfield is required, we
  1485. // only expect form validation to pass when validation is limited to a
  1486. // different field.
  1487. $this->submitForm(array('op' => 'Submit with limited validation', 'field_to_validate' => 'all'), FALSE);
  1488. $this->submitForm(array('op' => 'Submit with limited validation', 'field_to_validate' => 'textfield'), FALSE);
  1489. $this->submitForm(array('op' => 'Submit with limited validation', 'field_to_validate' => 'field_to_validate'), TRUE);
  1490. // Restore the current batch status.
  1491. $batch = $current_batch;
  1492. }
  1493. /**
  1494. * Helper function used to programmatically submit the form defined in
  1495. * form_test.module with the given values.
  1496. *
  1497. * @param $values
  1498. * An array of field values to be submitted.
  1499. * @param $valid_input
  1500. * A boolean indicating whether or not the form submission is expected to
  1501. * be valid.
  1502. * @param $expected_values
  1503. * (Optional) An array of field values that are expected to be stored by
  1504. * the form submit handler. If not set, the submitted $values are assumed
  1505. * to also be the expected stored values.
  1506. * @param $form_state
  1507. * (Optional) A keyed array containing the state of the form, to be sent in
  1508. * the call to drupal_form_submit(). The $values parameter is added to
  1509. * $form_state['values'] by default, if it is not already set.
  1510. */
  1511. private function submitForm($values, $valid_input, $expected_values = NULL, $form_state = array()) {
  1512. // Programmatically submit the given values.
  1513. $form_state += array('values' => $values);
  1514. drupal_form_submit('form_test_programmatic_form', $form_state);
  1515. // Check that the form returns an error when expected, and vice versa.
  1516. $errors = form_get_errors();
  1517. $valid_form = empty($errors);
  1518. $args = array(
  1519. '%values' => print_r($values, TRUE),
  1520. '%errors' => $valid_form ? t('None') : implode(' ', $errors),
  1521. );
  1522. $this->assertTrue($valid_input == $valid_form, format_string('Input values: %values<br/>Validation handler errors: %errors', $args));
  1523. // We check submitted values only if we have a valid input.
  1524. if ($valid_input) {
  1525. // By fetching the values from $form_state['storage'] we ensure that the
  1526. // submission handler was properly executed.
  1527. $stored_values = $form_state['storage']['programmatic_form_submit'];
  1528. if (!isset($expected_values)) {
  1529. $expected_values = $values;
  1530. }
  1531. foreach ($expected_values as $key => $value) {
  1532. $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))));
  1533. }
  1534. }
  1535. }
  1536. }
  1537. /**
  1538. * Test that FAPI correctly determines $form_state['triggering_element'].
  1539. */
  1540. class FormsTriggeringElementTestCase extends DrupalWebTestCase {
  1541. public static function getInfo() {
  1542. return array(
  1543. 'name' => 'Form triggering element determination',
  1544. 'description' => 'Test the determination of $form_state[\'triggering_element\'].',
  1545. 'group' => 'Form API',
  1546. );
  1547. }
  1548. function setUp() {
  1549. parent::setUp('form_test');
  1550. }
  1551. /**
  1552. * Test the determination of $form_state['triggering_element'] when no button
  1553. * information is included in the POST data, as is sometimes the case when
  1554. * the ENTER key is pressed in a textfield in Internet Explorer.
  1555. */
  1556. function testNoButtonInfoInPost() {
  1557. $path = 'form-test/clicked-button';
  1558. $edit = array();
  1559. $form_html_id = 'form-test-clicked-button';
  1560. // Ensure submitting a form with no buttons results in no
  1561. // $form_state['triggering_element'] and the form submit handler not
  1562. // running.
  1563. $this->drupalPost($path, $edit, NULL, array(), array(), $form_html_id);
  1564. $this->assertText('There is no clicked button.', '$form_state[\'triggering_element\'] set to NULL.');
  1565. $this->assertNoText('Submit handler for form_test_clicked_button executed.', 'Form submit handler did not execute.');
  1566. // Ensure submitting a form with one or more submit buttons results in
  1567. // $form_state['triggering_element'] being set to the first one the user has
  1568. // access to. An argument with 'r' in it indicates a restricted
  1569. // (#access=FALSE) button.
  1570. $this->drupalPost($path . '/s', $edit, NULL, array(), array(), $form_html_id);
  1571. $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to only button.');
  1572. $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');
  1573. $this->drupalPost($path . '/s/s', $edit, NULL, array(), array(), $form_html_id);
  1574. $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to first button.');
  1575. $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');
  1576. $this->drupalPost($path . '/rs/s', $edit, NULL, array(), array(), $form_html_id);
  1577. $this->assertText('The clicked button is button2.', '$form_state[\'triggering_element\'] set to first available button.');
  1578. $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');
  1579. // Ensure submitting a form with buttons of different types results in
  1580. // $form_state['triggering_element'] being set to the first button,
  1581. // regardless of type. For the FAPI 'button' type, this should result in the
  1582. // submit handler not executing. The types are 's'(ubmit), 'b'(utton), and
  1583. // 'i'(mage_button).
  1584. $this->drupalPost($path . '/s/b/i', $edit, NULL, array(), array(), $form_html_id);
  1585. $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to first button.');
  1586. $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');
  1587. $this->drupalPost($path . '/b/s/i', $edit, NULL, array(), array(), $form_html_id);
  1588. $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to first button.');
  1589. $this->assertNoText('Submit handler for form_test_clicked_button executed.', 'Form submit handler did not execute.');
  1590. $this->drupalPost($path . '/i/s/b', $edit, NULL, array(), array(), $form_html_id);
  1591. $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to first button.');
  1592. $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');
  1593. }
  1594. /**
  1595. * Test that $form_state['triggering_element'] does not get set to a button
  1596. * with #access=FALSE.
  1597. */
  1598. function testAttemptAccessControlBypass() {
  1599. $path = 'form-test/clicked-button';
  1600. $form_html_id = 'form-test-clicked-button';
  1601. // Retrieve a form where 'button1' has #access=FALSE and 'button2' doesn't.
  1602. $this->drupalGet($path . '/rs/s');
  1603. // Submit the form with 'button1=button1' in the POST data, which someone
  1604. // trying to get around security safeguards could easily do. We have to do
  1605. // a little trickery here, to work around the safeguards in drupalPost(): by
  1606. // renaming the text field that is in the form to 'button1', we can get the
  1607. // data we want into $_POST.
  1608. $elements = $this->xpath('//form[@id="' . $form_html_id . '"]//input[@name="text"]');
  1609. $elements[0]['name'] = 'button1';
  1610. $this->drupalPost(NULL, array('button1' => 'button1'), NULL, array(), array(), $form_html_id);
  1611. // Ensure that $form_state['triggering_element'] was not set to the
  1612. // restricted button. Do this with both a negative and positive assertion,
  1613. // because negative assertions alone can be brittle. See
  1614. // testNoButtonInfoInPost() for why the triggering element gets set to
  1615. // 'button2'.
  1616. $this->assertNoText('The clicked button is button1.', '$form_state[\'triggering_element\'] not set to a restricted button.');
  1617. $this->assertText('The clicked button is button2.', '$form_state[\'triggering_element\'] not set to a restricted button.');
  1618. }
  1619. }
  1620. /**
  1621. * Tests rebuilding of arbitrary forms by altering them.
  1622. */
  1623. class FormsArbitraryRebuildTestCase extends DrupalWebTestCase {
  1624. public static function getInfo() {
  1625. return array(
  1626. 'name' => 'Rebuild arbitrary forms',
  1627. 'description' => 'Tests altering forms to be rebuilt so there are multiple steps.',
  1628. 'group' => 'Form API',
  1629. );
  1630. }
  1631. function setUp() {
  1632. parent::setUp('form_test');
  1633. // Auto-create a field for testing.
  1634. $field = array(
  1635. 'field_name' => 'test_multiple',
  1636. 'type' => 'text',
  1637. 'cardinality' => -1,
  1638. 'translatable' => FALSE,
  1639. );
  1640. field_create_field($field);
  1641. $instance = array(
  1642. 'entity_type' => 'node',
  1643. 'field_name' => 'test_multiple',
  1644. 'bundle' => 'page',
  1645. 'label' => 'Test a multiple valued field',
  1646. 'widget' => array(
  1647. 'type' => 'text_textfield',
  1648. 'weight' => 0,
  1649. ),
  1650. );
  1651. field_create_instance($instance);
  1652. variable_set('user_register', USER_REGISTER_VISITORS);
  1653. }
  1654. /**
  1655. * Tests a basic rebuild with the user registration form.
  1656. */
  1657. function testUserRegistrationRebuild() {
  1658. $edit = array(
  1659. 'name' => 'foo',
  1660. 'mail' => 'bar@example.com',
  1661. );
  1662. $this->drupalPost('user/register', $edit, 'Rebuild');
  1663. $this->assertText('Form rebuilt.');
  1664. $this->assertFieldByName('name', 'foo', 'Entered user name has been kept.');
  1665. $this->assertFieldByName('mail', 'bar@example.com', 'Entered mail address has been kept.');
  1666. }
  1667. /**
  1668. * Tests a rebuild caused by a multiple value field.
  1669. */
  1670. function testUserRegistrationMultipleField() {
  1671. $edit = array(
  1672. 'name' => 'foo',
  1673. 'mail' => 'bar@example.com',
  1674. );
  1675. $this->drupalPost('user/register', $edit, t('Add another item'), array('query' => array('field' => TRUE)));
  1676. $this->assertText('Test a multiple valued field', 'Form has been rebuilt.');
  1677. $this->assertFieldByName('name', 'foo', 'Entered user name has been kept.');
  1678. $this->assertFieldByName('mail', 'bar@example.com', 'Entered mail address has been kept.');
  1679. }
  1680. }
  1681. /**
  1682. * Tests form API file inclusion.
  1683. */
  1684. class FormsFileInclusionTestCase extends DrupalWebTestCase {
  1685. public static function getInfo() {
  1686. return array(
  1687. 'name' => 'Form API file inclusion',
  1688. 'description' => 'Tests form API file inclusion.',
  1689. 'group' => 'Form API',
  1690. );
  1691. }
  1692. function setUp() {
  1693. parent::setUp('form_test');
  1694. }
  1695. /**
  1696. * Tests loading an include specified in hook_menu().
  1697. */
  1698. function testLoadMenuInclude() {
  1699. $this->drupalPostAJAX('form-test/load-include-menu', array(), array('op' => t('Save')), 'system/ajax', array(), array(), 'form-test-load-include-menu');
  1700. $this->assertText('Submit callback called.');
  1701. }
  1702. /**
  1703. * Tests loading a custom specified inlcude.
  1704. */
  1705. function testLoadCustomInclude() {
  1706. $this->drupalPost('form-test/load-include-custom', array(), t('Save'));
  1707. $this->assertText('Submit callback called.');
  1708. }
  1709. }
  1710. /**
  1711. * Tests checkbox element.
  1712. */
  1713. class FormCheckboxTestCase extends DrupalWebTestCase {
  1714. public static function getInfo() {
  1715. return array(
  1716. 'name' => 'Form API checkbox',
  1717. 'description' => 'Tests form API checkbox handling of various combinations of #default_value and #return_value.',
  1718. 'group' => 'Form API',
  1719. );
  1720. }
  1721. function setUp() {
  1722. parent::setUp('form_test');
  1723. }
  1724. function testFormCheckbox() {
  1725. // Ensure that the checked state is determined and rendered correctly for
  1726. // tricky combinations of default and return values.
  1727. foreach (array(FALSE, NULL, TRUE, 0, '0', '', 1, '1', 'foobar', '1foobar') as $default_value) {
  1728. // Only values that can be used for array indeces are supported for
  1729. // #return_value, with the exception of integer 0, which is not supported.
  1730. // @see form_process_checkbox().
  1731. foreach (array('0', '', 1, '1', 'foobar', '1foobar') as $return_value) {
  1732. $form_array = drupal_get_form('form_test_checkbox_type_juggling', $default_value, $return_value);
  1733. $form = drupal_render($form_array);
  1734. if ($default_value === TRUE) {
  1735. $checked = TRUE;
  1736. }
  1737. elseif ($return_value === '0') {
  1738. $checked = ($default_value === '0');
  1739. }
  1740. elseif ($return_value === '') {
  1741. $checked = ($default_value === '');
  1742. }
  1743. elseif ($return_value === 1 || $return_value === '1') {
  1744. $checked = ($default_value === 1 || $default_value === '1');
  1745. }
  1746. elseif ($return_value === 'foobar') {
  1747. $checked = ($default_value === 'foobar');
  1748. }
  1749. elseif ($return_value === '1foobar') {
  1750. $checked = ($default_value === '1foobar');
  1751. }
  1752. $checked_in_html = strpos($form, 'checked') !== FALSE;
  1753. $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)));
  1754. $this->assertIdentical($checked, $checked_in_html, $message);
  1755. }
  1756. }
  1757. // Ensure that $form_state['values'] is populated correctly for a checkboxes
  1758. // group that includes a 0-indexed array of options.
  1759. $results = json_decode($this->drupalPost('form-test/checkboxes-zero', array(), 'Save'));
  1760. $this->assertIdentical($results->checkbox_off, array(0, 0, 0), 'All three in checkbox_off are zeroes: off.');
  1761. $this->assertIdentical($results->checkbox_zero_default, array('0', 0, 0), 'The first choice is on in checkbox_zero_default');
  1762. $this->assertIdentical($results->checkbox_string_zero_default, array('0', 0, 0), 'The first choice is on in checkbox_string_zero_default');
  1763. $edit = array('checkbox_off[0]' => '0');
  1764. $results = json_decode($this->drupalPost('form-test/checkboxes-zero', $edit, 'Save'));
  1765. $this->assertIdentical($results->checkbox_off, array('0', 0, 0), 'The first choice is on in checkbox_off but the rest is not');
  1766. // Ensure that each checkbox is rendered correctly for a checkboxes group
  1767. // that includes a 0-indexed array of options.
  1768. $this->drupalPost('form-test/checkboxes-zero/0', array(), 'Save');
  1769. $checkboxes = $this->xpath('//input[@type="checkbox"]');
  1770. foreach ($checkboxes as $checkbox) {
  1771. $checked = isset($checkbox['checked']);
  1772. $name = (string) $checkbox['name'];
  1773. $this->assertIdentical($checked, $name == 'checkbox_zero_default[0]' || $name == 'checkbox_string_zero_default[0]', format_string('Checkbox %name correctly checked', array('%name' => $name)));
  1774. }
  1775. $edit = array('checkbox_off[0]' => '0');
  1776. $this->drupalPost('form-test/checkboxes-zero/0', $edit, 'Save');
  1777. $checkboxes = $this->xpath('//input[@type="checkbox"]');
  1778. foreach ($checkboxes as $checkbox) {
  1779. $checked = isset($checkbox['checked']);
  1780. $name = (string) $checkbox['name'];
  1781. $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)));
  1782. }
  1783. }
  1784. }
  1785. /**
  1786. * Tests uniqueness of generated HTML IDs.
  1787. */
  1788. class HTMLIdTestCase extends DrupalWebTestCase {
  1789. public static function getInfo() {
  1790. return array(
  1791. 'name' => 'Unique HTML IDs',
  1792. 'description' => 'Tests functionality of drupal_html_id().',
  1793. 'group' => 'Form API',
  1794. );
  1795. }
  1796. function setUp() {
  1797. parent::setUp('form_test');
  1798. }
  1799. /**
  1800. * Tests that HTML IDs do not get duplicated when form validation fails.
  1801. */
  1802. function testHTMLId() {
  1803. $this->drupalGet('form-test/double-form');
  1804. $this->assertNoDuplicateIds('There are no duplicate IDs');
  1805. // Submit second form with empty title.
  1806. $edit = array();
  1807. $this->drupalPost(NULL, $edit, 'Save', array(), array(), 'form-test-html-id--2');
  1808. $this->assertNoDuplicateIds('There are no duplicate IDs');
  1809. }
  1810. }