类org.openqa.selenium.Keys源码实例Demo

下面列出了怎么用org.openqa.selenium.Keys的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: marathonv5   文件: JMenuTest.java
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()));
}
 
源代码2 项目: masquerade   文件: DataGridImpl.java
/**
 * @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());
    }
 
源代码4 项目: selenium   文件: CombinedInputActionsTest.java
@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);
}
 
源代码5 项目: che   文件: CheTerminal.java
/**
 * 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));
}
 
源代码6 项目: flow   文件: SynchronizedPropertyIT.java
@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());

}
 
源代码7 项目: selenium   文件: BasicKeyboardInterfaceTest.java
@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");
}
 
源代码8 项目: demo   文件: SeleniumTests.java
/**
 * 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;
		}
	}
}
 
源代码10 项目: htmlunit   文件: TypingTest.java
/**
 * 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"));
}
 
源代码11 项目: flow   文件: TwoWayListBindingIT.java
@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());
}
 
源代码12 项目: htmlunit   文件: HTMLInputElementTest.java
/**
 * @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"));
}
 
源代码13 项目: marathonv5   文件: JButtonTest.java
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"));
}
 
源代码14 项目: htmlunit   文件: HtmlSearchInputTest.java
/**
 * @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"));
}
 
源代码15 项目: htmlunit   文件: HtmlPasswordInputTest.java
/**
 * @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"));
}
 
源代码16 项目: htmlunit   文件: DomElementTest.java
/**
 * @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());
}
 
源代码17 项目: M2Doc   文件: FrontEndTests.java
@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"));
}
 
源代码18 项目: masquerade   文件: DataGridImpl.java
@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;
}
 
源代码19 项目: apicurio-registry   文件: SeleniumProvider.java
public void pressEnter(WebElement element) {
    takeScreenShot();
    assertNotNull(element, "Selenium provider failed, element is null");
    element.sendKeys(Keys.RETURN);
    log.info("Enter pressed");
    takeScreenShot();
}
 
源代码20 项目: akita   文件: RoundUpSteps.java
/**
 * Эмулирует нажатие клавиш на клавиатуре
 */
@И("^выполнено нажатие на клавиатуре \"([^\"]*)\"$")
@And("^pressed \"([^\"]*)\" key $")
public void pushButtonOnKeyboard(String buttonName) {
    Keys key = Keys.valueOf(buttonName.toUpperCase());
    switchTo().activeElement().sendKeys(key);
}
 
源代码21 项目: marathonv5   文件: OSUtils.java
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?");
}
 
源代码22 项目: masquerade   文件: DateTimeFieldImpl.java
@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;
}
 
源代码23 项目: vividus   文件: KeyboardStepsTests.java
@Test
void testPressKeysContextNotFocused()
{
    Mockito.lenient().when(webUiContext.getSearchContext(WebElement.class)).thenReturn(webElement);
    keyboardSteps.pressKeys(KEYS);
    Mockito.verify(webElement, never()).sendKeys(Keys.CONTROL, A);
}
 
源代码24 项目: flow   文件: NotSyncedPropertyUpdateIT.java
@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")));
}
 
源代码25 项目: che   文件: CommandsEditor.java
/**
 * 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();
}
 
源代码26 项目: teammates   文件: AppPage.java
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);
}
 
源代码27 项目: che   文件: GoogleLogin.java
/** 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());
}
 
源代码28 项目: hsac-fitnesse-fixtures   文件: SeleniumHelper.java
/**
 * 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;
}
 
源代码29 项目: selenium   文件: IndividualKeyboardActionsTest.java
@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);
}
 
源代码30 项目: che   文件: TheiaTerminal.java
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);
}
 
 类所在包
 同包方法