Image Compare Check – Android

Google provided a tool ‘monkeyrunner’ which is written in Jython https://developer.android.com/studio/test/monkeyrunner

Its sub tool APIs “monkeyrunner class can be used to hold an image of the device or emulator’s screen. The image is copied from the screen buffer during a screenshot. This object’s methods allow you to convert the image into various storage formats, write the image to a file, copy parts of the image, and compare this object to other MonkeyImage objects.”

Jython script (firstly you need to install the Jython. I used Jython 2.7):

from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage
import sys
import os

device = MonkeyRunner.waitForConnection(deviceId=sys.argv[1])
result = device.takeSnapshot()

image_format = 'png'
golden_image = sys.argv[2] + '/' + sys.argv[3] + '.' + image_format
image_exists = os.path.isfile(golden_image)

if image_exists is False:
    print('Image does not exist. Creating golden image')
    try:
        os.makedirs(sys.argv[2])
    except OSError:
        pass
    result.writeToFile(golden_image, image_format)
    sys.exit(0)

ref = MonkeyRunner.loadImageFromFile(golden_image, image_format)

diff_image = sys.argv[2] + '/' + sys.argv[3] + '-diff.' + image_format
is_same = result.sameAs(ref, float(sys.argv[4]))

if is_same is False:
    print('Image is differed. Creating diffed image')
    result.writeToFile(diff_image, image_format)
    sys.exit(1)
else:
    print('Image is matched')
    sys.exit(0)

In your Python (my Python is 3.7) script, you can invoke it,

import subprocess
import os
from configs import ocha_configs as CONFIG
import inspect
import re


class ImageUtils:

    @staticmethod
    def diff_image(image_dir, image_name, should_diff=True):
        if should_diff is False:
            return

        jython_script = re.sub(r'test_suite(\S+)', '{}'.format('golden_images/jython_image.py'), image_dir)

        image_dir_translated = image_dir.replace('.py', '').replace('test_suite',
                                                                    'golden_images/' + os.getenv('DEVICE_NAME'))
        result = subprocess.run(
            ['monkeyrunner', jython_script, os.getenv('DEVICE_NAME'), image_dir_translated, image_name,
             CONFIG.IMAGE_DIFF_PERCENTAGE],
            stdout=subprocess.PIPE)

        print(result)
        assert result.returncode == 0, 'Image is mismatched'