You are here

public function ReferenceSourceTest::testAutocompletion in FileField Sources 8

Test autocompletion.

File

tests/src/Functional/ReferenceSourceTest.php, line 43

Class

ReferenceSourceTest
Tests the reference source.

Namespace

Drupal\Tests\filefield_sources\Functional

Code

public function testAutocompletion() {

  // Create test file.
  $file = $this
    ->createPermanentFileEntity();
  $filename = $file
    ->getFileName();
  $first_character = substr($filename, 0, 1);
  $second_character = substr($filename, 1, 1);
  $default_options = [
    'query' => [
      '_format' => 'json',
    ],
  ];
  $options = $default_options;

  // Switch to 'Starts with' match type.
  $this
    ->updateFilefieldSourcesSettings('source_reference', 'autocomplete', '0');

  // STARTS_WITH: empty results.
  $query = $this
    ->findCharacterNotInString($first_character);
  $options['query']['q'] = $query;
  $autocomplete_result = Json::decode($this
    ->drupalGet('file/reference/node/' . $this->typeName . '/' . $this->fieldName, $options));
  $this
    ->assertEqual($autocomplete_result, [], "No files that have name starts with '{$query}'");

  // STARTS_WITH: not empty results.
  $query = $first_character;
  $options['query']['q'] = $query;
  $autocomplete_result = Json::decode($this
    ->drupalGet('file/reference/node/' . $this->typeName . '/' . $this->fieldName, $options + [
    'query' => [
      'q' => $query,
    ],
  ]));
  $this
    ->assertEqual($autocomplete_result[0]['label'], $filename, 'Autocompletion return correct label.');
  $this
    ->assertEqual($autocomplete_result[0]['value'], $filename . ' [fid:' . $file
    ->id() . ']', 'Autocompletion return correct value.');

  // Switch to 'Contains' match type.
  $this
    ->updateFilefieldSourcesSettings('source_reference', 'autocomplete', '1');

  // CONTAINS: empty results.
  $query = $this
    ->findCharacterNotInString($filename);
  $options['query']['q'] = $query;
  $autocomplete_result = Json::decode($this
    ->drupalGet('file/reference/node/' . $this->typeName . '/' . $this->fieldName, $options + [
    'query' => [
      'q' => $query,
    ],
  ]));
  $this
    ->assertEqual($autocomplete_result, [], "No files that have name contains '{$query}'");

  // CONTAINS: not empty results.
  $query = $second_character;
  $options['query']['q'] = $query;
  $autocomplete_result = Json::decode($this
    ->drupalGet('file/reference/node/' . $this->typeName . '/' . $this->fieldName, $options + [
    'query' => [
      'q' => $query,
    ],
  ]));
  $this
    ->assertEqual($autocomplete_result[0]['label'], $filename, 'Autocompletion return correct label.');
  $this
    ->assertEqual($autocomplete_result[0]['value'], $filename . ' [fid:' . $file
    ->id() . ']', 'Autocompletion return correct value.');
}