使用 uiautomator2+pytest+allure 进行 Android 的 UI 自动化测试

news2024/10/5 18:27:10

目录

前言:

介绍

pytest

uiautomator2

allure

环境搭建

pytest

uiautomator2

allure

pytest 插件

实例

初始化 driver

fixture 机制

数据共享

测试类

参数化

指定顺序

运行指定级别

重试

hook 函数

断言

运行

运行某个文件夹下的用例

运行某个方法

运行某个类

运行 P0 级

运行非 P0 级

main 方式

报告

失败详情

失败截图

uiautomator2 基本操作

启动服务

事件

点击

滑动

监听

查看元素

安装

启动工具

无线运行


前言:

uiautomator2是基于Android平台的UI自动化测试框架,pytest是一种功能丰富的Python测试框架,而allure是一种用于生成漂亮测试报告的工具。结合使用这三个工具,您可以进行Android的UI自动化测试,并生成直观且可视化的测试报告。

本文主要讲解使用 uiautomator2+pytest+allure 进行 Android 的 UI 自动化测试,其实主要目的是写一些实战的脚本来更深入学习 pytest 框架.

另外也顺便介绍一下 uiautomator2 这款自动化框架,在使用上也是非常的顺畅.

之前我已经使用 appium+testng 写了一套自动化脚本了并且在公司实际使用了.这次就不用公司的 app 测试了,使用上家公司 58 同城的 app 进行自动化测试.

介绍

做 UI 自动化肯定需要选择一种适合的测试框架,比如 java 的 testng、python 的 unittest,主要目的是让代码的层级明确、简洁、复用性强,本次介绍下 python 的 pytest 框架.

pytest

pytest 官方:pytest: helps you write better programs — pytest documentation

The pytest framework makes it easy to write small tests, yet scales to support complex functional testing for applications and libraries.

官方的一段介绍,简单来说就是让写测试代码更容易并且没有那么多约束.当然这块不重点介绍 pytest 为什么好、怎么好,只需要记住 pytest 就是一个测试框架就够了.

uiautomator2

uiautomator2 是一个 Android UI 自动化框架,支持 Python 编写测试脚本对设备进行自动.底层基于 Google uiautomator,隶属于最近比较火热的 openatx 项目中.

下图是运行示意图:

image

设备中需要安装 atx-agent 作为 uiautomator2 的服务端,解析收到的请求,并转化成 uiautomator2 的代码.总体看来交互过程没有那么繁琐,在实际使用上的确比 appium 快不少.

allure

allure 是一款测试报告,炫酷的页面加上多种数据统计,比 HTMLTestRunner 报告强百倍,当然也支持多语言.

官方地址:http://allure.qatools.ru

环境搭建

使用 mac 电脑搭建环境

pytest

最新版本出到 4.0 了,但是实际使用 4.0 和 allure 有些不兼容.
所以推荐使用 3.7 版本的 pytest

pip install pytest==3.7

uiautomator2

uiautomator2 也是 python 的一个类库,用 pip 安装即可.

pip install uiautomator2

allure

brew install allure
pip install pytest-allure-adaptor

有了测试框架、自动化框架、测试报告,基本上就能 coding 了.

pytest 插件

pytest 插件可以实现失败重试、打印进度、指定顺序

pip install pytest-sugar # 打印进度

pip install pytest-rerunfailures # 失败重试

pip install pytest-ordering # 执行顺序

当然插件还有很多,这里就不一一介绍了.

实例

初始化 driver

做 UI 自动化都需要初始化一个 driver 对象,这个 driver 对象可以点击事件、滑动、双击等操作

uiautomator2 的初始化 driver 方式

相比 appium 配置很少,同时可以设置全局隐式等待元素时间

