You are here

class AssetFileEntityHelperTest in Media: Acquia DAM 8

Tests to validate that our file entity helper works as expected.

@group media_acquiadam

Hierarchy

Expanded class hierarchy of AssetFileEntityHelperTest

File

tests/src/Unit/AssetFileEntityHelperTest.php, line 30

Namespace

Drupal\Tests\media_acquiadam\Unit
View source
class AssetFileEntityHelperTest extends UnitTestCase {
  use AcquiadamAssetDataTrait, AcquiadamConfigTrait, AcquiadamAssetImageHelperTrait, AcquiadamMockedMediaEntityTrait, AcquiadamLoggerFactoryTrait;

  /**
   * Container builder helper.
   *
   * @var \Drupal\Core\DependencyInjection\ContainerBuilder
   */
  protected $container;

  /**
   * A mocked AssetFileEntityHelper.
   *
   * @var \Drupal\media_acquiadam\Service\AssetFileEntityHelper|\PHPUnit\Framework\MockObject\MockObject
   */
  protected $assetFileEntityHelper;

  /**
   * A mocked file entity.
   *
   * @var \Drupal\file\FileInterface|\PHPUnit\Framework\MockObject\MockObject
   */
  protected $mockedFileEntity;

  /**
   * Validates that the file destination builds correctly.
   */
  public function testGetDestinationFromEntity() {
    $media = $this
      ->getMockedMediaEntity($this
      ->getAssetData()->id);
    $this
      ->assertEquals('private://assets/replaced', $this->assetFileEntityHelper
      ->getDestinationFromEntity($media, 'phpunit_file_field'));
    $this
      ->assertEquals('public://acquiadam_assets', $this->assetFileEntityHelper
      ->getDestinationFromEntity($media, 'phpunit_test_fail'));
  }

