Beispiel #1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ExtensionConnection"/> class.
        /// </summary>
        /// <param name="lockObject">An <see cref="ILock"/> object used to lock the mutex port before connection.</param>
        /// <param name="binary">The <see cref="FirefoxBinary"/> on which to make the connection.</param>
        /// <param name="profile">The <see cref="FirefoxProfile"/> creating the connection.</param>
        /// <param name="host">The name of the host on which to connect to the Firefox extension (usually "localhost").</param>
        public ExtensionConnection(ILock lockObject, FirefoxBinary binary, FirefoxProfile profile, string host)
        {
            this.profile = profile;
            if (binary == null)
            {
                this.process = new FirefoxBinary();
            }
            else
            {
                this.process = binary;
            }

            lockObject.LockObject(this.process.TimeoutInMilliseconds);
            try
            {
                int portToUse = DetermineNextFreePort(host, profile.Port);

                profile.Port = portToUse;
                profile.UpdateUserPreferences();
                this.process.Clean(profile);
                this.process.StartProfile(profile, null);

                SetAddress(host, portToUse);

                // TODO (JimEvans): Get a better url algorithm.
                executor = new HttpCommandExecutor(new Uri(string.Format(CultureInfo.InvariantCulture, "http://{0}:{1}/hub/", host, portToUse)));
            }
            finally
            {
                lockObject.UnlockObject();
            }
        }
Beispiel #2
0
        //[Test]
        public void CanBlockInvalidSslCertificates()
        {
            FirefoxProfile profile = new FirefoxProfile();
            profile.AcceptUntrustedCertificates = false;
            string url = EnvironmentManager.Instance.UrlBuilder.WhereIsSecure("simpleTest.html");

            IWebDriver secondDriver = null;
            try
            {
                secondDriver = new FirefoxDriver(profile);
                secondDriver.Url = url;
                string gotTitle = secondDriver.Title;
                Assert.AreNotEqual("Hello IWebDriver", gotTitle);
            }
            catch (Exception)
            {
                Assert.Fail("Creating driver with untrusted certificates set to false failed.");
            }
            finally
            {
                if (secondDriver != null)
                {
                    secondDriver.Quit();
                }
            }
        }
Beispiel #3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ExtensionConnection"/> class.
        /// </summary>
        /// <param name="lockObject">An <see cref="ILock"/> object used to lock the mutex port before connection.</param>
        /// <param name="binary">The <see cref="FirefoxBinary"/> on which to make the connection.</param>
        /// <param name="profile">The <see cref="FirefoxProfile"/> creating the connection.</param>
        /// <param name="host">The name of the host on which to connect to the Firefox extension (usually "localhost").</param>
        public ExtensionConnection(ILock lockObject, FirefoxBinary binary, FirefoxProfile profile, string host)
        {
            this.profile = profile;
            if (binary == null)
            {
                this.process = new FirefoxBinary();
            }
            else
            {
                this.process = binary;
            }

            lockObject.LockObject(this.process.TimeoutInMilliseconds);
            try
            {
                int portToUse = DetermineNextFreePort(host, profile.Port);

                profile.Port = portToUse;
                profile.UpdateUserPreferences();
                this.process.Clean(profile);
                this.process.StartProfile(profile, null);

                SetAddress(host, portToUse);

                ConnectToBrowser(this.process.TimeoutInMilliseconds);
            }
            finally
            {
                lockObject.UnlockObject();
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ExtensionConnection"/> class.
 /// </summary>
 /// <param name="binary">The <see cref="FirefoxBinary"/> on which to make the connection.</param>
 /// <param name="profile">The <see cref="FirefoxProfile"/> creating the connection.</param>
 /// <param name="host">The name of the host on which to connect to the Firefox extension (usually "localhost").</param>
 /// <param name="commandTimeout">The maximum amount of time to wait for each command.</param>
 public ExtensionConnection(FirefoxBinary binary, FirefoxProfile profile, string host, TimeSpan commandTimeout)
 {
     this.host = host;
     this.timeout = commandTimeout;
     this.profile = profile;
     if (binary == null)
     {
         this.process = new FirefoxBinary();
     }
     else
     {
         this.process = binary;
     }
 } 
Beispiel #5
0
        /// <summary>
        /// Creates New Driver.
        /// </summary>
        /// <param name="browser">The browser.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentException">No such browser type!</exception>
        public static IWebDriver CreateDriver(string browser)
        {
            IWebDriver result = null;

            switch (browser)
            {
            case BrowserTypes.Chrome:
                ChromeOptions chromeOptions = new ChromeOptions();
                chromeOptions.AddArgument("--disable-extensions");
                chromeOptions.AddArgument("--silent");
                chromeOptions.AddArgument("--start-maximized");
                try
                {
                    result = new ChromeDriver(chromeOptions);
                    //result.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
                }
                catch (WebDriverException ex)
                {
                    throw;
                }
                break;

            case BrowserTypes.Firefox:
                FirefoxProfile profile = new FirefoxProfile();
                profile.SetPreference("plugins.hide_infobar_for_missing_plugin", true);
                profile.SetPreference("plugin.default.state", 0);
                profile.Port = 4321;

                FirefoxOptions optionsff = new FirefoxOptions();
                optionsff.Profile = profile;

                try
                {
                    result = new FirefoxDriver(optionsff);
                }
                catch (WebDriverException ex)
                {
                    throw;
                }
                break;

            default:
                throw new ArgumentException("No such browser type!");
            }
            result.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
            return(result);
        }
Beispiel #6
0
        public void Init(IWebDriver driver = null)
        {
            BaseTest.AddTestCase("Login to IMS Admin", "Login should be sucessfull");
            if (driver != null)
            {
                IMSDriver = driver;
            }
            else
            {
                if (FrameGlobals.useGrid.ToUpper() == "YES")
                {
                    FirefoxProfile      ffProfile            = new FirefoxProfile();
                    DesiredCapabilities desriredCapibilities = null;
                    desriredCapibilities = new DesiredCapabilities();
                    desriredCapibilities = DesiredCapabilities.Firefox();
                    desriredCapibilities.SetCapability(CapabilityType.BrowserName, "firefox");
                    // ffProfile.SetPreference("general.useragent.override", FrameGlobals.userAgentValue);

                    IMSDriver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), desriredCapibilities, TimeSpan.FromSeconds(420.0));
                    // IMSBrowser = new WebDriverBackedSelenium(IMSDriver, "http://www.google.com"); //_seleniumContainer.Add(Gallio.Framework.TestContext.CurrentContext.Test.Name, MyBrowser);
                }
                else
                {
                    IMSDriver = new ChromeDriver();
                    // IMSBrowser = new WebDriverBackedSelenium(IMSDriver, "https://admin-stg.ladbrokes.com");
                }
            }
            // IMSBrowser.Start();
            wAction.OpenURL(IMSDriver, "https://stg-gib.ladbrokes.com/telebet", "Telebet stage not loaded", FrameGlobals.reloadTimeOut);
            IMSDriver.Manage().Window.Maximize();
            //  IMSBrowser.WindowMaximize();

            wAction._Type(IMSDriver, ICE.ObjectRepository.ORFile.Telebet, wActions.locatorType.id, "username", "subhasini_k", "Username Textbox not found", FrameGlobals.elementTimeOut, false);
            wAction._Type(IMSDriver, ICE.ObjectRepository.ORFile.Telebet, wActions.locatorType.name, "password", "123456", "Password Textbox not found");
            wAction._Type(IMSDriver, ICE.ObjectRepository.ORFile.Telebet, wActions.locatorType.id, "terminalcode", "test_4", "Terminal code Textbox not found", FrameGlobals.elementTimeOut, false);
            wAction._Click(IMSDriver, ICE.ObjectRepository.ORFile.Telebet, wActions.locatorType.id, "submit", "Submit Textbox not found");

            //IMSDriver.SwitchTo().DefaultContent();
            //wAction.WaitAndMovetoFrame(IMSDriver, "menu", "Frame menu is not found", FrameGlobals.elementTimeOut);
            BaseTest.Assert.IsTrue(wAction._IsElementPresent(IMSDriver, ICE.ObjectRepository.ORFile.Telebet, wActions.locatorType.id, "searchacc"), "User not logged in");

            BaseTest.Pass();
            //IMSDriver.SwitchTo().DefaultContent();
            //wAction.WaitAndMovetoFrame(IMSDriver, "top", "Top Frame not found", FrameGlobals.elementTimeOut);
            //wAction._Click(IMSDriver, ORFile.IMSCommon, wActions.locatorType.xpath, "tryout_newlook_lnk", "Could not find try out new look link", 0, false);
        }
