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=rV20g6u0JPV/fOMPts3SF3q3UUPrJOaAb+EULQg7h3c=; b=GTuFSL1H0xVrkTvnUnDCqaRRkShh09PxNNQvjBuspRHhSQr/KIP/xuZKyyMEB3gSvz jIS//G7SeAnEs8/4xgYr2lPUhwiWzGOkZI3++CkKfwqJbqD36/QBmev3f9K2HZlNV0oe NaiKcdqOLTjfF0I33xUqM4vOriTgLZSPi8QSRT859yR60V2JxLXFbpaarQU5OX/OI2/A qZEvpcnIGohKtW5ImFmSRSmFxJDmC9CwuIzAQI3ShABqCnQM9Qh83FLNZqkBnKUWk8iX OdiCsjGbebjuaDNooWet3RC21aH7hoZJ8Q4sLTmExJJ+SOz4Zh4HagguyobgEGv+Qogi 5ILQ== From: Guilherme Campos Camargo Date: Tue, 24 Apr 2018 14:24:45 -0300 Message-Id: <20180424172451.2682-9-guicc@profusion.mobi> In-Reply-To: <20180424172451.2682-1-guicc@profusion.mobi> References: <20180424172451.2682-1-guicc@profusion.mobi> Subject: [Fuego] [PATCH 08/14] Add helper script for taking element/full-page 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 Add the helper script `take_screenshot.py` that navigates to a given URL and takes a screenshot of an element - or from the full viewport when the element is not provided. This script is useful for generating reference screenshots to be compared through the fuego-release-test's CheckScreenshot Selenium Command. Signed-off-by: Guilherme Campos Camargo --- .../helpers/take_screenshot.py | 145 ++++++++++++++++++ 1 file changed, 145 insertions(+) create mode 100755 engine/tests/Functional.fuego_release_test/helpers/take_screenshot.py diff --git a/engine/tests/Functional.fuego_release_test/helpers/take_screenshot.py b/engine/tests/Functional.fuego_release_test/helpers/take_screenshot.py new file mode 100755 index 0000000..c7ae049 --- /dev/null +++ b/engine/tests/Functional.fuego_release_test/helpers/take_screenshot.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 +import argparse +import requests +import sys +from io import BytesIO + +import selenium.common.exceptions as selenium_exceptions +from selenium import webdriver +from selenium.webdriver.common.by import By +from PIL import Image + + +def public_attributes(obj): + return [attr for attr in dir(By) if not attr.startswith('__')] + + +AVAILABLE_LOCATORS = public_attributes(By) +DEFAULT_VIEWPORT_RESOLUTION = "1920x1080" + + +class SeleniumSession: + def __init__(self, resolution): + options = webdriver.ChromeOptions() + options.add_argument('headless') + options.add_argument('no-sandbox') + options.add_argument('window-size=%s' % resolution) + options.add_experimental_option( + 'prefs', {'intl.accept_languages': 'en,en_US'}) + + self.driver = webdriver.Chrome(chrome_options=options) + self.driver.implicitly_wait(3) + + def __del__(self): + if self.driver: + self.driver.quit() + + def go(self, url): + try: + r = requests.get(url) + except (requests.exceptions.MissingSchema, + requests.exceptions.ConnectionError, + requests.exceptions.ConnectTimeout) as e: + print(e) + return 404 + + if r.status_code != requests.codes.ok: + print("Unable to navigate to the page %s" % url) + print("Please provide a valid URL") + return r.status_code + + self.driver.get(url) + return r.status_code + + def take_screenshot(self, locator_str, pattern): + def take_element_screenshot(locator, pattern): + try: + element = self.driver.find_element(locator, pattern) + except selenium_exceptions.NoSuchElementException: + print("Element not found") + return None + + location = element.location_once_scrolled_into_view + size = element.size + + viewport_screenshot = Image.open( + BytesIO(self.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 + + def take_full_screenshot(): + return Image.open( + BytesIO(self.driver.get_screenshot_as_png())) + + if not locator_str or not pattern: + print("Taking full screenshot (locator and/or pattern are empty)") + return take_full_screenshot() + + locator = getattr(By, locator_str, None) + if not locator: + print("Locator '%s' is not supported" % locator_str) + return None + + print("Taking element screenshot") + return take_element_screenshot(locator, pattern) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('url', help="""The URL from where a screenshot will be + taken""", type=str) + parser.add_argument('-l', '--locator', help="the " + """locator that will be used to find the element on the + page. Available locators are: %s""" % + AVAILABLE_LOCATORS, default=None, type=str) + parser.add_argument('-p', '--pattern', help="""The pattern that will be + used for locating the element.""", + default=None, type=str) + parser.add_argument('-o', '--out', help="""Resulting screenshot filename. + Defaults to '${locator}_${pattern}.png' if those + arguments are given or 'full_viewport.png' if not.""", + default=None, type=int) + parser.add_argument('-r', '--resolution', help="""Viewport resolution. + Defaults to %s. Make sure your page or element fits + this resolution, otherwise the results might be + cropped.""" % DEFAULT_VIEWPORT_RESOLUTION, + default=DEFAULT_VIEWPORT_RESOLUTION, type=str) + args = parser.parse_args() + + def generate_out_filename(): + if not args.locator or not args.pattern: + return 'full_screenshot.png' + else: + return args.locator + '_' + args.pattern + '.png' + + if not args.out: + args.out = generate_out_filename() + + selenium = SeleniumSession(args.resolution) + + status_code = selenium.go(args.url) + if status_code != requests.codes.ok: + print("Unable to navigate to URL") + return 1 + + screenshot = selenium.take_screenshot(args.locator, args.pattern) + if not screenshot: + print("Unable to take a screenshot") + return 1 + + try: + screenshot.save(args.out, format='PNG') + except FileNotFoundError as e: + print("Unable to save the screenshot to '%s'" % args.out) + print(" Reason: %s" % e) + return 1 + + return 0 + + +if __name__ == '__main__': + sys.exit(main()) -- 2.17.0