Return-Path: DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=profusion-mobi.20150623.gappssmtp.com; s=20150623; h=from:to:cc:subject:date:message-id:in-reply-to:references; bh=00/WSP31fypfAkH7541p75Y6W/1kMD5Opu1vW9rUeXY=; b=KMzgfKyLeLB14pDVnShVcJjTqGOVwi7VLpe/c2tJpiaPnehIHTwD6NwjCN/1TVHgUH 0h1HoHioGHI1a7CR+gNjgaQ6TGKRLgpdDns2Zqg0LpA2DkqKilEr2vs+ec6PcyMVyVpG j0uRCjS67AOsu1a8PfopL1p4zdfPaJs2C3PSqFQPKb4B6r6CJLJucu2RW3SZSOLu3BF8 EkmCQISdzp7UQ+ucfNaE0pVrIvZKd9Nxf4iDUpK1Mn5I3+AuM0sUg3L52JJI22ErMV5p KbUyCfDstejpEfd4nhUhEqCerRfqaquUhzeyw6ljxox9+cUtEYF1FVWlUroEqE5aiX66 k2nQ== From: Guilherme Campos Camargo Date: Tue, 24 Apr 2018 14:24:38 -0300 Message-Id: <20180424172451.2682-2-guicc@profusion.mobi> In-Reply-To: <20180424172451.2682-1-guicc@profusion.mobi> References: <20180424172451.2682-1-guicc@profusion.mobi> Subject: [Fuego] [PATCH 01/14] Add a SeleniumCommand that compares screenshots List-Id: Mailing list for the Fuego test framework List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , To: fuego@lists.linuxfoundation.org The newly added test takes a screenshot of an element present on the current webpage and compares it to a reference image. An optional argument 'threshold' may be provided to the CheckScreenshot constructor to allow a certain amount of difference to be disconsidered. This value represents the normalized root mean squared error (-metric rmse as briefly explained in https://www.imagemagick.org/script/command-line-options.php#. By default, this 'threshold' is set to 0.0. For the image comparison we're using ImageMagick Signed-off-by: Guilherme Campos Camargo --- .../Functional.fuego_release_test/test_run.py | 148 +++++++++++++++++- 1 file changed, 145 insertions(+), 3 deletions(-) diff --git a/engine/tests/Functional.fuego_release_test/test_run.py b/engine/tests/Functional.fuego_release_test/test_run.py index d4c3882..35c7e90 100755 --- a/engine/tests/Functional.fuego_release_test/test_run.py +++ b/engine/tests/Functional.fuego_release_test/test_run.py @@ -9,13 +9,15 @@ import re import subprocess import sys import time +from io import BytesIO import docker import pexpect import requests +import selenium.common.exceptions as selenium_exceptions from selenium import webdriver from selenium.webdriver.common.by import By -import selenium.common.exceptions as selenium_exceptions +from PIL import Image LOGGER = logging.getLogger('test_run') STREAM_HANDLER = logging.StreamHandler() @@ -39,6 +41,13 @@ def loop_until_timeout(func, timeout=10, num_tries=5): return False +def silent_remove(filename): + try: + os.remove(filename) + except (FileNotFoundError, IsADirectoryError): + pass + + class SeleniumCommand: def exec(self, selenium_ctx): self.driver = selenium_ctx.driver @@ -86,6 +95,20 @@ class SeleniumCommand: LOGGER.debug(" Element found") return element + @staticmethod + def get_element_screenshot(context, element): + location = element.location_once_scrolled_into_view + size = element.size + + viewport_screenshot = Image.open( + BytesIO(context.driver.get_screenshot_as_png())) + element_screenshot = viewport_screenshot.\ + crop((location['x'], location['y'], + location['x'] + size['width'], + location['y'] + size['height'],)) + + return element_screenshot + class Visit(SeleniumCommand): def __init__(self, url, timeout=10, expected_result=200): @@ -122,12 +145,121 @@ class CheckText(SeleniumCommand): element = SeleniumCommand.\ find_element(selenium_ctx, self.locator, self.pattern) - if element: - result = SeleniumCommand.check_element_text(element, self.text) + if not element: + return False + result = SeleniumCommand.check_element_text(element, self.text) return result == self.expected_result +class CheckScreenshot(SeleniumCommand): + def __init__(self, locator, pattern, ref_img, diff_img=None, + expected_result=True, threshold=0.0, + rm_images_on_success=True): + def add_suffix(filename, suffix): + head, sep, tail = ref_img.rpartition('.') + if sep: + return head + sep + suffix + '.' + tail + + return tail + '.' + suffix + + self.pattern = pattern + self.locator = locator + self.reference_img_path = ref_img + self.expected_result = expected_result + self.threshold = threshold + self.rm_images_on_success = rm_images_on_success + + if diff_img is None: + self.diff_img_path = add_suffix(ref_img, 'diff') + else: + self.diff_img_path = diff_img + + self.test_img_path = add_suffix(ref_img, 'test') + + def compare_images(self, current_img_path, reference_img_path, + diff_img_path, threshold): + cmd = ['magick', + 'compare', + '-verbose', + '-metric', + 'RMSE', + '-highlight-color', + 'Red', + '-compose', + 'Src', + current_img_path, + reference_img_path, + diff_img_path + ] + + LOGGER.debug(' Comparing images...') + LOGGER.debug(' cmd: $ %s', ' '.join(cmd)) + process = subprocess.Popen(cmd, universal_newlines=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + process_stdout, process_stderr = process.communicate() + LOGGER.debug(' Results:') + LOGGER.debug(' return code: %s', process.returncode) + LOGGER.debug(' stdout: %s', process_stdout.strip()) + LOGGER.debug(' stderr: %s', process_stderr.strip()) + + RESULTS_REGEX = re.compile(".*all:.*\(([0-9\-\.]*)\).*") + result = RESULTS_REGEX.search(process_stderr) + + if not result: + LOGGER.error(" Error processing the output.") + return False + + difference = float(result.group(1)) + if difference > threshold: + LOGGER.debug(" Resulting difference (%s) above threshold (%s). ", + difference, threshold) + LOGGER.debug(" Element's screenshot does not match the reference." + " See %s for a visual representation of the " + " differences.", diff_img_path) + return False + + LOGGER.debug(" Resulting difference (%s) below threshold (%s).", + difference, threshold) + LOGGER.debug(" Element's screenshot matches the reference.") + return True + + def exec(self, selenium_ctx): + super().exec(selenium_ctx) + + element = SeleniumCommand.\ + find_element(selenium_ctx, self.locator, self.pattern) + if not element: + return False + + screenshot = SeleniumCommand.\ + get_element_screenshot(selenium_ctx, element) + + try: + screenshot.save(self.test_img_path, format='PNG') + except FileNotFoundError: + LOGGER.error( + " Unable to save the screenshot to '%s'. Does the directory " + "exist and can you write to it?", self.test_img_path) + return False + + result = self.compare_images(self.test_img_path, + self.reference_img_path, + self.diff_img_path, + self.threshold) + + if result != self.expected_result: + return False + + # Remove diff and test images if there's a match + if self.rm_images_on_success: + silent_remove(self.diff_img_path) + silent_remove(self.test_img_path) + + return True + + class Click(SeleniumCommand): def __init__(self, locator, pattern): self.pattern = pattern @@ -474,6 +606,16 @@ def main(): if container: container.delete() + def get_abs_working_dirs(): + abs_install_dir = os.path.abspath(args.install_dir) + + if args.working_dir: + abs_working_dir = os.path.abspath(args.working_dir) + else: + abs_working_dir = abs_install_dir + + return abs_install_dir, abs_working_dir + def execute_tests(timeout): LOGGER.debug("Starting tests") -- 2.17.0