import uiautomator2  as ut2
def init_driver(self,device_name):
    '''
    初始化driver
    :return:driver
    '''
    try:
        logger.info(device_name)
        d = ut2.connect(device_name)
        #logger.info("设备信息:{}".format(d.info))
        # 设置全局寻找元素超时时间
        d.wait_timeout = wait_timeout  # default 20.0
        # 设置点击元素延迟时间
        d.click_post_delay = click_post_delay
        #d.service("uiautomator").stop()
        # 停止uiautomator 可能和atx agent冲突
        logger.info("连接设备:{}".format(device_name))
        return d
    except Exception as e:
        logger.info("初始化driver异常!{}".format(e))

fixture 机制

unittest 框架有 setup 和 teardown 方法,用来做初始化和结束测试操作.pytest 是用@pytest.fixture方法来实现 setup 和 teardown.

下面这段代码就是定义一个 driver_setup 方法,来初始化和结束.

# 当设置autouse为True时,
# 在一个session内的所有的test都会自动调用这个fixture
@pytest.fixture()
def driver_setup(request):
    logger.info("自动化测试开始!")
    request.instance.driver = Driver().init_driver(device_name)
    logger.info("driver初始化")
    request.instance.driver.app_start(pck_name, lanuch_activity, stop=True)
    time.sleep(lanuch_time)
    allow(request.instance.driver)
    def driver_teardown():
        logger.info("自动化测试结束!")
        request.instance.driver.app_stop(pck_name)
    request.addfinalizer(driver_teardown)

另外还有一种方式实现,可以理解为 setup 和 teardown 在一个方法内,通过 yield 关键字停顿.

@pytest.fixture()
def init(self,scope="class"):
    self.home = Home(self.driver)
    self.home.news_tab()
    self.news = News(self.driver)
    logger.info("初始化消息模块")
    yield self.news
    logger.info("结束消息模块")

yield 关键字是在 python 语法生成器和迭代器中使用,用来节省内存.
比如 for 循环一个大列表,一次性都循环出来非常浪费性能.
所以通过 yield 关键字来控制循环.

下面演示下 yield:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

def yt():
    print "第一次打印"
    yield 0
    print("第二次打印")

if __name__ == '__main__':
    a = yt()
    print next(a)
    print next(a)

如果直接调用 yt 函数会发现啥也打印不出来,因为此时只是声明了 yt 函数并没有真正的使用.

使用 next 方法调用第一次,输入结果如下:

yield 在此时相当于 return 0,此时不会输出"第二次打印",会在这块停住.

第一次打印
0

使用 next 方法调用第二次,输入结果如下:

第二次打印

再来回顾下上面那个例子:

在 yield 之前完成了 setup 操作并且返回 self.news 对象

在 yied 之后完成了 teardown 操作

@pytest.fixture()
def init(self,scope="class"):
    self.home = Home(self.driver)
    self.home.news_tab()
    self.news = News(self.driver)
    logger.info("初始化消息模块")
    yield self.news
    logger.info("结束消息模块")

数据共享

在 pytest 中只需要写 conftest.py 类,可以实现数据共享,不需要 import 就能自动找到一些配置.

刚才讲到的初始化 driver_setup 函数,就可以定在 conftest.py 类中,此时这个函数是全局可以函数,在测试类中使用如下:
使用@pytest.mark.usefixtures 装饰器就能引用到 driver_setup 函数

@allure.feature("测试发布")
@pytest.mark.usefixtures('driver_setup')
class TestNews:

    @pytest.fixture(params=item)
    def item(self, request):
        return request.param

测试类

pytest 检测如果是 test 开头或者 test 结尾的类,都认为是可以执行测试类.

在测试类中写 test 开头的测试方法

@allure.story('测试首页搜索')
def test_home_search(self,init):
    init.home_search()

参数化

假设场景是首页搜索多个词,需要借助参数化来完成

使用@pytest.mark.parametrize

@pytest.mark.parametrize(('kewords'), [(u"司机"), (u"老师"), (u"公寓")])
def test_home_moresearch(self, init,kewords):
    init.home_more_search(kewords)

指定顺序

假设发布用例,需要先登录才可以.可以通过用例排序的方式先登录,再发布

使用@pytest.mark.run,odrer 从小到大优先执行

