public static WebDriver getFirefoxDriver() throws Exception { baseDir = new File(".").getPath(); System.out.println("******** " + baseDir); String path = "src/test/resources/geckodriver"; System.out.println("******** " + path); System.setProperty("webdriver.gecko.driver", path); DesiredCapabilities capabilities = DesiredCapabilities.firefox(); capabilities.setCapability("marionette", true); capabilities.setCapability("networkConnectionEnabled", true); capabilities.setCapability("browserConnectionEnabled", true); WebDriver driver = new RemoteWebDriver( new URL("http://localhost:4444"), capabilities); // WebDriver driver = new MarionetteDriver(capabilities); return driver; }
private static WebDriver checkEmulators(String browserName, DesiredCapabilities caps, ProjectSettings settings, Boolean isGrid, String remoteUrl) { Emulator emulator = settings.getEmulators().getEmulator(browserName); if (emulator != null) { switch (emulator.getType()) { case "Duplicate": return create(emulator.getDriver(), caps, settings, isGrid, remoteUrl); case "Emulator": if (emulator.getDriver().equals("Chrome")) { return checkAndSetSize( create(emulator.getDriver(), getChromeUAECaps(caps, emulator), settings, isGrid, remoteUrl), emulator.getSize()); } else { return checkAndSetSize( create(emulator.getDriver(), getFFUAECaps(caps, emulator), settings, isGrid, remoteUrl), emulator.getSize()); } case "Chrome Emulator": return create("Chrome", getChromeEmulatorCaps(caps, emulator.getDriver()), settings, isGrid, remoteUrl); case "Remote URL": { return createRemoteDriver(emulator.getRemoteUrl(), caps, settings.getDriverSettings().useProxy(), settings.getDriverSettings()); } } } return null; }
/** * Create mocked {@link WebElement} object. * * @param type element type * @param value element value * @param isCheckbox 'true' is checkbox is desired; otherwise 'false' * @return mocked WebElement object */ private static WebElement mockElement(String type, String value, boolean isCheckbox) { WebElement element = mock(WebElement.class, withSettings().extraInterfaces(WrapsDriver.class)); when(element.getTagName()).thenReturn(type); if (isCheckbox) { when(element.getAttribute("type")).thenReturn("checkbox"); when(element.getAttribute("value")).thenReturn("isSelected: " + value); when(element.isSelected()).thenReturn(Boolean.parseBoolean(value)); } else { when(element.getAttribute("type")).thenReturn("text"); when(element.getAttribute("value")).thenReturn(value); when(element.isSelected()).thenReturn(false); } WebDriver driver = mockDriver(); when(((WrapsDriver) element).getWrappedDriver()).thenReturn(driver); return element; }
public static WebDriver getDriverUsingIf(DesiredCapabilities desiredCapabilities) { if (desiredCapabilities == null) { throw new IllegalStateException("DesiredCapabilities are missing!"); } final String browser = desiredCapabilities.getBrowserName(); if (CHROME.equalsIgnoreCase(browser)) { return new ChromeDriver(desiredCapabilities); } else if (FIREFOX.equalsIgnoreCase(browser)) { return new FirefoxDriver(desiredCapabilities); } else if (browser.isEmpty()) { throw new IllegalStateException("'browser' capability is missing!"); } throw new IllegalArgumentException(desiredCapabilities.getBrowserName() + " browser is not supported!"); }
@Override public WebDriver create(final Map<String, Object> options) { new Initialization(() -> { beforeInitialization(options); final File workDirectory = getWorkDirectory(options); final String expectedVersion = (String) options.get(EXPECTED_VERSION); final boolean forceUpdate = Boolean.parseBoolean((String) options.get(FORCE_UPDATE)); final File webDriverExecutable = new DownloadWebDriverExecutable(workDirectory, getWebDriverExecutableFromWorkDirectory, getLatestVersion, downloadExpectedVersion).get(expectedVersion, forceUpdate); new SystemPropertyWebDriverExecutableSetup(systemPropertyForExecutable, webDriverExecutable) .setup(); webDriver = instantiateWebDriver(options); new WebDriverShutdownHook(webDriver).install(); afterInitialization(options); }).initialize(); return webDriver; }
private <T extends TeasyElement> List<T> getElements(By locator, Function<WebDriver, List<WebElement>> condition, TeasyElementType type) { List<WebElement> webElements; try { webElements = fluentWait.waitFor(condition); } catch (AssertionError ignoredToReturnEmptyList) { return new ArrayList<>(); } if (webElements == null) { return new ArrayList<>(); } if (context == null) { return wrapList(webElements, locator, type); } else { return wrapList(context, webElements, locator, type); } }
public void load(SeleniumAction... actions){ WebDriver driver=null; try { driver=webDriverPool.get(); WebDriver.Options manage = driver.manage(); manage.window().maximize(); for(SeleniumAction action:actions){ action.execute(driver); } } catch (InterruptedException e) { e.printStackTrace(); log.error("",e); }finally{ if(driver!=null){ webDriverPool.returnToPool(driver); } } }
/** * This method captures a screenshot **/ public static void captureScreenshot(WebDriver driver, String screenshotName) { try { TakesScreenshot ts = (TakesScreenshot) driver; File source = ts.getScreenshotAs(OutputType.FILE); FileUtils.copyFile(source, new File(dirPath + "/ " + screenshotName + "_" + strDateStamp + ".png")); String ESCAPE_PROPERTY = "org.uncommons.reportng.escape-output"; System.setProperty(ESCAPE_PROPERTY, "false"); URL path = new File(dirPath + "/ " + screenshotName + "_" + strDateStamp + ".png").toURI().toURL(); String test = "<a href=" + path + "> click to open screenshot of " + screenshotName + "</a>"; Reporter.log(screenshotName + test + "<br>"); Reporter.log("<br>"); } catch (Exception e) { System.out.println("Exception while taking screenshot " + e.getMessage()); } }
private boolean isAlertPresent(WebDriver Driver) { try { Driver.switchTo().alert(); return true; } catch (NoAlertPresentException e) { Logger.getLogger(this.getClass().getName()).log(Level.OFF, e.getMessage(), e); return false; } }
@Nullable @Override public Boolean apply(@Nullable WebDriver webDriver) { List<String> actualTexts = new ArrayList<>(); errorElements = new ArrayList<>(); boolean isCorrect = true; for (TeasyElement el : elements) { actualTexts.add(el.getText()); if (!text.equals(el.getText())) { isCorrect = false; errorElements.add(el); } } return isCorrect; }
@Override public WebDriver createDriver(final Browser browser, final XmlConfig config) { final RemoteWebDriver driver = mock(RemoteWebDriver.class); when(driver.getScreenshotAs(OutputType.BYTES)).thenReturn(new byte[]{1, 2, 3}); doReturn(new SessionId(randomAlphanumeric(14))).when(driver).getSessionId(); return driver; }
public static WebDriver getChromeDriver() { String path = "src/test/resources/chromedriver"; System.setProperty("webdriver.chrome.driver", path); DesiredCapabilities capabilities = DesiredCapabilities.chrome(); capabilities.setCapability("networkConnectionEnabled", true); capabilities.setCapability("browserConnectionEnabled", true); return new ChromeDriver(capabilities); }
static public void esperaCargaPaginaNoTexto(WebDriver driver, String texto, int timeout) { Boolean resultado = (new WebDriverWait(driver, timeout)).until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//*[contains(text(),'" + texto + "')]"))); assertTrue(resultado); }
/** * Determine if the specified driver is capable of taking screenshots. * * @param optDriver optional web driver object * @param logger SLF4J logger object * @return 'true' if driver can take screenshots; otherwise 'false */ public static boolean canGetArtifact(Optional<WebDriver> optDriver, Logger logger) { if (optDriver.isPresent()) { WebDriver driver = optDriver.get(); if (driver instanceof TakesScreenshot) { return true; } else { String message = "This driver is not capable of taking a screenshot. If a screenshot is desired, use" + " a WebDriver implementation that supports screenshots. For more information, see https://" + "seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/TakesScreenshot.html"; logger.warn(message); } } return false; }
@Test public void testEventListenerWithError() { WebDriver webDriver = rule.getWebDriver(); webDriver.get("https://github.com"); WebElement searchInput = webDriver.findElement(By.cssSelector(".header-search-input")); searchInput.sendKeys("will", "test"); searchInput.sendKeys(Keys.ENTER); String searchKeyword = webDriver.findElement(By.cssSelector(".header-search-input")).getAttribute("value"); assertThat(searchKeyword, is("foooooo")); }
public String getScreenshot() { WebDriver driver = environment.getDriver(); if (driver instanceof TakesScreenshot) { return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BASE64); } return null; }
@Test public void cleanupThreadClosesTheDriver() { // given container.WEB_DRIVER = mock(WebDriver.class); WebDriverContainer.WebDriverCleanupThread cleanupThread = container.new WebDriverCleanupThread(); // when cleanupThread.run(); // then assertThat(container.WEB_DRIVER).isNull(); }
public static WebDriver getChromeDriver(String pathToChromeExecutable) { String path = System.getProperty("user.dir") + "\\Drivers\\chromedriver.exe"; System.setProperty("webdriver.chrome.driver",path); Map<String, Object> chromeOptions = new HashMap<String, Object>(); chromeOptions.put("binary", pathToChromeExecutable); DesiredCapabilities capabilities = DesiredCapabilities.chrome(); capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions); return new ChromeDriver(capabilities); }
static public List<WebElement> EsperaCargaPagina(WebDriver driver, String criterio, String id, int timeout) { String busqueda; if (criterio.equals("id")) busqueda = "//*[contains(@id,'" + id + "')]"; else if (criterio.equals("class")) busqueda = "//*[contains(@class,'" + id + "')]"; else busqueda = "//*[contains(text(),'" + id + "')]"; return EsperaCargaPaginaxpath(driver, busqueda, timeout); }
@Test public void onTest() { final WebDriver webDriver = Mockito.mock(WebDriver.class); final WebElement webElement = Mockito.mock(WebElement.class); final Type type = new Type(webDriver, "text", () -> {}); final By byId = By.id("id"); Mockito.when(webDriver.findElement(byId)).thenReturn(webElement); type.on(byId); Mockito.verify(webElement).sendKeys("text"); }
public WebDriver getDriver() { if (driver == null) { DriverProperties driverProperties = getDriverProperties(); driver = driverProperties.setDriver(driverProperties.getAppURL()); } return driver; }
/** * Web button click. * * @param driver the driver * @param logger the logger * @param element the element */ public static void webButtonClick(WebDriver driver, ExtentTest logger, WebElement element) { try { if (element != null && element.isEnabled()) { element.click(); } } catch (Exception e) { } }
static public void ClickSubopcionMenuHover(WebDriver driver, String submenu, String opcionclick) { //Pasamos el raton por el submenu de Gestion de alumnos para //que aparezca el menu desplegable Actions builder = new Actions(driver); WebElement hoverElement = driver.findElement(By.id(submenu)); builder.moveToElement(hoverElement).perform(); //Pinchamos la opcion opcionclick By locator = By.id(opcionclick); driver.findElement(locator).click(); }
public SatisfyBaseStepListener(final Class<? extends WebDriver> driverClass, final File outputDirectory, final Configuration configuration) { this(outputDirectory); this.driver = getProxyFactory().proxyFor(driverClass); this.configuration = configuration; }
private static WebDriver checkAndSetSize(WebDriver driver, String size) { if (driver != null) { if (size.matches("[0-9]+ x [0-9]+")) { int w = Integer.valueOf(size.split("x")[0].trim()); int h = Integer.valueOf(size.split("x")[1].trim()); driver.manage().window().setSize(new Dimension(w, h)); } } return driver; }
public static void main(String[] args) { WebDriver driver = new FirefoxDriver(); driver.get("http://cogenglab.csd.uwo.ca/rushdi.htm"); WebElement webElement = driver.findElement(By.xpath("//*[@id='content']")); System.out.println(webElement.getText()); }
public String getName() { String name = ""; Optional<Method> testMethod = context.getTestMethod(); if (testMethod.isPresent()) { name = testMethod.get().getName(); } name += "_" + parameter.getName() + "_" + object.getClass().getSimpleName(); if (WebDriver.class.isAssignableFrom(object.getClass())) { name += "_" + ((RemoteWebDriver) object).getSessionId(); } return name; }
public void returnToPool(WebDriver webDriver) { if (shutdowned.get()) { webDriver.quit(); webDriver = null; } else { Set<String> handles = webDriver.getWindowHandles(); if (handles.size() > 1) { int index = 0; for (String handle : handles) { if (index == 0) { index++; continue; } WindowUtil.changeWindowTo(webDriver, handle); webDriver.close(); index++; } } synchronized (shutdowned) { if(!shutdowned.get()){ innerQueue.add(webDriver); }else{ webDriver.quit(); webDriver = null; } } } }
public void tearDown() throws Exception { // Close all the browsers for (WebDriver webDriver : this.webDriverList) try { webDriver.quit(); } catch (Exception e) { e.printStackTrace(); } }
@TestTemplate void templateTest(WebDriver driver1, WebDriver driver2) { driver1.get("https://bonigarcia.github.io/selenium-jupiter/"); driver2.get("https://bonigarcia.github.io/selenium-jupiter/"); assertThat(driver1.getTitle(), containsString("A JUnit 5 extension for Selenium WebDriver")); assertThat(driver2.getTitle(), containsString("A JUnit 5 extension for Selenium WebDriver")); }
/** * 切换到新窗口 * * @param driver */ public void switchToNewWindow(WebDriver driver) { String[] handles = new String[driver.getWindowHandles().size()]; driver.getWindowHandles().toArray(handles);// 把list转换成数组 int i = handles.length; driver.switchTo().window(handles[i - 1]);// 切换窗口 }
/** * Produce page source from the specified driver. * * @param optDriver optional web driver object * @param reason impetus for capture request; may be 'null' * @param logger SLF4J logger object * @return page source; if capture fails, an empty string is returned */ public static byte[] getArtifact(Optional<WebDriver> optDriver, Throwable reason, Logger logger) { if (canGetArtifact(optDriver, logger)) { try { WebDriver driver = optDriver.get(); return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES); } catch (WebDriverException e) { logger.warn("The driver is capable of taking a screenshot, but it failed.", e); } } return new byte[0]; }
public synchronized static File takeScreenShot(WebDriver Driver) { try { return GalenUtils.makeFullScreenshot(Driver); } catch (IOException | InterruptedException ex) { Logger.getLogger(GalenWrapper.class.getName()).log(Level.SEVERE, null, ex); } return null; }
/** * Sequentially run the desired capabilities. */ protected void runSequential() { // NOPMD -- thread final WebDriver[] drivers = new WebDriver[repeatedCapabilities.length]; final boolean[] success = new boolean[repeatedCapabilities.length]; for (int index = 0; index < repeatedCapabilities.length; index++) { final int driverIndex = index; final DesiredCapabilities capability = repeatedCapabilities[driverIndex]; success[driverIndex] = false; runSequentialIndex(drivers, success, driverIndex, capability); } final List<String> faillures = checkResults(success); Assert.assertTrue("All browsers test failed", faillures.size() != success.length); Assert.assertEquals("Some browsers test failed", 0, faillures.size()); }
public FlavorRulesTemplatesShowPage(WebDriver webDriver) { super(webDriver); }
/** * Get robust web element factory for this context. * * @param context target context * @return robust web element factory */ private static synchronized InstanceCreator getCreator(WrapsContext context) { WebDriver driver = context.getWrappedDriver(); String driverName = driver.getClass().getName(); if (creatorMap.containsKey(driverName)) { return creatorMap.get(driverName); } WebElement reference = driver.findElement(By.tagName("*")); Class<? extends WebElement> refClass = reference.getClass(); Class<? extends WebElement> wrapperClass = new ByteBuddy() .subclass(refClass) .name(refClass.getPackage().getName() + ".Robust" + refClass.getSimpleName()) .method(not(isDeclaredBy(Object.class))) .intercept(MethodDelegation.withEmptyConfiguration() .withBinders(TargetMethodAnnotationDrivenBinder.ParameterBinder.DEFAULTS) .withResolvers(MethodNameEqualityResolver.INSTANCE, BindingPriority.Resolver.INSTANCE) .filter(not(isDeclaredBy(Object.class))) .toField("interceptor")) .implement(RobustWebElement.class) .defineField("interceptor", RobustElementWrapper.class, Visibility.PRIVATE) .implement(InterceptionAccessor.class).intercept(FieldAccessor.ofBeanProperty()) .make() .load(refClass.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER) .getLoaded(); InstanceCreator creator; try { creator = new ByteBuddy() .subclass(InstanceCreator.class) .method(not(isDeclaredBy(Object.class))) .intercept(MethodDelegation.toConstructor(wrapperClass)) .make() .load(wrapperClass.getClassLoader()) .getLoaded().newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw UncheckedThrow.throwUnchecked(e); } creatorMap.put(driverName, creator); return creator; }
public static WebDriver getDriver() { return driver.get(); }
public VisibleElementWaitFor(TeasyElement element, TeasyFluentWait<WebDriver> fluentWait) { this.element = element; this.fluentWait = fluentWait; }
/** * {@inheritDoc} */ @Override public byte[] getArtifact(ITestResult result) { Optional<WebDriver> optDriver = DriverManager.nabDriver(result.getInstance()); return ScreenshotUtils.getArtifact(optDriver, result.getThrowable(), LOGGER); }
public SessionHelper(WebDriver wd) { super(wd); }