def showScriptConf(self): try: getter.get_app_conf() except Exception as e: self.tipLabel.setText(e) self.tipLabel.setPalette(self.pe_red) return self.atConfig = AtConfig() self.atConfig.initUI()
def saveConfigs(self): cf = getter.get_app_conf() projectPath = str(cf.get('baseconf', 'projectLocation')) atConfigPath = os.path.join(projectPath, 'support', 'config.ini') file = open(atConfigPath, 'w') file.writelines('[baseconf]') file.writelines('\n') file.writelines('player=' + self.playerTxt.text()) file.writelines('\n') file.writelines('voiceDir=' + self.voiceDirTxt.text()) file.writelines('\n') file.writelines('logPath=' + self.runLogDirTxt.text()) file.writelines('\n') file.writelines('deviceSerial=' + self.deviceSerialTxt.text()) file.writelines('\n') file.writelines('phoneSerial=' + self.phoneSerialTxt.text()) file.writelines('\n') file.writelines('phoneBluetoothName=' + self.phoneBlueToothNameTxt.text()) file.writelines('\n') file.writelines('version=' + self.versionTxt.text()) file.writelines('\n') file.writelines('usbMusic=' + self.usbMusicTxt.text()) file.writelines('\n') # file.writelines('socketIp=' + self.socketIpTxt.text()) # file.writelines('\n') # file.writelines('socketPort=' + self.socketPortTxt.text()) # file.writelines('\n') file.close() self.close()
def run_behave_cmd(self, id, loopCnt): cf = getter.get_app_conf() projectPath = str(cf.get('baseconf', 'projectLocation')) # reportPath = os.path.join(projectPath, 'reports', str(id)) reportPath = os.path.join(projectPath, 'reports', str(id), 'report.log') # os.system('behave -k --junit --junit-directory ' + reportPath) try: for i in range(int(loopCnt)): os.system( 'behave -k --show-source --show-timings --format plain --outfile ' + reportPath) except: pass finally: self.progressBar.hide() self.runBtn.setText('运行') self.runBtn.setEnabled(True) # 上传logcat日志信息到服务器端 print('执行结束,更新任务状态') try: getter.update_task_status(id) file = open(reportPath, 'r').read() data = {'id': id, 'result': file} getter.save_result_to_task_his(data) except Exception as e: raise Exception(e) finally: self.show_task_history()
def downloadLog(self): print(self.tree.currentItem()) if self.tree.currentItem() == None: self.errMsgLabel.setText('请选中要下载日志的用例') return self.errMsgLabel.setText('') text, ok = QInputDialog.getText(self, '下载日志', '请输入保存日志目录') if ok: item = QTreeWidgetItem(self.tree.currentItem()) while type(item.parent()).__name__ != 'NoneType': item = item.parent() if not os.path.exists(text): os.makedirs(text) log_name = item.text(0) + '.log' logcat_file_name = os.path.join(text, log_name) print('要下载的日志为' + logcat_file_name + ', 任务ID为: ' + str(self.taskid) + ', 下载路径为: ' + text) # os.chdir(text) cf = getter.get_app_conf() logcat_url = 'http://' + str(cf.get('baseconf', 'serverIp')) + ':9527/' + str(self.taskid) + '/' + quote(log_name) print(logcat_url) subprocess.call('wget ' + logcat_url + ' --output-document=' + logcat_file_name, shell=True) # app = QApplication(sys.argv) # te = ViewResult() # te.initUI(14) # te.show() # sys.exit(app.exec_())
def saveConfigs(self): cf = getter.get_app_conf() projectPath = str(cf.get('baseconf', 'projectLocation')) # atConfigPath = os.path.join(projectPath, 'support', 'config.ini') homeDir = os.path.expanduser('~') file = open(os.path.join(homeDir, '.config.ini'), 'w') # file = open(atConfigPath, 'w') file.writelines('[baseconf]') file.writelines('\n') file.writelines('player=' + self.playerTxt.text()) file.writelines('\n') file.writelines('voiceDir=' + self.voiceDirTxt.text()) file.writelines('\n') file.writelines('logPath=' + self.runLogDirTxt.text()) file.writelines('\n') file.writelines('deviceSerial=' + self.deviceSerialTxt.text()) file.writelines('\n') file.writelines('deviceIPaddress=' + self.deviceIPaddressTxt.text()) file.writelines('\n') file.writelines('devicePcanBaudrate=' + self.devicePcanBaudrateTxt.text()) file.writelines('\n') file.writelines('phoneSerial=' + self.phoneSerialTxt.text()) file.writelines('\n') file.writelines('phoneBluetoothName=' + self.phoneBlueToothNameTxt.text()) file.writelines('\n') file.writelines('version=' + self.versionTxt.text()) file.writelines('\n') file.writelines('usbMusic=' + self.usbMusicTxt.text()) file.writelines('\n') # file.writelines('socketIp=' + self.socketIpTxt.text()) # file.writelines('\n') # file.writelines('socketPort=' + self.socketPortTxt.text()) # file.writelines('\n') file.close() self.close() # 判断测试工程是否存在,存在就覆盖配置文件,不存在就什么都不做 if os.path.exists(os.path.join(projectPath, 'support')): shutil.copyfile(os.path.join(homeDir, '.config.ini'), os.path.join(projectPath, 'support', 'config.ini'))
def getLatestScript(self): # 生成测试用例文件 cf = getter.get_app_conf() projectPath = str(cf.get('baseconf', 'projectLocation')) # 删除原来的工程 # 先删除.git文件夹 git_dir_path = os.path.join(projectPath, '.git') git_url = str(cf.get('baseconf', 'gitUrlForScript')) if os.path.exists(git_dir_path): if sys.platform == 'linux': shutil.rmtree(git_dir_path) else: subprocess.call('rd /q/s ' + git_dir_path, shell=True) try: fileList = os.listdir(projectPath) for f in fileList: testProjPath = os.path.join(projectPath, f) if os.path.isfile(testProjPath): os.remove(testProjPath) else: shutil.rmtree(testProjPath) except Exception as e: self.tipLabel.setText(str(e)) self.tipLabel.setPalette(self.pe_red) # 从git服务器上下载最新的测试工程 from git import Repo try: t = threading.Thread(target=Repo.clone_from, args=(git_url, projectPath)) t.setDaemon(True) t.start() t.join() # 复制配置文件 homeDir = os.path.expanduser('~') shutil.copyfile(os.path.join(homeDir, '.config.ini'), os.path.join(projectPath, 'support', 'config.ini')) # Repo.clone_from('https://github.com/ouguangqian/autotestproject.git', projectPath) except Exception as e: print(e) self.tipLabel.setText('测试工程脚本下载失败,请联系相关负责人') self.tipLabel.setPalette(self.pe_red) return self.tipLabel.setText('测试脚本更新完成') self.tipLabel.setPalette(self.pe_red)
def showConfigs(self): cf = getter.get_app_conf() projectPath = str(cf.get('baseconf', 'projectLocation')) atConfigPath = os.path.join(projectPath, 'support', 'config.ini') cf = ConfigParser() cf.read(atConfigPath) try: self.playerTxt.setText(str(cf.get('baseconf', 'player'))) self.voiceDirTxt.setText(str(cf.get('baseconf', 'voiceDir'))) self.runLogDirTxt.setText(str(cf.get('baseconf', 'logPath'))) self.deviceSerialTxt.setText( str(cf.get('baseconf', 'deviceSerial'))) self.phoneSerialTxt.setText(str(cf.get('baseconf', 'phoneSerial'))) self.phoneBlueToothNameTxt.setText( str(cf.get('baseconf', 'phoneBluetoothName'))) self.versionTxt.setText(str(cf.get('baseconf', 'version'))) self.usbMusicTxt.setText(str(cf.get('baseconf', 'usbMusic'))) # self.socketIpTxt.setText(str(cf.get('baseconf', 'socketIp'))) # self.socketPortTxt.setText(str(cf.get('baseconf', 'socketPort'))) except: pass
def initUI(self, id): self.setWindowTitle('结果查看') self.setWindowIcon(QIcon('./images/icon.jpg')) self.setGeometry(10, 10, 900, 800) # self.setMaximumSize() self.setWindowFlags(Qt.Qt.SubWindow | Qt.Qt.WindowStaysOnTopHint) self.taskid = id grid = QGridLayout() closeBtn = QPushButton('关闭') downloadReportBtn = QPushButton('下载报告') downloadLogBtn = QPushButton('下载日志') closeBtn.resize(closeBtn.sizeHint()) closeBtn.clicked.connect(self.close) downloadReportBtn.resize(downloadReportBtn.sizeHint()) downloadReportBtn.clicked.connect(self.downloadReport) downloadLogBtn.resize(downloadLogBtn.sizeHint()) downloadLogBtn.clicked.connect(self.downloadLog) self.tipLabel = QLabel() # self.tipLabel.(QColor(20,150,150)) self.tipLabel.setFont(QFont('sanserif', 12)) self.tipLabel.setText('') self.errMsgLabel = QLabel() self.errMsgLabel.setFont(QFont('sanserif', 16)) self.errMsgLabel.setText('') self.pe_red = QPalette() self.pe_red.setColor(QPalette.WindowText, Qt.Qt.red) self.errMsgLabel.setPalette(self.pe_red) self.tree = QTreeWidget() self.tree.setColumnCount(1) self.tree.setHeaderLabels(['']) self.tree.setColumnWidth(0, 750) self.featureTree = QTreeWidgetItem() grid.addWidget(closeBtn, 1, 9) grid.addWidget(downloadReportBtn, 1, 10) # grid.addWidget(downloadLogBtn, 1, 10) # 日志下载暂时停用 grid.addWidget(self.tipLabel, 2, 0, 1, 5) grid.addWidget(self.errMsgLabel, 2, 5, 1, 3) grid.addWidget(self.tree, 3, 0, 20, 11) self.setLayout(grid) self.show() cf = getter.get_app_conf() projectPath = str(cf.get('baseconf', 'projectLocation')) reportPath = os.path.join(projectPath, 'reports', str(id), 'report.log') # 获取结果 数据库查询 res = getter.get_task_his_by_id(self.taskid) result = res['result'] if len(result) == 0: self.errMsgLabel.setText('没有生成报告,请确定是否执行结束') return step_flag = None scen_flag = None total_cnt = 0 failed_cnt = 0 for f in result.split('\n'): if f.strip().startswith('场景:'): total_cnt += 1 step_flag = True scen_flag = True self.featureTree = QTreeWidgetItem(self.tree) self.featureTree.setText(0, f.strip()[len('场景:'):].strip()) elif not f.strip().startswith('背景:') and not f.strip().startswith( '功能:') and not f.strip() == '': backgroundTree = QTreeWidgetItem(self.featureTree) if '...' in f: backgroundTree.setText( 0, f.replace('\n', '')[:f.index('...')]) else: backgroundTree.setText(0, f.replace('\n', '')) if 'passed' in f: # backgroundTree.setBackground(0, QBrush(QColor(0, 250, 0))) step_flag = True if 'failed' in f: backgroundTree.setForeground(0, QBrush(QColor(250, 0, 0))) step_flag = False scen_flag = False failed_cnt += 1 if step_flag: pass # backgroundTree.setBackground(0, QBrush(QColor(0, 250, 0))) else: # backgroundTree.setBackground(0, QBrush(QColor(250, 0, 0))) backgroundTree.setForeground(0, QBrush(QColor(250, 0, 0))) if scen_flag: self.featureTree.setForeground(0, QBrush(QColor(0, 250, 0))) else: self.featureTree.setForeground(0, QBrush(QColor(255, 0, 0))) # file.close() self.tipLabel.setText('全部用例:' + str(total_cnt) + '条, 通过用例:' + str(total_cnt - failed_cnt) + '条, 失败用例:' + str(failed_cnt) + '条')
def run_tests(self): global t # 设置运行按钮展示字符 self.runFlag = not self.runFlag self.tipLabel.setText('') if self.runFlag: self.selected_features_cnt = len(self.selected_feature_ids) self.features_runned_cnt = 0 print(self.selected_features_cnt) self.progressBar.show() self.progressBar.setValue(0) self.runBtn.setText('停止') else: self.progressBar.hide() self.runBtn.setText('运行') print('用例运行状态为: ' + str(t.is_alive())) if t.is_alive(): if sys.platform == 'linux': ret = subprocess.Popen('ps -ef | grep behave', stdout=subprocess.PIPE, shell=True).stdout.readlines() for r in ret: r = r.decode().strip() if 'grep' in r: continue while ' ' in r: r = r.replace(' ', ' ') rlist = r.split(' ') pid = rlist[1] print('pid:' + pid) try: subprocess.call('kill -9 ' + pid, shell=True) except Exception as e: self.tipLabel.setText('用例停止失败,可以尝试重启应用解决') print(e) else: ret = subprocess.Popen( 'tasklist -V | findstr behave', stdout=subprocess.PIPE).stdout.readlines() for r in ret: r = r.decode('unicode_escape').strip() while ' ' in r: r = r.replace(' ', ' ') rlist = r.split(' ') pid = rlist[1] try: print(rlist[1]) subprocess.call('taskkill /T /F /pid ' + pid, shell=True) break except Exception as e: self.tipLabel.setText('用例停止失败,可以尝试重启应用解决') print(e) return # 获取用例循环次数 loopCnt = self.loopSpinbox.value() date_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S:%f') status = '执行中' feature_ids = '' # 根据选中的用例保存用例信息 for id in self.selected_feature_ids: if not len(feature_ids) == 0: feature_ids += ',' feature_ids += str(id) data = { 'status': status, 'date_time': date_time, 'feature_ids': feature_ids } ret_save = getter.save_task_history(data) self.show_task_history() # 生成测试用例文件 cf = getter.get_app_conf() projectPath = str(cf.get('baseconf', 'projectLocation')) featurePath = os.path.join(projectPath, 'features') filelist = os.listdir(featurePath) if len(filelist) > 0: for f in filelist: if f.endswith('.feature'): os.remove(os.path.join(featurePath, f)) # 写feature文件 for id in self.selected_feature_ids: fileName = os.path.join( featurePath, 'testcase-' + datetime.now().strftime('%Y_%m_%d%H_%M_%S_%f') + '.feature') print('要写入的文件为: ' + fileName) file = open(fileName, 'w', encoding='utf-8') print('写入文件的场景ID为: ' + str(id)) # 根据id 获取场景的feature_name and sce_name feature = getter.get_feature_info_by_id(id) print('# language: zh-CN') print('功能: ' + feature['feature_name']) # print(feature['tags']) print('场景: ' + feature['sce_name']) file.writelines('# language: zh-CN') file.writelines('\n') file.writelines('功能: ' + feature['feature_name']) file.writelines('\n') # file.writelines(feature['tags']) # file.writelines('\n') file.writelines('场景: ' + feature['sce_name']) file.writelines('\n') # 根据名称 获取关联的步骤场景 try: feature_steps_relationship = getter.get_featrue_step_relationship( feature['sce_name']) except: self.tipLabel.setText('获取步骤信息错误,可能步骤被删除') if len(feature_steps_relationship) > 0: feature_steps_info = [] for fs in feature_steps_relationship: step_id = fs['id'] step_info = getter.get_step_info_by_id(step_id) step_name = step_info['name'] step_is_chk = step_info['is_chk'] step_idx = fs['idx'] params = fs['params'] step_cnt = fs['repeat_cnt'] st = { 'name': step_name, 'is_chk': step_is_chk, 'params': params, 'repeat_cnt': step_cnt } feature_steps_info.insert(step_idx, st) for fsi in feature_steps_info: for t in range(fsi['repeat_cnt']): if fsi['is_chk']: print('那么< ' + fsi['name']) file.writelines('那么< ' + fsi['name']) file.writelines('\n') else: print('当< ' + fsi['name']) file.writelines('当< ' + fsi['name']) file.writelines('\n') if len(fsi['params']) > 0: for p in fsi['params']: print('|' + p['name'], end='') file.writelines('|' + p['name']) print('|') file.writelines('|') file.writelines('\n') for v in fsi['params']: print('|' + v['value'], end='') file.writelines('|' + v['value']) print('|') file.writelines('|') file.writelines('\n') file.close() print('文件生成完成') # 运行测试用例 os.chdir(projectPath) # 调用运行测试用例函数 t = threading.Thread(target=self.run_behave_cmd, args=(ret_save['id'], loopCnt)) t.setDaemon(True) t.start()