@pytest.mark.usefixtures('driver_setup')
@pytest.mark.run(order=1)
# 指定login先执行
class TestLogin:

运行指定级别

假设已经写了很多用例,有些用例是冒烟用例,可以指定级别运行.
使用@pytest.mark.P0

@allure.story('测试首页更多')
@pytest.mark.P0
def test_home_more(self, init):
    init.home_more()

命令行执行: pytest -v -m "P0", 会执行所有 P0 级别的用例

重试

这个时候需要借助 pytest-rerunfailures 插件,用法如下:

@pytest.mark.flaky(reruns=5, reruns_delay=2)
@allure.story('测试精选活动')
def test_news_good(self,init):
    init.news_good()

当然这种方法是指定某个 case 失败重试

还可以全局设置用户如下:

pytest --reruns 2 --reruns_delay 2

reruns:重试次数

reruns_delay:重试的间隔时间

hook 函数

在 conftest.py 文件中定义@pytest.hookimpl函数,这个函数可以 hook 住 pytest 运行的状况

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    '''
    hook pytest失败
    :param item:
    :param call:
    :return:
    '''
    # execute all other hooks to obtain the report object
    outcome = yield
    rep = outcome.get_result()
    # we only look at actual failing test calls, not setup/teardown
    if rep.when == "call" and rep.failed:
        mode = "a" if os.path.exists("failures") else "w"
        with open("failures", mode) as f:
            # let's also access a fixture for the fun of it
            if "tmpdir" in item.fixturenames:
                extra = " (%s)" % item.funcargs["tmpdir"]
            else:
                extra = ""
            f.write(rep.nodeid + extra + "\n")

从代码中可以看出可以获取失败情况的相关信息,当时有了失败信息就可以搞事情了,比如当用例失败的时候截图或者记录失败数量做数据统计.

断言

在跑用例的时候最后一步都会断言一下,比如断言元素是否存在等

def assert_exited(self, element):
    '''
    断言当前页面存在要查找的元素,存在则判断成功
    :param driver:
    :return:
    '''
    if self.find_elements(element):
        logger.info("断言{}元素存在,成功!".format(element))
        assert True
    else:
        logger.info("断言{}元素存在,失败!".format(element))
        assert False

还可以这样优化代码:

def assert_exited(self, element):
  '''
  断言当前页面存在要查找的元素,存在则判断成功
  :param driver:
  :return:
  '''
  assert self.find_elements(element) == True,"断言{}元素存在,失败!".format(element)
  logger.info("断言{}元素存在,成功!".format(element))

assert 失败后会跑出 AssertionError 和定义的文案

AssertionError: 断言xxxxx元素存在,失败!

运行

介绍下几种常用命令行运行

运行某个文件夹下的用例

运行某个文件下的所有用例

pytest android/testcase

运行某个方法

类文件地址::方法名

pytest test_home.py::test_home_more

或者使用-k 参数 + 方法名

pytest -k test_home_more

运行某个类

有的时候需要调试正个测试类中所有测试方法

直接跟上类文件地址

pytest test_home.py

运行 P0 级

pytest -v -m "P0"

运行非 P0 级

pytest -v -m "not P0"

main 方式

在 run.py 中写如下代码,这种方式相当于把命令行参数封装到脚本中.

pytest.main(["-s","--reruns=2", "android/testcase","--alluredir=data"])

报告

测试代码写完了,还差一个非常好看的报告.以前我们一般都用 HTMLTestRunner 报告,但是 HTMLTestRunner 报告功能比较单一并且也不支持失败截图.

偶然在社区中看到了 allure 的帖子,看了展示报告简直是吊炸天,先附一张跑完用例的截图.

image

image

另外可以在代码中设置报告层次,用法如下:

@allure.feature("测试首页")
@pytest.mark.usefixtures('driver_setup')
class TestHome:

    @pytest.fixture()
    def init(self,scope="class"):
        self.home = Home(self.driver)
        logger.info("初始化首页模块")
        yield self.home
        logger.info("结束首页模块")


    @allure.story('测试首页搜索')
    def test_home_search(self,init):
        init.home_search()

