Projet

Général

Profil

Paste
Télécharger (89,2 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / simpletest / tests / form.test @ 1afa1695

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
    // This is the main function we want to test: it is responsible for
525
    // populating user supplied $form_state['input'] to sanitized
526
    // $form_state['values'].
527
    form_builder($form_id, $form, $form_state);
528

    
529
    $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)));
530
  }
531
}
532

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

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

    
547
  function setUp() {
548
    parent::setUp(array('form_test'));
549
  }
550

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

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

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

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

    
593
/**
594
 * Test form alter hooks.
595
 */
596
class FormAlterTestCase extends DrupalWebTestCase {
597
  public static function getInfo() {
598
    return array(
599
      'name' => 'Form alter hooks',
600
      'description' => 'Tests hook_form_alter() and hook_form_FORM_ID_alter().',
601
      'group' => 'Form API',
602
    );
603
  }
604

    
605
  function setUp() {
606
    parent::setUp('form_test');
607
  }
608

    
609
  /**
610
   * Tests execution order of hook_form_alter() and hook_form_FORM_ID_alter().
611
   */
612
  function testExecutionOrder() {
613
    $this->drupalGet('form-test/alter');
614
    // Ensure that the order is first by module, then for a given module, the
615
    // id-specific one after the generic one.
616
    $expected = array(
617
      'block_form_form_test_alter_form_alter() executed.',
618
      'form_test_form_alter() executed.',
619
      'form_test_form_form_test_alter_form_alter() executed.',
620
      'system_form_form_test_alter_form_alter() executed.',
621
    );
622
    $content = preg_replace('/\s+/', ' ', filter_xss($this->content, array()));
623
    $this->assert(strpos($content, implode(' ', $expected)) !== FALSE, 'Form alter hooks executed in the expected order.');
624
  }
625
}
626

    
627
/**
628
 * Test form validation handlers.
629
 */
630
class FormValidationTestCase extends DrupalWebTestCase {
631
  public static function getInfo() {
632
    return array(
633
      'name' => 'Form validation handlers',
634
      'description' => 'Tests form processing and alteration via form validation handlers.',
635
      'group' => 'Form API',
636
    );
637
  }
638

    
639
  function setUp() {
640
    parent::setUp('form_test');
641
  }
642

    
643
  /**
644
   * Tests form alterations by #element_validate, #validate, and form_set_value().
645
   */
646
  function testValidate() {
647
    $this->drupalGet('form-test/validate');
648
    // Verify that #element_validate handlers can alter the form and submitted
649
    // form values.
650
    $edit = array(
651
      'name' => 'element_validate',
652
    );
653
    $this->drupalPost(NULL, $edit, 'Save');
654
    $this->assertFieldByName('name', '#value changed by #element_validate', 'Form element #value was altered.');
655
    $this->assertText('Name value: value changed by form_set_value() in #element_validate', 'Form element value in $form_state was altered.');
656

    
657
    // Verify that #validate handlers can alter the form and submitted
658
    // form values.
659
    $edit = array(
660
      'name' => 'validate',
661
    );
662
    $this->drupalPost(NULL, $edit, 'Save');
663
    $this->assertFieldByName('name', '#value changed by #validate', 'Form element #value was altered.');
664
    $this->assertText('Name value: value changed by form_set_value() in #validate', 'Form element value in $form_state was altered.');
665

    
666
    // Verify that #element_validate handlers can make form elements
667
    // inaccessible, but values persist.
668
    $edit = array(
669
      'name' => 'element_validate_access',
670
    );
671
    $this->drupalPost(NULL, $edit, 'Save');
672
    $this->assertNoFieldByName('name', 'Form element was hidden.');
673
    $this->assertText('Name value: element_validate_access', 'Value for inaccessible form element exists.');
674

    
675
    // Verify that value for inaccessible form element persists.
676
    $this->drupalPost(NULL, array(), 'Save');
677
    $this->assertNoFieldByName('name', 'Form element was hidden.');
678
    $this->assertText('Name value: element_validate_access', 'Value for inaccessible form element exists.');
679

    
680
    // Verify that #validate handlers don't run if the CSRF token is invalid.
681
    $this->drupalLogin($this->drupalCreateUser());
682
    $this->drupalGet('form-test/validate');
683
    $edit = array(
684
      'name' => 'validate',
685
      'form_token' => 'invalid token'
686
    );
687
    $this->drupalPost(NULL, $edit, 'Save');
688
    $this->assertNoFieldByName('name', '#value changed by #validate', 'Form element #value was not altered.');
689
    $this->assertNoText('Name value: value changed by form_set_value() in #validate', 'Form element value in $form_state was not altered.');
690
    $this->assertText('The form has become outdated. Copy any unsaved work in the form below');
691
  }
692

    
693
  /**
694
   * Tests partial form validation through #limit_validation_errors.
695
   */
696
  function testValidateLimitErrors() {
697
    $edit = array(
698
      'test' => 'invalid',
699
      'test_numeric_index[0]' => 'invalid',
700
      'test_substring[foo]' => 'invalid',
701
    );
702
    $path = 'form-test/limit-validation-errors';
703

    
704
    // Submit the form by pressing the 'Partial validate' button (uses
705
    // #limit_validation_errors) and ensure that the title field is not
706
    // validated, but the #element_validate handler for the 'test' field
707
    // is triggered.
708
    $this->drupalPost($path, $edit, t('Partial validate'));
709
    $this->assertNoText(t('!name field is required.', array('!name' => 'Title')));
710
    $this->assertText('Test element is invalid');
711

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

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

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

    
728
    // Now test full form validation and ensure that the #element_validate
729
    // handler is still triggered.
730
    $this->drupalPost($path, $edit, t('Full validate'));
731
    $this->assertText(t('!name field is required.', array('!name' => 'Title')));
732
    $this->assertText('Test element is invalid');
733
  }
734

    
735
  /**
736
   *  Tests error border of multiple fields with same name in a page.
737
   */
738
  function testMultiFormSameNameErrorClass() {
739
    $this->drupalGet('form-test/double-form');
740
    $edit = array();
741
    $this->drupalPost(NULL, $edit, t('Save'));
742
    $this->assertFieldByXpath('//input[@id="edit-name" and contains(@class, "error")]', NULL, 'Error input form element class found for first element.');
743
    $this->assertNoFieldByXpath('//input[@id="edit-name--2" and contains(@class, "error")]', NULL, 'No error input form element class found for second element.');
744
  }
745
}
746

    
747
/**
748
 * Test form element labels, required markers and associated output.
749
 */
