Example #1
0
        private void DeleteAllLessons()
        {
            var lessonsCount = driver.FindElements(By.CssSelector("div.lesson")).Count;

            for (var i = 0; i < lessonsCount; i++)
            {
                var currentLesson = driver.FindElement(By.CssSelector("div.lesson"));

                var     addPupil = driver.FindElement(By.CssSelector("div.col.pupils-list-side-panel > div > ul > li:nth-child(3) > div"));
                Actions actions  = new Actions(driver);
                actions.MoveToElement(addPupil);
                actions.Perform();


                driver.FindElement(By.CssSelector("div.lesson")).Click();
                wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.CssSelector("li.edit-lesson")));

                var lesson = driver.FindElement(By.CssSelector(".schedule-popover .name")).Text;
                var time   = driver.FindElement(By.CssSelector(".schedule-popover .time")).Text;

                driver.FindElement(By.CssSelector("li.edit-lesson")).Click();
                wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.CssSelector("button.delete")));

                driver.FindElement(By.CssSelector("button.delete")).Click();
                wait.Until(ExpectedConditions.StalenessOf(currentLesson));

                Console.WriteLine($"{lesson} - занятие {time} удалено");
            }

            Console.WriteLine("");
            Console.WriteLine($"Все занятия({lessonsCount}) на следующей неделе удалены");
        }
Example #2
0
        /// <summary>
        /// Wait until an element is no longer attached to the DOM.
        /// </summary>
        /// <param name="locator">Locator for the web element.</param>
        /// <param name="waitType">Type of wait from <see cref="WaitType"/>.</param>
        public void WaitForElementStaleness(By locator, WaitType waitType)
        {
            bool result = false;

            try
            {
                TimeSpan      time = GetWait(waitType);
                IWebElement   elem = (new SeleniumActions()).FindElement(locator);
                WebDriverWait wait = new WebDriverWait(Driver, time);
                result = wait.Until(ExpectedConditions.StalenessOf(elem));
                if (!result)
                {
                    throw new WebDriverTimeoutException();
                }
            }
            catch (WebDriverTimeoutException e)
            {
                string message = string.Format(" The element '{0}' is still attached with DOM in given wait time: '{1}'", locator, waitType.ToString());
                CustomExceptionHandler.CustomException(e, message);
            }
            catch (Exception e)
            {
                CustomExceptionHandler.CustomException(e);
            }
        }
Example #3
0
 public void RemoveItemsFromBasket(int number_of_items)
 {
     for (int i = 0; i < number_of_items; i++)
     {
         if (i == number_of_items - 1)
         //Removing the last item from the order
         {
             //Get last item in the order
             IWebElement LastItemInTheOrder = driver.FindElement(By.CssSelector("div#order_confirmation-wrapper tr:nth-of-type(2) td.item"));
             //Remove Item from the order
             driver.FindElement(By.CssSelector("button[name=remove_cart_item]")).Click();
             //Verify the order table has changed
             wait.Until(ExpectedConditions.StalenessOf(LastItemInTheOrder));
         }
         else
         {
             //Get last item in the order
             IWebElement LastItemInTheOrder = driver.FindElement(By.CssSelector("div#order_confirmation-wrapper tr:nth-of-type(2) td.item"));
             //Select first duck in the list
             driver.FindElement(By.CssSelector("ul.shortcuts li.shortcut:nth-of-type(1) a")).Click();
             //Remove Item from the order
             driver.FindElement(By.CssSelector("button[name=remove_cart_item]")).Click();
             //Verify the order table has changed
             wait.Until(ExpectedConditions.StalenessOf(LastItemInTheOrder));
         }
     }
 }
Example #4
0
        public void clickPlaceOrderButton()
        {
            var wait = new WebDriverWait(_driver, new TimeSpan(0, 0, 30));

            wait.Until(ExpectedConditions.StalenessOf(PlaceOrderButton));
            PlaceOrderButton.Click();
        }
