示例#1
0
  @Parameters("browser")
  @Test
  public void testLogin(String browser) throws MalformedURLException, InterruptedException {
    System.out.println(browser);

    DesiredCapabilities cap = null;

    if (browser.equals("firefox")) {
      cap = DesiredCapabilities.firefox();
      cap.setBrowserName("firefox");
      cap.setPlatform(Platform.ANY);
    } else if (browser.equals("chrome")) {
      cap = DesiredCapabilities.chrome();
      cap.setBrowserName("chrome");
      cap.setPlatform(Platform.ANY);
    } else if (browser.equals("iexplorer")) {
      cap = DesiredCapabilities.internetExplorer();
      cap.setBrowserName("iexplore");
      cap.setPlatform(Platform.WINDOWS);
    }
    driver = new RemoteWebDriver(new URL("http://192.168.1.133:5555/wd/hub"), cap);
    // driver.manage().window().maximize();
    driver.get("http://gmail.com");
    driver.findElement(By.id("Email")).sendKeys("Hello");
    Thread.sleep(10000L);
  }
 protected DesiredCapabilities createCommonCapabilities() {
   DesiredCapabilities browserCapabilities = new DesiredCapabilities();
   if (webProxySettings != null) {
     browserCapabilities.setCapability(PROXY, webProxySettings);
   }
   return browserCapabilities;
 }
 private void registerDefaults(Platform current) {
   if (current.equals(Platform.ANDROID)) {
     // AndroidDriver is here for backward-compatibility reasons, it should be removed at some
     // point
     registerDriver(DesiredCapabilities.android(), "org.openqa.selenium.android.AndroidDriver");
     registerDriver(DesiredCapabilities.android(), "org.openqa.selenium.android.AndroidApkDriver");
     return;
   }
   for (Map.Entry<Capabilities, String> entry : defaultDrivers.entrySet()) {
     Capabilities caps = entry.getKey();
     if (caps.getPlatform() != null && caps.getPlatform().is(current)) {
       registerDriver(caps, entry.getValue());
     } else if (caps.getPlatform() == null) {
       registerDriver(caps, entry.getValue());
     } else {
       log.info(
           "Default driver "
               + entry.getValue()
               + " registration is skipped: registration capabilities "
               + caps.toString()
               + " does not match with current platform: "
               + current.toString());
     }
   }
 }
  // chrome
  public void seleniumChrome(String filePath, String url) throws InterruptedException {
    System.out.println(String.format("Fetching %s...", url));

    // 设置
    System.setProperty(
        "webdriver.chrome.driver",
        "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe");
    System.out.println("chromedriver opened");

    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
    capabilities.setCapability("chrome.switches", Arrays.asList("--start-maximized"));

    WebDriver driver = new org.openqa.selenium.chrome.ChromeDriver(capabilities);
    driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS); // 5秒内没打开,重新加载
    while (true) {
      try {
        driver.get(url);
      } catch (Exception e) {
        driver.quit();
        driver = new ChromeDriver();
        driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
        continue;
      }
      break;
    }
    // save page
    String html = driver.getPageSource();
    saveHtml(filePath, html);
    System.out.println("save finish...");
    // Close the browser
    Thread.sleep(2000);
    driver.quit();
  }
  private void setSafely(DesiredCapabilities caps, String key, Object value) {
    if (value == null || caps.getCapability(key) != null) {
      return;
    }

    caps.setCapability(key, value);
  }
 public DesiredCapabilities getIECapabilities() {
   DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
   capabilities.setCapability(CapabilityType.ForSeleniumServer.ENSURING_CLEAN_SESSION, true);
   capabilities.setCapability(InternetExplorerDriver.ENABLE_PERSISTENT_HOVERING, true);
   capabilities.setCapability("requireWindowFocus", true);
   return addProxySettings(capabilities, proxy());
 }