Beispiel #7
0
        static public FirefoxDriver Make_Driver(string AccountProfile)
        {
            //Bulid a driver
            //Set a custom profile
            FirefoxProfile profile = new FirefoxProfile((FireFoxProfilesPath + AccountProfile));
            FirefoxOptions options = new FirefoxOptions();


            options.Profile = profile;


            FirefoxDriver driver = new FirefoxDriver(options);



            return(driver);
        }
        public static FirefoxOptions GetFirefoxOptions(string lang, bool headless = false, PlatformType platformType = PlatformType.Any)
        {
            FirefoxProfile profile = new FirefoxProfile();

            profile.SetPreference("intl.accept_languages", lang);
            FirefoxOptions options = new FirefoxOptions();

            options.AcceptInsecureCertificates = true;

            if (headless)
            {
                options.AddArgument("--headless");
            }

            SetPlatform(options, platformType);
            return(options);
        }
Beispiel #9
0
        /// <summary>
        /// Returns an instance of Firefox based driver.
        /// </summary>
        /// <returns>FireFox based driver</returns>
        private static IWebDriver FireFoxWebDriver()
        {
            // Proxy setup starts here
            OpenQA.Selenium.Proxy proxy = new OpenQA.Selenium.Proxy();

            //start fiddler and get the port used
            int proxyport = FiddlerProxy.StartFiddlerProxy(0);

            //use SslProxy for https sites
            proxy.SslProxy = string.Format("127.0.0.1:{0}", proxyport);


            FirefoxProfile profile = new FirefoxProfile();

            profile.AssumeUntrustedCertificateIssuer = false;
            // get Log Execution Path
            String getExecutingPath = new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName;

            // set profile preferences
            profile.SetPreference("FireFox" + DateTime.Now.Ticks + ".log", getExecutingPath);
            profile.SetPreference("browser.helperApps.alwaysAsk.force", false);
            profile.SetPreference("browser.download.folderList", 2);
            profile.SetPreference("browser.download.dir", AutomationConfigurationManager.DownloadFilePath.Replace("file:\\", ""));
            profile.SetPreference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", false);
            profile.SetPreference("browser.download.useDownloadDir", true);
            profile.SetPreference("browser.download.downloadDir", AutomationConfigurationManager.DownloadFilePath.Replace("file:\\", ""));
            profile.SetPreference("browser.download.defaultFolder", AutomationConfigurationManager.DownloadFilePath.Replace("file:\\", ""));
            profile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/zip, application/x-zip, application/x-zip-compressed, application/download, application/octet-stream");
            profile.EnableNativeEvents = true;
            profile.SetPreference("browser.cache.disk.enable", false);
            profile.SetPreference("browser.cache.memory.enable", false);
            profile.SetPreference("browser.cache.offline.enable", false);
            profile.SetPreference("network.http.use-cache", false);
            //set proxyperference
            profile.SetProxyPreferences(proxy);
            //to be sure that it picks up 32bit of ff always
            string        sBrowserExe = "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe";
            FirefoxBinary Bin         = new FirefoxBinary(sBrowserExe);
            IWebDriver    webDriver   = new FirefoxDriver();

            // set page load duration
            webDriver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(TimeOut));
            // set cursor position center of the screen
            Cursor.Position = new Point(Screen.PrimaryScreen.Bounds.Width / 2, Screen.PrimaryScreen.Bounds.Height / 2);
            return(webDriver);
        }
        public void OpenBrowser(Dictionary <string, string> preference)
        {
            //string pathToCurrentUserProfiles = Environment.ExpandEnvironmentVariables("%APPDATA%") + @"\Mozilla\Firefox\Profiles"; // Path to profile
            DebugHelper.Logger.Info("Otwieranie przeglodarki");

            FirefoxProfile profile = new FirefoxProfile();                 // (pathsToProfiles[0]);

            profile.SetPreference("browser.tabs.loadInBackground", false); // set preferences you need

            if (preference != null)
            {
                foreach (var pref in preference)
                {
                    profile.SetPreference(pref.Key, pref.Value);
                }
            }
            DebugHelper.Logger.Info("Koniec tworzenia profilu");
            //WebDriver = new PhantomJSDriver();
            try
            {
                //Thread.Sleep(1000); // TODO Testujemy czy to to rozwiaze problem z wieszaniem sie firefoxa przy starcie
                WebDriver = new FirefoxDriver(new FirefoxBinary(), profile);
            }
            catch (Exception)
            {
                DebugHelper.Logger.Info("ERROR IN OPEN");
                WebDriver = new FirefoxDriver(new FirefoxBinary(@"C:\Program Files (x86)\Mozilla Firefox\firefox.exe"), profile);
            }
            DebugHelper.Logger.Info("Init webdrivwer");
            WebDriver.Manage().Window.Maximize();
            // WebDriver = new InternetExplorerDriver();
            //DesiredCapabilities capabilities = DesiredCapabilities.Firefox(); // DesiredCapabilities.Firefox());

            //capabilities.SetCapability(FirefoxDriver.ProfileCapabilityName, profile.ToBase64String());
            //WebDriver = new RemoteWebDriver(new Uri("http://pro-test:4444/wd/hub"),DesiredCapabilities.InternetExplorer());

            // MEGA FAJNY RZECZ do debugowania !!!!!! tu sie pomysli o inncyh ciekawych zastosowaniach
            //System.Uri uri = new System.Uri("http://localhost:7055/hub");
            //WebDriver = new RemoteWebDriver(uri, DesiredCapabilities.Firefox());

            //DesiredCapabilities capabilities = DesiredCapabilities.Firefox();
            //capabilities.SetCapability(FirefoxDriver.ProfileCapabilityName,  prof);
            //driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capabilities);

            CurrentWebDriver = WebDriver;
        }
        private void InitLocalFf()
        {
            Log.InfoMsg("FireFox Browser session started.\r\n-----------------------------------------");

            FirefoxProfile ffProfile = new FirefoxProfile();
            var            port      = ParamsLib.BrwsrOptions.Port;

            if (port != 0)
            {
                ffProfile.Port = ParamsLib.BrwsrOptions.Port;
            }

            ffProfile.AcceptUntrustedCertificates = true;
            ffProfile.DeleteAfterUse = true;

            this.Instance = new FirefoxDriver(ffProfile);
        }
        public IWebDriver Firefox_PlayVideo_Fixture()
        {
            profile = new FirefoxProfile();


            profile.AddExtension(@"C:\Project\IETTVWebPortal\Firebug\firebug-2.0.9.xpi");
            profile.AddExtension(@"C:\Project\IETTVWebPortal\Firebug\netExport-0.9b7.xpi");
            profile.AddExtension(@"C:\Project\IETTVWebPortal\Firebug\fireStarter-0.1a6.xpi");

            profile.EnableNativeEvents = true;


            // Firebug Preferences

            profile.SetPreference("extensions.firebug.DBG_NETEXPORT", true);
            profile.SetPreference("extensions.firebug.script.enableSites", true);
            profile.SetPreference("extensions.firebug.net.persistent", true);
            profile.SetPreference("extensions.firebug.net.enableSites", true);
            profile.SetPreference("extensions.firebug.previousPlacement", 1);
            profile.SetPreference("extensions.firebug.console.enableSites", true);
            profile.SetPreference("extensions.firebug.consoles.enableSite", true);
            profile.SetPreference("extensions.firebug.addonBarOpened", true);
            profile.SetPreference("extensions.firebug.currentVersion", "2.0.9");
            profile.SetPreference("extensions.firebug.DBG_STARTER", true);
            profile.SetPreference("extensions.firebug.allPagesActivation", "on");
            profile.SetPreference("extensions.firebug.onByDefault", true);
            profile.SetPreference("extensions.firebug.defaultPanelName", "net");

            // Net Export Preferences

            profile.SetPreference("extensions.firebug.netexport.sendToConfirmation", false);
            profile.SetPreference("extensions.firebug.netexport.defaultLogDir", "C:\\Project\\IETTVWebPortal\\Firebug");
            profile.SetPreference("extensions.firebug.netexport.alwaysEnableAutoExport", true);
            profile.SetPreference("extensions.firebug.netexport.autoExportToFile", true);
            profile.SetPreference("extensions.firebug.netexport.saveFiles", true);
            profile.SetPreference("extensions.firebug.netexport.autoExportToServer", false);
            profile.SetPreference("extensions.firebug.netexport.Automation", true);
            profile.SetPreference("extensions.firebug.netexport.showPreview", true);  // preview.
            profile.SetPreference("extensions.firebug.netexport.timeout", 60000);
            profile.SetPreference("extensions.firebug.netexport.pageLoadedTimeout", 1500);
            profile.SetPreference("extensions.firebug.net.defaultPersist", true);

            driver = new FirefoxDriver(profile);

            return(driver);
        }
