form.test 69.6 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Unit tests for the Drupal Form API.
 */

class FormsTestCase extends DrupalWebTestCase {

10
  public static function getInfo() {
11
    return array(
12 13
      'name' => 'Form element validation',
      'description' => 'Tests various form element validation mechanisms.',
14
      'group' => 'Form API',
15 16 17
    );
  }

18 19 20 21
  function setUp() {
    parent::setUp('form_test');
  }

22 23 24
  /**
   * Check several empty values for required forms elements.
   *
25 26 27
   * Carriage returns, tabs, spaces, and unchecked checkbox elements are not
   * valid content for a required field.
   *
28 29 30 31
   * If the form field is found in form_get_errors() then the test pass.
   */
  function testRequiredFields() {
    // Originates from http://drupal.org/node/117748
32
    // Sets of empty strings and arrays.
33 34
    $empty_strings = array('""' => "", '"\n"' => "\n", '" "' => " ", '"\t"' => "\t", '" \n\t "' => " \n\t ", '"\n\n\n\n\n"' => "\n\n\n\n\n");
    $empty_arrays = array('array()' => array());
35
    $empty_checkbox = array(NULL);
36

37
    $elements['textfield']['element'] = array('#title' => $this->randomName(), '#type' => 'textfield');
38 39
    $elements['textfield']['empty_values'] = $empty_strings;

40 41 42
    $elements['telephone']['element'] = array('#title' => $this->randomName(), '#type' => 'tel');
    $elements['telephone']['empty_values'] = $empty_strings;

43
    $elements['password']['element'] = array('#title' => $this->randomName(), '#type' => 'password');
44 45
    $elements['password']['empty_values'] = $empty_strings;

46
    $elements['password_confirm']['element'] = array('#title' => $this->randomName(), '#type' => 'password_confirm');
47 48 49 50
    // Provide empty values for both password fields.
    foreach ($empty_strings as $key => $value) {
      $elements['password_confirm']['empty_values'][$key] = array('pass1' => $value, 'pass2' => $value);
    }
51

52
    $elements['textarea']['element'] = array('#title' => $this->randomName(), '#type' => 'textarea');
53 54
    $elements['textarea']['empty_values'] = $empty_strings;

55
    $elements['radios']['element'] = array('#title' => $this->randomName(), '#type' => 'radios', '#options' => array('' => t('None'), $this->randomName(), $this->randomName(), $this->randomName()));
56 57
    $elements['radios']['empty_values'] = $empty_arrays;

58 59 60
    $elements['checkbox']['element'] = array('#title' => $this->randomName(), '#type' => 'checkbox', '#required' => TRUE, '#title' => $this->randomName());
    $elements['checkbox']['empty_values'] = $empty_checkbox;

61
    $elements['checkboxes']['element'] = array('#title' => $this->randomName(), '#type' => 'checkboxes', '#options' => array($this->randomName(), $this->randomName(), $this->randomName()));
62 63
    $elements['checkboxes']['empty_values'] = $empty_arrays;

64
    $elements['select']['element'] = array('#title' => $this->randomName(), '#type' => 'select', '#options' => array('' => t('None'), $this->randomName(), $this->randomName(), $this->randomName()));
65 66
    $elements['select']['empty_values'] = $empty_strings;

67
    $elements['file']['element'] = array('#title' => $this->randomName(), '#type' => 'file');
68 69
    $elements['file']['empty_values'] = $empty_strings;

70
    // Regular expression to find the expected marker on required elements.
71
    $required_marker_preg = '@<label.*<abbr class="form-required" title="This field is required\.">\*</abbr></label>@';
72

73
    // Go through all the elements and all the empty values for them.
74 75
    foreach ($elements as $type => $data) {
      foreach ($data['empty_values'] as $key => $empty) {
76 77
        foreach (array(TRUE, FALSE) as $required) {
          $form_id = $this->randomName();
78 79
          $form = array();
          $form_state = form_state_defaults();
80 81 82 83 84
          form_clear_error();
          $form['op'] = array('#type' => 'submit', '#value' => t('Submit'));
          $element = $data['element']['#title'];
          $form[$element] = $data['element'];
          $form[$element]['#required'] = $required;
85
          $form_state['input'][$element] = $empty;
86 87 88 89 90
          $form_state['input']['form_id'] = $form_id;
          $form_state['method'] = 'post';
          drupal_prepare_form($form_id, $form, $form_state);
          drupal_process_form($form_id, $form, $form_state);
          $errors = form_get_errors();
91 92 93 94 95
          // Form elements of type 'radios' throw all sorts of PHP notices
          // when you try to render them like this, so we ignore those for
          // testing the required marker.
          // @todo Fix this work-around (http://drupal.org/node/588438).
          $form_output = ($type == 'radios') ? '' : drupal_render($form);
96 97 98
          if ($required) {
            // Make sure we have a form error for this element.
            $this->assertTrue(isset($errors[$element]), "Check empty($key) '$type' field '$element'");
99 100 101 102
            if (!empty($form_output)) {
              // Make sure the form element is marked as required.
              $this->assertTrue(preg_match($required_marker_preg, $form_output), "Required '$type' field is marked as required");
            }
103 104
          }
          else {
105 106 107 108 109 110 111 112 113 114 115 116 117 118
            if (!empty($form_output)) {
              // Make sure the form element is *not* marked as required.
              $this->assertFalse(preg_match($required_marker_preg, $form_output), "Optional '$type' field is not marked as required");
            }
            if ($type == 'select') {
              // Select elements are going to have validation errors with empty
              // input, since those are illegal choices. Just make sure the
              // error is not "field is required".
              $this->assertTrue((empty($errors[$element]) || strpos('field is required', $errors[$element]) === FALSE), "Optional '$type' field '$element' is not treated as a required element");
            }
            else {
              // Make sure there is *no* form error for this element.
              $this->assertTrue(empty($errors[$element]), "Optional '$type' field '$element' has no errors with empty input");
            }
119 120
          }
        }
121 122 123 124 125
      }
    }
    // Clear the expected form error messages so they don't appear as exceptions.
    drupal_get_messages();
  }
126 127

