Beispiel #1
0
        private void button1_Click(object sender, EventArgs e)
        {
            //************************* Firefox (Работает) ****************************************************
            //IWebDriver driverFirefox = new FirefoxDriver();
            //driverFirefox.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(30));
            //driverFirefox.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(55));
            //driverFirefox.Manage().Timeouts().SetScriptTimeout(TimeSpan.FromSeconds(30));

            //driverWork driverFirefoxWork = new driverWork(driverFirefox);
            //driverFirefoxWork.autoTest(firefoxNameVersion, width1280);
            //driverFirefoxWork.autoTest(firefoxNameVersion, width600);
            //driverFirefoxWork.autoTest(firefoxNameVersion, width480);
            //driverFirefoxWork.autoTest(firefoxNameVersion, width320);
            //driverFirefox.Close();
            //************************* Firefox ****************************************************


            //************************* Safari 5.1.7 только на версии Selenium 2.47 *****************************************************

            /*IWebDriver driverSafari = new SafariDriver();
             * driverSafari.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(30));
             * driverSafari.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(55));
             * driverSafari.Manage().Timeouts().SetScriptTimeout(TimeSpan.FromSeconds(30));
             *
             * driverWork driverSafariWork = new driverWork(driverSafari);
             * driverSafariWork.autoTest(safariNameVersion, width1280);
             * driverSafariWork.autoTest(safariNameVersion, width600);
             * driverSafariWork.autoTest(safariNameVersion, width480);
             * driverSafariWork.autoTest(safariNameVersion, width320);
             * driverSafari.Close();*/
            //************************* Safari 5.1.7 *******************************************************


            //************************* IE11 (Работает) *****************************************************
            IWebDriver driverIE = new InternetExplorerDriver();

            driverIE.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(30));
            driverIE.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(55));
            driverIE.Manage().Timeouts().SetScriptTimeout(TimeSpan.FromSeconds(30));

            driverWork driverIEWork = new driverWork(driverIE);

            driverIEWork.autoTest(IENameVersion, width1280);
            driverIEWork.autoTest(IENameVersion, width600);
            driverIEWork.autoTest(IENameVersion, width480);
            driverIEWork.autoTest(IENameVersion, width320);
            driverIE.Close();
            //************************* IE11 *******************************************************



            //************************* chrome_v53 ( Работает и на 2,47) *****************************************************
            //IWebDriver driverChrome = new ChromeDriver();
            //driverChrome.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(30));
            //driverChrome.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(55));
            //driverChrome.Manage().Timeouts().SetScriptTimeout(TimeSpan.FromSeconds(30));

            //driverWork driverChromeWork = new driverWork(driverChrome);
            //driverChromeWork.autoTest(chromeNameVersion, width1280);
            //driverChromeWork.autoTest(chromeNameVersion, width600);
            //driverChromeWork.autoTest(chromeNameVersion, width480);
            //driverChromeWork.autoTest(chromeNameVersion, width320);
            //driverChrome.Close();
            //************************* chrome_v53 *******************************************************
        }
Beispiel #2
0
        /// <summary>
        /// Configures a quick set button for the digital scan function on the device
        /// </summary>
        /// <param name="browser">The IE Browser instance to use.</param>
        public void ConfigureDigitalSend(InternetExplorerDriver browser)
        {
            By scanDigitalSendLinkLocator = By.LinkText("Scan/Digital Send");

            if (ElementExists(scanDigitalSendLinkLocator, browser))
            {
                _owner.OnUpdateStatus(this, "Clicking the 'Scan/Digital Send' link.");
                browser.FindElement(scanDigitalSendLinkLocator).Click();

                // Sometimes clicks don't navigate, still investigating and hope to remove this soon.
                if (browser.Url != $"http://{ (object)_device.Address}/hp/device/BasicSend/Index")
                {
                    browser.Navigate().GoToUrl($"http://{ (object)_device.Address}/hp/device/BasicSend/Index");
                }
            }
            else
            {
                ////throw new EwsAutomationException("Could not find the 'Scan/Digital Send' link.");
                // For some reason Selenium is unable to see the text for this link at all.  It manages to get a collection of the links but the
                // text property of them is all empty.  In that case we're just going to manually navigate.
                // This only occurs on smaller window sizes where the navigation menu is hidden.
                browser.Navigate().GoToUrl($"http://{_device.Address}/hp/device/BasicSend/Index");
            }

            By quickSetsLinkLocator = By.Id("QuickSetsFolder");

            if (ElementExists(quickSetsLinkLocator, browser))
            {
                _owner.OnUpdateStatus(this, "Clicking the 'Quick Sets' link");
                ClickElement(browser, browser.FindElement(quickSetsLinkLocator));
            }
            else
            {
                throw new EwsAutomationException("Could not find the Quick Set Folder link.");
            }

            By selectAllQuickSetsLocator = By.Id("QuickSetAll");

            if (ElementExists(selectAllQuickSetsLocator, browser))
            {
                _owner.OnUpdateStatus(this, "Found the select all checkbox in the quickset list.  Attempting to clear the quickset list.");
                ClickElement(browser, browser.FindElement(selectAllQuickSetsLocator));

                ClickElement(browser, browser.FindElement(By.Id("RemoveQuickSetButton")));

                By confirmRemoveButton = By.Id("DialogButtonYes");
                if (ElementExists(confirmRemoveButton, browser))
                {
                    browser.FindElement(confirmRemoveButton).Click();
                }
            }

            By addQuickSetButtonLocator = By.Id("AddQuickSetButton");

            if (ElementExists(addQuickSetButtonLocator, browser))
            {
                _owner.OnUpdateStatus(this, "Clicking the add QuickSet button.");
                browser.FindElement(addQuickSetButtonLocator).Click();
            }
            else
            {
                throw new EwsAutomationException("Could not find the 'Add QuickSet' button");
            }

            By quickSetTitleBoxLocator = By.Id("QuickSetTitle");

            if (ElementExists(quickSetsLinkLocator, browser))
            {
                _owner.OnUpdateStatus(this, $"Typing '{_activityData.Ews.QuickSetTitle}' into the quick set title box.");
                browser.FindElement(quickSetTitleBoxLocator).SendKeys(_activityData.Ews.QuickSetTitle);
            }
            else
            {
                throw new EwsAutomationException("Could not find the Quick Set Title textbox.");
            }

            By nextButtonLocator = By.Id("FormButtonNext");

            if (ElementExists(nextButtonLocator, browser))
            {
                browser.FindElement(nextButtonLocator).Click();
            }
            else
            {
                throw new EwsAutomationException("Could not find the 'Next' Button.");
            }

            By selectAllSharedNetworkFolderLocator = By.Id("SharedFolderAll");

            if (ElementExists(selectAllQuickSetsLocator, browser))
            {
                _owner.OnUpdateStatus(this, "Found the select all checkbox in the network folder list.  Attempting to clear the network folder list.");
                ClickElement(browser, browser.FindElement(selectAllSharedNetworkFolderLocator));

                ClickElement(browser, browser.FindElement(By.Id("SharedFolderRemove")));

                By confirmRemoveButton = By.Id("DialogButtonYes");
                if (ElementExists(confirmRemoveButton, browser))
                {
                    browser.FindElement(confirmRemoveButton).Click();
                }
            }

            By addSharedFolderButtonLocator = By.Id("SharedFolderAdd");

            if (ElementExists(addSharedFolderButtonLocator, browser))
            {
                _owner.OnUpdateStatus(this, "Clicking the Add Shared Folder button");
                browser.FindElement(addSharedFolderButtonLocator).Click();
            }

            By uncFolderPathBoxLocator = By.Id("UncPath");

            if (ElementExists(uncFolderPathBoxLocator, browser))
            {
                _owner.OnUpdateStatus(this, $"Typing '{_activityData.DigitalSend.OutputFolder.ToFQDNUncPath(_environment)}' into the UNC Path box.");
                browser.FindElement(uncFolderPathBoxLocator).SendKeys(_activityData.DigitalSend.OutputFolder.ToFQDNUncPath(_environment));
            }
            else
            {
                throw new EwsAutomationException("Could not find the UNC Path text box.");
            }

            By authenticationSettingsLocator = By.Id("UseMfpSignInCredentials");

            if (ElementExists(authenticationSettingsLocator, browser))
            {
                SelectElement authenticationSettingsSelect = new SelectElement(browser.FindElement(authenticationSettingsLocator));
                authenticationSettingsSelect.SelectByValue(true.ToString());
            }
            else
            {
                throw new EwsAutomationException("Could not find the authentication settings drop down list.");
            }

            By uncDomainBoxLocator = By.Id("UncDomain");

            if (ElementExists(uncDomainBoxLocator, browser))
            {
                _owner.OnUpdateStatus(this, $"Typing '{_userCredential.Domain}' into the UNC Domain box.");
                browser.FindElement(uncDomainBoxLocator).SendKeys(_userCredential.Domain);
            }
            else
            {
                throw new EwsAutomationException("Could not find the UNC Domain text box.");
            }

            By okButtonLocator = By.Id("FormButtonSubmit");

            if (ElementExists(okButtonLocator, browser))
            {
                browser.FindElement(okButtonLocator).Click();
            }
            else
            {
                throw new EwsAutomationException("Could not find the 'Ok' button.");
            }

            if (ElementExists(nextButtonLocator, browser))
            {
                _owner.OnUpdateStatus(this, "Clicking the Next button.");
                browser.FindElement(nextButtonLocator).Click();
            }
            else
            {
                throw new EwsAutomationException("Could not find the 'Next' Button.");
            }

            if (ElementExists(nextButtonLocator, browser))
            {
                _owner.OnUpdateStatus(this, "Clicking the Next button.");
                browser.FindElement(nextButtonLocator).Click();
            }
            else
            {
                throw new EwsAutomationException("Could not find the 'Next' Button.");
            }

            By finishButtonLocator = By.Id("FormButtonFinish");

            if (ElementExists(finishButtonLocator, browser))
            {
                _owner.OnUpdateStatus(this, "Clicking the Exit Wizard button.");
                browser.FindElement(finishButtonLocator).Click();
            }
            else
            {
                throw new EwsAutomationException("Could not find the 'Finish' Button.");
            }
        }
        public void LoginAndBecomeMember()
        {
            //20161024 change from FireFox to InternetExplorer
            IWebDriver driver = new InternetExplorerDriver();

            System.Threading.Thread.Sleep(6000);
            //IWebDriver driver = new FirefoxDriver();

            //Simplest way of dealing with time taken for pages to load.  One line here does it all.
            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));

            IWebElement element;

            driver.Navigate().GoToUrl("http://*****:*****@TestUser.com");
            System.Threading.Thread.Sleep(2000);

            element = driver.FindElement(By.Name("Password"));
            element.SendKeys("TestUser10~");
            System.Threading.Thread.Sleep(2000);
            // Now submit the form. WebDriver will find the form for us from the element
            element.Submit();

            System.Threading.Thread.Sleep(2000);

            // click the Become Member link to visit that page
            element = driver.FindElement(By.LinkText("Become Member"));
            element.Click();
            System.Threading.Thread.Sleep(6000);

            // select an option from the drop down box
            element = driver.FindElement(By.Id("purpose"));
            element.Click();
            System.Threading.Thread.Sleep(500);
            element.SendKeys("MemberFull");
            System.Threading.Thread.Sleep(500);
            element.Click();
            System.Threading.Thread.Sleep(500);

            // enter text box with text specificed in the send keys method below.
            element = driver.FindElement(By.Id("CardOwner"));
            element.SendKeys("Mr Tester");
            System.Threading.Thread.Sleep(2000);

            // enter text box with text specificed in the send keys method below.
            element = driver.FindElement(By.Id("CardType"));
            element.SendKeys("Visa");
            System.Threading.Thread.Sleep(2000);

            // enter text box with text specificed in the send keys method below.
            element = driver.FindElement(By.Id("CardNumber"));
            element.SendKeys("1111");
            System.Threading.Thread.Sleep(2000);

            // enter text box with text specificed in the send keys method below.
            element = driver.FindElement(By.Id("CSC"));
            element.SendKeys("111");
            System.Threading.Thread.Sleep(2000);

            // click submit
            element.Submit();
            System.Threading.Thread.Sleep(2000);
        }
        private static IWebDriver GetIEDriver()
        {
            IWebDriver driver = new InternetExplorerDriver();

            return(driver);
        }
