def do_GET(self): home= "../lib/html/" root = '../' response = 200 type = 'text/html' if self.path=='/': indexpage= open(home+ 'index.html', 'r') encoded=indexpage.read() encoded = encoded.encode(encoding='utf_8') elif self.path =='/favicon.ico': indexpage= open(home+'dash.ico', 'r') encoded=indexpage.read() type = "application/x-ico" elif self.path.startswith('/log') or self.path.startswith('/report'): path = os.path.abspath(root) path = path+ self.path.replace('//','/') if os.path.isfile(path): indexpage= open(path) encoded=indexpage.read() html = [] for line in encoded.split('\n'): html.append('<p>%s</p>'%line.replace('\r', '').replace('\n','')) encoded= ''.join(html) else: encoded =self.list_dir(path, self.path) #encoded = encoded.encode(encoding='utf_8') else: path = os.path.abspath(root) path = path+ self.path.replace('//','/') if os.path.isfile(path): from common import csvfile2array arrary = csvfile2array(path) encoded = self.array2htmltable(arrary) else: encoded =self.list_dir(path, self.path) self.send_response(200) self.send_header("Content-type", type) self.end_headers() self.wfile.write(encoded)
def test_csvstring2array(self): if __package__ is None: #import sys #from os import path #sys.path.append(os.path.sep.join([os.getcwd(),'..','lib'])) #sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) ) from common import csvstring2array, csvfile2array, LoadCaseFromCsv else: from ..lib.common import csvfile2array, csvstring2array a =csvstring2array('one,two,three\nline2,line2-2') print(a) #array2csvfile(a,'a.csv') print() pardir =os.path.dirname(os.path.realpath(__file__)) b = csvfile2array(os.path.sep.join([pardir, 'a.csv'])) print(b) sys.argv=[sys.argv[0],'../bench/local','../case/case1.csv','case1', 'full','cmd1'] sut,steps,mode = LoadCaseFromCsv('../bench/local','../case/case1.csv','case1', 'full', sys.argv)
def login(self): print('loginDone', self.loginDone) if self.is_simulation(): self.loginDone = True return #self.lockRelogin.acquire() login = '******'.upper() time.sleep(0.5) self.show() if self.attribute.has_key(login) and self.loginDone == False: seq = csvfile2array(self.attribute[login]) lineno = 0 for singlestep in seq: if self.loginDone: break lenStep = len(singlestep) if lenStep > 2: cmd, exp, wait = singlestep[:3] elif lenStep == 2: cmd, exp = singlestep wait = 1 elif lenStep == 1: cmd = singlestep[0] exp, wait = ['.*', 1] else: continue lineno += 1 try: self.stepCheck(self.name, lineno, cmd, exp, wait) except Exception as e: if self.loginDone: break else: #self.lockRelogin.release() raise e self.show() #self.singleStep(cmd, exp, wait) self.loginDone = True
def login(self): print('loginDone', self.loginDone) if self.is_simulation(): self.loginDone=True return #self.lockRelogin.acquire() login = '******'.upper() time.sleep(0.5) self.show() if self.attribute.has_key(login) and self.loginDone==False: seq = csvfile2array(self.attribute[login]) lineno =0 for singlestep in seq: if self.loginDone: break lenStep = len(singlestep) if lenStep>2: cmd, exp, wait = singlestep[:3] elif lenStep ==2: cmd, exp = singlestep wait= 1 elif lenStep ==1: cmd = singlestep[0] exp , wait= ['.*', 1] else: continue lineno+=1 try: self.stepCheck(self.name, lineno, cmd, exp, wait) except Exception as e : if self.loginDone: break else: #self.lockRelogin.release() raise e self.show() #self.singleStep(cmd, exp, wait) self.loginDone=True
def do_GET(self): print('do_Get....') config = ConfigParser.ConfigParser() conf = config.read('./html/init.cfg') home= "./html/" root = config.get('init','home')#'./' response = 200 logdir= config.get('init','logdir') casedir =config.get('init', 'casedir') type = 'text/html' if self.path=='/': indexpage= open(home+ 'index.html', 'r') encoded=indexpage.read() encoded = encoded.encode(encoding='utf_8') elif self.path =='/favicon.ico': indexpage= open(home+'dash.ico', 'r') encoded=indexpage.read() type = "application/x-ico" elif self.path=='/home': path = os.path.abspath(root) encoded =self.list_dir(path, './') elif self.path.startswith('/log'): path = os.path.abspath(logdir)#root path = path+self.path.replace('//','/').replace('%20', ' ')[4:] if os.path.isfile(path): indexpage= open(path) encoded=indexpage.read() html = [] for line in encoded.split('\n'): html.append('<p>%s</p>'%line.replace('\r', '').replace('\n','')) encoded= ''.join(html) else: encoded =self.list_dir(path, self.path) elif self.path.startswith('/case'): tmp_path = os.path.abspath(casedir)#root tmp_path = tmp_path+ '/'+ self.path[5:] path = tmp_path if os.path.isfile(path): if path.lower().endswith('.csv'): arrary = csvfile2array(path) encoded = self.array2htmltable(arrary) else: indexpage= open(path) encoded=indexpage.read() html = [] for line in encoded.split('\n'): html.append('<p>%s</p>'%line.replace('\r', '').replace('\n','')) encoded= ''.join(html) else: encoded =self.list_dir(path, self.path) elif self.path.startswith('/html'): encoded= 'not found!' with open(root+ self.path) as htmlfile: data = '\n'.join(htmlfile.readlines()) encoded =data else: path = os.path.abspath(root) path = path+ self.path.replace('//','/') if os.path.isfile(path): arrary = csvfile2array(path) encoded = self.array2htmltable(arrary) else: encoded =self.list_dir(path, self.path) self.send_response(200) self.send_header("Content-type", type) self.end_headers() self.wfile.write(encoded)
def do_GET(self): print("do_Get....") config = ConfigParser.ConfigParser() conf = config.read("./html/init.cfg") home = "./html/" root = config.get("init", "home") #'./' response = 200 logdir = config.get("init", "logdir") casedir = config.get("init", "casedir") type = "text/html" if self.path == "/": indexpage = open(home + "index.html", "r") encoded = indexpage.read() encoded = encoded.encode(encoding="utf_8") elif self.path == "/favicon.ico": indexpage = open(home + "dash.ico", "r") encoded = indexpage.read() type = "application/x-ico" elif self.path == "/home": path = os.path.abspath(root) encoded = self.list_dir(path, "./") elif self.path.startswith("/log"): path = os.path.abspath(logdir) # root path = path + self.path.replace("//", "/").replace("%20", " ")[4:] if os.path.isfile(path): indexpage = open(path) encoded = indexpage.read() html = [] for line in encoded.split("\n"): html.append("<p>%s</p>" % line.replace("\r", "").replace("\n", "")) encoded = "".join(html) else: encoded = self.list_dir(path, self.path) elif self.path.startswith("/case"): tmp_path = os.path.abspath(casedir) # root tmp_path = tmp_path + "/" + self.path[5:] path = tmp_path if os.path.isfile(path): if path.lower().endswith(".csv"): arrary = csvfile2array(path) encoded = self.array2htmltable(arrary) else: indexpage = open(path) encoded = indexpage.read() html = [] for line in encoded.split("\n"): html.append("<p>%s</p>" % line.replace("\r", "").replace("\n", "")) encoded = "".join(html) else: encoded = self.list_dir(path, self.path) elif self.path.startswith("/html"): encoded = "not found!" with open(root + self.path) as htmlfile: data = "\n".join(htmlfile.readlines()) encoded = data else: path = os.path.abspath(root) path = path + self.path.replace("//", "/") if os.path.isfile(path): arrary = csvfile2array(path) encoded = self.array2htmltable(arrary) else: encoded = self.list_dir(path, self.path) self.send_response(200) self.send_header("Content-type", type) self.end_headers() self.wfile.write(encoded)
def __init__(self,name,suts,steps=None,mode=None,DebugWhenFailed=False,logdir=None,caseconfigfile=None): """ init a Test Case instance """ self.Name= 'DefaultTestCaseName' self.SUTs={} self.Session={} self.Steps=[[],[],[]] self.arg =[] self.kwarg = {} self.argvs=[] self.kwargvs =[] self.ServerHost ='localhost' self.SocketResponse='' self.Mode= 'FULL' self.breakpoint=[[],[],[]] self.cp=[0,1] self.qCommand=queue.Queue() self.RecordReplay=[] self.IndexOfSutOutput= {'client':{'tel':[0,0]}} self.SUTNAME =[] if not steps : steps = [[],[],[]] if not mode: mode ='FULL' if not logdir: logdir = os.getcwd() if not caseconfigfile: caseconfigfile = './case.cfg' import threading self.lockOutput =threading.Lock() self.lockRR =threading.Lock() self.DebugWhenFailed=DebugWhenFailed a = csvfile2array(caseconfigfile) cfg={} for i in a: try: if len(i)>0: cfg.update({i[0].strip().lower():i[1].strip()}) except Exception as e: print(e.__str__()) try: self.ServerHost = cfg['serverhost'] self.ServerPort = int(cfg['serverport']) except: pass self.Name= name if len(self.Name)>80: self.Name=self.Name[0:80] import re self.Name = re.sub(r"[^\w]", "", self.Name) self.LogDir = '%s%s%s'%(os.path.abspath(logdir),os.sep,'%s%s'%(self.Name,time.strftime("_%Y%m%d_%H%M%S", time.localtime()))) #self.LogDir = self.LogDir.replace('\\',os.path.sep).replace('/', os.path.sep).replace(':','') os.mkdir(self.LogDir) self.Setup=steps[0] self.Run = steps[1] self.Teardown = steps[2] self.Steps=steps self.SUTs = suts self.Mode = mode.upper() import logging logfile = self.LogDir+os.sep+"TC_"+self.Name+".log" logging.basicConfig( level = logging.DEBUG, format = self.Name+' %(asctime)s -%(levelname)s: %(message)s' ) from common import CLogger self.logger = CLogger(self.Name) self.hdrlog = logging.FileHandler(logfile) self.logger.setLevel(logging.DEBUG) self.hdrlog .setFormatter(logging.Formatter('%(asctime)s -%(levelname)s: %(message)s')) self.logger.addHandler(self.hdrlog ) sutstring ='' self.SUTNAME= sorted(suts.keys()) self.SUTNAME.append('__case__') self.RecordReplay = [['[cs]'], ['#VAR'],['#SETUP']] newrecord = ['#SUTNAME', 'COMMAND', 'EXPECT', 'WAIT TIME(s)'] before1staction= ['#', '','','',] for sut in self.SUTNAME: newrecord.append(sut+' OUTPUT') before1staction.append('') self.RecordReplay.append(newrecord) self.RecordReplay.append(before1staction) thList =[] for sut in self.SUTs.keys() : if sut =='__case__': continue sutstring +='SUT(%s):[%s]\n'%(sut,self.SUTs[sut]) self.info('connecting to %s'%(sut)) try: thList.append( threading.Thread(target=self.Connect2Sut,args =[sut])) thList[-1].start() except Exception as e: import traceback self.info(traceback.format_exc()) print(traceback.format_exc()) raise Exception('Can NOT connected to %s'%sut) for t in thList: t.join() self.InitialDone=True
def __init__(self, name, suts, steps=None, mode=None, DebugWhenFailed=False, logdir=None, caseconfigfile=None): """ init a Test Case instance """ self.Name = 'DefaultTestCaseName' self.SUTs = {} self.Session = {} self.Steps = [[], [], []] self.arg = [] self.kwarg = {} self.argvs = [] self.kwargvs = [] self.ServerHost = 'localhost' self.SocketResponse = '' self.Mode = 'FULL' self.breakpoint = [[], [], []] self.cp = [0, 1] self.qCommand = queue.Queue() self.RecordReplay = [] self.IndexOfSutOutput = {'client': {'tel': [0, 0]}} self.SUTNAME = [] if not steps: steps = [[], [], []] if not mode: mode = 'FULL' if not logdir: logdir = os.getcwd() if not caseconfigfile: caseconfigfile = './case.cfg' import threading self.lockOutput = threading.Lock() self.lockRR = threading.Lock() self.DebugWhenFailed = DebugWhenFailed a = csvfile2array(caseconfigfile) cfg = {} for i in a: try: if len(i) > 0: cfg.update({i[0].strip().lower(): i[1].strip()}) except Exception as e: print(e.__str__()) try: self.ServerHost = cfg['serverhost'] self.ServerPort = int(cfg['serverport']) except: pass self.Name = name if len(self.Name) > 80: self.Name = self.Name[0:80] import re self.Name = re.sub(r"[^\w]", "", self.Name) self.LogDir = '%s%s%s' % ( os.path.abspath(logdir), os.sep, '%s%s' % (self.Name, time.strftime("_%Y%m%d_%H%M%S", time.localtime()))) #self.LogDir = self.LogDir.replace('\\',os.path.sep).replace('/', os.path.sep).replace(':','') os.mkdir(self.LogDir) self.Setup = steps[0] self.Run = steps[1] self.Teardown = steps[2] self.Steps = steps self.SUTs = suts self.Mode = mode.upper() import logging logfile = self.LogDir + os.sep + "TC_" + self.Name + ".log" logging.basicConfig(level=logging.DEBUG, format=self.Name + ' %(asctime)s -%(levelname)s: %(message)s') from common import CLogger self.logger = CLogger(self.Name) self.hdrlog = logging.FileHandler(logfile) self.logger.setLevel(logging.DEBUG) self.hdrlog.setFormatter( logging.Formatter('%(asctime)s -%(levelname)s: %(message)s')) self.logger.addHandler(self.hdrlog) sutstring = '' self.SUTNAME = sorted(suts.keys()) self.SUTNAME.append('__case__') self.RecordReplay = [['[cs]'], ['#VAR'], ['#SETUP']] newrecord = ['#SUTNAME', 'COMMAND', 'EXPECT', 'WAIT TIME(s)'] before1staction = [ '#', '', '', '', ] for sut in self.SUTNAME: newrecord.append(sut + ' OUTPUT') before1staction.append('') self.RecordReplay.append(newrecord) self.RecordReplay.append(before1staction) thList = [] for sut in self.SUTs.keys(): if sut == '__case__': continue sutstring += 'SUT(%s):[%s]\n' % (sut, self.SUTs[sut]) self.info('connecting to %s' % (sut)) try: thList.append( threading.Thread(target=self.Connect2Sut, args=[sut])) thList[-1].start() except Exception as e: import traceback self.info(traceback.format_exc()) print(traceback.format_exc()) raise Exception('Can NOT connected to %s' % sut) for t in thList: t.join() self.InitialDone = True