750
class FormsElementsLabelsTestCase extends DrupalWebTestCase {
751

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

    
760
  function setUp() {
761
    parent::setUp('form_test');
762
  }
763

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
826
    // Check title attribute for radios and checkboxes.
827
    $elements = $this->xpath('//div[@id="edit-form-checkboxes-title-attribute"]');
828
    $this->assertEqual($elements[0]['title'], 'Checkboxes test' . ' (' . t('Required') . ')', 'Title attribute found.');
829
    $elements = $this->xpath('//div[@id="edit-form-radios-title-attribute"]');
830
    $this->assertEqual($elements[0]['title'], 'Radios test' . ' (' . t('Required') . ')', 'Title attribute found.');
831
  }
832
}
833

    
834
/**
835
 * Test the tableselect form element for expected behavior.
836
 */
837
class FormsElementsTableSelectFunctionalTest extends DrupalWebTestCase {
838

    
839
  public static function getInfo() {
840
    return array(
841
      'name' => 'Tableselect form element type test',
842
      'description' => 'Test the tableselect element for expected behavior',
843
      'group' => 'Form API',
844
    );
845
  }
846

    
847
  function setUp() {
848
    parent::setUp('form_test');
849
  }
850

    
851

    
852
  /**
853
   * Test the display of checkboxes when #multiple is TRUE.
854
   */
855
  function testMultipleTrue() {
856

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

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

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

    
864
    $rows = array('row1', 'row2', 'row3');
865
    foreach ($rows as $row) {
866
      $this->assertFieldByXPath('//input[@type="checkbox"]', $row, format_string('Checkbox for value @row.', array('@row' => $row)));
867
    }
868
  }
869

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

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

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

    
881
    $rows = array('row1', 'row2', 'row3');
882
    foreach ($rows as $row) {
883
      $this->assertFieldByXPath('//input[@type="radio"]', $row, format_string('Radio button for value @row.', array('@row' => $row)));
884
    }
885
  }
886

    
887
  /**
888
   * Test the display of the #empty text when #options is an empty array.
889
   */
890
  function testEmptyText() {
891
    $this->drupalGet('form_test/tableselect/empty-text');
892
    $this->assertText(t('Empty text.'), 'Empty text should be displayed.');
893
  }
894

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

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

    
905
    $this->assertText(t('Submitted: row1 = row1'), 'Checked checkbox row1');
906
    $this->assertText(t('Submitted: row2 = 0'), 'Unchecked checkbox row2.');
907
    $this->assertText(t('Submitted: row3 = 0'), 'Unchecked checkbox row3.');
908

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

    
914
    $this->assertText(t('Submitted: row1 = row1'), 'Checked checkbox row1.');
915
    $this->assertText(t('Submitted: row2 = 0'), 'Unchecked checkbox row2.');
916
    $this->assertText(t('Submitted: row3 = row3'), 'Checked checkbox row3.');
917

    
918
  }
919

    
920
  /**
921
   * Test submission of values when #multiple is FALSE.
922
   */
923
  function testMultipleFalseSubmit() {
924
    $edit['tableselect'] = 'row1';
925
    $this->drupalPost('form_test/tableselect/multiple-false', $edit, 'Submit');
926
    $this->assertText(t('Submitted: row1'), 'Selected radio button');
927
  }
928

    
929
  /**
930
   * Test the #js_select property.
931
   */
932
  function testAdvancedSelect() {
933
    // When #multiple = TRUE a Select all checkbox should be displayed by default.
934
    $this->drupalGet('form_test/tableselect/advanced-select/multiple-true-default');
935
    $this->assertFieldByXPath('//th[@class="select-all"]', NULL, 'Display a "Select all" checkbox by default when #multiple is TRUE.');
936

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

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

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

    
949

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

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

    
957
    $form['tableselect'] = array(
958
      '#type' => 'tableselect',
959
      '#header' => $header,
960
      '#options' => $options,
961
    );
962

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

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

    
971
  }
972

    
973

    
974
  /**
975
   * Test the whether the option checker gives an error on invalid tableselect values for radios.
976
   */
977
  function testMultipleFalseOptionchecker() {
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
      '#multiple' => FALSE,
986
    );
987

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

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

    
997

    
998
  /**
999
   * Helper function for the option check test to submit a form while collecting errors.
1000
   *
1001
   * @param $form_element
1002
   *   A form element to test.
1003
   * @param $edit
1004
   *   An array containing post data.
1005
   *
1006
   * @return
1007
   *   An array containing the processed form, the form_state and any errors.
1008
   */
1009
  private function formSubmitHelper($form, $edit) {
1010
    $form_id = $this->randomName();
1011
    $form_state = form_state_defaults();
1012

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

    
1015
    $form_state['input'] = $edit;
1016
    $form_state['input']['form_id'] = $form_id;
1017

    
1018
    // The form token CSRF protection should not interfere with this test,
1019
    // so we bypass it by marking this test form as programmed.
1020
    $form_state['programmed'] = TRUE;
1021

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

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

    
1026
    $errors = form_get_errors();
1027

    
1028
    // Clear errors and messages.
1029
    drupal_get_messages();
1030
    form_clear_error();
1031

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

    
1037
}
1038

    
1039
/**
1040
 * Test the vertical_tabs form element for expected behavior.
1041
 */
1042
class FormsElementsVerticalTabsFunctionalTest extends DrupalWebTestCase {
1043

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

    
1052
  function setUp() {
1053
    parent::setUp('form_test');
1054
  }
1055

    
1056
  /**
1057
   * Ensures that vertical-tabs.js is included before collapse.js.
1058
   *
1059
   * Otherwise, collapse.js adds "SHOW" or "HIDE" labels to the tabs.
1060
   */
1061
  function testJavaScriptOrdering() {
1062
    $this->drupalGet('form_test/vertical-tabs');
1063
    $position1 = strpos($this->content, 'misc/vertical-tabs.js');
1064
    $position2 = strpos($this->content, 'misc/collapse.js');
1065
    $this->assertTrue($position1 !== FALSE && $position2 !== FALSE && $position1 < $position2, 'vertical-tabs.js is included before collapse.js');
1066
  }
1067
}
1068

    
1069
/**
1070
 * Test the form storage on a multistep form.
1071
 *
1072
 * The tested form puts data into the storage during the initial form
1073
 * construction. These tests verify that there are no duplicate form
1074
 * constructions, with and without manual form caching activiated. Furthermore
1075
 * when a validation error occurs, it makes sure that changed form element
1076
 * values aren't lost due to a wrong form rebuild.
1077
 */
