class SignIn(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) self.logger = LogObj() self.weblogin = web_login() self.weblogin.back_SigninPage() #返回到student 签到的页面 self.wd = WebDriverDoBeforeTest() self.wd.className = "studentSignin.Signin" self.wd.beforeClass() self.wd.driver = self.weblogin.driver self.webdriverpai = WebdriverApi(self.weblogin.driver) self.conn = Execute_SQL() def tearDown(self): unittest.TestCase.tearDown(self) self.wd.afterClass() self.weblogin.driver.close() self.conn.execute_conn_close() def test_student_singin(self): '''学生签到测试用例''' try: self.logger.info("SignIn.test_student_singin 测试用例已执行") api = self.webdriverpai sql = 'select * from test_lab;' res = self.conn.execute_select(sql) for i in res: #for循环式,默认从0--n-1 print "------ mysql testcase:", i row_A = i[0] row_B = i[1] row_C = i[2] api.webList_RandomSelectByOption(By.ID, "class_id", 3) api.webList_RandomSelectByOption(By.ID, "lab_id", 3) api.sendKeys(By.ID, "name", row_A) api.sendKeys(By.ID, "stuno", row_B) api.sendKeys(By.ID, "info", row_C) api.click(By.ID, "sign") b = api.is_Displayed(By.CLASS_NAME, "layui-layer-btn0") if b: capturename = api.getText(By.CLASS_NAME, "layui-layer-content") if "欢迎使用实验室数字化平台签到" != capturename: self.wd.capture(capturename) api.click(By.CLASS_NAME, "layui-layer-btn0") self.weblogin.back_SigninPage() #返回到student 签到的页面 print u"平台学生签到测试用例通过" except Exception, e: self.logger.error("SignIn.test_student_singin 测试用例出现异常" + str(e))
class SignIn(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) self.logger = LogObj() self.weblogin = web_login() self.weblogin.back_SigninPage() #返回到student 签到的页面 self.wd = WebDriverDoBeforeTest() self.wd.className ="studentSignin.Signin" self.wd.beforeClass() self.wd.driver = self.weblogin.driver self.webdriverpai = WebdriverApi(self.weblogin.driver) self.em = ExcelManager("UsersLogin.xls") def tearDown(self): unittest.TestCase.tearDown(self) self.wd.afterClass() self.weblogin.driver.close() def test_student_singin(self): '''学生签到测试用例''' try: self.logger.info("SignIn.test_student_singin 测试用例已执行") api = self.webdriverpai tes_xls_data = self.em.readexcel("students") #得到sheet页 nrows = tes_xls_data.nrows print "------ excel中的测试用例条数是:",nrows-1 #excel中 的数据行数从1行开始 for i in range(1,nrows): #for循环式,默认从0--n-1 print "------ 这是第:",i," 条用例" row_A = str(tes_xls_data.cell(i,0).value) row_B = str(tes_xls_data.cell(i,1).value) row_C = tes_xls_data.cell(i,2).value print row_A, row_B, row_C api.webList_RandomSelectByOption(By.ID, "class_id", 3) api.webList_RandomSelectByOption(By.ID, "lab_id", 3) api.sendKeys(By.ID, "name",row_A) api.sendKeys(By.ID, "stuno",row_B) api.sendKeys(By.ID, "info",row_C) api.click(By.ID, "sign") b = api.is_Displayed(By.CLASS_NAME,"layui-layer-btn0") if b: capturename = api.getText(By.CLASS_NAME, "layui-layer-content") if "欢迎使用实验室数字化平台签到" != capturename: self.wd.capture(capturename) api.click(By.CLASS_NAME,"layui-layer-btn0") self.weblogin.back_SigninPage() #返回到student 签到的页面 except Exception,e: self.logger.error("SignIn.test_student_singin 测试用例出现异常"+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 WebdriverApi(): def __init__(self, driver): fc = FileChecK() boolean = fc.is_has_file("framework.ini") if boolean: self.projectpath = fc.getProjectPath() self.fwInipath = fc.get_fileabspath() self.conf = Config(self.fwInipath) self.capturePath = os.path.join( self.projectpath, self.conf.get("capturePath", "capturePath")) self.pauseTime = self.conf.get("TimeSet", "pauseTime") self.logger = LogObj() self.driver = driver def pause(self, millisecond): try: time.sleep(millisecond) except Exception, e: self.logger.error("pause error:" + str(e))
class GetBrowserDriver(): def __init__(self): self.conf = ConfigParser.ConfigParser() self.__fileabspath = None self.__projectpath = None self.__logger = LogObj() fc = FileChecK() boolean = fc.is_has_file("driverpath.conf") if boolean: self.__fileabspath = fc.get_fileabspath() self.__projectpath = fc.getProjectPath() self.conf.read(self.__fileabspath) def get_IEDriver(self): try: # 获取指定的section, 指定的option的值 iedriverpath = self.conf.get("ie", "iedriver") iedriverabspath = os.path.join(self.__projectpath, iedriverpath) self.__logger.info("获取到IE Driver") return iedriverabspath except Exception, e: self.__logger.error("get_IEDriver()方法出现异常", e)
class FileChecK(): def __init__(self): self.__fileabspath = None #不可访问的 self.__logger = LogObj() ''' 是否存在指定的文件,路径默认为当前项目的目录 ''' def is_has_file(self, filename): propath = self.getProjectPath() boolean = self.is_path_has_file(propath, filename) return boolean ''' 指定目录下是否存在指定的文件 ''' def is_path_has_file(self, path, filename): boolean = self.check_has_file(path, filename) return boolean ''' 扫描指定目录下的所有文件,找到所要找的文件,return True or False ''' def check_has_file(self, path, filename): try: for filep, dirs, filelist in os.walk(path): for fl in filelist: if cmp(fl, filename) == 0: #这个字符串的比较存在风险,python3不支持,待修改 self.__fileabspath = os.path.join(filep, fl) self.__logger.info("查找的%s文件存在" % filename) return True return False except Exception, e: self.__logger.error("check_has_file()方法出现异常", e)
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 SignIn(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) self.wd = WebDriverDoBeforeTest() self.wd.className = "studentSignin.Signin" self.wd.beforeClass() self.logger = LogObj() self.weblogin = web_login() self.weblogin.back_SigninPage() #返回到student 签到的页面 self.webdriverpai = WebdriverApi(self.weblogin.driver) self.em = ExcelManager("UsersLogin.xls") def tearDown(self): unittest.TestCase.tearDown(self) self.wd.afterClass() self.weblogin.driver.close() def test_student_singin(self): try: self.logger.info("SignIn.test_student_singin 测试用例已执行") driver = self.weblogin.driver api = self.webdriverpai tes_xls_data = self.em.readexcel("students") #得到sheet页 nrows = tes_xls_data.nrows print "------ excel中的测试用例条数是:", nrows - 1 #excel中 的数据行数从1行开始 for i in range(1, nrows): #for循环式,默认从0--n-1 print "------ 这是第:", i, " 条用例" row_A = tes_xls_data.cell(i, 0).value row_B = tes_xls_data.cell(i, 1).value row_C = tes_xls_data.cell(i, 2).value print row_A, row_B, row_C clss = Select(driver.find_element_by_id("class_id")).options random.choice(clss).click() driver.implicitly_wait(2) lab = Select(driver.find_element_by_id("lab_id")).options random.choice(lab).click() driver.implicitly_wait(2) driver.find_element_by_id("name").clear() driver.find_element_by_id("name").send_keys(row_A) driver.implicitly_wait(2) driver.find_element_by_id("stuno").clear() driver.find_element_by_id("stuno").send_keys(row_B) driver.implicitly_wait(2) driver.find_element_by_id("info").clear() driver.find_element_by_id("info").send_keys(row_C) driver.implicitly_wait(2) driver.find_element_by_id("sign").click() b = driver.find_element_by_class_name( "layui-layer-btn0").is_displayed() if b: driver.find_element_by_class_name( "layui-layer-btn0").click() self.weblogin.back_SigninPage() #返回到student 签到的页面 except Exception, e: self.logger.error("SignIn.test_student_singin 测试用例出现异常" + str(e))
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))