Beispiel #5
0
        /// <summary>
        /// Walks the EWS and touches minor settings present.
        /// </summary>
        /// <param name="browser">The IE Browser instance to use.</param>
        public void EwsWalk(InternetExplorerDriver browser)
        {
            // Click the 'Job Log' link.
            By jobLogReportLinkLocator = By.Id("JobLogReport");

            if (ElementExists(jobLogReportLinkLocator, browser))
            {
                _owner.OnUpdateStatus(this, "Clicking the 'Job Log Report' link.");
                ClickElement(browser, browser.FindElement(jobLogReportLinkLocator));
            }
            else
            {
                throw new EwsAutomationException("Could not find the 'Job Log Report' link.");
            }

            // Click the 'Configuration' link.
            By configurationPageLocator = By.Id("InternalPages_Index_ConfigurationPage");

            if (ElementExists(configurationPageLocator, browser))
            {
                _owner.OnUpdateStatus(this, "Clicking the 'Configuration' link.");
                ClickElement(browser, browser.FindElement(configurationPageLocator));
            }
            else
            {
                throw new EwsAutomationException("Could not find the 'Configuration' link.");
            }

            // Click on the 'General' Tab.
            By settingsPageLinkLocator = By.Id("SettingsPages");

            if (ElementExists(settingsPageLinkLocator, browser))
            {
                _owner.OnUpdateStatus(this, "Clicking the 'General Tab' link.");
                ClickElement(browser, browser.FindElement(settingsPageLinkLocator));
            }
            else
            {
                throw new EwsAutomationException("Could not find the 'General' tab link.");
            }

            // Click on the 'QuickSets' link.
            By quickSetsLinkLocator = By.Id("QuickSets");

            if (ElementExists(quickSetsLinkLocator, browser))
            {
                _owner.OnUpdateStatus(this, "Clicking the 'QuickSets' link.");
                ClickElement(browser, browser.FindElement(quickSetsLinkLocator));
            }
            else
            {
                throw new EwsAutomationException("Could not find the 'Quick Sets' link.");
            }

            // Click on the 'Alerts' link.
            By alertsLinkLocator = By.Id("Alerts");

            if (ElementExists(alertsLinkLocator, browser))
            {
                _owner.OnUpdateStatus(this, "Clicking the 'Alerts' link.");
                ClickElement(browser, browser.FindElement(alertsLinkLocator));
            }
            else
            {
                throw new EwsAutomationException("Could not find the 'Alerts' link.");
            }
        }
Beispiel #6
0
        /// <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);
        }
Beispiel #7
0
        private static IWebDriver InitializeDriverRegularMode(BrowserConfiguration executionConfiguration, OpenQA.Selenium.Proxy webDriverProxy)
        {
            IWebDriver wrappedWebDriver;

            switch (executionConfiguration.BrowserType)
            {
            case BrowserType.Chrome:
                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:
                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:
                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:
                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:
                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:
                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:
                // 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:
                // 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);
        }
Beispiel #8
0
        private static IWebDriver GetIEBrowser()
        {
            IWebDriver driver = new InternetExplorerDriver(GetIeOption());

            return(driver);
        }
Beispiel #9
0
        /// <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;

                    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);

            WaitForElementAction.DefaultTimeout   = browserFactoryConfiguration.ElementLocateTimeout;
            WaitForListItemsAction.DefaultTimeout = browserFactoryConfiguration.ElementLocateTimeout;
            WaitForPageAction.DefaultTimeout      = browserFactoryConfiguration.PageLoadTimeout;

            // Maximize window
            managementSettings.Window.Maximize();

            return(driver);
        }
Beispiel #10
0
 public virtual void InitializeTest()
 {
     br   = new InternetExplorerDriver();
     wait = new SafeWebDriverWait(br, DefaultTimeOut);
     br.Navigate().GoToUrl(url);
 }
Beispiel #11
0
        public static IWebDriver BuildAndGetWebDriver(Browsers browser, IList <string> options)
        {
            IWebDriver webDriver;

            switch (browser)
            {
            case Browsers.EXPLORER:
                webDriver = new InternetExplorerDriver(_webDriversPath);
                break;

            case Browsers.FIREFOX:
                FirefoxOptions       FirefoxOptions       = new FirefoxOptions();
                FirefoxDriverService FirefoxDriverService = FirefoxDriverService.CreateDefaultService(_webDriversPath);
                FirefoxOptions.BrowserExecutableLocation = @"C:\Program Files\Mozilla Firefox\firefox.exe";
                TimeSpan TimeSpan = new TimeSpan(1, 0, 0);

                webDriver = new FirefoxDriver(FirefoxDriverService, FirefoxOptions, TimeSpan);

                break;

            case Browsers.CHROME:

                if (options != null)
                {
                    ChromeOptions crhomeOptions = new ChromeOptions();

                    foreach (string option in options)
                    {
                        crhomeOptions.AddArgument(option);
                    }

                    webDriver = new ChromeDriver(_webDriversPath, crhomeOptions);
                }
                else
                {
                    webDriver = new ChromeDriver(_webDriversPath);
                }

                break;

            case Browsers.EDGE:
                webDriver = new EdgeDriver(_webDriversPath);
                break;

            case Browsers.OPERA:
                OperaDriverService OperaDriverService = OperaDriverService.CreateDefaultService(_webDriversPath);
                OperaOptions       OperaOptions       = new OperaOptions();
                OperaOptions.BinaryLocation = @"C:\Program Files\Opera\54.0.2952.71\opera.exe";

                webDriver = new OperaDriver(OperaDriverService, OperaOptions);

                break;

            default:
                throw new Exception();
            }

            webDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(_milisecondsToWait);
            webDriver.Manage().Timeouts().PageLoad     = TimeSpan.FromMilliseconds(int.MaxValue);

            return(webDriver);
        }
