Java Code Examples for org.openqa.selenium.Dimension

The following are top voted examples for showing how to use org.openqa.selenium.Dimension. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: che   File: SeleniumWebDriver.java   Source Code and License 8 votes vote down vote up
private RemoteWebDriver doCreateDriver(URL webDriverUrl) {
  DesiredCapabilities capability;

  switch (browser) {
    case GOOGLE_CHROME:
      ChromeOptions options = new ChromeOptions();
      options.addArguments("--no-sandbox");
      options.addArguments("--dns-prefetch-disable");

      capability = DesiredCapabilities.chrome();
      capability.setCapability(ChromeOptions.CAPABILITY, options);
      break;

    default:
      capability = DesiredCapabilities.firefox();
      capability.setCapability("dom.max_script_run_time", 240);
      capability.setCapability("dom.max_chrome_script_run_time", 240);
  }

  RemoteWebDriver driver = new RemoteWebDriver(webDriverUrl, capability);
  driver.manage().window().setSize(new Dimension(1920, 1080));

  return driver;
}
 
Example 2
Project: opentest   File: AppiumTestAction.java   Source Code and License 7 votes vote down vote up
protected void swipeRight(MobileElement element) {
        Point point = element.getLocation();
        Point p = element.getCenter();

        Dimension size = driver.manage().window().getSize();

        int screenWidth = (int) (size.width * 0.90);
        // int elementX = point.getX();
        int elementX = p.getX();

        int endY = 0;
        int endX = element.getSize().getWidth();
//        Logger.debug("Device height:" + size.getHeight() + "$$$ Device width:" + size.getWidth());
//        Logger.debug("Element X:" + point.getX() + "$$$ Element Y:" + point.getY());
//        Logger.debug("Element Height:" + element.getSize().height + "$$$$ Element Width:" + element.getSize().width);
//        Logger.debug("end X:" + endX + "$$$$end Y:" + endY);
        TouchAction action = new TouchAction((MobileDriver) driver);
        //action.press(element).moveTo(endX, endY).release().perform();
        action.press((int) (point.getX() + (element.getSize().getWidth() * 0.10)), element.getCenter().getY()).moveTo((int) (screenWidth - (point.getX() + (element.getSize().getWidth() * 0.10))), endY).release().perform();

    }
 
Example 3
Project: che   File: TestWebElementRenderChecker.java   Source Code and License 7 votes vote down vote up
private void waitElementIsStatic(FluentWait<WebDriver> webDriverWait, WebElement webElement) {
  AtomicInteger sizeHashCode = new AtomicInteger();

  webDriverWait.until(
      (ExpectedCondition<Boolean>)
          driver -> {
            Dimension newDimension = waitAndGetWebElement(webElement).getSize();

            if (dimensionsAreEquivalent(sizeHashCode, newDimension)) {
              return true;
            } else {
              sizeHashCode.set(getSizeHashCode(newDimension));
              return false;
            }
          });
}
 
Example 4
Project: phoenix.webui.framework   File: TargetElementMark.java   Source Code and License 6 votes vote down vote up
@Override
public void mark(WebElement ele, File file) throws IOException
{
	BufferedImage bufImg = ImageIO.read(file);
	
	try
	{
		WebElement webEle = (WebElement) ele;
		Point loc = webEle.getLocation();
		Dimension size = webEle.getSize();
		
		Graphics2D g = bufImg.createGraphics();
		g.setColor(Color.red);
		g.drawRect(loc.getX(), loc.getY(), size.getWidth(), size.getHeight());
	}
	catch(StaleElementReferenceException se)
	{
	}
}
 
Example 5
Project: marathonv5   File: JavaDriverTest.java   Source Code and License 6 votes vote down vote up
public void windowSetSize() throws Throwable {
    driver = new JavaDriver();
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override public void run() {
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });
    Window window = driver.manage().window();
    Dimension actual = window.getSize();
    AssertJUnit.assertNotNull(actual);
    java.awt.Dimension expected = EventQueueWait.call(frame, "getSize");
    AssertJUnit.assertEquals(expected.width, actual.width);
    AssertJUnit.assertEquals(expected.height, actual.height);
    window.setSize(new Dimension(expected.width * 2, expected.height * 2));
    actual = window.getSize();
    AssertJUnit.assertEquals(expected.width * 2, actual.width);
    AssertJUnit.assertEquals(expected.height * 2, actual.height);
}
 
Example 6
Project: WebAndAppUITesting   File: IphoneBaseOpt.java   Source Code and License 6 votes vote down vote up
/**
 * 判断要点击的元素是否被其它元素覆盖
 * 
 * @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 7
Project: WebAndAppUITesting   File: AndroidBaseOpt.java   Source Code and License 6 votes vote down vote up
/**
 * 判断要点击的元素是否被其它元素覆盖
 * 
 * @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 8
Project: coteafs-appium   File: DeviceActions.java   Source Code and License 6 votes vote down vote up
private TouchAction swipeTo (final SwipeDirection direction, final SwipeDistance distance) {
	final Dimension size = this.driver.manage ()
		.window ()
		.getSize ();
	final int startX = size.getWidth () / 2;
	final int startY = size.getHeight () / 2;
	final int endX = (int) (startX * direction.getX () * distance.getDistance ());
	final int endY = (int) (startY * direction.getY () * distance.getDistance ());
	final int beforeSwipe = this.device.getSetting ()
		.getDelayBeforeSwipe ();
	final int afterSwipe = this.device.getSetting ()
		.getDelayAfterSwipe ();
	final TouchAction returnAction = new TouchAction (this.driver);
	returnAction.press (startX, startY)
		.waitAction (ofSeconds (beforeSwipe))
		.moveTo (endX, endY)
		.waitAction (ofSeconds (afterSwipe))
		.release ();
	return returnAction;
}
 
Example 9
Project: opentest   File: AppiumTestAction.java   Source Code and License 6 votes vote down vote up
protected void swipeDown(MobileElement element) {
        Point point = element.getLocation();
        Dimension size = driver.manage().window().getSize();

        int screenHeight = (int) (size.height * 0.90);
        int elementY = point.getY();

        int endX = 0;
        int endY = ((int) screenHeight - elementY);
//        Logger.debug("Device height:" + size.getHeight() + "$$$ Device width:" + size.getWidth());
//        Logger.debug("Element X:" + point.getX() + "$$$ Element Y:" + point.getY());
//        Logger.debug("Element Height:" + element.getSize().height + "$$$$ Element Width:" + element.getSize().width);
//        Logger.debug("end X:" + endX + "$$$$end Y:" + endY);
        TouchAction action = new TouchAction((MobileDriver) driver);
        //action.press(element).moveTo(endX, endY).release().perform();
        action.press(element.getCenter().getX(), element.getCenter().getY()).moveTo(endX, screenHeight - element.getCenter().getY()).release().perform();

    }
 
Example 10
Project: xtf   File: WebDriverService.java   Source Code and License 6 votes vote down vote up
private WebDriver createWebDriver(final Consumer<DesiredCapabilities> desiredCapabilities) {

		String hostName = GhostDriverService.get().getHostName();

		DesiredCapabilities capabilities = DesiredCapabilities.phantomjs();
		if (desiredCapabilities != null) {
			desiredCapabilities.accept(capabilities);
		}
		try {
			WebDriver driver = new RemoteWebDriver(new URL("http://localhost:" + GhostDriverService.get().getLocalPort() + "/"), capabilities);
			driver.manage().window().setSize(new Dimension(1920, 1080));
			return driver;
		} catch (MalformedURLException e) {
			throw new IllegalStateException("Wrong hostName '" + hostName + "', possibly GhostDriverService::start not called ", e);
		}
	}
 
Example 11
Project: Cognizant-Intelligent-Test-Scripter   File: Basic.java   Source Code and License 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 12
Project: mobileAutomation   File: Driver.java   Source Code and License 6 votes vote down vote up
/**
 * Swipe from xStart to xStop on the horizontal center of the screen.
 * 
 * @param xStart - start point in percents 
 * @param xStop - end point in percents 
 * @param speed - swipe speed
 */
