Best io.appium code snippet using io.appium.java_client.ScreenshotState.ScreenshotComparisonError
ScreenshotState.java
Source:ScreenshotState.java  
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     * () -> {30     * final byte[] srcImage = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);31     * return ImageIO.read(new ByteArrayInputStream(srcImage));32     * }33     * </code>34     * or35     * <code>36     * () -> {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}...ScreenshotStateTests.java
Source:ScreenshotStateTests.java  
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}...ScreenshotState.ScreenshotComparisonError
Using AI Code Generation
1import io.appium.java_client.ScreenshotState.ScreenshotComparisonError;2import io.appium.java_client.ScreenshotState.ScreenshotComparisonError;3import io.appium.java_client.ScreenshotState.ScreenshotComparisonError;4import io.appium.java_client.ScreenshotState.ScreenshotComparisonError;5import io.appium.java_client.ScreenshotState.ScreenshotComparisonError;6import io.appium.java_client.ScreenshotState.ScreenshotComparisonError;7import io.appium.java_client.ScreenshotState.ScreenshotComparisonError;8import io.appium.java_client.ScreenshotState.ScreenshotComparisonError;9import io.appium.java_client.ScreenshotState.ScreenshotComparisonError;10import io.appium.java_client.ScreenshotState.ScreenshotComparisonError;11import io.appium.java_client.ScreenshotState.ScreenshotComparisonError;12import io.appium.java_client.ScreenshotState.ScreenshotComparisonError;13import io.appium.java_client.ScreenshotState.ScreenshotComparisonError;14import io.appium.java_client.ScreenshotState.ScreenshotComparisonError;ScreenshotState.ScreenshotComparisonError
Using AI Code Generation
1import io.appium.java_client.ScreenshotState;2import io.appium.java_client.ScreenshotState.ScreenshotComparisonError;3import io.appium.java_client.ScreenshotState;4import io.appium.java_client.ScreenshotState.ScreenshotComparisonError;5import io.appium.java_client.ScreenshotState;6import io.appium.java_client.ScreenshotState.ScreenshotComparisonError;7import io.appium.java_client.ScreenshotState;8import io.appium.java_client.ScreenshotState.ScreenshotComparisonError;9import io.appium.java_client.ScreenshotState;10import io.appium.java_client.ScreenshotState.ScreenshotComparisonError;11import io.appium.java_client.ScreenshotState;12import io.appium.java_client.ScreenshotState.ScreenshotComparisonError;13import io.appium.java_client.ScreenshotState;14import io.appium.java_client.ScreenshotState.ScreenshotComparisonError;15import io.appium.java_client.ScreenshotState;16import io.appium.java_client.ScreenshotState.ScreenshotComparisonError;17import io.appium.java_client.ScreenshotState;18import io.appium.java_client.ScreenshotState.ScreenshotComparisonError;19import io.appium.java_client.ScreenshotState;20import io.appium.java_client.ScreenshotState.ScreenshotComparisonError;ScreenshotState.ScreenshotComparisonError
Using AI Code Generation
1ScreenshotState.ScreenshotComparisonError error = new ScreenshotState.ScreenshotComparisonError("Screenshot comparison error");2ScreenshotState.ScreenshotComparisonError error = new ScreenshotState.ScreenshotComparisonError("Screenshot comparison error",image1,image2);3ScreenshotState.ScreenshotComparisonError error = new ScreenshotState.ScreenshotComparisonError("Screenshot comparison error",image1,image2,0.1);4ScreenshotState.ScreenshotComparisonError error = new ScreenshotState.ScreenshotComparisonError("Screenshot comparison error",image1,image2,0.1,0.1);5ScreenshotState.ScreenshotComparisonError error = new ScreenshotState.ScreenshotComparisonError("Screenshot comparison error",image1,image2,0.1,0.1,0.1);6ScreenshotState.ScreenshotComparisonError error = new ScreenshotState.ScreenshotComparisonError("Screenshot comparison error",image1,image2,0.1,0.1,0.1,0.1);7ScreenshotState.ScreenshotComparisonError error = new ScreenshotState.ScreenshotComparisonError("Screenshot comparison error",image1,image2,0.1,0.1,0.1,0.1,0.1);8ScreenshotState.ScreenshotComparisonError error = new ScreenshotState.ScreenshotComparisonError("Screenshot comparison error",image1,image2,0.1,0.1,0.1,0.1,0.1,0.1);ScreenshotState.ScreenshotComparisonError
Using AI Code Generation
1import io.appium.java_client.ScreenshotState;2import io.appium.java_client.ScreenshotState.ScreenshotComparisonError;3ScreenshotState state = new ScreenshotState();4state.setScreenshotComparisonError(new ScreenshotComparisonError() {5    public void onComparisonError(String actual, String expected) {6    }7});8var screenshotState = require('io.appium.java_client.ScreenshotState');9var state = new screenshotState();10state.setScreenshotComparisonError(new screenshotState.ScreenshotComparisonError() {11    onComparisonError: function(actual, expected) {12    }13});14from io.appium.java_client import ScreenshotState15state = ScreenshotState()16state.setScreenshotComparisonError(ScreenshotState.ScreenshotComparisonError() {17    def onComparisonError(self, actual, expected):18})19state.setScreenshotComparisonError(ScreenshotState::ScreenshotComparisonError.new {20    def onComparisonError(actual, expected)21})22require_once('io/appium/java_client/ScreenshotState.php');23use io\appium\java_client\ScreenshotState;24use io\appium\java_client\ScreenshotState\ScreenshotComparisonError;25$state = new ScreenshotState();26$state->setScreenshotComparisonError(new ScreenshotComparisonError() {27    function onComparisonError($actual, $expected) {28    }29});30using io.appium.java_client;31using io.appium.java_client.ScreenshotState;32ScreenshotState state = new ScreenshotState();33state.setScreenshotComparisonError(new ScreenshotComparisonError() {34    onComparisonError: (actual, expected) => {35    }ScreenshotState.ScreenshotComparisonError
Using AI Code Generation
1ScreenshotState.ScreenshotComparisonError error = new ScreenshotState.ScreenshotComparisonError("screenshot", "screenshot");2ScreenshotState.ScreenshotComparisonError error = new ScreenshotState.ScreenshotComparisonError("screenshot", "screenshot", "screenshot");3ScreenshotState.ScreenshotComparisonError error = new ScreenshotState.ScreenshotComparisonError("screenshot", "screenshot", "screenshot", "screenshot");4ScreenshotState.ScreenshotComparisonError error = new ScreenshotState.ScreenshotComparisonError("screenshot", "screenshot", "screenshot", "screenshot", "screenshot");5ScreenshotState.ScreenshotComparisonError error = new ScreenshotState.ScreenshotComparisonError("screenshot", "screenshot", "screenshot", "screenshot", "screenshot", "screenshot");6ScreenshotState.ScreenshotComparisonError error = new ScreenshotState.ScreenshotComparisonError("screenshot", "screenshot", "screenshot", "screenshot", "screenshot", "screenshot", "screenshot");7ScreenshotState.ScreenshotComparisonError error = new ScreenshotState.ScreenshotComparisonError("screenshot", "screenshot", "screenshot", "screenshot", "screenshot", "screenshot", "screenshot", "screenshot");ScreenshotState.ScreenshotComparisonError
Using AI Code Generation
1ScreenshotState.ScreenshotComparisonError screenshotComparisonError = new ScreenshotState.ScreenshotComparisonError();2screenshotComparisonError.addScreenShot("test1.png");3screenshotComparisonError.addScreenShot("test2.png");4screenshotComparisonError.addScreenShot("test3.png");5screenshotComparisonError.addScreenShot("test4.png");6screenshotComparisonError.addScreenShot("test5.png");7screenshotComparisonError.addScreenShot("test6.png");8screenshotComparisonError.addScreenShot("test7.png");9screenshotComparisonError.addScreenShot("test8.png");10screenshotComparisonError.addScreenShot("test9.png");11screenshotComparisonError.addScreenShot("test10.png");12screenshotComparisonError.addScreenShot("test11.png");13screenshotComparisonError.addScreenShot("test12.png");14screenshotComparisonError.addScreenShot("test13.png");15screenshotComparisonError.addScreenShot("test14.png");16screenshotComparisonError.addScreenShot("test15.png");17screenshotComparisonError.addScreenShot("test16.png");18screenshotComparisonError.addScreenShot("test17.png");19screenshotComparisonError.addScreenShot("test18.png");20screenshotComparisonError.addScreenShot("test19.png");21screenshotComparisonError.addScreenShot("test20.png");22screenshotComparisonError.addScreenShot("test21.png");23screenshotComparisonError.addScreenShot("test22.png");24screenshotComparisonError.addScreenShot("test23.png");25screenshotComparisonError.addScreenShot("test24.png");26screenshotComparisonError.addScreenShot("test25.png");27screenshotComparisonError.addScreenShot("test26.png");28screenshotComparisonError.addScreenShot("test27.png");29screenshotComparisonError.addScreenShot("test28.png");30screenshotComparisonError.addScreenShot("test29.png");31screenshotComparisonError.addScreenShot("test30.png");32screenshotComparisonError.addScreenShot("test31.png");33screenshotComparisonError.addScreenShot("test32.png");34screenshotComparisonError.addScreenShot("test33.png");35screenshotComparisonError.addScreenShot("test34.png");36screenshotComparisonError.addScreenShot("test35.png");37screenshotComparisonError.addScreenShot("test36.png");38screenshotComparisonError.addScreenShot("test37.png");39screenshotComparisonError.addScreenShot("test38.png");40screenshotComparisonError.addScreenShot("test39.png");41screenshotComparisonError.addScreenShot("test40.pngScreenshotState.ScreenshotComparisonError
Using AI Code Generation
1import io.appium.java_client.ScreenshotState;2ScreenshotState.ScreenshotComparisonError s = new ScreenshotState.ScreenshotComparisonError("message", "expected", "actual", 0.0);3import io.appium.java_client.ScreenshotState;4ScreenshotState.ScreenshotComparisonError s = new ScreenshotState.ScreenshotComparisonError("message", "expected", "actual", 0.0);5import io.appium.java_client.ScreenshotState;6ScreenshotState.ScreenshotComparisonError s = new ScreenshotState.ScreenshotComparisonError("message", "expected", "actual", 0.0);7import io.appium.java_client.ScreenshotState;8ScreenshotState.ScreenshotComparisonError s = new ScreenshotState.ScreenshotComparisonError("message", "expected", "actual", 0.0);9import io.appium.java_client.ScreenshotState;10ScreenshotState.ScreenshotComparisonError s = new ScreenshotState.ScreenshotComparisonError("message", "expected", "actual", 0.0);11import io.appium.java_client.ScreenshotState;12ScreenshotState.ScreenshotComparisonError s = new ScreenshotState.ScreenshotComparisonError("message", "expected", "actual", 0.0);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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
