form.test 75 KB

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