Beispiel #12
0
        public IWebDriver CreateDriver(Browser browser)
        {
            ProxyService.GetNewProxyIp();
            _proxyServer = new ProxyServer();
            var explicitEndPoint = new ExplicitProxyEndPoint(System.Net.IPAddress.Any, 18882, false);

            _proxyServer.CertificateManager.TrustRootCertificate(true);
            _proxyServer.AddEndPoint(explicitEndPoint);
            _proxyServer.Start();
            _proxyServer.SetAsSystemHttpProxy(explicitEndPoint);
            _proxyServer.SetAsSystemHttpsProxy(explicitEndPoint);
            _proxyServer.UpStreamHttpProxy = new ExternalProxy {
                HostName = ProxyService.CurrentProxyIpHost, Port = ProxyService.CurrentProxyIpPort
            };
            _proxyServer.UpStreamHttpsProxy = new ExternalProxy {
                HostName = ProxyService.CurrentProxyIpHost, Port = ProxyService.CurrentProxyIpPort
            };

            var proxyChangerTimer = new Timer();

            proxyChangerTimer.Elapsed += ChangeProxyEventHandler;
            proxyChangerTimer.Interval = SecondsToRefreshProxy * 1000;
            proxyChangerTimer.Enabled  = true;

            var proxy = new Proxy
            {
                HttpProxy = "localhost:18882",
                SslProxy  = "localhost:18882",
                FtpProxy  = "localhost:18882",
            };

            IWebDriver webDriver;

            switch (browser)
            {
            case Browser.Chrome:

                var chromeOptions = new ChromeOptions
                {
                    Proxy = proxy
                };
                var chromeDriverService = ChromeDriverService.CreateDefaultService(_assemblyFolder);
                webDriver = new ChromeDriver(chromeDriverService, chromeOptions);
                webDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(ConfigurationService.Instance.GetWebSettings().Chrome.PageLoadTimeout);
                webDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(ConfigurationService.Instance.GetWebSettings().Chrome.ScriptTimeout);
                break;

            case Browser.Firefox:
                var firefoxOptions = new FirefoxOptions()
                {
                    Proxy = proxy
                };
                webDriver = new FirefoxDriver(Environment.CurrentDirectory, firefoxOptions);
                webDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(ConfigurationService.Instance.GetWebSettings().Firefox.PageLoadTimeout);
                webDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(ConfigurationService.Instance.GetWebSettings().Firefox.ScriptTimeout);
                break;

            case Browser.Edge:
                var edgeOptions = new EdgeOptions()
                {
                    Proxy = proxy
                };
                webDriver = new EdgeDriver(Environment.CurrentDirectory, edgeOptions);
                webDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(ConfigurationService.Instance.GetWebSettings().Edge.PageLoadTimeout);
                webDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(ConfigurationService.Instance.GetWebSettings().Edge.ScriptTimeout);
                break;

            case Browser.InternetExplorer:
                var ieOptions = new InternetExplorerOptions()
                {
                    Proxy = proxy
                };
                webDriver = new InternetExplorerDriver(Environment.CurrentDirectory, ieOptions);
                webDriver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(ConfigurationService.Instance.GetWebSettings().InternetExplorer.PageLoadTimeout);
                webDriver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(ConfigurationService.Instance.GetWebSettings().InternetExplorer.ScriptTimeout);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(browser), browser, null);
            }

            return(webDriver);
        }
        public void CodedUITestMethod1()
        {
            //string chromeDriverDirectory = @"C:\Users\E159279\Downloads\chromedriver_win32latest";
            //var timespan = TimeSpan.FromMinutes(3);
            //var options = new ChromeOptions();
            //options.AddArgument("-no-sandbox");
            //ChromeDriver drv = new ChromeDriver(chromeDriverDirectory,options,timespan);

            var ieoptions = new InternetExplorerOptions();

            ieoptions.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
            InternetExplorerDriver drv = new InternetExplorerDriver();



            WebDriverWait wt = new WebDriverWait(drv, System.TimeSpan.FromSeconds(300));

            drv.Manage().Window.Maximize();
            drv.Navigate().GoToUrl("http://*****:*****@class='loader']");
            WebDriverWait wait         = new WebDriverWait(drv, System.TimeSpan.FromSeconds(300));

            wait.Until(ExpectedConditions.InvisibilityOfElementLocated(loadingImage));
            wt.Until(ExpectedConditions.ElementToBeClickable(byloc));
            Thread.Sleep(2000);
            drv.FindElement(byloc).Click();
            Trace.WriteLine("Clicked Configuration Link");
            wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//div[text()='Well Configuration']")));
            drv.FindElement(By.XPath("//div[text()='Well Configuration']")).Click();
            Trace.WriteLine("Clicked Well Configuration Link");
            wait.Until(ExpectedConditions.InvisibilityOfElementLocated(loadingImage));
            Thread.Sleep(2000);
            Trace.WriteLine("Trying to click New Well button" + DateTime.Now.ToString());
            drv.FindElement(By.XPath("//button[contains(text(),'Create New Well')]")).Click();
            Trace.WriteLine("Clicked New Well Button" + DateTime.Now.ToString());


            //wellName
            drv.FindElement(By.Id("wellName")).SendKeys("RRL_0001");
            drv.FindElement(By.XPath("//kendo-dropdownlist[@id='wellType']")).Click();
            drv.FindElement(By.XPath("//li[text()='RRL']")).Click();
            //cygNetDomain
            drv.FindElement(By.XPath("//kendo-dropdownlist[@id='cygNetDomain']")).Click();
            drv.FindElement(By.XPath("//li[text()='27212']")).Click();
            wait.Until(ExpectedConditions.InvisibilityOfElementLocated(loadingImage));

            //siteService
            drv.FindElement(By.XPath("//kendo-dropdownlist[@id='siteService']")).Click();
            Thread.Sleep(5000);
            drv.FindElement(By.XPath("//li[contains(.,'.UIS')]")).Click();
            ////div[@id='facilityButtonDiv']
            drv.FindElement(By.XPath("//div[@id='facilityButtonDiv']")).Click();
            wait.Until(ExpectedConditions.InvisibilityOfElementLocated(loadingImage));

            //Selelct First Record of Facility Table:
            drv.FindElement(By.XPath("//table[contains(.,'Facility Id')]/descendant::td[1]")).Click();
            Trace.WriteLine("Extranoes wait to esnure Browser is open");
            drv.FindElement(By.Id("buttonApply")).Click();
            drv.FindElement(By.XPath("//input[@id='commissionDate']")).Click();
            System.Windows.Forms.SendKeys.SendWait("{Home}");
            Thread.Sleep(1000);
            drv.FindElement(By.XPath("//input[@id='commissionDate']")).SendKeys("02022016");
            drv.FindElement(By.XPath("//input[@id='assemblyAPI']")).SendKeys("122");
            //assemblyAPI
            drv.FindElement(By.XPath("//input[@id='subAssemblyAPI']")).SendKeys("1345");
            //subAssemblyAPI
            drv.FindElement(By.XPath("//input[@id='latitude']")).SendKeys("12");
            //latitude

            //longitude
            drv.FindElement(By.XPath("//input[@id='longitude']")).SendKeys("18");

            drv.FindElement(By.XPath("//button[@name='saveWellbutton']")).Click();
            Thread.Sleep(5000);



            //kendo-dropdownlist[@id='wellType']
            // To generate code for this test, select "Generate Code for Coded UI Test" from the shortcut menu and select one of the menu items.
        }
Beispiel #14
0
        public static void Initialize(bool isExecuteLocally, string remoteServerURL, string browser)
        {
            if (isExecuteLocally)
            {
                switch (browser.Trim().ToLower())
                {
                case "firefox":
                    Instance = new FirefoxDriver();

                    /*DesiredCapabilities capabilities = new DesiredCapabilities();
                     * capabilities = DesiredCapabilities.Firefox();
                     * //capabilities.SetCapability(CapabilityType.BrowserName, "firefox");
                     * //capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows));
                     * //capabilities.SetCapability(CapabilityType.Version, "29.0.1");
                     *
                     * Instance = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), capabilities);
                     * //driver = new FirefoxDriver();
                     * //baseURL = "https://www.google.co.in/";
                     * //verificationErrors = new StringBuilder();*/
                    break;

                case "chrome":
                    ChromeOptions chromeProfile = new ChromeOptions();
                    chromeProfile.AddArgument("ignore-certificate-errors");
                    Instance = new ChromeDriver("C:\\Drivers\\", chromeProfile);
                    //SetDefaultImplicitWait(5);
                    //Driver.Wait(TimeSpan())
                    //Instance.Manage().Window.Maximize();
                    break;

                //Instance = new ChromeDriver("C:\\Drivers\\");
                //break;
                case "ie":
                    Instance = new InternetExplorerDriver("C:\\Drivers\\");
                    break;

                default:
                    throw new Exception(string.Format("Browser {0} unknown", browser));
                }
            }
            else
            {
                switch (browser.Trim().ToLower())
                {
                case "firefox":
                    Instance = new RemoteWebDriver(new Uri(remoteServerURL), DesiredCapabilities.Firefox());

                    /*DesiredCapabilities capabilities = new DesiredCapabilities();
                     * capabilities = DesiredCapabilities.Firefox();
                     * capabilities.SetCapability(CapabilityType.BrowserName, "firefox");
                     * capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows));
                     * capabilities.SetCapability(CapabilityType.Version, "15.0");
                     *
                     * Instance = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), capabilities);
                     * //driver = new FirefoxDriver();
                     * /*baseURL = "https://www.google.co.in/";*/
                    //verificationErrors = new StringBuilder();*/
                    break;

                case "chrome":
                    Instance = new RemoteWebDriver(new Uri(remoteServerURL), DesiredCapabilities.Chrome());
                    break;

                case "ie":
                    Instance = new RemoteWebDriver(new Uri(remoteServerURL), DesiredCapabilities.InternetExplorer());
                    break;

                default:
                    throw new Exception(string.Format("Browser {0} unknown", browser));
                }
            }

            //Turn on explicit wait
            //Instance.Manage().Window.Maximize();
            //WaitOff = true;
            //Instance.TurnOnWait();
        }
