form.test 70 KB

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