1 package com.atlassian.selenium.junit4;
2
3 import com.atlassian.selenium.Browser;
4 import com.atlassian.selenium.SeleniumClient;
5 import com.atlassian.selenium.SeleniumConfiguration;
6 import com.atlassian.selenium.SeleniumStarter;
7 import org.apache.commons.lang.StringUtils;
8 import org.junit.runner.Description;
9 import org.junit.runner.notification.Failure;
10 import org.junit.runner.notification.RunListener;
11
12 import java.io.UnsupportedEncodingException;
13 import java.net.URLEncoder;
14
15
16
17
18
19
20
21
22
23
24 public class CaptureScreenshotListener extends RunListener
25 {
26 public CaptureScreenshotListener()
27 {
28 super();
29 }
30
31 @Override
32 public void testFailure(final Failure failure) throws Exception
33 {
34
35 final String reportsDirectory = System.getProperty("reportsDirectory");
36 if (!StringUtils.isEmpty(reportsDirectory))
37 {
38 try
39 {
40
41 final SeleniumClient seleniumClient = SeleniumStarter.getInstance().getSeleniumClient((SeleniumConfiguration) null);
42 if (seleniumClient.getBrowser().equals(Browser.FIREFOX))
43 {
44
45 seleniumClient.captureEntirePageScreenshot(reportsDirectory + "/" + createSreenshotFileName(failure.getDescription()), "background=#FFFFFF");
46 }
47 }
48 catch (Exception e)
49 {
50
51 }
52 }
53 }
54
55 protected String createSreenshotFileName(Description description)
56 {
57 final String displayName = description.getDisplayName();
58 int startIndex = displayName.indexOf("(");
59 int endIndex = displayName.lastIndexOf(")");
60 final String testName = displayName.substring(0, startIndex);
61
62 String filename;
63 if (startIndex != -1 && endIndex != -1)
64 {
65 filename = displayName.substring(startIndex + 1, endIndex);
66 if (!StringUtils.isEmpty(testName))
67 {
68 filename += "_" + testName;
69 }
70 }
71 else
72 {
73 filename = description.getDisplayName();
74 }
75
76 try
77 {
78 filename = URLEncoder.encode(filename, "UTF-8");
79 }
80 catch (UnsupportedEncodingException e)
81 {
82
83 }
84 return filename + ".png";
85 }
86 }