Beispiel #13
0
        public void GetProfilesTest()
        {
            var data     = DataLoader.GetSampleData("profiles.ini.txt");
            var lines    = data.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            var moz_path = "path";
            var ps       = FirefoxProfile.GetProfiles(lines, moz_path);

            Assert.AreEqual(2, ps.Count);
            Assert.AreEqual("default", ps[0].Name);
            Assert.IsTrue(ps[0].IsRelative);
            Assert.IsFalse(ps[0].IsDefault);
            Assert.AreEqual("path\\Profiles\\f3ezfk6m.default", ps[0].path);
            Assert.AreEqual("dev-edition-default", ps[1].Name);
            Assert.IsTrue(ps[1].IsRelative);
            Assert.IsTrue(ps[1].IsDefault);
            Assert.AreEqual("path\\Profiles\\42522y5w.dev-edition-default-1516971409783", ps[1].path);
        }
Beispiel #14
0
        /// <summary>
        /// Gets the FireFox driver.
        /// </summary>
        /// <param name="browserFactoryConfiguration">The browser factory configuration.</param>
        /// <returns>The configured web driver.</returns>
        private static IWebDriver GetFireFoxDriver(BrowserFactoryConfigurationElement browserFactoryConfiguration)
        {
            IWebDriver driver;

            if (browserFactoryConfiguration.Settings != null && browserFactoryConfiguration.Settings.Count > 0)
            {
                var ffprofile = new FirefoxProfile();

                foreach (NameValueConfigurationElement configurationElement in browserFactoryConfiguration.Settings)
                {
                    // Removed debug lines but left in comments for future logger support
                    // Debug.WriteLine("SpecBind.Selenium.SeleniumBrowserFactory.GetFireFoxDriver: Setting firefox profile setting:{0} with value: {1}", configurationElement.Name, configurationElement.Value);
                    bool boolValue;
                    int  intValue;

                    if (int.TryParse(configurationElement.Value, out intValue))
                    {
                        // Debug.WriteLine("SpecBind.Selenium.SeleniumBrowserFactory.GetFireFoxDriver: Setting firefox profile setting with int value: '{0}'", configurationElement.Name);
                        ffprofile.SetPreference(configurationElement.Name, intValue);
                    }
                    else if (bool.TryParse(configurationElement.Value, out boolValue))
                    {
                        // Debug.WriteLine("SpecBind.Selenium.SeleniumBrowserFactory.GetFireFoxDriver: Setting firefox profile setting with bool value: '{0}'", configurationElement.Name);
                        ffprofile.SetPreference(configurationElement.Name, boolValue);
                    }
                    else
                    {
                        // Debug.WriteLine("SpecBind.Selenium.SeleniumBrowserFactory.GetFireFoxDriver: Setting firefox profile setting with string value: '{0}'", configurationElement.Name);
                        ffprofile.SetPreference(configurationElement.Name, configurationElement.Value);
                    }
                }

                driver = new FirefoxDriver(ffprofile);
            }
            else
            {
                driver = new FirefoxDriver();
            }

            if (browserFactoryConfiguration.EnsureCleanSession)
            {
                driver.Manage().Cookies.DeleteAllCookies();
            }

            return(driver);
        }
        /// <summary>
        /// 创建WebDriver对象
        /// </summary>
        /// <returns>WebDriver对象</returns>
        protected RemoteWebDriver CreateWebDriver()
        {
            RemoteWebDriver webDriver;

            switch (Browser)
            {
            case Browser.Chrome:
            {
                ChromeDriverService cds = ChromeDriverService.CreateDefaultService();
                cds.HideCommandPromptWindow = true;
                ChromeOptions opt = new ChromeOptions();
                opt.AddUserProfilePreference("profile", new { default_content_setting_values = new { images = 2 } });
                webDriver = new ChromeDriver(cds, opt);
                break;
            }

            case Browser.Firefox:
            {
                string   path            = Environment.ExpandEnvironmentVariables("%APPDATA%") + @"\Mozilla\Firefox\Profiles\";
                string[] pathsToProfiles = Directory.GetDirectories(path, "*.webdriver", SearchOption.TopDirectoryOnly);
                if (pathsToProfiles.Length == 1)
                {
                    FirefoxProfile profile = new FirefoxProfile(pathsToProfiles[0], false)
                    {
                        AlwaysLoadNoFocusLibrary = true
                    };
                    FirefoxOptions options = new FirefoxOptions();
                    options.Profile = profile;
                    webDriver       = new FirefoxDriver(options);
                }
                else
                {
                    throw new Exception("No Firefox profiles: webdriver.");
                }
                break;
            }

            default:
            {
                throw new Exception("Unsupported browser!");
            }
            }

            webDriver.Manage().Window.Maximize();
            return(webDriver);
        }
