【Airtest】使用aircv实现局部截图

2,602 阅读2分钟

本人在一家游戏公司上班,担任测试一职,公司使用Unity引擎开发游戏,所以会运用到一些技术,提高工作效率,在这里想跟大家分享一下。


为什么要使用这项技术?

  1. 方便后期维护

    当策划调整游戏界面的时候,减少维护自动化用例的时间,大大提升效率

  2. 增加稳定性

    因为是根据元素坐标截图的,所以截图的位置非常准确,还可以随意控制

示例代码如下:


from GetID.GetDevice import serialno
from airtest.core.api import *
from airtest.aircv import *
from poco.drivers.unity3d import UnityPoco

class PartialScreenshot():
    """这是一个使用Airtest框架,实现局部截图的类."""

    def __init__(self,devices):
        self.devices = devices
        self.poco = UnityPoco()

    def get_phone_resolution(self):
        """
        获取手机屏幕分辨率
        :return: 屏幕分辨率,高height、宽width
        """

        # 判断当前屏幕为横屏还是竖屏,并获取当前屏幕的分辨率
        if G.DEVICE.display_info['orientation'] in [1,3]:
            self.height = G.DEVICE.display_info['width']
            self.width = G.DEVICE.display_info['height']
        else:
            self.height = G.DEVICE.display_info['height']
            self.width = G.DEVICE.display_info['width']

        # 返回屏幕分辨率
        return self.height,self.width

    def crop_screenshot(self,elm,dvaluey1,dvaluex2,dvaluey2,dvaluex1):
        """
        根据元素的坐标,对全屏截图的图片进行裁剪,实现区域截图的效果。
        :param elm:  定位的元素,即想要裁剪的区域
        :param dvaluey1: y轴最小值偏移值
        :param dvaluex2: x轴最大值偏移值
        :param dvaluey2: y轴最大值偏移值
        :param dvaluex1: x轴最小值偏移值
        :return:
        """
        # 获取手机分辨率
        self.get_phone_resolution()     

        # 获取UI元素的边界框参数。(右上y_min、右下x_max、左下y_max、左上x_min)
        bound =elm.get_bounds()

        # 把四个bounds值分别提取出来,dvalue是让测试人员填写的误差值,无误差直接填0(将 相对坐标 转换成 绝对坐标)
        y1 = (bound[0]+dvaluey1) * self.height  # 右上
        x2 = (bound[1]+dvaluex2) * self.width  # 右下
        y2 = (bound[2]+dvaluey2) * self.height  # 左下
        x1 = (bound[3]+dvaluex1) * self.width  # 左上

        # 将bounds值的数据类型转为 str,如果不是str,底下aircv.crop_image函数在调用的时候会报错
        y_min = str(round(y1))
        x_max = str(round(x2))
        y_max = str(round(y2))
        x_min = str(round(x1))

        screen = G.DEVICE.snapshot(quality=99)      # 全屏截图
        crop_photo = aircv.crop_image(screen,(x_min,y_min,x_max,y_max))     # 区域截图
        SavePath = '../Image/'       # 保存路径
        filename = 'partialscreenshot.jpg'      # 文件名
        filepath = os.path.join(SavePath, filename)     # 合并成完整路径
        aircv.imwrite(filepath, crop_photo, 99)     # 保存图片

if __name__ == '__main__':
    pss = PartialScreenshot(serialno())     # 实例化对象
    pss.crop_screenshot(pss.poco("Windows").offspring("PickItemList").child("Viewport").child("Content").child("ItemBox(Clone)").child("Icon"),0,0,0,0)