下面列出了怎么用org.openqa.selenium.remote.RemoteWebElement的API类实例代码及写法,或者点击链接到github查看源代码。
private void fixLocator(SearchContext context, String cssLocator, WebElement element) {
if (element instanceof RemoteWebElement) {
try {
@SuppressWarnings("rawtypes")
Class[] parameterTypes = new Class[] { SearchContext.class,
String.class, String.class };
Method m = element.getClass().getDeclaredMethod(
"setFoundBy", parameterTypes);
m.setAccessible(true);
Object[] parameters = new Object[] { context, "cssSelector", cssLocator };
m.invoke(element, parameters);
} catch (Exception fail) {
//fail("Something bad happened when fixing locator");
}
}
}
@Test
public void testHomeActions() {
WebDriverWait wait = new WebDriverWait(driver, 10);
// press home button twice to make sure we are on the page with reminders
ImmutableMap<String, String> pressHome = ImmutableMap.of("name", "home");
driver.executeScript("mobile: pressButton", pressHome);
driver.executeScript("mobile: pressButton", pressHome);
// find the reminders icon and long-press it
WebElement homeIcon = wait.until(ExpectedConditions.presenceOfElementLocated(REMINDER_ICON));
driver.executeScript("mobile: touchAndHold", ImmutableMap.of(
"element", ((RemoteWebElement)homeIcon).getId(),
"duration", 2.0
));
// now find the home action using the appropriate accessibility id
wait.until(ExpectedConditions.presenceOfElementLocated(ADD_REMINDER)).click();
// prove we opened up the reminders app to the view where we can add a reminder
wait.until(ExpectedConditions.presenceOfElementLocated(LISTS));
}
public void findElementGetsTheSameElementBetweenWindowCalls() throws Throwable {
driver = new JavaDriver();
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
WebElement element1 = driver.findElement(By.name("click-me"));
String id1 = ((RemoteWebElement) element1).getId();
driver.switchTo().window(titleOfWindow);
WebElement element2 = driver.findElement(By.name("click-me"));
String id2 = ((RemoteWebElement) element2).getId();
AssertJUnit.assertEquals(id1, id2);
}
public void getLocationInView() throws Throwable {
driver = new JavaDriver();
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
WebElement element1 = driver.findElement(By.name("click-me"));
try {
((RemoteWebElement) element1).getCoordinates().inViewPort();
throw new MissingException(WebDriverException.class);
} catch (WebDriverException e) {
}
}
public void windowTitleWithPercentage() throws Throwable {
driver = new JavaDriver();
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
frame.setTitle("My %Dialog%");
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
WebElement element1 = driver.findElement(By.name("click-me"));
String id1 = ((RemoteWebElement) element1).getId();
// driver.switchTo().window("My %25Dialog%25");
TargetLocator switchTo = driver.switchTo();
switchTo.window("My %Dialog%");
WebElement element2 = driver.findElement(By.name("click-me"));
String id2 = ((RemoteWebElement) element2).getId();
AssertJUnit.assertEquals(id1, id2);
}
public void doubleTap() {
LOGGER_BASE.info("Double Tap: "); // + Elements.getElementDetails(element));
if (this.settings.platform == PlatformType.Android) {
Double x = (double) this.element.getLocation().x
+ (double) (this.element.getSize().width / 2);
Double y = (double) this.element.getLocation().y
+ (double) (this.element.getSize().height / 2);
JavascriptExecutor js = (JavascriptExecutor) this.client.driver;
HashMap<String, Double> tapObject = new HashMap<String, Double>();
tapObject.put("x", x);
tapObject.put("y", y);
tapObject.put("touchCount", (double) 1);
tapObject.put("tapCount", (double) 1);
tapObject.put("duration", 0.05);
js.executeScript("mobile: tap", tapObject);
js.executeScript("mobile: tap", tapObject);
}
if (this.settings.platform == PlatformType.iOS) {
RemoteWebElement e = (RemoteWebElement) this.element;
((RemoteWebDriver) this.client.driver).executeScript("au.getElement('" + e.getId() + "').tapWithOptions({tapCount:2});");
}
}
@SuppressWarnings("unchecked")
@Override
public Object apply(Object result) {
if (result instanceof Collection<?>) {
Collection<QAFExtendedWebElement> results = (Collection<QAFExtendedWebElement>) result;
return Lists.newArrayList(Iterables.transform(results, this));
}
result = super.apply(result);
if (result instanceof RemoteWebElement) {
if (!(result instanceof QAFExtendedWebElement)) {
QAFExtendedWebElement ele = newRemoteWebElement();
ele.setId(((RemoteWebElement) result).getId());
return ele;
}
}
return result;
}
@Override
protected RemoteWebElement newRemoteWebElement() {
Class<? extends RemoteWebElement> target;
target = getElementClass(platform, automation);
try {
Constructor<? extends RemoteWebElement> constructor = target.getDeclaredConstructor();
constructor.setAccessible(true);
RemoteWebElement result = constructor.newInstance();
result.setParent(driver);
result.setFileDetector(driver.getFileDetector());
return result;
} catch (Exception e) {
throw new WebDriverException(e);
}
}
@Test
public void encodesWrappedElementInMoveOrigin() {
RemoteWebElement innerElement = new RemoteWebElement();
innerElement.setId("12345");
WebElement element = new WrappedWebElement(innerElement);
PointerInput pointerInput = new PointerInput(Kind.MOUSE, null);
Interaction move = pointerInput.createPointerMove(
Duration.ofMillis(100), Origin.fromElement(element), 0, 0);
Sequence sequence = new Sequence(move.getSource(), 0).addAction(move);
String rawJson = new Json().toJson(sequence);
ActionSequenceJson json = new Json().toType(
rawJson,
ActionSequenceJson.class,
PropertySetting.BY_FIELD);
assertThat(json.actions).hasSize(1);
ActionJson firstAction = json.actions.get(0);
assertThat(firstAction.origin).containsEntry(W3C.getEncodedElementKey(), "12345");
}
@Test
public void testDecoratedElementsShouldBeUnwrapped() {
final RemoteWebElement element = new RemoteWebElement();
element.setId("foo");
WebDriver driver = mock(WebDriver.class);
when(driver.findElement(new ByIdOrName("element"))).thenReturn(element);
PublicPage page = new PublicPage();
PageFactory.initElements(driver, page);
Object seen = new WebElementToJsonConverter().apply(page.element);
Object expected = new WebElementToJsonConverter().apply(element);
assertThat(seen).isEqualTo(expected);
}
@SuppressWarnings("unchecked")
@Test
public void convertsAListWithAWebElement() {
RemoteWebElement element = new RemoteWebElement();
element.setId("abc123");
RemoteWebElement element2 = new RemoteWebElement();
element2.setId("anotherId");
Object value = CONVERTER.apply(asList(element, element2));
assertThat(value).isInstanceOf(Collection.class);
List<Object> list = new ArrayList<>((Collection<Object>) value);
assertThat(list).hasSize(2);
assertIsWebElementObject(list.get(0), "abc123");
assertIsWebElementObject(list.get(1), "anotherId");
}
private void fixLocator(SearchContext context, String cssLocator,
WebElement element) {
if (element instanceof RemoteWebElement) {
try {
@SuppressWarnings("rawtypes")
Class[] parameterTypes = new Class[] { SearchContext.class,
String.class, String.class };
Method m = element.getClass().getDeclaredMethod(
"setFoundBy", parameterTypes);
m.setAccessible(true);
Object[] parameters = new Object[] { context,
"css selector", cssLocator };
m.invoke(element, parameters);
} catch (Exception fail) {
//NOOP Would like to log here?
}
}
}
@Test
void testWrappedWebElementUnwrap()
{
RemoteWebElement remoteWebElement = mock(RemoteWebElement.class);
WrapsDriver actual = WebDriverUtil.unwrap(new TextFormattingWebElement(remoteWebElement), WrapsDriver.class);
assertEquals(remoteWebElement, actual);
}
@Test
void testNonWrappedWebElementUnwrap()
{
RemoteWebElement remoteWebElement = mock(RemoteWebElement.class);
WrapsDriver actual = WebDriverUtil.unwrap(remoteWebElement, WrapsDriver.class);
assertEquals(remoteWebElement, actual);
}
@Override
public RemoteWebElement getElement(Duration timeout) {
try {
return super.getElement(timeout);
} catch (NoSuchElementException e) {
getLogger().error(e.getMessage());
long timeoutInSeconds = timeout == null
? AqualityServices.get(ITimeoutConfiguration.class).getCondition().getSeconds()
: timeout.getSeconds();
throw new NoSuchElementException(
String.format("element %s was not found in %d seconds in state %s by locator %s",
getName(), timeoutInSeconds, getElementState(), getLocator()));
}
}
@Test
public void testFlashElement() {
WebElement el = wait.until(ExpectedConditions.presenceOfElementLocated(loginScreen));
HashMap<String, Object> scriptArgs = new HashMap<>();
scriptArgs.put("element", ((RemoteWebElement)el).getId());
scriptArgs.put("durationMillis", 50); // how long should each flash take?
scriptArgs.put("repeatCount", 20); // how many times should we flash?
driver.executeScript("mobile: flashElement", scriptArgs);
}
public static void holdElementiOS(MobileElement element) {
JavascriptExecutor js = (JavascriptExecutor) DriverFactoryManager.getDriver();
HashMap<String, String> tapObject = new HashMap<String, String>();
tapObject.put("element", ((RemoteWebElement) element).getId());
tapObject.put("duration", "2");
js.executeScript("mobile: touchAndHold", tapObject);
}
public static void dataPicker(MobileElement element) {
JavascriptExecutor js = (JavascriptExecutor) DriverFactoryManager.getDriver();
HashMap<String, String> picker = new HashMap<String, String>();
picker.put("order", "next");
picker.put("offset", "0.15");
picker.put("element", ((RemoteWebElement) element).getId());
js.executeScript("mobile: selectPickerWheelValue", picker);
}
public void findElementGetsTheSameElementBetweenCalls() throws Throwable {
driver = new JavaDriver();
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
WebElement element1 = driver.findElement(By.name("click-me"));
String id1 = ((RemoteWebElement) element1).getId();
WebElement element2 = driver.findElement(By.name("click-me"));
String id2 = ((RemoteWebElement) element2).getId();
AssertJUnit.assertEquals(id1, id2);
}
@SuppressWarnings("unchecked")
@Override
public List<WebElement> findElements(SearchContext context) {
Object res;
if (context instanceof RemoteWebElement) {
res = ((JavascriptExecutor) ((RemoteWebElement) context).getWrappedDriver()).executeScript(CHILD_COMP_QUERY,
context, querySelector);
} else {
res = ((JavascriptExecutor) context).executeScript(COMP_QUERY, querySelector);
}
return (List<WebElement>) res;
}
@SuppressWarnings("unchecked")
@Override
public List<WebElement> findElements(SearchContext context) {
Object res;
if (context instanceof RemoteWebElement) {
res = ((JavascriptExecutor) ((RemoteWebElement) context).getWrappedDriver()).executeScript(CHILD_COMP_QUERY,
context, querySelector);
} else {
res = ((JavascriptExecutor) context).executeScript(COMP_QUERY, querySelector);
}
return (List<WebElement>) res;
}
/**
*
* @param locator - The pickerwheel element must be this specific
* type ("XCUIElementTypePickerWheel"), not “XCUIElementTypePicker”
* or any other parent/child of the pickerwheel.
* @param value - value to compare this must be exact
* @param direction - Direction to spin the spinner, either next or previous defaults to next
*/
@Then("^I pick \"(.*?)\" from \"(.*?)\" in the direction \"(.*?)\"$")
public static void setPickerWheel(String value, String locator, String direction){
if(!direction.contains("next") && !direction.contains("previous"))
{
direction = "next";
}
DeviceUtils.setPickerWheel( (RemoteWebElement) new QAFExtendedWebElement(locator), direction, value);
}
/**
* Sets the picker wheel to the value specified.
*
* @param picker - WebElement that holds the XCUIElementTypePicker
* @param direction - Direction to spin the spinner, either next or previous
* defaults to next
* @param value - value to compare this must be exact
*/
public static void setPickerWheel(RemoteWebElement picker, String direction, String value) {
value = value.replaceAll("[^\\x00-\\x7F]", "");
String name = picker.getAttribute("value").replaceAll("[^\\x00-\\x7F]", "");
while (!name.equals(value)) {
System.out.println(name);
pickerwheelStep(picker, direction);
// title based will retrieve the title as a string,
// view based will retrieve a string that represent the view
// (uniqueness depends on the developer of the app).
name = picker.getAttribute("value").replaceAll("[^\\x00-\\x7F]", "");
}
}
public boolean tapById(String id) {
try{
Map<String, ?> params = ImmutableMap.of("element", ((RemoteWebElement)driver.findElement(By.id(id))).getId());
((RobotRemoteWebDriver)this.driver).execute(DriverCommand.TOUCH_SINGLE_TAP, params);
}catch(Exception ex) {
return false;
}
return true;
}
public boolean tapByXPath(String xpath) {
try {
Map<String, ?> params = ImmutableMap.of("element", ((RemoteWebElement)driver.findElement(By.xpath(xpath))).getId());
((RobotRemoteWebDriver)this.driver).execute(DriverCommand.TOUCH_SINGLE_TAP, params);
}catch(Exception ex) {
return false;
}
return true;
}
public boolean tap(By by) {
try {
Map<String, ?> params = ImmutableMap.of("element", ((RemoteWebElement)driver.findElement(by)).getId());
((RobotRemoteWebDriver)this.driver).execute(DriverCommand.TOUCH_SINGLE_TAP, params);
}catch(Exception ex) {
return false;
}
return true;
}
private RemoteWebElement setOwner(RemoteWebElement element) {
if (driver != null) {
element.setParent(driver);
element.setFileDetector(driver.getFileDetector());
}
return element;
}
protected void fillFileBox(RemoteWebElement fileBoxElement, String fileName) {
if (fileName.isEmpty()) {
fileBoxElement.clear();
} else {
fileBoxElement.setFileDetector(new UselessFileDetector());
String filePath = new File(fileName).getAbsolutePath();
fileBoxElement.sendKeys(filePath);
}
}
protected void fillFileBox(RemoteWebElement fileBoxElement, String fileName) {
if (fileName.isEmpty()) {
fileBoxElement.clear();
} else {
fileBoxElement.setFileDetector(new UselessFileDetector());
String newFilePath = new File(fileName).getAbsolutePath();
fileBoxElement.sendKeys(newFilePath);
}
}
@Override
public Object apply(Object result) {
if (result instanceof RemoteWebElement
&& !(result instanceof CachingRemoteWebElement)) {
RemoteWebElement originalElement = (RemoteWebElement) result;
result = createCachingWebElement(originalElement);
}
return super.apply(result);
}