Example #5
0
        public void Test()
        {
            driver.Url = "http://localhost/litecart/";

            for (int i = 0; i < 3; i++)
            {
                driver.FindElement(By.CssSelector("li.product")).Click();
                if (driver.FindElements(By.CssSelector("select[name='options[Size]']")).Count() > 0)
                {
                    SelectElement selectElement = new SelectElement(driver.FindElement(By.CssSelector("select[name='options[Size]']")));
                    selectElement.SelectByIndex(1);
                }
                driver.FindElement(By.CssSelector("button[name=add_cart_product]")).Click();
                wait.Until(ExpectedConditions.TextToBePresentInElementLocated(By.CssSelector("div#cart span.quantity"), (i + 1).ToString()));
                driver.Navigate().Back();
            }

            driver.FindElement(By.CssSelector("div#cart a.link")).Click();

            while (driver.FindElements(By.CssSelector("div#box-checkout-summary table tr td")).Count > 0)
            {
                driver.FindElement(By.CssSelector("button[name = remove_cart_item]")).Click();
                wait.Until(ExpectedConditions.StalenessOf(driver.FindElement(By.CssSelector("div#box-checkout-summary table tr td"))));
            }
        }
Example #6
0
        void selectFirstProduct()
        {
            var products = driver.FindElements(productsLocator);

            products[0].Click();
            wait.Until(ExpectedConditions.StalenessOf(products[0]));
        }
Example #7
0
        public void RemoveItem()
        {
            var wait = new WebDriverWait(TestConfiguration.GetDriverInstance(), TimeSpan.FromSeconds(3));

            buttonClose.Click();
            wait.Until(ExpectedConditions.StalenessOf(item));
        }
Example #8
0
        public void RemoveItem(string name)
        {
            var element = _wait.Until(ExpectedConditions.ElementToBeClickable(By.LinkText("Shopping list")));

            element.Click();
            var buttons =
                _wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.ClassName("button")));
            var items =
                _wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.ClassName("is-size-4")));

            for (var i = 0; i < items.Count; i++)
            {
                if (items[i].Text == name)
                {
                    buttons[i + 1].Click();
                }
            }

            buttons = _wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.ClassName("button")));
            buttons[items.Count + 3].Click();
            _wait.Until(ExpectedConditions.StalenessOf(buttons[items.Count + 3]));
            buttons = _wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.ClassName("button")));
            buttons[items.Count + 3].Click();
            _itemCounter--;
        }
Example #9
0
        public void BuyDucks()
        {
            driver.Url = "https://litecart.stqa.ru/en/";
            for (int i = 1; i < 4; i++)
            {
                driver.FindElement(By.ClassName("product")).Click();


                if (IsElementPresent(By.CssSelector("[name=\"options[Size]\"]")))
                {
                    driver.FindElement(By.CssSelector("[name=\"options[Size]\"]")).Click();
                    driver.FindElement(By.CssSelector("[name=\"options[Size]\"] option:nth-child(2)")).Click();
                }
                driver.FindElement(By.CssSelector("[name = add_cart_product]")).Click();
                IWebElement   cart  = driver.FindElement(By.CssSelector("#cart .content .quantity"));
                string        count = Convert.ToString(i);
                WebDriverWait wait  = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
                wait.Until(ExpectedConditions.TextToBePresentInElement(cart, count));

                driver.Navigate().Back();
                Console.WriteLine(i);
            }
            driver.FindElement(By.CssSelector("#cart .link")).Click();

            if (IsElementPresent(By.CssSelector("[name=remove_cart_item]")))
            {
                IWebElement table = driver.FindElement(By.Id("box-checkout-summary"));
                driver.FindElement(By.CssSelector("[name=remove_cart_item]")).Click();
                wait.Until(ExpectedConditions.StalenessOf(table));
            }
        }
Example #10
0
        public void RecycleBin()
        {
            driver.Navigate().GoToUrl(baseURL);

            for (int i = 1; i <= 3; i++)
            {
                driver.FindElement(By.CssSelector("ul.listing-wrapper li.product")).Click();                                        //открыть первый товар

                var counterInCart = driver.FindElement(By.CssSelector("#cart span.quantity")).Text;                                 // количество в корзине

                driver.FindElement(By.Name("add_cart_product")).Click();                                                            //добавить товар в корзину

                wait.Until(ExpectedConditions.InvisibilityOfElementWithText(By.CssSelector("#cart span.quantity"), counterInCart)); // проверяем что количество в корзине изменилось

                driver.FindElement(By.Id("logotype-wrapper")).Click();                                                              // домашняя страница
            }

            driver.FindElement(By.CssSelector("#cart a.link")).Click();

            while (driver.FindElements(By.Name("remove_cart_item")).Count > 0)
            {
                var removeButton = driver.FindElement(By.Name("remove_cart_item"));

                removeButton.Click();

                wait.Until(ExpectedConditions.StalenessOf(removeButton));
            }

            driver.FindElement(By.CssSelector("#checkout-cart-wrapper p em"));
        }
