ru.yandex.qatools.ashot.Screenshot Java Examples

The following examples show how to use ru.yandex.qatools.ashot.Screenshot. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FileSystemBaselineRepository.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Override
public Optional<Screenshot> getBaseline(String baselineName) throws IOException
{
    File baselineFile = new File(baselineFolderResolver.get(), appendExtension(baselineName));
    if (!baselineFile.exists())
    {
        LOGGER.warn("Unable to find a baseline at the path: {}", baselineFile);
        return Optional.empty();
    }
    BufferedImage baselineImage = ImageIO.read(baselineFile);
    if (baselineImage == null)
    {
        throw new ResourceLoadException(
                "The baseline at the path '" + baselineFile + "' is broken or has unsupported format");
    }
    return Optional.of(new Screenshot(baselineImage));
}
 
Example #2
Source File: AshotScreenshotProviderTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
private void verifyScreesnhot(Screenshot screenshot, Screenshot actual) throws IOException
{
    assertSame(actual, screenshot);
    BufferedImage afterCropping = loadImage("after_cropping");
    assertThat(actual.getImage(), ImageTool.equalImage(afterCropping));
    verify(searchActions).findElements(A_LOCATOR);
    verify(searchActions).findElements(B_LOCATOR);
    verify(searchActions).findElements(ELEMENT_LOCATOR);
    verify(searchActions).findElements(AREA_LOCATOR);
    BufferedImage elementCropped = loadImage("element_cropped");
    InOrder ordered = Mockito.inOrder(screenshotDebugger);
    ordered.verify(screenshotDebugger).debug(eq(AshotScreenshotProvider.class), eq("cropped_by_ELEMENT"),
            equalTo(elementCropped));
    ordered.verify(screenshotDebugger).debug(eq(AshotScreenshotProvider.class), eq("cropped_by_AREA"),
            equalTo(afterCropping));
}
 
Example #3
Source File: AshotScreenshotProviderTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
void shouldTakeScreenshotAndProcessIgnoredElements() throws IOException
{
    SearchContext searchContext = mock(SearchContext.class);
    VisualCheck visualCheck = mockSearchContext(searchContext);
    visualCheck.setElementsToIgnore(STEP_LEVEL_STRATEGIES);
    screenshotProvider.setIgnoreStrategies(STRATEGIES);
    Screenshot screenshot = new Screenshot(loadImage("original"));
    WebDriver driver = mock(WebDriver.class);
    when(webDriverProvider.get()).thenReturn(driver);
    WebElement element = mock(WebElement.class);
    when(searchActions.findElements(ELEMENT_LOCATOR)).thenReturn(List.of(element));
    when(coordsProvider.ofElement(driver, element)).thenReturn(new Coords(704, 89, 272, 201));
    WebElement area = mock(WebElement.class);
    when(searchActions.findElements(AREA_LOCATOR)).thenReturn(List.of(area));
    when(coordsProvider.ofElement(driver, area)).thenReturn(new Coords(270, 311, 1139, 52));
    when(screenshotTaker.takeAshotScreenshot(searchContext, Optional.empty())).thenReturn(screenshot);

    Screenshot actual = screenshotProvider.take(visualCheck);

    verifyScreesnhot(screenshot, actual);
}
 
Example #4
Source File: VisualTestingEngineTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
void shouldReturnVisualCheckResultWithBaselineAndCheckpoint() throws IOException
{
    when(baselineRepository.getBaseline(BASELINE)).thenReturn(Optional.of(new Screenshot(loadImage(BASELINE))));
    VisualCheck visualCheck = createVisualCheck(VisualActionType.COMPARE_AGAINST);
    mockGetCheckpointScreenshot(visualCheck, BASELINE);
    VisualCheckResult checkResult = visualTestingEngine.compareAgainst(visualCheck);
    Assertions.assertAll(
        () -> assertEquals(BASELINE_BASE64, checkResult.getBaseline()),
        () -> assertEquals(BASELINE, checkResult.getBaselineName()),
        () -> assertEquals(BASELINE_BASE64, checkResult.getCheckpoint()),
        () -> assertEquals(VisualActionType.COMPARE_AGAINST, checkResult.getActionType()),
        () -> assertEquals(BASELINE_BASE64, checkResult.getDiff()),
        () -> assertTrue(checkResult.isPassed()));
    verify(baselineRepository, never()).saveBaseline(any(), any());
}
 
