Java Code Examples for org.openqa.selenium.Dimension

The following examples show how to use org.openqa.selenium.Dimension. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: hifive-pitalium   Source File: CompareEntirePageTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 十分な高さにしてスクロールが出ない状態でbodyのassertViewを実行するテスト.<br>
 * 前提条件:なし<br>
 * 実行環境:IE7~11/FireFox/Chrome/Android 2.3, 4.0, 4.4/iOS 8.1<br>
 * 期待結果:実行したタイムスタンプのフォルダ内にspecifyTargetBodyWithoutScroll_topPage_WINDOWS_(browser name).pngが生成される<br>
 *        仕様通りのresult.jsonと座標用のjsonファイルが生成される<br>
 *        RUN_TESTモードの場合、assertViewの比較で一致し、compareResultがtrueとなる
 */
@Test
public void specifyTargetBodyWithoutScroll() {
	String platformName = capabilities.getPlatformName();
	if (!"iOS".equals(platformName) && !"android".equalsIgnoreCase(platformName)) {
		driver.manage().window().setSize(new Dimension(1280, 2500));
	}

	driver.get(URL_TOP_PAGE);

	PtlWebDriverWait wait = new PtlWebDriverWait(driver, 30);
	wait.untilLoad();

	CompareTarget[] targets = { new CompareTarget(ScreenArea.of(SelectorType.TAG_NAME, "body")) };
	assertionView.assertView("topPage", targets, HIDDEN_ELEMENTS);
}
 
Example 2
Source Project: xframium-java   Source File: PressGesture.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
protected boolean _executeGesture( WebDriver webDriver )
{
	AppiumDriver appiumDriver = null;
	
	if ( webDriver instanceof AppiumDriver )
		appiumDriver = (AppiumDriver) webDriver;
	else if ( webDriver instanceof NativeDriverProvider )
	{
		NativeDriverProvider nativeProvider = (NativeDriverProvider) webDriver;
		if ( nativeProvider.getNativeDriver() instanceof AppiumDriver )
			appiumDriver = (AppiumDriver) nativeProvider.getNativeDriver();
		else
			throw new IllegalArgumentException( "Unsupported Driver Type " + webDriver );
	}
	Dimension screenDimension = appiumDriver.manage().window().getSize();
	
	Point pressPosition = getActualPoint( getPressPosition(), screenDimension );
	
	TouchAction swipeAction = new TouchAction( appiumDriver );
	swipeAction.press( PointOption.point( pressPosition.getX(), pressPosition.getY() ) ).waitAction( WaitOptions.waitOptions( Duration.ofMillis( getPressLength() ) ) ).release().perform();
	
	return true;
}
 
Example 3
Source Project: xframium-java   Source File: SwipeGesture.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
protected boolean _executeGesture( WebDriver webDriver )
{
	AppiumDriver appiumDriver = null;
	
	if ( webDriver instanceof AppiumDriver )
		appiumDriver = (AppiumDriver) webDriver;
	else if ( webDriver instanceof NativeDriverProvider )
	{
		NativeDriverProvider nativeProvider = (NativeDriverProvider) webDriver;
		if ( nativeProvider.getNativeDriver() instanceof AppiumDriver )
			appiumDriver = (AppiumDriver) nativeProvider.getNativeDriver();
		else
			throw new IllegalArgumentException( "Unsupported Driver Type " + webDriver );
	}
	Dimension screenDimension = appiumDriver.manage().window().getSize();
	
	Point actualStart = getActualPoint( getSwipeStart(), screenDimension );
	Point actualEnd = getActualPoint( getSwipeEnd(), screenDimension );
	
	TouchAction swipeAction = new TouchAction( appiumDriver );
	swipeAction.press( PointOption.point(actualStart.getX(), actualStart.getY() ) ).moveTo( PointOption.point(actualEnd.getX(), actualEnd.getY() ) ).release().perform();
	
	return true;
}
 
