Beispiel #1
0
        def wrapper(self, *args, **kwargs):
            ret = None
            element = self
            lineNo = getLineNo()  # 获取行号
            cmdParam = {'list': args, 'dict': kwargs}
            result = RunResult.FAIL
            errorMessage = ''
            sTime = time.time()
            number = int(EasyConfig().repeatFindTime)  # 重复查找次数
            n = number
            while n > 0:
                try:
                    ret = func(element, *args, **kwargs)
                    result = RunResult.PASS
                    errorMessage = '在%d次重复查找后找到元素' % (number -
                                                      n) if n != number else ''
                    break
                except WebDriverException:
                    time.sleep(2)
                    errorMessage = '由于页面改变,多次查找后未能找到元素'
                    element = self.elementFunc()  # 重新查找元素
                except Exception as e:
                    errorMessage = e
                n = n - 1

            eTime = time.time()
            image = screenShot(self.parent)
            data = getJsonData(result, func.__name__, cmdParam, errorMessage,
                               '%.3fs' % (eTime - sTime), image,
                               self.elementAlias, description, lineNo, 1)
            putLog(data, self.parent)

            time.sleep(EasyConfig().afterActionWait)

            return ret
Beispiel #2
0
def putLog(data, driver):
	if EasyConfig().isWriteLog:
		if findElementSuccess(data) and EasyConfig().showFindElementLog:  # 如果成功发现元素,则不打印日志
			putLogForFile(data, driver)  # 将日志写入文件
		elif findElementSuccess(data)==False :
			putLogForFile(data, driver)  # 将日志写入文件

	if EasyConfig().isRequest:
		putLogForServer(data, driver)  # 将入职发送到服务器
Beispiel #3
0
    def wrapper(self, by, value, alias):
        def saveFunc():
            # 该函数保存查找元素的状态及方法
            ret = None
            try:
                ret = func(self, by, value, alias)
                addElementAttr(ret, self, by, value, alias,
                               saveFunc)  # 为元素对象添加别名
            except Exception:
                pass
            return ret

        ret = None
        lineNo = getLineNo()  # 获取行号
        cmdParam = {'list': '', 'dict': {by: value}}
        errorMessage = ''
        elementAlias = ''
        result = RunResult.FAIL
        sTime = time.time()
        number = int(EasyConfig().repeatFindTime)  # 重复查找次数
        n = number
        while n > 0:
            try:
                ret = func(self, by, value, alias)
                result = RunResult.PASS
                errorMessage = '在%d次重复查找后找到元素' % (number -
                                                  n) if n != number else ''
                addElementAttr(ret, self, by, value, alias,
                               saveFunc)  # 为元素对象添加别名
                break
            except NoSuchElementException:
                errorMessage = '页面中没有该元素.NoSuchElementException'
                break
            except StaleElementReferenceException:
                errorMessage = '由于一些原因,多次查找后仍然找不到元素.StaleElementReferenceException'
                time.sleep(1)
            except Exception as e:
                errorMessage = e
            n = n - 1

        eTime = time.time()
        image = screenShot(self._driver, ret)
        data = getJsonData(result, func.__name__, cmdParam, errorMessage,
                           '%.3fs' % (eTime - sTime), image, elementAlias,
                           '查找元素', lineNo, 1)
        putLog(data, self._driver)

        time.sleep(EasyConfig().afterFindElementWait)
        return ret
Beispiel #4
0
        def wrapper(self, *args, **kwargs):
            ret = None
            lineNo = getLineNo()  # 获取行号
            cmdParam = {'list': args, 'dict': kwargs}
            errorMessage = ''
            result = RunResult.FAIL
            image = ''
            sTime = time.time()
            try:
                ret = func(self, *args, **kwargs)
                result = RunResult.PASS
            except Exception as e:
                errorMessage = e.args[0].split('\n')[0][:150]
            finally:
                eTime = time.time()
                if func.__name__ not in ['close', 'quit']:
                    image = screenShot(self._driver, ret)
                data = getJsonData(result, func.__name__, cmdParam,
                                   errorMessage, '%.3fs' % (eTime - sTime),
                                   image, '', description, lineNo, 1)
                putLog(data, self._driver)

                time.sleep(EasyConfig().afterActionWait)

            return ret