  /**
128 129
   * Test default value handling for checkboxes.
   *
130
   * @see _form_test_checkbox()
131
   */
132 133
  function testCheckboxProcessing() {
    // First, try to submit without the required checkbox.
134
    $edit = array();
135
    $this->drupalPost('form-test/checkbox', $edit, t('Submit'));
136
    $this->assertRaw(t('!name field is required.', array('!name' => 'required_checkbox')), t('A required checkbox is actually mandatory'));
137 138

    // Now try to submit the form correctly.
139
    $values = drupal_json_decode($this->drupalPost(NULL, array('required_checkbox' => 1), t('Submit')));
140 141
    $expected_values = array(
      'disabled_checkbox_on' => 'disabled_checkbox_on',
142
      'disabled_checkbox_off' => '',
143
      'checkbox_on' => 'checkbox_on',
144
      'checkbox_off' => '',
145
      'zero_checkbox_on' => '0',
146
      'zero_checkbox_off' => '',
147 148
    );
    foreach ($expected_values as $widget => $expected_value) {
149 150 151 152 153
      $this->assertEqual($values[$widget], $expected_value, t('Checkbox %widget returns expected value (expected: %expected, got: %value)', array(
        '%widget' => var_export($widget, TRUE),
        '%expected' => var_export($expected_value, TRUE),
        '%value' => var_export($values[$widget], TRUE),
      )));
154
    }
155
  }
156

157 158 159 160 161 162 163 164 165 166 167 168
  /**
   * Tests validation of #type 'select' elements.
   */
  function testSelect() {
    $form = $form_state = array();
    $form = form_test_select($form, $form_state);
    $error = '!name field is required.';
    $this->drupalGet('form-test/select');

    // Posting without any values should throw validation errors.
    $this->drupalPost(NULL, array(), 'Submit');
    $this->assertNoText(t($error, array('!name' => $form['select']['#title'])));
169 170
    $this->assertNoText(t($error, array('!name' => $form['select_required']['#title'])));
    $this->assertNoText(t($error, array('!name' => $form['select_optional']['#title'])));
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
    $this->assertNoText(t($error, array('!name' => $form['empty_value']['#title'])));
    $this->assertNoText(t($error, array('!name' => $form['empty_value_one']['#title'])));
    $this->assertText(t($error, array('!name' => $form['no_default']['#title'])));
    $this->assertNoText(t($error, array('!name' => $form['no_default_optional']['#title'])));
    $this->assertText(t($error, array('!name' => $form['no_default_empty_option']['#title'])));
    $this->assertNoText(t($error, array('!name' => $form['no_default_empty_option_optional']['#title'])));
    $this->assertText(t($error, array('!name' => $form['no_default_empty_value']['#title'])));
    $this->assertText(t($error, array('!name' => $form['no_default_empty_value_one']['#title'])));
    $this->assertNoText(t($error, array('!name' => $form['no_default_empty_value_optional']['#title'])));
    $this->assertNoText(t($error, array('!name' => $form['multiple']['#title'])));
    $this->assertNoText(t($error, array('!name' => $form['multiple_no_default']['#title'])));
    $this->assertText(t($error, array('!name' => $form['multiple_no_default_required']['#title'])));

    // Post values for required fields.
    $edit = array(
      'no_default' => 'three',
      'no_default_empty_option' => 'three',
      'no_default_empty_value' => 'three',
      'no_default_empty_value_one' => 'three',
      'multiple_no_default_required[]' => 'three',
    );
    $this->drupalPost(NULL, $edit, 'Submit');
    $values = drupal_json_decode($this->drupalGetContent());

    // Verify expected values.
    $expected = array(
      'select' => 'one',
      'empty_value' => 'one',
      'empty_value_one' => 'one',
      'no_default' => 'three',
201 202
      'no_default_optional' => 'one',
      'no_default_optional_empty_value' => '',
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
      'no_default_empty_option' => 'three',
      'no_default_empty_option_optional' => '',
      'no_default_empty_value' => 'three',
      'no_default_empty_value_one' => 'three',
      'no_default_empty_value_optional' => 0,
      'multiple' => array('two' => 'two'),
      'multiple_no_default' => array(),
      'multiple_no_default_required' => array('three' => 'three'),
    );
    foreach ($expected as $key => $value) {
      $this->assertIdentical($values[$key], $value, t('@name: @actual is equal to @expected.', array(
        '@name' => $key,
        '@actual' => var_export($values[$key], TRUE),
        '@expected' => var_export($value, TRUE),
      )));
    }
  }

221 222 223
  /**
   * Test handling of disabled elements.
   *
224
   * @see _form_test_disabled_elements()
225 226
   */
  function testDisabledElements() {
227
    // Get the raw form in its original state.
228 229 230
    $form_state = array();
    $form = _form_test_disabled_elements(array(), $form_state);

231 232 233
    // Build a submission that tries to hijack the form by submitting input for
    // elements that are disabled.
    $edit = array();
234
    foreach (element_children($form) as $key) {
235 236 237 238 239 240 241 242 243 244 245
      if (isset($form[$key]['#test_hijack_value'])) {
        if (is_array($form[$key]['#test_hijack_value'])) {
          foreach ($form[$key]['#test_hijack_value'] as $subkey => $value) {
            $edit[$key . '[' . $subkey . ']'] = $value;
          }
        }
        else {
          $edit[$key] = $form[$key]['#test_hijack_value'];
        }
      }
    }
246

247 248 249 250 251 252 253 254 255
    // Submit the form with no input, as the browser does for disabled elements,
    // and fetch the $form_state['values'] that is passed to the submit handler.
    $this->drupalPost('form-test/disabled-elements', array(), t('Submit'));
    $returned_values['normal'] = drupal_json_decode($this->content);

    // Do the same with input, as could happen if JavaScript un-disables an
    // element. drupalPost() emulates a browser by not submitting input for
    // disabled elements, so we need to un-disable those elements first.
    $this->drupalGet('form-test/disabled-elements');
256
    $disabled_elements = array();
257
    foreach ($this->xpath('//*[@disabled]') as $element) {
258
      $disabled_elements[] = (string) $element['name'];
259 260
      unset($element['disabled']);
    }
261 262 263

    // All the elements should be marked as disabled, including the ones below
    // the disabled container.
264
    $this->assertEqual(count($disabled_elements), 35, 'The correct elements have the disabled property in the HTML code.');
265

266 267 268 269 270 271
    $this->drupalPost(NULL, $edit, t('Submit'));
    $returned_values['hijacked'] = drupal_json_decode($this->content);

    // Ensure that the returned values match the form's default values in both
    // cases.
    foreach ($returned_values as $type => $values) {
272 273 274
      $this->assertFormValuesDefault($values, $form);
    }
  }
275

276 277 278 279 280 281
  /**
   * Assert that the values submitted to a form matches the default values of the elements.
   */
  function assertFormValuesDefault($values, $form) {
    foreach (element_children($form) as $key) {
      if (isset($form[$key]['#default_value'])) {
282 283 284 285 286 287
        if (isset($form[$key]['#expected_value'])) {
          $expected_value = $form[$key]['#expected_value'];
        }
        else {
          $expected_value = $form[$key]['#default_value'];
        }
288 289 290 291

        if ($key == 'checkboxes_multiple') {
          // Checkboxes values are not filtered out.
          $values[$key] = array_filter($values[$key]);
292
        }
293
        $this->assertIdentical($expected_value, $values[$key], t('Default value for %type: expected %expected, returned %returned.', array('%type' => $key, '%expected' => var_export($expected_value, TRUE), '%returned' => var_export($values[$key], TRUE))));
294
      }
295 296 297

      // Recurse children.
      $this->assertFormValuesDefault($values, $form[$key]);
298 299
    }
  }
300

301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
  /**
   * Verify markup for disabled form elements.
   *
   * @see _form_test_disabled_elements()
   */
  function testDisabledMarkup() {
    $this->drupalGet('form-test/disabled-elements');
    $form_state = array();
    $form = _form_test_disabled_elements(array(), $form_state);
    $type_map = array(
      'textarea' => 'textarea',
      'select' => 'select',
      'weight' => 'select',
      'date' => 'select',
    );

    foreach ($form as $name => $item) {
      // Skip special #types.
      if (!isset($item['#type']) || in_array($item['#type'], array('hidden', 'text_format'))) {
        continue;
      }
      // Setup XPath and CSS class depending on #type.
      if (in_array($item['#type'], array('image_button', 'button', 'submit'))) {
        $path = "//!type[contains(@class, :div-class) and @value=:value]";
        $class = 'form-button-disabled';
      }
      else {
        // starts-with() required for checkboxes.
        $path = "//div[contains(@class, :div-class)]/descendant::!type[starts-with(@name, :name)]";
        $class = 'form-disabled';
      }
      // Replace DOM element name in $path according to #type.
      $type = 'input';
      if (isset($type_map[$item['#type']])) {
        $type = $type_map[$item['#type']];
      }
      $path = strtr($path, array('!type' => $type));
      // Verify that the element exists.
      $element = $this->xpath($path, array(
        ':name' => check_plain($name),
        ':div-class' => $class,
        ':value' => isset($item['#value']) ? $item['#value'] : '',
      ));
344
      $this->assertTrue(isset($element[0]), t('Disabled form element class found for #type %type.', array('%type' => $item['#type'])));
345 346 347 348 349 350 351
    }

    // Verify special element #type text-format.
    $element = $this->xpath('//div[contains(@class, :div-class)]/descendant::textarea[@name=:name]', array(
      ':name' => 'text_format[value]',
      ':div-class' => 'form-disabled',
    ));
352
    $this->assertTrue(isset($element[0]), t('Disabled form element class found for #type %type.', array('%type' => 'text_format[value]')));
353 354 355 356
    $element = $this->xpath('//div[contains(@class, :div-class)]/descendant::select[@name=:name]', array(
      ':name' => 'text_format[format]',
      ':div-class' => 'form-disabled',
    ));
357
    $this->assertTrue(isset($element[0]), t('Disabled form element class found for #type %type.', array('%type' => 'text_format[format]')));
358 359
  }

360 361 362 363 364 365 366 367 368 369
  /**
   * Test Form API protections against input forgery.
   *
   * @see _form_test_input_forgery()
   */
  function testInputForgery() {
    $this->drupalGet('form-test/input-forgery');
    $checkbox = $this->xpath('//input[@name="checkboxes[two]"]');
    $checkbox[0]['value'] = 'FORGERY';
    $this->drupalPost(NULL, array('checkboxes[one]' => TRUE, 'checkboxes[two]' => TRUE), t('Submit'));
370
    $this->assertText('An illegal choice has been detected.', t('Input forgery was detected.'));
371
  }
372 373
}