Example 4
Source Project: coteafs-selenium   Source File: AbstractDriver.java    License: Apache License 2.0 6 votes vote down vote up
private void setScreen(final PlaybackSetting playback) {
    final ScreenState state = playback.getScreenState();
    if (getPlatform() == DESKTOP) {
        LOG.i("Setting screen size of Browser to {}...", state);
        switch (state) {
            case FULL_SCREEN:
                manageWindow(Window::fullscreen);
                break;
            case MAXIMIZED:
                manageWindow(Window::maximize);
                break;
            case NORMAL:
            default:
                final ScreenResolution resolution = playback.getScreenResolution();
                LOG.i("Setting screen resolution to [{}]...", resolution);
                manageWindow(w -> w.setSize(new Dimension(resolution.getWidth(), resolution.getHeight())));
                manageWindow(w -> w.setPosition(new Point(0, 0)));
                break;
        }
    }
}
 
Example 5
Source Project: nomulus   Source File: RegistrarConsoleScreenshotTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void settingsSecurityWithCerts() throws Throwable {
  server.runInAppEngineEnvironment(
      () -> {
        persistResource(
            loadRegistrar("TheRegistrar")
                .asBuilder()
                .setClientCertificate(CertificateSamples.SAMPLE_CERT, START_OF_TIME)
                .setFailoverClientCertificate(CertificateSamples.SAMPLE_CERT2, START_OF_TIME)
                .build());
        return null;
      });
  driver.manage().window().setSize(new Dimension(1050, 2000));
  driver.get(server.getUrl("/registrar#security-settings"));
  driver.waitForElement(By.tagName("h1"));
  driver.diffPage("view");
  driver.waitForElement(By.id("reg-app-btn-edit")).click();
  driver.waitForElement(By.tagName("h1"));
  driver.diffPage("edit");
}
 
Example 6
Source Project: nomulus   Source File: RegistrarConsoleScreenshotTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void settingsContactEdit_setRegistryLockPassword() throws Throwable {
  server.runInAppEngineEnvironment(
      () -> {
        persistResource(
            makeRegistrarContact2()
                .asBuilder()
                .setRegistryLockEmailAddress("[email protected]")
                .setAllowedToSetRegistryLockPassword(true)
                .build());
        persistResource(makeRegistrar2().asBuilder().setRegistryLockAllowed(true).build());
        return null;
      });
  driver.manage().window().setSize(new Dimension(1050, 2000));
  driver.get(server.getUrl("/registrar#contact-settings/[email protected]"));
  Thread.sleep(1000);
  driver.waitForElement(By.tagName("h1"));
  driver.waitForElement(By.id("reg-app-btn-edit")).click();
  driver.diffPage("page");
}
 
Example 7
@Override
public boolean popuplateDevice( DeviceWebDriver webDriver, String deviceId, Device device, String xFID )
{
    String uAgent = (String) webDriver.executeScript("return navigator.userAgent;");
    UserAgent userAgent = new UserAgent( uAgent );
    device.setBrowserName( userAgent.getBrowser().getName() );
    device.setManufacturer( userAgent.getOperatingSystem().getManufacturer().getName() );
    String[] osSplit = userAgent.getOperatingSystem().getName().split( " " );
    device.setOs( osSplit[ 0 ].toUpperCase() );
    if ( osSplit.length > 1 )
        device.setOsVersion( userAgent.getOperatingSystem().getName().split( " " )[ 1 ].toUpperCase() );
    
    Dimension winDim = webDriver.manage().window().getSize();
    if ( winDim != null )
        device.setResolution( winDim.getWidth() + " x " + winDim.height );
    else
        device.setResolution( null );
    
    return true;
}
 
Example 8
Source Project: NoraUi   Source File: DriverFactory.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Generates a selenium webdriver following a name given in parameter.
 * By default a chrome driver is generated.
 *
 * @param driverName
 *            The name of the web driver to generate
 * @return
 *         An instance a web driver whose type is provided by driver name given in parameter
 * @throws TechnicalException
 *             if an error occured when Webdriver setExecutable to true.
 */
