protected void _verifyTextIsInElement(RemoteWebDriver driver, IWebElement element, string text) { _getWebDriverWait(driver) .Until( ExpectedConditions.TextToBePresentInElement(element, text) ); }
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)); } }
public void VerifyCart() { var Shop = GoToShopPage(driver); //add products to cart for (var i = 1; i <= 3; i++) { var detailPage = Shop.SelectProduct("Most Popular", 1); if (detailPage.IsSizeControlExist()) { detailPage.SelectSize("Small"); } detailPage.AddToCart(); wait.Until(ExpectedConditions.TextToBePresentInElement(detailPage.QuantityElement, i.ToString())); Shop = GoToShopPage(driver); } var Cart = Shop.GoToCart(); int ProductCount = Cart.GetProductsCount(); if (ProductCount > 1) { Cart.SelectFirstShortcut(); } //stop crazy carusel while (Cart.IsAnyProductExist()) { Cart.DeleteFirstProduct(); ProductCount--; } wait.Until(ExpectedConditions.TextToBePresentInElementLocated(By.CssSelector("em"), "There are no items in your cart.")); Assert.IsTrue(Cart.AreElementsPresent(By.XPath("//em[.='There are no items in your cart.']"))); }
public void Method() { wait.Until(ExpectedConditions.TitleIs("webdriver - Поиск в Google")); wait.Until(ExpectedConditions.TitleContains("webdriver - Поиск в")); wait.Until(ExpectedConditions.UrlContains("login.php")); wait.Until(ExpectedConditions.UrlToBe("http://pagination.js.org/")); var regex = @"\d"; wait.Until(ExpectedConditions.UrlMatches(regex)); wait.Until(ExpectedConditions.AlertIsPresent()); //В С# я не нашел wait.Until(ExpectedConditions.NumberOfWindowsToBe()); //нужно проверять то, что у элемента есть какой-то класс, вместо того, чтобы проверять стиль элемента. //как правило, разработчики не меняют стили напрямую, они присваивают классы. wait.Until(x => x.FindElement(By.CssSelector("locator")).GetAttribute("class").Contains("error")); wait.Until(ExpectedConditions.TextToBePresentInElement(element, "text")); wait.Until(ExpectedConditions.ElementToBeSelected(element, false)); wait.Until(ExpectedConditions.ElementToBeClickable(element)); //ElementToBeClickable - не соответствует своему названию. Сдесь проверяется то, что //елемент 1.Видимый, 2.Не disabled. И конечно, здесь нет никаких проверок, что эта кнопка НЕ ЗАКРЫТА никаким другим //элементом а если она прозрачная, то она будет считаться невидимой. Так, что название этого метода просто напросто врет. //По-настоящему ИНТЕРАКТИВНОСТЬ ОНО НЕ ПРОВЕРЯЕТ. //условие количества элементов с локатором var elements = driver.FindElements(By.CssSelector("locator")); wait.Until(x => elements.Count == 10); //но здесь мы возвращаем коллекцию элементов. var returnedElements = wait.Until(x => { var elements2 = x.FindElements(By.CssSelector("locaotr")); return(elements2.Count == 10 ? elements2 : null); }); //хз что это... var wait2 = new DefaultWait <IWebElement>(element); }
public void AddUserTest(string user, string password = password) { var menu = new MenuPage(driver); var wait = new WebDriverWait(this.driver, TimeSpan.FromSeconds(10)); menu.AdministrationMenuLocator.ClickEx(driver); menu.UserManagementMenuLocator.Click(); var userPage = new UserManagementPage(driver); userPage.AddNewUser(user, random, password); userPage.IdButtonLocator.ClickEx(driver); Thread.Sleep(1000); wait.Until(ExpectedConditions.TextToBePresentInElement(userPage.Id[0], "1")); userPage.IdButtonLocator.Click(); Thread.Sleep(1000); Assert.AreEqual($"{user}{random}@test.com", userPage.Login[0].Text, $"User {user} is not added"); }
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); }
/// <summary> /// Selects Year Group based on the Year Group Count /// </summary> public void SelectNoOfYearGroups(int NoOfYearGroups) { waiter.Until(ExpectedConditions.TextToBePresentInElement(GroupHeader, "School Groups")); waiter.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(YearGroupsCheckBox)); ReadOnlyCollection <IWebElement> YearGroupCheckboxlistYG = WebContext.WebDriver.FindElements(YearGroupsCheckBox); int i = 0; foreach (IWebElement YearGroupElem in YearGroupCheckboxlistYG) { if (YearGroupElem.Displayed == true && NoOfYearGroups != 0) { waiter.Until(ExpectedConditions.ElementToBeClickable(YearGroupElem)); if (YearGroupElem.Selected == false) { YearGroupElem.Click(); i++; } } if (i == NoOfYearGroups) { break; } } }
public string GetLoggedName(string nameSurname) { Waiter.Until(ExpectedConditions.TextToBePresentInElement(LogedName, nameSurname)); string text = LogedName.Text; return(text); }
public void TestQuizzEdge() { using (var driver = new EdgeDriver(Path.GetDirectoryName (Assembly.GetExecutingAssembly().Location))) { driver.Navigate().GoToUrl (@"https://*****:*****@cimob.pt", "teste12"); driver.FindElement(By.Id("News")).Click(); driver.FindElement(By.Id("CreateEdital")).Click(); string testOpenDate = "01/01/2018"; string testCloseDate = "10/10/2018"; string testTitle = "I'm a testing edital!"; string testContent = "I'm a edital Test Content!"; string testUrl = "www.testing.testedital"; driver.FindElement(By.Id("OpenDate")).SendKeys(testOpenDate); driver.FindElement(By.Id("CloseDate")).SendKeys(testCloseDate); driver.FindElement(By.Id("Title")).SendKeys(testTitle); driver.FindElement(By.Id("TextContent")).SendKeys(testContent); driver.FindElement(By.Id("link-text")).SendKeys(testUrl); driver.FindElement(By.Id("EditalSubmit")).Click(); wait.Until(ExpectedConditions.TextToBePresentInElement(driver.FindElement(By.ClassName("table")), testTitle)); } }
public BasicCheckBoxPage AssertSingleCheckBoxDemoSuccessMessageWithWait() { GetWait(2).Until(ExpectedConditions.TextToBePresentInElement(_singleCheckBoxMessage, SingleCheckBoxMessageText)); Assert.AreEqual(SingleCheckBoxMessageText, _singleCheckBoxMessage.Text, "tekstas nesutampa!"); return(this); }
public CheckBoxPage AssertSingleCheckBoxDemoSuccessMessageWithWait() { //WebDriverWait wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(10)); // 5 sek neuzteko padarem 10; iskelem sita i BasePage(supaprastinom, nes kartojasi) GetWait(2).Until(ExpectedConditions.TextToBePresentInElement(_singleCheckBoxMessage, SingleCheckBoxMessageText)); //GetWait ateina is BasePage klases, supaprastintas wait; lauksim 2 sekundes Assert.AreEqual(SingleCheckBoxMessageText, _singleCheckBoxMessage.Text, "Tekstas nesutampa"); return(this); }
/// <summary> /// Generate cliente mails this instance. /// </summary> /// <returns></returns> private string Generateemail(string feature) { string clientemail = string.Empty; bool flag = true; var wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(5)); while (flag) { try { // var returnerEmail = _driver.FindElement(_homeDetailsLoc.FetchEmailId); var returnerEmail = _driver.FindElement(By.XPath("(.//tr[@style='display: table-row;']//td[2]/span[text()='" + feature + "']/../div/a[contains(text(),'.com.au')])[last()]")); wait.Until(ExpectedConditions.TextToBePresentInElement(returnerEmail, ".com")); // clientemail = _act.getText(_homeDetailsLoc.FetchEmailId, "ClientEmail"); clientemail = _act.getText(By.XPath("(.//tr[@style='display: table-row;']//td[2]/span[text()='" + feature + "']/../div/a[contains(text(),'.com.au')])[last()]"), "ClientEmail"); break; } catch (Exception) { clientemail = _act.getText(By.XPath("(.//tr[@style='display: table-row;']//td[2]/span[text()='" + feature + "']/../div/a[contains(text(),'.com.au')])[last()]"), "ClientEmail"); flag = false; break; } } return(clientemail); }
internal void ClickSubcategories() { try { SubCategoriesBtn.Click(); } catch (ElementClickInterceptedException) { JSClick(SubCategoriesBtn); Console.WriteLine("ElementClickInterc"); } Waiter.Until(ExpectedConditions.TextToBePresentInElement(AddNewCatSub, "Add Sub-category")); Thread.Sleep(500); }
public void addToCard(int positionNumber) { wait.Until(ExpectedConditions.ElementIsVisible(By.CssSelector("div[class='c4-product-card-actions']"))); int expectedCartProductsCount = Convert.ToInt16(cartProductsCountElement.Text) + 1; int i = 1; foreach (IWebElement e in allProductsDivs) { if (i == positionNumber) { try { e.FindElement(By.CssSelector("button[class='md-primary md-block md-button ng-scope md-ink-ripple']")).Click(); } catch (NoSuchElementException) { e.FindElement(By.CssSelector("button[class='md-button md-ink-ripple']:nth-child(3)")).Click(); } break; } i++; } wait.Until(ExpectedConditions.TextToBePresentInElement(cartProductsCountElement, Convert.ToString(expectedCartProductsCount))); addItemToList(positionNumber); }
public void AddProductInCart() { IWebElement incart = driver.FindElement(By.CssSelector("div#cart span.quantity")); string iCount = incart.GetAttribute("textContent"); int num = int.Parse(iCount); By locator = By.CssSelector("#box-product div.content tr:nth-child(1) strong"); By locator2 = By.CssSelector("#box-product div.content tr:nth-child(1) select"); for (int i = num; i <= 2; i++) { driver.FindElement(By.CssSelector("div.content div.name")).Click(); if (IsSelect(driver, By.CssSelector("#box-product div.content tr:nth-child(1) select"))) { SelectSize(By.CssSelector("#box-product div.content tr:nth-child(1) select")); } driver.FindElement(By.Name("add_cart_product")).Click(); i++; string j = i.ToString(); IWebElement incart2 = driver.FindElement(By.CssSelector("div#cart span.quantity")); string iCount2 = incart2.GetAttribute("textContent"); wait.Until(ExpectedConditions.TextToBePresentInElement(incart2, $"{j}")); i = int.Parse(j); i--; driver.FindElement(By.CssSelector("div#logotype-wrapper")).Click(); } }
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)); } }
public void RunCheckShoppingListTest() { try { _driver.Navigate().GoToUrl("http://localhost/litecart/"); string ducksSelector = "//div[@id = 'box-most-popular']//div[@class = 'content']//ul//li//a[@class='link' and not(@title = 'Yellow Duck')]"; ReadOnlyCollection <IWebElement> ducksToAdd = _driver.FindElements(By.XPath(ducksSelector)); for (int i = 0; i < 3; i++) { ducksToAdd[i].Click(); _wait.Until(d => d.FindElement(By.Name("add_cart_product"))); _driver.FindElement(By.Name("add_cart_product")).Click(); _driver.FindElement(By.CssSelector("#breadcrumbs>ul>li>a")).Click(); IWebElement quantity = _driver.FindElement(By.CssSelector("span.quantity")); _wait.Until(ExpectedConditions.TextToBePresentInElement(quantity, (i + 1).ToString())); ducksToAdd = _driver.FindElements(By.XPath(ducksSelector)); } _driver.FindElement(By.Id("cart")).Click(); _wait.Until(d => d.FindElement(By.Name("remove_cart_item"))); for (int i = 0; i < 3; i++) { IWebElement removeButton = _driver.FindElement(By.Name("remove_cart_item")); _wait.Until(ExpectedConditions.ElementToBeClickable(By.Name("remove_cart_item"))); removeButton.Click(); } } catch (Exception ex) { throw ex; } }
public static bool FindElementHeaderText(WebDriverWait wait, String ClassName, String TagName, String text) { WebItem Item = new WebItem("", ClassName, "", TagName); IWebElement element = TestFramework.FindWebElement(Item); return(wait.Until(ExpectedConditions.TextToBePresentInElement(element, text))); }
public void What_Is_Implicit_Wait_And_Explicit_Wait() { //Implicit wait- Asking the browser to wait for amount of time driver should wait while searching for an element if it is not present immediately //If the element is found beofre the time seciified the next step will be executed without waiting for remaining time mentioned in implicit wait. chromedriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10); //Explicit Wait- Specific wait OpenQA.Selenium.Support.UI.WebDriverWait wait = new OpenQA.Selenium.Support.UI.WebDriverWait(chromedriver, TimeSpan.FromSeconds(10)); wait.Message = ""; //Gets for sets the message to be displayed when time expires wait.IgnoreExceptionTypes(); //Configures this instance to ignore the specific exceptions while waiting on the condition wait.PollingInterval = TimeSpan.FromMilliseconds(100); //Gets or sets how often the condition should be evaluated. The deafult timeout is 500milliseond wait.Until(x => x.FindElements(By.XPath("")).Count > 1); //Condtion till the wait should be applied. Throws exception when timeout expires. //wait.Until(ExpectedConditions.) wait.Until(ExpectedConditions.AlertIsPresent()); //An expectation for checking that an element is present on the DOM of a page //This does not necessarily mean that the element is visible. //// Returns: // The OpenQA.Selenium.IWebElement once it is located. wait.Until(ExpectedConditions.ElementExists(By.Id("elem"))); // Summary: // An expectation for checking that an element is present on the DOM of a page and // visible. Visibility means that the element is not only displayed but also has // a height and width that is greater than 0. // Returns: // The OpenQA.Selenium.IWebElement once it is located and visible. wait.Until(ExpectedConditions.ElementIsVisible(By.Id("elem"))); wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("elem"))); wait.Until(ExpectedConditions.TextToBePresentInElement(chromedriver.FindElement(By.Id("elem")), "")); // An expectation for checking the title of a page. wait.Until(ExpectedConditions.TitleIs("")); wait.Until(ExpectedConditions.UrlContains("")); }
public void TestCountriesEditLinkOpening() { driver.Url = "http://*****:*****@class='dataTable']/tbody/tr[@class='row']/td[5]/a")).Click(); wait.Until(ExpectedConditions.ElementExists(By.Id("table-zones"))); var externalLinks = driver.FindElements(By.XPath("//i[@class='fa fa-external-link']/..")); foreach (var externalLink in externalLinks) { var originWindow = driver.CurrentWindowHandle; var originalWindows = driver.WindowHandles; externalLink.Click(); string newWindowOpening = wait.Until <string>((d) => { string foundWindow = null; List <string> newWindows = driver.WindowHandles.Except(originalWindows).ToList(); if (newWindows.Count > 0) { foundWindow = newWindows[0]; } return(foundWindow); }); driver.SwitchTo().Window(newWindowOpening); driver.Close(); driver.SwitchTo().Window(originWindow); } }
public void TestYandexCreateAccount() { driver.Navigate().GoToUrl("http://www.yandex.ru/"); try { wait.Until(ExpectedConditions.TextToBePresentInElement(driver.FindElement(By.LinkText("Завести почту")), "Завести почту")); driver.FindElement(By.LinkText("Завести почту")).Click(); driver.FindElement(By.Name("firstname")).SendKeys("Test12345"); driver.FindElement(By.Name("lastname")).SendKeys("Test12345"); driver.FindElement(By.Name("login")).SendKeys("Test.Create"); wait.Until(ExpectedConditions.ElementIsVisible((By.ClassName("reg-field__popup")))); driver.FindElement(By.Name("password")).SendKeys("TestCreate12345"); driver.FindElement(By.Name("password_confirm")).SendKeys("TestCreate12345"); driver.FindElement(By.ClassName("registration__pseudo-link")).Click(); driver.FindElement(By.ClassName("button2")).Click(); wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("/html/body/div[3]/div"))); driver.FindElement(By.XPath("/html/body/div[3]/div/div/div[5]/span")).Click(); driver.FindElement(By.Name("hint_answer")).SendKeys("143130"); driver.FindElement(By.Name("captcha")).SendKeys(RandomString("абвгдеёжзийклмнопрстуфхйчшщъыьэюя", 5)); driver.FindElement(By.ClassName("form__submit")).Click(); wait.Until(ExpectedConditions.TextToBePresentInElement(driver.FindElement(By.ClassName("reg-field__popup")), "Вы неверно ввели символы. Попробуйте еще раз")); } catch (NoSuchElementException ex) { Assert.Fail("[Selenium] Объект не найден!" + ex.ToString()); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("[Selenium] WTF exception: " + ex.ToString()); } }
// This method is used to wait until expected condition: waits for text present in dropdown. public static IWebElement WaitForTextInSelect(IWebDriver driver, By findByCondition, int waitInSeconds, string text) { WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(waitInSeconds)); IWebElement we = driver.FindElement(findByCondition); wait.Until(ExpectedConditions.TextToBePresentInElement(we, text)); return(we); }
public void WaitUntilCartNumberOfProductsIsRefreshed(int expectedNumberOfProductsInCart) { WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); //var temp = NumberOfProductsInCartWebElement; wait.Until(ExpectedConditions.TextToBePresentInElement(GetNumperOfProduct(), expectedNumberOfProductsInCart.ToString())); RefreshNumberOfProductsInCart(); }
public static void WaitUntilTilePageIsDisplayed(string text, int timeOUT) { var titlePage = By.ClassName(text); var eleTitle = Driver.FindElement(titlePage); _wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeOUT)); _wait.Until(ExpectedConditions.TextToBePresentInElement(eleTitle, text)); }
/// <summary> /// Clicking the Pupil Record Button and then coming back to the Marksheet Template Screen just to check if the /// </summary> public MarksheetTemplateDetails NavigatetoCreateMarksheetTemplateScreen() { waiter.Until(ExpectedConditions.TextToBePresentInElement(AddNewPupilButton, "Add New Pupil")); TaskMenu.Click(); waiter.Until(ExpectedConditions.ElementToBeClickable(ManageTemplatesLink)).Click(); waiter.Until(ExpectedConditions.TextToBePresentInElement(EnterMarksheetTemplateNameLabel, "Template Name")); return(new MarksheetTemplateDetails()); }
/// <summary> /// Selects a specific Additional Column /// </summary> public void SelectAddColByName(string AddColName) { waiter.Until(ExpectedConditions.TextToBePresentInElement(ACPDoneButton, "Done")); IWebElement element = WebContext.WebDriver.FindElements(AdditionalColumnList) .FirstOrDefault(ele => ele.Text == AddColName); element.FindChild(AdditionalColumnCheckbox).Click(); }
private void WaitingProductAdd(int quantityProducts) { // Переменная с элементом счетчика добавленного в корзину товара IWebElement productBage = driver.FindElement(By.ClassName("badge")); // Ожидание обновления productBage wait.Until(ExpectedConditions.TextToBePresentInElement(productBage, quantityProducts.ToString())); }
public DropDownDemoPage AssertDropDownMessage() { GetWait().Until(ExpectedConditions.TextToBePresentInElement(_dropDownSelectMessage, _dropDownSelectMessage.Text)); Assert.AreEqual($"Day selected :- {_dropDownSelect.SelectedOption.Text}", _dropDownSelectMessage.Text); return(this); }
public void AddToCart() { int currentQuantity = Int32.Parse(quantity.Text); addButton.Click(); currentQuantity++; wait.Until(ExpectedConditions.TextToBePresentInElement(quantity, currentQuantity.ToString())); }
internal void AddToCart() { int currentCartCount = Int32.Parse(driver.FindElement(By.CssSelector("div#cart span.quantity")).Text); SelectSize(); ClickButtonByName("add_cart_product"); wait.Until(ExpectedConditions.TextToBePresentInElement(driver.FindElement(By.CssSelector("div#cart span.quantity")), (currentCartCount + 1).ToString())); }