UI自动化测试工具AirTest学习笔记之自定义启动器

通过本篇,你将了解到Airtest的自定义启动器的运用,以及air脚本启动运行的原理,还有批量执行air脚本的方法。

在用Airtest IDE可以编写air脚本,运行脚本,之后我们会想到那我怎么一次运行多条脚本呢?能不能用setup和teardown呢?答案是当然可以,我们可以用自定义启动器!参见官方文档:7.3 脚本撰写的高级特性

Airtest在运行用例脚本时,在继承unittest.TestCase的基础上,实现了一个叫做AirtestCase的类,添加了所有执行基础Airtest脚本的相关功能。因此,假如需要添加自定义功能,只需要在AirtestCase类的基础上,往setup和teardown中加入自己的代码即可。如果这些设置和功能内容相对固定,可以将这些内容作为一个launcher,用来在运行实际测试用例之前初始化相关的自定义环境。

在这个自定义启动器里我们可以做什么呢?

  • 添加自定义变量与方法
  • 在正式脚本运行前后,添加子脚本的运行和其他自定义功能
  • 修改Airtest默认参数值

通过以下的例子看一下怎么实现,首先创建一个custom_launcher.py文件,实现以下代码

from airtest.cli.runner import AirtestCase, run_script
from airtest.cli.parser import runner_parser

class CustomAirtestCase(AirtestCase):
    PROJECT_ROOT = "子脚本存放公共路径" 
    def setUp(self):
        print("custom setup")
        # add var/function/class/.. to globals
        #将自定义变量添加到self.scope里,脚本代码中就能够直接使用这些变量
        self.scope["hunter"] = "i am hunter"
        self.scope["add"] = lambda x: x+1
        #将默认配置的图像识别准确率阈值改为了0.75
        ST.THRESHOLD = 0.75

        # exec setup script
        # 假设该setup.air脚本存放在PROJECT_ROOT目录下,调用时无需填写绝对路径,可以直接写相对路径
        self.exec_other_script("setup.air")  
        super(CustomAirtestCase, self).setUp()

    def tearDown(self):
        print("custom tearDown")
        # exec teardown script
        self.exec_other_script("teardown.air")
        super(CustomAirtestCase, self).setUp()

if __name__ == '__main__':
    ap = runner_parser()
    args = ap.parse_args()
    run_script(args, CustomAirtestCase)

然后,在IDE的设置中配置启动器

菜单-“选项”-“设置”-“Airtest”,点击“自定义启动器”可打开文件选择窗口,选择自定义的launcher.py文件即可。

点击“编辑”,可对launcher.py文件的内容进行编辑,点击“确定”按钮让新配置生效。

也可以用命令行启动

python custom_launcher.py test.air --device Android:///serial_num --log log_path

看到这里都没有提供一次运行多条脚本方法,但是有提供调用其他脚本的接口,相信聪明的你应该有些想法了,这个后面再讲,因为官方文档里都说了IDE确实没有提供批量执行脚本的功能呢

我们在脚本编写完成后,AirtestIDE可以让我们一次运行单个脚本验证结果,但是假如我们需要在多台手机上,同时运行多个脚本,完成自动化测试的批量执行工作时,AirtestIDE就无法满足我们的需求了。

目前可以通过命令行运行手机的方式来实现批量多机运行脚本,例如在Windows系统中,最简单的方式是直接编写多个bat脚本来启动命令行运行Airtest脚本。如果大家感兴趣的话,也可以自行实现任务调度、多线程运行的方案来运行脚本。请注意,若想同时运行多个脚本,请尽量在本地Python环境下运行,避免使用AirtestIDE来运行脚本。

划重点!划重点!划重点!源码分析来啦 ,以上都是“拾人牙慧”的搬运教程,下面才是“精华”,我们开始看看源码。

从这个命令行启动的方式可以看出,这是用python运行了custom_launcher.py文件,给传入的参数是‘test.air’、‘device’、‘log’,那我们回去看一下custom_launcher.py的入口。

