Projet

Général

Profil

Paste
Télécharger (93,3 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / simpletest / tests / form.test @ 01dfd3b5

1
<?php
2

    
3
/**
4
 * @file
5
 * Unit tests for the Drupal Form API.
6
 */
7

    
8
class FormsTestCase extends DrupalWebTestCase {
9

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

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

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

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

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

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

    
49
    $elements['textarea']['element'] = array('#title' => $this->randomName(), '#type' => 'textarea');
50
    $elements['textarea']['empty_values'] = $empty_strings;
51

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

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

    
58
    $elements['checkboxes']['element'] = array('#title' => $this->randomName(), '#type' => 'checkboxes', '#options' => array($this->randomName(), $this->randomName(), $this->randomName()));
59
    $elements['checkboxes']['empty_values'] = $empty_arrays;
60

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

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

    
67
    // Regular expression to find the expected marker on required elements.
68
    $required_marker_preg = '@<label.*<span class="form-required" title="This field is required\.">\*</span></label>@';
69

    
70
    // Go through all the elements and all the empty values for them.
71
    foreach ($elements as $type => $data) {
72
      foreach ($data['empty_values'] as $key => $empty) {
73
        foreach (array(TRUE, FALSE) as $required) {
74
          $form_id = $this->randomName();
75
          $form = array();
76
          $form_state = form_state_defaults();
77
          form_clear_error();
78
          $form['op'] = array('#type' => 'submit', '#value' => t('Submit'));
79
          $element = $data['element']['#title'];
80
          $form[$element] = $data['element'];
81
          $form[$element]['#required'] = $required;
82
          $form_state['input'][$element] = $empty;
83
          $form_state['input']['form_id'] = $form_id;
84
          $form_state['method'] = 'post';
85

    
86
          // The form token CSRF protection should not interfere with this test,
87
          // so we bypass it by marking this test form as programmed.
88
          $form_state['programmed'] = TRUE;
89
          drupal_prepare_form($form_id, $form, $form_state);
90
          drupal_process_form($form_id, $form, $form_state);
91
          $errors = form_get_errors();
92
          // Form elements of type 'radios' throw all sorts of PHP notices
93
          // when you try to render them like this, so we ignore those for
94
          // testing the required marker.
95
          // @todo Fix this work-around (http://drupal.org/node/588438).
96
          $form_output = ($type == 'radios') ? '' : drupal_render($form);
97
          if ($required) {
98
            // Make sure we have a form error for this element.
99
            $this->assertTrue(isset($errors[$element]), "Check empty($key) '$type' field '$element'");
100
            if (!empty($form_output)) {
101
              // Make sure the form element is marked as required.
102
              $this->assertTrue(preg_match($required_marker_preg, $form_output), "Required '$type' field is marked as required");
103
            }
104
          }
105
          else {
106
            if (!empty($form_output)) {
107
              // Make sure the form element is *not* marked as required.
108
              $this->assertFalse(preg_match($required_marker_preg, $form_output), "Optional '$type' field is not marked as required");
109
            }
110
            if ($type == 'select') {
111
              // Select elements are going to have validation errors with empty
112
              // input, since those are illegal choices. Just make sure the
113
              // error is not "field is required".
114
              $this->assertTrue((empty($errors[$element]) || strpos('field is required', $errors[$element]) === FALSE), "Optional '$type' field '$element' is not treated as a required element");
115
            }
116
            else {
117
              // Make sure there is *no* form error for this element.
118
              $this->assertTrue(empty($errors[$element]), "Optional '$type' field '$element' has no errors with empty input");
119
            }
120
          }
121
        }
122
      }
123
    }
124
    // Clear the expected form error messages so they don't appear as exceptions.
125
    drupal_get_messages();
126
  }
127

    
128
  /**
129
   * Tests validation for required checkbox, select, and radio elements.
130
   *
131
   * Submits a test form containing several types of form elements. The form
132
   * is submitted twice, first without values for required fields and then
133
   * with values. Each submission is checked for relevant error messages.
134
   *
135
   * @see form_test_validate_required_form()
136
   */
137
  function testRequiredCheckboxesRadio() {
138
    $form = $form_state = array();
139
    $form = form_test_validate_required_form($form, $form_state);
140

    
141
    // Attempt to submit the form with no required fields set.
142
    $edit = array();
143
    $this->drupalPost('form-test/validate-required', $edit, 'Submit');
144

    
145
    // The only error messages that should appear are the relevant 'required'
146
    // messages for each field.
147
    $expected = array();
148
    foreach (array('textfield', 'checkboxes', 'select', 'radios') as $key) {
149
      $expected[] = t('!name field is required.', array('!name' => $form[$key]['#title']));
150
    }
151

    
152
    // Check the page for error messages.
153
    $errors = $this->xpath('//div[contains(@class, "error")]//li');
154
    foreach ($errors as $error) {
155
      $expected_key = array_search($error[0], $expected);
156
      // If the error message is not one of the expected messages, fail.
157
      if ($expected_key === FALSE) {
158
        $this->fail(format_string("Unexpected error message: @error", array('@error' => $error[0])));
159
      }
160
      // Remove the expected message from the list once it is found.
161
      else {
162
        unset($expected[$expected_key]);
163
      }
164
    }
165

    
166
    // Fail if any expected messages were not found.
167
    foreach ($expected as $not_found) {
168
      $this->fail(format_string("Found error message: @error", array('@error' => $not_found)));
169
    }
170

    
171
    // Verify that input elements are still empty.
172
    $this->assertFieldByName('textfield', '');
173
    $this->assertNoFieldChecked('edit-checkboxes-foo');
174
    $this->assertNoFieldChecked('edit-checkboxes-bar');
175
    $this->assertOptionSelected('edit-select', '');
176
    $this->assertNoFieldChecked('edit-radios-foo');
177
    $this->assertNoFieldChecked('edit-radios-bar');
178
    $this->assertNoFieldChecked('edit-radios-optional-foo');
179
    $this->assertNoFieldChecked('edit-radios-optional-bar');
180
    $this->assertNoFieldChecked('edit-radios-optional-default-value-false-foo');
181
    $this->assertNoFieldChecked('edit-radios-optional-default-value-false-bar');
182

    
183
    // Submit again with required fields set and verify that there are no
184
    // error messages.
185
    $edit = array(
186
      'textfield' => $this->randomString(),
187
      'checkboxes[foo]' => TRUE,
188
      'select' => 'foo',
189
      'radios' => 'bar',
190
    );
191
    $this->drupalPost(NULL, $edit, 'Submit');
192
    $this->assertNoFieldByXpath('//div[contains(@class, "error")]', FALSE, 'No error message is displayed when all required fields are filled.');
193
    $this->assertRaw("The form_test_validate_required_form form was submitted successfully.", 'Validation form submitted successfully.');
194
  }
195

    
196
  /**
197
   * Tests validation for required textfield element without title.
198
   *
199
   * Submits a test form containing a textfield form elements without title.
200
   * The form is submitted twice, first without value for the required field
201
   * and then with value. Each submission is checked for relevant error
202
   * messages.
203
   *
204
   * @see form_test_validate_required_form_no_title()
205
   */
206
  function testRequiredTextfieldNoTitle() {
207
    $form = $form_state = array();
208
    $form = form_test_validate_required_form_no_title($form, $form_state);
209

    
210
    // Attempt to submit the form with no required field set.
211
    $edit = array();
212
    $this->drupalPost('form-test/validate-required-no-title', $edit, 'Submit');
213
    $this->assertNoRaw("The form_test_validate_required_form_no_title form was submitted successfully.", 'Validation form submitted successfully.');
214

    
215
    // Check the page for the error class on the textfield.
216
    $this->assertFieldByXPath('//input[contains(@class, "error")]', FALSE, 'Error input form element class found.');
217

    
218
    // Submit again with required fields set and verify that there are no
219
    // error messages.
220
    $edit = array(
221
      'textfield' => $this->randomString(),
222
    );
223
    $this->drupalPost(NULL, $edit, 'Submit');
224
    $this->assertNoFieldByXpath('//input[contains(@class, "error")]', FALSE, 'No error input form element class found.');
225
    $this->assertRaw("The form_test_validate_required_form_no_title form was submitted successfully.", 'Validation form submitted successfully.');
226
  }
227

    
228
  /**
229
   * Test default value handling for checkboxes.
230
   *
231
   * @see _form_test_checkbox()
232
   */
233
  function testCheckboxProcessing() {
234
    // First, try to submit without the required checkbox.
235
    $edit = array();
236
    $this->drupalPost('form-test/checkbox', $edit, t('Submit'));
237
    $this->assertRaw(t('!name field is required.', array('!name' => 'required_checkbox')), 'A required checkbox is actually mandatory');
238

    
239
    // Now try to submit the form correctly.
240
    $values = drupal_json_decode($this->drupalPost(NULL, array('required_checkbox' => 1), t('Submit')));
241
    $expected_values = array(
242
      'disabled_checkbox_on' => 'disabled_checkbox_on',
243
      'disabled_checkbox_off' => '',
244
      'checkbox_on' => 'checkbox_on',
245
      'checkbox_off' => '',
246
      'zero_checkbox_on' => '0',
247
      'zero_checkbox_off' => '',
248
    );
249
    foreach ($expected_values as $widget => $expected_value) {
250
      $this->assertEqual($values[$widget], $expected_value, format_string('Checkbox %widget returns expected value (expected: %expected, got: %value)', array(
251
        '%widget' => var_export($widget, TRUE),
252
        '%expected' => var_export($expected_value, TRUE),
253
        '%value' => var_export($values[$widget], TRUE),
254
      )));
255
    }
256
  }
257

    
258
  /**
259
   * Tests validation of #type 'select' elements.
260
   */
261
  function testSelect() {
262
    $form = $form_state = array();
263
    $form = form_test_select($form, $form_state);
264
    $error = '!name field is required.';
265
    $this->drupalGet('form-test/select');
266

    
267
    // Posting without any values should throw validation errors.
268
    $this->drupalPost(NULL, array(), 'Submit');
269
    $this->assertNoText(t($error, array('!name' => $form['select']['#title'])));
270
    $this->assertNoText(t($error, array('!name' => $form['select_required']['#title'])));
271
    $this->assertNoText(t($error, array('!name' => $form['select_optional']['#title'])));
272
    $this->assertNoText(t($error, array('!name' => $form['empty_value']['#title'])));
273
    $this->assertNoText(t($error, array('!name' => $form['empty_value_one']['#title'])));
274
    $this->assertText(t($error, array('!name' => $form['no_default']['#title'])));
275
    $this->assertNoText(t($error, array('!name' => $form['no_default_optional']['#title'])));
276
    $this->assertText(t($error, array('!name' => $form['no_default_empty_option']['#title'])));
277
    $this->assertNoText(t($error, array('!name' => $form['no_default_empty_option_optional']['#title'])));
278
    $this->assertText(t($error, array('!name' => $form['no_default_empty_value']['#title'])));
279
    $this->assertText(t($error, array('!name' => $form['no_default_empty_value_one']['#title'])));
280
    $this->assertNoText(t($error, array('!name' => $form['no_default_empty_value_optional']['#title'])));
281
    $this->assertNoText(t($error, array('!name' => $form['multiple']['#title'])));
282
    $this->assertNoText(t($error, array('!name' => $form['multiple_no_default']['#title'])));
283
    $this->assertText(t($error, array('!name' => $form['multiple_no_default_required']['#title'])));
284

    
285
    // Post values for required fields.
286
    $edit = array(
287
      'no_default' => 'three',
288
      'no_default_empty_option' => 'three',
289
      'no_default_empty_value' => 'three',
290
      'no_default_empty_value_one' => 'three',
291
      'multiple_no_default_required[]' => 'three',
292
    );
293
    $this->drupalPost(NULL, $edit, 'Submit');
294
    $values = drupal_json_decode($this->drupalGetContent());
295

    
296
    // Verify expected values.
297
    $expected = array(
298
      'select' => 'one',
299
      'empty_value' => 'one',
300
      'empty_value_one' => 'one',
301
      'no_default' => 'three',
302
      'no_default_optional' => 'one',
303
      'no_default_optional_empty_value' => '',
304
      'no_default_empty_option' => 'three',
305
      'no_default_empty_option_optional' => '',
306
      'no_default_empty_value' => 'three',
307
      'no_default_empty_value_one' => 'three',
308
      'no_default_empty_value_optional' => 0,
309
      'multiple' => array('two' => 'two'),
310
      'multiple_no_default' => array(),
311
      'multiple_no_default_required' => array('three' => 'three'),
312
    );
313
    foreach ($expected as $key => $value) {
314
      $this->assertIdentical($values[$key], $value, format_string('@name: @actual is equal to @expected.', array(
315
        '@name' => $key,
316
        '@actual' => var_export($values[$key], TRUE),
317
        '@expected' => var_export($value, TRUE),
318
      )));
319
    }
320
  }
321

    
322
  /**
323
   * Test handling of disabled elements.
324
   *
325
   * @see _form_test_disabled_elements()
326
   */
327
  function testDisabledElements() {
328
    // Get the raw form in its original state.
329
    $form_state = array();
330
    $form = _form_test_disabled_elements(array(), $form_state);
331

    
332
    // Build a submission that tries to hijack the form by submitting input for
333
    // elements that are disabled.
334
    $edit = array();
335
    foreach (element_children($form) as $key) {
336
      if (isset($form[$key]['#test_hijack_value'])) {
337
        if (is_array($form[$key]['#test_hijack_value'])) {
338
          foreach ($form[$key]['#test_hijack_value'] as $subkey => $value) {
339
            $edit[$key . '[' . $subkey . ']'] = $value;
340
          }
341
        }
342
        else {
343
          $edit[$key] = $form[$key]['#test_hijack_value'];
344
        }
345
      }
346
    }
347

    
348
    // Submit the form with no input, as the browser does for disabled elements,
349
    // and fetch the $form_state['values'] that is passed to the submit handler.
350
    $this->drupalPost('form-test/disabled-elements', array(), t('Submit'));
351
    $returned_values['normal'] = drupal_json_decode($this->content);
352

    
353
    // Do the same with input, as could happen if JavaScript un-disables an
354
    // element. drupalPost() emulates a browser by not submitting input for
355
    // disabled elements, so we need to un-disable those elements first.
356
    $this->drupalGet('form-test/disabled-elements');
357
    $disabled_elements = array();
358
    foreach ($this->xpath('//*[@disabled]') as $element) {
359
      $disabled_elements[] = (string) $element['name'];
360
      unset($element['disabled']);
361
    }
362

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

    
367
    $this->drupalPost(NULL, $edit, t('Submit'));
368
    $returned_values['hijacked'] = drupal_json_decode($this->content);
369

    
370
    // Ensure that the returned values match the form's default values in both
371
    // cases.
372
    foreach ($returned_values as $type => $values) {
373
      $this->assertFormValuesDefault($values, $form);
374
    }
375
  }
376

    
377
  /**
378
   * Assert that the values submitted to a form matches the default values of the elements.
379
   */
380
  function assertFormValuesDefault($values, $form) {
381
    foreach (element_children($form) as $key) {
382
      if (isset($form[$key]['#default_value'])) {
383
        if (isset($form[$key]['#expected_value'])) {
384
          $expected_value = $form[$key]['#expected_value'];
385
        }
386
        else {
387
          $expected_value = $form[$key]['#default_value'];
388
        }
389

    
390
        if ($key == 'checkboxes_multiple') {
391
          // Checkboxes values are not filtered out.
392
          $values[$key] = array_filter($values[$key]);
393
        }
394
        $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))));