374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
/**
 * Tests building and processing of core form elements.
 */
class FormElementTestCase extends DrupalWebTestCase {
  protected $profile = 'testing';

  public static function getInfo() {
    return array(
      'name' => 'Element processing',
      'description' => 'Tests building and processing of core form elements.',
      'group' => 'Form API',
    );
  }

  function setUp() {
    parent::setUp(array('form_test'));
  }

392
  /**
393
   * Tests placeholder text for elements that support placeholders.
394 395 396 397
   */
  function testPlaceHolderText() {
    $this->drupalGet('form-test/placeholder-text');
    $expected = 'placeholder-text';
398
    // Test to make sure non-textarea elements have the proper placeholder text.
399
    foreach (array('textfield', 'tel', 'password', 'email') as $type) {
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
      $element = $this->xpath('//input[@id=:id and @placeholder=:expected]', array(
        ':id' => 'edit-' . $type,
        ':expected' => $expected,
      ));
      $this->assertTrue(!empty($element), t('Placeholder text placed in @type.', array('@type' => $type)));
    }

    // Test to make sure textarea has the proper placeholder text.
    $element = $this->xpath('//textarea[@id=:id and @placeholder=:expected]', array(
      ':id' => 'edit-textarea',
      ':expected' => $expected,
    ));
    $this->assertTrue(!empty($element), t('Placeholder text placed in textarea.'));
  }

415 416 417 418 419 420 421 422 423
  /**
   * Tests expansion of #options for #type checkboxes and radios.
   */
  function testOptions() {
    $this->drupalGet('form-test/checkboxes-radios');

    // Verify that all options appear in their defined order.
    foreach (array('checkbox', 'radio') as $type) {
      $elements = $this->xpath('//input[@type=:type]', array(':type' => $type));
424
      $expected_values = array('0', 'foo', '1', 'bar', '>');
425 426 427 428 429 430 431 432 433 434 435 436 437
      foreach ($elements as $element) {
        $expected = array_shift($expected_values);
        $this->assertIdentical((string) $element['value'], $expected);
      }
    }

    // Enable customized option sub-elements.
    $this->drupalGet('form-test/checkboxes-radios/customize');

    // Verify that all options appear in their defined order, taking a custom
    // #weight into account.
    foreach (array('checkbox', 'radio') as $type) {
      $elements = $this->xpath('//input[@type=:type]', array(':type' => $type));
438
      $expected_values = array('0', 'foo', 'bar', '>', '1');
439 440 441 442 443 444 445
      foreach ($elements as $element) {
        $expected = array_shift($expected_values);
        $this->assertIdentical((string) $element['value'], $expected);
      }
    }
    // Verify that custom #description properties are output.
    foreach (array('checkboxes', 'radios') as $type) {
446 447
      $elements = $this->xpath('//input[@id=:id]/following-sibling::div[@class=:class]', array(
        ':id' => 'edit-' . $type . '-foo',
448 449 450 451 452 453 454 455 456
        ':class' => 'description',
      ));
      $this->assertTrue(count($elements), t('Custom %type option description found.', array(
        '%type' => $type,
      )));
    }
  }
}

