public static bool TestLoad(SafariDriver browser, string webPage) { bool result = false; browser = new SafariDriver(); try { result = SeleniumUtils.TestLoad(browser, webPage); } finally { browser.Quit(); } return(result); }
/// <summary> /// Instantiates a web driver singleton that drives the selected browser through pages /// </summary> public static void Initialize(Browser type) { switch (type) { case Browser.Chrome: { Instance = new ChromeDriver("C:/Selenium/Chrome_Driver/"); break; } case Browser.Firefox: { Instance = new FirefoxDriver(); break; } case Browser.IE: { var o = new InternetExplorerOptions { RequireWindowFocus = true, EnablePersistentHover = false }; Instance = new InternetExplorerDriver("C:/Selenium/IE_Driver/", o); break; } case Browser.Safari: { Instance = new SafariDriver(); break; } case Browser.Opera: { Instance = new OperaDriver("C:/Selenium/Opera_Driver/"); break; } } Instance.Manage().Window.Maximize(); TurnOnWait(); }
public ReturnModel TestStartSafari() { ReturnModel testOk = new ReturnModel(); try { IWebDriver driver = new SafariDriver(); string link = @"http://www.n11.com/"; driver.Navigate().GoToUrl(link); //LOGİN KISMI //driver.FindElement(By.ClassName("btnSignIn")).Click(); //driver.FindElement(By.Id("email")).SendKeys("*****@*****.**"); //driver.FindElement(By.Id("password")).SendKeys("tutkutektaspassword"); //driver.FindElement(By.Id("loginButton")).Click(); //Arama sonucunda 2. sayfa seçilme işlemi ve rastgele bir ürünü seçme işlemi driver.FindElement(By.Id("searchData")).SendKeys("Bilgisayar"); driver.FindElement(By.ClassName("searchBtn")).Click(); driver.FindElement(By.XPath(".//*[@id='contentListing']/div/div/div[2]/div[4]/a[2]")).Click();//Eğer burada hata veriyor ise div[4] olan kısım div[3] yapın //Yukardaki kodda .XPATH ile tüm sayfada döndük id si contentListing içine girip en alttaki 2. seçeneği seçtirdik. //Bunları yaparken contentListing içinde tek div var ona girdik sonra o divin içindede tek div var //3. kısımda 2 tane div var biz ortadaki olan div[2] yi seçtik. Son kısımda 4 div var. en altta sayfa geçişlerini sağlayan 4.Divi seçtik //4.Divin içindende sayfa adlar 'a' ile sıralanmış o yüzden a2 yi seçtik. driver.FindElement(By.XPath(".//*[@id='p-402919973']/div[1]/a")).Click(); //Son Kısım Sepet işlemleri driver.FindElement(By.ClassName("btnAddBasket")).Click(); driver.FindElement(By.ClassName("iconBasket")).Click(); driver.FindElement(By.ClassName("spinnerArrow")).Click(); driver.FindElement(By.ClassName("svgIcon_trash")).Click(); testOk.IsSuccess = true; } catch (Exception ex) { testOk.IsSuccess = false; testOk.ErrorMessage = "Hata : " + ex.Message; } return(testOk); }
public override IWebDriver LocalDriver(object options) { SafariDriverService driverService = null; IWebDriver driver; try { driverService = GetDefaultService <SafariDriverService>(); var safariOptions = options == null?SafariOptions() : (SafariOptions)options; driver = new SafariDriver(driverService, safariOptions, Timeout); } catch { driverService?.Dispose(); throw; } return(driver); }
public void LogInTest() { safari = new SafariDriver(); safari.Navigate().GoToUrl("https://www.bahn.de/p/view/meinebahn/login.shtml"); safari.FindElement(By.Id("Benutzername")).SendKeys("gaga231772"); safari.FindElement(By.Id("Passwort")).SendKeys("gaga2317"); safari.FindElement(By.ClassName("btn")).SendKeys(Keys.Enter); var username = safari.FindElementByClassName("nobttommargin").FindElement(By.TagName("span")).GetProperty("title"); bool isUsername = false; if (username == "Evgenij Bondarik") { isUsername = true; } else { isUsername = false; } Assert.IsTrue(isUsername); }
private RemoteWebDriver GetBrowserDriverToRunInBackground(BrowserEnum browser) { switch (browser) { case BrowserEnum.Firefox: var firefoxService = FirefoxDriverService.CreateDefaultService(); firefoxService.HideCommandPromptWindow = true; var firefoxDriver = new FirefoxDriver(firefoxService); return(firefoxDriver); case BrowserEnum.Chrome: var chromeService = ChromeDriverService.CreateDefaultService(); chromeService.HideCommandPromptWindow = true; var chromeDriver = new ChromeDriver(chromeService); return(chromeDriver); case BrowserEnum.InternetExplorer: var internetExplorerService = InternetExplorerDriverService.CreateDefaultService(); internetExplorerService.HideCommandPromptWindow = true; var internetExplorerDriver = new InternetExplorerDriver(internetExplorerService); return(internetExplorerDriver); case BrowserEnum.Edge: var edgeService = EdgeDriverService.CreateDefaultService(); edgeService.HideCommandPromptWindow = true; var options = new EdgeOptions(); var edgeDriver = new EdgeDriver(edgeService, options); return(edgeDriver); case BrowserEnum.Safari: var safariService = SafariDriverService.CreateDefaultService(); safariService.HideCommandPromptWindow = true; var safariDriver = new SafariDriver(safariService); return(safariDriver); default: throw new Exception("Browser not found for provided enum value."); } }
public void TestSafari() { IWebDriver driver = null; try { driver = new SafariDriver(); driver.Url = "http://www.softpost.org"; driver.Manage().Window.Maximize(); driver.Navigate(); } catch (Exception e) { Console.WriteLine("Exception ....*********" + e.ToString()); } finally { Thread.Sleep(2000); driver.Close(); driver.Quit(); } }
public static void Start(BrowserType browserType) { IWebDriver driver = default; switch (browserType) { case BrowserType.Chrome: new DriverManager().SetUpDriver(new ChromeConfig()); driver = new ChromeDriver(); break; case BrowserType.Edge: new DriverManager().SetUpDriver(new EdgeConfig()); driver = new EdgeDriver(); break; case BrowserType.Firefox: new DriverManager().SetUpDriver(new FirefoxConfig()); driver = new FirefoxDriver(); break; case BrowserType.Safari: driver = new SafariDriver(); break; default: throw new ArgumentOutOfRangeException( nameof(browserType), browserType, $"{nameof(browserType)} Not Supported"); } PreviousBrowserType.Value = browserType; WrappedDriver.Value = driver; driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(Configuration.ConfigurationService.Instance.GetTimeoutSettings().PageLoadTimeout); driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(Configuration.ConfigurationService.Instance.GetTimeoutSettings().JavascriptTimeout); }
public static IWebDriver GetWebDriver(Browser browser) { IWebDriver driver; switch (browser) { case Browser.Chrome: new DriverManager().SetUpDriver(new ChromeConfig()); driver = new ChromeDriver(GetChromeOptions()); break; case Browser.Edge: new DriverManager().SetUpDriver(new EdgeConfig()); driver = new EdgeDriver(GetEdgeOptions()); break; case Browser.Firefox: new DriverManager().SetUpDriver(new FirefoxConfig()); driver = new FirefoxDriver(GetFirefoxOptions()); break; case Browser.IE: new DriverManager().SetUpDriver(new InternetExplorerConfig()); driver = new InternetExplorerDriver(GetInternetExplorerOptions()); break; case Browser.Safari: driver = new SafariDriver(GetSafariOptions()); break; default: Console.WriteLine($"Browser '{browser.ToDescription()}' is not supported"); throw new ArgumentOutOfRangeException($"Browser '{browser.ToDescription()}' is not supported"); } return(driver); }
public IWebDriver InitializeDriver(Enumerations.Driver driverType) { IWebDriver _driver = null; switch (driverType) { case Enumerations.Driver.Chrome: _driver = new ChromeDriver(@"External"); break; case Enumerations.Driver.InternetExplorer: _driver = new InternetExplorerDriver(@"External"); break; case Enumerations.Driver.Safari: _driver = new SafariDriver(@"External"); break; case Enumerations.Driver.FireFox: _driver = new FirefoxDriver(); break; } return(_driver); }
/// <summary> /// Prepares RemoteWebDriver basing on configuration supplied /// </summary> /// <param name="browserConfig"></param> /// <returns></returns> public static RemoteWebDriver GetDriver(Dictionary <String, String> browserConfig) { RemoteWebDriver driver = null; //exePath get the assembly location it used for know the exe drivers location for other than FF browser string exePath = Directory.GetParent(Assembly.GetEntryAssembly().Location).ToString(); try { if (browserConfig["target"] == "local") { if (browserConfig["browser"] == "Firefox") { driver = new FirefoxDriver(); } else if (browserConfig["browser"] == "IE") { //TODO: Get rid of Framework Path driver = new InternetExplorerDriver(exePath); //DesiredCapabilities capabilities = new DesiredCapabilities(); //capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); //driver = new InternetExplorerDriver(capabilities); } else if (browserConfig["browser"] == "Chrome") { ChromeOptions options = new ChromeOptions(); //options.AddArgument("no-sandbox"); options.AddArguments("chrome.switches", "--disable-extensions"); driver = new ChromeDriver(exePath, options); } else if (browserConfig["browser"] == "PhantomJS") { PhantomJSDriverService service = PhantomJSDriverService.CreateDefaultService(exePath); service.IgnoreSslErrors = true; driver = new PhantomJSDriver(service); } else if (browserConfig["browser"] == "MSEdge") { EdgeOptions options = new EdgeOptions(); options.PageLoadStrategy = EdgePageLoadStrategy.Eager; driver = new EdgeDriver(exePath, options); } else if (browserConfig["browser"] == "Safari") { driver = new SafariDriver(); } driver.Manage().Window.Maximize(); //driver.Manage().Window.Size = new Size(680,1000); driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5)); } else if (browserConfig["target"] == "browserstack") { DesiredCapabilities desiredCapabilities = new DesiredCapabilities(); String[] bsCredentials = ConfigurationManager.AppSettings.Get("BrowserStackCredentials").Split(new Char[] { ':' }); desiredCapabilities.SetCapability("browserstack.user", bsCredentials[0].Trim()); desiredCapabilities.SetCapability("browserstack.key", bsCredentials[1].Trim()); foreach (KeyValuePair <String, String> capability in browserConfig) { if (capability.Key != "target") { desiredCapabilities.SetCapability(capability.Key, capability.Value); } } driver = new RemoteWebDriver(new Uri("http://hub.browserstack.com/wd/hub/"), desiredCapabilities); driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10)); } driver.Manage().Cookies.DeleteAllCookies(); } catch (Exception ex) { // this is not a good idea to suppress // we should better handle the situation where RemoteWebDriver initiation fail, // should not let entire execution halt } return(driver); }
public void TestSafari() { driver = new SafariDriver(); OpenPage <GoogleHomePage>("http://www.google.com/"); driver.Quit(); }
/// <summary> /// Creates the web driver. /// </summary> /// <param name="browserType">Type of the browser.</param> /// <param name="browserFactoryConfiguration">The browser factory configuration.</param> /// <returns>The created web driver.</returns> /// <exception cref="System.InvalidOperationException">Thrown if the browser is not supported.</exception> internal static IWebDriver CreateWebDriver(BrowserType browserType, BrowserFactoryConfigurationElement browserFactoryConfiguration) { IWebDriver driver; if (!RemoteDriverExists(browserFactoryConfiguration.Settings, browserType, out driver)) { switch (browserType) { case BrowserType.IE: var explorerOptions = new InternetExplorerOptions { EnsureCleanSession = browserFactoryConfiguration.EnsureCleanSession }; var internetExplorerDriverService = InternetExplorerDriverService.CreateDefaultService(); internetExplorerDriverService.HideCommandPromptWindow = true; driver = new InternetExplorerDriver(internetExplorerDriverService, explorerOptions); break; case BrowserType.FireFox: driver = GetFireFoxDriver(browserFactoryConfiguration); break; case BrowserType.Chrome: var chromeOptions = new ChromeOptions { LeaveBrowserRunning = false }; var chromeDriverService = ChromeDriverService.CreateDefaultService(); chromeDriverService.HideCommandPromptWindow = true; if (browserFactoryConfiguration.EnsureCleanSession) { chromeOptions.AddArgument("--incognito"); } driver = new ChromeDriver(chromeDriverService, chromeOptions); break; case BrowserType.PhantomJS: var phantomJsDriverService = PhantomJSDriverService.CreateDefaultService(); phantomJsDriverService.HideCommandPromptWindow = true; driver = new PhantomJSDriver(phantomJsDriverService); break; case BrowserType.Safari: driver = new SafariDriver(); break; default: throw new InvalidOperationException(string.Format("Browser type '{0}' is not supported in Selenium local mode. Did you mean to configure a remote driver?", browserType)); } } // Set Driver Settings var managementSettings = driver.Manage(); // Set timeouts managementSettings.Timeouts() .ImplicitlyWait(browserFactoryConfiguration.ElementLocateTimeout) .SetPageLoadTimeout(browserFactoryConfiguration.PageLoadTimeout); // Maximize window managementSettings.Window.Maximize(); return(driver); }
private static IWebDriver InitializeDriverRegularMode(BrowserConfiguration executionConfiguration, OpenQA.Selenium.Proxy webDriverProxy) { IWebDriver wrappedWebDriver; switch (executionConfiguration.BrowserType) { case BrowserType.Chrome: new DriverManager().SetUpDriver(new ChromeConfig(), VersionResolveStrategy.MatchingBrowser); var chromeDriverService = ChromeDriverService.CreateDefaultService(); chromeDriverService.SuppressInitialDiagnosticInformation = true; chromeDriverService.EnableVerboseLogging = false; var chromeOptions = executionConfiguration.DriverOptions; chromeOptions.AddArguments("--log-level=3"); Port = GetFreeTcpPort(); chromeDriverService.Port = Port; DebuggerPort = GetFreeTcpPort(); if (executionConfiguration.IsLighthouseEnabled) { chromeOptions.AddArgument("--remote-debugging-address=0.0.0.0"); chromeOptions.AddArgument($"--remote-debugging-port={DebuggerPort}"); ////ProcessProvider.StartCLIProcess($"chrome-debug --port={Port}"); ////chromeOptions.DebuggerAddress = $"127.0.0.1:{Port}"; } if (ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath != null) { string packedExtensionPath = ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath.NormalizeAppPath(); Logger.LogInformation($"Trying to load packed extension from path: {packedExtensionPath}"); chromeOptions.AddExtension(ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath); } if (ConfigurationService.GetSection <WebSettings>().ExecutionSettings.UnpackedExtensionPath != null) { string unpackedExtensionPath = ConfigurationService.GetSection <WebSettings>().ExecutionSettings.UnpackedExtensionPath.NormalizeAppPath(); Logger.LogInformation($"Trying to load unpacked extension from path: {unpackedExtensionPath}"); chromeOptions.AddArguments($"load-extension={unpackedExtensionPath}"); } if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled && !executionConfiguration.IsLighthouseEnabled) { chromeOptions.Proxy = webDriverProxy; } chromeOptions.AddArgument("hide-scrollbars"); chromeOptions.SetLoggingPreference(LogType.Browser, LogLevel.All); chromeOptions.SetLoggingPreference("performance", LogLevel.All); wrappedWebDriver = new ChromeDriver(chromeDriverService, chromeOptions); break; case BrowserType.ChromeHeadless: new DriverManager().SetUpDriver(new ChromeConfig(), VersionResolveStrategy.MatchingBrowser); var chromeHeadlessDriverService = ChromeDriverService.CreateDefaultService(); chromeHeadlessDriverService.SuppressInitialDiagnosticInformation = true; Port = GetFreeTcpPort(); chromeHeadlessDriverService.Port = Port; var chromeHeadlessOptions = executionConfiguration.DriverOptions; chromeHeadlessOptions.AddArguments("--headless"); chromeHeadlessOptions.AddArguments("--log-level=3"); chromeHeadlessOptions.AddArguments("--test-type"); chromeHeadlessOptions.AddArguments("--disable-infobars"); chromeHeadlessOptions.AddArguments("--allow-no-sandbox-job"); chromeHeadlessOptions.AddArguments("--ignore-certificate-errors"); chromeHeadlessOptions.AddArguments("--disable-gpu"); chromeHeadlessOptions.AddArguments("--no-sandbox"); chromeHeadlessOptions.AddUserProfilePreference("credentials_enable_service", false); chromeHeadlessOptions.AddUserProfilePreference("profile.password_manager_enabled", false); chromeHeadlessOptions.AddArgument("hide-scrollbars"); chromeHeadlessOptions.UnhandledPromptBehavior = UnhandledPromptBehavior.Dismiss; Port = GetFreeTcpPort(); chromeHeadlessDriverService.Port = Port; DebuggerPort = GetFreeTcpPort(); if (executionConfiguration.IsLighthouseEnabled) { chromeHeadlessOptions.AddArgument("--remote-debugging-address=0.0.0.0"); chromeHeadlessOptions.AddArgument($"--remote-debugging-port={DebuggerPort}"); } if (ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath != null) { string packedExtensionPath = ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath.NormalizeAppPath(); Logger.LogInformation($"Trying to load packed extension from path: {packedExtensionPath}"); chromeHeadlessOptions.AddExtension(ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath); } if (ConfigurationService.GetSection <WebSettings>().ExecutionSettings.UnpackedExtensionPath != null) { string unpackedExtensionPath = ConfigurationService.GetSection <WebSettings>().ExecutionSettings.UnpackedExtensionPath.NormalizeAppPath(); Logger.LogInformation($"Trying to load unpacked extension from path: {unpackedExtensionPath}"); chromeHeadlessOptions.AddArguments($"load-extension={unpackedExtensionPath}"); } if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled) { chromeHeadlessOptions.Proxy = webDriverProxy; } chromeHeadlessOptions.SetLoggingPreference(LogType.Browser, LogLevel.All); chromeHeadlessOptions.SetLoggingPreference("performance", LogLevel.All); wrappedWebDriver = new ChromeDriver(chromeHeadlessDriverService, chromeHeadlessOptions); break; case BrowserType.Firefox: new DriverManager().SetUpDriver(new FirefoxConfig(), VersionResolveStrategy.Latest); Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); var firefoxOptions = executionConfiguration.DriverOptions; firefoxOptions.AddAdditionalOption("acceptInsecureCerts", true); if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled) { firefoxOptions.Proxy = webDriverProxy; } var firefoxService = FirefoxDriverService.CreateDefaultService(); firefoxService.SuppressInitialDiagnosticInformation = true; firefoxService.Port = GetFreeTcpPort(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { if (File.Exists(@"C:\Program Files\Mozilla Firefox\firefox.exe")) { firefoxService.FirefoxBinaryPath = @"C:\Program Files\Mozilla Firefox\firefox.exe"; } else { firefoxService.FirefoxBinaryPath = @"C:\Program Files (x86)\Mozilla Firefox\firefox.exe"; } // TODO: Anton(15.12.2019): Add option to set the path via environment variable. } var firefoxProfile = ServicesCollection.Current.Resolve <FirefoxProfile>(executionConfiguration.ClassFullName); if (firefoxProfile == null) { firefoxOptions.Profile = new FirefoxProfile(_driverExecutablePath); ServicesCollection.Current.RegisterInstance(firefoxOptions.Profile, executionConfiguration.ClassFullName); } if (ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath != null) { Logger.LogError($"Packed Extension loading not supported in Firefox!"); // 05-Nov-2020 navramov: Extension loading does not work ////string packedExtensionPath = ConfigurationService.GetSection<WebSettings>().Firefox.PackedExtensionPath.NormalizeAppPath(); ////Logger.LogInformation($"Trying to load packed extension from path: {packedExtensionPath}"); ////firefoxOptions.Profile.AddExtension(ConfigurationService.GetSection<WebSettings>().Firefox.PackedExtensionPath); } if (ConfigurationService.GetSection <WebSettings>().ExecutionSettings.UnpackedExtensionPath != null) { Logger.LogError($"Unpacked Extension loading not supported in Firefox!"); } var firefoxTimeout = TimeSpan.FromSeconds(180); wrappedWebDriver = new FirefoxDriver(firefoxService, firefoxOptions, firefoxTimeout); break; case BrowserType.FirefoxHeadless: new DriverManager().SetUpDriver(new FirefoxConfig()); var firefoxHeadlessOptions = executionConfiguration.DriverOptions; firefoxHeadlessOptions.AddArguments("--headless"); firefoxHeadlessOptions.AddAdditionalOption("acceptInsecureCerts", true); if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled) { firefoxHeadlessOptions.Proxy = webDriverProxy; } if (ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath != null) { string packedExtensionPath = ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath.NormalizeAppPath(); Logger.LogInformation($"Trying to load packed extension from path: {packedExtensionPath}"); firefoxHeadlessOptions.Profile.AddExtension(ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath); } if (ConfigurationService.GetSection <WebSettings>().ExecutionSettings.UnpackedExtensionPath != null) { Logger.LogError($"Unpacked Extension loading not supported in Firefox!"); } var service = FirefoxDriverService.CreateDefaultService(); service.SuppressInitialDiagnosticInformation = true; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { if (File.Exists(@"C:\Program Files\Mozilla Firefox\firefox.exe")) { service.FirefoxBinaryPath = @"C:\Program Files\Mozilla Firefox\firefox.exe"; } else { service.FirefoxBinaryPath = @"C:\Program Files (x86)\Mozilla Firefox\firefox.exe"; } // TODO: Anton(15.12.2019): Add option to set the path via environment variable. } service.Port = GetFreeTcpPort(); wrappedWebDriver = new FirefoxDriver(service, firefoxHeadlessOptions); break; case BrowserType.Edge: new DriverManager().SetUpDriver(new EdgeConfig()); var edgeDriverService = Microsoft.Edge.SeleniumTools.EdgeDriverService.CreateChromiumService(); edgeDriverService.SuppressInitialDiagnosticInformation = true; var edgeOptions = executionConfiguration.DriverOptions; edgeOptions.PageLoadStrategy = PageLoadStrategy.Normal; edgeOptions.UseChromium = true; edgeOptions.AddArguments("--log-level=3"); if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled) { edgeOptions.Proxy = webDriverProxy; } if (ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath != null) { string packedExtensionPath = ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath.NormalizeAppPath(); Logger.LogInformation($"Trying to load packed extension from path: {packedExtensionPath}"); edgeOptions.AddExtension(ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath); } if (ConfigurationService.GetSection <WebSettings>().ExecutionSettings.UnpackedExtensionPath != null) { string unpackedExtensionPath = ConfigurationService.GetSection <WebSettings>().ExecutionSettings.UnpackedExtensionPath.NormalizeAppPath(); Logger.LogInformation($"Trying to load unpacked extension from path: {unpackedExtensionPath}"); edgeOptions.AddArguments($"load-extension={unpackedExtensionPath}"); } edgeOptions.SetLoggingPreference(LogType.Browser, LogLevel.Severe); edgeOptions.SetLoggingPreference("performance", LogLevel.All); wrappedWebDriver = new Microsoft.Edge.SeleniumTools.EdgeDriver(edgeDriverService, edgeOptions); break; case BrowserType.EdgeHeadless: new DriverManager().SetUpDriver(new EdgeConfig()); var edgeHeadlessDriverService = Microsoft.Edge.SeleniumTools.EdgeDriverService.CreateChromiumService(); edgeHeadlessDriverService.SuppressInitialDiagnosticInformation = true; var edgeHeadlessOptions = executionConfiguration.DriverOptions; edgeHeadlessOptions.AddArguments("--headless"); edgeHeadlessOptions.AddArguments("--log-level=3"); edgeHeadlessOptions.AddArguments("--test-type"); edgeHeadlessOptions.AddArguments("--disable-infobars"); edgeHeadlessOptions.AddArguments("--allow-no-sandbox-job"); edgeHeadlessOptions.AddArguments("--ignore-certificate-errors"); edgeHeadlessOptions.AddArguments("--disable-gpu"); edgeHeadlessOptions.AddArguments("--no-sandbox"); edgeHeadlessOptions.AddUserProfilePreference("credentials_enable_service", false); edgeHeadlessOptions.AddUserProfilePreference("profile.password_manager_enabled", false); edgeHeadlessOptions.AddArgument("hide-scrollbars"); edgeHeadlessOptions.UnhandledPromptBehavior = UnhandledPromptBehavior.Dismiss; edgeHeadlessOptions.PageLoadStrategy = PageLoadStrategy.Normal; edgeHeadlessOptions.UseChromium = true; if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled) { edgeHeadlessOptions.Proxy = webDriverProxy; } if (ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath != null) { string packedExtensionPath = ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath.NormalizeAppPath(); Logger.LogInformation($"Trying to load packed extension from path: {packedExtensionPath}"); edgeHeadlessOptions.AddExtension(ConfigurationService.GetSection <WebSettings>().ExecutionSettings.PackedExtensionPath); } if (ConfigurationService.GetSection <WebSettings>().ExecutionSettings.UnpackedExtensionPath != null) { string unpackedExtensionPath = ConfigurationService.GetSection <WebSettings>().ExecutionSettings.UnpackedExtensionPath.NormalizeAppPath(); Logger.LogInformation($"Trying to load unpacked extension from path: {unpackedExtensionPath}"); edgeHeadlessOptions.AddExtensionPath(unpackedExtensionPath); } edgeHeadlessOptions.SetLoggingPreference(LogType.Browser, LogLevel.Severe); edgeHeadlessOptions.SetLoggingPreference("performance", LogLevel.All); wrappedWebDriver = new Microsoft.Edge.SeleniumTools.EdgeDriver(edgeHeadlessDriverService, edgeHeadlessOptions); break; case BrowserType.Opera: new DriverManager().SetUpDriver(new OperaConfig()); // the driver will be different for different OS. // Check for different releases- https://github.com/operasoftware/operachromiumdriver/releases var operaOptions = executionConfiguration.DriverOptions; if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled) { operaOptions.Proxy = webDriverProxy; } var operaService = OperaDriverService.CreateDefaultService(); operaService.SuppressInitialDiagnosticInformation = true; operaService.Port = GetFreeTcpPort(); try { wrappedWebDriver = new OperaDriver(operaService, operaOptions); } catch (WebDriverException ex) when(ex.Message.Contains("DevToolsActivePort file doesn't exist")) { throw new Exception("This is a known issue in the latest versions of Opera driver. It is reported to the Opera team. As soon it is fixed we will update BELLATRIX.", ex); } break; case BrowserType.InternetExplorer: new DriverManager().SetUpDriver(new InternetExplorerConfig()); // Steps to configure IE to always allow blocked content: // From Internet Explorer, select the Tools menu, then the Options... // In the Internet Options dialog, select the Advanced tab... // Scroll down until you see the Security options. Enable the checkbox "Allow active content to run in files on My Computer" // Also, check https://github.com/SeleniumHQ/selenium/wiki/InternetExplorerDriver#required-configuration // in case of OpenQA.Selenium.NoSuchWindowException: Unable to get browser --> Uncheck IE Options --> Security Tab -> Uncheck "Enable Protected Mode" var ieOptions = executionConfiguration.DriverOptions; ieOptions.IntroduceInstabilityByIgnoringProtectedModeSettings = true; ieOptions.IgnoreZoomLevel = true; ieOptions.EnableNativeEvents = false; ieOptions.EnsureCleanSession = true; ieOptions.PageLoadStrategy = PageLoadStrategy.Eager; ieOptions.ForceShellWindowsApi = true; ieOptions.AddAdditionalCapability("disable-popup-blocking", true); if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled) { ieOptions.Proxy = webDriverProxy; } wrappedWebDriver = new InternetExplorerDriver(_driverExecutablePath, ieOptions); break; case BrowserType.Safari: var safariOptions = executionConfiguration.DriverOptions; if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled) { safariOptions.Proxy = webDriverProxy; } wrappedWebDriver = new SafariDriver(safariOptions); break; default: throw new NotSupportedException($"Not supported browser {executionConfiguration.BrowserType}"); } return(wrappedWebDriver); }
private static void SetupSafariDriver() { Driver = new SafariDriver(); }
/// <summary> /// Prepares RemoteWebDriver basing on configuration supplied /// </summary> /// <param name="browserConfig"></param> /// <returns></returns> public static RemoteWebDriver GetDriver(Dictionary <String, String> browserConfig) { RemoteWebDriver driver = null; //System.IO.Directory.CreateDirectory(Path.Combine(ConfigurationManager.AppSettings.Get("Downloads").ToString(), "Downloads" + "_" + DateTime.Now.ToString("dd-MMM-yyyy"))); //string dirdown = Path.Combine(ConfigurationManager.AppSettings.Get("Downloads").ToString(), "Downloads" + "_" + DateTime.Now.ToString("dd-MMM-yyyy")); if (browserConfig["target"] == "local") { if (browserConfig["browser"] == "Firefox") { driver = new FirefoxDriver(); } else if (browserConfig["browser"] == "IE") { //DesiredCapabilities capabilities = DesiredCapabilities.InternetExplorer(); //capabilities.SetCapability("ignoreProtectedModeSettings", true); //capabilities.SetCapability("requireWindowFocus", true); InternetExplorerOptions options = new InternetExplorerOptions(); options.EnablePersistentHover = false; options.EnableNativeEvents = false; options.RequireWindowFocus = true; options.EnsureCleanSession = true; ////TODO: Get rid of Framework Path //driver = new InternetExplorerDriver(Directory.GetParent(Assembly.GetEntryAssembly().Location).ToString(), options); } else if (browserConfig["browser"] == "Chrome") { //var content = new Dictionary<string, object> { { "webdriver.load.strategy", "unstable" } }; //var prefs = new Dictionary<string, object> { { "prefs", content } }; ////DesiredCapabilities capabilities = DesiredCapabilities.Chrome(); ChromeOptions chrOpts = new ChromeOptions(); //var field = chrOpts.GetType().GetField("additionalCapabilities", BindingFlags.Instance | BindingFlags.NonPublic); //chrOpts.AddUserProfilePreference("Proxy", null); //chrOpts.AddArgument("--dns-prefetch-disable"); //chrOpts.AddArgument("--log-level=3"); caps.setCapability("webdriver.load.strategy", "unstable"); //capabilities.SetCapability("webdriver.load.strategy", "unstable"); chrOpts.AddUserProfilePreference("profile.content_settings.pattern_pairs.*.multiple-automatic-downloads", 1); //chrOpts.AddUserProfilePreference("download.default_directory", dirdown); chrOpts.AddArgument("disable-popup-blocking"); chrOpts.AddArgument("disable-infobars"); chrOpts.AddArgument("--disable-extensions"); chrOpts.AddArgument("test-type"); chrOpts.AddArguments("no-sandbox"); chrOpts.AddArguments("headless"); chrOpts.AddArguments("disable-gpu"); //chrOpts.AddArguments("ignore-certificate-errors", "--disable-features"); //capabilities.SetCapability(ChromeOptions.Capability, prefs); //if (field != null) //{ // var dict = field.GetValue(chrOpts) as IDictionary<string, object>; // if (dict != null) dict.Add(ChromeOptions.Capability, prefs); //} // //chrOpts.AddUserProfilePreference("download.prompt_for_download", ConfigurationManager.AppSettings["ShowBrowserDownloadPrompt"]); string driverLocation = Directory.GetParent(Assembly.GetEntryAssembly().Location).ToString(); driver = new ChromeDriver(driverLocation, chrOpts); //driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromMinutes(Convert.ToInt32(ConfigurationManager.AppSettings.Get("ElementPageLoad")))); driver.Manage().Window.Maximize(); } else if (browserConfig["browser"] == "PhanthomJS") { //DesiredCapabilities capabilities = DesiredCapabilities.PhantomJS(); //capabilities.IsJavaScriptEnabled=true; //capabilities.SetCapability(PhantomJSDriverService.CreateDefaultService, new String[] { "--web-security=no", "--ignore-ssl-errors=yes", "--ssl-protocol=tlsv1" }); //driver = new PhantomJSDriver(capabilities); //PhantomJSDriverService service = PhantomJSDriverService.CreateDefaultService(); //service.IgnoreSslErrors = true; //service.LoadImages = false; //service.ProxyType = "none"; driver = new PhantomJSDriver(); } else if (browserConfig["browser"] == "Safari") { driver = new SafariDriver(); } } driver.Manage().Cookies.DeleteAllCookies(); return(driver); }
/// <summary> /// Creates the web driver. /// </summary> /// <param name="browserType">Type of the browser.</param> /// <param name="browserFactoryConfiguration">The browser factory configuration.</param> /// <returns>The created web driver.</returns> /// <exception cref="System.InvalidOperationException">Thrown if the browser is not supported.</exception> internal static IWebDriver CreateWebDriver(BrowserType browserType, BrowserFactoryConfigurationElement browserFactoryConfiguration) { if (!RemoteDriverExists(browserFactoryConfiguration.Settings, browserType, out IWebDriver driver)) { switch (browserType) { case BrowserType.IE: NameValueConfigurationElement ignoreProtectedModeSettingsNameValueConfigurationElement = browserFactoryConfiguration.Settings[IgnoreProtectedModeSettings]; bool ignoreProtectedModeSettings = false; if (!string.IsNullOrWhiteSpace(ignoreProtectedModeSettingsNameValueConfigurationElement?.Value)) { if (!bool.TryParse(ignoreProtectedModeSettingsNameValueConfigurationElement.Value, out ignoreProtectedModeSettings)) { throw new ConfigurationErrorsException( $"The {IgnoreProtectedModeSettings} setting is not a valid boolean: {ignoreProtectedModeSettingsNameValueConfigurationElement.Value}"); } } var explorerOptions = new InternetExplorerOptions { EnsureCleanSession = browserFactoryConfiguration.EnsureCleanSession, IntroduceInstabilityByIgnoringProtectedModeSettings = ignoreProtectedModeSettings }; var internetExplorerDriverService = InternetExplorerDriverService.CreateDefaultService(); internetExplorerDriverService.HideCommandPromptWindow = true; driver = new InternetExplorerDriver(internetExplorerDriverService, explorerOptions); break; case BrowserType.FireFox: driver = GetFireFoxDriver(browserFactoryConfiguration); break; case BrowserType.Chrome: case BrowserType.ChromeHeadless: var chromeOptions = new ChromeOptions { LeaveBrowserRunning = false }; var cmdLineSetting = browserFactoryConfiguration.Settings[ChromeArgumentSetting]; if (!string.IsNullOrWhiteSpace(cmdLineSetting?.Value)) { foreach (var arg in cmdLineSetting.Value.Split(';')) { chromeOptions.AddArgument(arg); } } // Activate chrome headless via a command line if (browserType == BrowserType.ChromeHeadless) { chromeOptions.AddArgument("--headless"); } var chromeDriverService = ChromeDriverService.CreateDefaultService(); chromeDriverService.HideCommandPromptWindow = true; driver = new ChromeDriver(chromeDriverService, chromeOptions); break; case BrowserType.PhantomJS: var phantomJsDriverService = PhantomJSDriverService.CreateDefaultService(); phantomJsDriverService.HideCommandPromptWindow = true; driver = new PhantomJSDriver(phantomJsDriverService); break; case BrowserType.Safari: driver = new SafariDriver(); break; case BrowserType.Edge: var edgeOptions = new EdgeOptions { PageLoadStrategy = EdgePageLoadStrategy.Normal }; var edgeDriverService = EdgeDriverService.CreateDefaultService(); driver = new EdgeDriver(edgeDriverService, edgeOptions); break; default: throw new InvalidOperationException( $"Browser type '{browserType}' is not supported in Selenium local mode. Did you mean to configure a remote driver?"); } } // Set Driver Settings var managementSettings = driver.Manage(); // Set timeouts var applicationConfiguration = SettingHelper.GetConfigurationSection().Application; var timeouts = managementSettings.Timeouts(); timeouts.ImplicitWait = browserFactoryConfiguration.ElementLocateTimeout; timeouts.PageLoad = browserFactoryConfiguration.PageLoadTimeout; ActionBase.DefaultTimeout = browserFactoryConfiguration.ElementLocateTimeout; WaitForPageAction.DefaultTimeout = browserFactoryConfiguration.PageLoadTimeout; ActionBase.RetryValidationUntilTimeout = applicationConfiguration.RetryValidationUntilTimeout; // Maximize window managementSettings.Window.Maximize(); return(driver); }
/// <summary> /// Method, that initializes an <see cref="IWebDriver" /> type, depending on the given attributes. /// <para>Logs the event optionally.</para> /// </summary> /// <param name="executionMode">Switch between local and remote execution.</param> /// <param name="browserType"> The type of the selected browser to be automated.</param> /// <param name="driverOptions">An <see cref="DriverOptions" /> object containing the desired capabilities of the browser.</param> /// <param name="localDriverDirectory">The full path to the directory containing ***driver.exe.</param> /// <param name="seleniumGridHubUrl"> /// URI containing the address of the WebDriver remote server (e.g. /// http://127.0.0.1:4444/wd/hub). /// </param> /// <param name="logger"> /// The used <see cref="Logger" /> instance to display logged messages (<see cref="LogEventLevel" /> = /// <see cref="LogEventLevel.Information" />) during /// the method exeuction. /// </param> public static IWebDriver StartWebDriver( ExecutionMode executionMode, BrowserType browserType, [NotNull] DriverOptions driverOptions, [CanBeNull] string localDriverDirectory = null, [CanBeNull] Uri seleniumGridHubUrl = null, [CanBeNull] Logger logger = null) { if (driverOptions == null) { throw new ArgumentNullException(nameof(driverOptions)); } IWebDriver driver; switch (executionMode) { case ExecutionMode.LOCAL: { logger?.Information($"Attempting to start a ({browserType}) WebDriver on " + $"({executionMode}) ExecutionMode, " + $"using local driver directory ({localDriverDirectory}) " + $"with the following DriverOptions: ({driverOptions})"); if (localDriverDirectory == null) { var errorMessage = $"Using WebDriver in ({ExecutionMode.LOCAL}) mode requires a valid local path for the WebDriver."; logger?.Error(errorMessage); throw new ArgumentException(errorMessage); } switch (browserType) { case BrowserType.CHROME: { driver = new ChromeDriver(localDriverDirectory, (ChromeOptions)driverOptions); break; } case BrowserType.EDGE: { driver = new EdgeDriver(localDriverDirectory, (EdgeOptions)driverOptions); break; } case BrowserType.FIREFOX: { driver = new FirefoxDriver(localDriverDirectory, (FirefoxOptions)driverOptions); break; } case BrowserType.INTERNETEXPLROER: { driver = new InternetExplorerDriver(localDriverDirectory, (InternetExplorerOptions)driverOptions); break; } case BrowserType.SAFARI: { driver = new SafariDriver(localDriverDirectory, (SafariOptions)driverOptions); break; } case BrowserType.OPERA: { driver = new OperaDriver(localDriverDirectory, (OperaOptions)driverOptions); break; } default: { throw new ArgumentOutOfRangeException(nameof(browserType), browserType, null); } } } break; case ExecutionMode.REMOTE: { logger?.Information($"Attempting to start a ({browserType}) WebDriver on " + $"({executionMode}) ExecutionMode, " + $"using SeleniumGrid Hub Url ({seleniumGridHubUrl?.AbsoluteUri}) " + $"with the following DriverOptions: ({driverOptions})"); if (seleniumGridHubUrl == null) { var errorMessage = $"Using WebDriver in ({ExecutionMode.REMOTE}) mode requires a valid url to connect to a SeleniumGrid Hub."; logger?.Error(errorMessage); throw new ArgumentException(errorMessage); } switch (browserType) { case BrowserType.CHROME: { driver = new RemoteWebDriver(seleniumGridHubUrl, (ChromeOptions)driverOptions); break; } case BrowserType.EDGE: { driver = new RemoteWebDriver(seleniumGridHubUrl, (EdgeOptions)driverOptions); break; } case BrowserType.FIREFOX: { driver = new RemoteWebDriver(seleniumGridHubUrl, (FirefoxOptions)driverOptions); break; } case BrowserType.INTERNETEXPLROER: { driver = new RemoteWebDriver(seleniumGridHubUrl, (FirefoxOptions)driverOptions); break; } case BrowserType.SAFARI: { driver = new RemoteWebDriver(seleniumGridHubUrl, (SafariOptions)driverOptions); break; } case BrowserType.OPERA: { driver = new RemoteWebDriver(seleniumGridHubUrl, (OperaOptions)driverOptions); break; } default: { throw new ArgumentOutOfRangeException(nameof(browserType), browserType, null); } } } break; default: { throw new ArgumentOutOfRangeException(nameof(executionMode), executionMode, null); } } logger?.Information("WebDriver has been started successfully."); return(driver); }
/// <summary> /// Prepares RemoteWebDriver basing on configuration supplied /// </summary> /// <param name="browserConfig"></param> /// <returns></returns> public static RemoteWebDriver GetDriver(Dictionary <String, String> browserConfig) { RemoteWebDriver driver = null; System.IO.Directory.CreateDirectory(Path.Combine(ConfigurationManager.AppSettings.Get("ReportsDownloadpath").ToString(), "ReportDownloads")); string dirdown = Path.Combine(ConfigurationManager.AppSettings.Get("ReportsDownloadpath").ToString(), "ReportDownloads"); if (browserConfig["target"] == "local") { if (browserConfig["browser"] == "Firefox") { FirefoxProfile profile = new FirefoxProfile(); profile.SetPreference("browser.download.folderList", 2); profile.SetPreference("browser.download.dir", dirdown); profile.SetPreference("browser.download.manager.alertOnEXEOpen", false); profile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/msword,application/csv,text/csv,image/png ,image/jpeg, application/pdf, text/html,text/plain,application/octet-stream"); profile.SetPreference("browser.download.manager.focusWhenStarting", false); profile.SetPreference("browser.download.useDownloadDir", true); profile.SetPreference("browser.helperApps.alwaysAsk.force", false); profile.SetPreference("browser.download.manager.alertOnEXEOpen", false); profile.SetPreference("browser.download.manager.closeWhenDone", false); profile.SetPreference("browser.download.manager.showAlertOnComplete", false); profile.SetPreference("browser.download.manager.useWindow", false); profile.SetPreference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", false); profile.SetPreference("pdfjs.disabled", true); driver = new FirefoxDriver(profile); driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromMinutes(Convert.ToInt32(ConfigurationManager.AppSettings.Get("ElementPageLoad")))); driver.Manage().Cookies.DeleteAllCookies(); driver.Manage().Window.Maximize(); } else if (browserConfig["browser"] == "IE") { //TODO: Get rid of Framework Path driver = new InternetExplorerDriver(Directory.GetParent(Assembly.GetEntryAssembly().Location).ToString()); driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromMinutes(Convert.ToInt32(ConfigurationManager.AppSettings.Get("ElementPageLoad")))); driver.Manage().Window.Maximize(); } else if (browserConfig["browser"] == "Chrome") { DesiredCapabilities capabilities = DesiredCapabilities.Chrome(); ChromeOptions chrOpts = new ChromeOptions(); chrOpts.AddArguments("test-type"); chrOpts.AddUserProfilePreference("profile.content_settings.pattern_pairs.*.multiple-automatic-downloads", 1); chrOpts.AddUserProfilePreference("download.default_directory", dirdown); chrOpts.AddArgument("disable-popup-blocking"); chrOpts.AddArgument("--disable-extensions"); chrOpts.AddArguments("ignore-certificate-errors", "--disable-features"); driver = new ChromeDriver(Directory.GetParent(Assembly.GetEntryAssembly().Location).ToString(), chrOpts); //driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds()))); driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromMinutes(Convert.ToInt32(ConfigurationManager.AppSettings.Get("ElementPageLoad")))); driver.Manage().Cookies.DeleteAllCookies(); driver.Manage().Window.Maximize(); } if (browserConfig["browser"].ToUpper() == "PHANTHOMJS") { DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities = DesiredCapabilities.PhantomJS(); capabilities.SetCapability(CapabilityType.BrowserName, "Opera"); capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows)); capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Any)); capabilities.SetCapability(CapabilityType.IsJavaScriptEnabled, true); //capabilities.SetCapability(CapabilityType.Version, "9"); driver = new PhantomJSDriver(Directory.GetParent(Assembly.GetEntryAssembly().Location).ToString()); driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromMinutes(Convert.ToInt32(ConfigurationManager.AppSettings.Get("ElementPageLoad")))); driver.Manage().Cookies.DeleteAllCookies(); } else if (browserConfig["browser"] == "Safari") { SafariOptions opts = new SafariOptions(); opts.AddAdditionalCapability("browser.download.dir", dirdown); opts.AddAdditionalCapability("browser.helperApps.neverAsk.saveToDisk", "application/msword,application/csv,text/csv,image/png ,image/jpeg, application/pdf, text/html,text/plain,application/octet-stream"); driver = new SafariDriver(opts); driver.Manage().Window.Maximize(); } } else if (browserConfig["target"] == "browserstack") { DesiredCapabilities desiredCapabilities = new DesiredCapabilities(); String[] bsCredentials = ConfigurationManager.AppSettings.Get("BrowserStackCredentials").Split(new Char[] { ':' }); desiredCapabilities.SetCapability("browserstack.user", bsCredentials[0].Trim()); desiredCapabilities.SetCapability("browserstack.key", bsCredentials[1].Trim()); foreach (KeyValuePair <String, String> capability in browserConfig) { if (capability.Key != "target") { desiredCapabilities.SetCapability(capability.Key, capability.Value); } } driver = new RemoteWebDriver(new Uri("http://hub.browserstack.com/wd/hub/"), desiredCapabilities); driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromMinutes(Convert.ToInt32(ConfigurationManager.AppSettings.Get("ElementPageLoad")))); driver.Manage().Cookies.DeleteAllCookies(); } else if (browserConfig["target"] == "HUB") { if (ConfigurationManager.AppSettings.Get("DefaultBrowser").ToString().ToUpper().Contains("LOCAL")) { String[] ipandport = ConfigurationManager.AppSettings.Get("IPandPort").Split(new Char[] { ':' }); string ip = ipandport[0].Trim(); string port = ipandport[1].Trim(); string NodeURl = "http://" + ip + ":" + port + "/wd/hub"; if (browserConfig["browser"].ToUpper() == "FIREFOX") { DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities = DesiredCapabilities.Firefox(); capabilities.SetCapability(CapabilityType.BrowserName, "firefox"); capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows)); driver = new RemoteWebDriver(new Uri(NodeURl), capabilities); } if (browserConfig["browser"].ToUpper() == "CHROME") { DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities = DesiredCapabilities.Chrome(); capabilities.SetCapability(CapabilityType.BrowserName, "chrome"); capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows)); driver = new RemoteWebDriver(new Uri(NodeURl), capabilities); driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromMinutes(Convert.ToInt32(ConfigurationManager.AppSettings.Get("ElementPageLoad")))); driver.Manage().Cookies.DeleteAllCookies(); } if (browserConfig["browser"].ToUpper() == "SAFARI") { DesiredCapabilities capabilities = DesiredCapabilities.Safari(); capabilities.SetCapability(CapabilityType.BrowserName, "Safari"); capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows)); driver = new RemoteWebDriver(new Uri(NodeURl), capabilities); driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromMinutes(Convert.ToInt32(ConfigurationManager.AppSettings.Get("ElementPageLoad")))); driver.Manage().Cookies.DeleteAllCookies(); } if (browserConfig["browser"].ToUpper() == "IE") { DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities = DesiredCapabilities.InternetExplorer(); capabilities.SetCapability(CapabilityType.BrowserName, "ie"); // capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows)); capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Any)); //capabilities.SetCapability(CapabilityType.IsJavaScriptEnabled, true); //capabilities.SetCapability(CapabilityType.Version, "9"); driver = new RemoteWebDriver(new Uri(NodeURl), capabilities); driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromMinutes(Convert.ToInt32(ConfigurationManager.AppSettings.Get("ElementPageLoad")))); driver.Manage().Cookies.DeleteAllCookies(); } //unit drivers if (browserConfig["browser"].ToUpper() == "UNIT") { DesiredCapabilities capabilities = DesiredCapabilities.HtmlUnitWithJavaScript(); capabilities.SetCapability(CapabilityType.BrowserName, "htmlunit"); capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows)); //driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(Convert.ToInt32(ConfigurationManager.AppSettings.Get("ElementPageLoad")))); //driver.Manage().Cookies.DeleteAllCookies(); driver = new RemoteWebDriver(new Uri(NodeURl), capabilities); } driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromMinutes(Convert.ToInt32(ConfigurationManager.AppSettings.Get("ElementPageLoad")))); driver.Manage().Cookies.DeleteAllCookies(); driver.Manage().Window.Maximize(); } else { String[] TargetIP = ConfigurationManager.AppSettings.Get("TargetNode").Split(new Char[] { ':' }); string Tip = TargetIP[0].Trim(); string Tport = TargetIP[1].Trim(); string TNodeURl = "http://" + Tip + ":" + Tport + "/wd/hub"; if (browserConfig["browser"].ToUpper() == "FIREFOX") { DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities = DesiredCapabilities.Firefox(); capabilities.SetCapability(CapabilityType.BrowserName, "firefox"); capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows)); driver = new RemoteWebDriver(new Uri(TNodeURl), capabilities); } if (browserConfig["browser"].ToUpper() == "CHROME") { // ChromeOptions opt = new ChromeOptions(); // opt.AddExtension(Directory.GetParent(Assembly.GetEntryAssembly().Location).ToString() + "\\chromedriver.exe"); // DesiredCapabilities capabilities = DesiredCapabilities.Chrome(); // //capabilities.SetCapability("webdriver.chrome.driver", Directory.GetParent(Assembly.GetEntryAssembly().Location).ToString() + "\\chromedriver.exe"); // capabilities.SetCapability(CapabilityType.BrowserName, "chrome"); // ////capabilities.SetCapability(CapabilityType.Platform, "ANY"); // capabilities.SetCapability(CapabilityType.Version, "2.4"); //capabilities.SetCapability("webdriver.chrome.driver", Directory.GetParent(Assembly.GetEntryAssembly().Location).ToString() + "\\chromedriver.exe"); // capabilities.SetCapability(ChromeOptions.Capability, opt); // //driver = new RemoteWebDriver(new Uri(NodeURl), capabilities); DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities = DesiredCapabilities.Chrome(); capabilities.SetCapability(CapabilityType.BrowserName, "chrome"); capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows)); driver = new RemoteWebDriver(new Uri(TNodeURl), capabilities); driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromMinutes(Convert.ToInt32(ConfigurationManager.AppSettings.Get("ElementPageLoad")))); driver.Manage().Cookies.DeleteAllCookies(); } if (browserConfig["browser"].ToUpper() == "SAFARI") { DesiredCapabilities capabilities = DesiredCapabilities.Safari(); capabilities.SetCapability(CapabilityType.BrowserName, "Safari"); capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows)); driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromMinutes(Convert.ToInt32(ConfigurationManager.AppSettings.Get("ElementPageLoad")))); driver.Manage().Cookies.DeleteAllCookies(); driver = new RemoteWebDriver(new Uri(TNodeURl), capabilities); } if (browserConfig["browser"].ToUpper() == "IE") { DesiredCapabilities capabilities = DesiredCapabilities.InternetExplorer(); capabilities.SetCapability(CapabilityType.BrowserName, "IE"); capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows)); driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromMinutes(Convert.ToInt32(ConfigurationManager.AppSettings.Get("ElementPageLoad")))); driver.Manage().Cookies.DeleteAllCookies(); driver = new RemoteWebDriver(new Uri(TNodeURl), capabilities); } ////unit drivers if (browserConfig["browser"].ToUpper() == "UNIT") { DesiredCapabilities capabilities = DesiredCapabilities.HtmlUnitWithJavaScript(); capabilities.SetCapability(CapabilityType.BrowserName, "htmlunit"); capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows)); //driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(Convert.ToInt32(ConfigurationManager.AppSettings.Get("ElementPageLoad")))); //driver.Manage().Cookies.DeleteAllCookies(); driver = new RemoteWebDriver(new Uri(TNodeURl), capabilities); } } driver.Manage().Window.Maximize(); } return(driver); }
public void SetupChromeDriver() { safari = new SafariDriver(); }
/// <summary. /// Saves a screenshot of the current error page /// </summary> public static void SaveScreenShot(string fileName, IWebDriver sDriver) { try { //Get the screenshot Type driverType = sDriver.GetType(); string fileExt = ".jpg"; Screenshot screenshot = null; if (KomodoTestSuite.config.Browser == "htmlunit") { fileExt = ".html"; } if (KomodoTestSuite.config.RemoteWebDriver != "true") { switch (KomodoTestSuite.config.Browser.ToLower()) { case "firefox": FirefoxDriver ff = (FirefoxDriver)sDriver; screenshot = ff.GetScreenshot(); break; case "iexplore": InternetExplorerDriver ie = (InternetExplorerDriver)sDriver; screenshot = ie.GetScreenshot(); break; case "chrome": ChromeDriver chr = (ChromeDriver)sDriver; screenshot = chr.GetScreenshot(); break; case "safari": SafariDriver safD = (SafariDriver)sDriver; screenshot = safD.GetScreenshot(); break; case "android": //AndroidDriver an = (AndroidDriver)sDriver; //screenshot = an.GetScreenshot(); break; case "htmlunit": fileExt = ".html"; break; default: break; } } if (KomodoTestSuite.config.RemoteWebDriver == "true" && fileExt != ".html") { screenshot = ((ScreenShotRemoteWebDriver)sDriver).GetScreenshot(); } //Build up on our filename StringBuilder filename = new StringBuilder(fileName); filename.Append("-"); filename.Append(String.Format("{0:yyyyMMdd}", DateTime.Now));//DateTime.Now.ToShortDateString().Replace("/", "_")); filename.Append(fileExt); FileInfo fileInfo = new FileInfo(filename.ToString()); if (!Directory.Exists(fileInfo.FullName)) { Directory.CreateDirectory(fileInfo.DirectoryName); } //save the image if (fileExt == ".jpg") { Common.SaveScreenShot(filename.ToString(), screenshot); } else { Common.SaveFile(fileName.ToString(), sDriver.PageSource); } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine("Error: Unable to take screenshot, at the moment this will not work with remotewebdriver"); // throw; } }
public void SuccessLoginCapital() { //For Mac Inıtialize the Safari Driver SafariDriver safariDriver = new SafariDriver(); // Maximize the browser safariDriver.Manage().Window.Maximize(); // Go to the "Lolaflora" login page safariDriver.Navigate().GoToUrl("https://www.lolaflora.com/en-es/login"); // Find the email/username textbox (by ID) on the login page var emailBox = safariDriver.FindElementById("EmailLogin"); // Enter the mail adress for login emailBox.SendKeys("*****@*****.**"); // Find the password (by ID) on the login page var passwordBox = safariDriver.FindElementById("Password"); // Enter the password for login passwordBox.SendKeys("123654789"); try { Thread.Sleep(1000); } catch (NullReferenceException e) { Console.WriteLine("Exception:" + e); } // Find the search button (by Name) on the homepage var signIn = safariDriver.FindElementByXPath("//*[@id='userLogin']/div[6]/button"); // Click "Submit" to start the search signIn.SendKeys(Keys.Return); try { Thread.Sleep(3000); } catch (NullReferenceException e) { Console.WriteLine("Exception:" + e); } //Find an element on page after login var successLoginRemark = safariDriver.FindElementByXPath("/html/body/div[2]/div[2]/div/div[2]/div[2]/nav/ul/li[3]"); try { Thread.Sleep(5000); } catch (NullReferenceException e) { Console.WriteLine("Exception:" + e); } //[email protected] //123654789 safariDriver.Dispose(); }
private static IWebDriver InitializeDriverRegularMode(BrowserConfiguration executionConfiguration, OpenQA.Selenium.Proxy webDriverProxy) { IWebDriver wrappedWebDriver; switch (executionConfiguration.BrowserType) { case BrowserType.Chrome: new DriverManager().SetUpDriver(new ChromeConfig()); var chromeDriverService = ChromeDriverService.CreateDefaultService(_driverExecutablePath); chromeDriverService.SuppressInitialDiagnosticInformation = true; chromeDriverService.EnableVerboseLogging = false; chromeDriverService.Port = GetFreeTcpPort(); var chromeOptions = GetChromeOptions(executionConfiguration.ClassFullName); chromeOptions.AddArguments("--log-level=3"); if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled) { chromeOptions.Proxy = webDriverProxy; } wrappedWebDriver = new ChromeDriver(chromeDriverService, chromeOptions); var chromePageLoadTimeout = ConfigurationService.GetSection <WebSettings>().Chrome.PageLoadTimeout; wrappedWebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(chromePageLoadTimeout); var chromeScriptTimeout = ConfigurationService.GetSection <WebSettings>().Chrome.ScriptTimeout; wrappedWebDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(chromeScriptTimeout); BrowserSettings = ConfigurationService.GetSection <WebSettings>().Chrome; break; case BrowserType.ChromeHeadless: new DriverManager().SetUpDriver(new ChromeConfig()); var chromeHeadlessDriverService = ChromeDriverService.CreateDefaultService(_driverExecutablePath); chromeHeadlessDriverService.SuppressInitialDiagnosticInformation = true; chromeHeadlessDriverService.Port = GetFreeTcpPort(); var chromeHeadlessOptions = GetChromeOptions(executionConfiguration.ClassFullName); chromeHeadlessOptions.AddArguments("--headless"); chromeHeadlessOptions.AddArguments("--log-level=3"); if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled) { chromeHeadlessOptions.Proxy = webDriverProxy; } wrappedWebDriver = new ChromeDriver(chromeHeadlessDriverService, chromeHeadlessOptions); var chromeHeadlessPageLoadTimeout = ConfigurationService.GetSection <WebSettings>().ChromeHeadless.PageLoadTimeout; wrappedWebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(chromeHeadlessPageLoadTimeout); var chromeHeadlessScriptTimeout = ConfigurationService.GetSection <WebSettings>().ChromeHeadless.ScriptTimeout; wrappedWebDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(chromeHeadlessScriptTimeout); BrowserSettings = ConfigurationService.GetSection <WebSettings>().ChromeHeadless; break; case BrowserType.Firefox: new DriverManager().SetUpDriver(new FirefoxConfig()); Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); var firefoxOptions = GetFirefoxOptions(executionConfiguration.ClassFullName); if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled) { firefoxOptions.Proxy = webDriverProxy; } var firefoxService = FirefoxDriverService.CreateDefaultService(_driverExecutablePath); firefoxService.SuppressInitialDiagnosticInformation = true; firefoxService.Port = GetFreeTcpPort(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { if (File.Exists(@"C:\Program Files\Mozilla Firefox\firefox.exe")) { firefoxService.FirefoxBinaryPath = @"C:\Program Files\Mozilla Firefox\firefox.exe"; } else { firefoxService.FirefoxBinaryPath = @"C:\Program Files (x86)\Mozilla Firefox\firefox.exe"; } // TODO: Anton(15.12.2019): Add option to set the path via environment variable. } var firefoxProfile = ServicesCollection.Current.Resolve <FirefoxProfile>(executionConfiguration.ClassFullName); if (firefoxProfile != null) { firefoxOptions.Profile = firefoxProfile; } var firefoxTimeout = TimeSpan.FromSeconds(180); wrappedWebDriver = new FirefoxDriver(firefoxService, firefoxOptions, firefoxTimeout); var firefoxPageLoadTimeout = ConfigurationService.GetSection <WebSettings>().Firefox.PageLoadTimeout; wrappedWebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(firefoxPageLoadTimeout); var firefoxScriptTimeout = ConfigurationService.GetSection <WebSettings>().Firefox.ScriptTimeout; wrappedWebDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(firefoxScriptTimeout); BrowserSettings = ConfigurationService.GetSection <WebSettings>().Firefox; break; case BrowserType.FirefoxHeadless: new DriverManager().SetUpDriver(new FirefoxConfig()); var firefoxHeadlessOptions = GetFirefoxOptions(executionConfiguration.ClassFullName); firefoxHeadlessOptions.AddArguments("--headless"); if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled) { firefoxHeadlessOptions.Proxy = webDriverProxy; } var service = FirefoxDriverService.CreateDefaultService(_driverExecutablePath); service.SuppressInitialDiagnosticInformation = true; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { if (File.Exists(@"C:\Program Files\Mozilla Firefox\firefox.exe")) { service.FirefoxBinaryPath = @"C:\Program Files\Mozilla Firefox\firefox.exe"; } else { service.FirefoxBinaryPath = @"C:\Program Files (x86)\Mozilla Firefox\firefox.exe"; } // TODO: Anton(15.12.2019): Add option to set the path via environment variable. } service.Port = GetFreeTcpPort(); wrappedWebDriver = new FirefoxDriver(service, firefoxHeadlessOptions); var firefoxHeadlessPageLoadTimeout = ConfigurationService.GetSection <WebSettings>().FirefoxHeadless.PageLoadTimeout; wrappedWebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(firefoxHeadlessPageLoadTimeout); var firefoxHeadlessScriptTimeout = ConfigurationService.GetSection <WebSettings>().FirefoxHeadless.ScriptTimeout; wrappedWebDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(firefoxHeadlessScriptTimeout); BrowserSettings = ConfigurationService.GetSection <WebSettings>().FirefoxHeadless; break; case BrowserType.Edge: new DriverManager().SetUpDriver(new EdgeConfig()); var edgeDriverService = Microsoft.Edge.SeleniumTools.EdgeDriverService.CreateChromiumService(_driverExecutablePath); edgeDriverService.SuppressInitialDiagnosticInformation = true; var edgeOptions = GetEdgeOptions(executionConfiguration.ClassFullName); edgeOptions.PageLoadStrategy = PageLoadStrategy.Normal; edgeOptions.UseChromium = true; edgeOptions.AddArguments("--log-level=3"); if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled) { edgeOptions.Proxy = webDriverProxy; } wrappedWebDriver = new Microsoft.Edge.SeleniumTools.EdgeDriver(edgeDriverService, edgeOptions); var edgePageLoadTimeout = ConfigurationService.GetSection <WebSettings>().Edge.PageLoadTimeout; wrappedWebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(edgePageLoadTimeout); var edgeScriptTimeout = ConfigurationService.GetSection <WebSettings>().Edge.ScriptTimeout; wrappedWebDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(edgeScriptTimeout); BrowserSettings = ConfigurationService.GetSection <WebSettings>().Edge; break; case BrowserType.EdgeHeadless: new DriverManager().SetUpDriver(new EdgeConfig()); var edgeHeadlessDriverService = Microsoft.Edge.SeleniumTools.EdgeDriverService.CreateChromiumService(_driverExecutablePath); edgeHeadlessDriverService.SuppressInitialDiagnosticInformation = true; var edgeHeadlessOptions = GetEdgeOptions(executionConfiguration.ClassFullName); edgeHeadlessOptions.AddArguments("--headless"); edgeHeadlessOptions.AddArguments("--log-level=3"); edgeHeadlessOptions.PageLoadStrategy = PageLoadStrategy.Normal; edgeHeadlessOptions.UseChromium = true; if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled) { edgeHeadlessOptions.Proxy = webDriverProxy; } wrappedWebDriver = new Microsoft.Edge.SeleniumTools.EdgeDriver(edgeHeadlessDriverService, edgeHeadlessOptions); var edgeHeadlessPageLoadTimeout = ConfigurationService.GetSection <WebSettings>().Edge.PageLoadTimeout; wrappedWebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(edgeHeadlessPageLoadTimeout); var edgeHeadlessScriptTimeout = ConfigurationService.GetSection <WebSettings>().Edge.ScriptTimeout; wrappedWebDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(edgeHeadlessScriptTimeout); BrowserSettings = ConfigurationService.GetSection <WebSettings>().Edge; break; case BrowserType.Opera: new DriverManager().SetUpDriver(new OperaConfig()); // the driver will be different for different OS. // Check for different releases- https://github.com/operasoftware/operachromiumdriver/releases var operaOptions = GetOperaOptions(executionConfiguration.ClassFullName); if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled) { operaOptions.Proxy = webDriverProxy; } var operaService = OperaDriverService.CreateDefaultService(_driverExecutablePath); operaService.SuppressInitialDiagnosticInformation = true; operaService.Port = GetFreeTcpPort(); try { wrappedWebDriver = new OperaDriver(operaService, operaOptions); } catch (WebDriverException ex) when(ex.Message.Contains("DevToolsActivePort file doesn't exist")) { throw new Exception("This is a known issue in the latest versions of Opera driver. It is reported to the Opera team. As soon it is fixed we will update BELLATRIX.", ex); } var operaPageLoadTimeout = ConfigurationService.GetSection <WebSettings>().Opera.PageLoadTimeout; wrappedWebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(operaPageLoadTimeout); var operaScriptTimeout = ConfigurationService.GetSection <WebSettings>().Opera.ScriptTimeout; wrappedWebDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(operaScriptTimeout); BrowserSettings = ConfigurationService.GetSection <WebSettings>().Opera; break; case BrowserType.InternetExplorer: new DriverManager().SetUpDriver(new InternetExplorerConfig()); // Steps to configure IE to always allow blocked content: // From Internet Explorer, select the Tools menu, then the Options... // In the Internet Options dialog, select the Advanced tab... // Scroll down until you see the Security options. Enable the checkbox "Allow active content to run in files on My Computer" // Also, check https://github.com/SeleniumHQ/selenium/wiki/InternetExplorerDriver#required-configuration // in case of OpenQA.Selenium.NoSuchWindowException: Unable to get browser --> Uncheck IE Options --> Security Tab -> Uncheck "Enable Protected Mode" var ieOptions = GetInternetExplorerOptions(executionConfiguration.ClassFullName); ieOptions.IntroduceInstabilityByIgnoringProtectedModeSettings = true; ieOptions.IgnoreZoomLevel = true; ieOptions.EnableNativeEvents = false; ieOptions.EnsureCleanSession = true; ieOptions.PageLoadStrategy = PageLoadStrategy.Eager; ieOptions.ForceShellWindowsApi = true; ieOptions.AddAdditionalCapability("disable-popup-blocking", true); if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled) { ieOptions.Proxy = webDriverProxy; } wrappedWebDriver = new InternetExplorerDriver(_driverExecutablePath, ieOptions); var iePageLoadTimeout = ConfigurationService.GetSection <WebSettings>().InternetExplorer.PageLoadTimeout; wrappedWebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(iePageLoadTimeout); var ieScriptTimeout = ConfigurationService.GetSection <WebSettings>().InternetExplorer.ScriptTimeout; wrappedWebDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(ieScriptTimeout); BrowserSettings = ConfigurationService.GetSection <WebSettings>().InternetExplorer; break; case BrowserType.Safari: var safariOptions = GetSafariOptions(executionConfiguration.ClassFullName); if (executionConfiguration.ShouldCaptureHttpTraffic && _proxyService.IsEnabled) { safariOptions.Proxy = webDriverProxy; } wrappedWebDriver = new SafariDriver(safariOptions); var safariPageLoadTimeout = ConfigurationService.GetSection <WebSettings>().Safari.PageLoadTimeout; wrappedWebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(safariPageLoadTimeout); var safariScriptTimeout = ConfigurationService.GetSection <WebSettings>().Safari.ScriptTimeout; wrappedWebDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(safariScriptTimeout); BrowserSettings = ConfigurationService.GetSection <WebSettings>().Safari; break; default: throw new NotSupportedException($"Not supported browser {executionConfiguration.BrowserType}"); } return(wrappedWebDriver); }
public override void TestInit() { Driver = new SafariDriver(); base.TestInit(); }
private IWebDriver GetWebDriver(string browser, bool useRemoteServer, string host, string port, string ieDriverLocation, string chromeDriverLocation) { DesiredCapabilities capabilities = null; ICapabilities safariCapabilities = null; IWebDriver webDriver; if (useRemoteServer == true) { Uri remoteAddress = null; if (port == string.Empty) { remoteAddress = new Uri(string.Format("http://{0}/wd/hub", host)); } else { remoteAddress = new Uri(string.Format("http://{0}:{1}/wd/hub", host, port)); } switch (browser) { case "Firefox": var ffp = new FirefoxProfile(); ffp.AcceptUntrustedCertificates = true; ffp.SetPreference("app.update.auto", false); ffp.SetPreference("app.update.enabled", false); ffp.SetPreference("browser.search.update", false); ffp.SetPreference("browser.shell.checkDefaultBrowser", false); ffp.SetPreference("browser.startup.page", 0); ffp.SetPreference("browser.tabs.warnOnClose", false); ffp.SetPreference("browser.tabs.warnOnOpen;false", false); ffp.SetPreference("extensions.checkCompatibility", false); ffp.SetPreference("layout.spellcheckDefault", 0); ffp.AlwaysLoadNoFocusLibrary = true; ffp.EnableNativeEvents = false; capabilities = DesiredCapabilities.Firefox(); capabilities.SetCapability(FirefoxDriver.ProfileCapabilityName, ffp); webDriver = new RemoteWebDriver(remoteAddress, capabilities); break; case "GoogleChrome": ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.AddArgument("start-maximized"); capabilities = DesiredCapabilities.Chrome(); capabilities.SetCapability(ChromeOptions.Capability, chromeOptions); webDriver = new RemoteWebDriver(remoteAddress, capabilities); break; case "IE7": case "IE8": case "IE9": case "IE10": capabilities = DesiredCapabilities.InternetExplorer(); capabilities.SetCapability("ignoreProtectedModeSettings", true); webDriver = new RemoteWebDriver(remoteAddress, capabilities); break; case "Safari": safariCapabilities = DesiredCapabilities.Safari(); webDriver = new RemoteWebDriver(remoteAddress, safariCapabilities); break; default: capabilities = DesiredCapabilities.Firefox(); webDriver = new RemoteWebDriver(remoteAddress, capabilities); break; } } else { switch (browser) { case "Firefox": FirefoxProfileManager ffpm = new FirefoxProfileManager(); var ffp = new FirefoxProfile(); if (ffpm.GetProfile("WebDriver") != null) { ffp = ffpm.GetProfile("WebDriver"); ffp.SetPreference("app.update.auto", false); ffp.SetPreference("app.update.enabled", false); ffp.SetPreference("browser.search.update", false); ffp.SetPreference("browser.shell.checkDefaultBrowser", false); ffp.SetPreference("browser.startup.page", 0); ffp.SetPreference("browser.tabs.warnOnClose", false); ffp.SetPreference("browser.tabs.warnOnOpen;false", false); ffp.SetPreference("layout.spellcheckDefault", 0); ffp.SetPreference("extensions.checkCompatibility", false); ffp.AlwaysLoadNoFocusLibrary = true; ffp.EnableNativeEvents = false; } ffp.AcceptUntrustedCertificates = true; webDriver = new FirefoxDriver(ffp); break; case "GoogleChrome": ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.AddArgument("start-maximized"); capabilities = DesiredCapabilities.Chrome(); capabilities.SetCapability(ChromeOptions.Capability, chromeOptions); webDriver = new ChromeDriver(chromeDriverLocation, chromeOptions); break; case "IE7": case "IE8": case "IE9": case "IE10": InternetExplorerOptions internetExplorerOptions = new InternetExplorerOptions(); internetExplorerOptions.IntroduceInstabilityByIgnoringProtectedModeSettings = true; webDriver = new InternetExplorerDriver(ieDriverLocation, internetExplorerOptions); break; case "Safari": webDriver = new SafariDriver(); break; default: var dffp = new FirefoxProfile(); dffp.AlwaysLoadNoFocusLibrary = true; dffp.EnableNativeEvents = false; dffp.AcceptUntrustedCertificates = true; dffp.SetPreference("app.update.auto", false); dffp.SetPreference("app.update.enabled", false); dffp.SetPreference("browser.search.update", false); dffp.SetPreference("browser.shell.checkDefaultBrowser", false); dffp.SetPreference("browser.startup.page", 0); dffp.SetPreference("browser.tabs.warnOnClose", false); dffp.SetPreference("browser.tabs.warnOnOpen;false", false); dffp.SetPreference("layout.spellcheckDefault", 0); dffp.SetPreference("extensions.checkCompatibility", false); webDriver = new FirefoxDriver(dffp); break; } } return(webDriver); }
/// <summary> /// Create browser given browser type /// </summary> /// <param name="browserType"></param> /// <returns></returns> public IWebDriver CreateBrowser(BrowserType browserType) { IWebDriver result; switch (browserType) { case BrowserType.Ie: { TestEasyHelpers.Tools.DownloadTool("IEDriverServer.exe", addToFirewall: true); result = new InternetExplorerDriver( Environment.ExpandEnvironmentVariables(TestEasyConfig.Instance.Tools.DefaultLocalToolsPath), new InternetExplorerOptions { IntroduceInstabilityByIgnoringProtectedModeSettings = true }, TimeSpan.FromMinutes(5)); } break; case BrowserType.Chrome: { TestEasyHelpers.Tools.DownloadTool("ChromeDriver.exe", addToFirewall: true); var options = new ChromeOptions(); options.AddArgument("--test-type"); result = new ChromeDriver(Environment.ExpandEnvironmentVariables(TestEasyConfig.Instance.Tools.DefaultLocalToolsPath), options, TimeSpan.FromMinutes(5)); } break; case BrowserType.Firefox: result = new FirefoxDriver(); break; case BrowserType.Safari: result = new SafariDriver(); break; default: // <- case BrowserType.HtmlUnit or BrowserType.Default { var capability = DesiredCapabilities.HtmlUnitWithJavaScript(); try { result = new RemoteWebDriver(capability); } catch { try { // if selenium standalone server is not running we should see exception if (_standaloneServerJar == null) { var serverSingletonPath = TestEasyHelpers.Tools.DownloadTool("selenium-server-standalone.jar"); var startInfo = new ProcessStartInfo(serverSingletonPath, ""); _standaloneServerJar = Process.Start(startInfo); } result = new RemoteWebDriver(capability); } catch (Exception e) { throw new Exception("Could not initialize HtmlUnit WebDriver. Make sure that latest Java runtime is installed on you machine and selenium-server-standalone.jar is running. Java runtime environment can be downloaded from http://java.com/en/download/index.jsp or from TestEasy tools path.", e); } } } break; } return(result); }
public static void Intialize() { try { string browser = ConfigurationManager.AppSettings.Get("browser"); string env = ConfigurationManager.AppSettings.Get("environment"); if (env.ToLower() == "local") { url = ConfigurationManager.AppSettings.Get("devurl"); } else { url = ConfigurationManager.AppSettings.Get("produrl"); } DesiredCapabilities cap; if (string.Equals(env, "Remote", StringComparison.OrdinalIgnoreCase)) { if (string.Equals(browser, "firefox", StringComparison.OrdinalIgnoreCase)) { // System.Environment.SetEnvironmentVariable("webdriver.gecko.driver", "c://Users//openr//Desktop//Ravi//geckodriver.exe"); //cap = DesiredCapabilities.Firefox(); // cap.SetCapability("marionette", true); // cap.SetCapability(CapabilityType.BrowserName, "firefox"); // cap.SetCapability(CapabilityType.Platform, "org.openqa.selenium.Platform.ANY"); // driver = new RemoteWebDriver(new Uri("http://192.168.2.49:4444/wd/hub"), cap); // driver.Manage().Window.Maximize(); } else if (string.Equals(browser, "chrome", StringComparison.OrdinalIgnoreCase)) { ChromeOptions options = new ChromeOptions(); options.AddArguments("disable-infobars"); options.AddUserProfilePreference("credentials_enable_service", false); options.AddUserProfilePreference("profile.password_manager_enabled", false); driver = new ChromeDriver(options); cap = options.ToCapabilities() as DesiredCapabilities; driver.Manage().Window.Maximize(); } else if (string.Equals(browser, "ie", StringComparison.OrdinalIgnoreCase)) { // cap = DesiredCapabilities.InternetExplorer(); //cap.SetCapability("ignoreProtectedModeSettings", true); //cap.SetCapability(CapabilityType.BrowserName, "ie"); //cap.SetCapability(CapabilityType.Platform, "org.openqa.selenium.Platform.ANY"); //driver = new RemoteWebDriver(new Uri("http://192.168.2.49:4444/wd/hub"), cap); //driver.Manage().Window.Maximize(); } else if (string.Equals(browser, "safari", StringComparison.OrdinalIgnoreCase)) { //cap = DesiredCapabilities.Safari(); //cap.SetCapability(CapabilityType.BrowserName, "safari"); //cap.SetCapability(CapabilityType.Platform, "org.openqa.selenium.Platform.WINDOWS"); //Console.WriteLine(System.Environment.GetEnvironmentVariable("user.dir")); //driver = new RemoteWebDriver(new Uri("http://192.168.2.49:4444/wd/hub"), cap); //driver.Manage().Window.Maximize(); //driver.Manage().Cookies.DeleteAllCookies(); //driver.Navigate().GoToUrl(url); } } else if (string.Equals(env, "Mobile", StringComparison.OrdinalIgnoreCase)) { if (string.Equals(browser, "chrome", StringComparison.OrdinalIgnoreCase)) { ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.AddAdditionalCapability("androidPackage", "com.android.chrome"); chromeOptions.AddAdditionalCapability("androidDeviceSerial", "HT4CBJT01080"); System.Environment.SetEnvironmentVariable("webdriver.chrome.driver", System.Environment.GetEnvironmentVariable("user.dir") + "/src/test/resources/chromedriver"); driver = new ChromeDriver(chromeOptions); } else if (string.Equals(browser, "safari", StringComparison.OrdinalIgnoreCase)) { } } // * To run tests in Local machine else { if (string.Equals(browser, "firefox", StringComparison.OrdinalIgnoreCase)) { //Console.WriteLine("In the ie block"); ///*FirefoxProfile prof = new FirefoxProfile(); //prof.setEnableNativeEvents(true); //driver = new FirefoxDriver(prof); //driver.manage().window().maximize()*/ //; //System.Environment.SetEnvironmentVariable("webdriver.gecko.driver", System.Environment.GetEnvironmentVariable("user.dir") + "/src/test/resources/geckodriver"); //DesiredCapabilities capabilities = DesiredCapabilities.Firefox(); //capabilities.SetCapability("marionette", true); //driver = new FirefoxDriver(capabilities); //driver.Manage().Cookies.DeleteAllCookies(); //driver.Manage().Window.Maximize(); } else if (string.Equals(browser, "chrome", StringComparison.OrdinalIgnoreCase)) { // System.Environment.SetEnvironmentVariable("webdriver.chrome.driver", System.Environment.GetEnvironmentVariable("user.dir") + "/src/test/resources/chromedriver"); driver = new ChromeDriver(); Console.WriteLine("In the chrome block"); driver.Manage().Window.Maximize(); } else if (string.Equals(browser, "ie", StringComparison.OrdinalIgnoreCase)) { System.Environment.SetEnvironmentVariable("webdriver.ie.driver", System.Environment.GetEnvironmentVariable("user.dir") + "/src/test/resources/IEDriverServer.exe"); driver = new InternetExplorerDriver(); driver.Manage().Window.Maximize(); } else if (string.Equals(browser, "safari", StringComparison.OrdinalIgnoreCase)) { driver = new SafariDriver(); driver.Manage().Window.Maximize(); } } } catch (Exception e) { e.StackTrace.ToString(); } }
/// <summary> /// Creates an istance of selected browser /// </summary> /// <param name="browserType"> Type of Browser user wants to create </param> /// <param name="defaultTimeOut">Time until the webdriver should try to create an instance of webdriver</param> /// <param name="browserOptions"> Options for the browser </param> public static void StartBrowser(BrowserTypes browserType = BrowserTypes.Firefox, int defaultTimeOut = 30, object browserOptions = null) { switch (browserType) { case BrowserTypes.Firefox: if (browserOptions != null) { Browser = new FirefoxDriver((FirefoxOptions)browserOptions); } else { Browser = new FirefoxDriver(); } break; case BrowserTypes.FirefoxHeadless: ((FirefoxOptions)browserOptions).AddArguments("--headless"); Browser = new FirefoxDriver((FirefoxOptions)browserOptions); break; case BrowserTypes.InternetExplorer: if (browserOptions != null) { Browser = new InternetExplorerDriver((InternetExplorerOptions)browserOptions); } else { Browser = new InternetExplorerDriver(); } break; case BrowserTypes.Chrome: if (browserOptions != null) { Browser = new ChromeDriver((ChromeOptions)browserOptions); } else { Browser = new ChromeDriver(); } break; case BrowserTypes.ChromeHeadless: if (browserOptions != null) { ((ChromeOptions)browserOptions).AddArgument("--headless"); ((ChromeOptions)browserOptions).AddArgument("disable-gpu"); } else { browserOptions = new ChromeOptions(); ((ChromeOptions)browserOptions).AddArgument("--headless"); ((ChromeOptions)browserOptions).AddArgument("disable-gpu"); } Browser = new ChromeDriver((ChromeOptions)browserOptions); break; case BrowserTypes.Edge: if (browserOptions != null) { Browser = new EdgeDriver((EdgeOptions)browserOptions); } else { Browser = new EdgeDriver(); } break; case BrowserTypes.Safari: if (browserOptions != null) { Browser = new SafariDriver((SafariOptions)browserOptions); } else { Browser = new SafariDriver(); } break; case BrowserTypes.Opera: if (browserOptions != null) { Browser = new OperaDriver((OperaOptions)browserOptions); } else { Browser = new OperaDriver(); } break; } BrowserWait = new WebDriverWait(Browser, TimeSpan.FromSeconds(defaultTimeOut)); }
public void StartBrowser() { this.driver = new SafariDriver(); }
/// <summary> /// Creates the web driver. /// </summary> /// <param name="browserType">Type of the browser.</param> /// <param name="browserFactoryConfiguration">The browser factory configuration.</param> /// <returns>The created web driver.</returns> /// <exception cref="System.InvalidOperationException">Thrown if the browser is not supported.</exception> internal static IWebDriver CreateWebDriver(BrowserType browserType, BrowserFactoryConfigurationElement browserFactoryConfiguration) { IWebDriver driver; if (!RemoteDriverExists(browserFactoryConfiguration.Settings, browserType, out driver)) { switch (browserType) { case BrowserType.IE: var explorerOptions = new InternetExplorerOptions { EnsureCleanSession = browserFactoryConfiguration.EnsureCleanSession }; driver = new InternetExplorerDriver(explorerOptions); break; case BrowserType.FireFox: driver = GetFireFoxDriver(browserFactoryConfiguration); break; case BrowserType.Chrome: // ReSharper disable UnusedVariable //Not currently used as current Chrome stable (38) doesn't support automating incognito mode var chromeOptions = GetChromeOptions(browserFactoryConfiguration); // ReSharper restore UnusedVariable driver = new ChromeDriver(); break; case BrowserType.ChromeCanary: var chromeCanaryOptions = new ChromeOptions { LeaveBrowserRunning = false, BinaryLocation = GetChromeCanaryBinaryLocation() }; driver = new ChromeDriver(chromeCanaryOptions); break; case BrowserType.PhantomJS: driver = new PhantomJSDriver(); break; case BrowserType.Safari: driver = new SafariDriver(); break; default: throw new InvalidOperationException(string.Format("Browser type '{0}' is not supported in Selenium local mode. Did you mean to configure a remote driver?", browserType)); } } // Set Driver Settings var managementSettings = driver.Manage(); // Set timeouts managementSettings.Timeouts() .ImplicitlyWait(browserFactoryConfiguration.ElementLocateTimeout) .SetPageLoadTimeout(browserFactoryConfiguration.PageLoadTimeout); // Maximize window managementSettings.Window.Maximize(); return(driver); }