Example #1
1
        public void TestCleanup()
        {
            if (Properties.Settings.Default.BROWSER == BrowserType.Ie)
            {
                driver.Quit();
                driver = null;
            }

            try
            {
                if (MyBook.Name != "")
                {
                    MyBook.Save();
                    MyBook.Close();
                }
                if (MyApp.Name != "")
                {
                    MyApp.Quit();
                }
            }catch
            { }

            KillProcess("EXCEL");
            KillProcess("IEDriverServer");
            KillProcess("iexplore");
        }
        public void Logout(IWebDriver driverToUse = null)
        {
            if (driverToUse == null)
                driverToUse = driver;

            driverToUse.FindElement(By.Id("LoginStatus1")).Click();
        }
Example #3
0
        private void TrySetupSteps(DriverType driverType, SeleniteTest test, IWebDriver webDriver)
        {
            if (test.TestCollection.SetupSteps.IsNullOrNotAny())
                return;

            var fileName = String.IsNullOrWhiteSpace(test.TestCollection.SetupStepsFile)
                ? test.TestCollection.ResolvedFile
                : test.TestCollection.SetupStepsFile;

            foreach (var pair in _setupStepsMap)
            {
                if (pair.Key.Target != webDriver)
                    continue;

                if (pair.Value.Any(f => String.Equals(f, fileName, StringComparison.InvariantCultureIgnoreCase)))
                    return;
            }

            foreach (var setupStep in test.TestCollection.SetupSteps)
                _testService.ExecuteTest(webDriver, driverType, setupStep, true);

            var weakReference = new WeakReference(webDriver);
            var testFiles = new List<string> { fileName };
            _setupStepsMap.Add(weakReference, testFiles);
        }
Example #4
0
        protected override object HandleSeleneseCommand(IWebDriver driver, string pattern, string ignored)
        {
            string text = string.Empty;
            IWebElement body = driver.FindElement(By.XPath("/html/body"));
            IJavaScriptExecutor executor = driver as IJavaScriptExecutor;
            if (executor == null)
            {
                text = body.Text;
            }
            else
            {
                text = JavaScriptLibrary.CallEmbeddedHtmlUtils(driver, "getTextContent", body).ToString();
            }

            text = text.Trim();

            string strategyName = "implicit";
            string use = pattern;

            if (TextMatchingStrategyAndValueRegex.IsMatch(pattern))
            {
                Match textMatch = TextMatchingStrategyAndValueRegex.Match(pattern);
                strategyName = textMatch.Groups[1].Value;
                use = textMatch.Groups[2].Value;
            }

            ITextMatchingStrategy strategy = textMatchingStrategies[strategyName];
            return strategy.IsAMatch(use, text);
        }
