改造 uiautomator2screenshot 方法

uiautomator2 不支持 base64 格式截图,需要对截图的方法进行改造。
uiautomator2/__init__.py中找到 screenshot 方法,添加生成 base64 格式图片的代码,改造后的方法如下:

def screenshot(self, filename=None, format='pillow'):
        """
        Image format is JPEG

        Args:
            filename (str): saved filename
            format (string): used when filename is empty. one of "pillow" or "opencv"

        Raises:
            IOError, SyntaxError

        Examples:
            screenshot("saved.jpg")
            screenshot().save("saved.png")
            cv2.imwrite('saved.jpg', screenshot(format='opencv'))
        """
        r = requests.get(self.server.screenshot_uri, timeout=10)
        if filename:
            with open(filename, 'wb') as f:
                f.write(r.content)
            return filename
        elif format == 'pillow':
            from PIL import Image
            buff = io.BytesIO(r.content)
            return Image.open(buff)
        elif format == 'opencv':
            import cv2
            import numpy as np
            nparr = np.fromstring(r.content, np.uint8)
            return cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        elif format == 'raw':
            return r.content
        #----新增代码开始------
        elif format == 'base64':
            import base64
            # b64encode是编码,b64decode是解码
            base64_data = base64.b64encode(r.content)
            # base64.b64decode(base64data)
            return base64_data
        #----新增代码结束------
        else:
            raise RuntimeError("Invalid format " + format)

python 将图片转 base64,前端显示

截图添加进入测试报告

HTMLTestRunner_cn 项目的 gitbub 地址中下载 HTMLTestRunner_cn.py 文件,放入C:\Python27\Lib文件夹中

生成报告的 demo:

# coding: utf-8

import uiautomator2 as u2
from HTMLTestRunner_cn import HTMLTestRunner
import unittest
import os, re

class TestCaseUi2(unittest.TestCase):
    """docstring for TestCaseUi2"""

    @classmethod
    def setUpClass(cls):
        deviceInfo = os.popen("adb devices").read().strip('\n')
        deviceSerial = re.search('attached\n(.*)\t', deviceInfo).group(1).strip()
        print deviceSerial
        cls.driver = u2.connect(deviceSerial)

    @classmethod
    def tearDownClass(cls):
        pass


    def add_img(self):
        self.imgs.append(self.driver.screenshot(format='base64'))
        return True

    def setUp(self):
        self.driver.session('com.szchmtech.parkingfee')

    def tearDown(self):
        self.driver.app_stop('com.szchmtech.parkingfee')

    def test_case1(self):
        self.add_img()
        self.add_img()


if __name__ == "__main__":
    suite = unittest.TestLoader().loadTestsFromTestCase(TestCaseUi2)
    runer = HTMLTestRunner(title="带截图的测试报告", description="小试牛刀", stream=open("sample_test_report_uiautomator2.html", "wb"), verbosity=2, retry=1, save_last_try=True)
    runer.run(suite)


↙↙↙阅读原文可查看相关链接,并与作者交流