Beispiel #16
0
        public void SetUp()
        {
            var binary = new FirefoxBinary(ConfigUtils.Read("FirefoxPath"));
            // string path = ReadFirefoxProfile();
            FirefoxProfile ffprofile = new FirefoxProfile();

            driver = new FirefoxDriver(binary, ffprofile);
            //  driver = new InternetExplorerDriver(internetExplorerDriverServerDirectory: "\\srv10177\\TEMPSHTIW$\\Desktop\\SIT\\SITSmokeTests\\IEDriverServer.exe");
            driver.Manage().Cookies.DeleteAllCookies();
            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(15));
            // Before each test
            wait           = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
            datafilePath   = ConfigUtils.Read("TestDataPath");
            sGMethods      = new GeneralMethods();
            intigrationmon = new MOnitorUI(driver);
            iccPortal      = new ICCBAMPageObj(driver);
        }
        private IWebDriver BuildFFDriver()
        {
            FirefoxProfile ffProfile = new FirefoxProfile();

            JavaScriptError.AddExtension(ffProfile);

            ffProfile.AddExtension(SaveBinaryResource("firebug-2.0.8-fx.xpi", TestResources.firebug_2_0_8_fx));

            ffProfile.SetPreference("extensions.firebug.showStackTrace", "true");
            ffProfile.SetPreference("extensions.firebug.delayLoad", "false");
            ffProfile.SetPreference("extensions.firebug.showFirstRunPage", "false");
            ffProfile.SetPreference("extensions.firebug.allPagesActivation", "on");
            ffProfile.SetPreference("extensions.firebug.console.enableSites", "true");
            ffProfile.SetPreference("extensions.firebug.defaultPanelName", "console");

            return(new FirefoxDriver(ffProfile));
        }