if __name__ == '__main__':
    ap = runner_parser()
    args = ap.parse_args()
    run_script(args, CustomAirtestCase)

runner_parser()接口是用ArgumentParser添加参数的定义

def runner_parser(ap=None):
    if not ap:
        ap = argparse.ArgumentParser()
    ap.add_argument("script", help="air path")
    ap.add_argument("--device", help="connect dev by uri string, e.g. Android:///", nargs="?", action="append")
    ap.add_argument("--log", help="set log dir, default to be script dir", nargs="?", const=True)
    ap.add_argument("--recording", help="record screen when running", nargs="?", const=True)
    return ap

 然后用argparse库解析出命令行传入的参数

    # =====================================
    # Command line argument parsing methods
    # =====================================
    def parse_args(self, args=None, namespace=None):
        args, argv = self.parse_known_args(args, namespace)
        if argv:
            msg = _('unrecognized arguments: %s')
            self.error(msg % ' '.join(argv))
        return args

最后调用run_script(),把解析出来的args和我们实现的自定义启动器——CustomAirtestCase类一起传进去

def run_script(parsed_args, testcase_cls=AirtestCase):
    global args  # make it global deliberately to be used in AirtestCase & test scripts
    args = parsed_args
    suite = unittest.TestSuite()
    suite.addTest(testcase_cls())
    result = unittest.TextTestRunner(verbosity=0).run(suite)
    if not result.wasSuccessful():
        sys.exit(-1)

这几行代码,用过unittest的朋友应该都很熟悉了,传入的参数赋值给一个全局变量以供AirtestCase和测试脚本调用,

  1. 创建一个unittest的测试套件;
  2. 添加一条AirtestCase类型的case,因为接口入参默认testcase_cls=AirtestCase,也可以是CustomAirtestCase
  3. 用TextTestRunner运行这个测试套件

所以Airtest的运行方式是用的unittest框架,一个测试套件下只有一条testcase,在这个testcase里执行调用air脚本,具体怎么实现的继续来看AirtestCase类,这是CustomAirtestCase的父类,这部分代码比较长,我就直接在源码里写注释吧

class AirtestCase(unittest.TestCase):

    PROJECT_ROOT = "."
    SCRIPTEXT = ".air"
    TPLEXT = ".png"

    @classmethod
    def setUpClass(cls):
        #run_script传进来的参数转成全局的args
        cls.args = args
        #根据传入参数进行初始化
        setup_by_args(args)
        # setup script exec scope
        #所以在脚本中用exec_script就是调的exec_other_script接口
        cls.scope = copy(globals())
        cls.scope["exec_script"] = cls.exec_other_script

    def setUp(self):
        if self.args.log and self.args.recording:
            #如果参数配置了log路径且recording为Ture
            for dev in G.DEVICE_LIST: 
                #遍历全部设备
                try:
                    #开始录制
                    dev.start_recording()
                except:
                    traceback.print_exc()

    def tearDown(self):
        #停止录制
        if self.args.log and self.args.recording:
            for k, dev in enumerate(G.DEVICE_LIST):
                try:
                    output = os.path.join(self.args.log, "recording_%d.mp4" % k)
                    dev.stop_recording(output)
                except:
                    traceback.print_exc()

    def runTest(self):
        #运行脚本
        #参数传入的air脚本路径
        scriptpath = self.args.script
        #根据air文件夹的路径转成py文件的路径
        pyfilename = os.path.basename(scriptpath).replace(self.SCRIPTEXT, ".py")
        pyfilepath = os.path.join(scriptpath, pyfilename)
        pyfilepath = os.path.abspath(pyfilepath)
        self.scope["__file__"] = pyfilepath
        #把py文件读进来
        with open(pyfilepath, 'r', encoding="utf8") as f:
            code = f.read()
        pyfilepath = pyfilepath.encode(sys.getfilesystemencoding())
        #用exec运行读进来的py文件
        try:
            exec(compile(code.encode("utf-8"), pyfilepath, 'exec'), self.scope)
        except Exception as err:
            #出错处理,记录日志
            tb = traceback.format_exc()
            log("Final Error", tb)
            six.reraise(*sys.exc_info())

    def exec_other_script(cls, scriptpath):
    #这个接口不分析了,因为已经用using代替了。
    #这个接口就是在你的air脚本中如果用了exec_script就会调用这里,它会把子脚本的图片文件拷过来,并读取py文件执行exec

