py+webdriver学习之旅9:错误截图+测试报告
__author__ = 'Administrator' #coding=gbk from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoAlertPresentException import unittest, time, re import HTMLTestRunner class Py1(unittest.TestCase): #初始化部分,在测试用例执行前,这个方法中的函数将先被调用。这里将浏览器的调用和 URL 的访问放到初始化部分 def setUp(self): self.driver = webdriver.Firefox() self.driver.implicitly_wait(30) self.base_url = "www.baidu.com" #脚本运行时,错误信息被打印到该列表 self.verificationErrors = [] self.accept_next_alert = True def test_py1(self): driver = self.driver driver.get(self.base_url) driver.find_element_by_name("tj_login").click() driver.find_element_by_name("userName").send_keys("xxx") driver.find_element_by_name("password").send_keys("xxx") try: #kw是一个无法找到的元素id driver.find_element_by_id("kw").send_keys("test") except: driver.get_screenshot_as_file("D:\\test.png") #该函数查找页面元素是否存在 def is_element_present(self, how, what): try: self.driver.find_element(by=how, value=what) except NoSuchElementException, e: return False return True #对弹窗异常的处理 def is_alert_present(self): try: self.driver.switch_to_alert() except NoAlertPresentException, e: return False return True #关闭警告和对得到文本框的处理,如果不熟悉 python 的异常处理和 if 语句的话,请去补基础知识,这里不多解释。 def close_alert_and_get_its_text(self): try: alert = self.driver.switch_to_alert() alert_text = alert.text if self.accept_next_alert: alert.accept() else: alert.dismiss() return alert_text finally: self.accept_next_alert = True def tearDown(self): self.driver.quit() self.assertEqual([], self.verificationErrors) #定义测试集 def suite(self): suite=unittest.TestSuite() suite.addTest(Py1("test_py1")) #进行测试 if __name__ == "__main__": #定义个报告存放路径,支持相对路径。 filename = 'D:\\result.html' fp = file(filename, 'wb') runner =HTMLTestRunner.HTMLTestRunner( stream=fp, title='Report_title', description='Report_description') #自动进行测试 runner.run(suite)