示例#7
0
  private WebDriver setRemoteServer(Map<String, String> getsessionConfig) {
    DesiredCapabilities cap = null;
    browser = System.getProperty("browser");

    if (browser == null) browser = getsessionConfig.get("browser").toString();
    if (browser.equalsIgnoreCase("firefox")) {
      cap = DesiredCapabilities.firefox();
    } else if (browser.equalsIgnoreCase("chrome")) {
      cap = DesiredCapabilities.chrome();
    } else if (browser.equalsIgnoreCase("ie")
        || browser.equalsIgnoreCase("internetexplorer")
        || browser.equalsIgnoreCase("InternetExplorer")) {
      cap = DesiredCapabilities.internetExplorer();
    }

    String seleniumhubAddress = System.getProperty("hub");
    if (seleniumhubAddress == null) {
      seleniumhubAddress = getsessionConfig.get("seleniumserverhost1");
    }
    URL serverhost = null;

    try {
      serverhost = new URL(seleniumhubAddress);
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }
    cap.setJavascriptEnabled(true);
    return new RemoteWebDriver(serverhost, cap);
  }
  /**
   * private method to load the InternetExplorer Driver
   *
   * @param loadRemote
   */
  private static RemoteWebDriver loadIEDriver(boolean loadRemote) throws Exception {

    log.info("Entering BrowserFactory class loadIEDriver...");

    RemoteWebDriver remoteDriver = null;
    DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
    capabilities.setCapability(
        InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);

    if (loadRemote) {
      log.info("loading IE driver in remote");
      log.info("Loading  Remote Run URL " + CommonUtils.readFromConfig("RemoteWebAppUrl"));
      URL url = new URL(CommonUtils.readFromConfig("RemoteWebAppUrl"));
      remoteDriver = new RemoteWebDriver(url, capabilities);
      log.info("loading IE driver in remote successful");
    } else {
      log.info("loading Generic IE driver");
      System.setProperty(
          "webdriver.ie.driver", "src/main/resources/browser_exe/ie/IEDriverServer.exe");
      remoteDriver = new InternetExplorerDriver(capabilities);
      log.info("loading Generic IE driver successful");
    }

    log.info("Exiting BrowserFactory class loadIEDriver...");

    return remoteDriver;
  }
示例#9
0
 public PhantomDriver(ElasticSearch elsatic) {
   // Initiate PhantomJS
   DesiredCapabilities dc = new DesiredCapabilities();
   dc.setCapability("phantomjs.page.settings.loadImages", false);
   _driver = new PhantomJSDriver(dc);
   _elastic = elsatic;
 }