private WebDriver generateWebDriver(String driverName) throws TechnicalException {
    WebDriver driver;
    if (IE.equals(driverName)) {
        driver = generateIEDriver();
    } else if (CHROME.equals(driverName)) {
        driver = generateGoogleChromeDriver();
    } else if (FIREFOX.equals(driverName)) {
        driver = generateFirefoxDriver();
    } else {
        driver = generateGoogleChromeDriver();
    }
    // As a workaround: NoraUi specify window size manually, e.g. window_size: 1920 x 1080 (instead of .window().maximize()).
    driver.manage().window().setSize(new Dimension(1920, 1080));
    driver.manage().timeouts().implicitlyWait(IMPLICIT_WAIT, TimeUnit.MILLISECONDS);
    drivers.put(driverName, driver);
    return driver;

}
 
Example 9
/**
 * 判断要点击的元素是否被其它元素覆盖
 * 
 * @param clickBy
 * @param coverBy
 * @return
 */
public boolean isCover(By clickBy, By coverBy) {

	MobileElement clickElement = getDriver().findElement(clickBy);
	MobileElement coverElement = getDriver().findElement(coverBy);

	// 获取控件开始位置高度
	Point clickstart = clickElement.getLocation();
	int clickStartY = clickstart.y;

	Point coverstart = coverElement.getLocation();
	int coverStartY = coverstart.y;

	// 获取控件高度
	Dimension firstq = clickElement.getSize();
	int height = firstq.getHeight();

	// 控件中间高度是否大于底部高度
	if (clickStartY + height / 2 >= coverStartY) {
		return true;
	}
	return false;
}
 
Example 10
/**
 * 判断要点击的元素是否被其它元素覆盖
 * 
 * @param clickBy
 * @param coverBy
 * @return
 */
public boolean isCover(By clickBy, By coverBy) {

	MobileElement clickElement = getDriver().findElement(clickBy);
	MobileElement coverElement = getDriver().findElement(coverBy);

	// 获取控件开始位置高度
	Point clickstart = clickElement.getLocation();
	int clickStartY = clickstart.y;

	Point coverstart = coverElement.getLocation();
	int coverStartY = coverstart.y;

	// 获取控件高度
	Dimension firstq = clickElement.getSize();
	int height = firstq.getHeight();

	// 控件中间高度是否大于底部高度
	if (clickStartY + height / 2 >= coverStartY) {

		return true;
	}
	return false;
}
 
Example 11
Source Project: Quantum   Source File: PerfectoDeviceSteps.java    License: MIT License 6 votes vote down vote up
/**
 * Performs the lo touch gesture according to the point coordinates.
 *
 * @param locator
 *            write in format of x,y. can be in pixels or
 *            percentage(recommended) for example 50%,50%.
 */
@Then("^I tap on \"(.*?)\" for \"(\\d*\\.?\\d*)\" seconds$")
public static void tapElement(String locator, int seconds) {

	QAFExtendedWebElement myElement = new QAFExtendedWebElement(locator);

	Point location = myElement.getLocation();
	Dimension size = myElement.getSize();

	// determine location to click and convert to an appropriate string
	int xToClick = location.getX() + (size.getWidth() / 2);
	int yToClick = location.getY() + (size.getHeight() / 2);
	String clickLocation = xToClick + "," + yToClick;

	DeviceUtils.longTouch(clickLocation, seconds);

}
 
Example 12
Source Project: coteafs-appium   Source File: SwipeUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param direction
 * @param startPosition
 * @param distancePercent
 * @param setting
 * @param screenSize
 * @param elementSize
 * @param elementLocation
 * @param actions
 * @return action
 * @author wasiq.bhamla
 * @since Sep 18, 2018 8:03:55 PM
 */