457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
/**
 * Test form alter hooks.
 */
class FormAlterTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Form alter hooks',
      'description' => 'Tests hook_form_alter() and hook_form_FORM_ID_alter().',
      'group' => 'Form API',
    );
  }

  function setUp() {
    parent::setUp('form_test');
  }

  /**
   * Tests execution order of hook_form_alter() and hook_form_FORM_ID_alter().
   */
  function testExecutionOrder() {
    $this->drupalGet('form-test/alter');
    // Ensure that the order is first by module, then for a given module, the
    // id-specific one after the generic one.
    $expected = array(
      'block_form_form_test_alter_form_alter() executed.',
      'form_test_form_alter() executed.',
      'form_test_form_form_test_alter_form_alter() executed.',
      'system_form_form_test_alter_form_alter() executed.',
    );
    $content = preg_replace('/\s+/', ' ', filter_xss($this->content, array()));
487
    $this->assert(strpos($content, implode(' ', $expected)) !== FALSE, t('Form alter hooks executed in the expected order.'));
488 489 490
  }
}

491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
/**
 * Test form validation handlers.
 */
class FormValidationTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Form validation handlers',
      'description' => 'Tests form processing and alteration via form validation handlers.',
      'group' => 'Form API',
    );
  }

  function setUp() {
    parent::setUp('form_test');
  }

  /**
   * Tests form alterations by #element_validate, #validate, and form_set_value().
   */
  function testValidate() {
    $this->drupalGet('form-test/validate');
    // Verify that #element_validate handlers can alter the form and submitted
    // form values.
    $edit = array(
      'name' => 'element_validate',
    );
    $this->drupalPost(NULL, $edit, 'Save');
518 519
    $this->assertFieldByName('name', '#value changed by #element_validate', t('Form element #value was altered.'));
    $this->assertText('Name value: value changed by form_set_value() in #element_validate', t('Form element value in $form_state was altered.'));
520 521 522 523 524 525 526

    // Verify that #validate handlers can alter the form and submitted
    // form values.
    $edit = array(
      'name' => 'validate',
    );
    $this->drupalPost(NULL, $edit, 'Save');
527 528
    $this->assertFieldByName('name', '#value changed by #validate', t('Form element #value was altered.'));
    $this->assertText('Name value: value changed by form_set_value() in #validate', t('Form element value in $form_state was altered.'));
529 530 531 532 533 534 535 536

    // Verify that #element_validate handlers can make form elements
    // inaccessible, but values persist.
    $edit = array(
      'name' => 'element_validate_access',
    );
    $this->drupalPost(NULL, $edit, 'Save');
    $this->assertNoFieldByName('name', t('Form element was hidden.'));
537
    $this->assertText('Name value: element_validate_access', t('Value for inaccessible form element exists.'));
538 539 540 541

    // Verify that value for inaccessible form element persists.
    $this->drupalPost(NULL, array(), 'Save');
    $this->assertNoFieldByName('name', t('Form element was hidden.'));
542
    $this->assertText('Name value: element_validate_access', t('Value for inaccessible form element exists.'));
543
  }