示例#10
0
  private ResultItems myDownload(Request request, Spider spider) throws IOException {
    ResultItems resultItems = new ResultItems(request, spider);

    DesiredCapabilities cap = DesiredCapabilities.chrome();
    ChromeOptions co = new ChromeOptions();
    String userAgent = request.getUserAgent();
    co.addArguments("--user-agent=" + userAgent);
    cap.setCapability(ChromeOptions.CAPABILITY, co);

    Proxy myProxy = spider.getProxy(request);
    if (myProxy != null) {
      String proxy = myProxy.getHost() + ":" + myProxy.getPort();
      org.openqa.selenium.Proxy p = new org.openqa.selenium.Proxy();
      p.setHttpProxy(proxy).setFtpProxy(proxy).setSslProxy(proxy);
      cap.setCapability(CapabilityType.PROXY, p);
    }

    WebDriver driver = new ChromeDriver(cap);
    driver.get(request.getUrl());
    // Get the html source of the page
    String pageSource = driver.getPageSource();
    // Close the browser
    driver.quit();
    return resultItems.setResource(Jsoup.parse(pageSource, request.getUrl()));
  }
  @Override
  public WebDriver newWebDriver(Capabilities capabilities, ConfigurationProperties configuration) {
    if (!available) {
      throw new ConfigurationException("WebDriver " + webDriverClassName + " is not available.");
    }

    try {
      DesiredCapabilities defaultCapabilities = newDefaultCapabilities();
      if (defaultCapabilities != null) {
        defaultCapabilities.merge(capabilities);
        capabilities = defaultCapabilities;
      }

      if (capabilities != null && !capabilities.asMap().isEmpty()) {
        ArrayList<Object> argsList = new ArrayList<>(Arrays.asList(args));
        argsList.add(0, capabilities);
        try {
          return newInstance(webDriverClass, configuration, argsList.toArray());
        } catch (NoSuchMethodException e) { // NOPMD EmptyCatchBlock
          // Ignore capabilities.
        }
      }
      return newInstance(webDriverClass, configuration, args);
    } catch (InstantiationException
        | IllegalAccessException
        | NoSuchMethodException
        | InvocationTargetException e) {
      throw new ConfigurationException("Can't create new WebDriver instance", e);
    }
  }
  protected WebDriver createInstanceOf(String className) {
    try {
      DesiredCapabilities capabilities = createCommonCapabilities();
      capabilities.setJavascriptEnabled(true);
      capabilities.setCapability(TAKES_SCREENSHOT, true);
      capabilities.setCapability(ACCEPT_SSL_CERTS, true);
      capabilities.setCapability(SUPPORTS_ALERTS, true);
      if (isPhantomjs()) {
        capabilities.setCapability(
            "phantomjs.cli.args", // PhantomJSDriverService.PHANTOMJS_CLI_ARGS ==
                                  // "phantomjs.cli.args"
            new String[] {"--web-security=no", "--ignore-ssl-errors=yes"});
      }

      Class<?> clazz = Class.forName(className);
      if (WebDriverProvider.class.isAssignableFrom(clazz)) {
        return ((WebDriverProvider) clazz.newInstance()).createDriver(capabilities);
      } else {
        Constructor<?> constructor = Class.forName(className).getConstructor(Capabilities.class);
        return (WebDriver) constructor.newInstance(capabilities);
      }
    } catch (InvocationTargetException e) {
      throw runtime(e.getTargetException());
    } catch (Exception invalidClassName) {
      throw new IllegalArgumentException(invalidClassName);
    }
  }
示例#13
0
  @Parameters({"environment"})
  @BeforeClass
  public void setup(String environment) {

    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
    capabilities.setCapability("chrome.switches", Arrays.asList("--disable-extensions"));
    driver = new ChromeDriver(capabilities);
    driver.manage().window().maximize();
    wait = new WebDriverWait(driver, timeoutSeconds);
    String qa_username = "******";
    String qa_pwd = "Cres@2737";
    String prod_username = "******";
    String prod_pwd = "rajatgupta";
    js = (JavascriptExecutor) driver;
    if (environment.equalsIgnoreCase("QA")) {
      url = "http://mad-learn.com.embr.mobi/";
      driver.navigate().to(url + "Login.aspx");
      waitForElement("btnGo");
      login(qa_username, qa_pwd);
    } else {
      url = "http://platform.mad-learn.com/";
      driver.navigate().to(url + "Login.aspx");
      login(prod_username, prod_pwd);
    }
  }
示例#14
0
 /**
  * This method will grab the app path from the config and install the app on the attached iOS
  * device. Please make sure the appPath is accessible by the appium server.
  *
  * <p>Please make sure to set the app path using the setApp method.
  */
 public void installApp() {
   if (desired.getCapability("app") != null) {
     this.installApp(desired.getCapability("app").toString());
   } else {
     logger.error("You have to supply the app parameter before calling the install app.");
   }
 }
 protected WebDriver createChromeDriver() {
   DesiredCapabilities capabilities = createCommonCapabilities();
   ChromeOptions options = new ChromeOptions();
   options.addArguments("test-type");
   capabilities.setCapability(ChromeOptions.CAPABILITY, options);
   return new ChromeDriver(capabilities);
 }
