Exemple #1
0
 def debugTest(self, tempFun, tempObj, jparam, tparam=tuple()):
     jsonArgs = {}
     for arg in getargspec(tempFun).args:
         val = ObjOperation.tryGetVal(jparam, arg, None)
         if val != None:
             jsonArgs[arg] = val
     tempFun(tempObj, *tparam, **jsonArgs)
Exemple #2
0
    def report(self, repHandler=slog.info, sumTitle='Test Summary:'):
        repRes = self.reportResult()
        if self.isInMode('show') or self.isInMode('scenario'):
            repHandler('\r\nFind Test Case(%s of %s):', repRes[MTConst.passed],
                       repRes['num'])
            self.reportResult(MTConst.passed, repHandler)
            repHandler('Summary: %s of %s', repRes[MTConst.passed],
                       repRes['num'])
        else:
            repHandler('\r\n%s\r\n%s' % (sumTitle, '-' * 60))
            sumInfo = '\r\nTotal\t%s, %sm:\r\n\t' % (
                repRes['num'], int(repRes['time'] / 60 + 0.5))
            hasRunRes = False
            for resType in range(4):
                try:
                    resInfo = self.getResInfo(resType)
                    resNum = ObjOperation.tryGetVal(repRes, resType, 0)
                    if resType != MTConst.notRun:
                        repHandler('%s\t%s:', resInfo, resNum)
                        self.reportResult(resType, repHandler)
                    sumInfo += (" + %s: %s"
                                if hasRunRes else "%s: %s") % (resInfo, resNum)
                    hasRunRes = True
                except Exception as ex:
                    slog.warn(ex)
                    continue
            repHandler(sumInfo)
#            repHandler('\r\nLog File:\r\n\t%s\n\n' % self.tlog.GetLoggerPath())
        return repRes
Exemple #3
0
    def packageCode(self, module, branch='trunk', svnPath="", codeIp=""):

        config = ObjOperation.tryGetVal(self.getModuleInfo(), module, {})
        packageName = "%s-%s-%s" % (module, branch,
                                    time.strftime("%Y%m%d-%H%M"))
        pkFile = '%s/%s.tar' % (pkFolder, packageName)
        if os.path.exists(pkFile):
            return 0, packageName

        # package code
        path = ObjOperation.tryGetVal(config, branch, svnPath)
        if path == "":
            path = ObjOperation.tryGetVal(config, "trunk", svnPath)
        resp = curlCservice(pkHost,
                            "PackageTool/packageToLocalFolder",
                            isCheckResp=True,
                            curlHeader={"host": pkHostName},
                            path=path,
                            module=module,
                            branch=branch,
                            packageName=packageName,
                            toFolder=ObjOperation.tryGetVal(
                                config, "deployFolder", module))
        plog.info(resp)

        # down load code
        downloadPkCmd = 'wget %s/file/%s_tar  --header="Host: %s" -q -O %s > /dev/null' % (
            pkHost, packageName, pkHostName, pkFile)
        os.system(downloadPkCmd)

        try:
            resp = curlCservice(pkHost,
                                "PackageTool/deletePackage",
                                isCheckResp=True,
                                curlHeader={"host": pkHostName},
                                packageName=packageName)
        except Exception as ex:
            return ex

        # check package
        if os.path.exists(pkFile):
            fsize = os.path.getsize(pkFile)
            if fsize < 20480:
                os.system("rm -rf %s" % pkFile)
        else:
            fsize = -1
        return fsize, packageName
