- <?php
- * @file
- * Unit tests for the Backdrop Form API.
- */
-
- include_once(dirname(__FILE__) . '/system_config_test.inc');
-
- class FormsTestCase extends BackdropWebTestCase {
- function setUp() {
- parent::setUp('form_test');
- }
-
-
- * Check several empty values for required forms elements.
- *
- * Carriage returns, tabs, spaces, and unchecked checkbox elements are not
- * valid content for a required field.
- *
- * If the form field is found in form_get_errors() then the test pass.
- */
- function testRequiredFields() {
-
-
- $empty_strings = array('""' => "", '"\n"' => "\n", '" "' => " ", '"\t"' => "\t", '" \n\t "' => " \n\t ", '"\n\n\n\n\n"' => "\n\n\n\n\n");
- $empty_arrays = array('array()' => array());
- $empty_checkbox = array(NULL);
-
- $elements['textfield']['element'] = array('#title' => $this->randomName(), '#type' => 'textfield');
- $elements['textfield']['empty_values'] = $empty_strings;
-
- $elements['telephone']['element'] = array('#title' => $this->randomName(), '#type' => 'tel');
- $elements['telephone']['empty_values'] = $empty_strings;
-
- $elements['url']['element'] = array('#title' => $this->randomName(), '#type' => 'url');
- $elements['url']['empty_values'] = $empty_strings;
-
- $elements['search']['element'] = array('#title' => $this->randomName(), '#type' => 'search');
- $elements['search']['empty_values'] = $empty_strings;
-
- $elements['password']['element'] = array('#title' => $this->randomName(), '#type' => 'password');
- $elements['password']['empty_values'] = $empty_strings;
-
- $elements['password_confirm']['element'] = array('#title' => $this->randomName(), '#type' => 'password_confirm');
-
- foreach ($empty_strings as $key => $value) {
- $elements['password_confirm']['empty_values'][$key] = array('pass1' => $value, 'pass2' => $value);
- }
-
- $elements['textarea']['element'] = array('#title' => $this->randomName(), '#type' => 'textarea');
- $elements['textarea']['empty_values'] = $empty_strings;
-
- $elements['radios']['element'] = array('#title' => $this->randomName(), '#type' => 'radios', '#options' => array('' => t('None'), $this->randomName(), $this->randomName(), $this->randomName()));
- $elements['radios']['empty_values'] = $empty_arrays;
-
- $elements['checkbox']['element'] = array('#title' => $this->randomName(), '#type' => 'checkbox', '#required' => TRUE);
- $elements['checkbox']['empty_values'] = $empty_checkbox;
-
- $elements['checkboxes']['element'] = array('#title' => $this->randomName(), '#type' => 'checkboxes', '#options' => array($this->randomName(), $this->randomName(), $this->randomName()));
- $elements['checkboxes']['empty_values'] = $empty_arrays;
-
- $elements['select']['element'] = array('#title' => $this->randomName(), '#type' => 'select', '#options' => array('' => t('None'), $this->randomName(), $this->randomName(), $this->randomName()));
- $elements['select']['empty_values'] = $empty_strings;
-
- $elements['file']['element'] = array('#title' => $this->randomName(), '#type' => 'file');
- $elements['file']['empty_values'] = $empty_strings;
-
-
- $required_marker_preg = '@<label.*<abbr class="form-required" title="This field is required\.">\*</abbr></label>@';
-
-
- foreach ($elements as $type => $data) {
- foreach ($data['empty_values'] as $key => $empty) {
- foreach (array(TRUE, FALSE) as $required) {
- $form_id = $this->randomName();
- $form = array();
- $form_state = form_state_defaults();
- form_clear_error();
- $form['op'] = array('#type' => 'submit', '#value' => t('Submit'));
- $element = $data['element']['#title'];
- $form[$element] = $data['element'];
- $form[$element]['#required'] = $required;
- $form_state['input'][$element] = $empty;
- $form_state['input']['form_id'] = $form_id;
- $form_state['method'] = 'post';
-
-
-
- $form_state['programmed'] = TRUE;
- backdrop_prepare_form($form_id, $form, $form_state);
- backdrop_process_form($form_id, $form, $form_state);
- $errors = form_get_errors();
-
-
-
-
- $form_output = ($type == 'radios') ? '' : backdrop_render($form);
- if ($required) {
-
- $this->assertTrue(isset($errors[$element]), "Check empty($key) '$type' field '$element'");
- if (!empty($form_output)) {
-
- $this->assertTrue(preg_match($required_marker_preg, $form_output), "Required '$type' field is marked as required");
- }
- }
- else {
- if (!empty($form_output)) {
-
- $this->assertFalse(preg_match($required_marker_preg, $form_output), "Optional '$type' field is not marked as required");
- }
- if ($type == 'select') {
-
-
-
- $this->assertTrue((empty($errors[$element]) || strpos('field is required', $errors[$element]) === FALSE), "Optional '$type' field '$element' is not treated as a required element");
- }
- else {
-
- $this->assertTrue(empty($errors[$element]), "Optional '$type' field '$element' has no errors with empty input");
- }
- }
- }
- }
- }
-
- backdrop_get_messages();
- }
-
-
- * Tests validation for required checkbox, select, and radio elements.
- *
- * Submits a test form containing several types of form elements. The form
- * is submitted twice, first without values for required fields and then
- * with values. Each submission is checked for relevant error messages.
- *
- * @see form_test_validate_required_form()
- */
- function testRequiredCheckboxesRadio() {
- $form = $form_state = array();
- $form = form_test_validate_required_form($form, $form_state);
-
-
- $edit = array();
- $this->backdropPost('form-test/validate-required', $edit, 'Submit');
-
-
-
- $expected = array();
- foreach (array('textfield', 'checkboxes', 'select', 'radios') as $key) {
- if (isset($form[$key]['#required_message'])) {
- $expected[] = $form[$key]['#required_message'];
- }
- elseif (isset($form[$key]['#form_test_expected_message'])) {
- $expected[] = $form[$key]['#form_test_expected_message'];
- }
- }
-
-
- $errors = $this->xpath('//div[contains(@class, "error")]//li');
- foreach ($errors as $error) {
- $expected_key = array_search($error[0], $expected);
-
- if ($expected_key === FALSE) {
- $this->fail(format_string("Unexpected error message: @error", array('@error' => $error[0])));
- }
-
- else {
- unset($expected[$expected_key]);
- }
- }
-
-
- foreach ($expected as $not_found) {
- $this->fail(format_string("Found error message: @error", array('@error' => $not_found)));
- }
-
-
- $this->assertFieldByName('textfield', '');
- $this->assertNoFieldChecked('edit-checkboxes-foo');
- $this->assertNoFieldChecked('edit-checkboxes-bar');
- $this->assertOptionSelected('edit-select', '');
- $this->assertNoFieldChecked('edit-radios-foo');
- $this->assertNoFieldChecked('edit-radios-bar');
- $this->assertNoFieldChecked('edit-radios-optional-foo');
- $this->assertNoFieldChecked('edit-radios-optional-bar');
- $this->assertNoFieldChecked('edit-radios-optional-default-value-false-foo');
- $this->assertNoFieldChecked('edit-radios-optional-default-value-false-bar');
-
-
-
- $this->assertNoRaw('Please select the "foo" option.');
-
-
-
-
- $edit = array(
- 'select' => 'bar',
- );
- $this->backdropPost(NULL, $edit, 'Submit');
- $this->assertRaw('Please select the "foo" option.');
-
-
-
- $edit = array(
- 'textfield' => $this->randomString(),
- 'checkboxes[foo]' => TRUE,
- 'select' => 'foo',
- 'radios' => 'bar',
- );
- $this->backdropPost(NULL, $edit, 'Submit');
- $this->assertNoFieldByXpath('//div[contains(@class, "error")]', FALSE, 'No error message is displayed when all required fields are filled.');
- $this->assertRaw("The form_test_validate_required_form form was submitted successfully.", 'Validation form submitted successfully.');
- }
-
-
- * Tests validation for required textfield element without title.
- *
- * Submits a test form containing a textfield form elements without title.
- * The form is submitted twice, first without value for the required field
- * and then with value. Each submission is checked for relevant error
- * messages.
- *
- * @see form_test_validate_required_form_no_title()
- */
- function testRequiredTextfieldNoTitle() {
- $form = $form_state = array();
- $form = form_test_validate_required_form_no_title($form, $form_state);
-
-
- $edit = array();
- $this->backdropPost('form-test/validate-required-no-title', $edit, 'Submit');
- $this->assertNoRaw("The form_test_validate_required_form_no_title form was submitted successfully.", 'Validation form submitted successfully.');
-
-
- $this->assertFieldByXPath('//input[contains(@class, "error")]', FALSE, 'Error input form element class found.');
-
-
-
- $edit = array(
- 'textfield' => $this->randomString(),
- );
- $this->backdropPost(NULL, $edit, 'Submit');
- $this->assertNoFieldByXpath('//input[contains(@class, "error")]', FALSE, 'No error input form element class found.');
- $this->assertRaw("The form_test_validate_required_form_no_title form was submitted successfully.", 'Validation form submitted successfully.');
- }
-
-
- * Test default value handling for checkboxes.
- *
- * @see _form_test_checkbox()
- */
- function testCheckboxProcessing() {
-
- $edit = array();
- $this->backdropPost('form-test/checkbox', $edit, t('Submit'));
- $this->assertRaw(t('!name field is required.', array('!name' => 'required_checkbox')), 'A required checkbox is actually mandatory');
-
-
- $values = backdrop_json_decode($this->backdropPost(NULL, array('required_checkbox' => 1), t('Submit')));
- $expected_values = array(
- 'disabled_checkbox_on' => 'disabled_checkbox_on',
- 'disabled_checkbox_off' => 0,
- 'checkbox_on' => 'checkbox_on',
- 'checkbox_off' => 0,
- 'zero_checkbox_on' => '0',
- 'zero_checkbox_off' => 0,
- );
- foreach ($expected_values as $widget => $expected_value) {
- $this->assertEqual($values[$widget], $expected_value, format_string('Checkbox %widget returns expected value (expected: %expected, got: %value)', array(
- '%widget' => var_export($widget, TRUE),
- '%expected' => var_export($expected_value, TRUE),
- '%value' => var_export($values[$widget], TRUE),
- )));
- }
- }
-
-
- * Tests validation of #type 'select' elements.
- */
- function testSelect() {
- $form = $form_state = array();
- $form = form_test_select($form, $form_state);
- $error = '!name field is required.';
- $this->backdropGet('form-test/select');
-
-
- $this->backdropPost(NULL, array(), 'Submit');
- $this->assertNoText(t($error, array('!name' => $form['select']['#title'])));
- $this->assertNoText(t($error, array('!name' => $form['select_required']['#title'])));
- $this->assertNoText(t($error, array('!name' => $form['select_optional']['#title'])));
- $this->assertNoText(t($error, array('!name' => $form['empty_value']['#title'])));
- $this->assertNoText(t($error, array('!name' => $form['empty_value_one']['#title'])));
- $this->assertText(t($error, array('!name' => $form['no_default']['#title'])));
- $this->assertNoText(t($error, array('!name' => $form['no_default_optional']['#title'])));
- $this->assertText(t($error, array('!name' => $form['no_default_empty_option']['#title'])));
- $this->assertNoText(t($error, array('!name' => $form['no_default_empty_option_optional']['#title'])));
- $this->assertText(t($error, array('!name' => $form['no_default_empty_value']['#title'])));
- $this->assertText(t($error, array('!name' => $form['no_default_empty_value_one']['#title'])));
- $this->assertNoText(t($error, array('!name' => $form['no_default_empty_value_optional']['#title'])));
- $this->assertNoText(t($error, array('!name' => $form['multiple']['#title'])));
- $this->assertNoText(t($error, array('!name' => $form['multiple_no_default']['#title'])));
- $this->assertText(t($error, array('!name' => $form['multiple_no_default_required']['#title'])));
-
-
- $edit = array(
- 'no_default' => 'three',
- 'no_default_empty_option' => 'three',
- 'no_default_empty_value' => 'three',
- 'no_default_empty_value_one' => 'three',
- 'multiple_no_default_required[]' => 'three',
- );
- $this->backdropPost(NULL, $edit, 'Submit');
- $values = backdrop_json_decode($this->backdropGetContent());
-
-
- $expected = array(
- 'select' => 'one',
- 'empty_value' => 'one',
- 'empty_value_one' => 'one',
- 'no_default' => 'three',
- 'no_default_optional' => 'one',
- 'no_default_optional_empty_value' => '',
- 'no_default_empty_option' => 'three',
- 'no_default_empty_option_optional' => '',
- 'no_default_empty_value' => 'three',
- 'no_default_empty_value_one' => 'three',
- 'no_default_empty_value_optional' => 0,
- 'multiple' => array('two' => 'two'),
- 'multiple_no_default' => array(),
- 'multiple_no_default_required' => array('three' => 'three'),
- );
- foreach ($expected as $key => $value) {
- $this->assertIdentical($values[$key], $value, format_string('@name: @actual is equal to @expected.', array(
- '@name' => $key,
- '@actual' => var_export($values[$key], TRUE),
- '@expected' => var_export($value, TRUE),
- )));
- }
- }
-
-
- * Tests validation of #type 'color' elements.
- */
- function testColorValidation() {
-
- $values = array(
- '' => '#000000',
- '#000' => '#000000',
- 'AAA' => '#aaaaaa',
- '#af0DEE' => '#af0dee',
- '#99ccBc' => '#99ccbc',
- '#aabbcc' => '#aabbcc',
- '123456' => '#123456',
- );
-
-
- foreach ($values as $input => $expected) {
- $edit = array(
- 'color' => $input,
- );
- $result = json_decode($this->backdropPost('form-test/color', $edit, 'Submit'));
- $this->assertEqual($result->color, $expected);
- }
-
-
- $values = array('#0008', '#1234', '#fffffg', '#abcdef22', '17', '#uaa');
- foreach ($values as $input) {
- $edit = array(
- 'color' => $input,
- );
- $this->backdropPost('form-test/color', $edit, 'Submit');
- $this->assertRaw(t('%name must be a valid color.', array('%name' => 'Color')));
- }
- }
-
-
- * Tests validation of #type 'number' elements.
- */
- function testNumber() {
- $form = $form_state = array();
- $form = form_test_number($form, $form_state);
- $this->backdropGet('form-test/number');
-
-
-
- $error_messages = array(
- 'no_number' => 'The value for %name must be numeric.',
- 'too_low' => 'The value for %name must be greater than or equal to %min.',
- 'too_high' => 'The value for %name must be less than or equal to %max.',
- 'step_mismatch_integer' => 'The value for %name must be a whole number.',
- 'step_mismatch_general' => 'The value for %name must be a whole number of steps of size %step, starting from %offset.',
- );
-
-
- $expected = array(
- 'integer_no_number' => 'no_number',
- 'integer_no_step' => 0,
- 'integer_no_step_step_error' => 'step_mismatch_integer',
- 'integer_step' => 0,
- 'integer_step_error' => 'step_mismatch_general',
- 'integer_step_min' => 0,
- 'integer_step_min_error' => 'too_low',
- 'integer_step_max' => 0,
- 'integer_step_max_error' => 'too_high',
- 'integer_step_min_border' => 0,
- 'integer_step_max_border' => 0,
- 'integer_step_based_on_min' => 0,
- 'integer_step_based_on_min_error' => 'step_mismatch_general',
- 'float_small_step' => 0,
- 'float_step_no_error' => 0,
- 'float_step_error' => 'step_mismatch_general',
- 'float_step_hard_no_error' => 0,
- 'float_step_hard_error' => 'step_mismatch_general',
- 'float_step_any_no_error' => 0,
- );
-
-
- foreach (array('form-test/number', 'form-test/number/range') as $path) {
-
- $this->backdropPost($path, array(), 'Submit');
-
- foreach ($expected as $element => $error) {
-
- $placeholders = array(
- '%name' => $form[$element]['#title'],
- '%value' => $form[$element]['#default_value'],
- '%min' => isset($form[$element]['#min']) ? $form[$element]['#min'] : '0',
- '%max' => isset($form[$element]['#max']) ? $form[$element]['#max'] : '0',
- '%step' => isset($form[$element]['#step']) ? $form[$element]['#step'] : '1',
- '%offset' => isset($form[$element]['#min']) ? $form[$element]['#min'] : 0.0,
- );
-
- foreach ($error_messages as $id => $message) {
-
-
- if ($id === $error) {
- $this->assertRaw(format_string($message, $placeholders));
- }
- else {
- $this->assertNoRaw(format_string($message, $placeholders));
- }
- }
- }
- }
- }
-
-
- * Test handling of disabled elements.
- *
- * @see _form_test_disabled_elements()
- */
- function testDisabledElements() {
-
- $form_state = array();
- $form = _form_test_disabled_elements(array(), $form_state);
-
-
-
- $edit = array();
- foreach (element_children($form) as $key) {
- if (isset($form[$key]['#test_hijack_value'])) {
- if (is_array($form[$key]['#test_hijack_value'])) {
- foreach ($form[$key]['#test_hijack_value'] as $subkey => $value) {
- $edit[$key . '[' . $subkey . ']'] = $value;
- }
- }
- else {
- $edit[$key] = $form[$key]['#test_hijack_value'];
- }
- }
- }
-
-
-
- $this->backdropPost('form-test/disabled-elements', array(), t('Submit'));
- $returned_values['normal'] = backdrop_json_decode($this->content);
-
-
-
-
- $this->backdropGet('form-test/disabled-elements');
- $disabled_elements = array();
- foreach ($this->xpath('//*[@disabled]') as $element) {
- $disabled_elements[] = (string) $element['name'];
- unset($element['disabled']);
- }
-
-
-
- $this->assertEqual(count($disabled_elements), 39, 'The correct elements have the disabled property in the HTML code.');
-
- $this->backdropPost(NULL, $edit, t('Submit'));
- $returned_values['hijacked'] = backdrop_json_decode($this->content);
-
-
-
- foreach ($returned_values as $type => $values) {
- $this->assertFormValuesDefault($values, $form);
- }
- }
-
-
- * Assert that the values submitted to a form matches the default values of the elements.
- */
- function assertFormValuesDefault($values, $form) {
- foreach (element_children($form) as $key) {
- if (isset($form[$key]['#default_value'])) {
- if (isset($form[$key]['#expected_value'])) {
- $expected_value = $form[$key]['#expected_value'];
- }
- else {
- $expected_value = $form[$key]['#default_value'];
- }
-
- if ($key == 'checkboxes_multiple') {
-
- $values[$key] = array_filter($values[$key]);
- }
- $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),
- )));
- }
-
-
- $this->assertFormValuesDefault($values, $form[$key]);
- }
- }
-
-
- * Verify markup for disabled form elements.
- *
- * @see _form_test_disabled_elements()
- */
- function testDisabledMarkup() {
- $this->backdropGet('form-test/disabled-elements');
- $form_state = array();
- $form = _form_test_disabled_elements(array(), $form_state);
- $type_map = array(
- 'textarea' => 'textarea',
- 'select' => 'select',
- 'weight' => 'select',
- 'date' => 'select',
- );
-
- foreach ($form as $name => $item) {
-
- if (!isset($item['#type']) || in_array($item['#type'], array('hidden', 'text_format'))) {
- continue;
- }
-
- if (in_array($item['#type'], array('image_button', 'button', 'submit'))) {
- $path = "//!type[contains(@class, :div-class) and @value=:value]";
- $class = 'form-button-disabled';
- }
- else {
-
- $path = "//div[contains(@class, :div-class)]/descendant::!type[starts-with(@name, :name)]";
- $class = 'form-disabled';
- }
-
- $type = 'input';
- if (isset($type_map[$item['#type']])) {
- $type = $type_map[$item['#type']];
- }
- $path = strtr($path, array('!type' => $type));
-
- $element = $this->xpath($path, array(
- ':name' => check_plain($name),
- ':div-class' => $class,
- ':value' => isset($item['#value']) ? $item['#value'] : '',
- ));
- $this->assertTrue(isset($element[0]), format_string('Disabled form element class found for #type %type.', array('%type' => $item['#type'])));
- }
-
-
- $element = $this->xpath('//div[contains(@class, :div-class)]/descendant::textarea[@name=:name]', array(
- ':name' => 'text_format[value]',
- ':div-class' => 'form-disabled',
- ));
- $this->assertTrue(isset($element[0]), format_string('Disabled form element class found for #type %type.', array('%type' => 'text_format[value]')));
- $element = $this->xpath('//div[contains(@class, :div-class)]/descendant::select[@name=:name]', array(
- ':name' => 'text_format[format]',
- ':div-class' => 'form-disabled',
- ));
- $this->assertTrue(isset($element[0]), format_string('Disabled form element class found for #type %type.', array('%type' => 'text_format[format]')));
- }
-
-
- * Test Form API protections against input forgery.
- *
- * @see _form_test_input_forgery()
- */
- function testInputForgery() {
- $this->backdropGet('form-test/input-forgery');
- $checkbox = $this->xpath('//input[@name="checkboxes[two]"]');
- $checkbox[0]['value'] = 'FORGERY';
- $this->backdropPost(NULL, array('checkboxes[one]' => TRUE, 'checkboxes[two]' => TRUE), t('Submit'));
- $message = t('Invalid option %choice in %name element', array('%choice' => 'FORGERY', '%name' => 'checkboxes'));
- $this->assertRaw($message, 'Input forgery was detected.');
- }
- }
-
- * Tests building and processing of core form elements.
- */
- class FormElementTestCase extends BackdropWebTestCase {
- protected $profile = 'testing';
-
- function setUp() {
- parent::setUp(array('form_test'));
- }
-
-
- * Tests placeholder text for elements that support placeholders.
- */
- function testPlaceHolderText() {
- $this->backdropGet('form-test/placeholder-text');
- $expected = 'placeholder-text';
-
- foreach (array('textfield', 'tel', 'url', 'password', 'number') as $type) {
- $element = $this->xpath('//input[@id=:id and @placeholder=:expected]', array(
- ':id' => 'edit-' . $type,
- ':expected' => $expected,
- ));
- $this->assertTrue(!empty($element), format_string('Placeholder text placed in @type.', array('@type' => $type)));
- }
-
-
- $element = $this->xpath('//textarea[@id=:id and @placeholder=:expected]', array(
- ':id' => 'edit-textarea',
- ':expected' => $expected,
- ));
- $this->assertTrue(!empty($element), 'Placeholder text placed in textarea.');
- }
-
-
- * Tests expansion of #options for #type checkboxes and radios.
- */
- function testOptions() {
- $this->backdropGet('form-test/checkboxes-radios');
-
-
- foreach (array('checkbox', 'radio') as $type) {
- $elements = $this->xpath('//input[@type=:type]', array(':type' => $type));
- $expected_values = array('0', 'foo', '1', 'bar', '>');
- foreach ($elements as $element) {
- $expected = array_shift($expected_values);
- $this->assertIdentical((string) $element['value'], $expected);
- }
- }
-
-
- $this->backdropGet('form-test/checkboxes-radios/customize');
-
-
-
- foreach (array('checkbox', 'radio') as $type) {
- $elements = $this->xpath('//input[@type=:type]', array(':type' => $type));
- $expected_values = array('0', 'foo', 'bar', '>', '1');
- foreach ($elements as $element) {
- $expected = array_shift($expected_values);
- $this->assertIdentical((string) $element['value'], $expected);
- }
- }
-
- foreach (array('checkboxes', 'radios') as $type) {
- $elements = $this->xpath('//input[@id=:id]/following-sibling::div[@class=:class]', array(
- ':id' => 'edit-' . $type . '-foo',
- ':class' => 'description',
- ));
- $this->assertTrue(count($elements), format_string('Custom %type option description found.', array(
- '%type' => $type,
- )));
- }
- }
-
-
- * Test indentations for checkboxes, radios and select options.
- */
- public function testOptionIndentations() {
- $this->backdropGet('form-test/checkboxes-radios-select-indentations');
-
- $indentations = array(
- 'foo' => 1,
- 'bar' => 2,
- );
-
- foreach ($indentations as $key => $indentation) {
-
- $elements = $this->xpath('//div[@class="form-checkboxes"]//div[contains(@class, :class)]', array(':class' => 'form-item-indentation-' . $indentation));
- $this->assertEqual(count($elements), 1, format_string('Checkbox element with key :key has an indentation of :indentation',
- array(
- ':key' => $key,
- ':indentation' => $indentation,
- )
- ));
-
-
- $elements = $this->xpath('//div[@class="form-radios"]//div[contains(@class, :class)]', array(':class' => 'form-item-indentation-' . $indentation));
- $this->assertEqual(count($elements), 1, format_string('Radio element with value :key has an indentation of :indentation',
- array(
- ':key' => $key,
- ':indentation' => $indentation,
- )
- ));
-
-
- $elements = $this->xpath('//option[@value=:key ]', array(':key' => $key));
- $this->assertEqual($indentation, substr_count($elements[0], '·'), format_string('Select option with key :key has :indentation middle dot indentations',
- array(
- ':key' => $key,
- ':indentation' => $indentation,
- )
- ));
- }
- }
- }
-
- * Test form alter hooks.
- */
- class FormAlterTestCase extends BackdropWebTestCase {
- protected $profile = 'testing';
-
- function setUp() {
- parent::setUp('form_test');
- }
-
-
- * Tests execution order of hook_form_alter() and hook_form_FORM_ID_alter().
- */
- function testExecutionOrder() {
- $this->backdropGet('form-test/alter');
-
-
- $expected = array(
- 'form_test_form_alter() executed.',
- 'form_test_form_form_test_alter_form_alter() executed.',
- 'system_form_form_test_alter_form_alter() executed.',
- );
- $content = preg_replace('/\s+/', ' ', filter_xss($this->content, array()));
- $this->assert(strpos($content, implode(' ', $expected)) !== FALSE, format_string('Form alter hooks executed in the expected order.'));
- }
- }
-
- * Test form validation handlers.
- */
- class FormValidationTestCase extends BackdropWebTestCase {
- protected $profile = 'testing';
-
- function setUp() {
- parent::setUp('form_test');
- }
-
-
- * Tests form alterations by #element_validate, #validate, and form_set_value().
- */
- function testValidate() {
- $this->backdropGet('form-test/validate');
-
-
- $edit = array(
- 'name' => 'element_validate',
- );
- $this->backdropPost(NULL, $edit, 'Save');
- $this->assertFieldByName('name', '#value changed by #element_validate', 'Form element #value was altered.');
- $this->assertText('Name value: value changed by form_set_value() in #element_validate', 'Form element value in $form_state was altered.');
-
-
-
- $edit = array(
- 'name' => 'validate',
- );
- $this->backdropPost(NULL, $edit, 'Save');
- $this->assertFieldByName('name', '#value changed by #validate', 'Form element #value was altered.');
- $this->assertText('Name value: value changed by form_set_value() in #validate', 'Form element value in $form_state was altered.');
-
-
-
- $edit = array(
- 'name' => 'element_validate_access',
- );
- $this->backdropPost(NULL, $edit, 'Save');
- $this->assertNoFieldByName('name', t('Form element was hidden.'));
- $this->assertText('Name value: element_validate_access', 'Value for inaccessible form element exists.');
-
-
- $this->backdropPost(NULL, array(), 'Save');
- $this->assertNoFieldByName('name', t('Form element was hidden.'));
- $this->assertText('Name value: element_validate_access', 'Value for inaccessible form element exists.');
-
-
- $this->backdropLogin($this->backdropCreateUser());
- $this->backdropGet('form-test/validate');
- $edit = array(
- 'name' => 'validate',
- 'form_token' => 'invalid token'
- );
- $this->backdropPost(NULL, $edit, 'Save');
- $this->assertNoFieldByName('name', '#value changed by #validate', 'Form element #value was not altered.');
- $this->assertNoText('Name value: value changed by form_set_value() in #validate', 'Form element value in $form_state was not altered.');
- $this->assertText('The form has become outdated.');
- }
-
-
- * Tests that a form with a disabled CSRF token can be validated.
- */
- function testDisabledToken() {
- $this->backdropPost('form-test/validate-no-token', array(), 'Save');
- $this->assertText('The form_test_validate_no_token form has been submitted successfully.');
- }
-
-
- * Tests partial form validation through #limit_validation_errors.
- */
- function testValidateLimitErrors() {
- $edit = array(
- 'test' => 'invalid',
- 'test_numeric_index[0]' => 'invalid',
- 'test_substring[foo]' => 'invalid',
- );
- $path = 'form-test/limit-validation-errors';
-
-
-
-
-
- $this->backdropPost($path, $edit, t('Partial validate'));
- $this->assertNoText(t('!name field is required.', array('!name' => 'Title')));
- $this->assertText('Test element is invalid');
-
-
-
-
- $this->backdropPost($path, $edit, t('Partial validate (numeric index)'));
- $this->assertNoText(t('!name field is required.', array('!name' => 'Title')));
- $this->assertText('Test (numeric index) element is invalid');
-
-
- $this->backdropPost($path, $edit, t('Partial validate (substring)'));
- $this->assertNoText(t('!name field is required.', array('!name' => 'Title')));
- $this->assertText('Test (substring) foo element is invalid');
-
-
- $this->backdropPost($path, array('title' => '', 'test' => 'valid'), t('Partial validate'));
- $this->assertText('Only validated values appear in the form values.');
-
-
-
- $this->backdropPost($path, $edit, t('Full validate'));
- $this->assertText(t('!name field is required.', array('!name' => 'Title')));
- $this->assertText('Test element is invalid');
- }
-
-
- * Tests error border of multiple fields with same name in a page.
- */
- function testMultiFormSameNameErrorClass() {
- $this->backdropGet('form-test/double-form');
- $edit = array();
- $this->backdropPost(NULL, $edit, t('Save'));
- $this->assertFieldByXpath('//input[@id="edit-name" and contains(@class, "error")]', NULL, 'Error input form element class found for first element.');
- $this->assertNoFieldByXpath('//input[@id="edit-name--2" and contains(@class, "error")]', NULL, 'No error input form element class found for second element.');
- }
-
-
- * Tests #required with custom validation errors.
- *
- * @see form_test_validate_required_form()
- */
- function testCustomRequiredMessage() {
- $form = $form_state = array();
- $form = form_test_validate_required_form($form, $form_state);
-
-
- $edit = array();
- $this->backdropPost('form-test/validate-required', $edit, 'Submit');
-
- foreach (element_children($form) as $key) {
- if (isset($form[$key]['#required_message'])) {
- $this->assertNoText(t('!name field is required.', array('!name' => $form[$key]['#title'])));
- $this->assertText($form[$key]['#required_message']);
- }
- elseif (isset($form[$key]['#form_test_expected_message'])) {
- $this->assertText($form[$key]['#form_test_expected_message']);
- }
- }
- $this->assertNoText(t('An illegal choice has been detected. Please contact the site administrator.'));
-
-
- $edit = array(
- 'textfield' => $this->randomString(),
- 'checkboxes[foo]' => TRUE,
- 'select' => 'foo',
- 'radios' => 'foo',
- );
- $this->backdropPost('form-test/validate-required', $edit, 'Submit');
-
- foreach (element_children($form) as $key) {
- if (isset($form[$key]['#required_message'])) {
- $this->assertNoText($form[$key]['#required_message']);
- }
- elseif (isset($form[$key]['#form_test_expected_message'])) {
- $this->assertNoText($form[$key]['#form_test_expected_message']);
- }
- }
- $this->assertNoText(t('An illegal choice has been detected. Please contact the site administrator.'));
- }
- }
-
- * Test form element labels, required markers and associated output.
- */
- class FormsElementsLabelsTestCase extends BackdropWebTestCase {
- protected $profile = 'testing';
-
- function setUp() {
- parent::setUp('form_test');
- }
-
-
- * Test form elements, labels, title attributes and required marks output
- * correctly and have the correct label option class if needed.
- */
- function testFormLabels() {
- $this->backdropGet('form_test/form-labels');
-
-
-
- $elements = $this->xpath('//input[@id="edit-form-checkboxes-test-third-checkbox"]/following-sibling::label[@for="edit-form-checkboxes-test-third-checkbox" and @class="option"]');
- $this->assertTrue(isset($elements[0]), 'Label follows field and label option class correct for regular checkboxes.');
-
-
- $elements = $this->xpath('//input[@id="edit-form-checkboxes-test-0"]/following-sibling::label[@for="edit-form-checkboxes-test-0" and @class="option"]');
- $this->assertTrue(isset($elements[0]), 'Label 0 found checkbox.');
-
- $elements = $this->xpath('//input[@id="edit-form-radios-test-second-radio"]/following-sibling::label[@for="edit-form-radios-test-second-radio" and @class="option"]');
- $this->assertTrue(isset($elements[0]), 'Label follows field and label option class correct for regular radios.');
-
-
- $elements = $this->xpath('//input[@id="edit-form-radios-test-0"]/following-sibling::label[@for="edit-form-radios-test-0" and @class="option"]');
- $this->assertTrue(isset($elements[0]), 'Label 0 found radios.');
-
-
-
- $elements = $this->xpath('//input[@id="edit-form-checkbox-test"]/following-sibling::label[@for="edit-form-checkbox-test" and @class="option"]');
- $this->assertTrue(isset($elements[0]), 'Label follows field and label option class correct for a checkbox by default.');
-
-
-
- $elements = $this->xpath('//label[@for="edit-form-textfield-test-title-and-required"]/child::abbr[@class="form-required"]/parent::*/following-sibling::input[@id="edit-form-textfield-test-title-and-required"]');
- $this->assertTrue(isset($elements[0]), 'Label precedes textfield, with required marker inside label.');
-
- $elements = $this->xpath('//input[@id="edit-form-textfield-test-no-title-required"]/preceding-sibling::label[@for="edit-form-textfield-test-no-title-required"]/abbr[@class="form-required"]');
- $this->assertTrue(isset($elements[0]), 'Label tag with required marker precedes required textfield with no title.');
-
- $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"]');
- $this->assertTrue(isset($elements[0]), 'Label preceding field and label class is element-invisible.');
-
- $elements = $this->xpath('//input[@id="edit-form-textfield-test-title"]/preceding-sibling::abbr[@class="form-required"]');
- $this->assertFalse(isset($elements[0]), 'No required marker on non-required field.');
-
- $elements = $this->xpath('//input[@id="edit-form-textfield-test-title-after"]/following-sibling::label[@for="edit-form-textfield-test-title-after" and @class="option"]');
- $this->assertTrue(isset($elements[0]), 'Label after field and label option class correct for text field.');
-
- $elements = $this->xpath('//label[@for="edit-form-textfield-test-title-no-show"]');
- $this->assertFalse(isset($elements[0]), 'No label tag when title set not to display.');
-
-
- $elements = $this->xpath('//span[@class="field-prefix"]/following-sibling::div[@id="edit-form-radios-test"]');
- $this->assertTrue(isset($elements[0]), 'Properly placed the #field_prefix element after the label and before the field.');
-
- $elements = $this->xpath('//span[@class="field-suffix"]/preceding-sibling::div[@id="edit-form-radios-test"]');
- $this->assertTrue(isset($elements[0]), 'Properly places the #field_suffix element immediately after the form field.');
-
-
- $elements = $this->xpath('//div[@id="form-test-textfield-title-prefix"]/following-sibling::div[contains(@class, \'form-item-form-textfield-test-title\')]');
- $this->assertTrue(isset($elements[0]), 'Properly places the #prefix element before the form item.');
-
- $elements = $this->xpath('//div[@id="form-test-textfield-title-suffix"]/preceding-sibling::div[contains(@class, \'form-item-form-textfield-test-title\')]');
- $this->assertTrue(isset($elements[0]), 'Properly places the #suffix element before the form item.');
-
-
-
- $this->assertFieldByXPath('//div[contains(@class, "form-item-form-checkboxes-test-title-display-attribute")]/div[contains(@class, "description")]', NULL, 'Description displayed for #title_display attribute.');
- $this->assertNoFieldByXPath('//label[@for="edit-form-checkboxes-test-title-display-attribute"]', NULL, 'No title displayed for #title_display attribute.');
-
-
- $elements = $this->xpath('//div[@id="edit-form-checkboxes-title-attribute"]');
- $this->assertEqual($elements[0]['title'], 'Checkboxes test (' . t('Required') . ')', 'Title attribute found.');
- $elements = $this->xpath('//div[@id="edit-form-radios-title-attribute"]');
- $this->assertEqual($elements[0]['title'], 'Radios test (' . t('Required') . ')', 'Title attribute found.');
- }
- }
-
- * Test the tableselect form element for expected behavior.
- */
- class FormsElementsTableSelectFunctionalTest extends BackdropWebTestCase {
- protected $profile = 'testing';
-
- function setUp() {
- parent::setUp('form_test');
- }
-
-
-
- * Test the display of checkboxes when #multiple is TRUE.
- */
- function testMultipleTrue() {
-
- $this->backdropGet('form_test/tableselect/multiple-true');
-
- $this->assertNoText(t('Empty text.'), 'Empty text should not be displayed.');
-
-
- $this->assertFieldByXPath('//th[@class="select-all"]', NULL, 'Presence of the "Select all" checkbox.');
-
- $rows = array('row1', 'row2', 'row3');
- foreach ($rows as $row) {
- $this->assertFieldByXPath('//input[@type="checkbox"]', $row, format_string('Checkbox for value @row.', array('@row' => $row)));
- }
- }
-
-
- * Test the display of radios when #multiple is FALSE.
- */
- function testMultipleFalse() {
- $this->backdropGet('form_test/tableselect/multiple-false');
-
- $this->assertNoText(t('Empty text.'), 'Empty text should not be displayed.');
-
-
- $this->assertNoFieldByXPath('//th[@class="select-all"]', '', 'Absence of the "Select all" checkbox.');
-
- $rows = array('row1', 'row2', 'row3');
- foreach ($rows as $row) {
- $this->assertFieldByXPath('//input[@type="radio"]', $row, format_string('Radio button for value @row.', array('@row' => $row)));
- }
- }
-
-
- * Test the display of the #empty text when #options is an empty array.
- */
- function testEmptyText() {
- $this->backdropGet('form_test/tableselect/empty-text');
- $this->assertText(t('Empty text.'), 'Empty text should be displayed.');
- }
-
-
- * Test the submission of single and multiple values when #multiple is TRUE.
- */
- function testMultipleTrueSubmit() {
-
-
- $edit = array();
- $edit['tableselect[row1]'] = TRUE;
- $this->backdropPost('form_test/tableselect/multiple-true', $edit, 'Submit');
-
- $this->assertText(t('Submitted: row1 = row1'), 'Checked checkbox row1');
- $this->assertText(t('Submitted: row2 = 0'), 'Unchecked checkbox row2.');
- $this->assertText(t('Submitted: row3 = 0'), 'Unchecked checkbox row3.');
-
-
- $edit['tableselect[row1]'] = TRUE;
- $edit['tableselect[row3]'] = TRUE;
- $this->backdropPost('form_test/tableselect/multiple-true', $edit, 'Submit');
-
- $this->assertText(t('Submitted: row1 = row1'), 'Checked checkbox row1.');
- $this->assertText(t('Submitted: row2 = 0'), 'Unchecked checkbox row2.');
- $this->assertText(t('Submitted: row3 = row3'), 'Checked checkbox row3.');
-
- }
-
-
- * Test submission of values when #multiple is FALSE.
- */
- function testMultipleFalseSubmit() {
- $edit['tableselect'] = 'row1';
- $this->backdropPost('form_test/tableselect/multiple-false', $edit, 'Submit');
- $this->assertText(t('Submitted: row1'), 'Selected radio button');
- }
-
-
- * Test the #js_select property.
- */
- function testAdvancedSelect() {
-
- $this->backdropGet('form_test/tableselect/advanced-select/multiple-true-default');
- $this->assertFieldByXPath('//th[@class="select-all"]', NULL, 'Display a "Select all" checkbox by default when #multiple is TRUE.');
-
-
- $this->backdropGet('form_test/tableselect/advanced-select/multiple-true-no-advanced-select');
- $this->assertNoFieldByXPath('//th[@class="select-all"]', NULL, 'Do not display a "Select all" checkbox when #js_select is FALSE.');
-
-
- $this->backdropGet('form_test/tableselect/advanced-select/multiple-false-default');
- $this->assertNoFieldByXPath('//th[@class="select-all"]', NULL, 'Do not display a "Select all" checkbox when #multiple is FALSE.');
-
- $this->backdropGet('form_test/tableselect/advanced-select/multiple-false-advanced-select');
- $this->assertNoFieldByXPath('//th[@class="select-all"]', NULL, 'Do not display a "Select all" checkbox when #multiple is FALSE, even when #js_select is TRUE.');
- }
-
-
-
- * Test the whether the option checker gives an error on invalid tableselect values for checkboxes.
- */
- function testMultipleTrueOptionChecker() {
-
- list($header, $options) = _form_test_tableselect_get_data();
-
- $form['tableselect'] = array(
- '#type' => 'tableselect',
- '#header' => $header,
- '#options' => $options,
- );
-
-
- list($processed_form, $form_state, $errors) = $this->formSubmitHelper($form, array('tableselect' => array('row1' => 'row1')));
- $this->assertFalse(isset($errors['tableselect']), 'Option checker allows valid values for checkboxes.');
-
-
- list($processed_form, $form_state, $errors) = $this->formSubmitHelper($form, array('tableselect' => array('non_existing_value' => 'non_existing_value')));
- $this->assertTrue(isset($errors['tableselect']), 'Option checker disallows invalid values for checkboxes.');
-
- }
-
-
-
- * Test the whether the option checker gives an error on invalid tableselect values for radios.
- */
- function testMultipleFalseOptionChecker() {
-
- list($header, $options) = _form_test_tableselect_get_data();
-
- $form['tableselect'] = array(
- '#type' => 'tableselect',
- '#header' => $header,
- '#options' => $options,
- '#multiple' => FALSE,
- );
-
-
- list($processed_form, $form_state, $errors) = $this->formSubmitHelper($form, array('tableselect' => 'row1'));
- $this->assertFalse(isset($errors['tableselect']), 'Option checker allows valid values for radio buttons.');
-
-
- list($processed_form, $form_state, $errors) = $this->formSubmitHelper($form, array('tableselect' => 'non_existing_value'));
- $this->assertTrue(isset($errors['tableselect']), 'Option checker disallows invalid values for radio buttons.');
- }
-
-
- * Test presence of ajax functionality
- */
- function testAjax() {
- $rows = array('row1', 'row2', 'row3');
-
- foreach ($rows as $row) {
- $element = 'tableselect[' . $row . ']';
- $edit = array($element => TRUE);
- $result = $this->backdropPostAJAX('form_test/tableselect/multiple-true', $edit, $element);
- $this->assertFalse(empty($result), t('Ajax triggers on checkbox for @row.', array('@row' => $row)));
- }
-
- $element = 'tableselect';
- foreach ($rows as $row) {
- $edit = array($element => $row);
- $result = $this->backdropPostAjax('form_test/tableselect/multiple-false', $edit, $element);
- $this->assertFalse(empty($result), t('Ajax triggers on radio for @row.', array('@row' => $row)));
- }
- }
-
-
- * Helper function for the option check test to submit a form while collecting errors.
- *
- * @param $form_element
- * A form element to test.
- * @param $edit
- * An array containing post data.
- *
- * @return
- * An array containing the processed form, the form_state and any errors.
- */
- private function formSubmitHelper($form, $edit) {
- $form_id = $this->randomName();
- $form_state = form_state_defaults();
-
- $form['op'] = array('#type' => 'submit', '#value' => t('Submit'));
-
- $form_state['input'] = $edit;
- $form_state['input']['form_id'] = $form_id;
-
-
-
- $form_state['programmed'] = TRUE;
-
- backdrop_prepare_form($form_id, $form, $form_state);
-
- backdrop_process_form($form_id, $form, $form_state);
-
- $errors = form_get_errors();
-
-
- backdrop_get_messages();
- form_clear_error();
-
-
-
- return array($form, $form_state, $errors);
- }
-
- }
-
- * Test the vertical_tabs form element for expected behavior.
- */
- class FormsElementsVerticalTabsFunctionalTest extends BackdropWebTestCase {
- protected $profile = 'testing';
-
- function setUp() {
- parent::setUp('form_test');
- }
-
-
- * Ensures that vertical-tabs.js is included before collapse.js.
- *
- * Otherwise, collapse.js adds "SHOW" or "HIDE" labels to the tabs.
- */
- function testJavaScriptOrdering() {
- $this->backdropGet('form_test/vertical-tabs');
- $position1 = strpos($this->content, 'core/misc/vertical-tabs.js');
- $position2 = strpos($this->content, 'core/misc/collapse.js');
- $this->assertTrue($position1 !== FALSE && $position2 !== FALSE && $position1 < $position2, 'vertical-tabs.js is included before collapse.js');
- }
- }
-
- * Test the form storage on a multistep form.
- *
- * The tested form puts data into the storage during the initial form
- * construction. These tests verify that there are no duplicate form
- * constructions, with and without manual form caching activated. Furthermore
- * when a validation error occurs, it makes sure that changed form element
- * values aren't lost due to a wrong form rebuild.
- */
- class FormsFormStorageTestCase extends BackdropWebTestCase {
- protected $profile = 'testing';
-
-
- * @var User
- */
- protected $web_user;
-
- function setUp() {
- parent::setUp('form_test');
-
- $this->web_user = $this->backdropCreateUser();
- $this->backdropLogin($this->web_user);
- }
-
-
- * Tests using the form in a usual way.
- */
- function testForm() {
- $this->backdropGet('form_test/form-storage');
- $this->assertText('Form constructions: 1');
-
- $edit = array('title' => 'new', 'value' => 'value_is_set');
-
-
- $this->backdropPost(NULL, $edit, 'Continue submit');
- $this->assertText('Form constructions: 2');
- $this->assertText('Form constructions: 3');
-
-
-
- $this->backdropPost(NULL, array('title' => 'changed'), 'Reset');
- $this->assertFieldByName('title', 'new', 'Values have been reset.');
-
- $this->assertText('Form constructions: 4');
-
- $this->backdropPost(NULL, $edit, 'Save');
- $this->assertText('Form constructions: 4');
- $this->assertText('Title: new', 'The form storage has stored the values.');
- }
-
-
- * Tests using the form with an activated $form_state['cache'] property.
- */
- function testFormCached() {
- $this->backdropGet('form_test/form-storage', array('query' => array('cache' => 1)));
- $this->assertText('Form constructions: 1');
-
- $edit = array('title' => 'new', 'value' => 'value_is_set');
-
-
- $this->backdropPost(NULL, $edit, 'Continue submit');
- $this->assertText('Form constructions: 2');
-
-
-
- $this->backdropPost(NULL, array('title' => 'changed'), 'Reset');
- $this->assertFieldByName('title', 'new', 'Values have been reset.');
- $this->assertText('Form constructions: 3');
-
- $this->backdropPost(NULL, $edit, 'Save');
- $this->assertText('Form constructions: 3');
- $this->assertText('Title: new', 'The form storage has stored the values.');
- }
-
-
- * Tests validation when form storage is used.
- */
- function testValidation() {
- $this->backdropPost('form_test/form-storage', array('title' => '', 'value' => 'value_is_set'), 'Continue submit');
- $this->assertPattern('/value_is_set/', 'The input values have been kept.');
- }
-
-
- * Tests updating cached form storage during form validation.
- *
- * If form caching is enabled and a form stores data in the form storage, then
- * the form storage also has to be updated in case of a validation error in
- * the form. This test re-uses the existing form for multi-step tests, but
- * triggers a special #element_validate handler to update the form storage
- * during form validation, while another, required element in the form
- * triggers a form validation error.
- */
- function testCachedFormStorageValidation() {
-
- $this->backdropGet('form_test/form-storage', array('query' => array('cache' => 1)));
-
-
-
-
- $edit = array('title' => 'foo');
- $this->backdropPost(NULL, $edit, 'Continue submit');
-
-
-
-
-
- $edit = array('title' => '', 'value' => 'change_title');
- $this->backdropPost(NULL, $edit, 'Save');
-
-
-
-
-
- $this->backdropPost(NULL, array('title' => 'foo', 'value' => 'bar'), 'Save');
- $this->assertText("The thing has been changed.", 'The altered form storage value was updated in cache and taken over.');
- }
-
-
- * Tests a form using form state without using 'storage' to pass data from the
- * constructor to a submit handler. The data has to persist even when caching
- * gets activated, what may happen when a modules alter the form and adds
- * #ajax properties.
- */
- function testFormStatePersist() {
-
- $run_options = array(
- array(),
- array('query' => array('cache' => 1)),
- );
- foreach ($run_options as $options) {
- $this->backdropPost('form-test/state-persist', array(), t('Submit'), $options);
-
- $this->assertText('State persisted.');
-
-
- $this->backdropPost('form-test/state-persist', array('title' => ''), t('Submit'), $options);
- $this->assertText(t('!name field is required.', array('!name' => 'title')));
-
- $this->backdropPost(NULL, array('title' => 'foo'), t('Submit'), $options);
- $this->assertText('State persisted.');
-
-
- $this->backdropPost(NULL, array('title' => 'bar'), t('Submit'), $options);
- $this->assertText('State persisted.');
- }
- }
-
-
- * Verify that the form build-id remains the same when validation errors
- * occur on a mutable form.
- */
- function testMutableForm() {
-
- $this->backdropGet('form_test/form-storage', array('query' => array('cache' => 1)));
- $buildIdFields = $this->xpath('//input[@name="form_build_id"]');
- $this->assertEqual(count($buildIdFields), 1, 'One form build id field on the page');
- $buildId = (string) $buildIdFields[0]['value'];
-
-
- $edit = array('title' => '');
- $this->backdropPost(NULL, $edit, 'Continue submit');
-
-
- $this->assertFieldByName('form_build_id', $buildId, 'Build id remains the same when form validation fails');
- }
-
-
- * Verifies that form build-id is regenerated when loading an immutable form
- * from the cache.
- */
- function testImmutableForm() {
-
- $this->backdropGet('form_test/form-storage', array('query' => array('cache' => 1, 'immutable' => 1)));
- $buildIdFields = $this->xpath('//input[@name="form_build_id"]');
- $this->assertEqual(count($buildIdFields), 1, 'One form build id field on the page');
- $buildId = (string) $buildIdFields[0]['value'];
-
-
- $edit = array('title' => '');
- $this->backdropPost(NULL, $edit, 'Continue submit');
-
-
- $this->assertNoFieldByName('form_build_id', $buildId, 'Build id changes when form validation fails');
-
-
- $buildIdFields = $this->xpath('//input[@name="form_build_id"]');
- $this->assertEqual(count($buildIdFields), 1, 'One form build id field on the page');
- $buildId = (string) $buildIdFields[0]['value'];
-
-
- $edit = array('title' => '');
- $this->backdropPost(NULL, $edit, 'Continue submit');
-
-
- $this->assertFieldByName('form_build_id', $buildId, 'Build id remains the same when form validation fails subsequently');
- }
-
-
- * Verify that existing contrib code cannot overwrite immutable form state.
- */
- public function testImmutableFormLegacyProtection() {
- module_enable(array('dblog'));
-
- $this->backdropGet('form_test/form-storage', array('query' => array('cache' => 1, 'immutable' => 1)));
- $build_id_fields = $this->xpath('//input[@name="form_build_id"]');
- $this->assertEqual(count($build_id_fields), 1, 'One form build id field on the page');
- $build_id = (string) $build_id_fields[0]['value'];
-
-
- $original = $this->backdropGetAJAX('form_test/form-storage-legacy/' . $build_id);
- $this->assertEqual($original['form']['#build_id_old'], $build_id, 'Original build_id was recorded');
- $this->assertNotEqual($original['form']['#build_id'], $build_id, 'New build_id was generated');
-
-
- $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.'));
- $this->assert($status, 'A watchdog message was logged by form_set_cache');
-
-
- $original = $this->backdropGetAJAX('form_test/form-storage-legacy/' . $build_id);
- $this->assertEqual($original['form']['#build_id_old'], $build_id, 'Original build_id was recorded');
- $this->assertNotEqual($original['form']['#build_id'], $build_id, 'New build_id was generated');
- $this->assert(empty($original['form']['#poisoned']), 'Original form structure was preserved');
- $this->assert(empty($original['form_state']['poisoned']), 'Original form state was preserved');
- }
- }
-
- * Test the form storage when page caching for anonymous users is turned on.
- */
- class FormsFormStoragePageCacheTestCase extends BackdropWebTestCase {
- protected $profile = 'testing';
-
- public function setUp() {
- parent::setUp('form_test');
-
- config_set('system.core', 'cache', TRUE);
- }
-
-
- * Return the build id of the current form.
- */
- protected function getFormBuildId() {
- $build_id_fields = $this->xpath('//main//input[@name="form_build_id"]');
- $this->assertEqual(count($build_id_fields), 1, 'One form build id field on the page');
- return (string) $build_id_fields[0]['value'];
- }
-
-
- * Build-id is regenerated when validating cached form.
- */
- public function testValidateFormStorageOnCachedPage() {
- $this->backdropGet('form_test/form-storage-page-cache');
- $this->assertEqual($this->backdropGetHeader('X-Backdrop-Cache'), 'MISS', 'Page was not cached.');
- $this->assertText('No old build id', 'No old build id on the page');
- $build_id_initial = $this->getFormBuildId();
-
-
- $edit = array('title' => '');
- $this->backdropPost(NULL, $edit, 'Save');
- $this->assertText($build_id_initial, 'Old build id on the page');
- $build_id_first_validation = $this->getFormBuildId();
- $this->assertNotEqual($build_id_initial, $build_id_first_validation, 'Build id changes when form validation fails');
-
-
- $edit = array('title' => '');
- $this->backdropPost(NULL, $edit, 'Save');
- $this->assertText('No old build id', 'No old build id on the page');
- $build_id_second_validation = $this->getFormBuildId();
- $this->assertEqual($build_id_first_validation, $build_id_second_validation, 'Build id remains the same when form validation fails subsequently');
-
-
- $this->backdropGet('form_test/form-storage-page-cache');
- $this->assertEqual($this->backdropGetHeader('X-Backdrop-Cache'), 'HIT', 'Page was cached.');
- $this->assertText('No old build id', 'No old build id on the page');
- $build_id_from_cache_initial = $this->getFormBuildId();
- $this->assertEqual($build_id_initial, $build_id_from_cache_initial, 'Build id is the same as on the first request');
-
-
- $edit = array('title' => '');
- $this->backdropPost(NULL, $edit, 'Save');
- $this->assertText($build_id_initial, 'Old build id is initial build id');
- $build_id_from_cache_first_validation = $this->getFormBuildId();
- $this->assertNotEqual($build_id_initial, $build_id_from_cache_first_validation, 'Build id changes when form validation fails');
- $this->assertNotEqual($build_id_first_validation, $build_id_from_cache_first_validation, 'Build id from first user is not reused');
-
-
- $edit = array('title' => '');
- $this->backdropPost(NULL, $edit, 'Save');
- $this->assertText('No old build id', 'No old build id on the page');
- $build_id_from_cache_second_validation = $this->getFormBuildId();
- $this->assertEqual($build_id_from_cache_first_validation, $build_id_from_cache_second_validation, 'Build id remains the same when form validation fails subsequently');
- }
-
-
- * Build-id is regenerated when rebuilding cached form.
- */
- public function testRebuildFormStorageOnCachedPage() {
- $this->backdropGet('form_test/form-storage-page-cache');
- $this->assertEqual($this->backdropGetHeader('X-Backdrop-Cache'), 'MISS', 'Page was not cached.');
- $this->assertText('No old build id', 'No old build id on the page');
- $build_id_initial = $this->getFormBuildId();
-
-
- $edit = array('title' => 'something');
- $this->backdropPost(NULL, $edit, 'Rebuild');
- $this->assertText($build_id_initial, 'Initial build id as old build id on the page');
- $build_id_first_rebuild = $this->getFormBuildId();
- $this->assertNotEqual($build_id_initial, $build_id_first_rebuild, 'Build id changes on first rebuild.');
-
-
- $edit = array('title' => 'something');
- $this->backdropPost(NULL, $edit, 'Rebuild');
- $this->assertText($build_id_first_rebuild, 'First build id as old build id on the page');
- $build_id_second_rebuild = $this->getFormBuildId();
- $this->assertNotEqual($build_id_first_rebuild, $build_id_second_rebuild, 'Build id changes on second rebuild.');
- }
- }
-
- * Test cache_form.
- */
- class FormsFormCacheTestCase extends BackdropWebTestCase {
- protected $profile = 'testing';
-
-
- * Overrides BackdropWebTestCase::setUp() for upgrade for form cache test.
- */
- public function setUp() {
- parent::setUp('form_test');
- }
-
-
- * Tests storing and retrieving the form from cache.
- */
- public function testCacheForm() {
- $form = backdrop_get_form('form_test_cache_form');
- $form_state = array('foo' => 'bar', 'build_info' => array('baz'));
- form_set_cache($form['#build_id'], $form, $form_state);
-
- $cached_form_state = array();
- $cached_form = form_get_cache($form['#build_id'], $cached_form_state);
-
- $this->assertEqual($cached_form['#build_id'], $form['#build_id'], 'Form retrieved from cache_form successfully.');
- $this->assertEqual($cached_form_state['foo'], 'bar', 'Data retrieved from cache_form successfully.');
- }
-
-
- * Tests changing form_cache_expiration.
- */
- public function testCacheFormCustomExpiration() {
- config_set('system.core', 'form_cache_expiration', -1 * (24 * 60 * 60));
-
- $form = backdrop_get_form('form_test_cache_form');
- $form_state = array('foo' => 'bar', 'build_info' => array('baz'));
- form_set_cache($form['#build_id'], $form, $form_state);
-
-
-
- db_delete('tempstore')
- ->condition('expire', REQUEST_TIME, '<')
- ->execute();
-
- $cached_form_state = array();
- $cached_form = form_get_cache($form['#build_id'], $cached_form_state);
-
- $this->assertNull($cached_form, 'Expired form was not returned from cache.');
- $this->assertTrue(empty($cached_form_state), 'No data retrieved from cache for expired form.');
- }
- }
-
- * Test wrapper form callbacks.
- */
- class FormsFormWrapperTestCase extends BackdropWebTestCase {
- protected $profile = 'testing';
-
- function setUp() {
- parent::setUp('form_test');
- }
-
-
- * Tests using the form in a usual way.
- */
- function testWrapperCallback() {
- $this->backdropGet('form_test/wrapper-callback');
- $this->assertText('Form wrapper callback element output.', 'The form contains form wrapper elements.');
- $this->assertText('Form builder element output.', 'The form contains form builder elements.');
- }
- }
-
- * Test $form_state clearance.
- */
- class FormStateValuesCleanTestCase extends BackdropWebTestCase {
- protected $profile = 'testing';
-
- function setUp() {
- parent::setUp('form_test');
- }
-
-
- * Tests form_state_values_clean().
- */
- function testFormStateValuesClean() {
- $values = backdrop_json_decode($this->backdropPost('form_test/form-state-values-clean', array(), t('Submit')));
-
-
- $result = array(
- 'beer' => 1000,
- 'baz' => array('beer' => 2000),
- );
-
-
- $this->assertFalse(isset($values['form_id']), format_string('%element was removed.', array('%element' => 'form_id')));
- $this->assertFalse(isset($values['form_token']), format_string('%element was removed.', array('%element' => 'form_token')));
- $this->assertFalse(isset($values['form_build_id']), format_string('%element was removed.', array('%element' => 'form_build_id')));
- $this->assertFalse(isset($values['op']), format_string('%element was removed.', array('%element' => 'op')));
-
-
- $this->assertFalse(isset($values['foo']), format_string('%element was removed.', array('%element' => 'foo')));
- $this->assertFalse(isset($values['bar']), format_string('%element was removed.', array('%element' => 'bar')));
- $this->assertFalse(isset($values['baz']['foo']), format_string('%element was removed.', array('%element' => 'foo')));
- $this->assertFalse(isset($values['baz']['baz']), format_string('%element was removed.', array('%element' => 'baz')));
-
-
- $this->assertTrue(isset($values['baz']['beer']), 'Nested form value still exists.');
-
-
- $this->assertEqual($values, $result, 'Expected form values equal actual form values.');
- }
- }
-
- * Tests $form_state clearance with form elements having buttons.
- */
- class FormStateValuesCleanAdvancedTestCase extends BackdropWebTestCase {
- protected $profile = 'testing';
-
-
- * An image file path for uploading.
- */
- protected $image;
-
- function setUp() {
- parent::setUp('file', 'form_test');
- }
-
-
- * Tests form_state_values_clean().
- */
- function testFormStateValuesCleanAdvanced() {
-
-
- $image_files = $this->backdropGetTestFiles('image');
- $this->image = current($image_files);
-
-
- $this->assertTrue(is_file($this->image->uri), "The image file we're going to upload exists.");
-
-
- $edit = array('files[image]' => backdrop_realpath($this->image->uri));
-
-
- $this->backdropPost('form_test/form-state-values-clean-advanced', $edit, t('Submit'));
-
-
- $this->assertResponse(200, 'Received a 200 response for posted test file.');
- $this->assertRaw(t('You WIN!'), 'Found the success message.');
- }
- }
-
- * Tests form rebuilding.
- *
- * @todo Add tests for other aspects of form rebuilding.
- */
- class FormsRebuildTestCase extends BackdropWebTestCase {
-
-
- * @var User
- */
- protected $web_user;
-
- function setUp() {
- parent::setUp('form_test');
-
- $this->web_user = $this->backdropCreateUser();
- $this->backdropLogin($this->web_user);
- }
-
-
- * Tests preservation of values.
- */
- function testRebuildPreservesValues() {
- $edit = array(
- 'checkbox_1_default_off' => TRUE,
- 'checkbox_1_default_on' => FALSE,
- 'text_1' => 'foo',
- );
- $this->backdropPost('form-test/form-rebuild-preserve-values', $edit, 'Add more');
-
-
- $this->assertFieldChecked('edit-checkbox-1-default-off', 'A submitted checked checkbox retained its checked state during a rebuild.');
- $this->assertNoFieldChecked('edit-checkbox-1-default-on', 'A submitted unchecked checkbox retained its unchecked state during a rebuild.');
- $this->assertFieldById('edit-text-1', 'foo', 'A textfield retained its submitted value during a rebuild.');
-
-
- $this->assertFieldChecked('edit-checkbox-2-default-on', 'A newly added checkbox was initialized with a default checked state.');
- $this->assertNoFieldChecked('edit-checkbox-2-default-off', 'A newly added checkbox was initialized with a default unchecked state.');
- $this->assertFieldById('edit-text-2', 'DEFAULT 2', 'A newly added textfield was initialized with its default value.');
- }
-
-
- * Tests that a form's action is retained after an Ajax submission.
- *
- * The 'action' attribute of a form should not change after an Ajax submission
- * followed by a non-Ajax submission, which triggers a validation error.
- */
- function testPreserveFormActionAfterAJAX() {
-
- $field_name = 'field_ajax_test';
- $field = array(
- 'field_name' => $field_name,
- 'type' => 'text',
- 'cardinality' => FIELD_CARDINALITY_UNLIMITED,
- );
- field_create_field($field);
- $instance = array(
- 'field_name' => $field_name,
- 'entity_type' => 'node',
- 'bundle' => 'page',
- );
- field_create_instance($instance);
-
-
- $this->web_user = $this->backdropCreateUser(array('create page content'));
- $this->backdropLogin($this->web_user);
-
-
-
-
- $this->backdropGet('node/add/page');
- $this->backdropPostAJAX(NULL, array(), array('field_ajax_test_add_more' => t('Add another')), 'system/ajax', array(), array(), 'page-node-form');
- $this->assert(count($this->xpath('//div[contains(@class, "field-name-field-ajax-test")]//input[@type="text"]')) == 2, 'AJAX submission succeeded.');
-
-
-
-
-
-
- $this->backdropPost(NULL, array(), t('Save'));
- $this->assertText('Title field is required.', 'Non-AJAX submission correctly triggered a validation error.');
-
-
-
- $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.');
-
-
- $forms = $this->xpath('//form[contains(@class, "node-page-form")]');
- $this->assert(count($forms) == 1 && $forms[0]['action'] == url('node/add/page'), 'Re-rendered form contains the correct action value.');
- }
- }
-
- * Tests form redirection.
- */
- class FormsRedirectTestCase extends BackdropWebTestCase {
- protected $profile = 'testing';
-
- function setUp() {
- parent::setUp(array('form_test'));
- }
-
-
- * Tests form redirection.
- */
- function testRedirect() {
- $path = 'form-test/redirect';
- $options = array('query' => array('foo' => 'bar'));
- $options['absolute'] = TRUE;
-
-
- $edit = array(
- 'redirection' => TRUE,
- 'destination' => $this->randomName(),
- );
- $this->backdropPost($path, $edit, t('Submit'));
- $this->assertUrl($edit['destination'], array(), 'Basic redirection works.');
-
-
-
- $edit = array(
- 'redirection' => FALSE,
- );
- $this->backdropPost($path, $edit, t('Submit'));
- $this->assertUrl($path, array(), 'When redirect is set to FALSE, there should be no redirection.');
-
-
- $edit = array(
- 'redirection' => TRUE,
- 'destination' => $this->randomName(),
- );
- $this->backdropPost($path, $edit, t('Submit'), $options);
- $this->assertUrl($edit['destination'], array(), 'Redirection with query parameters works.');
-
-
- $edit = array(
- 'redirection' => FALSE,
- );
- $this->backdropPost($path, $edit, t('Submit'), $options);
- $this->assertUrl($path, $options, 'When redirect is set to FALSE, there should be no redirection, and the query parameters should be passed along.');
-
-
- $edit = array(
- 'redirection' => TRUE,
- 'destination' => '',
- );
- $this->backdropPost($path, $edit, t('Submit'));
- $this->assertUrl($path, array(), 'When using an empty redirection string, there should be no redirection.');
-
-
- $edit = array(
- 'redirection' => TRUE,
- 'destination' => '',
- );
- $this->backdropPost($path, $edit, t('Submit'), $options);
- $this->assertUrl($path, $options, 'When using an empty redirection string, there should be no redirection, and the query parameters should be passed along.');
- }
-
- }
-
- * Test the programmatic form submission behavior.
- */
- class FormsProgrammaticTestCase extends BackdropWebTestCase {
- protected $profile = 'testing';
-
- function setUp() {
- parent::setUp('form_test');
- }
-
-
- * Test the programmatic form submission workflow.
- */
- function testSubmissionWorkflow() {
-
-
- $current_batch = $batch =& batch_get();
- $batch = array();
-
-
-
- $this->submitForm(array(), FALSE);
- $this->submitForm(array('textfield' => 'test 1'), TRUE);
- $this->submitForm(array(), FALSE);
- $this->submitForm(array('textfield' => 'test 2'), TRUE);
-
-
-
- $this->submitForm(array('textfield' => 'dummy value', 'checkboxes' => array(1 => 1, 2 => 2)), TRUE);
- $this->submitForm(array('textfield' => 'dummy value', 'checkboxes' => array(1 => 1, 2 => NULL)), TRUE);
- $this->submitForm(array('textfield' => 'dummy value', 'checkboxes' => array(1 => NULL, 2 => 2)), TRUE);
- $this->submitForm(array('textfield' => 'dummy value', 'checkboxes' => array(1 => NULL, 2 => NULL)), TRUE);
-
-
-
- $this->submitForm(array('textfield' => 'dummy value', 'textfield_no_access' => 'test value'), TRUE);
-
-
- $submitted_values = array('textfield' => 'dummy value', 'textfield_no_access' => 'test value');
- $expected_values = array('textfield' => 'dummy value', 'textfield_no_access' => 'default value');
- $form_state = array('programmed_bypass_access_check' => FALSE);
- $this->submitForm($submitted_values, TRUE, $expected_values, $form_state);
-
-
-
-
-
-
- $this->submitForm(array('op' => 'Submit with limited validation', 'field_to_validate' => 'all'), FALSE);
- $this->submitForm(array('op' => 'Submit with limited validation', 'field_to_validate' => 'textfield'), FALSE);
- $this->submitForm(array('op' => 'Submit with limited validation', 'field_to_validate' => 'field_to_validate'), TRUE);
-
-
- $batch = $current_batch;
- }
-
-
- * Helper function used to programmatically submit the form defined in
- * form_test.module with the given values.
- *
- * @param $values
- * An array of field values to be submitted.
- * @param $valid_input
- * A boolean indicating whether or not the form submission is expected to
- * be valid.
- * @param $expected_values
- * (Optional) An array of field values that are expected to be stored by
- * the form submit handler. If not set, the submitted $values are assumed
- * to also be the expected stored values.
- * @param $form_state
- * (Optional) A keyed array containing the state of the form, to be sent in
- * the call to backdrop_form_submit(). The $values parameter is added to
- * $form_state['values'] by default, if it is not already set.
- */
- private function submitForm($values, $valid_input, $expected_values = NULL, $form_state = array()) {
-
- $form_state += array('values' => $values);
- backdrop_form_submit('form_test_programmatic_form', $form_state);
-
-
- $errors = form_get_errors();
- $valid_form = empty($errors);
- $args = array(
- '%values' => print_r($values, TRUE),
- '%errors' => $valid_form ? t('None') : implode(' ', $errors),
- );
- $this->assertTrue($valid_input == $valid_form, format_string('Input values: %values<br/>Validation handler errors: %errors', $args));
-
-
- if ($valid_input) {
-
-
- $stored_values = $form_state['storage']['programmatic_form_submit'];
- if (!isset($expected_values)) {
- $expected_values = $values;
- }
- foreach ($expected_values as $key => $value) {
- $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),
- )));
- }
- }
- }
- }
-
- * Test that FAPI correctly determines $form_state['triggering_element'].
- */
- class FormsTriggeringElementTestCase extends BackdropWebTestCase {
- protected $profile = 'testing';
-
- function setUp() {
- parent::setUp('form_test');
- }
-
-
- * Test the determination of $form_state['triggering_element'] when no button
- * information is included in the POST data, as is sometimes the case when
- * the ENTER key is pressed in a textfield in Internet Explorer.
- */
- function testNoButtonInfoInPost() {
- $path = 'form-test/clicked-button';
- $edit = array();
- $form_html_id = 'form-test-clicked-button';
-
-
-
-
- $this->backdropPost($path, $edit, NULL, array(), array(), $form_html_id);
- $this->assertText('There is no clicked button.', '$form_state[\'triggering_element\'] set to NULL.');
- $this->assertNoText('Submit handler for form_test_clicked_button executed.', 'Form submit handler did not execute.');
-
-
-
-
-
- $this->backdropPost($path . '/s', $edit, NULL, array(), array(), $form_html_id);
- $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to only button.');
- $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');
-
- $this->backdropPost($path . '/s/s', $edit, NULL, array(), array(), $form_html_id);
- $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to first button.');
- $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');
-
- $this->backdropPost($path . '/rs/s', $edit, NULL, array(), array(), $form_html_id);
- $this->assertText('The clicked button is button2.', '$form_state[\'triggering_element\'] set to first available button.');
- $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');
-
-
-
-
-
-
- $this->backdropPost($path . '/s/b/i', $edit, NULL, array(), array(), $form_html_id);
- $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to first button.');
- $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');
-
- $this->backdropPost($path . '/b/s/i', $edit, NULL, array(), array(), $form_html_id);
- $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to first button.');
- $this->assertNoText('Submit handler for form_test_clicked_button executed.', 'Form submit handler did not execute.');
-
- $this->backdropPost($path . '/i/s/b', $edit, NULL, array(), array(), $form_html_id);
- $this->assertText('The clicked button is button1.', '$form_state[\'triggering_element\'] set to first button.');
- $this->assertText('Submit handler for form_test_clicked_button executed.', 'Form submit handler executed.');
- }
-
-
- * Test that $form_state['triggering_element'] does not get set to a button
- * with #access=FALSE.
- */
- function testAttemptAccessControlBypass() {
- $path = 'form-test/clicked-button';
- $form_html_id = 'form-test-clicked-button';
-
-
- $this->backdropGet($path . '/rs/s');
-
-
-
-
-
-
- $elements = $this->xpath('//form[@id="' . $form_html_id . '"]//input[@name="text"]');
- $elements[0]['name'] = 'button1';
- $this->backdropPost(NULL, array('button1' => 'button1'), NULL, array(), array(), $form_html_id);
-
-
-
-
-
-
- $this->assertNoText('The clicked button is button1.', '$form_state[\'triggering_element\'] not set to a restricted button.');
- $this->assertText('The clicked button is button2.', '$form_state[\'triggering_element\'] not set to a restricted button.');
- }
- }
-
- * Tests rebuilding of arbitrary forms by altering them.
- */
- class FormsArbitraryRebuildTestCase extends BackdropWebTestCase {
- function setUp() {
- parent::setUp('form_test');
-
- $field = array(
- 'field_name' => 'test_multiple',
- 'type' => 'text',
- 'cardinality' => -1,
- 'translatable' => FALSE,
- );
- field_create_field($field);
-
- $instance = array(
- 'entity_type' => 'node',
- 'field_name' => 'test_multiple',
- 'bundle' => 'page',
- 'label' => 'Test a multiple valued field',
- 'widget' => array(
- 'type' => 'text_textfield',
- 'weight' => 0,
- ),
- );
- field_create_instance($instance);
- config_set('system.core', 'user_register', USER_REGISTER_VISITORS);
- }
-
-
- * Tests a basic rebuild with the user registration form.
- */
- function testUserRegistrationRebuild() {
- $edit = array(
- 'name' => 'foo',
- 'mail' => 'bar@example.com',
- );
- $this->backdropPost('user/register', $edit, 'Rebuild');
- $this->assertText('Form rebuilt.');
- $this->assertFieldByName('name', 'foo', 'Entered user name has been kept.');
- $this->assertFieldByName('mail', 'bar@example.com', 'Entered mail address has been kept.');
- }
-
-
- * Tests a rebuild caused by a multiple value field.
- */
- function testUserRegistrationMultipleField() {
- $edit = array(
- 'name' => 'foo',
- 'mail' => 'bar@example.com',
- );
- $this->backdropPost('user/register', $edit, t('Add another'), array('query' => array('field' => TRUE)));
- $this->assertText('Test a multiple valued field', 'Form has been rebuilt.');
- $this->assertFieldByName('name', 'foo', 'Entered user name has been kept.');
- $this->assertFieldByName('mail', 'bar@example.com', 'Entered mail address has been kept.');
- }
- }
-
- * Tests form API file inclusion.
- */
- class FormsFileInclusionTestCase extends BackdropWebTestCase {
- protected $profile = 'testing';
-
- function setUp() {
- parent::setUp('form_test');
- }
-
-
- * Tests loading an include specified in hook_menu().
- */
- function testLoadMenuInclude() {
- $this->backdropPostAJAX('form-test/load-include-menu', array(), array('op' => t('Save')), 'system/ajax', array(), array(), 'form-test-load-include-menu');
- $this->assertText('Submit callback called.');
- }
-
-
- * Tests loading a custom specified include.
- */
- function testLoadCustomInclude() {
- $this->backdropPost('form-test/load-include-custom', array(), t('Save'));
- $this->assertText('Submit callback called.');
- }
- }
-
- * Tests checkbox element.
- */
- class FormCheckboxTestCase extends BackdropWebTestCase {
- protected $profile = 'testing';
-
- function setUp() {
- parent::setUp('form_test');
- }
-
- function testFormCheckbox() {
-
-
- foreach (array(FALSE, NULL, TRUE, 0, '0', '', 1, '1', 'foobar', '1foobar') as $default_value) {
-
-
-
- foreach (array('0', '', 1, '1', 'foobar', '1foobar') as $return_value) {
- $form_array = backdrop_get_form('form_test_checkbox_type_juggling', $default_value, $return_value);
- $form = backdrop_render($form_array);
- if ($default_value === TRUE) {
- $checked = TRUE;
- }
- elseif ($return_value === '0') {
- $checked = ($default_value === '0');
- }
- elseif ($return_value === '') {
- $checked = ($default_value === '');
- }
- elseif ($return_value === 1 || $return_value === '1') {
- $checked = ($default_value === 1 || $default_value === '1');
- }
- elseif ($return_value === 'foobar') {
- $checked = ($default_value === 'foobar');
- }
- elseif ($return_value === '1foobar') {
- $checked = ($default_value === '1foobar');
- }
- $checked_in_html = strpos($form, 'checked') !== FALSE;
- $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),
- ));
- $this->assertIdentical($checked, $checked_in_html, $message);
- }
- }
-
-
-
- $results = json_decode($this->backdropPost('form-test/checkboxes-zero', array(), 'Save'));
- $this->assertIdentical($results->checkbox_off, array(0, 0, 0), 'All three in checkbox_off are zeroes: off.');
- $this->assertIdentical($results->checkbox_zero_default, array('0', 0, 0), 'The first choice is on in checkbox_zero_default');
- $this->assertIdentical($results->checkbox_string_zero_default, array('0', 0, 0), 'The first choice is on in checkbox_string_zero_default');
- $edit = array('checkbox_off[0]' => '0');
- $results = json_decode($this->backdropPost('form-test/checkboxes-zero', $edit, 'Save'));
- $this->assertIdentical($results->checkbox_off, array('0', 0, 0), 'The first choice is on in checkbox_off but the rest is not');
-
-
-
- $this->backdropPost('form-test/checkboxes-zero/0', array(), 'Save');
- $checkboxes = $this->xpath('//input[@type="checkbox"]');
- foreach ($checkboxes as $checkbox) {
- $checked = isset($checkbox['checked']);
- $name = (string) $checkbox['name'];
- $this->assertIdentical($checked, $name == 'checkbox_zero_default[0]' || $name == 'checkbox_string_zero_default[0]', format_string('Checkbox %name correctly checked', array('%name' => $name)));
- }
- $edit = array('checkbox_off[0]' => '0');
- $this->backdropPost('form-test/checkboxes-zero/0', $edit, 'Save');
- $checkboxes = $this->xpath('//input[@type="checkbox"]');
- foreach ($checkboxes as $checkbox) {
- $checked = isset($checkbox['checked']);
- $name = (string) $checkbox['name'];
- $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)));
- }
-
-
-
-
- $admin_user = $this->backdropCreateUser(array(
- 'access content overview',
- 'bypass node access',
- 'access administration pages',
- ));
- $this->backdropLogin($admin_user);
- $options = array(
- 'query' => array(
- 'status' => 'All',
- 'type' => 'All',
- 'title' => '',
- 'order' => 'title',
- 'sort' => 'asc',
- ),
- );
- $values = array(
- '0' => FALSE,
- 'foobar' => FALSE,
- '1' => TRUE,
- );
- foreach ($values as $key => $checked) {
- $options['query']['timestamp'] = $key;
- $this->backdropGet('admin/content/node', $options);
- $checkbox = $this->xpath('//input[@id="edit-timestamp"]');
- $attributes = $checkbox[0]->attributes();
-
- $this->assertEqual(isset($attributes['checked']), $values[$key], format_string('Expected checked status is set via GET for value %key.', array(
- '%key' => $key,
- )));
- }
- }
-
- }
-
- * Test transition from old JS-based textarea resize to new CSS approach.
- */
- class FormResizableTextareaTestCase extends BackdropWebTestCase {
-
- protected $profile = 'testing';
-
-
- * {@inheritdoc}
- */
- protected function setUp() {
- parent::setUp('form_test');
- return TRUE;
- }
-
-
- * Test that setting #resizable on form item results in correct CSS classes.
- */
- protected function testResizableTextarea() {
- $this->backdropGet('form-test/textarea-resize');
-
- $name_classes = array(
- 'text-true' => 'form-textarea resize-vertical',
- 'text-false' => 'form-textarea resize-none',
- 'text-vertical' => 'form-textarea resize-vertical',
- 'text-horizontal' => 'form-textarea resize-horizontal',
- 'text-none' => 'form-textarea resize-none',
- 'text-wrong' => 'form-textarea',
- );
-
- foreach ($name_classes as $name => $classes) {
- $textarea = $this->xpath('//textarea[@name=:name]', array(
- ':name' => $name,
- ));
- $class_attrib = (string) $textarea[0]->attributes()->class;
- $this->assertEqual($class_attrib, $classes, format_string('Classes for item with name %name set to %classes', array(
- '%name' => $name,
- '%classes' => $classes,
- )));
- }
- }
-
- }
-
- * Tests email element.
- */
- class FormEmailTestCase extends BackdropWebTestCase {
- protected $profile = 'testing';
-
- function setUp() {
- parent::setUp('form_test');
- }
-
-
- * Tests that #type 'email' fields are properly validated.
- */
- function testFormEmail() {
- $edit = array();
- $edit['email'] = 'invalid';
- $edit['email_required'] = ' ';
- $this->backdropPost('form-test/email', $edit, 'Submit');
- $this->assertRaw(t('The email address %mail is not valid.', array('%mail' => 'invalid')));
- $this->assertRaw(t('!name field is required.', array('!name' => 'Address')));
-
- $edit = array();
- $edit['email_required'] = ' foo.bar@example.com ';
- $values = backdrop_json_decode($this->backdropPost('form-test/email', $edit, 'Submit'));
- $this->assertIdentical($values['email'], '');
- $this->assertEqual($values['email_required'], 'foo.bar@example.com');
-
- $edit = array();
- $edit['email'] = 'foo@example.com';
- $edit['email_required'] = 'example@backdropcms.org';
- $values = backdrop_json_decode($this->backdropPost('form-test/email', $edit, 'Submit'));
- $this->assertEqual($values['email'], 'foo@example.com');
- $this->assertEqual($values['email_required'], 'example@backdropcms.org');
- }
- }
-
- * Tests html5 date and time elements.
- */
- class FormH5datetimeTestCase extends BackdropWebTestCase {
- protected $profile = 'testing';
-
- function setUp() {
- parent::setUp('form_test');
- }
-
-
- * Tests for #type 'html_date', 'html_time' and 'html_datetime' validation.
- */
- function testFormH5datetime() {
- $edit = array();
-
- $edit['h5date'] = '2002-02-01';
- $edit['h5time'] = '10:33:00';
- $edit['h5datetime[date]'] = '1990-03-22';
- $edit['h5datetime[time]'] = '10:30:20';
- $values = backdrop_json_decode($this->backdropPost('form-test/h5datetime', $edit, 'Submit'));
- $this->assertEqual($values['h5date'], '2002-02-01', 'Correct h5date input validates');
- $this->assertEqual($values['h5time'], '10:33:00', 'Correct h5time input validates');
- $message = 'Correct h5 date and time combined input validates';
- $this->assertEqual($values['h5datetime'], array('date' => '1990-03-22', 'time' => '10:30:20'), $message);
-
-
- $edit = array();
- $edit['h5date'] = '2002-02-40';
- $edit['h5time'] = '10:66:00';
- $this->backdropPost('form-test/h5datetime', $edit, 'Submit');
- $this->assertRaw(t('%date is not a valid date.', array('%date' => '2002-02-40')), 'Invalid date doesn\'t validate');
- $this->assertRaw(t('%time is not a valid time.', array('%time' => '10:66:00')), 'Invalid time doesn\'t validate');
- }
-
-
- * Test return value for disabled html_date and html_time elements.
- *
- * These two FAPI elements use an array for #default_value, so, the value
- * callback function html_date_or_time_value_callback needs to take care of
- * converting the array to a string upon submission of a form that contains
- * them.
- */
- public function testNoAccessH5DateOrTimeElement() {
- $values = backdrop_json_decode($this->backdropPost('form-test/no-access-h5date-h5time', array(), 'Submit'));
-
-
- $this->assertEqual($values['no_access_h5date'], '2023-01-01', 'Correct no_access_h5date value');
- $this->assertEqual($values['no_access_h5time'], '20:30', 'Correct no_access_h5time value');
- $this->assertEqual($values['disabled_h5date'], '2023-01-01', 'Correct disabled_h5date value');
- $this->assertEqual($values['disabled_h5time'], '20:30', 'Correct disabled_h5time value');
- }
- }
-
- * Tests uniqueness of generated HTML IDs.
- */
- class HTMLIdTestCase extends BackdropWebTestCase {
- protected $profile = 'testing';
-
- function setUp() {
- parent::setUp('form_test');
- }
-
-
- * Tests that HTML IDs do not get duplicated when form validation fails.
- */
- function testHTMLId() {
- $this->backdropGet('form-test/double-form');
- $this->assertNoDuplicateIds('There are no duplicate IDs');
-
-
- $edit = array();
- $this->backdropPost(NULL, $edit, 'Save', array(), array(), 'form-test-html-id--2');
- $this->assertNoDuplicateIds('There are no duplicate IDs');
- }
- }
-
- * Tests url element.
- */
- class FormUrlTestCase extends BackdropWebTestCase {
- protected $profile = 'testing';
-
- public function setUp() {
- parent::setUp('form_test');
- }
-
-
- * Tests that #type 'url' fields are properly validated and trimmed.
- */
- function testFormUrl() {
- $edit = array();
- $edit['url'] = 'http://';
- $edit['url_required'] = ' ';
- $this->backdropPost('form-test/url', $edit, 'Submit');
- $this->assertRaw(t('The URL %url is not valid.', array('%url' => 'http://')));
- $this->assertRaw(t('!name field is required.', array('!name' => 'Required URL')));
-
- $edit = array();
- $edit['url'] = "\n";
- $edit['url_required'] = 'http://example.com/ ';
- $values = backdrop_json_decode($this->backdropPost('form-test/url', $edit, 'Submit'));
- $this->assertIdentical($values['url'], '');
- $this->assertEqual($values['url_required'], 'http://example.com/');
-
- $edit = array();
- $edit['url'] = 'http://foo.bar.example.com/';
- $edit['url_required'] = 'https://backdropcms.org/example?page=0&foo=bar#new';
- $values = backdrop_json_decode($this->backdropPost('form-test/url', $edit, 'Submit'));
- $this->assertEqual($values['url'], $edit['url']);
- $this->assertEqual($values['url_required'], $edit['url_required']);
- }
- }
-
- * Tests for form textarea.
- */
- class FormTextareaTestCase extends BackdropUnitTestCase {
- protected $profile = 'testing';
-
-
- * Tests that textarea value is properly set.
- */
- public function testValueCallback() {
- $element = array();
- $form_state = array();
- $test_cases = array(
- array(NULL, FALSE),
- array(NULL, NULL),
- array('', array('test')),
- array('test', 'test'),
- array('123', 123),
- );
- foreach ($test_cases as $test_case) {
- list($expected, $input) = $test_case;
- $this->assertIdentical($expected, form_type_textarea_value($element, $input, $form_state));
- }
- }
- }
-
- class SystemSettingsFormTest extends SystemConfigFormCase {
- protected $profile = 'testing';
-
- public function setUp() {
- parent::setUp(array('form_test'));
- $this->form_id = 'form_test_system_config_form';
- $this->values = array(
- 'abc' => array(
- '#value' => $this->randomString(),
- '#config_name' => 'simpletest.testconfig',
- '#config_key' => 'abc',
- ),
- 'def' => array(
- '#value' => $this->randomString(),
- '#config_name' => 'simpletest.testconfig',
- '#config_key' => 'def',
- ),
-
- 'rss_description' => array(
- '#value' => $this->randomString(),
- '#config_name' => 'system.core',
- '#config_key' => 'rss_description',
- ),
-
- 'ghi' => array(
- '#value' => $this->randomString(),
- '#config_name' => 'simpletest.secondconfig',
- '#config_key' => 'ghi',
- ),
- 'jkl' => array(
- '#value' => $this->randomString(),
- '#config_name' => 'simpletest.secondconfig',
- '#config_key' => 'jkl',
- ),
- );
- }
- }