1 form.test FormsTestCase::testNumber()

Tests validation of #type 'number' elements.

File

core/modules/simpletest/tests/form.test, line 379
Unit tests for the Backdrop Form API.

Class

FormsTestCase

Code

function testNumber() {
  $form = $form_state = array();
  $form = form_test_number($form, $form_state);
  $this->backdropGet('form-test/number');

  // Array with all the error messages to be checked.
  // @see form_validate_number() for the messages.
  $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.',
  );

  // The expected errors.
  $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,
  );

  // First test the number element type, then range.
  foreach (array('form-test/number', 'form-test/number/range') as $path) {
    // Post form and show errors.
    $this->backdropPost($path, array(), 'Submit');

    foreach ($expected as $element => $error) {
      // Create placeholder array.
      $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) {
        // Check if the error exists on the page, if the current message ID is
        // expected. Otherwise ensure that the error message is not present.
        if ($id === $error) {
          $this->assertRaw(format_string($message, $placeholders));
        }
        else {
          $this->assertNoRaw(format_string($message, $placeholders));
        }
      }
    }
  }
}