395
      }
396

    
397
      // Recurse children.
398
      $this->assertFormValuesDefault($values, $form[$key]);
399
    }
400
  }
401

    
402
  /**
403
   * Verify markup for disabled form elements.
404
   *
405
   * @see _form_test_disabled_elements()
406
   */
407
  function testDisabledMarkup() {
408
    $this->drupalGet('form-test/disabled-elements');
409
    $form_state = array();
410
    $form = _form_test_disabled_elements(array(), $form_state);
411
    $type_map = array(
412
      'textarea' => 'textarea',
413
      'select' => 'select',
414
      'weight' => 'select',
415
      'date' => 'select',
416
    );
417

    
418
    foreach ($form as $name => $item) {
419
      // Skip special #types.
420
      if (!isset($item['#type']) || in_array($item['#type'], array('hidden', 'text_format'))) {
421
        continue;
422
      }
423
      // Setup XPath and CSS class depending on #type.
424
      if (in_array($item['#type'], array('image_button', 'button', 'submit'))) {
425
        $path = "//!type[contains(@class, :div-class) and @value=:value]";
426
        $class = 'form-button-disabled';
427
      }
428
      else {
429
        // starts-with() required for checkboxes.
430
        $path = "//div[contains(@class, :div-class)]/descendant::!type[starts-with(@name, :name)]";
431
        $class = 'form-disabled';
432
      }
433
      // Replace DOM element name in $path according to #type.
434
      $type = 'input';
435
      if (isset($type_map[$item['#type']])) {
436
        $type = $type_map[$item['#type']];
437
      }
438
      $path = strtr($path, array('!type' => $type));
439
      // Verify that the element exists.
440
      $element = $this->xpath($path, array(
441
        ':name' => check_plain($name),
442
        ':div-class' => $class,
443
        ':value' => isset($item['#value']) ? $item['#value'] : '',
444
      ));
445
      $this->assertTrue(isset($element[0]), format_string('Disabled form element class found for #type %type.', array('%type' => $item['#type'])));
446
    }
447

    
448
    // Verify special element #type text-format.
449
    $element = $this->xpath('//div[contains(@class, :div-class)]/descendant::textarea[@name=:name]', array(
450
      ':name' => 'text_format[value]',
451
      ':div-class' => 'form-disabled',
452
    ));
453
    $this->assertTrue(isset($element[0]), format_string('Disabled form element class found for #type %type.', array('%type' => 'text_format[value]')));
454
    $element = $this->xpath('//div[contains(@class, :div-class)]/descendant::select[@name=:name]', array(
455
      ':name' => 'text_format[format]',
456
      ':div-class' => 'form-disabled',
457
    ));
458
    $this->assertTrue(isset($element[0]), format_string('Disabled form element class found for #type %type.', array('%type' => 'text_format[format]')));
459
  }
460

    
461
  /**
462
   * Test Form API protections against input forgery.
463
   *
464
   * @see _form_test_input_forgery()
465
   */
466
  function testInputForgery() {
467
    $this->drupalGet('form-test/input-forgery');
468
    $checkbox = $this->xpath('//input[@name="checkboxes[two]"]');
469
    $checkbox[0]['value'] = 'FORGERY';
470
    $this->drupalPost(NULL, array('checkboxes[one]' => TRUE, 'checkboxes[two]' => TRUE), t('Submit'));
471
    $this->assertText('An illegal choice has been detected.', 'Input forgery was detected.');
472
  }
473

    
474
  /**
475
   * Tests that submitted values are converted to scalar strings for textfields.
476
   */
477
  public function testTextfieldStringValue() {
478
    // Check multivalued submissions.
479
    $multivalue = array('evil' => 'multivalue', 'not so' => 'good');
480
    $this->checkFormValue('textfield', $multivalue, '');
481
    $this->checkFormValue('password', $multivalue, '');
482
    $this->checkFormValue('textarea', $multivalue, '');
483
    $this->checkFormValue('machine_name', $multivalue, '');
484
    $this->checkFormValue('password_confirm', $multivalue, array('pass1' => '', 'pass2' => ''));
485
    // Check integer submissions.
486
    $integer = 5;
487
    $string = '5';
488
    $this->checkFormValue('textfield', $integer, $string);
489
    $this->checkFormValue('password', $integer, $string);
490
    $this->checkFormValue('textarea', $integer, $string);
491
    $this->checkFormValue('machine_name', $integer, $string);
492
    $this->checkFormValue('password_confirm', array('pass1' => $integer, 'pass2' => $integer), array('pass1' => $string, 'pass2' => $string));
493
    // Check that invalid array keys are ignored for password confirm elements.
494
    $this->checkFormValue('password_confirm', array('pass1' => 'test', 'pass2' => 'test', 'extra' => 'invalid'), array('pass1' => 'test', 'pass2' => 'test'));
495
  }
496

    
497
  /**
498
   * Checks that a given form input value is sanitized to the expected result.
499
   *
500
   * @param string $element_type
501
   *   The form element type. Example: textfield.
502
   * @param mixed $input_value
503
   *   The submitted user input value for the form element.
504
   * @param mixed $expected_value
505
   *   The sanitized result value in the form state after calling
506
   *   form_builder().
507
   */
508
  protected function checkFormValue($element_type, $input_value, $expected_value) {
509
    $form_id = $this->randomName();
510
    $form = array();
511
    $form_state = form_state_defaults();
512
    $form['op'] = array('#type' => 'submit', '#value' => t('Submit'));
513
    $form[$element_type] = array(
514
      '#type' => $element_type,
515
      '#title' => 'test',
516
    );
517

    
518
    $form_state['input'][$element_type] = $input_value;
519
    $form_state['input']['form_id'] = $form_id;
520
    $form_state['method'] = 'post';
521
    $form_state['values'] = array();
522
    drupal_prepare_form($form_id, $form, $form_state);
523

    
524
    // Set the CSRF token in the user-provided input.
525
    $form_state['input']['form_token'] = $form['form_token']['#default_value'];
526

    
527
    // This is the main function we want to test: it is responsible for
528
    // populating user supplied $form_state['input'] to sanitized
529
    // $form_state['values'].
530
    form_builder($form_id, $form, $form_state);
531

    
532
    $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)));
533
  }
534
}
535

    
536
/**
537
 * Tests building and processing of core form elements.
538
 */