public static void horizontalSwipe(double xStart, double xStop, int speed)
{
	Dimension size = driver.manage().window().getSize();
	((AppiumDriver<?>) driver).swipe(

			// start point
			(int)xStart,
			size.height/2,
			
			// end point
			(int)xStop,
			size.height/2,

			speed);
	ThreadUtils.sleepQuiet(2000);
}
 
Example 13
Project: mobileAutomation   File: Driver.java   Source Code and License 6 votes vote down vote up
/**
 * Swipe from yStart to yStop on the vertical center of the screen.
 * 
 * @param yStart - start point in percents  
 * @param yStop - end point in percents 
 * @param speed - swipe speed
 */
public static void verticalSwipe(double yStart, double yStop, int speed)
{
	Dimension size = driver.manage().window().getSize();
	((AppiumDriver<?>) driver).swipe(

			// start point
			size.width/2,
			(int)(size.height*yStart),

			// end point
			size.width/2,
			(int)(size.height*yStop), 

			speed);
	ThreadUtils.sleepQuiet(2000);
}
 
Example 14
Project: bobcat   File: DroppableWebElement.java   Source Code and License 6 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 15
Project: xframium-java   File: ReportingWebElementAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public Dimension getSize()
{
    Dimension returnValue = null;
    webDriver.getExecutionContext().startStep( createStep( "AT" ), null, null );
    try
    {
        returnValue = baseElement.getSize();
    }
    catch( Exception e )
    {
        webDriver.getExecutionContext().completeStep( StepStatus.FAILURE, e );
    }
    
    webDriver.getExecutionContext().completeStep( StepStatus.SUCCESS, null );
    
    return returnValue;
}
 
Example 16
Project: xframium-java   File: CachedWebElement.java   Source Code and License 6 votes vote down vote up
@Override
public Dimension getSize()
{
	try
	{
		String height = null, width = null;
		
		height=getAttribute( "height" );
		width=getAttribute( "width" );
		if ( height != null && width != null )
		    return new Dimension( Integer.parseInt( width ), Integer.parseInt( height ) );
		else
		    return new Dimension( 0, 0 );
	}
	catch( Exception e )
	{
		return webDriver.findElement( by ).getSize();
	}
	
	
}
 
Example 17
Project: xframium-java   File: DeviceWebDriver.java   Source Code and License 6 votes vote down vote up
public void get( String url )
{
    setLastAction();
    webDriver.get( url );
    
    try
    {
        double outerHeight = Integer.parseInt( executeScript( "return window.outerHeight;" ) + "" );
        double outerWidth = Integer.parseInt( executeScript( "return window.outerWidth;" ) + "" );
        
        Dimension windowSize = manage().window().getSize();
        Object f = executeScript( "return window.outerHeight;" );
        heightModifier = (double) windowSize.getHeight() / outerHeight;
        widthModifier = (double) windowSize.getWidth() / outerWidth;
        
    }
    catch( Exception e )
    {
        log.warn( "Could not extract height/width modifiers" );
        heightModifier = 1;
        widthModifier = 1;
    }
}
 
Example 18
Project: xframium-java   File: SELENIUMCloudActionProvider.java   Source Code and License 6 votes vote down vote up
@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 19
Project: xframium-java   File: SAUCELABSCloudActionProvider.java   Source Code and License 6 votes vote down vote up
@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 20
Project: xframium-java   File: PressGesture.java   Source Code and License 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(  pressPosition.getX(), pressPosition.getY() ).waitAction( Duration.ofMillis( getPressLength() ) ).release().perform();
	
	return true;
}
 
Example 21
Project: xframium-java   File: SwipeGesture.java   Source Code and License 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( actualStart.getX(), actualStart.getY() ).moveTo( actualEnd.getX(), actualEnd.getY() ).release().perform();
	
	return true;
}
 
Example 22
Project: menggeqa   File: AppiumDriver.java   Source Code and License 6 votes vote down vote up
/**
 * Convenience method for pinching an element on the screen.
 * "pinching" refers to the action of two appendages pressing the
 * screen and sliding towards each other.
 * NOTE:
 * This convenience method places the initial touches around the element, if this would
 * happen to place one of them off the screen, appium with return an outOfBounds error.
 * In this case, revert to using the MultiTouchAction api instead of this method.
 *
 * @param el The element to pinch.
 */