示例#16
0
  private void setupForSauceLabsTesting() throws Exception {
    URL url =
        new URL(
            "http://"
                + authentication.getUsername()
                + ":"
                + authentication.getAccessKey()
                + "@ondemand.saucelabs.com:80/wd/hub");
    // DesiredCapabilities capabilities = new
    // DesiredCapabilities(BrowserType.SAFARI,"latest",Platform.MAC);
    DesiredCapabilities capabilities = new DesiredCapabilities();

    capabilities.setCapability(CapabilityType.BROWSER_NAME, browser);
    if (version != null) {
      capabilities.setCapability(CapabilityType.VERSION, version);
    }
    capabilities.setCapability(CapabilityType.PLATFORM, os);

    String methodName = this.name.getMethodName();
    String className = this.getClass().getSimpleName();
    capabilities.setCapability("name", className + "_" + methodName);

    this.driver = new RemoteWebDriver(url, capabilities);
    this.sessionId = (((RemoteWebDriver) driver).getSessionId()).toString();
  }
  @Test
  public void testRemoteWebDriver() {
    DesiredCapabilities cap = new DesiredCapabilities();
    cap.setPlatform(Platform.ANY);
    cap.setBrowserName("opera");
    RemoteWebDriver driver = null;
    try {
      driver = new RemoteWebDriver(new URL("http://192.168.1.176:4444/wd/hub"), cap);
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }
    // Navigate to Google using firefox
    driver.get("http://www.google.com");
    driver
        .findElement(By.name("q"))
        .sendKeys("selenium automation using grid on windows 8.1 with firefox machine");
    driver = (RemoteWebDriver) new Augmenter().augment(driver);
    File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    try {
      FileUtils.copyFile(srcFile, new File("remoteScreenshot.jpg"));
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    System.out.println(driver.getCurrentUrl());
    driver.quit();
  }
示例#18
0
  private static DesiredCapabilities getWebCaps(
      Method testMethod, Map<String, Object> customCapabilities) throws Exception {
    // String browserType = ConfigManager.getInstance().getProperty("browser");
    String browserType = "chrome";
    DesiredCapabilities capabilities = null;
    switch (browserType) {
      case "chrome":
        ChromeOptions options = createChromeOptions();
        capabilities = DesiredCapabilities.chrome();
        capabilities.setCapability(ChromeOptions.CAPABILITY, options);
        try {
          String os = null;
          String chromeDriver = "chromedriver";
          if (SystemUtils.IS_OS_MAC_OSX) {
            os = "mac";
          } else if (SystemUtils.IS_OS_LINUX) {
            os = "linux";
            chromeDriver += System.getProperty("sun.arch.data.model");
          } else if (SystemUtils.IS_OS_WINDOWS) {
            os = "windows";
          }
          System.setProperty("webdriver.chrome.driver", "src/resources/chromedriver");
        } catch (Exception e) {
          throw new Exception("Unable to find chromdriver");
        }
        break;
      case "safari":
        // capabilities = DesiredCapabilities.internetExplorer();
        break;
    }

    return capabilities;
  }
示例#19
0
  /**
   * Creates a new {@link RemoteWebDriver} instance to be used to run WebDriver tests using Sauce.
   *
   * @param username the Sauce username
   * @param key the Sauce access key
   * @param os the operating system to be used
   * @param browser the name of the browser to be used
   * @param browserVersion the version of the browser to be used
   * @param method the test method being executed
   * @throws Exception thrown if any errors occur in the creation of the WebDriver instance
   */
  @Parameters({"username", "key", "os", "browser", "browserVersion"})
  @BeforeMethod
  public void setUp(
      @Optional("ivolf") String username,
      @Optional("90e3bb89-c21d-4885-85cf-f25494db06ff") String key,
      @Optional("Windows 8.1") String os,
      @Optional("internet explorer") String browser,
      @Optional("11") String browserVersion,
      Method method)
      throws Exception {

    if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(key)) {
      authentication = new SauceOnDemandAuthentication(username, key);
    } else {
      authentication =
          new SauceOnDemandAuthentication("ivolf", "90e3bb89-c21d-4885-85cf-f25494db06ff");
    }

    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setBrowserName(browser);
    capabilities.setCapability("version", browserVersion);
    capabilities.setCapability("platform", os);
    capabilities.setCapability("name", method.getName());
    this.driver =
        new RemoteWebDriver(
            new URL(
                "http://"
                    + authentication.getUsername()
                    + ":"
                    + authentication.getAccessKey()
                    + "@ondemand.saucelabs.com:80/wd/hub"),
            capabilities);
  }