539
class FormElementTestCase extends DrupalWebTestCase {
540
  protected $profile = 'testing';
541

    
542
  public static function getInfo() {
543
    return array(
544
      'name' => 'Element processing',
545
      'description' => 'Tests building and processing of core form elements.',
546
      'group' => 'Form API',
547
    );
548
  }
549

    
550
  function setUp() {
551
    parent::setUp(array('form_test'));
552
  }
553

    
554
  /**
555
   * Tests expansion of #options for #type checkboxes and radios.
556
   */
557
  function testOptions() {
558
    $this->drupalGet('form-test/checkboxes-radios');
559

    
560
    // Verify that all options appear in their defined order.
561
    foreach (array('checkbox', 'radio') as $type) {
562
      $elements = $this->xpath('//input[@type=:type]', array(':type' => $type));
563
      $expected_values = array('0', 'foo', '1', 'bar', '>');
564
      foreach ($elements as $element) {
565
        $expected = array_shift($expected_values);
566
        $this->assertIdentical((string) $element['value'], $expected);
567
      }
568
    }
569

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

    
573
    // Verify that all options appear in their defined order, taking a custom
574
    // #weight into account.
575
    foreach (array('checkbox', 'radio') as $type) {
576
      $elements = $this->xpath('//input[@type=:type]', array(':type' => $type));
577
      $expected_values = array('0', 'foo', 'bar', '>', '1');
578
      foreach ($elements as $element) {
579
        $expected = array_shift($expected_values);
580
        $this->assertIdentical((string) $element['value'], $expected);
581
      }
582
    }
583
    // Verify that custom #description properties are output.
584
    foreach (array('checkboxes', 'radios') as $type) {
585
      $elements = $this->xpath('//input[@id=:id]/following-sibling::div[@class=:class]', array(
586
        ':id' => 'edit-' . $type . '-foo',
587
        ':class' => 'description',
588
      ));
589
      $this->assertTrue(count($elements), format_string('Custom %type option description found.', array(
590
        '%type' => $type,
591
      )));
592
    }
593
  }
594

    
595
  /**
596
   * Tests Weight form element #default_value behavior.
597
   */
598
  public function testWeightDefaultValue() {
599
    $element = array(
600
      '#type' => 'weight',
601
      '#delta' => 10,
602
      '#default_value' => 15,
603
    );
604
    $element = form_process_weight($element);
605
    $this->assertTrue(isset($element['#options'][$element['#default_value']]), 'Default value exists in #options list');
606
  }
607
}
608

    
609
/**
610
 * Test form alter hooks.
611
 */
612
class FormAlterTestCase extends DrupalWebTestCase {
613
  public static function getInfo() {
614
    return array(
615
      'name' => 'Form alter hooks',
616
      'description' => 'Tests hook_form_alter() and hook_form_FORM_ID_alter().',
617
      'group' => 'Form API',
618
    );
619
  }
620

    
621
  function setUp() {
622
    parent::setUp('form_test');
623
  }
624

    
625
  /**
626
   * Tests execution order of hook_form_alter() and hook_form_FORM_ID_alter().
627
   */
628
  function testExecutionOrder() {
629
    $this->drupalGet('form-test/alter');
630
    // Ensure that the order is first by module, then for a given module, the
631
    // id-specific one after the generic one.
632
    $expected = array(
633
      'block_form_form_test_alter_form_alter() executed.',
634
      'form_test_form_alter() executed.',
635
      'form_test_form_form_test_alter_form_alter() executed.',
636
      'system_form_form_test_alter_form_alter() executed.',
637
    );
638
    $content = preg_replace('/\s+/', ' ', filter_xss($this->content, array()));
639
    $this->assert(strpos($content, implode(' ', $expected)) !== FALSE, 'Form alter hooks executed in the expected order.');
640
  }
641
}
642

    
643
/**
644
 * Test form validation handlers.
645
 */
646
class FormValidationTestCase extends DrupalWebTestCase {
647
  public static function getInfo() {
648
    return array(
649
      'name' => 'Form validation handlers',
650
      'description' => 'Tests form processing and alteration via form validation handlers.',
651
      'group' => 'Form API',
652
    );
653
  }
654

    
655
  function setUp() {
656
    parent::setUp('form_test');
657
  }
658

    
659
  /**
660
   * Tests form alterations by #element_validate, #validate, and form_set_value().
661
   */
662
  function testValidate() {
663
    $this->drupalGet('form-test/validate');
664
    // Verify that #element_validate handlers can alter the form and submitted
665
    // form values.
666
    $edit = array(
667
      'name' => 'element_validate',
668
    );
669
    $this->drupalPost(NULL, $edit, 'Save');
670
    $this->assertFieldByName('name', '#value changed by #element_validate', 'Form element #value was altered.');
671
    $this->assertText('Name value: value changed by form_set_value() in #element_validate', 'Form element value in $form_state was altered.');
672

    
673
    // Verify that #validate handlers can alter the form and submitted
674
    // form values.
675
    $edit = array(
676
      'name' => 'validate',
677
    );
678
    $this->drupalPost(NULL, $edit, 'Save');
679
    $this->assertFieldByName('name', '#value changed by #validate', 'Form element #value was altered.');
680
    $this->assertText('Name value: value changed by form_set_value() in #validate', 'Form element value in $form_state was altered.');
681

    
682
    // Verify that #element_validate handlers can make form elements
683
    // inaccessible, but values persist.
684
    $edit = array(
685
      'name' => 'element_validate_access',
686
    );
687
    $this->drupalPost(NULL, $edit, 'Save');
688
    $this->assertNoFieldByName('name', 'Form element was hidden.');
689
    $this->assertText('Name value: element_validate_access', 'Value for inaccessible form element exists.');
690

    
691
    // Verify that value for inaccessible form element persists.
692
    $this->drupalPost(NULL, array(), 'Save');
693
    $this->assertNoFieldByName('name', 'Form element was hidden.');
694
    $this->assertText('Name value: element_validate_access', 'Value for inaccessible form element exists.');
695

    
696
    // Verify that #validate handlers don't run if the CSRF token is invalid.
697
    $this->drupalLogin($this->drupalCreateUser());
698
    $this->drupalGet('form-test/validate');
699
    $edit = array(
700
      'name' => 'validate',
701
      'form_token' => 'invalid token'
702
    );
703
    $this->drupalPost(NULL, $edit, 'Save');
704
    $this->assertNoFieldByName('name', '#value changed by #validate', 'Form element #value was not altered.');
705
    $this->assertNoText('Name value: value changed by form_set_value() in #validate', 'Form element value in $form_state was not altered.');
706
    $this->assertText('The form has become outdated.');
707
  }
708

    
709
  /**
710
   * Tests that a form with a disabled CSRF token can be validated.
711
   */
712
  function testDisabledToken() {
713
    $this->drupalPost('form-test/validate-no-token', array(), 'Save');
714
    $this->assertText('The form_test_validate_no_token form has been submitted successfully.');
715
  }
716

    
717
  /**
718
   * Tests partial form validation through #limit_validation_errors.
719
   */
720
  function testValidateLimitErrors() {
721
    $edit = array(
722
      'test' => 'invalid',
723
      'test_numeric_index[0]' => 'invalid',
724
      'test_substring[foo]' => 'invalid',
725
    );
726
    $path = 'form-test/limit-validation-errors';
727

    
728
    // Submit the form by pressing the 'Partial validate' button (uses
729
    // #limit_validation_errors) and ensure that the title field is not
730
    // validated, but the #element_validate handler for the 'test' field
731
    // is triggered.
732
    $this->drupalPost($path, $edit, t('Partial validate'));
733
    $this->assertNoText(t('!name field is required.', array('!name' => 'Title')));
734
    $this->assertText('Test element is invalid');
735

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

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

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

    
752
    // Now test full form validation and ensure that the #element_validate
753
    // handler is still triggered.
754
    $this->drupalPost($path, $edit, t('Full validate'));
755
    $this->assertText(t('!name field is required.', array('!name' => 'Title')));
756
    $this->assertText('Test element is invalid');
757
  }
758

    
759
  /**
760
   *  Tests error border of multiple fields with same name in a page.
761
   */
762
  function testMultiFormSameNameErrorClass() {
763
    $this->drupalGet('form-test/double-form');
764
    $edit = array();
765
    $this->drupalPost(NULL, $edit, t('Save'));
766
    $this->assertFieldByXpath('//input[@id="edit-name" and contains(@class, "error")]', NULL, 'Error input form element class found for first element.');
767
    $this->assertNoFieldByXpath('//input[@id="edit-name--2" and contains(@class, "error")]', NULL, 'No error input form element class found for second element.');
768
  }
769
}
770

    
771
/**
772
 * Test form element labels, required markers and associated output.
773
 */
774
class FormsElementsLabelsTestCase extends DrupalWebTestCase {
775

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

    
784
  function setUp() {
785
    parent::setUp('form_test');
786
  }
787

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

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

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

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

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

    
811
    // Exercise various defaults for checkboxes and modifications to ensure
812
    // appropriate override and correct behavior.
813
    $elements = $this->xpath('//input[@id="edit-form-checkbox-test"]/following-sibling::label[@for="edit-form-checkbox-test" and @class="option"]');
814
    $this->assertTrue(isset($elements[0]), "Label follows field and label option class correct for a checkbox by default.");
815

    
816
    // Exercise various defaults for textboxes and modifications to ensure
817
    // appropriate override and correct behavior.
818
    $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"]');
819
    $this->assertTrue(isset($elements[0]), "Label precedes textfield, with required marker inside label.");
820

    
821
    $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"]');
822
    $this->assertTrue(isset($elements[0]), "Label tag with required marker precedes required textfield with no title.");
823

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

    
827
    $elements = $this->xpath('//input[@id="edit-form-textfield-test-title"]/preceding-sibling::span[@class="form-required"]');
828
    $this->assertFalse(isset($elements[0]), "No required marker on non-required field.");
829

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

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

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

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

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

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

    
850
    // Check title attribute for radios and checkboxes.
851
    $elements = $this->xpath('//div[@id="edit-form-checkboxes-title-attribute"]');
852
    $this->assertEqual($elements[0]['title'], 'Checkboxes test' . ' (' . t('Required') . ')', 'Title attribute found.');
853
    $elements = $this->xpath('//div[@id="edit-form-radios-title-attribute"]');
854
    $this->assertEqual($elements[0]['title'], 'Radios test' . ' (' . t('Required') . ')', 'Title attribute found.');
855
  }
856
}
857

    
858
/**
859
 * Test the tableselect form element for expected behavior.
860
 */
861
class FormsElementsTableSelectFunctionalTest extends DrupalWebTestCase {
862

    
863
  public static function getInfo() {
864
    return array(
865
      'name' => 'Tableselect form element type test',
866
      'description' => 'Test the tableselect element for expected behavior',
867
      'group' => 'Form API',
868
    );
869
  }
870

    
871
  function setUp() {
872
    parent::setUp('form_test');
873
  }
874

    
875

    
876
  /**
877
   * Test the display of checkboxes when #multiple is TRUE.
878
   */
879
  function testMultipleTrue() {
880

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

    
883
    $this->assertNoText(t('Empty text.'), 'Empty text should not be displayed.');
884

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

    
888
    $rows = array('row1', 'row2', 'row3');
889
    foreach ($rows as $row) {
890
      $this->assertFieldByXPath('//input[@type="checkbox"]', $row, format_string('Checkbox for value @row.', array('@row' => $row)));
891
    }
892
  }
893

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

    
900
    $this->assertNoText(t('Empty text.'), 'Empty text should not be displayed.');
901

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

    
905
    $rows = array('row1', 'row2', 'row3');
906
    foreach ($rows as $row) {
907
      $this->assertFieldByXPath('//input[@type="radio"]', $row, format_string('Radio button for value @row.', array('@row' => $row)));
908
    }
909
  }
