【專項】【頁面加載時間】uiautomator2+opencv-python基於圖片識別算法實現自動化統計頁面加載時間DEMO

uiautomator2+opencv-python基於圖片識別算法實現自動化統計頁面加載時間DEMO:

一、實踐要點記錄

1.uiautomator2實現UI操作

2.opencv-python基於圖片識別算法,機器判斷圖片加載完成

3.過程:

#點擊頁面入口時開始記錄時間start_time

# 邊加載頁面邊截圖 # 定義一個標準,哈希值範圍是0-64,哈希值越小,圖片越相似

# 當加載完成的頁面和預期頁面相似度高(python opencv 圖片相似度 的算法),如哈希算法,當哈希值小於某個值,判斷爲加載完成

# 記錄此時的時間點end_time

# 終止截圖、圖片對比循環過程 # 計算時間差,即頁面加載時間=end_time-start_time

4.代碼實現:

#encoding utf-8
import uiautomator2 as u2
from time import sleep
from uiautomator2.ext.htmlreport import HTMLReport
import pytest
import allure
import os
from Tools import logger#自己封裝的logger
from Tools import compimgs_similar#封裝了python opencv 圖片相似度 的算法
import time
import datetime

'''
(1)連接:
wifi連接:
d=u2.connect('192.168.1.89')#手機和電腦同一個WIFI,此爲手機IP地址
usb連接:
u2.connect('3ac86305')#device:3ac86305
(2)包名:
隨手記APP包名:com.mymoney
(3)定位:
ResourceId定位:
d(resourceId="com.mymoney:id/item_entry_img")
Text定位:
d(text="清理存儲")
Description定位:
d(description=" ")
ClassName定位:
d(className="android.widget.RelativeLayout")
(4)報告:
        from uiautomator2.ext.htmlreport import HTMLReport
        html_report=HTMLReport(self.d,'report')
        html_report.patch_click()
(5)執行:
規範pytest:
class名:首字母大寫,包含Test
初始化環境:setup(),u小寫
清理環境:teardown(),d小寫
測試用例方法:test開頭,加上和測試模塊相關的字母縮寫(自定義發揮,能看懂測撒)
'''

LOG = logger.Logger("TestPhm").getlog()
class TestMym():
    def setup(self):
        self.log = LOG
        self.log.debug("連接設備")
        self.d=u2.connect('3ac86305')
        self.d.healthcheck()  # 解鎖屏幕並啓動uiautomator服務
        html_report=HTMLReport(self.d,'report')
        html_report.patch_click()
        self.log.debug("啓動APP")
        self.d.app_start("com.mymoney")
        #啓動頁有個幾秒的閃屏,也可以點擊跳過
        sleep(3)
        pass

    @allure.MASTER_HELPER.step("投資")
    def test_invest(self):
        self.d(resourceId="com.mymoney:id/main_top_nav_button_second").click()
        #點擊頁面入口時開始記錄時間start_time
        start_time=datetime.datetime.now()
        path = os.path.dirname(os.path.abspath(__file__))
        temp_img2 = path + "/expected_resultimg/" + "ss_except.jpg"
        # 邊加載頁面邊截圖
        # 定義一個標準,哈希值範圍是0-64,哈希值越小,圖片越相似
        # 當加載完成的頁面和預期頁面相似度高,即哈希值小於某個值,判斷爲加載完成
        # 記錄此時的時間點end_time
        # 終止截圖、圖片對比循環過程
        # 計算時間差,即頁面加載時間=end_time-start_time
        while 1:
            temp_img1=self.d.screenshot(path + "/temp_screenshot/"+"ss_test.jpg")
            h=compimgs_similar.runImgSimilar(temp_img1,temp_img2)
            if h<5:
                end_time=datetime.datetime.now()
                print('[差值]哈希=', h)
                break
            print('[差值]哈希=', h,'>=5')
        #print('相差:%s微秒' % (start_time-end_time).microseconds)
        print('頁面加載時間:%s秒' % (end_time - start_time  ).total_seconds())
        #sleep(6)
        # self.log.debug("完成")
        # temp_img = self.d.screenshot(path + "/expected_resultimg/" + "ss_except.jpg")
        # sleep(1)

    def teardown(self):
        self.log.debug("退出APP")
        self.d.app_stop("com.mymoney")
        pass

if __name__ == '__main__':
    '''
    cmd生成HTML報告
    allure generate <xml路徑> -o <html路徑> --clean
    cmd查看HTML報告
    allure open -h 127.0.0.1 -p 8083 <html路徑>
    xml、html的報告路徑
    '''
    path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    file_result = path + "/py_result/xml"
    file_report=path+"/py_result/html"
    pytest.main(['-s', '-q', '--alluredir', file_result])

二、執行結果:

二、數據統計:

代碼實現:

1.執行次數:

pip3 install pytest-repeat,裝飾器實現

@pytest.mark.repeat(10)#用例執行N次 def test_invest(self):

2.數據處理

#求最大值、最小值、平均值,寫入EXCEL
def test_datadeal(self):
    #加載時間從小到大排序
    or_list=self.loadtime
    list1=sorted(self.loadtime)
    #取最大值
    max_loadtime=list1[-1]
    #取最小值
    min_loadtime=list1[0]
    #數組元素求平均值,取小數點後6位
    sumtimes=0
    for i in list1:
        sumtimes+=i
    ever_loadtime=format(sumtimes/(len(list1)),'.6f')
    #打印
    print('頁面加載時間\nmax值:%s\nmin值:%s\n平均值:%s'%(max_loadtime,min_loadtime,ever_loadtime))

    #寫入excel
    # 創建一個workbook 設置編碼
    book = xlwt.Workbook(encoding='utf-8')
    sheet = book.add_sheet('app_page_loadingtime')
    # 參數對應 行, 列, 值
    sheet.write(0, 0, '測試頁面')
    sheet.write(1, 0, 'vest')
    sheet.write(0, 1, '第N次加載')
    sheet.write(0, 2, '加載耗時')
    for i in range(len(or_list)):
        sheet.write(i+1, 1, i+1)
        sheet.write(i+1,2,or_list[i])

    sheet.write(0, 3, 'N次加載最大值')
    sheet.write(1, 3, max_loadtime)
    sheet.write(0, 4, '最小值')
    sheet.write(1, 4, min_loadtime)
    sheet.write(0, 5, '平均值')
    sheet.write(1, 5, ever_loadtime)
    # 保存
    book.save(self.path + "/loadingtime_data/"+"test_loadingtime.xls")

運行結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章