1、在使用uiautomator进行自动化测试过程当中,执行某些动作之后,要进行判断是否已执行的动作成功时,需要添加检查点来判断,因此添加判断点除了使用id、text、view等方式进行之外,存在一种问题是界面无任何的可判定元素来判断当前的测试动作是否成功时,就需要用到截图对比;
2、以下是简单的截图对比与自动化执行相结合使用的小例子,在真正的测试执行过程中,可将截图方法进行封装,在使用时调用即可;
# -*- coding: utf- -*- from uiautomator import Device
import time
import os
import cv2
import numpy as npclass Test:
def __init__(self,deviceid):
self.device=Device(deviceid)
self.deviceid=deviceid def click(self,x,y):
self.device.click(x,y) def startActivity(self,activity):
os.system('adb -s %s shell am start %s' %(self.deviceid,activity)) #平均hash算法计算
def classify_aHash(self,image1,image2):
image1 = cv2.resize(image1,(,))
image2 = cv2.resize(image2,(,))
gray1 = cv2.cvtColor(image1,cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(image2,cv2.COLOR_BGR2GRAY)
hash1 = self.getHash(gray1)
hash2 = self.getHash(gray2)
return self.Hamming_distance(hash1,hash2) #输入灰度值,返回hash
def getHash(self,image):
avreage = np.mean(image)
hash = []
for i in range(image.shape[]):
for j in range(image.shape[]):
if image[i,j] > avreage:
hash.append()
else:
hash.append()
return hash # 计算汉明距离
def Hamming_distance(self,hash1,hash2):
num =
for index in range(len(hash1)):
if hash1[index] != hash2[index]:
num +=
return num #使用adb命令截取手机页面图片
def screenshot(self):
time.sleep()
#os.system("adb shell /system/bin/screencap -p /sdcard/p2.png") #(保存到SDCard)
#os.system("adb pull /sdcard/p2.png E:\Study\uiautomator\picture") #(保存到电脑)
self.device.screenshot("E:\\Study\\uiautomator\\picture\\p2.png")if __name__ == "__main__":
w=Test('0123456789ABCDEF') #记录手机串号,查看方式adb devices
w.startActivity('com.android.mms/.ui.ConversationList')
w.screenshot()
img1 = cv2.imread("E:\\Study\\uiautomator\\picture\\p1.png") #读取保存的图片,原始图片
img2 = cv2.imread("E:\\Study\\uiautomator\\picture\\p2.png") #读取与原始图相同使用screenshot方法截取的页面图片
cv2.imshow("img1",img1) #展示图片1
cv2.imshow("img2",img2) #展示图片2
degree = w.classify_aHash(img1,img2) #调用方法,对比两张图片是否相同,返回值0为相同,返回1为不同,值越小,返回值越小,相似度越高
print degree
cv2.waitKey()