Example #5
Source File: VisualTestingEngineTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
void shouldReturnVisualCheckResultWithDiffBaselineAndCheckpoint() throws IOException
{
    when(baselineRepository.getBaseline(BASELINE)).thenReturn(Optional.of(new Screenshot(loadImage(BASELINE))));
    VisualCheck visualCheck = createVisualCheck(VisualActionType.COMPARE_AGAINST);
    mockGetCheckpointScreenshot(visualCheck);
    VisualCheckResult checkResult = visualTestingEngine.compareAgainst(visualCheck);
    Assertions.assertAll(
        () -> assertEquals(BASELINE_BASE64, checkResult.getBaseline()),
        () -> assertEquals(BASELINE, checkResult.getBaselineName()),
        () -> assertEquals(CHECKPOINT_BASE64, checkResult.getCheckpoint()),
        () -> assertEquals(VisualActionType.COMPARE_AGAINST, checkResult.getActionType()),
        () -> assertEquals(DIFF_BASE64, checkResult.getDiff()),
        () -> assertFalse(checkResult.isPassed()));
    verify(baselineRepository, never()).saveBaseline(any(), any());
}
 
Example #6
Source File: VisualTestingEngine.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Override
public VisualCheckResult compareAgainst(VisualCheck visualCheck) throws IOException
{
    VisualCheckResult comparisonResult = new VisualCheckResult(visualCheck);
    Screenshot checkpoint = getCheckpointScreenshot(visualCheck);
    comparisonResult.setCheckpoint(imageToBase64(checkpoint.getImage()));
    Optional<Screenshot> baseline = baselineRepository.getBaseline(visualCheck.getBaselineName());
    Screenshot baselineScreenshot;
    if (baseline.isPresent())
    {
        baselineScreenshot = baseline.get();
        comparisonResult.setBaseline(imageToBase64(baselineScreenshot.getImage()));
    }
    else
    {
        baselineScreenshot = EMPTY_SCREENSHOT;
    }
    ImageDiffer differ = new ImageDiffer().withDiffMarkupPolicy(new PointsMarkupPolicy().withDiffColor(DIFF_COLOR));
    ImageDiff diff = differ.makeDiff(baselineScreenshot, checkpoint);

    comparisonResult.setPassed(!diff.hasDiff());
    comparisonResult.setDiff(imageToBase64(diff.getMarkedImage()));
    if (overrideBaselines)
    {
        baselineRepository.saveBaseline(checkpoint, visualCheck.getBaselineName());
    }
    return comparisonResult;
}
 
Example #7
Source File: FileSystemBaselineRepositoryTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Test
void shouldSaveBaselineIntoFolder(@TempDir File folder) throws IOException
{
    fileSystemBaselineRepository.setBaselinesFolder(folder);
    Screenshot screenshot = mock(Screenshot.class);
    BufferedImage baseline = loadBaseline();
    when(screenshot.getImage()).thenReturn(baseline);
    fileSystemBaselineRepository.saveBaseline(screenshot, BASELINE);
    File baselineFile = new File(folder, BASELINE + DEFAULT_EXTENSION);
    assertThat(baselineFile, FileMatchers.anExistingFile());
    assertThat(logger.getLoggingEvents(), is(List.of(info("Baseline saved to: {}",
            baselineFile.getAbsolutePath()))));
    assertThat(ImageIO.read(baselineFile), ImageTool.equalImage(baseline));
}
 
Example #8
Source File: VisualTestingEngine.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Override
public VisualCheckResult establish(VisualCheck visualCheck) throws IOException
{
    VisualCheckResult comparisonResult = new VisualCheckResult(visualCheck);
    Screenshot checkpoint = getCheckpointScreenshot(visualCheck);
    comparisonResult.setCheckpoint(imageToBase64(checkpoint.getImage()));
    baselineRepository.saveBaseline(checkpoint, visualCheck.getBaselineName());
    return comparisonResult;
}
 
