def get_captcha(self, element, language='eng', highlight_seconds=0): """ 识别图片验证码 :param element: 验证码图片元素 :param language: eng:英文,chi_sim:中文 :return: """ # 为防止截图包含高亮影响识别,元素不进行高亮 captcha_webElement = self._change_element_to_webElement_type( element, highlight_seconds) left = captcha_webElement.location['x'] top = captcha_webElement.location['y'] right = captcha_webElement.location['x'] + captcha_webElement.size[ 'width'] bottom = captcha_webElement.location['y'] + captcha_webElement.size[ 'height'] # 首先进行屏幕截图 captcha_image_file_name = DateTimeTool.getNowTime( '%Y%m%d%H%M%S%f_') + 'captcha.png' captcha_image_file_name = os.path.abspath( 'output/web_ui/' + self._config.current_browser + '/' + captcha_image_file_name) self._driver.get_screenshot_as_file(captcha_image_file_name) img = Image.open(captcha_image_file_name) # 验证码图片裁切并保存 img = img.crop((left, top, right, bottom)) img.save(captcha_image_file_name) # 识别图片验证码 captcha = CaptchaRecognitionTool.captchaRecognition( captcha_image_file_name, language) captcha = captcha.strip() captcha = captcha.replace(' ', '') return captcha
def mitmproxy_init(): mitmproxy_config = Read_Mitmproxy_Config().mitmproxy_config port = mitmproxy_config.proxy_port if "windows" == platform.system().lower(): get_mitmproxy_process_id_command = 'netstat -ano|findstr "0.0.0.0:%s"' % port try: mitmproxy_process_id = subprocess.check_output( get_mitmproxy_process_id_command, shell=True) mitmproxy_process_id = mitmproxy_process_id.decode('utf-8') mitmproxy_process_id = StrTool.getStringWithLBRB( mitmproxy_process_id, 'LISTENING', '\r\n').strip() kill_mitmproxy_process_command = 'taskkill /F /pid %s' % mitmproxy_process_id try: print('%s关闭mitmproxy进程,进程id:%s,该进程监听已监听端口:%s' % (DateTimeTool.getNowTime(), mitmproxy_process_id, port)) subprocess.check_call(kill_mitmproxy_process_command, shell=True) except: print('%s关闭mitmproxy进程失败,进程id:%s,该进程监听已监听端口:%s' % (DateTimeTool.getNowTime(), mitmproxy_process_id, port)) except: print('%smitmproxy未查找到监听端口%s的服务' % (DateTimeTool.getNowTime(), port)) elif "linux" == platform.system().lower(): # 获得当前mitmproxy所有进程id get_mitmproxy_process_ids_command = "ps -ef|grep 'mitmdump'|grep -v grep|awk '{print $2}'" try: mitmproxy_process_ids = subprocess.check_output( get_mitmproxy_process_ids_command, shell=True) mitmproxy_process_ids = mitmproxy_process_ids.decode('utf-8') get_lambda = lambda info: list(filter(None, info.split('\n')) ) if info else [] mitmproxy_process_ids = get_lambda(mitmproxy_process_ids) if not len(mitmproxy_process_ids) > 0: print('%smitmproxy未查找到监听端口%s的服务' % (DateTimeTool.getNowTime(), port)) for mitmproxy_process_id in mitmproxy_process_ids: try: print('%s关闭mitmproxy进程,进程id:%s,该进程监听已监听端口:%s' % (DateTimeTool.getNowTime(), mitmproxy_process_id, port)) subprocess.check_output("kill -9 " + mitmproxy_process_id, shell=True) except: print('%s关闭mitmproxy进程失败,进程id:%s,该进程监听已监听端口:%s' % (DateTimeTool.getNowTime(), mitmproxy_process_id, port)) except: print('%smitmproxy未查找到监听端口%s的服务' % (DateTimeTool.getNowTime(), port)) elif "darwin" == platform.system().lower(): pass print('%s启动mitmproxy,使用端口%s' % (DateTimeTool.getNowTime(), port)) p = multiprocessing.Process(target=start_mitmproxy, args=(port, )) p.daemon = True p.start()
def stop_recording_screen(self, fileName=''): """ 停止录像并将视频附加到报告里 :param fileName: :return: """ fileName = DateTimeTool.getNowTime('%Y%m%d%H%M%S%f_') + fileName data = self._driver.stop_recording_screen() allure.attach(name=fileName, body=base64.b64decode(data), attachment_type=allure.attachment_type.MP4)
def stop_android_monkey(self, udid: str, sub_p=None): if sub_p: sub_p.kill() #kill monkey monkey_process_id = '' if 'Windows' == platform.system(): get_monkey_process_id_command = 'adb -s %s shell ps|findstr monkey' % udid try: monkey_process_id = subprocess.check_output( get_monkey_process_id_command, shell=True) monkey_process_id = monkey_process_id.decode('utf-8') except: print('%s未查找到%s的monkey服务' % (DateTimeTool.getNowTime(), udid)) else: get_monkey_process_id_command = 'adb -s %s shell ps|grep monkey' % udid try: monkey_process_id = subprocess.check_output( get_monkey_process_id_command, shell=True) monkey_process_id = monkey_process_id.decode('utf-8') except: print('%s未查找到%s的monkey服务' % (DateTimeTool.getNowTime(), udid)) if monkey_process_id: get_lambda = lambda info: list(filter(None, info.split(' ')) ) if info else [] monkey_process_id = get_lambda(monkey_process_id) monkey_process_id = monkey_process_id[1] kill_monkey_process_command = 'adb -s %s shell kill %s' % ( udid, monkey_process_id) try: result = subprocess.check_call(kill_monkey_process_command, shell=True) print('%s关闭monkey进程,进程id:%s' % (DateTimeTool.getNowTime(), monkey_process_id)) return result except: print('%s关闭monkey进程,进程id:%s' % (DateTimeTool.getNowTime(), monkey_process_id))
def send_by_markdown(self,title:str,text:str,atMobiles:list=(),isAtAll=False): params = {} params.update({'msgtype': 'markdown'}) params.update({'markdown': {'title': title,'text':text}}) at_params = {} if not isinstance(atMobiles, list): atMobiles = list(atMobiles) at_params.update({'at': {'atMobiles': atMobiles, 'isAtAll': isAtAll}}) params.update(at_params) params = ujson.dumps(params) # 构造path path = '/' if self.secret_key: timestamp = DateTimeTool.getNowTimeStampWithMillisecond() path = '×tamp={}&sign={}'.format(timestamp, self._generator_sign(timestamp, self.secret_key)) # 发送文本 httpResponseResult = self.doRequest.post_with_form(path, params) return httpResponseResult
def save_element_image(self, element, image_file_name, highlight_seconds=0): webElement = self._change_element_to_webElement_type(element, highlight_seconds) left = webElement.location['x'] top = webElement.location['y'] right = webElement.location['x'] + webElement.size['width'] bottom = webElement.location['y'] + webElement.size['height'] # 进行屏幕截图 image_file_name = DateTimeTool.getNowTime('%Y%m%d%H%M%S%f_') + '%s.png'%image_file_name if not os.path.exists('output/tmp/'+self._config.current_browser): os.mkdir('output/tmp/'+self._config.current_browser) image_file_name = os.path.abspath( 'output/tmp/' + self._config.current_browser + '/' + image_file_name) self._driver.get_screenshot_as_file(image_file_name) img = Image.open(image_file_name) # 验证码图片裁切并保存 img = img.crop((left, top, right, bottom)) img.save(image_file_name) return image_file_name
def get_screenshot(self, fileName): fileName = DateTimeTool.getNowTime('%Y%m%d%H%M%S%f_') + fileName allure.attach(name=fileName, body=self._driver.get_screenshot_as_png(), attachment_type=allure.attachment_type.PNG)
parser.add_argument('-d','--dir',help='指定要测试的目录',type=str) parser.add_argument('-m','--markexpr',help='只运行符合给定的mark表达式的测试',type=str) parser.add_argument('-s', '--capture', help='是否在标准输出流中输出日志,1:是、0:否,默认为0',type=str) parser.add_argument('-r', '--reruns', help='失败重跑次数,默认为0',type=str) parser.add_argument('-lf', '--lf', help='是否运行上一次失败的用例,1:是、0:否,默认为0',type=str) parser.add_argument('-clr', '--clr', help='是否清空已有测试结果,1:是、0:否,默认为0', type=str) args=parser.parse_args() # 处理pytest文件 deal_pytest_ini_file() # 初始化java依赖的libs java_maven_init() # 初始化 print('%s开始初始化......'%DateTimeTool.getNowTime()) api_init() print('%s初始化完成......'%DateTimeTool.getNowTime()) # 执行pytest前的参数准备 pytest_execute_params=['-c', 'config/pytest.ini', '-v', '--alluredir', 'output/api/report_data/'] # 判断目录参数 dir = 'cases/api/' if args.dir: dir=args.dir # 判断关键字参数 if args.keyword: pytest_execute_params.append('-k') pytest_execute_params.append(args.keyword) # 判断markexpr参数 if args.markexpr:
parser.add_argument('-s', '--capture', help='是否在标准输出流中输出日志,1:是、0:否,默认为0', type=str) parser.add_argument('-r', '--reruns', help='失败重跑次数,默认为0', type=str) parser.add_argument('-lf', '--lf', help='是否运行上一次失败的用例,1:是、0:否,默认为0', type=str) parser.add_argument('-clr', '--clr', help='是否清空已有测试结果,1:是、0:否,默认为0', type=str) args = parser.parse_args() print('%s开始初始化......' % DateTimeTool.getNowTime()) print('%s开始检测selenium server是否可用......' % DateTimeTool.getNowTime()) try: doRquest = DoRequest(Read_WEB_UI_Config().web_ui_config.selenium_hub) httpResponseResult = doRquest.get('/status') result = ujson.loads(httpResponseResult.body) if result['status'] == 0: print('%sselenium server状态为可用......' % DateTimeTool.getNowTime()) else: sys.exit('%sselenium server状态为不可用' % DateTimeTool.getNowTime()) except: sys.exit('%sselenium server状态为不可用' % DateTimeTool.getNowTime()) # 处理pytest文件 deal_pytest_ini_file()
def start_app_device_test(index,device_info,keyword,dir,markexpr,capture,reruns,lf,clr): for path, dirs, files in os.walk('config/app_ui_tmp'): for file in files: if(int(file)==index): os.rename(os.path.join(path,file),os.path.join(path,str(os.getpid()))) print('%s开始检测appium server是否可用......'%DateTimeTool.getNowTime()) try: doRquest = DoRequest('http://'+device_info['server_ip']+':%s/wd/hub'%device_info['server_port'].strip()) httpResponseResult = doRquest.get('/status') result = ujson.loads(httpResponseResult.body) if result['status'] == 0: print('%sappium server状态为可用......'%DateTimeTool.getNowTime()) else: sys.exit('%sappium server状态为不可用'%DateTimeTool.getNowTime()) except: print('%sappium server状态为不可用'%DateTimeTool.getNowTime()) raise Exception('%sappium server状态为不可用'%DateTimeTool.getNowTime()) a_devices_desired_capabilities = device_info['capabilities'] print('%s开始设备%s测试......'%(DateTimeTool.getNowTime(),device_info['device_desc'])) print('%s当前设备所需测试的desired_capabilities为:%s'%(DateTimeTool.getNowTime(),a_devices_desired_capabilities)) for desired_capabilities in a_devices_desired_capabilities: FileTool.writeObjectIntoFile(desired_capabilities,'config/app_ui_tmp/'+str(os.getpid())+'_current_desired_capabilities') desired_capabilities_desc=None if 'appPackage' in desired_capabilities.keys(): desired_capabilities_desc = desired_capabilities['appPackage'] elif 'app' in desired_capabilities.keys(): desired_capabilities_desc = desired_capabilities['app'].split('/')[-1] elif 'bundleId' in desired_capabilities.keys(): desired_capabilities_desc = desired_capabilities['bundleId'] print('%s当前设备开始测试的desired_capabilities为:%s'%(DateTimeTool.getNowTime(),desired_capabilities)) # 执行pytest前的参数准备 pytest_execute_params = ['-c', 'config/pytest.ini', '-v', '--alluredir', 'output/app_ui/%s/%s/report_data/'%(device_info['device_desc'],desired_capabilities_desc)] # 判断目录参数 if not dir: dir = 'cases/app_ui/' # 判断关键字参数 if keyword: pytest_execute_params.append('-k') pytest_execute_params.append(keyword) # 判断markexpr参数 if markexpr: pytest_execute_params.append('-m') pytest_execute_params.append(markexpr) # 判断是否输出日志 if capture: if int(capture): pytest_execute_params.append('-s') # 判断是否失败重跑 if reruns: if int(reruns): pytest_execute_params.append('--reruns') pytest_execute_params.append(reruns) # 判断是否只运行上一次失败的用例 if lf: if int(lf): pytest_execute_params.append('--lf') # 判断是否清空已有测试结果 if clr: if int(clr): pytest_execute_params.append('--clean-alluredir') pytest_execute_params.append(dir) # 构建孙进程 process = multiprocessing.Process(target=pytest_main,args=(pytest_execute_params,)) process.start() process.join() print('%s当前设备结束测试的desired_capabilities为:%s' % (DateTimeTool.getNowTime(),desired_capabilities)) print('%s结束设备%s测试......'%(DateTimeTool.getNowTime(),device_info['device_desc']))
# 初始化mitmproxy mitmproxy_init() keyword=args.keyword dir=args.dir markexpr=args.markexpr capture=args.capture reruns=args.reruns lf=args.lf clr=args.clr test_type=args.test_type.lower() devices_info_file=args.devices_info_file if test_type=='phone': if not devices_info_file: sys.exit('请指定多设备并行信息文件,查看帮助:python run_app_ui_test.py --help') print('%s开始初始化进程......'%DateTimeTool.getNowTime()) p_pool = Custom_Pool(int(Read_APP_UI_Config().app_ui_config.max_device_pool)) devices_info=Read_APP_UI_Devices_Info(devices_info_file).devices_info print('%s当前使用的配置文件为:%s'%(DateTimeTool.getNowTime(),devices_info_file)) if os.path.exists('config/app_ui_tmp'): FileTool.truncateDir('config/app_ui_tmp/') else: os.mkdir('config/app_ui_tmp') for i in range(len(devices_info)): device_info=devices_info[i] FileTool.writeObjectIntoFile(device_info,'config/app_ui_tmp/'+str(i)) p=p_pool.apply_async(start_app_device_test,(i,device_info,keyword,dir,markexpr,capture,reruns,lf,clr)) p_pool.close() p_pool.join() else: # 执行pytest前的参数准备
if args.dir: dir = args.dir # 判断关键字参数 if args.keyword: pytest_execute_params.append('-k') pytest_execute_params.append(args.keyword) # 判断markexpr参数 if args.markexpr: pytest_execute_params.append('-m') pytest_execute_params.append(args.markexpr) # 判断是否输出日志 if args.capture: if int(args.capture): pytest_execute_params.append('-s') # 判断是否失败重跑 if args.reruns: if int(args.reruns): pytest_execute_params.append('--reruns') pytest_execute_params.append(args.reruns) # 判断是否只运行上一次失败的用例 if args.lf: if int(args.lf): pytest_execute_params.append('--lf') # 判断是否清空已有测试结果 if args.clr: if int(args.clr): pytest_execute_params.append('--clean-alluredir') pytest_execute_params.append(dir) print('%s开始测试......' % DateTimeTool.getNowTime()) exit_code = pytest.main(pytest_execute_params)
def generate_windows_reports(report_dir, test_time, port): generate_report_command = 'allure generate %s/report_data -o %s/report/app_ui_report_%s' % ( report_dir, report_dir, test_time) subprocess.check_output(generate_report_command, shell=True) open_report_command = 'start cmd.exe @cmd /c "allure open -p %s %s/report/app_ui_report_%s"' % ( port, report_dir, test_time) subprocess.check_output(open_report_command, shell=True) if __name__ == '__main__': report_config = Read_Report_Config().report_config start_port = report_config.app_ui_start_port notice_title = 'APP UI自动化测试报告' test_time = DateTimeTool.getNowTime('%Y_%m_%d_%H_%M_%S_%f') notice_markdown_text = '* APP UI生成时间:%s \n' % test_time report_dirs = [] devices_dirs = os.listdir('output/app_ui/') for device_dir in devices_dirs: for report_dir in os.listdir('output/app_ui/' + device_dir): report_dirs.append('output/app_ui/' + device_dir + '/' + report_dir) if 'Windows' == platform.system(): # 初始化进程池 p_pool = Custom_Pool(20) for i in range(len(report_dirs)): port = str(int(start_port) + i) get_allure_process_id_command = 'netstat -ano|findstr "0.0.0.0:%s"' % port try:
from common.strTool import StrTool import multiprocessing import platform import subprocess def generate_windows_reports(test_time, port): generate_report_command='allure generate output/api/report_data -o output/api/report/api_report_%s'%(test_time) subprocess.check_output(generate_report_command,shell=True) open_report_command='start cmd.exe @cmd /c "allure open -p %s output/api/report/api_report_%s"'%(port,test_time) subprocess.check_output(open_report_command,shell=True) if __name__ == '__main__': report_config = Read_Report_Config().report_config port = report_config.api_port notice_title = 'API自动化测试报告' test_time=DateTimeTool.getNowTime('%Y_%m_%d_%H_%M_%S_%f') notice_markdown_text = '* API生成时间:%s \n' % test_time if 'Windows' == platform.system(): get_allure_process_id_command = 'netstat -ano|findstr "0.0.0.0:%s"' % port try: get_allure_process_id = subprocess.check_output(get_allure_process_id_command, shell=True) get_allure_process_id = get_allure_process_id.decode('utf-8') get_allure_process_id = StrTool.getStringWithLBRB(get_allure_process_id, 'LISTENING', '\r\n').strip() kill_allure_process_command = 'taskkill /F /pid %s' % get_allure_process_id try: subprocess.check_call(kill_allure_process_command, shell=True) except: print('%s关闭allure进程,进程id:%s,该进程监听已监听端口:%s'%(DateTimeTool.getNowTime(),get_allure_process_id,port)) except: print('%sallure未查找到监听端口%s的服务' % (DateTimeTool.getNowTime(),port)) print('%s生成报告,使用端口%s'%(DateTimeTool.getNowTime(),port))
def generate_windows_reports(report_dir, test_time, port): generate_report_command = 'allure generate %s/report_data -o %s/report/web_ui_report_%s' % ( report_dir, report_dir, test_time) subprocess.check_output(generate_report_command, shell=True) open_report_command = 'start cmd.exe @cmd /c "allure open -p %s %s/report/web_ui_report_%s"' % ( port, report_dir, test_time) subprocess.check_output(open_report_command, shell=True) if __name__ == '__main__': report_config = Read_Report_Config().report_config ieport = report_config.web_ui_ie_port chromeport = report_config.web_ui_chrome_port firefoxport = report_config.web_ui_firefox_port notice_title = 'WEB UI自动化测试报告' test_time = DateTimeTool.getNowTime('%Y_%m_%d_%H_%M_%S_%f') notice_markdown_text = '* WEB UI生成时间:%s \n' % test_time if 'Windows' == platform.system(): # 初始化进程池 p_pool = Custom_Pool(3) if ieport: # 获得当前监听ie端口的进程id get_ieport_process_id_command = 'netstat -ano|findstr "0.0.0.0:%s"' % ieport try: get_allure_process_id = subprocess.check_output( get_ieport_process_id_command, shell=True) get_allure_process_id = get_allure_process_id.decode('utf-8') get_allure_process_id = StrTool.getStringWithLBRB( get_allure_process_id, 'LISTENING', '\r\n').strip() kill_allure_process_command = 'taskkill /F /pid %s' % get_allure_process_id try:
def get_screenshot(self, fileName): fileName = DateTimeTool.getNowTime('%Y%m%d%H%M%S%f_') + fileName allure.MASTER_HELPER.attach(fileName, self._driver.get_screenshot_as_png(), allure.MASTER_HELPER.attach_type.PNG)