Beispiel #15
0
        /// <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);
        }
Beispiel #16
0
 public void LoadDrivers()
 {
     if (_config.ChromeDriver)
     {
         log.Info("Loading Chrome Driver and starting Chrome Instance");
         using (IWebDriver driver = new ChromeDriver())
         {
             try
             {
                 var runner = new TestRunner(_config);
                 runner.Run(driver, "Chrome");
             }
             catch (Exception ex)
             {
                 log.Error("The following Error Occured" + ex.Message);
             }
             finally
             {
                 driver.Close();
             }
         }
     }
     if (_config.FirefoxDriver)
     {
         log.Info("Loading FireFox Driver and starting FireFox Instance");
         using (IWebDriver driver = new FirefoxDriver())
         {
             try
             {
                 var runner = new TestRunner(_config);
                 runner.Run(driver, "FireFox");
             }
             catch (Exception ex)
             {
                 log.Error("The following Error Occured" + ex.Message);
             }
             finally
             {
                 driver.Close();
             }
         }
     }
     if (_config.IEDriver)
     {
         log.Info("Loading Internet Explorer Driver and starting Internet Explorer Instance");
         using (IWebDriver driver = new InternetExplorerDriver())
         {
             try
             {
                 var runner = new TestRunner(_config);
                 runner.Run(driver, "Internet Explorer");
             }
             catch (Exception ex)
             {
                 log.Error("The following Error Occured" + ex.Message);
             }
             finally
             {
                 driver.Close();
             }
         }
     }
 }
 public virtual void InitializeTest()
 {
     br = new InternetExplorerDriver();
     br.Navigate().GoToUrl(url);
 }
Beispiel #18
0
        /// <summary>
        /// SlideUseIE
        /// </summary>
        /// <param name="companyName"></param>
        /// <returns></returns>
        private static string SlideUseIE(string companyName)
        {
            const string url = "http://www.gsxt.gov.cn/index.html";

            InternetExplorerOptions options = new InternetExplorerOptions();

            //取消浏览器的保护模式 设置为true
            options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
            //这里用chrome浏览器 ie浏览器有问题
            //var options = new ChromeOptions();
            //options.AddArgument("--user-agent=Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
            //options.AddArgument("--start-maximized");

            using (var driver = new InternetExplorerDriver(options))
            {
                //设置浏览器大小 设置为最大 元素的X,Y坐标就准了 不然就不准(不知道原因)
                driver.Manage().Window.Maximize();


                var navigation = driver.Navigate();
                navigation.GoToUrl(url);
                //等待时间
                var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
                //等待元素全部加载完成
                wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("keyword")));
                var keyWord = driver.FindElement(By.Id("keyword"));
                //keyWord.SendKeys("温州红辣椒电子商务有限公司");
                keyWord.SendKeys(companyName);

                //等待元素全部加载完成
                wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("btn_query")));

                var js       = (IJavaScriptExecutor)driver;
                var btnQuery = driver.FindElement(By.Id("btn_query"));
                //经测试,这里要停一下,不然刚得到元素就click可能不会出现滑动块窗口(很坑的地方)
                Thread.Sleep(1000);
                js.ExecuteScript("arguments[0].click();", btnQuery);
                //btnQuery.Click();
                //btnQuery.SendKeys(Keys.Enter);

                //截图加滑动处理
                //因为只有一个弹出窗口,所以直接进到这个里面就好了
                var allWindowsId = driver.WindowHandles;
                if (allWindowsId.Count != 1)
                {
                    throw new Exception("多个弹出窗口。");
                }

                foreach (var windowId in allWindowsId)
                {
                    driver.SwitchTo().Window(windowId);
                }


                //等待元素全部加载完成
                wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.CssSelector("div.gt_box")));

                //找到图片
                var imageBox = driver.FindElement(By.CssSelector("div.gt_box"));
                //先休息一会,不然截图不对
                Thread.Sleep(1000);
                //截图得到子图片
                var imageFirst = GetSubImage(driver, imageBox);
                imageFirst?.Save("c:/test.png");


                var slide  = driver.FindElement(By.CssSelector("div.gt_slider_knob.gt_show"));
                var action = new Actions(driver);
                //移到起始位置
                action.ClickAndHold(slide).MoveByOffset(0, 0).Perform();
                //先休息一会,不然截图不对
                Thread.Sleep(1000);
                //再截图得到子图片
                var imageSecond = GetSubImage(driver, imageBox);
                imageSecond?.Save("c:/test1.png");

                var pass     = false;
                var tryTimes = 0;
                //试5次或者pass
                while (tryTimes++ < 5 && !pass)
                {
                    Console.WriteLine($"第{tryTimes}次。");
                    var left = SlideImageHandler.FindXDiffRectangeOfTwoImage(imageFirst, imageSecond) - 7;
                    Console.WriteLine($"减7后等于:{left}");
                    if (left <= 0)
                    {
                        Console.WriteLine("算出的距离小于等于0");
                        continue;
                        //throw new Exception("算出的距离小于等于0");
                    }
                    var pointsTrace = SlideImageHandler.GeTracePoints(left);

                    //移动
                    MoveHandler(pointsTrace, action, slide);

                    wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.XPath("//div[@class='gt_info_text']/span[@class='gt_info_type']")));
                    //找得到元素,但是它不在当前可见的页面上。
                    var infoText = driver.FindElement(By.XPath("//div[@class='gt_info_text']/span[@class='gt_info_type']")).Text;
                    if (infoText.Contains("验证通过"))
                    {
                        pass = true;
                    }
                    //如果判断为非人行为 刷新验证码 重新截图
                    else if (infoText.Contains("再来一次"))
                    {
                        wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.ClassName("gt_refresh_button")));
                        var refreshButtom = driver.FindElement(By.ClassName("gt_refresh_button"));
                        refreshButtom.Click();
                        //等待元素全部加载完成
                        wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.CssSelector("div.gt_box")));
                        //找到图片
                        imageBox = driver.FindElement(By.CssSelector("div.gt_box"));
                        //先休息一会,不然截图不对
                        Thread.Sleep(1000);
                        //截图得到子图片
                        imageFirst = GetSubImage(driver, imageBox);
                        imageFirst?.Save("c:/test.png");
                        //移到起始位置
                        action.ClickAndHold(slide).MoveByOffset(0, 0).Perform();
                        //先休息一会,不然截图不对
                        Thread.Sleep(1000);
                        //再截图得到子图片
                        imageSecond = GetSubImage(driver, imageBox);
                        imageSecond?.Save("c:/test1.png");
                        Console.WriteLine("刷新图片。");
                        pass = false;
                    }
                    else
                    {
                        pass = false;
                    }
                    Console.WriteLine($"pass:{pass}。");
                    //先休息一会,不然截图不对
                    //Thread.Sleep(1000);
                    var imageThird = GetSubImage(driver, imageBox);
                    imageThird?.Save("c:/test2.png");
                }


                Console.WriteLine(pass ? "验证通过。" : "验证失败。");

                if (!pass)
                {
                    Console.WriteLine("极速验证码验证失败。");
                    //throw new Exception("极速验证码验证失败。");
                }
                //得到页面内容
                return(driver.PageSource);
            }
        }
Beispiel #19
0
        private static InternetExplorerDriver GetIEDriver()
        {
            InternetExplorerDriver driver = new InternetExplorerDriver(GetIEOptions());

            return(driver);
        }
Beispiel #20
0
        private void button1_Click_1(object sender, EventArgs e)
        {
            input_id = textBox1.Text;
            input_pw = textBox2.Text;

            if (textBox1.Text == "" && textBox2.Text == "")
            {
                MessageBox.Show(new Form {
                    TopMost = true
                }, "아이디 또는 비밀번호를 제대로 입력해주세요.");
                return;
            }
            else
            {
                Student.input_id = input_id;
            }

            textBox1.Text = "";
            textBox2.Text = "";

            int Now_Hour = int.Parse(DateTime.Now.ToString("hh"));

            var ChromeService  = ChromeDriverService.CreateDefaultService();
            var Chrome_options = new ChromeOptions();

            Chrome_options.AddArgument("--window-size=1280,720");
            ChromeService.HideCommandPromptWindow = true;

            var IEService = InternetExplorerDriverService.CreateDefaultService();

            IEService.HideCommandPromptWindow = true;

            var IEoptions = new InternetExplorerOptions();

            IEoptions.IntroduceInstabilityByIgnoringProtectedModeSettings = true;


            switch (comboBox1.SelectedIndex)
            {
            case 0:

                IWebDriver sys_driver = new InternetExplorerDriver(IEService, IEoptions);
                Login_Sys(input_id, input_pw, sys_driver);

                break;

            case 1:

                IWebDriver check_driver = new ChromeDriver(ChromeService, Chrome_options);
                Login_Check(input_id, input_pw, check_driver);

                if (textBox3.Text != "")
                {
                    string link_value;
                    check_driver.Url = "https://check.kimpo.ac.kr/index.php/student/main";
                    if (Now_Hour == 9)
                    {
                        IWebElement First_Class = check_driver.FindElement(By.XPath("//*[@id='schedule']/ul/li[1]"));
                        link_value = First_Class.GetAttribute("lid");
                        First_Class.Click();
                        Check(check_driver, link_value);
                    }
                    else if (Now_Hour == 1)
                    {
                        IWebElement Second_Class = check_driver.FindElement(By.XPath("//*[@id='schedule']/ul/li[4]"));
                        link_value = Second_Class.GetAttribute("lid");
                        Second_Class.Click();
                        Check(check_driver, link_value);
                    }
                    else if (Now_Hour == 4)
                    {
                        IWebElement Third_Class = check_driver.FindElement(By.XPath("//*[@id='schedule']/ul/li[7]"));
                        link_value = Third_Class.GetAttribute("lid");
                        Third_Class.Click();
                        Check(check_driver, link_value);
                    }
                    else
                    {
                        MessageBox.Show(new Form {
                            TopMost = true
                        }, "출석체크가 가능한 시간이 아닙니다.");
                    }
                }

                break;

            case 2:

                IWebDriver ncs_driver = new ChromeDriver(ChromeService, Chrome_options);
                Login_Ncs(input_id, input_pw, ncs_driver);

                break;

            default:
                MessageBox.Show(new Form {
                    TopMost = true
                }, "항목을 선택해주세요...!");
                break;
            }
        }
