You are here

function FileFieldWidgetTest::testWidgetValidation in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/file/src/Tests/FileFieldWidgetTest.php \Drupal\file\Tests\FileFieldWidgetTest::testWidgetValidation()

Tests validation with the Upload button.

File

core/modules/file/src/Tests/FileFieldWidgetTest.php, line 381
Contains \Drupal\file\Tests\FileFieldWidgetTest.

Class

FileFieldWidgetTest
Tests the file field widget, single and multi-valued, with and without AJAX, with public and private files.

Namespace

Drupal\file\Tests

Code

function testWidgetValidation() {
  $type_name = 'article';
  $field_name = strtolower($this
    ->randomMachineName());
  $this
    ->createFileField($field_name, 'node', $type_name);
  $this
    ->updateFileField($field_name, $type_name, array(
    'file_extensions' => 'txt',
  ));
  foreach (array(
    'nojs',
    'js',
  ) as $type) {

    // Create node and prepare files for upload.
    $node = $this
      ->drupalCreateNode(array(
      'type' => 'article',
    ));
    $nid = $node
      ->id();
    $this
      ->drupalGet("node/{$nid}/edit");
    $test_file_text = $this
      ->getTestFile('text');
    $test_file_image = $this
      ->getTestFile('image');
    $name = 'files[' . $field_name . '_0]';

    // Upload file with incorrect extension, check for validation error.
    $edit[$name] = drupal_realpath($test_file_image
      ->getFileUri());
    switch ($type) {
      case 'nojs':
        $this
          ->drupalPostForm(NULL, $edit, t('Upload'));
        break;
      case 'js':
        $button = $this
          ->xpath('//input[@type="submit" and @value="' . t('Upload') . '"]');
        $this
          ->drupalPostAjaxForm(NULL, $edit, array(
          (string) $button[0]['name'] => (string) $button[0]['value'],
        ));
        break;
    }
    $error_message = t('Only files with the following extensions are allowed: %files-allowed.', array(
      '%files-allowed' => 'txt',
    ));
    $this
      ->assertRaw($error_message, t('Validation error when file with wrong extension uploaded (JSMode=%type).', array(
      '%type' => $type,
    )));

    // Upload file with correct extension, check that error message is removed.
    $edit[$name] = drupal_realpath($test_file_text
      ->getFileUri());
    switch ($type) {
      case 'nojs':
        $this
          ->drupalPostForm(NULL, $edit, t('Upload'));
        break;
      case 'js':
        $button = $this
          ->xpath('//input[@type="submit" and @value="' . t('Upload') . '"]');
        $this
          ->drupalPostAjaxForm(NULL, $edit, array(
          (string) $button[0]['name'] => (string) $button[0]['value'],
        ));
        break;
    }
    $this
      ->assertNoRaw($error_message, t('Validation error removed when file with correct extension uploaded (JSMode=%type).', array(
      '%type' => $type,
    )));
  }
}