function LinkFieldTest::testURLValidation

Tests link field URL validation.

File

drupal/core/modules/field/modules/link/lib/Drupal/link/Tests/LinkFieldTest.php, line 45
Contains Drupal\link\Tests\LinkFieldTest.

Class

LinkFieldTest
Tests link field widgets and formatters.

Namespace

Drupal\link\Tests

Code

function testURLValidation() {

  // Create a field with settings to validate.
  $this->field = array(
    'field_name' => drupal_strtolower($this
      ->randomName()),
    'type' => 'link',
  );
  field_create_field($this->field);
  $this->instance = array(
    'field_name' => $this->field['field_name'],
    'entity_type' => 'test_entity',
    'bundle' => 'test_bundle',
    'settings' => array(
      'title' => DRUPAL_DISABLED,
    ),
    'widget' => array(
      'type' => 'link_default',
      'settings' => array(
        'placeholder_url' => 'http://example.com',
      ),
    ),
    'display' => array(
      'full' => array(
        'type' => 'link',
      ),
    ),
  );
  field_create_instance($this->instance);
  $langcode = LANGUAGE_NOT_SPECIFIED;

  // Display creation form.
  $this
    ->drupalGet('test-entity/add/test_bundle');
  $this
    ->assertFieldByName("{$this->field['field_name']}[{$langcode}][0][url]", '', 'Link URL field is displayed');
  $this
    ->assertRaw('placeholder="http://example.com"');

  // Verify that a valid URL can be submitted.
  $value = 'http://www.example.com/';
  $edit = array(
    "{$this->field['field_name']}[{$langcode}][0][url]" => $value,
  );
  $this
    ->drupalPost(NULL, $edit, t('Save'));
  preg_match('|test-entity/manage/(\\d+)/edit|', $this->url, $match);
  $id = $match[1];
  $this
    ->assertRaw(t('test_entity @id has been created.', array(
    '@id' => $id,
  )));
  $this
    ->assertRaw($value);

  // Verify that invalid URLs cannot be submitted.
  $wrong_entries = array(
    // Missing protcol
    'not-an-url',
    // Invalid protocol
    'invalid://not-a-valid-protocol',
    // Missing host name
    'http://',
  );
  $this
    ->drupalGet('test-entity/add/test_bundle');
  foreach ($wrong_entries as $invalid_value) {
    $edit = array(
      "{$this->field['field_name']}[{$langcode}][0][url]" => $invalid_value,
    );
    $this
      ->drupalPost(NULL, $edit, t('Save'));
    $this
      ->assertText(t('The URL @url is not valid.', array(
      '@url' => $invalid_value,
    )));
  }
}