示例#1
0
 def getTerminalSN(self):
     # 从提供的设备列表中选择对应的移动终端
     if TerminalSn is not None:
         return TerminalSn
     terminalList = []  # 用于存放匹配的设备列表
     terminalObject = ParseExcel()
     print(TerminalFilePath)
     terminalObject.loadWorkBook(TerminalFilePath)
     # 根据用例步骤名获取步骤sheet对象
     stepSheet = terminalObject.getSheetByName('Terminal')
     # 获取步骤sheet中步骤数
     stepNum = terminalObject.getRowsNumber(stepSheet)
     # 获取前端入参
     orderPlatform = self.jsonDict.get('orderplatform',
                                       'android')  # 获取终端系统类型
     bitType = self.jsonDict.get('bitType', '32')  # 获取终端设备位数
     manufacturer = self.jsonDict.get('manufacturer', 'huawei')  # 获取终端厂商名称
     for step in range(2, stepNum + 1):
         stepRow = terminalObject.getRow(stepSheet, step)
         terminalSN = stepRow[terminal_ser - 1].value
         terminalPlatform = stepRow[terminal_platform - 1].value
         terminalBittype = str(stepRow[terminal_bittype - 1].value)
         terminalManufacturer = stepRow[terminal_manufacturer - 1].value
         terminalIsonline = stepRow[terminal_isonline - 1].value
         if terminalPlatform == orderPlatform and terminalBittype == bitType:
             if terminalSN and terminalIsonline == 'Y':
                 terminalList.append(terminalSN)
     return None if len(terminalList) == 0 else terminalList[random.randint(
         0,
         len(terminalList) - 1)]
#encoding = utf-8
import traceback
from action.PageAction import *
import time
from config.VarConfig import *
from util.ParseExcel import ParseExcel
from util.Log import *

#创建解析Excel对象
excelObj = ParseExcel()
#将Excel数据文件加载到内存
excelObj.loadWorkBook(dataFilePath)


#用例或用例步骤执行结束后,向Excel中写执行结果信息
def writeTestResult(sheetObj,
                    rowNo,
                    colsNo,
                    testResult,
                    errorInfo=None,
                    picPath=None):

    #测试通过结果信息为绿色,失败为红色
    colorDict = {"pass": "******", "faild": "red"}

    #因为"测试用例"工作表和"用例步骤sheet表"中都有测试执行时间和测试结果列,定义此字典对象是为了区分具体应该写哪个工作表
    colsDict = {
        "testCase": [testCase_runTime, testCase_testResult],
        "caseStep": [testStep_runTime, testStep_testResult]
    }
    try:
