public void GivenIHaveEnteredSomethingIntoTheSearch(int zip, int category, int subCategory) { //Navigate to the site driver.Navigate().GoToUrl(WeNeedUHaveUrls.Home); // Find the text input element by its name IWebElement query = driver.FindElement(By.Name("ZipCode")); // Enter something to search for query.SendKeys(zip.ToString()); WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(3000)); wait.Until(x => { try { SelectElement selectElement = new SelectElement(driver.AjaxFind(By.Id("Category"), 3000)); return selectElement.Options.Count>1; } catch (StaleElementReferenceException) { return false; } }); IWebElement dropDownListBox = driver.FindElement(By.Id("Category")); SelectElement clickThis = new SelectElement(dropDownListBox); clickThis.SelectByIndex(category); IWebElement dropDownListBox2 = driver.FindElement(By.Id("SubCategory")); SelectElement clickThis2 = new SelectElement(dropDownListBox2); clickThis2.SelectByIndex(subCategory); // Now submit the form query.Submit(); }
public void TestDropdown() { //Get the Dropdown as a Select using it's name attribute SelectElement make = new SelectElement(driver.FindElement(By.Name("make"))); //Verify Dropdown does not support multiple selection Assert.IsFalse(make.IsMultiple); //Verify Dropdown has four options for selection Assert.AreEqual(4, make.Options.Count); //We will verify Dropdown has expected values as listed in a array ArrayList exp_options = new ArrayList(new String [] {"BMW", "Mercedes", "Audi","Honda"}); var act_options = new ArrayList(); //Retrieve the option values from Dropdown using getOptions() method foreach(IWebElement option in make.Options) act_options.Add(option.Text); //Verify expected options array and actual options array match Assert.AreEqual(exp_options.ToArray(),act_options.ToArray()); //With Select class we can select an option in Dropdown using Visible Text make.SelectByText("Honda"); Assert.AreEqual("Honda", make.SelectedOption.Text); //or we can select an option in Dropdown using value attribute make.SelectByValue("audi"); Assert.AreEqual("Audi", make.SelectedOption.Text); //or we can select an option in Dropdown using index make.SelectByIndex(0); Assert.AreEqual("BMW", make.SelectedOption.Text); }
protected override void Execute(IWebDriver driver, IWebElement element, CommandDesc command) { var selectElement = new SelectElement(element); var lowerCommand = command.Parameter.ToLower(); if (lowerCommand.StartsWith("label=")) { selectElement.SelectByText(command.Parameter.Substring(6)); return; } if (lowerCommand.StartsWith("value=")) { selectElement.SelectByValue(command.Parameter.Substring(6)); return; } if (lowerCommand.StartsWith("index=")) { selectElement.SelectByIndex(int.Parse(command.Parameter.Substring(6))); return; } selectElement.SelectByText(command.Parameter); }
private static void AssetSelection(IWebDriver driver) { for (var n = 0; n <= 1; n++) { driver.FindElement(By.CssSelector("img.img-responsive.center-block")).Click(); driver.FindElement(By.Id("s2id_autogen1")).Click(); var groups = new SelectElement(driver.FindElement(By.Id("groups"))); groups.SelectByIndex(n); var assetType = groups.SelectedOption.Text; driver.FindElement(By.CssSelector("button.btn.gradient")).Click(); //click search //Groups dropdown IList<IWebElement> details = driver.FindElements(By.LinkText("Details")); Console.WriteLine("There are {0} {1} ", details.Count(), assetType); NavigateGroups(driver, details); // driver.FindElement(By.CssSelector("img.img-responsive.center-block")).Click(); // driver.FindElement(By.CssSelector("a.select2-search-choice-close")).Click(); //clear } //Console.ReadKey(); }
public void Step2DeliveryOptions() { var StatementDropdownSelect = new SelectElement(StatementDropdown); var TaxDropdownSelect = new SelectElement(TaxDropdown); StatementDropdownSelect.SelectByIndex(new Random().Next(1,2)); TaxDropdownSelect.SelectByIndex(new Random().Next(1, 2)); NextButton.Click(); }
public void ShouldAllowOptionsToBeSelectedByIndex() { IWebElement element = driver.FindElement(By.Name("select_empty_multiple")); SelectElement elementWrapper = new SelectElement(element); elementWrapper.SelectByIndex(1); IWebElement firstSelected = elementWrapper.AllSelectedOptions[0]; Assert.AreEqual("select_2", firstSelected.Text); }
public void Create() { var restaurantList = new SelectElement(Driver.Instance.FindElement(By.Id("RestaurantId"))); restaurantList.SelectByIndex(1); Driver.Instance.FindElement(By.Id("Body")).SendKeys("Incroybalement mauvais"); Driver.Instance.FindElement(By.Id("Rating")).SendKeys("1"); Driver.Instance.FindElement(By.Id("create_button")).Click(); }
/// <summary> /// Select Dropdown using Index /// </summary> /// <param name="element">IWebElement</param> /// <param name="indexToSelect">Index of the element to Select</param> /// <return> N/A </return> public void SelectDropDownByIndex(IWebElement element, int indexToSelect) { try { OpenQA.Selenium.Support.UI.SelectElement selectElement = new OpenQA.Selenium.Support.UI.SelectElement(element); selectElement.SelectByIndex(indexToSelect); } catch (Exception ex) { throw new ConduentUIAutomationException(ex.Message); } }
public void IFilloutAdvancedForm() { IWebElement mission = driver.FindElement(By.Id(EditOrganizationDOMElements.MissionStatementInputId)); mission.SendKeys("Sample mission"); IWebElement donation = driver.FindElement(By.Id(EditOrganizationDOMElements.DonationDescriptionInputId)); donation.SendKeys("Sample donation description"); SelectElement pickup = new SelectElement(driver.FindElement(By.Id(EditOrganizationDOMElements.PickupSelectId))); pickup.SelectByIndex(1); donation.Submit(); }
public bool selectByIndex(By locator, int index, string locatorName) { bool flag = false; try { Select s = new Select(driver.FindElement(locator)); s.SelectByIndex(index); flag = true; return(flag); } catch (Exception) { return(flag); } }
public void AddBook(string bookName, int[] bookAuthors) { AddBookButton.Click(); WaitUntil(_driver, CustomExpectedConditions.ElementIsVisible(BookNameField), TimeSpan.FromSeconds(10)); BookNameField.SendKeys(bookName); WaitUntil(_driver, CustomExpectedConditions.ElementIsVisible(SelectedAuthorsField), TimeSpan.FromSeconds(10)); SelectElement SelectedAuthorsSelect = new SelectElement(SelectedAuthorsField); foreach(int authorId in bookAuthors) SelectedAuthorsSelect.SelectByIndex(authorId); WaitUntil(_driver, CustomExpectedConditions.ElementIsVisible(SubmitBookButton), TimeSpan.FromSeconds(10)); SubmitBookButton.Click(); WaitForSuccessAjax(_driver, TimeSpan.FromSeconds(10)); WaitUntil(this._driver, CustomExpectedConditions.ElementIsNotPresent(By.ClassName("blockUI")), TimeSpan.FromSeconds(10)); }
public static void ChooseElementInList(IWebDriver driver, string name, int elementIndex) { try { WaitLoop(indice => { var selectElement = new SelectElement(driver.FindElement(By.Name(name))); selectElement.SelectByIndex(elementIndex); }); } catch (Exception ex) { var msgErro = string.Format("Erro selecionando inddice, {0} no elemento.: {1}", elementIndex, name); throw new InvalidOperationException(msgErro, ex); } }
public void incluirAnaliseManifestacao() { btnGridAnalisar.Click(); var comboboxAreaManifestacao = driver.FindElement(By.Id("dropAreaManifestacao")); var selectElementCanalAcesso = new OpenQA.Selenium.Support.UI.SelectElement(comboboxAreaManifestacao); selectElementCanalAcesso.SelectByText("AREA ADMINISTRATIVA"); var comboboxItemManifestacao = driver.FindElement(By.Id("dropTipoItemManifestacao")); var selectElementTipoDocumento = new OpenQA.Selenium.Support.UI.SelectElement(comboboxItemManifestacao); selectElementTipoDocumento.SelectByIndex(1); texto.SendKeys("Texto Andamento"); btnSalvar.Click(); }
/// <summary> /// selectの選択 /// </summary> /// <param name="driver"></param> private static void EditSelectField(IWebDriver driver) { // <select>の選択 // OpenQA.Selenium.Support.UI(NuGet: Selenium.Supportで入る)の // SelectElement()を使って選択する var element = driver.FindElement(By.Id("id_selected")); var selectElement = new OpenQA.Selenium.Support.UI.SelectElement(element); // 選択方法は3種類 // SelectByIndexは<option>のIndexに一致するもの selectElement.SelectByIndex(2); // SelectByValueは<option value="1">が一致するもの selectElement.SelectByValue("1"); // SelectByTextは<option>の値が一致するもの selectElement.SelectByText("select3"); }
public static void CheckProfilesPerIndicatorPopup(IWebDriver driver) { // Click show me which profiles these indicators are in var profilePerIndicator = driver.FindElement(By.Id(FingertipsIds.ProfilePerIndicator)); profilePerIndicator.Click(); // Wait for indicator menu to be visible in pop up var byIndicatorMenu = By.Id(FingertipsIds.ListOfIndicators); new WaitFor(driver).ExpectedElementToBeVisible(byIndicatorMenu); // Select 2nd indicator in list var listOfIndicators = driver.FindElement(byIndicatorMenu); var selectMenu = new SelectElement(listOfIndicators); selectMenu.SelectByIndex(1); // Check list of profiles is displayed var listOfProfiles = driver.FindElements(By.XPath(XPaths.ListOfProfilesInPopup)); Assert.IsTrue(listOfProfiles.Count > 0); }
public void AddNewDropdown() { SwitchToPopUps(); SelectElement se = new SelectElement(BrowserDriver.Instance.Driver.FindElement(By.Id("lookupListIdSelect"))); // se.SelectByText("Item1"); se.SelectByIndex(1); Thread.Sleep(2000); SwitchToPopUps(); new SelectElement(BrowserDriver.Instance.Driver.FindElement(By.Id("lookupListIdSelect"))).SelectByText("Admin - Locale Supported Language Codes"); Thread.Sleep(2000); // ((IJavaScriptExecutor)BrowserDriver.Instance.Driver).ExecuteScript("document.getElementById('lookupListIdSelect').selectedIndex ='2'"); javascriptClick(By.XPath(General.Default.NewB)); typeDataName("description", "ABAutomation"); Thread.Sleep(2000); javascriptClick(By.XPath(General.Default.CreateB)); // IWebElement ele = BrowserDriver.Instance.Driver.FindElement(By.XPath(General.Default.CreateB)); // ele.Click(); Thread.Sleep(2000); SwitchToPopUps(); }
public Messages.BaseResult ExecuteTest(OpenQA.Selenium.IWebDriver driverToTest, Parser.TestItem itemToTest) { BaseResult br = new BaseResult(); try { SelectElement selectList; IWebElement element; SeleniumHtmlHelper helper = new SeleniumHtmlHelper(browserDriver: driverToTest); element = helper.ElementLocator(itemToTest.Selector); selectList = new SelectElement(element); if (itemToTest.Value.StartsWith("label=")) { selectList.SelectByText(itemToTest.Value.Replace("label=", "")); } else if (itemToTest.Value.StartsWith("value=")) { selectList.SelectByValue(itemToTest.Value.Replace("value=", "")); } else if (itemToTest.Value.StartsWith("id=")) { element.FindElement(By.XPath(string.Format(@"option[@id='{0}']", itemToTest.Value.Replace("id=", "")))); } else if (itemToTest.Value.StartsWith("index=")) { int index = int.Parse(itemToTest.Value.Replace("index=", "")); selectList.SelectByIndex(index); } br.Status = true; br.Message = "OK"; } catch (Exception e) { #if DEBUG throw; #endif br.Status = false; br.Message = string.Format("Exception type: {0}. Message: {1}.", e.GetType(), e.Message); } return br; }
public void test3() { IWebElement FirmEdit = driver.FindElement(By.Id("contentPlaceHolder_txtCompanyName")); FirmEdit.Click(); FirmEdit.Clear(); FirmEdit.SendKeys(getRandomString(10, 55)); IWebElement Street1Edit = driver.FindElement(By.Id("contentPlaceHolder_locations_Location0_txtStreetAddress")); Street1Edit.Click(); Street1Edit.Clear(); Street1Edit.SendKeys(getRandomString(10, 55)); IWebElement CityEdit = driver.FindElement(By.Id("contentPlaceHolder_locations_Location0_txtCity")); CityEdit.Click(); CityEdit.Clear(); CityEdit.SendKeys(getRandomString(10, 55)); IWebElement StateEdit = driver.FindElement(By.Id("contentPlaceHolder_locations_Location0_lstState")); SelectElement selectList = new SelectElement(StateEdit); selectList.SelectByIndex(random.Next(1, 55)); IWebElement ZipEdit = driver.FindElement(By.Id("contentPlaceHolder_locations_Location0_txtZip")); ZipEdit.Click(); ZipEdit.Clear(); ZipEdit.SendKeys(getRandomString(10, 55)); String phoneToSend = getRandomString(10, 55); IWebElement PhoneEdit = driver.FindElement(By.Id("contentPlaceHolder_locations_Location0_txtPhone")); PhoneEdit.Click(); PhoneEdit.Clear(); PhoneEdit.SendKeys(phoneToSend); IWebElement NextButton = driver.FindElement(By.Id("contentPlaceHolder_btnNext")); NextButton.Click(); // Вторая страница try { wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.Id("ctl00_contentPlaceHolder_newUserInfoEditor_txtPhone"))); } catch (WebDriverTimeoutException e) { Assert.Fail("Second page was not loaded"); } IWebElement Phone2Edit = driver.FindElement(By.Id("ctl00_contentPlaceHolder_newUserInfoEditor_txtPhone")); Assert.AreEqual(phoneToSend, Phone2Edit.GetAttribute("value"), "Phones are different"); }
public void SelectIndex(Func<IElement> element, int optionIndex) { this.Act(() => { var unwrappedElement = element() as Element; SelectElement selectElement = new SelectElement(unwrappedElement.WebElement); if (selectElement.IsMultiple) selectElement.DeselectAll(); selectElement.SelectByIndex(optionIndex); }); }
public void MultiSelectIndex(Func<IElement> element, int[] optionIndices) { this.Act(() => { var unwrappedElement = element() as Element; SelectElement selectElement = new SelectElement(unwrappedElement.WebElement); if (selectElement.IsMultiple) selectElement.DeselectAll(); foreach (var optionIndex in optionIndices) { selectElement.SelectByIndex(optionIndex); } }); }
/// <summary> /// Select a dropdown by its label and return the name of the selected value. /// </summary> /// <param name="label">The label of the dropdown field.</param> /// <returns>The text of the selected option.</returns> private string RandomDropdown(string label) { var dropdown = new SelectElement(Browser.FindElement(_themes.Get("FontDropdown", label))); var count = dropdown.Options.Count; var option = _rand.Next(count - 1) + 1; dropdown.SelectByIndex(option); return dropdown.Options[option].Text; }
/// <summary> /// Select value in dropdown using index. /// </summary> /// <param name="index">Index value to be selected.</param> /// <param name="timeout">The timeout.</param> public void SelectByIndex(int index, double timeout) { timeout = timeout.Equals(0) ? BaseConfiguration.AjaxWaitingTime : timeout; var element = this.WaitUntilDropdownIsPopulated(timeout); var selectElement = new SelectElement(element); try { selectElement.SelectByIndex(index); } catch (NoSuchElementException e) { Console.WriteLine("unable to select given index: " + index); Console.WriteLine(e.Message); } }
public static void SelectElement(By locator, int index) { select = new SelectElement(GenericHelper.GetElement(locator)); select.SelectByIndex(index); }
public static IWebElement WhenISelectARandomOptionInTheElement(string cssSelector) { SelectElement selectElement = new SelectElement(CurrentDriver.GetElementFromActivePage(cssSelector)); Random rnd = new Random(Guid.NewGuid().GetHashCode()); var randomIndex = rnd.Next(selectElement.Options.Count); var randomOption = selectElement.Options[randomIndex]; selectElement.SelectByIndex(randomIndex); ScenarioContext.Current["randomOption:" + cssSelector] = randomOption; ScenarioContext.Current["randomOptionText:" + cssSelector] = randomOption.Text; return randomOption; }
public void Select(int index) { selection = new SelectElement(Self); selection.SelectByIndex(index); }
public void SelectByIndex(int index) { SelectElement element = new SelectElement(aWebElement); element.SelectByIndex(index); }
private void FillOutImportFields() { var oldWait = Browser.ImplicitWait; Browser.ImplicitWait = 5; var dropdown = new SelectElement(Browser.FindElement(_r, "residuals.import.processor")); dropdown.SelectByIndex(1); // Wil fail if there are no processors. // Browser.DropdownSelectByText(_r, "residuals.import.processor", "Vantiv") Browser.Click(_r, "residuals.import.file-date"); Thread.Sleep(2000); var days = Browser.FindElements(_r, "residuals.import.calendar-days"); days[new Random().Next(days.Count)].Click(); Browser.ImplicitWait = oldWait; }
/// <summary> /// Choose an element in IWebElement 'select'. Has 3 ways to select element (value, index, text) /// </summary> /// <param name="value"></param> /// <param name="select"></param> /// <param name="by"></param> public void ChooseElementInSelect(string value, IWebElement select, SelectBy by) { SelectElement selector = new SelectElement(select); if (by == SelectBy.Text) { selector.SelectByText(value); } if (by == SelectBy.Index) { selector.SelectByIndex(Convert.ToInt32(value)); } if (by == SelectBy.Value) { selector.SelectByValue(value); } }
/** * 下拉选择框根据索引值选择, 这是通过检查一个元素的“index”属性来完成的, 而不仅仅是通过计数 * @param locator * @param index * @see org.openqa.selenium.support.ui.Select.selectByIndex(int index) */ public static void SelectByIndex(By locator, int index) { select = new SelectElement(Driver.FindElement(locator)); select.SelectByIndex(index); }
public void Test4() { // Arrange driver.Navigate().GoToUrl("http://suvian.in/selenium/1.4gender_dropdown.html"); wait.Until(ExpectedConditions.ElementIsVisible(By.CssSelector(".intro-header .container .row .col-lg-12 .intro-message select"))); // Act IWebElement element = driver.FindElement(By.CssSelector(".intro-header .container .row .col-lg-12 .intro-message select")); SelectElement selectElement = new SelectElement(element); // Assert try { selectElement.SelectByText("Male"); // case sensitive Assert.IsNotNull(selectElement.SelectedOption); } catch (Exception e) { verificationErrors.Append(e.Message); } IWebElement option = null; try { option = selectElement.Options.First(o => o.Text.Equals("male", StringComparison.InvariantCultureIgnoreCase)); } catch (Exception e) { verificationErrors.Append(e.Message); } Assert.IsNotNull(option); selectElement.SelectByIndex(1); StringAssert.AreEqualIgnoringCase("male", selectElement.SelectedOption.Text); }
public void test4() { IWebElement FirmEdit = driver.FindElement(By.Id("contentPlaceHolder_txtCompanyName")); FirmEdit.Click(); FirmEdit.Clear(); FirmEdit.SendKeys(getRandomString(10, 55)); IWebElement Street1Edit = driver.FindElement(By.Id("contentPlaceHolder_locations_Location0_txtStreetAddress")); Street1Edit.Click(); Street1Edit.Clear(); Street1Edit.SendKeys(getRandomString(10, 55)); IWebElement CityEdit = driver.FindElement(By.Id("contentPlaceHolder_locations_Location0_txtCity")); CityEdit.Click(); CityEdit.Clear(); CityEdit.SendKeys(getRandomString(10, 55)); IWebElement StateEdit = driver.FindElement(By.Id("contentPlaceHolder_locations_Location0_lstState")); SelectElement selectList = new SelectElement(StateEdit); selectList.SelectByIndex(random.Next(1, 55)); IWebElement ZipEdit = driver.FindElement(By.Id("contentPlaceHolder_locations_Location0_txtZip")); ZipEdit.Click(); ZipEdit.Clear(); ZipEdit.SendKeys(getRandomString(10, 55)); String phoneToSend = getRandomString(10, 55); IWebElement PhoneEdit = driver.FindElement(By.Id("contentPlaceHolder_locations_Location0_txtPhone")); PhoneEdit.Click(); PhoneEdit.Clear(); PhoneEdit.SendKeys(""); // предполагаем, что пользователь забыл ввести одно из полей, так как на // на всех полях данной формы причина ошибки и сама ошибка идентичные IWebElement NextButton = driver.FindElement(By.Id("contentPlaceHolder_btnNext")); NextButton.Click(); try { bool isErrorDisplayed = driver.FindElement(By.Id("contentPlaceHolder_valSummary")).Displayed; } catch(StaleElementReferenceException) { Assert.Fail("Error was not displayed"); } PhoneEdit.Click(); PhoneEdit.SendKeys(phoneToSend); NextButton.Click(); // Вторая страница try { wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.Id("ctl00_contentPlaceHolder_btnNext"))); } catch (WebDriverTimeoutException e) { Assert.Fail("Second page was not loaded"); } // Очищаем все поля на проверку полей на ошибку отстутсвия содержания в них IWebElement FirstNameEdit = driver.FindElement(By.Id("ctl00_contentPlaceHolder_newUserInfoEditor_txtFirstName")); FirstNameEdit.Clear(); IWebElement LastNameEdit = driver.FindElement(By.Id("ctl00_contentPlaceHolder_newUserInfoEditor_txtLastName")); LastNameEdit.Clear(); IWebElement Phone2Edit = driver.FindElement(By.Id("ctl00_contentPlaceHolder_newUserInfoEditor_txtPhone")); Phone2Edit.Clear(); IWebElement EmailEdit = driver.FindElement(By.Id("ctl00_contentPlaceHolder_newUserInfoEditor_txtEmail")); EmailEdit.Clear(); IWebElement SecondEmailEdit = driver.FindElement(By.Id("ctl00_contentPlaceHolder_newUserInfoEditor_txtSecondEmail")); SecondEmailEdit.Clear(); IWebElement PasswordEdit = driver.FindElement(By.Id("ctl00_contentPlaceHolder_passwordControl_txtPassword")); PasswordEdit.Clear(); IWebElement PasswordConfirmEdit = driver.FindElement(By.Id("ctl00_contentPlaceHolder_passwordControl_txtPasswordConfirm")); PasswordConfirmEdit.Clear(); // Нажимаем на submit, ожидаем всплывающее окно с ошибкой и парсим ее, проверяя на валидность IWebElement NextButton2 = driver.FindElement(By.Id("ctl00_contentPlaceHolder_btnNext")); NextButton2.Click(); wait.Until(ExpectedConditions.AlertIsPresent()); IAlert errorWindow = driver.SwitchTo().Alert(); String errorWindowText = errorWindow.Text; bool emptyFirstNameError = errorWindowText.Contains("- Enter first name"); bool emptyLastNameError = errorWindowText.Contains("- Enter last name"); bool emptyPhoneError = errorWindowText.Contains("- Enter phone"); bool emptyEmailError = errorWindowText.Contains("- Enter email"); bool emptyConfirmEmailError = errorWindowText.Contains("- Confirm email"); bool emptyPasswordError = errorWindowText.Contains("- Enter password"); bool emptyConfirmPasswordError = errorWindowText.Contains("- Confirm password"); bool allEmptyFieldsError = emptyFirstNameError && emptyLastNameError && emptyPhoneError && emptyEmailError && emptyConfirmEmailError && emptyPasswordError && emptyConfirmPasswordError; Assert.IsTrue(allEmptyFieldsError, "Error of empty fields fails"); errorWindow.Accept(); // Можно разделить на несколько отдельных тестов, но я решил соблюсти пункты ТЗ и сделать // конкретно 4 теста, поэтому проверка на разные типы валидности ошибок в одном тесте // вводим все поля и Email не соответствующий регулярному выражению судя из данных по валидности // и проверяем на валидный вывод ошибки String firstName = ""; firstName = getRandomString(5, 16); FirstNameEdit.Click(); FirstNameEdit.Clear(); FirstNameEdit.SendKeys(firstName); String lastName = ""; lastName = getRandomString(5, 16); LastNameEdit.Click(); LastNameEdit.Clear(); LastNameEdit.SendKeys(lastName); Phone2Edit.Click(); Phone2Edit.Clear(); Phone2Edit.SendKeys(getRandomString(10, 55)); String emailToSend = ""; emailToSend += getRandomString(5, 25); // emailToSend += "@"; emailToSend += getRandomString(3, 10); // emailToSend += "."; emailToSend += getRandomString(3, 10); EmailEdit.Click(); EmailEdit.Clear(); EmailEdit.SendKeys(emailToSend); SecondEmailEdit.Click(); SecondEmailEdit.Clear(); SecondEmailEdit.SendKeys(emailToSend); String password = ""; do { password = getRandomString(10, 55); } while (password.Contains(firstName) || password.Contains(lastName) || password.Contains(emailToSend)); PasswordEdit.Click(); PasswordEdit.Clear(); PasswordEdit.SendKeys(password); PasswordConfirmEdit.Click(); PasswordConfirmEdit.Clear(); PasswordConfirmEdit.SendKeys(password); NextButton2.Click(); wait.Until(ExpectedConditions.AlertIsPresent()); IAlert errorWindow2 = driver.SwitchTo().Alert(); String errorWindow2Text = errorWindow2.Text; bool InvalidEmailError = errorWindow2Text.Contains("- Invalid email"); bool InvalidConfirmEmailError = errorWindow2Text.Contains("- Invalid email confirmation"); bool IvalidEmailFieldsError = InvalidEmailError && InvalidConfirmEmailError; Assert.IsTrue(IvalidEmailFieldsError, "Error of empty fields fails"); errorWindow.Accept(); // Email Confirmation test, проверяем ошибку связанную с неверным подтревждением email emailToSend = ""; emailToSend += getRandomString(5, 25); emailToSend += "@"; emailToSend += getRandomString(3, 10); emailToSend += "."; emailToSend += getRandomString(3, 10); EmailEdit.Click(); EmailEdit.Clear(); EmailEdit.SendKeys(emailToSend); SecondEmailEdit.Click(); SecondEmailEdit.Clear(); SecondEmailEdit.SendKeys(emailToSend+"mistake"); NextButton2.Click(); wait.Until(ExpectedConditions.AlertIsPresent()); IAlert errorWindow3 = driver.SwitchTo().Alert(); String errorWindow3Text = errorWindow3.Text; bool differentEmailsError = errorWindow3Text.Contains("- Emails are different"); Assert.IsTrue(differentEmailsError, "Error of different email confirmation fails"); errorWindow.Accept(); SecondEmailEdit.Click(); SecondEmailEdit.Clear(); SecondEmailEdit.SendKeys(emailToSend); // Проверка на валидность ошибки при вводе пароля меньше 5 символов String password2 = ""; do { password2 = getRandomString(1, 4); } while (password2.Contains(firstName) || password2.Contains(lastName) || password2.Contains(emailToSend)); PasswordEdit.Click(); PasswordEdit.Clear(); PasswordEdit.SendKeys(password2); PasswordConfirmEdit.Click(); PasswordConfirmEdit.Clear(); PasswordConfirmEdit.SendKeys(password2); NextButton2.Click(); wait.Until(ExpectedConditions.AlertIsPresent()); IAlert errorWindow4 = driver.SwitchTo().Alert(); String errorWindow4Text = errorWindow4.Text; bool shortPasswordError = errorWindow4Text.Contains("- Enter password which is of at least " + "5 characters length and doesn't contain your email or full name"); Assert.IsTrue(shortPasswordError, "Error of short password fails"); errorWindow.Accept(); // Проверка валидности ошибки на содержание текста поля First Name в пароле String password3 = ""; do { password3 += getRandomString(1, 4); password3 += firstName; password3 += getRandomString(1, 4); } while (password3.Contains(lastName) || password3.Contains(emailToSend)); PasswordEdit.Click(); PasswordEdit.Clear(); PasswordEdit.SendKeys(password3); PasswordConfirmEdit.Click(); PasswordConfirmEdit.Clear(); PasswordConfirmEdit.SendKeys(password3); NextButton2.Click(); try { wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.Id("ctl00_contentPlaceHolder_btnNext"))); } catch (WebDriverTimeoutException e) { Assert.Fail("Page was not loaded"); } IWebElement passwordError = driver.FindElement(By.Id("ctl00_contentPlaceHolder_lblPasswordError")); String errorText = passwordError.Text; if (!errorText.Equals("Select another password that meets all of the following criteria: is at least "+ "5 characters; does not contain your email or full name. Type a password which meets these " + "requirements in both text boxes.")) { Assert.Fail("Error was not displayed when the password contains First name"); } // Проверка валидности ошибки на содержание текста поля Last Name в пароле String password4 = ""; do { password4 += getRandomString(1, 4); password4 += lastName; password4 += getRandomString(1, 4); } while (password4.Contains(firstName) || password4.Contains(emailToSend)); IWebElement PasswordEdit2 = driver.FindElement(By.Id("ctl00_contentPlaceHolder_passwordControl_txtPassword")); PasswordEdit2.Click(); PasswordEdit2.Clear(); PasswordEdit2.SendKeys(password4); IWebElement PasswordConfirmEdit2 = driver.FindElement(By.Id("ctl00_contentPlaceHolder_passwordControl_txtPasswordConfirm")); PasswordConfirmEdit2.Click(); PasswordConfirmEdit2.Clear(); PasswordConfirmEdit2.SendKeys(password4); IWebElement NextButton3 = driver.FindElement(By.Id("ctl00_contentPlaceHolder_btnNext")); NextButton3.Click(); try { wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.Id("ctl00_contentPlaceHolder_btnNext"))); } catch (WebDriverTimeoutException e) { Assert.Fail("Page was not loaded"); } IWebElement passwordError2 = driver.FindElement(By.Id("ctl00_contentPlaceHolder_lblPasswordError")); String errorText2 = passwordError2.Text; if (!errorText.Equals("Select another password that meets all of the following criteria: is at least " + "5 characters; does not contain your email or full name. Type a password which meets these " + "requirements in both text boxes.")) { Assert.Fail("Error was not displayed when the password contains Last name"); } // Проверка валидности ошибки на содержание текста поля Email в пароле String password5 = ""; do { password5 += getRandomString(1, 4); password5 += emailToSend; password5 += getRandomString(1, 4); } while (password5.Contains(firstName) || password5.Contains(lastName)); IWebElement PasswordEdit3 = driver.FindElement(By.Id("ctl00_contentPlaceHolder_passwordControl_txtPassword")); PasswordEdit3.Click(); PasswordEdit3.Clear(); PasswordEdit3.SendKeys(password5); IWebElement PasswordConfirmEdit3 = driver.FindElement(By.Id("ctl00_contentPlaceHolder_passwordControl_txtPasswordConfirm")); PasswordConfirmEdit3.Click(); PasswordConfirmEdit3.Clear(); PasswordConfirmEdit3.SendKeys(password5); IWebElement NextButton4 = driver.FindElement(By.Id("ctl00_contentPlaceHolder_btnNext")); NextButton4.Click(); try { wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.Id("ctl00_contentPlaceHolder_btnNext"))); } catch (WebDriverTimeoutException e) { Assert.Fail("Page was not loaded"); } IWebElement passwordError3 = driver.FindElement(By.Id("ctl00_contentPlaceHolder_lblPasswordError")); String errorText3 = passwordError3.Text; if (!errorText.Equals("Select another password that meets all of the following criteria: is at least " + "5 characters; does not contain your email or full name. Type a password which meets these " + "requirements in both text boxes.")) { Assert.Fail("Error was not displayed when the password contains Email"); } }
public int Execute() { try { var working_driver = VariableStorage.WebDriverVar[webDriverInstanceVar].Item2 as IWebDriver; System.Uri input_uri = new Uri(selenium_url); string input_uriWithoutScheme = input_uri.Host.Replace("www.", "") + input_uri.PathAndQuery + input_uri.Fragment; System.Uri base_uri = new Uri(working_driver.Url); string Base_uriWithoutScheme = base_uri.Host.Replace("www.", "") + base_uri.PathAndQuery + base_uri.Fragment; if (Base_uriWithoutScheme == input_uriWithoutScheme) { IList <string> tabs = new List <string>(working_driver.WindowHandles); working_driver.SwitchTo().Window(tabs[0]); } else { working_driver.Navigate().GoToUrl(selenium_url); } //var dropdown = WebDriverGenerator.working_driver.FindElement(By.Id(SetDropDownList_HtmlElemtnInfo_list[i].Html_element_idv)); IWebElement element; for (int i = 0; i < SetDropDownList_HtmlElemtnInfo_list.Count; i++) { if (!string.IsNullOrEmpty(SetDropDownList_HtmlElemtnInfo_list[i].Html_element_id)) { element = working_driver.FindElement(By.Id(SetDropDownList_HtmlElemtnInfo_list[i].Html_element_id)); } else if (!string.IsNullOrEmpty(SetDropDownList_HtmlElemtnInfo_list[i].Html_element_XPATH)) { element = working_driver.FindElement(By.XPath(SetDropDownList_HtmlElemtnInfo_list[i].Html_element_XPATH)); } else { element = working_driver.FindElement(By.Name(SetDropDownList_HtmlElemtnInfo_list[i].Html_element_name)); } //element.SendKeys(ClickOnWebPage_HtmlElemtnInfo_list[i].Html_element_input_text); var selectElement = new OpenQA.Selenium.Support.UI.SelectElement(element); selectElement.SelectByIndex(SetDropDownList_HtmlElemtnInfo_list[i].Html_drop_down_index); //element.Click(); } //driver.Quit(); // driver.FindElement(By.Id(selenium_id)).SendKeys(Keys.Enter); return(1); } catch (Exception) { return(0); } throw new NotImplementedException(); }
public void test1() { IWebElement FirmEdit = driver.FindElement(By.Id("contentPlaceHolder_txtCompanyName")); FirmEdit.Click(); FirmEdit.Clear(); FirmEdit.SendKeys(getRandomString(10, 55)); /* IWebElement WebSiteEdit = driver.FindElement(By.Id("contentPlaceHolder_txtWebSite")); WebSiteEdit.Click(); WebSiteEdit.Clear(); WebSiteEdit.SendKeys(getRandomString(10,55)); */ /* IWebElement NameEdit = driver.FindElement(By.Id("contentPlaceHolder_locations_Location0_txtName")); NameEdit.Click(); NameEdit.Clear(); NameEdit.SendKeys(getRandomString(10,55)); */ IWebElement Street1Edit = driver.FindElement(By.Id("contentPlaceHolder_locations_Location0_txtStreetAddress")); Street1Edit.Click(); Street1Edit.Clear(); Street1Edit.SendKeys(getRandomString(10, 55)); /* IWebElement Street2Edit = driver.FindElement(By.Id("contentPlaceHolder_locations_Location0_txtStreetAddress2")); FirmEdit.Click(); FirmEdit.Clear(); FirmEdit.SendKeys(getRandomString(10,55));*/ IWebElement CityEdit = driver.FindElement(By.Id("contentPlaceHolder_locations_Location0_txtCity")); CityEdit.Click(); CityEdit.Clear(); CityEdit.SendKeys(getRandomString(10,55)); IWebElement StateEdit = driver.FindElement(By.Id("contentPlaceHolder_locations_Location0_lstState")); SelectElement selectList = new SelectElement(StateEdit); selectList.SelectByIndex(random.Next(1, 55)); IWebElement ZipEdit = driver.FindElement(By.Id("contentPlaceHolder_locations_Location0_txtZip")); ZipEdit.Click(); ZipEdit.Clear(); ZipEdit.SendKeys(getRandomString(10, 55)); IWebElement PhoneEdit = driver.FindElement(By.Id("contentPlaceHolder_locations_Location0_txtPhone")); PhoneEdit.Click(); PhoneEdit.Clear(); PhoneEdit.SendKeys(getRandomString(10, 55)); /* IWebElement FaxEdit = driver.FindElement(By.Id("contentPlaceHolder_locations_Location0_txtFax")); FaxEdit.Click(); FaxEdit.Clear(); FaxEdit.SendKeys(getRandomString(10, 55)); */ IWebElement NextButton = driver.FindElement(By.Id("contentPlaceHolder_btnNext")); NextButton.Click(); // Вторая страница try { wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.Id("ctl00_contentPlaceHolder_newUserInfoEditor_txtFirstName"))); } catch (WebDriverTimeoutException e) { Assert.Fail("Second page was not loaded"); } String firstName = ""; firstName = getRandomString(5, 16); IWebElement FirstNameEdit = driver.FindElement(By.Id("ctl00_contentPlaceHolder_newUserInfoEditor_txtFirstName")); FirstNameEdit.Click(); FirstNameEdit.Clear(); FirstNameEdit.SendKeys(firstName); String lastName = ""; lastName = getRandomString(5, 16); IWebElement LastNameEdit = driver.FindElement(By.Id("ctl00_contentPlaceHolder_newUserInfoEditor_txtLastName")); LastNameEdit.Click(); LastNameEdit.Clear(); LastNameEdit.SendKeys(lastName); IWebElement Phone2Edit = driver.FindElement(By.Id("ctl00_contentPlaceHolder_newUserInfoEditor_txtPhone")); Phone2Edit.Click(); Phone2Edit.Clear(); Phone2Edit.SendKeys(getRandomString(10, 55)); String emailToSend = ""; emailToSend += getRandomString(5, 25); emailToSend += "@"; emailToSend += getRandomString(3, 10); emailToSend += "."; emailToSend += getRandomString(3, 10); IWebElement EmailEdit = driver.FindElement(By.Id("ctl00_contentPlaceHolder_newUserInfoEditor_txtEmail")); EmailEdit.Click(); EmailEdit.Clear(); EmailEdit.SendKeys(emailToSend); IWebElement SecondEmailEdit = driver.FindElement(By.Id("ctl00_contentPlaceHolder_newUserInfoEditor_txtSecondEmail")); SecondEmailEdit.Click(); SecondEmailEdit.Clear(); SecondEmailEdit.SendKeys(emailToSend); String password = ""; do { password = getRandomString(10, 55); } while (password.Contains(firstName) || password.Contains(lastName) || password.Contains(emailToSend)); IWebElement PasswordEdit = driver.FindElement(By.Id("ctl00_contentPlaceHolder_passwordControl_txtPassword")); PasswordEdit.Click(); PasswordEdit.Clear(); PasswordEdit.SendKeys(password); IWebElement PasswordConfirmEdit = driver.FindElement(By.Id("ctl00_contentPlaceHolder_passwordControl_txtPasswordConfirm")); PasswordConfirmEdit.Click(); PasswordConfirmEdit.Clear(); PasswordConfirmEdit.SendKeys(password); IWebElement NextButton2 = driver.FindElement(By.Id("ctl00_contentPlaceHolder_btnNext")); NextButton2.Click(); try { wait.Until(ExpectedConditions.AlertIsPresent()); Assert.Fail("alert appears with error message"); } catch (WebDriverTimeoutException e) { // все хорошо, всплывающего окна об ошибке нету } }
public void ShouldThrowExceptionOnSelectByIndexIfOptionDoesNotExist() { IWebElement element = driver.FindElement(By.Name("select_empty_multiple")); SelectElement elementWrapper = new SelectElement(element); elementWrapper.SelectByIndex(10); }
/// <summary> /// Select value in dropdown using index. /// </summary> /// <param name="index">Index value to be selected.</param> /// <param name="timeout">The timeout.</param> public void SelectByIndex(int index, double timeout) { timeout = timeout.Equals(0) ? BaseConfiguration.MediumTimeout : timeout; var element = this.WaitUntilDropdownIsPopulated(timeout); var selectElement = new SelectElement(element); try { selectElement.SelectByIndex(index); } catch (NoSuchElementException e) { Logger.Error(CultureInfo.CurrentCulture, "unable to select given index: {0}", index); Logger.Error(e.Message); } }
public void EditBook(int bookId, string bookNewName, int[] bookNewAuthors) { _driver.FindElement(By.CssSelector(String.Format("#btnEditBook[data-bookid='{0}']", bookId))).Click(); WaitUntil(_driver, CustomExpectedConditions.ElementIsVisible(BookNameField), TimeSpan.FromSeconds(10)); BookNameField.Clear(); BookNameField.SendKeys(bookNewName); WaitUntil(_driver, CustomExpectedConditions.ElementIsVisible(SelectedAuthorsField), TimeSpan.FromSeconds(10)); SelectElement SelectedAuthorsSelect = new SelectElement(SelectedAuthorsField); foreach (int authorId in bookNewAuthors) SelectedAuthorsSelect.SelectByIndex(authorId); WaitUntil(_driver, CustomExpectedConditions.ElementIsVisible(SubmitBookButton), TimeSpan.FromSeconds(10)); SubmitBookButton.Click(); WaitForSuccessAjax(_driver, TimeSpan.FromSeconds(10)); WaitUntil(this._driver, CustomExpectedConditions.ElementIsNotPresent(By.ClassName("blockUI")), TimeSpan.FromSeconds(10)); }