public void pinch(WebElement el) {
    MultiTouchAction multiTouch = new MultiTouchAction(this);

    Dimension dimensions = el.getSize();
    Point upperLeft = el.getLocation();
    Point center = new Point(upperLeft.getX() + dimensions.getWidth() / 2,
        upperLeft.getY() + dimensions.getHeight() / 2);
    int yOffset = center.getY() - upperLeft.getY();

    TouchAction action0 =
        new TouchAction(this).press(el, center.getX(), center.getY() - yOffset).moveTo(el)
            .release();
    TouchAction action1 =
        new TouchAction(this).press(el, center.getX(), center.getY() + yOffset).moveTo(el)
            .release();

    multiTouch.add(action0).add(action1);

    multiTouch.perform();
}
 
Example 23
Project: menggeqa   File: AppiumDriver.java   Source Code and License 6 votes vote down vote up
/**
 * Convenience method for "zooming in" on an element on the screen.
 * "zooming in" refers to the action of two appendages pressing the screen and sliding
 * away from each other.
 * NOTE:
 * This convenience method slides touches away from the element, if this would happen
 * to place one of them off the screen, appium will return an outOfBounds error.
 * In this case, revert to using the MultiTouchAction api instead of this method.
 *
 * @param el The element to pinch.
 */
public void zoom(WebElement el) {
    MultiTouchAction multiTouch = new MultiTouchAction(this);

    Dimension dimensions = el.getSize();
    Point upperLeft = el.getLocation();
    Point center = new Point(upperLeft.getX() + dimensions.getWidth() / 2,
        upperLeft.getY() + dimensions.getHeight() / 2);
    int yOffset = center.getY() - upperLeft.getY();

    TouchAction action0 = new TouchAction(this).press(center.getX(), center.getY())
        .moveTo(el, center.getX(), center.getY() - yOffset).release();
    TouchAction action1 = new TouchAction(this).press(center.getX(), center.getY())
        .moveTo(el, center.getX(), center.getY() + yOffset).release();

    multiTouch.add(action0).add(action1);

    multiTouch.perform();
}
 
Example 24
Project: awplab-core   File: SeleniumProvider.java   Source Code and License 6 votes vote down vote up
@Override
public AutoClosableWebDriver wrapDriver(WebDriver webDriver) {
    AutoClosableWebDriver autoClosableWebDriver = new AutoClosableWebDriver(webDriver);
    if (waitUntilTimeout != null && waitUntilTimeoutUnit != null) {
        autoClosableWebDriver.setDefaultWaitUntilTimeout(waitUntilTimeout);
        autoClosableWebDriver.setDefaultWaitUntilTimeoutUnit(TimeUnit.valueOf(waitUntilTimeoutUnit));
    }
    if (implicityWaitTime != null && implicityWaitTimeUnit != null) {
        autoClosableWebDriver.manage().timeouts().implicitlyWait(implicityWaitTime, TimeUnit.valueOf(implicityWaitTimeUnit));
    }
    if (pageLoadTimeout != null && pageLoadTimeoutUnit != null) {
        autoClosableWebDriver.manage().timeouts().pageLoadTimeout(pageLoadTimeout, TimeUnit.valueOf(pageLoadTimeoutUnit));
    }
    if (scriptTimeout != null && scriptTimeoutUnit != null) {
        autoClosableWebDriver.manage().timeouts().setScriptTimeout(scriptTimeout, TimeUnit.valueOf(scriptTimeoutUnit));
    }
    if (windowHeight != null && windowWidth != null) {
        autoClosableWebDriver.manage().window().setSize(new Dimension(windowWidth, windowHeight));
    }

    return autoClosableWebDriver;
}
 
Example 25
Project: alimama   File: SeleniumUtil.java   Source Code and License 6 votes vote down vote up
public static BufferedImage createElementImage(WebDriver driver,WebElement webElement)  
          throws IOException {  
try{

          // 获得webElement的位置和大小。  
          Point location = webElement.getLocation();  
          Dimension size = webElement.getSize();  
          // 创建全屏截图。  
          BufferedImage originalImage =  
          ImageIO.read(new ByteArrayInputStream(takeScreenshot(driver)));  
          // 截取webElement所在位置的子图。  
          BufferedImage croppedImage = originalImage.getSubimage(  
          location.getX(),  
          location.getY(),  
          size.getWidth(),  
          size.getHeight());  
          return croppedImage;  
}catch(Exception e){
 e.printStackTrace();
}
return null;
          }
 
Example 26
Project: aet   File: ScreenCollector.java   Source Code and License 6 votes vote down vote up
private byte[] getImagePart(byte[] fullPage, WebElement webElement)
    throws IOException, ProcessingException {
  InputStream in = new ByteArrayInputStream(fullPage);
  try {
    BufferedImage fullImg = ImageIO.read(in);
    Point point = webElement.getLocation();
    Dimension size = webElement.getSize();
    BufferedImage screenshotSection = fullImg.getSubimage(point.getX(), point.getY(),
        size.getWidth(), size.getHeight());
    return bufferedImageToByteArray(screenshotSection);
  } catch (IOException e) {
    throw new ProcessingException("Unable to create image from taken screenshot", e);
  } finally {
    IOUtils.closeQuietly(in);
  }
}
 
Example 27
Project: hugegherkin   File: BrowserClass.java   Source Code and License 6 votes vote down vote up
/**
 * Example: =1204,1024
 */
@Autowired
public BrowserClass(@Value("${browser.web}") final String browserWebPropertyStr,
                    @Value("${browser.tablet}") final String browserTabletPropertyStr,
                    @Value("${browser.mobile}") final String browserMobilePropertyStr,
                    @Value("${browser.phantom}") final String browserPhantomPropertyStr) {
    List<Integer> browserWebProperty = stringToInts(browserWebPropertyStr);
    List<Integer> browserTabletProperty = stringToInts(browserTabletPropertyStr);
    List<Integer> browserMobileProperty = stringToInts(browserMobilePropertyStr);
    List<Integer> browserPhantomProperty = stringToInts(browserPhantomPropertyStr);


    browserClassMap.put(BrowserType.WEB, new Dimension(browserWebProperty.get(0), browserWebProperty.get(1)));
    browserClassMap.put(BrowserType.TABLET, new Dimension(browserTabletProperty.get(0), browserTabletProperty.get(1)));
    browserClassMap.put(BrowserType.MOBILE, new Dimension(browserMobileProperty.get(0), browserMobileProperty.get(1)));
    browserClassMap.put(BrowserType.PHANTOM, new Dimension(browserPhantomProperty.get(0), browserPhantomProperty.get(1)));

}
 