public static <T extends TouchAction<T>> T swipeTo(final SwipeDirection direction,
    final SwipeStartPosition startPosition, final int distancePercent, final PlaybackSetting setting,
    final Dimension screenSize, final Dimension elementSize, final Point elementLocation, final T actions) {
    final double distance = distancePercent / 100.0;
    final Point source = getStartPoint(startPosition, screenSize, elementSize, elementLocation);
    int endX = source.getX() + (int) (source.getX() * direction.getX() * distance);
    int endY = source.getY() + (int) (source.getY() * direction.getY() * distance);
    if (elementSize != null) {
        endX = source.getX() + (int) (elementSize.getWidth() * direction.getX() * distance);
        endY = source.getY() + (int) (elementSize.getHeight() * direction.getY() * distance);
    }
    return actions.press(PointOption.point(source.getX(), source.getY()))
        .waitAction(WaitOptions.waitOptions(Duration.ofMillis(setting.getDelayBeforeSwipe())))
        .moveTo(PointOption.point(endX, endY))
        .release();
}
 
Example 13
@Before
public void setUp() throws Exception {
	ChromeOptions options = new ChromeOptions();
	// This is hardcoded but we cannot do otherwise. The alternative would
	// be to run a docker grid
	driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), options);
	driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	// Many suggests to define the size, but if you tests requires a
	// different setting, change this
	driver.manage().window().setSize(new Dimension(1024, 768));
	//
	((RemoteWebDriver) driver).setFileDetector(new LocalFileDetector());
	// This is important: docker-compose randomly assign ports and names to
	// those logical entities so we get them from the rule
	String codeDefendersHome = "http://frontend:8080/codedefenders";
	//
	//
	driver.get(codeDefendersHome);
}
 
Example 14
Source Project: opentest   Source File: ReadElementAspect.java    License: MIT License 6 votes vote down vote up
@Override
public void run() {
    super.run();
    
    By locator = this.readLocatorArgument("locator");

    WebElement element = this.getElement(locator);
    Point point = element.getLocation();

    int x = point.getX();
    int y = point.getY();

    Dimension size = element.getSize();
    int width = size.width;
    int height = size.height;

    this.writeOutput("x", x);
    this.writeOutput("y", y);
    this.writeOutput("width", width);
    this.writeOutput("height", height);
}
 
