51Testing软件测试论坛
标题:
python3 通过线程解决安装 apk 时的权限弹窗问题
[打印本页]
作者:
巴黎的灯光下
时间:
2019-4-10 16:19
标题:
python3 通过线程解决安装 apk 时的权限弹窗问题
在我们做UI自动化之前,需要自动安装apk,然而很多时候会遇到很多系统弹窗,那么我们可以用python3的线程去监控点掉系统弹窗,直到我们的目标apk安装成功,再退出这个线程。
# -*- coding: utf-8 -*-
# @author: xiaoxiao
# @date : 2019/4/6
import threading
import os
import uiautomator2 as u2
driver = u2.connect("882QADT9UWT")
class usb_install_thread(threading.Thread): # 安装确认
def __init__(self):
threading.Thread.__init__(self)
def run(self): # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
self.usb_install()
# 判断apk是否已经安装
def is_apk_has_installed(self, package_name, device_id = ''):
if device_id != '':
cmd = "adb -s " + str(device_id) + " shell pm list package | grep '" + str(package_name) +"'"
else:
cmd = "adb shell pm list package | grep '" + str(package_name) + "'"
result = os.popen(cmd).read()
return result
# 判断app应用是否启动到前台
def is_activity_started(self, package_name, device_id=''):
if device_id != '':
cmd_current_activity = "adb -s %s shell dumpsys activity activities | sed -En -e '/Running activities/,/Run #0/p' | grep 'ActivityRecord'" % device_id
else:
cmd_current_activity = "adb shell dumpsys activity activities | sed -En -e '/Running activities/,/Run #0/p' | grep 'ActivityRecord'"
cmd_result = str(self.shell(cmd_current_activity))
# 如果当前应用处于前台或resume后台状态,返回True
if package_name in cmd_result:
# 启动app后,如果有系统权限弹窗,也需要点掉它
if 'GrantPermissionsActivity' in cmd_result:
return False
return True
else:
return False
# 等待元素出现,默认等待10s
def wait_for_element_visible(self, text, timeout=10):
# return bool
return driver(text = text).wait(timeout=timeout)
# 点掉系统弹窗
def usb_install(self):
print("Begin to install apk...\n")
while True:
# 如果apk安装成功,则退出
if self.is_apk_has_installed('com.xxx'):
# print("The apk has been installed~")
break
# 点掉弹窗"允许"、"确认"、"继续安装"等
try:
driver(text="允许").click()
except:
pass
try:
driver(text="确认").click()
except:
pass
try:
driver(text="继续安装").click()
except:
pass
try:
driver(text="安装").click()
except:
pass
# 执行adb shell
def shell(self, cmd):
p = os.popen(cmd)
return p.read()
# 安装apk
def app_install(self, app_file_path, device_id = ''):
if device_id == '':
cmd = 'adb install -r ' + str(app_file_path)
else:
cmd = 'adb -s ' + str(device_id) +'install -r ' + str(app_file_path)
self.shell(cmd)
thread1 = usb_install_thread()
thread1.start()
print("The thread is alive: " + str(thread1.is_alive()))
thread1.app_install('/Users/xiaoxiao/Downloads/xxx.apk', '882QADT9UWT')
print("After install the apk, the thread is alive: " + str(thread1.is_alive()))
复制代码
欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/)
Powered by Discuz! X3.2