910

    
911
  /**
912
   * Test the display of the #empty text when #options is an empty array.
913
   */
914
  function testEmptyText() {
915
    $this->drupalGet('form_test/tableselect/empty-text');
916
    $this->assertText(t('Empty text.'), 'Empty text should be displayed.');
917
  }
918

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

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

    
929
    $this->assertText(t('Submitted: row1 = row1'), 'Checked checkbox row1');
930
    $this->assertText(t('Submitted: row2 = 0'), 'Unchecked checkbox row2.');
931
    $this->assertText(t('Submitted: row3 = 0'), 'Unchecked checkbox row3.');
932

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

    
938
    $this->assertText(t('Submitted: row1 = row1'), 'Checked checkbox row1.');
939
    $this->assertText(t('Submitted: row2 = 0'), 'Unchecked checkbox row2.');
940
    $this->assertText(t('Submitted: row3 = row3'), 'Checked checkbox row3.');
941

    
942
  }
943

    
944
  /**
945
   * Test submission of values when #multiple is FALSE.
946
   */
947
  function testMultipleFalseSubmit() {
948
    $edit['tableselect'] = 'row1';
949
    $this->drupalPost('form_test/tableselect/multiple-false', $edit, 'Submit');
950
    $this->assertText(t('Submitted: row1'), 'Selected radio button');
951
  }
952

    
953
  /**
954
   * Test the #js_select property.
955
   */
956
  function testAdvancedSelect() {
957
    // When #multiple = TRUE a Select all checkbox should be displayed by default.
958
    $this->drupalGet('form_test/tableselect/advanced-select/multiple-true-default');
959
    $this->assertFieldByXPath('//th[@class="select-all"]', NULL, 'Display a "Select all" checkbox by default when #multiple is TRUE.');
960

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

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

    
969
    $this->drupalGet('form_test/tableselect/advanced-select/multiple-false-advanced-select');
970
    $this->assertNoFieldByXPath('//th[@class="select-all"]', NULL, 'Do not display a "Select all" checkbox when #multiple is FALSE, even when #js_select is TRUE.');
971
  }
972

    
973

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

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

    
981
    $form['tableselect'] = array(
982
      '#type' => 'tableselect',
983
      '#header' => $header,
984
      '#options' => $options,
985
    );
986

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

    
991
    // Test with an invalid value.
992
    list($processed_form, $form_state, $errors) = $this->formSubmitHelper($form, array('tableselect' => array('non_existing_value' => 'non_existing_value')));
993
    $this->assertTrue(isset($errors['tableselect']), 'Option checker disallows invalid values for checkboxes.');
994

    
995
  }
996

    
997

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

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

    
1005
    $form['tableselect'] = array(
1006
      '#type' => 'tableselect',
1007
      '#header' => $header,
1008
      '#options' => $options,
1009
      '#multiple' => FALSE,
1010
    );
1011

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

    
1016
    // Test with an invalid value.
1017
    list($processed_form, $form_state, $errors) = $this->formSubmitHelper($form, array('tableselect' => 'non_existing_value'));
1018
    $this->assertTrue(isset($errors['tableselect']), 'Option checker disallows invalid values for radio buttons.');
1019
  }
1020

    
1021
  /**
1022
   * Test presence of ajax functionality
1023
   */
1024
  function testAjax() {
1025
    $rows = array('row1', 'row2', 'row3');
1026
    // Test checkboxes (#multiple == TRUE).
1027
    foreach ($rows as $row) {
1028
      $element = 'tableselect[' . $row . ']';
1029
      $edit = array($element => TRUE);
1030
      $result = $this->drupalPostAJAX('form_test/tableselect/multiple-true', $edit, $element);
1031
      $this->assertFalse(empty($result), t('Ajax triggers on checkbox for @row.', array('@row' => $row)));
1032
    }
1033
    // Test radios (#multiple == FALSE).
1034
    $element = 'tableselect';
1035
    foreach ($rows as $row) {
1036
      $edit = array($element => $row);
1037
      $result = $this->drupalPostAjax('form_test/tableselect/multiple-false', $edit, $element);
1038
      $this->assertFalse(empty($result), t('Ajax triggers on radio for @row.', array('@row' => $row)));
1039
    }
1040
  }
1041

    
1042
  /**
1043
   * Helper function for the option check test to submit a form while collecting errors.
1044
   *
1045
   * @param $form_element
1046
   *   A form element to test.
1047
   * @param $edit
1048
   *   An array containing post data.
1049
   *
1050
   * @return
1051
   *   An array containing the processed form, the form_state and any errors.
1052
   */
1053
  private function formSubmitHelper($form, $edit) {
1054
    $form_id = $this->randomName();
1055
    $form_state = form_state_defaults();
1056

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

    
1059
    $form_state['input'] = $edit;
1060
    $form_state['input']['form_id'] = $form_id;
1061

    
1062
    // The form token CSRF protection should not interfere with this test,
1063
    // so we bypass it by marking this test form as programmed.
1064
    $form_state['programmed'] = TRUE;
1065

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

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

    
1070
    $errors = form_get_errors();
1071

    
1072
    // Clear errors and messages.
1073
    drupal_get_messages();
1074
    form_clear_error();
1075

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

    
1081
}
1082

    
1083
/**
1084
 * Test the vertical_tabs form element for expected behavior.
1085
 */
1086
class FormsElementsVerticalTabsFunctionalTest extends DrupalWebTestCase {
1087

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

    
1096
  function setUp() {
1097
    parent::setUp('form_test');
1098
  }
1099

    
1100
  /**
1101
   * Ensures that vertical-tabs.js is included before collapse.js.
1102
   *
1103
   * Otherwise, collapse.js adds "SHOW" or "HIDE" labels to the tabs.
1104
   */
1105
  function testJavaScriptOrdering() {
1106
    $this->drupalGet('form_test/vertical-tabs');
1107
    $position1 = strpos($this->content, 'misc/vertical-tabs.js');
1108
    $position2 = strpos($this->content, 'misc/collapse.js');
1109
    $this->assertTrue($position1 !== FALSE && $position2 !== FALSE && $position1 < $position2, 'vertical-tabs.js is included before collapse.js');
1110
  }
1111
}
1112

    
1113
/**
1114
 * Test the form storage on a multistep form.
1115
 *
1116
 * The tested form puts data into the storage during the initial form
1117
 * construction. These tests verify that there are no duplicate form
1118
 * constructions, with and without manual form caching activiated. Furthermore
1119
 * when a validation error occurs, it makes sure that changed form element
1120
 * values aren't lost due to a wrong form rebuild.
1121
 */
1122
class FormsFormStorageTestCase extends DrupalWebTestCase {
1123

    
1124
  public static function getInfo() {
1125
    return array(
1126
      'name'  => 'Multistep form using form storage',
1127
      'description'  => 'Tests a multistep form using form storage and makes sure validation and caching works right.',
1128
      'group' => 'Form API',
1129
    );
1130
  }
1131

    
1132
  function setUp() {
1133
    parent::setUp('form_test');
1134

    
1135
    $this->web_user = $this->drupalCreateUser(array('access content'));
1136
    $this->drupalLogin($this->web_user);
1137
  }
1138

    
1139
  /**
1140
   * Tests using the form in a usual way.
1141
   */
1142
  function testForm() {
1143
    $this->drupalGet('form_test/form-storage');
1144
    $this->assertText('Form constructions: 1');
1145

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

    
1148
    // Use form rebuilding triggered by a submit button.
1149
    $this->drupalPost(NULL, $edit, 'Continue submit');
1150
    $this->assertText('Form constructions: 2');
1151
    $this->assertText('Form constructions: 3');
1152

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

    
1160
    $this->drupalPost(NULL, $edit, 'Save');
1161
    $this->assertText('Form constructions: 4');
1162
    $this->assertText('Title: new', 'The form storage has stored the values.');
1163
  }
1164

    
1165
  /**
1166
   * Tests using the form with an activated $form_state['cache'] property.
1167
   */
1168
  function testFormCached() {
1169
    $this->drupalGet('form_test/form-storage', array('query' => array('cache' => 1)));
1170
    $this->assertText('Form constructions: 1');
1171

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

    
1174
    // Use form rebuilding triggered by a submit button.
1175
    $this->drupalPost(NULL, $edit, 'Continue submit');
1176
    $this->assertText('Form constructions: 2');
1177

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

    
1184
    $this->drupalPost(NULL, $edit, 'Save');
1185
    $this->assertText('Form constructions: 3');
1186
    $this->assertText('Title: new', 'The form storage has stored the values.');
1187
  }
1188

    
1189
  /**
1190
   * Tests validation when form storage is used.
1191
   */
1192
  function testValidation() {
1193
    $this->drupalPost('form_test/form-storage', array('title' => '', 'value' => 'value_is_set'), 'Continue submit');
1194
    $this->assertPattern('/value_is_set/', 'The input values have been kept.');
1195
  }
1196

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

    
1211
    // Skip step 1 of the multi-step form, since the first step copies over
1212
    // 'title' into form storage, but we want to verify that changes in the form
1213
    // storage are updated in the cache during form validation.
1214
    $edit = array('title' => 'foo');
1215
    $this->drupalPost(NULL, $edit, 'Continue submit');
1216

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

    
1224
    // At this point, the form storage should contain updated values, but we do
1225
    // not see them, because the form has not been rebuilt yet due to the
1226
    // validation error. Post again and verify that the rebuilt form contains
1227
    // the values of the updated form storage.
1228
    $this->drupalPost(NULL, array('title' => 'foo', 'value' => 'bar'), 'Save');
1229
    $this->assertText("The thing has been changed.", 'The altered form storage value was updated in cache and taken over.');
1230
  }
1231

    
1232
  /**
1233
   * Tests a form using form state without using 'storage' to pass data from the
1234
   * constructor to a submit handler. The data has to persist even when caching
1235
   * gets activated, what may happen when a modules alter the form and adds
1236
   * #ajax properties.
1237
   */
1238
  function testFormStatePersist() {
1239
    // Test the form one time with caching activated and one time without.
1240
    $run_options = array(
1241
      array(),
1242
      array('query' => array('cache' => 1)),
1243
    );
1244
    foreach ($run_options as $options) {
1245
      $this->drupalPost('form-test/state-persist', array(), t('Submit'), $options);
1246
      // The submit handler outputs the value in $form_state, assert it's there.
1247
      $this->assertText('State persisted.');
1248

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

    
1256
      // Now post to the rebuilt form and verify it's still there afterwards.
1257
      $this->drupalPost(NULL, array('title' => 'bar'), t('Submit'), $options);
1258
      $this->assertText('State persisted.');
1259
    }
1260
  }
