form.test 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215
  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 that a form with a disabled CSRF token can be validated.
  624. */
  625. function testDisabledToken() {
  626. $this->drupalPost('form-test/validate-no-token', array(), 'Save');
  627. $this->assertText('The form_test_validate_no_token form has been submitted successfully.');
  628. }
  629. /**
  630. * Tests partial form validation through #limit_validation_errors.
  631. */
  632. function testValidateLimitErrors() {
  633. $edit = array(
  634. 'test' => 'invalid',
  635. 'test_numeric_index[0]' => 'invalid',
  636. 'test_substring[foo]' => 'invalid',
  637. );
  638. $path = 'form-test/limit-validation-errors';
  639. // Submit the form by pressing the 'Partial validate' button (uses
  640. // #limit_validation_errors) and ensure that the title field is not
  641. // validated, but the #element_validate handler for the 'test' field
  642. // is triggered.
  643. $this->drupalPost($path, $edit, t('Partial validate'));
  644. $this->assertNoText(t('!name field is required.', array('!name' => 'Title')));
  645. $this->assertText('Test element is invalid');
  646. // Edge case of #limit_validation_errors containing numeric indexes: same
  647. // thing with the 'Partial validate (numeric index)' button and the
  648. // 'test_numeric_index' field.
  649. $this->drupalPost($path, $edit, t('Partial validate (numeric index)'));
  650. $this->assertNoText(t('!name field is required.', array('!name' => 'Title')));
  651. $this->assertText('Test (numeric index) element is invalid');
  652. // Ensure something like 'foobar' isn't considered "inside" 'foo'.
  653. $this->drupalPost($path, $edit, t('Partial validate (substring)'));
  654. $this->assertNoText(t('!name field is required.', array('!name' => 'Title')));
  655. $this->assertText('Test (substring) foo element is invalid');
  656. // Ensure not validated values are not available to submit handlers.
  657. $this->drupalPost($path, array('title' => '', 'test' => 'valid'), t('Partial validate'));
  658. $this->assertText('Only validated values appear in the form values.');
  659. // Now test full form validation and ensure that the #element_validate
  660. // handler is still triggered.
  661. $this->drupalPost($path, $edit, t('Full validate'));
  662. $this->assertText(t('!name field is required.', array('!name' => 'Title')));
  663. $this->assertText('Test element is invalid');
  664. }
  665. /**
  666. * Tests error border of multiple fields with same name in a page.
  667. */
  668. function testMultiFormSameNameErrorClass() {
  669. $this->drupalGet('form-test/double-form');
  670. $edit = array();
  671. $this->drupalPost(NULL, $edit, t('Save'));
  672. $this->assertFieldByXpath('//input[@id="edit-name" and contains(@class, "error")]', NULL, 'Error input form element class found for first element.');
  673. $this->assertNoFieldByXpath('//input[@id="edit-name--2" and contains(@class, "error")]', NULL, 'No error input form element class found for second element.');
  674. }
  675. }
  676. /**
  677. * Test form element labels, required markers and associated output.
  678. */
  679. class FormsElementsLabelsTestCase extends DrupalWebTestCase {
  680. public static function getInfo() {
  681. return array(
  682. 'name' => 'Form element and label output test',
  683. 'description' => 'Test form element labels, required markers and associated output.',
  684. 'group' => 'Form API',
  685. );
  686. }
  687. function setUp() {
  688. parent::setUp('form_test');
  689. }
  690. /**
  691. * Test form elements, labels, title attibutes and required marks output
  692. * correctly and have the correct label option class if needed.
  693. */
  694. function testFormLabels() {
  695. $this->drupalGet('form_test/form-labels');
  696. // Check that the checkbox/radio processing is not interfering with
  697. // basic placement.
  698. $elements = $this->xpath('//input[@id="edit-form-checkboxes-test-third-checkbox"]/following-sibling::label[@for="edit-form-checkboxes-test-third-checkbox" and @class="option"]');
  699. $this->assertTrue(isset($elements[0]), "Label follows field and label option class correct for regular checkboxes.");
  700. // Make sure the label is rendered for checkboxes.
  701. $elements = $this->xpath('//input[@id="edit-form-checkboxes-test-0"]/following-sibling::label[@for="edit-form-checkboxes-test-0" and @class="option"]');
  702. $this->assertTrue(isset($elements[0]), "Label 0 found checkbox.");
  703. $elements = $this->xpath('//input[@id="edit-form-radios-test-second-radio"]/following-sibling::label[@for="edit-form-radios-test-second-radio" and @class="option"]');
  704. $this->assertTrue(isset($elements[0]), "Label follows field and label option class correct for regular radios.");
  705. // Make sure the label is rendered for radios.
  706. $elements = $this->xpath('//input[@id="edit-form-radios-test-0"]/following-sibling::label[@for="edit-form-radios-test-0" and @class="option"]');
  707. $this->assertTrue(isset($elements[0]), "Label 0 found radios.");
  708. // Exercise various defaults for checkboxes and modifications to ensure
  709. // appropriate override and correct behavior.
  710. $elements = $this->xpath('//input[@id="edit-form-checkbox-test"]/following-sibling::label[@for="edit-form-checkbox-test" and @class="option"]');
  711. $this->assertTrue(isset($elements[0]), "Label follows field and label option class correct for a checkbox by default.");
  712. // Exercise various defaults for textboxes and modifications to ensure
  713. // appropriate override and correct behavior.
  714. $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"]');
  715. $this->assertTrue(isset($elements[0]), "Label precedes textfield, with required marker inside label.");
  716. $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"]');
  717. $this->assertTrue(isset($elements[0]), "Label tag with required marker precedes required textfield with no title.");
  718. $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"]');
  719. $this->assertTrue(isset($elements[0]), "Label preceding field and label class is element-invisible.");
  720. $elements = $this->xpath('//input[@id="edit-form-textfield-test-title"]/preceding-sibling::span[@class="form-required"]');
  721. $this->assertFalse(isset($elements[0]), "No required marker on non-required field.");
  722. $elements = $this->xpath('//input[@id="edit-form-textfield-test-title-after"]/following-sibling::label[@for="edit-form-textfield-test-title-after" and @class="option"]');
  723. $this->assertTrue(isset($elements[0]), "Label after field and label option class correct for text field.");
  724. $elements = $this->xpath('//label[@for="edit-form-textfield-test-title-no-show"]');
  725. $this->assertFalse(isset($elements[0]), "No label tag when title set not to display.");
  726. // Check #field_prefix and #field_suffix placement.
  727. $elements = $this->xpath('//span[@class="field-prefix"]/following-sibling::div[@id="edit-form-radios-test"]');
  728. $this->assertTrue(isset($elements[0]), "Properly placed the #field_prefix element after the label and before the field.");
  729. $elements = $this->xpath('//span[@class="field-suffix"]/preceding-sibling::div[@id="edit-form-radios-test"]');
  730. $this->assertTrue(isset($elements[0]), "Properly places the #field_suffix element immediately after the form field.");
  731. // Check #prefix and #suffix placement.
  732. $elements = $this->xpath('//div[@id="form-test-textfield-title-prefix"]/following-sibling::div[contains(@class, \'form-item-form-textfield-test-title\')]');
  733. $this->assertTrue(isset($elements[0]), "Properly places the #prefix element before the form item.");
  734. $elements = $this->xpath('//div[@id="form-test-textfield-title-suffix"]/preceding-sibling::div[contains(@class, \'form-item-form-textfield-test-title\')]');
  735. $this->assertTrue(isset($elements[0]), "Properly places the #suffix element before the form item.");
  736. // Check title attribute for radios and checkboxes.
  737. $elements = $this->xpath('//div[@id="edit-form-checkboxes-title-attribute"]');
  738. $this->assertEqual($elements[0]['title'], 'Checkboxes test' . ' (' . t('Required') . ')', 'Title attribute found.');
  739. $elements = $this->xpath('//div[@id="edit-form-radios-title-attribute"]');
  740. $this->assertEqual($elements[0]['title'], 'Radios test' . ' (' . t('Required') . ')', 'Title attribute found.');
  741. }
  742. }
  743. /**
  744. * Test the tableselect form element for expected behavior.
  745. */
  746. class FormsElementsTableSelectFunctionalTest extends DrupalWebTestCase {
  747. public static function getInfo() {
  748. return array(
  749. 'name' => 'Tableselect form element type test',
  750. 'description' => 'Test the tableselect element for expected behavior',
  751. 'group' => 'Form API',
  752. );
  753. }
  754. function setUp() {
  755. parent::setUp('form_test');
  756. }
  757. /**
  758. * Test the display of checkboxes when #multiple is TRUE.
  759. */
  760. function testMultipleTrue() {
  761. $this->drupalGet('form_test/tableselect/multiple-true');
  762. $this->assertNoText(t('Empty text.'), 'Empty text should not be displayed.');
  763. // Test for the presence of the Select all rows tableheader.
  764. $this->assertFieldByXPath('//th[@class="select-all"]', NULL, 'Presence of the "Select all" checkbox.');
  765. $rows = array('row1', 'row2', 'row3');
  766. foreach ($rows as $row) {
  767. $this->assertFieldByXPath('//input[@type="checkbox"]', $row, format_string('Checkbox for value @row.', array('@row' => $row)));
  768. }
  769. }
  770. /**
  771. * Test the display of radios when #multiple is FALSE.
  772. */
  773. function testMultipleFalse() {
  774. $this->drupalGet('form_test/tableselect/multiple-false');
  775. $this->assertNoText(t('Empty text.'), 'Empty text should not be displayed.');
  776. // Test for the absence of the Select all rows tableheader.
  777. $this->assertNoFieldByXPath('//th[@class="select-all"]', '', 'Absence of the "Select all" checkbox.');
  778. $rows = array('row1', 'row2', 'row3');
  779. foreach ($rows as $row) {
  780. $this->assertFieldByXPath('//input[@type="radio"]', $row, format_string('Radio button for value @row.', array('@row' => $row)));
  781. }
  782. }
  783. /**
  784. * Test the display of the #empty text when #options is an empty array.
  785. */
  786. function testEmptyText() {
  787. $this->drupalGet('form_test/tableselect/empty-text');
  788. $this->assertText(t('Empty text.'), 'Empty text should be displayed.');
  789. }
  790. /**
  791. * Test the submission of single and multiple values when #multiple is TRUE.
  792. */
  793. function testMultipleTrueSubmit() {
  794. // Test a submission with one checkbox checked.
  795. $edit = array();
  796. $edit['tableselect[row1]'] = 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 = 0'), 'Unchecked checkbox row3.');
  801. // Test a submission with multiple checkboxes checked.
  802. $edit['tableselect[row1]'] = TRUE;
  803. $edit['tableselect[row3]'] = TRUE;
  804. $this->drupalPost('form_test/tableselect/multiple-true', $edit, 'Submit');
  805. $this->assertText(t('Submitted: row1 = row1'), 'Checked checkbox row1.');
  806. $this->assertText(t('Submitted: row2 = 0'), 'Unchecked checkbox row2.');
  807. $this->assertText(t('Submitted: row3 = row3'), 'Checked checkbox row3.');
  808. }
  809. /**
  810. * Test submission of values when #multiple is FALSE.
  811. */
  812. function testMultipleFalseSubmit() {
  813. $edit['tableselect'] = 'row1';
  814. $this->drupalPost('form_test/tableselect/multiple-false', $edit, 'Submit');
  815. $this->assertText(t('Submitted: row1'), 'Selected radio button');
  816. }
  817. /**
  818. * Test the #js_select property.
  819. */
  820. function testAdvancedSelect() {
  821. // When #multiple = TRUE a Select all checkbox should be displayed by default.
  822. $this->drupalGet('form_test/tableselect/advanced-select/multiple-true-default');
  823. $this->assertFieldByXPath('//th[@class="select-all"]', NULL, 'Display a "Select all" checkbox by default when #multiple is TRUE.');
  824. // When #js_select is set to FALSE, a "Select all" checkbox should not be displayed.
  825. $this->drupalGet('form_test/tableselect/advanced-select/multiple-true-no-advanced-select');
  826. $this->assertNoFieldByXPath('//th[@class="select-all"]', NULL, 'Do not display a "Select all" checkbox when #js_select is FALSE.');
  827. // A "Select all" checkbox never makes sense when #multiple = FALSE, regardless of the value of #js_select.
  828. $this->drupalGet('form_test/tableselect/advanced-select/multiple-false-default');
  829. $this->assertNoFieldByXPath('//th[@class="select-all"]', NULL, 'Do not display a "Select all" checkbox when #multiple is FALSE.');
  830. $this->drupalGet('form_test/tableselect/advanced-select/multiple-false-advanced-select');
  831. $this->assertNoFieldByXPath('//th[@class="select-all"]', NULL, 'Do not display a "Select all" checkbox when #multiple is FALSE, even when #js_select is TRUE.');
  832. }
  833. /**
  834. * Test the whether the option checker gives an error on invalid tableselect values for checkboxes.
  835. */
  836. function testMultipleTrueOptionchecker() {
  837. list($header, $options) = _form_test_tableselect_get_data();
  838. $form['tableselect'] = array(
  839. '#type' => 'tableselect',
  840. '#header' => $header,
  841. '#options' => $options,
  842. );
  843. // Test with a valid value.
  844. list($processed_form, $form_state, $errors) = $this->formSubmitHelper($form, array('tableselect' => array('row1' => 'row1')));
  845. $this->assertFalse(isset($errors['tableselect']), 'Option checker allows valid values for checkboxes.');
  846. // Test with an invalid value.
  847. list($processed_form, $form_state, $errors) = $this->formSubmitHelper($form, array('tableselect' => array('non_existing_value' => 'non_existing_value')));
  848. $this->assertTrue(isset($errors['tableselect']), 'Option checker disallows invalid values for checkboxes.');
  849. }
  850. /**
  851. * Test the whether the option checker gives an error on invalid tableselect values for radios.
  852. */
  853. function testMultipleFalseOptionchecker() {
  854. list($header, $options) = _form_test_tableselect_get_data();
  855. $form['tableselect'] = array(
  856. '#type' => 'tableselect',
  857. '#header' => $header,
  858. '#options' => $options,
  859. '#multiple' => FALSE,
  860. );
  861. // Test with a valid value.
  862. list($processed_form, $form_state, $errors) = $this->formSubmitHelper($form, array('tableselect' => 'row1'));
  863. $this->assertFalse(isset($errors['tableselect']), 'Option checker allows valid values for radio buttons.');
  864. // Test with an invalid value.
  865. list($processed_form, $form_state, $errors) = $this->formSubmitHelper($form, array('tableselect' => 'non_existing_value'));
  866. $this->assertTrue(isset($errors['tableselect']), 'Option checker disallows invalid values for radio buttons.');
  867. }
  868. /**
  869. * Test presence of ajax functionality
  870. */
  871. function testAjax() {
  872. $rows = array('row1', 'row2', 'row3');
  873. // Test checkboxes (#multiple == TRUE).
  874. foreach ($rows as $row) {
  875. $element = 'tableselect[' . $row . ']';
  876. $edit = array($element => TRUE);
  877. $result = $this->drupalPostAJAX('form_test/tableselect/multiple-true', $edit, $element);
  878. $this->assertFalse(empty($result), t('Ajax triggers on checkbox for @row.', array('@row' => $row)));
  879. }
  880. // Test radios (#multiple == FALSE).
  881. $element = 'tableselect';
  882. foreach ($rows as $row) {
  883. $edit = array($element => $row);
  884. $result = $this->drupalPostAjax('form_test/tableselect/multiple-false', $edit, $element);
  885. $this->assertFalse(empty($result), t('Ajax triggers on radio for @row.', array('@row' => $row)));
  886. }
  887. }
  888. /**
  889. * Helper function for the option check test to submit a form while collecting errors.
  890. *
  891. * @param $form_element
  892. * A form element to test.
  893. * @param $edit
  894. * An array containing post data.
  895. *
  896. * @return
  897. * An array containing the processed form, the form_state and any errors.
  898. */
  899. private function formSubmitHelper($form, $edit) {
  900. $form_id = $this->randomName();
  901. $form_state = form_state_defaults();
  902. $form['op'] = array('#type' => 'submit', '#value' => t('Submit'));
  903. $form_state['input'] = $edit;
  904. $form_state['input']['form_id'] = $form_id;
  905. // The form token CSRF protection should not interfere with this test,
  906. // so we bypass it by marking this test form as programmed.
  907. $form_state['programmed'] = TRUE;
  908. drupal_prepare_form($form_id, $form, $form_state);
  909. drupal_process_form($form_id, $form, $form_state);
  910. $errors = form_get_errors();
  911. // Clear errors and messages.
  912. drupal_get_messages();
  913. form_clear_error();
  914. // Return the processed form together with form_state and errors
  915. // to allow the caller lowlevel access to the form.
  916. return array($form, $form_state, $errors);
  917. }
  918. }
  919. /**
  920. * Test the vertical_tabs form element for expected behavior.
  921. */
  922. class FormsElementsVerticalTabsFunctionalTest extends DrupalWebTestCase {
  923. public static function getInfo() {
  924. return array(
  925. 'name' => 'Vertical tabs form element type test',
  926. 'description' => 'Test the vertical_tabs element for expected behavior',
  927. 'group' => 'Form API',
  928. );
  929. }
  930. function setUp() {
  931. parent::setUp('form_test');
  932. }
  933. /**
  934. * Ensures that vertical-tabs.js is included before collapse.js.
  935. *
  936. * Otherwise, collapse.js adds "SHOW" or "HIDE" labels to the tabs.
  937. */
  938. function testJavaScriptOrdering() {
  939. $this->drupalGet('form_test/vertical-tabs');
  940. $position1 = strpos($this->content, 'misc/vertical-tabs.js');
  941. $position2 = strpos($this->content, 'misc/collapse.js');
  942. $this->assertTrue($position1 !== FALSE && $position2 !== FALSE && $position1 < $position2, 'vertical-tabs.js is included before collapse.js');
  943. }
  944. }
  945. /**
  946. * Test the form storage on a multistep form.
  947. *
  948. * The tested form puts data into the storage during the initial form
  949. * construction. These tests verify that there are no duplicate form
  950. * constructions, with and without manual form caching activiated. Furthermore
  951. * when a validation error occurs, it makes sure that changed form element
  952. * values aren't lost due to a wrong form rebuild.
  953. */
  954. class FormsFormStorageTestCase extends DrupalWebTestCase {
  955. public static function getInfo() {
  956. return array(
  957. 'name' => 'Multistep form using form storage',
  958. 'description' => 'Tests a multistep form using form storage and makes sure validation and caching works right.',
  959. 'group' => 'Form API',
  960. );
  961. }
  962. function setUp() {
  963. parent::setUp('form_test');
  964. $this->web_user = $this->drupalCreateUser(array('access content'));
  965. $this->drupalLogin($this->web_user);
  966. }
  967. /**
  968. * Tests using the form in a usual way.
  969. */
  970. function testForm() {
  971. $this->drupalGet('form_test/form-storage');
  972. $this->assertText('Form constructions: 1');
  973. $edit = array('title' => 'new', 'value' => 'value_is_set');
  974. // Use form rebuilding triggered by a submit button.
  975. $this->drupalPost(NULL, $edit, 'Continue submit');
  976. $this->assertText('Form constructions: 2');
  977. $this->assertText('Form constructions: 3');
  978. // Reset the form to the values of the storage, using a form rebuild
  979. // triggered by button of type button.
  980. $this->drupalPost(NULL, array('title' => 'changed'), 'Reset');
  981. $this->assertFieldByName('title', 'new', 'Values have been resetted.');
  982. // After rebuilding, the form has been cached.
  983. $this->assertText('Form constructions: 4');
  984. $this->drupalPost(NULL, $edit, 'Save');
  985. $this->assertText('Form constructions: 4');
  986. $this->assertText('Title: new', 'The form storage has stored the values.');
  987. }
  988. /**
  989. * Tests using the form with an activated $form_state['cache'] property.
  990. */
  991. function testFormCached() {
  992. $this->drupalGet('form_test/form-storage', array('query' => array('cache' => 1)));
  993. $this->assertText('Form constructions: 1');
  994. $edit = array('title' => 'new', 'value' => 'value_is_set');
  995. // Use form rebuilding triggered by a submit button.
  996. $this->drupalPost(NULL, $edit, 'Continue submit');
  997. $this->assertText('Form constructions: 2');
  998. // Reset the form to the values of the storage, using a form rebuild
  999. // triggered by button of type button.
  1000. $this->drupalPost(NULL, array('title' => 'changed'), 'Reset');
  1001. $this->assertFieldByName('title', 'new', 'Values have been resetted.');
  1002. $this->assertText('Form constructions: 3');
  1003. $this->drupalPost(NULL, $edit, 'Save');
  1004. $this->assertText('Form constructions: 3');
  1005. $this->assertText('Title: new', 'The form storage has stored the values.');
  1006. }
  1007. /**
  1008. * Tests validation when form storage is used.
  1009. */
  1010. function testValidation() {
  1011. $this->drupalPost('form_test/form-storage', array('title' => '', 'value' => 'value_is_set'), 'Continue submit');
  1012. $this->assertPattern('/value_is_set/', 'The input values have been kept.');
  1013. }
  1014. /**
  1015. * Tests updating cached form storage during form validation.
  1016. *
  1017. * If form caching is enabled and a form stores data in the form storage, then
  1018. * the form storage also has to be updated in case of a validation error in
  1019. * the form. This test re-uses the existing form for multi-step tests, but
  1020. * triggers a special #element_validate handler to update the form storage
  1021. * during form validation, while another, required element in the form
  1022. * triggers a form validation error.
  1023. */
  1024. function testCachedFormStorageValidation() {
  1025. // Request the form with 'cache' query parameter to enable form caching.
  1026. $this->drupalGet('form_test/form-storage', array('query' => array('cache' => 1)));
  1027. // Skip step 1 of the multi-step form, since the first step copies over
  1028. // 'title' into form storage, but we want to verify that changes in the form
  1029. // storage are updated in the cache during form validation.
  1030. $edit = array('title' => 'foo');
  1031. $this->drupalPost(NULL, $edit, 'Continue submit');
  1032. // In step 2, trigger a validation error for the required 'title' field, and
  1033. // post the special 'change_title' value for the 'value' field, which
  1034. // conditionally invokes the #element_validate handler to update the form
  1035. // storage.
  1036. $edit = array('title' => '', 'value' => 'change_title');
  1037. $this->drupalPost(NULL, $edit, 'Save');
  1038. // At this point, the form storage should contain updated values, but we do
  1039. // not see them, because the form has not been rebuilt yet due to the
  1040. // validation error. Post again and verify that the rebuilt form contains
  1041. // the values of the updated form storage.
  1042. $this->drupalPost(NULL, array('title' => 'foo', 'value' => 'bar'), 'Save');
  1043. $this->assertText("The thing has been changed.", 'The altered form storage value was updated in cache and taken over.');
  1044. }
  1045. /**
  1046. * Tests a form using form state without using 'storage' to pass data from the
  1047. * constructor to a submit handler. The data has to persist even when caching
  1048. * gets activated, what may happen when a modules alter the form and adds
  1049. * #ajax properties.
  1050. */
  1051. function testFormStatePersist() {
  1052. // Test the form one time with caching activated and one time without.
  1053. $run_options = array(
  1054. array(),
  1055. array('query' => array('cache' => 1)),
  1056. );
  1057. foreach ($run_options as $options) {
  1058. $this->drupalPost('form-test/state-persist', array(), t('Submit'), $options);
  1059. // The submit handler outputs the value in $form_state, assert it's there.
  1060. $this->assertText('State persisted.');
  1061. // Test it again, but first trigger a validation error, then test.
  1062. $this->drupalPost('form-test/state-persist', array('title' => ''), t('Submit'), $options);
  1063. $this->assertText(t('!name field is required.', array('!name' => 'title')));
  1064. // Submit the form again triggering no validation error.
  1065. $this->drupalPost(NULL, array('title' => 'foo'), t('Submit'), $options);
  1066. $this->assertText('State persisted.');
  1067. // Now post to the rebuilt form and verify it's still there afterwards.
  1068. $this->drupalPost(NULL, array('title' => 'bar'), t('Submit'), $options);
  1069. $this->assertText('State persisted.');
  1070. }
  1071. }
  1072. /**
  1073. * Verify that the form build-id remains the same when validation errors
  1074. * occur on a mutable form.
  1075. */
  1076. function testMutableForm() {
  1077. // Request the form with 'cache' query parameter to enable form caching.
  1078. $this->drupalGet('form_test/form-storage', array('query' => array('cache' => 1)));
  1079. $buildIdFields = $this->xpath('//input[@name="form_build_id"]');
  1080. $this->assertEqual(count($buildIdFields), 1, 'One form build id field on the page');
  1081. $buildId = (string) $buildIdFields[0]['value'];
  1082. // Trigger validation error by submitting an empty title.
  1083. $edit = array('title' => '');
  1084. $this->drupalPost(NULL, $edit, 'Continue submit');
  1085. // Verify that the build-id did not change.
  1086. $this->assertFieldByName('form_build_id', $buildId, 'Build id remains the same when form validation fails');
  1087. }
  1088. /**
  1089. * Verifies that form build-id is regenerated when loading an immutable form
  1090. * from the cache.
  1091. */
  1092. function testImmutableForm() {
  1093. // Request the form with 'cache' query parameter to enable form caching.
  1094. $this->drupalGet('form_test/form-storage', array('query' => array('cache' => 1, 'immutable' => 1)));
  1095. $buildIdFields = $this->xpath('//input[@name="form_build_id"]');
  1096. $this->assertEqual(count($buildIdFields), 1, 'One form build id field on the page');
  1097. $buildId = (string) $buildIdFields[0]['value'];
  1098. // Trigger validation error by submitting an empty title.
  1099. $edit = array('title' => '');
  1100. $this->drupalPost(NULL, $edit, 'Continue submit');
  1101. // Verify that the build-id did change.
  1102. $this->assertNoFieldByName('form_build_id', $buildId, 'Build id changes when form validation fails');
  1103. // Retrieve the new build-id.
  1104. $buildIdFields = $this->xpath('//input[@name="form_build_id"]');
  1105. $this->assertEqual(count($buildIdFields), 1, 'One form build id field on the page');
  1106. $buildId = (string) $buildIdFields[0]['value'];
  1107. // Trigger validation error by again submitting an empty title.
  1108. $edit = array('title' => '');
  1109. $this->drupalPost(NULL, $edit, 'Continue submit');
  1110. // Verify that the build-id does not change the second time.
  1111. $this->assertFieldByName('form_build_id', $buildId, 'Build id remains the same when form validation fails subsequently');
  1112. }
  1113. /**
  1114. * Verify that existing contrib code cannot overwrite immutable form state.
  1115. */
  1116. public function testImmutableFormLegacyProtection() {
  1117. $this->drupalGet('form_test/form-storage', array('query' => array('cache' => 1, 'immutable' => 1)));
  1118. $build_id_fields = $this->xpath('//input[@name="form_build_id"]');
  1119. $this->assertEqual(count($build_id_fields), 1, 'One form build id field on the page');
  1120. $build_id = (string) $build_id_fields[0]['value'];
  1121. // Try to poison the form cache.
  1122. $original = $this->drupalGetAJAX('form_test/form-storage-legacy/' . $build_id);
  1123. $this->assertEqual($original['form']['#build_id_old'], $build_id, 'Original build_id was recorded');
  1124. $this->assertNotEqual($original['form']['#build_id'], $build_id, 'New build_id was generated');
  1125. // Assert that a watchdog message was logged by form_set_cache.
  1126. $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.'));
  1127. $this->assert($status, 'A watchdog message was logged by form_set_cache');
  1128. // Ensure that the form state was not poisoned by the preceeding call.
  1129. $original = $this->drupalGetAJAX('form_test/form-storage-legacy/' . $build_id);
  1130. $this->assertEqual($original['form']['#build_id_old'], $build_id, 'Original build_id was recorded');
  1131. $this->assertNotEqual($original['form']['#build_id'], $build_id, 'New build_id was generated');
  1132. $this->assert(empty($original['form']['#poisoned']), 'Original form structure was preserved');
  1133. $this->assert(empty($original['form_state']['poisoned']), 'Original form state was preserved');
  1134. }
  1135. }
  1136. /**
  1137. * Test the form storage when page caching for anonymous users is turned on.
  1138. */
  1139. class FormsFormStoragePageCacheTestCase extends DrupalWebTestCase {
  1140. protected $profile = 'testing';
  1141. public static function getInfo() {
  1142. return array(
  1143. 'name' => 'Forms using form storage on cached pages',
  1144. 'description' => 'Tests a form using form storage and makes sure validation and caching works when page caching for anonymous users is turned on.',
  1145. 'group' => 'Form API',
  1146. );
  1147. }
  1148. public function setUp() {
  1149. parent::setUp('form_test');
  1150. variable_set('cache', TRUE);
  1151. }
  1152. /**
  1153. * Return the build id of the current form.
  1154. */
  1155. protected function getFormBuildId() {
  1156. $build_id_fields = $this->xpath('//input[@name="form_build_id"]');
  1157. $this->assertEqual(count($build_id_fields), 1, 'One form build id field on the page');
  1158. return (string) $build_id_fields[0]['value'];
  1159. }
  1160. /**
  1161. * Build-id is regenerated when validating cached form.
  1162. */
  1163. public function testValidateFormStorageOnCachedPage() {
  1164. $this->drupalGet('form_test/form-storage-page-cache');
  1165. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Page was not cached.');
  1166. $this->assertText('No old build id', 'No old build id on the page');
  1167. $build_id_initial = $this->getFormBuildId();
  1168. // Trigger validation error by submitting an empty title.
  1169. $edit = array('title' => '');
  1170. $this->drupalPost(NULL, $edit, 'Save');
  1171. $this->assertText($build_id_initial, 'Old build id on the page');
  1172. $build_id_first_validation = $this->getFormBuildId();
  1173. $this->assertNotEqual($build_id_initial, $build_id_first_validation, 'Build id changes when form validation fails');
  1174. // Trigger validation error by again submitting an empty title.
  1175. $edit = array('title' => '');
  1176. $this->drupalPost(NULL, $edit, 'Save');
  1177. $this->assertText('No old build id', 'No old build id on the page');
  1178. $build_id_second_validation = $this->getFormBuildId();
  1179. $this->assertEqual($build_id_first_validation, $build_id_second_validation, 'Build id remains the same when form validation fails subsequently');
  1180. // Repeat the test sequence but this time with a page loaded from the cache.
  1181. $this->drupalGet('form_test/form-storage-page-cache');
  1182. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
  1183. $this->assertText('No old build id', 'No old build id on the page');
  1184. $build_id_from_cache_initial = $this->getFormBuildId();
  1185. $this->assertEqual($build_id_initial, $build_id_from_cache_initial, 'Build id is the same as on the first request');
  1186. // Trigger validation error by submitting an empty title.
  1187. $edit = array('title' => '');
  1188. $this->drupalPost(NULL, $edit, 'Save');
  1189. $this->assertText($build_id_initial, 'Old build id is initial build id');
  1190. $build_id_from_cache_first_validation = $this->getFormBuildId();
  1191. $this->assertNotEqual($build_id_initial, $build_id_from_cache_first_validation, 'Build id changes when form validation fails');
  1192. $this->assertNotEqual($build_id_first_validation, $build_id_from_cache_first_validation, 'Build id from first user is not reused');
  1193. // Trigger validation error by again submitting an empty title.
  1194. $edit = array('title' => '');
  1195. $this->drupalPost(NULL, $edit, 'Save');
  1196. $this->assertText('No old build id', 'No old build id on the page');
  1197. $build_id_from_cache_second_validation = $this->getFormBuildId();
  1198. $this->assertEqual($build_id_from_cache_first_validation, $build_id_from_cache_second_validation, 'Build id remains the same when form validation fails subsequently');
  1199. }
  1200. /**
  1201. * Build-id is regenerated when rebuilding cached form.
  1202. */
  1203. public function testRebuildFormStorageOnCachedPage() {
  1204. $this->drupalGet('form_test/form-storage-page-cache');
  1205. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Page was not cached.');
  1206. $this->assertText('No old build id', 'No old build id on the page');
  1207. $build_id_initial = $this->getFormBuildId();
  1208. // Trigger rebuild, should regenerate build id.
  1209. $edit = array('title' => 'something');
  1210. $this->drupalPost(NULL, $edit, 'Rebuild');
  1211. $this->assertText($build_id_initial, 'Initial build id as old build id on the page');
  1212. $build_id_first_rebuild = $this->getFormBuildId();
  1213. $this->assertNotEqual($build_id_initial, $build_id_first_rebuild, 'Build id changes on first rebuild.');
  1214. // Trigger subsequent rebuild, should regenerate the build id again.
  1215. $edit = array('title' => 'something');
  1216. $this->drupalPost(NULL, $edit, 'Rebuild');
  1217. $this->assertText($build_id_first_rebuild, 'First build id as old build id on the page');
  1218. $build_id_second_rebuild = $this->getFormBuildId();
  1219. $this->assertNotEqual($build_id_first_rebuild, $build_id_second_rebuild, 'Build id changes on second rebuild.');
  1220. }
  1221. }
  1222. /**
  1223. * Test cache_form.
  1224. */
  1225. class FormsFormCacheTestCase extends DrupalWebTestCase {
  1226. public static function getInfo() {
  1227. return array(
  1228. 'name' => 'Form caching',
  1229. 'description' => 'Tests storage and retrieval of forms from cache.',
  1230. 'group' => 'Form API',
  1231. );
  1232. }
  1233. function setUp() {
  1234. parent::setUp('form_test');
  1235. }
  1236. /**
  1237. * Tests storing and retrieving the form from cache.
  1238. */
  1239. function testCacheForm() {
  1240. $form = drupal_get_form('form_test_cache_form');
  1241. $form_state = array('foo' => 'bar', 'build_info' => array('baz'));
  1242. form_set_cache($form['#build_id'], $form, $form_state);
  1243. $cached_form_state = array();
  1244. $cached_form = form_get_cache($form['#build_id'], $cached_form_state);
  1245. $this->assertEqual($cached_form['#build_id'], $form['#build_id'], 'Form retrieved from cache_form successfully.');
  1246. $this->assertEqual($cached_form_state['foo'], 'bar', 'Data retrieved from cache_form successfully.');
  1247. }
  1248. /**
  1249. * Tests changing form_cache_expiration.
  1250. */
  1251. function testCacheFormCustomExpiration() {
  1252. variable_set('form_cache_expiration', -1 * (24 * 60 * 60));
  1253. $form = drupal_get_form('form_test_cache_form');
  1254. $form_state = array('foo' => 'bar', 'build_info' => array('baz'));
  1255. form_set_cache($form['#build_id'], $form, $form_state);
  1256. // Clear expired entries from cache_form, which should include the entry we
  1257. // just stored. Without this, the form will still be retrieved from cache.
  1258. cache_clear_all(NULL, 'cache_form');
  1259. $cached_form_state = array();
  1260. $cached_form = form_get_cache($form['#build_id'], $cached_form_state);
  1261. $this->assertNull($cached_form, 'Expired form was not returned from cache.');
  1262. $this->assertTrue(empty($cached_form_state), 'No data retrieved from cache for expired form.');
  1263. }
  1264. }
  1265. /**
  1266. * Test wrapper form callbacks.
  1267. */
  1268. class FormsFormWrapperTestCase extends DrupalWebTestCase {
  1269. public static function getInfo() {
  1270. return array(
  1271. 'name' => 'Form wrapper callback',
  1272. 'description' => 'Tests form wrapper callbacks to pass a prebuilt form to form builder functions.',
  1273. 'group' => 'Form API',
  1274. );
  1275. }
  1276. function setUp() {
  1277. parent::setUp('form_test');
  1278. }
  1279. /**
  1280. * Tests using the form in a usual way.
  1281. */
  1282. function testWrapperCallback() {
  1283. $this->drupalGet('form_test/wrapper-callback');
  1284. $this->assertText('Form wrapper callback element output.', 'The form contains form wrapper elements.');
  1285. $this->assertText('Form builder element output.', 'The form contains form builder elements.');
  1286. }
  1287. }
  1288. /**
  1289. * Test $form_state clearance.
  1290. */
  1291. class FormStateValuesCleanTestCase extends DrupalWebTestCase {
  1292. public static function getInfo() {
  1293. return array(
  1294. 'name' => 'Form state values clearance',
  1295. 'description' => 'Test proper removal of submitted form values using form_state_values_clean().',
  1296. 'group' => 'Form API',
  1297. );
  1298. }
  1299. function setUp() {
  1300. parent::setUp('form_test');
  1301. }
  1302. /**
  1303. * Tests form_state_values_clean().
  1304. */
  1305. function testFormStateValuesClean() {
  1306. $values = drupal_json_decode($this->drupalPost('form_test/form-state-values-clean', array(), t('Submit')));
  1307. // Setup the expected result.
  1308. $result = array(
  1309. 'beer' => 1000,
  1310. 'baz' => array('beer' => 2000),
  1311. );
  1312. // Verify that all internal Form API elements were removed.
  1313. $this->assertFalse(isset($values['form_id']), format_string('%element was removed.', array('%element' => 'form_id')));
  1314. $this->assertFalse(isset($values['form_token']), format_string('%element was removed.', array('%element' => 'form_token')));
  1315. $this->assertFalse(isset($values['form_build_id']), format_string('%element was removed.', array('%element' => 'form_build_id')));
  1316. $this->assertFalse(isset($values['op']), format_string('%element was removed.', array('%element' => 'op')));
  1317. // Verify that all buttons were removed.
  1318. $this->assertFalse(isset($values['foo']), format_string('%element was removed.', array('%element' => 'foo')));
  1319. $this->assertFalse(isset($values['bar']), format_string('%element was removed.', array('%element' => 'bar')));
  1320. $this->assertFalse(isset($values['baz']['foo']), format_string('%element was removed.', array('%element' => 'foo')));
  1321. $this->assertFalse(isset($values['baz']['baz']), format_string('%element was removed.', array('%element' => 'baz')));
  1322. // Verify that nested form value still exists.
  1323. $this->assertTrue(isset($values['baz']['beer']), 'Nested form value still exists.');
  1324. // Verify that actual form values equal resulting form values.
  1325. $this->assertEqual($values, $result, 'Expected form values equal actual form values.');
  1326. }
  1327. }
  1328. /**
  1329. * Tests $form_state clearance with form elements having buttons.
  1330. */
  1331. class FormStateValuesCleanAdvancedTestCase extends DrupalWebTestCase {
  1332. /**
  1333. * An image file path for uploading.
  1334. */
  1335. protected $image;
  1336. public static function getInfo() {
  1337. return array(
  1338. 'name' => 'Form state values clearance (advanced)',
  1339. 'description' => 'Test proper removal of submitted form values using form_state_values_clean() when having forms with elements containing buttons like "managed_file".',
  1340. 'group' => 'Form API',
  1341. );
  1342. }
  1343. function setUp() {
  1344. parent::setUp('form_test');
  1345. }
  1346. /**
  1347. * Tests form_state_values_clean().
  1348. */
  1349. function testFormStateValuesCleanAdvanced() {
  1350. // Get an image for uploading.
  1351. $image_files = $this->drupalGetTestFiles('image');
  1352. $this->image = current($image_files);
  1353. // Check if the physical file is there.
  1354. $this->assertTrue(is_file($this->image->uri), "The image file we're going to upload exists.");
  1355. // "Browse" for the desired file.
  1356. $edit = array('files[image]' => drupal_realpath($this->image->uri));
  1357. // Post the form.
  1358. $this->drupalPost('form_test/form-state-values-clean-advanced', $edit, t('Submit'));
  1359. // Expecting a 200 HTTP code.
  1360. $this->assertResponse(200, 'Received a 200 response for posted test file.');
  1361. $this->assertRaw(t('You WIN!'), 'Found the success message.');
  1362. }
  1363. }
  1364. /**
  1365. * Tests form rebuilding.
  1366. *
  1367. * @todo Add tests for other aspects of form rebuilding.
  1368. */
  1369. class FormsRebuildTestCase extends DrupalWebTestCase {
  1370. public static function getInfo() {
  1371. return array(
  1372. 'name' => 'Form rebuilding',
  1373. 'description' => 'Tests functionality of drupal_rebuild_form().',
  1374. 'group' => 'Form API',
  1375. );
  1376. }
  1377. function setUp() {
  1378. parent::setUp('form_test');
  1379. $this->web_user = $this->drupalCreateUser(array('access content'));
  1380. $this->drupalLogin($this->web_user);
  1381. }
  1382. /**
  1383. * Tests preservation of values.
  1384. */
  1385. function testRebuildPreservesValues() {
  1386. $edit = array(
  1387. 'checkbox_1_default_off' => TRUE,
  1388. 'checkbox_1_default_on' => FALSE,
  1389. 'text_1' => 'foo',
  1390. );
  1391. $this->drupalPost('form-test/form-rebuild-preserve-values', $edit, 'Add more');
  1392. // Verify that initial elements retained their submitted values.
  1393. $this->assertFieldChecked('edit-checkbox-1-default-off', 'A submitted checked checkbox retained its checked state during a rebuild.');
  1394. $this->assertNoFieldChecked('edit-checkbox-1-default-on', 'A submitted unchecked checkbox retained its unchecked state during a rebuild.');
  1395. $this->assertFieldById('edit-text-1', 'foo', 'A textfield retained its submitted value during a rebuild.');
  1396. // Verify that newly added elements were initialized with their default values.
  1397. $this->assertFieldChecked('edit-checkbox-2-default-on', 'A newly added checkbox was initialized with a default checked state.');
  1398. $this->assertNoFieldChecked('edit-checkbox-2-default-off', 'A newly added checkbox was initialized with a default unchecked state.');
  1399. $this->assertFieldById('edit-text-2', 'DEFAULT 2', 'A newly added textfield was initialized with its default value.');
  1400. }
  1401. /**
  1402. * Tests that a form's action is retained after an Ajax submission.
  1403. *
  1404. * The 'action' attribute of a form should not change after an Ajax submission
  1405. * followed by a non-Ajax submission, which triggers a validation error.
  1406. */
  1407. function testPreserveFormActionAfterAJAX() {
  1408. // Create a multi-valued field for 'page' nodes to use for Ajax testing.
  1409. $field_name = 'field_ajax_test';
  1410. $field = array(
  1411. 'field_name' => $field_name,
  1412. 'type' => 'text',
  1413. 'cardinality' => FIELD_CARDINALITY_UNLIMITED,
  1414. );
  1415. field_create_field($field);
  1416. $instance = array(
  1417. 'field_name' => $field_name,
  1418. 'entity_type' => 'node',
  1419. 'bundle' => 'page',
  1420. );
  1421. field_create_instance($instance);
  1422. // Log in a user who can create 'page' nodes.
  1423. $this->web_user = $this->drupalCreateUser(array('create page content'));
  1424. $this->drupalLogin($this->web_user);
  1425. // Get the form for adding a 'page' node. Submit an "add another item" Ajax
  1426. // submission and verify it worked by ensuring the updated page has two text
  1427. // field items in the field for which we just added an item.
  1428. $this->drupalGet('node/add/page');
  1429. $this->drupalPostAJAX(NULL, array(), array('field_ajax_test_add_more' => t('Add another item')), 'system/ajax', array(), array(), 'page-node-form');
  1430. $this->assert(count($this->xpath('//div[contains(@class, "field-name-field-ajax-test")]//input[@type="text"]')) == 2, 'AJAX submission succeeded.');
  1431. // Submit the form with the non-Ajax "Save" button, leaving the title field
  1432. // blank to trigger a validation error, and ensure that a validation error
  1433. // occurred, because this test is for testing what happens when a form is
  1434. // re-rendered without being re-built, which is what happens when there's
  1435. // a validation error.
  1436. $this->drupalPost(NULL, array(), t('Save'));
  1437. $this->assertText('Title field is required.', 'Non-AJAX submission correctly triggered a validation error.');
  1438. // Ensure that the form contains two items in the multi-valued field, so we
  1439. // know we're testing a form that was correctly retrieved from cache.
  1440. $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.');
  1441. // Ensure that the form's action is correct.
  1442. $forms = $this->xpath('//form[contains(@class, "node-page-form")]');
  1443. $this->assert(count($forms) == 1 && $forms[0]['action'] == url('node/add/page'), 'Re-rendered form contains the correct action value.');
  1444. }
  1445. }
  1446. /**
  1447. * Tests form redirection.
  1448. */
  1449. class FormsRedirectTestCase extends DrupalWebTestCase {
  1450. public static function getInfo() {
  1451. return array(
  1452. 'name' => 'Form redirecting',
  1453. 'description' => 'Tests functionality of drupal_redirect_form().',
  1454. 'group' => 'Form API',
  1455. );
  1456. }
  1457. function setUp() {
  1458. parent::setUp(array('form_test'));
  1459. }
  1460. /**
  1461. * Tests form redirection.
  1462. */
  1463. function testRedirect() {
  1464. $path = 'form-test/redirect';
  1465. $options = array('query' => array('foo' => 'bar'));
  1466. $options['absolute'] = TRUE;
  1467. // Test basic redirection.
  1468. $edit = array(
  1469. 'redirection' => TRUE,
  1470. 'destination' => $this->randomName(),
  1471. );
  1472. $this->drupalPost($path, $edit, t('Submit'));
  1473. $this->assertUrl($edit['destination'], array(), 'Basic redirection works.');
  1474. // Test without redirection.
  1475. $edit = array(
  1476. 'redirection' => FALSE,
  1477. );
  1478. $this->drupalPost($path, $edit, t('Submit'));
  1479. $this->assertUrl($path, array(), 'When redirect is set to FALSE, there should be no redirection.');
  1480. // Test redirection with query parameters.
  1481. $edit = array(
  1482. 'redirection' => TRUE,
  1483. 'destination' => $this->randomName(),
  1484. );
  1485. $this->drupalPost($path, $edit, t('Submit'), $options);
  1486. $this->assertUrl($edit['destination'], array(), 'Redirection with query parameters works.');
  1487. // Test without redirection but with query parameters.
  1488. $edit = array(
  1489. 'redirection' => FALSE,
  1490. );
  1491. $this->drupalPost($path, $edit, t('Submit'), $options);
  1492. $this->assertUrl($path, $options, 'When redirect is set to FALSE, there should be no redirection, and the query parameters should be passed along.');
  1493. // Test redirection back to the original path.
  1494. $edit = array(
  1495. 'redirection' => TRUE,
  1496. 'destination' => '',
  1497. );
  1498. $this->drupalPost($path, $edit, t('Submit'));
  1499. $this->assertUrl($path, array(), 'When using an empty redirection string, there should be no redirection.');
  1500. // Test redirection back to the original path with query parameters.
  1501. $edit = array(
  1502. 'redirection' => TRUE,
  1503. 'destination' => '',
  1504. );
  1505. $this->drupalPost($path, $edit, t('Submit'), $options);
  1506. $this->assertUrl($path, $options, 'When using an empty redirection string, there should be no redirection, and the query parameters should be passed along.');
  1507. }
  1508. }
  1509. /**
  1510. * Test the programmatic form submission behavior.
  1511. */
  1512. class FormsProgrammaticTestCase extends DrupalWebTestCase {
  1513. public static function getInfo() {
  1514. return array(
  1515. 'name' => 'Programmatic form submissions',
  1516. 'description' => 'Test the programmatic form submission behavior.',
  1517. 'group' => 'Form API',
  1518. );
  1519. }
  1520. function setUp() {
  1521. parent::setUp('form_test');
  1522. }
  1523. /**
  1524. * Test the programmatic form submission workflow.
  1525. */
  1526. function testSubmissionWorkflow() {
  1527. // Backup the current batch status and reset it to avoid conflicts while
  1528. // processing the dummy form submit handler.
  1529. $current_batch = $batch =& batch_get();
  1530. $batch = array();
  1531. // Test that a programmatic form submission is rejected when a required
  1532. // textfield is omitted and correctly processed when it is provided.
  1533. $this->submitForm(array(), FALSE);
  1534. $this->submitForm(array('textfield' => 'test 1'), TRUE);
  1535. $this->submitForm(array(), FALSE);
  1536. $this->submitForm(array('textfield' => 'test 2'), TRUE);
  1537. // Test that a programmatic form submission can turn on and off checkboxes
  1538. // which are, by default, checked.
  1539. $this->submitForm(array('textfield' => 'dummy value', 'checkboxes' => array(1 => 1, 2 => 2)), TRUE);
  1540. $this->submitForm(array('textfield' => 'dummy value', 'checkboxes' => array(1 => 1, 2 => NULL)), TRUE);
  1541. $this->submitForm(array('textfield' => 'dummy value', 'checkboxes' => array(1 => NULL, 2 => 2)), TRUE);
  1542. $this->submitForm(array('textfield' => 'dummy value', 'checkboxes' => array(1 => NULL, 2 => NULL)), TRUE);
  1543. // Test that a programmatic form submission can successfully submit values
  1544. // even for fields where the #access property is FALSE.
  1545. $this->submitForm(array('textfield' => 'dummy value', 'textfield_no_access' => 'test value'), TRUE);
  1546. // Test that #access is respected for programmatic form submissions when
  1547. // requested to do so.
  1548. $submitted_values = array('textfield' => 'dummy value', 'textfield_no_access' => 'test value');
  1549. $expected_values = array('textfield' => 'dummy value', 'textfield_no_access' => 'default value');
  1550. $form_state = array('programmed_bypass_access_check' => FALSE);
  1551. $this->submitForm($submitted_values, TRUE, $expected_values, $form_state);
  1552. // Test that a programmatic form submission can correctly click a button
  1553. // that limits validation errors based on user input. Since we do not
  1554. // submit any values for "textfield" here and the textfield is required, we
  1555. // only expect form validation to pass when validation is limited to a
  1556. // different field.
  1557. $this->submitForm(array('op' => 'Submit with limited validation', 'field_to_validate' => 'all'), FALSE);
  1558. $this->submitForm(array('op' => 'Submit with limited validation', 'field_to_validate' => 'textfield'), FALSE);
  1559. $this->submitForm(array('op' => 'Submit with limited validation', 'field_to_validate' => 'field_to_validate'), TRUE);
  1560. // Restore the current batch status.
  1561. $batch = $current_batch;
  1562. }
  1563. /**
  1564. * Helper function used to programmatically submit the form defined in
  1565. * form_test.module with the given values.
  1566. *
  1567. * @param $values
  1568. * An array of field values to be submitted.
  1569. * @param $valid_input
  1570. * A boolean indicating whether or not the form submission is expected to
  1571. * be valid.
  1572. * @param $expected_values
  1573. * (Optional) An array of field values that are expected to be stored by
  1574. * the form submit handler. If not set, the submitted $values are assumed
  1575. * to also be the expected stored values.
  1576. * @param $form_state
  1577. * (Optional) A keyed array containing the state of the form, to be sent in
  1578. * the call to drupal_form_submit(). The $values parameter is added to
  1579. * $form_state['values'] by default, if it is not already set.
  1580. */
  1581. private function submitForm($values, $valid_input, $expected_values = NULL, $form_state = array()) {
  1582. // Programmatically submit the given values.
  1583. $form_state += array('values' => $values);
  1584. drupal_form_submit('form_test_programmatic_form', $form_state);
  1585. // Check that the form returns an error when expected, and vice versa.
  1586. $errors = form_get_errors();
  1587. $valid_form = empty($errors);
  1588. $args = array(
  1589. '%values' => print_r($values, TRUE),
  1590. '%errors' => $valid_form ? t('None') : implode(' ', $errors),
  1591. );
  1592. $this->assertTrue($valid_input == $valid_form, format_string('Input values: %values<br/>Validation handler errors: %errors', $args));
  1593. // We check submitted values only if we have a valid input.
  1594. if ($valid_input) {
  1595. // By fetching the values from $form_state['storage'] we ensure that the
  1596. // submission handler was properly executed.
  1597. $stored_values = $form_state['storage']['programmatic_form_submit'];
  1598. if (!isset($expected_values)) {
  1599. $expected_values = $values;
  1600. }
  1601. foreach ($expected_values as $key => $value) {
  1602. $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))));
  1603. }
  1604. }
  1605. }
  1606. }
  1607. /**
  1608. * Test that FAPI correctly determines $form_state['triggering_element'].
  1609. */
  1610. class FormsTriggeringElementTestCase extends DrupalWebTestCase {
  1611. public static function getInfo() {
  1612. return array(
  1613. 'name' => 'Form triggering element determination',
  1614. 'description' => 'Test the determination of $form_state[\'triggering_element\'].',
  1615. 'group' => 'Form API',
  1616. );
  1617. }
  1618. function setUp() {
  1619. parent::setUp('form_test');
  1620. }
  1621. /**
  1622. * Test the determination of $form_state['triggering_element'] when no button
  1623. * information is included in the POST data, as is sometimes the case when
  1624. * the ENTER key is pressed in a textfield in Internet Explorer.
  1625. */
  1626. function testNoButtonInfoInPost() {
  1627. $path = 'form-test/clicked-button';
  1628. $edit = array();
  1629. $form_html_id = 'form-test-clicked-button';
  1630. // Ensure submitting a form with no buttons results in no
  1631. // $form_state['triggering_element'] and the form submit handler not
  1632. // running.
  1633. $this->drupalPost($path, $edit, NULL, array(), array(), $form_html_id);
  1634. $this->assertText('There is no clicked button.', '$form_state[\'triggering_element\'] set to NULL.');
  1635. $this->assertNoText('Submit handler for form_test_clicked_button executed.', 'Form submit handler did not execute.');
  1636. // Ensure submitting a form with one or more submit buttons results in
  1637. // $form_state['triggering_element'] being set to the first one the user has
  1638. // access to. An argument with 'r' in it indicates a restricted
  1639. // (#access=FALSE) button.
  1640. $this->drupalPost($path . '/s', $edit, NULL, array(), array(), $form_html_id);
  1641. $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to only button.');
  1642. $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');
  1643. $this->drupalPost($path . '/s/s', $edit, NULL, array(), array(), $form_html_id);
  1644. $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to first button.');
  1645. $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');
  1646. $this->drupalPost($path . '/rs/s', $edit, NULL, array(), array(), $form_html_id);
  1647. $this->assertText('The clicked button is button2.', '$form_state[\'triggering_element\'] set to first available button.');
  1648. $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');
  1649. // Ensure submitting a form with buttons of different types results in
  1650. // $form_state['triggering_element'] being set to the first button,
  1651. // regardless of type. For the FAPI 'button' type, this should result in the
  1652. // submit handler not executing. The types are 's'(ubmit), 'b'(utton), and
  1653. // 'i'(mage_button).
  1654. $this->drupalPost($path . '/s/b/i', $edit, NULL, array(), array(), $form_html_id);
  1655. $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to first button.');
  1656. $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');
  1657. $this->drupalPost($path . '/b/s/i', $edit, NULL, array(), array(), $form_html_id);
  1658. $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to first button.');
  1659. $this->assertNoText('Submit handler for form_test_clicked_button executed.', 'Form submit handler did not execute.');
  1660. $this->drupalPost($path . '/i/s/b', $edit, NULL, array(), array(), $form_html_id);
  1661. $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to first button.');
  1662. $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');
  1663. }
  1664. /**
  1665. * Test that $form_state['triggering_element'] does not get set to a button
  1666. * with #access=FALSE.
  1667. */
  1668. function testAttemptAccessControlBypass() {
  1669. $path = 'form-test/clicked-button';
  1670. $form_html_id = 'form-test-clicked-button';
  1671. // Retrieve a form where 'button1' has #access=FALSE and 'button2' doesn't.
  1672. $this->drupalGet($path . '/rs/s');
  1673. // Submit the form with 'button1=button1' in the POST data, which someone
  1674. // trying to get around security safeguards could easily do. We have to do
  1675. // a little trickery here, to work around the safeguards in drupalPost(): by
  1676. // renaming the text field that is in the form to 'button1', we can get the
  1677. // data we want into $_POST.
  1678. $elements = $this->xpath('//form[@id="' . $form_html_id . '"]//input[@name="text"]');
  1679. $elements[0]['name'] = 'button1';
  1680. $this->drupalPost(NULL, array('button1' => 'button1'), NULL, array(), array(), $form_html_id);
  1681. // Ensure that $form_state['triggering_element'] was not set to the
  1682. // restricted button. Do this with both a negative and positive assertion,
  1683. // because negative assertions alone can be brittle. See
  1684. // testNoButtonInfoInPost() for why the triggering element gets set to
  1685. // 'button2'.
  1686. $this->assertNoText('The clicked button is button1.', '$form_state[\'triggering_element\'] not set to a restricted button.');
  1687. $this->assertText('The clicked button is button2.', '$form_state[\'triggering_element\'] not set to a restricted button.');
  1688. }
  1689. }
  1690. /**
  1691. * Tests rebuilding of arbitrary forms by altering them.
  1692. */
  1693. class FormsArbitraryRebuildTestCase extends DrupalWebTestCase {
  1694. public static function getInfo() {
  1695. return array(
  1696. 'name' => 'Rebuild arbitrary forms',
  1697. 'description' => 'Tests altering forms to be rebuilt so there are multiple steps.',
  1698. 'group' => 'Form API',
  1699. );
  1700. }
  1701. function setUp() {
  1702. parent::setUp('form_test');
  1703. // Auto-create a field for testing.
  1704. $field = array(
  1705. 'field_name' => 'test_multiple',
  1706. 'type' => 'text',
  1707. 'cardinality' => -1,
  1708. 'translatable' => FALSE,
  1709. );
  1710. field_create_field($field);
  1711. $instance = array(
  1712. 'entity_type' => 'node',
  1713. 'field_name' => 'test_multiple',
  1714. 'bundle' => 'page',
  1715. 'label' => 'Test a multiple valued field',
  1716. 'widget' => array(
  1717. 'type' => 'text_textfield',
  1718. 'weight' => 0,
  1719. ),
  1720. );
  1721. field_create_instance($instance);
  1722. variable_set('user_register', USER_REGISTER_VISITORS);
  1723. }
  1724. /**
  1725. * Tests a basic rebuild with the user registration form.
  1726. */
  1727. function testUserRegistrationRebuild() {
  1728. $edit = array(
  1729. 'name' => 'foo',
  1730. 'mail' => 'bar@example.com',
  1731. );
  1732. $this->drupalPost('user/register', $edit, 'Rebuild');
  1733. $this->assertText('Form rebuilt.');
  1734. $this->assertFieldByName('name', 'foo', 'Entered user name has been kept.');
  1735. $this->assertFieldByName('mail', 'bar@example.com', 'Entered mail address has been kept.');
  1736. }
  1737. /**
  1738. * Tests a rebuild caused by a multiple value field.
  1739. */
  1740. function testUserRegistrationMultipleField() {
  1741. $edit = array(
  1742. 'name' => 'foo',
  1743. 'mail' => 'bar@example.com',
  1744. );
  1745. $this->drupalPost('user/register', $edit, t('Add another item'), array('query' => array('field' => TRUE)));
  1746. $this->assertText('Test a multiple valued field', 'Form has been rebuilt.');
  1747. $this->assertFieldByName('name', 'foo', 'Entered user name has been kept.');
  1748. $this->assertFieldByName('mail', 'bar@example.com', 'Entered mail address has been kept.');
  1749. }
  1750. }
  1751. /**
  1752. * Tests form API file inclusion.
  1753. */
  1754. class FormsFileInclusionTestCase extends DrupalWebTestCase {
  1755. public static function getInfo() {
  1756. return array(
  1757. 'name' => 'Form API file inclusion',
  1758. 'description' => 'Tests form API file inclusion.',
  1759. 'group' => 'Form API',
  1760. );
  1761. }
  1762. function setUp() {
  1763. parent::setUp('form_test');
  1764. }
  1765. /**
  1766. * Tests loading an include specified in hook_menu().
  1767. */
  1768. function testLoadMenuInclude() {
  1769. $this->drupalPostAJAX('form-test/load-include-menu', array(), array('op' => t('Save')), 'system/ajax', array(), array(), 'form-test-load-include-menu');
  1770. $this->assertText('Submit callback called.');
  1771. }
  1772. /**
  1773. * Tests loading a custom specified inlcude.
  1774. */
  1775. function testLoadCustomInclude() {
  1776. $this->drupalPost('form-test/load-include-custom', array(), t('Save'));
  1777. $this->assertText('Submit callback called.');
  1778. }
  1779. }
  1780. /**
  1781. * Tests checkbox element.
  1782. */
  1783. class FormCheckboxTestCase extends DrupalWebTestCase {
  1784. public static function getInfo() {
  1785. return array(
  1786. 'name' => 'Form API checkbox',
  1787. 'description' => 'Tests form API checkbox handling of various combinations of #default_value and #return_value.',
  1788. 'group' => 'Form API',
  1789. );
  1790. }
  1791. function setUp() {
  1792. parent::setUp('form_test');
  1793. }
  1794. function testFormCheckbox() {
  1795. // Ensure that the checked state is determined and rendered correctly for
  1796. // tricky combinations of default and return values.
  1797. foreach (array(FALSE, NULL, TRUE, 0, '0', '', 1, '1', 'foobar', '1foobar') as $default_value) {
  1798. // Only values that can be used for array indeces are supported for
  1799. // #return_value, with the exception of integer 0, which is not supported.
  1800. // @see form_process_checkbox().
  1801. foreach (array('0', '', 1, '1', 'foobar', '1foobar') as $return_value) {
  1802. $form_array = drupal_get_form('form_test_checkbox_type_juggling', $default_value, $return_value);
  1803. $form = drupal_render($form_array);
  1804. if ($default_value === TRUE) {
  1805. $checked = TRUE;
  1806. }
  1807. elseif ($return_value === '0') {
  1808. $checked = ($default_value === '0');
  1809. }
  1810. elseif ($return_value === '') {
  1811. $checked = ($default_value === '');
  1812. }
  1813. elseif ($return_value === 1 || $return_value === '1') {
  1814. $checked = ($default_value === 1 || $default_value === '1');
  1815. }
  1816. elseif ($return_value === 'foobar') {
  1817. $checked = ($default_value === 'foobar');
  1818. }
  1819. elseif ($return_value === '1foobar') {
  1820. $checked = ($default_value === '1foobar');
  1821. }
  1822. $checked_in_html = strpos($form, 'checked') !== FALSE;
  1823. $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)));
  1824. $this->assertIdentical($checked, $checked_in_html, $message);
  1825. }
  1826. }
  1827. // Ensure that $form_state['values'] is populated correctly for a checkboxes
  1828. // group that includes a 0-indexed array of options.
  1829. $results = json_decode($this->drupalPost('form-test/checkboxes-zero', array(), 'Save'));
  1830. $this->assertIdentical($results->checkbox_off, array(0, 0, 0), 'All three in checkbox_off are zeroes: off.');
  1831. $this->assertIdentical($results->checkbox_zero_default, array('0', 0, 0), 'The first choice is on in checkbox_zero_default');
  1832. $this->assertIdentical($results->checkbox_string_zero_default, array('0', 0, 0), 'The first choice is on in checkbox_string_zero_default');
  1833. $edit = array('checkbox_off[0]' => '0');
  1834. $results = json_decode($this->drupalPost('form-test/checkboxes-zero', $edit, 'Save'));
  1835. $this->assertIdentical($results->checkbox_off, array('0', 0, 0), 'The first choice is on in checkbox_off but the rest is not');
  1836. // Ensure that each checkbox is rendered correctly for a checkboxes group
  1837. // that includes a 0-indexed array of options.
  1838. $this->drupalPost('form-test/checkboxes-zero/0', array(), 'Save');
  1839. $checkboxes = $this->xpath('//input[@type="checkbox"]');
  1840. foreach ($checkboxes as $checkbox) {
  1841. $checked = isset($checkbox['checked']);
  1842. $name = (string) $checkbox['name'];
  1843. $this->assertIdentical($checked, $name == 'checkbox_zero_default[0]' || $name == 'checkbox_string_zero_default[0]', format_string('Checkbox %name correctly checked', array('%name' => $name)));
  1844. }
  1845. $edit = array('checkbox_off[0]' => '0');
  1846. $this->drupalPost('form-test/checkboxes-zero/0', $edit, 'Save');
  1847. $checkboxes = $this->xpath('//input[@type="checkbox"]');
  1848. foreach ($checkboxes as $checkbox) {
  1849. $checked = isset($checkbox['checked']);
  1850. $name = (string) $checkbox['name'];
  1851. $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)));
  1852. }
  1853. }
  1854. }
  1855. /**
  1856. * Tests uniqueness of generated HTML IDs.
  1857. */
  1858. class HTMLIdTestCase extends DrupalWebTestCase {
  1859. public static function getInfo() {
  1860. return array(
  1861. 'name' => 'Unique HTML IDs',
  1862. 'description' => 'Tests functionality of drupal_html_id().',
  1863. 'group' => 'Form API',
  1864. );
  1865. }
  1866. function setUp() {
  1867. parent::setUp('form_test');
  1868. }
  1869. /**
  1870. * Tests that HTML IDs do not get duplicated when form validation fails.
  1871. */
  1872. function testHTMLId() {
  1873. $this->drupalGet('form-test/double-form');
  1874. $this->assertNoDuplicateIds('There are no duplicate IDs');
  1875. // Submit second form with empty title.
  1876. $edit = array();
  1877. $this->drupalPost(NULL, $edit, 'Save', array(), array(), 'form-test-html-id--2');
  1878. $this->assertNoDuplicateIds('There are no duplicate IDs');
  1879. }
  1880. }
  1881. /**
  1882. * Tests for form textarea.
  1883. */
  1884. class FormTextareaTestCase extends DrupalUnitTestCase {
  1885. public static function getInfo() {
  1886. return array(
  1887. 'name' => 'Form textarea',
  1888. 'description' => 'Tests form textarea related functions.',
  1889. 'group' => 'Form API',
  1890. );
  1891. }
  1892. /**
  1893. * Tests that textarea value is properly set.
  1894. */
  1895. public function testValueCallback() {
  1896. $element = array();
  1897. $form_state = array();
  1898. $test_cases = array(
  1899. array(NULL, FALSE),
  1900. array(NULL, NULL),
  1901. array('', array('test')),
  1902. array('test', 'test'),
  1903. array('123', 123),
  1904. );
  1905. foreach ($test_cases as $test_case) {
  1906. list($expected, $input) = $test_case;
  1907. $this->assertIdentical($expected, form_type_textarea_value($element, $input, $form_state));
  1908. }
  1909. }
  1910. }