示例#20
0
  @Ignore({ANDROID, CHROME, HTMLUNIT, IE, IPHONE, OPERA, OPERA_MOBILE, PHANTOMJS, SAFARI})
  @NeedsLocalEnvironment
  @Test
  public void requiredProxyCapabilityShouldHavePriority() {
    ProxyServer desiredProxyServer = new ProxyServer();
    registerProxyTeardown(desiredProxyServer);

    Proxy desiredProxy = desiredProxyServer.asProxy();
    Proxy requiredProxy = proxyServer.asProxy();

    DesiredCapabilities desiredCaps = new DesiredCapabilities();
    desiredCaps.setCapability(PROXY, desiredProxy);
    DesiredCapabilities requiredCaps = new DesiredCapabilities();
    requiredCaps.setCapability(PROXY, requiredProxy);

    WebDriver driver =
        new WebDriverBuilder()
            .setDesiredCapabilities(desiredCaps)
            .setRequiredCapabilities(requiredCaps)
            .get();
    registerDriverTeardown(driver);

    driver.get(pages.simpleTestPage);

    assertFalse(
        "Desired proxy should not have been called.",
        desiredProxyServer.hasBeenCalled("simpleTest.html"));
    assertTrue(
        "Required proxy should have been called.", proxyServer.hasBeenCalled("simpleTest.html"));
  }
示例#21
0
  @Ignore(
      value = {ANDROID, IPHONE, OPERA_MOBILE, PHANTOMJS, SAFARI},
      reason = "Android/Iphone/PhantomJS - not tested," + "Opera mobile/Safari - not implemented")
  @NeedsLocalEnvironment
  @Test
  public void canConfigureProxyThroughPACFile() {
    WebServer helloServer =
        createSimpleHttpServer("<!DOCTYPE html><title>Hello</title><h3>Hello, world!</h3>");
    WebServer pacFileServer =
        createPacfileServer(
            Joiner.on('\n')
                .join(
                    "function FindProxyForURL(url, host) {",
                    "  return 'PROXY " + getHostAndPort(helloServer) + "';",
                    "}"));

    Proxy proxy = new Proxy();
    proxy.setProxyAutoconfigUrl("http://" + getHostAndPort(pacFileServer) + "/proxy.pac");

    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability(PROXY, proxy);

    WebDriver driver = new WebDriverBuilder().setDesiredCapabilities(caps).get();
    registerDriverTeardown(driver);

    driver.get(pages.mouseOverPage);
    assertEquals(
        "Should follow proxy to another server",
        "Hello, world!",
        driver.findElement(By.tagName("h3")).getText());
  }