Example #11
0
        public void Task_13()
        {
            IWebElement cartCounter;

            for (int i = 1; i <= 3; i++)
            {
                driver.Navigate().GoToUrl("http://localhost/litecart/en/");
                driver.FindElement(By.CssSelector(".product")).Click();
                if (driver.Url.Contains("yellow-duck-p-1"))
                {
                    var select = new SelectElement(driver.FindElement(By.Name("options[Size]")));
                    select.SelectByIndex(1);
                }
                driver.FindElement(By.Name("add_cart_product")).Click();
                cartCounter = driver.FindElement(By.ClassName("quantity"));
                wait.Until(ExpectedConditions.TextToBePresentInElement(cartCounter, i.ToString()));
            }

            driver.FindElement(By.Id("cart")).Click();

            if (driver.IsElementPresent(By.Id("order_confirmation-wrapper")))
            {
                var table   = driver.FindElement(By.Id("order_confirmation-wrapper"));
                var counter = driver.FindElements(By.CssSelector(".dataTable tr")).Count - 5;
                do
                {
                    wait.Until((IWebDriver d) => d.FindElements(By.CssSelector(".dataTable tr")).Count - 5 == counter);
                    driver.FindElement(By.Name("remove_cart_item")).Click();
                    counter--;
                } while (counter > 0);
                wait.Until(ExpectedConditions.StalenessOf(table));
            }
        }
Example #12
0
        public static Dictionary <string, object> GetAllAttributes(this IWebElement element)
        {
            ExpectedConditions.StalenessOf(element);
            ExpectedConditions.TextToBePresentInElement(element, "");

            string js =
                "var items = {};" +
                "for (i = 0; i < arguments[0].attributes.length; ++i) {" +
                "   if (arguments[0].attributes[i].value != undefined) {" +
                "       items[arguments[0].attributes[i].name] = arguments[0].attributes[i].value;" +
                "   }" +
                "}" +
                "return items;";

            Dictionary <string, object> attributes = null;

            try
            {
                attributes = (Dictionary <string, object>)((IJavaScriptExecutor)BaseSeleniumPage.webDriver).ExecuteScript(js, element);
            }
            catch (Exception)
            {
            }

            return(attributes);
        }
Example #13
0
        public void TestAddAndDeleteEmail()
        {
            GoToSettings();
            Driver.FindElementByXPath("//*[@id=\"content\"]/div/div[2]/div[1]/div/ul/li[2]/a").Click();
            Driver.FindElementById("showAddEmailBtn").Click();
            var emailInput = Driver.FindElementById("emailInput");

            emailInput.SendKeys("*****@*****.**");
            var initEmailRowsCount = Driver.FindElementsById("emailContainer").Count;

            Driver.FindElementById("addBtn").Click();

            WebDriverWait wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(10));
            IWebElement   newEmailSpan;

            try
            {
                newEmailSpan = wait.Until(x =>
                {
                    var spans = x.FindElements(By.Id("emailContainer"));
                    return(spans.Count > initEmailRowsCount ? spans[spans.Count - 1] : null);
                });
            }
            catch (WebDriverTimeoutException)
            {
                throw new Exception("email not add");
            }

            newEmailSpan.FindElement(By.Id("delete")).Click();
            wait.Until(ExpectedConditions.StalenessOf(newEmailSpan));
            Driver.FindElementById("cancelBtn").Click();
        }