Beispiel #5
0
	def readTestPlanXML(self):
		'''
		加载测试方案配置文件
		:return:
		'''
		try:
			tree = ET.parse(self.path)  # 打开xml文档
			root = tree.getroot()  # 获得root节点
			for child in root:
				if child.tag == 'connection':
					for hub in child:
						self.addHub(hub.attrib['browser'], hub.get('enabled'), hub.text.strip())
				elif child.tag == 'scene':
					for tc in child:
						paramPath = tc.get('paramPath')
						if paramPath:
							if ':' not in paramPath and self.isNoneOrEmpty(paramPath) == False:
								paramPath = paramPath[1:] if paramPath[:1] == '/' or paramPath[
																					 :1] == '\\' else paramPath
								paramPath = '%s%s' % (EasyConfig().dataDir, paramPath)
						else:
							paramPath = ''
						testCasePath = tc.text.strip()
						testCasePath = testCasePath[1:] if testCasePath[:1] == '/' or testCasePath[
																					  :1] == '\\' else testCasePath

						self.addTestCase(testCasePath, tc.get('enabled'), paramPath)
		except Exception as e:
			print("[Error-TestPlan.readTestPlanXML]:读取测试方案错误 %s %s" % (self.path, str(e)))
Beispiel #6
0
    def bingDataToTable(self, index, model):
        number = str(index + 1)  # 序号
        enabled = model['enabled']  # 启用

        newCheckBox = QtWidgets.QCheckBox()
        newCheckBox.setChecked(enabled)

        name = model['name']  # 用例名称
        # 用例路径
        relativePath = model['path'].split(self.lineEdit_project.text())[1]
        relativePath = relativePath[:-3] if relativePath[
            -3:] == '.py' else relativePath
        # 参数化路径
        paramRelativePath = model['paramPath'].split(EasyConfig(
        ).dataDir)[1] if model['paramPath'].strip() != '' else ''

        dataList = [number, newCheckBox, name, relativePath, paramRelativePath]
        for i, content in enumerate(dataList):
            if isinstance(content, str):
                item = QtWidgets.QTableWidgetItem(content)
                self.tableWidget_testCase.setItem(index, i, item)
            elif isinstance(content, QWidget):
                self.tableWidget_testCase.setCellWidget(index, i, content)

        self.tableWidget_testCase.item(index, 0).testCase = model  # 绑定测试用例
Beispiel #7
0
 def start(self):
     # 配置场景
     runType = EasyConfig().runType.upper()
     if runType == RunType.REMOTE:
         self.__onLine()
     elif runType == RunType.BROWSER:
         self.__offLine()
Beispiel #8
0
	def addTestCase(self, relativePath, enabled='True', paramPath=''):
		path = os.path.join(EasyConfig().rootPath, relativePath).replace('\\', '/')
		path = path + '.py' if path[-3:] != '.py' else path
		fileName = os.path.basename(path).split('.')[0]
		enabled = True if enabled is None or enabled.lower().strip() == 'true' else False
		model = {'name': fileName, 'obj': TestCase(path, paramPath), 'path': path, 'paramPath': paramPath,
				 'enabled': enabled}
		self.testCaseList.append(model)
Beispiel #9
0
	def __init__(self, name, path=''):
		self.path = path
		self.name = name
		self.hub = []
		self.testCaseList = []
		self.acceptBrowser = ['ff', 'chrome', 'ie']
		self.testCaseDir = EasyConfig().getDir('/script/testCase/')  # 测试用例脚本目录
		self.readTestPlanXML()  # 分析xml文件
