form.test 87 KB

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