def run(self, cmd=''): p = ProcBar().start("execute cmd %s ..." % color_str(cmd, "yellow")) try: FCmd.run(self, cmd=cmd) except Exception as err: p and p.stop(color_str(str(err), "red")) return False p.stop(color_str("OK", "green"))
def __run_script_part(self, script, step, caserep, stage, silence, mod="common"): """ parse a cmd and open a subprocess to execute script """ # 解析配置中action行的命令, procrep = caseProcReport() caserep.add(procrep) #print(caserep, procrep) cmd = None try: cmd = caseCmd(script, self.__case_file) procrep.description(cmd.description()) procrep.stage(stage) script_cmd = cmd.parse(self.__config_dict) except Exception as e: procrep.result(-1) procrep.details("ERR :" + str(e)) print(color_str(str(e), 'red')) return False, cmd, procrep, None # 解析之后第一个必然是脚本的名字,后续的是参数 c = script_cmd.split(' ') f = os.path.join(self.__script_dir, c[0]) pargs = [ self.__config_dict.get("run", {}).get("python", self.__python_run), f ] + c[1:] # 提示开始测试了... procrep.script(f, ' '.join(c[1:])) if not silence and mod == "common": sys.stdout.write("PROCESS %02d " % step + cmd.description().encode('utf-8')) # 校验脚本是否存在 if not os.path.exists(f): if not silence: print(color_str(" ... ERROR", 'red')) print("- details:") print(color_str("-- ERR :" + f + " not exists", 'red')) procrep.details("ERR :" + f + " not exists") return False, cmd, procrep, None # 开启子进程执行脚本 procrep.isrun("yes") procrep.start_time("now") proc = subprocess.Popen(pargs, stdout=subprocess.PIPE) return True, cmd, procrep, proc
def run(self, profile='internal', number=''): p = ProcBar().start( "searching number %s on profile %s ..." % (color_str( number or "[all]", "sky_blue"), color_str(profile, "yellow"))) try: FCmd.run(self, cmd="sofia status profile %s reg %s" % (profile, number)) except Exception as err: p and p.stop(color_str(str(err), "red")) return False p.stop(color_str("OK", "green"))
def __run_common_script(self, script, step, caserep, stage, silence): """ open subprocess for every script to runing and then check&report them result note: the subprocess is blocking, scripts is serializable, running..done..running..done one by one """ if not script: return True, step step += 1 for cnt, s in enumerate(script): # 执行脚本 res, cmd, procrep, proc = self.__run_script_part( s, step + cnt, caserep, stage, silence) if not res: return False, step + cnt # 注意:此函数会等待子进程运行完成之后返回。若脚本有阻塞,这里会一直阻塞 res = proc.communicate() procrep.end_time("now") # 约定检查脚本中最后一次输出0代表检查成功,之前的输出是脚本的运行过程 if res is not None and res[0] is not None and '0' in res[0].split( '\n')[-2:]: procrep.result(0) for detail in res[0].split('\n')[:-2]: procrep.details(detail) if not silence: print("... " + color_str("OK", 'green')) else: # 若执行失败,则输出脚本的执行过程 procrep.result(1) details = res[0].split('\n')[:-2] if not silence: print("... " + color_str("ERROR", 'red')) if details: print("- details:") for detail in details: if not silence: print( color_str( "-- " + detail, 'red' if 'ERR' in detail[:6] else 'sky_blue')) procrep.details(detail) return False, step + cnt # 尝试结束子进程 try: proc.terminate() except Exception as err: pass else: return True, step + cnt
def run(self, context): """ run scripts, you can type ctrl + c to terminate the long time process """ cnt, caserep, lang, silence, dup_time, dup_times = context[ "count"], context["case_rep"], context["lang"], context[ "silence"], context["dup_time"], context["dup_times"] name = dup_time == 0 and self.__name or "%s(dup_%d)" % (self.__name, dup_time) if not silence: print( color_str( "\ncase%d: %s testing%s... " % (cnt, name, ("(duplicated %d)" % dup_times) if dup_times > 1 and dup_time == 0 else ""), "purple")) print(color_str("description: %s" % (self.__description), "yellow")) print(color_str("expection : %s" % (self.__expection), "sky_blue")) try: # 报表收集信息开始 caserep.name(name) caserep.description(self.__description) caserep.expection(self.__expection) caserep.active(self.__active) caserep.start_time("now") # 开始运行脚本测试 if self.__active: step = 0 res, step = self.__run_check(step, caserep, silence) if res: # check成功才能进行setup res, step = self.__run_setup(step, caserep, silence) if res: # setup成功才能进行execute res, step = self.__run_execute(step, caserep, silence) # 只要setup成功,无论execute是否成功都应该teardown self.__run_teardown(step, caserep, silence) else: if not silence: print( color_str( "active : %s" % (lang == "Chinese" and "否" or "no"), "red")) # 报表收集信息结束 caserep.end_time("now") except KeyboardInterrupt as err: sys.exit(1)
def login(self, host='', port=22, user='******', password=''): self.__host = host self.__user = user self.__password = password try: p = ProcBar().start("logining server %s@%s:%d ..." % (user, host, port)) self.__ssh = Ssh(host, port, username=user, password=password) p.stop(color_str("OK", "green")) except Exception as err: if 'p' in list(locals().keys()): p and p.stop(color_str(str(err), "red")) raise Exception(str(err)) return False return True
def __load_config(self): """ load the variable config YAML file """ if self.__debug: print("load config") try: with open(self.__config_file) as f: self.__config = yaml.load(f) #print(self.__config) return True except Exception as e: print(color_str(str(e), "red")) return False
def pat_ProcBar(): try: print("yeah!yeah!yeah! ~~SHOW TIME~~") #月光舞法 法苏天女 变身! Dancingbaby 法苏 Trans out! [变身完] Lightning! for i in range(0, 20): p = ProcBar(timeout=5) p.start("月光舞法 法苏天女 变身! Dancing baby 法苏 Trans out...") #time.sleep(1) p.stop(color_str("lightning", "red")) time.sleep(1) del p for i in range(0, 20): p = ProcBar(timeout=5, frequency=5, symbol='pig') p.start("月光舞法 法苏天女 变身! Dancing baby 法苏 Trans out...") #time.sleep(1) p.stop(color_str("lightning", "yellow")) del p for i in range(0, 20): p = ProcBar(timeout=5, frequency=5, symbol='smile') p.start("月光舞法 法苏天女 变身! Dancing baby 法苏 Trans out...") #time.sleep(1) p.stop(color_str("lightning", "blue")) del p for i in range(0, 20): p = ProcBar(timeout=5, frequency=5, symbol='cat') p.start("月光舞法 法苏天女 变身! Dancing baby 法苏 Trans out...") #time.sleep(1) p.stop(color_str("lightning", "green")) del p #炫光舞法 朵蜜天女 变身!Dancing baby 朵蜜 Dance up! [变身完] Shining! for i in range(0, 20): p = ProcBar(mod='details') total = 12 p.set_details(total, widget_type="percent") p.start("炫光舞法 朵蜜天女 变身! Dancing baby 朵蜜 Dance up...") for i in range(0, total): if p.move(): time.sleep(0.1) p.stop(color_str("shining", "sky_blue")) time.sleep(1) del p #灿星舞法 拉媞天女 变身!Dancing baby 拉媞 Dance up! [变身完] Blinking! for i in range(0, 2): p = ProcBar(frequency=20, mod='details', symbol='bubble') total = 23 p.set_details(total, widget_type="count").start( "灿星舞法 拉媞天女 变身! Dancing baby 拉媞 Dance up...") for i in range(0, total): if p.move(): time.sleep(0.1) p.stop(color_str("blinking", "sky_blue")) time.sleep(1) del p print("yeah!yeah!yeah! ~~ENDING~~") except Exception as err: raise Exception(err)
def run(self, rep_mod, rep_dir, rep_success, silence): cnt = 0 rep = report(conf=self.__config) rep.report_dir(rep_dir) rep.start_time("now") lang = rep.language() # 循环测试用例packet --> suit(s) --> case(s) cc = None total = sum([len(cc.get("case", {}) or {}) for cc in self.__case]) s = color_str("total ", "purple") + color_str( "%d" % total, "sky_blue") + color_str(" case(s) testing... ", "purple") if not total: return if silence: p = ProcBar(mod='details').set_details( total, widget_type="count").start(s) else: print(s) for cc in self.__case: for c in cc.get("case", {}) or {}: cnt += 1 with case(cc["case_path"], c, self.__config, self.__script_dir) as ct: for t in range(0, ct.times()): caserep = caseReport(packet_path=self.__packet_file, suit_path=cc["suit_path"], case_path=cc["case_path"]) ct.run({ "count": cnt, "case_rep": caserep, "lang": lang, "silence": silence, "dup_time": t, "dup_times": ct.times() }) rep.add(caserep) #print(rep, caserep) if silence: p.move() else: if silence: if cc: p.stop(color_str("OK", "green")) else: p.stop(color_str("WARNING (no cases run)", "yellow")) return # 生成报表 s = color_str("\nreport... ", "purple") if silence: p = ProcBar().start(s) else: print(s) rep.name(cc["packet_name"]) rep.description(cc["packet_description"]) rep.end_time("now") rep.generation(rep_mod, rep_success, silence) rep.mail(silence) s = color_str("OK", "green") if silence: p.stop(s) total, success, success_list, failed, failed_list, error, error_list, unactive, unactive_list = rep.statistics( ) print( color_str("\n%s" % (lang == "Chinese" and "统计" or "statistics"))) print(color_str("===============")) print( color_str( " {0:<14}:{1}".format( "%s" % (lang == "Chinese" and "成功" or "success"), success), "green" if success else "white")) print( color_str( " {0:<14}:{1}".format( "%s" % (lang == "Chinese" and "失败" or "failed"), failed), "red" if failed else "white")) print( color_str( " {0:<14}:{1}".format( "%s" % (lang == "Chinese" and "错误" or "error"), error), "red" if error else "white")) print( color_str( " {0:<14}:{1}".format( "%s" % (lang == "Chinese" and "未激活" or "unactive"), unactive), "red" if unactive else "white")) print(color_str("---------------")) print( color_str( " {0:<14}:{1}".format( "%s" % (lang == "Chinese" and "总计" or "total"), total), "sky_blue"))
def __load_case(self): """ load the case YAML file """ if self.__debug: print("load case") root = os.path.split(self.__packet_file)[0] try: with open(self.__packet_file) as f: p = yaml.load(f) # 配置中的包描述(删除YAML结构中的description和name,方便代码编写) packet_description = p.pop( "description") if "description" in p else "" packet_name = p.pop("name") if "name" in p else "" if not p: return True # 遍历配置包中的测试套 for suit_dir, suit_file_list in p.items(): for suit_file in suit_file_list if suit_file_list else []: suit_path = os.path.join(root, suit_dir, suit_file) if not os.path.exists(suit_path): print( color_str("file " + suit_path + " is not exists", "yellow")) continue try: with open(suit_path) as f: s = yaml.load(f) except Exception as err: print(color_str(str(err), "red")) continue # 配置中的测试套描述 suit_description = s.pop( "description") if "description" in s else "" suit_name = s.pop("name") if "name" in s else "" if not s: continue # 遍历配置套中的测试用例 for case_dir, case_file_list in s.items(): for case_file in case_file_list if case_file_list else []: case_path = os.path.join(root, case_dir, case_file) if not os.path.exists(case_path): print( color_str( "file " + case_path + " is not exists, please check file:" + suit_path, "yellow")) continue try: with open(case_path) as f: c = yaml.load(f) except Exception as err: print(color_str(str(err), "red")) continue #print(c) self.__case.append({"case": c, "case_path":case_path, \ "suit_path":suit_path, "suit_description":suit_description, "suit_name":suit_name,\ "packet_path":self.__packet_file, "packet_description":packet_description, "packet_name":packet_name,\ }) return True except Exception as e: print(color_str(str(e), "red")) return False
def __run_execute(self, step, caserep, silence): """ run 'execute' stage scripts. specially, this stage can't blocking in a script, start thread to execute """ cases = [] if not self.__execute: return True, step step += 1 for cnt, s in enumerate(self.__execute): # 执行脚本 res, cmd, procrep, proc = self.__run_script_part( s, step + cnt, caserep, "execute", silence, "exe") if not res: return False, step + cnt # 开启线程等待脚本进程的返回 d = { 'result': None, 'subproc': proc, 'thread': None, 'cmd': cmd, 'rep': procrep } d['thread'] = executeThread(cnt, self.__name.encode('utf-8'), d, 3) d['thread'].start() cases.append(d) # 每个子进程之间执行间隔1秒 time.sleep(1) else: # 等待所有线程结束(即子进程返回) for c in cases: c['thread'].join() # 报表 for cnt, c in enumerate(cases): # 约定检查脚本中最后一次输出0代表检查成功 res = c['result'] if res is not None and res[0] is not None and '0' in res[0].split( '\n')[-2:]: if not silence: print("PROCESS %02d " % (step + cnt) + c['cmd'].description().encode('utf-8') + "... " + color_str("OK", 'green')) c['rep'].result(0) #c['rep'].details("PROCESS %02d " % (step + cnt) + c['cmd'].description() + " OK") for detail in res[0].split('\n')[:-2]: c['rep'].details(detail) pass else: # 若执行失败,则输出脚本的执行过程 c['rep'].result(1) details = res[0].split('\n')[:-2] if not silence: if details: print("PROCESS %02d " % (step + cnt) + c['cmd'].description().encode('utf-8') + "... " + color_str("ERROR", 'red')) print("- details:") else: print("PROCESS %02d " % (step + cnt) + c['cmd'].description().encode('utf-8') + "... " + color_str("ERROR (no details)", 'red')) for detail in details: if not silence: print( color_str( "-- " + detail, 'red' if 'ERR' in detail else 'sky_blue')) c['rep'].details(detail) # 尝试结束子进程 try: c['subproc'].terminate() except Exception as err: pass else: return True, cnt + step
import os, sys import subprocess import threading import time from treport import report, caseReport, caseProcReport from neko import color_str, ProcBar # yaml包 try: import yaml except ImportError as err: if "No module named" in str(err): print( color_str( "this script base on PyYaml, I will install it first, please wait a moment", "purple")) result = os.system( "yum -y install python-pip && pip install --upgrade pip && pip install pyyaml" ) if 0 != result: print( color_str( "sorry, there have some problems on auto-install PyYaml, please install it manually", "red")) sys.exit(result) else: import yaml # 解析配置脚本中能执行脚本的配置项参数