1261

    
1262
  /**
1263
   * Verify that the form build-id remains the same when validation errors
1264
   * occur on a mutable form.
1265
   */
1266
  function testMutableForm() {
1267
    // Request the form with 'cache' query parameter to enable form caching.
1268
    $this->drupalGet('form_test/form-storage', array('query' => array('cache' => 1)));
1269
    $buildIdFields = $this->xpath('//input[@name="form_build_id"]');
1270
    $this->assertEqual(count($buildIdFields), 1, 'One form build id field on the page');
1271
    $buildId = (string) $buildIdFields[0]['value'];
1272

    
1273
    // Trigger validation error by submitting an empty title.
1274
    $edit = array('title' => '');
1275
    $this->drupalPost(NULL, $edit, 'Continue submit');
1276

    
1277
    // Verify that the build-id did not change.
1278
    $this->assertFieldByName('form_build_id', $buildId, 'Build id remains the same when form validation fails');
1279
  }
1280

    
1281
  /**
1282
   * Verifies that form build-id is regenerated when loading an immutable form
1283
   * from the cache.
1284
   */
1285
  function testImmutableForm() {
1286
    // Request the form with 'cache' query parameter to enable form caching.
1287
    $this->drupalGet('form_test/form-storage', array('query' => array('cache' => 1, 'immutable' => 1)));
1288
    $buildIdFields = $this->xpath('//input[@name="form_build_id"]');
1289
    $this->assertEqual(count($buildIdFields), 1, 'One form build id field on the page');
1290
    $buildId = (string) $buildIdFields[0]['value'];
1291

    
1292
    // Trigger validation error by submitting an empty title.
1293
    $edit = array('title' => '');
1294
    $this->drupalPost(NULL, $edit, 'Continue submit');
1295

    
1296
    // Verify that the build-id did change.
1297
    $this->assertNoFieldByName('form_build_id', $buildId, 'Build id changes when form validation fails');
1298

    
1299
    // Retrieve the new build-id.
1300
    $buildIdFields = $this->xpath('//input[@name="form_build_id"]');
1301
    $this->assertEqual(count($buildIdFields), 1, 'One form build id field on the page');
1302
    $buildId = (string) $buildIdFields[0]['value'];
1303

    
1304
    // Trigger validation error by again submitting an empty title.
1305
    $edit = array('title' => '');
1306
    $this->drupalPost(NULL, $edit, 'Continue submit');
1307

    
1308
    // Verify that the build-id does not change the second time.
1309
    $this->assertFieldByName('form_build_id', $buildId, 'Build id remains the same when form validation fails subsequently');
1310
  }
1311

    
1312
  /**
1313
   * Verify that existing contrib code cannot overwrite immutable form state.
1314
   */
1315
  public function testImmutableFormLegacyProtection() {
1316
    $this->drupalGet('form_test/form-storage', array('query' => array('cache' => 1, 'immutable' => 1)));
1317
    $build_id_fields = $this->xpath('//input[@name="form_build_id"]');
1318
    $this->assertEqual(count($build_id_fields), 1, 'One form build id field on the page');
1319
    $build_id = (string) $build_id_fields[0]['value'];
1320

    
1321
    // Try to poison the form cache.
1322
    $original = $this->drupalGetAJAX('form_test/form-storage-legacy/' . $build_id);
1323
    $this->assertEqual($original['form']['#build_id_old'], $build_id, 'Original build_id was recorded');
1324
    $this->assertNotEqual($original['form']['#build_id'], $build_id, 'New build_id was generated');
1325

    
1326
    // Assert that a watchdog message was logged by form_set_cache.
1327
    $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.'));
1328
    $this->assert($status, 'A watchdog message was logged by form_set_cache');
1329

    
1330
    // Ensure that the form state was not poisoned by the preceeding call.
1331
    $original = $this->drupalGetAJAX('form_test/form-storage-legacy/' . $build_id);
1332
    $this->assertEqual($original['form']['#build_id_old'], $build_id, 'Original build_id was recorded');
1333
    $this->assertNotEqual($original['form']['#build_id'], $build_id, 'New build_id was generated');
1334
    $this->assert(empty($original['form']['#poisoned']), 'Original form structure was preserved');
1335
    $this->assert(empty($original['form_state']['poisoned']), 'Original form state was preserved');
1336
  }
1337
}
1338

    
1339
/**
1340
 * Test the form storage when page caching for anonymous users is turned on.
1341
 */
1342
class FormsFormStoragePageCacheTestCase extends DrupalWebTestCase {
1343
  protected $profile = 'testing';
1344

    
1345
  public static function getInfo() {
1346
    return array(
1347
      'name'  => 'Forms using form storage on cached pages',
1348
      'description'  => 'Tests a form using form storage and makes sure validation and caching works when page caching for anonymous users is turned on.',
1349
      'group' => 'Form API',
1350
    );
1351
  }
1352

    
1353
  public function setUp() {
1354
    parent::setUp('form_test');
1355

    
1356
    variable_set('cache', TRUE);
1357
  }
1358

    
1359
  /**
1360
   * Return the build id of the current form.
1361
   */
1362
  protected function getFormBuildId() {
1363
    $build_id_fields = $this->xpath('//input[@name="form_build_id"]');
1364
    $this->assertEqual(count($build_id_fields), 1, 'One form build id field on the page');
1365
    return (string) $build_id_fields[0]['value'];
1366
  }
1367

    
1368
  /**
1369
   * Build-id is regenerated when validating cached form.
1370
   */
1371
  public function testValidateFormStorageOnCachedPage() {
1372
    $this->drupalGet('form_test/form-storage-page-cache');
1373
    $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Page was not cached.');
1374
    $this->assertText('No old build id', 'No old build id on the page');
1375
    $build_id_initial = $this->getFormBuildId();
1376

    
1377
    // Trigger validation error by submitting an empty title.
1378
    $edit = array('title' => '');
1379
    $this->drupalPost(NULL, $edit, 'Save');
1380
    $this->assertText($build_id_initial, 'Old build id on the page');
1381
    $build_id_first_validation = $this->getFormBuildId();
1382
    $this->assertNotEqual($build_id_initial, $build_id_first_validation, 'Build id changes when form validation fails');
1383

    
1384
    // Trigger validation error by again submitting an empty title.
1385
    $edit = array('title' => '');
1386
    $this->drupalPost(NULL, $edit, 'Save');
1387
    $this->assertText('No old build id', 'No old build id on the page');
1388
    $build_id_second_validation = $this->getFormBuildId();
1389
    $this->assertEqual($build_id_first_validation, $build_id_second_validation, 'Build id remains the same when form validation fails subsequently');
1390

    
1391
    // Repeat the test sequence but this time with a page loaded from the cache.
1392
    $this->drupalGet('form_test/form-storage-page-cache');
1393
    $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
1394
    $this->assertText('No old build id', 'No old build id on the page');
1395
    $build_id_from_cache_initial = $this->getFormBuildId();
1396
    $this->assertEqual($build_id_initial, $build_id_from_cache_initial, 'Build id is the same as on the first request');
1397

    
1398
    // Trigger validation error by submitting an empty title.
1399
    $edit = array('title' => '');
1400
    $this->drupalPost(NULL, $edit, 'Save');
1401
    $this->assertText($build_id_initial, 'Old build id is initial build id');
1402
    $build_id_from_cache_first_validation = $this->getFormBuildId();
1403
    $this->assertNotEqual($build_id_initial, $build_id_from_cache_first_validation, 'Build id changes when form validation fails');
1404
    $this->assertNotEqual($build_id_first_validation, $build_id_from_cache_first_validation, 'Build id from first user is not reused');
1405

    
1406
    // Trigger validation error by again submitting an empty title.
1407
    $edit = array('title' => '');
1408
    $this->drupalPost(NULL, $edit, 'Save');
1409
    $this->assertText('No old build id', 'No old build id on the page');
1410
    $build_id_from_cache_second_validation = $this->getFormBuildId();
1411
    $this->assertEqual($build_id_from_cache_first_validation, $build_id_from_cache_second_validation, 'Build id remains the same when form validation fails subsequently');
1412
  }
1413

    
1414
  /**
1415
   * Build-id is regenerated when rebuilding cached form.
1416
   */
1417
  public function testRebuildFormStorageOnCachedPage() {
1418
    $this->drupalGet('form_test/form-storage-page-cache');
1419
    $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Page was not cached.');
1420
    $this->assertText('No old build id', 'No old build id on the page');
1421
    $build_id_initial = $this->getFormBuildId();
1422

    
1423
    // Trigger rebuild, should regenerate build id.
1424
    $edit = array('title' => 'something');
1425
    $this->drupalPost(NULL, $edit, 'Rebuild');
1426
    $this->assertText($build_id_initial, 'Initial build id as old build id on the page');
1427
    $build_id_first_rebuild = $this->getFormBuildId();
1428
    $this->assertNotEqual($build_id_initial, $build_id_first_rebuild, 'Build id changes on first rebuild.');
1429

    
1430
    // Trigger subsequent rebuild, should regenerate the build id again.
1431
    $edit = array('title' => 'something');
1432
    $this->drupalPost(NULL, $edit, 'Rebuild');
1433
    $this->assertText($build_id_first_rebuild, 'First build id as old build id on the page');
1434
    $build_id_second_rebuild = $this->getFormBuildId();
1435
    $this->assertNotEqual($build_id_first_rebuild, $build_id_second_rebuild, 'Build id changes on second rebuild.');
1436
  }
1437
}
1438

    
1439
/**
1440
 * Test cache_form.
1441
 */
1442
class FormsFormCacheTestCase extends DrupalWebTestCase {
1443
  public static function getInfo() {
1444
    return array(
1445
      'name' => 'Form caching',
1446
      'description' => 'Tests storage and retrieval of forms from cache.',
1447
      'group' => 'Form API',
1448
    );
1449
  }
1450

    
1451
  function setUp() {
1452
    parent::setUp('form_test');
1453
  }
1454

    
1455
  /**
1456
   * Tests storing and retrieving the form from cache.
1457
   */
1458
  function testCacheForm() {
1459
    $form = drupal_get_form('form_test_cache_form');
1460
    $form_state = array('foo' => 'bar', 'build_info' => array('baz'));
1461
    form_set_cache($form['#build_id'], $form, $form_state);
1462

    
1463
    $cached_form_state = array();
1464
    $cached_form = form_get_cache($form['#build_id'], $cached_form_state);
1465

    
1466
    $this->assertEqual($cached_form['#build_id'], $form['#build_id'], 'Form retrieved from cache_form successfully.');
1467
    $this->assertEqual($cached_form_state['foo'], 'bar', 'Data retrieved from cache_form successfully.');
1468
  }
1469

    
1470
  /**
1471
   * Tests changing form_cache_expiration.
1472
   */
1473
  function testCacheFormCustomExpiration() {
1474
    variable_set('form_cache_expiration', -1 * (24 * 60 * 60));
1475

    
1476
    $form = drupal_get_form('form_test_cache_form');
1477
    $form_state = array('foo' => 'bar', 'build_info' => array('baz'));
1478
    form_set_cache($form['#build_id'], $form, $form_state);
1479

    
1480
    // Clear expired entries from cache_form, which should include the entry we
1481
    // just stored. Without this, the form will still be retrieved from cache.
1482
    cache_clear_all(NULL, 'cache_form');
1483

    
1484
    $cached_form_state = array();
1485
    $cached_form = form_get_cache($form['#build_id'], $cached_form_state);
1486

    
1487
    $this->assertNull($cached_form, 'Expired form was not returned from cache.');
1488
    $this->assertTrue(empty($cached_form_state), 'No data retrieved from cache for expired form.');
1489
  }
1490
}
1491

    
1492
/**
1493
 * Test wrapper form callbacks.
1494
 */