544 545 546 547 548

  /**
   * Tests partial form validation through #limit_validation_errors.
   */
  function testValidateLimitErrors() {
549
    $edit = array(
550
      'test' => 'invalid',
551 552 553
      'test_numeric_index[0]' => 'invalid',
      'test_substring[foo]' => 'invalid',
    );
554 555
    $path = 'form-test/limit-validation-errors';

556 557 558 559
    // Submit the form by pressing the 'Partial validate' button (uses
    // #limit_validation_errors) and ensure that the title field is not
    // validated, but the #element_validate handler for the 'test' field
    // is triggered.
560 561 562
    $this->drupalPost($path, $edit, t('Partial validate'));
    $this->assertNoText(t('!name field is required.', array('!name' => 'Title')));
    $this->assertText('Test element is invalid');
563 564 565 566 567 568 569 570 571 572 573 574

    // Edge case of #limit_validation_errors containing numeric indexes: same
    // thing with the 'Partial validate (numeric index)' button and the
    // 'test_numeric_index' field.
    $this->drupalPost($path, $edit, t('Partial validate (numeric index)'));
    $this->assertNoText(t('!name field is required.', array('!name' => 'Title')));
    $this->assertText('Test (numeric index) element is invalid');

    // Ensure something like 'foobar' isn't considered "inside" 'foo'.
    $this->drupalPost($path, $edit, t('Partial validate (substring)'));
    $this->assertNoText(t('!name field is required.', array('!name' => 'Title')));
    $this->assertText('Test (substring) foo element is invalid');
575

576 577 578 579
    // Ensure not validated values are not available to submit handlers.
    $this->drupalPost($path, array('title' => '', 'test' => 'valid'), t('Partial validate'));
    $this->assertText('Only validated values appear in the form values.');

580 581 582 583 584 585
    // Now test full form validation and ensure that the #element_validate
    // handler is still triggered.
    $this->drupalPost($path, $edit, t('Full validate'));
    $this->assertText(t('!name field is required.', array('!name' => 'Title')));
    $this->assertText('Test element is invalid');
  }
586 587
}

588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
/**
 * Test form element labels, required markers and associated output.
 */
class FormsElementsLabelsTestCase extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Form element and label output test',
      'description' => 'Test form element labels, required markers and associated output.',
      'group' => 'Form API',
    );
  }

  function setUp() {
    parent::setUp('form_test');
  }

  /**
   * Test form elements, labels, title attibutes and required marks output
   * correctly and have the correct label option class if needed.
   */
  function testFormLabels() {
    $this->drupalGet('form_test/form-labels');

    // Check that the checkbox/radio processing is not interfering with
    // basic placement.
    $elements = $this->xpath('//input[@id="edit-form-checkboxes-test-third-checkbox"]/following-sibling::label[@for="edit-form-checkboxes-test-third-checkbox" and @class="option"]');
615
    $this->assertTrue(isset($elements[0]), t("Label follows field and label option class correct for regular checkboxes."));
616

617 618 619 620
    // Make sure the label is rendered for checkboxes.
    $elements = $this->xpath('//input[@id="edit-form-checkboxes-test-0"]/following-sibling::label[@for="edit-form-checkboxes-test-0" and @class="option"]');
    $this->assertTrue(isset($elements[0]), t("Label 0 found checkbox."));

621
    $elements = $this->xpath('//input[@id="edit-form-radios-test-second-radio"]/following-sibling::label[@for="edit-form-radios-test-second-radio" and @class="option"]');
622
    $this->assertTrue(isset($elements[0]), t("Label follows field and label option class correct for regular radios."));
623

624 625 626 627
    // Make sure the label is rendered for radios.
    $elements = $this->xpath('//input[@id="edit-form-radios-test-0"]/following-sibling::label[@for="edit-form-radios-test-0" and @class="option"]');
    $this->assertTrue(isset($elements[0]), t("Label 0 found radios."));

628 629 630
    // Exercise various defaults for checkboxes and modifications to ensure
    // appropriate override and correct behaviour.
    $elements = $this->xpath('//input[@id="edit-form-checkbox-test"]/following-sibling::label[@for="edit-form-checkbox-test" and @class="option"]');
631
    $this->assertTrue(isset($elements[0]), t("Label follows field and label option class correct for a checkbox by default."));
632 633 634

    // Exercise various defaults for textboxes and modifications to ensure
    // appropriate override and correct behaviour.
635
    $elements = $this->xpath('//label[@for="edit-form-textfield-test-title-and-required"]/child::abbr[@class="form-required"]/parent::*/following-sibling::input[@id="edit-form-textfield-test-title-and-required"]');
636
    $this->assertTrue(isset($elements[0]), t("Label precedes textfield, with required marker inside label."));
637

638
    $elements = $this->xpath('//input[@id="edit-form-textfield-test-no-title-required"]/preceding-sibling::label[@for="edit-form-textfield-test-no-title-required"]/abbr[@class="form-required"]');
639
    $this->assertTrue(isset($elements[0]), t("Label tag with required marker precedes required textfield with no title."));
640

641
    $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"]');
642
    $this->assertTrue(isset($elements[0]), t("Label preceding field and label class is element-invisible."));
643

644
    $elements = $this->xpath('//input[@id="edit-form-textfield-test-title"]/preceding-sibling::abbr[@class="form-required"]');
645
    $this->assertFalse(isset($elements[0]), t("No required marker on non-required field."));
646 647

    $elements = $this->xpath('//input[@id="edit-form-textfield-test-title-after"]/following-sibling::label[@for="edit-form-textfield-test-title-after" and @class="option"]');
648
    $this->assertTrue(isset($elements[0]), t("Label after field and label option class correct for text field."));
649 650

    $elements = $this->xpath('//label[@for="edit-form-textfield-test-title-no-show"]');
651
    $this->assertFalse(isset($elements[0]), t("No label tag when title set not to display."));
652 653 654

    // Check #field_prefix and #field_suffix placement.
    $elements = $this->xpath('//span[@class="field-prefix"]/following-sibling::div[@id="edit-form-radios-test"]');
655
    $this->assertTrue(isset($elements[0]), t("Properly placed the #field_prefix element after the label and before the field."));
656 657

    $elements = $this->xpath('//span[@class="field-suffix"]/preceding-sibling::div[@id="edit-form-radios-test"]');
658
    $this->assertTrue(isset($elements[0]), t("Properly places the #field_suffix element immediately after the form field."));
659 660 661

    // Check #prefix and #suffix placement.
    $elements = $this->xpath('//div[@id="form-test-textfield-title-prefix"]/following-sibling::div[contains(@class, \'form-item-form-textfield-test-title\')]');
662
    $this->assertTrue(isset($elements[0]), t("Properly places the #prefix element before the form item."));
663 664

    $elements = $this->xpath('//div[@id="form-test-textfield-title-suffix"]/preceding-sibling::div[contains(@class, \'form-item-form-textfield-test-title\')]');
665
    $this->assertTrue(isset($elements[0]), t("Properly places the #suffix element before the form item."));
666 667 668
  }
}

