Exemple #1
0
    def getTestList(self, child):
        testCaseList = []
        for tc in child:
            if tc.tag == settings.XML_TAG['testPlan']['testCase']:
                enabled = tc.get(settings.XML_TAG['testPlan']['enabled'])
                if enabled is None or enabled.lower().strip() == 'true':
                    testCasePath = tc.text  # 测试用例路径
                    if not isNoneOrEmpty(testCasePath):
                        testCasePath = testCasePath.strip()
                        testCasePath = delsuffix(testCasePath, '.py')  # 去掉后缀

                        paramPath = tc.get(
                            settings.XML_TAG['testPlan']['paramPath'])
                        if not isNoneOrEmpty(paramPath):
                            paramPath = paramPath.strip()
                            paramPath = delsuffix(paramPath, '.xml',
                                                  False)  # 增加后缀
                            if not isAbsolutePath(paramPath):
                                paramPath = delFirstChar(
                                    paramPath, ['/', '\\'])
                                paramPath = os.path.join(
                                    settings.PARAMETERIZATION['dataDir'],
                                    paramPath).replace('\\', '/')
                        else:
                            paramPath = None

                        scriptId = tc.get(
                            settings.XML_TAG['testPlan']['scriptId'])  # 脚本id
                        testCaseList.append({
                            'paramPath': paramPath,
                            'testCase': testCasePath,
                            'scriptId': scriptId
                        })
        return testCaseList
Exemple #2
0
    def updateSettings(self, model):
        if model == RunModel.TESTING:  # 测试模式
            settings.RUNMODEL = model
            settings.TESTCASE['runType'] = RunType.BROWSER

        if model == RunModel.ONLINE:  # 在线模式
            settings.RUNMODEL = model
            try:
                decodeJson = json.loads(self.uniqueCode.replace("'", "\""))
                hubDict = {}
                for browser in decodeJson['browsers'].keys():
                    br = browser.lower()[:2]
                    if br in BROWSER_ID:
                        hubDict[br] = decodeJson['browsers'][browser]
                        break
                self.hubDict = hubDict
                settings.SERVER['requestURL'] = decodeJson['requestURL']
            except Exception as e:
                putSystemLog('[ERROR-1002]:解析外部传入的JSON字符串引发的异常.%s' % e, None,
                             False, '', '', True)
                raise

            settings.TESTCASE['runType'] = RunType.REMOTE
            settings.REPORT['isWriteLog'] = True

        if model == RunModel.NORMAL:  # 正常模式
            settings.RUNMODEL = model

        # 修正
        if isNoneOrEmpty(settings.SERVER['requestURL']):  # 如果服务器url不正确,就不发送数据
            settings.SERVER['isRequest'] = False
Exemple #3
0
	def on_pushButton_save_clicked(self):
		try:
			self.testParamObj.paramsList = []

			rowCount = self.tableWidget_param.rowCount()

			for index in range(rowCount):
				id = self.tableWidget_param.item(index, 1).text()
				value = self.tableWidget_param.item(index, 2).text()
				description = self.tableWidget_param.item(index, 3).text()
				self.testParamObj.addParam(id, value, description)

			if isNoneOrEmpty(self.path):
				if rowCount > 0:
					self.path = self._parent.on_pushButton_createparam_clicked()
					self.testParamObj.path = self.path
				else:
					QMessageBox.information(self, '提示', '没有保存任何数据!')
			result = self.testParamObj.writeTestParamToXML()
			if result:
				self.loadParamData(self.path, True)
				success=qMessageBoxQuestion(self,'提示','保存成功!要关闭当前编辑窗口吗?')
				if success:
					self.hide()
			else:
				QMessageBox.warning(self, '警告', '保存失败!')
		except Exception as e:
			print(e)
Exemple #4
0
 def wrapper(driver, *args, **kwargs):
     ret = None
     lineNo = getLineNo()  # 获取行号
     errorMessage = ''
     result = RunResult.ERROR
     try:
         ret = func(driver, *args, **kwargs)
     except ConnectionRefusedError as e:
         errorMessage = '浏览器异常关闭.' + e.strerror
     except ScreenShotException as e:
         result = RunResult.WARNING
         errorMessage = e.message
     except Exception as e:
         if func.__name__ == 'runTest':
             errorMessage = getErrorMessage(e, '测试用例脚本发生错误,请检查脚本代码:')
         else:
             errorMessage = getErrorMessage(
                 e,
                 '[decorator.codeException_dec.%s]:' % (func.__name__))
     finally:
         if not isNoneOrEmpty(errorMessage):
             data = getJsonData(result, func.__name__, '', errorMessage,
                                '', '', '', '', lineNo, level,
                                driver._driver.sceneId,
                                driver._driver.logger.scriptId)
             putLog(data, driver._driver.logger, driver._driver.sceneId)
         return ret
Exemple #5
0
	def addHub(self, browser, enabled, remoteUrl='http://0.0.0.0:5555/wd/hub'):
		if isNoneOrEmpty(browser):
			browser = BROWSER_ID[0]
		enabled = True if enabled is None or enabled.lower().strip() == 'true' else False
		remoteUrl = 'http://0.0.0.0:4444/wd/hub' if remoteUrl is None else remoteUrl
		model = {'browser': browser, 'enabled': enabled, 'remoteUrl': remoteUrl}
		return model
Exemple #6
0
def getImagePath(imagePath):
	image = ''
	if not isNoneOrEmpty(imagePath):
		tempImage = imagePath.split(settings.REPORT['screenShotDir'])
		if len(tempImage) > 1:
			image = '截图:' + tempImage[1]
	return image
Exemple #7
0
	def __FF(self):
		location = settings.BROWSER['fireFox']['binary_location']
		if not isNoneOrEmpty(location):
			ffProfile = FirefoxProfile(profile_directory=location)
			driver = Firefox(firefox_profile=ffProfile)
		else:
			driver = Firefox()
		return driver
Exemple #8
0
 def initParams(self):
     if isNoneOrEmpty(self.params):
         self.params = {}
     else:
         try:
             self.params = json.loads(self.params.replace("'",
                                                          "\""))  #可能会报异常
         except Exception as e:
             raise JsonLoadsException(e)
Exemple #9
0
def setImageFormat(path):
	'''
	设置图片路径格式为相对路径
	:param image:
	:return:
	'''
	image = ''
	if not isNoneOrEmpty(path):
		image = pathJoin(basename(settings.SCRIPT_DIR), path.split(settings.SCRIPT_DIR)[1])
	return image
Exemple #10
0
	def addTestCase(self, testCasePath, enabled, paramPath):
		displayParamPath = ''
		absoluteParamPath = ''
		if not isNoneOrEmpty(paramPath):
			if not isAbsolutePath(paramPath):
				paramPath = delFirstChar(paramPath, ['/', '\\'])

				displayParamPath = delsuffix(paramPath, '.xml')
				absoluteParamPath = pathJoin(settings.PARAMETERIZATION['dataDir'], paramPath)
				absoluteParamPath = delsuffix(absoluteParamPath, '.xml', False)

		fileName = ''  # 文件名称
		disPlayPath = ''  # 显示路径
		absolutePath = ''  # 绝对路径
		if not isNoneOrEmpty(testCasePath):
			testCaseDir = settings.TESTCASE['testCaseDir']
			testCasePath = delFirstChar(testCasePath, ['/', '\\'])

			if not testCasePath.startswith(testCaseDir):
				testCasePath = testCaseDir + testCasePath

			absolutePath = pathJoin(settings.SCRIPT_DIR, testCasePath)
			absolutePath = delsuffix(absolutePath, '.py', False)
			fileName = os.path.basename(absolutePath).split('.')[0]
			disPlayPath = absolutePath.split(testCaseDir)[1]
			disPlayPath = delsuffix(disPlayPath, '.py')

		enabled = True if enabled is None or enabled.lower().strip() == 'true' else False

		def testCaseFunc():
			return TestCase(absolutePath, absoluteParamPath)

		model = {'name': fileName,
				 'obj': testCaseFunc,
				 'path': disPlayPath,
				 'paramPath': displayParamPath,
				 'absolutePath': absolutePath,
				 'absoluteParamPath': absoluteParamPath,
				 'enabled': enabled,
				 'unique': randomStr(10, True, True, True)
				 }
		return model
