划重点!划重点!划重点!源码分析来啦 ,以上都是“拾人牙慧”的搬运教程,下面才是“精华”,我们开始看看源码。
从这个命令行启动的方式可以看出,这是用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)
好了,源码分析就这么多,下面进入实战阶段 ,怎么来做脚本的“批量运行”呢?很简单,有两种思路:
用unittest框架,在testcase里用exec_other_script接口来调air脚本
自己写一个循环,调用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