/*
   * Factory method to return a WebDriver instance given the browser to hit
   *
   * @param browser : String representing the local browser to hit
   *
   * @param username : username for BASIC authentication on the page to test
   *
   * @param password : password for BASIC authentication on the page to test
   *
   * @return WebDriver instance
   */
  public static WebDriver getInstance(String browser, String username, String password) {

    if (webDriver != null) {
      return webDriver;
    }

    if (CHROME.equals(browser)) {
      webDriver = new ChromeDriver();

    } else if (FIREFOX.equals(browser)) {

      FirefoxProfile ffProfile = new FirefoxProfile();

      // Authenication Hack for Firefox
      if (username != null && password != null) {
        ffProfile.setPreference("network.http.phishy-userpass-length", 255);
      }

      webDriver = new FirefoxDriver(ffProfile);

    } else if (INTERNET_EXPLORER.equals(browser)) {
      webDriver = new InternetExplorerDriver();

    } else {

      // HTMLunit Check
      if (username != null && password != null) {
        webDriver = (HtmlUnitDriver) AuthenticatedHtmlUnitDriver.create(username, password);
      } else {
        webDriver = new HtmlUnitDriver(true);
      }
    }

    return webDriver;
  }
Example #2
0
  public void startProfile(FirefoxProfile profile, File profileDir, String... commandLineFlags)
      throws IOException {
    String profileAbsPath = profileDir.getAbsolutePath();
    setEnvironmentProperty("XRE_PROFILE_PATH", profileAbsPath);
    setEnvironmentProperty("MOZ_NO_REMOTE", "1");
    setEnvironmentProperty("MOZ_CRASHREPORTER_DISABLE", "1"); // Disable Breakpad
    setEnvironmentProperty(
        "NO_EM_RESTART", "1"); // Prevent the binary from detaching from the console

    if (isOnLinux() && (profile.enableNativeEvents() || profile.alwaysLoadNoFocusLib())) {
      modifyLinkLibraryPath(profileDir);
    }

    List<String> commands = new ArrayList<String>();
    commands.add(getExecutable().getPath());
    commands.addAll(Arrays.asList(commandLineFlags));
    ProcessBuilder builder = new ProcessBuilder(commands);
    builder.redirectErrorStream(true);
    builder.environment().putAll(getExtraEnv());
    getExecutable().setLibraryPath(builder, getExtraEnv());

    if (stream == null) {
      stream = getExecutable().getDefaultOutputStream();
    }

    startFirefoxProcess(builder);

    copeWithTheStrangenessOfTheMac(builder);

    startOutputWatcher();
  }
  private static WebDriver getFirefoxDriver() {

    FirefoxProfile profile = new FirefoxProfile();

    profile.setAcceptUntrustedCertificates(true);

    return new FirefoxDriver(profile);
  }
 @Test
 public void shouldInstallExtensionFromZip() throws IOException {
   FirefoxProfile profile = new FirefoxProfile();
   profile.addExtension(InProject.locate(FIREBUG_PATH));
   File profileDir = profile.layoutOnDisk();
   File extensionDir = new File(profileDir, "extensions/[email protected]");
   assertTrue(extensionDir.exists());
 }
 @Test
 public void shouldInstallExtensionUsingClasspath() throws IOException {
   FirefoxProfile profile = new FirefoxProfile();
   profile.addExtension(
       FirefoxProfileTest.class, "/org/openqa/selenium/testing/drivers/firebug-1.5.0-fx.xpi");
   File profileDir = profile.layoutOnDisk();
   File extensionDir = new File(profileDir, "extensions/[email protected]");
   assertTrue(extensionDir.exists());
 }
Example #6
0
 public void setup() throws InterruptedException {
   FirefoxProfile profile = new FirefoxProfile();
   profile.setAcceptUntrustedCertificates(true);
   profile.setAssumeUntrustedCertificateIssuer(false);
   driver = new FirefoxDriver(profile);
   // baseUrl = "http://www.uat-thetimes.co.uk/";
   driver.manage().deleteAllCookies();
   driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
 }