669 670 671 672 673
/**
 * Test the tableselect form element for expected behavior.
 */
class FormsElementsTableSelectFunctionalTest extends DrupalWebTestCase {

674
  public static function getInfo() {
675
    return array(
676 677 678
      'name' => 'Tableselect form element type test',
      'description' => 'Test the tableselect element for expected behavior',
      'group' => 'Form API',
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
    );
  }

  function setUp() {
    parent::setUp('form_test');
  }


  /**
   * Test the display of checkboxes when #multiple is TRUE.
   */
  function testMultipleTrue() {

    $this->drupalGet('form_test/tableselect/multiple-true');

694
    $this->assertNoText(t('Empty text.'), t('Empty text should not be displayed.'));
695 696

    // Test for the presence of the Select all rows tableheader.
697
    $this->assertFieldByXPath('//th[@class="select-all"]', NULL, t('Presence of the "Select all" checkbox.'));
698 699

    $rows = array('row1', 'row2', 'row3');
700
    foreach ($rows as $row) {
701
      $this->assertFieldByXPath('//input[@type="checkbox"]', $row, t('Checkbox for value @row.', array('@row' => $row)));
702 703 704 705 706 707 708 709 710
    }
  }

  /**
   * Test the display of radios when #multiple is FALSE.
   */
  function testMultipleFalse() {
    $this->drupalGet('form_test/tableselect/multiple-false');

711
    $this->assertNoText(t('Empty text.'), t('Empty text should not be displayed.'));
712 713

    // Test for the absence of the Select all rows tableheader.
714
    $this->assertNoFieldByXPath('//th[@class="select-all"]', '', t('Absence of the "Select all" checkbox.'));
715 716

    $rows = array('row1', 'row2', 'row3');
717
    foreach ($rows as $row) {
718
      $this->assertFieldByXPath('//input[@type="radio"]', $row, t('Radio button for value @row.', array('@row' => $row)));
719 720 721 722 723 724 725 726
    }
  }

  /**
   * Test the display of the #empty text when #options is an empty array.
   */
  function testEmptyText() {
    $this->drupalGet('form_test/tableselect/empty-text');
727
    $this->assertText(t('Empty text.'), t('Empty text should be displayed.'));
728 729 730 731 732 733 734 735 736 737 738 739
  }

  /**
   * Test the submission of single and multiple values when #multiple is TRUE.
   */
  function testMultipleTrueSubmit() {

    // Test a submission with one checkbox checked.
    $edit = array();
    $edit['tableselect[row1]'] = TRUE;
    $this->drupalPost('form_test/tableselect/multiple-true', $edit, 'Submit');

740 741 742
    $this->assertText(t('Submitted: row1 = row1'), t('Checked checkbox row1'));
    $this->assertText(t('Submitted: row2 = 0'), t('Unchecked checkbox row2.'));
    $this->assertText(t('Submitted: row3 = 0'), t('Unchecked checkbox row3.'));
743 744 745 746 747 748

    // Test a submission with multiple checkboxes checked.
    $edit['tableselect[row1]'] = TRUE;
    $edit['tableselect[row3]'] = TRUE;
    $this->drupalPost('form_test/tableselect/multiple-true', $edit, 'Submit');

749 750 751
    $this->assertText(t('Submitted: row1 = row1'), t('Checked checkbox row1.'));
    $this->assertText(t('Submitted: row2 = 0'), t('Unchecked checkbox row2.'));
    $this->assertText(t('Submitted: row3 = row3'), t('Checked checkbox row3.'));
752 753 754 755 756 757 758 759 760

  }

  /**
   * Test submission of values when #multiple is FALSE.
   */
  function testMultipleFalseSubmit() {
    $edit['tableselect'] = 'row1';
    $this->drupalPost('form_test/tableselect/multiple-false', $edit, 'Submit');
761
    $this->assertText(t('Submitted: row1'), t('Selected radio button'));
762 763 764 765 766 767 768 769
  }

  /**
   * Test the #js_select property.
   */
  function testAdvancedSelect() {
    // When #multiple = TRUE a Select all checkbox should be displayed by default.
    $this->drupalGet('form_test/tableselect/advanced-select/multiple-true-default');
770
    $this->assertFieldByXPath('//th[@class="select-all"]', NULL, t('Display a "Select all" checkbox by default when #multiple is TRUE.'));
771 772 773

    // When #js_select is set to FALSE, a "Select all" checkbox should not be displayed.
    $this->drupalGet('form_test/tableselect/advanced-select/multiple-true-no-advanced-select');
774
    $this->assertNoFieldByXPath('//th[@class="select-all"]', NULL, t('Do not display a "Select all" checkbox when #js_select is FALSE.'));
775 776 777

    // A "Select all" checkbox never makes sense when #multiple = FALSE, regardless of the value of #js_select.
    $this->drupalGet('form_test/tableselect/advanced-select/multiple-false-default');
778
    $this->assertNoFieldByXPath('//th[@class="select-all"]', NULL, t('Do not display a "Select all" checkbox when #multiple is FALSE.'));
779 780

    $this->drupalGet('form_test/tableselect/advanced-select/multiple-false-advanced-select');
781
    $this->assertNoFieldByXPath('//th[@class="select-all"]', NULL, t('Do not display a "Select all" checkbox when #multiple is FALSE, even when #js_select is TRUE.'));
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
  }