1078
class FormsFormStorageTestCase extends DrupalWebTestCase {
1079

    
1080
  public static function getInfo() {
1081
    return array(
1082
      'name'  => 'Multistep form using form storage',
1083
      'description'  => 'Tests a multistep form using form storage and makes sure validation and caching works right.',
1084
      'group' => 'Form API',
1085
    );
1086
  }
1087

    
1088
  function setUp() {
1089
    parent::setUp('form_test');
1090

    
1091
    $this->web_user = $this->drupalCreateUser(array('access content'));
1092
    $this->drupalLogin($this->web_user);
1093
  }
1094

    
1095
  /**
1096
   * Tests using the form in a usual way.
1097
   */
1098
  function testForm() {
1099
    $this->drupalGet('form_test/form-storage');
1100
    $this->assertText('Form constructions: 1');
1101

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

    
1104
    // Use form rebuilding triggered by a submit button.
1105
    $this->drupalPost(NULL, $edit, 'Continue submit');
1106
    $this->assertText('Form constructions: 2');
1107
    $this->assertText('Form constructions: 3');
1108

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

    
1116
    $this->drupalPost(NULL, $edit, 'Save');
1117
    $this->assertText('Form constructions: 4');
1118
    $this->assertText('Title: new', 'The form storage has stored the values.');
1119
  }
1120

    
1121
  /**
1122
   * Tests using the form with an activated $form_state['cache'] property.
1123
   */
1124
  function testFormCached() {
1125
    $this->drupalGet('form_test/form-storage', array('query' => array('cache' => 1)));
1126
    $this->assertText('Form constructions: 1');
1127

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

    
1130
    // Use form rebuilding triggered by a submit button.
1131
    $this->drupalPost(NULL, $edit, 'Continue submit');
1132
    $this->assertText('Form constructions: 2');
1133

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

    
1140
    $this->drupalPost(NULL, $edit, 'Save');
1141
    $this->assertText('Form constructions: 3');
1142
    $this->assertText('Title: new', 'The form storage has stored the values.');
1143
  }
1144

    
1145
  /**
1146
   * Tests validation when form storage is used.
1147
   */
1148
  function testValidation() {
1149
    $this->drupalPost('form_test/form-storage', array('title' => '', 'value' => 'value_is_set'), 'Continue submit');
1150
    $this->assertPattern('/value_is_set/', 'The input values have been kept.');
1151
  }
1152

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

    
1167
    // Skip step 1 of the multi-step form, since the first step copies over
1168
    // 'title' into form storage, but we want to verify that changes in the form
1169
    // storage are updated in the cache during form validation.
1170
    $edit = array('title' => 'foo');
1171
    $this->drupalPost(NULL, $edit, 'Continue submit');
1172

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

    
1180
    // At this point, the form storage should contain updated values, but we do
1181
    // not see them, because the form has not been rebuilt yet due to the
1182
    // validation error. Post again and verify that the rebuilt form contains
1183
    // the values of the updated form storage.
1184
    $this->drupalPost(NULL, array('title' => 'foo', 'value' => 'bar'), 'Save');
1185
    $this->assertText("The thing has been changed.", 'The altered form storage value was updated in cache and taken over.');
1186
  }
1187

    
1188
  /**
1189
   * Tests a form using form state without using 'storage' to pass data from the
1190
   * constructor to a submit handler. The data has to persist even when caching
1191
   * gets activated, what may happen when a modules alter the form and adds
1192
   * #ajax properties.
1193
   */
1194
  function testFormStatePersist() {
1195
    // Test the form one time with caching activated and one time without.
1196
    $run_options = array(
1197
      array(),
1198
      array('query' => array('cache' => 1)),
1199
    );
1200
    foreach ($run_options as $options) {
1201
      $this->drupalPost('form-test/state-persist', array(), t('Submit'), $options);
1202
      // The submit handler outputs the value in $form_state, assert it's there.
1203
      $this->assertText('State persisted.');
1204

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

    
1212
      // Now post to the rebuilt form and verify it's still there afterwards.
1213
      $this->drupalPost(NULL, array('title' => 'bar'), t('Submit'), $options);
1214
      $this->assertText('State persisted.');
1215
    }
1216
  }
1217

    
1218
  /**
1219
   * Verify that the form build-id remains the same when validation errors
1220
   * occur on a mutable form.
1221
   */
1222
  function testMutableForm() {
1223
    // Request the form with 'cache' query parameter to enable form caching.
1224
    $this->drupalGet('form_test/form-storage', array('query' => array('cache' => 1)));
1225
    $buildIdFields = $this->xpath('//input[@name="form_build_id"]');
1226
    $this->assertEqual(count($buildIdFields), 1, 'One form build id field on the page');
1227
    $buildId = (string) $buildIdFields[0]['value'];
1228

    
1229
    // Trigger validation error by submitting an empty title.
1230
    $edit = array('title' => '');
1231
    $this->drupalPost(NULL, $edit, 'Continue submit');
1232

    
1233
    // Verify that the build-id did not change.
1234
    $this->assertFieldByName('form_build_id', $buildId, 'Build id remains the same when form validation fails');
1235
  }
1236

    
1237
  /**
1238
   * Verifies that form build-id is regenerated when loading an immutable form
1239
   * from the cache.
1240
   */
1241
  function testImmutableForm() {
1242
    // Request the form with 'cache' query parameter to enable form caching.
1243
    $this->drupalGet('form_test/form-storage', array('query' => array('cache' => 1, 'immutable' => 1)));
1244
    $buildIdFields = $this->xpath('//input[@name="form_build_id"]');
1245
    $this->assertEqual(count($buildIdFields), 1, 'One form build id field on the page');
1246
    $buildId = (string) $buildIdFields[0]['value'];
1247

    
1248
    // Trigger validation error by submitting an empty title.
1249
    $edit = array('title' => '');
1250
    $this->drupalPost(NULL, $edit, 'Continue submit');
1251

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

    
1255
    // Retrieve the new build-id.
1256
    $buildIdFields = $this->xpath('//input[@name="form_build_id"]');
1257
    $this->assertEqual(count($buildIdFields), 1, 'One form build id field on the page');
1258
    $buildId = (string) $buildIdFields[0]['value'];
1259

    
1260
    // Trigger validation error by again submitting an empty title.
1261
    $edit = array('title' => '');
1262
    $this->drupalPost(NULL, $edit, 'Continue submit');
1263

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

    
1268
  /**
1269
   * Verify that existing contrib code cannot overwrite immutable form state.
1270
   */
1271
  public function testImmutableFormLegacyProtection() {
1272
    $this->drupalGet('form_test/form-storage', array('query' => array('cache' => 1, 'immutable' => 1)));
1273
    $build_id_fields = $this->xpath('//input[@name="form_build_id"]');
1274
    $this->assertEqual(count($build_id_fields), 1, 'One form build id field on the page');
1275
    $build_id = (string) $build_id_fields[0]['value'];
1276

    
1277
    // Try to poison the form cache.
1278
    $original = $this->drupalGetAJAX('form_test/form-storage-legacy/' . $build_id);
1279
    $this->assertEqual($original['form']['#build_id_old'], $build_id, 'Original build_id was recorded');
1280
    $this->assertNotEqual($original['form']['#build_id'], $build_id, 'New build_id was generated');
1281

    
1282
    // Assert that a watchdog message was logged by form_set_cache.
1283
    $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.'));
1284
    $this->assert($status, 'A watchdog message was logged by form_set_cache');
1285

    
1286
    // Ensure that the form state was not poisoned by the preceeding call.
1287
    $original = $this->drupalGetAJAX('form_test/form-storage-legacy/' . $build_id);
1288
    $this->assertEqual($original['form']['#build_id_old'], $build_id, 'Original build_id was recorded');
1289
    $this->assertNotEqual($original['form']['#build_id'], $build_id, 'New build_id was generated');
1290
    $this->assert(empty($original['form']['#poisoned']), 'Original form structure was preserved');
1291
    $this->assert(empty($original['form_state']['poisoned']), 'Original form state was preserved');
1292
  }
1293
}
1294

    
1295
/**
1296
 * Test the form storage when page caching for anonymous users is turned on.
1297
 */