Example #14
0
        public void RemoveAllProducts(IWebDriver driver, WebDriverWait wait)
        {
            IWebElement         productNameElement = null;
            IList <IWebElement> productsInTable    = driver.FindElements(By.XPath(".//*[@id='order_confirmation-wrapper']/table/tbody/tr/td[2]"));
            IWebElement         product            = null;
            int numberOfProducts = 0;

            //SelectActiveProduct(driver, wait);
            productNameElement = driver.FindElement(By.XPath(".//a/strong"));
            for (int i = 0; i < productsInTable.Count; i++)
            {
                if (productsInTable[i].GetAttribute("textContent") == productNameElement.GetAttribute("textContent"))
                {
                    product = productsInTable[i];
                }
            }
            numberOfProducts = CheckNumberOfProducts(driver);

            for (int i = 0; i < numberOfProducts; i++)
            {
                wait.Until(ExpectedConditions.ElementIsVisible(By.Name("remove_cart_item")));
                driver.FindElement(By.Name("remove_cart_item")).Click();
                wait.Until(ExpectedConditions.StalenessOf(product));
            }
        }
        /// <summary>
        /// Waits for a page to load
        /// </summary>
        /// <param name="element">An element from the previous page. If omitted, the code will wait for the body of the page to be viosible</param>
        public void WaitForPageToLoad(IWebElement element)
        {
            if (RecordPerformance)
            {
                RatTimerCollection.StartTimer();
            }

            if (element == null)
            {
                var load = new WebDriverWait(Driver, BaseSettings.Timeout)
                           .Until(ExpectedConditions.ElementIsVisible(By.TagName("body")));
            }
            else if (typeof(TWebDriver) != typeof(OperaDriver))
            {
                var wait = new WebDriverWait(Driver, Preferences.BaseSettings.Timeout)
                           .Until(
                    ExpectedConditions.StalenessOf(element));
            }
            else
            {
                //TODO: Investigate the Opera Driver with respect to DOM staleness
                Console.Out.WriteLine("Opera does not currently seem to report staleness of the DOM. Under investigation");
            }

            if (RecordPerformance)
            {
                RatTimerCollection.StopTimer(EnumTiming.PageLoad);
            }
        }
Example #16
0
        public void ClickToSubmitFileUpload()
        {
            var element = UploadFileSubmitLink;

            element.Click();
            BrowserWait().Until(ExpectedConditions.StalenessOf(element));
        }
Example #17
0
        /*
         * Created By : Srikanth D
         * Description: To Perform Signout
         * Date Modified:
         * Modification Details :
         */
        public void Signout(String BrowserType)
        {
            //Due to issues in the Web Driver Move to Element is not working consistently

            InternalWait.Until(ExpectedConditions.ElementExists(txtbox_SearchGames));
            InternalWait.Until(ExpectedConditions.ElementIsVisible(txtbox_SearchGames));

            //Work Arrounds to hover over user options selection button. It is different for firefox and Chrome
            if (BrowserType.Trim().ToLower() == "firefox")
            {
                commonfunctions.ClickElement(driver, btn_UserOptions);
            }

            if (BrowserType.Trim().ToLower() == "chrome")
            {
                InternalWait.Until(ExpectedConditions.ElementExists(btn_UserOptions));
                InternalWait.Until(ExpectedConditions.StalenessOf(driver.FindElement(btn_UserOptions)));
                InternalWait.Until(ExpectedConditions.ElementIsVisible(btn_UserOptions));
                InternalWait.Until(ExpectedConditions.ElementToBeClickable(btn_UserOptions));

                Actions act = new Actions(driver);
                act.MoveToElement(driver.FindElement(btn_UserOptions)).ContextClick(driver.FindElement(btn_UserOptions)).Build().Perform();
            }

            commonfunctions.ClickElement(driver, btn_signout);
        }
Example #18
0
        public void Basket()
        {
            driver.Url = "http://localhost/litecart";
            wait.Until(ExpectedConditions.TitleIs("Online Store | My Store"));
            do
            {
                driver.FindElement(By.CssSelector("ul.listing-wrapper li:first-child")).Click();
                wait.Until(ExpectedConditions.ElementExists(By.Name("add_cart_product")));
                if (driver.FindElements(By.Name("options[Size]")).Count > 0)
                {
                    SelectElement SelectSize = new SelectElement(driver.FindElement(By.Name("options[Size]")));
                    SelectSize.SelectByIndex(1);
                }

                driver.FindElement(By.Name("add_cart_product")).Click();
                System.Threading.Thread.Sleep(700);
                driver.FindElement(By.Id("logotype-wrapper")).Click();
                wait.Until(ExpectedConditions.TitleIs("Online Store | My Store"));
            } while (Convert.ToInt32(driver.FindElement(By.CssSelector("span.quantity")).Text) < 3);
            driver.FindElement(By.Id("cart-wrapper")).Click();
            wait.Until(ExpectedConditions.TitleIs("Checkout | My Store"));
            do
            {
                IWebElement ProductsTable = driver.FindElement(By.ClassName("items"));
                wait.Until(ExpectedConditions.ElementToBeClickable(By.Name("remove_cart_item")));
                driver.FindElement(By.Name("remove_cart_item")).Click();
                wait.Until(ExpectedConditions.StalenessOf(ProductsTable));
            } while (driver.FindElements(By.Id("box-checkout-summary")).Count > 0);
        }
