Example #1
0
        /// <summary>
        /// Creates the remote driver.
        /// </summary>
        /// <returns>The created remote web driver.</returns>
        public IWebDriver Create()
        {
            var remoteUri = this.GetRemoteDriverUri();

            if (remoteUri == null)
            {
                return(this.CreateLocalDriver());
            }

            DriverOptions driverOptions = this.CreateRemoteDriverOptions();

            // Add any additional settings that are not reserved
            var envRegex         = new System.Text.RegularExpressions.Regex("\\$\\{(.+)\\}");
            var reservedSettings = new[] { RemoteUrlSetting };

            foreach (var setting in this.Settings
                     .OfType <NameValueConfigurationElement>()
                     .Where(s => reservedSettings
                            .All(r => !string.Equals(r, s.Name, StringComparison.OrdinalIgnoreCase))))
            {
                // Support environment variables
                var value = setting.Value;
                var match = envRegex.Match(value);
                if (match.Success)
                {
                    value = SettingHelper.GetEnvironmentVariable(match.Groups[1].Value);
                }

                driverOptions.AddAdditionalCapability(setting.Name, value);
            }

            return(new RemoteScreenshotWebDriver(remoteUri, driverOptions.ToCapabilities()));
        }
Example #2
0
        private static ICapabilities ConvertOptionsToCapabilities(DriverOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options", "Driver options must not be null");
            }

            return(options.ToCapabilities());
        }
Example #3
0
 protected Task <IWebDriver> CreateRemoteWebDriver(Uri serverUri, DriverOptions driverOptions, TimeSpan newCommandTimeout, Action <IWebDriver> callback)
 {
     logger.Info("===> Create Remote Web Driver");
     return(Task.Run <IWebDriver>(() =>
     {
         var driver = new RemoteWebDriver(serverUri, driverOptions.ToCapabilities(), newCommandTimeout);
         callback(driver);
         return driver;
     }));
 }
 protected IWebDriver LaunchGridDriver(DriverOptions options, Uri uri)
 {
     try
     {
         return(new RemoteWebDriver(uri, options.ToCapabilities(), TimeSpan.FromSeconds(600)));
     }
     catch (WebDriverException) //Need to check exception type
     {
         throw new WebDriverException("Unable to connect to the grid url");
     }
 }
Example #5
0
 private static void SetOptionsAndDriver(DriverOptions options, RemoteWebDriver instanceOfdriver)
 {
     if (Config.IsSeleniumGrid)
     {
         options.PlatformName = PlatformType.Windows.ToString();
         driver = new RemoteWebDriver(new Uri(Config.URLToHubOfSeleniumGrid), options.ToCapabilities());
     }
     else
     {
         driver = instanceOfdriver;
     }
 }
Example #6
0
        public virtual Task <IWebDriver> Create(Uri serverUri, DriverOptions driverOptions, TimeSpan newCommandTimeout, Action <IWebDriver> callback)
        {
            switch (driverOptions.ToCapabilities().GetCapability(MobileCapabilityType.PlatformName))
            {
            case MobilePlatform.Android:
                return(CreateAndroidDriver(serverUri, driverOptions, newCommandTimeout, callback));

            case MobilePlatform.IOS:
                return(CreateIOSDriver(serverUri, driverOptions, newCommandTimeout, callback));

            default:
                return(CreateRemoteWebDriver(serverUri, driverOptions, newCommandTimeout, callback));
            }
        }
        private IWebDriver CreateDriver(DriverOptions options)
        {
            string server  = ConfigurationManager.AppSettings["server_configuration"];
            var    browser = GetBrowser();
            var    url     = "";

            if (server == "LOCAL")
            {
                url = string.Format("http://" + ConfigurationManager.AppSettings["local_server"] + "/wd/hub");
                switch (browser)
                {
                case "CHROME":
                    Driver = new ChromeDriver(ChromeDriverService.CreateDefaultService(), (ChromeOptions)options, TimeSpan.FromSeconds(90));
                    break;

                case "IE":
                    Driver = new InternetExplorerDriver(InternetExplorerDriverService.CreateDefaultService(), (InternetExplorerOptions)options, TimeSpan.FromSeconds(90));
                    break;

                case "FIREFOX":
                    Driver = new FirefoxDriver(FirefoxDriverService.CreateDefaultService(), (FirefoxOptions)options, TimeSpan.FromSeconds(90));
                    break;

                default:
                    throw new Exception("A Browser must be specified in App.config");
                }
            }

            else
            {
                //Create Remote WebDriver
                string bsUsername            = Environment.GetEnvironmentVariable("BROWSERSTACK_USERNAME");
                string bsAccessKey           = Environment.GetEnvironmentVariable("BROWSERSTACK_ACCESS_KEY");
                var    browserstackUsername  = (string.IsNullOrEmpty(bsUsername)) ? ConfigurationManager.AppSettings["browserstack_user"] : bsUsername;
                var    browserstackAccessKey = (string.IsNullOrEmpty(bsAccessKey)) ? ConfigurationManager.AppSettings["browserstack_key"] : bsAccessKey;

                url = string.Format(
                    "https://{0}:{1}@hub-cloud.browserstack.com/wd/hub",
                    browserstackUsername,
                    browserstackAccessKey);
                Driver = new RemoteWebDriver(new Uri(url), options.ToCapabilities());
            }
            return(Driver);
        }