Beispiel #10
0
 def __FF(self):
     location = EasyConfig().ffLocation
     if self.isNoneOrEmpty(location) == False:
         ffProfile = FirefoxProfile(profile_directory=location)
         driver = Firefox(firefox_profile=ffProfile)
     else:
         driver = Firefox()
     return driver
Beispiel #11
0
    def __Chrome(self):
        option = webdriver.ChromeOptions()
        option.add_argument('--disable-popup-blocking')  #屏蔽窗口拦截
        option.add_experimental_option("excludeSwitches",
                                       ["ignore-certificate-errors"])  #屏蔽收藏
        location = EasyConfig().chromeLocation
        if self.isNoneOrEmpty(location) == False:
            option.binary_location = location

        # userDataDir=EasyConfig().chromeUserDataDir
        # if self.isNoneOrEmpty(userDataDir)==False:
        # 	option.add_argument(userDataDir)
        driver = Chrome(chrome_options=option)
        return driver
Beispiel #12
0
    def selectModel(self):
        '''
		######################选择启动模式########################
		如果启动的时候,外部有传入参数,则使用外部传入的xml配置文件路径
		如果外部没有传入参数,则使用config.xml配置的xml路径
		self.__xmlPath:测试用例的xml配置文件路径
		######################选择启动模式########################
		'''
        if len(sys.argv) > 1:
            self.__xmlPath = sys.argv[1]
        else:
            if ':' in self.__xml:
                self.__xmlPath = self.__xml  # 绝对路径
            else:
                self.__xmlPath = '%s%s' % (EasyConfig().xmlDir, self.__xml)
Beispiel #13
0
 def setBrowserView(self, testPlan):
     for name, controls in self.browsersDict.items():
         result = False if EasyConfig().runType == 'Browser' else True
         controls[1].setEnabled(result)
         controls[0].setEnabled(True)
         self.setBrowserValue(controls)
         for hub in testPlan.hub:
             browserName = hub['browser'].strip().lower()
             if browserName == name:
                 self.setBrowserValue(controls, hub['enabled'],
                                      hub['remoteUrl'], hub)
                 break
         if not controls[0].hub:
             model = testPlan.addHub(name, 'False')
             self.setBrowserValue(controls, model['enabled'],
                                  model['remoteUrl'], model)
Beispiel #14
0
def screenShot(driver, element=None):
    image = ""
    if EasyConfig().isScreenShot:
        if element and not isinstance(element, list):
            elementId = drawRect(driver, element)
            image = startScreenShot(driver)
            removeRectByJs(elementId, driver)
        elif element and isinstance(element, list):
            index = 0
            elementIdList = []
            for e in element:
                elementId = drawRect(driver, e, index)
                elementIdList.append(elementId)
                index = index + 1
            image = startScreenShot(driver)
            removeRect(elementIdList, driver)
        else:
            image = startScreenShot(driver)
    return image
Beispiel #15
0
    def loadTestCaseXML(self):
        '''
		加载测试用例配置文件
		:return:
		'''
        try:
            tree = ET.parse(self.__xmlPath)  # 打开xml文档
            root = tree.getroot()  # 获得root节点
            for child in root:
                if child.tag == 'connection':
                    for hub in child:
                        enabled = hub.get('enabled').lower().strip(
                        ) if hub.get('enabled') is not None else 'true'
                        if enabled == 'true' or enabled == '1':
                            self.__hubDict[
                                hub.attrib['browser']] = hub.text.strip()
                elif child.tag == 'scene':
                    for tc in child:
                        enabled = tc.get('enabled').lower().strip() if tc.get(
                            'enabled') is not None else 'true'
                        if enabled == 'true' or enabled == '1':
                            if 'paramPath' in tc.attrib.keys():
                                paramPath = tc.attrib['paramPath']
                                if ':' not in paramPath and self.isNoneOrEmpty(
                                        paramPath) == False:
                                    paramPath = paramPath[
                                        1:] if paramPath[:
                                                         1] == '/' or paramPath[:
                                                                                1] == '\\' else paramPath
                                    paramPath = '%s%s' % (EasyConfig().dataDir,
                                                          paramPath)
                            else:
                                paramPath = None
                            self.__testCaseList.append({
                                'paramPath':
                                paramPath,
                                'testCase':
                                tc.text.strip()
                            })
        except Exception:
            print("Error:测试用例配置文件加载失败:%s." % (self.__xmlPath))
            raise