Exemple #4
0
    def reportResult(self, resType=None, repHandler=slog.info):
        runRep = {
            'startTime': self.startTime,
            'endTime': time.time(),
            'num': 0,
            'time': 0,
            'cases': {
                MTConst.passed: {},
                MTConst.warned: {},
                MTConst.failed: {},
                MTConst.notRun: {}
            },
            MTConst.passed: 0,
            MTConst.warned: 0,
            MTConst.failed: 0,
            MTConst.notRun: 0
        }

        for tsName in self.tcInfos.keys():
            tcInfo = self.getTCInfo(tsName)
            for tcName in tcInfo.keys():
                tcResMap = tcInfo[tcName]
                for tpIndex in tcResMap.keys():
                    tcResInfo = tcResMap[tpIndex]
                    tcRes = tcResInfo['r']
                    tcTime = tcResInfo['t']
                    runRep[tcRes] = ObjOperation.tryGetVal(runRep, tcRes,
                                                           0) + 1
                    runRep['num'] += 1
                    runRep['time'] += tcTime

                    tcFullName = self.getTCFullName(tcName, tpIndex,
                                                    tcResInfo['d'])
                    if resType is None:
                        searchkey = tcResInfo['k']
                        author = ObjOperation.tryGetVal(
                            searchkey, 'author', '')
                        priority = ObjOperation.tryGetVal(
                            searchkey, 'priority', '')
                        runRep['cases'][tcRes][tcFullName] = "%ss%s%s" % (
                            tcTime, "" if author == "" else
                            (", %s" % author), "" if priority == "" else
                            (", %s" % priority))
                    elif resType == tcRes:
                        repHandler("\t%s%s", tcFullName,
                                   ("\t%ss" % tcTime) if tcTime > 0 else "")
        return runRep
Exemple #5
0
 def actionCalledView(self, dAct):
     retInfo = "%s = " % dAct.getReturnName() if dAct.isActive else ""
     callName = ObjOperation.tryGetVal(dAct.adpInfo, "calledName", "")
     if callName != "":
         callName = "%s.%s" % (callName, dAct.ActName)
     else:
         callName = dAct.ActName
     return '%s%s%s' % (retInfo, callName, dAct.ActInput)
Exemple #6
0
    def __init__(self, vmode):
        self.dactions = []
        self.paramKeyUsed = set()

        self.resetFileInfo()
        self.resetClassInfo()
        self.resetLanFormat()
        
        self.viewer = ObjOperation.tryGetVal(self.vmodes, vmode, ViewBase)(self.resetLanFormat)
Exemple #7
0
    def __init__(self, tParam, whereCondition, group):

        self.tParam = TValueGroup(tParam)
        self.condition = ObjOperation.tryGetVal(whereCondition, "condition",
                                                None)
        self.combSp = self.__combParam__(tParam, whereCondition, group)

        self.totalParams = self.combSp.getTotalNum()
        self.curOrderNum = 0
        self.curParamIndex = 0
Exemple #8
0
    def __groupParam__(self, tParam, whereCondition, group):
        if self.isNotGroup:
            return CombineWhereParam.__groupParam__(self, tParam,
                                                    whereCondition, group)
        defCombine = ObjOperation.tryGetVal(whereCondition, "combine", [])
        defStrategy = ObjOperation.tryGetVal(whereCondition, "strategy", [])
        self.isPureNum = True
        self.isList = False

        gdegress = []
        for gp in group:
            if not ObjOperation.tryGetVal(gp, "active", True):
                continue
            combine = ObjOperation.tryGetVal(gp, "combine", defCombine)
            strategy = ObjOperation.tryGetVal(gp, "strategy", defStrategy)
            r = ParamRender(gp['param'], combine, strategy == "datalist",
                            strategy != "product", True)
            self.paramRender.append(r)
            gdegress.append(r.getDegree())
        return GroupCombSpace(*gdegress)
