public JsonElement sendXMLHttpGETRequest( final String url, final boolean async ) { ( ( EventFiringWebDriver ) driver ).manage().timeouts().setScriptTimeout( 20, TimeUnit.SECONDS ); StrBuilder builder = new StrBuilder( "var callback = arguments[arguments.length - 1];\n" ); builder.appendln( "var xhr = new XMLHttpRequest();" ); builder.append( "xhr.open( 'GET', '" ).append( url ).append( "', '" ).append( async ).append( "' );" ); builder.appendln( "xhr.onreadystatechange = function() { " ); builder.appendln( " if (xhr.readyState == 4) { " ); builder.appendln( " callback(xhr.responseText);" ); builder.appendln( " }" ); builder.appendln( "}" ); builder.appendln( "xhr.send();" ); Object response = executeAsyncScript( builder.toString() ); Gson gson = new Gson(); return gson.fromJson( ( String ) response, JsonElement.class ); }
@Override @SuppressWarnings("unchecked") protected void before() throws Throwable { DriverServiceFactory driverServiceFactory = drivertype.driverServiceFactory(configuration); service = driverServiceFactory.createService(); log.info("starting service"); service.start(); driver = driverServiceFactory.createWebDriver(service); Preconditions.checkNotNull(driver,"driver should not be null after creation"); if (!listeners.isEmpty()) { EventFiringWebDriver eventFiringWebDriver = new EventFiringWebDriver(driver); listeners.forEach(eventFiringWebDriver::register); driver = eventFiringWebDriver; } }
@Test @SuppressWarnings("unchecked") public void shouldBeWrappedInEventFiringWebdriver() throws Throwable { AbstractWebDriverEventListener eventListener = new AbstractWebDriverEventListener() { }; driverService = new DriverService(DriverType.PHANTOMJS, eventListener); driverService.before(); WebDriver driver = driverService.getDriver(); assertThat(driver).isInstanceOf(EventFiringWebDriver.class); EventFiringWebDriver eventFiringWebDriver = (EventFiringWebDriver) driver; Field field = EventFiringWebDriver.class.getDeclaredField("eventListeners"); field.setAccessible(true); assertThat(((List<WebDriverEventListener>) field.get(eventFiringWebDriver)).size()).isEqualTo(1); }
private DefaultSession(final DriverFactory factory, TemporaryFilesystem tempFs, SessionId sessionId, final Capabilities capabilities) throws Exception { this.knownElements = new KnownElements(); this.sessionId = sessionId; this.tempFs = tempFs; final BrowserCreator browserCreator = new BrowserCreator(factory, capabilities); final FutureTask<EventFiringWebDriver> webDriverFutureTask = new FutureTask<EventFiringWebDriver>(browserCreator); executor = new ThreadPoolExecutor(1, 1, 600L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); // Ensure that the browser is created on the single thread. EventFiringWebDriver initialDriver = execute(webDriverFutureTask); if (!isQuietModeEnabled(browserCreator, capabilities)) { // Memo to self; this is not a constructor escape of "this" - probably ;) initialDriver.register(new SnapshotScreenListener(this)); } this.driver = initialDriver; this.capabilities = browserCreator.getCapabilityDescription(); updateLastAccessTime(); }
private WebDriver configDriver(WebDriver driver) { // Adding Web Event Listener if (eventFiring) { EventFiringWebDriver efirDriver = new EventFiringWebDriver(driver); WebEventListener driverListner = new WebEventListener(); driver = efirDriver.register(driverListner); } else { log.warn( "FrameWork Wont Work Properly : 'Event Firing' Set To : '{}'", eventFiring); } if (fullscreen) { driver.manage().window().maximize(); } driver.manage().timeouts().pageLoadTimeout(MAX_WAIT, TimeUnit.SECONDS); driver.manage().timeouts().implicitlyWait(MAX_WAIT, TimeUnit.SECONDS); return driver; }
/** * Check if WebElement is present in the page Returns the boolean status * * @param */ public synchronized boolean isPresent(By by) { log.trace("Is Present Element : {}", by); WebDriver driver = DriverManager.getDriver(); WebDriver simpleDriver = driver; if (driver instanceof EventFiringWebDriver) { EventFiringWebDriver eventFirDriver = (EventFiringWebDriver) driver; simpleDriver = eventFirDriver.getWrappedDriver(); } try { if (simpleDriver.findElements(by).size() > 0) { return true; } } catch (Exception e) { return false; } return false; }
/** * {@inheritDoc} */ @Override public WebDriver getWebDriverInstance() { WebDriver retVal = getWebDriver(); if (null == retVal || !(((EventFiringWebDriver)retVal).getWrappedDriver() instanceof RemoteWebDriver)) { try { RemoteWebDriver remoteVal = new RemoteWebDriver(new URL(url), caps.get()); remoteVal.setFileDetector(new LocalFileDetector()); retVal = remoteVal; } catch (MalformedURLException e) { //TODO add handling for bad url e.printStackTrace(); } setWebDriver(retVal); } return retVal; }
/** * Create a WebDriver instance with useful settings based on the WEBDRIVER environment variable. * @return The WebDriver */ public static EventFiringWebDriver createFromEnvVar() { String browser = System.getenv(WEBDRIVER_ENV_NAME); if (browser == null) { log.info("WebDriver type not specified, defaulting to Chrome."); browser = "chrome"; } switch (browser.toLowerCase()) { case "firefox": return createFirefox(); default: log.warn("Unknown WebDriver type '{}', defaulting to Chrome.", browser); case "chrome": return createChrome(); } }
private WebDriver callPostConstruct(D webDriverToBeChangedAfterConstruction) { webDriverConfigurationParticipantList .forEach(participant -> participant.postConstruct(webDriverToBeChangedAfterConstruction)); EventFiringWebDriver eventFiringWebDriver = new EventFiringWebDriver(webDriverToBeChangedAfterConstruction); eventListeners.forEach(eventListener -> eventFiringWebDriver.register(eventListener)); return eventFiringWebDriver; }
@Parameters(name = "{index}: {0} {1}") public static Collection<Object[]> data() { return asList(new Object[][] { { SafariDriver.class, WebDriverException.class }, { EventFiringWebDriver.class, InstantiationException.class }, { HtmlUnitDriver.class, null }, { RemoteWebDriver.class, IllegalAccessException.class } }); }
@Before public void beforeEachTest() throws IOException { tempFolder = testFolder.newFolder(); driverPhantomJS = new EventFiringWebDriver(driverServicePhantomJS.getDriver()) .register(new ErrorLoggingWebDriverEventListener(tempFolder.getPath())); chromeEventListener = new ErrorLoggingWebDriverEventListener(tempFolder.getPath()); driverChrome = new EventFiringWebDriver(driverServiceChrome.getDriver()) .register(chromeEventListener); }
public EventFiringWebDriver call() throws Exception { WebDriver rawDriver = factory.newInstance(capabilities); Capabilities actualCapabilities = capabilities; if (rawDriver instanceof HasCapabilities) { actualCapabilities = ((HasCapabilities) rawDriver).getCapabilities(); isAndroid = actualCapabilities.getPlatform().is(Platform.ANDROID); } describedCapabilities = getDescription(rawDriver, actualCapabilities); return new EventFiringWebDriver(rawDriver); }
@Override public WebDriver enhance(WebDriver instance, Class<? extends Annotation> qualifier) { //System.out.println("Adding AngularJS capabilities to WebDriver"); instance.manage().timeouts().setScriptTimeout(2, TimeUnit.SECONDS); EventFiringWebDriver driver = new EventFiringWebDriver(instance); WebDriverEventListener listener = new AngularJSEventHandler(); driver.register(listener); return driver; }
@Override public WebDriver deenhance(WebDriver enhancedInstance, Class<? extends Annotation> qualifier) { if (EventFiringWebDriver.class.isInstance(enhancedInstance)) { //System.out.println("Removing AngularJS capabilities to WebDriver"); EventFiringWebDriver driver = (EventFiringWebDriver) enhancedInstance; driver.unregister(listener); listener = null; return driver.getWrappedDriver(); } return enhancedInstance; }
/** * 如果当前进程没有绑定driver,创建一个然后绑定上,如果已经有了就直接返回 * create a driver for this thread if not exist. or return it directly */ public static WebDriver getDriver(){ WebDriver driver= DriverManager.ThreadDriver.get(); if (driver==null){ if (browserType.equals("firefox")){ driver = new EventFiringWebDriver(new FirefoxDriver()).register(new LogEventListener()); ThreadDriver.set(driver); //找东西前等三秒wait 3 second for every find by DriverManager.getDriver().manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS); } //有需求的同学自己在这里添加IE等浏览器的支持 //you can add ie/chrome or other driver here } return driver; }
/** * Sets the web driver. * * @param webDriver * the webDriver to set */ public final void setWebDriver(final WebDriver webDriver) { EventFiringWebDriver eDriver = new EventFiringWebDriver(webDriver); // multiWindowsHandler = new MultiWindowsHandler(this); eDriver.register((MultiWindowsHandler)GlobalUtils.getTargetObject(multiWindowsHandler)); this.webDriver = eDriver; }
@Override public WebDriver enhance(WebDriver instance, Class<? extends Annotation> qualifier) { instance.manage().timeouts().setScriptTimeout(2, TimeUnit.SECONDS); EventFiringWebDriver driver = new EventFiringWebDriver(instance); listener = new AngularJSEventHandler(); driver.register(listener); return driver; }
@Override public WebDriver deenhance(WebDriver enhancedInstance, Class<? extends Annotation> qualifier) { if (EventFiringWebDriver.class.isInstance(enhancedInstance)) { EventFiringWebDriver driver = (EventFiringWebDriver) enhancedInstance; driver.unregister(listener); listener = null; return driver.getWrappedDriver(); } return enhancedInstance; }
@Override public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(SessionContext.getSession().getWebDriver().toString()); sb.append(" ").append(method.getName()); for (Object param : params) if (param instanceof WebElement && !(SessionContext.getSession().getWebDriver() instanceof EventFiringWebDriver)) sb.append(" ").append(((RemoteWebElement) param).getId()); else if (param instanceof WebElement && SessionContext.getSession().getWebDriver() instanceof EventFiringWebDriver) { sb.append(" ").append(((WebElement) param).getLocation()); } else { sb.append(" ").append(param.toString()); } return sb.toString(); }
@Override public WebDriver get() { String webDriverKey = config.get(WebConstants.WEBDRIVER_KEY); log.info("Creating new WebDriver instance with key '{}'...", webDriverKey); DesiredCapabilities capabilities = capabilitiesMap.get(webDriverKey); // we must disable WebDriver's overlapping check to be able to use our own topMostElementCheck flag capabilities.setCapability("overlappingCheckDisabled", true); //TODO this flag tells FirefoxDriver whether to run in legacy mode or in Marionette mode // => remove it, once the W3C actions API is correctly implemented in GeckoDriver Boolean isWebdriverFirefoxMarionette = config.getBoolean(FirefoxDriver.SystemProperty.DRIVER_USE_MARIONETTE); capabilities.setCapability(FirefoxDriver.MARIONETTE, isWebdriverFirefoxMarionette); // post event so users can customize capabilities eventBus.post(new BeforeWebDriverCreationEvent(webDriverKey, capabilities)); WebDriver webDriver = createWebDriver(capabilities); checkState(!(webDriver instanceof EventFiringWebDriver), "WebDrivers must not be wrapped explicitly into an EventFiringWebDriver. This is implicitly done by jFunk."); long implicitWaitSeconds = config.getLong(WebConstants.WEBDRIVER_IMPLICIT_WAIT_SECONDS, 0L); if (implicitWaitSeconds > 0) { webDriver.manage().timeouts().implicitlyWait(implicitWaitSeconds, TimeUnit.SECONDS); } EventFiringWebDriver eventFiringWebDriver = new EventFiringWebDriver(webDriver); for (WebDriverEventListener listener : eventListeners) { eventFiringWebDriver.register(listener); } return eventFiringWebDriver; }
/** * Create a Chrome WebDriver instance. * @return The WebDriver */ public static EventFiringWebDriver createChrome() { String chromeDriverBinary = WebDriverBinaryFinder.findChromeDriver(); System.setProperty("webdriver.chrome.driver", chromeDriverBinary); log.info("Using ChromeDriver binary from {}", chromeDriverBinary); // Prevent annoying yellow warning bar from being displayed. ChromeOptions options = new ChromeOptions(); options.setExperimentalOption("excludeSwitches", ImmutableList.of("ignore-certificate-errors")); DesiredCapabilities caps = getCapabilities(); caps.setCapability(ChromeOptions.CAPABILITY, options); return withReports(new ChromeDriver(caps)); }
public void enableActionsLogging() { this.setDriver(new EventFiringWebDriver(driver).register(new ReportingWebDriverEventListner())); }
public void disableActionsLogging() { this.setDriver(new EventFiringWebDriver(driver).unregister(new ReportingWebDriverEventListner())); }
private void registerEventListeners(final EventFiringWebDriver closingWebDriver) { listeners.stream().forEach(closingWebDriver::register); }
public WebDriver createRemoteWebDriver(final String browser, final String mode) throws Exception { WebDriver driver = null; config.setBrowser(BrowserType.getBrowserType(browser)); config.setMode(DriverMode.valueOf(mode)); if (config.getMode() == DriverMode.ExistingGrid) { webDriverBuilder = new RemoteDriverFactory(this.config); } else { if (config.getBrowser() == BrowserType.FireFox) { webDriverBuilder = new FirefoxDriverFactory(this.config); } else if (config.getBrowser() == BrowserType.Marionette) { webDriverBuilder = new MarionetteDriverFactory(this.config); } else if (config.getBrowser() == BrowserType.InternetExplore) { webDriverBuilder = new IEDriverFactory(this.config); } else if (config.getBrowser() == BrowserType.Chrome) { webDriverBuilder = new ChromeDriverFactory(this.config); } else if (config.getBrowser() == BrowserType.HtmlUnit) { webDriverBuilder = new HtmlUnitDriverFactory(this.config); } else if (config.getBrowser() == BrowserType.Safari) { webDriverBuilder = new SafariDriverFactory(this.config); } else if (config.getBrowser() == BrowserType.SauceLabs) { webDriverBuilder = new SauceLabsDriverFactory(this.config); } else if (config.getBrowser() == BrowserType.Android) { webDriverBuilder = new AndroidDriverFactory(this.config); } else if (config.getBrowser() == BrowserType.IPhone) { webDriverBuilder = new IPhoneDriverFactory(this.config); } else { throw new RuntimeException("Unsupported browser: " + browser); } } synchronized (this.getClass()) { driver = webDriverBuilder.createWebDriver(); if(config.isEventFiringWebDriver()) { CustomEventListener eventListener = new CustomEventListener(); EventFiringWebDriver eventFiringWebDriver = new EventFiringWebDriver(driver); eventFiringWebDriver.register(eventListener); WebUIDriver.setWebDriver(eventFiringWebDriver); driverSession.set(eventFiringWebDriver); driver = handleListeners(eventFiringWebDriver); } else { driverSession.set(driver); driver = handleListeners(driver); } } return driver; }
@Before public void beforeEachTest() throws IOException { folder = testFolder.getRoot(); driver = new EventFiringWebDriver(driverService.getDriver()); }
void checkExpiry() { for (SessionId sessionId : driverSessions.getSessions()) { Session session = driverSessions.get(sessionId); if (session != null) { boolean useDeleteSession = false; boolean killed = false; boolean inUse = session.isInUse(); if (!inUse && session.isTimedOut(clientGoneTimeout)) { useDeleteSession = true; log.info("Session " + session.getSessionId() + " deleted due to client timeout"); } if (inUse && session.isTimedOut(insideBrowserTimeout)) { WebDriver driver = session.getDriver(); if (driver instanceof EventFiringWebDriver){ driver = ((EventFiringWebDriver)driver).getWrappedDriver(); } if (driver instanceof Killable) { //session.interrupt(); ((Killable) driver).kill(); killed = true; log.warning("Browser killed and session " + session.getSessionId() + " terminated due to in-browser timeout."); } else { useDeleteSession = true; log.warning("Session " + session.getSessionId() + " deleted due to in-browser timeout. " + "Terminating driver with DeleteSession since it does not support Killable, " + "the driver in question does not support selenium-server timeouts fully"); } } if (useDeleteSession) { DeleteSession deleteSession = new DeleteSession(session); try { deleteSession.call(); } catch (Exception e) { throw new RuntimeException(e); } } if (useDeleteSession || killed) { driverSessions.deleteSession(sessionId); final PerSessionLogHandler logHandler = LoggingManager.perSessionLogHandler(); logHandler.transferThreadTempLogsToSessionLogs(sessionId); logHandler.removeSessionLogs(sessionId); } } } }
@Override public boolean canEnhance(InstanceOrCallableInstance instance, Class<?> droneType, Class<? extends Annotation> qualifier) { return droneType.isAssignableFrom(EventFiringWebDriver.class); }
public DevSWebDriver() throws Exception { driver = new EventFiringWebDriver(BrowserManager.getWebDriver());//firefox web driver maxWaitTime = UITestConstants.WAITING_TIME_CONSTANT; driver.register(errorListener); }
private static EventFiringWebDriver withReports(WebDriver driver) { return ReportingWebDriverEventListener.applyTo(driver, REPORTS_CLASS_PREFIX); }
/** * Returns the wrapped {@link WebDriver} instance if the given one is an * {@link EventFiringWebDriver}. * * @param webDriver * the {@link WebDriver} instance * @return the wrapped {@link WebDriver} instance */ public static WebDriver getWrappedDriver(final WebDriver webDriver) { if (webDriver instanceof EventFiringWebDriver) { return ((EventFiringWebDriver) webDriver).getWrappedDriver(); } return webDriver; }
/** * Create a Firefox WebDriver instance. * @return The WebDriver */ public static EventFiringWebDriver createFirefox() { return withReports(new FirefoxDriver(getCapabilities())); }