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