Example #8
0
 internal static ICapabilities SetPlatformToCapabilities(DriverOptions dc, string desiredPlatform)
 {
     dc.AddAdditionalCapability(MobileCapabilityType.PlatformName, desiredPlatform);
     return(dc.ToCapabilities());
 }
Example #9
0
 public virtual RemoteWebDriver GetRemoteDriver(DriverOptions browserOptions)
 {
     return(new RemoteWebDriver(new Uri("https://ondemand.saucelabs.com/wd/hub"),
                                browserOptions.ToCapabilities(), TimeSpan.FromSeconds(600)));
 }
Example #10
0
 public IWebDriver CreateRemoteWebDriver(DriverOptions browserOptions)
 {
     _driver = new RemoteWebDriver(new Uri("https://ondemand.saucelabs.com/wd/hub"),
                                   browserOptions.ToCapabilities(), TimeSpan.FromSeconds(600));
     return(_driver);
 }
        private void Init_(string testName)
        {
            // Initialize the eyes SDK and set your private API key.
            Eyes eyes = InitEyes_();

            string testNameWithArguments = testName;

            foreach (object argValue in TestContext.CurrentContext.Test.Arguments)
            {
                testNameWithArguments += "_" + argValue;
            }

            if (eyes.runner_ is VisualGridRunner)
            {
                testName += "_VG";
                testNameWithArguments += "_VG";
            }
            else if (stitchMode_ == StitchModes.Scroll)
            {
                testName += "_Scroll";
                testNameWithArguments += "_Scroll";
            }

            TestUtils.SetupLogging(eyes, testNameWithArguments);
            eyes.Logger.Log("initializing test: {0}", TestContext.CurrentContext.Test.FullName);
            SpecificTestContextRequirements testContextReqs = new SpecificTestContextRequirements(eyes, testName);

            testDataByTestId_.Add(TestContext.CurrentContext.Test.ID, testContextReqs);

            if ((eyes.runner_ is VisualGridRunner && RUNS_ON_CI) || USE_MOCK_VG)
            {
                eyes.Logger.Log("using VG mock eyes connector");
                string testNameAsFilename = TestUtils.SanitizeForFilename(TestContext.CurrentContext.Test.FullName);
                testContextReqs.TestNameAsFilename = testNameAsFilename;
                Assembly thisAssembly             = Assembly.GetCallingAssembly();
                Stream   expectedOutputJsonStream = thisAssembly.GetManifestResourceStream("Test.Eyes.Selenium.DotNet.Resources.VGTests." + testNameAsFilename + ".json");
                if (expectedOutputJsonStream != null)
                {
                    using (StreamReader reader = new StreamReader(expectedOutputJsonStream))
                    {
                        testContextReqs.ExpectedVGOutput = reader.ReadToEnd();
                    }
                    eyes.visualGridEyes_.EyesConnectorFactory = new Mock.MockEyesConnectorFactory();
                }
            }
            else
            {
                eyes.Logger.Log("using regular VG eyes connector");
            }

            string seleniumServerUrl = SetupSeleniumServer(testName);
            bool   isWellFormedUri   = Uri.IsWellFormedUriString(seleniumServerUrl, UriKind.Absolute);

            RemoteWebDriver webDriver = SeleniumUtils.RetryCreateWebDriver(() =>
            {
                RemoteWebDriver driver = null;
                if (isWellFormedUri)
                {
                    try
                    {
                        eyes.Logger.Log("Trying to create RemoteWebDriver on {0}", seleniumServerUrl);
                        driver = new RemoteWebDriver(new Uri(seleniumServerUrl), options_.ToCapabilities(), TimeSpan.FromMinutes(4));
                    }
                    catch (Exception e)
                    {
                        eyes.Logger.Log("Failed creating RemoteWebDriver on {0}. Creating local WebDriver.", seleniumServerUrl);
                        eyes.Logger.Log("Exception: " + e);
                    }
                }

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

                if (TestUtils.RUNS_ON_CI)
                {
                    if (options_.BrowserName.Equals(BrowserNames.Chrome, StringComparison.OrdinalIgnoreCase) ||
                        options_.BrowserName.Equals(BrowserNames.Firefox, StringComparison.OrdinalIgnoreCase))
                    {
                        eyes.Logger.Log("webdriver is null, running on a CI and trying to initialize {0} browser.", options_.BrowserName);
                        driver = (RemoteWebDriver)SeleniumUtils.CreateWebDriver(options_);
                    }
                }
                else
                {
                    eyes.Logger.Log("webdriver is null, running locally and trying to initialize {0}.", options_.BrowserName);
                    driver = (RemoteWebDriver)SeleniumUtils.CreateWebDriver(options_);
                }

                return(driver);
            });

            eyes.AddProperty("Selenium Session ID", webDriver.SessionId.ToString());

            eyes.AddProperty("ForceFPS", eyes.ForceFullPageScreenshot ? "true" : "false");
            eyes.AddProperty("Agent ID", eyes.FullAgentId);

            //IWebDriver webDriver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), capabilities_);

            eyes.Logger.Log("navigating to URL: " + testedPageUrl);

            IWebDriver driver;

            try
            {
                BeforeOpen(eyes);
                driver = eyes.Open(webDriver, testSuitName_, testName, testedPageSize);
            }
            catch
            {
                webDriver.Quit();
                throw;
            }

            //string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            driver.Navigate().GoToUrl(testedPageUrl);
            eyes.Logger.Log($"{testName} ({options_.BrowserName}) : {TestDataProvider.BatchInfo.Name}");

            testDataByTestId_[TestContext.CurrentContext.Test.ID].WrappedDriver = driver;
            testDataByTestId_[TestContext.CurrentContext.Test.ID].WebDriver     = webDriver;
        }
