-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathVisualCeption.php
More file actions
executable file
·440 lines (374 loc) · 16.6 KB
/
Copy pathVisualCeption.php
File metadata and controls
executable file
·440 lines (374 loc) · 16.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
<?php
namespace Codeception\Module;
use Codeception\Module\ImageDeviationException;
/**
* Class VisualCeption
*
* @copyright Copyright (c) 2014 G+J Digital Products GmbH
* @license MIT license, http://www.opensource.org/licenses/mit-license.php
* @package Codeception\Module
*
* @author Nils Langner <langner.nils@guj.de>
* @author Torsten Franz
* @author Sebastian Neubert
*/
class VisualCeption extends \Codeception\Module
{
private $referenceImageDir;
/**
* This var represents the directory where the taken images are stored
* @var string
*/
private $currentImageDir;
private $maximumDeviation = 0;
private $webDriver = null;
private $webDriverModule = null;
/**
* Create an object from VisualCeption Class
*
* @param array $config
* @return result
*/
public function __construct($config)
{
$result = parent::__construct($config);
$this->init();
return $result;
}
/**
* Event hook before a test starts
*
* @param \Codeception\TestCase $test
* @throws \Exception
*/
public function _before(\Codeception\TestCase $test)
{
if (!$this->hasModule("WebDriver")) {
throw new \Exception("VisualCeption uses the WebDriver. Please be sure that this module is activated.");
}
$this->webDriverModule = $this->getModule("WebDriver");
$this->webDriver = $this->webDriverModule->webDriver;
$jQueryString = file_get_contents(__DIR__ . "/jquery.js");
$this->webDriver->executeScript($jQueryString);
$this->webDriver->executeScript('jQuery.noConflict();');
$this->test = $test;
}
public function getReferenceImageDir()
{
return $this->referenceImageDir;
}
/**
* Compare the reference image with a current screenshot, identified by their indentifier name
* and their element ID.
*
* @param string $identifier Identifies your test object
* @param string $elementID DOM ID of the element, which should be screenshotted
* @param string|array $excludeElements Element name or array of Element names, which should not appear in the screenshot
*/
public function seeVisualChanges($identifier, $elementID = null, $excludeElements = array())
{
$excludeElements = (array)$excludeElements;
$deviationResult = $this->getDeviation($identifier, $elementID, $excludeElements);
if (!is_null($deviationResult["deviationImage"])) {
// used for assertion counter in codeception / phpunit
$this->assertTrue(true);
if ($deviationResult["deviation"] <= $this->maximumDeviation) {
$compareScreenshotPath = $this->getDeviationScreenshotPath($identifier);
$deviationResult["deviationImage"]->writeImage($compareScreenshotPath);
throw new ImageDeviationException("The deviation of the taken screenshot is too low (" . $deviationResult["deviation"] . "%).\nSee $compareScreenshotPath for a deviation screenshot.",
$this->getExpectedScreenshotPath($identifier),
$this->getScreenshotPath($identifier),
$compareScreenshotPath);
}
}
}
/**
* Compare the reference image with a current screenshot, identified by their indentifier name
* and their element ID.
*
* @param string $identifier identifies your test object
* @param string $elementID DOM ID of the element, which should be screenshotted
* @param string|array $excludeElements string of Element name or array of Element names, which should not appear in the screenshot
*/
public function dontSeeVisualChanges($identifier, $elementID = null, $excludeElements = array())
{
$excludeElements = (array)$excludeElements;
$deviationResult = $this->getDeviation($identifier, $elementID, $excludeElements);
if (!is_null($deviationResult["deviationImage"])) {
// used for assertion counter in codeception / phpunit
$this->assertTrue(true);
if ($deviationResult["deviation"] > $this->maximumDeviation) {
$compareScreenshotPath = $this->getDeviationScreenshotPath($identifier);
$deviationResult["deviationImage"]->writeImage($compareScreenshotPath);
throw new ImageDeviationException("The deviation of the taken screenshot is too hight (" . $deviationResult["deviation"] . "%).\nSee $compareScreenshotPath for a deviation screenshot.",
$this->getExpectedScreenshotPath($identifier),
$this->getScreenshotPath($identifier),
$compareScreenshotPath);
}
}
}
/**
* Hide an element to set the visibility to hidden
*
* @param $elementSelector String of jQuery Element selector, set visibility to hidden
*/
private function hideElement($elementSelector)
{
$this->webDriver->executeScript(
if( jQuery("' . $elementSelector . '").length > 0 ) {
jQuery( "' . $elementSelector . '" ).css("visibility","hidden");
}
');
$this->debug("set visibility of element '$elementSelector' to 'hidden'");
}
/**
* Show an element to set the visibility to visible
*
* @param $elementSelector String of jQuery Element selector, set visibility to visible
*/
private function showElement($elementSelector)
{
$this->webDriver->executeScript(
if( jQuery("' . $elementSelector . '").length > 0 ) {
jQuery( "' . $elementSelector . '" ).css("visibility","visible");
}
');
$this->debug("set visibility of element '$elementSelector' to 'visible'");
}
/**
* Compares the two images and calculate the deviation between expected and actual image
*
* @param string $identifier Identifies your test object
* @param string $elementID DOM ID of the element, which should be screenshotted
* @param array $excludeElements Element names, which should not appear in the screenshot
* @return array Includes the calculation of deviation in percent and the diff-image
*/
private function getDeviation($identifier, $elementID, array $excludeElements = array())
{
$coords = $this->getCoordinates($elementID);
$this->createScreenshot($identifier, $coords, $excludeElements);
$compareResult = $this->compare($identifier);
$deviation = round($compareResult[1] * 100, 2);
$this->debug("The deviation between the images is ". $deviation . " percent");
return array (
"deviation" => $deviation,
"deviationImage" => $compareResult[0],
"currentImage" => $compareResult['currentImage'],
);
}
/**
* Initialize the module and read the config.
* Throws a runtime exception, if the
* reference image dir is not set in the config
*
* @throws \RuntimeException
*/
private function init()
{
if (array_key_exists('maximumDeviation', $this->config)) {
$this->maximumDeviation = $this->config["maximumDeviation"];
}
if (array_key_exists('saveCurrentImageIfFailure', $this->config)) {
$this->saveCurrentImageIfFailure = (boolean) $this->config["saveCurrentImageIfFailure"];
}
if (array_key_exists('referenceImageDir', $this->config)) {
$this->referenceImageDir = $this->config["referenceImageDir"];
} else {
$this->referenceImageDir = \Codeception\Configuration::dataDir() . 'VisualCeption/';
}
if (!is_dir($this->referenceImageDir)) {
$this->debug("Creating directory: $this->referenceImageDir");
mkdir($this->referenceImageDir, 0777, true);
}
if (array_key_exists('currentImageDir', $this->config)) {
$this->currentImageDir = $this->config["currentImageDir"];
}else{
$this->currentImageDir = \Codeception\Configuration::logDir() . 'debug/tmp/';
}
}
/**
* Find the position and proportion of a DOM element, specified by it's ID.
* The method inject the
* JQuery Framework and uses the "noConflict"-mode to get the width, height and offset params.
*
* @param string $elementId DOM ID of the element, which should be screenshotted
* @return array coordinates of the element
*/
private function getCoordinates($elementId)
{
if (is_null($elementId)) {
$elementId = 'body';
}
$jQueryString = file_get_contents(__DIR__ . "/jquery.js");
$this->webDriver->executeScript($jQueryString);
$this->webDriver->executeScript('jQuery.noConflict();');
$imageCoords = array();
$elementExists = (bool)$this->webDriver->executeScript('return jQuery( "' . $elementId . '" ).length > 0;');
if (!$elementExists) {
throw new \Exception("The element you want to examine ('" . $elementId . "') was not found.");
}
$imageCoords['offset_x'] = (string)$this->webDriver->executeScript('return jQuery( "' . $elementId . '" ).offset().left;');
$imageCoords['offset_y'] = (string)$this->webDriver->executeScript('return jQuery( "' . $elementId . '" ).offset().top;');
$imageCoords['width'] = (string)$this->webDriver->executeScript('return jQuery( "' . $elementId . '" ).width();');
$imageCoords['height'] = (string)$this->webDriver->executeScript('return jQuery( "' . $elementId . '" ).height();');
return $imageCoords;
}
/**
* Generates a screenshot image filename
* it uses the testcase name and the given indentifier to generate a png image name
*
* @param string $identifier identifies your test object
* @return string Name of the image file
*/
private function getScreenshotName($identifier)
{
$caseName = str_replace('Cept.php', '', $this->test->getFileName());
$search = array('/', '\\', ':');
$replace = array('.', '.', '');
$caseName = str_replace($search, $replace, $caseName);
return $caseName . '.' . $identifier . '.png';
}
/**
* Returns the temporary path including the filename where a the screenshot should be saved
* If the path doesn't exist, the method generate it itself
*
* @param string $identifier identifies your test object
* @return string Path an name of the image file
* @throws \RuntimeException if debug dir could not create
*/
private function getScreenshotPath($identifier)
{
$debugDir = $this->currentImageDir;
if (!is_dir($debugDir)) {
$created = mkdir($debugDir, 0777, true);
if ($created) {
$this->debug("Creating directory: $debugDir");
} else {
throw new \RuntimeException("Unable to create temporary screenshot dir ($debugDir)");
}
}
return $debugDir . $this->getScreenshotName($identifier);
}
/**
* Returns the reference image path including the filename
*
* @param string $identifier identifies your test object
* @return string Name of the reference image file
*/
private function getExpectedScreenshotPath($identifier)
{
return $this->referenceImageDir . $this->getScreenshotName($identifier);
}
/**
* Generate the screenshot of the dom element
*
* @param string $identifier identifies your test object
* @param array $coords Coordinates where the DOM element is located
* @param array $excludeElements List of elements, which should not appear in the screenshot
* @return string Path of the current screenshot image
*/
private function createScreenshot($identifier, array $coords, array $excludeElements = array())
{
$screenShotDir = \Codeception\Configuration::logDir() . 'debug/';
if( !is_dir($screenShotDir)) {
mkdir($screenShotDir, 0777, true);
}
$screenshotPath = $screenShotDir . getmypid() .'.fullscreenshot.tmp.png';
$elementPath = $this->getScreenshotPath($identifier);
$this->hideElementsForScreenshot($excludeElements);
$this->webDriver->takeScreenshot($screenshotPath);
$this->resetHideElementsForScreenshot($excludeElements);
$screenShotImage = new \Imagick();
$screenShotImage->readImage($screenshotPath);
$screenShotImage->cropImage($coords['width'], $coords['height'], $coords['offset_x'], $coords['offset_y']);
$screenShotImage->writeImage($elementPath);
unlink($screenshotPath);
return $elementPath;
}
/**
* Hide the given elements with CSS visibility = hidden. Wait a second after hiding
*
* @param array $excludeElements Array of strings, which should be not visible
*/
private function hideElementsForScreenshot(array $excludeElements)
{
foreach ($excludeElements as $element) {
$this->hideElement($element);
}
$this->webDriverModule->wait(1);
}
/**
* Reset hiding the given elements with CSS visibility = visible. Wait a second after reset hiding
*
* @param array $excludeElements array of strings, which should be visible again
*/
private function resetHideElementsForScreenshot(array $excludeElements)
{
foreach ($excludeElements as $element) {
$this->showElement($element);
}
$this->webDriverModule->wait(1);
}
/**
* Returns the image path including the filename of a deviation image
*
* @param $identifier identifies your test object
* @return string Path of the deviation image
*/
private function getDeviationScreenshotPath ($identifier, $alternativePrefix = '')
{
$debugDir = \Codeception\Configuration::logDir() . 'debug/';
$prefix = ( $alternativePrefix === '') ? 'compare' : $alternativePrefix;
return $debugDir . $prefix . $this->getScreenshotName($identifier);
}
/**
* Compare two images by its identifiers.
* If the reference image doesn't exists
* the image is copied to the reference path.
*
* @param $identifier identifies your test object
* @return array Test result of image comparison
*/
private function compare($identifier)
{
$expectedImagePath = $this->getExpectedScreenshotPath($identifier);
$currentImagePath = $this->getScreenshotPath($identifier);
if (!file_exists($expectedImagePath)) {
$this->debug("Copying image (from $currentImagePath to $expectedImagePath");
copy($currentImagePath, $expectedImagePath);
return array (null, 0, 'currentImage' => null);
} else {
return $this->compareImages($expectedImagePath, $currentImagePath);
}
}
/**
* Compares to images by given file path
*
* @param $image1 Path to the exprected reference image
* @param $image2 Path to the current image in the screenshot
* @return array Result of the comparison
*/
private function compareImages($image1, $image2)
{
$this->debug("Trying to compare $image1 with $image2");
$imagick1 = new \Imagick($image1);
$imagick2 = new \Imagick($image2);
$imagick1Size = $imagick1->getImageGeometry();
$imagick2Size = $imagick2->getImageGeometry();
$maxWidth = max($imagick1Size['width'], $imagick2Size['width']);
$maxHeight = max($imagick1Size['height'], $imagick2Size['height']);
$imagick1->extentImage($maxWidth, $maxHeight, 0, 0);
$imagick2->extentImage($maxWidth, $maxHeight, 0, 0);
try {
$result = $imagick1->compareImages($imagick2, \Imagick::METRIC_MEANSQUAREERROR);
$result[0]->setImageFormat('png');
$result['currentImage'] = clone $imagick2;
$result['currentImage']->setImageFormat('png');
}
catch (\ImagickException $e) {
$this->debug("IMagickException! could not campare image1 ($image1) and image2 ($image2).\nExceptionMessage: " . $e->getMessage());
$this->fail($e->getMessage() . ", image1 $image1 and image2 $image2.");
}
return $result;
}
}