Beispiel #21
0
        public override void RunCommand(object sender)
        {
            var engine           = (AutomationEngineInstance)sender;
            var convertedOptions = v_SeleniumOptions.ConvertUserVariableToString(engine);
            var vURL             = v_URL.ConvertUserVariableToString(engine);

            IWebDriver webDriver;

            switch (v_EngineType)
            {
            case "Chrome":
                ChromeOptions chromeOptions = new ChromeOptions();
                chromeOptions.AddUserProfilePreference("download.prompt_for_download", true);

                if (!string.IsNullOrEmpty(convertedOptions.Trim()))
                {
                    chromeOptions.AddArguments(convertedOptions);
                }

                webDriver = new ChromeDriver(chromeOptions);
                break;

            case "Firefox":
                string firefoxExecutablePath = @"C:\Program Files\Mozilla Firefox\firefox.exe";
                if (!File.Exists(firefoxExecutablePath))
                {
                    throw new FileNotFoundException($"Could not locate '{firefoxExecutablePath}'");
                }

                FirefoxOptions firefoxOptions = new FirefoxOptions();
                firefoxOptions.BrowserExecutableLocation = firefoxExecutablePath;

                webDriver = new FirefoxDriver(firefoxOptions);
                break;

            case "Internet Explorer":
                InternetExplorerOptions ieOptions = new InternetExplorerOptions();
                ieOptions.IgnoreZoomLevel = true;

                webDriver = new InternetExplorerDriver(ieOptions);
                break;

            default:
                throw new Exception($"The selected engine type '{v_EngineType}' is not valid.");
            }

            //add app instance
            webDriver.AddAppInstance(engine, v_InstanceName);

            //handle app instance tracking
            if (v_InstanceTracking == "Keep Instance Alive")
            {
                GlobalAppInstances.AddInstance(v_InstanceName, webDriver);
            }

            switch (v_BrowserWindowOption)
            {
            case "Maximize":
                webDriver.Manage().Window.Maximize();
                break;

            case "Normal":
            case "":
            default:
                break;
            }

            if (!string.IsNullOrEmpty(vURL.Trim()) && vURL.Trim() != "https://")
            {
                try
                {
                    webDriver.Navigate().GoToUrl(vURL);
                }
                catch (Exception ex)
                {
                    if (!vURL.StartsWith("https://"))
                    {
                        webDriver.Navigate().GoToUrl("https://" + vURL);
                    }
                    else
                    {
                        throw ex;
                    }
                }
            }
        }
Beispiel #22
0
        /// <summary>
        /// Intantiates a WebDriver (creating a session) using the current App.config.
        /// </summary>
        public static IWebDriver Create()
        {
            #region Properties

            // Define the current App.config (from the App.config)
            string appConfig = ConfigurationManager.AppSettings["appConfig"];
            // Declare a string for the Base URL
            string baseUrl = ConfigurationManager.AppSettings["baseUrl"];
            // Define the Browser (from the App.config)
            string browser = ConfigurationManager.AppSettings["browser"] ?? "chrome";
            // Define the Grid Hub URI (from the App.config)
            Uri hubUri = new Uri(ConfigurationManager.AppSettings["hubUri"] ?? "http://*****:*****@"--disable-extensions");
                    // Use Remote Chrome
                    try
                    {
                        // Create a remote session using the Grid Hub URI (from the App.config)
                        returnValue = new RemoteWebDriver(hubUri, options);
                    }
                    // Use Local Chrome
                    catch
                    {
                        // Write result to log
                        Log.WriteLine(logPadding.InfoPadding + "[WARNING] Unable to create a remote session, so creating a local one.");
                        // Create a local session
                        returnValue = new ChromeDriver(options);
                    }
                }
                else if (browser.Equals("edge"))
                {
                    // Create an options object to specify command line arguments for the Edge web driver
                    EdgeOptions options = new EdgeOptions();
                    // Use Remote Edge
                    try
                    {
                        // Create a remote session using the Grid Hub URI (from the App.config)
                        returnValue = new RemoteWebDriver(hubUri, options);
                    }
                    // Use Local Edge
                    catch
                    {
                        // Write result to log
                        Log.WriteLine(logPadding.InfoPadding + "[WARNING] Unable to create a remote session, so creating a local one.");
                        // Create a local session
                        returnValue = new EdgeDriver(options);
                    }
                }
                else if (browser.Equals("firefox"))
                {
                    // Create an options object to specify command line arguments for the Firefox web driver
                    FirefoxOptions options = new FirefoxOptions();
                    // Use Remote Firefox
                    try
                    {
                        // Create a remote session using the Grid Hub URI (from the App.config)
                        returnValue = new RemoteWebDriver(hubUri, options);
                    }
                    // Use Local Firefox
                    catch
                    {
                        // Write result to log
                        Log.WriteLine(logPadding.InfoPadding + "[WARNING] Unable to create a remote session, so creating a local one.");
                        try
                        {
                            // Create a local session
                            returnValue = new FirefoxDriver(options);
                        }
                        catch
                        {
                            // Write result to log
                            Log.WriteLine(logPadding.InfoPadding + "[WARNING] Unable to create a local session using the default location.");
                            // Load Firefox From Specific Location
                            options.BrowserExecutableLocation = @"C:\Program Files\Mozilla Firefox\firefox.exe";
                            Log.WriteLine(logPadding.InfoPadding + "[INFO] Browser Executable Location: " + options.BrowserExecutableLocation);
                            // Create a local session
                            returnValue = new FirefoxDriver(options);
                        }
                    }
                }
                else if (browser.Equals("safari"))
                {
                    // Create an options object to specify command line arguments for the Safari web driver
                    SafariOptions options = new SafariOptions();
                    // Create a remote session using the Grid Hub URI (from the App.config)
                    returnValue = new RemoteWebDriver(hubUri, options);
                }
                else
                {
                    throw new NotImplementedException(browser + " not handled in Session.Create() method.");
                }

                // Save a reference to the current Test's driver in its TestContext
                TestContext.Set("driver", returnValue);
                // Save a reference to the current Test's base url in its TestContext
                TestContext.Set("baseUrl", baseUrl);
                // Save a reference to the current Test's screenshot folder in its TestContext
                TestContext.Set("screenshotFolder", screenshotFolder);

                // Logging - After action
                Log.Success(logPadding.Padding);
                Log.Finally(logPadding.Padding);
            }
            catch (Exception e)
            {
                // Logging - After action exception
                sb = Log.Exception(sb, e);
                // Fail current Test
                Assert.Fail(sb.ToString());
            }
            finally
            {
                // Logging - After action
                Log.Finally(logPadding.Padding);
            }
            // Return the return value
            return(returnValue);
        }