Exemple #9
0
    def __addPathToArgPathContainer(self, argPathContainer, testPath,
                                    repeatCount):
        pathParam = TValueGroup({})
        stepIndexList = []
        stepIndexToCombIndex = {}
        isCondCover = self.strategy == "condition"
        isEdgeCover = self.strategy == "edge" or self.strategy == "condEdge" or isCondCover
        notCondCover = self.strategy == "path" or self.strategy == "edge" or self.strategy == 'available'

        noNewEdge, stepIndex, combIndex = self.__prepareTestPath(
            testPath, pathParam, stepIndexList, stepIndexToCombIndex,
            isEdgeCover, isCondCover)
        if isEdgeCover and noNewEdge:
            return

        pathCovered = False
        stepArg = CombineSingleParam(pathParam, {
            'combine': stepIndexList,
            'strategy': self.strategy
        }, None)
        while True:
            pathArg = stepArg.nextParam()
            if pathArg == None:
                break
            acceptRes, acceptStepIndex = self.__isTestPathAccept(
                testPath, pathArg)
            if acceptRes <= 9:
                addTestPath = testPath
                if stepIndex > acceptStepIndex:
                    addTestPath = list(testPath)
                    delStepIndex = stepIndex
                    while delStepIndex > acceptStepIndex:
                        addTestPath.__delitem__(delStepIndex)
                        pathArg.__delitem__(delStepIndex)
                        delStepIndex -= 1
                pathCovered = True
                argPathContainer.append({
                    'path': addTestPath,
                    'accept': acceptRes,
                    'arg': pathArg
                })
                if notCondCover:
                    break

            addCombIndex = ObjOperation.tryGetVal(stepIndexToCombIndex,
                                                  acceptStepIndex, combIndex)
            if addCombIndex < combIndex:
                stepArg.toNextParamArg(addCombIndex)

        if isEdgeCover and pathCovered:
            self.__coverTestPath(testPath)
Exemple #10
0
    def endFun(self, caseName, sparam, pIndex, searchKey, tcInfo, caseInfo):

        self.viewer.resetTestInfo(caseName, pIndex, sparam, tcInfo, searchKey)

        className = self.viewer.testClassNamedView(tcInfo.name)
        if not self.isCurClsName(className):
            classMeta = self.viewer.testClassMetaView()

            baseClass = ObjOperation.tryGetVal(tcInfo, "BaseClass", "")
            imports = ObjOperation.tryGetVal(tcInfo, "Imports", "")

            self.resetClassInfo(className, baseClass, classMeta, imports)

        funName = self.viewer.testCaseNamedView(None)
        funReturn = self.viewer.testCaseReturnView()
        funMeta = self.viewer.testCaseMetaView()
        funImpls = []
        for actCalled in self.dactions:
            funImpls += actCalled.getAction()
        self.addFun(funName, funReturn, funMeta, ("", funImpls))

        self.paramKeyUsed.clear()
        self.dactions = []
Exemple #11
0
    def getAction(self):

        caller = self.actionFactory.viewer.actionCalledView(self)
        result = [caller]

        if not self.adpInfo.__contains__("calledName"):
            clsName = self.adpInfo['_sys_n']
            self.adpInfo["calledName"] = ObjOperation.tryGetVal(
                self.adpInfo, "obj", clsName[0].lower() + clsName[1:])
            result.insert(
                0,
                self.actionFactory.viewer.objectInitView(
                    clsName, self.adpInfo["calledName"]))

        return result
Exemple #12
0
 def reportResult(self, resType=None, repHandler=slog.info):
     runRep = {'num':0, 'time':0, MTConst.passed:0, MTConst.warned:0, MTConst.failed:0, MTConst.notRun:0}
     for tsName in self.tcInfos.keys():
         tcInfo = self.getTCInfo(tsName)
         for tcName in tcInfo.keys():
             tcResMap = tcInfo[tcName]
             for tpIndex in tcResMap.keys():
                 tcResInfo = tcResMap[tpIndex]
                 tcRes = tcResInfo['r']
                 tcTime = tcResInfo['t']
                 runRep[tcRes] = ObjOperation.tryGetVal(runRep, tcRes, 0) + 1
                 runRep['num'] += 1
                 runRep['time'] += tcTime
                 if resType == tcRes:
                     repHandler("\t%s%s", self.getTCFullName(tcName, tpIndex, tcResInfo['d']) , ("\t%ss" % tcTime) if tcTime > 0 else "")
     return runRep