1298
class FormsFormStoragePageCacheTestCase extends DrupalWebTestCase {
1299
  protected $profile = 'testing';
1300

    
1301
  public static function getInfo() {
1302
    return array(
1303
      'name'  => 'Forms using form storage on cached pages',
1304
      'description'  => 'Tests a form using form storage and makes sure validation and caching works when page caching for anonymous users is turned on.',
1305
      'group' => 'Form API',
1306
    );
1307
  }
1308

    
1309
  public function setUp() {
1310
    parent::setUp('form_test');
1311

    
1312
    variable_set('cache', TRUE);
1313
  }
1314

    
1315
  /**
1316
   * Return the build id of the current form.
1317
   */
1318
  protected function getFormBuildId() {
1319
    $build_id_fields = $this->xpath('//input[@name="form_build_id"]');
1320
    $this->assertEqual(count($build_id_fields), 1, 'One form build id field on the page');
1321
    return (string) $build_id_fields[0]['value'];
1322
  }
1323

    
1324
  /**
1325
   * Build-id is regenerated when validating cached form.
1326
   */
1327
  public function testValidateFormStorageOnCachedPage() {
1328
    $this->drupalGet('form_test/form-storage-page-cache');
1329
    $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Page was not cached.');
1330
    $this->assertText('No old build id', 'No old build id on the page');
1331
    $build_id_initial = $this->getFormBuildId();
1332

    
1333
    // Trigger validation error by submitting an empty title.
1334
    $edit = array('title' => '');
1335
    $this->drupalPost(NULL, $edit, 'Save');
1336
    $this->assertText($build_id_initial, 'Old build id on the page');
1337
    $build_id_first_validation = $this->getFormBuildId();
1338
    $this->assertNotEqual($build_id_initial, $build_id_first_validation, 'Build id changes when form validation fails');
1339

    
1340
    // Trigger validation error by again submitting an empty title.
1341
    $edit = array('title' => '');
1342
    $this->drupalPost(NULL, $edit, 'Save');
1343
    $this->assertText('No old build id', 'No old build id on the page');
1344
    $build_id_second_validation = $this->getFormBuildId();
1345
    $this->assertEqual($build_id_first_validation, $build_id_second_validation, 'Build id remains the same when form validation fails subsequently');
1346

    
1347
    // Repeat the test sequence but this time with a page loaded from the cache.
1348
    $this->drupalGet('form_test/form-storage-page-cache');
1349
    $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
1350
    $this->assertText('No old build id', 'No old build id on the page');
1351
    $build_id_from_cache_initial = $this->getFormBuildId();
1352
    $this->assertEqual($build_id_initial, $build_id_from_cache_initial, 'Build id is the same as on the first request');
1353

    
1354
    // Trigger validation error by submitting an empty title.
1355
    $edit = array('title' => '');
1356
    $this->drupalPost(NULL, $edit, 'Save');
1357
    $this->assertText($build_id_initial, 'Old build id is initial build id');
1358
    $build_id_from_cache_first_validation = $this->getFormBuildId();
1359
    $this->assertNotEqual($build_id_initial, $build_id_from_cache_first_validation, 'Build id changes when form validation fails');
1360
    $this->assertNotEqual($build_id_first_validation, $build_id_from_cache_first_validation, 'Build id from first user is not reused');
1361

    
1362
    // Trigger validation error by again submitting an empty title.
1363
    $edit = array('title' => '');
1364
    $this->drupalPost(NULL, $edit, 'Save');
1365
    $this->assertText('No old build id', 'No old build id on the page');
1366
    $build_id_from_cache_second_validation = $this->getFormBuildId();
1367
    $this->assertEqual($build_id_from_cache_first_validation, $build_id_from_cache_second_validation, 'Build id remains the same when form validation fails subsequently');
1368
  }
1369

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

    
1379
    // Trigger rebuild, should regenerate build id.
1380
    $edit = array('title' => 'something');
1381
    $this->drupalPost(NULL, $edit, 'Rebuild');
1382
    $this->assertText($build_id_initial, 'Initial build id as old build id on the page');
1383
    $build_id_first_rebuild = $this->getFormBuildId();
1384
    $this->assertNotEqual($build_id_initial, $build_id_first_rebuild, 'Build id changes on first rebuild.');
1385

    
1386
    // Trigger subsequent rebuild, should regenerate the build id again.
1387
    $edit = array('title' => 'something');
1388
    $this->drupalPost(NULL, $edit, 'Rebuild');
1389
    $this->assertText($build_id_first_rebuild, 'First build id as old build id on the page');
1390
    $build_id_second_rebuild = $this->getFormBuildId();
1391
    $this->assertNotEqual($build_id_first_rebuild, $build_id_second_rebuild, 'Build id changes on second rebuild.');
1392
  }
1393
}
1394

    
1395
/**
1396
 * Test wrapper form callbacks.
1397
 */
1398
class FormsFormWrapperTestCase extends DrupalWebTestCase {
1399
  public static function getInfo() {
1400
    return array(
1401
      'name' => 'Form wrapper callback',
1402
      'description' => 'Tests form wrapper callbacks to pass a prebuilt form to form builder functions.',
1403
      'group' => 'Form API',
1404
    );
1405
  }
1406

    
1407
  function setUp() {
1408
    parent::setUp('form_test');
1409
  }
1410

    
1411
  /**
1412
   * Tests using the form in a usual way.
1413
   */
1414
  function testWrapperCallback() {
1415
    $this->drupalGet('form_test/wrapper-callback');
1416
    $this->assertText('Form wrapper callback element output.', 'The form contains form wrapper elements.');
1417
    $this->assertText('Form builder element output.', 'The form contains form builder elements.');
1418
  }
1419
}
1420

    
1421
/**
1422
 * Test $form_state clearance.
1423
 */
