Пример #1
0
    def LoadFile(self, SuiteFile, caserange=None, args=None):
        if caserange == None:
            caserange = 'ALL'
        if args == None:
            args = ''
        self.ArgStr = args.encode()
        print('ArgStr:', self.ArgStr)
        import os
        if str(SuiteFile).find('\\') != -1 or str(SuiteFile).find('/') != -1:
            self.SuiteFile = SuiteFile
        else:
            self.SuiteFile = self.RunCfg['suitedir'] + os.path.sep + SuiteFile

        with open(self.SuiteFile) as f:  #, newline=''
            suitestring = f.read()
            index = 0

            #temp = args.split(',')[1:]
            import shlex
            temp = shlex.split(args)

            print(temp)
            for arg in temp:
                suitestring = suitestring.replace("${%d}" % (index + 1), arg)
                index = index + 1
            print(suitestring)
        from common import csvstring2array
        self.CaseList = csvstring2array(suitestring)

        response = '%s(%s):completed' % (sys._getframe().f_code.co_name,
                                         self.SuiteFile)
        self.CaseRangeStr = caserange
        self.SetRange(caserange)
        return response
Пример #2
0
def FunctionArgParser(stringOfArgs):
    def GetFunArg(*argvs, **kwargs):
        Argvs = []
        Kwargvs = {}
        for arg in argvs:
            Argvs.append(arg)
        for k in kwargs.keys():
            Kwargvs.update({k: kwargs[k]})
        return Argvs, Kwargvs

    try:
        args, kw = eval('GetFunArg(%s)' % stringOfArgs)
    except Exception as e:

        from common import csvstring2array
        args = csvstring2array(stringOfArgs)[0]
        newargs = []
        for a in args:
            tmp = a.strip()
            if tmp.startswith('"') or tmp.startswith("'"):
                newargs.append(tmp)
            else:
                newargs.append('"%s"' % tmp)
        newstringArg = ','.join(newargs)
        args, kw = eval('GetFunArg(%s)' % newstringArg)

    return args, kw
Пример #3
0
    def loadcsv(self, filename, bench, casename, mode, arg=None):
        from common import LoadCaseFromCsv
        #bench,csvfile,casename, mode, argv=None

        if arg:
            from common import csvstring2array
            arg = csvstring2array(arg)
            arg = arg[0]
        else:
            arg = []
        arg.insert(0, mode)
        arg.insert(0, casename)
        arg.insert(0, bench)
        arg.insert(0, filename)
        arg.insert(0, '')
        sut, [Setup, Run,
              Teardown], MODE = LoadCaseFromCsv(bench, filename, casename,
                                                mode, arg)
        for i in Setup:
            if len(i) > 1:
                self.cmdbank.append(i[1])
        for i in Run:
            if len(i) > 1:
                self.cmdbank.append(i[1])
        for i in Teardown:
            if len(i) > 1:
                self.cmdbank.append(i[1])
Пример #4
0
    def LoadFile(self, SuiteFile, caserange=None, args=None):
        if caserange==None:
            caserange='ALL'
        if args==None:
            args=''
        self.ArgStr=args.encode()
        print('ArgStr:' ,self.ArgStr)
        import os
        if str(SuiteFile).find('\\')!=-1 or str(SuiteFile).find('/')!=-1:
            self.SuiteFile = SuiteFile
        else:
            self.SuiteFile = self.RunCfg['suitedir']+os.path.sep+SuiteFile

        with open(self.SuiteFile) as f:#, newline=''
            suitestring = f.read()
            index = 0

            #temp = args.split(',')[1:]
            import shlex
            temp = shlex.split(args)

            print(temp)
            for arg in temp:
                suitestring= suitestring.replace("${%d}"%(index+1), arg)
                index=index+1
            print(suitestring)
        from common import csvstring2array
        self.CaseList = csvstring2array(suitestring)


        response = '%s(%s):completed'%(sys._getframe().f_code.co_name, self.SuiteFile)
        self.CaseRangeStr = caserange
        self.SetRange(caserange)
        return response