Example #7
0
  @Before
  public void setUp() {
    File file = new File("e:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
    FirefoxBinary binary = new FirefoxBinary(file);
    FirefoxProfile profile = new FirefoxProfile();
    profile.setPreference("browser.startup.homepage", "");

    driver = new FirefoxDriver(binary, profile);
  }
  @Test
  public void userPrefsArePreservedWhenConvertingToAndFromJson() throws IOException {
    profile.setPreference("browser.startup.homepage", "http://www.example.com");

    String json = profile.toJson();
    FirefoxProfile rebuilt = FirefoxProfile.fromJson(json);
    Preferences parsedPrefs = parseUserPrefs(rebuilt);

    assertEquals("http://www.example.com", parsedPrefs.getPreference("browser.startup.homepage"));
  }
  public static void main(String[] args) {

    FirefoxProfile profile = new FirefoxProfile();

    profile.setAssumeUntrustedCertificateIssuer(true);

    profile.setAcceptUntrustedCertificates(true);

    FirefoxDriver driver = new FirefoxDriver(profile);
  }
 @Test
 public void shouldInstallExtensionFromDirectory() throws IOException {
   FirefoxProfile profile = new FirefoxProfile();
   File extension = InProject.locate(FIREBUG_PATH);
   File unzippedExtension = FileHandler.unzip(new FileInputStream(extension));
   profile.addExtension(unzippedExtension);
   File profileDir = profile.layoutOnDisk();
   File extensionDir = new File(profileDir, "extensions/[email protected]");
   assertTrue(extensionDir.exists());
 }
 /*overriding setup method*/
 @SuppressWarnings("deprecation")
 @BeforeClass
 public void setUp() throws Exception {
   FirefoxProfile profile = new FirefoxProfile();
   profile.setEnableNativeEvents(true);
   driver = new FirefoxDriver(profile);
   baseUrl = "https://www.easyfinancial.com";
   driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
   Log.info(
       "Lets Begin the test!!--------------------------------------------------------------------");
 }
  @Test
  public void backslashedCharsArePreservedWhenConvertingToAndFromJson() throws IOException {
    String dir =
        "c:\\aaa\\bbb\\ccc\\ddd\\eee\\fff\\ggg\\hhh\\iii\\jjj\\kkk\\lll\\mmm\\nnn\\ooo\\ppp\\qqq\\rrr\\sss\\ttt\\uuu\\vvv\\www\\xxx\\yyy\\zzz";
    profile.setPreference("browser.download.dir", dir);

    String json = profile.toJson();
    FirefoxProfile rebuilt = FirefoxProfile.fromJson(json);
    Preferences parsedPrefs = parseUserPrefs(rebuilt);

    assertEquals(dir, parsedPrefs.getPreference("browser.download.dir"));
  }
Example #13
0
  public FirefoxProfile createCopy(int port) {
    File tmpDir = new File(System.getProperty("java.io.tmpdir"));
    File to = new File(tmpDir, "webdriver-" + System.currentTimeMillis());
    to.mkdirs();

    FileHandler.copyDir(profileDir, to);
    FirefoxProfile profile = new FirefoxProfile(to);
    profile.addAdditionalPreferences(additionalPrefs);
    profile.setPort(port);
    profile.updateUserPrefs();

    return profile;
  }
Example #14
0
 @BeforeMethod(alwaysRun = true)
 public void reportHeader(Method method) throws Throwable {
   // itc = ctx;
   Date date = new Date();
   SimpleDateFormat sdf = new SimpleDateFormat("dd_MMM_yyyy hh mm ss SSS");
   String formattedDate = sdf.format(date);
   ReportStampSupport.calculateTestCaseStartTime();
   if (browser.equalsIgnoreCase("firefox")) {
     ProfilesIni profile = new ProfilesIni();
     FirefoxProfile ffprofile = new FirefoxProfile();
     ffprofile.setEnableNativeEvents(true);
     webDriver = new FirefoxDriver(ffprofile);
   } else if (browser.equalsIgnoreCase("ie")) {
     File file = new File("Drivers\\IEDriverServer.exe");
     System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
     DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
     caps.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
     webDriver = new InternetExplorerDriver(caps);
     i = i + 1;
   } else if (browser.equalsIgnoreCase("chrome")) {
     System.setProperty("webdriver.chrome.driver", "Drivers\\chromedriver.exe");
     DesiredCapabilities capabilities = new DesiredCapabilities();
     ChromeOptions options = new ChromeOptions();
     options.addArguments("test-type");
     capabilities.setCapability(ChromeOptions.CAPABILITY, options);
     webDriver = new ChromeDriver(capabilities);
   } else if (browser.equalsIgnoreCase("iphone")) {
     Iosdriver.resetApp();
   } else if (browser.equalsIgnoreCase("android")) {
     AndroidDriver2.resetApp();
   }
   flag = false;
   if ((!(browser.equalsIgnoreCase("Android"))) & (!(browser.equalsIgnoreCase("iPhone")))) {
     driver = /*new EventFiringWebDriver*/ (webDriver);
     /*ActionEngineSupport myListener = new ActionEngineSupport();
     driver.register(myListener);*/
     driver.manage().window().maximize();
     driver.manage().timeouts().implicitlyWait(3, TimeUnit.MINUTES);
     driver.get(url);
   }
   HtmlReportSupport.tc_name = method.getName().toString() + "-" + formattedDate;
   String[] ts_Name = this.getClass().getName().toString().split("\\.");
   HtmlReportSupport.packageName = ts_Name[0] + "." + ts_Name[1] + "." + ts_Name[2];
   HtmlReportSupport.testHeader(HtmlReportSupport.tc_name, browser);
   stepNum = 0;
   PassNum = 0;
   FailNum = 0;
   testName = method.getName();
   logger.info("Current Test : " + testName);
 }
  @Test
  public void shouldAllowUserToSuccessfullyOverrideTheHomePage() {
    FirefoxProfile profile = new FirefoxProfile();
    profile.setPreference("browser.startup.page", "1");
    profile.setPreference("browser.startup.homepage", pages.javascriptPage);

    final WebDriver driver2 = newFirefoxDriver(profile);

    try {
      new WebDriverWait(driver2, 30).until(urlToBe(pages.javascriptPage));
    } finally {
      driver2.quit();
    }
  }
  @Test
  public void shouldBeAbleToStartFromProfileWithLogFileSetToStdout() throws IOException {
    FirefoxProfile profile = new FirefoxProfile();

    profile.setPreference("webdriver.log.file", "/dev/stdout");

    try {
      WebDriver secondDriver = newFirefoxDriver(profile);
      secondDriver.quit();
    } catch (Exception e) {
      e.printStackTrace();
      fail("Expected driver to be created successfully");
    }
  }
  /**
   * private method to load the Firefox Driver
   *
   * @param loadRemote
   */
  private static RemoteWebDriver loadFireFoxDriver(boolean loadRemote) throws Exception {

    log.info("Entering BrowserFactory class loadFireFoxDriver...");
    String loadffProfile = CommonUtils.readFromConfig("loadffProfile");

    RemoteWebDriver remoteDriver = null;

    FirefoxProfile profile = null;

    if ("true".equalsIgnoreCase(loadffProfile)) {
      String profilePath = CommonUtils.readFromConfig("FIREFOXPROFILEDIR");
      File profileDir = new File(profilePath);
      profile = new FirefoxProfile(profileDir);
      profile.setAcceptUntrustedCertificates(false);
    }

    DesiredCapabilities capabilities = DesiredCapabilities.firefox();
    if (loadRemote) {

      log.info("loading firefox driver in remote");
      log.info("Loading  Remote Run URL " + CommonUtils.readFromConfig("RemoteWebAppUrl"));
      URL url = new URL(CommonUtils.readFromConfig("RemoteWebAppUrl"));

      if ("true".equalsIgnoreCase(loadffProfile)) {
        log.info("loading firefox profile in remote");
        capabilities.setCapability(FirefoxDriver.PROFILE, profile);
        log.info("loading firefox profile in remote sucessful");
      }
      remoteDriver = new RemoteWebDriver(url, capabilities);
      log.info("loading firefox driver in remote successful");

    } else {
      if ("true".equalsIgnoreCase(loadffProfile)) {
        log.info("loading firefox driver with profile");

        remoteDriver = new FirefoxDriver(profile);
        log.info("loading firefox driver loadffProfile profile successfully");
      } else {
        log.info("loading firefox driver without profile");
        remoteDriver = new FirefoxDriver();

        log.info("loading firefox driver without profile successfully");
      }
    }

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

    return remoteDriver;
  }
  private WebDriver createWebDriver(TestName testName) throws IOException {
    String browser = System.getenv("BROWSER");
    if (browser == null) browser = "firefox";
    browser = browser.toLowerCase(Locale.ENGLISH);

    switch (browser) {
      case "firefox":
        FirefoxProfile profile = new FirefoxProfile();
        profile.setPreference(LANGUAGE_SELECTOR, "en");

        return new FirefoxDriver(profile);
      case "ie":
      case "iexplore":
      case "iexplorer":
        return new InternetExplorerDriver();
      case "chrome":
        Map<String, String> prefs = new HashMap<String, String>();
        prefs.put(LANGUAGE_SELECTOR, "en");
        ChromeOptions options = new ChromeOptions();
        options.setExperimentalOption("prefs", prefs);

        return new ChromeDriver(options);
      case "safari":
        return new SafariDriver();
      case "htmlunit":
        return new HtmlUnitDriver(true);
      case "saucelabs":
      case "saucelabs-firefox":
        DesiredCapabilities caps = DesiredCapabilities.firefox();
        caps.setCapability("version", "29");
        caps.setCapability("platform", "Windows 7");
        caps.setCapability("name", testName.get());

        // if running inside Jenkins, expose build ID
        String tag = System.getenv("BUILD_TAG");
        if (tag != null) caps.setCapability("build", tag);

        return new SauceLabsConnection().createWebDriver(caps);
      case "phantomjs":
        DesiredCapabilities capabilities = DesiredCapabilities.phantomjs();
        capabilities.setCapability(LANGUAGE_SELECTOR, "en");
        capabilities.setCapability(LANGUAGE_SELECTOR_PHANTOMJS, "en");
        return new PhantomJSDriver(capabilities);

      default:
        throw new Error("Unrecognized browser type: " + browser);
    }
  }
Example #19
0
  @Ignore(FIREFOX)
  public void testANewProfileShouldAllowSettingAdditionalParameters() {
    FirefoxProfile profile = new FirefoxProfile();
    profile.setPreference("browser.startup.homepage", formPage);

    try {
      WebDriver secondDriver = new FirefoxDriver(profile);
      String title = secondDriver.getTitle();
      secondDriver.quit();

      assertThat(title, is("We Leave From Here"));
    } catch (Exception e) {
      e.printStackTrace();
      fail("Expected driver to be created succesfully");
    }
  }
Example #20
0
  private static FirefoxProfile extractProfile(
      Capabilities desiredCapabilities, Capabilities requiredCapabilities) {

    FirefoxProfile profile = null;
    Object raw = null;
    if (desiredCapabilities != null && desiredCapabilities.getCapability(PROFILE) != null) {
      raw = desiredCapabilities.getCapability(PROFILE);
    }
    if (requiredCapabilities != null && requiredCapabilities.getCapability(PROFILE) != null) {
      raw = requiredCapabilities.getCapability(PROFILE);
    }
    if (raw != null) {
      if (raw instanceof FirefoxProfile) {
        profile = (FirefoxProfile) raw;
      } else if (raw instanceof String) {
        try {
          profile = FirefoxProfile.fromJson((String) raw);
        } catch (IOException e) {
          throw new WebDriverException(e);
        }
      }
    }
    profile = getProfile(profile);

    populateProfile(profile, desiredCapabilities);
    populateProfile(profile, requiredCapabilities);

    return profile;
  }
 @Test
 public void proxyAutodetect() throws Exception {
   profile.setProxyPreferences(new Proxy().setAutodetect(true));
   List<String> prefLines = readGeneratedProperties(profile);
   String prefs = new ArrayList<String>(prefLines).toString();
   assertThat(prefs, containsString("network.proxy.type\", 4"));
 }
 @Test
 public void proxyAutoconfigUrl() throws Exception {
   profile.setProxyPreferences(new Proxy().setProxyAutoconfigUrl("http://foo/bar.pac"));
   List<String> prefLines = readGeneratedProperties(profile);
   String prefs = new ArrayList<String>(prefLines).toString();
   assertThat(prefs, containsString("network.proxy.autoconfig_url\", \"http://foo/bar.pac\""));
   assertThat(prefs, containsString("network.proxy.type\", 2"));
 }
  @Test
  public void shouldBeAbleToStartFromProfileWithLogFileSet() throws IOException {
    FirefoxProfile profile = new FirefoxProfile();
    File logFile = File.createTempFile("test", "firefox.log");
    logFile.deleteOnExit();

    profile.setPreference("webdriver.log.file", logFile.getAbsolutePath());

    try {
      WebDriver secondDriver = newFirefoxDriver(profile);
      assertTrue("log file should exist", logFile.exists());
      secondDriver.quit();
    } catch (Exception e) {
      e.printStackTrace();
      fail("Expected driver to be created successfully");
    }
  }
Example #24
0
  public FirefoxProfile createCopy(int port) {
    File to = TemporaryFilesystem.createTempDir("webdriver", "profilecopy");

    try {
      FileHandler.copy(profileDir, to);
    } catch (IOException e) {
      throw new WebDriverException(
          "Cannot create copy of profile " + profileDir.getAbsolutePath(), e);
    }
    FirefoxProfile profile = new FirefoxProfile(to);
    additionalPrefs.addTo(profile);
    profile.setPort(port);
    profile.setEnableNativeEvents(enableNativeEvents);
    profile.updateUserPrefs();

    return profile;
  }
  @Test
  public void shouldConvertItselfIntoAMeaningfulRepresentation() throws IOException {
    FirefoxProfile profile = new FirefoxProfile();
    profile.setPreference("i.like.cheese", true);

    String json = profile.toJson();

    assertNotNull(json);

    File dir = TemporaryFilesystem.getDefaultTmpFS().createTempDir("webdriver", "duplicated");
    new Zip().unzip(json, dir);

    File prefs = new File(dir, "user.js");
    assertTrue(prefs.exists());

    assertTrue(FileHandler.readAsString(prefs).contains("i.like.cheese"));
  }
 static {
   _firefoxProfile.setPreference("browser.download.dir", TestPropsValues.OUTPUT_DIR);
   _firefoxProfile.setPreference("browser.download.folderList", 2);
   _firefoxProfile.setPreference("browser.download.manager.showWhenStarting", false);
   _firefoxProfile.setPreference("browser.download.useDownloadDir", true);
   _firefoxProfile.setPreference("browser.helperApps.alwaysAsk.force", false);
   _firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/zip");
   _firefoxProfile.setPreference("dom.max_chrome_script_run_time", 300);
   _firefoxProfile.setPreference("dom.max_script_run_time", 300);
 }
  // public static WebDriver getInstance(Browser browser, String username, String password) {
  public static WebDriver getDriver() {

    if (webDriver != null) {
      return webDriver;
    }

    Browser browser = new Browser();
    browser.setName(get(BROWSER_NAME_KEY));

    if (CHROME.equals(browser.getName())) {
      webDriver = new ChromeDriver();
      logger.info("ChromeDriver has created");
    } else if (FIREFOX.equals(browser.getName())) {
      FirefoxProfile ffProfile = new FirefoxProfile();

      // Authenication Hack for Firefox
      //            if (username != null && password != null) {
      //                ffProfile.setPreference("network.http.phishy-userpass-length", 255);
      //            }
      ffProfile.setPreference("network.http.phishy-userpass-length", 255);

      try {
        webDriver = new FirefoxDriver();
      } catch (WebDriverException wdex) {
        // TODO ������� ���� � ���������
        FirefoxBinary binary =
            new FirefoxBinary(new File("D:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"));
        webDriver = new FirefoxDriver(binary, new FirefoxProfile());

        // driver = new InternetExplorerDriver();
      } catch (Throwable th) {
        th.printStackTrace();
      }

      logger.info("FirefoxDriver has created");
    } else if (INTERNET_EXPLORER.equals(browser.getName())) {
      webDriver = new InternetExplorerDriver();
      logger.info("InternetExplorerDriver has created");
    } else {
      webDriver = new ChromeDriver();
      logger.info("ChromeDriver has created");
    }

    return webDriver;
  }
Example #28
0
  public void clean(FirefoxProfile profile, File profileDir) throws IOException {
    startProfile(profile, profileDir, "-silent");
    try {
      waitFor();
    } catch (InterruptedException e) {
      throw new WebDriverException(e);
    }

    if (Platform.getCurrent().is(Platform.WINDOWS)) {
      while (profile.isRunning(profileDir)) {
        sleep(500);
      }

      do {
        sleep(500);
      } while (profile.isRunning(profileDir));
    }
  }
Example #29
0
 public void quit() {
   if (connection != null) {
     connection.quit();
     connection = null;
   }
   if (profile != null) {
     profile.cleanTemporaryModel();
   }
 }
  private static Capabilities getCapabilities(String driverType) {
    DesiredCapabilities result = new DesiredCapabilities();

    switch (driverType) {
      case BrowserType.FIREFOX:
        result = DesiredCapabilities.firefox();
        FirefoxProfile profile =
            (FirefoxProfile) ConfigLoader.config().getProperty("firefox.profile");
        if (profile == null) {
          profile = new FirefoxProfile();
          if (ConfigLoader.config().getBoolean("webdriver.accept.java", true)) {
            profile.setPreference("plugin.state.java", 2);
          }
          if (ConfigLoader.config().getBoolean("webdriver.accept.ssl", true)) {
            profile.setAcceptUntrustedCertificates(true);
            profile.setAssumeUntrustedCertificateIssuer(true);
          }
          if (ConfigLoader.config().getBoolean("webdriver.autodownload", true)) {
            profile.setPreference("browser.download.folderList", 2);
            profile.setPreference("browser.helperApps.alwaysAsk.force", false);
            profile.setPreference("browser.download.manager.showWhenStarting", false);
            profile.setPreference("browser.helperApps.neverAsk.saveToDisk", autoDownloadFiles());
          }
        }
        result.setCapability(FirefoxDriver.PROFILE, profile);
        result.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
        break;
      case BrowserType.IE:
        result = DesiredCapabilities.internetExplorer();
        result.setCapability("ignoreProtectedModeSettings", true);
        result.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
        break;
      case BrowserType.CHROME:
        result = DesiredCapabilities.chrome();
        ChromeOptions chromOptions = new ChromeOptions();
        //
        //	chromOptions.setExperimentalOption("excludeSwitches",Lists.newArrayList("ignore-certificate-errors"));
        chromOptions.addArguments("chrome.switches", "--disable-extensions");
        result.setCapability(ChromeOptions.CAPABILITY, chromOptions);
        result.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
        break;
      default:
        result = new DesiredCapabilities(driverType, "", Platform.ANY);
        break;
    }
    String proxy = ConfigLoader.config().getString("webdriver.proxy");
    if (!Strings.isNullOrEmpty(proxy)) {
      Proxy p = new Proxy();
      p.setHttpProxy(proxy).setSslProxy(proxy);
      result.setCapability(CapabilityType.PROXY, p);
      log.info("Using proxy {}", proxy);
    }
    return concatenate(result, capabilities);
  }