How to use ScreenshotState.ScreenshotComparisonTimeout class of io.appium.java_client package

Best io.appium code snippet using io.appium.java_client.ScreenshotState.ScreenshotComparisonTimeout

ScreenshotState.java

Source:ScreenshotState.java Github

copy

Full Screen

1package utils;2import io.appium.java_client.ComparesImages;3import static com.google.common.base.Preconditions.checkNotNull;4import static java.util.Optional.ofNullable;5import java.awt.image.BufferedImage;6import java.io.ByteArrayOutputStream;7import java.io.IOException;8import java.time.Duration;9import java.time.LocalDateTime;10import java.util.Base64;11import java.util.function.Function;12import java.util.function.Supplier;13import javax.imageio.ImageIO;14public class ScreenshotState {15 private static final Duration DEFAULT_INTERVAL_MS = Duration.ofMillis(500);16 private BufferedImage previousScreenshot;17 private final Supplier<BufferedImage> stateProvider;18 private final ComparesImages comparator;19 private Duration comparisonInterval = DEFAULT_INTERVAL_MS;20 /**21 * The class constructor accepts two arguments. The first one is image comparator, the second22 * parameter is lambda function, that provides the screenshot of the necessary23 * screen area to be verified for similarity.24 * This lambda method is NOT called upon class creation.25 * One has to invoke {@link #remember()} method in order to call it.26 *27 * <p>Examples of provider function with Appium driver:28 * <code>29 * () -&gt; {30 * final byte[] srcImage = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);31 * return ImageIO.read(new ByteArrayInputStream(srcImage));32 * }33 * </code>34 * or35 * <code>36 * () -&gt; {37 * final byte[] srcImage = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);38 * final BufferedImage screenshot = ImageIO.read(new ByteArrayInputStream(srcImage));39 * final WebElement element = driver.findElement(locator);40 * // Can be simplified in Selenium 3.0+ by using getRect method of WebElement interface41 * final Point elementLocation = element.getLocation();42 * final Dimension elementSize = element.getSize();43 * return screenshot.getSubimage(44 * new Rectangle(elementLocation.x, elementLocation.y, elementSize.width, elementSize.height);45 * }46 * </code>47 *48 * @param comparator image comparator49 * @param stateProvider lambda function, which returns a screenshot for further comparison50 */51 public ScreenshotState(ComparesImages comparator, Supplier<BufferedImage> stateProvider) {52 this.comparator = checkNotNull(comparator);53 this.stateProvider = stateProvider;54 }55 public ScreenshotState(ComparesImages comparator) {56 this(comparator, null);57 }58 /**59 * Gets the interval value in ms between similarity verification rounds in <em>verify*</em> methods.60 *61 * @return current interval value in ms62 */63 public Duration getComparisonInterval() {64 return comparisonInterval;65 }66 /**67 * Sets the interval between similarity verification rounds in <em>verify*</em> methods.68 *69 * @param comparisonInterval interval value. 500 ms by default70 * @return self instance for chaining71 */72 public ScreenshotState setComparisonInterval(Duration comparisonInterval) {73 this.comparisonInterval = comparisonInterval;74 return this;75 }76 /**77 * Call this method to save the initial screenshot state.78 * It is mandatory to call before any <em>verify*</em> method is invoked.79 *80 * @return self instance for chaining81 */82 public ScreenshotState remember() {83 this.previousScreenshot = stateProvider.get();84 return this;85 }86 /**87 * This method allows to pass a custom bitmap for further comparison88 * instead of taking one using screenshot provider function. This might89 * be useful in some advanced cases.90 *91 * @param customInitialState valid bitmap92 * @return self instance for chaining93 */94 public ScreenshotState remember(BufferedImage customInitialState) {95 this.previousScreenshot = checkNotNull(customInitialState);96 return this;97 }98 public static class ScreenshotComparisonError extends RuntimeException {99 private static final long serialVersionUID = -7011854909939194466L;100 ScreenshotComparisonError(Throwable reason) {101 super(reason);102 }103 ScreenshotComparisonError(String message) {104 super(message);105 }106 }107 public static class ScreenshotComparisonTimeout extends RuntimeException {108 private static final long serialVersionUID = 6336247721154252476L;109 private final double currentScore;110 ScreenshotComparisonTimeout(String message, double currentScore) {111 super(message);112 this.currentScore = currentScore;113 }114 public double getCurrentScore() {115 return currentScore;116 }117 }118 private ScreenshotState checkState(Function<Double, Boolean> checkerFunc, Duration timeout) {119 final LocalDateTime started = LocalDateTime.now();120 double score;121 do {122 final BufferedImage currentState = stateProvider.get();123 score = getOverlapScore(ofNullable(this.previousScreenshot)124 .orElseThrow(() -> new ScreenshotComparisonError("Initial screenshot state is not set. "125 + "Nothing to compare")), currentState);126 if (checkerFunc.apply(score)) {127 return this;128 }129 try {130 Thread.sleep(comparisonInterval.toMillis());131 } catch (InterruptedException e) {132 throw new ScreenshotComparisonError(e);133 }134 }135 while (Duration.between(started, LocalDateTime.now()).compareTo(timeout) <= 0);136 throw new ScreenshotComparisonTimeout(137 String.format("Screenshot comparison timed out after %s ms. Actual similarity score: %.5f",138 timeout.toMillis(), score), score);139 }140 /**141 * Verifies whether the state of the screenshot provided by stateProvider lambda function142 * is changed within the given timeout.143 *144 * @param timeout timeout value145 * @param minScore the value in range (0.0, 1.0)146 * @return self instance for chaining147 * @throws ScreenshotComparisonTimeout if the calculated score is still148 * greater or equal to the given score after timeout happens149 * @throws ScreenshotComparisonError if {@link #remember()} method has not been invoked yet150 */151 public ScreenshotState verifyChanged(Duration timeout, double minScore) {152 return checkState((x) -> x < minScore, timeout);153 }154 /**155 * Verifies whether the state of the screenshot provided by stateProvider lambda function156 * is not changed within the given timeout.157 *158 * @param timeout timeout value159 * @param minScore the value in range (0.0, 1.0)160 * @return self instance for chaining161 * @throws ScreenshotComparisonTimeout if the calculated score is still162 * less than the given score after timeout happens163 * @throws ScreenshotComparisonError if {@link #remember()} method has not been invoked yet164 */165 public ScreenshotState verifyNotChanged(Duration timeout, double minScore) {166 return checkState((x) -> x >= minScore, timeout);167 }168 /**169 * Compares two valid java bitmaps and calculates similarity score between them.170 * Both images are expected to be of the same size/resolution. The method171 * implicitly invokes {@link ComparesImages#getImagesSimilarity(byte[], byte[])}.172 *173 * @param refImage reference image174 * @param tplImage template175 * @return similarity score value in range (-1.0, 1.0]. 1.0 is returned if the images are equal176 * @throws ScreenshotComparisonError if provided images are not valid or have177 * different resolution178 */179 public double getOverlapScore(BufferedImage refImage, BufferedImage tplImage) {180 try (ByteArrayOutputStream img1 = new ByteArrayOutputStream();181 ByteArrayOutputStream img2 = new ByteArrayOutputStream()) {182 ImageIO.write(refImage, "png", img1);183 ImageIO.write(tplImage, "png", img2);184 return comparator185 .getImagesSimilarity(Base64.getEncoder().encode(img1.toByteArray()),186 Base64.getEncoder().encode(img2.toByteArray()))187 .getScore();188 } catch (IOException e) {189 throw new ScreenshotComparisonError(e);190 }191 }192}...