示例#3
0
class GetRequestData(object):
    def __init__(self, filePath):
        # 创建解析Excel工具类的实例对象
        self.parseEx = ParseExcel()
        # 将数据文件Excel加载到内存
        self.parseEx.loadWorkBook(filePath)
        self.apiSheetFileName = ""
        self.apiName = ""
        self.requestMethod = ""
        self.requestUrl = ""
        self.paramsInfo = ""
        self.reponseDataStore = {}
        self.CheckPoint = {}

    def getApi(self):
        # 通过Excel工具类中提供的getSheetByName方法获取数据文件中存放api工作表的对象
        apiSheetObject = self.parseEx.getSheetByName(ApiSheetName)
        # 获取api表中是否需要执行列对象
        isExecColObj = self.parseEx.getColumn(apiSheetObject, API_isExecute)
        # print('isExecColObj=',isExecColObj)
        for idx, col in enumerate(isExecColObj[1:]):
            print('idx=', idx)
            if col.value == "y":
                # 如果单元格的值为y,说明该行的api需要被执行

                # 依次获取需要执行api的行对象,以便拿到请求api的相关数据
                rowObj = self.parseEx.getRow(apiSheetObject, idx + 2)
                # API_name等变量定义在GloableData里面
                self.apiName = rowObj[API_name - 1].value
                self.requestUrl = rowObj[API_requestUrl - 1].value
                self.requestMethod = rowObj[API_requestMothod - 1].value
                self.paramsInfo = rowObj[API_paramsInfo - 1].value
                apiTestCasefileName = rowObj[API_requestDataFile - 1].value
                print(self.apiName, self.requestUrl, self.requestMethod,
                      self.paramsInfo, apiTestCasefileName)
                self.getTestCase(apiTestCasefileName)
            else:
                print(u"接口【" + rowObj[API_name - 1].value + u"】被忽略执行")

    def getTestCase(self, testCaseSheetName):
        try:
            # 根据测试用例sheet名获取sheet对象
            testCaseObj = self.parseEx.getSheetByName(testCaseSheetName)
            # 获取测试用例表中是否执行列对象
            isExeccolObj = self.parseEx.getColumn(testCaseObj,
                                                  TestCase_isExecute)
            for t_idx, t_col in enumerate(isExeccolObj[1:]):
                # 依次遍历测试用例表中的测试用例行,需要执行则执行
                if t_col.value == "y":
                    # 如果测试用例单元格值为y,说明该行测试用例需要被执行
                    rowObj = self.parseEx.getRow(testCaseObj, t_idx + 2)
                    RequestHeaders = rowObj[TestCase_requestHeaders - 1].value
                    HeadersEncrypt = rowObj[TestCase_headersEncrypt - 1].value
                    RequestData = rowObj[TestCase_requestData - 1].value
                    # 如果没有内容,得到的将是None,如果有内容,根据我们自己定义的规则,得到将是一个字符串字典类型数据"{xxx}"
                    BodyEncrypt = rowObj[TestCase_bodyEncrypt - 1].value

                    ResponseDecrypt = rowObj[TestCase_responseDecrypt -
                                             1].value
                    DependDataStore = rowObj[TestCase_DependDataStore -
                                             1].value
                    self.CheckPoint = rowObj[TestCase_checkPoint - 1].value
                    print(RequestHeaders, RequestData, DependDataStore,
                          self.CheckPoint)

                    RequestHeaders = ast.literal_eval(RequestHeaders) if (
                        RequestHeaders) else None
                    RequestData = ast.literal_eval(RequestData) if (
                        RequestData) else None
                    print('111111111111', type(RequestData))
                    HeadersEncrypt = ast.literal_eval(HeadersEncrypt) if (
                        HeadersEncrypt) else None
                    BodyEncrypt = ast.literal_eval(BodyEncrypt) if (
                        BodyEncrypt) else None

                    if BodyEncrypt and RequestData:
                        # 对请求参数进行加密处理,如果需要的话
                        RequestData = paramsOper(RequestData, BodyEncrypt)
                        print("sdfd = ", type(RequestData))
                    if HeadersEncrypt and RequestHeaders:
                        # 对头信息进行加密处理,如果需要的话
                        RequestHeaders = paramsOper(RequestHeaders,
                                                    HeadersEncrypt)
                        print(RequestHeaders)
                    # 数据存储
                    if DependDataStore:
                        DependDataStore = ast.literal_eval(DependDataStore)
                        if isinstance(DependDataStore,
                                      dict) and "request" in DependDataStore:
                            requestDataStore = {
                                "request": DependDataStore["request"]
                            }

                            d = DataStore()
                            print("sdfd = ", type(RequestData))
                            # storage(self, fileName, ApiName, sourceData, sourceDataIndex, needStoreData)
                            d.storage(ApiSheetName, self.apiName, RequestData,
                                      t_idx + 1, requestDataStore)
                        elif isinstance(
                                DependDataStore,
                                dict) and "response" in DependDataStore:
                            self.reponseDataStore = {
                                "response": DependDataStore["response"]
                            }
                        else:
                            print(u"存储数据数据规则错误")
                    else:
                        print(u"不需要存储依赖数据")
                    # 处理完请求参数以及依赖数据存储后,接下来该发送接口请求了
                    self.sendRequest(RequestData, RequestHeaders, t_idx + 1)
                else:
                    print(u"测试用例文件【" + testCaseSheetName + "】中第%d条用例被忽略执行" %
                          (t_idx + 1))
        except Exception as e:
            raise e

    def sendRequest(self, RequestData, RequestHeaders, index):
        dataFormat, paramType, dataOper = "", "", ""
        res = self.paramsInfo.split("_")
        if len(res) == 3:
            dataFormat, paramType, dataOper = res
        elif len(res) == 2:
            dataFormat, paramType = res
            print('dataFormat, paramType=', dataFormat, paramType)
        elif len(res) == 1:
            dataFormat = res[0]
            print('dataFormat=', dataFormat)
        if dataOper == "json":
            RequestData = json.dumps(RequestData)
        elif dataFormat == 'data':
            if type(RequestData) == str:
                RequestData = ast.literal_eval(RequestData)

        httpC = HttpClient()
        # requestMethod, requesturl, paramMethod = None, requestData = None, headers = None, ** kwargs
        responseObj = httpC.request(self.requestMethod,
                                    self.requestUrl,
                                    paramType,
                                    RequestData,
                                    RequestHeaders,
                                    timeout=10)
        print(responseObj.json())
        print(responseObj.text)
        print(type(responseObj.text))
        self.ReponseDataStore(responseObj.text, index)

    def ReponseDataStore(self, responseObj, index):
        if self.reponseDataStore:
            d = DataStore()
            # fileName, ApiName, sourceData, sourceDataIndex, needStoreData
            if type(responseObj) == str:
                RequestData = ast.literal_eval(responseObj)
            d.storage(ApiSheetName, self.apiName, responseObj, index,
                      self.reponseDataStore)
        checkPoint = ast.literal_eval(
            self.CheckPoint) if self.CheckPoint else {}
