class ExcelManager(): def __init__(self, excelfilename): self.excelfilename = excelfilename fc = FileChecK() boolean = fc.is_has_file(excelfilename) if boolean: self.excel_path = fc.get_fileabspath() self.logger = LogObj() def readexcel(self, excel_sheet_name): #打开目标excel文件 r--读,w--写(覆盖),a--追加写 xlsdata = xlrd.open_workbook(self.excel_path, "rb") table = xlsdata.sheet_by_name(excel_sheet_name) #打开sheet页 self.logger.debug("打开的%s文件中的sheet页" % (self.excelfilename)) return table # 将指定的sheet页对象返回给调用者 ############################################################# def writexcel(self, row, column, value): xdata = xlrd.open_workbook(self.excel_path, "rb") #只能是xls文件 copy_Sheet = copy(xdata) #copy,并对附件进行操作 writeXLS = copy_Sheet.get_sheet(0) #得到附件中的sheet页 writeXLS.write(row, column, value) #将测试的结果追加到附件中sheet页中每一行的后面 copy_Sheet.save(self.excel_path) #覆盖保存(注意编码错误)
def test_run_suite(): logger = LogObj() logger.debug("测试集test_run_suite执行了") html_obj = html_reporter() #调用html测试报告方法 suite = unittest.TestSuite() #调用套件自动执行容器 for key in lists_class: #将lists_class中的类通过加载器进行加载 suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(key)) #使用htmltestrunner生成html报告 tle = " LabDigitalPlatform By Python Design Testing By Author jayzhen" drp = " 基于Spring MVC的实验室数字化平台-自动化测试 V1.0版本 -自动化测试报告" runner = HTMLTestRunner.HTMLTestRunner(stream=html_obj,title=tle,description=drp) #批量执行容器中的测试用例 runner.run(suite)
class web_login(): def __init__(self): fc = FileChecK() boolean = fc.is_has_file("framework.ini") if boolean: rwb_ini_path = fc.get_fileabspath() conf = Config(rwb_ini_path) baseURL = conf.get("baseURL", "baseURL") self.driver = RunBrowser(baseURL) self.driverapi = WebdriverApi(self.driver) self.logger = LogObj() self.basecase = WebDriverDoBeforeTest() self.basecase.driver = self.driver ''' 1.登录身份类型设置后,通过两次的定位,如果有定位到错误弹框的元素,及登录的账号密码有问题 ''' def userType_login(self, user, passwd, typeNum): isSucceed = False self.driver.implicitly_wait(3) try: self.driver.find_element_by_xpath( "//input[@name='sf' and @value='%s']" % typeNum).click() self.driver.find_element_by_id("input_username").clear() self.driver.find_element_by_id("input_username").send_keys(user) self.driver.find_element_by_id("input_password").clear() self.driver.find_element_by_id("input_password").send_keys(passwd) self.driver.find_element(by.By.ID, "login_btn").click() self.driver.implicitly_wait(3) try: errorbtn = self.driver.find_element_by_class_name( "layui-layer-btn0") boolean = errorbtn.is_displayed() if boolean: errotcontent = self.driver.find_element_by_class_name( "layui-layer-content").text self.basecase.capture(errotcontent) self.logger.debug(errotcontent) isSucceed = True errorbtn.click() except Exception, e: self.logger.debug("未定位到layui-layer-btn0元素,证明登陆的账号密码没有问题") try: webelenment = self.driver.find_element_by_xpath( "//a[@href='logout']").is_displayed() if webelenment: isSucceed = True self.logger.debug("定位到logout元素,证明实验员成功登录该平台") except Exception, e: self.logger.debug("未定位到logout元素,证明没有登录成功")
def html_reporter(): logger = LogObj() fc = FileChecK() pro_path = fc.getProjectPath() boolean = fc.is_has_file("framework.ini") if boolean: inipath = fc.get_fileabspath() fw_conf = Config(inipath) htmlrp_path = fw_conf.get("htmlreportPath", "htmlreportPath") htmreportl_abs_path = os.path.join(pro_path,htmlrp_path) timecurrent = DateTimeManager().formatedTime("%Y-%m-%d-%H-%M-%S") logger.debug("=====创建了一个html文件报告,路径是::"+htmreportl_abs_path) if not os.path.exists(htmreportl_abs_path): os.makedirs(htmreportl_abs_path) file_path = str(htmreportl_abs_path)+timecurrent+"-LDP-TestingRreporter.html" try: if os.path.exists(file_path): html_obj = open(file_path,"a") #打开文件 追加 return html_obj else: html_obj = file(file_path,"wb+") return html_obj except Exception,e: logger.error("创建html_reporter出现错误"+str(e))
class Emails(): def __init__(self): self.fc = FileChecK() bools = self.fc.is_has_file("email.ini") if bools: fp = self.fc.get_fileabspath() conf = Config(fp) self.smtp_host = conf.get("emails", "smtp_host") self.pop3_host = conf.get("emails", "pop3_host") self.receiver = conf.get("emails", "receiver").split(",") self.receiver_pa = conf.get("emails", "receiver_pa") self.sender = conf.get("emails", "sender") self.sender_pa = conf.get("emails", "sender_pa") self.logger = LogObj() def SendEmail_IsHTML(self): latestfpath, fname, currentfolder = self.fc.get_LatestFile() msgRoot = MIMEMultipart('related') ff = open(latestfpath, 'rb') message = MIMEText(ff.read(), 'html', 'utf-8') ff.close() message['From'] = self.sender #message['To'] = self.receiver subject = '实验室数字化平台-自动化测试报告' message['Subject'] = Header(subject, 'utf-8') msgRoot.attach(message) try: smtpObj = smtplib.SMTP() smtpObj.connect(self.smtp_host) smtpObj.login(self.sender, self.sender_pa) smtpObj.sendmail(self.sender, self.receiver, msgRoot.as_string()) self.logger.debug("SendEmail_withFile邮件发送成功") smtpObj.close() except Exception, e: print e self.logger.error("Error: 无法发送邮件::" + str(e))
class InitBrowser(): ''' configbrowser本身的self对象去调用其他的类方法 ''' def __init__(self): self.__GBD = GetBrowserDriver() self.__logger = LogObj() self.driver = None fc = FileChecK() boolean = fc.is_has_file("framework.ini") if boolean: self.inipath = fc.get_fileabspath() self.fw_conf = Config(self.inipath) self.waitTimeout = self.fw_conf.get("TimeSet", "waitTimeout") self.scriptTimeout = self.fw_conf.get("TimeSet", "scriptTimeout") self.pageLoadTimeout = self.fw_conf.get("TimeSet", "pageLoadTimeout") def beforeTestInitBrowser(self, browsername, baseURL): if "chrome" == browsername: self.startChromeDriver(baseURL) elif "ie" == browsername: self.startInternetExplorerDriver(baseURL) elif "firefox" == browsername: self.startFirefoxDriver(baseURL) else: self.startFirefoxDriver(baseURL) def startFirefoxDriver(self, baseURL): try: firefoxdriver = self.__GBD.get_FirefoxDrvier() os.environ["webdriver.firefox.bin"] = firefoxdriver self.driver = webdriver.Firefox() self.driver.set_page_load_timeout(self.pageLoadTimeout) self.__logger.debug("set pageLoadTimeout : " + self.pageLoadTimeout) self.driver.implicitly_wait(self.waitTimeout) self.__logger.debug("set waitTimeout : " + self.waitTimeout) self.driver.set_script_timeout(self.scriptTimeout) self.__logger.debug("set scriptTimeout : " + self.scriptTimeout) self.__logger.info("初始化火狐浏览器成功") self.driver.maximize_window() self.get(baseURL, 3) except Exception, e: self.__logger.error("getFirefoxDriver()方法发生异常,异常信息:" + e)
class Execute_SQL(): def __init__(self): self.logger = LogObj() self.fc = FileChecK() boolean = self.fc.is_has_file("db.ini") if boolean: self.inipath = self.fc.get_fileabspath() self.conf = Config(self.inipath) self.host = str(self.conf.get("dbset", "host")) self.port = int(self.conf.get("dbset", "port")) self.user = str(self.conf.get("dbset", "user")) self.passwd = str(self.conf.get("dbset", "passwd")) self.db = str(self.conf.get("dbset", "db")) self.charset = str(self.conf.get("dbset", "charset")) self.conn = MySQLdb.Connect(self.host, self.user, self.passwd, self.db, self.port, self.charset) self.logger.debug("数据库初始化完成" + self.host + str(self.port) + self.db + self.charset) def execute_select(self, sql): cursor = self.conn.cursor() try: cursor.execute(sql) self.logger.debug("check_acct_available :" + sql) res = cursor.fetchall() if len(res) < 1: self.logger.error("%s执行查询内容不存在" % sql) return res finally: cursor.close() return None def execute_addone(self, sql): cursor = self.conn.cursor() #操作数据库的游标 try: cursor.execute(sql) #执行sql语句 if cursor.rowcount == 1: self.logger.debug("%s添加成功" % sql) self.conn.commit() #执行成功后向数据库进行提交 return True except Exception, e: self.conn.rollback() self.logger.error("插入数据出现错误" + str(e)) finally:
class WebDriverDoBeforeTest(): def __init__(self): self.driver = None self.className = None self.beforeSuiteStarts = 0 self.afterSuiteStops = 0 self.beforeClassStarts = 0 self.afterClassStops = 0 self.beforeTestStarts = 0 self.afterTestStops = 0 fc = FileChecK() boolean = fc.is_has_file("framework.ini") if boolean: self.projectpath = fc.getProjectPath() self.fwInipath = fc.get_fileabspath() self.logger = LogObj() self.capturePath = os.path.join( self.projectpath, Config(self.fwInipath).get("capturePath", "capturePath")) def getDriverTooler(self, initbrowsername, baseURL): initbrowser = InitBrowser() initbrowser.beforeTestInitBrowser(initbrowsername, baseURL) self.driver = initbrowser.getWebDriver() return self.driver def beforeSuite(self): begins = DateTimeManager().formatedTime("%Y-%m-%d %H:%M:%S:%f") self.beforeSuiteStarts = time.time() self.logger.info("======" + begins + ":测试集开始======") def afterSuite(self): ends = DateTimeManager().formatedTime("%Y-%m-%d %H:%M:%S:%f") self.afterSuiteStops = time.time() self.logger.info("======" + ends + ":测试集结束======") self.logger.info("======本次测试集运行消耗时间 " + str(self.afterSuiteStops - self.beforeSuiteStarts) + " 秒!======") def beforeClass(self): begins = DateTimeManager().formatedTime("%Y-%m-%d %H:%M:%S:%f") self.beforeClassStarts = time.time() self.logger.info("======" + str(begins) + ":测试【" + str(self.className) + "】开始======") def afterClass(self): ends = DateTimeManager().formatedTime("%Y-%m-%d %H:%M:%S:%f") self.afterClassStops = time.time() self.logger.info("======" + str(ends) + ":测试【" + str(self.className) + "】结束======") self.logger.info("======本次测试运行消耗时间 " + str(self.afterClassStops - self.beforeClassStarts) + " 秒!======") def beforeTest(self, methodName): begins = DateTimeManager().formatedTime("%Y-%m-%d %H:%M:%S:%f") self.beforeTestStarts = time.time() self.logger.info("======" + begins + ":案例【" + str(self.className) + "." + methodName + "】开始======") def afterTest(self, methodName, isSucceed): ends = DateTimeManager().formatedTime("%Y-%m-%d %H:%M:%S:%f") captureName = "" if (isSucceed): self.logger.info("案例 【" + str(self.className) + "." + methodName + "】 运行通过!") else: dateTime = DateTimeManager().formatedTime("-%Y%m%d-%H%M%S%f") captureName = self.capturePath + str( self.className) + "." + methodName + str(dateTime) + ".png" self.captureScreenshot(captureName) self.logger.error("案例 【" + str(self.className) + "." + methodName + "】 运行失败,请查看截图快照:" + captureName) self.logger.info("======" + ends + ":案例【" + str(self.className) + "." + methodName + "】结束======") afterTestStops = time.time() self.logger.info("======本次案例运行消耗时间 " + str(afterTestStops - self.beforeTestStarts) + " 秒!======") return captureName ''' * 截取屏幕截图并保存到指定路径 * @param name:保存屏幕截图名称 * @return 无 ''' def capture(self, name): time.sleep(3) dateTime = DateTimeManager().formatedTime("-%Y%m%d-%H%M%S-%f") captureName = self.capturePath + name + dateTime + ".png" self.captureScreenshot(captureName) self.logger.debug("请查看截图快照:" + captureName) ''' * 截取屏幕截图并保存到指定路径 * @param filepath:保存屏幕截图完整文件名称及路径 * @return 无 ''' def captureScreenshot(self, filepath): try: self.driver.get_screenshot_as_file(filepath) except Exception, e: self.logger.error("保存屏幕截图失败,失败信息:" + str(e))
class LaboratoryManagement(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) self.wd = WebDriverDoBeforeTest() self.wd.className = "LaboratoryManagement" self.wd.beforeClass() self.logger = LogObj() self.weblogin = web_login() self.weblogin.back_LoginPage(3) self.driver = self.weblogin.driver self.driverapi = WebdriverApi(self.driver) self.em = ExcelManager("UsersLogin.xls") def tearDown(self): unittest.TestCase.tearDown(self) self.driver.close() self.wd.afterClass() def test_LaboratoryManagement(self): '''实验员管理测试用例''' self.logger.info( "LaboratoryManagement.test_LaboratoryManagement测试用例已执行") api = self.driverapi loginlab = self.weblogin tes_xls_data = self.em.readexcel("users") nrows = tes_xls_data.nrows for i in range(1, nrows): typeNum = tes_xls_data.cell(i, 2).value if typeNum == '2': user = tes_xls_data.cell(i, 0).value passwd = tes_xls_data.cell(i, 1).value print "实验室管理员账号密码及类型", user, passwd, typeNum b = loginlab.userType_login(user, passwd, typeNum) if b: api.click(By.XPATH, "//a[@href='lab_tech']") api.click(By.ID, "ref_but") api.click(By.ID, "add_lab_tech_but") num = random.randint(1, 20) newname = "jayzhen" + str(num) api.sendKeys(By.ID, "lab_tech_name_text", newname) newemail = "*****@*****.**" api.sendKeys(By.ID, "lab_tech_email_text", newemail) newqq = str(random.randint(111111, 999999999)) api.sendKeys(By.ID, "lab_tech_qq_text", newqq) newphone = str(random.randint(18311111111, 18399999999)) api.sendKeys(By.ID, "lab_tech_phone_text", newphone) api.webList_RandomSelectByOption(By.ID, "lab_id", 3) api.click(By.ID, "save_lab_tech_but") bb = api.is_Displayed(By.CLASS_NAME, "layui-layer-btn0") if bb: errorcont = api.getText(By.CLASS_NAME, "layui-layer-btn0") self.logger.debug("填完新增实验员的内容后,点击确定,提示:%s" % errorcont) api.click(By.CLASS_NAME, "layui-layer-btn0") api.click(By.CLASS_NAME, "close") print "实验室管理测试用例通过"
class ApplyLab(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) self.wd = WebDriverDoBeforeTest() self.wd.className ="ApplyLab" self.wd.beforeClass() self.logger = LogObj() self.weblogin = web_login() self.weblogin.back_LoginPage(3) self.driver = self.weblogin.driver self.driverapi = WebdriverApi(self.driver) self.em = ExcelManager("UsersLogin.xls") def tearDown(self): unittest.TestCase.tearDown(self) self.driver.close() self.wd.afterClass() def test_ApplyLab(self): '''教师申请实验室用例''' self.logger.info("ApplyLab.test_ApplyLab测试用例已执行") api = self.driverapi loginlab = self.weblogin tes_xls_data = self.em.readexcel("users") nrows = tes_xls_data.nrows for i in range(1,nrows): typeNum = tes_xls_data.cell(i,2).value if typeNum == '3': user = tes_xls_data.cell(i,0).value passwd = tes_xls_data.cell(i,1).value print "实验室管理员账号密码及类型",user, passwd, typeNum b = loginlab.userType_login(user, passwd, typeNum) if b: api.click(By.XPATH, "//a[@href='apply']") api.webList_RandomSelectByOption(By.ID,"year_id", 2) api.webList_RandomSelectByOption(By.ID,"lab_id", 2) api.webList_RandomSelectByOption(By.ID,"class_id", 2) api.webList_RandomSelectByOption(By.ID,"course_id", 2) bb = True while bb : begin = random.randint(1,68) api.sendKeys(By.ID, "ksjc", str(begin)) end = random.randint(begin+1,begin+3) api.sendKeys(By.ID, "jsjc", str(end)) show = api.getText(By.ID, "ErrorInfo") ebtn = api.is_Displayed(By.CLASS_NAME, "layui-layer-btn0") if ebtn: api.click(By.CLASS_NAME, "layui-layer-btn0") continue if show.strip()=="": bb = False print "执行选择周次" beginWeek = random.randint(1,4) api.selectByValue(By.ID,"kszc",str(beginWeek), 5) endWeek = random.randint(beginWeek+1,beginWeek+5) print "结束周次是:%s"%endWeek api.selectByValue(By.ID,"jszc",str(endWeek), 5) self.logger.debug("课时选择提示:%s"%show) api.click(By.ID, "check_but") show2 = api.getText(By.ID, "ErrorInfo") if "可申请,请点击右侧申请按钮进行申请" == show2: api.click(By.ID, "apply_but") api.click(By.CLASS_NAME, "layui-layer-btn0") result = api.getText(By.CLASS_NAME,"layui-layer-content") self.logger.debug("申请实验室的结果:%s" %result) api.click(By.CLASS_NAME, "layui-layer-btn0") print "申请实验室测试用例通过"
class PersonalCenter(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) self.wd = WebDriverDoBeforeTest() self.wd.className = "PersonalCenter" self.wd.beforeClass() self.logger = LogObj() self.weblogin = web_login() self.weblogin.back_LoginPage(3) self.driver = self.weblogin.driver self.driverapi = WebdriverApi(self.driver) self.em = ExcelManager("UsersLogin.xls") def tearDown(self): unittest.TestCase.tearDown(self) self.driver.close() self.wd.afterClass() def test_tester_Personal_Center(self): '''实验员个人中心测试用例''' self.logger.info( "test_PersonalCenter.test_tester_Personal_Center测试用例已执行") api = self.driverapi loginlab = self.weblogin tes_xls_data = self.em.readexcel("users") nrows = tes_xls_data.nrows for i in range(1, nrows): #for循环式,默认从0--n-1 typeNum = tes_xls_data.cell(i, 2).value if typeNum == '1': user = tes_xls_data.cell(i, 0).value passwd = tes_xls_data.cell(i, 1).value print "实验室实验员账号密码及类型", user, passwd, typeNum b = loginlab.userType_login(user, passwd, typeNum) if b: api.click(By.XPATH, "//a[@href='myinfo']") api.click(By.ID, "ref_but") api.click(By.ID, "update_myinfo_but") oldname = api.getText(By.ID, "show_name") #api.sendKeys(By.ID, "input_name_text", oldname) oldemail = api.getText(By.ID, "show_email") #api.sendKeys(By.ID, "input_email_text",oldemail ) newQQ = "1157757910" api.sendKeys(By.ID, "input_tencentno_text", newQQ) newPhone = "18511403089" api.sendKeys(By.ID, "input_phone_text", newPhone) bb = api.isSelected(By.ID, "is_change_pw") if bb is False: api.scrollbar_SlideTOBottom('main_table_left_box') api.click(By.ID, "is_change_pw") newPW = "123456" api.sendKeys(By.ID, "input_pw_text", newPW) api.click(By.ID, "go_update_myinfo_but") api.accept_alert() loginlab.back_LoginPage(2) self.logger.debug( "个人中心信息修改为:%s::%s::%s::%s::%s" % (oldname, oldemail, newQQ, newPhone, newPW)) print "个人中心信息修改测试用例通过"