form.test 91 KB

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