Пример #5
0
    def loadcsv(self, filename,bench, casename, mode, arg=None):
        from common import  LoadCaseFromCsv
        #bench,csvfile,casename, mode, argv=None

        if arg:
            from common import csvstring2array
            arg = csvstring2array(arg)
            arg=arg[0]
        else:
            arg=[]
        arg.insert(0,mode)
        arg.insert(0,casename)
        arg.insert(0,bench)
        arg.insert(0,filename)
        arg.insert(0,'')
        sut,[Setup,Run,Teardown],MODE = LoadCaseFromCsv(bench,filename,casename,mode,arg)
        for i in Setup:
            if len(i)>1:
                self.cmdbank.append(i[1])
        for i in Run:
            if len(i)>1:
                self.cmdbank.append(i[1])
        for i in Teardown:
            if len(i)>1:
                self.cmdbank.append(i[1])
Пример #6
0
def FunctionArgParser(stringOfArgs):
    def GetFunArg(*argvs, **kwargs):
        Argvs =[]
        Kwargvs ={}
        for arg in argvs:
            Argvs.append(arg)
        for k in kwargs.keys():
            Kwargvs.update({k:kwargs[k]})
        return Argvs, Kwargvs
    try:
        args, kw = eval('GetFunArg(%s)'%stringOfArgs)
    except Exception as e:

        from common import csvstring2array
        args = csvstring2array(stringOfArgs)[0]
        newargs = []
        for a in args:
            tmp = a.strip()
            if tmp.startswith('"') or tmp.startswith("'"):
                newargs.append(tmp)
            else:
                newargs.append('"%s"'%tmp)
        newstringArg= ','.join(newargs)
        args, kw = eval('GetFunArg(%s)'%newstringArg)


    return args, kw
Пример #7
0
    def __init__(self, name, attrs={}, logger=None, logpath='./'):
        self.sutname = name
        self.attrs = attrs
        command = attrs.get('CMD')
        if not attrs.get('TIMEOUT'):
            self.attrs.update({'TIMEOUT': int(30)})
        else:
            self.attrs.update({'TIMEOUT': int(attrs.get('TIMEOUT'))})
        #spawn.__init__(self, command, args, timeout, maxread, searchwindowsize, logfile, cwd, env, ignore_sighup)
        import os
        log = os.path.abspath(logpath)
        log = '%s%s%s' % (log, os.path.sep, '%s.log' % name)
        if self.attrs.get('LOGIN'):
            from common import csvstring2array
            self.loginstep = csvstring2array(self.attrs['LOGIN'])

        self.seslog = open(log, "wb")
        CSession.__init__(self, name, attrs, logger, logpath)
Пример #8
0
 def __init__(self,name,attrs={},logger=None,logpath='./'):
     self.sutname=name
     self.attrs=attrs        
     command = attrs.get('CMD')
     if not attrs.get('TIMEOUT'):
         self.attrs.update({'TIMEOUT':int(30)})
     else:
         self.attrs.update({'TIMEOUT':int(attrs.get('TIMEOUT'))})
     #spawn.__init__(self, command, args, timeout, maxread, searchwindowsize, logfile, cwd, env, ignore_sighup)
     import os
     log = os.path.abspath(logpath)
     log= '%s%s%s'%(log,os.path.sep,'%s.log'%name)
     if self.attrs.get('LOGIN'):
         from common import csvstring2array
         self.loginstep= csvstring2array(self.attrs['LOGIN'])
      
     self.seslog = open(log, "wb")
     CSession.__init__(self, name, attrs,logger, logpath)
Пример #9
0
        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)
Пример #10
0
 def __init__(self, name, attrs={}, logger=None, logpath=None):
     self.argvs = []
     self.kwargvs = {}
     if logpath == None:
         import os
         logpath = '.%s' % (os.path.sep)
     self.sutname = name
     self.attrs = attrs
     if not attrs.get('TIMEOUT'):
         self.attrs.update({'TIMEOUT': int(30)})
     else:
         self.attrs.update({'TIMEOUT': int(attrs.get('TIMEOUT'))})
     import os
     log = os.path.abspath(logpath)
     log = '%s%s%s' % (log, os.path.sep, '%s.log' % name)
     if self.attrs.get('LOGIN'):
         from common import csvstring2array
         self.loginstep = csvstring2array(self.attrs['LOGIN'])
     self.seslog = open(log, "wb")
     self.InteractionBuffer = ''
     self.InteractionMatch = ''