Beispiel #18
0
 private static ICommandExecutor CreateExecutor(FirefoxDriverServiceEx service, FirefoxDriverServiceEx options, TimeSpan commandTimeout)
 {
     if (options.UseLegacyImplementation)
     {
         FirefoxProfile profile = options.Profile;
         if (profile == null)
         {
             profile = new FirefoxProfile();
         }
         return CreateExtensionConnection(new FirefoxBinary(options.BrowserExecutableLocation), profile, commandTimeout);
     }
     if (service == null)
     {
         throw new ArgumentNullException("service", "You requested a service-based implementation, but passed in a null service object.");
     }
     return new DriverServiceCommandExecutor(service, commandTimeout);
 }
Beispiel #19
0
        public void setup()
        {
            #region For Normal Use

            ChooseBrowser(ConfigManager.GetConfigValue("Browser"));
            bulider = new Actions(driver);
            FirefoxProfile profile = new FirefoxProfile();
            profile.EnableNativeEvents = true;

            #endregion

            driver.Navigate().GoToUrl(Server);
            wait = new WebDriverWait(driver, TimeSpan.FromMinutes(9));
            //string s=driver.CurrentWindowHandle;
            //driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(20));
            driver.Manage().Window.Maximize();
        }
Beispiel #20
0
        static private IBrowserSession CreateFirefoxAdapter(BrowserSettings settings)
        {
            string pathToCurrentUserProfiles = Environment.ExpandEnvironmentVariables("%TEMP%") + @"\ff_selenium_etsy3";
            //string[] pathsToProfiles = Directory.GetDirectories(pathToCurrentUserProfiles, "*.default", SearchOption.TopDirectoryOnly);
            //if (pathsToProfiles.Length != 0)
            //{
            //    FirefoxProfile profile = new FirefoxProfile(pathsToProfiles[0]);
            //    profile.SetPreference("browser.tabs.loadInBackground", false); // set preferences you need
            //    driver = new FirefoxDriver(new FirefoxBinary(), profile, serverTimeout);
            //}
            //FirefoxProfile profile = new FirefoxProfile(@"C:\Users\stefan\AppData\Roaming\Mozilla\Firefox\Profiles\ui906pgj.selenium_etsy", false); //"P:\\var\\ff_profile"
            //var profileManager = new FirefoxProfileManager();
            //FirefoxProfile profile = profileManager.GetProfile(@"ff_etsy");
            FirefoxProfile profile = new FirefoxProfile();

            if (profile == null)
            {
                profile = new FirefoxProfile();
            }
            profile.SetPreference("browser.tabs.loadInBackground", false);
            profile.SetPreference("dom.max_chrome_script_run_time", settings.CommandTimeout);
            profile.SetPreference("dom.max_script_run_time", settings.CommandTimeout);
            //profile.SetPreference("webdriver.firefox.profile", "ff_etsy");
            profile.DeleteAfterUse = false;
            //profile.SetPreference("xpinstall.signatures.required", false);
            if (settings.PluginFileName != null)
            {
                profile.AddExtension(settings.PluginFileName);
            }
            var cc = TimeSpan.FromSeconds(settings.CommandTimeout);

            FirefoxOptions opt = new FirefoxOptions();

            //opt.Profile = profile;
            // To have geckodriver pick up an existing profile on the filesystem, you may pass ["-profile", "/path/to/profile"].
            opt.AddArguments(new string[] { "-profile", pathToCurrentUserProfiles });  // @"P:\var\ff_profile"
            //opt.AddArguments( new string[] { "-P", "ff_etsy" });
            //opt.AddAdditionalCapability(CapabilityType.AcceptSslCertificates, true);
            //opt.AddAdditionalCapability(CapabilityType.IsJavaScriptEnabled, true);
            //opt.AddAdditionalCapability(CapabilityType.HasNativeEvents, true);
            //opt.SetPreference("webdriver.firefox.profile", "ff_etsy");
            //var webDriver = new FirefoxDriver(FirefoxDriverService.CreateDefaultService(), opt, TimeSpan.FromSeconds(settings.CommandTimeout));
            var webDriver = new FirefoxDriver(opt);

            return(new DefaultBrowserSession(webDriver).Configure(settings));
        }