设置 allure.feature 和 allure.story,相当于上下级关系.

失败详情

点击失败用例就能看到失败的相关信息

image

失败截图

在跑自动化的过程已经遇到失败情况,需要一张截图描述当时的情况.

在上面提到@pytest.hookimpl函数中,最后调用截图方法,使用
allure.attach 把截图加上.

需要注意的是 attach 中的第二个参数是图片的二进制信息.

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    '''
    hook pytest失败
    :param item:
    :param call:
    :return:
    '''
    # execute all other hooks to obtain the report object
    outcome = yield
    rep = outcome.get_result()
    # we only look at actual failing test calls, not setup/teardown
    if rep.when == "call" and rep.failed:
        mode = "a" if os.path.exists("failures") else "w"
        with open("failures", mode) as f:
            # let's also access a fixture for the fun of it
            if "tmpdir" in item.fixturenames:
                extra = " (%s)" % item.funcargs["tmpdir"]
            else:
                extra = ""
            f.write(rep.nodeid + extra + "\n")
        pic_info = adb_screen_shot()
        with allure.step('添加失败截图...'):
            allure.attach("失败截图", pic_info, allure.attach_type.JPG)    

image

uiautomator2 基本操作

启动服务

执行如下命令:

python -m uiautomator2 init

会在手机上安装 atx-agent.apk 并且会在手机上启动服务

2018-12-14 18:03:50,691 - __main__.py:327 - INFO - Detect pluged devices: [u'a3f8ca3a']
2018-12-14 18:03:50,693 - __main__.py:343 - INFO - Device(a3f8ca3a) initialing ...
2018-12-14 18:03:51,154 - __main__.py:133 - INFO - install minicap
2018-12-14 18:03:51,314 - __main__.py:140 - INFO - install minitouch
2018-12-14 18:03:51,743 - __main__.py:168 - INFO - apk(1.1.7) already installed, skip
2018-12-14 18:03:51,744 - __main__.py:350 - INFO - atx-agent is already running, force stop
2018-12-14 18:03:52,308 - __main__.py:213 - INFO - atx-agent(0.5.0) already installed, skip
2018-12-14 18:03:52,490 - __main__.py:254 - INFO - launch atx-agent daemon
2018-12-14 18:03:54,568 - __main__.py:273 - INFO - atx-agent version: 0.5.0
atx-agent output: 2018/12/14 18:03:52 [INFO][github.com/openatx/atx-agent] main.go:508: atx-agent listening on 192.168.129.93:7912

监听的是手机上的 ip+ 默认 7921.

事件

事件类型比如点击和滑动等,介绍几个常用的.

点击

根据 id、xpath、text 定位元素,和 appium 使用上差别不大.

self.d(resourceId=element).click()
self.d.xpath(element).click()
self.d(text=element).click()

滑动

前 4 个参数是坐标,time 是控制滑动时间

self.d.drag(self.width / 2, self.height * 3 / 4, self.width / 2, self.height / 4, time)

监听

这个用于首次启动 app 点击权限或者开屏幕广告

when 方法就相当于 if 判断,满足条件才会点击,可以生去一大堆逻辑代码.

driver.watcher("允许").when(text="允许").click(text="允许")
driver.watcher("跳过 >").when(text="跳过 >").click(text="跳过 >")
driver.watcher("不要啦").when(text="不要啦").click(text="不要啦")

查看元素

安装

需要安装 weditor 库

pip install weditor

启动工具

python -m weditor

会在自动打开浏览器并且展示元素,相当于 web 版本的 uiautomatorviewer,使用起来比较方便.

image

无线运行

上边提到的手机 ip,有个这个手机 ip 就可以进行无线运行脚本

把 connect 中的方法替换成手机 ip 就可以了

# d = ut2.connect(device_name)
d = ut2.connect("192.168.129.93")

  作为一位过来人也是希望大家少走一些弯路

在这里我给大家分享一些自动化测试前进之路的必须品,希望能对你带来帮助。