Beispiel #23
0
        //public static HomePage Launch(string homePageUrl, string browser = "ie")
        public static HomePage Launch(string homePageUrl, string browser, string browserExecutableLocation)
        {
            // based on the browser passed in, created your web driver
            IWebDriver driver;

            if (browser.StartsWith("chrome"))
            {
                var chromeOptions = new ChromeOptions();

                if (browser.EndsWith("headless"))
                {
                    chromeOptions.AddArgument("--headless");
                }

                if (!String.IsNullOrEmpty(browserExecutableLocation))
                {
                    chromeOptions.BinaryLocation = browserExecutableLocation;
                }

                driver = new ChromeDriver(chromeOptions);
            }
            else if (browser.StartsWith("firefox"))
            {
                var firefoxOptions = new FirefoxOptions();

                if (browser.EndsWith("headless"))
                {
                    firefoxOptions.AddArgument("--headless");
                }

                if (!String.IsNullOrEmpty(browserExecutableLocation))
                {
                    firefoxOptions.BrowserExecutableLocation = browserExecutableLocation;
                }

                driver = new FirefoxDriver(firefoxOptions);
            }
            else if (browser.StartsWith("edge"))
            {
                var edgeOptions = new EdgeOptions();

                driver = new EdgeDriver(edgeOptions);
            }

            else if (browser.Equals("phantomjs"))
            {
                driver = new PhantomJSDriver();
            }
            else
            {
                var ieOptions = new InternetExplorerOptions();
                ieOptions.IgnoreZoomLevel = true;

                driver = new InternetExplorerDriver(ieOptions);
            }

            // set the window size of the browser and browse to the home page
            driver.Manage().Window.Size = new Size(1920, 1080);
            driver.Navigate().GoToUrl(homePageUrl);
            return(new HomePage(driver));
        }
        public void  RunParcelTaxReaderInfo(List <string> parcels)
        {
            int       numberOfParcels = parcels.Count;
            int       rowCount        = 0;
            Stopwatch stopWatch       = new Stopwatch();
            Hashtable currentRow      = null;

            currentRow = new Hashtable();
            bool runAutomation = true;

            string parcelNumber    = string.Empty;
            string rawParcelNumber = string.Empty;

            while (runAutomation && numberOfParcels > 0)
            {
                appendRow = true;

                driver = new InternetExplorerDriver(_seleniumDriverFolder);
                try
                {
                    rawParcelNumber = parcels[rowCount];
                    parcelNumber    = rawParcelNumber.Replace(" ", string.Empty);

                    stopWatch.Start();

                    currentRow = new TruantPropertyTaxRecord(driver, parcelNumber).GetRow(new Hashtable());
                    currentRow = new EReal(driver, parcelNumber).GetRow(currentRow);

                    currentRow["TaxId"]    = rawParcelNumber;
                    currentRow["RawTaxId"] = rawParcelNumber;

                    stopWatch.Stop();
                    TimeSpan ts          = stopWatch.Elapsed;
                    string   elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                         ts.Hours,
                                                         ts.Minutes,
                                                         ts.Seconds,
                                                         ts.Milliseconds / 10);


                    currentRow["QueryTime"] = elapsedTime;

                    _dataReader.InsertRecord(currentRow);
                    Console.WriteLine("Current Row : " + rowCount);
                    if (rowCount != 0 && rowCount % 20 == 0)
                    {
                        //Thread.Sleep(300000);
                        Console.WriteLine("Execution Paused");
                    }


                    stopWatch.Reset();
                    driver.Dispose();
                }
                catch (ReRerunException re)
                {
                    runAutomation = ReRunLogic(re);
                }
                if (appendRow)
                {
                    retryCount = 0;
                    rowCount++;

                    if ((rowCount > numberOfParcels - 1))
                    {
                        runAutomation = false;
                    }
                }
            }

            driver.Dispose();
            Console.WriteLine("Crawl Complete");
        }
Beispiel #25
0
        /// <summary>
        /// Configures the 'Networking' tab settings
        /// </summary>
        /// <param name="browser">The IE Browser instance to use.</param>
        public void ConfigureNetworking(InternetExplorerDriver browser)
        {
            By networkingLinkLocator = By.Id("Networking");

            if (ElementExists(networkingLinkLocator, browser))
            {
                _owner.OnUpdateStatus(this, "Clicking on the 'Networking' link.");
                ClickElement(browser, browser.FindElement(networkingLinkLocator));
            }
            else
            {
                throw new EwsAutomationException("Could not find the 'Networking' link.");
            }

            By tcpIpSettingLinkLocator = By.LinkText("TCP/IP Settings");

            if (ElementExists(tcpIpSettingLinkLocator, browser))
            {
                _owner.OnUpdateStatus(this, "Moving to the TCP/IP Settings page.");
                ClickElement(browser, browser.FindElement(tcpIpSettingLinkLocator));
            }
            else
            {
                ////throw new EwsAutomationException("Could not find the 'TCP/IP Settings' link.");
                // For some reason Selenium is unable to see the text for this link at all.  It manages to get a collection of the links but the
                // text property of them is all empty.  In that case we're just going to manually navigate.
                // This only occurs on smaller window sizers with the navigation menu is hidden.
                browser.Navigate().GoToUrl($"http://{_device.Address}/tcp_summary.htm");
            }

            By ipv6LinkLocator = By.LinkText("TCP/IP(v6)");

            if (ElementExists(ipv6LinkLocator, browser))
            {
                _owner.OnUpdateStatus(this, "Clicking the 'TCP/IP(v6)' link.");
                ClickElement(browser, browser.FindElement(ipv6LinkLocator));
            }
            else
            {
                ////throw new EwsAutomationException("Could not find the 'TCP/IP(v6)' link.");
                // For some reason Selenium is unable to see the text for this link at all.  It manages to get a collection of the links but the
                // text property of them is all empty.  In that case we're just going to manually navigate.
                // This only occurs on smaller window sizes where the navigation menu is hidden.
                browser.Navigate().GoToUrl($"http://{_device.Address}/tcpipv6.htm");
            }

            _owner.OnUpdateStatus(this, "Unchecking the IP6 Enable checkbox.");
            if (browser.FindElement(By.Id("IP6_Enable")).Selected)
            {
                ClickElement(browser, browser.FindElement(By.Id("IP6_Enable")));
            }

            _owner.OnUpdateStatus(this, "Clicking the 'Apply' link.");
            browser.FindElement(By.Id("Apply")).Click();

            if (ElementExists(By.Name("ok"), browser))
            {
                _owner.OnUpdateStatus(this, "Clicking the 'OK' link.");
                ClickElement(browser, browser.FindElement(By.Name("ok")));
            }

            By authenticationLinkLocator = By.PartialLinkText("802.1X Authentication");

            if (ElementExists(authenticationLinkLocator, browser))
            {
                _owner.OnUpdateStatus(this, "Clicking the '802.1X Authentication' link.");
                ClickElement(browser, browser.FindElement(authenticationLinkLocator));
            }
            else
            {
                ////throw new EwsAutomationException("Could not find the '802.1X Authentication' link.");
                // For some reason Selenium is unable to see the text for this link at all.  It manages to get a collection of the links but the
                // text property of them is all empty.  In that case we're just going to manually navigate.
                // This only occurs on smaller window sizes where the navigation sidebar is hidden.
                _owner.OnUpdateStatus(this, "Navigating to the '802.1X Authentication' page.");
                browser.Navigate().GoToUrl($"http://{_device.Address}/dot1x_config.htm");
            }

            By managementProtocolsLinkLocator = By.LinkText("Mgmt. Protocols");

            if (ElementExists(managementProtocolsLinkLocator, browser))
            {
                _owner.OnUpdateStatus(this, "Clicking the 'Mgmt. Protocols' link.");
                ClickElement(browser, browser.FindElement(managementProtocolsLinkLocator));

                // Sometimes clicks don't navigate, still investigating and hope to remove this soon.
                if (browser.Url != $"http://{ (object)_device.Address}/websecurity/http_mgmt.html")
                {
                    browser.Navigate().GoToUrl($"http://{ (object)_device.Address}/websecurity/http_mgmt.html");
                }
            }
            else
            {
                ////throw new EwsAutomationException("Could not find the 'Mgmt. Protocols' link.");
                // For some reason Selenium is unable to see the text for this link at all.  It manages to get a collection of the links but the
                // text property of them is all empty.  In that case we're just going to manually navigate.
                // This only occurs on smaller window sizes where the navigation sidebar is hidden.
                _owner.OnUpdateStatus(this, "Navigating to the 'Mgmt. Protocols' page.");
                browser.Navigate().GoToUrl($"http://{_device.Address}/websecurity/http_mgmt.html");
            }

            _owner.OnUpdateStatus(this, "Unchecking the encrypt all checkbox.");
            var encryptAllCheckbox = browser.FindElement(By.Id("encryptall"));

            if (encryptAllCheckbox.Selected)
            {
                encryptAllCheckbox.Click();
            }

            _owner.OnUpdateStatus(this, "Clicking the 'Apply' link.");
            browser.FindElement(By.Name("Apply")).Click();

            if (ElementExists(By.Name("ok"), browser))
            {
                _owner.OnUpdateStatus(this, "Clicking the 'OK' link.");
                browser.FindElement(By.Name("ok")).Click();
            }
        }