Exemple #11
0
 def getParamPath(self, testCase_node):
     paramPath = testCase_node.get(
         settings.XML_TAG['testPlan']['paramPath'])
     if not isNoneOrEmpty(paramPath):
         paramPath = delsuffix(paramPath.strip(), '.xml', False)  # 增加后缀
         if not isAbsolutePath(paramPath):
             paramPath = delFirstChar(paramPath, ['/', '\\'])
             paramPath = os.path.join(settings.PARAMETERIZATION['dataDir'],
                                      paramPath).replace('\\', '/')
     else:
         paramPath = None
     return paramPath
Exemple #12
0
 def getHubDict(self, child):
     hubDict = {}
     for hub in child:
         if hub.tag == settings.XML_TAG['testPlan']['hub']:
             enabled = hub.get(settings.XML_TAG['testPlan']['enabled'])
             if enabled is None or enabled.lower().strip() == 'true':
                 browser = hub.get(settings.XML_TAG['testPlan']['browser'])
                 if not isNoneOrEmpty(browser):
                     remotePath = hub.text.strip(
                     ) if hub.text is not None else ''
                     hubDict[browser.lower().strip()] = remotePath
     return hubDict
Exemple #13
0
	def __Chrome(self):
		option = webdriver.ChromeOptions()
		option.add_argument('--disable-popup-blocking')  # 屏蔽窗口拦截
		option.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"])  # 屏蔽收藏
		location = settings.BROWSER['chrome']['binary_location']
		if not isNoneOrEmpty(location):
			option.binary_location = location

		# userDataDir=EasyConfig().chromeUserDataDir
		# if self.isNoneOrEmpty(userDataDir)==False:
		# 	option.add_argument(userDataDir)
		driver = Chrome(chrome_options=option)
		return driver
Exemple #14
0
 def run(self):
     if isNoneOrEmpty(self.xmlPath):  # 当没有传入测试方案的时候,从控制台获取
         self.setTestPlanPathFromUser()
     testPlanName = self.xmlPath  #测试方案文件名称
     putSystemLog('程序启动.%s' % testPlanName, None, False, '', '', True)
     try:
         self.setRunModel()  # 设置运行模式
         self.updateSettings(self.model)  # 根据运行模式更新settings设置
         self.loadTestPlanXML()  # 加载测试方案配置文件
         self.start()  # 启动
     except Exception as e:
         pass
     finally:
         putSystemLog('程序结束.%s\n' % testPlanName, None, False, '', '', True)
Exemple #15
0
 def setHubDict(self, connection_node):
     if len(self.hubDict) != 0:
         return
     hubDict = {}
     hub_nodes = xmlHelper.find_nodes(connection_node,
                                      settings.XML_TAG['testPlan']['hub'])
     hub_nodes = xmlHelper.get_node_by_keyvalue(
         hub_nodes, {settings.XML_TAG['testPlan']['enabled']: 'True'}, True)
     for hub in hub_nodes:
         browser = hub.get(settings.XML_TAG['testPlan']['browser'])
         if not isNoneOrEmpty(browser):
             remotePath = hub.text.strip() if hub.text is not None else ''
             hubDict[browser.lower().strip()] = remotePath
     self.hubDict = hubDict
Exemple #16
0
def writeLog(data, logger):
	image = ''
	if not isNoneOrEmpty(data['image']):
		tempImage = data['image'].split(settings.REPORT['screenShotDir'])
		if len(tempImage) > 1:
			image = '截图:' + tempImage[1]

	txt = '行号:%-4s %-5s  %s[%s] ' % (data['lineNo'], data['result'], data['description'], data['cmd'])
	if data['result'] == RunResult.TRUE or data['result'] == RunResult.FALSE:
		txt += '用时:%s ' % (data['during'])
	elif data['result'] == RunResult.FAIL:
		txt += '%s 用时:%s %s 参数:%s ' % (data['elementAlias'], data['during'], image, data['cmdParam'])
	else:
		txt += '%s 用时:%s %s ' % (data['elementAlias'], data['during'], image)
	txt += data['errorMessage']

	logger.info(txt)