Beispiel #21
0
        public void LoginForm_ValidLogin()
        {
            FirefoxProfile fireFoxP = new FirefoxProfile("SeleniumProfile", false);

            using (IWebDriver driver = new FirefoxDriver(fireFoxP))
            {
                driver.Navigate().GoToUrl(gg);

                //Открытие формы
                IWebElement formLink = driver.FindElement(By.XPath(@"//*[@id=""top_back""]/div[3]/a[1]"));
                formLink.Click();

                WebDriverWait wait          = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
                IWebElement   overlay       = driver.FindElement(By.Id("cboxOverlay"));
                IWebElement   colorbox      = driver.FindElement(By.Id("colorbox"));
                IWebElement   messageBox    = driver.FindElement(By.ClassName("status-error"));
                IWebElement   loginButton   = wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath(@"//*[@id=""authblock""]/div[2]/form/div[7]/button")));
                IWebElement   emailField    = wait.Until(ExpectedConditions.ElementToBeClickable(By.Name("Email")));
                IWebElement   passwordField = wait.Until(ExpectedConditions.ElementToBeClickable(By.Name("Password")));

                Assert.IsTrue(colorbox.Displayed, "Форма не открылась");

                //Ввод реквизитов
                emailField.SendKeys(validEmail);
                passwordField.SendKeys(validPassword);
                loginButton.Click();
                try { wait.Until(ExpectedConditions.ElementToBeClickable(By.PartialLinkText("Личный кабинет"))); }
                catch (Exception e) { Assert.Fail("Авторизация не прошла"); }

                Assert.IsTrue(IsStale(colorbox), "Форма не закрылась");
                Assert.IsTrue(IsStale(overlay), "Оверлей не пропал");
            }

            //Переоткрытие браузера
            using (IWebDriver driver = new FirefoxDriver(fireFoxP))
            {
                driver.Navigate().GoToUrl(gg);
                WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
                try
                {
                    wait.Until(ExpectedConditions.ElementToBeClickable(By.PartialLinkText("Личный кабинет")));
                    Assert.Fail("Авторизация сохраняется");
                }
                catch (Exception e) { }
            }
        }
        public IWebDriver EnterWithFirefox(string proxyAddress)
        {
            Log("Starting Firefox.");
            Log("Using proxy: " + proxyAddress);
            FirefoxProfile profile = new FirefoxProfile();
            Proxy          proxy   = new Proxy();

            proxy.HttpProxy = proxyAddress;
            proxy.FtpProxy  = proxyAddress;
            proxy.SslProxy  = proxyAddress;
            profile.SetProxyPreferences(proxy);
            Driver = new FirefoxDriver(profile);
            wait   = new WebDriverWait(Driver, TimeSpan.FromSeconds(12));
            JS     = Driver as IJavaScriptExecutor;
            return(Driver);
            //
        }
        public static FirefoxDriver CreateFirefoxDriver(DriverOptionsConfig driverOptionsConfig)
        {
            FirefoxProfile firefoxProfile = new FirefoxProfile();

            InitParameterFirefoxOption(firefoxProfile, driverOptionsConfig);
            FirefoxOptions firefoxOptions = new FirefoxOptions();

            if (driverOptionsConfig.IsHeadless)
            {
                firefoxOptions.AddArgument("--headless");
            }
            firefoxOptions.PageLoadStrategy = driverOptionsConfig.PageLoadStrategy;
            firefoxOptions.Profile          = firefoxProfile;
            var firefoxDriver = new FirefoxDriver(firefoxOptions);

            return(firefoxDriver);
        }
Beispiel #24
0
        //    public static test()
        //    {
        //         FirefoxProfile profile = new FirefoxProfile();
        //if (System.getProperty("os.name").equalsIgnoreCase("Mac OS X")) {
        // path = "/Users/Jignesh/developer/test-automation";
        //} else {
        // path = "c:\\Downloads_new";
        //}

        //profile.setPreference("dom.max_chrome_script_run_time", "999");
        //profile.setPreference("dom.max_script_run_time", "999");
        //profile.setPreference("browser.download.folderList", 2);
        //profile.setPreference("browser.download.dir", path);
        //profile.setPreference(
        //  "browser.helperApps.neverAsk.openFile",
        //  "text/csv,application/x-msexcel,application/excel,application/x-excel,application/vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml");
        //profile.setPreference(
        //  "browser.helperApps.neverAsk.saveToDisk",
        //  "text/csv,application/x-msexcel,application/excel,application/x-excel,application/vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml");
        //profile.setPreference("browser.download.manager.showWhenStarting",
        //  false);
        //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("browser.download.manager.showWhenStarting",
        //  false);

        //profile.setPreference(
        //  "services.sync.prefs.sync.browser.download.manager.showWhenStarting",
        //  false);
        //profile.setPreference("pdfjs.disabled", true);
        //profile.setAcceptUntrustedCertificates(true);
        //profile.setPreference("security.OCSP.enabled", 0);
        //profile.setEnableNativeEvents(false);
        //profile.setPreference("network.http.use-cache", false);

        //// added Dependancy to disable hardware acceleration.

        ///*
        // * profile.setPreference("gfx.direct2d.disabled",true);
        // * profile.setPreference("layers.acceleration.disabled", true);
        // */

        //profile.setPreference("gfx.direct2d.disabled", true);
        //profile.setPreference("layers.acceleration.disabled", true);
        //// profile.setPreference("webgl.force-enabled", true);
        //// Proxy proxy = new Proxy().setHttpProxy("localhost:3129");

        //// cap.setCapability(CapabilityType.PROXY, proxy);

        //capability = DesiredCapabilities.firefox();
        //// proxy code
        //// capability.setCapability(CapabilityType.PROXY,proxy);
        //capability.setJavascriptEnabled(true);
        //capability.setCapability(FirefoxDriver.PROFILE, profile);
        //browserName = capability.getBrowserName();
        //osName = System.getProperty("os.name");
        //browserVersion = capability.getVersion().toString();

        //System.out.println("=========" + "firefox Driver " + "==========");
        //driver = new RemoteWebDriver(remote_grid, capability);
        //    }
        public static IWebDriver OpenFirefoxBrowserWithUrl(IWebDriver driver, string strUrlToOpen, Boolean OpenInNewWindow = false)
        {
            try
            {
                //driver = new FirefoxDriver();

                Uri remote_grid = new Uri("http://" + "localhost" + ":" + "4444" + "/wd/hub");
                DesiredCapabilities capability = null;
                //browser = System.getProperty("browser");

                string browser = "firefox";

                if (browser == null || browser.Contains("firefox"))
                {
                    //FirefoxProfileManager myProfile = new FirefoxProfileManager();
                    //FirefoxProfile profile = myProfile.GetProfile("default");
                    FirefoxProfile profile = new FirefoxProfile();

                    capability = DesiredCapabilities.Firefox();
                    capability.IsJavaScriptEnabled = true;
                    profile.EnableNativeEvents     = true;

                    //
                    profile.SetPreference("gfx.direct2d.disabled", true);
                    profile.SetPreference("layers.acceleration.disabled", true);

                    capability.SetCapability(FirefoxDriver.ProfileCapabilityName, profile);
                }

                Console.WriteLine(capability);
                driver = new ScreenShotRemoteWebDriver(remote_grid, capability);

                //Console.WriteLine(strUrlToOpen);

                driver.Navigate().GoToUrl(strUrlToOpen);
                Report.AddToHtmlReportPassed("FireFox Browser Open for '" + strUrlToOpen + "' .");

                driver.Manage().Window.Maximize();
            }
            catch (Exception ex)
            {
                Report.AddToHtmlReportFailed(driver, ex, "FireFox Browser Open for '" + strUrlToOpen + "' .");
            }
            return(driver);
        }