示例#4
0
class executeScriptWithPC(object):
    #针对pc环境的脚本执行操作
    def __init__(self, FilePath):
        # 创建解析Excel对象
        self.excelObj = ParseExcel()
        self.excelFile = FilePath
        self.excelObj.loadWorkBook(FilePath)

    def executeStep(self, stepSheet, step, stepDescribe, keyWord, locationType,
                    locatorExpression, operateValue):
        #执行web主流程测试步骤,并记录测试结果到excel文件中
        #初始化执行语句表达式为空
        expressionStr = ""
        # 构造需要执行的python语句,
        # 对应的是PageAction.py文件中的页面动作函数调用的字符串表示
        if keyWord and operateValue and locationType is None and locatorExpression is None:
            expressionStr = keyWord.strip() + "('" + operateValue + "')"
        elif keyWord and operateValue is None and locationType is None and locatorExpression is None:
            expressionStr = keyWord.strip() + "()"
        elif keyWord and locationType and operateValue and locatorExpression is None:
            expressionStr = keyWord.strip() + "('" + locationType.strip(
            ) + "', '" + operateValue + "')"
        elif keyWord and locationType and locatorExpression and operateValue:
            expressionStr = keyWord.strip() + "('" + locationType.strip(
            ) + "', '" + locatorExpression.replace(
                "'", '"').strip() + "', '" + operateValue + "')"
        elif keyWord and locationType and locatorExpression and operateValue is None:
            expressionStr = keyWord.strip() + "('" + locationType.strip(
            ) + "', '" + locatorExpression.replace("'", '"').strip() + "')"
        print(expressionStr)
        try:
            eval(expressionStr)
            # 在测试执行时间列写入执行时间
            self.excelObj.writeCellCurrentTime(stepSheet,
                                               rowNo=step,
                                               colsNo=testStep_runTime)
        except Exception as err:
            # 截取异常屏幕图片
            capturePic = capture_screen()
            # 获取详细的异常堆栈信息
            errorInfo = traceback.format_exc()
            # 在测试步骤Sheet中写入失败信息
            writeTestResult(self.excelObj, stepSheet, step, "pc", "faild",
                            errorInfo, capturePic)
            info("步骤“%s”执行失败! 函数执行表达式为:%s" % (stepDescribe, expressionStr))
        else:
            # 在测试步骤Sheet中写入成功信息
            writeTestResult(self.excelObj, stepSheet, step, "pc", "pass")
            info("步骤“%s”执行通过!函数执行表达式为:%s" % (stepDescribe, expressionStr))

    def execute(self, caseStepSheetName):
        #根据测试sheetName,遍历表单中的测试步骤
        try:
            # 根据用例步骤名获取步骤sheet对象
            info('开始<%s>场景的测试...' % caseStepSheetName)
            stepSheet = self.excelObj.getSheetByName(caseStepSheetName)
            # 获取步骤sheet中步骤数
            stepNum = self.excelObj.getRowsNumber(stepSheet)
            for step in range(2, stepNum + 1):
                # 因为步骤sheet中的第一行为标题行,无需执行
                # 获取步骤sheet中第step行对象
                stepRow = self.excelObj.getRow(stepSheet, step)
                #获取测试步骤描述
                stepDescribe = stepRow[testStep_testStepDescribe - 1].value
                # 获取关键字作为调用的函数名
                keyWord = stepRow[testStep_keyWords - 1].value
                # 获取操作元素定位方式作为调用的函数的参数
                locationType = stepRow[testStep_locationType - 1].value
                # 获取操作元素的定位表达式作为调用函数的参数
                locatorExpression = stepRow[testStep_locatorExpression -
                                            1].value
                # 获取操作值作为调用函数的参数
                operateValue = stepRow[testStep_operateValue - 1].value
                # 将操作值为数字类型的数据转成字符串类型,方便字符串拼接
                if isinstance(operateValue, int):
                    operateValue = str(operateValue)
                #列出execute函数的入参
                args = stepSheet, step, stepDescribe, keyWord, locationType, locatorExpression, operateValue
                self.executeStep(*args)
        except Exception as err:
            # 打印详细的异常堆栈信息
            debug(traceback.print_exc())
        finally:
            eval("close_browser()")  #最终关闭浏览器

    def getOrderId(self):
        #获取订单号
        #参数在varConfig全局配置中定义
        return getAttr(expression_type, expression_str, expression_value)
