public static IWebDriver initializeDriver(BrowserType myBrowser)
        {
            if (myBrowser.Equals(BrowserType.Chrome))
            {
                driver = new ChromeDriver();
                driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(5000);
                driver.Manage().Window.Maximize();
            }
            else if (myBrowser.Equals(BrowserType.Firefox))
            {
                driver = new FirefoxDriver();
                driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(5000);
                driver.Manage().Window.Maximize();
            }
            else if (myBrowser.Equals(BrowserType.InternetExplorer))
            {
                driver = new InternetExplorerDriver();
                driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(5000);
                driver.Manage().Window.Maximize();
            }
            else
            {
                driver = new SafariDriver();
                driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(5000);
                driver.Manage().Window.Maximize();
            }

            return(driver);
        }
Exemple #2
0
 internal void IntializeDriver(ref OpenQA.Selenium.IWebDriver driver, ref bool IsBrowserDimendion, ref List <OpenQA.Selenium.IWebDriver> driverlist, ref int width, ref int height)
 {
     driver = new SafariDriver();
     driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(150));
     driver.Manage().Window.Maximize();
     if (IsBrowserDimendion)
     {
         driver.Manage().Window.Size = new System.Drawing.Size(width, height);
     }
     driverlist.Add(driver);
 }
        private void StartBrowserRegularMode(BrowserConfiguration browserConfiguration)
        {
            IWebDriver driver = default;

            switch (browserConfiguration.Browser)
            {
            case Browser.Chrome:
                driver = new ChromeDriver(Environment.CurrentDirectory);
                driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(ConfigurationService.GetSection <WebSettings>().Chrome.PageLoadTimeout);
                driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(ConfigurationService.GetSection <WebSettings>().Chrome.ScriptTimeout);
                driver.Manage().Window.Maximize();
                break;

            case Browser.ChromeHeadless:
                var options = ServiceContainer.Resolve <ChromeOptions>("testClassFullName");
                options.AddArgument("--headless");
                options.AddArgument("--log-level=3");
                driver = new ChromeDriver(Environment.CurrentDirectory, options);
                ////driver = new ChromeDriver(Environment.CurrentDirectory);
                driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(ConfigurationService.GetSection <WebSettings>().Chrome.PageLoadTimeout);
                driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(ConfigurationService.GetSection <WebSettings>().Chrome.ScriptTimeout);
                driver.Manage().Window.Maximize();
                break;

            case Browser.Firefox:
                driver = new FirefoxDriver(Environment.CurrentDirectory);
                driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(ConfigurationService.GetSection <WebSettings>().FireFox.PageLoadTimeout);
                driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(ConfigurationService.GetSection <WebSettings>().FireFox.ScriptTimeout);
                driver.Manage().Window.Maximize();
                break;

            case Browser.Edge:
                driver = new EdgeDriver(Environment.CurrentDirectory);
                driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(ConfigurationService.GetSection <WebSettings>().Edge.PageLoadTimeout);
                driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(ConfigurationService.GetSection <WebSettings>().Edge.ScriptTimeout);
                driver.Manage().Window.Maximize();
                break;

            case Browser.Safari:
                driver = new SafariDriver(Environment.CurrentDirectory);
                driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(ConfigurationService.GetSection <WebSettings>().Safari.PageLoadTimeout);
                driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(ConfigurationService.GetSection <WebSettings>().Safari.ScriptTimeout);
                driver.Manage().Window.Maximize();
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(browserConfiguration.Browser), browserConfiguration.BrowserBehavior.ToString());
            }

            ServiceContainer.RegisterInstance(driver);
        }
Exemple #4
0
        public void TestSafari()
        {
            IWebDriver driver = null;

            try
            {
                SafariOptions options = new SafariOptions();

                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();
            }
        }