1424
class FormStateValuesCleanTestCase extends DrupalWebTestCase {
1425
  public static function getInfo() {
1426
    return array(
1427
      'name' => 'Form state values clearance',
1428
      'description' => 'Test proper removal of submitted form values using form_state_values_clean().',
1429
      'group' => 'Form API',
1430
    );
1431
  }
1432

    
1433
  function setUp() {
1434
    parent::setUp('form_test');
1435
  }
1436

    
1437
  /**
1438
   * Tests form_state_values_clean().
1439
   */
1440
  function testFormStateValuesClean() {
1441
    $values = drupal_json_decode($this->drupalPost('form_test/form-state-values-clean', array(), t('Submit')));
1442

    
1443
    // Setup the expected result.
1444
    $result = array(
1445
      'beer' => 1000,
1446
      'baz' => array('beer' => 2000),
1447
    );
1448

    
1449
    // Verify that all internal Form API elements were removed.
1450
    $this->assertFalse(isset($values['form_id']), format_string('%element was removed.', array('%element' => 'form_id')));
1451
    $this->assertFalse(isset($values['form_token']), format_string('%element was removed.', array('%element' => 'form_token')));
1452
    $this->assertFalse(isset($values['form_build_id']), format_string('%element was removed.', array('%element' => 'form_build_id')));
1453
    $this->assertFalse(isset($values['op']), format_string('%element was removed.', array('%element' => 'op')));
1454

    
1455
    // Verify that all buttons were removed.
1456
    $this->assertFalse(isset($values['foo']), format_string('%element was removed.', array('%element' => 'foo')));
1457
    $this->assertFalse(isset($values['bar']), format_string('%element was removed.', array('%element' => 'bar')));
1458
    $this->assertFalse(isset($values['baz']['foo']), format_string('%element was removed.', array('%element' => 'foo')));
1459
    $this->assertFalse(isset($values['baz']['baz']), format_string('%element was removed.', array('%element' => 'baz')));
1460

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

    
1464
    // Verify that actual form values equal resulting form values.
1465
    $this->assertEqual($values, $result, 'Expected form values equal actual form values.');
1466
  }
1467
}
1468

    
1469
/**
1470
 * Tests $form_state clearance with form elements having buttons.
1471
 */
1472
class FormStateValuesCleanAdvancedTestCase extends DrupalWebTestCase {
1473
  /**
1474
   * An image file path for uploading.
1475
   */
1476
  protected $image;
1477

    
1478
  public static function getInfo() {
1479
    return array(
1480
      'name' => 'Form state values clearance (advanced)',
1481
      'description' => 'Test proper removal of submitted form values using form_state_values_clean() when having forms with elements containing buttons like "managed_file".',
1482
      'group' => 'Form API',
1483
    );
1484
  }
1485

    
1486
  function setUp() {
1487
    parent::setUp('form_test');
1488
  }
1489

    
1490
  /**
1491
   * Tests form_state_values_clean().
1492
   */
1493
  function testFormStateValuesCleanAdvanced() {
1494

    
1495
    // Get an image for uploading.
1496
    $image_files = $this->drupalGetTestFiles('image');
1497
    $this->image = current($image_files);
1498

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

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

    
1505
    // Post the form.
1506
    $this->drupalPost('form_test/form-state-values-clean-advanced', $edit, t('Submit'));
1507

    
1508
    // Expecting a 200 HTTP code.
1509
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
1510
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
1511
  }
1512
}
1513

    
1514
/**
1515
 * Tests form rebuilding.
1516
 *
1517
 * @todo Add tests for other aspects of form rebuilding.
1518
 */
1519
class FormsRebuildTestCase extends DrupalWebTestCase {
1520
  public static function getInfo() {
1521
    return array(
1522
      'name' => 'Form rebuilding',
1523
      'description' => 'Tests functionality of drupal_rebuild_form().',
1524
      'group' => 'Form API',
1525
    );
1526
  }
1527

    
1528
  function setUp() {
1529
    parent::setUp('form_test');
1530

    
1531
    $this->web_user = $this->drupalCreateUser(array('access content'));
1532
    $this->drupalLogin($this->web_user);
1533
  }
1534

    
1535
  /**
1536
   * Tests preservation of values.
1537
   */
1538
  function testRebuildPreservesValues() {
1539
    $edit = array(
1540
      'checkbox_1_default_off' => TRUE,
1541
      'checkbox_1_default_on' => FALSE,
1542
      'text_1' => 'foo',
1543
    );
1544
    $this->drupalPost('form-test/form-rebuild-preserve-values', $edit, 'Add more');
1545

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

    
1551
    // Verify that newly added elements were initialized with their default values.
1552
    $this->assertFieldChecked('edit-checkbox-2-default-on', 'A newly added checkbox was initialized with a default checked state.');
1553
    $this->assertNoFieldChecked('edit-checkbox-2-default-off', 'A newly added checkbox was initialized with a default unchecked state.');
1554
    $this->assertFieldById('edit-text-2', 'DEFAULT 2', 'A newly added textfield was initialized with its default value.');
1555
  }
1556

    
1557
  /**
1558
   * Tests that a form's action is retained after an Ajax submission.
1559
   *
1560
   * The 'action' attribute of a form should not change after an Ajax submission
1561
   * followed by a non-Ajax submission, which triggers a validation error.
1562
   */
1563
  function testPreserveFormActionAfterAJAX() {
1564
    // Create a multi-valued field for 'page' nodes to use for Ajax testing.
1565
    $field_name = 'field_ajax_test';
1566
    $field = array(
1567
      'field_name' => $field_name,
1568
      'type' => 'text',
1569
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
1570
    );
1571
    field_create_field($field);
1572
    $instance = array(
1573
      'field_name' => $field_name,
1574
      'entity_type' => 'node',
1575
      'bundle' => 'page',
1576
    );
1577
    field_create_instance($instance);
1578

    
1579
    // Log in a user who can create 'page' nodes.
1580
    $this->web_user = $this->drupalCreateUser(array('create page content'));
1581
    $this->drupalLogin($this->web_user);
1582

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

    
1590
    // Submit the form with the non-Ajax "Save" button, leaving the title field
1591
    // blank to trigger a validation error, and ensure that a validation error
1592
    // occurred, because this test is for testing what happens when a form is
1593
    // re-rendered without being re-built, which is what happens when there's
1594
    // a validation error.
1595
    $this->drupalPost(NULL, array(), t('Save'));
1596
    $this->assertText('Title field is required.', 'Non-AJAX submission correctly triggered a validation error.');
1597

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

    
1602
    // Ensure that the form's action is correct.
1603
    $forms = $this->xpath('//form[contains(@class, "node-page-form")]');
1604
    $this->assert(count($forms) == 1 && $forms[0]['action'] == url('node/add/page'), 'Re-rendered form contains the correct action value.');
1605
  }
1606
}
1607

    
1608
/**
1609
 * Tests form redirection.
1610
 */
