form.test 93 KB

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