Beispiel #25
0
        public SIT_LibraryTest()
        {
            var binary = new FirefoxBinary(ConfigUtils.Read("FirefoxPath"));
            // string path = ReadFirefoxProfile();
            FirefoxProfile ffprofile = new FirefoxProfile();

            driver = new FirefoxDriver(binary, ffprofile);
            // driver.Manage().Cookies.DeleteAllCookies();
            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(15));
            Thread.Sleep(1000);
            driver.Manage().Window.Maximize();
            Thread.Sleep(2000);
            // Before each test
            wait         = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
            datafilePath = System.Environment.GetEnvironmentVariable("ProjectWorkingDirectory") + ConfigUtils.Read("TestDataPath");
            libraryUi    = new SIT_Library_UI(driver);
            iccPortal    = new ICCBAMPageObj(driver);
        }
        private static FirefoxOptions GetFirefoxOptions()
        {
            var firefoxProfile = new FirefoxProfile();

            firefoxProfile.AcceptUntrustedCertificates = true;
            firefoxProfile.SetPreference("intl.accept_languages", ConfigInstance.Language);

            var options = new FirefoxOptions {
                Profile = firefoxProfile
            };

            options.SetLoggingPreference(LogType.Driver, LogLevel.Off);
            options.SetLoggingPreference(LogType.Browser, LogLevel.Off);
            options.LogLevel = FirefoxDriverLogLevel.Default;
            options.AddArgument("-headless");

            return(options);
        }
Beispiel #27
0
        /// <summary>
        /// Provides an example of how to create and register a custom Firefox driver with
        /// a custom firefox Profile.
        /// </summary>
        private void RegisterCustomFirefoxBrowser()
        {
            // Create profile and set some settings
            // (typical scneario of specifying how to download files)
            var firefoxProfile = new FirefoxProfile();

            firefoxProfile.SetPreference("browser.download.folderList", 2);
            firefoxProfile.SetPreference("browser.download.manager.showWhenStarting", false);
            firefoxProfile.SetPreference("browser.download.dir", "C:\\Temp"); // Better to pass this in via a config value
            firefoxProfile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/x-gzip");

            // Pass options to a new chrome browser and pass into the BrowserSession
            var customFirefoxDriver = new CustomFirefoxSeleniumDriver(firefoxProfile);
            var browserSession      = new BrowserSession(customFirefoxDriver);

            // Finally, register with the DI container.
            _objectContainer.RegisterInstanceAs <BrowserSession>(browserSession);
        }
Beispiel #28
0
 public BrowserOp(string url, BrowserType type)
 {
     if (type == BrowserType.Firefox)
     {
         FirefoxProfileManager ffm = new FirefoxProfileManager();
         FirefoxProfile        ff  = ffm.GetProfile("default");
         driver = new FirefoxDriver(ff);
     }
     else
     {
         driver = new InternetExplorerDriver();
         Maximize();
     }
     // if (!url.Contains("http")) {
     //    url = "http://" + url;
     //   }
     driver.Url = url;
 }
        public void ShouldAllowUserToSuccessfullyOverrideTheHomePage()
        {
            FirefoxProfile profile = new FirefoxProfile();

            profile.SetPreference("browser.startup.page", "1");
            profile.SetPreference("browser.startup.homepage", javascriptPage);

            IWebDriver driver2 = new FirefoxDriver(profile);

            try
            {
                Assert.AreEqual(javascriptPage, driver2.Url);
            }
            finally
            {
                driver2.Quit();
            }
        }
        public void ShouldAllowExplicitlySpecifyingXpiPath()
        {
            FirefoxProfile ffProfile = new FirefoxProfile();

            JavaScriptError.AddExtension(ffProfile, xpiDirectory());

            using (IWebDriver driver = new FirefoxDriver(ffProfile))
            {
                driver.Navigate().GoToUrl(urlSimpleHtml);

                IEnumerable <JavaScriptError> expectedErrors = new List <JavaScriptError>()
                {
                    errorSimpleHtml
                };
                IEnumerable <JavaScriptError> jsErrors = JavaScriptError.ReadErrors(driver);
                AssertErrorsEqual(expectedErrors, jsErrors);
            }
        }
        public void TestVerifyDownloadForFirefox()
        {
            String         myDownloadFolder = @"c:\temp\";
            FirefoxProfile fp = new FirefoxProfile();

            fp.SetPreference("browser.download.folderList", 2);
            fp.SetPreference("browser.download.dir", myDownloadFolder);
            fp.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");
            // disable Firefox's built-in PDF viewer
            fp.SetPreference("pdfjs.disabled", true);

            driver = new FirefoxDriver(fp);
            driver.Navigate().GoToUrl("http://zhimin.com/books/selenium-recipes");
            driver.FindElement(By.LinkText("Download")).Click();
            System.Threading.Thread.Sleep(10000); // wait 10 seconds for downloading to complete

            Assert.IsTrue(File.Exists(@"c:\temp\selenium-recipes-in-ruby-sample.pdf"));
        }
    public void SetUp()
    {
        FolderPath = System.Environment.CurrentDirectory +
                     $"/../../../{System.Guid.NewGuid().ToString()}";
        Directory.CreateDirectory(FolderPath);

        FirefoxProfile Profile = new FirefoxProfile();

        Profile.SetPreference("browser.download.dir", FolderPath);
        Profile.SetPreference("browser.download.folderList", 2);
        Profile.SetPreference("browser.helperApps.neverAsk.saveToDisk",
                              "image/jpeg, application/pdf, application/octet-stream");
        Profile.SetPreference("pdfjs.disabled", true);
        FirefoxOptions Options = new FirefoxOptions();

        Options.Profile = Profile;
        Driver          = new FirefoxDriver(Options);
    }