Example #19
0
        /*[FindsBySequence]
         * [FindsBy(How = How.ClassName, Using = "dropdown_8")]
         * [FindsBy (How=How.ClassName, Using = "ty-float-left")]
         * For some reason the popup didn't work from ClassName method, it didn't find it*/
        //[FindsBy(How=How.XPath,Using = "//*[@id='dropdown_8']/div/div[2]/div[1]")]
        //private IWebElement cart_page;

        //[FindsBy(How = How.ClassName, Using = "notification-body-extended")]
        //private IWebElement popUp_element;
        public CartPage addtoTheCart()
        {
            //cart_page.Click();
            try
            {
                addCart.Click();
                IWebElement popUp_element = wait.Until(a => a.FindElement(By.ClassName("notification-body-extended")));

                //async_delay(10000); here the method will not affect the main thread, that's why i didn't work
                //Thread.Sleep(7000); // here the main thread is affected/frozen untill the method has ended
                //wait.Until(ExpectedConditions.StalenessOf(popUp_element));
                //Thread.Sleep(6000);
                wait.Until(ExpectedConditions.StalenessOf(popUp_element));
                buttonMyCart.Click();

                IWebElement cart_page = wait.Until(a => a.FindElement(By.XPath("//*[@id='dropdown_8']/div/div[2]/div[1]")));
                cart_page.Click();
            }
            catch (Exception err)
            {
                ScenarioContext.Current[("Error")] = err;
            }

            return(new CartPage(driver));
        }
Example #20
0
        public string click(IWebDriver driver, List <filtry.unactiveFilters> lists, int number)
        {
            string filterName;

            IWait <IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));

            if (number >= 0)
            {
                filterName = lists[number].textFilter.Text;
                lists[number].textFilter.Click();
                return(filterName);
            }
            else
            {
                number = rand.Next(0, lists.Count - 1);

                filterName = lists[number].textFilter.Text;

                ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", lists[number].textFilter);
                driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(2));
                try
                {
                    lists[number].textFilter.Click();
                    wait.Until(ExpectedConditions.StalenessOf(lists[number].textFilter));
                    driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(2));
                }
                catch
                {
                    MessageBox.Show("Nie udało się kliknąć filtru");
                }
                return(filterName);
            }
        }
        //Проверка на ИСЧЕЗНОВЕНИЕ элемента это не то же самое, проверка на ОТСУТСТВИЕ элемента
        //ОТСУТСТВИЕ - это когда у нас есть локатор, но мы по этому локатору ничего не можем найти
        //ИСЧЕЗНОВЕНИЕ - это когда элемент есть, потом он пропадает и на его место появлятеся точно такой же
        //элемент или очень похожий.
        //Речь идет об именно том элементе, который ранее был найден по локатору.
        //Сначала надо найти элемент, а потом ждать его исчезновения.

        //Если браузер пытается обратиться к элементу использую идентафикатор, который вернул метод FindElement
        //и возникает StaleElementRefferanceException - именно по этому признаку можно определить, что элемент исчез.

        public void Method()
        {
            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));

            //Здесь не используется никаких неявных ожиданий т.к мы ничего не ищем!
            wait.Until(ExpectedConditions.StalenessOf(element));
        }
 /// <summary>
 ///     Waits until an element is no longer attached to the DOM, then waits until page title matches the passed parameter
 ///     and then execute WaitUntilHtmlTagLoads,
 ///     where it finds the first <see cref="T:OpenQA.Selenium.IWebElement" /> using the given method.
 /// </summary>
 /// <param name="driver">The <see cref="IWebDriver" />.</param>
 /// <param name="titleOnNewPage">Title of the page</param>
 /// <param name="elementOnOldPage">The <see cref="IWebElement" /></param>
 /// <returns>The <see cref="IWebElement" /> of html tag.</returns>
 public static IWebElement WaitUntilPageLoad(this IWebDriver driver, IWebElement elementOnOldPage,
                                             string titleOnNewPage)
 {
     driver.Wait().Until(ExpectedConditions.StalenessOf(elementOnOldPage));
     driver.Wait().Until(ExpectedConditions.TitleIs(titleOnNewPage));
     return(driver.WaitUntilHtmlTagLoads());
 }
