form.test 76 KB

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