Example 15
Source Project: Cognizant-Intelligent-Test-Scripter   Source File: Basic.java    License: Apache License 2.0 6 votes vote down vote up
@Action(object = ObjectType.BROWSER, desc = "Changes the browser size into [<Data>]", input = InputType.YES)
public void setBrowserSize() {
    try {
        if (Data.matches("\\d*(x|,| )\\d*")) {
            String size = Data.replaceFirst("(x|,| )", " ");
            String[] sizes = size.split(" ", 2);
            Driver.manage().window().setSize(new Dimension(Integer.parseInt(sizes[0]), Integer.parseInt(sizes[1])));
            Report.updateTestLog(Action, " Browser is resized to " + Data,
                    Status.DONE);
        } else {
            Report.updateTestLog(Action, " Invalid Browser size [" + Data + "]",
                    Status.DEBUG);
        }
    } catch (Exception ex) {
        Report.updateTestLog(Action, "Unable to resize the Window ",
                Status.FAIL);
        Logger.getLogger(Basic.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 16
Source Project: opentest   Source File: ReadElementAspect.java    License: MIT License 6 votes vote down vote up
@Override
public void run() {
    super.run();
    
    By locator = readLocatorArgument("locator");
    
    this.swipeAndCheckElementVisible(locator, this.getSwipeOptions());

    MobileElement element = this.getElement(locator);
    Point point = element.getLocation();

    int x = point.getX();
    int y = point.getY();

    Dimension size = element.getSize();
    int width = size.width;
    int height = size.height;
    
    Logger.trace(String.format("The element aspect is (%s,%s,%s,%s)",
            x, y, width, height));

    this.writeOutput("x", x);
    this.writeOutput("y", y);
    this.writeOutput("width", width);
    this.writeOutput("height", height);
}
 
Example 17
Source Project: apicurio-registry   Source File: SeleniumProvider.java    License: Apache License 2.0 5 votes vote down vote up
public void setupDriver(WebDriver driver) {
    this.driver = driver;
    this.driver.manage().window().setPosition(new Point(0, 0));
    this.driver.manage().window().setSize(new Dimension(1366, 768));
    driverWait = new WebDriverWait(driver, 10);
    browserScreenshots.clear();
}
 
Example 18
Source Project: selenium-shutterbug   Source File: Browser.java    License: MIT License 5 votes vote down vote up
public Coordinates getBoundingClientRect(WebElement element) {
    FileUtil.getJsScript(RELATIVE_COORDS_JS);
    ArrayList<String> list = (ArrayList<String>) executeJsScript(RELATIVE_COORDS_JS, element);
    Point start = new Point(Integer.parseInt(list.get(0)), Integer.parseInt(list.get(1)));
    Dimension size = new Dimension(Integer.parseInt(list.get(2)), Integer.parseInt(list.get(3)));
    return new Coordinates(start, size, devicePixelRatio);
}
 
Example 19
Source Project: nomulus   Source File: RegistrarConsoleScreenshotTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void settingsContactAdd() throws Throwable {
  driver.manage().window().setSize(new Dimension(1050, 2000));
  driver.get(server.getUrl("/registrar#contact-settings"));
  Thread.sleep(1000);
  driver.waitForElement(By.tagName("h1"));
  driver.waitForElement(By.id("reg-app-btn-add")).click();
  driver.diffPage("page");
}
 
Example 20
Source Project: vividus   Source File: JavascriptActions.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Dimension getViewportSize()
{
    Map<String, Long> result = executeScript(
            "return {width: Math.max(document.documentElement.clientWidth, window.innerWidth || 0),"
                    + "height: Math.max(document.documentElement.clientHeight, window.innerHeight || 0)}");
    return new Dimension(result.get("width").intValue(), result.get("height").intValue());
}
 
Example 21
Source Project: nomulus   Source File: RegistrarConsoleScreenshotTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void settingsContactEdit_setRegistryLockPassword_notAllowedForContact() throws Throwable {
  server.runInAppEngineEnvironment(
      () -> persistResource(makeRegistrar2().asBuilder().setRegistryLockAllowed(true).build()));
  driver.manage().window().setSize(new Dimension(1050, 2000));
  driver.get(server.getUrl("/registrar#contact-settings/[email protected]"));
  Thread.sleep(1000);
  driver.waitForElement(By.tagName("h1"));
  driver.waitForElement(By.id("reg-app-btn-edit")).click();
  driver.diffPage("page");
}
 
Example 22
Source Project: vividus   Source File: WindowsActions.java    License: Apache License 2.0 5 votes vote down vote up
private int getWindowSize(String windowHandle)
{
    WebDriver driver = getWebDriver();
    driver.switchTo().window(windowHandle);
    Dimension dimension = driver.manage().window().getSize();
    return dimension.getHeight() * dimension.getWidth();
}
 
Example 23
Source Project: bobcat   Source File: DroppableWebElement.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @return Point in the middle of the drop area.
 */
@Override
public Point getCurrentLocation() {
  Point inViewPort = null;
  switcher.switchTo(getFramePath());
  try {
    Dimension size = dropArea.getSize();
    inViewPort = ((Locatable) dropArea).getCoordinates().inViewPort()
        .moveBy(size.getWidth() / 2, size.getHeight() / 2);
  } finally {
    switcher.switchBack();
  }
  return inViewPort;
}
 
Example 24
Source Project: vividus   Source File: WebDriverManagerTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testGetNativeApplicationViewportCached()
{
    mockWebDriverHavingCapabilities(Map.of(CapabilityType.PLATFORM_NAME, MobilePlatform.IOS));
    when(webDriverProvider.getUnwrapped(Rotatable.class)).thenReturn(mobileDriver);
    lenient().when(webDriverManagerContext.getParameter(WebDriverManagerParameter.ORIENTATION)).thenReturn(null);
    when(mobileDriver.getOrientation()).thenReturn(ScreenOrientation.PORTRAIT);
    Dimension dimension = new Dimension(375, 667);
    lenient().when(webDriverManagerContext.getParameter(WebDriverManagerParameter.SCREEN_SIZE))
            .thenReturn(dimension);
    Dimension actualDimension = webDriverManager.getSize();
    assertEquals(dimension.getHeight(), actualDimension.getHeight());
    assertEquals(dimension.getWidth(), actualDimension.getWidth());
    verify(this.mobileDriver, never()).manage();
}
 
Example 25
Source Project: vividus   Source File: DelegatingWebElementTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testGetSize()
{
    Dimension dimension = Mockito.mock(Dimension.class);
    when(webElement.getSize()).thenReturn(dimension);
    assertEquals(dimension, delegatingWebElement.getSize());
}
 
Example 26
Source Project: vividus   Source File: ScreenshotFileNameGeneratorTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testGenerateScreenshotFileNameWithoutBrowserName()
{
    Dimension dimension = new Dimension(WIDTH, HEIGHT);
    when(webDriverManager.getSize()).thenReturn(dimension);
    String screenshotFileName = screenshotFileNameGenerator.generateScreenshotFileName(SCREENSHOT_NAME);
    assertTrue(screenshotFileName.matches(FILE_DATE_PATTERN + SCREENSHOT_NAME + WIDTH_X_HEIGHT_EXTENSION));
}
 
Example 27
private static WebDriver checkAndSetSize(WebDriver driver, String size) {
    if (driver != null) {
        if (size.matches("[0-9]+ x [0-9]+")) {
            int w = Integer.valueOf(size.split("x")[0].trim());
            int h = Integer.valueOf(size.split("x")[1].trim());
            driver.manage().window().setSize(new Dimension(w, h));
        }
    }
    return driver;
}
 
Example 28
Source Project: nomulus   Source File: RegistrarConsoleScreenshotTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void settingsWhoisEditError() throws Throwable {
  driver.manage().window().setSize(new Dimension(1050, 2000));
  driver.get(server.getUrl("/registrar#whois-settings"));
  driver.waitForElement(By.id("reg-app-btn-edit")).click();
  driver.setFormFieldsById(ImmutableMap.of("faxNumber", "cat"));
  driver.waitForElement(By.id("reg-app-btn-save")).click();
  Thread.sleep(1000);
  driver.diffPage("page");
}
 
Example 29
Source Project: vividus   Source File: JavascriptActionsTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testGetViewportSize()
{
    Map<String, Long> map = new HashMap<>();
    Long width = 375L;
    Long height = 600L;
    map.put("width", width);
    map.put("height", height);
    String viewportSize = "return {width: Math.max(document.documentElement.clientWidth, window.innerWidth || 0),"
            + "height: Math.max(document.documentElement.clientHeight, window.innerHeight || 0)}";
    when(((JavascriptExecutor) webDriver).executeScript(viewportSize)).thenReturn(map);
    Dimension size = javascriptActions.getViewportSize();
    assertEquals(new Dimension(width.intValue(), height.intValue()), size);
}
 
Example 30
@Override
public Rectangle findImage( DeviceWebDriver webDriver, String imageName, Map<String, String> propertyMap )
{
    
    ImageExecution imageExec = PerfectoMobile.instance( webDriver.getxFID() ).imaging().imageExists( webDriver.getExecutionId(), webDriver.getDeviceName(), imageName, propertyMap );
    
    if ( imageExec != null && Boolean.parseBoolean( imageExec.getStatus() ) )
        return new Rectangle( new Point( Integer.parseInt( imageExec.getLeft() ), Integer.parseInt( imageExec.getTop() ) ), new Dimension( Integer.parseInt( imageExec.getWidth() ), Integer.parseInt( imageExec.getHeight() ) ) );
    
    return null;
}