From b2c320503b0fd04ddc6e2e991630a0e17797a47a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Corentin=20S=C3=A9chet?= Date: Fri, 8 Apr 2022 14:32:05 +0200 Subject: [PATCH] screenshot: save only files where there is a diff --- frontools/screenshot.py | 39 ++++++++++++++++++++++++++++----------- pyproject.toml | 2 ++ 2 files changed, 30 insertions(+), 11 deletions(-) diff --git a/frontools/screenshot.py b/frontools/screenshot.py index 292fbed..d29436a 100644 --- a/frontools/screenshot.py +++ b/frontools/screenshot.py @@ -1,7 +1,9 @@ """Pages screenshots""" from pathlib import Path +from tempfile import NamedTemporaryFile from typing import Optional +from PIL import Image, ImageChops from playwright.async_api import BrowserContext from frontools import Config @@ -60,21 +62,36 @@ async def screenshot_diff( async def _diff_url( left: BrowserContext, right: BrowserContext, url: str, output_path: Path ) -> None: - await _screenshot_url(left, url, output_path, "left") - await _screenshot_url(right, url, output_path, "right") + left_bytes = await _screenshot_url(left, url) + right_bytes = await _screenshot_url(right, url) + with NamedTemporaryFile(mode='wb') as left_file: + left_file.write(left_bytes) + left_image = Image.open(left_file.name) + + with NamedTemporaryFile(mode='wb') as right_file: + right_file.write(right_bytes) + right_image = Image.open(right_file.name) + + diff = ImageChops.difference(left_image, right_image) + + if not diff.getbbox(): # images are the same + return -async def _screenshot_url( - browser: BrowserContext, url: str, output_path: Path, suffix: str -) -> None: - page = await browser.new_page() - await page.goto(url) - await page.wait_for_load_state('networkidle') url_slug = get_url_slug(url) if not output_path.is_dir(): output_path.mkdir() - screenshot_bytes = await page.screenshot(full_page=True) + with open(output_path / f"{url_slug}_left", "wb") as screenshot_file: + screenshot_file.write(left_bytes) - with open(output_path / f"{url_slug}_{suffix}", "wb") as screenshot_file: - screenshot_file.write(screenshot_bytes) + with open(output_path / f"{url_slug}_right", "wb") as screenshot_file: + screenshot_file.write(right_bytes) + + +async def _screenshot_url(browser: BrowserContext, url: str) -> bytes: + page = await browser.new_page() + await page.goto(url) + await page.wait_for_load_state("networkidle") + + return await page.screenshot(full_page=True) diff --git a/pyproject.toml b/pyproject.toml index 5f938d7..6628fdf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -38,6 +38,7 @@ click = "^8.0.4" aiohttp = "^3.8.1" PyYAML = "^6.0" tinycss2 = "^1.1.1" +Pillow = "^9.1.0" [tool.poetry.dev-dependencies] isort = "^5.10.1" @@ -45,6 +46,7 @@ black = "^22.1.0" mypy = "^0.942" pylint = "^2.13.2" types-click = "^7.1.8" +types-Pillow = "^9.0.11" [tool.poetry-dynamic-versioning] enable = true