Пример #11
0
 def __init__(self, name,attrs={},logger=None, logpath=None):
     self.argvs=[]
     self.kwargvs={}
     if logpath ==None:
         import os
         logpath = '.%s'%(os.path.sep)
     self.sutname=name
     self.attrs=attrs
     if not attrs.get('TIMEOUT'):
         self.attrs.update({'TIMEOUT':int(30)})
     else:
         self.attrs.update({'TIMEOUT':int(attrs.get('TIMEOUT'))})
     import os
     log = os.path.abspath(logpath)
     log= '%s%s%s'%(log,os.path.sep,'%s.log'%name)
     if self.attrs.get('LOGIN'):
         from common import csvstring2array
         self.loginstep= csvstring2array(self.attrs['LOGIN'])
     self.seslog = open(log, "wb")
     self.InteractionBuffer=''
     self.InteractionMatch=''
Пример #12
0
        def loadCsvSuite2Array(filename, arglist, rangelist='all'):
            totalCase = 0

            from common import csvstring2array
            numOfArglist = len(arglist)
            pComments = re.compile('\s*#', re.IGNORECASE)
            SuiteArray = []
            lstConc = []
            caserange = rangelist
            if rangelist == 'all':
                caserange = []
            lastLineNoOfConcurrent = 0
            with open(suitfile, 'r') as suitefile:
                from runner import run_case_in_suite, loop, concurrent

                previousAction = run_case_in_suite
                lineNo = 0
                suiteIndex = 0
                for line in suitefile.readlines():
                    lineNo += 1

                    if re.match(pComments, line):
                        continue
                    if rangelist == 'all':
                        caserange.append(suiteIndex)
                    if (suiteIndex) not in caserange:
                        suiteIndex += 1
                        continue
                    index = 0
                    while index < numOfArglist:
                        index += 1
                        line = re.sub('\$\s*\{\s*%d\s*\}' % (index),
                                      arglist[index - 1], line)
                    columns = csvstring2array(line)[0]
                    tmp = []
                    totalCase += 1
                    for i in columns:
                        if re.match(pComments, i):
                            break
                        else:
                            tmp.append(i)
                    columns = tmp
                    lenColum = len(columns)
                    # case line     	#fail action	#loop	                #concurrent
                    #default	        continue        loop 1 stop_at_fail	    concurrent 0
                    #	                break	        loop xxx no_stop	    concurrent not_zero
                    #	                continue	    loop xxx stop_at_fail	concurrent 0

                    default_case_line = ''
                    default_failAction = 'continue'
                    default_loop = 'loop 1 stop_at_fail'
                    default_concurrent = 'concurrent 0'
                    SuiteLine = [
                        default_case_line, default_failAction, default_loop,
                        default_concurrent
                    ]
                    maxCol = len(SuiteLine)
                    for index, col in enumerate(columns[:maxCol]):
                        if col.strip() == '':
                            continue
                        else:
                            SuiteLine[index] = col
                    if lineNo == 8:
                        pass
                    cmd, failAction, loopAction, ConcAction = SuiteLine
                    failAction = parseFailAction(lineNo, failAction)
                    newConc, ConcNumber, flagAllFailIsFail = parserConcurent(
                        lineNo, ConcAction)
                    loopCounter, loop_stop_at_fail = parserLoop(
                        lineNo, loopAction)

                    tmpSuiteLine = SuiteLine
                    currentAction = previousAction

                    if ConcNumber > 0:
                        currentAction = concurrent
                        failAction = 'break'
                        stop_on_fail = True
                        lastLineNoOfConcurrent = lineNo
                        if newConc == 'new':
                            if previousAction == concurrent:
                                newSuiteLine = [currentAction, lstConc]
                                SuiteArray.append(
                                    [lineNo - 1, failAction, newSuiteLine])
                            else:
                                previousAction = currentAction
                            if loopCounter > 1:
                                action = concurrent
                                lstConc = [[
                                    ConcNumber, lineNo - 1, failAction, action,
                                    cmd, flagAllFailIsFail, loopCounter,
                                    loop_stop_at_fail
                                ]]
                                #lstConc=[[action, loopCounter, loop_stop_at_fail, cmd, ]]
                            else:
                                action = run_case_in_suite
                                lstConc = [[
                                    ConcNumber, lineNo - 1, failAction, action,
                                    cmd, flagAllFailIsFail, loopCounter,
                                    loop_stop_at_fail
                                ]]
                                #lstConc=[[action,loopCounter, loop_stop_at_fail,  cmd]]
                        else:

                            if loopCounter > 1:
                                action = loop
                                lstConc.append([
                                    action, loopCounter, loop_stop_at_fail, cmd
                                ])
                            else:
                                action = run_case_in_suite
                                lstConc.append([
                                    ConcNumber, lineNo - 1, failAction, action,
                                    cmd, flagAllFailIsFail, loopCounter,
                                    loop_stop_at_fail
                                ])
                                #fork, LineNo,failAction,cmd, allFailIsFail
                                #fork, index, totalThread, LineNo,indexInSuite,failAction,logpath,cmd, allFailIsFail
                            previousAction = currentAction
                    else:
                        currentAction = None
                        if previousAction == concurrent:
                            newSuiteLine = [previousAction, lstConc]
                            lstConc = []
                            prefailAction = 'break'
                            SuiteArray.append(
                                [lineNo - 1, prefailAction, newSuiteLine])

                        if loopCounter > 1:
                            action = loop
                            currentAction = action
                            newSuiteLine = [
                                action, loopCounter, loop_stop_at_fail, cmd
                            ]
                            SuiteArray.append(
                                [lineNo, failAction, newSuiteLine])
                        else:
                            action = run_case_in_suite
                            currentAction = action
                            newSuiteLine = [action, cmd]
                            SuiteArray.append(
                                [lineNo, failAction, newSuiteLine])
                    suiteIndex += 1
                if lstConc != []:
                    SuiteArray.append([
                        lastLineNoOfConcurrent, 'break', [concurrent, lstConc]
                    ])
                return totalCase, SuiteArray