Exemple #13
0
    def __defineInput(self, actFun, tupleArg, jsonArg, adpInfo):
        actName = ObjOperation.tryGetVal(adpInfo, actFun.__name__,
                                         actFun.__name__)
        argspec = getargspec(actFun)
        argNames = argspec.args
        argDefaults = argspec.defaults
        if tupleArg is None:
            cpInput = None
        else:
            cpInput = []
            actInput = ArgsOperation.getTupleArgs(jsonArg, argNames, tupleArg,
                                                  argDefaults)

            for inputArg in actInput:
                try:
                    cpInput.append(copy.deepcopy(inputArg))
                except:
                    cpInput.append(inputArg)
            cpInput = tuple(cpInput)
        return actName, argNames, cpInput
Exemple #14
0
    def sendEmail(self, emailProxy, smtpAddr, smtpLogin, sender, receiver):
        if emailProxy == "" or smtpAddr == "" or receiver == "": return

        try:
            receiver = receiver.split(";")
            mimeMail = self.__makeEmail(sender, receiver, self.subject,
                                        self.htmlContent)
            if emailProxy.strip() != "":
                from server.cclient import curl
                from libs.parser import toJsonStr
                slog.info("Sending report: %s -> %s" % (emailProxy, receiver))
                slog.info(
                    curl(
                        "%s/cservice/TestPlanApi/sendMtestEmail" % emailProxy,
                        toJsonStr({
                            "mimeMail": mimeMail.as_string(),
                            "mailto": ";".join(receiver),
                            "mailcc": "",
                            "verify": "mtest"
                        })))
                return

            smtpAccount, smtpPasswd = base64.decodestring(smtpLogin).split("/")
            slog.info("Sending report mail(SMTP %s):\n\t%s -> %s" %
                      (smtpAddr, smtpAccount, receiver))
            smtp = smtpAddr.split(':')
            smtpServer = smtp[0]
            smtpPort = int(ObjOperation.tryGetVal(smtp, 1, 25))

            from smtplib import SMTP
            smtpClient = SMTP(smtpServer, smtpPort)
            try:
                smtpClient.ehlo()
                smtpClient.login(smtpAccount, smtpPasswd)
            except:
                pass
            smtpClient.sendmail(sender, receiver, mimeMail.as_string())
            smtpClient.quit()
        except Exception as ex:
            slog.info(self.htmlContent)
            slog.info("Fail to send mail for: %s" % ex)
Exemple #15
0
    def __init__(self):
        self.emailDailySubject = cprop.getVal('plan', 'emailDailySubject')
        self.emailDailySp = cprop.getVal('plan', 'emailDailySp')
        self.emailDailyRow = cprop.getVal('plan', 'emailDailyRow')
        self.emailDailyBody = cprop.getVal('plan', 'emailDailyBody')
        self.planLink = cprop.getVal('plan', 'planLink')
        self.emailDailyTitle = cprop.getVal('plan', 'emailDailyTitle')

        self.riskStatusDefine = cprop.getVal('plan', 'planStatus').split()
        self.emailPlanBodyTemplate = cprop.getVal('plan',
                                                  'emailPlanBodyTemplate')
        emailPlanRowFormat = 'textarea'
        self.emailPlanRowFormat = ObjOperation.tryGetVal(
            {
                'textarea': "<textarea>%s</textarea>",
                'pre': "<pre>%s</pre>"
            }, emailPlanRowFormat, '%s')
        self.emailPlanRow = cprop.getVal('plan', 'emailPlanRow')
        self.emailPlanRowTitle = cprop.getVal('plan', 'emailPlanRowTitle')

        self.reportBodyTemplate = cprop.getVal('plan', 'reportBodyTemplate')
