def printCheckStepDebug(test_name, step, *res_1): """ # 检查测试例step对错,打印 如果fail则暂停脚本 :param test_name: test name :param step: step 1 2 :param res_1: other args :return: 0 or 1 """ time.sleep(0.5) _res = 0 global FILEDSTEPLIST for i in res_1: if i == 0: printRes('[res = ' + str(i) + ']Check res = 0,OK!') else: printResError('[res = ' + str(i) + ']Check res = 0,Failed!') _res = 1 if _res == 1: FILEDSTEPLIST.append(step) if wx.FindWindowById(10).nowrunning not in wx.FindWindowById(10).faillist: if wx.FindWindowById(10).nowrunning != '': wx.FindWindowById(10).faillist.append(wx.FindWindowById(10).nowrunning) printResError(test_name + ' ' + step + ' is FAILED!') wx.MessageBox('该Step不通过,已停止脚本保留现场') wx.FindWindowById(10).PauseTestAuto() else: printRes(test_name + ' ' + step + ' is PASSED!') time.sleep(0.5) return _res
def run(self): """ 读取远程服务器发送回来的信息,并且通过协程传递给chlidframe.WriteTextCtrl函数显示到窗口 :return: """ self.c.send(None) # 协程实现部分代码 while 1: if self.thread_control.isSet(): self.channel.disconnectChannel() break try: msg = self.channel.readChannel() except BaseException as e: printResError('[异常]线程读取远端服务器发送回来的信息异常,异常如下:{}'.format(e)) if msg: self.c.send(msg) # 协程实现部分代码 else: self.thread_control.wait(0.1)
def WriteChannel(self, input_str): """ 程序通过SetCmd命令往终端发送命令 :param input_str: 输入命令内容 :return: 0 表示终止发送消息 1 成功发送消息 2 读取远程终端信息线程重启失败 3 远程终端连接失败 """ try: if not self.sendMessageFlag: return 0 # 表明停止串口输入对应toolbar中的Stop Send Message if self.thread1.isAlive(): if self.thread1.channel.connected: self.thread1.channel.writeChannel( input_str) # 窗口线程存在,并且远端串口连接成功执行写入操作 return 1 else: printResWarn('[告警]进入自动重连模式...') if self.thread1.channel.reconnectChannel( ) and self.thread1.channel.connected: self.thread1.channel.writeChannel(input_str) return 1 else: printResWarn('[告警]重连失败') return 3 else: printResWarn( '[告警]远程连接线程不是alive状态!') # 读取远程终端信息线程is not alive时候重启线程 if self.thread1.channel.reconnectChannel( ) and self.thread1.channel.connected: self.thread1.stop() self.thread1 = ReadThread(self.title, self, self.conn, self.consumer()) # 协程实现 self.thread1.start() if self.thread1.isAlive(): self.thread1.channel.writeChannel(input_str) return 1 else: printResWarn('[告警]远程连接线程重启失败!') return 2 else: printResWarn('[告警]重连失败') return 3 except BaseException as e: printResError('[异常]往远程终端服务器命发送命令异常: {}'.format(e))
def printCheckStep(test_name, step, *res_1): """ 检查测试例step对错,打印并记录 :param test_name: test name :param step: 步骤 step 1 2 :param res_1: other args :return: 0 or 1 success or fail """ time.sleep(0.5) _res = 0 global FILEDSTEPLIST for i in res_1: if i == 0: printRes('[res = ' + str(i) + ']Check res = 0,OK!') else: printResError('[res = ' + str(i) + ']Check res = 0,Failed!') _res = 1 if _res == 1: FILEDSTEPLIST.append(step) if wx.FindWindowById(10).nowrunning not in wx.FindWindowById(10).faillist: if wx.FindWindowById(10).nowrunning != '': wx.FindWindowById(10).faillist.append(wx.FindWindowById(10).nowrunning) printResError(test_name + ' ' + step + ' is FAILED!') if LoadErrorStopConfig(): def errorPause(): """ 遇错暂停 :return: """ window = wx.FindWindowByName('Main') window.PauseTestAuto() errorPause() else: printRes(test_name + ' ' + step + ' is PASSED!') time.sleep(0.5) return _res
def WriteTextCtrl(self, raw_msg): """ 1 记录log信息,并且返回self.res记录remote返回信息 2 处理remote发送回来的raw_msg(回显,响应回车空格换行等) 说明 后续支持其他特性在此处扩展即可(Core) :param raw_msg:(linux)服务器传输过来的原始字符串 :return:None """ if self.page.GetLastPosition() >= 300000: self.SetInsertPoint() self.page.Remove(0, 60000) self.insertPoint = self.insertPoint - 60000 try: # 写入log print2debug = re.sub('\r', '', raw_msg.decode('utf-8')) self.res = f'{self.res}{print2debug}' if self.debugflag == 1: self.debugres = f'{self.debugres}{print2debug}' self.SetInsertionPointLocal(self.insertPoint) self.bs.feed(raw_msg) msg = self.dp.msg if msg: for _msg in msg: data, cmd = _msg.args, _msg.name if 'carriage_return' == cmd: # 归位 self.page.SetInsertionPointEnd() self.insertPoint = self.page.GetInsertionPoint() self.SetInsertionPointLocal( self.insertPoint - self.page.GetLineLength( self.page.GetNumberOfLines())) elif 'linefeed' == cmd: # 换行 self.page.SetInsertionPointEnd() linetemp = self.page.GetRange( self.last_enter_pos, self.page.GetInsertionPoint()) self.last_enter_pos = self.page.GetInsertionPoint() + 1 self.page.AppendText('\n') if self.logger: self.logger.info(linetemp) elif 'backspace' == cmd: # 回格 self.SetInsertionPointLocal(self.insertPoint - 1) elif 'erase_in_display' == cmd and data: # 擦除回显: data = int(data[0]) if data == 0: # -- Erases from cursor to end of screen, including cursor position. erase_length = self.page.GetLineLength( self.page.GetNumberOfLines( )) - self.insertPoint self.page.Replace(self.insertPoint, erase_length, '') elif data == 1: # `1`` -- Erases from beginning of screen to cursor pass # 目前暂不实现 elif data == 2 or 3: # 2 or 3 --- Erases complete display pass # 目前暂不实现 elif 'bell' == cmd: wx.Bell() # 响铃,发声 elif 'draw' == cmd and data: # 回显字符串 try: data = data[0] except Exception: pass else: self.page.Replace(self.insertPoint, self.insertPoint + len(data), data) self.insertPoint = self.page.GetInsertionPoint() except Exception as e: printResError('[异常]将远端服务器返回信息解析并写入打开的窗口异常,异常信息如下:{}'.format(e))
def CreateNewChannel(self, con_type, con_title, con_host, path=None, log_type='default', logprefix=''): """ 新建连接(标签页建立连接并打开标签) :param con_type: TelnetCCM Telnet Serial :param con_title: s1 s2 :param con_host: 172.17.100.1 :param path: 日志路径 :param log_type: 日志类型 :param logprefix: 日志前缀 :return: None """ try: self.childnamelist.append(con_title) if len(self.countlist): self.count = self.countlist[0] self.countlist.remove(self.count) else: self.count += 1 con_port = 23 conn = '' # -----------------------Telnet PC---------------------------- if con_type == 'Telnet': con_port = 23 pcConn = DautoTelnetPCFactory().createDautoChannel( con_host, int(con_port)) conn = pcConn.getChannelOP() # -----------------------Telnet CCM---------------------------- elif con_type == 'TelnetCCM': con_host_list = con_host.split(':') if len(con_host_list) == 2: con_host = con_host_list[0] con_port = con_host_list[1] try: con_port = int(con_port) except BaseException as e: printResError('[CreateNewChannel] {}'.format(e)) ccmConn = DautoTelnetCCMFactory().createDautoChannel( con_host, con_port) conn = ccmConn.getChannelOP() # -----------------------Connect Serial---------------------------- elif con_type == 'Serial': con_port = con_host try: con_port = int(con_port) except BaseException as e: printResError('[CreateNewChannel] {}'.format(e)) serialConn = DautoSerialFactory().createDautoChannel(con_port) conn = serialConn.getChannelOP() elif con_type == 'Shell': childpage = DebugFrame(self) childpage.Show() return 0 if conn.connected: child = ChildFrame(self, self.count, str(con_host), str(con_title), conn, path, log_type, logprefix) self.childqueue.append(child) child.Activate() else: ParentFrame.ErrorReport(self, conn.msg) self.childnamelist.remove(con_title) self.countlist.append(self.count) except BaseException as e: printResError('Occur Exception: {}'.format(e))
def printGlobal(title, switch, msg='', logprefix=''): """ 方案脚本控制-开始计时/结束计时,统计执行信息 说明:此处的函数实现不合理,但是为了兼容原有的实现方式不得已保留,后续可对此进行重构 :param title: s1 s2 :param switch:控制start stop end tlend :param msg: 打印的信息 :param logprefix: 日志前缀 :return: None """ global TESTNAME global TESTNUM global tempTESTNUM global TOTALTESTNUM global tempTOTALTESTNUM global RERUNTESTNUM global FAILLIST global TOTALFAILLIST global STARTTIME global TOTALSTARTTIME global RERUNSTARTTEME global ENDTIME global TOTALENDTIME global RERUNENDTIME global TESTID TESTNAME = title thistime = datetime.datetime.now() mainWin = wx.FindWindowById(10) affirm_tl_operate = mainWin.tl # 获取跟testlink服务器交互句柄 if (switch == 'start') or (switch == 'Start'): TESTID = time.strftime("%Y%m%d", time.localtime()) + str(int(time.time())) mainWin.dbInfo['id'] = TESTID STARTTIME = thistime TESTNUM = 0 FAILLIST = [] res = printFormat(title + ' ' + switch + ' ' + str(thistime), msg) # 开始记录console的log if mainWin.logger: mainWin.logger = close_logger(mainWin.logger) mainWin.logger = DcnLog(log_base_path=mainWin.log_base_path, log_define_type='run', prefix_log_name=logprefix, console_name='console', test_name=TESTNAME).create_log() printAll(res) elif (switch == 'Rerunstart') or (switch == 'RerunStart'): TESTID = time.strftime("%Y%m%d", time.localtime()) + str(int(time.time())) mainWin.dbInfo['id'] = TESTID RERUNSTARTTEME = thistime RERUNTESTNUM = 0 tempTESTNUM = TESTNUM tempTOTALTESTNUM = TOTALTESTNUM FAILLIST = [] res = printFormat(title + ' ' + switch + ' ' + str(thistime), msg) printAll(res) if mainWin.logger: mainWin.logger = close_logger(mainWin.logger) mainWin.logger = DcnLog(log_base_path=mainWin.log_base_path, log_define_type='run', prefix_log_name=logprefix + '[ReRun]', console_name='console', test_name=TESTNAME).create_log() elif (switch == 'end') or (switch == 'End'): ENDTIME = thistime duration = timediff(STARTTIME, ENDTIME) res = printFormat(title + ' ' + switch + ' ' + str(thistime), 'TestCase Duration Time:' + duration) printAll(res) res_str = 'AutoTest Name :' + TESTNAME + '\n' + 'Start Time :' + str(STARTTIME) + '\n' + 'End Time :' + str( ENDTIME) + '\n' + 'Duration Time :' + str(duration) failnum = len(FAILLIST) printAll(res_str) printAll('TestCase : Total ' + str(TESTNUM) + '\n Pass ' + str( TESTNUM - failnum) + '\n Fail ' + str(failnum)) if failnum > 0: printstr = '' printAll('Failed TestCase :') for j in FAILLIST: printstr += str(j) + '\n' printAll(printstr) printAll('') mainWin.dbInfo['totalcases'] = str(TESTNUM) mainWin.dbInfo['passed'] = str(TESTNUM - failnum) mainWin.dbInfo['failed'] = str(failnum) mainWin.dbInfo['knownbugs'] = 'Not available' mainWin.dbInfo['unknowbugs'] = 'Not available' mainWin.dbInfo['failsummary'] = str(FAILLIST) mainWin.dbInfo['suggestions'] = 'Not available' mainWin.dbInfo['starttime'] = str(STARTTIME) mainWin.dbInfo['stoptime'] = str(ENDTIME) mainWin.dbInfo['totaltime'] = str(duration) time.sleep(3) printRes(res_str) printRes('TestCase : Total ' + str(TESTNUM) + '\n Pass ' + str( TESTNUM - failnum) + '\n Fail ' + str(failnum)) if failnum > 0: printstr = '' printResWarn('Failed TestCase :') for j in FAILLIST: printstr += str(j) + '\n' printResWarn(printstr) elif (switch == 'Rerunend') or (switch == 'RerunEnd'): TESTNUM = tempTESTNUM TOTALTESTNUM = tempTOTALTESTNUM RERUNENDTIME = thistime TOTALFAILLIST.extend(FAILLIST) printRes('TOTALFAILLIST={}'.format(TOTALFAILLIST)) duration = timediff(RERUNSTARTTEME, RERUNENDTIME) res = printFormat(title + ' ' + switch + ' ' + str(thistime), 'TestCase Duration Time:' + duration) printAll(res) res_str = 'AutoTest Name :' + TESTNAME + '\n' + 'Start Time :' + str( RERUNSTARTTEME) + '\n' + 'End Time :' + str(RERUNENDTIME) + '\n' + 'Duration Time :' + str(duration) failnum = len(FAILLIST) printAll(res_str) printAll('TestCase : Total ' + str(RERUNTESTNUM) + '\n Pass ' + str( RERUNTESTNUM - failnum) + '\n Fail ' + str(failnum)) if failnum > 0: printstr = '' printAll('Failed TestCase :') for j in FAILLIST: printstr += str(j) + '\n' printAll(printstr) duration = timediff(STARTTIME, RERUNENDTIME) res = printFormat(title + ' ' + switch + ' ' + str(thistime), 'TestCase Duration Time:' + duration) printAll(res) res_str = 'AutoTest Name :' + TESTNAME + '\n' + 'Start Time :' + str(STARTTIME) + '\n' + 'End Time :' + str( RERUNENDTIME) + '\n' + 'Duration Time :' + str(duration) printAll(res_str) printAll('TestCase : Total ' + str(TESTNUM) + '\n Pass ' + str( TESTNUM - failnum) + '\n Fail ' + str(failnum)) if failnum > 0: printstr = '' printAll('Failed TestCase :') for j in FAILLIST: printstr += str(j) + '\n' printAll(printstr) printAll('') mainWin.dbInfo['totalcases'] = str(TESTNUM) mainWin.dbInfo['passed'] = str(TESTNUM - failnum) mainWin.dbInfo['failed'] = str(failnum) mainWin.dbInfo['knownbugs'] = 'Not available' mainWin.dbInfo['unknowbugs'] = 'Not available' mainWin.dbInfo['failsummary'] = str(FAILLIST) mainWin.dbInfo['suggestions'] = 'Not available' mainWin.dbInfo['starttime'] = str(STARTTIME) mainWin.dbInfo['stoptime'] = str(ENDTIME) mainWin.dbInfo['totaltime'] = str(duration) time.sleep(3) printRes(res_str) printRes('TestCase : Total ' + str(TESTNUM) + '\n Pass ' + str( TESTNUM - failnum) + '\n Fail ' + str(failnum)) if failnum > 0: printstr = '' printResWarn('Failed TestCase :') for j in FAILLIST: printstr += str(j) + '\n' printResWarn(printstr) elif switch == 'TlEnd': if mainWin.logger: mainWin.logger = close_logger(mainWin.logger) mainWin.logger = DcnLog(log_base_path=mainWin.log_base_path, log_define_type='run', prefix_log_name=logprefix, console_name='summary', test_name=TESTNAME).create_log() # 创建一个汇总结果的日志文件summary printRes('TOTALFAILLIST{}'.format(TOTALFAILLIST)) TOTALENDTIME = thistime duration = timediff(TOTALSTARTTIME, TOTALENDTIME) res = printFormat(title + ' ' + switch + ' ' + str(thistime), 'TestCase Duration Time:' + duration) printAll(res) res_str = 'AutoTest Name :' + TESTNAME + '\n' + 'Start Time :' + str( TOTALSTARTTIME) + '\n' + 'End Time :' + str(TOTALENDTIME) + '\n' + 'Duration Time :' + str(duration) failnum = len(TOTALFAILLIST) printAll(res_str) printAll('TestCase : Total ' + str(TOTALTESTNUM) + '\n Pass ' + str( TOTALTESTNUM - failnum) + '\n Fail ' + str(failnum)) if failnum > 0: printstr = '' printAll('Failed TestCase :') for j in TOTALFAILLIST: printstr += str(j) + '\n' printAll(printstr) DcnCommonFtp(ftp_config=mainWin.ftp_config_file).upload( mainWin.logfiles) # 日志上传到用户指定服务器,指定服务器配置在config/ftpconfig.json try: if 'job_id' in affirm_tl_operate.tl.__args__ and mainWin.logger and mainWin.logfiles: printResDebug('\ntestlink args are:\n{arg}'.format( arg=json.dumps(affirm_tl_operate.tl.__args__, ensure_ascii=False, indent=4, sort_keys=True))) DcnTestlinkFtp(affirm_tl_operate.tl.__args__, ip=mainWin.ftp_server_ip).upload( mainWin.logfiles) # 日志上传到testlink ftp服务器 recover_args() # testlink/args.py文件恢复初始状态 affirm_tl_operate.set_waffirm_end() # 关闭确认测试平台窗口 except Exception as ex: printResError('error %s' % ex) TOTALTESTNUM = 0 TOTALFAILLIST = []