1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package edu.samplu.common;
17
18 import org.apache.commons.lang.StringUtils;
19 import org.apache.commons.lang3.exception.ExceptionUtils;
20 import org.openqa.selenium.By;
21 import org.openqa.selenium.JavascriptExecutor;
22 import org.openqa.selenium.NoSuchFrameException;
23 import org.openqa.selenium.Proxy;
24 import org.openqa.selenium.WebDriver;
25 import org.openqa.selenium.WebElement;
26 import org.openqa.selenium.chrome.ChromeDriver;
27 import org.openqa.selenium.chrome.ChromeDriverService;
28 import org.openqa.selenium.firefox.FirefoxDriver;
29 import org.openqa.selenium.firefox.FirefoxProfile;
30 import org.openqa.selenium.remote.CapabilityType;
31 import org.openqa.selenium.remote.DesiredCapabilities;
32 import org.openqa.selenium.remote.RemoteWebDriver;
33 import org.openqa.selenium.safari.SafariDriver;
34
35 import com.thoughtworks.selenium.SeleneseTestBase;
36
37 import java.io.File;
38 import java.net.MalformedURLException;
39 import java.net.URL;
40 import java.util.concurrent.TimeUnit;
41
42
43
44
45
46
47
48
49 public class WebDriverUtil {
50
51 public static boolean jGrowlEnabled = false;
52
53 public static boolean jsHighlightEnabled = false;
54
55
56
57
58
59
60 public static int DEFAULT_IMPLICIT_WAIT_TIME = 30;
61
62
63
64
65
66 public static final boolean JGROWL_ERROR_FAILURE = false;
67
68
69
70
71 public static final String JS_HIGHLIGHT_BACKGROUND = "green";
72
73
74
75
76 public static final String JS_HIGHLIGHT_BOARDER = "green";
77
78
79
80
81 public static final int JS_HIGHLIGHT_MS = 400;
82
83
84
85
86 public static final String JS_HIGHLIGHT_PROPERTY = "remote.driver.highlight";
87
88
89
90
91
92
93 public static int SHORT_IMPLICIT_WAIT_TIME = 1;
94
95
96
97
98
99 public static final String REMOTE_DRIVER_SAUCELABS_PROPERTY = "remote.driver.saucelabs";
100
101
102
103
104 public static final String WEBDRIVER_CHROME_DRIVER = "webdriver.chrome.driver";
105
106
107
108
109 public static final String REMOTE_JGROWL_ENABLED = "remote.jgrowl.enabled";
110
111
112
113
114 public static final String REMOTE_LOGIN_UIF = "remote.login.uif";
115
116
117
118
119 public static final String REMOTE_PUBLIC_CHROME = "remote.public.chrome";
120
121
122
123
124
125
126 public static final int SETUP_URL_LOAD_WAIT_SECONDS = 120;
127
128
129
130
131
132 public static final String PROXY_HOST_PROPERTY = "remote.public.proxy";
133
134
135
136
137
138
139
140
141
142 public static WebDriver setUp(String username, String url) throws Exception {
143 return setUp(username, url, null, null);
144 }
145
146
147
148
149
150
151
152
153
154
155
156 public static WebDriver setUp(String username, String url, String className, String testName) throws Exception {
157 if ("true".equals(System.getProperty(REMOTE_JGROWL_ENABLED, "false"))) {
158 jGrowlEnabled = true;
159 }
160
161 if ("true".equals(System.getProperty(JS_HIGHLIGHT_PROPERTY, "false"))) {
162 jsHighlightEnabled = true;
163 }
164
165 WebDriver driver = null;
166 if (System.getProperty(REMOTE_DRIVER_SAUCELABS_PROPERTY) == null) {
167 driver = getWebDriver();
168 } else {
169 SauceLabsWebDriverHelper saucelabs = new SauceLabsWebDriverHelper();
170 saucelabs.setUp(className, testName);
171 driver = saucelabs.getDriver();
172 }
173
174 driver.manage().timeouts().implicitlyWait(SETUP_URL_LOAD_WAIT_SECONDS, TimeUnit.SECONDS);
175
176 if (!System.getProperty(SauceLabsWebDriverHelper.SAUCE_BROWSER_PROPERTY,"ff").equals("opera")) {
177 driver.manage().window().maximize();
178 }
179
180
181
182 if (!url.startsWith("http")) {
183 url = ITUtil.getBaseUrlString() + url;
184 }
185
186 driver.get(url);
187 driver.manage().timeouts().implicitlyWait(DEFAULT_IMPLICIT_WAIT_TIME, TimeUnit.SECONDS);
188 return driver;
189 }
190
191
192
193
194
195
196
197
198
199 public static void tearDown(boolean passed, String sessionId, String testParam, String userParam) throws Exception {
200
201 if (System.getProperty(SauceLabsWebDriverHelper.SAUCE_PROPERTY) != null) {
202 SauceLabsWebDriverHelper.tearDown(passed, sessionId, System.getProperty(SauceLabsWebDriverHelper.SAUCE_USER_PROPERTY),
203 System.getProperty(SauceLabsWebDriverHelper.SAUCE_KEY_PROPERTY));
204 }
205
206 if (System.getProperty(WebDriverLegacyITBase.REMOTE_PUBLIC_USERPOOL_PROPERTY) != null) {
207 ITUtil.getHTML(ITUtil.prettyHttp(System.getProperty(WebDriverLegacyITBase.REMOTE_PUBLIC_USERPOOL_PROPERTY) + "?test="
208 + testParam + "&user=" + userParam));
209 }
210 }
211
212
213
214
215
216
217 public static String determineUser(String testParam) {
218 String user = null;
219
220 if (System.getProperty(WebDriverLegacyITBase.REMOTE_PUBLIC_USER_PROPERTY) != null) {
221 return System.getProperty(WebDriverLegacyITBase.REMOTE_PUBLIC_USER_PROPERTY);
222 } else if (System.getProperty(WebDriverLegacyITBase.REMOTE_PUBLIC_USERPOOL_PROPERTY) != null) {
223 String userResponse = ITUtil.getHTML(ITUtil.prettyHttp(System.getProperty(
224 WebDriverLegacyITBase.REMOTE_PUBLIC_USERPOOL_PROPERTY) + "?test=" + testParam.trim()));
225 return userResponse.substring(userResponse.lastIndexOf(":") + 2, userResponse.lastIndexOf("\""));
226 }
227
228 return user;
229 }
230
231
232
233
234
235
236
237 public static void checkForIncidentReport(WebDriver driver, String locator, Failable failable,
238 String message) {
239 ITUtil.checkForIncidentReport(driver.getPageSource(), locator, failable, message);
240 }
241
242
243
244
245
246
247
248
249 public static ChromeDriverService chromeDriverCreateCheck() {
250 String driverParam = System.getProperty(ITUtil.HUB_DRIVER_PROPERTY);
251
252 if (driverParam != null && "chrome".equals(driverParam.toLowerCase())) {
253 if (System.getProperty(WEBDRIVER_CHROME_DRIVER) == null) {
254 if (System.getProperty(REMOTE_PUBLIC_CHROME) != null) {
255 System.setProperty(WEBDRIVER_CHROME_DRIVER, System.getProperty(REMOTE_PUBLIC_CHROME));
256 }
257 }
258 try {
259 ChromeDriverService chromeDriverService = new ChromeDriverService.Builder()
260 .usingDriverExecutable(new File(System.getProperty(WEBDRIVER_CHROME_DRIVER)))
261 .usingAnyFreePort()
262 .build();
263 return chromeDriverService;
264 } catch (Throwable t) {
265 throw new RuntimeException("Exception starting chrome driver service, is chromedriver ( http://code.google.com/p/chromedriver/downloads/list ) installed? You can include the path to it using -Dremote.public.chrome", t) ;
266 }
267 }
268 return null;
269 }
270
271 public static void jGrowl(WebDriver driver, String jGrowlHeader, boolean sticky, String message, Throwable t) {
272 if (jGrowlEnabled) {
273 jGrowl(driver, jGrowlHeader, sticky, message + " " + t.getMessage() + "\n" + ExceptionUtils.getStackTrace(t));
274 }
275 }
276
277 public static void jGrowl(WebDriver driver, String jGrowlHeader, boolean sticky, String message) {
278 if (jGrowlEnabled) {
279 try {
280 String javascript="jQuery.jGrowl('" + message + "' , {sticky: " + sticky + ", header : '" + jGrowlHeader + "'});";
281 ((JavascriptExecutor) driver).executeScript(javascript);
282 } catch (Throwable t) {
283 jGrowlException(t);
284 }
285 }
286 }
287
288 public static void jGrowlException(Throwable t) {
289 String failMessage = t.getMessage() + "\n" + ExceptionUtils.getStackTrace(t);
290 System.out.println("jGrowl failure " + failMessage);
291 if (JGROWL_ERROR_FAILURE) {
292 SeleneseTestBase.fail(failMessage);
293 }
294 }
295
296 public static void highlightElement(WebDriver webDriver, WebElement webElement) {
297 if (jsHighlightEnabled) {
298 try {
299 JavascriptExecutor js = (JavascriptExecutor) webDriver;
300 js.executeScript("element = arguments[0];\n"
301 + "originalStyle = element.getAttribute('style');\n"
302 + "element.setAttribute('style', originalStyle + \"; background: "
303 + JS_HIGHLIGHT_BACKGROUND + "; border: 2px solid " + JS_HIGHLIGHT_BOARDER + ";\");\n"
304 + "setTimeout(function(){\n"
305 + " element.setAttribute('style', originalStyle);\n"
306 + "}, " + JS_HIGHLIGHT_MS + ");", webElement);
307 } catch (Throwable t) {
308 System.out.println("Throwable during javascript highlight element");
309 t.printStackTrace();
310 }
311 }
312 }
313
314
315
316
317
318
319
320
321 public static WebDriver getWebDriver() {
322 String driverParam = System.getProperty(ITUtil.HUB_DRIVER_PROPERTY);
323 String hubParam = System.getProperty(ITUtil.HUB_PROPERTY);
324 String proxyParam = System.getProperty(PROXY_HOST_PROPERTY);
325
326
327 DesiredCapabilities capabilities = new DesiredCapabilities();
328 WebDriver webDriver = null;
329 if (StringUtils.isNotEmpty(proxyParam)) {
330 capabilities.setCapability(CapabilityType.PROXY, new Proxy().setHttpProxy(proxyParam));
331 }
332
333 if (hubParam == null) {
334 if (driverParam == null || "firefox".equalsIgnoreCase(driverParam)) {
335 FirefoxProfile profile = new FirefoxProfile();
336 profile.setEnableNativeEvents(false);
337 capabilities.setCapability(FirefoxDriver.PROFILE, profile);
338 return new FirefoxDriver(capabilities);
339 } else if ("chrome".equalsIgnoreCase(driverParam)) {
340 return new ChromeDriver(capabilities);
341 } else if ("safari".equals(driverParam)) {
342 System.out.println("SafariDriver probably won't work, if it does please contact Erik M.");
343 return new SafariDriver(capabilities);
344 }
345 } else {
346 try {
347 if (driverParam == null || "firefox".equalsIgnoreCase(driverParam)) {
348 return new RemoteWebDriver(new URL(ITUtil.getHubUrlString()), DesiredCapabilities.firefox());
349 } else if ("chrome".equalsIgnoreCase(driverParam)) {
350 return new RemoteWebDriver(new URL(ITUtil.getHubUrlString()), DesiredCapabilities.chrome());
351 }
352 } catch (MalformedURLException mue) {
353 System.out.println(ITUtil.getHubUrlString() + " " + mue.getMessage());
354 mue.printStackTrace();
355 }
356 }
357 return null;
358 }
359
360
361
362
363
364
365
366
367
368 public static void kradLogin(WebDriver driver, String userName, Failable failable) throws InterruptedException {
369 driver.findElement(By.name("login_user")).clear();
370 driver.findElement(By.name("login_user")).sendKeys(userName);
371 driver.findElement(By.id("Rice-LoginButton")).click();
372 Thread.sleep(1000);
373 String contents = driver.getPageSource();
374 ITUtil.failOnInvalidUserName(userName, contents, failable);
375 ITUtil.checkForIncidentReport(driver.getPageSource(), "Krad Login", failable, "Krad Login failure");
376 }
377
378
379
380
381
382
383
384
385 public static void login(WebDriver driver, String userName, Failable failable) throws InterruptedException {
386 driver.findElement(By.name("__login_user")).clear();
387 driver.findElement(By.name("__login_user")).sendKeys(userName);
388 driver.findElement(By.cssSelector("input[type=\"submit\"]")).click();
389 Thread.sleep(1000);
390 String contents = driver.getPageSource();
391 ITUtil.failOnInvalidUserName(userName, contents, failable);
392 ITUtil.checkForIncidentReport(driver.getPageSource(), "KNS Login", failable, "KNS Login failure");
393 }
394
395 public static void loginKradOrKns(WebDriver driver, String user, Failable failable) throws InterruptedException {
396 if ("true".equalsIgnoreCase(System.getProperty(ITUtil.REMOTE_AUTOLOGIN_PROPERTY, "true"))) {
397 if (isKradLogin()){
398 WebDriverUtil.kradLogin(driver, user, failable);
399 } else {
400 WebDriverUtil.login(driver, user, failable);
401 }
402 }
403 }
404
405
406
407
408 public static boolean isKradLogin(){
409
410 String loginUif = System.getProperty(REMOTE_LOGIN_UIF);
411 if (loginUif == null) {
412 loginUif = ITUtil.REMOTE_UIF_KRAD;
413 }
414
415 return (ITUtil.REMOTE_UIF_KRAD.equalsIgnoreCase(loginUif));
416 }
417
418 protected static void selectFrameSafe(WebDriver driver, String locator) {
419 try {
420 driver.switchTo().frame(locator);
421 } catch (NoSuchFrameException nsfe) {
422
423 }
424 }
425
426
427
428
429
430
431
432
433
434
435
436 public static void waitFor(WebDriver driver, int waitSeconds, By by, String message) throws InterruptedException {
437 driver.manage().timeouts().implicitlyWait(waitSeconds, TimeUnit.SECONDS);
438 Thread.sleep(1000);
439 driver.findElement(by);
440 driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
441 }
442
443
444
445
446
447
448
449
450
451
452
453 public static void waitFors(WebDriver driver, int waitSeconds, By by, String message) throws InterruptedException {
454 driver.manage().timeouts().implicitlyWait(waitSeconds, TimeUnit.SECONDS);
455 Thread.sleep(1000);
456 driver.findElements(by);
457 driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
458 }
459
460
461 public static void failOnMatchedJira(String contents, Failable failable) {
462 JiraAwareFailureUtil.failOnMatchedJira(contents, failable);
463 }
464
465 private static void failWithReportInfoForKim(String contents, String linkLocator, String message) {
466 final String kimIncidentReport = extractIncidentReportKim(contents, linkLocator, message);
467 SeleneseTestBase.fail(kimIncidentReport);
468 }
469
470 private static String extractIncidentReportKim(String contents, String linkLocator, String message) {
471 String chunk = contents.substring(contents.indexOf("id=\"headerarea\""), contents.lastIndexOf("</div>") );
472 String docIdPre = "type=\"hidden\" value=\"";
473 String docId = chunk.substring(chunk.indexOf(docIdPre) + docIdPre.length(), chunk.indexOf("\" name=\"documentId\""));
474
475 String stackTrace = chunk.substring(chunk.lastIndexOf("name=\"displayMessage\""), chunk.length());
476 String stackTracePre = "value=\"";
477 stackTrace = stackTrace.substring(stackTrace.indexOf(stackTracePre) + stackTracePre.length(), stackTrace.indexOf("name=\"stackTrace\"") - 2);
478
479 return "\nIncident report "+ message+ " navigating to "+ linkLocator + " Doc Id: "+ docId.trim()+ "\nStackTrace: "+ stackTrace.trim().replace(" at ","");
480 }
481
482 private static void processIncidentReport(String contents, String linkLocator, Failable failable, String message) {
483 failOnMatchedJira(contents, failable);
484
485 if (contents.indexOf("Incident Feedback") > -1) {
486 failWithReportInfo(contents, linkLocator, message);
487 }
488
489 if (contents.indexOf("Incident Report") > -1) {
490 failWithReportInfoForKim(contents, linkLocator, message);
491 }
492
493 SeleneseTestBase.fail("\nIncident report detected " + message + "\n Unable to parse out details for the contents that triggered exception: " + deLinespace(
494 contents));
495 }
496
497 private static void failWithReportInfo(String contents, String linkLocator, String message) {
498 final String incidentReportInformation = extractIncidentReportInfo(contents, linkLocator, message);
499 SeleneseTestBase.fail(incidentReportInformation);
500 }
501
502 private static String extractIncidentReportInfo(String contents, String linkLocator, String message) {
503 String chunk = contents.substring(contents.indexOf("Incident Feedback"), contents.lastIndexOf("</div>") );
504 String docId = chunk.substring(chunk.lastIndexOf("Document Id"), chunk.indexOf("View Id"));
505 docId = docId.substring(0, docId.indexOf("</span>"));
506 docId = docId.substring(docId.lastIndexOf(">") + 2, docId.length());
507
508 String viewId = chunk.substring(chunk.lastIndexOf("View Id"), chunk.indexOf("Error Message"));
509 viewId = viewId.substring(0, viewId.indexOf("</span>"));
510 viewId = viewId.substring(viewId.lastIndexOf(">") + 2, viewId.length());
511
512 String stackTrace = chunk.substring(chunk.lastIndexOf("(only in dev mode)"), chunk.length());
513 stackTrace = stackTrace.substring(stackTrace.indexOf("<span id=\"") + 3, stackTrace.length());
514 stackTrace = stackTrace.substring(stackTrace.indexOf("\">") + 2, stackTrace.indexOf("</span>"));
515
516 return "\nIncident report "+ message+ " navigating to "+ linkLocator+ " : View Id: "+ viewId.trim()+ " Doc Id: "+ docId.trim()+ "\nStackTrace: "+ stackTrace.trim().replace(" at ", "");
517 }
518
519 public static String deLinespace(String contents) {
520 while (contents.contains("\n\n")) {
521 contents = contents.replaceAll("\n\n", "\n");
522 }
523
524 return contents;
525 }
526 }