Creating and comparing screenshots at runtime

Last edited on

Introduction

Here is an example for taking screenshots at runtime, and for comparing images/screenshots at runtime with the help of an external (Java-based) tool:

import os
import os.path
import subprocess
import sys


def main():
    startApplication("myaut")


    # Create remote screenshot and copy
    # screenshot file to the local computer:
    some_object = waitForObject("some_object_name_here")
    img1 = "temp1.png"
    myGrabWidget(window, img1)


    # Do something in application...


    # Create remote screenshot and copy
    # screenshot file to the local computer:
    img2 = "temp2.png"
    myGrabWidget(window, img2)


    # Compare images:
    if compare_images(img1, img2):
        test.passes("Images are identical")
    else:
        test.fail("Images are different")


def compare_images(img1, img2):
    # Verify that CompareImages.class exists
    # in the test suite folder:
    compare_tool_class = squishinfo.testCase + "/../CompareImages.class"
    if not os.path.exists(compare_tool_class) or os.path.isdir(compare_tool_class):
        raise RuntimeError("Compare tool .class file not found. Aborting...")

    compare_tool_name = squishinfo.testCase + "/../CompareImages.sh"
    if sys.platform == "win32":
        compare_tool_name = squishinfo.testCase + "/../CompareImages.bat"

    # Verify that CompareImages.bat/.sh exists
    # in the test suite folder:
    if not os.path.exists(compare_tool_name) or os.path.isdir(compare_tool_name):
        raise RuntimeError("Compare tool '%s' not found. Aborting..." % compare_tool_name)

    # Verify that CompareImages.bat/,sh file
    # can be executed:
    try:
        proc = subprocess.Popen(args=[compare_tool_name])
        proc.communicate()
        if proc.returncode != 10:
            raise RuntimeError("Executing compare tool ('%s') failed (exit code %s). Is it executable?" % (compare_tool_name, exit_code))
    except OSError:
        raise RuntimeError("Executing compare tool ('%s') failed. Is it executable?" % (compare_tool_name))

    # Compare images:
    args = [compare_tool_name, img1, img2]
    proc = subprocess.Popen(args)
    proc.communicate()
    test.log("%s" % proc.returncode)
    return proc.returncode == 0


def myGrabWidget(widget, filename):
    # Create remote screenshot:
    img = object.grabScreenshot(widget)

    img.save(filename, "PNG")

    # Copy remote file to computer that is
    # executing this script/squishrunner;
    # file will be in squishrunner working
    # directory (default is test case folder):
    testData.get(filename)
test.py

Required Files

These files need to be placed into the test suite folder (not in any of the test case folders).