Example #9
Source File: VisualTestingEngineTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Test
void shouldOverrideBaselinesIfPropertySet() throws IOException
{
    visualTestingEngine.setOverrideBaselines(true);
    when(baselineRepository.getBaseline(BASELINE)).thenReturn(Optional.of(new Screenshot(loadImage(BASELINE))));
    VisualCheck visualCheck = createVisualCheck(VisualActionType.COMPARE_AGAINST);
    BufferedImage finalImage = mockGetCheckpointScreenshot(visualCheck);
    visualTestingEngine.compareAgainst(visualCheck);
    verify(baselineRepository).saveBaseline(argThat(s -> finalImage.equals(s.getImage())), eq(BASELINE));
}
 
Example #10
Source File: VisualTestingEngineTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
private BufferedImage mockGetCheckpointScreenshot(VisualCheck visualCheck, String imageName) throws IOException
{
    BufferedImage image = loadImage(imageName);
    Screenshot screenshot = new Screenshot(image);
    when(screenshotProvider.take(visualCheck)).thenReturn(screenshot);
    return image;
}
 
Example #11
Source File: AshotScreenshotProvider.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Override
public Screenshot take(VisualCheck visualCheck)
{
    Screenshot screenshot = screenshotTaker.takeAshotScreenshot(
            visualCheck.getSearchContext(), visualCheck.getScreenshotConfiguration());
    BufferedImage original = screenshot.getImage();
    Map<IgnoreStrategy, Set<By>> stepLevelElementsToIgnore = visualCheck.getElementsToIgnore();
    for (Map.Entry<IgnoreStrategy, Set<By>> strategy : ignoreStrategies.entrySet())
    {
        IgnoreStrategy cropStrategy = strategy.getKey();
        Set<Coords> ignore = Stream.concat(
                getLocatorsStream(strategy.getValue()),
                getLocatorsStream(stepLevelElementsToIgnore.get(cropStrategy)))
                .distinct()
                .map(searchActions::findElements)
                .flatMap(Collection::stream)
                .map(e -> coordsProvider.ofElement(webDriverProvider.get(), e))
                .collect(Collectors.toSet());
        if (ignore.isEmpty())
        {
            continue;
        }
        original = cropStrategy.crop(original, ignore);
        screenshotDebugger.debug(this.getClass(), "cropped_by_" + cropStrategy, original);
    }
    screenshot.setImage(original);
    return screenshot;
}
 
Example #12
Source File: AshotScreenshotProviderTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Test
void shouldTakeScreenshot()
{
    SearchContext searchContext = mock(SearchContext.class);
    VisualCheck visualCheck = mockSearchContext(searchContext);
    Screenshot screenshot = mock(Screenshot.class);
    when(searchActions.findElements(A_LOCATOR)).thenReturn(List.of());
    when(screenshotTaker.takeAshotScreenshot(searchContext, Optional.empty())).thenReturn(screenshot);
    screenshotProvider.setIgnoreStrategies(Map.of(IgnoreStrategy.AREA, Set.of(A_LOCATOR)));
    assertSame(screenshot, screenshotProvider.take(visualCheck));
    verifyNoInteractions(screenshotDebugger);
}
 
Example #13
Source File: FileSystemBaselineRepository.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Override
public void saveBaseline(Screenshot toSave, String baselineName) throws IOException
{
    File baselineToSave = new File(baselineFolderResolver.get(), baselineName);
    ImageUtils.writeAsPng(toSave.getImage(), baselineToSave);
    LOGGER.info("Baseline saved to: {}", appendExtension(baselineToSave.getAbsolutePath()));
}
 
Example #14
Source File: ImageVisualTestingServiceTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
private BufferedImage mockScreenshot(ApplitoolsVisualCheck applitoolsVisualCheck)
{
    Screenshot screenshot = mock(Screenshot.class);
    when(screenshotProvider.take(applitoolsVisualCheck)).thenReturn(screenshot);
    BufferedImage image = mock(BufferedImage.class);
    when(screenshot.getImage()).thenReturn(image);
    return image;
}
 
