form.test 97 KB

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