def login(self, browser, user='******'): driver = DriverMethods(browser) app.config.from_object(user_conf[user]) USERNAME = app.config['USERNAME'] PASSWORD = app.config['PASSWORD'] try: driver.clear('登录页面', '用户名输入框') driver.send('登录页面', '用户名输入框', USERNAME) driver.clear('登录页面', '密码输入框') driver.send('登录页面', '密码输入框', PASSWORD) driver.click('登录页面', '登录按钮') '''driver.find_element_by_id("txtName").clear() driver.find_element_by_id("txtName").send_keys(USERNAME) driver.find_element_by_id("txtPwd").clear() driver.find_element_by_id("txtPwd").send_keys(PASSWORD) driver.find_element_by_id("btnLogin").click()''' except Exception as e: Log.writeLogError(self.logName, "funcname: login" + e.__str__()) WebDriverTools.get_pic(driver, 'func_login') #WebDriverTools.waitSpinner(driver, '登陆页面', 'spinner', timeout=23) time.sleep(3) ele = False try: ele = driver.display("Beop首页", 'logo') except: pass if ele: print("用户%s登陆成功" % app.config['USERNAME']) else: WebDriverTools.get_pic(driver, 'func_login') assert 0,"用户%s 密码%s登陆失败,请检查账号密码是否正确!" % (USERNAME, PASSWORD) return browser
def InitialFirefox(self, url, case): profileDir = r"C:\Users\woody\AppData\Roaming\Mozilla\Firefox\Profiles\e34lhn08.default" ff_profile = webdriver.FirefoxProfile(profileDir) driver = None try: driver = webdriver.Firefox(firefox_profile=ff_profile) driver.get(url) driver.implicitly_wait(8) except Exception: driver.close() driver = None time.sleep(5) try: driver.maximize_window() except Exception as e: Log.writeLogError(self.logName, "funcname: InitialFirefox" + e.__str__()) if driver: try: driver.maximize_window() except Exception as e: Log.writeLogError(self.logName, "funcname: InitialFirefox" + e.__str__()) if driver: WebDriverTools.get_pic(driver, case) time.sleep(5) return driver else: assert 0, "用例" + case + "执行失败!"
def switchWindow(self, driver, now_handle, window_handles): try: for handle in window_handles: if handle != now_handle: driver.switch_to_window(handle) except Exception as e: Log.writeLogError(self.logName, 'funcName: switchWindow error: %s' % e.__str__())
def delMemTime(self, keys): rt = False try: mc = memcache.Client(self.hostlist, debug=0) rt = mc.delete_multi(keys) except Exception as e: Log.writeLogError(self.logName, e.__str__()) return rt
def setMemTime(self, key, value, time=0): rt = False try: mc = memcache.Client(self.hostlist, debug=0) rt = mc.set(key, value, time=time) except Exception as e: Log.writeLogError(self.logName, e.__str__()) return rt
def Go(self, threadNumber): runCase.killBrowser() self.suffix = "通过" print("自动化测试任务开始!") begin = time.time() startTime = time.strftime('%Y-%m-%d %H:%M:%S') pool =threadpool.ThreadPool(threadNumber) requests = threadpool.makeRequests(self.suite,args_list=self.all_case) [pool.putRequest(req) for req in requests] pool.wait() Result2 = sorted(self.Result2) result3 = [] for y in range(0,len(Result2)): result3.append(self.ReportResultAll[Result2[y]]) final_result = [] for x in result3: if x not in final_result: final_result.append(x) else: pass env = Environment(loader=PackageLoader(__name__, 'templates',encoding='utf-8')) template = env.get_template('template.html') resultHTML = template.render(reportStruct=final_result) nowtime = time.strftime("%Y-%m-%d %H.%M.%S", time.localtime()) with open('%s\TestReport\自动化测试报告%s.html' % (self.reportPath, nowtime) ,'wb') as file: file.write(resultHTML.encode()) if self.Failed: suffix = '未通过,失败%d个/%d个' % (self.Failed, len(final_result)) else: suffix = '通过,%d个' % (len(final_result)) cost = (time.time() - begin) / 60 web = app.config['SERVER_LIST'] serverip = app.config['SERVERIP'] test_mails = app.config.get('TEST_GROUP_EMAILS') public_mails = app.config.get('PUBLIC_EMAILS') while True: try: if web[app.config['SERVERIP']] == "国服": if app.config.get('CONDITION'): MailTools.send_mail(public_mails, web[serverip]+'-回归测试 '+'('+suffix+') '+startTime+' 历时'+str(int(cost))+'分钟', cost, resultHTML) break else: MailTools.send_mail(test_mails, web[serverip]+'-回归测试 '+'('+suffix+') '+startTime+' 历时'+str(int(cost))+'分钟', cost, resultHTML) break else: print("Test server is not beop.rnbtech.com.hk") MailTools.send_mail(test_mails, web[serverip]+'-回归测试 '+'('+suffix+') '+startTime+' 历时'+str(int(cost))+'分钟', cost, resultHTML) break except Exception as e: Log.writeLogError(self.logName, e.__str__()) break self.Failed = 0 self.ReportResultAll = {} self.Result2 = [] self.failCase = []
def wrapper(*args, **kw): error = '' for i in range(0, N): try: return func(*args, **kw) except Exception as e: error = e.__str__() Log.writeLogError(app.config['CSS_ERROR'], func.__name__ + e.__str__()) raise Exception("%s函数出错!详情: %s" % (func.__name__, error))
def getMemTime(self, key): rt = None try: mc = memcache.Client(self.hostlist, debug=0) rt = mc.get(key) except Exception as e: print(e.__str__()) Log.writeLogError(self.logName, e.__str__()) return rt
def click_image(self, driver): try: # e元素为第一个图的标题,默认为untitled e = driver.find_element_by_css_selector( "#divWSPane>div>h4.divPageTitle") # 将鼠标移动到e元素上方30px的地方并点击,达到进入该图表的功能 ActionChains(driver).move_to_element_with_offset( e, 0, 30).click().perform() except Exception as e: Log.writeLogError(self.logName, 'funcName: click_image error: %s' % e.__str__())
def clickEle(self, driver, css, testCaseID, projectName, page, errors=[]): try: WebDriverWait(driver, 5).until( lambda x: x.find_element_by_css_selector(css).is_displayed()) driver.find_element_by_css_selector(css).click() except Exception as e: self.get_pic(driver, testCaseID) Log.writeLogError(self.logName, 'funcName: clickEle error: %s' % e.__str__()) errors.append('CaseID: %s, error: 点击%s项目-%s元素失败! details: %s' % (testCaseID, projectName, page, e.__str__()))
def getExcelFile(self, page): try: data = open_workbook( os.path.join(app.config['CSS_PAGE'], page + '.xlsx')) #选取sheet1 sheet = data.sheet_by_index(0) if sheet.nrows > 1: return [sheet.row_values(i) for i in range(1, sheet.nrows)] except Exception as e: Log.writeLogError(self.logName, 'funcname: getExcelFile error: %s' % e.__str__()) return [] return []
def waitElementNotFound(self, driver, ele, caseID, timeout=15): try: WebDriverWait(driver, timeout).until_not( lambda x: x.find_element_by_css_selector(ele)) except Exception as e: self.get_pic(driver, caseID) Log.writeLogError( self.logName, 'funcname: waitElementNotFound error: timeout for wait element disappear %s' % ele) raise Exception( 'funcname: waitElementNotFound error: timeout for wait element disappear %s' % ele)
def loginnow(self, driver): try: driver.find_element_by_id("txtName").clear() driver.find_element_by_id("txtName").send_keys(username) driver.find_element_by_id("txtPwd").clear() driver.find_element_by_id("txtPwd").send_keys(password) driver.find_element_by_id("btnLogin").click() # Calculate time for login WebDriverTools.waitSpinner(driver, 'Beop首页', 'spinner') time.sleep(2) return driver except Exception as e: Log.writeLogError(self.logName, e.__str__()) driver.quit()
def isElementsPresent(self, driver, ele): a = False try: eles = driver.find_elements_by_css_selector(ele) if eles: a = True except NoSuchElementException as e: driver.get_screenshot_as_file( r'.\ErrorPicture\%s.png' % time.strftime("%Y-%m-%d %H-%M-%S", time.localtime())) Log.writeLogError( self.logName, 'funcName: IsElementsPresent error: %s' % e.__str__()) return a
def getBrowserVersion(self, browser): driver = None try: driver = eval('webdriver.{}()'.format(browser)) version = driver.execute_script('return navigator.userAgent') version = [x for x in version.split(" ") if browser in x][0].replace('/', " ") app.config['BROWSER_VERSION'].append(version) except Exception as e: Log.writeLogError( self.logName, 'funcName: getBrowserVersion error: open %s failed. %s' % (browser, e.__str__())) finally: if driver: driver.quit()
def loginPatrol(self, driver, url, user='******'): app.config.from_object(user_conf[user]) try: driver.find_element_by_id("txtName").clear() driver.find_element_by_id("txtName").send_keys(app.config['USERNAME']) driver.find_element_by_id("txtPwd").clear() driver.find_element_by_id("txtPwd").send_keys(app.config['PASSWORD']) driver.find_element_by_id("btnLogin").click() except Exception as e: Log.writeLogError(self.logName, e.__str__()) WebDriverTools.get_pic(driver, 'func_loginPatrol') WebDriverTools.waitSpinner(driver, '登陆页面', 'spinner') time.sleep(2) driver.get(url+"/patrol?projectId=72") time.sleep(15) return driver
def waitSpinner(self, driver, page, name='spinnerMask', timeout=23, implicit=8, mode=0): try: use = self.findSpinner(driver, name, timeout, mode, implicit, page) print("进入%s 消耗时间: %.2f秒" % (page, use)) return use except Exception as e: Log.writeLogError(self.logName, 'funcName: waitSpinner error: %s' % e.__str__()) self.get_pic(driver, 'spinner') assert 0, "进入" + page + e.__str__()
def get_pic(self, driver, testCaseID=None): '截图函数,传入CaseID以及driver即可' try: if testCaseID: dirName = os.path.join(self.path, 'ErrorPicture\%s' % testCaseID) else: dirName = os.path.join(self.path, 'ErrorPicture') if not os.path.exists(dirName): os.mkdir(dirName) driver.get_screenshot_as_file( r'%s\%s.png' % (dirName, time.strftime("%Y-%m-%d %H-%M-%S", time.localtime()))) except Exception as e: Log.writeLogError(self.logName, 'funcName: get_pic error: %s' % e.__str__())
def InitialChrome2(self, url, case): url = 'http://' + app.config['SERVERIP'] driver = None if self.browser: print('用例: {}指定浏览器为{}'.format(case, self.browser)) driverStr = 'webdriver.{}()'.format(self.browser) else: print('用例: {}未指定浏览器,默认为Chrome'.format(case)) driverStr = 'webdriver.Chrome()' try: driver = eval(driverStr) self.base_url = url except Exception as e: Log.writeLogError(self.logName, 'webdriver.Chrome() error:' + e.__str__()) if driver: try: WebDriverTools.get_pic(driver, case) driver.close() driver = None except Exception as e: Log.writeLogError(self.logName, 'funcname: InitialChrome' + e.__str__()) if driver: try: driver.get(self.base_url) driver.implicitly_wait(8) driver.maximize_window() except Exception as e: Log.writeLogError(self.logName, 'funcname: InitialChrome' + e.__str__()) if driver: WebDriverTools.get_pic(driver, case) time.sleep(3) return driver else: assert 0, "用例" + case + "执行失败!"
def loginInitial_Chrome(self, case): if self.browser: print('用例: {}指定浏览器为{}'.format(case, self.browser)) driverStr = 'webdriver.{}()'.format(self.browser) else: print('用例: {}未指定浏览器,默认为Chrome'.format(case)) driverStr = 'webdriver.Chrome()' driver = None url = 'http://' + app.config['SERVERIP'] try: driver = eval(driverStr) driver.get(url) except Exception as e: Log.writeLogError(self.logName, "funcname: loginInitial_Chrome" + e.__str__()) if driver: WebDriverTools.get_pic(driver, 'func_loginInitial_Chrome') driver.close() driver = None if driver: try: driver.implicitly_wait(8) driver.maximize_window() except Exception as e: Log.writeLogError(self.logName, case + '---' + e.__str__()) WebDriverTools.get_pic(driver, 'func_loginInitial_Chrome') driverwait = WebDriverWait(driver, 35) time.sleep(5) try: #等待页面加载完成 driverwait.until(lambda dr: dr.find_element_by_css_selector("#indexMain").is_displayed()) except Exception: WebDriverTools.get_pic(driver, 'func_loginInitial_Chrome') assert 0,"打开beop,等待35秒后还没找到登陆窗口!" time.sleep(3) return driver else: assert 0, "用例" + case + "执行失败!"
def InitialChromeFactory(self, url, case): driver = None if self.browser: print('用例: {}指定浏览器为{}'.format(case, self.browser)) driverStr = 'webdriver.{}()'.format(self.browser) else: print('用例: {}未指定浏览器,默认为Chrome'.format(case)) driverStr = 'webdriver.Chrome()' try: driver = eval(driverStr) base_url = url + "/factory" driver.get(base_url) except Exception as e: Log.writeLogError(self.logName, 'funcname: InitialChromeFactory' + e.__str__()) if driver: try: WebDriverTools.get_pic(driver, case) driver.close() except Exception as e: Log.writeLogError(self.logName, 'funcname: InitialChromeFactory' + e.__str__()) if driver: try: driver.maximize_window() driver.implicitly_wait(8) except Exception as e: Log.writeLogError(self.logName, 'funcname: InitialChromeFactory' + e.__str__()) WebDriverTools.get_pic(driver, case) time.sleep(5) driverwait = WebDriverWait(driver, 35) time.sleep(5) #等待页面加载完成 try: driverwait.until(lambda dr: dr.find_element_by_css_selector("#login").is_displayed()) time.sleep(3) except Exception as e: assert 0,"连接%s后登陆按钮35秒内没有加载出来!" % self.base_url return driver else: assert 0, "用例" + case + "执行失败!"
def Go(self): self.suffix = "通过" ''' if app.config.get('CONDITION'): BeopTools.getInstance().delMemTime(app.config['ALL_CASE']) time.sleep(10) ''' self.killBrowser() print("自动化测试任务开始!") begin = time.time() startTime = time.strftime('%Y-%m-%d %H:%M:%S') threads = [] # # #创建3个线程 # t1 = threading.Thread(target=self.suite, args=('suite_a', self.suite_a)) # t2 = threading.Thread(target=self.suite, args=('suite_b', self.suite_b)) # t3 = threading.Thread(target=self.suite, args=('suite_c', self.suite_c)) # t4 = threading.Thread(target=self.suite, args=('suite_d', self.suite_d)) # #添加至线程池 # threads.append(t1) # threads.append(t2) # threads.append(t3) # threads.append(t4) # length = len(threads) # #开始线程并守护 # try: # for i in range(length): # threads[i].start() # for i in range(length): # threads[i].join() # except Exception as e: # print(e.__str__()) final_result, self.reportResultAll, resultHTML = self.report() nowtime = time.strftime("%Y-%m-%d %H.%M.%S", time.localtime()) with open('%s\TestReport\自动化测试报告%s.html' % (self.reportPath, nowtime), 'wb') as file: file.write(resultHTML.encode()) if self.Failed: suffix = '未通过,失败%d个/%d个' % (self.Failed, len(final_result)) else: suffix = '通过,%d个' % (len(final_result)) cost = (time.time() - begin) / 60 web = app.config['SERVER_LIST'] serverip = app.config['SERVERIP'] test_mails = app.config.get('TEST_GROUP_EMAILS') public_mails = app.config.get('PUBLIC_EMAILS') while True: try: if web[app.config['SERVERIP']] == "国服": if app.config.get('CONDITION'): #MailTools.send_mail(public_mails, web[serverip]+'-回归测试 '+'('+suffix+') '+startTime+' 历时'+str(int(cost))+'分钟', cost, resultHTML) pass break else: #MailTools.send_mail(test_mails, web[serverip]+'-回归测试 '+'('+suffix+') '+startTime+' 历时'+str(int(cost))+'分钟', cost, resultHTML) pass break else: print("Test server is not beop.rnbtech.com.hk") #MailTools.send_mail(test_mails, web[serverip]+'-回归测试 '+'('+suffix+') '+startTime+' 历时'+str(int(cost))+'分钟', cost, resultHTML) pass break except Exception as e: Log.writeLogError(self.logName, e.__str__()) continue self.Failed = 0 self.ReportResultAll = {} self.Result2 = [] self.failCase = []
runTime = app.config['RUNTIME'] threadNumber = app.config['THREADNUMBER'] for browser in app.config['BROWSER_LIST']: WebDriverTools.getBrowserVersion(browser) while 1: try: if datetime.datetime.now().hour in runTime: print("Run Go!") a = runCase() a.Go(threadNumber) print(datetime.datetime.now(),"Done! sleep 1 hour!") sleep(60*60) print(datetime.datetime.now(),"Have slept 1 hour,continue while!") continue else: print(datetime.datetime.now(),"sleep 60s") sleep(60) print(datetime.datetime.now(),"Have slept 60s ,continue while!") continue except Exception as e: Log.writeLogError(runCase.logName, e.__str__()) print(e.__str__()) break
def alert(self, driver): try: driver.switch_to_alert().accept() except Exception as e: Log.writeLogError(self.logName, 'funcName: alert error: %s' % e.__str__())