总结一下吧,上层的air脚本不需要用到什么测试框架,直接就写脚本,是因为有这个AirtestCase在支撑,用runTest这一个测试用例去处理所有的air脚本运行,这种设计思路确实降低了脚本的上手门槛,跟那些用excel表格和自然语言脚本的框架有点像。另外setup_by_args接口就是一些初始化的工作,如连接设备、日志等

#参数设置
def setup_by_args(args):
    # init devices
    if isinstance(args.device, list):
        #如果传入的设备参数是一个列表,所以命令行可以设置多个设备哦
        devices = args.device
    elif args.device:
        #不是列表就给转成列表
        devices = [args.device]
    else:
        devices = []
        print("do not connect device")

    # set base dir to find tpl 脚本路径
    args.script = decode_path(args.script)

    # set log dir日志路径
    if args.log is True:
        print("save log in %s/log" % args.script)
        args.log = os.path.join(args.script, "log")
    elif args.log:
        print("save log in '%s'" % args.log)
        args.log = decode_path(args.log)
    else:
        print("do not save log")

    # guess project_root to be basedir of current .air path
    # 把air脚本的路径设置为工程根目录
    project_root = os.path.dirname(args.script) if not ST.PROJECT_ROOT else None
    # 设备的初始化连接,设置工程路径,日志路径等。
    auto_setup(args.script, devices, args.log, project_root)

好了,源码分析就这么多,下面进入实战阶段 ,怎么来做脚本的“批量运行”呢?很简单,有两种思路:

  1. 用unittest框架,在testcase里用exec_other_script接口来调air脚本
  2. 自己写一个循环,调用run_script接口,每次传入不同的参数(不同air脚本路径)
from launcher import Custom_luancher
from Method import Method
import unittest
from airtest.core.api import *
class TestCaseDemo(unittest.TestCase):
    def setUp(self):
        auto_setup(args.script, devices, args.log, project_root)

    def test_01_register(self):
        self.exec_other_script('test_01register.air')

    def test_02_name(self):
        self.exec_other_script('login.air')
        self.exec_other_script('test_02add.air')

    def tearDown(self):
        Method.tearDown(self)

if __name__ == "__main__":
    unittest.main()
def find_all_script(file_path):
    '''查找air脚本'''
    A = []
    files = os.listdir(file_path)
    for f1 in files:
        tmp_path = os.path.join(file_path, files)
        if not os.path.isdir(tmp_path):
            pass
        else:
            if(tmp_path.endswith('.air')):
                A.append(tmp_path)
            else:
                subList = find_all_script(tmp_path)
                A = A+subList
    return A

def run_airtest(path, dev=''):
    '''运行air脚本'''
    log_path = os.path.join(path, 'log')
    #组装参数
    args = Namespace(device=dev, log=log_path, recording=None, script=path)
    try:
        result = run_script(args, CustomLuancher)
    except:
        pass
    finally:
        if result and result.wasSuccessful():
            return True
        else:
            return False

if __name__ == '__main__':
    #查找指定路径下的全部air脚本
    air_list = find_all_script(CustomLuancher.PROJECT_ROOT)

    for case in air_list:
        result = run_airtest(case)
        if not result:
           print("test fail : "+ case)
        else:
           print("test pass : "+ case)
    sys.exit(-1)

总结,两种方式实现Airtest脚本的批量执行,各有优缺点,自己体会吧,如果喜欢Airtest的结果报告建议用第二种方式,可以完整的保留日志,结果以及启动运行。第一种方式是自己写的unittest来执行,就没有用的Airtest的启动器了,报告部分要自己再处理一下,然后每添加一条air脚本,对应这里也要加一条case。

  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值