  /**
   * Validates we can create a new file.
   */
  public function testCreateNewFile() {
    $asset = $this
      ->getAssetData();
    $this
      ->assertInstanceOf(FileInterface::class, $this->assetFileEntityHelper
      ->createNewFile($asset, 'private://assets/replaced'));
    $this
      ->assertFalse($this->assetFileEntityHelper
      ->createNewFile($asset, 'random://bad/folder'));
  }

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $this->mockedFileEntity = $this
      ->getMockBuilder(FileInterface::class)
      ->disableOriginalConstructor()
      ->getMockForAbstractClass();
    $this->mockedFileEntity
      ->method('id')
      ->willReturn(333);
    $acquiadam = $this
      ->getMockBuilder(Acquiadam::class)
      ->disableOriginalConstructor()
      ->getMock();
    $asset_media_factory = $this
      ->getMockBuilder(AssetMediaFactory::class)
      ->disableOriginalConstructor()
      ->getMock();
    $asset_media_factory
      ->method('getFileEntity')
      ->willReturn($this->mockedFileEntity
      ->id());
    $this->container = new ContainerBuilder();
    $this
      ->setMockedDrupalServices($this->container);
    $this->container
      ->set('media_acquiadam.asset_image.helper', $this
      ->getAssetImageHelperStub());
    $this->container
      ->set('media_acquiadam.acquiadam', $acquiadam);
    $this->container
      ->set('media_acquiadam.asset_media.factory', $asset_media_factory);
    $this->container
      ->set('logger.factory', $this
      ->getLoggerFactoryStub());
    \Drupal::setContainer($this->container);
    $this->assetFileEntityHelper = $this
      ->getMockedAssetFileEntityHelper();
  }

  /**
   * Sets Drupal mocked services into a container.
   *
   * @param \Drupal\Core\DependencyInjection\ContainerBuilder $container
   *   The container to set mocks into.
   */
  protected function setMockedDrupalServices(ContainerBuilder $container) {
    $file_storage = $this
      ->getMockBuilder(EntityStorageInterface::class)
      ->disableOriginalConstructor()
      ->getMock();
    $file_storage
      ->method('load')
      ->with($this->mockedFileEntity
      ->id())
      ->willReturn($this->mockedFileEntity);
    $file_storage
      ->method('loadByProperties')
      ->willReturnMap([
      [
        [
          'uri' => 'private://assets/replaced/' . $this
            ->getAssetData()->filename,
        ],
        [
          $this->mockedFileEntity,
        ],
      ],
      [
        [
          'uri' => 'private://assets/replaced/Micro turbine 60.jpg',
        ],
        [
          $this->mockedFileEntity,
        ],
      ],
    ]);
    $entity_type_manager = $this
      ->getMockBuilder(EntityTypeManagerInterface::class)
      ->disableOriginalConstructor()
      ->getMock();
    $entity_type_manager
      ->method('getStorage')
      ->willReturnMap([
      [
        'file',
        $file_storage,
      ],
    ]);
    $data_definition = $this
      ->getMockBuilder(DataDefinitionInterface::class)
      ->disableOriginalConstructor()
      ->getMock();
    $data_definition
      ->method('getSetting')
      ->willReturnMap([
      [
        'uri_scheme',
        'private',
      ],
      [
        'file_directory',
        'assets/[token]',
      ],
    ]);
    $field_definition = $this
      ->getMockBuilder(FieldDefinitionInterface::class)
      ->disableOriginalConstructor()
      ->getMock();
    $field_definition
      ->method('getItemDefinition')
      ->willReturn($data_definition);
    $entity_field_manager = $this
      ->getMockBuilder(EntityFieldManagerInterface::class)
      ->disableOriginalConstructor()
      ->getMock();
    $entity_field_manager
      ->method('getFieldDefinitions')
      ->willReturnMap([
      [
        'media',
        'acquiadam',
        [
          'phpunit_file_field' => $field_definition,
        ],
      ],
    ]);
    $token = $this
      ->getMockBuilder(Token::class)
      ->disableOriginalConstructor()
      ->getMock();
    $token
      ->method('replace')
      ->willReturnCallback(function ($string, $a, $b, $c) {
      return 'assets/[token]' == $string ? 'assets/replaced' : $string;
    });
    $file_system = $this
      ->getMockBuilder(FileSystem::class)
      ->disableOriginalConstructor()
      ->setMethods([
      'prepareDirectory',
    ])
      ->getMockForAbstractClass();
    $file_system
      ->method('prepareDirectory')
      ->willReturnMap([
      [
        'private://assets/replaced',
        FileSystemInterface::CREATE_DIRECTORY,
        TRUE,
      ],
    ]);
    $container
      ->set('entity_type.manager', $entity_type_manager);
    $container
      ->set('entity_field.manager', $entity_field_manager);
    $container
      ->set('config.factory', $this
      ->getConfigFactoryStub());
    $container
      ->set('file_system', $file_system);
    $container
      ->set('token', $token);
  }

  /**
   * Get a mocked AssetFileEntityHelper that stubs file operations.
   *
   * @return \Drupal\media_acquiadam\Service\AssetFileEntityHelper|\PHPUnit\Framework\MockObject\MockObject
   *   The mocked AssetFileEntityHelper class.
   */
  protected function getMockedAssetFileEntityHelper() {
    $helper = $this
      ->getMockBuilder(AssetFileEntityHelper::class)
      ->setConstructorArgs([
      $this->container
        ->get('entity_type.manager'),
      $this->container
        ->get('entity_field.manager'),
      $this->container
        ->get('config.factory'),
      $this->container
        ->get('file_system'),
      $this->container
        ->get('token'),
      $this->container
        ->get('media_acquiadam.asset_image.helper'),
      $this->container
        ->get('media_acquiadam.acquiadam'),
      $this->container
        ->get('media_acquiadam.asset_media.factory'),
      $this->container
        ->get('logger.factory'),
    ])
      ->setMethods([
      'phpFileGetContents',
      'drupalFileSaveData',
    ])
      ->getMock();
    $helper
      ->method('phpFileGetContents')
      ->willReturn('File contents');
    $helper
      ->method('drupalFileSaveData')
      ->willReturn($this->mockedFileEntity);
    return $helper;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AcquiadamAssetDataTrait::generateNewVersion protected function Create a new version of a given asset.
AcquiadamAssetDataTrait::getAssetData protected function Returns an Asset object for testing against.
AssetFileEntityHelperTest::$assetFileEntityHelper protected property A mocked AssetFileEntityHelper.
AssetFileEntityHelperTest::$container protected property Container builder helper.
AssetFileEntityHelperTest::$mockedFileEntity protected property A mocked file entity.
AssetFileEntityHelperTest::getMockedAssetFileEntityHelper protected function Get a mocked AssetFileEntityHelper that stubs file operations.
AssetFileEntityHelperTest::setMockedDrupalServices protected function Sets Drupal mocked services into a container.
AssetFileEntityHelperTest::setUp protected function Overrides UnitTestCase::setUp
AssetFileEntityHelperTest::testCreateNewFile public function Validates we can create a new file.
AssetFileEntityHelperTest::testGetDestinationFromEntity public function Validates that the file destination builds correctly.
PhpunitCompatibilityTrait::getMock Deprecated public function Returns a mock object for the specified class using the available method.
PhpunitCompatibilityTrait::setExpectedException Deprecated public function Compatibility layer for PHPUnit 6 to support PHPUnit 4 code.
UnitTestCase::$randomGenerator protected property The random generator.
UnitTestCase::$root protected property The app root. 1
UnitTestCase::assertArrayEquals protected function Asserts if two arrays are equal by sorting them first.
UnitTestCase::getBlockMockWithMachineName Deprecated protected function Mocks a block with a block plugin. 1
UnitTestCase::getClassResolverStub protected function Returns a stub class resolver.
UnitTestCase::getConfigFactoryStub public function Returns a stub config factory that behaves according to the passed array.
UnitTestCase::getConfigStorageStub public function Returns a stub config storage that returns the supplied configuration.
UnitTestCase::getContainerWithCacheTagsInvalidator protected function Sets up a container with a cache tags invalidator.
UnitTestCase::getRandomGenerator protected function Gets the random generator for the utility methods.
UnitTestCase::getStringTranslationStub public function Returns a stub translation manager that just returns the passed string.
UnitTestCase::randomMachineName public function Generates a unique random string containing letters and numbers.