Beispiel #33
0
        public void TakeScreenshotsByCityCoordinates()
        {
            FirefoxProfile profile = new FirefoxProfile();

            profile.AddExtension(this.adBlockPath);
            this.driver = new FirefoxDriver(profile);

            //ChromeOptions options = new ChromeOptions();
            //options.AddExtension(this.adBlockChromePath);
            //this.driver = new ChromeDriver(this.chromeDriverPath, options);

            this.driver.Manage().Window.Maximize();
            this.driver.Url = this.baseUrl;
            this.driver.Url = this.cityListUrl;

            CityListPage cityListPage = new CityListPage();

            this.WaitForElement(cityListPage.ResultsTableLocator);
            IWebElement[] links = this.driver.FindElements(cityListPage.ResultsTableLocator).ToArray();

            List <string> linkUrls = new List <string>();

            for (int i = 0; i < 10; i++)
            {
                linkUrls.Add(links[i].GetAttribute("href"));
            }

            CityInfoPage   cityInfoPage   = new CityInfoPage();
            GoogleMapsPage googleMapsPage = new GoogleMapsPage();

            foreach (var linkUrl in linkUrls)
            {
                this.driver.Url = linkUrl;
                this.WaitForElement(cityInfoPage.CityTableLocator);

                CityInfo info = cityInfoPage.GetCityInfo(this.driver);

                this.driver.Url = info.GoogleMapsLink;
                this.WaitForElement(googleMapsPage.StreetViewControl);
                this.TakeScreenshot(this.screenshotsPath + info.ToString() + ".jpg");
            }

            this.driver.Dispose();
        }
        private static Func <IWebDriver> GenerateBrowserSpecificDriver(Browser browser, TimeSpan commandTimeout)
        {
            string driverPath = string.Empty;

            switch (browser)
            {
            case Browser.InternetExplorer:
                driverPath = EmbeddedResources.UnpackFromAssembly("IEDriverServer32.exe", "IEDriverServer.exe", Assembly.GetAssembly(typeof(SeleniumWebDriver)));
                return(new Func <IWebDriver>(() => new IEDriverWrapper(Path.GetDirectoryName(driverPath), commandTimeout)));

            case Browser.InternetExplorer64:
                driverPath = EmbeddedResources.UnpackFromAssembly("IEDriverServer64.exe", "IEDriverServer.exe", Assembly.GetAssembly(typeof(SeleniumWebDriver)));
                return(new Func <IWebDriver>(() => new IEDriverWrapper(Path.GetDirectoryName(driverPath), commandTimeout)));

            case Browser.Firefox:
                return(new Func <IWebDriver>(() => {
                    var service = FirefoxDriverService.CreateDefaultService();
                    var profile = new FirefoxProfile
                    {
                        EnableNativeEvents = false,
                        AcceptUntrustedCertificates = true,
                        AlwaysLoadNoFocusLibrary = true
                    };
                    var ffOptions = new FirefoxOptions()
                    {
                        Profile = profile,
                    };
                    return new FirefoxDriver(service, ffOptions, commandTimeout);
                }));

            case Browser.Chrome:
                driverPath = EmbeddedResources.UnpackFromAssembly("chromedriver.exe", Assembly.GetAssembly(typeof(SeleniumWebDriver)));

                var chromeService = ChromeDriverService.CreateDefaultService(Path.GetDirectoryName(driverPath));
                chromeService.SuppressInitialDiagnosticInformation = true;

                var chromeOptions = new ChromeOptions();
                chromeOptions.AddArgument("--log-level=3");

                return(new Func <IWebDriver>(() => new ChromeDriver(chromeService, chromeOptions, commandTimeout)));
            }

            throw new NotImplementedException("Selected browser " + browser.ToString() + " is not supported yet.");
        }
Beispiel #35
0
        public void ShouldAllowUserToSuccessfullyOverrideTheHomePage()
        {
            FirefoxProfile profile = new FirefoxProfile();
            profile.SetPreference("browser.startup.page", "1");
            profile.SetPreference("browser.startup.homepage", javascriptPage);

            IWebDriver driver2 = new FirefoxDriver(profile);

            try
            {
                Assert.AreEqual(javascriptPage, driver2.Url);
            }
            finally
            {
                driver2.Quit();
            }
        }
Beispiel #36
0
 public void SetUp()
 {
     profile = new FirefoxProfile();
 }