Example #23
0
 public void ClickAndWait()
 {
     WaitUntilElementExists();
     WaitUntilClickable();
     Element.Click();
     Wait.Until(ExpectedConditions.StalenessOf(Element));
 }
Example #24
0
        public void clickUpdateCartButton()
        {
            var wait = new WebDriverWait(_driver, new TimeSpan(0, 0, 30));

            wait.Until(ExpectedConditions.StalenessOf(UpdateCartButton));
            UpdateCartButton.Click();
        }
        //Что означает "окончание загрузки страницы"? -- http://barancev.github.io/page-loading-complete/
        //В процессе обработки страницы браузер меняет специальное свойство document.readyState, которое как раз
        //и содержит информацию о текущем этапе загрузки:
        //- LOADING означает, что страница ещё загружается
        //- INTERACTIVE означает, что основное содержимое страницы загрузилось и отрисовалось, пользователь
        //уже может с ней взаимодействовать, но ещё продолжается загрузка дополнительных ресурсов,
        //- COMPLETE означает, что все дополнительные ресурсы тоже загружены.
        //Selenium использует именно свойство document.readyState для определения загрузки страницы.
        //По - умолчанию Selenium ждет пока свойство document.readyState будет COMPLETE(но это можно поменять)
        //https://www.reg.ru/choose/domain/?domains=software - пример где после document.readyState=COMPLETE все еще идут запросы.
        //ВЫВОД - недостаточно ждать конца загрузки страницы -> нужно ждать пока появится элемент с которым я буду работать.


        //Как Selenium ожидает окончания загрузки страницы? -- http://barancev.github.io/how-selenium-waits-for-page-to-load/
        //Когда Selenium ждет? Selenium ждет не ПОСЛЕ команды, а ПЕРЕД командой.
        //Другими словами перед выполнением каждой команды Selenium ждет пока свойство document.readyState будет COMPLETE.

        //Что делать, если страница загружается слишком долго? -- http://barancev.github.io/slow-loading-pages/
        //Пример с картинкой на 7мб - страница грузится доооолго. Т.е свойство document.readyState никак не может стать
        //COMPLETE - оно продолжает оставаться в состоянии INTERACTIVE.
        //В таком случае есть два способа подсказать Selenium, чтобы он не ждал такой длинной загрузки.
        //ПЛОХОЙ СПОСОБ
        public void SetUp()
        {
            var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));

            driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(1);
            //Ну, раз уж мы отобрали у Selenium и взяли на себя ответственность за ожидание
            //загрузки страницы, надо брать ответственность и за “выгрузку” страницы тоже. То есть
            //перед ожиданием появления элемента, который должен найтись на следующей странице, нужно
            //сначала подождать, пока исчезнет элемент, находящийся на текущей странице. Например,
            //исчезнет та самая кнопка, по которой кликали
            // открываем сайт, но ждём недолго
            try
            {
                driver.Url = "http://www.sazehgostar.com/SitePages/HomePage.aspx";
            }
            catch (TimeoutException ignore)
            {
            }
            // ждём появления кнопки на "недозагруженной" странице
            IWebElement button = wait.Until(ExpectedConditions.ElementIsVisible(By.Id("en")));

            // кликаем
            try
            {
                button.Click();
            }
            catch (TimeoutException ignore)
            {
            }
            // ждём исчезновения кнопки, то есть "выгрузки" страницы
            wait.Until(ExpectedConditions.StalenessOf(button));
            // ждём загрузки следующей страницы
            wait.Until(ExpectedConditions.ElementIsVisible(By.Id("en")));
        }
        public void RemoverUmContatoDeUmUsuario()
        {
            //Clicar pelo elemento XPath //span[text()="+554788881122"]/following-sibling::a
            navegador.FindElement(By.XPath("//span[text()='554788881122']/following-sibling::a")).Click();

            //Confirmar a janela java script o botão Ok
            navegador.SwitchTo().Alert().Accept();

            //Validar que a mensagem apresentanda Rest in peace, dear email! id = "toast-container"
            IWebElement mensagemPop = navegador.FindElement(By.Id("toast-container"));
            string      mensagem    = mensagemPop.Text;

            Assert.AreEqual("Rest in peace, dear phone!", mensagem);

            string nomeDoArquivo = @"C:\temp\" + Generator.dataHoraParaArquivo() + "RemoverUmcontatoParaUsusario.png";

            Foto.tirar(navegador, nomeDoArquivo);



            //Depois da janela ser apresentada aguardar 10 segundos a janela desaparecer.3
            aguardar = new WebDriverWait(navegador, TimeSpan.FromSeconds(10));

            //aguardar.Until(driver => navegador.FindElement(By.Id("toast-container")));
            aguardar.Until(ExpectedConditions.StalenessOf(mensagemPop));

            //Fazer logaunt clicar no link Logout
            navegador.FindElement(By.LinkText("Logout")).Click();
        }
