【python】adb+uiautomator 操作手机

uiautomator配置

  1. uiautomator2 是一个可以使用Python对Android设备进行UI自动化的库。其底层基于Google uiautomator,Google提供的uiautomator库可以获取屏幕上任意一个APP的任意一个控件属性,并对其进行任意操作
  2. 安装uiautomator : pip install uiautomator
  3. 依赖: app-uiautomator.apk,app-uiautomator-test.apk,bundle.jar,uiautomator-stub.jar
#!/usr/bin/env python
# -*- coding=utf-8 -*-
__author__ = 'Man Li' 

import os,sys,re,subprocess
from time import sleep
from uiautomator import device as d
from datetime import datetime

import setting


#检查是否成功连接adb
def check_sp():
    spinfo=subprocess.check_output('adb devices')
    #return spinfo.split("\r\n")
    if spinfo.split("\r\n")[1] == '':
        return False
    elif spinfo.split("\r\n")[1] != '':
        print "adb init successfully."
        #logger.info(" *** adb init successfully ***")
        return True
    else:
        return 00001


class SP:
    def __init__(self):
        self.init_sp=check_sp()
        self.app_uiautomator = "./app-uiautomator.apk"
        self.app_uiautomator_test = "./app-uiautomator-test.apk"
        self.bundle = "./bundle.jar"
        self.uiautomator_stub = "./uiautomator-stub.jar"


    def status_init(self):
        print "["+str(str(datetime.now()).split(" ")[1])[0:-7]+"] ==SP==  Doing ---> : Status_init."
        if self.init_sp == True:
            install_mesg=subprocess.check_output('adb install -r '+self.app_uiautomator)
            if "Success" in install_mesg:
                subprocess.check_output('adb install -r '+self.app_uiautomator_test)
            else:
                install_mesg=subprocess.check_output('adb push '+self.bundle+' /data/local/tmp')
                if "No such file or directory" in install_mesg:
                    print "[one should know that] Install fail!!!"
                    #logger.info("Install fail!!!")
                else:
                    subprocess.check_output('adb push '+self.uiautomator_stub+' /data/local/tmp')
        else:
            print "Please examine ADB and SP !!!"
    
    '''
        @获取手机厂商
    '''
    def sp_Vendor(self):
        print "["+str(str(datetime.now()).split(" ")[1])[0:-7]+"] ==SP==  Doing ---> : Vendor info."
        if self.init_sp == True:
            sp_mesg=subprocess.check_output('adb -d shell getprop ro.product.brand')
            return str(sp_mesg)
        else:
            print "Please examine ADB and SP !!!"
	
	'''
        @获取手机型号
    '''
    def sp_name(self):
        print "["+str(str(datetime.now()).split(" ")[1])[0:-7]+"] ==SP==  Doing ---> : SP info."
        if self.init_sp == True:
            deviceName = subprocess.check_output('adb shell getprop ro.product.model')
            return str(deviceName)
        else:
            print "Please examine ADB and SP !!!"

    '''
        @打开手机的BT
    '''
    def open_BT(self):
        print "["+str(str(datetime.now()).split(" ")[1])[0:-7]+"] ==SP==  Doing ---> : open BT UI."
        if self.init_sp == True:
            '''
            subprocess.check_output('adb shell am start -a android.bluetooth.adapter.action.REQUEST_ENABLE')
            sleep(0.5)
            open_bt=d(text="是").wait.exists(timeout=500)
            open_bt2=d(text="允许").wait.exists(timeout=500)
            if open_bt == True:
                d(text="是").click()
            if open_bt2 == True:
                d(text="允许").click()
            '''
            bt_settings=subprocess.check_output('adb shell am start -a android.settings.BLUETOOTH_SETTINGS')
            print len(bt_settings.split("\n"))
            if len(bt_settings.split("\n"))==2 or len(bt_settings.split("\n"))==3:
                print "ok open BT"
            else:
                settings_open=subprocess.check_output('adb shell am start -a android.settings.SETTINGS')
                print len(settings_open.split("\n"))
                if len(settings_open.split("\n"))==2 or len(settings_open.split("\n"))==3:
                    print "ok open settings"
                    sleep(1)
                    #d(text=u"连接").click()
                    if d(text=u"连接").wait.exists(timeout=500) == True:
                        d(text=u"连接").click()
                        if d(text=u"蓝牙").wait.exists(timeout=500) == True:
                            d(text=u"蓝牙").click()
                            print "open BT successfully!!!"
                    else:
                        print "not font plases add code..."
                else:
                    print "not open settings"
            #subprocess.check_output('adb shell am start -a android.settings.BLUETOOTH_SETTINGS')
        else:
            print "Please examine ADB and SP !!!"
    
    '''
        @在BT界面开关BT
    '''
    def popf_bt(self):
        if self.init_sp == True:
            deviceName = subprocess.check_output('adb shell getprop ro.product.model')
            print "["+str(str(datetime.now()).split(" ")[1])[0:-7]+"] ==SP==  Doing ---> : power on/off BT."    
            if "M6SPlus" in deviceName:
                print deviceName
                if d(text=u"蓝牙").wait.exists(timeout=500) == True:
                    if d(text=u"已开启").wait.exists(timeout=500) == True:
                        d(text=u"已开启").click()
                    elif d(text=u"已关闭").wait.exists(timeout=500) == True:
                        d(text=u"已关闭").click()
                else:
                    subprocess.check_output('adb shell am start -a android.settings.BLUETOOTH_SETTINGS')
            elif "samsung" in subprocess.check_output('adb -d shell getprop ro.product.brand'):
                if d(text=u"开").wait.exists(timeout=500) == True:
                    d(text=u"开").click()
                elif d(text=u"关").wait.exists(timeout=500) == True:
                    d(text=u"关").click()
            #elif d(text=u"蓝牙").wait.exists(timeout=500) or d(text=u"BT").wait.exists(timeout=500) == True:
            else:
                if d(text=u"蓝牙").wait.exists(timeout=500) == True:
                    if d(text=u"开启").wait.exists(timeout=500) == True:
                        d(text=u"开启").click()
                    elif d(text=u"关闭").wait.exists(timeout=500) == True:
                        d(text=u"关闭").click()
                    else:
                        if d(text=u"蓝牙").wait.exists(timeout=500) == True:
                            d(text=u"蓝牙").click()
                        else:
                            d(className="android.widget.ListView", resourceId="android:id/list").child_by_text(u"蓝牙", className="android.widget.LinearLayout").child(className="android.widget.Switch").click()
                else:
                    subprocess.check_output('adb shell am start -a android.settings.BLUETOOTH_SETTINGS')
        else:
            print "Please examine ADB and SP !!!"

    '''
        @在WLAN界面开关wifi
    '''
    def popf_wifi(self):
        if self.init_sp == True:
            deviceName = subprocess.check_output('adb shell getprop ro.product.model')
            print "["+str(str(datetime.now()).split(" ")[1])[0:-7]+"] ==SP==  Doing ---> : power on/off wifi."        
            if "M6SPlus" in deviceName:
                print deviceName
                if d(text=u"WLAN").wait.exists(timeout=500) == True:
                    if d(text=u"已开启").wait.exists(timeout=500) == True:
                        d(text=u"已开启").click()
                    elif d(text=u"已关闭").wait.exists(timeout=500) == True:
                        d(text=u"已关闭").click()
            elif d(text=u"WLAN").wait.exists(timeout=500) or d(text=u"wifi").wait.exists(timeout=500) == True:
                print "all"
                d(className="android.widget.ListView", resourceId="android:id/list").child_by_text("WLAN", className="android.widget.LinearLayout").child(className="android.widget.Switch").click()
        else:
            print "Please examine ADB and SP !!!"
    
    '''
        @在WLAN界面开关wifi
    '''
    def call(self,number):
        print "["+str(str(datetime.now()).split(" ")[1])[0:-7]+"] ==SP==  Doing ---> : Calling : "+str(number)
        if self.init_sp == True:
            call_cmd='adb shell am start -a android.intent.action.CALL tel:'+str(number)
            subprocess.check_output(call_cmd)
        else:
            print "Please examine ADB and SP !!!"
    

    '''
        @手机重启
    '''
    def sp_reboot(self):
        print "["+str(str(datetime.now()).split(" ")[1])[0:-7]+"] ==SP==  Doing ---> : Reboot. "
        if self.init_sp == True:
            subprocess.check_output('adb shell reboot')
        else:
            print "Please examine ADB and SP !!!"

    '''
        @手机解屏
    '''
    def Slider(self):
        print "["+str(str(datetime.now()).split(" ")[1])[0:-7]+"] ==SP==  Doing ---> : Slider. "
        if self.init_sp == True:
            d.screen.on()
            d.swipe(600, 1000, 600, 10, steps=10)
            d.press.home()
            #subprocess.check_output('adb shell input keyevent 82')
        else:
            print "Please examine ADB and SP !!!"
    
    '''
        @手机BT寻找devices 的蓝牙地址
    '''
    def con_devices(self,devices_btnumber):
        print "["+str(str(datetime.now()).split(" ")[1])[0:-7]+"] ==SP==  Doing ---> : Found Devices BT add : "+str(devices_btnumber)
        devices_bt=d(text=devices_btnumber).wait.exists(timeout=500)
        if devices_bt == True:
            d(text=devices_btnumber).click()
        else:
            print "not fund devices BT"

    '''
        @在手机BT里点击devices的蓝牙地址并确认断开
    '''
    def discon_devices(self,devices_btnumber):
        print "["+str(str(datetime.now()).split(" ")[1])[0:-7]+"] ==SP==  Doing ---> : Disconnection Devices BT add : "+str(devices_btnumber)
        devices_bt=d(text=devices_btnumber).wait.exists(timeout=500)
        if devices_bt == True:
            d(text=devices_btnumber).click()
            if d(text=u"确定").wait.exists(timeout=500) == True:
                d(text=u"确定").click()
            elif d(text="OK").wait.exists(timeout=500) == True:
                d(text="OK").click()
            else:
                print "not discon_devices"
        else:
            print "not fund devices BT"

    def btconn_ok(self):
        if d(text=u"蓝牙").wait.exists(timeout=500) or d(text=u"BT").wait.exists(timeout=500) == True:
            return d(text=u"已连接").wait.exists(timeout=500)
        else:
            self.open_BT()
            print "open sp bt..."

    #获取当前电脑接入的SP
    def get_sp(self):
        deviceInfo= subprocess.check_output('adb devices -l')    
        sp=deviceInfo.split('\n')[1]
        sp_sn=sp.split(' ')[0]
        sp_name=sp.split(' ')[-1]
        deviceName = subprocess.check_output('adb shell getprop ro.product.model')
        return sp_sn,sp_name,deviceName

    #获取SP的所有信息
    def sp_info(self):
        sp_hand=check_sp()
        if sp_hand ==True:
            try:
                a=get_sp()
                model_number= subprocess.check_output('adb shell getprop ro.product.model')
                sp_ver=subprocess.check_output('adb shell getprop ro.build.version.release')
                sp_bui=subprocess.check_output('adb shell getprop ro.bootimage.build.fingerprint')
                sp_pro=subprocess.check_output('adb shell cat /proc/version')
                sp_med=subprocess.check_output('adb shell getprop ro.mediatek.version.release')
                SP_info={"SP SN":a[0],"SP Name":a[1],"SP Model number":model_number,"Android version":sp_ver,"SP Build nymber":sp_bui,
                    "SP Kernel version":sp_pro,"SP Custom build version":sp_med
                    }
                return SP_info
            except:
                error= "adb error."
                return error
        else:
            error= "not fond SP."
            return error

    #获取MTKLog
    def get_MTKLog(self,savepath):
        try:
            mtklog=subprocess.check_output('adb pull /storage/sdcard0/mtklog/ '+savepath)
            #print mtklog
            return mtklog
        except:
            error= "adb error."
            return error

    #安装apk
    def adb_install(self,apkpath):
        try:
            mtklog=subprocess.check_output('adb install '+apkpath)
            print mtklog
        except:
            print "fail"

    def connect_Wifi(self):
        d.open.quick_settings()
        wifi_c=d(text="Wi-Fi").wait.exists(timeout=500)
        wlan_c=d(text="WLAN").wait.exists(timeout=500)
        if wifi_c==True:
            d(text="Wi-Fi").click()
            d(text="7697AP").click()
            model_number= subprocess.check_output('adb shell input text \"12345678\"')
            d(text=" CONNECT").click()
            return 001
        elif wlan_c ==True:
            d(text="WLAN").click()
            d(text="7697AP").click()
            model_number= subprocess.check_output('adb shell input text \"12345678\"')
            d(text=u"连接").click()
            return 002
        else:
            return False

    # APK:  BluetoothLeTestClient
    def BluetoothLeTestClient_doing(self):
        #from uiautomator import device as d
        #d.wakeup()
        d.screen.on()
        d.swipe(700, 2300, 800, 10, steps=10)
        tester_tool.add_info("open BluetoothLeTestClient APK")
        keil_app=subprocess.check_output('adb shell am force-stop com.test.bluetooth.le.client')
        d.press.home()
        model_number= subprocess.check_output('adb shell am start -n com.test.bluetooth.le.client/com.test.bluetooth.le.client.DeviceScanActivity')
        open_bt=d(text="允许").wait.exists(timeout=500)
        scon_init=d(text="Scan").wait.exists(timeout=500)
        print open_bt
        if open_bt == True:
            d(text="允许").click()
        if scon_init == True:
            d(text="Scan").click()
        #time.sleep(5)
        #xml=d.dump()
        #print xml
        tester_tool.add_info("BluetoothLeTestClient APK doing Scan")
        scon_end=d(text="Scan").wait.exists(timeout=30000)
        a=d(text="cdf").wait.exists(timeout=5000)
        print a
        if a==True:
            tester_tool.add_info("BluetoothLeTestClient APK have BLE name :  cdf")
            #print "have cdf"
            #d.swipe(500, 500, 500, 10)
            d(text="cdf").click()
            tester_tool.add_info("BluetoothLeTestClient APK clicking cdf")
            #print "click cdf"
            d.wait.idle()
            conn=d(text=" Connected").wait.exists(timeout=20000)
            return conn
        elif a==False and scon_end== True:
            count = 0
            while (count < 3):
                print "have scon"
                d.swipe(700, 1800, 800, 10)
                if a==True:
                    d(text="cdf").click()
                    print "click cdf"
                    print "fund cdf"
                    break
                else:
                    print "go"
                print 'The count is:', count
                count = count + 1
            #info="not fund cdf"
            conn=d(text=" Connected").wait.exists(timeout=20000)
            if conn==True:
                con="ok"
                return con
            else:
                con="conn fail"
                return con
            #return info
        else:
            tester_tool.add_info("BluetoothLeTestClient APK not fund BLE name :  cdf")
            print "not fund cdf" 

    # APK:  BluetoothLeTestServer
    def BluetoothLeTestServer_doing(self):
        d.screen.on()
        d.swipe(700, 2300, 800, 10, steps=10)
        keil_app=subprocess.check_output('adb shell am force-stop com.test.bluetooth.le.server')
        d.press.home()
        model_number= subprocess.check_output('adb shell am start -n com.test.bluetooth.le.server/.DeviceControlActivity')
        #d(text="BLE Test Server").right().click()
        d(text='', className='android.widget.ImageButton').click()
        d(text="AdvertiserManager").click()
        d(text="Add").click()
        d(text="1. Add Advertiser 1").click()
        d(text="AdvertiserManager").click()



