下面列出了怎么用org.openqa.selenium.Keys的API类实例代码及写法,或者点击链接到github查看源代码。
public void menuItemShortcuts() throws Throwable {
// This test for testing keyboard shortcuts on menu items need to be
// fixed after the bug fix in send keys.
driver = new JavaDriver();
WebElement textArea = driver.findElement(By.cssSelector("text-area"));
textArea.click();
textArea.sendKeys(Keys.chord(Keys.ALT, "1"));
AssertJUnit.assertTrue(
"Error:Expected to end with:\n" + "Event source: A text-only menu item (an instance of JMenuItem)\n" + "\nActual:\n"
+ textArea.getText().trim(),
textArea.getText().trim().endsWith("Event source: A text-only menu item (an instance of JMenuItem)\n".trim()));
textArea.sendKeys(Keys.chord(Keys.ALT, "2"));
AssertJUnit.assertTrue(
"Error:Expected to end with:\n" + "Event source: A text-only menu item (an instance of JMenuItem)\n" + "\nActual:\n"
+ textArea.getText().trim(),
textArea.getText().trim().endsWith("Event source: An item in the submenu (an instance of JMenuItem)\n".trim()));
}
/**
* @return control key depending on operating system
*/
protected Keys getControlKey() {
Keys controlKey = Keys.CONTROL;
WebDriver webDriver = WebDriverRunner.getWebDriver();
if (webDriver instanceof JavascriptExecutor) {
// check if working on MacOS
Object result = ((JavascriptExecutor) webDriver)
.executeScript("return window.navigator.platform");
if (result instanceof String) {
String platform = (String) result;
if (MAC_OS_PLATFORM.equals(platform)) {
controlKey = Keys.COMMAND;
}
}
}
return controlKey;
}
private void checkSimpleCtrlBInteractionWorks() {
driver.get(KEY_CLICK_DISPLAY);
new Actions(driver).keyDown(Keys.CONTROL).
sendKeys("b").
keyUp(Keys.CONTROL).
perform();
System.out.println(driver.findElement(By.id("events")).getText());
assertEquals( "only expected 4 events",
4,
driver.findElements(
By.cssSelector("#events p")).size());
}
@Test
@Ignore(IE)
@NotYetImplemented(SAFARI)
public void testCombiningShiftAndClickResultsInANewWindow() {
driver.get(pages.linkedImage);
WebElement link = driver.findElement(By.id("link"));
String originalTitle = driver.getTitle();
int nWindows = driver.getWindowHandles().size();
new Actions(driver)
.moveToElement(link)
.keyDown(Keys.SHIFT)
.click()
.keyUp(Keys.SHIFT)
.perform();
wait.until(windowHandleCountToBe(nWindows + 1));
assertThat(driver.getTitle())
.describedAs("Should not have navigated away").isEqualTo(originalTitle);
}
/**
* scroll terminal by pressing key 'End'
*
* @param item is the name of the highlighted item
*/
public void moveDownListTerminal(String item) {
loader.waitOnClosed();
typeIntoActiveTerminal(Keys.END.toString());
WaitUtils.sleepQuietly(2);
WebElement element =
seleniumWebDriver.findElement(
By.xpath(format("(//span[contains(text(), '%s')])[position()=1]", item)));
if (!element.getCssValue("background-color").equals(LINE_HIGHLIGHTED_GREEN)) {
typeIntoActiveTerminal(Keys.ARROW_UP.toString());
element =
seleniumWebDriver.findElement(
By.xpath(format("(//span[contains(text(), '%s')])[position()=1]", item)));
WaitUtils.sleepQuietly(2);
}
new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC)
.until(visibilityOf(element));
WebElement finalElement = element;
new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC)
.until(
(WebDriver input) ->
finalElement.getCssValue("background-color").equals(LINE_HIGHLIGHTED_GREEN));
}
@Test
public void synchronizeInitialValueNotSentToServer() {
open();
WebElement syncOnChangeInitialValue = findElement(
By.id("syncOnChangeInitialValue"));
WebElement labelSyncOnChange = findElement(
By.id("syncOnChangeInitialValueLabel"));
// Property was set after label was created and sync set up
// It is intentionally in the "wrong" state until there is a sync
// message from the client
Assert.assertEquals("Server value on create: null",
labelSyncOnChange.getText());
syncOnChangeInitialValue.sendKeys(Keys.END);
syncOnChangeInitialValue.sendKeys("123");
blur();
Assert.assertEquals("Server value in change listener: initial123",
labelSyncOnChange.getText());
}
@Test
@NotYetImplemented(SAFARI)
@NotYetImplemented(EDGE)
public void testSendingKeysWithShiftPressed() {
driver.get(pages.javascriptPage);
WebElement keysEventInput = driver.findElement(By.id("theworks"));
keysEventInput.click();
String existingResult = getFormEvents();
Action pressShift = getBuilder(driver).keyDown(keysEventInput, Keys.SHIFT).build();
pressShift.perform();
Action sendLowercase = getBuilder(driver).sendKeys(keysEventInput, "ab").build();
sendLowercase.perform();
Action releaseShift = getBuilder(driver).keyUp(keysEventInput, Keys.SHIFT).build();
releaseShift.perform();
String expectedEvents = " keydown keydown keypress keyup keydown keypress keyup keyup";
assertThatFormEventsFiredAreExactly("Shift key not held", existingResult + expectedEvents);
assertThat(keysEventInput.getAttribute("value")).isEqualTo("AB");
}
/**
* In this case, we have one book and one borrower,
* so we should get a dropdown
*
* more detail:
* Under lending, books and borrowers inputs have three modes.
* a) if no books/borrowers, lock the input
* b) If 1 - 9, show a dropdown
* c) If 10 and up, show an autocomplete
*/
@Test
public void test_shouldShowDropdowns() {
// clear the database...
driver.get("http://localhost:8080/demo/flyway");
ApiCalls.registerBook("some book");
ApiCalls.registerBorrowers("some borrower");
driver.get("http://localhost:8080/demo/library.html");
// using the arrow keys to select an element is a very "dropdown" kind of behavior.
driver.findElement(By.id("lend_book")).sendKeys(Keys.ARROW_UP);
driver.findElement(By.id("lend_borrower")).sendKeys(Keys.ARROW_UP);
driver.findElement(By.id("lend_book_submit")).click();
final String result = driver.findElement(By.id("result")).getText();
assertEquals("SUCCESS", result);
}
/**
* Press the delete key on the active element. This step is known to have issues with
* the Firefox Marionette driver.
* @param times The number of times to press the delete key
* @param ignoreErrors Add this text to ignore any exceptions. This is really only useful for debugging.
*/
@When("^I press(?: the)? Delete(?: key)? on the active element(?: \"(\\d+)\" times)?( ignoring errors)?$")
public void pressDeleteStep(final Integer times, final String ignoreErrors) {
try {
final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread();
final WebElement element = webDriver.switchTo().activeElement();
for (int i = 0; i < ObjectUtils.defaultIfNull(times, 1); ++i) {
element.sendKeys(Keys.DELETE);
sleepUtils.sleep(State.getFeatureStateForThread().getDefaultKeyStrokeDelay());
}
sleepUtils.sleep(State.getFeatureStateForThread().getDefaultSleep());
} catch (final Exception ex) {
if (StringUtils.isBlank(ignoreErrors)) {
throw ex;
}
}
}
/**
* A test.
*/
@Test
public void deleteAndBackspaceKeys() {
final WebDriver driver = getWebDriver("/javascriptPage.html");
final WebElement element = driver.findElement(By.id("keyReporter"));
element.sendKeys("abcdefghi");
assertThat(element.getAttribute("value"), is("abcdefghi"));
element.sendKeys(Keys.LEFT, Keys.LEFT, Keys.DELETE);
assertThat(element.getAttribute("value"), is("abcdefgi"));
element.sendKeys(Keys.LEFT, Keys.LEFT, Keys.BACK_SPACE);
assertThat(element.getAttribute("value"), is("abcdfgi"));
}
@Test
public void itemsInList_twoWayDataBinding_updatesAreSentToServer() {
open();
findElement(By.id("enable")).click();
List<WebElement> fields = $("two-way-list-binding").first()
.$(DivElement.class).first().findElements(By.id("input"));
// self check
Assert.assertEquals(2, fields.size());
fields.get(0).clear();
fields.get(0).sendKeys("baz");
fields.get(0).sendKeys(Keys.TAB);
Assert.assertEquals("[baz, bar]", getLastInfoMessage());
fields.get(1).sendKeys("foo");
fields.get(1).sendKeys(Keys.TAB);
Assert.assertEquals("[baz, barfoo]", getLastInfoMessage());
}
/**
* @throws Exception if the test fails
*/
@Test
public void typeMaxLength() throws Exception {
final String html
= HtmlPageTest.STANDARDS_MODE_PREFIX_
+ "<html><body>\n"
+ "<form>\n"
+ "<input type='text' id='text1' maxlength='5'/>\n"
+ "<input type='password' id='password1' maxlength='6'/>\n"
+ "</form></body></html>";
final WebDriver webDriver = loadPage2(html);
final WebElement textField = webDriver.findElement(By.id("text1"));
textField.sendKeys("123456789");
assertEquals("12345", textField.getAttribute("value"));
textField.sendKeys(Keys.BACK_SPACE);
textField.sendKeys("7");
assertEquals("12347", textField.getAttribute("value"));
final WebElement passwordField = webDriver.findElement(By.id("password1"));
passwordField.sendKeys("123456789");
assertEquals("123456", passwordField.getAttribute("value"));
passwordField.sendKeys(Keys.BACK_SPACE);
passwordField.sendKeys("7");
assertEquals("123457", passwordField.getAttribute("value"));
}
public void sendKeys() throws Throwable {
driver = new JavaDriver();
List<WebElement> buttons = driver.findElements(By.cssSelector("button"));
AssertJUnit.assertEquals(3, buttons.size());
WebElement b1 = buttons.get(0);
AssertJUnit.assertEquals("Disable middle button", b1.getText());
WebElement b2 = buttons.get(1);
AssertJUnit.assertEquals("Middle button", b2.getText());
WebElement b3 = buttons.get(2);
AssertJUnit.assertEquals("Enable middle button", b3.getText());
AssertJUnit.assertEquals("true", b1.getAttribute("enabled"));
AssertJUnit.assertEquals("true", b2.getAttribute("enabled"));
AssertJUnit.assertEquals("false", b3.getAttribute("enabled"));
b1.sendKeys(Keys.SPACE);
AssertJUnit.assertEquals("false", b1.getAttribute("enabled"));
AssertJUnit.assertEquals("false", b2.getAttribute("enabled"));
AssertJUnit.assertEquals("true", b3.getAttribute("enabled"));
}
/**
* @throws Exception if the test fails
*/
@Test
public void type() throws Exception {
final String html = "<html><head></head><body><input id='t' type='search'/></body></html>";
final WebDriver webDriver = loadPage2(html);
final WebElement input = webDriver.findElement(By.id("t"));
input.sendKeys("abc");
assertEquals("abc", input.getAttribute("value"));
input.sendKeys(Keys.BACK_SPACE);
assertEquals("ab", input.getAttribute("value"));
input.sendKeys(Keys.BACK_SPACE);
assertEquals("a", input.getAttribute("value"));
input.sendKeys(Keys.BACK_SPACE);
assertEquals("", input.getAttribute("value"));
input.sendKeys(Keys.BACK_SPACE);
assertEquals("", input.getAttribute("value"));
}
/**
* @throws Exception if the test fails
*/
@Test
public void type() throws Exception {
final String html = "<html><head></head><body><input type='password' id='p'/></body></html>";
final WebDriver driver = loadPage2(html);
final WebElement p = driver.findElement(By.id("p"));
p.sendKeys("abc");
assertEquals("abc", p.getAttribute("value"));
p.sendKeys(Keys.BACK_SPACE);
assertEquals("ab", p.getAttribute("value"));
p.sendKeys(Keys.BACK_SPACE);
assertEquals("a", p.getAttribute("value"));
p.sendKeys(Keys.BACK_SPACE);
assertEquals("", p.getAttribute("value"));
p.sendKeys(Keys.BACK_SPACE);
assertEquals("", p.getAttribute("value"));
}
/**
* @throws Exception on test failure
*/
@Test
public void sendEnterKey() throws Exception {
final String html = "<!DOCTYPE html>\n"
+ "<html><head></head>\n"
+ "<body>\n"
+ " <form id='myForm' action='" + URL_SECOND + "'>\n"
+ " <input id='myText' type='text'>\n"
+ " </form>\n"
+ "</body></html>";
final String secondContent = "second content";
getMockWebConnection().setResponse(URL_SECOND, secondContent);
final WebDriver driver = loadPage2(html);
driver.findElement(By.id("myText")).sendKeys(Keys.ENTER);
assertEquals(2, getMockWebConnection().getRequestCount());
assertEquals(URL_SECOND, getMockWebConnection().getLastWebRequest().getUrl());
}
@Test
public void completionApplyCaretPosition() throws InterruptedException {
driver.navigate().to(url);
// Start the add-in
driver.findElement(By.id("startButton")).click();
driver.findElement(By.id("genconfURI")).sendKeys(genconfURI);
driver.findElement(By.id("expression")).click();
driver.findElement(By.id("expression")).sendKeys("self.ances");
Thread.sleep(2000);
driver.findElement(By.id("expression")).sendKeys("t");
Thread.sleep(1000);
driver.findElement(By.id("expression")).sendKeys(Keys.DOWN);
driver.findElement(By.id("expression")).sendKeys(Keys.ENTER);
Thread.sleep(1000);
assertEquals("self.ancestors()", driver.findElement(By.id("expression")).getAttribute("value"));
assertEquals("15", driver.findElement(By.id("expression")).getAttribute("selectionStart"));
assertEquals("15", driver.findElement(By.id("expression")).getAttribute("selectionEnd"));
}
@Override
public SelenideElement deselectRow(By rowBy) {
this.shouldBe(VISIBLE)
.shouldBe(ENABLED);
SelenideElement row = getRow(rowBy)
.shouldBe(visible)
.shouldHave(selectedClass);
WebDriver webDriver = WebDriverRunner.getWebDriver();
Actions action = new Actions(webDriver);
Keys controlKey = getControlKey();
action.keyDown(controlKey)
.click(row.getWrappedElement())
.keyUp(controlKey)
.build()
.perform();
return row;
}
public void pressEnter(WebElement element) {
takeScreenShot();
assertNotNull(element, "Selenium provider failed, element is null");
element.sendKeys(Keys.RETURN);
log.info("Enter pressed");
takeScreenShot();
}
/**
* Эмулирует нажатие клавиш на клавиатуре
*/
@И("^выполнено нажатие на клавиатуре \"([^\"]*)\"$")
@And("^pressed \"([^\"]*)\" key $")
public void pushButtonOnKeyboard(String buttonName) {
Keys key = Keys.valueOf(buttonName.toUpperCase());
switchTo().activeElement().sendKeys(key);
}
public static Keys getMenuKey() {
int keyMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
if (keyMask == Event.CTRL_MASK) {
return Keys.CONTROL;
}
if (keyMask == Event.META_MASK) {
return Keys.META;
}
if (keyMask == Event.ALT_MASK) {
return Keys.ALT;
}
throw new WebDriverException("Unable to find the keymask... not control or meta?");
}
@Override
public DateTimeField setTimeValue(String value) {
SelenideElement timeFieldImpl = $(byChain(by, TIMEPART));
timeFieldImpl
.shouldBe(visible)
.shouldBe(enabled)
.shouldNotBe(readonly)
.click();
timeFieldImpl.sendKeys(Keys.HOME, value);
return this;
}
@Test
void testPressKeysContextNotFocused()
{
Mockito.lenient().when(webUiContext.getSearchContext(WebElement.class)).thenReturn(webElement);
keyboardSteps.pressKeys(KEYS);
Mockito.verify(webElement, never()).sendKeys(Keys.CONTROL, A);
}
@Test
public void unsyncedPropertyUpdate_internalError() {
open();
WebElement input = findElement(By.tagName("input"));
input.sendKeys("bar", Keys.ENTER);
// system error which means there is an exception on the server side
Assert.assertTrue(isElementPresent(By.className("v-system-error")));
}
/**
* Places cursor to the specified {@code positionLine}.
*
* @param positionLine number of the line where cursor should be placed
*/
public void setCursorToLine(int positionLine) {
loader.waitOnClosed();
seleniumWebDriverHelper.sendKeys(Keys.chord(CONTROL, "l"));
askForValueDialog.waitFormToOpen();
loader.waitOnClosed();
askForValueDialog.typeAndWaitText(String.valueOf(positionLine));
loader.waitOnClosed();
askForValueDialog.clickOkBtn();
askForValueDialog.waitFormToClose();
editor.waitActive();
}
protected void fillTextBox(WebElement textBoxElement, String value) {
try {
scrollElementToCenterAndClick(textBoxElement);
} catch (WebDriverException e) {
// It is important that a text box element is clickable before we fill it but due to legacy reasons we continue
// attempting to fill the text box element even if it's not clickable (which may lead to an unexpected failure
// later on)
System.out.println("Unexpectedly not able to click on the text box element because of: ");
System.out.println(e);
}
// If the intended value is empty `clear` works well enough for us
if (value.isEmpty()) {
textBoxElement.clear();
return;
}
// Otherwise we need to do special handling of entering input because `clear` and `sendKeys` work differently.
// See documentation for `clearAndSendKeys` for more details.
clearAndSendKeys(textBoxElement, value);
// Add event hook before blurring the text box element so we can detect the event.
firefoxChangeHandler.addChangeEventHook(textBoxElement);
textBoxElement.sendKeys(Keys.TAB); // blur the element to receive events
// Although events should not be manually fired, the `change` event does not fire when text input is changed if
// Firefox is not in focus. Setting profile option `focusmanager.testmode = true` does not help as well.
// A temporary solution is to fire the `change` event until the buggy behavior is fixed.
// More details can be found in the umbrella issue of related bugs in the following link:
// https://github.com/mozilla/geckodriver/issues/906
// The firing of `change` event is also imperfect because no check for the type of the elements is done before firing
// the event, for instance a `change` event will be wrongly fired on any content editable element. The firing time of
// `change` events is also incorrect for several `input` types such as `checkbox` and `date`.
// See: https://developer.mozilla.org/en-US/docs/Web/Events/change
firefoxChangeHandler.fireChangeEventIfNotFired(textBoxElement);
}
/** type into password field on Google authorization page user - defined password */
public void typePasswordDefinedByUser(String password) {
new WebDriverWait(seleniumWebDriver, 10)
.until(ExpectedConditions.visibilityOf(passwordInput))
.sendKeys(password);
passwordInput.sendKeys(Keys.ENTER.toString());
}
/**
* Simulates 'copy' (e.g. Ctrl+C on Windows) on the active element, copying the current selection to the clipboard.
* @return whether an active element was found.
*/
public boolean copy() {
boolean result = false;
WebElement element = getActiveElement();
if (element != null) {
if (connectedToMac()) {
element.sendKeys(Keys.CONTROL, Keys.INSERT);
} else {
element.sendKeys(Keys.CONTROL, "c");
}
result = true;
}
return result;
}
@Test
public void testAllModifierKeysRegardedAsSuch() {
new KeyDownAction(mockKeyboard, mockMouse, stubLocatable, Keys.SHIFT);
new KeyDownAction(mockKeyboard, mockMouse, stubLocatable, Keys.LEFT_SHIFT);
new KeyDownAction(mockKeyboard, mockMouse, stubLocatable, Keys.CONTROL);
new KeyDownAction(mockKeyboard, mockMouse, stubLocatable, Keys.LEFT_CONTROL);
new KeyDownAction(mockKeyboard, mockMouse, stubLocatable, Keys.ALT);
new KeyDownAction(mockKeyboard, mockMouse, stubLocatable, Keys.LEFT_ALT);
new KeyDownAction(mockKeyboard, mockMouse, stubLocatable, Keys.META);
new KeyDownAction(mockKeyboard, mockMouse, stubLocatable, Keys.COMMAND);
}
private void copyTerminalTextToClipboard(int terminalIndex) {
Dimension textLayerSize = getTextLayer(terminalIndex).getSize();
final Actions action = seleniumWebDriverHelper.getAction();
final int xBeginCoordinateShift = -(textLayerSize.getWidth() / 2);
final int yBeginCoordinateShift = -(textLayerSize.getHeight() / 2);
seleniumWebDriverHelper.moveCursorTo(getTextLayer(terminalIndex));
// shift to top left corner
seleniumWebDriverHelper
.getAction()
.moveByOffset(xBeginCoordinateShift, yBeginCoordinateShift)
.perform();
// select all terminal area by mouse
action.clickAndHold().perform();
seleniumWebDriverHelper
.getAction()
.moveByOffset(textLayerSize.getWidth(), textLayerSize.getHeight())
.perform();
action.release().perform();
// copy terminal output to clipboard
String keysCombination = Keys.chord(CONTROL, INSERT);
seleniumWebDriverHelper.sendKeys(keysCombination);
// cancel terminal area selection
clickOnTerminal(terminalIndex);
}