(软件测试相关资料,自动化测试相关资料,技术问题答疑等等)

相信能使你更好的进步!

点击下方小卡片

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/768323.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

unity 2019 内置渲染管线 光照与Lighting面板 参数详解

文章目录 前言一 Unity的光照 与 烘焙光照1 unity完整的光照组成2 光的亮度与颜色3 全局光照直接光间接光5 间接光≠光照贴图 二 色彩空间与自动烘焙1 unity的色彩空间2 自动烘焙光照 三 烘焙1 什么是烘焙,烘焙的是什么2 如何进行烘焙3 烘焙的优点和缺点4 查看光照贴…

Redis : zmalloc.h:50:31: 致命错误:jemalloc/jemalloc.h:没有那个文件或目录

In file included from adlist.c:34:0: zmalloc.h:50:31: 致命错误&#xff1a;jemalloc/jemalloc.h&#xff1a;没有那个文件或目录 #include <jemalloc/jemalloc.h> 解决 : 如上图使用命令 make MALLOClibc

2023杭电多校(一)

1002 City Upgrading 类似题及其题解 City Upgrading Time Limit: 12000/6000 MS (Java/Others) Memory Limit: 524288/131072 K (Java/Others) Total Submission(s): 306 Accepted Submission(s): 78 Problem Description The city where crazyzhk resides is stru…

分布式事务几种实现方案

前言 分布式事务&#xff1f; 分布式事务是指涉及多个参与者的事务&#xff0c;这些参与者可能分布在不同的计算机、进程或者网络中。分布式事务需要保证ACID属性&#xff0c;即原子性、一致性、隔离性和持久性 解释 现在我们接触的系统基本上都是分布式系统&#xff0c;并且每…

计算几何(二维),定理及证明(持续更新中..)

注&#xff1a;定理来自这篇博客&#xff0c;本文注重证明 向量基本运算 加法 向量 a ⃗ ( x 1 , y 1 ) , b ⃗ ( x 2 , y 2 ) \vec{a}\left(x_1,y_1\right),\vec{b}\left(x_2,y_2\right) a (x1​,y1​),b (x2​,y2​) 则 a ⃗ b ⃗ ( x 1 x 2 , y 1 y 2 ) \vec{a}\…

P7 第二章 电阻电路的等效变换

1、等效变换应用举例 化简套路&#xff1a; 电压源与其串联的电阻&#xff0c;可以等效为电流源并联电阻&#xff0c;然后电流源就可以拿去合并电路中的&#xff0c;与之并联的电流&#xff0c;电阻则可以拿去合并与之并联的电阻。 公式法&#xff1a; 就是根据端的电压与端的…

第一节 C++ 变量

文章目录 1. Visual Studio Community 安装1.1. Visual Studio 介绍1.2. Visual Studio的安装1.3 Visual Studio创建与使用1.3.1 创建一个工程项目1.3.2 新建一个C文件1.3.3 编写执行文件 2. Dev-C 安装(初学者建议使用)2.1 Dev-C 介绍2.2 Dev-C 安装2.3 Dev-C 快捷键使用 3. 认…

数学建模常用模型(九) :偏最小二乘回归分析

数学建模常用模型&#xff08;九&#xff09; &#xff1a;偏最小二乘回归分析 偏最小二乘回归&#xff08;Partial Least Squares Regression&#xff0c;PLS Regression&#xff09;是一种常用的统计建模方法&#xff0c;用于解决多元线性回归中自变量间高度相关的问题。在偏…

【java】三大容器类(List、Set、Map)的常用实现类的特点

三大容器类&#xff08;List、Set、Map&#xff09;的常用实现类的特点 简介 本文总结三大容器类&#xff08;List、Set、Map&#xff09;的常用实现类&#xff08;ArrayList、Vector、LinkedList、HashSet、HashMap、HashTable&#xff09;的特点 一、List部分 1、ArrayLi…

C# DlibDotNet 人脸识别、人脸68特征点识别、人脸5特征点识别、人脸对齐,三角剖分,人脸特征比对

