ATX 浅谈自动化测试工具 python-uiautomator2

1、简介

  python-uiautomator2是一个自动化测试开源工具,仅支持Android平台的原生应用测试

2、支持平台及语言

  python-uiautomator2封装了谷歌自带的uiautomator2测试框架,提供便利的python接口。他允许测试人员直接在PC上编写Python的测试代码,操作手机应用,完成自动化,大大提高了自动化代码编写的效率。

3、python-uiautomator2主要分为两个部分

  python端:运行脚本,并向移动设备发送HTTP请求

  移动设备:移动设备上运行了封装了uiautomator2的HTTP服务,解析收到的请求,并转化成uiautomator2的代码。

4、环境搭建

  安装adb并使手机或模拟器与电脑连接, adb.exe的目录加入到系统的PATH中

  adb connect 127.0.0.1:62001 连接设备

  adb devices 查看连接设备

  adb shell

5、安装python-uiautomator2

  pip install --pre -U uiautomator

  pip install pillow

6、设备安装atx-agent

  python -m uiautomator2 init 最后提示success,代表atx-agent初始化成功。

7、python-uiautomator2连接手机的方式有两种

  import uiautomator2 as u2

  d = u2.connect(‘192.168.1.169’)  // 通过WIFI

  d = u2.connect_usb(‘123456f’)    // 通过USB(手机的序列号可以通过adb devices获取到,假设序列号是123456f)

  d.make_toast("Hello world", 3)

  sess = d.session("com.netease.cloudmusic") # 启动网易云音乐( com.ss.android.ugc.aweme )

  sess(text="私人FM").click()

例子(九宫格解锁):

  import uiautomator2 as u2

  u = u2.connect() # 手机连接到PC即可

  u.swipe_points([(0.235, 0.456), (0.503, 0.449), (0.509, 0.601), (0.777, 0.603), (0.771, 0.763), (0.222, 0.75)], 0.2)

8、抓取手机上应用的控件

  虽然很想用Android SDK内置工具uiautomatorviewer.bat,但是运行uiautomator2的时候,uiautomatorviewer.bat运行不起来,两者之间冲突太严重。

  于是参考着uiautomatorviewer的界面,我又写了一个weditor,调用python-uiautomator2的两个接口screenshot和dump_hierarchy这样就不会有冲突问题了

9、安装weditor与运行

  pip install --pre weditor

  python -m weditor

10、定位方式

  a)、ResourceId定位:d(resourceId="com.smartisanos.clock:id/text_stopwatch").click()

  b)、Text定位:d(text="秒表").click()

  c)、Description定位:d(description="..").click()

  d)、ClassName定位:d(className="android.widget.TextView").click()

11、操作控件

  # click d(text="Settings").click()

  # long click d(text="Settings").long_click()

  # 等待元素的出现 d(text="Settings").wait(timeout=10.0)

12、中文字符的输入

  d(text="Settings").set_text("你好")

如果定位不到元素需要使用send_keys方法,以及切换输入法

  d.set_fastinput_ime(True)

  d.send_keys("你好 Hello")

  d.set_fastinput_ime(False) # 输入法用完关掉

  截图:d.screenshot("home.jpg")

  获取图层信息:xml = d.dump_hierarchy()

https://github.com/openatx/uiautomator2 GitHub文档

原文地址:https://www.cnblogs.com/eline2018/p/10366661.html