Пример #13
0
        def segTest(lineno, global_vars, previousDut, curseg, linestring, var,
                    setup, run, teardown, dutset):
            def substitude(global_var, local_vars, linestring):
                index = 0
                tmpline = linestring
                for gv in global_vars:
                    try:
                        tmpline = re.sub('\$\s*\{\s*%d\s*\}' % index, gv,
                                         tmpline)  #re.escape(gv)
                    except:
                        tmpline = re.sub('\$\s*\{\s*%d\s*\}' % index,
                                         re.escape(gv),
                                         tmpline)  #re.escape(gv)
                    index += 1
                for ln, lv, no in local_vars:
                    tmpline = re.sub('\$\s*\{\s*%s\s*\}' % (ln), lv, tmpline)
                return tmpline

            seg = curseg
            curdut = previousDut
            import re as sre
            reCaseEnd = sre.compile("^[\s]*#[\s]*END[\s]*", sre.I)
            reVar = sre.compile("^[\s]*#[\s]*VAR[\s]*", sre.I)
            reSetup = sre.compile("^[\s]*#[\s]*SETUP[\s]*", sre.I)
            reRun = sre.compile("^[\s]*#[\s]*RUN[\s]*", sre.I)
            reTeardown = sre.compile("^[\s]*#[\s]*TEARDOWN[\s]*", sre.I)
            #reOnFail    = sre.compile("^[\s]*#[\s]*ONFAIL[\s]*",sre.I)
            reComment = sre.compile("^[\s]*#.*", sre.I | sre.DOTALL)
            from common import csvstring2array
            strcsv = substitude(global_vars, var, linestring)
            rawdata = csvstring2array(strcsv)
            if len(rawdata):
                csv = rawdata[0]
            else:
                return seg, curdut
            strcsv = linestring  # ','.join(csv)

            if sre.match(reCaseEnd, strcsv):
                seg = state.index('end')
            elif sre.match(reVar, strcsv):
                seg = state.index('var')
            elif sre.match(reSetup, strcsv):
                seg = state.index('setup')
            elif sre.match(reRun, strcsv):
                seg = state.index('run')
            elif sre.match(reTeardown, strcsv):
                seg = state.index('teardown')
            elif sre.match(reComment, strcsv):
                pass
            else:
                if seg == state.index('begin'):
                    pass
                elif seg == state.index('var'):
                    addVar(csv, var, lineno)
                elif seg == state.index('setup'):
                    curdut = add2Segment(lineno, previousDut, csv, setup,
                                         dutset)
                elif seg == state.index('run'):
                    curdut = add2Segment(lineno, previousDut, csv, run, dutset)
                elif seg == state.index('teardown'):
                    curdut = add2Segment(lineno, previousDut, csv, teardown,
                                         dutset)
                elif seg == state.index('end'):
                    pass
                else:
                    raise ValueError(
                        'unknown state(%d) in CSV file, it should be one of %s'
                        % (seg, str(state)))
            return seg, curdut