1495
class FormsFormWrapperTestCase extends DrupalWebTestCase {
1496
  public static function getInfo() {
1497
    return array(
1498
      'name' => 'Form wrapper callback',
1499
      'description' => 'Tests form wrapper callbacks to pass a prebuilt form to form builder functions.',
1500
      'group' => 'Form API',
1501
    );
1502
  }
1503

    
1504
  function setUp() {
1505
    parent::setUp('form_test');
1506
  }
1507

    
1508
  /**
1509
   * Tests using the form in a usual way.
1510
   */
1511
  function testWrapperCallback() {
1512
    $this->drupalGet('form_test/wrapper-callback');
1513
    $this->assertText('Form wrapper callback element output.', 'The form contains form wrapper elements.');
1514
    $this->assertText('Form builder element output.', 'The form contains form builder elements.');
1515
  }
1516
}
1517

    
1518
/**
1519
 * Test $form_state clearance.
1520
 */
1521
class FormStateValuesCleanTestCase extends DrupalWebTestCase {
1522
  public static function getInfo() {
1523
    return array(
1524
      'name' => 'Form state values clearance',
1525
      'description' => 'Test proper removal of submitted form values using form_state_values_clean().',
1526
      'group' => 'Form API',
1527
    );
1528
  }
1529

    
1530
  function setUp() {
1531
    parent::setUp('form_test');
1532
  }
1533

    
1534
  /**
1535
   * Tests form_state_values_clean().
1536
   */
1537
  function testFormStateValuesClean() {
1538
    $values = drupal_json_decode($this->drupalPost('form_test/form-state-values-clean', array(), t('Submit')));
1539

    
1540
    // Setup the expected result.
1541
    $result = array(
1542
      'beer' => 1000,
1543
      'baz' => array('beer' => 2000),
1544
    );
1545

    
1546
    // Verify that all internal Form API elements were removed.
1547
    $this->assertFalse(isset($values['form_id']), format_string('%element was removed.', array('%element' => 'form_id')));
1548
    $this->assertFalse(isset($values['form_token']), format_string('%element was removed.', array('%element' => 'form_token')));
1549
    $this->assertFalse(isset($values['form_build_id']), format_string('%element was removed.', array('%element' => 'form_build_id')));
1550
    $this->assertFalse(isset($values['op']), format_string('%element was removed.', array('%element' => 'op')));
1551

    
1552
    // Verify that all buttons were removed.
1553
    $this->assertFalse(isset($values['foo']), format_string('%element was removed.', array('%element' => 'foo')));
1554
    $this->assertFalse(isset($values['bar']), format_string('%element was removed.', array('%element' => 'bar')));
1555
    $this->assertFalse(isset($values['baz']['foo']), format_string('%element was removed.', array('%element' => 'foo')));
1556
    $this->assertFalse(isset($values['baz']['baz']), format_string('%element was removed.', array('%element' => 'baz')));
1557

    
1558
    // Verify that nested form value still exists.
1559
    $this->assertTrue(isset($values['baz']['beer']), 'Nested form value still exists.');
1560

    
1561
    // Verify that actual form values equal resulting form values.
1562
    $this->assertEqual($values, $result, 'Expected form values equal actual form values.');
1563
  }
1564
}
1565

    
1566
/**
1567
 * Tests $form_state clearance with form elements having buttons.
1568
 */
1569
class FormStateValuesCleanAdvancedTestCase extends DrupalWebTestCase {
1570
  /**
1571
   * An image file path for uploading.
1572
   */
1573
  protected $image;
1574

    
1575
  public static function getInfo() {
1576
    return array(
1577
      'name' => 'Form state values clearance (advanced)',
1578
      'description' => 'Test proper removal of submitted form values using form_state_values_clean() when having forms with elements containing buttons like "managed_file".',
1579
      'group' => 'Form API',
1580
    );
1581
  }
1582

    
1583
  function setUp() {
1584
    parent::setUp('form_test');
1585
  }
1586

    
1587
  /**
1588
   * Tests form_state_values_clean().
1589
   */
1590
  function testFormStateValuesCleanAdvanced() {
1591

    
1592
    // Get an image for uploading.
1593
    $image_files = $this->drupalGetTestFiles('image');
1594
    $this->image = current($image_files);
1595

    
1596
    // Check if the physical file is there.
1597
    $this->assertTrue(is_file($this->image->uri), "The image file we're going to upload exists.");
1598

    
1599
    // "Browse" for the desired file.
1600
    $edit = array('files[image]' => drupal_realpath($this->image->uri));
1601

    
1602
    // Post the form.
1603
    $this->drupalPost('form_test/form-state-values-clean-advanced', $edit, t('Submit'));
1604

    
1605
    // Expecting a 200 HTTP code.
1606
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
1607
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
1608
  }
1609
}
1610

    
1611
/**
1612
 * Tests form rebuilding.
1613
 *
1614
 * @todo Add tests for other aspects of form rebuilding.
1615
 */
1616
class FormsRebuildTestCase extends DrupalWebTestCase {
1617
  public static function getInfo() {
1618
    return array(
1619
      'name' => 'Form rebuilding',
1620
      'description' => 'Tests functionality of drupal_rebuild_form().',
1621
      'group' => 'Form API',
1622
    );
1623
  }
1624

    
1625
  function setUp() {
1626
    parent::setUp('form_test');
1627

    
1628
    $this->web_user = $this->drupalCreateUser(array('access content'));
1629
    $this->drupalLogin($this->web_user);
1630
  }
1631

    
1632
  /**
1633
   * Tests preservation of values.
1634
   */
1635
  function testRebuildPreservesValues() {
1636
    $edit = array(
1637
      'checkbox_1_default_off' => TRUE,
1638
      'checkbox_1_default_on' => FALSE,
1639
      'text_1' => 'foo',
1640
    );
1641
    $this->drupalPost('form-test/form-rebuild-preserve-values', $edit, 'Add more');
1642

    
1643
    // Verify that initial elements retained their submitted values.
1644
    $this->assertFieldChecked('edit-checkbox-1-default-off', 'A submitted checked checkbox retained its checked state during a rebuild.');
1645
    $this->assertNoFieldChecked('edit-checkbox-1-default-on', 'A submitted unchecked checkbox retained its unchecked state during a rebuild.');
1646
    $this->assertFieldById('edit-text-1', 'foo', 'A textfield retained its submitted value during a rebuild.');
1647

    
1648
    // Verify that newly added elements were initialized with their default values.
1649
    $this->assertFieldChecked('edit-checkbox-2-default-on', 'A newly added checkbox was initialized with a default checked state.');
1650
    $this->assertNoFieldChecked('edit-checkbox-2-default-off', 'A newly added checkbox was initialized with a default unchecked state.');
1651
    $this->assertFieldById('edit-text-2', 'DEFAULT 2', 'A newly added textfield was initialized with its default value.');
1652
  }
1653

    
1654
  /**
1655
   * Tests that a form's action is retained after an Ajax submission.
1656
   *
1657
   * The 'action' attribute of a form should not change after an Ajax submission
1658
   * followed by a non-Ajax submission, which triggers a validation error.
1659
   */
1660
  function testPreserveFormActionAfterAJAX() {
1661
    // Create a multi-valued field for 'page' nodes to use for Ajax testing.
1662
    $field_name = 'field_ajax_test';
1663
    $field = array(
1664
      'field_name' => $field_name,
1665
      'type' => 'text',
1666
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
1667
    );
1668
    field_create_field($field);
1669
    $instance = array(
1670
      'field_name' => $field_name,
1671
      'entity_type' => 'node',
1672
      'bundle' => 'page',
1673
    );
1674
    field_create_instance($instance);
1675

    
1676
    // Log in a user who can create 'page' nodes.
1677
    $this->web_user = $this->drupalCreateUser(array('create page content'));
1678
    $this->drupalLogin($this->web_user);
1679

    
1680
    // Get the form for adding a 'page' node. Submit an "add another item" Ajax
1681
    // submission and verify it worked by ensuring the updated page has two text
1682
    // field items in the field for which we just added an item.
1683
    $this->drupalGet('node/add/page');
1684
    $this->drupalPostAJAX(NULL, array(), array('field_ajax_test_add_more' => t('Add another item')), 'system/ajax', array(), array(), 'page-node-form');
1685
    $this->assert(count($this->xpath('//div[contains(@class, "field-name-field-ajax-test")]//input[@type="text"]')) == 2, 'AJAX submission succeeded.');
1686

    
1687
    // Submit the form with the non-Ajax "Save" button, leaving the title field
1688
    // blank to trigger a validation error, and ensure that a validation error
1689
    // occurred, because this test is for testing what happens when a form is
1690
    // re-rendered without being re-built, which is what happens when there's
1691
    // a validation error.
1692
    $this->drupalPost(NULL, array(), t('Save'));
1693
    $this->assertText('Title field is required.', 'Non-AJAX submission correctly triggered a validation error.');
1694

    
1695
    // Ensure that the form contains two items in the multi-valued field, so we
1696
    // know we're testing a form that was correctly retrieved from cache.
1697
    $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.');
1698

    
1699
    // Ensure that the form's action is correct.
1700
    $forms = $this->xpath('//form[contains(@class, "node-page-form")]');
1701
    $this->assert(count($forms) == 1 && $forms[0]['action'] == url('node/add/page'), 'Re-rendered form contains the correct action value.');
1702
  }
1703
}
1704

    
1705
/**
1706
 * Tests form redirection.
1707
 */