1611
class FormsRedirectTestCase extends DrupalWebTestCase {
1612

    
1613
  public static function getInfo() {
1614
    return array(
1615
      'name' => 'Form redirecting',
1616
      'description' => 'Tests functionality of drupal_redirect_form().',
1617
      'group' => 'Form API',
1618
    );
1619
  }
1620

    
1621
  function setUp() {
1622
    parent::setUp(array('form_test'));
1623
  }
1624

    
1625
  /**
1626
   * Tests form redirection.
1627
   */
1628
  function testRedirect() {
1629
    $path = 'form-test/redirect';
1630
    $options = array('query' => array('foo' => 'bar'));
1631
    $options['absolute'] = TRUE;
1632

    
1633
    // Test basic redirection.
1634
    $edit = array(
1635
      'redirection' => TRUE,
1636
      'destination' => $this->randomName(),
1637
    );
1638
    $this->drupalPost($path, $edit, t('Submit'));
1639
    $this->assertUrl($edit['destination'], array(), 'Basic redirection works.');
1640

    
1641

    
1642
    // Test without redirection.
1643
    $edit = array(
1644
      'redirection' => FALSE,
1645
    );
1646
    $this->drupalPost($path, $edit, t('Submit'));
1647
    $this->assertUrl($path, array(), 'When redirect is set to FALSE, there should be no redirection.');
1648

    
1649
    // Test redirection with query parameters.
1650
    $edit = array(
1651
      'redirection' => TRUE,
1652
      'destination' => $this->randomName(),
1653
    );
1654
    $this->drupalPost($path, $edit, t('Submit'), $options);
1655
    $this->assertUrl($edit['destination'], array(), 'Redirection with query parameters works.');
1656

    
1657
    // Test without redirection but with query parameters.
1658
    $edit = array(
1659
      'redirection' => FALSE,
1660
    );
1661
    $this->drupalPost($path, $edit, t('Submit'), $options);
1662
    $this->assertUrl($path, $options, 'When redirect is set to FALSE, there should be no redirection, and the query parameters should be passed along.');
1663

    
1664
    // Test redirection back to the original path.
1665
    $edit = array(
1666
      'redirection' => TRUE,
1667
      'destination' => '',
1668
    );
1669
    $this->drupalPost($path, $edit, t('Submit'));
1670
    $this->assertUrl($path, array(), 'When using an empty redirection string, there should be no redirection.');
1671

    
1672
    // Test redirection back to the original path with query parameters.
1673
    $edit = array(
1674
      'redirection' => TRUE,
1675
      'destination' => '',
1676
    );
1677
    $this->drupalPost($path, $edit, t('Submit'), $options);
1678
    $this->assertUrl($path, $options, 'When using an empty redirection string, there should be no redirection, and the query parameters should be passed along.');
1679
  }
1680

    
1681
}
1682

    
1683
/**
1684
 * Test the programmatic form submission behavior.
1685
 */
1686
class FormsProgrammaticTestCase extends DrupalWebTestCase {
1687

    
1688
  public static function getInfo() {
1689
    return array(
1690
      'name' => 'Programmatic form submissions',
1691
      'description' => 'Test the programmatic form submission behavior.',
1692
      'group' => 'Form API',
1693
    );
1694
  }
1695

    
1696
  function setUp() {
1697
    parent::setUp('form_test');
1698
  }
1699

    
1700
  /**
1701
   * Test the programmatic form submission workflow.
1702
   */
1703
  function testSubmissionWorkflow() {
1704
    // Backup the current batch status and reset it to avoid conflicts while
1705
    // processing the dummy form submit handler.
1706
    $current_batch = $batch =& batch_get();
1707
    $batch = array();
1708

    
1709
    // Test that a programmatic form submission is rejected when a required
1710
    // textfield is omitted and correctly processed when it is provided.
1711
    $this->submitForm(array(), FALSE);
1712
    $this->submitForm(array('textfield' => 'test 1'), TRUE);
1713
    $this->submitForm(array(), FALSE);
1714
    $this->submitForm(array('textfield' => 'test 2'), TRUE);
1715

    
1716
    // Test that a programmatic form submission can turn on and off checkboxes
1717
    // which are, by default, checked.
1718
    $this->submitForm(array('textfield' => 'dummy value', 'checkboxes' => array(1 => 1, 2 => 2)), TRUE);
1719
    $this->submitForm(array('textfield' => 'dummy value', 'checkboxes' => array(1 => 1, 2 => NULL)), TRUE);
1720
    $this->submitForm(array('textfield' => 'dummy value', 'checkboxes' => array(1 => NULL, 2 => 2)), TRUE);
1721
    $this->submitForm(array('textfield' => 'dummy value', 'checkboxes' => array(1 => NULL, 2 => NULL)), TRUE);
1722

    
1723
    // Test that a programmatic form submission can successfully submit values
1724
    // even for fields where the #access property is FALSE.
1725
    $this->submitForm(array('textfield' => 'dummy value', 'textfield_no_access' => 'test value'), TRUE);
1726
    // Test that #access is respected for programmatic form submissions when
1727
    // requested to do so.
1728
    $submitted_values = array('textfield' => 'dummy value', 'textfield_no_access' => 'test value');
1729
    $expected_values = array('textfield' => 'dummy value', 'textfield_no_access' => 'default value');
1730
    $form_state = array('programmed_bypass_access_check' => FALSE);
1731
    $this->submitForm($submitted_values, TRUE, $expected_values, $form_state);
1732

    
1733
    // Test that a programmatic form submission can correctly click a button
1734
    // that limits validation errors based on user input. Since we do not
1735
    // submit any values for "textfield" here and the textfield is required, we
1736
    // only expect form validation to pass when validation is limited to a
1737
    // different field.
1738
    $this->submitForm(array('op' => 'Submit with limited validation', 'field_to_validate' => 'all'), FALSE);
1739
    $this->submitForm(array('op' => 'Submit with limited validation', 'field_to_validate' => 'textfield'), FALSE);
1740
    $this->submitForm(array('op' => 'Submit with limited validation', 'field_to_validate' => 'field_to_validate'), TRUE);
1741

    
1742
    // Restore the current batch status.
1743
    $batch = $current_batch;
1744
  }
1745

    
1746
  /**
1747
   * Helper function used to programmatically submit the form defined in
1748
   * form_test.module with the given values.
1749
   *
1750
   * @param $values
1751
   *   An array of field values to be submitted.
1752
   * @param $valid_input
1753
   *   A boolean indicating whether or not the form submission is expected to
1754
   *   be valid.
1755
   * @param $expected_values
1756
   *   (Optional) An array of field values that are expected to be stored by
1757
   *   the form submit handler. If not set, the submitted $values are assumed
1758
   *   to also be the expected stored values.
1759
   * @param $form_state
1760
   *   (Optional) A keyed array containing the state of the form, to be sent in
1761
   *   the call to drupal_form_submit(). The $values parameter is added to
1762
   *   $form_state['values'] by default, if it is not already set.
1763
   */
1764
  private function submitForm($values, $valid_input, $expected_values = NULL, $form_state = array()) {
1765
    // Programmatically submit the given values.
1766
    $form_state += array('values' => $values);
1767
    drupal_form_submit('form_test_programmatic_form', $form_state);
1768

    
1769
    // Check that the form returns an error when expected, and vice versa.
1770
    $errors = form_get_errors();
1771
    $valid_form = empty($errors);
1772
    $args = array(
1773
      '%values' => print_r($values, TRUE),
1774
      '%errors' => $valid_form ? t('None') : implode(' ', $errors),
1775
    );
1776
    $this->assertTrue($valid_input == $valid_form, format_string('Input values: %values<br/>Validation handler errors: %errors', $args));
1777

    
1778
    // We check submitted values only if we have a valid input.
1779
    if ($valid_input) {
1780
      // By fetching the values from $form_state['storage'] we ensure that the
1781
      // submission handler was properly executed.
1782
      $stored_values = $form_state['storage']['programmatic_form_submit'];
1783
      if (!isset($expected_values)) {
1784
        $expected_values = $values;
1785
      }
1786
      foreach ($expected_values as $key => $value) {
1787
        $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))));