  /**
   * Test the whether the option checker gives an error on invalid tableselect values for checkboxes.
   */
  function testMultipleTrueOptionchecker() {

    list($header, $options) = _form_test_tableselect_get_data();

    $form['tableselect'] = array(
      '#type' => 'tableselect',
      '#header' => $header,
      '#options' => $options,
    );

    // Test with a valid value.
799
    list($processed_form, $form_state, $errors) = $this->formSubmitHelper($form, array('tableselect' => array('row1' => 'row1')));
800
    $this->assertFalse(isset($errors['tableselect']), t('Option checker allows valid values for checkboxes.'));
801 802

    // Test with an invalid value.
803
    list($processed_form, $form_state, $errors) = $this->formSubmitHelper($form, array('tableselect' => array('non_existing_value' => 'non_existing_value')));
804
    $this->assertTrue(isset($errors['tableselect']), t('Option checker disallows invalid values for checkboxes.'));
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824

  }


  /**
   * Test the whether the option checker gives an error on invalid tableselect values for radios.
   */
  function testMultipleFalseOptionchecker() {

    list($header, $options) = _form_test_tableselect_get_data();

    $form['tableselect'] = array(
      '#type' => 'tableselect',
      '#header' => $header,
      '#options' => $options,
      '#multiple' => FALSE,
    );

    // Test with a valid value.
    list($processed_form, $form_state, $errors) = $this->formSubmitHelper($form, array('tableselect' => 'row1'));
825
    $this->assertFalse(isset($errors['tableselect']), t('Option checker allows valid values for radio buttons.'));
826 827 828

    // Test with an invalid value.
    list($processed_form, $form_state, $errors) = $this->formSubmitHelper($form, array('tableselect' => 'non_existing_value'));
829
    $this->assertTrue(isset($errors['tableselect']), t('Option checker disallows invalid values for radio buttons.'));
830 831 832 833 834 835 836 837 838 839 840 841 842 843
  }


  /**
   * Helper function for the option check test to submit a form while collecting errors.
   *
   * @param $form_element
   *   A form element to test.
   * @param $edit
   *   An array containing post data.
   *
   * @return
   *   An array containing the processed form, the form_state and any errors.
   */
844
  private function formSubmitHelper($form, $edit) {
845
    $form_id = $this->randomName();
846
    $form_state = form_state_defaults();
847 848 849

    $form['op'] = array('#type' => 'submit', '#value' => t('Submit'));

850 851
    $form_state['input'] = $edit;
    $form_state['input']['form_id'] = $form_id;
852 853 854 855 856 857 858 859 860

    drupal_prepare_form($form_id, $form, $form_state);

    drupal_process_form($form_id, $form, $form_state);

    $errors = form_get_errors();

    // Clear errors and messages.
    drupal_get_messages();
861
    form_clear_error();
862 863 864 865 866 867 868 869

    // Return the processed form together with form_state and errors
    // to allow the caller lowlevel access to the form.
    return array($form, $form_state, $errors);
  }

}

870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
/**
 * Test the vertical_tabs form element for expected behavior.
 */
class FormsElementsVerticalTabsFunctionalTest extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Vertical tabs form element type test',
      'description' => 'Test the vertical_tabs element for expected behavior',
      'group' => 'Form API',
    );
  }

  function setUp() {
    parent::setUp('form_test');
  }

  /**
   * Ensures that vertical-tabs.js is included before collapse.js.
   *
   * Otherwise, collapse.js adds "SHOW" or "HIDE" labels to the tabs.
   */
  function testJavaScriptOrdering() {
    $this->drupalGet('form_test/vertical-tabs');
894 895
    $position1 = strpos($this->content, 'core/misc/vertical-tabs.js');
    $position2 = strpos($this->content, 'core/misc/collapse.js');
896 897 898 899
    $this->assertTrue($position1 !== FALSE && $position2 !== FALSE && $position1 < $position2, t('vertical-tabs.js is included before collapse.js'));
  }
}

900 901 902 903 904 905 906 907 908 909 910
/**
 * Test the form storage on a multistep form.
 *
 * The tested form puts data into the storage during the initial form
 * construction. These tests verify that there are no duplicate form
 * constructions, with and without manual form caching activiated. Furthermore
 * when a validation error occurs, it makes sure that changed form element
 * values aren't lost due to a wrong form rebuild.
 */
class FormsFormStorageTestCase extends DrupalWebTestCase {

911
  public static function getInfo() {
912
    return array(
913 914 915
      'name'  => 'Multistep form using form storage',
      'description'  => 'Tests a multistep form using form storage and makes sure validation and caching works right.',
      'group' => 'Form API',
916 917 918 919 920
    );
  }

  function setUp() {
    parent::setUp('form_test');
921 922 923

    $this->web_user = $this->drupalCreateUser(array('access content'));
    $this->drupalLogin($this->web_user);
924 925 926 927 928 929
  }

  /**
   * Tests using the form in a usual way.
   */
  function testForm() {
930 931 932 933 934
    $this->drupalGet('form_test/form-storage');
    $this->assertText('Form constructions: 1');

    $edit = array('title' => 'new', 'value' => 'value_is_set');

935
    // Use form rebuilding triggered by a submit button.
936
    $this->drupalPost(NULL, $edit, 'Continue submit');
937
    $this->assertText('Form constructions: 2');
938 939 940 941 942 943 944
    $this->assertText('Form constructions: 3');

    // Reset the form to the values of the storage, using a form rebuild
    // triggered by button of type button.
    $this->drupalPost(NULL, array('title' => 'changed'), 'Reset');
    $this->assertFieldByName('title', 'new', 'Values have been resetted.');
    // After rebuilding, the form has been cached.
945
    $this->assertText('Form constructions: 4');
946

947
    $this->drupalPost(NULL, $edit, 'Save');
948
    $this->assertText('Form constructions: 4');
949
    $this->assertText('Title: new', t('The form storage has stored the values.'));
950 951 952
  }

