ThunderImageCompareTestTrait.php in Thunder 8.2
File
tests/src/FunctionalJavascript/ThunderImageCompareTestTrait.php
View source
<?php
namespace Drupal\Tests\thunder\FunctionalJavascript;
use Drupal\Component\FileSystem\FileSystem;
use Imagick;
trait ThunderImageCompareTestTrait {
protected $generateMode = FALSE;
protected $fileSystem;
protected $screenShotPrefix = 'test_ss_';
public function setGenerateMode($generateMode) {
$this->generateMode = $generateMode;
}
protected function getFileSystem() {
if (!isset($this->fileSystem)) {
$this->fileSystem = \Drupal::service('file_system');
}
return $this->fileSystem;
}
protected function setWindowSize(array $windowSize) {
$this
->getSession()
->getDriver()
->resizeWindow($windowSize['width'], $windowSize['height']);
$this
->assertSession()
->assertWaitOnAjaxRequest();
}
public function compareScreenToImage($expectedImageFile, array $imageSize = [], array $windowSize = [], $threshold = 0.01) {
$tempScreenShotFile = $this
->getFileSystem()
->tempnam(FileSystem::getOsTemporaryDirectory(), $this->screenShotPrefix);
if (!$tempScreenShotFile) {
throw new \Exception('Unable to get temporally file name.');
}
$adjustWindowForScreenshot = !empty($windowSize);
if ($adjustWindowForScreenshot) {
$this
->setWindowSize($windowSize);
}
$this
->createScreenshot($tempScreenShotFile);
$tempScreenShotFile = realpath($tempScreenShotFile);
if ($adjustWindowForScreenshot) {
$this
->setWindowSize($this
->getWindowSize());
}
if (!empty($imageSize)) {
$image = new Imagick($tempScreenShotFile);
$image
->cropImage($imageSize['width'], $imageSize['height'], $imageSize['x'], $imageSize['y']);
file_put_contents($tempScreenShotFile, $image);
}
return $this
->compareImages($expectedImageFile, $tempScreenShotFile, $threshold);
}
public function compareImages($expectedImageFile, $actualImageFile, $threshold = 0.01) {
if ($this->generateMode) {
$newFileName = file_unmanaged_move($actualImageFile, $expectedImageFile, FILE_EXISTS_REPLACE);
if (!$newFileName) {
throw new \Exception(sprintf('Unable to create file in %s.', $expectedImageFile));
}
return TRUE;
}
$expectedImage = new Imagick(realpath($expectedImageFile));
$actualImage = new Imagick(realpath($actualImageFile));
$result = $actualImage
->compareImages($expectedImage, Imagick::METRIC_MEANSQUAREERROR);
$differentImages = $result[1] < $threshold;
if (!$differentImages) {
$this
->storeDiffImage($expectedImageFile, $result);
}
return $differentImages;
}
protected function storeDiffImage($expectedImageFile, array $compareResult) {
$fileName = $this
->getScreenshotFolder() . '/' . basename($expectedImageFile) . '_' . date('Ymd_His') . '.png';
file_put_contents($fileName, $compareResult[0]);
}
public function getScreenshotFile($screenshotName) {
return dirname(__FILE__) . sprintf('/../../fixtures/screenshots/%s.png', $screenshotName);
}
}