Example 28
Project: web-test-framework   File: TestCaseContextTest.java   Source Code and License 6 votes vote down vote up
/**
 *
 */
@Test(groups = "local")
  public void testSetWindowSize() {
      DriverFactory factory = new DriverFactory();
      Dimension dimension = new Dimension(400, 600);

      TestCaseContext context = new TestCaseContext();
      context.parameters()
              .setBrowserVersionPlatform(BrowserVersionPlatform.WIN7FF)
              .setWindowSize(dimension);
      context.setDriverFactory(factory);

      Driver driver = context.getDriver();

      Dimension actualDimension = driver.manage().window().getSize();
      Assert.assertEquals(actualDimension.height, dimension.height);
      Assert.assertEquals(actualDimension.width, dimension.width);

      driver.quit();
  }
 
Example 29
Project: edx-app-android   File: NativeAppDriver.java   Source Code and License 6 votes vote down vote up
/**
 * Wait till the element is displayed and swipe till the particular time
 * slot
 * 
 * @param id
 *            - id of the element
 */
public void swipe(String id) {
	try {
		if (isAndroid()) {
			new WebDriverWait(appiumDriver, 20).until(ExpectedConditions
					.presenceOfElementLocated(By.id(id)));
			Dimension dimension = appiumDriver.manage().window().getSize();
			int ht = dimension.height;
			int width = dimension.width;
			appiumDriver.swipe((width / 2), (ht / 4), (width / 2),
					(ht / 2), 1000);
		} else {
			new WebDriverWait(appiumDriver, 20).until(ExpectedConditions
					.presenceOfElementLocated(By.id(id)));
			if (deviceName.equalsIgnoreCase("iphone 5")) {
				appiumDriver.swipe((int) 0.1, 557, 211, 206, 500);
			} else if (deviceName.equalsIgnoreCase("iphone 6")) {
				appiumDriver.swipe((int) 0.1, 660, 50, 50, 500);
			}
		}
	} catch (Throwable e) {
		Reporter.log("Element by Id " + id + " not visible");
		captureScreenshot();
		throw e;
	}
}
 
Example 30
Project: appformer   File: PerspectiveSaveRestoreTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testResizeWestPanel() throws Exception {
    WebElement splitterDragHandle = driver.findElement(By.className("gwt-SplitLayoutPanel-HDragger"));

    Actions dragAndDrop = new Actions(driver);
    dragAndDrop.dragAndDropBy(splitterDragHandle,
                              123,
                              0);
    dragAndDrop.perform();

    ResizeWidgetWrapper westScreen = new ResizeWidgetWrapper(driver,
                                                             "west");
    Dimension westScreenNewSize = westScreen.getReportedSize();

    driver.get(baseUrl + "#" + DefaultPerspectiveActivity.class.getName());
    waitForDefaultPerspective();

    driver.get(baseUrl + "#" + NonTransientMultiPanelPerspective.class.getName());
    ResizeWidgetWrapper westScreenReloaded = new ResizeWidgetWrapper(driver,
                                                                     "west");
    assertEquals(westScreenNewSize,
                 westScreenReloaded.getReportedSize());
}
 
Example 31
Project: appformer   File: WorkbenchResizeTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testListPerspectiveSizeWithNestedPanels() throws Exception {
    driver.get(baseUrl + "#" + ListPerspectiveActivity.class.getName());
    ResizeWidgetWrapper widgetWrapper = new ResizeWidgetWrapper(driver,
                                                                "listPerspectiveDefault");

    TopHeaderWrapper topHeaderWrapper = new TopHeaderWrapper(driver);
    topHeaderWrapper.addPanelToRoot(CompassPosition.WEST,
                                    MultiListWorkbenchPanelPresenter.class,
                                    ResizeTestScreenActivity.class,
                                    "id",
                                    "resize1");

    Dimension sizeAfterWestPanelAdded = widgetWrapper.getActualSize();
    topHeaderWrapper.addPanelToRoot(CompassPosition.EAST,
                                    MultiListWorkbenchPanelPresenter.class,
                                    ResizeTestScreenActivity.class,
                                    "id",
                                    "resize2");

    Dimension sizeAfterBothPanelsAdded = widgetWrapper.getActualSize();

    assertTrue(sizeAfterWestPanelAdded.width < WINDOW_WIDTH);
    assertTrue(sizeAfterBothPanelsAdded.width < sizeAfterWestPanelAdded.width);
}
 
Example 32
Project: appformer   File: MaximizePanelTest.java   Source Code and License 6 votes vote down vote up
@Test
public void maximizeButtonShouldWorkOnTabbedPanel() throws Exception {
    MaximizeTestScreenWrapper tabPanelScreen4 =
            new MaximizeTestScreenWrapper(driver,
                                          MaximizeTestPerspective.TAB_PANEL_SCREEN_4_ID);
    Dimension reportedSizeBefore = tabPanelScreen4.getReportedSize();

    tabPanel.clickMaximizeButton();

    Dimension reportedSizeAfter = tabPanelScreen4.getReportedSize();
    assertBigger(reportedSizeBefore,
                 reportedSizeAfter);
    assertObscuredBy(tabPanel,
                     listPanel);
    assertObscuredBy(tabPanel,
                     simplePanel);
}
 
Example 33
Project: appformer   File: MaximizePanelTest.java   Source Code and License 6 votes vote down vote up
@Test
public void maximizeButtonShouldWorkOnListPanel() throws Exception {
    MaximizeTestScreenWrapper listPanelScreen2 =
            new MaximizeTestScreenWrapper(driver,
                                          MaximizeTestPerspective.LIST_PANEL_SCREEN_2_ID);
    Dimension reportedSizeBefore = listPanelScreen2.getReportedSize();

    listPanel.clickMaximizeButton();

    Dimension reportedSizeAfter = listPanelScreen2.getReportedSize();
    assertBigger(reportedSizeBefore,
                 reportedSizeAfter);
    assertObscuredBy(listPanel,
                     tabPanel);
    assertObscuredBy(listPanel,
                     simplePanel);
}
 