Пример #14
0
        def test_Case(self):
            from common import DumpStack
            try:
                try :
                    abc='str, abc'
                    import inspect
                    print(globals())
                    print(locals())
                    trace= inspect.trace()
                    lastframe = trace[-1][0]
                    locals= repr(lastframe.f_locals).replace('\\\\', '\\')
                    globals= repr(lastframe.f_globals).replace('\\\\', '\\')
                    print(locals)
                    print(globals)
                    raise 'abc'

                except Exception as e:
                    def dumpenv(env):
                        import operator
                        d = {}
                        s=''
                        key =env.keys()
                        key = sorted(key)
                        for k in key:
                            n = k
                            o= env[k]
                            s+='\t%s: %s\n'%(repr(n),repr(o).replace('\\\\', '\\'))
                        print(s)
                        return d
                    dumpenv(locals())
                    def dump_into_ns(env,*x):
                        class A:
                            def __init__(self):
                                for n,o in env.items():
                                    vars(self).update({n: o})

                        return A(*x)


                    a = 19
                    b = 'Monday'
                    c = 'Wednesday'

                    print()
                    def ftry(x,y):
                        palat = 'obastey'
                        a = x -1
                        b = y +100
                        c = x*y -8
                        return dump_into_ns(locals(),a,b,c)


                    import sys,traceback
                    h = dump_into_ns(globals())
                    exc_type, exc_value, exc_traceback = sys.exc_info()
                    str = traceback.format_exception(exc_type, exc_value,exc_traceback)
                    str = ''.join(str)
                    str=str.replace('\n', '\n*\t')

                    trace= inspect.trace()
                    lastframe = trace[-1][0]
                    locals= repr(lastframe.f_locals).replace('\\\\', '\\')
                    globals= repr(lastframe.f_globals).replace('\\\\', '\\')
                    from common import csvstring2array
                    d =csvstring2array(locals)
                    print(d)




                cmd = 'telnet 192.168.1.112'
                attr={'TIMEOUT':180,'LOGIN': '******','CMD':cmd, 'LINEEND':u''+chr(13), 'EXP':'name:', 'SUT':'' }

                #attr={'TIMEOUT': 10,'LOGIN': '******','CMD':'telnet 192.168.1.112' 'EXP':'login:'******'LINEEND':"u''+chr(13)"}
                sut = {'tel':attr}
                tcpport =50001
                ip = '192.168.1.110'
                from Server import Server

                svr = Server(ip, tcpport,'Case', 'Case',{'name':'abc', 'suts':sut,  'logdir':'../log', 'caseconfigfile':'../lib/case.cfg'}, 'IsAlive')
                c = svr.Handler
                try :
                    raise 'abc'

                except Exception as e:
                    s =DumpStack(e)
                    print(s)
                print(c.pp('SUTs'))
                #c.ActionCheck(['telLocal','pwd','~]',10])
                c.troubleshooting()
                client='192.168.1.100_61429_CASE2014-07-1702:20:12'
                resp =c.AddClient(client)
                resp = c.RequestSUTOutput(client,"tel")
                c.ActionCheck(['tel','ping localhost','.*', 1])
                c.ActionCheck(['tel','try 3:ctrl:c','SLV1 >', 30])
                #time.sleep(10)
                #resp =c.ActionCheck(['__case__', 'RequestSUTOutput("192.168.1.100_55710_CASE2014-07-1719:42:25""'])
                #resp =c.ActionCheck(['__case__', 'RequestSUTOutput("192.168.1.100_55710_CASE2014-07-1719:42:25""'])
                #resp =c.RequestSUTOutput(client,'tel')
                #time.sleep(10)
                #resp =c.RequestSUTOutput(client,'tel')
                #    c.ActionCheck(['telLocal','SLEEP(20.0)','~]',30])
                #c.ActionCheck(['telLocal','TRY 2:pwd','no:abc',30])
                #c.ActionCheck(['telLocal','TRY 2:noaction:pwd','nowait:no:abc',30])
                #import base64
                import json
                cmd =['RequestSUTOutput', client, 'tel']
                jcmd =json.dumps(cmd)
                from CSocket import SendRequest2Server
                resp = SendRequest2Server(ip, tcpport, jcmd)
                print(resp)
                #time.sleep(2)
        #        resp = SendRequest2Server(ip, tcpport, jcmd)
                c.EndCase(True)
                svr.StopServer()
            except Exception as e:

                print(DumpStack(e))
                print(e.__str__())
                msg = traceback.format_exc()
                print(msg)
                print('!!!!!!!!!!!!!!!!!!!!!!!!!!!CASE Failed!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
                exit(1)

            print('!!!!!!!!!!!!!!!!!!!!!!!!!!!CASE End!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
            exit(0)
Пример #15
0
        def loadCsvSuite2Array(filename, arglist, rangelist='all'):
            totalCase =0

            from common import csvstring2array
            numOfArglist = len(arglist)
            pComments = re.compile('\s*#',re.IGNORECASE)
            SuiteArray = []
            lstConc = []
            caserange = rangelist
            if rangelist=='all':
                caserange = []
            lastLineNoOfConcurrent=0
            with open(suitfile, 'r') as suitefile:
                from runner import run_case_in_suite, loop, concurrent

                previousAction = run_case_in_suite
                lineNo = 0
                suiteIndex = 0
                for line in suitefile.readlines():
                    lineNo+=1

                    if re.match(pComments, line):
                        continue
                    if rangelist =='all':
                        caserange.append(suiteIndex)
                    if (suiteIndex) not in caserange:
                        suiteIndex+=1
                        continue
                    index = 0
                    while index <numOfArglist:
                        index+=1
                        line =  re.sub('\$\s*\{\s*%d\s*\}'%(index), arglist[index-1], line)
                    columns = csvstring2array(line)[0]
                    tmp =[]
                    totalCase+=1
                    for i in columns:
                        if re.match(pComments, i):
                            break
                        else:
                            tmp.append(i)
                    columns =tmp
                    lenColum = len(columns)
                    # case line     	#fail action	#loop	                #concurrent
                    #default	        continue        loop 1 stop_at_fail	    concurrent 0
                    #	                break	        loop xxx no_stop	    concurrent not_zero
                    #	                continue	    loop xxx stop_at_fail	concurrent 0

                    default_case_line   = ''
                    default_failAction  = 'continue'
                    default_loop        = 'loop 1 stop_at_fail'
                    default_concurrent  = 'concurrent 0'
                    SuiteLine = [default_case_line,default_failAction, default_loop, default_concurrent]
                    maxCol = len(SuiteLine)
                    for index, col in enumerate( columns[:maxCol]):
                        if col.strip()=='':
                            continue
                        else:
                            SuiteLine[index]=col
                    if lineNo==8:
                        pass
                    cmd, failAction, loopAction, ConcAction = SuiteLine
                    failAction = parseFailAction(lineNo, failAction)
                    newConc,ConcNumber, flagAllFailIsFail = parserConcurent(lineNo, ConcAction)
                    loopCounter , loop_stop_at_fail = parserLoop(lineNo, loopAction)

                    tmpSuiteLine = SuiteLine
                    currentAction = previousAction

                    if ConcNumber>0:
                        currentAction = concurrent
                        failAction = 'break'
                        stop_on_fail = True
                        lastLineNoOfConcurrent =lineNo
                        if newConc =='new':
                            if previousAction ==  concurrent:
                                newSuiteLine =[currentAction,  lstConc]
                                SuiteArray.append([lineNo-1,failAction, newSuiteLine])
                            else:
                                previousAction= currentAction
                            if loopCounter>1:
                                action = concurrent
                                lstConc=[[ConcNumber, lineNo-1, failAction,action, cmd, flagAllFailIsFail, loopCounter, loop_stop_at_fail]]
                                #lstConc=[[action, loopCounter, loop_stop_at_fail, cmd, ]]
                            else:
                                action = run_case_in_suite
                                lstConc=[[ConcNumber, lineNo-1, failAction,action, cmd, flagAllFailIsFail, loopCounter, loop_stop_at_fail]]
                                #lstConc=[[action,loopCounter, loop_stop_at_fail,  cmd]]
                        else:

                            if loopCounter>1:
                                action = loop
                                lstConc.append([action,loopCounter, loop_stop_at_fail, cmd])
                            else:
                                action = run_case_in_suite
                                lstConc.append([ConcNumber, lineNo-1, failAction,action, cmd, flagAllFailIsFail,loopCounter, loop_stop_at_fail])
                                #fork, LineNo,failAction,cmd, allFailIsFail
                                #fork, index, totalThread, LineNo,indexInSuite,failAction,logpath,cmd, allFailIsFail
                            previousAction = currentAction
                    else:
                        currentAction = None
                        if previousAction== concurrent:
                            newSuiteLine =[previousAction, lstConc]
                            lstConc = []
                            prefailAction = 'break'
                            SuiteArray.append([lineNo-1,prefailAction, newSuiteLine])


                        if loopCounter>1:
                            action = loop
                            currentAction =action
                            newSuiteLine =[action,loopCounter, loop_stop_at_fail,cmd]
                            SuiteArray.append([lineNo,failAction, newSuiteLine])
                        else:
                            action = run_case_in_suite
                            currentAction = action
                            newSuiteLine =[action, cmd]
                            SuiteArray.append([lineNo,failAction, newSuiteLine])
                    suiteIndex+=1
                if lstConc !=[]:
                    SuiteArray.append([lastLineNoOfConcurrent,'break', [concurrent, lstConc]])
                return totalCase, SuiteArray
Пример #16
0
        def segTest(lineno,global_vars, previousDut, curseg , linestring, var,setup, run, teardown, dutset):

            def substitude(global_var, local_vars, linestring):
                index = 0
                tmpline = linestring
                for gv in global_vars:
                    try:
                        tmpline = re.sub('\$\s*\{\s*%d\s*\}'%index, gv, tmpline)#re.escape(gv)
                    except:
                        tmpline = re.sub('\$\s*\{\s*%d\s*\}'%index, re.escape(gv), tmpline)#re.escape(gv)
                    index+=1
                for ln, lv, no in local_vars:
                    tmpline = re.sub('\$\s*\{\s*%s\s*\}'%(ln), lv, tmpline)
                return tmpline
            seg = curseg
            curdut=previousDut
            import re as sre
            reCaseEnd   = sre.compile("^[\s]*#[\s]*END[\s]*",sre.I)
            reVar       = sre.compile("^[\s]*#[\s]*VAR[\s]*",sre.I)
            reSetup     = sre.compile("^[\s]*#[\s]*SETUP[\s]*",sre.I)
            reRun       = sre.compile("^[\s]*#[\s]*RUN[\s]*",sre.I)
            reTeardown  = sre.compile("^[\s]*#[\s]*TEARDOWN[\s]*",sre.I)
            #reOnFail    = sre.compile("^[\s]*#[\s]*ONFAIL[\s]*",sre.I)
            reComment    = sre.compile("^[\s]*#.*",sre.I|sre.DOTALL)
            from common import csvstring2array
            strcsv = substitude(global_vars,var,linestring)
            rawdata = csvstring2array(strcsv)
            if len(rawdata):
                csv = rawdata[0]
            else:
                return seg, curdut
            strcsv =linestring # ','.join(csv)

            if sre.match(reCaseEnd, strcsv):
                seg =  state.index('end')
            elif sre.match(reVar, strcsv):
                seg = state.index('var')
            elif sre.match(reSetup, strcsv):
                seg = state.index('setup')
            elif sre.match(reRun, strcsv):
                seg = state.index('run')
            elif sre.match(reTeardown, strcsv):
                seg = state.index('teardown')
            elif sre.match(reComment, strcsv):
                pass
            else:
                if seg == state.index('begin'):
                    pass
                elif seg == state.index('var'):
                    addVar(csv , var,lineno)
                elif seg == state.index('setup'):
                    curdut = add2Segment(lineno, previousDut, csv, setup, dutset)
                elif seg == state.index('run'):
                    curdut = add2Segment(lineno, previousDut, csv, run, dutset)
                elif seg == state.index('teardown'):
                    curdut = add2Segment(lineno, previousDut, csv, teardown, dutset)
                elif seg == state.index('end'):
                    pass
                else:
                    raise ValueError('unknown state(%d) in CSV file, it should be one of %s'%(seg, str(state)))
            return seg, curdut