Exemple #16
0
    def runScenario(self, tcObj, tcFun, caseName, param, where, group, status,
                    despFormat, searchKey):  # Status is for status modeling
        isInfoExcept = self.tc.isInMode("debug")

        clsName = tcObj.__class__.__name__
        tcInfo = self.tc.getTCInfo(clsName)
        tsInfo = tcInfo[caseName]
        for sKey in tcInfo.searchKey:
            if not searchKey.__contains__(sKey):
                searchKey[sKey] = tcInfo.searchKey[sKey]

        if status != None:
            from tmodel.model.statusmodel import TestModeling
            self.tc.isModeling = True
            modelLauncher = TestModeling(
                tcObj, ObjOperation.tryGetVal(status, "start", "Start"),
                ObjOperation.tryGetVal(status, "coverage", "all"))
            self.tc.isModeling = False
            param["sPath"] = modelLauncher.generatePaths()

            try:
                where["combine"].append("sPath")
            except:
                where = copy.deepcopy(where)
                where["combine"] = ["sPath"]
            tcFun = modelLauncher.launchTestPath

        try:
            mparam = ObjOperation.tryGetVal(where, "handle",
                                            CombineGroupParam)(param, where,
                                                               group)
        except Exception as ex:
            slog.warn(
                "Fail to generate parameter, case %s\nerror: %s\nparam= %s\nwhere= %s\ngroupParam= %s"
                % (caseName, "%s %s" %
                   (ex.__class__.__name__, ex), param, where, group))
            return not isInfoExcept
        while True:
            try:
                sparam = mparam.nextParam()
            except Exception as ex:
                sparam = None
                slog.warn(
                    "Fail to generate parameter, case %s\nerror: %s\nparam= %s\nwhere= %s\ngroupParam= %s"
                    % (caseName, "%s %s" %
                       (ex.__class__.__name__, ex), param, where, group))

            if sparam is None:
                break

            desp = self.tc.getTCDespcription(sparam, despFormat)
            caseInfo = self.tc.getCaseInfo(tsInfo, sparam.pIndex, desp,
                                           searchKey)
            caseFullName = self.tc.getTCFullName(caseName, sparam.pIndex, desp)

            if not self.tc.isInScope(caseFullName, searchKey):
                continue

            if self.tc.isInMode("show", -1):
                caseInfo['r'] = MTConst.passed
                if self.tc.isInMode("param"):
                    slog.info("%s\n%s\n", caseFullName, sparam)
                elif self.tc.isInMode("look"):
                    slog.info("%s\n%s\n%s\n", caseFullName, searchKey, sparam)
                elif self.tc.isInMode("scenario", -1):
                    if self.tc.isInMode("slook"):
                        slog.info("%s\n%s\n%s\n", caseFullName, searchKey,
                                  param)
                    tsInfo[0]['d'] = ""
                    return
                continue

            self.tassert.isWarned = False
            tcObj.param = sparam
            caseSimpleName = caseFullName.split(" ")[0]

            slog.info(MTConst.beginTestCaseInfo, caseFullName)
            self.tlog.beginTestCase(clsName, caseSimpleName, desp, sparam,
                                    searchKey)

            if self.tc.isInMode("debug", 1, True):
                resCode, exeTime = self.runTest(tcObj, tcInfo, tcFun, desp,
                                                isInfoExcept)
                if isInfoExcept and (resCode == MTConst.failed
                                     or resCode >= 3):
                    return False

            if self.endTestHandler != None:
                self.endTestHandler(caseName, sparam, sparam.pIndex, searchKey,
                                    tcInfo, caseInfo)

            try:
                resInfo = self.tc.getResInfo(resCode)
            except:
                resCode = MTConst.failed
                resInfo = self.tc.getResInfo(resCode)

            caseInfo['t'] = exeTime
            caseInfo['r'] = resCode

            (slog.warn if resCode == MTConst.failed else slog.info)(
                MTConst.endTestCaseInfo, resInfo, caseSimpleName)
            self.tlog.endTestCase(caseSimpleName, resInfo, resCode, exeTime)