Exemple #5
0
        public void WrongChar()
        {
            //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");

            String [] wrongChar = { "!", ":", "?", ";", ",", "'", "%", "&", "/", "<", ">", "(", ")", "[", "]", "{", "}", "*" };

            Random random = new Random();
            int    rand   = random.Next(0, wrongChar.Length - 1);

            // Enter the mail adress for login
            emailBox.SendKeys("*****@*****.**" + wrongChar[rand]);

            // Find the password (by ID) on the login page
            var passwordBox = safariDriver.FindElementById("Password");

            // Enter the password for login
            passwordBox.SendKeys("123456789");

            // 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(2000);
            }
            catch (NullReferenceException e)
            {
                Console.WriteLine("Exception:" + e);
            }

            //Find an element on page after login
            var failLoginRemark = safariDriver.FindElementByXPath("//*[@id='userLogin']/div[2]/span[1]");

            try
            {
                Thread.Sleep(2000);
            }
            catch (NullReferenceException e)
            {
                Console.WriteLine("Exception:" + e);
            }

            //[email protected]
            //123654789

            safariDriver.Dispose();
        }
Exemple #6
0
        /// <summary>
        /// Returns an instance of Safari based driver.
        /// </summary>
        /// <returns>Safari based driver.</returns>
        private static IWebDriver SafariWebDriver()
        {
            // create safari browser object
            IWebDriver webDriver = new SafariDriver();

            webDriver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(TimeOut));
            return(webDriver);
        }
Exemple #7
0
        public void WithoutAtCharOnMailAddress()
        {
            //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("testusertestuser.com");

            // Find the password (by ID) on the login page
            var passwordBox = safariDriver.FindElementById("Password");

            // Enter the password for login
            passwordBox.SendKeys("123654789");

            // 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(2000);
            }
            catch (NullReferenceException e)
            {
                Console.WriteLine("Exception:" + e);
            }

            //Find an element on page after login
            var failLoginRemark = safariDriver.FindElementByXPath("//*[@id='userLogin']/div[2]/span[1]");

            try
            {
                Thread.Sleep(2000);
            }
            catch (NullReferenceException e)
            {
                Console.WriteLine("Exception:" + e);
            }

            //[email protected]
            //123654789


            safariDriver.Dispose();
        }
Exemple #8
0
        public static IWebDriver OpenSafariBrowserWithUrl(IWebDriver driver, string strUrlToOpen, Boolean OpenInNewWindow = false)
        {
            try
            {
                Uri remote_grid = new Uri("http://" + "localhost" + ":" + "4444" + "/wd/hub");
                DesiredCapabilities capability = null;

                string browser = "safari";
                //if (browser == null || browser.Contains("safari"))
                {
                    //SafariProfile profile = new SafariProfile();

                    capability = DesiredCapabilities.Safari();
                    capability.IsJavaScriptEnabled = true;

                    //profile.EnableNativeEvents = true;

                    //capability.SetCapability(SafariDriver.ProfileCapabilityName, profile);
                }

                SafariOptions so = new SafariOptions();
                so.AddAdditionalCapability(DesiredCapabilities.Safari().IsJavaScriptEnabled.ToString(), true);

                //DesiredCapabilities capabilities = DesiredCapabilities.Safari();
                //capabilities.BrowserName.Insert(0, "safari");
                //ICommandExecutor executor = new SeleneseCommandExecutor( "http:localhost:4444/" ,"http://www.google.com/" , capabilities);
                //IWebDriver driver1 = new RemoteWebDriver(executor, capabilities);

                driver = new SafariDriver(so); // ScreenShotRemoteWebDriver(remote_grid, capability);
                //driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(20));

                WebDriverBackedSelenium BackedSelenium = new WebDriverBackedSelenium(driver, remote_grid);
                BackedSelenium.Start();

                driver.Navigate().GoToUrl(strUrlToOpen);
                Report.AddToHtmlReportPassed("Safari Browser Open for '" + strUrlToOpen + "' .");
                new Common(driver).pause(70000);
                driver.Manage().Window.Maximize();

                //ScreenShotRemoteWebDriver sd = new ScreenShotRemoteWebDriver(remote_grid, capability);
                //sd.GetScreenshot().SaveAsFile()
            }
            catch (Exception ex)
            {
                //Console.WriteLine("ex::" + ex);
                //Console.WriteLine("ex.Message::" + ex.Message);
                //Console.WriteLine("ex.InnerException::" + ex.InnerException);
                //Console.WriteLine("ex.StackTrace::" + ex.StackTrace);
                //Report.AddToHtmlReportFailed(driver, ex, "Safari Browser Open for '" + strUrlToOpen + "' .");
            }
            return(driver);
        }
Exemple #9
0
        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);
        }
        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 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();
            }
        }
Exemple #12
0
        /// <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);
        }