1708
class FormsRedirectTestCase extends DrupalWebTestCase {
1709

    
1710
  public static function getInfo() {
1711
    return array(
1712
      'name' => 'Form redirecting',
1713
      'description' => 'Tests functionality of drupal_redirect_form().',
1714
      'group' => 'Form API',
1715
    );
1716
  }
1717

    
1718
  function setUp() {
1719
    parent::setUp(array('form_test'));
1720
  }
1721

    
1722
  /**
1723
   * Tests form redirection.
1724
   */
1725
  function testRedirect() {
1726
    $path = 'form-test/redirect';
1727
    $options = array('query' => array('foo' => 'bar'));
1728
    $options['absolute'] = TRUE;
1729

    
1730
    // Test basic redirection.
1731
    $edit = array(
1732
      'redirection' => TRUE,
1733
      'destination' => $this->randomName(),
1734
    );
1735
    $this->drupalPost($path, $edit, t('Submit'));
1736
    $this->assertUrl($edit['destination'], array(), 'Basic redirection works.');
1737

    
1738

    
1739
    // Test without redirection.
1740
    $edit = array(
1741
      'redirection' => FALSE,
1742
    );
1743
    $this->drupalPost($path, $edit, t('Submit'));
1744
    $this->assertUrl($path, array(), 'When redirect is set to FALSE, there should be no redirection.');
1745

    
1746
    // Test redirection with query parameters.
1747
    $edit = array(
1748
      'redirection' => TRUE,
1749
      'destination' => $this->randomName(),
1750
    );
1751
    $this->drupalPost($path, $edit, t('Submit'), $options);
1752
    $this->assertUrl($edit['destination'], array(), 'Redirection with query parameters works.');
1753

    
1754
    // Test without redirection but with query parameters.
1755
    $edit = array(
1756
      'redirection' => FALSE,
1757
    );
1758
    $this->drupalPost($path, $edit, t('Submit'), $options);
1759
    $this->assertUrl($path, $options, 'When redirect is set to FALSE, there should be no redirection, and the query parameters should be passed along.');
1760

    
1761
    // Test redirection back to the original path.
1762
    $edit = array(
1763
      'redirection' => TRUE,
1764
      'destination' => '',
1765
    );
1766
    $this->drupalPost($path, $edit, t('Submit'));
1767
    $this->assertUrl($path, array(), 'When using an empty redirection string, there should be no redirection.');
1768

    
1769
    // Test redirection back to the original path with query parameters.
1770
    $edit = array(
1771
      'redirection' => TRUE,
1772
      'destination' => '',
1773
    );
1774
    $this->drupalPost($path, $edit, t('Submit'), $options);
1775
    $this->assertUrl($path, $options, 'When using an empty redirection string, there should be no redirection, and the query parameters should be passed along.');
1776
  }
1777

    
1778
}
1779

    
1780
/**
1781
 * Test the programmatic form submission behavior.
1782
 */
1783
class FormsProgrammaticTestCase extends DrupalWebTestCase {
1784

    
1785
  public static function getInfo() {
1786
    return array(
1787
      'name' => 'Programmatic form submissions',
1788
      'description' => 'Test the programmatic form submission behavior.',
1789
      'group' => 'Form API',
1790
    );
1791
  }
1792

    
1793
  function setUp() {
1794
    parent::setUp('form_test');
1795
  }
1796

    
1797
  /**
1798
   * Test the programmatic form submission workflow.
1799
   */
1800
  function testSubmissionWorkflow() {
1801
    // Backup the current batch status and reset it to avoid conflicts while
1802
    // processing the dummy form submit handler.
1803
    $current_batch = $batch =& batch_get();
1804
    $batch = array();
1805

    
1806
    // Test that a programmatic form submission is rejected when a required
1807
    // textfield is omitted and correctly processed when it is provided.
1808
    $this->submitForm(array(), FALSE);
1809
    $this->submitForm(array('textfield' => 'test 1'), TRUE);
1810
    $this->submitForm(array(), FALSE);
1811
    $this->submitForm(array('textfield' => 'test 2'), TRUE);
1812

    
1813
    // Test that a programmatic form submission can turn on and off checkboxes
1814
    // which are, by default, checked.
1815
    $this->submitForm(array('textfield' => 'dummy value', 'checkboxes' => array(1 => 1, 2 => 2)), TRUE);
1816
    $this->submitForm(array('textfield' => 'dummy value', 'checkboxes' => array(1 => 1, 2 => NULL)), TRUE);
1817
    $this->submitForm(array('textfield' => 'dummy value', 'checkboxes' => array(1 => NULL, 2 => 2)), TRUE);
1818
    $this->submitForm(array('textfield' => 'dummy value', 'checkboxes' => array(1 => NULL, 2 => NULL)), TRUE);
1819

    
1820
    // Test that a programmatic form submission can successfully submit values
1821
    // even for fields where the #access property is FALSE.
1822
    $this->submitForm(array('textfield' => 'dummy value', 'textfield_no_access' => 'test value'), TRUE);
1823
    // Test that #access is respected for programmatic form submissions when
1824
    // requested to do so.
1825
    $submitted_values = array('textfield' => 'dummy value', 'textfield_no_access' => 'test value');
1826
    $expected_values = array('textfield' => 'dummy value', 'textfield_no_access' => 'default value');
1827
    $form_state = array('programmed_bypass_access_check' => FALSE);
1828
    $this->submitForm($submitted_values, TRUE, $expected_values, $form_state);
1829

    
1830
    // Test that a programmatic form submission can correctly click a button
1831
    // that limits validation errors based on user input. Since we do not
1832
    // submit any values for "textfield" here and the textfield is required, we
1833
    // only expect form validation to pass when validation is limited to a
1834
    // different field.
1835
    $this->submitForm(array('op' => 'Submit with limited validation', 'field_to_validate' => 'all'), FALSE);
1836
    $this->submitForm(array('op' => 'Submit with limited validation', 'field_to_validate' => 'textfield'), FALSE);
1837
    $this->submitForm(array('op' => 'Submit with limited validation', 'field_to_validate' => 'field_to_validate'), TRUE);
1838

    
1839
    // Restore the current batch status.
1840
    $batch = $current_batch;
1841
  }
1842

    
1843
  /**
1844
   * Helper function used to programmatically submit the form defined in
1845
   * form_test.module with the given values.
1846
   *
1847
   * @param $values
1848
   *   An array of field values to be submitted.
1849
   * @param $valid_input
1850
   *   A boolean indicating whether or not the form submission is expected to
1851
   *   be valid.
1852
   * @param $expected_values
1853
   *   (Optional) An array of field values that are expected to be stored by
1854
   *   the form submit handler. If not set, the submitted $values are assumed
1855
   *   to also be the expected stored values.
1856
   * @param $form_state
1857
   *   (Optional) A keyed array containing the state of the form, to be sent in
1858
   *   the call to drupal_form_submit(). The $values parameter is added to
1859
   *   $form_state['values'] by default, if it is not already set.
1860
   */
1861
  private function submitForm($values, $valid_input, $expected_values = NULL, $form_state = array()) {
1862
    // Programmatically submit the given values.
1863
    $form_state += array('values' => $values);
1864
    drupal_form_submit('form_test_programmatic_form', $form_state);
1865

    
1866
    // Check that the form returns an error when expected, and vice versa.
1867
    $errors = form_get_errors();
1868
    $valid_form = empty($errors);
1869
    $args = array(
1870
      '%values' => print_r($values, TRUE),
1871
      '%errors' => $valid_form ? t('None') : implode(' ', $errors),
1872
    );
1873
    $this->assertTrue($valid_input == $valid_form, format_string('Input values: %values<br/>Validation handler errors: %errors', $args));
1874

    
1875
    // We check submitted values only if we have a valid input.
1876
    if ($valid_input) {
1877
      // By fetching the values from $form_state['storage'] we ensure that the
1878
      // submission handler was properly executed.
1879
      $stored_values = $form_state['storage']['programmatic_form_submit'];
1880
      if (!isset($expected_values)) {
1881
        $expected_values = $values;
1882
      }
1883
      foreach ($expected_values as $key => $value) {
1884
        $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))));
1885
      }
1886
    }
1887
  }
1888
}
1889

    
1890
/**
1891
 * Test that FAPI correctly determines $form_state['triggering_element'].
1892
 */
1893
class FormsTriggeringElementTestCase extends DrupalWebTestCase {
1894

    
1895
  public static function getInfo() {
1896
    return array(
1897
      'name' => 'Form triggering element determination',
1898
      'description' => 'Test the determination of $form_state[\'triggering_element\'].',
1899
      'group' => 'Form API',
1900
    );
1901
  }
1902

    
1903
  function setUp() {
1904
    parent::setUp('form_test');
1905
  }
1906

    
1907
  /**
1908
   * Test the determination of $form_state['triggering_element'] when no button
1909
   * information is included in the POST data, as is sometimes the case when
1910
   * the ENTER key is pressed in a textfield in Internet Explorer.
1911
   */
1912
  function testNoButtonInfoInPost() {
1913
    $path = 'form-test/clicked-button';
1914
    $edit = array();
1915
    $form_html_id = 'form-test-clicked-button';
1916

    
1917
    // Ensure submitting a form with no buttons results in no
1918
    // $form_state['triggering_element'] and the form submit handler not
1919
    // running.
1920
    $this->drupalPost($path, $edit, NULL, array(), array(), $form_html_id);
1921
    $this->assertText('There is no clicked button.', '$form_state[\'triggering_element\'] set to NULL.');
1922
    $this->assertNoText('Submit handler for form_test_clicked_button executed.', 'Form submit handler did not execute.');
1923

    
1924
    // Ensure submitting a form with one or more submit buttons results in
1925
    // $form_state['triggering_element'] being set to the first one the user has
1926
    // access to. An argument with 'r' in it indicates a restricted
1927
    // (#access=FALSE) button.
1928
    $this->drupalPost($path . '/s', $edit, NULL, array(), array(), $form_html_id);
1929
    $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to only button.');
1930
    $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');
1931

    
1932
    $this->drupalPost($path . '/s/s', $edit, NULL, array(), array(), $form_html_id);
1933
    $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to first button.');
1934
    $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');
1935

    
1936
    $this->drupalPost($path . '/rs/s', $edit, NULL, array(), array(), $form_html_id);
1937
    $this->assertText('The clicked button is button2.', '$form_state[\'triggering_element\'] set to first available button.');
1938
    $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');
1939

    
1940
    // Ensure submitting a form with buttons of different types results in
1941
    // $form_state['triggering_element'] being set to the first button,
1942
    // regardless of type. For the FAPI 'button' type, this should result in the
1943
    // submit handler not executing. The types are 's'(ubmit), 'b'(utton), and
1944
    // 'i'(mage_button).
1945
    $this->drupalPost($path . '/s/b/i', $edit, NULL, array(), array(), $form_html_id);
1946
    $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to first button.');
1947
    $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');
1948

    
1949
    $this->drupalPost($path . '/b/s/i', $edit, NULL, array(), array(), $form_html_id);
1950
    $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to first button.');
1951
    $this->assertNoText('Submit handler for form_test_clicked_button executed.', 'Form submit handler did not execute.');
1952

    
1953
    $this->drupalPost($path . '/i/s/b', $edit, NULL, array(), array(), $form_html_id);
1954
    $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to first button.');
1955
    $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');
1956
  }
1957

    
1958
  /**
1959
   * Test that $form_state['triggering_element'] does not get set to a button
1960
   * with #access=FALSE.
1961
   */
1962
  function testAttemptAccessControlBypass() {
1963
    $path = 'form-test/clicked-button';
1964
    $form_html_id = 'form-test-clicked-button';
1965

    
1966
    // Retrieve a form where 'button1' has #access=FALSE and 'button2' doesn't.
1967
    $this->drupalGet($path . '/rs/s');
1968

    
1969
    // Submit the form with 'button1=button1' in the POST data, which someone
1970
    // trying to get around security safeguards could easily do. We have to do
1971
    // a little trickery here, to work around the safeguards in drupalPost(): by
1972
    // renaming the text field that is in the form to 'button1', we can get the
1973
    // data we want into $_POST.
1974
    $elements = $this->xpath('//form[@id="' . $form_html_id . '"]//input[@name="text"]');
1975
    $elements[0]['name'] = 'button1';
1976
    $this->drupalPost(NULL, array('button1' => 'button1'), NULL, array(), array(), $form_html_id);
1977

    
1978
    // Ensure that $form_state['triggering_element'] was not set to the
1979
    // restricted button. Do this with both a negative and positive assertion,
1980
    // because negative assertions alone can be brittle. See
1981
    // testNoButtonInfoInPost() for why the triggering element gets set to
1982
    // 'button2'.
1983
    $this->assertNoText('The clicked button is button1.', '$form_state[\'triggering_element\'] not set to a restricted button.');
1984
    $this->assertText('The clicked button is button2.', '$form_state[\'triggering_element\'] not set to a restricted button.');
1985
  }
1986
}
1987

    
1988
/**
1989
 * Tests rebuilding of arbitrary forms by altering them.
1990
 */