1788
      }
1789
    }
1790
  }
1791
}
1792

    
1793
/**
1794
 * Test that FAPI correctly determines $form_state['triggering_element'].
1795
 */
1796
class FormsTriggeringElementTestCase extends DrupalWebTestCase {
1797

    
1798
  public static function getInfo() {
1799
    return array(
1800
      'name' => 'Form triggering element determination',
1801
      'description' => 'Test the determination of $form_state[\'triggering_element\'].',
1802
      'group' => 'Form API',
1803
    );
1804
  }
1805

    
1806
  function setUp() {
1807
    parent::setUp('form_test');
1808
  }
1809

    
1810
  /**
1811
   * Test the determination of $form_state['triggering_element'] when no button
1812
   * information is included in the POST data, as is sometimes the case when
1813
   * the ENTER key is pressed in a textfield in Internet Explorer.
1814
   */
1815
  function testNoButtonInfoInPost() {
1816
    $path = 'form-test/clicked-button';
1817
    $edit = array();
1818
    $form_html_id = 'form-test-clicked-button';
1819

    
1820
    // Ensure submitting a form with no buttons results in no
1821
    // $form_state['triggering_element'] and the form submit handler not
1822
    // running.
1823
    $this->drupalPost($path, $edit, NULL, array(), array(), $form_html_id);
1824
    $this->assertText('There is no clicked button.', '$form_state[\'triggering_element\'] set to NULL.');
1825
    $this->assertNoText('Submit handler for form_test_clicked_button executed.', 'Form submit handler did not execute.');
1826

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

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

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

    
1843
    // Ensure submitting a form with buttons of different types results in
1844
    // $form_state['triggering_element'] being set to the first button,
1845
    // regardless of type. For the FAPI 'button' type, this should result in the
1846
    // submit handler not executing. The types are 's'(ubmit), 'b'(utton), and
1847
    // 'i'(mage_button).
1848
    $this->drupalPost($path . '/s/b/i', $edit, NULL, array(), array(), $form_html_id);
1849
    $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to first button.');
1850
    $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');
1851

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

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

    
1861
  /**
1862
   * Test that $form_state['triggering_element'] does not get set to a button
1863
   * with #access=FALSE.
1864
   */
1865
  function testAttemptAccessControlBypass() {
1866
    $path = 'form-test/clicked-button';
1867
    $form_html_id = 'form-test-clicked-button';
1868

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

    
1872
    // Submit the form with 'button1=button1' in the POST data, which someone
1873
    // trying to get around security safeguards could easily do. We have to do
1874
    // a little trickery here, to work around the safeguards in drupalPost(): by
1875
    // renaming the text field that is in the form to 'button1', we can get the
1876
    // data we want into $_POST.
1877
    $elements = $this->xpath('//form[@id="' . $form_html_id . '"]//input[@name="text"]');
1878
    $elements[0]['name'] = 'button1';
1879
    $this->drupalPost(NULL, array('button1' => 'button1'), NULL, array(), array(), $form_html_id);
1880

    
1881
    // Ensure that $form_state['triggering_element'] was not set to the
1882
    // restricted button. Do this with both a negative and positive assertion,
1883
    // because negative assertions alone can be brittle. See
1884
    // testNoButtonInfoInPost() for why the triggering element gets set to
1885
    // 'button2'.
1886
    $this->assertNoText('The clicked button is button1.', '$form_state[\'triggering_element\'] not set to a restricted button.');
1887
    $this->assertText('The clicked button is button2.', '$form_state[\'triggering_element\'] not set to a restricted button.');
1888
  }
1889
}
1890

    
1891
/**
1892
 * Tests rebuilding of arbitrary forms by altering them.
1893
 */
1894
class FormsArbitraryRebuildTestCase extends DrupalWebTestCase {
1895
  public static function getInfo() {
1896
    return array(
1897
      'name' => 'Rebuild arbitrary forms',
1898
      'description' => 'Tests altering forms to be rebuilt so there are multiple steps.',
1899
      'group' => 'Form API',
1900
    );
1901
  }
1902

    
1903
  function setUp() {
1904
    parent::setUp('form_test');
1905
    // Auto-create a field for testing.
1906
    $field = array(
1907
      'field_name' => 'test_multiple',
1908
      'type' => 'text',
1909
      'cardinality' => -1,
1910
      'translatable' => FALSE,
1911
    );
1912
    field_create_field($field);
1913

    
1914
    $instance = array(
1915
      'entity_type' => 'node',
1916
      'field_name' => 'test_multiple',
1917
      'bundle' => 'page',
1918
      'label' => 'Test a multiple valued field',
1919
      'widget' => array(
1920
        'type' => 'text_textfield',
1921
        'weight' => 0,
1922
      ),
1923
    );
1924
    field_create_instance($instance);
1925
    variable_set('user_register', USER_REGISTER_VISITORS);
1926
  }
1927

    
1928
  /**
1929
   * Tests a basic rebuild with the user registration form.
1930
   */
1931
  function testUserRegistrationRebuild() {
1932
    $edit = array(
1933
      'name' => 'foo',
1934
      'mail' => 'bar@example.com',
1935
    );
1936
    $this->drupalPost('user/register', $edit, 'Rebuild');
1937
    $this->assertText('Form rebuilt.');
1938
    $this->assertFieldByName('name', 'foo', 'Entered user name has been kept.');
1939
    $this->assertFieldByName('mail', 'bar@example.com', 'Entered mail address has been kept.');
1940
  }
1941

    
1942
  /**
1943
   * Tests a rebuild caused by a multiple value field.
1944
   */
1945
  function testUserRegistrationMultipleField() {
1946
    $edit = array(
1947
      'name' => 'foo',
1948
      'mail' => 'bar@example.com',
1949
    );
1950
    $this->drupalPost('user/register', $edit, t('Add another item'), array('query' => array('field' => TRUE)));
1951
    $this->assertText('Test a multiple valued field', 'Form has been rebuilt.');
1952
    $this->assertFieldByName('name', 'foo', 'Entered user name has been kept.');
1953
    $this->assertFieldByName('mail', 'bar@example.com', 'Entered mail address has been kept.');
1954
  }
1955
}
1956

    
1957
/**
1958
 * Tests form API file inclusion.
1959
 */
1960
class FormsFileInclusionTestCase extends DrupalWebTestCase {
1961

    
1962
  public static function getInfo() {
1963
    return array(
1964
      'name' => 'Form API file inclusion',
1965
      'description' => 'Tests form API file inclusion.',
1966
      'group' => 'Form API',
1967
    );
1968
  }
1969

    
1970
  function setUp() {
1971
    parent::setUp('form_test');
1972
  }
1973

    
1974
  /**
1975
   * Tests loading an include specified in hook_menu().
1976
   */
1977
  function testLoadMenuInclude() {
1978
    $this->drupalPostAJAX('form-test/load-include-menu', array(), array('op' => t('Save')), 'system/ajax', array(), array(), 'form-test-load-include-menu');
1979
    $this->assertText('Submit callback called.');
1980
  }
1981

    
1982
  /**
1983
   * Tests loading a custom specified inlcude.
1984
   */
1985
  function testLoadCustomInclude() {
1986
    $this->drupalPost('form-test/load-include-custom', array(), t('Save'));
1987
    $this->assertText('Submit callback called.');
1988
  }
1989
}
1990

    
1991
/**
1992
 * Tests checkbox element.
1993
 */
1994
class FormCheckboxTestCase extends DrupalWebTestCase {
1995

    
1996
  public static function getInfo() {
1997
    return array(
1998
      'name' => 'Form API checkbox',
1999
      'description' => 'Tests form API checkbox handling of various combinations of #default_value and #return_value.',
2000
      'group' => 'Form API',
2001
    );
2002
  }
2003

    
2004
  function setUp() {
2005
    parent::setUp('form_test');
2006
  }
2007

    
2008
  function testFormCheckbox() {
2009
    // Ensure that the checked state is determined and rendered correctly for
2010
    // tricky combinations of default and return values.
2011
    foreach (array(FALSE, NULL, TRUE, 0, '0', '', 1, '1', 'foobar', '1foobar') as $default_value) {
2012
      // Only values that can be used for array indeces are supported for
2013
      // #return_value, with the exception of integer 0, which is not supported.
2014
      // @see form_process_checkbox().
2015
      foreach (array('0', '', 1, '1', 'foobar', '1foobar') as $return_value) {
2016
        $form_array = drupal_get_form('form_test_checkbox_type_juggling', $default_value, $return_value);
2017
        $form = drupal_render($form_array);
2018
        if ($default_value === TRUE) {
2019
          $checked = TRUE;
2020
        }
2021
        elseif ($return_value === '0') {
2022
          $checked = ($default_value === '0');
2023
        }
2024
        elseif ($return_value === '') {
2025
          $checked = ($default_value === '');
2026
        }
2027
        elseif ($return_value === 1 || $return_value === '1') {
2028
          $checked = ($default_value === 1 || $default_value === '1');
2029
        }
2030
        elseif ($return_value === 'foobar') {
2031
          $checked = ($default_value === 'foobar');
2032
        }
2033
        elseif ($return_value === '1foobar') {
2034
          $checked = ($default_value === '1foobar');
2035
        }
2036
        $checked_in_html = strpos($form, 'checked') !== FALSE;
2037
        $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)));
2038
        $this->assertIdentical($checked, $checked_in_html, $message);
2039
      }
2040
    }