Beispiel #26
0
        public void FluxoNSRH(string matricula)
        {
            /*Variavel de inicialização de opções do Internet Explorer*/
            InternetExplorerOptions options = new InternetExplorerOptions();

            /*permite que o driver do navegador ignore modais de diálogo que estão habilitadas,
             * porém não estão visíveis ao usuário*/
            options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
            DesiredCapabilities ieCapabilities = options.ToCapabilities() as DesiredCapabilities;

            ieCapabilities.SetCapability("Ignore", InternetExplorerUnexpectedAlertBehavior.Ignore);

            /*Driver do navegador: é a base de qualquer teste automatizado.
             * Ele é responsável por acessar URL´s, acessar elementos de tela e alterar o tamanho da página, por exemplo*/
            IWebDriver driver = new InternetExplorerDriver(options);

            /* Variável do tipo WebDriverWait: utilizada quando é preciso aguardar algum elemento em tela
             * estar visível ou habilitado para executar uma ação. Ela irá esperar até o tempo definido. */
            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));

            /* Variável do tipo IJavaScriptExecutor: utilizada para acessar elementos de tela que
             * utilizam de mecanismos do JavaScript*/
            IJavaScriptExecutor jse = (IJavaScriptExecutor)driver;


            #region LOGIN
            driver.Url = "https://nsrh-teste.newspace.com.br/ ";

            /*Maximizando a janela*/
            driver.Manage().Window.Maximize();

            /*Driver acessando um elemento textbox e enviando um dado */
            driver.FindElement(By.Id("MainContent_txtUsuario")).SendKeys("desenv");
            driver.FindElement(By.Id("MainContent_txtSenha")).SendKeys("123");
            wait.Until(d => d.FindElement(By.CssSelector(".btn.btn-default.btnLoginEntrar")).Enabled);
            driver.FindElement(By.CssSelector(".btn.btn-default.btnLoginEntrar")).Click();
            #endregion

            #region APLICAÇÃO

            /*Exemplo de uma espera explícita: aguardando o elemento estar visível para executar
             * a próxima linha de comando*/
            wait.Until(d => d.FindElement(By.Id("MainContent_ddlCliente")).Displayed);

            /* Variável do tipo IWebElement: armazena elementos de tela.
             * Seu uso mais comum é em situações em que temos uma combo box de dados, mas apenas um dado é relevante, como mostra as próximas linhas*/
            IWebElement element = driver.FindElement(By.Id("MainContent_ddlCliente"));

            /*Variável do tipo SelectElement: utiliza a variável do tipo IWebElement como referência para selecionar um dado específico da combo box */
            SelectElement selectElement = new SelectElement(element);
            selectElement.SelectByText("Grupo Brasanitas");

            /*Espera implícita Thread: esse comando força o sistema a parar por um tempo determinado (milisegundos).
             * Seu uso não é muito recomendado, mas há exceções.
             * Ex.: quando não quer esperar um determinado elemento estar visível na tela*/
            Thread.Sleep(1000);
            driver.FindElement(By.CssSelector(".btn.btn-default.btnLoginEntrar")).Click();
            #endregion

            #region UPLOAD
            wait.Until(d => d.FindElement(By.XPath("//a[text()='Upload']")).Displayed);
            driver.FindElement(By.XPath("//a[text()='Upload']")).Click();
            wait.Until(d => d.FindElement(By.XPath("//a[text()='Documento']")).Displayed);
            driver.FindElement(By.XPath("//a[text()='Documento']")).Click();
            #endregion

            #region PESQUISA UPLOAD

            driver.FindElement(By.Id("MainContent_ucPesquisaComum_txtEtiqueta")).SendKeys(matricula);
            driver.FindElement(By.Id("btnPesquisar")).Click();
            Thread.Sleep(2000);
            try
            {
                driver.FindElement(By.Id("btnUpload")).Click();
            }
            catch (NoSuchElementException)
            {
                Assert.Fail("Etiqueta não está na fila 'Aguardando Upload'.");
            }

            #endregion

            #region UPLOAD DE IMAGEM

            wait.Until(d => d.FindElement(By.XPath("//*[@id='ctl00_MainContent_ucArquivos_btnSelecionar']")).Displayed);
            IWebElement file = driver.FindElement(By.XPath("//*[@id='ctl00_MainContent_ucArquivos_btnSelecionar']"));

            //for (int i = 0; i <= 2; i++)
            //{
            //    UploadCPF(file);
            //    Thread.Sleep(1000);
            //    cont++;
            //}

            UploadTitulo(file);
            Thread.Sleep(1000);

            driver.FindElement(By.Id("ctl00_MainContent_ucArquivos_btnUpload")).Click();
            Thread.Sleep(2000);
            try
            {
                wait.Until(d => d.FindElement(By.Id("ctl00_MainContent_ucArquivos_btnFinalizar")).Enabled);
                driver.FindElement(By.Id("ctl00_MainContent_ucArquivos_btnFinalizar")).Click();
            }
            catch (WebDriverTimeoutException)
            {
                Assert.Fail("Problemas ao finalizar o Upload.");
            }


            #endregion

            #region TIPIFICAÇÃO
            wait.Until(d => d.FindElement(By.XPath("//a[text()='Análise']")).Displayed);
            driver.FindElement(By.XPath("//a[text()='Análise']")).Click();
            wait.Until(d => d.FindElement(By.XPath("//a[text()='Tipificação']")).Displayed);
            driver.FindElement(By.XPath("//a[text()='Tipificação']")).Click();
            Thread.Sleep(1000);
            //for (int i = 0; i <= cont; i++)
            //{
            driver.FindElement(By.Id("txtFiltro")).SendKeys("CPF");
            jse.ExecuteScript("window.scrollBy(0,250)", "");
            driver.FindElement(By.XPath("//button[text()='Salvar']")).Click();
            Thread.Sleep(1000);
            //}
            //driver.FindElement(By.Id("txtFiltro")).SendKeys("RG");
            //jse.ExecuteScript("window.scrollBy(0,250)", "");
            //driver.FindElement(By.XPath("//button[text()='Salvar']")).Click();

            try
            {
                wait.Until(d => d.FindElement(By.XPath("//div[text()= 'Não existem mais documentos a serem Tipificados.']")).Displayed);
                driver.FindElement(By.CssSelector(".btn.btn-default.btnModalCancelar")).Click();
            }
            catch (WebDriverTimeoutException)
            {
                Assert.Fail("Não foram encontrados documentos para tipificação.");
            }

            #endregion

            #region FORMALIZAÇÃO
            driver.FindElement(By.XPath("//a[text()='Análise']")).Click();
            wait.Until(d => d.FindElement(By.XPath("//a[text()='Formalização']")).Displayed);
            driver.FindElement(By.XPath("//a[text()='Formalização']")).Click();
            wait.Until(d => d.FindElement(By.Id("MainContent_ucPesquisaComum_txtEtiqueta")).Displayed);
            driver.FindElement(By.Id("MainContent_ucPesquisaComum_txtEtiqueta")).SendKeys("99984453722610");
            Thread.Sleep(1000);
            driver.FindElement(By.Id("btnPesquisar")).Click();

            try
            {
                wait.Until(d => d.FindElement(By.Id("ctl00_MainContent_ucPesquisaComum_radCampos_ctl00__0")).Displayed);
                driver.FindElement(By.Id("btnPesquisar")).Click();
            }
            catch (WebDriverTimeoutException)
            {
                Assert.Fail("Etiqueta não foi encontrada. Verificar se o documento foi tipificado corretamente.");
            }
            driver.FindElement(By.Id("btnAnalisar")).Click();
            //do
            //{
            //    driver.FindElement(By.Id("btnPesquisar")).Click();
            //} while (wait.Until(d => d.FindElement(By.Id("ctl00_MainContent_ucPesquisaComum_radCampos_ctl00__0")).Displayed) == false);

            #endregion

            #region ANÁLISE FORMALIZAÇÃO
            wait.Until(d => d.FindElement(By.Id("chkVerTodos")).Enabled);
            driver.FindElement(By.Id("chkVerTodos")).Click();

            for (int i = 0; i <= 110; i++)
            {
                string        id      = "//div[@class='col-md-3']/select[@id='MainContent_rptCriterio_ddlCriterio_" + i + "']";
                SelectElement escolha = new SelectElement(driver.FindElement(By.XPath(id)));
                escolha.SelectByText("Sim");
            }

            driver.FindElement(By.Id("btnSalvar")).Click();
            #endregion

            #region AGUARDANDO FISICO

            wait.Until(d => d.FindElement(By.Id("MainContent_ucPesquisaComum_txtEtiqueta")).Displayed);
            driver.FindElement(By.XPath("//a[text()='Protocolo']")).Click();
            wait.Until(d => d.FindElement(By.XPath("//a[text()='Envio']")).Displayed);
            driver.FindElement(By.XPath("//a[text()='Envio']")).Click();
            wait.Until(d => d.FindElement(By.Id("txtEtiqueta")).Displayed);
            driver.FindElement(By.Id("txtEtiqueta")).SendKeys(matricula);
            driver.FindElement(By.Id("btnPesquisar")).Click();
            wait.Until(d => d.FindElement(By.Id("ctl00_MainContent_radPesquisa_ctl00__0")).Displayed);
            driver.FindElement(By.Id("ctl00_MainContent_radPesquisa_ctl00__0")).Click();
            driver.FindElement(By.Id("btnAdicionar")).Click();
            Thread.Sleep(1000);
            numProtocolo = driver.FindElement(By.Id("lblValorProtocolo")).Text;
            driver.FindElement(By.Id("btnFinalizar")).Click();
            wait.Until(d => d.FindElement(By.Id("numMalote")).Displayed);
            driver.FindElement(By.Id("numMalote")).SendKeys(numProtocolo);
            driver.FindElement(By.Id("numLacre")).SendKeys(numProtocolo);
            driver.FindElement(By.Id("btnGerarProt")).Click();

            #endregion

            #region CAIXA TEMPORÁRIA

            string caixa = "CX" + numProtocolo;
            wait.Until(d => d.FindElement(By.XPath("//button[text()= 'Imprimir Protocolo']")).Displayed);
            driver.FindElement(By.XPath("//a[text()= 'Expedição']")).Click();
            wait.Until(d => d.FindElement(By.XPath("//a[text()= 'Caixa Temporária']")).Displayed);
            driver.FindElement(By.XPath("//a[text()= 'Caixa Temporária']")).Click();
            wait.Until(d => d.FindElement(By.Id("txtCodigoCaixa")).Displayed);
            driver.FindElement(By.Id("txtCodigoCaixa")).SendKeys(caixa);
            driver.FindElement(By.Id("txtDescricaoCaixa")).SendKeys("Teste");
            driver.FindElement(By.Id("btnSalvar")).Click();
            #endregion

            #region RECEPÇÃO PROTOCOLO
            Thread.Sleep(2000);
            driver.FindElement(By.XPath("//a[text()='Recepção']")).Click();
            wait.Until(d => d.FindElement(By.XPath("//ul[@id = 'NavigationMenu:submenu:10']/li[@class= 'dynamic']/a[text()= 'Protocolo']")).Displayed);
            driver.FindElement(By.XPath("//ul[@id = 'NavigationMenu:submenu:10']/li[@class= 'dynamic']/a[text()= 'Protocolo']")).Click();
            wait.Until(d => d.FindElement(By.Id("btnContinuar")).Displayed);
            driver.FindElement(By.Id("txtProtocolo")).SendKeys(numProtocolo);
            driver.FindElement(By.Id("btnContinuar")).Click();
            wait.Until(d => d.FindElement(By.Id("txtCaixaTemp")).Displayed);
            driver.FindElement(By.Id("txtCaixaTemp")).SendKeys(caixa);
            driver.FindElement(By.Id("txtEtiqueta")).SendKeys(matricula);
            driver.FindElement(By.Id("btnPesquisar")).Click();
            driver.FindElement(By.Id("btnRecepcionar")).Click();
            driver.FindElement(By.Id("btnFechar")).Click();

            #endregion

            #region RECEPÇÃO MALOTE
            wait.Until(d => d.FindElement(By.Id("btnRecepcionar")).Displayed);
            driver.FindElement(By.XPath("//a[text()='Recepção']")).Click();
            wait.Until(d => d.FindElement(By.XPath("//ul[@id = 'NavigationMenu:submenu:10']/li[@class= 'dynamic']/a[text()= 'Malote']")).Displayed);
            driver.FindElement(By.XPath("//ul[@id = 'NavigationMenu:submenu:10']/li[@class= 'dynamic']/a[text()= 'Malote']")).Click();
            wait.Until(d => d.FindElement(By.Id("txtMalote")).Displayed);
            driver.FindElement(By.Id("txtMalote")).SendKeys(numProtocolo);
            driver.FindElement(By.Id("txtLacre")).SendKeys(numProtocolo);
            driver.FindElement(By.Id("btnOK")).Click();
            #endregion

            //driver.Close();
        }
        public void TestLogin()
        {
            // Create a new instance of the Firefox driver.
            // Documentation says we can run with IE with a small code change but this is not working for us
            // Documentation says Google Chrome is possible with an extra download
            // Ref more info at bottom of page: http://www.seleniumhq.org/docs/03_webdriver.jsp

            //20161024 change from FireFox to InternetExplorer
            IWebDriver driver = new InternetExplorerDriver();

            System.Threading.Thread.Sleep(6000);
            //IWebDriver driver = new FirefoxDriver();

            //Simplest way of dealing with time taken for pages to load.  One line here does it all.
            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));

            IWebElement element;

            driver.Navigate().GoToUrl("http://*****:*****@example.com");
            System.Threading.Thread.Sleep(2000);

            element = driver.FindElement(By.Name("Password"));
            element.SendKeys("Admin@123456");
            System.Threading.Thread.Sleep(2000);
            // Now submit the form. WebDriver will find the form for us from the element
            element.Submit();

            //Check out the page for results
            //string s = driver.PageSource;
            //bool test = s.Contains("Hello [email protected]!");

            //Assert.IsTrue(test, "Not logged in as attempted");

            System.Threading.Thread.Sleep(2000);

            //buy something
            //look in the catalog under "communications"
            element = driver.FindElement(By.LinkText("Tools"));
            element.Click();
            System.Threading.Thread.Sleep(6000);

            //Challenge - input element button does not have id or name
            //Success - use XPath to find the input with onclick="NavCart('JWLTRANS6')"
            element = driver.FindElement(By.XPath("//input[@onclick=\"NavCart('1MOR4ME')\"]"));
            element.Click();

            System.Threading.Thread.Sleep(2000);

            //We are now in the shopping cart
            //Change quantity
            element = driver.FindElement(By.Id("quantity_1"));
            //We want to clear the a"1" that is already there
            element.Clear();
            element.SendKeys("2");
            System.Threading.Thread.Sleep(2000);

            element = driver.FindElement(By.XPath("//input[@value=\"Go To Checkout\"]"));
            System.Threading.Thread.Sleep(2000);
            element.Click();

            //Major page navigation, give some time
            System.Threading.Thread.Sleep(2000);

            //Checkout Form

            element = driver.FindElement(By.Id("CustomerName"));
            element.SendKeys("John Tester");
            System.Threading.Thread.Sleep(2000);

            element = driver.FindElement(By.Id("AddressStreet"));
            element.SendKeys("111 Imaginary Rd");
            System.Threading.Thread.Sleep(2000);

            element = driver.FindElement(By.Id("Location"));
            element.SendKeys("Henderson");
            System.Threading.Thread.Sleep(2000);

            element = driver.FindElement(By.Id("Country"));
            element.SendKeys("NZ");
            System.Threading.Thread.Sleep(2000);

            element = driver.FindElement(By.Id("PostCode"));
            element.SendKeys("0612");
            System.Threading.Thread.Sleep(2000);

            element = driver.FindElement(By.Id("CardOwner"));
            element.SendKeys("Mr Tester");
            System.Threading.Thread.Sleep(2000);

            element = driver.FindElement(By.Id("CardType"));
            element.SendKeys("Visa");
            System.Threading.Thread.Sleep(2000);

            element = driver.FindElement(By.Id("CardNumber"));
            element.SendKeys("1111");
            System.Threading.Thread.Sleep(2000);

            element = driver.FindElement(By.Id("CSC"));
            element.SendKeys("111");
            System.Threading.Thread.Sleep(2000);

            element.Submit();
            System.Threading.Thread.Sleep(2000);

            //Check out the page for results
            string s    = driver.PageSource;
            bool   test = s.Contains("Payment of 919.98 is accepted");



            //Close the browser
            //driver.Quit();
        }
 public void Setup()
 {
     Driver  = new InternetExplorerDriver("Resources/");
     Logger  = new LoggerMock();
     Service = new ParseService(Driver, Logger);
 }
        public IWebDriver InitialiseWebDriver()
        {
            // get the driver type from the configuration
            var driverType = Environment.GetEnvironmentVariable("LACTALIS_TEST_SELENIUM_WEB_DRIVER")
                             ?? _seleniumSettings.Webdriver.ToLower();

            switch (driverType)
            {
            case "chrome":
            case "chrome-edge":
                var chromeOptions = new ChromeOptions();

                if (_seleniumSettings.Headless)
                {
                    chromeOptions.AddArguments("--silent-launch");
                    chromeOptions.AddArguments("--no-startup-window");
                    chromeOptions.AddArguments("--no-sandbox");
                    chromeOptions.AddArguments("--headless");
                    chromeOptions.AddArguments("--allow-insecure-localhost");
                    chromeOptions.AddArguments("--disable-gpu");
                    chromeOptions.AddAdditionalCapability("acceptInsecureCerts", true, true);
                }

                // the screensize is set custom if it is either headless or overwritten flag is active
                if (_seleniumSettings.OverwriteDefault || _seleniumSettings.Headless)
                {
                    chromeOptions.AddArguments($"--window-size={_seleniumSettings.Width},{_seleniumSettings.Height}");
                }
                else
                {
                    chromeOptions.AddArguments("--start-maximized");
                }


                /*
                 * for different chromium browsers we will need to specify the binary
                 * path to tell it which version to use
                 */
                string chromeDriverDirectory;
                if (driverType == "chrome")
                {
                    chromeDriverDirectory = ".";
                }
                else if (driverType == "chrome-edge")
                {
                    chromeDriverDirectory = "./EdgeChromiumDriver";
                    var binaryPath = _seleniumSettings.EdgeChromiumPath;
                    chromeOptions.BinaryLocation = binaryPath;
                }
                else
                {
                    throw new Exception("Could not find chromium driver");
                }

                // chrome options are shared between chromium drivers
                WebDriver = new ChromeDriver(ChromeDriverService.CreateDefaultService(chromeDriverDirectory), chromeOptions, TimeSpan.FromMinutes(3));
                break;

            case "firefox":
                var firefoxOptions = new FirefoxOptions();

                /*
                 * this is required to fix a but in dotnet core where there is an implicit timeout waiting
                 * for ipv6 to resolve. See: https://github.com/SeleniumHQ/selenium/issues/6597
                 */
                var service = FirefoxDriverService.CreateDefaultService(".");
                service.Host = "::1";

                if (_seleniumSettings.Headless)
                {
                    firefoxOptions.AddArguments("--silent-launch");
                    firefoxOptions.AddArguments("--no-startup-window");
                    firefoxOptions.AddArguments("--no-sandbox");
                    firefoxOptions.AddArguments("--headless");
                    firefoxOptions.AddArguments("--allow-insecure-localhost");
                    firefoxOptions.AddArguments("--disable-gpu");
                    firefoxOptions.AddAdditionalCapability("acceptInsecureCerts", true, true);
                }


                WebDriver = new FirefoxDriver(service, firefoxOptions);

                if (_seleniumSettings.OverwriteDefault || _seleniumSettings.Headless)
                {
                    WebDriver.Manage().Window.Size = new Size(_seleniumSettings.Width, _seleniumSettings.Height);
                }
                else
                {
                    WebDriver.Manage().Window.Maximize();
                }
                break;

            case "ie":
                WebDriver = new InternetExplorerDriver();

                break;

            case "edge":
                WebDriver = new EdgeDriver();

                break;

            default:
                //default to using a chrome driver which is maximised
                var defaultOptions = new ChromeOptions();
                defaultOptions.AddArguments(new List <string>()
                {
                    "--start-maximized"
                    ,
                });
                WebDriver = new ChromeDriver(".", defaultOptions);
                break;
            }


            return(WebDriver);
        }
Beispiel #30
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);
        }