示例#5
0
class executeScriptWithMobile(object):
    #针对移动终端的脚本执行操作
    def __init__(self, FilePath):
        self.excelObj = ParseExcel()
        self.excelFile = FilePath
        self.excelObj.loadWorkBook(FilePath)

    def executeStep(self, stepSheet, step, stepDescribe, keyWord, picValue,
                    threshold, target_pos, rgb):
        temp = ""  #初始化中间临时变量
        # 构造需要执行的python语句,对应的是AppAction.py文件中的终端动作函数调用的字符串表示
        if isinstance(picValue, int):
            picValue = str(picValue)
        if picValue and picValue.endswith('.png'):
            picValue = os.path.join(os.path.split(self.excelFile)[0], picValue)
        if threshold is None and target_pos is None and rgb is None:
            if picValue and picValue.endswith('.png'):
                temp = "(Template(r'" + picValue + "'))"
            else:
                temp = "'" + picValue + "'"
        elif threshold and target_pos is None and rgb is None:
            temp = "Template(r'" + picValue + "', threshold=" + str(
                threshold) + ")"
        elif threshold is None and target_pos and rgb is None:
            temp = "Template(r'" + picValue + "', target_pos=" + str(
                target_pos) + ")"
        elif threshold is None and target_pos is None and rgb:
            temp = "Template(r'" + picValue + "', rgb=" + rgb + ")"
        elif threshold and target_pos and rgb is None:
            temp = "Template('r" + picValue + "', threshold=" + str(
                threshold) + ", target_pos=" + str(target_pos) + ")"
        elif threshold and target_pos is None and rgb:
            temp = "Template(r'" + picValue + "', threshold=" + str(
                threshold) + ", rgb=" + rgb + ")"
        elif threshold is None and target_pos and rgb:
            temp = "Template(r'" + picValue + "', target_pos=" + str(
                target_pos) + ", rgb=" + rgb + ")"
        elif threshold and target_pos and rgb:
            temp = "Template(r'" + picValue + "', threshold=" + str(
                threshold) + ", target_pos=" + str(
                    target_pos) + ", rgb=" + rgb + ")"
        expressionStr = keyWord.strip() + "(" + temp + ")"
        # 执行表达式
        print(expressionStr)
        try:
            eval(expressionStr)
            # 在测试执行时间列写入执行时间
            self.excelObj.writeCellCurrentTime(stepSheet,
                                               rowNo=step,
                                               colsNo=mobile_runTime)
        except Exception as err:
            # 截取异常屏幕图片
            capturePic = snapShot()
            # 获取详细的异常堆栈信息
            errorInfo = traceback.format_exc()
            # 在测试步骤Sheet中写入失败信息
            writeTestResult(self.excelObj, stepSheet, step, "mobile", "faild",
                            errorInfo, capturePic)
            info("步骤“%s”执行失败!函数执行表达式为:%s" % (stepDescribe, expressionStr))
        else:
            # 在测试步骤Sheet中写入成功信息
            writeTestResult(self.excelObj, stepSheet, step, "mobile", "pass")
            # 记录syslog信息
            info("步骤“%s”执行通过!函数执行表达式为:%s" % (stepDescribe, expressionStr))

    def execute(self, caseStepSheetName):
        # 利用aritest执行手机终端,遍历指定excel表单中的内容
        try:
            # 根据用例步骤名获取步骤sheet对象
            info('开始<%s>场景的测试...' % caseStepSheetName)
            stepSheet = self.excelObj.getSheetByName(caseStepSheetName)
            # 获取步骤sheet中步骤数
            stepNum = self.excelObj.getRowsNumber(stepSheet)
            for step in range(2, stepNum + 1):
                stepRow = self.excelObj.getRow(stepSheet, step)
                # 获取excel表单中每一行单元格的数据
                stepDescribe = stepRow[testStep_testStepDescribe - 1].value
                keyWord = stepRow[mobile_keyWords - 1].value
                picValue = stepRow[mobile_picPath - 1].value
                threshold = stepRow[mobile_threshold - 1].value
                target_pos = stepRow[mobile_target_pos - 1].value
                rgb = stepRow[mobile_rgb - 1].value
                args = stepSheet, step, stepDescribe, keyWord, picValue, threshold, target_pos, rgb
                self.executeStep(*args)
        except Exception as err:
            # 打印详细的异常堆栈信息
            debug(traceback.print_exc())

    def getOrderId(self):
        # 获取订单号
        if jsonDict.get('orderTerminal') == '4':
            time.sleep(5)
            return TerminalPoco("com.jd.lib.ordercenter:id/atm").get_text()