You are here

public function FileFieldPathsGeneralTest::testFileUsage in File (Field) Paths 8

Test a file usage of a basic file upload with File (Field) Paths.

File

tests/src/Functional/FileFieldPathsGeneralTest.php, line 243

Class

FileFieldPathsGeneralTest
Test general functionality.

Namespace

Drupal\Tests\filefield_paths\Functional

Code

public function testFileUsage() {

  /** @var \Drupal\node\NodeStorage $node_storage */
  $node_storage = $this->container
    ->get('entity_type.manager')
    ->getStorage('node');

  /** @var \Drupal\file\FileUsage\FileUsageInterface $file_usage */
  $file_usage = $this->container
    ->get('file.usage');

  // Create a File field with 'node/[node:nid]' as the File path.
  $field_name = mb_strtolower($this
    ->randomMachineName());
  $third_party_settings['filefield_paths']['file_path']['value'] = 'node/[node:nid]';
  $this
    ->createFileField($field_name, 'node', $this->contentType, [], [], $third_party_settings);

  // Create a node with a test file.

  /** @var \Drupal\file\Entity\File $test_file */
  $test_file = $this
    ->getTestFile('text');
  $nid = $this
    ->uploadNodeFile($test_file, $field_name, $this->contentType);

  // Get file usage for uploaded file.
  $node_storage
    ->resetCache([
    $nid,
  ]);
  $node = $node_storage
    ->load($nid);
  $file = $node->{$field_name}->entity;
  $usage = $file_usage
    ->listUsage($file);

  // Ensure file usage count for new node is correct.
  $this
    ->assertNotEmpty($usage['file']['node'][$nid]);
  $this
    ->assertSame(1, (int) $usage['file']['node'][$nid], 'File usage count for new node is correct.');

  // Update node.
  $this
    ->drupalGet("node/{$nid}/edit");
  $this
    ->submitForm([
    'revision' => FALSE,
  ], 'Save');
  $usage = $file_usage
    ->listUsage($file);

  // Ensure file usage count for updated node is correct.
  $this
    ->assertNotEmpty($usage['file']['node'][$nid]);
  $this
    ->assertSame(1, (int) $usage['file']['node'][$nid], 'File usage count for updated node is correct.');

  // Update node with revision.
  $this
    ->drupalGet("node/{$nid}/edit");
  $this
    ->submitForm([
    'revision' => TRUE,
  ], 'Save');
  $usage = $file_usage
    ->listUsage($file);

  // Ensure file usage count for updated node with revision is correct.
  $this
    ->assertNotEmpty($usage['file']['node'][$nid]);
  $this
    ->assertSame(2, (int) $usage['file']['node'][$nid], 'File usage count for updated node with revision is correct.');
}