form.test 93 KB

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