Example #5
0
 public void Login()
 {
     driver = new InternetExplorerDriver();
     try
     {
         //Run before any test
         driver.Navigate().GoToUrl(url + "MDM");
         driver.FindElement(By.Id("userNameTextBox")).SendKeys(user);
         driver.FindElement(By.Id("passwordTextBox")).SendKeys(password);
         driver.FindElement(By.Id("loginBtn")).Click();
         Common.WaitForElement(driver, By.ClassName("breadcrumbs"), 30);
     }
     catch (TimeoutException e)
     {
         System.Console.WriteLine("TimeoutException: " + e.Message);
         Assert.Fail(e.Message);
     }
     catch (NoSuchElementException e)
     {
         Assert.Fail(e.Message);
     }
     catch (Exception e)
     {
         System.Console.WriteLine("unhandled exception: " + e.Message);
         Assert.Fail(e.Message);
     }
 }
 public static void Start(BrowserType browserType = BrowserType.Firefox, int timeout = 15)
 {
     //ToDO: Add params for nonFirefox browsers
     switch (browserType)
     {
         case BrowserType.Firefox:
             WebDriver = new FirefoxDriver();
             break;
         case BrowserType.Ie:
             WebDriver = new ChromeDriver();
             break;
         case BrowserType.Chrome:
             WebDriver = new ChromeDriver();
             break;
         case BrowserType.Edge:
             WebDriver = new EdgeDriver();
             break;
         case BrowserType.PhantomJs:
             WebDriver = new PhantomJSDriver();
             break;
         default:
             throw new ArgumentOutOfRangeException(nameof(browserType), browserType, null);
     }
     BrowserWait = new WebDriverWait(WebDriver, TimeSpan.FromSeconds(timeout));
 }
        public static string GetElementXPath(IWebElement webElement, IWebDriver webDriver)
        {
            IJavaScriptExecutor jsExec = webDriver as IJavaScriptExecutor;
            return (string)jsExec.ExecuteScript(
            @"
            function getPathTo(element) {
            if (element === document.body)
            return '/html/' + element.tagName.toLowerCase();

            var ix = 0;
            var siblings = element.parentNode.childNodes;
            for (var i = 0; i < siblings.length; i++) {
            var sibling = siblings[i];
            if (sibling === element)
            {
            return getPathTo(element.parentNode) + '/' + element.tagName.toLowerCase() + '[' + (ix + 1) + ']';
            }
            if (sibling.nodeType === 1 && sibling.tagName === element.tagName)
            ix++;
            }
            }

            var element = arguments[0];
            var xpath = '';
            xpath = getPathTo(element);
            return xpath;
            ", webElement);
        }
        public IWebDriver LaunchBrowser(Browser browser)
        {
            switch (browser)
            {
                case Browser.IE:
                    driver = StartIEBrowser();
                    break;
                case Browser.Chrome:
                    driver = StartChromeBrowser();
                    break;
                case Browser.Safari:
                    driver = StartSafariBrowser();
                    break;
                case Browser.Firefox:
                default:
                    driver = StartFirefoxBrowser();
                    break;
            }

            driver.Manage().Cookies.DeleteAllCookies();
            SetBrowserSize();
            var eDriver = new EventedWebDriver(driver);

            return eDriver.driver;
        }
        public override void Specify()
        {
            given("the browser is firefox", delegate
            {
                Browser = arrange(() => new FirefoxBrowser());

                go();
            });

            // maybe support skip remaining tests if any have failed so far?

            given("the browser is internet explorer", delegate
            {
                Browser = arrange(() => new InternetExplorerBroser());

                go();
            });

            given("the browser is chrome", delegate
            {
                Browser = arrange(() => new ChromeBrowser());

                go();
            });
        }
        public void Run(IWebDriver webDriver, Step step)
        {
            var e = ((ElementHasStyleStep)step);
            try
            {
                var element = ElementHelper.GetVisibleElement(webDriver, e.Element);

                string style = element.GetAttribute("style");
                var styles = style.Split(';').Select(x =>
                                                     {
                                                         var parts = x.Replace(" ", "").Split(':');
                                                         if (parts.Length != 2) return null;
                                                         return new Style(parts[0], parts[1]);
                                                     }).Where(x => x != null).ToList();

                if (styles.All(x => x.Key != e.StyleKey))
                    throw new StepException(string.Format("The element '{0}' did not have the '{1}' style.", e.Element,
                        e.StyleKey));

                if (!styles.Any(x => x.Key == e.StyleKey && x.Value == e.StyleValue))
                    throw new StepException(
                        string.Format("The element '{0}' had the '{1}' style, but it's value was not '{2}'.", e.Element,
                            e.StyleKey, e.StyleValue));
            }
            catch (NoSuchElementException ex)
            {
                throw new StepException(string.Format("The document does not contain an element that matches '{0}'.",
                    e.Element));
            }
        }
        public void WhereIsMyCheese(string url)
        {
            try
            {
                _driver = Browser.GetFirefoxDriver();

                _driver.Navigate().GoToUrl(url);

                _driver.FindElement(By.Id("windowOpener")).Click();

                _driver.SwitchTo().Window("windowName");
                _driver.FindElement(By.Id("CheesyButton")).Click();

                _driver.SwitchTo().Alert().Accept();
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("An exception occured: " + ex.Message);
                Debug.WriteLine("An exception occured: " + ex.Message);
            }
            finally
            {
                _driver.Quit();
            }
        }
Example #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TouchActions"/> class.
        /// </summary>
        /// <param name="driver">The <see cref="IWebDriver"/> object on which the actions built will be performed.</param>
        public TouchActions(IWebDriver driver)
            : base(driver)
        {
            IHasTouchScreen touchScreenDriver = driver as IHasTouchScreen;
            if (touchScreenDriver == null)
            {
                IWrapsDriver wrapper = driver as IWrapsDriver;
                while (wrapper != null)
                {
                    touchScreenDriver = wrapper.WrappedDriver as IHasTouchScreen;
                    if (touchScreenDriver != null)
                    {
                        break;
                    }

                    wrapper = wrapper.WrappedDriver as IWrapsDriver;
                }
            }

            if (touchScreenDriver == null)
            {
                throw new ArgumentException("The IWebDriver object must implement or wrap a driver that implements IHasTouchScreen.", "driver");
            }

            this.touchScreen = touchScreenDriver.TouchScreen;
        }
Example #13
0
        protected override object HandleSeleneseCommand(IWebDriver driver, string locator, string value)
        {
            string tableString = string.Empty;

            if (!TableParts.IsMatch(locator))
            {
                throw new SeleniumException("Invalid target format. Correct format is tableName.rowNum.columnNum");
            }

            Match tableMatch = TableParts.Match(locator);
            string tableName = tableMatch.Groups[0].Value;
            long row = int.Parse(tableMatch.Groups[1].Value, CultureInfo.InvariantCulture);
            long col = int.Parse(tableMatch.Groups[2].Value, CultureInfo.InvariantCulture);

            IWebElement table = finder.FindElement(driver, tableName);

            string script =
                "var table = arguments[0]; var row = arguments[1]; var col = arguments[2];" +
                "if (row > table.rows.length) { return \"Cannot access row \" + row + \" - table has \" + table.rows.length + \" rows\"; }" +
                "if (col > table.rows[row].cells.length) { return \"Cannot access column \" + col + \" - table row has \" + table.rows[row].cells.length + \" columns\"; }" +
                "return table.rows[row].cells[col];";

            object returnValue = JavaScriptLibrary.ExecuteScript(driver, script, table, row, col);
            IWebElement elementReturned = returnValue as IWebElement;
            if (elementReturned != null)
            {
                tableString = ((IWebElement)returnValue).Text.Trim();
            }
            else
            {
                throw new SeleniumException(returnValue.ToString());
            }

            return tableString;
        }
Example #14
0
        //Start the browser depending on the setting
        public void GetDriver(WebBrowsers webBrws)
        {
            WebBrws = webBrws;
            if (webBrws == WebBrowsers.Ie)
            {
                //Secutiry setting for IE
                var capabilitiesInternet = new InternetExplorerOptions { IntroduceInstabilityByIgnoringProtectedModeSettings = true };
                Driver = new InternetExplorerDriver(capabilitiesInternet);
            }
            else
                if (webBrws == WebBrowsers.FireFox)
                {
                    //FirefoxBinary binary = new FirefoxBinary(@"C:\Program Files (x86)\Mozilla Firefox\firefox.exe");
                    FirefoxProfile profile = new FirefoxProfile();
                    // profile.SetPreference("webdriver.firefox.bin", "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
                    Driver = new FirefoxDriver(profile);
                }
                else
                    if (webBrws == WebBrowsers.Chrome)
                    {
                        //Chrome driver requires the ChromeDriver.exe
                        Driver = new ChromeDriver(@"..\..\..\lib\BrowserDriver\Chrome");
                    }
                    else { throw new WebDriverException(); }

            Selenium = new WebDriverBackedSelenium(Driver, BaseUrl);
        }
Example #15
0
 ManageQueueSection(
     IWebDriver          webBrowserDriver)
         : base(webBrowserDriver)
 {
     this.QueueInformation = new QueueInformationSection(webBrowserDriver);
     this.QueueClient      = new QueueClientSection(webBrowserDriver);
 }
 public void Selectanoption(IWebDriver driver, By by, string optiontoselect)
 {
     var data = driver.FindElement(@by);
     //IList<IWebElement> dataoptions = data.FindElements(By.TagName("option"));
     var select = new SelectElement(data);
     @select.SelectByText(optiontoselect);
 }
 public void Recreate()
 {
     SeleniumTestBase.LogDriverId(driver, "Recreation - SelfCleanUpWebDriver (OLD)");
     Dispose();
     driver = CreateInstance();
     SeleniumTestBase.LogDriverId(driver, "Recreation - SelfCleanUpWebDriver (NEW)");
 }
Example #18
0
 public void Setup()
 {
     
     _driver = Starter.WebDriver;
     _driver.Navigate().GoToUrl("http://qm-homework.wikia.com");
     _hp = PageObjects.HomePage;
 }
Example #19
0
 public void SetupTest()
 {
     driver = new FirefoxDriver();
     driver.Manage().Window.Maximize();
     baseURL = WebDriverExtension.BASE_URL;
     verificationErrors = new StringBuilder();
 }
Example #20
0
 public SearchPage(IWebDriver driver)
 {
     this.driver = driver;
     Boolean isPresent = driver.FindElement(By.CssSelector("#btnFTPOutputFile")).Size > 0;
     if (isPresent == false)
         throw new NoSuchElementException("This is not the Search page");               
 }
        internal static void DestroyVisualSearch(IWebDriver webDriver)
        {
            MyLog.Write("DestroyVisualSearch: Started");
            IJavaScriptExecutor jsExec = webDriver as IJavaScriptExecutor;

            string[] JavaSCriptObjectsToDestroy = new string[]
            {
                "document.SWD_Page_Recorder",
                "document.Swd_prevActiveElement",
                "document.swdpr_command",
            };

            StringBuilder deathBuilder = new StringBuilder();

            foreach (var sentencedToDeath in JavaSCriptObjectsToDestroy)
            {

                deathBuilder.AppendFormat(@" try {{ delete {0}; }} catch (e) {{ if (console) {{ console.log('ERROR: |{0}| --> ' + e.message)}} }} ", sentencedToDeath);
            }

            if (IsVisualSearchScriptInjected(webDriver))
            {
                MyLog.Write("DestroyVisualSearch: Scripts have been injected previously. Kill'em all!");
                jsExec.ExecuteScript(deathBuilder.ToString());
            }

            MyLog.Write("DestroyVisualSearch: Finished");
        }
        public static void Dispose()
        {

            Driver.Quit();
            Driver = null;

        }
        /// <summary>
        /// Handles the command.
        /// </summary>
        /// <param name="driver">The driver used to execute the command.</param>
        /// <param name="locator">The first parameter to the command.</param>
        /// <param name="value">The second parameter to the command.</param>
        /// <returns>The result of the command.</returns>
        protected override object HandleSeleneseCommand(IWebDriver driver, string locator, string value)
        {
            UserLookupStrategy strategy = new UserLookupStrategy(value);
            this.finder.AddStrategy(locator, strategy);

            return null;
        }
        public static void Init()
        {
            if (TestEnvironment.BrowserName == BrowserType.FireFox & Driver == null)
            {
                Driver = new FirefoxDriver();

                Driver.Manage().Window.Maximize();

                //LoadPage();
            }
            if (TestEnvironment.BrowserName == BrowserType.Chrome & Driver == null)
            {
                //Driver = new ChromeDriver(@"D:\Projects\Solution1\Eclips\Lib\BrowserExe");
                Driver = new ChromeDriver();
                Driver.Manage().Window.Maximize();
                //LoadPage();
            }
            if (TestEnvironment.BrowserName == BrowserType.IE & Driver == null)
            {
                Driver = new InternetExplorerDriver();
                Driver.Manage().Window.Maximize();
                //LoadPage();
            }
            LoadPage();
            //clearBrowserCache();

            Driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(20));
        }
 public CreateCustomerPage(IWebDriver driver) : base(driver)
 {
     if (!driver.PageSource.Contains("Server Error") && driver.Title != "Nuovo cliente")
     {
         throw new ArgumentException("This is not the create customer page: " + driver.Title);
     }
 }
