简单实例
注:安卓6.0以上的手机不会自动安装app-uiautomator.apk和app-uiautomator-test.apk,需要手动安装,否则报错ioerror RPC server not started
uiautomator +python+HTMLTestRunner 安卓UI自动化实现
#coding:utf-8
from uiautomator importDeviceimportosimportunittestfrom HTMLTestRunner importHTMLTestRunnerimporttime
d=Device(‘127.0.0.1:62001‘)printd.infoclassTestEle(unittest.TestCase):defsetUp(self):
cmd= ‘adb shell am start me.ele/me.ele.application.ui.home.HomeActivity‘os.system(cmd)
cmd= ‘adb shell am start me.ele/me.ele.shopping.ui.search.SearchActivity‘os.system(cmd)deftearDown(self):
cmd=‘adb shell am force-stop me.ele‘os.system(cmd)deftestSearch(self):
d(resourceId=‘me.ele:id/editor‘).set_text(‘coco‘)
d(resourceId=‘me.ele:id/search‘).click()
d.screenshot(r"E:\code\auto\ele_search.png")
self.assertTrue(d(text="coco").exists)if __name__ == ‘__main__‘:
suite=unittest.TestSuite()
suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestEle))
now= time.strftime(‘%Y-%m-%d‘, time.localtime(time.time()))
test_dir= r‘E:\code\auto‘filename= test_dir + ‘/‘ + now + ‘test_result.html‘fp= file(filename,‘wb‘)
runner= HTMLTestRunner(stream=fp, title=‘ele demo by uiautomator‘, description= u‘测试结果‘)
runner.run(suite)
注:
1.通过adb devices获取设备名,127.0.0.1:62001是夜神模拟器的设备名
2.通过adb shell dumpsys window | findstr mCurrentFocus命令获取apk应用名和.MainActivity,如me.ele/me.ele.application.ui.home.HomeActivity
3.‘adb shell am start me.ele/me.ele.application.ui.home.HomeActivity‘ 启动模拟器上app的activity,使用真机无法启动,可能是app应用不允许外部访问
C:\Users\admin>adb shell am start me.ele/me.ele.application.ui.home.HomeActivity
Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=me.ele/.application.ui.home.HomeActivity }
java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER]
flg=0x10000000 cmp=me.ele/.application.ui.home.HomeActivity } from null (pid=21101, uid=2000) not exported from uid 10046
at android.os.Parcel.readException(Parcel.java:1468)
at android.os.Parcel.readException(Parcel.java:1422)
at android.app.ActivityManagerProxy.startActivityAsUser(ActivityManagerNative.java:2150)
at com.android.commands.am.Am.runStart(Am.java:694)
at com.android.commands.am.Am.onRun(Am.java:272)
at com.android.internal.os.BaseCommand.run(BaseCommand.java:47)
at com.android.commands.am.Am.main(Am.java:78)
at com.android.internal.os.RuntimeInit.nativeFinishInit(Native Method)
at com.android.internal.os.RuntimeInit.main(RuntimeInit.java:243)
at dalvik.system.NativeStart.main(Native Method)
4.通过uiautomatorviewer获取resourceId
运行结果:d(text="coco").exists包含了搜索栏的‘coco‘,故而断言成功