示例#22
0
 private WebDriver startIEBrowser() {
   setIEDriverPath();
   DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
   ieCapabilities.setCapability(InternetExplorerDriver.IGNORE_ZOOM_SETTING, true);
   ieCapabilities.setCapability(
       InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
   return new InternetExplorerDriver(ieCapabilities);
 }
 @Override
 public WebDriver newInstance(DriverOptions driverOptions) {
   DesiredCapabilities caps = setupProxy(DesiredCapabilities.safari(), driverOptions);
   caps.merge(driverOptions.getCapabilities());
   SafariDriver driver = new SafariDriver(caps);
   setInitialWindowSize(driver, driverOptions);
   return driver;
 }
示例#24
0
 @Before
 public void setUp() throws Exception {
   DesiredCapabilities caps = DesiredCapabilities.chrome();
   caps.setCapability("platform", "Windows XP");
   caps.setCapability("version", "43.0");
   driver = new RemoteWebDriver(new URL(URL), caps);
   driver.get("https://www.op.fi/op?sym=" + stock + ".HSE&id=32455&srcpl=3");
 }
  @JavascriptEnabled
  @Ignore(
      value = {HTMLUNIT, IPHONE, SELENESE, OPERA, FIREFOX},
      reason = "This is an IE only tests")
  @NoDriverAfterTest
  @NeedsLocalEnvironment
  @Test
  public void testPersistentHoverCanBeTurnedOff() throws Exception {
    if (!hasInputDevices()) {
      return;
    }

    assumeTrue(TestUtilities.isInternetExplorer(driver));
    // Destroy the previous driver to make sure the hovering thread is
    // stopped.
    driver.quit();

    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability(ENABLE_PERSISTENT_HOVERING, false);
    WebDriverBuilder builder = new WebDriverBuilder().setDesiredCapabilities(caps);
    driver = builder.get();

    try {
      driver.get(pages.javascriptPage);
      // Move to a different element to make sure the mouse is not over the
      // element with id 'item1' (from a previous test).
      new Actions(driver).moveToElement(driver.findElement(By.id("keyUp"))).build().perform();
      WebElement element = driver.findElement(By.id("menu1"));

      final WebElement item = driver.findElement(By.id("item1"));
      assertEquals("", item.getText());

      ((JavascriptExecutor) driver)
          .executeScript("arguments[0].style.background = 'green'", element);
      new Actions(driver).moveToElement(element).build().perform();

      // Move the mouse somewhere - to make sure that the thread firing the events making
      // hover persistent is not active.
      Robot robot = new Robot();
      robot.mouseMove(50, 50);

      // Intentionally wait to make sure hover DOES NOT persist.
      Thread.sleep(1000);

      waitFor(
          new Callable<Boolean>() {

            public Boolean call() throws Exception {
              return item.getText().equals("");
            }
          });

      assertEquals("", item.getText());

    } finally {
      driver.quit();
    }
  }
示例#26
0
 @BeforeMethod
 public void before() {
   // Setting Proxy
   String myProxy = "proxy.corp.globant.com:3128";
   DesiredCapabilities capabilities = new DesiredCapabilities();
   capabilities.setCapability(CapabilityType.PROXY, new Proxy().setHttpProxy(myProxy));
   driver = new FirefoxDriver(capabilities);
   // Navigator parameterized from suite.
 }
示例#27
0
 public DesiredCapabilities getDesiredCapabilities() {
   DesiredCapabilities dc = new DesiredCapabilities();
   if (isFrameworkProperties) {
     dc.merge(getDCFrameworkProp());
   }
   dc.merge(getDCClient());
   dc.merge(getDCJvm());
   return dc;
 }
 protected WebDriver createRemoteDriver(String remote, String browser) {
   try {
     DesiredCapabilities capabilities = createCommonCapabilities();
     capabilities.setBrowserName(browser);
     return new RemoteWebDriver(new URL(remote), capabilities);
   } catch (MalformedURLException e) {
     throw new IllegalArgumentException("Invalid 'remote' parameter: " + remote, e);
   }
 }
示例#29
0
 @Test
 public void shouldBeAbleToEnableProfilerLog() {
   DesiredCapabilities caps = new DesiredCapabilities();
   caps.setCapability(ENABLE_PROFILING_CAPABILITY, true);
   WebDriverBuilder builder = new WebDriverBuilder().setDesiredCapabilities(caps);
   localDriver = builder.get();
   Set<String> logTypes = localDriver.manage().logs().getAvailableLogTypes();
   assertTrue("Profiler log should be enabled", logTypes.contains(LogType.PROFILER));
 }
 /** Add the common capability to custom capabilities */
 protected DesiredCapabilities addDefaultCapabilities(DesiredCapabilities desiredCapabilities) {
   desiredCapabilities.setCapability("takeScreenshot", true);
   desiredCapabilities.setCapability("hostName", hostName);
   // get the Jenkins build tag
   if (asJenkinsRun) {
     desiredCapabilities.setCapability("jenkinsBuildTag", jenkinsBuildTag);
   }
   return desiredCapabilities;
 }