Example 34
Project: appformer   File: MaximizePanelTest.java   Source Code and License 6 votes vote down vote up
@Test
public void maximizeButtonShouldWorkOnSimplePanel() throws Exception {
    MaximizeTestScreenWrapper simplePanelScreen5 =
            new MaximizeTestScreenWrapper(driver,
                                          MaximizeTestPerspective.SIMPLE_PANEL_SCREEN_5_ID);
    Dimension reportedSizeBefore = simplePanelScreen5.getReportedSize();

    simplePanel.clickMaximizeButton();

    Thread.sleep(3000);
    Dimension reportedSizeAfter = simplePanelScreen5.getReportedSize();
    assertBigger(reportedSizeBefore,
                 reportedSizeAfter);
    assertObscuredBy(simplePanel,
                     tabPanel);
    assertObscuredBy(simplePanel,
                     listPanel);
}
 
Example 35
Project: appformer   File: MaximizePanelTest.java   Source Code and License 6 votes vote down vote up
@Test
public void maximizedTabPanelShouldTrackWindowSize() throws Exception {
    MaximizeTestScreenWrapper tabPanelScreen4 =
            new MaximizeTestScreenWrapper(driver,
                                          MaximizeTestPerspective.TAB_PANEL_SCREEN_4_ID);

    tabPanel.clickMaximizeButton();

    Dimension originalMaximizedSize = tabPanelScreen4.getReportedSize();
    driver.manage().window().setSize(new Dimension(WINDOW_WIDTH + 50,
                                                   WINDOW_HEIGHT - 40));
    new WebDriverWait(driver,
                      5)
            .until(reportedSizeIs(tabPanelScreen4,
                                  new Dimension(originalMaximizedSize.width + 50,
                                                originalMaximizedSize.height - 40)));
}
 
Example 36
Project: appformer   File: MaximizePanelTest.java   Source Code and License 6 votes vote down vote up
@Test
public void maximizedListPanelShouldTrackWindowSize() throws Exception {
    MaximizeTestScreenWrapper listPanelScreen2 =
            new MaximizeTestScreenWrapper(driver,
                                          MaximizeTestPerspective.LIST_PANEL_SCREEN_2_ID);

    listPanel.clickMaximizeButton();

    Dimension originalMaximizedSize = listPanelScreen2.getReportedSize();
    driver.manage().window().setSize(new Dimension(WINDOW_WIDTH + 50,
                                                   WINDOW_HEIGHT - 40));
    new WebDriverWait(driver,
                      5)
            .until(reportedSizeIs(listPanelScreen2,
                                  new Dimension(originalMaximizedSize.width + 50,
                                                originalMaximizedSize.height - 40)));
}
 
Example 37
Project: hifive-pitalium   File: PtlWebDriverFactory.java   Source Code and License 6 votes vote down vote up
/**
 * 初期設定(baseUrl、タイムアウト時間、ウィンドウサイズ)済のWebDriverを取得します。
 * 
 * @return WebDriver
 */
public PtlWebDriver getDriver() {
	synchronized (PtlWebDriverFactory.class) {
		LOG.debug("[Get WebDriver] create new session.");

		URL url = getGridHubURL();
		PtlWebDriver driver = createWebDriver(url);
		driver.setEnvironmentConfig(environmentConfig);
		driver.setBaseUrl(testAppConfig.getBaseUrl());
		driver.manage().timeouts().implicitlyWait(environmentConfig.getMaxDriverWait(), TimeUnit.SECONDS)
				.setScriptTimeout(environmentConfig.getScriptTimeout(), TimeUnit.SECONDS);
		if (!isMobile()) {
			driver.manage().window()
					.setSize(new Dimension(testAppConfig.getWindowWidth(), testAppConfig.getWindowHeight()));
		}

		LOG.debug("[Get WebDriver] new session created. ({})", driver);
		return driver;
	}
}
 
Example 38
Project: hifive-pitalium   File: ExcludeSingleElementTest.java   Source Code and License 6 votes vote down vote up
/**
 * 単体要素撮影時に、小数点以下がある幅を持つ単体要素を指定して除外する。
 *
 * @ptl.expect 除外領域が正しく保存されていること。
 */
@Test
public void singleTestWithDecimal() {
	openBasicColorPage();
	driver.manage().window().setSize(new Dimension(1100, (int) driver.getWindowHeight()));

	ScreenshotArgument arg = ScreenshotArgument.builder("s").addNewTarget().addExcludeById("colorColumn1").build();
	assertionView.assertView(arg);

	// Check
	Rect rect = getRectById("colorColumn1");
	TargetResult result = loadTargetResults("s").get(0);
	assertThat(result.getExcludes(), hasSize(1));

	RectangleArea area = result.getExcludes().get(0).getRectangle();
	RectangleArea expectArea = rect.toExcludeRect().toRectangleArea();
	assertThat(area, is(expectArea));
}
 
Example 39
Project: hifive-pitalium   File: TakeEntirePageScreenshotTest.java   Source Code and License 6 votes vote down vote up
/**
 * 十分な高さにしてスクロールが出ない状態でbodyのtakeScreenshotを実行するテスト.<br>
 * 前提条件:なし<br>
 * 実行環境:IE7~11/FireFox/Chrome/Android 2.3, 4.0, 4.4/iOS 8.1<br>
 * 期待結果:結果オブジェクト(ScrrenshotResult)に想定通りの値が入っている<br>
 *        また、全体の画像とbodyの画像が取得でき、それらをpersistすると画像ファイルが生成される。<br>
 *        これらの画像の内容は目視で確認を行うこと。
 * 
 * @throws IOException
 */
@Test
public void specifyTargetBodyWithoutScroll() throws IOException {
	String platformName = capabilities.getPlatformName();
	if (!"iOS".equals(platformName) && !"android".equalsIgnoreCase(platformName)) {
		driver.manage().window().setSize(new Dimension(1280, 2500));
	}

	driver.get(TEST_TOP_PAGE_URL);

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

	ScreenshotResult result = driver.takeScreenshot("topPage");
	assertScreenshotResult(result, "specifyTargetBodyWithoutScroll");
}
 
Example 40
Project: hifive-pitalium   File: AssertViewOfEntirePageTest.java   Source Code and License 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);
}
 