Example #12
0
 public IWebDriver GetDriver(DriverOptions options)
 {
     //InternetExplorerOptions Options = new InternetExplorerOptions();
     if (!localtest)
     {
         if (_driver == null)
         {
             _driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub/"), options.ToCapabilities(), TimeSpan.FromSeconds(600));
         }
     }
     else
     {
         if (_driver == null)
         {
             _driver = new ChromeDriver();
         }
     }
     return(_driver);
 }
 private IWebDriver GetDriver(DriverOptions driverOptions)
 {
     //
     return(new RemoteWebDriver(new Uri("https://hub.screener.io:443/wd/hub"),
                                driverOptions.ToCapabilities(), TimeSpan.FromSeconds(60)));
 }
        internal static IWebDriver InitializeDriver(string browserType)
        {
            string hubIpAddress = JsonConfig.GetJsonValue("HubIpAddress");

            remoteWebDriverWaitTime = JsonConfig.GetJsonValue("RemoteWebdriverWait");
            elementLoadWaitTime     = JsonConfig.GetJsonValue("ElementWaitTime");
            pageLoadWaitTime        = JsonConfig.GetJsonValue("PageLoad");

            IWebDriver _driver = null;

            var browser = browserType.ToLower();

            try
            {
                switch (browser)
                {
                case "ie":
                    option = new InternetExplorerOptions();
                    option.AddAdditionalCapability("--window-size=1920,1080", true);
                    option.AddAdditionalCapability("--start-maximized", true);
                    option.AddAdditionalCapability("", true);
                    break;

                case "chrome":
                    chromeOptions = new ChromeOptions();
                    //chromeOptions.PlatformName = "LINUX";
                    chromeOptions.AddArgument("no-sandbox");
                    chromeOptions.AddArgument("--headless");
                    //chromeOptions.AddArgument("--start-maximized");
                    break;

                case "firefox":
                    option = new FirefoxOptions();
                    //option.PlatformName = "LINUX";
                    break;

                case "edge":
                    option = new EdgeOptions();
                    option.AddAdditionalCapability("--window-size=1920,1080", true);
                    option.AddAdditionalCapability("--start-maximized", true);
                    break;

                case "localhost":
                    _driver = new FirefoxDriver();
                    _driver.Manage().Window.Size = new Size(1920, 1080);
                    _driver.Manage().Window.Maximize();
                    break;
                }


                if (browser.Equals("chrome"))
                {
                    _driver = new RemoteWebDriver(new Uri($"{hubIpAddress}"), chromeOptions.ToCapabilities(), TimeSpan.FromSeconds(int.Parse(remoteWebDriverWaitTime)));
                    _driver.Manage().Window.Size = new Size(1920, 1080);
                    _driver.Manage().Window.Maximize();
                }
                else if (browser.Equals("firefox"))
                {
                    _driver = new RemoteWebDriver(new Uri($"{hubIpAddress}"), option.ToCapabilities(), TimeSpan.FromSeconds(int.Parse(remoteWebDriverWaitTime)));
                    _driver.Manage().Window.Size = new Size(1920, 1080);
                    _driver.Manage().Window.Maximize();
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            _driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(int.Parse(elementLoadWaitTime));
            _driver.Manage().Timeouts().PageLoad     = TimeSpan.FromSeconds(int.Parse(pageLoadWaitTime));
            _driver.Manage().Cookies.DeleteAllCookies();
            var allowsDetection = (OpenQA.Selenium.IAllowsFileDetection)_driver;

            allowsDetection.FileDetector = new LocalFileDetector();
            return(_driver);
        }
Example #15
0
 public override void InitialiseDriver(DriverOptions opts, int waitSecs)
 {
     SauceLabsFlowController.ControlFlow();
     try {
         //Console.WriteLine("About to create Driver");
         Driver = new SauceryRemoteWebDriver(new Uri(SauceOpsConstants.SAUCELABS_HUB), opts.ToCapabilities());
         Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(waitSecs);
     } catch (Exception ex) {
         Console.WriteLine(ex.Message);
     }
 }
Example #16
0
        private void Init_(string testName)
        {
            string testNameWithArguments = InitTestName_(ref testName);

            ILogHandler logHandler = TestUtils.InitLogHandler(testNameWithArguments);

            // Initialize the eyes SDK and set your private API key.
            Eyes eyes = InitEyes_(testName, logHandler);

            eyes.Logger.Log(TraceLevel.Notice, Stage.TestFramework, StageType.Start,
                            new { TestName = TestContext.CurrentContext.Test.FullName });

            string seleniumServerUrl = SetupSeleniumServer(testName);
            bool   isWellFormedUri   = Uri.IsWellFormedUriString(seleniumServerUrl, UriKind.Absolute);

            RemoteWebDriver webDriver = SeleniumUtils.RetryCreateWebDriver(() =>
            {
                RemoteWebDriver rwDriver = null;
                if (isWellFormedUri)
                {
                    try
                    {
                        eyes.Logger.Log(TraceLevel.Info, Stage.TestFramework, StageType.Start,
                                        new { message = $"Trying to create RemoteWebDriver on {seleniumServerUrl}" });
                        rwDriver = new RemoteWebDriver(new Uri(seleniumServerUrl), options_.ToCapabilities(), TimeSpan.FromMinutes(4));
                    }
                    catch (Exception e)
                    {
                        CommonUtils.LogExceptionStackTrace(eyes.Logger, Stage.TestFramework, StageType.Start, e,
                                                           testName, seleniumServerUrl);
                    }
                }

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

                if (TestUtils.RUNS_ON_CI)
                {
                    if (options_.BrowserName.Equals(BrowserNames.Chrome, StringComparison.OrdinalIgnoreCase) ||
                        options_.BrowserName.Equals(BrowserNames.Firefox, StringComparison.OrdinalIgnoreCase))
                    {
                        rwDriver = (RemoteWebDriver)SeleniumUtils.CreateWebDriver(options_);
                    }
                }
                else
                {
                    rwDriver = (RemoteWebDriver)SeleniumUtils.CreateWebDriver(options_);
                }

                return(rwDriver);
            });

            eyes.AddProperty("Selenium Session ID", webDriver.SessionId.ToString());

            eyes.AddProperty("ForceFPS", eyes.ForceFullPageScreenshot ? "true" : "false");
            eyes.AddProperty("Agent ID", eyes.FullAgentId);

            //IWebDriver webDriver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), capabilities_);

            IWebDriver driver;

            try
            {
                BeforeOpen(eyes);
                driver = eyes.Open(webDriver, testSuitName_, testName, testedPageSize);
            }
            catch
            {
                webDriver.Quit();
                throw;
            }

            //string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            driver.Navigate().GoToUrl(testedPageUrl);
            eyes.Logger.Log($"{testName} ({options_.BrowserName}) : {TestDataProvider.BatchInfo.Name}");

            testDataByTestId_[TestContext.CurrentContext.Test.ID].WrappedDriver = driver;
            testDataByTestId_[TestContext.CurrentContext.Test.ID].WebDriver     = webDriver;
            testDataByTestId_[TestContext.CurrentContext.Test.ID].WebDriverProvider.SetDriver(driver);
        }