Beispiel #16
0
 def run(self):
     logger = self.logger
     for x in range(int(EasyConfig().runTime)):
         try:
             putSystemLog('程序开始.', logger)
             putSystemLog('正在初始化....', logger)
             sTime = time()
             driver = self.getDriverObj()  # 获取一个浏览器驱动
             putSystemLog('%s浏览器启动成功.' % (driver.name), logger)
             putSystemLog('开始加载脚本...', logger)
             suite = self.suiteFactory(x, driver)  # 创建并配置测试单元套件
             putSystemLog('脚本加载完成...', logger)
             unittest.TextTestRunner().run(suite)
         except Exception as e:
             putSystemLog('程序运行过程中发生异常.', logger)
             putSystemLog(e, logger)
             raise
         finally:
             driver.quit()
             eTime = time()
             putSystemLog('程序结束,用时:%.3fs.' % (eTime - sTime), logger)
Beispiel #17
0
def sendLogToHTTP(_url, method='get', data=None, response=False):
	url = EasyConfig().requestURL if _url == '' else _url
	res_data = ""
	try:
		if 'GET' == method.upper():
			if data != None:
				fullUrl = url + '?' + urlencode(data)
			else:
				fullUrl = url
			res_data = urlopen(fullUrl)
		elif 'POST' == method.upper():
			res_data = urlopen(url, urlencode(data).encode(encoding='UTF8'))
		else:
			print('error:请求类型错误!')

		if response:
			return res_data
		else:
			return True
	except Exception as  e:
		# print('ERROR:发送请求失败,url:'+url)
		print(e)
Beispiel #18
0
def writeLog(data, driver):
	if data['image'] == '' or data['image'] == None:
		image = ''
	else:
		image = '截图:' + basename(data['image'])

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

	if int(data['level']) <= int(EasyConfig().logLevel):
		driver.logger.info(txt)
Beispiel #19
0
	def initConfig(self):
		self.implicitly_wait(EasyConfig().implicitlyWait)  # 查找元素等待30秒
Beispiel #20
0
 def createLoggerObj(self):
     if EasyConfig().isWriteLog:
         # 创建日志对象
         logDir = createDir(EasyConfig().logDir)  # 创建日志目录
         logPath = os.path.join(logDir, getLogName())  # 日志绝对路径
         self.logger = createLog(logPath)  # 日志对象
Beispiel #21
0
 def getEasyTestConfigSingletonObj(self):
     return EasyConfig()
Beispiel #22
0
 def setUp(self):
     putSystemLog('开始运行脚本%s' % (str(self.__class__)), self._driver.logger)
     if EasyConfig().maxWindow:
         self._driver.maximize_window()
Beispiel #23
0
 def createScreenShotDir(self):
     if EasyConfig().isScreenShot:
         screenShotDir = createDir(EasyConfig().screenShotDir)  # 创建截图目录
         self.screenShotDir = screenShotDir
Beispiel #24
0
def putSystemLog(data,logger):
	if EasyConfig().isWriteLog:
		logger.info(data)
Beispiel #25
0
	def __init__(self,projectPath,configXmlPath=None):
		super(ConfigFactory, self).__init__(projectPath,configXmlPath)
		self.testPlanList=[] #测试方案列表
		self.loadConfigFile()
		self.xmlDir=EasyConfig().xmlDir #测试方案配置文件目录
		self.templateList=self.getTemplatePathList(projectPath)