Example 41
Project: hifive-pitalium   File: CompareWithExcludesTest.java   Source Code and License 6 votes vote down vote up
/**
 * 十分な高さにしてスクロールが出ない状態でexcludeを指定するテスト<br>
 * 前提条件:なし<br>
 * 実行環境:IE7~11/FireFox/Chrome/Android 2.3, 4.0, 4.4, 5.1/iOS 8.1, 8.3<br>
 * 期待結果:テストに成功する
 */
@Test
public void excludeForBodyWithoutScroll() {
	String platformName = capabilities.getPlatformName();
	if (!"ios".equalsIgnoreCase(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();

	if (PtlTestConfig.getInstance().getEnvironment().getExecMode() == ExecMode.RUN_TEST) {
		wait.until(ExpectedConditions.presenceOfElementLocated(By.className("fb-like-box")));
		driver.executeJavaScript("document.getElementsByClassName('fb-like-box')[0].style.backgroundColor='red'");
	}

	CompareTarget[] targets = { new CompareTarget(ScreenArea.of(SelectorType.TAG_NAME, "body"), EXCLUDES, true) };
	assertionView.assertView("topPage", targets, HIDDEN_ELEMENTS);
}
 
Example 42
Project: hifive-pitalium   File: CompareEntirePageTest.java   Source Code and License 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 43
Project: find   File: TopicMapView.java   Source Code and License 6 votes vote down vote up
private List<ImmutablePair<WebElement, Integer>> childConcepts(final int clusterIndex) {
    //((lowestX,highestX),(lowestY,highestY))
    final Double[][] boundariesOfChosenCluster = nthConceptCluster(clusterIndex).getBoundaries();

    final Point mapCoordinates = map().getLocation();
    //L:Concept; Y:Index
    final List<ImmutablePair<WebElement, Integer>> childConceptsOfChosenCluster = new ArrayList<>();

    int entityIndex = 0;
    for(final WebElement concepts : concepts()) {
        final Dimension entitySize = concepts.getSize();
        final Point absolutePosition = concepts.getLocation();

        final int centreX = absolutePosition.x - mapCoordinates.x + entitySize.getWidth() / 2;
        final int centreY = absolutePosition.y - mapCoordinates.y + entitySize.getHeight() / 2;
        final Point centre = new Point(centreX, centreY);

        if(boundariesOfChosenCluster[0][0] <= centre.x && centre.x <= boundariesOfChosenCluster[0][1]
            && boundariesOfChosenCluster[1][0] <= centre.y && centre.y <= boundariesOfChosenCluster[1][1]) {
            childConceptsOfChosenCluster.add(new ImmutablePair<>(concepts, entityIndex));
        }

        entityIndex++;
    }
    return childConceptsOfChosenCluster;
}
 
Example 44
Project: mamute   File: AcceptanceTestBase.java   Source Code and License 6 votes vote down vote up
@BeforeClass
	public static void buildDriver() {
//		System.setProperty("webdriver.chrome.driver",
//				"/home/csokol/programas/chromedriver/chromedriver");
//		driver = new ChromeDriver();
		String localTest = System.getenv("LOCAL_TEST");
		if ("remote".equals(localTest)) {
			driver = ghostDriver();
		} else {
			FirefoxBinary firefox = new FirefoxBinary();
			String display = System.getProperty("DISPLAY", ":0");
			firefox.setEnvironmentProperty("DISPLAY", display);
			driver = new FirefoxDriver();
		}
		driver.manage().window().setSize(new Dimension(1280, 800));
		waitForFirstBodyPresence();
	}
 
Example 45
Project: Selenium-sample-with-Jenkins   File: SimpleTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws Exception
{
    Properties properties = System.getProperties();
    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setBrowserName(properties.getProperty("browserName"));

    driver = new RemoteWebDriver(
            new URL("http://localhost:4444/wd/hub"),
            capabilities
            );
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    driver.manage().window().setSize(new Dimension(width, height));

    baseUrl = "http://www.adventar.org/";
}
 
Example 46
Project: testdroid-samples   File: AbstractAppiumTest.java   Source Code and License 6 votes vote down vote up
protected void swipeUp(Point rootLocation, Dimension rootSize, int duration, float topPad, float bottomPad) {
    int offset = 1;
    int topOffset = Math.round(rootSize.getHeight() * topPad);
    int bottomOffset = Math.round(rootSize.getHeight() * bottomPad);
    Point center = new Point(rootLocation.x + rootSize.getWidth() / 2, rootLocation.y + rootSize.getHeight() / 2);
    logger.debug("Swiping up at" +
            " x1: " + center.getX() +
            " y1:" + (rootLocation.getY() + rootSize.getHeight() - bottomOffset + offset) +
            " x2:" + center.getX() +
            " y2:" + (rootLocation.getY() + topOffset));
    driver.swipe(center.getX(),
            rootLocation.getY() + rootSize.getHeight() - bottomOffset + offset,
            center.getX(),
            rootLocation.getY() + topOffset,
            duration);
}
 
Example 47
Project: testdroid-samples   File: AbstractAppiumTest.java   Source Code and License 6 votes vote down vote up
protected void swipeDown(Point rootLocation, Dimension rootSize, int duration, float topPad, float bottomPad) {
    int offset = 1;
    int topOffset = Math.round(rootSize.getHeight() * topPad);
    int bottomOffset = Math.round(rootSize.getHeight() * bottomPad);
    Point center = new Point(rootLocation.x + rootSize.getWidth() / 2, rootLocation.y + rootSize.getHeight() / 2);
    logger.debug("Swiping down at" +
            " x1: " + center.getX() +
            " y1:" + (rootLocation.getY() + topOffset) +
            " x2:" + center.getX() +
            " y2:" + (rootLocation.getY() + rootSize.getHeight() - bottomOffset + offset));
    driver.swipe(center.getX(),
            (rootLocation.getY() + topOffset),
            center.getX(),
            (rootLocation.getY() + rootSize.getHeight() - bottomOffset + offset),
            duration);
}
 
Example 48
Project: testdroid-samples   File: AbstractAppiumTest.java   Source Code and License 6 votes vote down vote up
protected void swipeLeft(Point rootLocation, Dimension rootSize, int duration, float leftPad, float rightPad) {
    int offset = 1;
    int leftOffset = Math.round(rootSize.getWidth() * leftPad);
    int rightOffset = Math.round(rootSize.getWidth() * rightPad);
    Point center = new Point(rootLocation.x + rootSize.getWidth() / 2, rootLocation.y + rootSize.getHeight() / 2);
    logger.debug("Swiping left at" +
            " x1: " + (rootLocation.getX() + rootSize.getWidth() - rightOffset + offset) +
            " y1:" + center.getY() +
            " x2:" + (rootLocation.getX() + leftOffset) +
            " y2:" + center.getY());
    driver.swipe((rootLocation.getX() + rootSize.getWidth() - rightOffset + offset),
            center.getY(),
            (rootLocation.getX() + leftOffset),
            center.getY(),
            duration);
}
 
Example 49
Project: testdroid-samples   File: AbstractAppiumTest.java   Source Code and License 6 votes vote down vote up
protected void swipeRight(Point rootLocation, Dimension rootSize, int duration, float leftPad, float rightPad) {
    int offset = 1;
    int leftOffset = Math.round(rootSize.getWidth() * leftPad);
    int rightOffset = Math.round(rootSize.getWidth() * rightPad);
    Point center = new Point(rootLocation.x + rootSize.getWidth() / 2, rootLocation.y + rootSize.getHeight() / 2);
    logger.debug("Swiping right at" +
            " x1: " + (rootLocation.getX() + leftOffset) +
            " y1:" + center.getY() +
            " x2:" + (rootLocation.getX() + rootSize.getWidth() - rightOffset + offset) +
            " y2:" + center.getY());
    driver.swipe((rootLocation.getX() + leftOffset),
            center.getY(),
            (rootLocation.getX() + rootSize.getWidth() - rightOffset + offset),
            center.getY(),
            duration);
}
 
Example 50
Project: testdroid-samples   File: TestdroidImageRecognition.java   Source Code and License 6 votes vote down vote up
public void tapAtCoordinates(int x, int y) throws Exception {
    if (automationName.equalsIgnoreCase("selendroid")) {
        selendroidTapAtCoordinate(x, y, 1);
    } else if (platform.equals(PlatformType.ANDROID)){
        Dimension size = driver.manage().window().getSize();
    	if(y > size.getHeight() || x > size.getWidth()){
			log("using adb tap at " + x + ", " + y);
			try{
                //run eclipse from commandline to get path variable correct and find adb
        		Process p = Runtime.getRuntime().exec("adb -s " + udid + " shell input tap " + x + " " + y);
        		p.waitFor();
			} catch (Exception e) {
				log(e.toString());
			}
    	} else {
    		driver.tap(1, x, y, 1);
    	}
    } else {
    	driver.tap(1, x, y, 1);
    }
}
 
Example 51
Project: testdroid-samples   File: TestdroidImageRecognition.java   Source Code and License 6 votes vote down vote up
public void swipeHorizontally(double x_offset, double y_offset, int distance, int swipes, double frequency) throws Exception {

        Dimension size = driver.manage().window().getSize();
        Point middle = new Point(size.getWidth(), size.getHeight());
        Point middleWithOffset = new Point(middle.x * x_offset, middle.y * y_offset);

        int startX = (int) middleWithOffset.x;
        int startY = (int) middleWithOffset.y;
        int endX = startX + distance;
        int endY = startY;


        for (int i = 0; i < swipes; i++) {
            if (PlatformType.IOS.equals(PlatformType.IOS)) {
                iOSSwipe(startX, startY, endX, endY);
            } else {
                androidSwipe(startX, startY, endX, endY);
            }
            sleep(frequency);
        }
        log("Finished executing swipes");
    }
 
Example 52
Project: testdroid-samples   File: TestdroidImageRecognition.java   Source Code and License 6 votes vote down vote up
public void swipeHorizontally(double x_offset, double y_offset, double distance, int swipes, double frequency) throws Exception { //positive distance for swipe right, negative for swipe left.

        Dimension size = driver.manage().window().getSize();
        Point middle = new Point(size.getWidth(), size.getHeight());
        Point middleWithOffset = new Point(middle.x * x_offset, middle.y * y_offset);
        double relative_distance = middle.x * distance;

        int startX = (int) middleWithOffset.x;
        int startY = (int) middleWithOffset.y;
        int endX = startX + (int) Math.floor(relative_distance);
        int endY = startY;


        for (int i = 0; i < swipes; i++) {
            if (PlatformType.IOS.equals(PlatformType.IOS)) {
                iOSSwipe(startX, startY, endX, endY);
            } else {
                androidSwipe(startX, startY, endX, endY);
            }
            sleep(frequency);
        }
        log("Finished executing swipes");
    }
 
Example 53
Project: testdroid-samples   File: TestdroidImageRecognition.java   Source Code and License 6 votes vote down vote up
public void swipeVertically(double x_offset, double y_offset, int distance, int swipes, double frequency) throws Exception {

        Dimension size = driver.manage().window().getSize();
        Point middle = new Point(size.getWidth(), size.getHeight());
        Point middleWithOffset = new Point(middle.x * x_offset, middle.y * y_offset);

        int startX = (int) middleWithOffset.x;
        int startY = (int) middleWithOffset.y;
        int endX = startX;
        int endY = startY + distance;


        for (int i = 0; i < swipes; i++) {
            if (PlatformType.IOS.equals(PlatformType.IOS)) {
                iOSSwipe(startX, startY, endX, endY);
            } else {
                androidSwipe(startX, startY, endX, endY);
            }
            sleep(frequency);
        }
        log("Finished executing swipes");
    }
 
Example 54
Project: testdroid-samples   File: TestdroidImageRecognition.java   Source Code and License 6 votes vote down vote up
public void swipeVertically(double x_offset, double y_offset, double distance, int swipes, double frequency) throws Exception {

        Dimension size = driver.manage().window().getSize();
        Point middle = new Point(size.getWidth(), size.getHeight());
        Point middleWithOffset = new Point(middle.x * x_offset, middle.y * y_offset);
        double relative_distance = middle.y * distance;


        int startX = (int) middleWithOffset.x;
        int startY = (int) middleWithOffset.y;
        int endX = startX;
        int endY = startY + (int) Math.floor(relative_distance);


        for (int i = 0; i < swipes; i++) {
            if (PlatformType.IOS.equals(PlatformType.IOS)) {
                iOSSwipe(startX, startY, endX, endY);
            } else {
                androidSwipe(startX, startY, endX, endY);
            }
            sleep(frequency);
        }
        log("Finished executing swipes");
    }
 
Example 55
Project: testdroid-samples   File: TestdroidImageRecognition.java   Source Code and License 6 votes vote down vote up
public void dragImageToMiddle(String object) throws Exception {
    Dimension size = driver.manage().window().getSize();
    Point middle = new Point(size.getWidth() / 2 - 20, size.getHeight() / 2 + 20);

    ImageRecognitionSettings settings = new ImageRecognitionSettings();
    settings.setRetries(10);
    ImageSearchResult object_image = findImageOnScreen(object, settings);
    assert(object_image.isFound());
    ImageLocation object_image_location = object_image.getImageLocation();

    int startX = (int) object_image_location.getCenter().x;
    int startY = (int) object_image_location.getCenter().y;

    int endX = (int) middle.x;
    int endY = (int) middle.y;

    if (automationName.equalsIgnoreCase("selendroid")) {
        androidSwipe(startX, startY, endX, endY);
    } else {
        iOSSwipe(startX, startY, endX, endY);
    }
}
 
Example 56
Project: testdroid-samples   File: TestdroidImageRecognition.java   Source Code and License 6 votes vote down vote up
public void dragImageToCoordinates(String object, double x_offset, double y_offset) throws Exception {

        Dimension size = driver.manage().window().getSize();
        Point screen = new Point(size.getWidth(), size.getHeight());
        Point swipe_end = new Point(screen.x * x_offset, screen.y * y_offset);

        ImageRecognitionSettings settings = new ImageRecognitionSettings();
        settings.setRetries(10);
        ImageSearchResult object_image = findImageOnScreen(object, settings);
        assert(object_image.isFound());
        ImageLocation object_image_location = object_image.getImageLocation();

        int startX = (int) object_image_location.getCenter().x;
        int startY = (int) object_image_location.getCenter().y;

        int endX = (int) swipe_end.x;
        int endY = (int) swipe_end.y;

        if (automationName.equalsIgnoreCase("selendroid")) {
            androidSwipe(startX, startY, endX, endY);
        } else {
            iOSSwipe(startX, startY, endX, endY);
        }
    }
 
Example 57
Project: testdroid-samples   File: TestdroidImageRecognition.java   Source Code and License 6 votes vote down vote up
/**
 * ======================================================================================
 * OTHER UTILITIES
 * ======================================================================================
 */

//TODO: experimental method
public Point correctAndroidCoordinates(Point appium_coord) throws Exception {

    Dimension appium_dimensions = driver.manage().window().getSize();
    int appium_screenWidth = appium_dimensions.getWidth();
    int appium_screenHeight = appium_dimensions.getHeight();

    Dimension adb_dimension = getScreenSizeADB();
    int adb_screenWidth = adb_dimension.getWidth();
    int adb_screenHeight = adb_dimension.getHeight();

    double x_offset = appium_coord.x / appium_screenWidth;
    double y_offset = appium_coord.y / appium_screenHeight;
    log("x_offset is : " + x_offset);
    log("y_offset is : " + y_offset);

    return new Point(x_offset * adb_screenWidth, y_offset * adb_screenHeight);
}
 
Example 58
Project: atom   File: TestBase.java   Source Code and License 6 votes vote down vote up
@Parameters({ "url", "browserName" })
   @BeforeClass
   public void init(String url, String browserName) {
websiteUrl = url;
// websiteUrl = PropertyLoader.loadProperty("site.url");
gridHubUrl = PropertyLoader.loadProperty("grid2.hub");

browser = new Browser();
browser.setName(browserName);
// browser.setName(PropertyLoader.loadProperty("browser.name"));
browser.setVersion(PropertyLoader.loadProperty("browser.version"));
browser.setPlatform(PropertyLoader.loadProperty("browser.platform"));

String username = PropertyLoader.loadProperty("user.username");
String password = PropertyLoader.loadProperty("user.password");

webDriver = WebDriverFactory.getInstance(gridHubUrl, browser, username, password);

// webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
webDriver.manage().window().setSize(new Dimension(1024, 768));
// webDriver.
   }
 
Example 59
Project: crawljax   File: SerializeTest.java   Source Code and License 6 votes vote down vote up
private OutPutModel createModel() throws IOException {
	ImmutableList<CandidateElementPosition> candidateElements =
	        ImmutableList.of(new CandidateElementPosition("a/b/c", new Point(1, 2),
	                new Dimension(3, 4)));
	State state1 =
	        new State("state1", "http://example.com/a", candidateElements, 1, 1, 1,
	                ImmutableList.of("failedEvent1"));
	State state2 =
	        new State("state2", "http://example.com/b", candidateElements, 1, 1, 1,
	                ImmutableList.of("failedEvent2"));
	ImmutableMap<String, State> states =
	        ImmutableMap.of(state1.getName(), state1, state2.getName(), state2);
	ImmutableList<Edge> edges =
	        ImmutableList.of(new Edge(state1.getName(), state2.getName(), 1, "the link",
	                "id1", "A", "click"));
	return new OutPutModel(states, edges, newStatistics(states.values()),
	        ExitStatus.EXHAUSTED);
}
 
Example 60
Project: desert   File: WebDriverFactory.java   Source Code and License 6 votes vote down vote up
synchronized public static WebDriver getDriver(Capabilities capabilities) {
	if (driver == null) {
		try {
			driver = createLocalDriver(capabilities);
			driver.manage().window().setSize(new Dimension(
				PropertyLoader.loadPropertyInteger("browser.window.width"),
				PropertyLoader.loadPropertyInteger("browser.window.height")
			));
			driver.manage().timeouts().implicitlyWait(
				PropertyLoader.loadPropertyInteger("timeout.implicitlyWait"),
				TimeUnit.MILLISECONDS
			);
			driver.manage().timeouts().pageLoadTimeout(
				PropertyLoader.loadPropertyInteger("timeout.pageLoadTimeout"),
				TimeUnit.MILLISECONDS
			);
		} catch (Exception e) {
			dismissAll();
			e.printStackTrace();
			Assert.fail("Driver setup problem");
		}
	}
	return driver;
}