Exemple #17
0
    def compareResult(self):
        param = self.param
        r = self.response
        expectType = param.expectType
        putSystemLog('响应值:%s' % (r.status_code), self.logger, True,
                     RunStatus.RUNNING, RunResult.PASS, True, '响应值')
        if expectType == RequestDataType.JSON:
            if isNoneOrEmpty(self.param.expect):
                pass
            else:
                compareResult = self.compare()
                putSystemLog('Json对比结果:%s,%s' % compareResult[0],
                             compareResult[1], self.logger, True,
                             RunStatus.RUNNING, RunResult.PASS, True,
                             'Json对比结果')

        elif expectType == RequestDataType.STRING:
            putSystemLog(r.text, self.logger)
Exemple #18
0
	def readParamXml(self, paramPath, className='EasyCase', time=0):
		# 读取参数xml文件的数据
		params = {}
		try:
			tree = ET.parse(paramPath)  # 打开xml文档
			root = tree.getroot()  # 获得root节点
			count = len(root.findall('testCase'))
			num = time % count  # 读取参数的次数
			testClassElement = root[num].find("testClass[@name='%s']" % (className))
			if testClassElement is not None:
				for param in testClassElement:
					id = param.get(settings.XML_TAG['testParam']['id'])
					if not isNoneOrEmpty(id):
						value = '' if param.text is None else param.text
						params[id] = value
		except ZeroDivisionError as e:
			raise ReadParamFileException(e, '请检查参数化文件是否正确', RunResult.WARNING)
		except Exception as e:
			raise ReadParamFileException(e)
		return params
    def readParamXml(self, paramPath, className='EasyCase'):
        # 读取参数xml文件的数据
        paramsList = []  # 参数化测试用例的列表

        try:
            tree = xmlHelper.read_xml(paramPath)
            testCase_nodes = xmlHelper.find_nodes(
                tree, settings.XML_TAG['testParam']['testCase'])
            for testCase_node in testCase_nodes:
                testClass_node = xmlHelper.find_nodes(
                    testCase_node, "testClass[@name='EasyCase']")[0]
                params = {}
                for param in testClass_node:
                    id = param.get(settings.XML_TAG['testParam']['id'])
                    if not isNoneOrEmpty(id):
                        value = param.text or ''
                        params[id] = value
                paramsList.append(params)
        except Exception as e:
            raise ReadParamFileException(e)
        return paramsList
Exemple #20
0
def writeLogForInterface(data,logger):
	txt = '%-5s %s' % (data['result'], data['description'])
	if not isNoneOrEmpty(data['during']):
		txt+=' 用时:%s'%data['during']
	txt += ' %s'%str(data['errorMessage'])
	logger.info(txt)
Exemple #21
0
 def run(self):
     if isNoneOrEmpty(self.xmlPath):  # 当没有传入测试方案的时候,从控制台获取
         self.setTestPlanPathFromUser()
Exemple #22
0
 def getTestCasePath(self, testCase_node):
     path = testCase_node.text
     if isNoneOrEmpty(path):
         return None
     return delsuffix(path.strip(), '.py')  # 去掉后缀
Exemple #23
0
	def loadParamData(self, absoluteParamPath, fresh=False):
		if not fresh and self.path == absoluteParamPath and not isNoneOrEmpty(self.path):
			return
		self.path = absoluteParamPath
		self.testParamObj = TestParam(self.path)
		self.loadParamTable(self.testParamObj.paramsList)
Exemple #24
0
    def updateCommonSettings(self):
        '''
		该方法内更新通用设置
		'''
        if isNoneOrEmpty(settings.SERVER['requestURL']):  # 如果服务器url不正确,就不发送数据
            settings.SERVER['isRequest'] = False