Security update for Core, with self-updated composer
[yaffs-website] / web / core / modules / system / tests / src / Functional / Form / FormTest.php
1 <?php
2
3 namespace Drupal\Tests\system\Functional\Form;
4
5 use Drupal\Component\Serialization\Json;
6 use Drupal\Component\Utility\Html;
7 use Drupal\Component\Utility\SafeMarkup;
8 use Drupal\Core\Form\FormState;
9 use Drupal\Core\Render\Element;
10 use Drupal\Core\Url;
11 use Drupal\form_test\Form\FormTestDisabledElementsForm;
12 use Drupal\Tests\BrowserTestBase;
13 use Drupal\user\RoleInterface;
14 use Drupal\filter\Entity\FilterFormat;
15
16 /**
17  * Tests various form element validation mechanisms.
18  *
19  * @group Form
20  */
21 class FormTest extends BrowserTestBase {
22
23   /**
24    * Modules to enable.
25    *
26    * @var array
27    */
28   public static $modules = ['filter', 'form_test', 'file', 'datetime'];
29
30   protected function setUp() {
31     parent::setUp();
32
33     $filtered_html_format = FilterFormat::create([
34       'format' => 'filtered_html',
35       'name' => 'Filtered HTML',
36     ]);
37     $filtered_html_format->save();
38
39     $filtered_html_permission = $filtered_html_format->getPermissionName();
40     user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, [$filtered_html_permission]);
41   }
42
43   /**
44    * Check several empty values for required forms elements.
45    *
46    * Carriage returns, tabs, spaces, and unchecked checkbox elements are not
47    * valid content for a required field.
48    *
49    * If the form field is found in $form_state->getErrors() then the test pass.
50    */
51   public function testRequiredFields() {
52     // Originates from https://www.drupal.org/node/117748.
53     // Sets of empty strings and arrays.
54     $empty_strings = ['""' => "", '"\n"' => "\n", '" "' => " ", '"\t"' => "\t", '" \n\t "' => " \n\t ", '"\n\n\n\n\n"' => "\n\n\n\n\n"];
55     $empty_arrays = ['array()' => []];
56     $empty_checkbox = [NULL];
57
58     $elements['textfield']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'textfield'];
59     $elements['textfield']['empty_values'] = $empty_strings;
60
61     $elements['telephone']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'tel'];
62     $elements['telephone']['empty_values'] = $empty_strings;
63
64     $elements['url']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'url'];
65     $elements['url']['empty_values'] = $empty_strings;
66
67     $elements['search']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'search'];
68     $elements['search']['empty_values'] = $empty_strings;
69
70     $elements['password']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'password'];
71     $elements['password']['empty_values'] = $empty_strings;
72
73     $elements['password_confirm']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'password_confirm'];
74     // Provide empty values for both password fields.
75     foreach ($empty_strings as $key => $value) {
76       $elements['password_confirm']['empty_values'][$key] = ['pass1' => $value, 'pass2' => $value];
77     }
78
79     $elements['textarea']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'textarea'];
80     $elements['textarea']['empty_values'] = $empty_strings;
81
82     $elements['radios']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'radios', '#options' => ['' => t('None'), $this->randomMachineName(), $this->randomMachineName(), $this->randomMachineName()]];
83     $elements['radios']['empty_values'] = $empty_arrays;
84
85     $elements['checkbox']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'checkbox', '#required' => TRUE];
86     $elements['checkbox']['empty_values'] = $empty_checkbox;
87
88     $elements['checkboxes']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'checkboxes', '#options' => [$this->randomMachineName(), $this->randomMachineName(), $this->randomMachineName()]];
89     $elements['checkboxes']['empty_values'] = $empty_arrays;
90
91     $elements['select']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'select', '#options' => ['' => t('None'), $this->randomMachineName(), $this->randomMachineName(), $this->randomMachineName()]];
92     $elements['select']['empty_values'] = $empty_strings;
93
94     $elements['file']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'file'];
95     $elements['file']['empty_values'] = $empty_strings;
96
97     // Regular expression to find the expected marker on required elements.
98     $required_marker_preg = '@<.*?class=".*?js-form-required.*form-required.*?">@';
99     // Go through all the elements and all the empty values for them.
100     foreach ($elements as $type => $data) {
101       foreach ($data['empty_values'] as $key => $empty) {
102         foreach ([TRUE, FALSE] as $required) {
103           $form_id = $this->randomMachineName();
104           $form = [];
105           $form_state = new FormState();
106           $form['op'] = ['#type' => 'submit', '#value' => t('Submit')];
107           $element = $data['element']['#title'];
108           $form[$element] = $data['element'];
109           $form[$element]['#required'] = $required;
110           $user_input[$element] = $empty;
111           $user_input['form_id'] = $form_id;
112           $form_state->setUserInput($user_input);
113           $form_state->setFormObject(new StubForm($form_id, $form));
114           $form_state->setMethod('POST');
115           // The form token CSRF protection should not interfere with this test,
116           // so we bypass it by setting the token to FALSE.
117           $form['#token'] = FALSE;
118           \Drupal::formBuilder()->prepareForm($form_id, $form, $form_state);
119           \Drupal::formBuilder()->processForm($form_id, $form, $form_state);
120           $errors = $form_state->getErrors();
121           // Form elements of type 'radios' throw all sorts of PHP notices
122           // when you try to render them like this, so we ignore those for
123           // testing the required marker.
124           // @todo Fix this work-around (https://www.drupal.org/node/588438).
125           $form_output = ($type == 'radios') ? '' : \Drupal::service('renderer')->renderRoot($form);
126           if ($required) {
127             // Make sure we have a form error for this element.
128             $this->assertTrue(isset($errors[$element]), "Check empty($key) '$type' field '$element'");
129             if (!empty($form_output)) {
130               // Make sure the form element is marked as required.
131               $this->assertTrue(preg_match($required_marker_preg, $form_output), "Required '$type' field is marked as required");
132             }
133           }
134           else {
135             if (!empty($form_output)) {
136               // Make sure the form element is *not* marked as required.
137               $this->assertFalse(preg_match($required_marker_preg, $form_output), "Optional '$type' field is not marked as required");
138             }
139             if ($type == 'select') {
140               // Select elements are going to have validation errors with empty
141               // input, since those are illegal choices. Just make sure the
142               // error is not "field is required".
143               $this->assertTrue((empty($errors[$element]) || strpos('field is required', (string) $errors[$element]) === FALSE), "Optional '$type' field '$element' is not treated as a required element");
144             }
145             else {
146               // Make sure there is *no* form error for this element.
147               $this->assertTrue(empty($errors[$element]), "Optional '$type' field '$element' has no errors with empty input");
148             }
149           }
150         }
151       }
152     }
153     // Clear the expected form error messages so they don't appear as exceptions.
154     drupal_get_messages();
155   }
156
157   /**
158    * Tests validation for required checkbox, select, and radio elements.
159    *
160    * Submits a test form containing several types of form elements. The form
161    * is submitted twice, first without values for required fields and then
162    * with values. Each submission is checked for relevant error messages.
163    *
164    * @see \Drupal\form_test\Form\FormTestValidateRequiredForm
165    */
166   public function testRequiredCheckboxesRadio() {
167     $form = \Drupal::formBuilder()->getForm('\Drupal\form_test\Form\FormTestValidateRequiredForm');
168
169     // Attempt to submit the form with no required fields set.
170     $edit = [];
171     $this->drupalPostForm('form-test/validate-required', $edit, 'Submit');
172
173     // The only error messages that should appear are the relevant 'required'
174     // messages for each field.
175     $expected = [];
176     foreach (['textfield', 'checkboxes', 'select', 'radios'] as $key) {
177       if (isset($form[$key]['#required_error'])) {
178         $expected[] = $form[$key]['#required_error'];
179       }
180       elseif (isset($form[$key]['#form_test_required_error'])) {
181         $expected[] = $form[$key]['#form_test_required_error'];
182       }
183       else {
184         $expected[] = t('@name field is required.', ['@name' => $form[$key]['#title']]);
185       }
186     }
187
188     // Check the page for error messages.
189     $errors = $this->xpath('//div[contains(@class, "error")]//li');
190     foreach ($errors as $error) {
191       $expected_key = array_search($error->getText(), $expected);
192       // If the error message is not one of the expected messages, fail.
193       if ($expected_key === FALSE) {
194         $this->fail(format_string("Unexpected error message: @error", ['@error' => $error[0]]));
195       }
196       // Remove the expected message from the list once it is found.
197       else {
198         unset($expected[$expected_key]);
199       }
200     }
201
202     // Fail if any expected messages were not found.
203     foreach ($expected as $not_found) {
204       $this->fail(format_string("Found error message: @error", ['@error' => $not_found]));
205     }
206
207     // Verify that input elements are still empty.
208     $this->assertFieldByName('textfield', '');
209     $this->assertNoFieldChecked('edit-checkboxes-foo');
210     $this->assertNoFieldChecked('edit-checkboxes-bar');
211     $this->assertOptionSelected('edit-select', '');
212     $this->assertNoFieldChecked('edit-radios-foo');
213     $this->assertNoFieldChecked('edit-radios-bar');
214     $this->assertNoFieldChecked('edit-radios-optional-foo');
215     $this->assertNoFieldChecked('edit-radios-optional-bar');
216     $this->assertNoFieldChecked('edit-radios-optional-default-value-false-foo');
217     $this->assertNoFieldChecked('edit-radios-optional-default-value-false-bar');
218
219     // Submit again with required fields set and verify that there are no
220     // error messages.
221     $edit = [
222       'textfield' => $this->randomString(),
223       'checkboxes[foo]' => TRUE,
224       'select' => 'foo',
225       'radios' => 'bar',
226     ];
227     $this->drupalPostForm(NULL, $edit, 'Submit');
228     $this->assertNoFieldByXpath('//div[contains(@class, "error")]', FALSE, 'No error message is displayed when all required fields are filled.');
229     $this->assertRaw("The form_test_validate_required_form form was submitted successfully.", 'Validation form submitted successfully.');
230   }
231
232   /**
233    * Tests that input is retained for safe elements even with an invalid token.
234    *
235    * Submits a test form containing several types of form elements.
236    */
237   public function testInputWithInvalidToken() {
238     // We need to be logged in to have CSRF tokens.
239     $account = $this->createUser();
240     $this->drupalLogin($account);
241     // Submit again with required fields set but an invalid form token and
242     // verify that all the values are retained.
243     $this->drupalGet(Url::fromRoute('form_test.validate_required'));
244     $this->assertSession()
245       ->elementExists('css', 'input[name="form_token"]')
246       ->setValue('invalid token');
247     $edit = [
248       'textfield' => $this->randomString(),
249       'checkboxes[bar]' => TRUE,
250       'select' => 'bar',
251       'radios' => 'foo',
252     ];
253     $this->drupalPostForm(NULL, $edit, 'Submit');
254     $this->assertFieldByXpath('//div[contains(@class, "error")]', NULL, 'Error message is displayed with invalid token even when required fields are filled.');
255     $this->assertText('The form has become outdated. Copy any unsaved work in the form below');
256     // Verify that input elements retained the posted values.
257     $this->assertFieldByName('textfield', $edit['textfield']);
258     $this->assertNoFieldChecked('edit-checkboxes-foo');
259     $this->assertFieldChecked('edit-checkboxes-bar');
260     $this->assertOptionSelected('edit-select', 'bar');
261     $this->assertFieldChecked('edit-radios-foo');
262
263     // Check another form that has a textarea input.
264     $this->drupalGet(Url::fromRoute('form_test.required'));
265     $this->assertSession()
266       ->elementExists('css', 'input[name="form_token"]')
267       ->setValue('invalid token');
268     $edit = [
269       'textfield' => $this->randomString(),
270       'textarea' => $this->randomString() . "\n",
271     ];
272     $this->drupalPostForm(NULL, $edit, 'Submit');
273     $this->assertFieldByXpath('//div[contains(@class, "error")]', NULL, 'Error message is displayed with invalid token even when required fields are filled.');
274     $this->assertText('The form has become outdated. Copy any unsaved work in the form below');
275     $this->assertFieldByName('textfield', $edit['textfield']);
276     $this->assertFieldByName('textarea', $edit['textarea']);
277
278     // Check another form that has a number input.
279     $this->drupalGet(Url::fromRoute('form_test.number'));
280     $this->assertSession()
281       ->elementExists('css', 'input[name="form_token"]')
282       ->setValue('invalid token');
283     $edit = [
284       'integer_step' => mt_rand(1, 100),
285     ];
286     $this->drupalPostForm(NULL, $edit, 'Submit');
287     $this->assertFieldByXpath('//div[contains(@class, "error")]', NULL, 'Error message is displayed with invalid token even when required fields are filled.');
288     $this->assertText('The form has become outdated. Copy any unsaved work in the form below');
289     $this->assertFieldByName('integer_step', $edit['integer_step']);
290
291     // Check a form with a Url field
292     $this->drupalGet(Url::fromRoute('form_test.url'));
293     $this->assertSession()
294       ->elementExists('css', 'input[name="form_token"]')
295       ->setValue('invalid token');
296     $edit = [
297       'url' => $this->randomString(),
298     ];
299     $this->drupalPostForm(NULL, $edit, 'Submit');
300     $this->assertFieldByXpath('//div[contains(@class, "error")]', NULL, 'Error message is displayed with invalid token even when required fields are filled.');
301     $this->assertText('The form has become outdated. Copy any unsaved work in the form below');
302     $this->assertFieldByName('url', $edit['url']);
303   }
304
305   /**
306    * CSRF tokens for GET forms should not be added by default.
307    */
308   public function testGetFormsCsrfToken() {
309     // We need to be logged in to have CSRF tokens.
310     $account = $this->createUser();
311     $this->drupalLogin($account);
312
313     $this->drupalGet(Url::fromRoute('form_test.get_form'));
314     $this->assertNoRaw('form_token');
315   }
316
317   /**
318    * Tests validation for required textfield element without title.
319    *
320    * Submits a test form containing a textfield form element without title.
321    * The form is submitted twice, first without value for the required field
322    * and then with value. Each submission is checked for relevant error
323    * messages.
324    *
325    * @see \Drupal\form_test\Form\FormTestValidateRequiredNoTitleForm
326    */
327   public function testRequiredTextfieldNoTitle() {
328     // Attempt to submit the form with no required field set.
329     $edit = [];
330     $this->drupalPostForm('form-test/validate-required-no-title', $edit, 'Submit');
331     $this->assertNoRaw("The form_test_validate_required_form_no_title form was submitted successfully.", 'Validation form submitted successfully.');
332
333     // Check the page for the error class on the textfield.
334     $this->assertFieldByXPath('//input[contains(@class, "error")]', FALSE, 'Error input form element class found.');
335
336     // Check the page for the aria-invalid attribute on the textfield.
337     $this->assertFieldByXPath('//input[contains(@aria-invalid, "true")]', FALSE, 'Aria invalid attribute found.');
338
339     // Submit again with required fields set and verify that there are no
340     // error messages.
341     $edit = [
342       'textfield' => $this->randomString(),
343     ];
344     $this->drupalPostForm(NULL, $edit, 'Submit');
345     $this->assertNoFieldByXpath('//input[contains(@class, "error")]', FALSE, 'No error input form element class found.');
346     $this->assertRaw("The form_test_validate_required_form_no_title form was submitted successfully.", 'Validation form submitted successfully.');
347   }
348
349   /**
350    * Test default value handling for checkboxes.
351    *
352    * @see _form_test_checkbox()
353    */
354   public function testCheckboxProcessing() {
355     // First, try to submit without the required checkbox.
356     $edit = [];
357     $this->drupalPostForm('form-test/checkbox', $edit, t('Submit'));
358     $this->assertRaw(t('@name field is required.', ['@name' => 'required_checkbox']), 'A required checkbox is actually mandatory');
359
360     // Now try to submit the form correctly.
361     $this->drupalPostForm(NULL, ['required_checkbox' => 1], t('Submit'));
362     $values = Json::decode($this->getSession()->getPage()->getContent());
363     $expected_values = [
364       'disabled_checkbox_on' => 'disabled_checkbox_on',
365       'disabled_checkbox_off' => 0,
366       'checkbox_on' => 'checkbox_on',
367       'checkbox_off' => 0,
368       'zero_checkbox_on' => '0',
369       'zero_checkbox_off' => 0,
370     ];
371     foreach ($expected_values as $widget => $expected_value) {
372       $this->assertSame($values[$widget], $expected_value, format_string('Checkbox %widget returns expected value (expected: %expected, got: %value)', [
373         '%widget' => var_export($widget, TRUE),
374         '%expected' => var_export($expected_value, TRUE),
375         '%value' => var_export($values[$widget], TRUE),
376       ]));
377     }
378   }
379
380   /**
381    * Tests validation of #type 'select' elements.
382    */
383   public function testSelect() {
384     $form = \Drupal::formBuilder()->getForm('Drupal\form_test\Form\FormTestSelectForm');
385     $this->drupalGet('form-test/select');
386
387     // Verify that the options are escaped as expected.
388     $this->assertEscaped('<strong>four</strong>');
389     $this->assertNoRaw('<strong>four</strong>');
390
391     // Posting without any values should throw validation errors.
392     $this->drupalPostForm(NULL, [], 'Submit');
393     $no_errors = [
394         'select',
395         'select_required',
396         'select_optional',
397         'empty_value',
398         'empty_value_one',
399         'no_default_optional',
400         'no_default_empty_option_optional',
401         'no_default_empty_value_optional',
402         'multiple',
403         'multiple_no_default',
404     ];
405     foreach ($no_errors as $key) {
406       $this->assertNoText(t('@name field is required.', ['@name' => $form[$key]['#title']]));
407     }
408
409     $expected_errors = [
410         'no_default',
411         'no_default_empty_option',
412         'no_default_empty_value',
413         'no_default_empty_value_one',
414         'multiple_no_default_required',
415     ];
416     foreach ($expected_errors as $key) {
417       $this->assertText(t('@name field is required.', ['@name' => $form[$key]['#title']]));
418     }
419
420     // Post values for required fields.
421     $edit = [
422       'no_default' => 'three',
423       'no_default_empty_option' => 'three',
424       'no_default_empty_value' => 'three',
425       'no_default_empty_value_one' => 'three',
426       'multiple_no_default_required[]' => 'three',
427     ];
428     $this->drupalPostForm(NULL, $edit, 'Submit');
429     $values = Json::decode($this->getRawContent());
430
431     // Verify expected values.
432     $expected = [
433       'select' => 'one',
434       'empty_value' => 'one',
435       'empty_value_one' => 'one',
436       'no_default' => 'three',
437       'no_default_optional' => 'one',
438       'no_default_optional_empty_value' => '',
439       'no_default_empty_option' => 'three',
440       'no_default_empty_option_optional' => '',
441       'no_default_empty_value' => 'three',
442       'no_default_empty_value_one' => 'three',
443       'no_default_empty_value_optional' => 0,
444       'multiple' => ['two' => 'two'],
445       'multiple_no_default' => [],
446       'multiple_no_default_required' => ['three' => 'three'],
447     ];
448     foreach ($expected as $key => $value) {
449       $this->assertIdentical($values[$key], $value, format_string('@name: @actual is equal to @expected.', [
450         '@name' => $key,
451         '@actual' => var_export($values[$key], TRUE),
452         '@expected' => var_export($value, TRUE),
453       ]));
454     }
455   }
456
457   /**
458    * Tests a select element when #options is not set.
459    */
460   public function testEmptySelect() {
461     $this->drupalGet('form-test/empty-select');
462     $this->assertFieldByXPath("//select[1]", NULL, 'Select element found.');
463     $this->assertNoFieldByXPath("//select[1]/option", NULL, 'No option element found.');
464   }
465
466   /**
467    * Tests validation of #type 'number' and 'range' elements.
468    */
469   public function testNumber() {
470     $form = \Drupal::formBuilder()->getForm('\Drupal\form_test\Form\FormTestNumberForm');
471
472     // Array with all the error messages to be checked.
473     $error_messages = [
474       'no_number' => '%name must be a number.',
475       'too_low' => '%name must be higher than or equal to %min.',
476       'too_high' => '%name must be lower than or equal to %max.',
477       'step_mismatch' => '%name is not a valid number.',
478     ];
479
480     // The expected errors.
481     $expected = [
482       'integer_no_number' => 'no_number',
483       'integer_no_step' => 0,
484       'integer_no_step_step_error' => 'step_mismatch',
485       'integer_step' => 0,
486       'integer_step_error' => 'step_mismatch',
487       'integer_step_min' => 0,
488       'integer_step_min_error' => 'too_low',
489       'integer_step_max' => 0,
490       'integer_step_max_error' => 'too_high',
491       'integer_step_min_border' => 0,
492       'integer_step_max_border' => 0,
493       'integer_step_based_on_min' => 0,
494       'integer_step_based_on_min_error' => 'step_mismatch',
495       'float_small_step' => 0,
496       'float_step_no_error' => 0,
497       'float_step_error' => 'step_mismatch',
498       'float_step_hard_no_error' => 0,
499       'float_step_hard_error' => 'step_mismatch',
500       'float_step_any_no_error' => 0,
501     ];
502
503     // First test the number element type, then range.
504     foreach (['form-test/number', 'form-test/number/range'] as $path) {
505       // Post form and show errors.
506       $this->drupalPostForm($path, [], 'Submit');
507
508       foreach ($expected as $element => $error) {
509         // Create placeholder array.
510         $placeholders = [
511           '%name' => $form[$element]['#title'],
512           '%min' => isset($form[$element]['#min']) ? $form[$element]['#min'] : '0',
513           '%max' => isset($form[$element]['#max']) ? $form[$element]['#max'] : '0',
514         ];
515
516         foreach ($error_messages as $id => $message) {
517           // Check if the error exists on the page, if the current message ID is
518           // expected. Otherwise ensure that the error message is not present.
519           if ($id === $error) {
520             $this->assertRaw(format_string($message, $placeholders));
521           }
522           else {
523             $this->assertNoRaw(format_string($message, $placeholders));
524           }
525         }
526       }
527     }
528   }
529
530   /**
531    * Tests default value handling of #type 'range' elements.
532    */
533   public function testRange() {
534     $this->drupalPostForm('form-test/range', [], 'Submit');
535     $values = json_decode($this->getSession()->getPage()->getContent());
536     $this->assertEqual($values->with_default_value, 18);
537     $this->assertEqual($values->float, 10.5);
538     $this->assertEqual($values->integer, 6);
539     $this->assertEqual($values->offset, 6.9);
540
541     $this->drupalPostForm('form-test/range/invalid', [], 'Submit');
542     $this->assertFieldByXPath('//input[@type="range" and contains(@class, "error")]', NULL, 'Range element has the error class.');
543   }
544
545   /**
546    * Tests validation of #type 'color' elements.
547    */
548   public function testColorValidation() {
549     // Keys are inputs, values are expected results.
550     $values = [
551       '' => '#000000',
552       '#000' => '#000000',
553       'AAA' => '#aaaaaa',
554       '#af0DEE' => '#af0dee',
555       '#99ccBc' => '#99ccbc',
556       '#aabbcc' => '#aabbcc',
557       '123456' => '#123456',
558     ];
559
560     // Tests that valid values are properly normalized.
561     foreach ($values as $input => $expected) {
562       $edit = [
563         'color' => $input,
564       ];
565       $this->drupalPostForm('form-test/color', $edit, 'Submit');
566       $result = json_decode($this->getSession()->getPage()->getContent());
567       $this->assertEqual($result->color, $expected);
568     }
569
570     // Tests invalid values are rejected.
571     $values = ['#0008', '#1234', '#fffffg', '#abcdef22', '17', '#uaa'];
572     foreach ($values as $input) {
573       $edit = [
574         'color' => $input,
575       ];
576       $this->drupalPostForm('form-test/color', $edit, 'Submit');
577       $this->assertRaw(t('%name must be a valid color.', ['%name' => 'Color']));
578     }
579   }
580
581   /**
582    * Test handling of disabled elements.
583    *
584    * @see _form_test_disabled_elements()
585    */
586   public function testDisabledElements() {
587     // Get the raw form in its original state.
588     $form_state = new FormState();
589     $form = (new FormTestDisabledElementsForm())->buildForm([], $form_state);
590
591     // Build a submission that tries to hijack the form by submitting input for
592     // elements that are disabled.
593     $edit = [];
594     foreach (Element::children($form) as $key) {
595       if (isset($form[$key]['#test_hijack_value'])) {
596         if (is_array($form[$key]['#test_hijack_value'])) {
597           foreach ($form[$key]['#test_hijack_value'] as $subkey => $value) {
598             $edit[$key . '[' . $subkey . ']'] = $value;
599           }
600         }
601         else {
602           $edit[$key] = $form[$key]['#test_hijack_value'];
603         }
604       }
605     }
606
607     // Submit the form with no input, as the browser does for disabled elements,
608     // and fetch the $form_state->getValues() that is passed to the submit handler.
609     $this->drupalPostForm('form-test/disabled-elements', [], t('Submit'));
610     $returned_values['normal'] = Json::decode($this->getSession()->getPage()->getContent());
611
612     // Do the same with input, as could happen if JavaScript un-disables an
613     // element. drupalPostForm() emulates a browser by not submitting input for
614     // disabled elements, so we need to un-disable those elements first.
615     $this->drupalGet('form-test/disabled-elements');
616     $disabled_elements = [];
617     foreach ($this->xpath('//*[@disabled]') as $element) {
618       $disabled_elements[] = (string) $element->getAttribute('name');
619     }
620
621     // All the elements should be marked as disabled, including the ones below
622     // the disabled container.
623     $actual_count = count($disabled_elements);
624     $expected_count = 42;
625     $this->assertEqual($actual_count, $expected_count, SafeMarkup::format('Found @actual elements with disabled property (expected @expected).', [
626       '@actual' => count($disabled_elements),
627       '@expected' => $expected_count,
628     ]));
629
630     // Mink does not "see" hidden elements, so we need to set the value of the
631     // hidden element directly.
632     $this->assertSession()
633       ->elementExists('css', 'input[name="hidden"]')
634       ->setValue($edit['hidden']);
635     unset($edit['hidden']);
636     $this->drupalPostForm(NULL, $edit, t('Submit'));
637     $returned_values['hijacked'] = Json::decode($this->getSession()->getPage()->getContent());
638
639     // Ensure that the returned values match the form's default values in both
640     // cases.
641     foreach ($returned_values as $values) {
642       $this->assertFormValuesDefault($values, $form);
643     }
644   }
645
646   /**
647    * Assert that the values submitted to a form matches the default values of the elements.
648    */
649   public function assertFormValuesDefault($values, $form) {
650     foreach (Element::children($form) as $key) {
651       if (isset($form[$key]['#default_value'])) {
652         if (isset($form[$key]['#expected_value'])) {
653           $expected_value = $form[$key]['#expected_value'];
654         }
655         else {
656           $expected_value = $form[$key]['#default_value'];
657         }
658
659         if ($key == 'checkboxes_multiple') {
660           // Checkboxes values are not filtered out.
661           $values[$key] = array_filter($values[$key]);
662         }
663         $this->assertIdentical($expected_value, $values[$key], format_string('Default value for %type: expected %expected, returned %returned.', ['%type' => $key, '%expected' => var_export($expected_value, TRUE), '%returned' => var_export($values[$key], TRUE)]));
664       }
665
666       // Recurse children.
667       $this->assertFormValuesDefault($values, $form[$key]);
668     }
669   }
670
671   /**
672    * Verify markup for disabled form elements.
673    *
674    * @see _form_test_disabled_elements()
675    */
676   public function testDisabledMarkup() {
677     $this->drupalGet('form-test/disabled-elements');
678     $form = \Drupal::formBuilder()->getForm('\Drupal\form_test\Form\FormTestDisabledElementsForm');
679     $type_map = [
680       'textarea' => 'textarea',
681       'select' => 'select',
682       'weight' => 'select',
683       'datetime' => 'datetime',
684     ];
685
686     foreach ($form as $name => $item) {
687       // Skip special #types.
688       if (!isset($item['#type']) || in_array($item['#type'], ['hidden', 'text_format'])) {
689         continue;
690       }
691       // Setup XPath and CSS class depending on #type.
692       if (in_array($item['#type'], ['button', 'submit'])) {
693         $path = "//!type[contains(@class, :div-class) and @value=:value]";
694         $class = 'is-disabled';
695       }
696       elseif (in_array($item['#type'], ['image_button'])) {
697         $path = "//!type[contains(@class, :div-class) and @value=:value]";
698         $class = 'is-disabled';
699       }
700       else {
701         // starts-with() required for checkboxes.
702         $path = "//div[contains(@class, :div-class)]/descendant::!type[starts-with(@name, :name)]";
703         $class = 'form-disabled';
704       }
705       // Replace DOM element name in $path according to #type.
706       $type = 'input';
707       if (isset($type_map[$item['#type']])) {
708         $type = $type_map[$item['#type']];
709       }
710       if (isset($item['#value']) && is_object($item['#value'])) {
711         $item['#value'] = (string) $item['#value'];
712       }
713       $path = strtr($path, ['!type' => $type]);
714       // Verify that the element exists.
715       $element = $this->xpath($path, [
716         ':name' => Html::escape($name),
717         ':div-class' => $class,
718         ':value' => isset($item['#value']) ? $item['#value'] : '',
719       ]);
720       $this->assertTrue(isset($element[0]), format_string('Disabled form element class found for #type %type.', ['%type' => $item['#type']]));
721     }
722
723     // Verify special element #type text-format.
724     $element = $this->xpath('//div[contains(@class, :div-class)]/descendant::textarea[@name=:name]', [
725       ':name' => 'text_format[value]',
726       ':div-class' => 'form-disabled',
727     ]);
728     $this->assertTrue(isset($element[0]), format_string('Disabled form element class found for #type %type.', ['%type' => 'text_format[value]']));
729     $element = $this->xpath('//div[contains(@class, :div-class)]/descendant::select[@name=:name]', [
730       ':name' => 'text_format[format]',
731       ':div-class' => 'form-disabled',
732     ]);
733     $this->assertTrue(isset($element[0]), format_string('Disabled form element class found for #type %type.', ['%type' => 'text_format[format]']));
734   }
735
736   /**
737    * Test Form API protections against input forgery.
738    *
739    * @see \Drupal\form_test\Form\FormTestInputForgeryForm
740    */
741   public function testInputForgery() {
742     $this->drupalGet('form-test/input-forgery');
743     // The value for checkboxes[two] was changed using post render to simulate
744     // an input forgery.
745     // @see \Drupal\form_test\Form\FormTestInputForgeryForm::postRender
746     $this->drupalPostForm(NULL, ['checkboxes[one]' => TRUE, 'checkboxes[two]' => TRUE], t('Submit'));
747     $this->assertText('An illegal choice has been detected.', 'Input forgery was detected.');
748   }
749
750   /**
751    * Tests required attribute.
752    */
753   public function testRequiredAttribute() {
754     $this->drupalGet('form-test/required-attribute');
755     $expected = 'required';
756     // Test to make sure the elements have the proper required attribute.
757     foreach (['textfield', 'password'] as $type) {
758       $element = $this->xpath('//input[@id=:id and @required=:expected]', [
759         ':id' => 'edit-' . $type,
760         ':expected' => $expected,
761       ]);
762       $this->assertTrue(!empty($element), format_string('The @type has the proper required attribute.', ['@type' => $type]));
763     }
764
765     // Test to make sure textarea has the proper required attribute.
766     $element = $this->xpath('//textarea[@id=:id and @required=:expected]', [
767       ':id' => 'edit-textarea',
768       ':expected' => $expected,
769     ]);
770     $this->assertTrue(!empty($element), 'The textarea has the proper required attribute.');
771   }
772
773 }