Full Screen

Full Screen

ScreenshotStateTests.java

Source:ScreenshotStateTests.java Github

copy

Full Screen

1package io.appium.java_client.utils;2import static org.hamcrest.CoreMatchers.is;3import static org.hamcrest.CoreMatchers.notNullValue;4import static org.hamcrest.Matchers.greaterThanOrEqualTo;5import static org.hamcrest.Matchers.lessThan;6import static org.junit.Assert.assertThat;7import io.appium.java_client.ScreenshotState;8import org.junit.Before;9import org.junit.Test;10import java.awt.Color;11import java.awt.Graphics2D;12import java.awt.geom.Rectangle2D;13import java.awt.image.BufferedImage;14import java.time.Duration;15import java.util.Random;16public class ScreenshotStateTests {17 private static final Random rand = new Random();18 private static final Duration ONE_SECOND = Duration.ofSeconds(1);19 private static final double MAX_SCORE = 0.999;20 private ImagesGenerator randomImageOfStaticSize;21 private ImagesGenerator randomImageOfRandomSize;22 private ImagesGenerator staticImage;23 private static class ImagesGenerator {24 private boolean isRandom;25 private boolean isSizeStatic;26 private static final int DEFAULT_WIDTH = 100;27 private static final int MIN_WIDTH = 50;28 private static final int DEFAULT_HEIGHT = 100;29 private static final int MIN_HEIGHT = 50;30 ImagesGenerator(boolean isRandom, boolean isSizeStatic) {31 this.isRandom = isRandom;32 this.isSizeStatic = isSizeStatic;33 }34 private BufferedImage generate() {35 final int width = isSizeStatic ? DEFAULT_WIDTH : MIN_WIDTH + rand.nextInt(DEFAULT_WIDTH);36 final int height = isSizeStatic ? DEFAULT_HEIGHT : MIN_HEIGHT + rand.nextInt(DEFAULT_HEIGHT);37 final BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);38 final Graphics2D g2 = result.createGraphics();39 try {40 g2.setColor(isRandom ? new Color(rand.nextInt(256), rand.nextInt(256),41 rand.nextInt(256)) : Color.red);42 g2.fill(new Rectangle2D.Float(0, 0,43 isRandom ? rand.nextInt(DEFAULT_WIDTH) : DEFAULT_WIDTH / 2,44 isRandom ? rand.nextInt(DEFAULT_HEIGHT) : DEFAULT_HEIGHT / 2));45 } finally {46 g2.dispose();47 }48 return result;49 }50 }51 @Before52 public void setUp() {53 randomImageOfStaticSize = new ImagesGenerator(true, true);54 randomImageOfRandomSize = new ImagesGenerator(true, false);55 staticImage = new ImagesGenerator(false, true);56 }57 //region Positive Tests58 @Test59 public void testBasicComparisonScenario() {60 final ScreenshotState currentState = new ScreenshotState(staticImage::generate)61 .remember();62 assertThat(currentState.verifyNotChanged(ONE_SECOND, MAX_SCORE), is(notNullValue()));63 }64 @Test65 public void testChangedImageVerification() {66 final ScreenshotState currentState = new ScreenshotState(randomImageOfStaticSize::generate)67 .remember();68 assertThat(currentState.verifyChanged(ONE_SECOND, MAX_SCORE), is(notNullValue()));69 }70 @Test71 public void testChangedImageVerificationWithDifferentSize() {72 final ScreenshotState currentState = new ScreenshotState(randomImageOfRandomSize::generate)73 .remember();74 assertThat(currentState.verifyChanged(ONE_SECOND, MAX_SCORE,75 ScreenshotState.ResizeMode.REFERENCE_TO_TEMPLATE_RESOLUTION), is(notNullValue()));76 }77 @Test78 public void testChangedImageVerificationWithCustomRememberedImage() {79 final ScreenshotState currentState = new ScreenshotState(randomImageOfRandomSize::generate)80 .remember(randomImageOfRandomSize.generate());81 assertThat(currentState.verifyChanged(ONE_SECOND, MAX_SCORE,82 ScreenshotState.ResizeMode.REFERENCE_TO_TEMPLATE_RESOLUTION), is(notNullValue()));83 }84 @Test85 public void testChangedImageVerificationWithCustomInterval() {86 final ScreenshotState currentState = new ScreenshotState(randomImageOfRandomSize::generate)87 .setComparisonInterval(Duration.ofMillis(100)).remember();88 assertThat(currentState.verifyChanged(ONE_SECOND, MAX_SCORE,89 ScreenshotState.ResizeMode.REFERENCE_TO_TEMPLATE_RESOLUTION), is(notNullValue()));90 }91 @Test92 public void testDirectOverlapScoreCalculation() {93 final BufferedImage anImage = staticImage.generate();94 final double score = ScreenshotState.getOverlapScore(anImage, anImage);95 assertThat(score, is(greaterThanOrEqualTo(MAX_SCORE)));96 }97 @Test98 public void testScreenshotComparisonUsingStaticMethod() {99 BufferedImage img1 = randomImageOfStaticSize.generate();100 // ImageIO.write(img1, "png", new File("img1.png"));101 BufferedImage img2 = randomImageOfStaticSize.generate();102 // ImageIO.write(img2, "png", new File("img2.png"));103 assertThat(ScreenshotState.getOverlapScore(img1, img2), is(lessThan(MAX_SCORE)));104 }105 //endregion106 //region Negative Tests107 @Test(expected = ScreenshotState.ScreenshotComparisonError.class)108 public void testDifferentSizeOfTemplates() {109 new ScreenshotState(randomImageOfRandomSize::generate).remember().verifyChanged(ONE_SECOND, MAX_SCORE);110 }111 @Test(expected = NullPointerException.class)112 public void testInvalidProvider() {113 new ScreenshotState(() -> null).remember();114 }115 @Test(expected = ScreenshotState.ScreenshotComparisonTimeout.class)116 public void testImagesComparisonExpectationFailed() {117 new ScreenshotState(randomImageOfStaticSize::generate).remember().verifyNotChanged(ONE_SECOND, MAX_SCORE);118 }119 @Test(expected = ScreenshotState.ScreenshotComparisonTimeout.class)120 public void testImagesComparisonExpectationFailed2() {121 new ScreenshotState(staticImage::generate).remember().verifyChanged(ONE_SECOND, MAX_SCORE);122 }123 @Test(expected = ScreenshotState.ScreenshotComparisonError.class)124 public void testScreenshotInitialStateHasNotBeenRemembered() {125 new ScreenshotState(staticImage::generate).verifyNotChanged(ONE_SECOND, MAX_SCORE);126 }127 //endregion128}...

