@Override public WebElement randomSelect(Element ele) { Select select = createSelect(ele); if(select != null) { List<WebElement> options = select.getOptions(); if(CollectionUtils.isNotEmpty(options)) { int count = options.size(); int index = RandomUtils.nextInt(count); index = (index == 0 ? 1 : index); //通常第一个选项都是无效的选项 select.selectByIndex(index); return options.get(index); } } return null; }
/** * Update the specified element with the indicated value * * @param element target element (input, select) * @param value desired value * @return 'true' if element value changed; otherwise 'false' */ public static boolean updateValue(WebElement element, String value) { Objects.requireNonNull(element, "[element] must be non-null"); String tagName = element.getTagName().toLowerCase(); if ("input".equals(tagName)) { if ("checkbox".equals(element.getAttribute("type"))) { return updateValue(element, Boolean.parseBoolean(value)); } else if (!valueEquals(element, value)) { if (value == null) { element.clear(); } else { WebDriverUtils.getExecutor(element).executeScript("arguments[0].select();", element); element.sendKeys(value); } return true; } } else if ("select".equals(tagName) && !valueEquals(element, value)) { new Select(element).selectByValue(value); return true; } return false; }
public static void SelectByVisibleText_BootStrap( WebDriver driver, By elementById, String visibleOptionText ) { try { String elementId = elementById.toString().split( ":" )[ 1 ].trim(); String js = String.format( "document.getElementById('%s').removeAttribute('class');", elementId ); ( ( JavascriptExecutor ) driver ).executeScript( js ); //( ( JavascriptExecutor ) driver ).executeScript( String.format( "document.getElementById('%s').style.display='block';", elementId ) ); String cssSelector = String.format( "select#%s", elementId ); Select selectObject = new Select( driver.findElement( By.cssSelector( cssSelector ) ) ); selectObject.selectByVisibleText( visibleOptionText ); } catch( Exception e ) { throw new WebDriverException("Some error occured while Selecting option", e); } }
@Override public void etreSelectionne(String type, String selector, String valeur) { WebElement elem = this.findElement(BySelec.get(type, selector)); String tagName = elem.getTagName(); if (tagName.equals("select")) { Select listProfile = new Select(elem); if (!listProfile.getFirstSelectedOption().getText().equals(valeur)) { Assert.fail("la valeur de l'élément ne correspond pas à la valeur " + valeur + "!"); } } else { WebElement item = elem.findElement(By.cssSelector("li > div > div:first-child()")); if (!item.getText().equals(valeur)) { Assert.fail("la valeur de l'élément ne correspond pas à la valeur " + valeur + "!"); } } }
/** * select a value * * @param value the value to select */ @Override @PublicAtsApi public void setValue( String value ) { new RealHtmlElementState(this).waitToBecomeExisting(); try { WebElement element = RealHtmlElementLocator.findElement(this); Select select = new Select(element); select.selectByVisibleText(value); } catch (NoSuchElementException nsee) { throw new SeleniumOperationException("Option with label '" + value + "' not found. (" + this.toString() + ")"); } UiEngineUtilities.sleep(); }
/** * unselect a value * * @param value the value to unselect */ @Override @PublicAtsApi public void unsetValue( String value ) { new RealHtmlElementState(this).waitToBecomeExisting(); WebElement element = RealHtmlElementLocator.findElement(this); Select select = new Select(element); // select.deselectByVisibleText( value ); // this method doesn't throw an exception if the option doesn't exist for (WebElement option : select.getOptions()) { if (option.getText().equals(value)) { if (option.isSelected()) { option.click(); UiEngineUtilities.sleep(); } return; } } throw new SeleniumOperationException("Option with label '" + value + "' not found. (" + this.toString() + ")"); }
/** * @return the selected values */ @Override @PublicAtsApi public String[] getValues() { new RealHtmlElementState(this).waitToBecomeExisting(); WebElement element = RealHtmlElementLocator.findElement(this); Select select = new Select(element); List<WebElement> selectedOptions = select.getAllSelectedOptions(); String[] result = new String[selectedOptions.size()]; int i = 0; for (WebElement selectedOption : selectedOptions) { result[i++] = selectedOption.getText(); } return result; }
/** * set the single selection value * * @param value the value to select */ @Override @PublicAtsApi public void setValue( String value ) { new RealHtmlElementState(this).waitToBecomeExisting(); try { WebElement element = RealHtmlElementLocator.findElement(this); Select select = new Select(element); select.selectByVisibleText(value); } catch (NoSuchElementException nsee) { throw new SeleniumOperationException("Option with label '" + value + "' not found. (" + this.toString() + ")"); } UiEngineUtilities.sleep(); }
/** * @return a list with all possible selection values */ @Override @PublicAtsApi public List<String> getAllPossibleValues() { List<String> values = new ArrayList<String>(); new RealHtmlElementState(this).waitToBecomeExisting(); WebElement element = RealHtmlElementLocator.findElement(this); Select select = new Select(element); Iterator<WebElement> iterator = select.getOptions().iterator(); if (!select.getAllSelectedOptions().isEmpty()) { while (iterator.hasNext()) { values.add(iterator.next().getText()); } return values; } throw new SeleniumOperationException("There is no selectable 'option' in " + this.toString()); }
public HomePageObject createEvent(String title, String country, String location, String description){ setText("createEventForm:title",title); setText("createEventForm:location",location); setText("createEventForm:description",description); new Select(driver.findElement(By.id("createEventForm:country"))).selectByVisibleText(country); driver.findElement(By.id("createEventForm:createButton")).click(); waitForPageToLoad(); if(isOnPage()){ return null; } else { return new HomePageObject(driver); } }
public HomePageObject createUser(String userId, String password, String confirmPassword, String firstName, String middleName, String lastName, String country){ setText("createUserForm:userName",userId); setText("createUserForm:password",password); setText("createUserForm:confirmPassword",confirmPassword); setText("createUserForm:firstName",firstName); setText("createUserForm:middleName",middleName); setText("createUserForm:lastName",lastName); try { new Select(driver.findElement(By.id("createUserForm:country"))).selectByVisibleText(country); } catch (Exception e){ return null; } driver.findElement(By.id("createUserForm:createButton")).click(); waitForPageToLoad(); if(isOnPage()){ return null; } else { return new HomePageObject(driver); } }
private void doCreditCardPaymentOnPaymentPanel(Payment response) { RemoteWebDriver driver = openFirefoxAtUrl(response.getRedirectLocation()); driver.findElement(By.name("selCC|VISA")).click(); WebDriverWait wait = new WebDriverWait(driver, 20); wait.until(ExpectedConditions.elementToBeClickable(By.id("cardnumber"))); driver.findElement(By.id("cardnumber")).sendKeys("4444333322221111"); driver.findElement(By.id("cvc")).sendKeys("123"); (new Select(driver.findElement(By.id("expiry-month")))).selectByValue("05"); (new Select(driver.findElement(By.id("expiry-year")))).selectByValue(getYear()); driver.findElement(By.name("profile_id")).sendKeys("x"); driver.findElement(By.id("right")).click(); wait.until(ExpectedConditions.elementToBeClickable(By.id("right"))); driver.findElement(By.id("right")).click(); }
/** * Select option by option text. * * @param locator * - element locator * @param replacement * - if element contains dynamic part, i.e. '$value' in locator * part, then '$value' part will be replaced by replacement value * @param optionText * - dropdown option text * @throws PropertyNotFoundException * - throw this exception when declared locator is not found in * object repository * @throws InvalidLocatorStrategyException * - throw this exception when locator strategy is wrong. Valid * locator strategies are 'ID', 'XPATH', 'NAME', 'CSS_SELECTOR', * 'CLASS_NAME', 'LINK_TEXT', 'PARTIAL_LINK_TEXT' and 'TAG_NAME' */ public void selectOptionByText(String locator, String replacement, String optionText) throws PropertyNotFoundException, InvalidLocatorStrategyException { if (replacement != null) { if (locator.contains("$value")) { locator = locator.replace("$value", replacement); } } element = ElementFinder.findElement(driver, locator); Select dropdown = new Select(element); dropdown.selectByVisibleText(optionText); LOGGER.info("Successfully selected option '" + optionText + "' from element '" + locator + "' with locator value '" + props.getProperty(locator) + "'"); }
/** * Select option by option index. * * @param locator * - element locator * @param replacement * - if element contains dynamic part, i.e. '$value' in locator * part, then '$value' part will be replaced by replacement value * @param optionIndex * - index of dropdown option * @throws PropertyNotFoundException * - throw this exception when declared locator is not found in * object repository * @throws InvalidLocatorStrategyException * - throw this exception when locator strategy is wrong. Valid * locator strategies are 'ID', 'XPATH', 'NAME', 'CSS_SELECTOR', * 'CLASS_NAME', 'LINK_TEXT', 'PARTIAL_LINK_TEXT' and 'TAG_NAME' */ public void selectOptionByIndex(String locator, String replacement, int optionIndex) throws PropertyNotFoundException, InvalidLocatorStrategyException { if (replacement != null) { if (locator.contains("$value")) { locator = locator.replace("$value", replacement); } } element = ElementFinder.findElement(driver, locator); Select dropdown = new Select(element); dropdown.selectByIndex(optionIndex); LOGGER.info("Successfully selected option with index " + optionIndex + "' from element '" + locator + "' with locator value '" + props.getProperty(locator) + "'"); }
@Override public String createOidcBearerClient(String clientName) { try { // .../auth/admin/master/console/#/create/client/foobar driver.navigate().to(authUrl + "/admin/master/console/#/create/client/" + realm + "/"); DriverUtil.waitFor(driver, By.id("clientId")); driver.findElement(By.id("clientId")).sendKeys(clientName); driver.findElement(By.xpath("//button[contains(text(),'Save')]")).click(); DriverUtil.waitFor(driver, By.id("accessType")); Select accessTypeSelect = new Select(driver.findElement(By.id("accessType"))); accessTypeSelect.selectByVisibleText(OpenIdAccessType.BEARER_ONLY.getLabel()); String clientId = driver.getCurrentUrl(); int lastSlash = clientId.lastIndexOf("/"); clientId = clientId.substring(lastSlash + 1); driver.findElement(By.xpath("//button[contains(text(),'Save')]")).click(); return clientId; } catch (InterruptedException | TimeoutException e) { throw new IllegalStateException("Failed to ...", e); } }
@Action(object = ObjectType.SELENIUM, desc = "Assert if the select list [<Object>] contains [<Data>]", input = InputType.YES) public void assertSelectContains() { if (elementPresent()) { Boolean isPresent = false; Select select = new Select(Element); for (WebElement option : select.getOptions()) { if (option.getText().trim().equals(Data)) { isPresent = true; break; } } if (isPresent) { Report.updateTestLog(Action, ObjectName + " Contains the Option " + Data, Status.DONE); } else { Report.updateTestLog(Action, ObjectName + " doesn't Contains the Option " + Data, Status.DEBUG); } } else { throw new ElementException(ElementException.ExceptionType.Element_Not_Found, ObjectName); } }
@Override public boolean selectByText(Element element, String text) { Select select = createSelect(element); if(select != null) { select.selectByVisibleText(text); return true; } return false; }
@Override public boolean selectByValue(Element element, String value) { Select select = createSelect(element); if(select != null) { select.selectByValue(value); return true; } return false; }
@Override public boolean selectByIndex(Element element, int index) { Select select = createSelect(element); if(select != null) { select.selectByIndex(index); return true; } return false; }
@Override public boolean deselectByText(Element element, String text) { Select select = createSelect(element); if(select != null) { select.deselectByVisibleText(text); return true; } return false; }
@Override public boolean deselectByValue(Element element, String value) { Select select = createSelect(element); if(select != null) { select.deselectByValue(value); return true; } return false; }
@Override public boolean deselectByIndex(Element element, int index) { Select select = createSelect(element); if(select != null) { select.deselectByIndex(index); return true; } return false; }
@Override public boolean deselectAll(Element element) { Select select = createSelect(element); if(select != null) { select.deselectAll(); return true; } return false; }
@Override public boolean isMultiple(Element element) { Select select = createSelect(element); if(select != null) { return select.isMultiple(); } return false; }
/** * 转化为Selenium支持的下拉列表对象 * @param element * @return */ private Select createSelect(Element element) { WebElement webEle = searchStrategyUtils.findStrategy(WebElement.class, element).search(element); if (webEle != null) { return new Select(webEle); } return null; }
@Override public boolean clickDropdownOptionAndIndex(WebElement w, String... args) throws Exception{ boolean result = false; String d = args[0]; try{ Select s = new Select(w); s.selectByIndex(Integer.parseInt(d) - 1); result = true; }catch(Exception e){ e.printStackTrace(); result = false; } Assert.assertTrue(result, w.toString() + " - select drop down item with index = " + d); return result; }
public void fillUnit1Form(Unit1Data unit1Data, boolean creation) { type(By.name("text_field"), unit1Data.getTextField()); type(By.name("big_text_field"), unit1Data.getBigTextField()); attach(By.name("photo"), unit1Data.getPhoto()); if (creation) { if (unit1Data.getUnits2().size() > 0) { Assert.assertTrue(unit1Data.getUnits2().size() == 1); new Select(driver.findElement(By.name("new_unit2"))) .selectByVisibleText(unit1Data.getUnits2().iterator().next().getTextField()); } } else { Assert.assertFalse(isElementPresent(By.name("new_unit2"))); } }
public List<String> getSelectedOptions(String locator) { List<String> optionValues = new ArrayList<String>(); Select menuList = getSelectObject(locator); List<WebElement> options = menuList.getAllSelectedOptions(); for (WebElement option : options) { optionValues.add(option.getText()); } return optionValues; }
public List<String> getAllListOptions(String locator) { List<String> optionValues = new ArrayList<String>(); Select menuList = getSelectObject(locator); List<WebElement> options = menuList.getOptions(); for (WebElement option : options) { optionValues.add(option.getText()); } return optionValues; }
private void setDropDownValue(PageElement element, String text) throws TechnicalException, FailureException { WebElement select = Context.waitUntil(ExpectedConditions.elementToBeClickable(Utilities.getLocator(element))); Select dropDown = new Select(select); int index = NameUtilities.findOptionByIgnoreCaseText(text, dropDown); if (index != -1) { dropDown.selectByIndex(index); } else { new Result.Failure<>(text, Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_VALUE_NOT_AVAILABLE_IN_THE_LIST), element, element.getPage().getApplication()), false, element.getPage().getCallBack()); } }
public static int findOptionByIgnoreCaseText(String text, Select dropDown) { int index = 0; for (WebElement option : dropDown.getOptions()) { if (comparingNames(text, option.getText())) { return index; } index++; } return -1; }
/** * @return the single selection value */ @Override @PublicAtsApi public String getValue() { new RealHtmlElementState(this).waitToBecomeExisting(); WebElement element = RealHtmlElementLocator.findElement(this); Select select = new Select(element); if (!select.getAllSelectedOptions().isEmpty()) { return select.getFirstSelectedOption().getText(); } throw new SeleniumOperationException("There is no selected 'option' in " + this.toString()); }
/** * Selects the specified option in the (dropdown/multi-select) field. * @param optionText The text of the option to select * @param label The field label */ public void selectOptionInField(String optionText, String label) { // find the input associated with the specified label... WebElement labelElement = webDriver.findElement(By.xpath("//label[contains(text(),'" + label + "')]")); Select selectElement = new Select(webDriver.findElement(By.id(labelElement.getAttribute("for")))); selectElement.selectByVisibleText(optionText); }
public void populatePublication(Publication publication) { populateDocumentTitle(publication.getTitle()); populateDocumentSummary(publication.getSummary()); getPubliclyAccessibleWidget().select(publication.isPubliclyAccessible()); populateDocumentNominalDate(publication.getNominalPublicationDate().asInstant()); GeographicCoverage geographicCoverage = publication.getGeographicCoverage(); if (geographicCoverage != null) { new Select(helper.findElement( By.xpath(XpathSelectors.EDITOR_BODY + "//span[text()='Geographic Coverage']/../following-sibling::div//select[@class='dropdown-plugin']") )).selectByVisibleText( geographicCoverage.getDisplayValue() ); } InformationType informationType = publication.getInformationType(); if (informationType != null) { getInformationTypeSection().addInformationTypeField(); new Select(helper.findElement( By.xpath(XpathSelectors.EDITOR_BODY + "//span[text()='Information Type']/../following-sibling::div//select[@class='dropdown-plugin']") )).selectByVisibleText( informationType.getDisplayName() ); } Granularity granularity = publication.getGranularity(); if (granularity != null) { getGranularitySection().addGranularityField(); getGranularitySection().populateGranularityField(granularity); } populateTaxonomy(publication); getAttachmentsWidget().uploadAttachments(publication.getAttachments()); }
@Override public void run() { super.run(); By locator = this.readLocatorArgument("locator"); String optionValue = this.readStringArgument("optionValue", null); String optionText = this.readStringArgument("optionText", null); Integer optionNumber = this.readIntArgument("optionNumber", null); this.waitForAsyncCallsToFinish(); Select dropdownElement = new Select(this.getElement(locator)); if (optionValue != null) { dropdownElement.selectByValue(optionValue); } else if (optionText != null) { dropdownElement.selectByVisibleText(optionText); } else if (optionNumber != null) { dropdownElement.selectByIndex(optionNumber - 1); } else { throw new RuntimeException( "You must identify the option you want to select from the " + "list by providing one of the following arguments: " + "optionValue, optionText or optionIndex."); } }
@Override public void run() { super.run(); By locator = this.readLocatorArgument("locator"); String optionValue = this.readStringArgument("optionValue", null); String optionText = this.readStringArgument("optionText", null); Integer optionNumber = this.readIntArgument("optionNumber", null); this.waitForAsyncCallsToFinish(); Select dropdownElement = new Select(this.getElement(locator)); if (optionValue != null) { dropdownElement.deselectByValue(optionValue); } else if (optionText != null) { dropdownElement.deselectByVisibleText(optionText); } else if (optionNumber != null) { dropdownElement.deselectByIndex(optionNumber - 1); } else { throw new RuntimeException( "You must identify the option you want to deselect from the " + "list by providing one of the following arguments: " + "optionValue, optionText or optionIndex."); } }
@Override public String createOicdConfidentialClient(String clientName, String rootUrl, List<String> redirectUri, String baseUrl, String adminUrl) { try { // .../auth/admin/master/console/#/create/client/foobar driver.navigate().to(authUrl + "/admin/master/console/#/create/client/" + realm + "/"); DriverUtil.waitFor(driver, By.id("clientId"), By.id("rootUrl")); driver.findElement(By.id("clientId")).sendKeys(clientName); driver.findElement(By.id("rootUrl")).sendKeys(rootUrl); driver.findElement(By.xpath("//button[contains(text(),'Save')]")).click(); DriverUtil.waitFor(driver, By.id("accessType")); Select accessTypeSelect = new Select(driver.findElement(By.id("accessType"))); accessTypeSelect.selectByVisibleText(OpenIdAccessType.CONFIDENTIAL.getLabel()); DriverUtil.waitFor(driver, By.id("newRedirectUri"), By.id("rootUrl")); driver.findElement(By.id("newRedirectUri")).sendKeys(redirectUri.get(0)); driver.findElement(By.id("baseUrl")).sendKeys(baseUrl); driver.findElement(By.id("adminUrl")).sendKeys(adminUrl); String clientId = driver.getCurrentUrl(); int lastSlash = clientId.lastIndexOf("/"); clientId = clientId.substring(lastSlash + 1); driver.findElement(By.xpath("//button[contains(text(),'Save')]")).click(); return clientId; } catch (InterruptedException | TimeoutException e) { throw new IllegalStateException("Failed to ...", e); } }
@Override public String createInsecureSamlClient(String clientName, String masterSamlUrl, String baseUrl, List<String> redirectUris) { try { driver.navigate().to(authUrl + "/admin/master/console/#/create/client/" + realm + "/"); DriverUtil.waitFor(driver, By.id("clientId")); driver.findElement(By.id("clientId")).sendKeys(clientName); Select accessTypeSelect = new Select(driver.findElement(By.id("protocol"))); accessTypeSelect.selectByVisibleText(ProtocolType.SAML.getLabel()); driver.findElement(By.id("masterSamlUrl")).sendKeys(masterSamlUrl); driver.findElement(By.xpath("//button[contains(text(),'Save')]")).click(); DriverUtil.waitFor(driver, By.id("baseUrl"), By.id("newRedirectUri")); driver.findElement(By.xpath("//label[@for='samlServerSignature']/span/span[contains(@class, 'onoffswitch-active')]")).click(); driver.findElement(By.xpath("//label[@for='samlClientSignature']/span/span[contains(@class, 'onoffswitch-active')]")).click(); driver.findElement(By.id("baseUrl")).sendKeys(baseUrl); driver.findElement(By.xpath("//button[contains(text(),'Save')]")).click(); for (String redirectUri : redirectUris) { DriverUtil.waitFor(driver, By.id("newRedirectUri")); driver.findElement(By.id("newRedirectUri")).sendKeys(redirectUri); driver.findElement(By.xpath("//button[contains(text(),'Save')]")).click(); } String clientUuid = driver.getCurrentUrl(); int lastSlash = clientUuid.lastIndexOf("/"); return clientUuid.substring(lastSlash + 1); } catch (InterruptedException | TimeoutException e) { throw new IllegalStateException("Failed to create saml client"); } }