Example #26
0
 /// <summary>
 /// Handles the command.
 /// </summary>
 /// <param name="driver">The driver used to execute the command.</param>
 /// <param name="locator">The first parameter to the command.</param>
 /// <param name="value">The second parameter to the command.</param>
 /// <returns>The result of the command.</returns>
 protected override object HandleSeleneseCommand(IWebDriver driver, string locator, string value)
 {
     StringBuilder builder = new StringBuilder();
     this.mutator.Mutate(locator, builder);
     ((IJavaScriptExecutor)driver).ExecuteScript(builder.ToString());
     return null;
 }
		public void PasswordlessAuthentication()
		{
			string email = "admin@test";
			_webDriver = new RemoteWebDriver(new Uri("http://localhost:9515"), DesiredCapabilities.Chrome());
			_webDriver.Manage().Window.Maximize();
			_webDriver.Navigate().GoToUrl("http://dev.icms/Account/Login");
			//Enter email address on login page
			IWebElement emailLogin = _webDriver.FindElement(By.Id("Email"));
			emailLogin.Clear();
			emailLogin.SendKeys(email);
			IWebElement authenticateButton = _webDriver.FindElement(By.Id("requestauth"));
			authenticateButton.Click();
			//this should have sent me an email
			//Let's pretend we got the email and check the server for the authtoken and plug it into the URL
			
			string token = HttpUtility.UrlEncode(TestUtilities.AuthenticationUtil.GetAuthToken(email));
			string goToUrl = string.Format("http://dev.icms/account/authorize/?authtoken={0}&email={1}&returnUrl=%2f", token, email);

			_webDriver.Quit();
			_webDriver = new RemoteWebDriver(new Uri("http://localhost:9515"), DesiredCapabilities.Chrome());
			
			_webDriver.Navigate().GoToUrl(goToUrl);	

			//Check DOM to see if we are logged in
			IWebElement elem = _webDriver.FindElement(By.CssSelector("h1"));
			Assert.IsTrue(elem.Text == "Welcome Admin Development");

		}
Example #28
0
 public void TakeScreenshot(IWebDriver driver, string path)
 {
     ITakesScreenshot screenshotDriver = driver as ITakesScreenshot;
     Screenshot screenshot = screenshotDriver.GetScreenshot();
     screenshot.SaveAsFile(path, System.Drawing.Imaging.ImageFormat.Png);
     screenshot.ToString();
 }
Example #29
0
 public void BaseTestInitialize(IWebDriver initialDriver, string baseUri, int timeout)
 {
     this.Driver = initialDriver;
     this.BaseUri = baseUri;
     this.Timeout = timeout;
     this.Wait = new WebDriverWait(initialDriver, TimeSpan.FromSeconds(timeout));
 }
 private void GetDriver()
 {
     _driver = (IWebDriver)Registry.hashTable["driver"]; //забираем из хештаблицы сохраненный ранее драйвер
     _driver.Navigate().GoToUrl(Paths.UrlCreatePk); //заходим по ссылке
     _driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
     //ставим ожидание в 10 сек на случай, если страница медленно грузится и нужные эл-ты появятся не сразу
 }