1991
class FormsArbitraryRebuildTestCase extends DrupalWebTestCase {
1992
  public static function getInfo() {
1993
    return array(
1994
      'name' => 'Rebuild arbitrary forms',
1995
      'description' => 'Tests altering forms to be rebuilt so there are multiple steps.',
1996
      'group' => 'Form API',
1997
    );
1998
  }
1999

    
2000
  function setUp() {
2001
    parent::setUp('form_test');
2002
    // Auto-create a field for testing.
2003
    $field = array(
2004
      'field_name' => 'test_multiple',
2005
      'type' => 'text',
2006
      'cardinality' => -1,
2007
      'translatable' => FALSE,
2008
    );
2009
    field_create_field($field);
2010

    
2011
    $instance = array(
2012
      'entity_type' => 'node',
2013
      'field_name' => 'test_multiple',
2014
      'bundle' => 'page',
2015
      'label' => 'Test a multiple valued field',
2016
      'widget' => array(
2017
        'type' => 'text_textfield',
2018
        'weight' => 0,
2019
      ),
2020
    );
2021
    field_create_instance($instance);
2022
    variable_set('user_register', USER_REGISTER_VISITORS);
2023
  }
2024

    
2025
  /**
2026
   * Tests a basic rebuild with the user registration form.
2027
   */
2028
  function testUserRegistrationRebuild() {
2029
    $edit = array(
2030
      'name' => 'foo',
2031
      'mail' => 'bar@example.com',
2032
    );
2033
    $this->drupalPost('user/register', $edit, 'Rebuild');
2034
    $this->assertText('Form rebuilt.');
2035
    $this->assertFieldByName('name', 'foo', 'Entered user name has been kept.');
2036
    $this->assertFieldByName('mail', 'bar@example.com', 'Entered mail address has been kept.');
2037
  }
2038

    
2039
  /**
2040
   * Tests a rebuild caused by a multiple value field.
2041
   */
2042
  function testUserRegistrationMultipleField() {
2043
    $edit = array(
2044
      'name' => 'foo',
2045
      'mail' => 'bar@example.com',
2046
    );
2047
    $this->drupalPost('user/register', $edit, t('Add another item'), array('query' => array('field' => TRUE)));
2048
    $this->assertText('Test a multiple valued field', 'Form has been rebuilt.');
2049
    $this->assertFieldByName('name', 'foo', 'Entered user name has been kept.');
2050
    $this->assertFieldByName('mail', 'bar@example.com', 'Entered mail address has been kept.');
2051
  }
2052
}
2053

    
2054
/**
2055
 * Tests form API file inclusion.
2056
 */
2057
class FormsFileInclusionTestCase extends DrupalWebTestCase {
2058

    
2059
  public static function getInfo() {
2060
    return array(
2061
      'name' => 'Form API file inclusion',
2062
      'description' => 'Tests form API file inclusion.',
2063
      'group' => 'Form API',
2064
    );
2065
  }
2066

    
2067
  function setUp() {
2068
    parent::setUp('form_test');
2069
  }
2070

    
2071
  /**
2072
   * Tests loading an include specified in hook_menu().
2073
   */
2074
  function testLoadMenuInclude() {
2075
    $this->drupalPostAJAX('form-test/load-include-menu', array(), array('op' => t('Save')), 'system/ajax', array(), array(), 'form-test-load-include-menu');
2076
    $this->assertText('Submit callback called.');
2077
  }
2078

    
2079
  /**
2080
   * Tests loading a custom specified inlcude.
2081
   */
2082
  function testLoadCustomInclude() {
2083
    $this->drupalPost('form-test/load-include-custom', array(), t('Save'));
2084
    $this->assertText('Submit callback called.');
2085
  }
2086
}
2087

    
2088
/**
2089
 * Tests checkbox element.
2090
 */
2091
class FormCheckboxTestCase extends DrupalWebTestCase {
2092

    
2093
  public static function getInfo() {
2094
    return array(
2095
      'name' => 'Form API checkbox',
2096
      'description' => 'Tests form API checkbox handling of various combinations of #default_value and #return_value.',
2097
      'group' => 'Form API',
2098
    );
2099
  }
2100

    
2101
  function setUp() {
2102
    parent::setUp('form_test');
2103
  }
2104

    
2105
  function testFormCheckbox() {
2106
    // Ensure that the checked state is determined and rendered correctly for
2107
    // tricky combinations of default and return values.
2108
    foreach (array(FALSE, NULL, TRUE, 0, '0', '', 1, '1', 'foobar', '1foobar') as $default_value) {
2109
      // Only values that can be used for array indeces are supported for
2110
      // #return_value, with the exception of integer 0, which is not supported.
2111
      // @see form_process_checkbox().
2112
      foreach (array('0', '', 1, '1', 'foobar', '1foobar') as $return_value) {
2113
        $form_array = drupal_get_form('form_test_checkbox_type_juggling', $default_value, $return_value);
2114
        $form = drupal_render($form_array);
2115
        if ($default_value === TRUE) {
2116
          $checked = TRUE;
2117
        }
2118
        elseif ($return_value === '0') {
2119
          $checked = ($default_value === '0');
2120
        }
2121
        elseif ($return_value === '') {
2122
          $checked = ($default_value === '');
2123
        }
2124
        elseif ($return_value === 1 || $return_value === '1') {
2125
          $checked = ($default_value === 1 || $default_value === '1');
2126
        }
2127
        elseif ($return_value === 'foobar') {
2128
          $checked = ($default_value === 'foobar');
2129
        }
2130
        elseif ($return_value === '1foobar') {
2131
          $checked = ($default_value === '1foobar');
2132
        }
2133
        $checked_in_html = strpos($form, 'checked') !== FALSE;
2134
        $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)));
2135
        $this->assertIdentical($checked, $checked_in_html, $message);
2136
      }
2137
    }
2138

    
2139
    // Ensure that $form_state['values'] is populated correctly for a checkboxes
2140
    // group that includes a 0-indexed array of options.
2141
    $results = json_decode($this->drupalPost('form-test/checkboxes-zero', array(), 'Save'));
2142
    $this->assertIdentical($results->checkbox_off, array(0, 0, 0), 'All three in checkbox_off are zeroes: off.');
2143
    $this->assertIdentical($results->checkbox_zero_default, array('0', 0, 0), 'The first choice is on in checkbox_zero_default');
2144
    $this->assertIdentical($results->checkbox_string_zero_default, array('0', 0, 0), 'The first choice is on in checkbox_string_zero_default');
2145
    $edit = array('checkbox_off[0]' => '0');
2146
    $results = json_decode($this->drupalPost('form-test/checkboxes-zero', $edit, 'Save'));
2147
    $this->assertIdentical($results->checkbox_off, array('0', 0, 0), 'The first choice is on in checkbox_off but the rest is not');
2148

    
2149
    // Ensure that each checkbox is rendered correctly for a checkboxes group
2150
    // that includes a 0-indexed array of options.
2151
    $this->drupalPost('form-test/checkboxes-zero/0', array(), 'Save');
2152
    $checkboxes = $this->xpath('//input[@type="checkbox"]');
2153
    foreach ($checkboxes as $checkbox) {
2154
      $checked = isset($checkbox['checked']);
2155
      $name = (string) $checkbox['name'];
2156
      $this->assertIdentical($checked, $name == 'checkbox_zero_default[0]' || $name == 'checkbox_string_zero_default[0]', format_string('Checkbox %name correctly checked', array('%name' => $name)));
2157
    }
2158
    $edit = array('checkbox_off[0]' => '0');
2159
    $this->drupalPost('form-test/checkboxes-zero/0', $edit, 'Save');
2160
    $checkboxes = $this->xpath('//input[@type="checkbox"]');
2161
    foreach ($checkboxes as $checkbox) {
2162
      $checked = isset($checkbox['checked']);
2163
      $name = (string) $checkbox['name'];
2164
      $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)));
2165
    }
2166
  }
2167
}
2168

    
2169
/**
2170
 * Tests uniqueness of generated HTML IDs.
2171
 */
2172
class HTMLIdTestCase extends DrupalWebTestCase {
2173

    
2174
  public static function getInfo() {
2175
    return array(
2176
      'name' => 'Unique HTML IDs',
2177
      'description' => 'Tests functionality of drupal_html_id().',
2178
      'group' => 'Form API',
2179
    );
2180
  }
2181

    
2182
  function setUp() {
2183
    parent::setUp('form_test');
2184
  }
2185

    
2186
  /**
2187
   * Tests that HTML IDs do not get duplicated when form validation fails.
2188
   */
2189
  function testHTMLId() {
2190
    $this->drupalGet('form-test/double-form');
2191
    $this->assertNoDuplicateIds('There are no duplicate IDs');
2192

    
2193
    // Submit second form with empty title.
2194
    $edit = array();
2195
    $this->drupalPost(NULL, $edit, 'Save', array(), array(), 'form-test-html-id--2');
2196
    $this->assertNoDuplicateIds('There are no duplicate IDs');
2197
  }
2198
}
2199

    
2200
/**
2201
 * Tests for form textarea.
2202
 */
2203
class FormTextareaTestCase extends DrupalUnitTestCase {
2204

    
2205
  public static function getInfo() {
2206
    return array(
2207
      'name' => 'Form textarea',
2208
      'description' => 'Tests form textarea related functions.',
2209
      'group' => 'Form API',
2210
    );
2211
  }
2212

    
2213
  /**
2214
   * Tests that textarea value is properly set.
2215
   */
2216
  public function testValueCallback() {
2217
    $element = array();
2218
    $form_state = array();
2219
    $test_cases = array(
2220
      array(NULL, FALSE),
2221
      array(NULL, NULL),
2222
      array('', array('test')),
2223
      array('test', 'test'),
2224
      array('123', 123),
2225
    );
2226
    foreach ($test_cases as $test_case) {
2227
      list($expected, $input) = $test_case;
2228
      $this->assertIdentical($expected, form_type_textarea_value($element, $input, $form_state));
2229
    }
2230
  }
2231
}