class SP_state:
    def __init__(self):
        self.init_sp=check_sp()
    #检查sp是否有连上a2dp
    def a2dp_init(self):
        if self.init_sp == True:
            deviceName = subprocess.check_output('adb shell \"dumpsys audio | grep \'Devices: \'\"')
            print "["+str(str(datetime.now()).split(" ")[1])[0:-7]+"] ==SP==  State ---> : BT Init Info."        
            print "- STREAM_VOICE_CALL:"+ str(deviceName.split("Devices:")[1])
            print "- STREAM_SYSTEM:"+str(deviceName.split("Devices:")[2])
            print "- STREAM_MUSIC:"+str(deviceName.split("Devices:")[4])
            print "- STREAM_BLUETOOTH_SCO:"+str(deviceName.split("Devices:")[7])
            if "bt_a2dp" in str(deviceName.split("Devices:")[4]) and str(deviceName.split("Devices:")[7]):
                return True
            else:
                return False
        else:
            print "Please examine ADB and SP !!!"

    #检查与sp 连接a2dp设备的名称
    def a2dp_devices(self):
        if self.init_sp == True:
            deviceName = subprocess.check_output('adb shell \"dumpsys audio | grep \'mBluetoothName\'\"')
            print "["+str(str(datetime.now()).split(" ")[1])[0:-7]+"] ==SP==  State ---> : Connected A2DP Devices Name."        
            #print deviceName
            if "null" in str(deviceName.split("mBluetoothName=")[1]):
                return "not connect a2dp devices!\n"
            else:
                return str(deviceName.split("mBluetoothName=")[1])
        else:
            print "Please examine ADB and SP !!!"
    #打开 media.player
    def open_music_player(self):
        if self.init_sp == True:
            subprocess.check_output('adb shell am start -a android.intent.action.MUSIC_PLAYER')
        else:
            print "Please examine ADB and SP !!!"

    #检查 player状态
    def player_state(self):
        if self.init_sp == True:
            deviceName = subprocess.check_output('adb shell \"dumpsys media.player | grep \'state\'\"')
            musicName = subprocess.check_output('adb shell \"dumpsys media.player | grep \'/proc/\'\"')
            #print musicName
            musicName_1 = str(musicName.split("/proc/")[-1])
            musicName_2 = str(musicName_1.split("/")[-1])
            if "mp3" in str(musicName_2.split(".")[-1]) or "wav" in str(musicName_2.split(".")[-1]):
                print "Music Name: "+ str(musicName_2.split(".")[0])
                #logger.info("Music Name: "+ str(musicName_2.split(".")[0]))
            else:
                print "not play music, plase play music;"
                
            if "state(0)" in deviceName:
                print "player_state : play"
                #logger.info("state : 0")
                return 1
            elif "state(2)" in deviceName:
                print "player_state : pause"
                #logger.info("state : 2")
                return 2
            else:
                print "player_state : not play music"
                #logger.info("state : ?")
                return 0
        else:
            print "Please examine ADB and SP !!!"

    def play_music_name(self):
        if self.init_sp == True:
            musicName = subprocess.check_output('adb shell \"dumpsys media.player | grep \'/proc/\'\"')
            musicName_1 = str(musicName.split("/proc/")[-1])
            musicName_2 = str(musicName_1.split("/")[-1])
            if "mp3" in str(musicName_2.split(".")[-1]) or "wav" in str(musicName_2.split(".")[-1]):
                print "Music Name: "+ str(musicName_2.split(".")[0])
                return str(musicName_2.split(".")[0])
            else:
                print "not play music, plase play music;"
        else:
            print "Please examine ADB and SP !!!"

    #检查call 状态
    def call_state(self):
        if self.init_sp == True:
            deviceName = subprocess.check_output('adb shell \"dumpsys window | grep \'mCurrentFocus\'\"')
            if "com.android.incallui.InCallActivity" in deviceName.split("/")[-1]:
                print "sp have call."
                return 101
            else:
                print "not call."
                return 102
        else:
            print "Please examine ADB and SP !!!"

    

你可能感兴趣的:(脚本,测试,python)