  /**
953
   * Tests using the form with an activated $form_state['cache'] property.
954 955
   */
  function testFormCached() {
956 957 958 959
    $this->drupalGet('form_test/form-storage', array('query' => array('cache' => 1)));
    $this->assertText('Form constructions: 1');

    $edit = array('title' => 'new', 'value' => 'value_is_set');
960

961
    // Use form rebuilding triggered by a submit button.
962 963 964 965 966 967 968 969 970 971 972
    $this->drupalPost(NULL, $edit, 'Continue submit');
    $this->assertText('Form constructions: 2');

    // Reset the form to the values of the storage, using a form rebuild
    // triggered by button of type button.
    $this->drupalPost(NULL, array('title' => 'changed'), 'Reset');
    $this->assertFieldByName('title', 'new', 'Values have been resetted.');
    $this->assertText('Form constructions: 3');

    $this->drupalPost(NULL, $edit, 'Save');
    $this->assertText('Form constructions: 3');
973
    $this->assertText('Title: new', t('The form storage has stored the values.'));
974 975 976 977 978 979
  }

  /**
   * Tests validation when form storage is used.
   */
  function testValidation() {
980
    $this->drupalPost('form_test/form-storage', array('title' => '', 'value' => 'value_is_set'), 'Continue submit');
981
    $this->assertPattern('/value_is_set/', t('The input values have been kept.'));
982
  }
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001

  /**
   * Tests updating cached form storage during form validation.
   *
   * If form caching is enabled and a form stores data in the form storage, then
   * the form storage also has to be updated in case of a validation error in
   * the form. This test re-uses the existing form for multi-step tests, but
   * triggers a special #element_validate handler to update the form storage
   * during form validation, while another, required element in the form
   * triggers a form validation error.
   */
  function testCachedFormStorageValidation() {
    // Request the form with 'cache' query parameter to enable form caching.
    $this->drupalGet('form_test/form-storage', array('query' => array('cache' => 1)));

    // Skip step 1 of the multi-step form, since the first step copies over
    // 'title' into form storage, but we want to verify that changes in the form
    // storage are updated in the cache during form validation.
    $edit = array('title' => 'foo');
1002
    $this->drupalPost(NULL, $edit, 'Continue submit');
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012

    // In step 2, trigger a validation error for the required 'title' field, and
    // post the special 'change_title' value for the 'value' field, which
    // conditionally invokes the #element_validate handler to update the form
    // storage.
    $edit = array('title' => '', 'value' => 'change_title');
    $this->drupalPost(NULL, $edit, 'Save');

    // At this point, the form storage should contain updated values, but we do
    // not see them, because the form has not been rebuilt yet due to the
1013 1014 1015 1016
    // validation error. Post again and verify that the rebuilt form contains
    // the values of the updated form storage.
    $this->drupalPost(NULL, array('title' => 'foo', 'value' => 'bar'), 'Save');
    $this->assertText("The thing has been changed.", 'The altered form storage value was updated in cache and taken over.');
1017
  }
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030

  /**
   * Tests a form using form state without using 'storage' to pass data from the
   * constructor to a submit handler. The data has to persist even when caching
   * gets activated, what may happen when a modules alter the form and adds
   * #ajax properties.
   */
  function testFormStatePersist() {
    // Test the form one time with caching activated and one time without.
    $run_options = array(
      array(),
      array('query' => array('cache' => 1)),
    );
1031
    foreach ($run_options as $options) {
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
      $this->drupalPost('form-test/state-persist', array(), t('Submit'), $options);
      // The submit handler outputs the value in $form_state, assert it's there.
      $this->assertText('State persisted.');

      // Test it again, but first trigger a validation error, then test.
      $this->drupalPost('form-test/state-persist', array('title' => ''), t('Submit'), $options);
      $this->assertText(t('!name field is required.', array('!name' => 'title')));
      // Submit the form again triggering no validation error.
      $this->drupalPost(NULL, array('title' => 'foo'), t('Submit'), $options);
      $this->assertText('State persisted.');

      // Now post to the rebuilt form and verify it's still there afterwards.
      $this->drupalPost(NULL, array('title' => 'bar'), t('Submit'), $options);
      $this->assertText('State persisted.');
    }
  }
1048
}
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070

/**
 * Test wrapper form callbacks.
 */
class FormsFormWrapperTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Form wrapper callback',
      'description' => 'Tests form wrapper callbacks to pass a prebuilt form to form builder functions.',
      'group' => 'Form API',
    );
  }

  function setUp() {
    parent::setUp('form_test');
  }

  /**
   * Tests using the form in a usual way.
   */
  function testWrapperCallback() {
    $this->drupalGet('form_test/wrapper-callback');
1071 1072
    $this->assertText('Form wrapper callback element output.', t('The form contains form wrapper elements.'));
    $this->assertText('Form builder element output.', t('The form contains form builder elements.'));
1073 1074 1075
  }
}

1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
/**
 * Test $form_state clearance.
 */
class FormStateValuesCleanTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Form state values clearance',
      'description' => 'Test proper removal of submitted form values using form_state_values_clean().',
      'group' => 'Form API',
    );
  }

  function setUp() {
    parent::setUp('form_test');
  }

  /**
   * Tests form_state_values_clean().
   */
  function testFormStateValuesClean() {
1096
    $values = drupal_json_decode($this->drupalPost('form_test/form-state-values-clean', array(), t('Submit')));
1097 1098 1099 1100 1101 1102 1103 1104

    // Setup the expected result.
    $result = array(
      'beer' => 1000,
      'baz' => array('beer' => 2000),
    );

    // Verify that all internal Form API elements were removed.
1105 1106 1107 1108
    $this->assertFalse(isset($values['form_id']), t('%element was removed.', array('%element' => 'form_id')));
    $this->assertFalse(isset($values['form_token']), t('%element was removed.', array('%element' => 'form_token')));
    $this->assertFalse(isset($values['form_build_id']), t('%element was removed.', array('%element' => 'form_build_id')));
    $this->assertFalse(isset($values['op']), t('%element was removed.', array('%element' => 'op')));
1109 1110

    // Verify that all buttons were removed.