環境:
Python3 + Android + Uiautomator1
unittest單元測試框架:見:https://www.cnblogs.com/yufeihlf/p/5707929.html
一、啓動 app startapp.py
# -*- coding:utf-8 -*-
import sys
#reload(sys)
#sys.setdefaultencoding("utf-8")
# author:Peng Ji time:2018/5/11
import os #導入系統命令模塊,用於調用adb命令來啓動指定APP
import time #導入時間模塊,用於調用時間等待
#import automail #這裏是導入我打包的自動發送mail腳本
import uiautomator #導入uiautomator模塊
import urllib
import importlib
importlib.reload(sys)
from uiautomator import device as d #導入uiautomator模塊中的device方法命名爲d
Phone=d.info #d.info會返會設備信息,需要注意的是,返回的是字典型
print(Phone) #在屏幕上打印出設備信息
h=Phone['displayHeight'] #這裏是從設備信息中獲取屏幕的尺寸
w=Phone['displayWidth']
def devicesInfo():
print(u"獲取設備信息")
Phone=d.info #d.info會返會設備信息,需要注意的是,返回的是字典型
print(Phone) #在屏幕上打印出設備信息
try:
devicesInfo()#這裏是捕獲各種異常,出現異常會提示 "獲取設備信息失敗,請檢查設備連接"
except:
print("獲取設備信息失敗,請檢查設備連接")
def LaunchAPP():
print('啓動APP')
os.system("adb shell monkey -p com.oneteam.theaccompanying -c android.intent.category.LAUNCHER 1")
#這裏是調用cmd adb shell 啓動指定的APP ,這裏的包名可以從uiautomatorviewer 中看到
if d(resourceId="com.oneteam.theaccompanying:id/textView_password").wait.exists(timeout=20000):
#這裏時判斷APP首頁中指定元素是否出現
print("APP啓動成功")
else:
print("APP首頁搜索框加載時間超過20S")
try:
LaunchAPP()
except:
print("APP啓動失敗")
測試腳本:
from uiautomator import device as d
import time
import sys
import random
import unittest
import HTMLTestRunner
#reload(sys)
#sys.setdefaultencoding("utf-8")
import importlib
importlib.reload(sys)
class My_Test_Suite(unittest.TestCase):
def setUp(self):
print (u"--------------初始化工作")
# 測試註冊
def test_reg(self):
print (u"--------------測試註冊")
# ........
# 測試登陸
def test_login(self):
print (u"test_login ")
try:
#d(text="登錄").click()
d(resourceId="com.oneteam.theaccompanying:id/textView_forget").clear_text()
d(resourceId="com.oneteam.theaccompanying:id/textView_forget").set_text('189xxxxxx')
d(resourceId="com.oneteam.theaccompanying:id/textView_password").set_text("123456")
d(text="登錄").click()
# d(text="請輸入您的姓名").set_text("123456")
# d(text="完成").click()
time.sleep(2)
# if d(text="簽到").exists:
print (u"登錄成功")
except Exception as e:
print (u"Error: 登錄失敗\n", e)
# 測試忘記密碼
def test_forget_password(self):
try:
pass # 一些測試步驟
except Exception as e:
print (u"Error: 重置密碼or修改密碼失敗\n", e)
#......更多的測試模塊用例
def tearDown(self):
try:
if d(text="我的").exists:
d(text="我的").click()
d(text="退出").click()
print (u"退出APP")
except Exception as e:
print (u"Error: 退出APP失敗\n", e)
if __name__ == "__main__":
print (u"__main__ ")
phone_number = '18911006376'
#random.choice(['139', '188', '185', '136', '158', '151'])+"".join(random.choice("0123456789") for i in range(8))
test_unit = unittest.TestSuite()
test_unit.addTest(My_Test_Suite("test_login"))
filename = './Result_auto_android.html'
#fp = open(filename, 'w',encoding="utf-16")
fp = open(filename, 'w')
runner = HTMLTestRunner.HTMLTestRunner(stream=fp,title=u"測試報告",description=u"測試結果詳情:")
runner.run(test_unit)
print (u"test_unit ")