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 project_root = os.path.dirname( args.script) if not ST.PROJECT_ROOT else None # 此处不设置日志路径,防止生成多余的log.txt auto_setup(args.script, devices, None, project_root)
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 dirpath, _ = script_dir_name(args.script) # set log dir if args.log: args.log = script_log_dir(dirpath, args.log) print("save log in '%s'" % args.log) else: print("do not save log") # guess project_root to be basedir of current .air path project_root = os.path.dirname( args.script) if not ST.PROJECT_ROOT else None auto_setup(dirpath, devices, args.log, project_root)
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 dirpath, _ = script_dir_name(args.script) # set log dir if args.log: args.log = script_log_dir(dirpath, args.log) print("save log in '%s'" % args.log) else: print("do not save log") # set snapshot quality if args.compress: compress = args.compress else: compress = ST.SNAPSHOT_QUALITY if args.no_image: ST.SAVE_IMAGE = False # guess project_root to be basedir of current .air path project_root = os.path.dirname( args.script) if not ST.PROJECT_ROOT else None auto_setup(dirpath, devices, args.log, project_root, compress)
def begin(group_name, update_frequency): global StatusRun StatusRun = 1 if not cli_setup(): auto_setup( __file__, logdir=True, devices=[ "Android://127.0.0.1:5037/127.0.0.1:7555?cap_method=JAVACAP&&ori_method=ADBORI", ]) poco = AndroidUiautomationPoco() get_into_group = 0 group = poco('com.tencent.mm:id/baj') # group hook in WeChat for each_group in group: if each_group.get_text() == group_name: each_group.click() get_into_group = 1 if not get_into_group: StatusRun = 0 while (True): time.sleep(update_frequency) if is_bao_exist(): status = catch_bao(poco('com.tencent.mm:id/auk')[-1]) if status == 0: print('Fail to get Envelop\n') else: print('\nWin: ' + str(status)) setting.addMoney(status) print('Total Win: ' + str(setting.get_setting()['money']) + '\n') poco('com.tencent.mm:id/m1').click()
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 脚本的路径设置为工程根目录 project_root = os.path.dirname(args.script) if not ST.PROJECT_ROOT else None # 这个接口很熟悉吧,在IDE里新建一个air脚本就会自动生成这句,里面就设备的初始化连接,设置工程路径,日志路径。 auto_setup(args.script, devices, args.log, project_root)
def start_test(self, pages, ip=None, port=None, device_id=None): """ 开始测试 :param pages: 待测试的页面列表 :param ip: 测试手机的IP地址 option :param port: 测试手机的端口号 option :param device_id: 测试手机的设备id option :return: """ self.log_path = setup_log_path(create_report_dir(self.platform)) auto_setup(__file__, logdir=self.log_path) if pages is None or len(pages) == 0: self.log("没有设置测试页面") raise ValueError("没有设置测试页面") pages = [ page for page in map( lambda item: item if isinstance(item, PageData) else PageData(item), pages) ] if ip: url = "{0}:{1}".format(ip, port) else: url = "{0}".format(device_id) self.log_step("应用信息", 'AppId:{0}'.format(self.app_name)) self.log("应用信息:AppId:{0}".format(self.app_name)) self.log("开始连接设备:{0}".format(url)) try: self.driver = self.connect(ip, port, device_id) except Exception as e: self.test_result_status = False log = traceback.print_exc() print(log) self.log_error("连接设备失败") self.log_error(traceback.format_exc()) self.log_step("连接设备", '连接"{0}"失败:{1}'.format(url, e), False, traceback.format_exc()) raise e self.connected() self.check_device() self.check_version(self.version_name, self.version_code, self.app_url, self.is_cover_install) self.log("设备连接成功开始,开始测试.....") self.log_step("连接设备", '连接"{0}"成功'.format(url)) self.do_test(pages) name = report(self.task, self.log_path) self.upload_report(self.log_path, name) self.finished() if self.task is not None: self.log("{0}已执行完毕,报告已生成".format(self.task.name)) self.log_step("生成报告", "")
def test_auto_setup(self): # 连接本机默认端口连的一台设备号为SJE5T17B17的手机 auto_setup(__file__, devices=["Android://127.0.0.1:5037/SJE5T17B17"]) ## 连接本机默认端口连的设备号为123和456的两台手机 auto_setup(__file__, devices=[ "Android://127.0.0.1:5037/123", "Android://127.0.0.1:5037/456" ])
def setUp(self): if self.args.log and self.args.recording: for dev in G.DEVICE_LIST: try: dev.start_recording() except: traceback.print_exc() # 设置日志路径 auto_setup(logdir=self._logdir)
def __init__(self, device, logging_level=logging.ERROR): logger = logging.getLogger("airtest") logger.setLevel(logging_level) auto_setup(__file__, devices=[device]) start_app('com.tencent.qqlite') self.poco = AndroidUiautomationPoco( use_airtest_input=True, screenshot_each_action=False) self.normalize_qqlite()
def init_setup(device=None): """ 初始化airtest, 尝试连接安卓device :param device: * ``android:///`` # 本地adb device * ``android://adbhost:adbport/1234566?cap_method=javacap&touch_method=adb`` #远程adb device :return: None """ if device is None: device = ["android:///"] auto_setup(basedir=caseFileName, devices=device, logdir=reportLogDir)
def suite(): """ return test suite """ test_suite = unittest.TestSuite() # 添加执行case方法1 Testcases = [TestDemo] for i in Testcases: auto_setup(basedir=globalparam.test_images_path) # 初始化图像算法路径 test_suite.addTest(unittest.makeSuite(i)) return test_suite
def setUpClass(cls): #由子类构造日志目录和脚本目录 #取得case相关信息 if ST.REPORT_PATH: #生成日志需要配置这些信息 如果不配置日志路径 将不会生成报告和日志 infor=json.loads(get_script_info(cls.file)) #获得脚本信息 cls.__logPath, cls.__reportPath = makePath(cls.file) # 是否录像标志 cls.__recording=ST.RECORDING #type:bool makeCaseInfo(cls.file, cls.__reportPath,infor) auto_setup(basedir=cls.file, logdir=cls.__logPath) else: auto_setup()
def appium_desired(): data = get_desired_caps() desired_caps = data['desired_caps'] # airtest 输入法禁用 此输入法禁用后,无法使用poco().set_text() # yosemite = '?ime_method=None' auto_setup(__file__, devices=[ "Android:///%s?ime_method=ADBIME" % data['desired_caps']['udid'] ]) logging.info('start app...') driver = webdriver.Remote( 'http://%s:%s/wd/hub' % (data['ip'], data['port']), desired_caps) driver.implicitly_wait(3) return driver
def __init__(self): self.config = DeviceConfig.getDeviceConfig() if not cli_setup(): auto_setup(self.filePath(), logdir=True, devices=[ self.config.DEV, ]) logging.basicConfig( filename="log.txt", filemode='w', level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logging.getLogger(self.filePath()) ImageUtil.addLocalImageRoot(os.path.dirname(self.filePath()))
def execute(uuid, apk_path, package_name, game_name): # todo 需要加上这一句,否则pocoservice会报错 # init_device(uuid=uuid) log_dir = os.path.join(APP.AIRTEST_LOG_FILE_PATH, uuid, time.strftime("%Y_%m_%d_%H_%M_%S")) if not os.path.exists(log_dir): os.makedirs(log_dir) # todo 需要加上这一句,否则pocoservice会报错 auto_setup(basedir=APP.WORKSPACE, devices=["Android:///" + uuid], logdir=log_dir) Cases.execute_install(uuid, apk_path, package_name) Cases.execute_allow_permission(uuid, game_name) ret = run_one_report(os.path.join(APP.AIRTEST_LOG_FILE_PATH, "empty.py"), uuid, log_dir) return uuid, ret
def __init__(self, serial_number, task_list, status): from farmer.view import Cache self.status = status if Cache.running: raise TaskRunningError Cache.running = self self.status.set_status(self.status.RUNNING) try: connect_device(f"android:///{serial_number}?touch_method=adb") auto_setup(__file__) except: Cache.running = None self.status.set_status(self.status.READY) raise DeviceError self.task_list = deepcopy(task_list) self.thread = Thread(target=self._run_tasks)
def run_case(uuid): log_dir = os.path.join(APP.AIRTEST_LOG_FILE_PATH, uuid, time.strftime("%Y_%m_%d_%H_%M_%S")) if not os.path.exists(log_dir): os.makedirs(log_dir) # todo 需要加上这一句,否则pocoservice会报错 auto_setup(basedir=APP.WORKSPACE, devices=["Android:///" + uuid], logdir=log_dir) APK = "3139_wdsm_wdsm_3k_20191112_28835_28835.apk" game_name_, package_name_, launchable_activity = get_packagename_and_launchable_activity( APK) # discover = unittest.defaultTestLoader.discover(start_dir=APP.TEST_CASE_ROOT_PATH, # pattern="test*.py", # top_level_dir=None) # todo: 需要实现测试发现功能 # 这里需要注意一下:后续会开放多个接口,有一键执行多个用例接口,有执行特定用例接口; suite = unittest.TestSuite() suite.addTest( BaseCase.parametrize(TestInstall, uuid=uuid, group_name=game_name_, apk_path=APK, package_name=package_name_)) suite.addTest( BaseCase.parametrize(TestAllowPermission, uuid=uuid, group_name=game_name_, apk_path=APK, package_name=package_name_)) unittest.TextTestRunner().run(suite) ret_ = run_one_report(os.path.join(APP.AIRTEST_LOG_FILE_PATH, "empty.py"), uuid, log_dir) return uuid, ret_
def _wrap(*args, **kwargs): print("调用到了") print("这是 " + __file__) curdir_time = str(int(time.time())) logdir = log_path + '/' + curdir_time + '/' + func.__name__ print("日志路径:" + logdir) os.makedirs(logdir) auto_setup(__file__, logdir=logdir, project_root=True) print(func) func(*args) logfile = logdir + f'/{func.__name__}.html' simple_report(__file__, logpath=logdir, output=logfile) time.sleep(2) print("这是啥: " + pkdir) with open(logfile, 'r+', encoding='utf-8') as f: context = f.read() temp = context.replace(os.path.dirname(rootpath), '') print("看看:", os.path.dirname(rootpath)) # print(temp) allure.attach(temp, 'report.html', attachment_type=allure.attachment_type.HTML)
def run_case_auto(uuid, apk_path): """ 自动添加测试用例文件下全部用例(执行顺序需按照既定的规则) :param uuid: :param apk_path: :return: """ log_dir = os.path.join(APP.AIRTEST_LOG_FILE_PATH, uuid, time.strftime("%Y_%m_%d_%H_%M_%S")) if not os.path.exists(log_dir): os.makedirs(log_dir) # todo 需要加上这一句,否则pocoservice会报错 auto_setup(basedir=APP.WORKSPACE, devices=["Android:///" + uuid], logdir=log_dir) game_name, package_name, activity = get_packagename_and_launchable_activity( apk_path) # todo: 需要实现测试发现功能 # 这里需要注意一下:后续会开放多个接口,有一键执行多个用例接口,有执行特定用例接口; suite = suite_all_case(uuid, group_name=game_name, apk_path=apk_path, package_name=package_name) try: unittest.TextTestRunner().run(suite) except Exception as e: logger.info(str(e)) return uuid, {} else: # 运行报告 result = run_one_report( os.path.join(APP.AIRTEST_LOG_FILE_PATH, "empty.py"), uuid, log_dir) return uuid, result
class MyTestCase(unittest.TestCase): __file__ = os.getcwd() print(__file__) auto_setup(__file__) def setUp(self) -> None: init_device("Android", "CLBGL18A23000056") def test_1(self): touch( Template(r"tpl1606792128602.png", record_pos=(-0.12, 0.412), resolution=(1080, 1920)))
async def run_script(uuid): log_dir = os.path.join(APP.AIRTEST_LOG_FILE_PATH, uuid, time.strftime("%Y_%m_%d_%H_%M_%S")) if not os.path.exists(log_dir): os.makedirs(log_dir) # todo 需要加上这一句,否则pocoservice会报错 auto_setup(basedir=APP.WORKSPACE, devices=["Android:///" + uuid], logdir=log_dir) APK = "3139_wdsm_wdsm_3k_20191112_28835_28835.apk" game_name_, package_name_, launchable_activity = get_packagename_and_launchable_activity( APK) # 需要实现测试发现功能 suite = unittest.TestSuite() suite.addTest( BaseCase.parametrize(TestInstall, uuid=uuid, group_name=game_name_, apk_path=APK, package_name=package_name_)) suite.addTest( BaseCase.parametrize(TestAllowPermission, uuid=uuid, group_name=game_name_, apk_path=APK, package_name=package_name_)) # todo: 单元测试的run方法导致协程不能运行? unittest.TextTestRunner().run(suite) ret_ = run_one_report(os.path.join(APP.AIRTEST_LOG_FILE_PATH, "empty.py"), uuid, log_dir) return uuid, ret_
def run_case_by_custom(uuid, apk_path): """ 手动添加测试用例,确保用例执行顺序 :param uuid: :param apk_path: :return: """ log_dir = os.path.join(APP.AIRTEST_LOG_FILE_PATH, uuid, time.strftime("%Y_%m_%d_%H_%M_%S")) if not os.path.exists(log_dir): os.makedirs(log_dir) # todo 需要加上这一句,否则pocoservice会报错 auto_setup(basedir=APP.WORKSPACE, devices=["Android:///" + uuid], logdir=log_dir) game_name, package_name, activity = get_packagename_and_launchable_activity( apk_path) # 测试用例添加进测试套件 suite = unittest.TestSuite() param = (uuid, game_name, apk_path, package_name) # 参数 suite.addTest(BaseCase.parametrize(TestInstall, *param)) suite.addTest(BaseCase.parametrize(TestAllowPermission, *param)) try: unittest.TextTestRunner().run(suite) except Exception as e: logger.info(str("run_case_by_custom error: {0}".format(e))) return uuid, {} else: # 运行报告 result = run_one_report( os.path.join(APP.AIRTEST_LOG_FILE_PATH, "empty.py"), uuid, log_dir) return uuid, result
def setUp(self): auto_setup(logdir=self._logdir) self.RecordScreen()
from airtest.core.api import Template, auto_setup auto_setup(__file__) login_and_register = Template(r"tpl1565079561943.png", record_pos=(-0.174, -0.653), resolution=(1080, 1920)) login_username_label = Template(r"tpl1565079489937.png", record_pos=(-0.236, -0.686), resolution=(1080, 1920))
log.BEGIN() log.LOG('begin running') def endPorgram(): print('end the program') os._exit(0) # Connect the Android Stimulator and start WeChat try: log.LOG('begin connect android stimulator...') if not cli_setup(): auto_setup( __file__, logdir=True, devices=[ "Android://127.0.0.1:5037/127.0.0.1:7555?cap_method=JAVACAP&&ori_method=ADBORI", ]) poco = AndroidUiautomationPoco() #poco.device.wake() #poco(text='微信').click() except Exception as e: log.EXCEPTION(e) endPorgram() # Set the setting item group_name = input('\ngroup name: ') update_frequency = float(input('update frequency: ')) log.LOG('Setting Information: \nGroup Name: ' + group_name + '\nUpdate Frequency: ' + str(update_frequency) + '\n')
from airtest.cli.parser import cli_setup from airtest.core.android import Android from airtest.core.api import sleep, keyevent, auto_setup from airtest.core.cv import Template from settings import * if not cli_setup(): auto_setup(__file__, logdir=True, devices=[ "android://127.0.0.1:5037/%s" % (VM if DEBUG else WIRE_VIVO), ]) dev = Android() def home(): """ 返回家 :return: None """ while True: pos = Template(r"../item/home-tower.png").match_in(dev.snapshot()) if pos is not None: dev.touch(pos) sleep(1) break pos = Template(r"../item/home-map.png").match_in(dev.snapshot()) if pos is not None: