selenium pyunit单元测试框架
#PyUnit框架
#coding = utf - 8
#将要被测试的类
class Widget:
def __int__(self,size = (40,40)):
self._size = size
def getSize(self):
return self._size
def resize(self,width,height):
if width<0 or height < 0:
raise ValueError,"illegal size"
self._size = (width,height)
def dispose(self):
pass
#auto.py 测试类
#coding = utf-8
from widget import Widget
import unittest
#执行测试的类
class WidgetTestCase(unittest.TestCase):
def setUp(self):
self.widget = Widget()
#测试getsize()方法的测试用例
def testSize(self):
self.assertEqual(self.widget.getSize(),(40,40))
#测试resize()方法的测试用例
def testResize(self):
self.widget.resize(100,100)
self.assertEqual(self.wiget.getSize(),(100,100))
def tearDown(self):
self.widget = None
#构造测试集
def suite():
suite = unittest.TestSuite()
suite.addTest(WidgetTestCase("testSize"))
return suite
实例:
#coding = utf-8
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
import unittest,time,re
class Baidu(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "https://www.baidu.com"
self.verificationErrors = []
self.accept_next_alert= True
#百度搜索用例
def test_baidu_search(self):
driver = self.driver
driver.get(self.base_url + "/")
driver.find_element_by_id("kw").send_keys("selenium webdriver")
driver.find_element_by_id("su").click()
time.sleep(2)
driver.close()
#百度设置用例
def test_baidu_set(self):
driver = self.driver
#进入搜索设置页面
driver.get(self.base_url + "/gaoji/preferences.html")
#设置每页搜索结果为100条
m = driver.find_element_by_name("NR")
m.find_element_by_xpath("//option[@value = '100']").click()
time.sleep(2)
#保存设置的信息
driver.find_element_by_xpath("//[@value = '保存设置']").click()
time.sleep(2)
driver.switch_to.alert().accept() #切换到alert弹窗;Python2用法:switch_to_alert();Python3用法:switch_to.alert()
#目前接触到的switch_to的用法包括以下几种:
driver.switch_to.window(window_name)#切换到制定的window_name页面
driver.switch_to.alert()#切换到alert弹窗
driver.switch_to.active_element()#切换到当前聚焦的元素上
driver.switch_to.default_content()#切换到最上层页面(主文档?)
driver.switch_to.frame(frame_reference)#通过id、name、element(定位的某个元素)、索引来切换到某个frame
driver.switch_to.parent_frame()#这是switch_to中独有的方法,可以切换到上一层的frame,对于层层嵌套的frame很有用
def tearDown(self):
self.driver.quit()
self.assertEqual([],self.verificationErrors)