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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
|
/*
* Copyright 2000-2014 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.tests.tb3;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.vaadin.testbench.Parameters;
import com.vaadin.testbench.ScreenshotOnFailureRule;
import com.vaadin.testbench.parallel.BrowserUtil;
import com.vaadin.testbench.screenshot.ImageFileUtil;
/**
* Base class which provides functionality for tests which use the automatic
* screenshot comparison function.
*
* @author Vaadin Ltd
*/
public abstract class ScreenshotTB3Test extends AbstractTB3Test {
@Rule
public ScreenshotOnFailureRule screenshotOnFailure = new ScreenshotOnFailureRule(
this, true) {
@Override
protected void failed(Throwable throwable, Description description) {
super.failed(throwable, description);
closeApplication();
}
@Override
protected void succeeded(Description description) {
super.succeeded(description);
closeApplication();
}
@Override
protected File getErrorScreenshotFile(Description description) {
return ImageFileUtil
.getErrorScreenshotFile(getScreenshotFailureName());
};
};
private String screenshotBaseName;
@Rule
public TestRule watcher = new TestWatcher() {
@Override
protected void starting(org.junit.runner.Description description) {
Class<?> testClass = description.getTestClass();
// Runner adds [BrowserName] which we do not want to use in the
// screenshot name
String testMethod = description.getMethodName();
testMethod = testMethod.replaceAll("\\[.*\\]", "");
String className = testClass.getSimpleName();
screenshotBaseName = className + "-" + testMethod;
}
};
/**
* Contains a list of screenshot identifiers for which
* {@link #compareScreen(String)} has failed during the test
*/
private List<String> screenshotFailures;
/**
* Defines TestBench screen comparison parameters before each test run
*/
@Before
public void setupScreenComparisonParameters() {
screenshotFailures = new ArrayList<String>();
Parameters.setScreenshotErrorDirectory(getScreenshotErrorDirectory());
Parameters
.setScreenshotReferenceDirectory(getScreenshotReferenceDirectory());
}
/**
* Grabs a screenshot and compares with the reference image with the given
* identifier. Supports alternative references and will succeed if the
* screenshot matches at least one of the references.
*
* In case of a failed comparison this method stores the grabbed screenshots
* in the error directory as defined by
* {@link #getScreenshotErrorDirectory()}. It will also generate a html file
* in the same directory, comparing the screenshot with the first found
* reference.
*
* @param identifier
* @throws IOException
*/
protected void compareScreen(String identifier) throws IOException {
compareScreen(null, identifier);
}
protected void compareScreen(WebElement element, String identifier)
throws IOException {
if (identifier == null || identifier.isEmpty()) {
throw new IllegalArgumentException("Empty identifier not supported");
}
File mainReference = getScreenshotReferenceFile(identifier);
List<File> referenceFiles = findReferenceAndAlternatives(mainReference);
List<File> failedReferenceFiles = new ArrayList<File>();
for (File referenceFile : referenceFiles) {
boolean match = false;
if (element == null) {
// Full screen
match = testBench(driver).compareScreen(referenceFile);
} else {
// Only the element
match = customTestBench(driver).compareScreen(element,
referenceFile,
BrowserUtil.isIE8(getDesiredCapabilities()));
}
if (match) {
// There might be failure files because of retries in TestBench.
deleteFailureFiles(getErrorFileFromReference(referenceFile));
break;
} else {
failedReferenceFiles.add(referenceFile);
}
}
File referenceToKeep = null;
if (failedReferenceFiles.size() == referenceFiles.size()) {
// Ensure we use the correct browser version (e.g. if running IE11
// and only an IE 10 reference was available, then mainReference
// will be for IE 10, not 11)
String originalName = getScreenshotReferenceName(identifier);
File exactVersionFile = new File(originalName);
if (!exactVersionFile.equals(mainReference)) {
// Rename png+html to have the correct version
File correctPng = getErrorFileFromReference(exactVersionFile);
File producedPng = getErrorFileFromReference(mainReference);
File correctHtml = htmlFromPng(correctPng);
File producedHtml = htmlFromPng(producedPng);
producedPng.renameTo(correctPng);
producedHtml.renameTo(correctHtml);
referenceToKeep = exactVersionFile;
screenshotFailures.add(exactVersionFile.getName());
} else {
// All comparisons failed, keep the main error image + HTML
screenshotFailures.add(mainReference.getName());
referenceToKeep = mainReference;
}
}
// Remove all PNG/HTML files we no longer need (failed alternative
// references or all error files (PNG/HTML) if comparison succeeded)
for (File failedAlternative : failedReferenceFiles) {
File failurePng = getErrorFileFromReference(failedAlternative);
if (failedAlternative != referenceToKeep) {
// Delete png + HTML
deleteFailureFiles(failurePng);
}
}
if (referenceToKeep != null) {
File errorPng = getErrorFileFromReference(referenceToKeep);
enableAutoswitch(new File(errorPng.getParentFile(),
errorPng.getName() + ".html"));
}
}
private CustomTestBenchCommandExecutor customTestBench = null;
private CustomTestBenchCommandExecutor customTestBench(WebDriver driver) {
if (customTestBench == null) {
customTestBench = new CustomTestBenchCommandExecutor(driver);
}
return customTestBench;
}
private void enableAutoswitch(File htmlFile) throws FileNotFoundException,
IOException {
if (htmlFile == null || !htmlFile.exists()) {
return;
}
String html = FileUtils.readFileToString(htmlFile);
html = html.replace("body onclick=\"",
"body onclick=\"clearInterval(autoSwitch);");
html = html.replace("</script>",
";autoSwitch=setInterval(switchImage,500);</script>");
FileUtils.writeStringToFile(htmlFile, html);
}
private void deleteFailureFiles(File failurePng) {
File failureHtml = htmlFromPng(failurePng);
failurePng.delete();
failureHtml.delete();
}
/**
* Returns a new File which points to a .html file instead of the given .png
* file
*
* @param png
* @return
*/
private static File htmlFromPng(File png) {
return new File(png.getParentFile(), png.getName().replaceAll(
"\\.png$", ".png.html"));
}
/**
*
* @param referenceFile
* The reference image file (in the directory defined by
* {@link #getScreenshotReferenceDirectory()})
* @return the file name of the file generated in the directory defined by
* {@link #getScreenshotErrorDirectory()} if comparison with the
* given reference image fails.
*/
private File getErrorFileFromReference(File referenceFile) {
String absolutePath = referenceFile.getAbsolutePath();
String screenshotReferenceDirectory = getScreenshotReferenceDirectory();
String screenshotErrorDirectory = getScreenshotErrorDirectory();
// We throw an exception to safeguard against accidental reference
// deletion. See (#14446)
if (!absolutePath.contains(screenshotReferenceDirectory)) {
throw new IllegalStateException(
"Reference screenshot not in reference directory. Screenshot path: '"
+ absolutePath + "', directory path: '"
+ screenshotReferenceDirectory + "'");
}
return new File(absolutePath.replace(screenshotReferenceDirectory,
screenshotErrorDirectory));
}
/**
* Finds alternative references for the given files
*
* @param reference
* @return all references which should be considered when comparing with the
* given files, including the given reference
*/
private List<File> findReferenceAndAlternatives(File reference) {
List<File> files = new ArrayList<File>();
files.add(reference);
File screenshotDir = reference.getParentFile();
String name = reference.getName();
// Remove ".png"
String nameBase = name.substring(0, name.length() - 4);
for (int i = 1;; i++) {
File file = new File(screenshotDir, nameBase + "_" + i + ".png");
if (file.exists()) {
files.add(file);
} else {
break;
}
}
return files;
}
/**
* @param testName
* @return the reference file name to use for the given browser, as
* described by {@literal capabilities}, and identifier
*/
private File getScreenshotReferenceFile(String identifier) {
DesiredCapabilities capabilities = getDesiredCapabilities();
String originalName = getScreenshotReferenceName(identifier);
File exactVersionFile = new File(originalName);
if (exactVersionFile.exists()) {
return exactVersionFile;
}
String browserVersion = capabilities.getVersion();
if (browserVersion.matches("\\d+")) {
for (int version = Integer.parseInt(browserVersion); version > 0; version--) {
String fileName = getScreenshotReferenceName(identifier,
version);
File oldVersionFile = new File(fileName);
if (oldVersionFile.exists()) {
return oldVersionFile;
}
}
}
return exactVersionFile;
}
/**
* @return the base directory of 'reference' and 'errors' screenshots
*/
protected abstract String getScreenshotDirectory();
/**
* @return the base directory of 'reference' and 'errors' screenshots with a
* trailing file separator
*/
private String getScreenshotDirectoryWithTrailingSeparator() {
String screenshotDirectory = getScreenshotDirectory();
if (!screenshotDirectory.endsWith(File.separator)) {
screenshotDirectory += File.separator;
}
return screenshotDirectory;
}
/**
* @return the directory where reference images are stored (the 'reference'
* folder inside the screenshot directory)
*/
private String getScreenshotReferenceDirectory() {
return getScreenshotDirectoryWithTrailingSeparator() + "reference";
}
/**
* @return the directory where comparison error images should be created
* (the 'errors' folder inside the screenshot directory)
*/
private String getScreenshotErrorDirectory() {
return getScreenshotDirectoryWithTrailingSeparator() + "errors";
}
/**
* Checks if any screenshot comparisons failures occurred during the test
* and combines all comparison errors into one exception
*
* @throws IOException
* If there were failures during the test
*/
@After
public void checkCompareFailures() throws IOException {
if (screenshotFailures != null && !screenshotFailures.isEmpty()) {
throw new IOException(
"The following screenshots did not match the reference: "
+ screenshotFailures.toString());
}
}
/**
* @return the name of a "failure" image which is stored in the folder
* defined by {@link #getScreenshotErrorDirectory()} when the test
* fails
*/
private String getScreenshotFailureName() {
return getScreenshotBaseName() + "_" + getUniqueIdentifier(null)
+ "-failure.png";
}
/**
* @return the base name used for screenshots. This is the first part of the
* screenshot file name, typically created as "testclass-testmethod"
*/
public String getScreenshotBaseName() {
return screenshotBaseName;
}
/**
* Returns the name of the reference file based on the given parameters.
*
* @param testName
* @param capabilities
* @param identifier
* @return the full path of the reference
*/
private String getScreenshotReferenceName(String identifier) {
return getScreenshotReferenceName(identifier, null);
}
/**
* Returns the name of the reference file based on the given parameters. The
* version given in {@literal capabilities} is used unless it is overridden
* by the {@literal versionOverride} parameter.
*
* @param testName
* @param capabilities
* @param identifier
* @return the full path of the reference
*/
private String getScreenshotReferenceName(String identifier,
Integer versionOverride) {
return getScreenshotReferenceDirectory() + File.separator
+ getScreenshotBaseName() + "_"
+ getUniqueIdentifier(versionOverride) + "_" + identifier
+ ".png";
}
private String getUniqueIdentifier(Integer versionOverride) {
String testNameAndParameters = testName.getMethodName();
// runTest-wildfly9-nginx[Windows_Firefox_24][/buffering/demo][valo]
String parameters = testNameAndParameters.substring(
testNameAndParameters.indexOf("[") + 1,
testNameAndParameters.length() - 1);
// Windows_Firefox_24][/buffering/demo][valo
parameters = parameters.replace("][", "_");
// Windows_Firefox_24_/buffering/demo_valo
parameters = parameters.replace("/", "");
// Windows_Firefox_24_bufferingdemo_valo
if (versionOverride != null) {
// Windows_Firefox_17_-buffering-demo_valo
parameters = parameters.replaceFirst("_"
+ getDesiredCapabilities().getVersion(), "_"
+ versionOverride);
}
return parameters;
}
/**
* Returns the base name of the screenshot in the error directory. This is a
* name so that all files matching {@link #getScreenshotErrorBaseName()}*
* are owned by this test instance (taking into account
* {@link #getDesiredCapabilities()}) and can safely be removed before
* running this test.
*/
private String getScreenshotErrorBaseName() {
return getScreenshotReferenceName("dummy", null).replace(
getScreenshotReferenceDirectory(),
getScreenshotErrorDirectory()).replace("_dummy.png", "");
}
/**
* Removes any old screenshots related to this test from the errors
* directory before running the test
*/
@Before
public void cleanErrorDirectory() {
// Remove any screenshots for this test from the error directory
// before running it. Leave unrelated files as-is
File errorDirectory = new File(getScreenshotErrorDirectory());
// Create errors directory if it does not exist
if (!errorDirectory.exists()) {
errorDirectory.mkdirs();
}
final String errorBase = getScreenshotErrorBaseName();
File[] files = errorDirectory.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
String thisFile = pathname.getAbsolutePath();
if (thisFile.startsWith(errorBase)) {
return true;
}
return false;
}
});
for (File f : files) {
f.delete();
}
}
}
|