Example #15
Source File: SeleniumDriver.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 5 votes vote down vote up
private File getScreenShotFromAShot(WebDriver driver, ShootingStrategy strategy) throws IOException {
    File file = File.createTempFile("screenshot", ".png");
    Screenshot screenshot = new AShot().shootingStrategy(strategy)
            .takeScreenshot(driver);
    ImageIO.write(screenshot.getImage(), "png", file);
    return file;
}
 
Example #16
Source File: TakeScreenShotSeleniumLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenGoogleIsLoaded_thenCaptureLogo() throws IOException {
    WebElement logo = driver.findElement(By.id("hplogo"));

    Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000))
        .coordsProvider(new WebDriverCoordsProvider())
        .takeScreenshot(driver, logo);

    ImageIO.write(screenshot.getImage(), "jpg", new File(resolveTestResourcePath("google-logo.png")));
    assertTrue(new File(resolveTestResourcePath("google-logo.png")).exists());
}
 
Example #17
Source File: VisualTestingEngine.java    From vividus with Apache License 2.0 4 votes vote down vote up
private Screenshot getCheckpointScreenshot(VisualCheck visualCheck)
{
    return screenshotProvider.take(visualCheck);
}
 
Example #18
Source File: AssertElementImage.java    From opentest with MIT License 4 votes vote down vote up
/**
 * Capture the image of the target HTML element.
 * @param targetLocator The locator of the HTML element to capture.
 * @param ignoredElements The HTML elements ignored from the comparison.
 * @param scaleFactor For retina displays, this has to be set to 2.
 * @param ignoredPixelsColor The color that will be used to obscure the
 * HTML elements that are ignored from the comparison.
 * @return The image of the HTML element.
 */
private BufferedImage captureImage(By targetLocator, By[] ignoredElements, Double scaleFactor, Color ignoredPixelsColor) {
    WebElement targetElement = this.getElement(targetLocator);
    ShootingStrategy shootingStrategy = ShootingStrategies.viewportPasting(ShootingStrategies.scaling(scaleFactor.floatValue()), 100);
    AShot ashot = new AShot()
            .coordsProvider(new WebDriverCoordsProvider())
            .shootingStrategy(shootingStrategy);

    // Hide scroll bars, so they don't impact the captured image
    JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
    Object overflowValue = jsExecutor.executeScript("return document.querySelector('html').style.overflow");
    if (!(overflowValue instanceof String)) {
        overflowValue = "initial";
    }
    jsExecutor.executeScript("document.querySelector('html').style.overflow = 'hidden'");

    Screenshot screenshot = ashot.takeScreenshot(driver, targetElement);
    BufferedImage capturedImage = screenshot.getImage();

    jsExecutor.executeScript(String.format("document.querySelector('html').style.overflow = '%s';", overflowValue));

    for (By by : ignoredElements) {
        Point targetElemLocation = targetElement.getLocation();

        WebElement ignoredElement = this.getElement(by);
        Point ignoredElementLocation = ignoredElement.getLocation();

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

        int relativeX = ignoredElementLocation.getX() - targetElemLocation.getX();
        int relativeY = ignoredElementLocation.getY() - targetElemLocation.getY();

        for (int xCoord = relativeX; xCoord < relativeX + width; xCoord++) {
            for (int yCoord = relativeY; yCoord < relativeY + height; yCoord++) {
                capturedImage.setRGB(xCoord, yCoord, ignoredPixelsColor.getRGB());
            }
        }
    }

    return capturedImage;
}
 
Example #19
Source File: IBaselineRepository.java    From vividus with Apache License 2.0 votes vote down vote up
Optional<Screenshot> getBaseline(String baselineName) throws IOException; 
Example #20
Source File: IBaselineRepository.java    From vividus with Apache License 2.0 votes vote down vote up
void saveBaseline(Screenshot screenshot, String baselineName) throws IOException; 
Example #21
Source File: ScreenshotProvider.java    From vividus with Apache License 2.0 votes vote down vote up
Screenshot take(VisualCheck visualCheck);