/
WebDriverUtils.java
286 lines (261 loc) · 10.5 KB
/
WebDriverUtils.java
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
package qa.webdriver.util;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.Point;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.util.StatusPrinter;
import qa.webdriver.util.CoreUtils;
/**
* @author Jon Austen
*
*/
public abstract class WebDriverUtils extends CoreUtils {
protected WebDriverUtils() {
// do nothing
}
protected static RemoteWebDriver driver;
public static int DEFAULT_IMPLICIT_WAIT = 30;
public static int DEFAULT_EXPLICIT_WAIT = 10; // seconds that LoadableComponent get() will try to load
protected static String mainHandle = "";
protected static String mainWindowTitle = "";
protected static Set<String> handleCache = new HashSet<String>();
public static int testXOffset = 0; //default value
public static void clearAndSetValue( WebElement field, String text ) {
field.clear();
field.sendKeys( Keys.chord(Keys.CONTROL, "a" ), text );
}
public static void clearAndType( WebElement field, String text ) {
field.submit();
field.clear();
field.sendKeys( text );
}
public static void mouseClickByLocator( By locator ) {
WebElement el = driver.findElement( locator );
Actions builder = new Actions( driver );
builder.moveToElement( el ).click( el );
builder.perform();
}
public static void switchToWindowByName( String name ) {
Set<String> windowSet = driver.getWindowHandles();
for( String handle: windowSet ) {
driver.switchTo().window( handle );
if ( driver.getTitle().equals( name ) ) {
break;
}
}
}
public static void clickByIdWithJavascript( String id ) {
JavascriptExecutor js = (JavascriptExecutor)driver;
WebElement element= driver.findElement( By.id( id ) );
js.executeScript( "arguments[0].click();", element );
js = null;
}
public static void closeAllBrowserWindows() {
Set<String> handles = driver.getWindowHandles();
if ( handles.size() > 1 ) {
LOGGER.info("Closing " + handles.size() + " window(s).");
for ( String windowId : handles ) {
LOGGER.info("-- Closing window handle: " + windowId );
// this can hang if you replaced the DOM with a document.write before calling this
driver.switchTo().window( windowId ).close();
}
} else if ( handles.size()==1 ) {
LOGGER.info("Closing last open window.");
} else {
LOGGER.info("There were no window handles to close.");
}
driver.quit(); // this quit is critical, otherwise last window will hang open
}
public static void closeWindowByHandle( String windowHandle ) {
driver.switchTo().window( windowHandle );
LOGGER.info("Closing window with title \"" + driver.getTitle() + "\"." );
driver.close();
}
/**
* Print internal Logger status
*/
public static void returnLoggerState() {
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
StatusPrinter.print(lc);
}
/**
* Loops to determine if WebDriver.getWindowHandles() returns any
* additional windows that the allHandles cache does not currently
* contain. If new windows are found, switch to latest window and
* update allHandles cache.
*/
public static String handleNewWindow() {
String newHandle = "";
printHandles();
Set<String> updatedHandles = driver.getWindowHandles();
if ( updatedHandles.size() < handleCache.size() ) {
mainHandle = "";
LOGGER.info("Illegal state: actually, I saw a window close.");
throw new IllegalStateException("This method handleNewWindow is not appropriate\n" +
"in this case. You are probably looking for the\n"+
"use of the updateHandleCache method.");
} else if ( updatedHandles.size() == handleCache.size() ) {
LOGGER.info("handleNewWindow() will do nothing because there are no new window handles.");
} else {
if ( !updatedHandles.isEmpty() ) {
for ( String windowId : updatedHandles ) {
if ( !windowId.equals( mainHandle ) ) { // for all windows except main window
if ( !handleCache.contains( windowId) ) { // for child windows not in allHandles cache
newHandle = windowId; // set value of newly found window handle
LOGGER.info("-- Open window handle: " + newHandle + " (new window)" );
}
}
}
if ( !newHandle.equals("") ) { // outside loop so it catches latest window handle if there are multiple
LOGGER.info("Switch to new window.");
driver.switchTo().window( newHandle ); // switch to new window handle
}
} else {
mainHandle = "";
throw new IllegalStateException("No browser window handles are open.");
}
}
handleCache = updatedHandles; // updates remembered set of open windows
return newHandle;
}
public static void scrollDownWithArrowKey() {
waitTimer(2, 500);
WebElement bt = driver.findElement( By.tagName("body") );
bt.sendKeys(Keys.ARROW_DOWN); //scroll to bring button into view
}
public static void updateHandleCache() {
LOGGER.info("Updating cache of window handles...");
printHandles();
Set<String> updatedHandles = driver.getWindowHandles();
if ( !updatedHandles.isEmpty() ) {
if ( updatedHandles.size() > handleCache.size() ) {
LOGGER.info( "Window handle number increased to: " + updatedHandles.size() );
} else if ( updatedHandles.size() == handleCache.size() ) {
LOGGER.info( "Window handle number is unchanged from: " + updatedHandles.size() );
} else {
LOGGER.info( "Window handle number decreased to: " + updatedHandles.size() );
}
} else {
mainHandle = null;
throw new IllegalStateException("No browser window handles are open.");
}
handleCache = updatedHandles; // updates remembered set of open windows
}
public static void printHandles() {
LOGGER.info( "Open windows:" );
for ( String windowId : handleCache ) {
LOGGER.info( "-- Open window handle: " + windowId );
if ( windowId.equals( mainHandle ) ) {
LOGGER.info(" (main handle)");
}
}
}
public static void initializeLocalBrowser( String type ) {
if ( type.equalsIgnoreCase( "firefox" ) ) {
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("network.proxy.http", "localhost");
profile.setPreference("network.proxy.http_port", "3128");
driver = new FirefoxDriver( profile );
} else if ( type.equalsIgnoreCase( "internetExplorer" ) ) {
driver = new InternetExplorerDriver();
}
else if ( type.equalsIgnoreCase( "chrome" ) ) {
driver = new ChromeDriver();
} else {
LOGGER.info( "Invalid browser type. Cannot initialize." );
}
driver.manage().timeouts().implicitlyWait( DEFAULT_IMPLICIT_WAIT, TimeUnit.MILLISECONDS );
positionMainHandle();
}
public static void initializeRemoteBrowser( String type, String host, int port ) {
DesiredCapabilities dc = new DesiredCapabilities();
dc.setCapability( "takesScreenshot", true );
dc.setCapability( "webdriver.remote.quietExceptions", false );
try {
if ( type.equalsIgnoreCase( "firefox" ) ) {
dc.setBrowserName("firefox");
driver = new RemoteWebDriver( new URL("http://" + host + ":" + port + "/wd/hub"), dc );
} else if ( type.equalsIgnoreCase( "ie" ) ) {
dc.setBrowserName("internetExplorer");
driver = new RemoteWebDriver( new URL("http://" + host + ":" + port + "/wd/hub"), dc );
}
else if ( type.equalsIgnoreCase( "chrome" ) ) {
dc.setBrowserName("chrome");
driver = new RemoteWebDriver( new URL("http://" + host + ":" + port + "/wd/hub"), dc );
} else {
LOGGER.info( "Invalid browser type. Cannot initialize." );
}
} catch ( MalformedURLException e ) {
e.printStackTrace();
}
driver.manage().timeouts().implicitlyWait( DEFAULT_IMPLICIT_WAIT, TimeUnit.MILLISECONDS );
positionMainHandle();
}
private static void positionMainHandle() {
handleCache = driver.getWindowHandles();
if ( handleCache.size() == 0 ) {
mainHandle = "";
throw new IllegalStateException("No browser window handles are open.\n" +
"Browser is uninitialized.");
} else if ( handleCache.size() > 1 ) {
mainHandle = "";
throw new IllegalStateException("More than one browser window handle is open.\n" +
"Please close all browsers and restart test.");
} else {
mainHandle = driver.switchTo().defaultContent().getWindowHandle();
mainWindowTitle = driver.switchTo().defaultContent().getTitle();
int fromLeft = Integer.parseInt( System.getProperty("windowXPosition") );
int fromTop = Integer.parseInt( System.getProperty("windowYPosition") );
int width = Integer.parseInt( System.getProperty("windowWidth") );
int height = Integer.parseInt( System.getProperty("windowHeight") );
setWindowPosition( mainHandle, width, height, fromLeft + testXOffset, fromTop );
}
}
public static void setWindowPosition(String handle, int width, int height, int fleft, int ftop) {
driver.switchTo().window( handle ).manage().window().setPosition( new Point(fleft, ftop) );
driver.switchTo().window( handle ).manage().window().setSize( new Dimension( width, height) );
//TODO add a javascript executor to get window focus
}
public static WebElement getElementByLocator( final By locator ) {
LOGGER.info( "Get element by locator: " + locator.toString() );
final long startTime = System.currentTimeMillis();
WebElement we = null;
int tries = 0;
while ( (System.currentTimeMillis() - startTime) < 91000 ) {
LOGGER.info( "Searching for element. Try number " + (tries++) );
try {
we = driver.findElement( locator );
waitTimer(5, 1000);
break;
} catch ( StaleElementReferenceException e ) {
LOGGER.info( "Stale element exception.");
}
}
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
LOGGER.info("Searched for " + totalTime + " milliseconds." );
return we;
}
public void showMessageInBrowser( String message ) {
message = "<HTML><HEAD><TITLE>Message</TITLE></HEAD><BODY>" + message + "</BODY></HTML>";
String script = "document.write( '" + message + "' );";
((JavascriptExecutor)driver).executeScript( script );
}
}