人脸识别 人脸68特征点识别 人脸5特征点识别 人脸对齐 三角剖分 人脸特征比对 项目 VS2022.net4.8OpenCvSharp4DlibDotNet Demo下载 代码 using DlibDotNet.Extensions; using DlibDotNet; using System; using System.Collections.Generic; using System.ComponentModel; …

学堂在线数据结构(上)(2023春)邓俊辉 课后作业错题整理

The reverse number of a sequence is defined as the total number of reversed pairs in the sequence, and the total number of element comparisons performed by the insertion sort in the list of size n is: 一个序列的逆序数定义为该序列中的逆序对总数&#xff0c;…

transformer Position Embedding

这是最近一段很棒的 Youtube 视频&#xff0c;它深入介绍了位置嵌入&#xff0c;并带有精美的动画&#xff1a; Transformer 神经网络视觉指南 -&#xff08;第 1 部分&#xff09;位置嵌入 让我们尝试理解计算位置嵌入的公式的“sin”部分&#xff1a; 这里“pos”指的是“单词…

自定义view(一)----自定义TextView

自定义view也算是Android的一大难点&#xff0c;里面涉及到很多值得学习的地方&#xff0c;我会在接下来写一系列文章去介绍它&#xff0c;本篇文章以自定义一个TextView为例。 View的构造方法 自定义view之前我们先了解view的四个构造方法&#xff0c;自定义view无非就是新建一…

R语言逻辑回归(Logistic Regression)、回归决策树、随机森林信用卡违约分析信贷数据集...

原文链接&#xff1a;http://tecdat.cn/?p23344 本文中我们介绍了决策树和随机森林的概念&#xff0c;并在R语言中用逻辑回归、回归决策树、随机森林进行信用卡违约数据分析&#xff08;查看文末了解数据获取方式&#xff09;&#xff08;点击文末“阅读原文”获取完整代码数据…

MVSNet、PatchMatchNet中的 eval.sh文件超参数解释

下面以PatchMatchNet为例, 打开PatchMatchNet程序中的 eavl.sh文件, 可以看到文件设置了数据集路径,及超参数设置(超参数,也可以不写,会使用默认参数) 上图中各参数意思如下: 执行文件python eval.py; 数据集加载方方式使用dtu_yao_eval ; batch_size=1 ,视图数N设…

【C++】命名空间 ( namespace )

目录搁这 什么是命名空间命名空间的作用如何定义命名空间命名空间的种类如何使用命名空间内的成员作用域限定符命名空间展开命名空间全部展开命名空间部分展开 总结 什么是命名空间 命名空间是一种用来避免命名冲突的机制&#xff0c;它可以将一段代码的名称隔离开&#xff0c…

中国地图使用心得

中国地图使用心得 注册地图是注册在echarts对象上而非 自己构建的echarts dom上、。 请求本地json文件 ​ vue项目的public打包时不会动&#xff0c;所以线上和本地地址直接指向了public同级目录&#xff0c;请求时直接相对路径 绘制中国地图时&#xff0c;如何在各个省会地方…

「深度学习之优化算法」(十三)蝙蝠算法

1. 蝙蝠算法简介 (以下描述,均不是学术用语,仅供大家快乐的阅读)   蝙蝠算法(Bat Algorithm)是受蝙蝠回声定位的特性启发而提出的新兴算法,提出时间是2010年,虽然距今(2020)有近10年,但与其它的经典算法相比仍算一个新算法。算法也已有一定规模的研究和应用,但仍…

【LLM系列之LLaMA2】LLaMA 2技术细节详细介绍!

Llama 2 发布&#xff01; Meta 刚刚发布了 LLaMa 2&#xff0c;它是 LLaMA 的下一代版本&#xff0c;具有商业友好的许可证。&#x1f92f;&#x1f60d; LLaMA 2 有 3 种不同的尺寸&#xff1a;7B、13B 和 70B。 7B & 13B 使用与 LLaMA 1 相同的架构&#xff0c;并且是商…