2041

    
2042
    // Ensure that $form_state['values'] is populated correctly for a checkboxes
2043
    // group that includes a 0-indexed array of options.
2044
    $results = json_decode($this->drupalPost('form-test/checkboxes-zero', array(), 'Save'));
2045
    $this->assertIdentical($results->checkbox_off, array(0, 0, 0), 'All three in checkbox_off are zeroes: off.');
2046
    $this->assertIdentical($results->checkbox_zero_default, array('0', 0, 0), 'The first choice is on in checkbox_zero_default');
2047
    $this->assertIdentical($results->checkbox_string_zero_default, array('0', 0, 0), 'The first choice is on in checkbox_string_zero_default');
2048
    $edit = array('checkbox_off[0]' => '0');
2049
    $results = json_decode($this->drupalPost('form-test/checkboxes-zero', $edit, 'Save'));
2050
    $this->assertIdentical($results->checkbox_off, array('0', 0, 0), 'The first choice is on in checkbox_off but the rest is not');
2051

    
2052
    // Ensure that each checkbox is rendered correctly for a checkboxes group
2053
    // that includes a 0-indexed array of options.
2054
    $this->drupalPost('form-test/checkboxes-zero/0', array(), 'Save');
2055
    $checkboxes = $this->xpath('//input[@type="checkbox"]');
2056
    foreach ($checkboxes as $checkbox) {
2057
      $checked = isset($checkbox['checked']);
2058
      $name = (string) $checkbox['name'];
2059
      $this->assertIdentical($checked, $name == 'checkbox_zero_default[0]' || $name == 'checkbox_string_zero_default[0]', format_string('Checkbox %name correctly checked', array('%name' => $name)));
2060
    }
2061
    $edit = array('checkbox_off[0]' => '0');
2062
    $this->drupalPost('form-test/checkboxes-zero/0', $edit, 'Save');
2063
    $checkboxes = $this->xpath('//input[@type="checkbox"]');
2064
    foreach ($checkboxes as $checkbox) {
2065
      $checked = isset($checkbox['checked']);
2066
      $name = (string) $checkbox['name'];
2067
      $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)));
2068
    }
2069
  }
2070
}
2071

    
2072
/**
2073
 * Tests uniqueness of generated HTML IDs.
2074
 */
2075
class HTMLIdTestCase extends DrupalWebTestCase {
2076

    
2077
  public static function getInfo() {
2078
    return array(
2079
      'name' => 'Unique HTML IDs',
2080
      'description' => 'Tests functionality of drupal_html_id().',
2081
      'group' => 'Form API',
2082
    );
2083
  }
2084

    
2085
  function setUp() {
2086
    parent::setUp('form_test');
2087
  }
2088

    
2089
  /**
2090
   * Tests that HTML IDs do not get duplicated when form validation fails.
2091
   */
2092
  function testHTMLId() {
2093
    $this->drupalGet('form-test/double-form');
2094
    $this->assertNoDuplicateIds('There are no duplicate IDs');
2095

    
2096
    // Submit second form with empty title.
2097
    $edit = array();
2098
    $this->drupalPost(NULL, $edit, 'Save', array(), array(), 'form-test-html-id--2');
2099
    $this->assertNoDuplicateIds('There are no duplicate IDs');
2100
  }
2101
}