Full Screen

Full Screen

ScreenshotState.ScreenshotComparisonTimeout

Using AI Code Generation

copy

Full Screen

1import java.io.File;2import java.io.IOException;3import java.net.URL;4import org.openqa.selenium.OutputType;5import org.openqa.selenium.TakesScreenshot;6import org.openqa.selenium.remote.DesiredCapabilities;7import io.appium.java_client.AppiumDriver;8import io.appium.java_client.MobileElement;9import io.appium.java_client.android.AndroidDriver;10import io.appium.java_client.android.AndroidElement;11import io.appium.java_client.android.ScreenshotState;12import io.appium.java_client.android.ScreenshotState.ScreenshotComparisonTimeout;13import io.appium.java_client.android.nativekey.AndroidKey;14import io.appium.java_client.android.nativekey.KeyEvent;15import io.appium.java_client.remote.MobileCapabilityType;16public class ScreenshotStateTest {17 private static AppiumDriver<MobileElement> driver;18 private static DesiredCapabilities capabilities = new DesiredCapabilities();19 public static void main(String[] args) throws IOException {20 capabilities.setCapability("deviceName", "emulator-5554");21 capabilities.setCapability("platformName", "Android");22 capabilities.setCapability("appPackage", "com.android.calculator2");23 capabilities.setCapability("appActivity", "com.android.calculator2.Calculator");24 capabilities.setCapability("noReset", true);25 capabilities.setCapability("automationName", "UiAutomator2");26 capabilities.setCapability("adbExecTimeout", 500000);

Full Screen

Full Screen

ScreenshotState.ScreenshotComparisonTimeout

Using AI Code Generation

copy

Full Screen

1ScreenshotState.ScreenshotComparisonTimeout screenshotComparisonTimeout = new ScreenshotState.ScreenshotComparisonTimeout(5000, 200);2ScreenshotState screenshotState = new ScreenshotState(screenshotComparisonTimeout);3screenshotState.setScreenshotComparisonTimeout(screenshotComparisonTimeout);4ScreenshotState.ScreenshotComparisonTimeout screenshotComparisonTimeout = screenshotState.getScreenshotComparisonTimeout();5ScreenshotState.ScreenshotComparisonTimeout screenshotComparisonTimeout = screenshotState.getScreenshotComparisonTimeout();6ScreenshotState screenshotState = new ScreenshotState();7screenshotState.getScreenshotComparisonTimeout();8ScreenshotState screenshotState = new ScreenshotState();9screenshotState.getScreenshotComparisonTimeout();10ScreenshotState screenshotState = new ScreenshotState();11screenshotState.getScreenshotComparisonTimeout();12ScreenshotState screenshotState = new ScreenshotState();13screenshotState.getScreenshotComparisonTimeout();14ScreenshotState screenshotState = new ScreenshotState();15screenshotState.getScreenshotComparisonTimeout();

Full Screen

Full Screen

ScreenshotState.ScreenshotComparisonTimeout

Using AI Code Generation

copy

Full Screen

1ScreenshotState.ScreenshotComparisonTimeout screenshotComparisonTimeout = new ScreenshotState.ScreenshotComparisonTimeout();2screenshotComparisonTimeout.setScreenshotComparisonTimeout(20000);3ScreenshotState.ScreenshotComparisonTolerance screenshotComparisonTolerance = new ScreenshotState.ScreenshotComparisonTolerance();4screenshotComparisonTolerance.setScreenshotComparisonTolerance(0.1);5ScreenshotState screenshotState = new ScreenshotState();6screenshotState.setScreenshotComparisonTimeout(screenshotComparisonTimeout);7screenshotState.setScreenshotComparisonTolerance(screenshotComparisonTolerance);8AppiumDriver driver = new AppiumDriver();9driver.setScreenshotState(screenshotState);10AppiumDriver driver = new AppiumDriver();11driver.getScreenshotState();12AppiumDriver driver = new AppiumDriver();13driver.getScreenshotState().getScreenshotComparisonTimeout().getScreenshotComparisonTimeout();14AppiumDriver driver = new AppiumDriver();15driver.getScreenshotState().getScreenshotComparisonTolerance().getScreenshotComparisonTolerance();16AppiumDriver driver = new AppiumDriver();17driver.getScreenshotState().getScreenshotComparisonTolerance().getScreenshotComparisonTolerance();18AppiumDriver driver = new AppiumDriver();19driver.getScreenshotState().getScreenshotComparisonTimeout().getScreenshotComparisonTimeout();20AppiumDriver driver = new AppiumDriver();21driver.getScreenshotState().getScreenshotComparisonTolerance().getScreenshotComparisonTolerance();

Full Screen

Full Screen

ScreenshotState.ScreenshotComparisonTimeout

Using AI Code Generation

copy

Full Screen

1import io.appium.java_client.ScreenshotState.ScreenshotComparisonTimeout;2ScreenshotComparisonTimeout screenshotComparisonTimeout = ScreenshotComparisonTimeout.of(Duration.ofSeconds(5));3import io.appium.java_client.ScreenshotState.ScreenshotComparisonTimeout;4ScreenshotComparisonTimeout screenshotComparisonTimeout = ScreenshotComparisonTimeout.of(Duration.ofSeconds(5));5import io.appium.java_client.ScreenshotState.ScreenshotComparisonTimeout;6ScreenshotComparisonTimeout screenshotComparisonTimeout = ScreenshotComparisonTimeout.of(Duration.ofSeconds(5));7import io.appium.java_client.ScreenshotState.ScreenshotComparisonTimeout;8ScreenshotComparisonTimeout screenshotComparisonTimeout = ScreenshotComparisonTimeout.of(Duration.ofSeconds(5));9import io.appium.java_client.ScreenshotState.ScreenshotComparisonTimeout;10ScreenshotComparisonTimeout screenshotComparisonTimeout = ScreenshotComparisonTimeout.of(Duration.ofSeconds(5));11import io.appium.java_client.ScreenshotState.ScreenshotComparisonTimeout;12ScreenshotComparisonTimeout screenshotComparisonTimeout = ScreenshotComparisonTimeout.of(Duration.ofSeconds(5));13import io.appium.java_client.ScreenshotState.ScreenshotComparisonTimeout;14ScreenshotComparisonTimeout screenshotComparisonTimeout = ScreenshotComparisonTimeout.of(Duration.ofSeconds(5));15import io.appium.java_client.ScreenshotState.ScreenshotComparisonTimeout;16ScreenshotComparisonTimeout screenshotComparisonTimeout = ScreenshotComparisonTimeout.of(Duration.ofSeconds(5));17import io.appium.java_client.ScreenshotState.ScreenshotComparisonTimeout;18ScreenshotComparisonTimeout screenshotComparisonTimeout = ScreenshotComparisonTimeout.of(Duration.ofSeconds(5));19import io

Full Screen

Full Screen

ScreenshotState.ScreenshotComparisonTimeout

Using AI Code Generation

copy

Full Screen

1driver.getScreenshotState().setScreenshotComparisonTimeout(5000);2driver.getScreenshotState().getScreenshotComparisonTimeout();3driver.setScreenshotComparisonTimeout(5000);4driver.getScreenshotComparisonTimeout();5driver.set_screenshot_comparison_timeout(5000);6driver.get_screenshot_comparison_timeout();7driver.SetScreenshotComparisonTimeout(5000)8driver.GetScreenshotComparisonTimeout()9driver.getScreenshotComparisonTimeout()

Full Screen

Full Screen

ScreenshotState.ScreenshotComparisonTimeout

Using AI Code Generation

copy

Full Screen

1ScreenshotState.ScreenshotComparisonTimeout timeout = new ScreenshotState.ScreenshotComparisonTimeout(10, TimeUnit.SECONDS);2ScreenshotState screenshotState = new ScreenshotState(timeout);3((AppiumDriver)driver).setScreenshotState(screenshotState);4timeout = ScreenshotState.ScreenshotComparisonTimeout(10, TimeUnit.SECONDS)5screenshot_state = ScreenshotState(timeout)6self.driver.set_screenshot_state(screenshot_state)7timeout = ScreenshotState::ScreenshotComparisonTimeout.new(10, TimeUnit::SECONDS)8screenshot_state = ScreenshotState.new(timeout)9driver.set_screenshot_state(screenshot_state)

Full Screen

Full Screen

ScreenshotState.ScreenshotComparisonTimeout

Using AI Code Generation

copy

Full Screen

1public void testAppium() throws MalformedURLException, InterruptedException {2 DesiredCapabilities caps = new DesiredCapabilities();3 caps.setCapability("deviceName", "Pixel 3a XL API 29");4 caps.setCapability("platformName", "Android");5 caps.setCapability("platformVersion", "10.0");6 caps.setCapability("appPackage", "com.android.calculator2");7 caps.setCapability("appActivity", "com.android.calculator2.Calculator");8 caps.setCapability("noReset", "true");

Full Screen

Full Screen

ScreenshotState.ScreenshotComparisonTimeout

Using AI Code Generation

copy

Full Screen

1ScreenshotState.ScreenshotComparisonTimeout();2screenshotComparisonTimeout.getTimeout());3ScreenshotState.ScreenshotComparisonTimeout();4screenshotComparisonTimeout.getTimeout());5ScreenshotState.ScreenshotComparisonTimeout();6screenshotComparisonTimeout.getTimeout());7ScreenshotState.ScreenshotComparisonTimeout();8screenshotComparisonTimeout.getTimeout());9ScreenshotState.ScreenshotComparisonTimeout();10screenshotComparisonTimeout.getTimeout());11ScreenshotState.ScreenshotComparisonTimeout();12screenshotComparisonTimeout.getTimeout());13ScreenshotState.ScreenshotComparisonTimeout();

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run io.appium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used methods in ScreenshotState.ScreenshotComparisonTimeout

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful