class ImageStyleTest

Same name in this branch
  1. 10 core/modules/jsonapi/tests/src/Functional/ImageStyleTest.php \Drupal\Tests\jsonapi\Functional\ImageStyleTest
Same name in other branches
  1. 9 core/modules/jsonapi/tests/src/Functional/ImageStyleTest.php \Drupal\Tests\jsonapi\Functional\ImageStyleTest
  2. 9 core/modules/image/tests/src/Unit/ImageStyleTest.php \Drupal\Tests\image\Unit\ImageStyleTest
  3. 8.9.x core/modules/jsonapi/tests/src/Functional/ImageStyleTest.php \Drupal\Tests\jsonapi\Functional\ImageStyleTest
  4. 8.9.x core/modules/image/tests/src/Unit/ImageStyleTest.php \Drupal\Tests\image\Unit\ImageStyleTest
  5. 11.x core/modules/jsonapi/tests/src/Functional/ImageStyleTest.php \Drupal\Tests\jsonapi\Functional\ImageStyleTest
  6. 11.x core/modules/image/tests/src/Unit/ImageStyleTest.php \Drupal\Tests\image\Unit\ImageStyleTest

@coversDefaultClass \Drupal\image\Entity\ImageStyle

@group Image

Hierarchy

Expanded class hierarchy of ImageStyleTest

File

core/modules/image/tests/src/Unit/ImageStyleTest.php, line 16

Namespace

Drupal\Tests\image\Unit
View source
class ImageStyleTest extends UnitTestCase {
    
    /**
     * The entity type used for testing.
     *
     * @var \Drupal\Core\Entity\EntityTypeInterface|\PHPUnit\Framework\MockObject\MockObject
     */
    protected $entityType;
    
    /**
     * The entity type manager used for testing.
     *
     * @var \Drupal\Core\Entity\EntityTypeManagerInterface|\PHPUnit\Framework\MockObject\MockObject
     */
    protected $entityTypeManager;
    
    /**
     * The ID of the type of the entity under test.
     *
     * @var string
     */
    protected $entityTypeId;
    
    /**
     * Gets a mocked image style for testing.
     *
     * @param string $image_effect_id
     *   The image effect ID.
     * @param \Drupal\image\ImageEffectInterface|\PHPUnit\Framework\MockObject\MockObject $image_effect
     *   The image effect used for testing.
     * @param array $stubs
     *   An array of additional method names to mock.
     *
     * @return \Drupal\image\ImageStyleInterface
     *   The mocked image style.
     */
    protected function getImageStyleMock($image_effect_id, $image_effect, $stubs = []) {
        $effectManager = $this->getMockBuilder('\\Drupal\\image\\ImageEffectManager')
            ->disableOriginalConstructor()
            ->getMock();
        $effectManager->expects($this->any())
            ->method('createInstance')
            ->with($image_effect_id)
            ->willReturn($image_effect);
        $default_stubs = [
            'getImageEffectPluginManager',
            'fileDefaultScheme',
        ];
        $image_style = $this->getMockBuilder('\\Drupal\\image\\Entity\\ImageStyle')
            ->setConstructorArgs([
            [
                'effects' => [
                    $image_effect_id => [
                        'id' => $image_effect_id,
                    ],
                ],
            ],
            $this->entityTypeId,
        ])
            ->onlyMethods(array_merge($default_stubs, $stubs))
            ->getMock();
        $image_style->expects($this->any())
            ->method('getImageEffectPluginManager')
            ->willReturn($effectManager);
        $image_style->expects($this->any())
            ->method('fileDefaultScheme')
            ->willReturnCallback([
            $this,
            'fileDefaultScheme',
        ]);
        return $image_style;
    }
    
    /**
     * {@inheritdoc}
     */
    protected function setUp() : void {
        parent::setUp();
        $this->entityTypeId = $this->randomMachineName();
        $provider = $this->randomMachineName();
        $this->entityType = $this->createMock('\\Drupal\\Core\\Entity\\EntityTypeInterface');
        $this->entityType
            ->expects($this->any())
            ->method('getProvider')
            ->willReturn($provider);
        $this->entityTypeManager = $this->createMock('\\Drupal\\Core\\Entity\\EntityTypeManagerInterface');
        $this->entityTypeManager
            ->expects($this->any())
            ->method('getDefinition')
            ->with($this->entityTypeId)
            ->willReturn($this->entityType);
    }
    
    /**
     * @covers ::getDerivativeExtension
     */
    public function testGetDerivativeExtension() : void {
        $image_effect_id = $this->randomMachineName();
        $logger = $this->getMockBuilder('\\Psr\\Log\\LoggerInterface')
            ->getMock();
        $image_effect = $this->getMockBuilder('\\Drupal\\image\\ImageEffectBase')
            ->setConstructorArgs([
            [],
            $image_effect_id,
            [],
            $logger,
        ])
            ->getMock();
        $image_effect->expects($this->any())
            ->method('getDerivativeExtension')
            ->willReturn('png');
        $image_style = $this->getImageStyleMock($image_effect_id, $image_effect);
        $extensions = [
            'jpeg',
            'gif',
            'png',
        ];
        foreach ($extensions as $extension) {
            $extensionReturned = $image_style->getDerivativeExtension($extension);
            $this->assertEquals('png', $extensionReturned);
        }
    }
    
    /**
     * @covers ::buildUri
     */
    public function testBuildUri() : void {
        // Image style that changes the extension.
        $image_effect_id = $this->randomMachineName();
        $logger = $this->getMockBuilder('\\Psr\\Log\\LoggerInterface')
            ->getMock();
        $image_effect = $this->getMockBuilder('\\Drupal\\image\\ImageEffectBase')
            ->setConstructorArgs([
            [],
            $image_effect_id,
            [],
            $logger,
        ])
            ->getMock();
        $image_effect->expects($this->any())
            ->method('getDerivativeExtension')
            ->willReturn('png');
        $image_style = $this->getImageStyleMock($image_effect_id, $image_effect);
        $this->assertEquals($image_style->buildUri('public://test.jpeg'), 'public://styles/' . $image_style->id() . '/public/test.jpeg.png');
        // Image style that doesn't change the extension.
        $image_effect_id = $this->randomMachineName();
        $image_effect = $this->getMockBuilder('\\Drupal\\image\\ImageEffectBase')
            ->setConstructorArgs([
            [],
            $image_effect_id,
            [],
            $logger,
        ])
            ->getMock();
        $image_effect->expects($this->any())
            ->method('getDerivativeExtension')
            ->willReturnArgument(0);
        $image_style = $this->getImageStyleMock($image_effect_id, $image_effect);
        $this->assertEquals($image_style->buildUri('public://test.jpeg'), 'public://styles/' . $image_style->id() . '/public/test.jpeg');
    }
    
    /**
     * @covers ::getPathToken
     */
    public function testGetPathToken() : void {
        $logger = $this->getMockBuilder('\\Psr\\Log\\LoggerInterface')
            ->getMock();
        $private_key = $this->randomMachineName();
        $hash_salt = $this->randomMachineName();
        // Image style that changes the extension.
        $image_effect_id = $this->randomMachineName();
        $image_effect = $this->getMockBuilder('\\Drupal\\image\\ImageEffectBase')
            ->setConstructorArgs([
            [],
            $image_effect_id,
            [],
            $logger,
        ])
            ->getMock();
        $image_effect->expects($this->any())
            ->method('getDerivativeExtension')
            ->willReturn('png');
        $image_style = $this->getImageStyleMock($image_effect_id, $image_effect, [
            'getPrivateKey',
            'getHashSalt',
        ]);
        $image_style->expects($this->any())
            ->method('getPrivateKey')
            ->willReturn($private_key);
        $image_style->expects($this->any())
            ->method('getHashSalt')
            ->willReturn($hash_salt);
        // Assert the extension has been added to the URI before creating the token.
        $this->assertEquals($image_style->getPathToken('public://test.jpeg.png'), $image_style->getPathToken('public://test.jpeg'));
        $this->assertEquals(substr(Crypt::hmacBase64($image_style->id() . ':' . 'public://test.jpeg.png', $private_key . $hash_salt), 0, 8), $image_style->getPathToken('public://test.jpeg'));
        $this->assertNotEquals(substr(Crypt::hmacBase64($image_style->id() . ':' . 'public://test.jpeg', $private_key . $hash_salt), 0, 8), $image_style->getPathToken('public://test.jpeg'));
        // Image style that doesn't change the extension.
        $image_effect_id = $this->randomMachineName();
        $image_effect = $this->getMockBuilder('\\Drupal\\image\\ImageEffectBase')
            ->setConstructorArgs([
            [],
            $image_effect_id,
            [],
            $logger,
        ])
            ->getMock();
        $image_effect->expects($this->any())
            ->method('getDerivativeExtension')
            ->willReturnArgument(0);
        $image_style = $this->getImageStyleMock($image_effect_id, $image_effect, [
            'getPrivateKey',
            'getHashSalt',
        ]);
        $image_style->expects($this->any())
            ->method('getPrivateKey')
            ->willReturn($private_key);
        $image_style->expects($this->any())
            ->method('getHashSalt')
            ->willReturn($hash_salt);
        // Assert no extension has been added to the uri before creating the token.
        $this->assertNotEquals($image_style->getPathToken('public://test.jpeg.png'), $image_style->getPathToken('public://test.jpeg'));
        $this->assertNotEquals(substr(Crypt::hmacBase64($image_style->id() . ':' . 'public://test.jpeg.png', $private_key . $hash_salt), 0, 8), $image_style->getPathToken('public://test.jpeg'));
        $this->assertEquals(substr(Crypt::hmacBase64($image_style->id() . ':' . 'public://test.jpeg', $private_key . $hash_salt), 0, 8), $image_style->getPathToken('public://test.jpeg'));
    }
    
    /**
     * @covers ::flush
     */
    public function testFlush() : void {
        $cache_tag_invalidator = $this->createMock('\\Drupal\\Core\\Cache\\CacheTagsInvalidator');
        $file_system = $this->createMock('\\Drupal\\Core\\File\\FileSystemInterface');
        $module_handler = $this->createMock('\\Drupal\\Core\\Extension\\ModuleHandlerInterface');
        $stream_wrapper_manager = $this->createMock('\\Drupal\\Core\\StreamWrapper\\StreamWrapperManagerInterface');
        $stream_wrapper_manager->expects($this->any())
            ->method('getWrappers')
            ->will($this->returnValue([]));
        $theme_registry = $this->createMock('\\Drupal\\Core\\Theme\\Registry');
        $container = new ContainerBuilder();
        $container->set('cache_tags.invalidator', $cache_tag_invalidator);
        $container->set('file_system', $file_system);
        $container->set('module_handler', $module_handler);
        $container->set('stream_wrapper_manager', $stream_wrapper_manager);
        $container->set('theme.registry', $theme_registry);
        \Drupal::setContainer($container);
        $image_effect_id = $this->randomMachineName();
        $image_effect = $this->getMockBuilder('\\Drupal\\image\\ImageEffectBase');
        $image_style = $this->getImageStyleMock($image_effect_id, $image_effect, [
            'buildUri',
            'getCacheTagsToInvalidate',
        ]);
        $image_style->expects($this->any())
            ->method('buildUri')
            ->willReturn('test.jpg');
        $image_style->expects($this->any())
            ->method('getCacheTagsToInvalidate')
            ->willReturn([]);
        // Assert the theme registry is reset.
        $theme_registry->expects($this->once())
            ->method('reset');
        // Assert the cache tags are invalidated.
        $cache_tag_invalidator->expects($this->once())
            ->method('invalidateTags');
        $image_style->flush();
        // Assert the theme registry is not reset a path is flushed.
        $theme_registry->expects($this->never())
            ->method('reset');
        // Assert the cache tags are not reset a path is flushed.
        $cache_tag_invalidator->expects($this->never())
            ->method('invalidateTags');
        $image_style->flush('test.jpg');
    }
    
    /**
     * Mock function for ImageStyle::fileDefaultScheme().
     */
    public function fileDefaultScheme() {
        return 'public';
    }

}

Members

Title Sort descending Deprecated Modifiers Object type Summary Overriden Title Overrides
ImageStyleTest::$entityType protected property The entity type used for testing.
ImageStyleTest::$entityTypeId protected property The ID of the type of the entity under test.
ImageStyleTest::$entityTypeManager protected property The entity type manager used for testing.
ImageStyleTest::fileDefaultScheme public function Mock function for ImageStyle::fileDefaultScheme().
ImageStyleTest::getImageStyleMock protected function Gets a mocked image style for testing.
ImageStyleTest::setUp protected function Overrides UnitTestCase::setUp
ImageStyleTest::testBuildUri public function @covers ::buildUri
ImageStyleTest::testFlush public function @covers ::flush
ImageStyleTest::testGetDerivativeExtension public function @covers ::getDerivativeExtension
ImageStyleTest::testGetPathToken public function @covers ::getPathToken
PhpUnitWarnings::$deprecationWarnings private static property Deprecation warnings from PHPUnit to raise with @trigger_error().
PhpUnitWarnings::addWarning public function Converts PHPUnit deprecation warnings to E_USER_DEPRECATED.
RandomGeneratorTrait::getRandomGenerator protected function Gets the random generator for the utility methods.
RandomGeneratorTrait::randomMachineName protected function Generates a unique random string containing letters and numbers.
RandomGeneratorTrait::randomObject public function Generates a random PHP object.
RandomGeneratorTrait::randomString public function Generates a pseudo-random string of ASCII characters of codes 32 to 126.
RandomGeneratorTrait::randomStringValidate Deprecated public function Callback for random string validation.
UnitTestCase::$root protected property The app root. 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::getStringTranslationStub public function Returns a stub translation manager that just returns the passed string.
UnitTestCase::setUpBeforeClass public static function
UnitTestCase::__get public function

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.