Example #27
0
        public static void FastWaitForStaleness(this IWebDriver driver, IWebElement element, int time = 20000)
        {
            WebDriverWait waiter = new WebDriverWait(driver, TimeSpan.FromMilliseconds(time));

            waiter.PollingInterval = TimeSpan.FromMilliseconds(1);
            waiter.Until(ExpectedConditions.StalenessOf(element));
        }
        public void TestAddingProductToCheckout()
        {
            driver.Url = "http://localhost:8080/litecart";
            wait.Until(ExpectedConditions.ElementExists(By.Id("slider-wrapper")));
            int i = 1;

            do
            {
                driver.FindElement(By.CssSelector("#box-most-popular [class^=product]")).Click();
                wait.Until(ExpectedConditions.ElementExists(By.CssSelector("[name=add_cart_product]")));


                driver.FindElement(By.CssSelector("[name=add_cart_product]")).Click();
                var quantityInCart = driver.FindElement(By.CssSelector("#cart .quantity"));
                wait.Until(ExpectedConditions.TextToBePresentInElement(quantityInCart, Convert.ToString(i)));
                driver.Navigate().Back();
                wait.Until(ExpectedConditions.ElementExists(By.Id("slider-wrapper")));
                i++;
            } while (driver.FindElement(By.CssSelector("#cart .quantity")).Text != "3");

            driver.FindElement(By.CssSelector("#cart .link")).Click();
            wait.Until(ExpectedConditions.ElementExists(By.Id("box-checkout-summary")));

            do
            {
                var productList = driver.FindElement(By.CssSelector("#order_confirmation-wrapper table tbody"));
                driver.FindElement(By.CssSelector("[value=Remove]")).Click();
                wait.Until(ExpectedConditions.StalenessOf(productList));
            } while (IsElementPresent(driver, By.CssSelector("#order_confirmation-wrapper")));
        }
        private string Delete_from_cart(IWebDriver driver, string path)
        {
            Random rand = new Random();

            try
            {
                IWebElement table = driver.FindElement(By.CssSelector("#order_confirmation-wrapper"));

                try
                {
                    driver.FindElement(By.Name("remove_cart_item")).Click();
                }
                catch (NoSuchElementException ex)
                {
                    return("not ok");
                }

                if (wait.Until(ExpectedConditions.StalenessOf(table)) == true)
                {
                    write_into_file("Удалили утку", path);
                }
                else
                {
                    write_into_file("Не смогли удалить утку", path);
                }

                return("ok");
            }
            catch (NoSuchElementException ex)
            {
                return("not ok");
            }
        }
Example #30
0
        private void DeleteAllLessonsForSelectedWeek(int weekIndex)
        {
            var week = weekIndex;

            // scroll to target week
            wait.Until(ExpectedConditions.ElementExists(By.CssSelector(".timetable-body")));
            Thread.Sleep(1000);

            for (var i = 0; i < week; i++)
            {
                wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.CssSelector("span.next")));
                var timetable = driver.FindElement(By.CssSelector(".timetable-body"));

                driver.FindElement(By.CssSelector("span.next")).Click();
                wait.Until(ExpectedConditions.StalenessOf(timetable));
            }

            try
            {
                wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.CssSelector("div.lesson")));
                DeleteAllLessons();
            }
            catch (WebDriverTimeoutException)
            {
                Console.WriteLine("Занятий на следующей неделе не было (но это не точно)");
                return;
            }
        }