數據驅動和關鍵字驅動簡單例子(登錄)
數據驅動:程序和數據分離,測試數據存入一個文件中,腳本存入另一個文件中
公司項目為保密項目,地址使用xxx代替
數據文件:D:\\test\\loginData.txt
文件內容:
admin_cyl||123456a
admin_test||a123456
test_shi||a123456
代碼:
#encoding=utf-8
import unittest
from selenium import webdriver
import time
class VisitClosePlaceByIe(unittest.TestCase):
def setUp(self):
#啟動Ie瀏覽器
self.driver = webdriver.Ie(executable_path = "D:\\IEDriverServer")
def test_visitURL(self):
with open("D:\\test\\loginData.txt") as fp:
for line in fp:
username,password = line.split("||")
password = password.strip().decode("gbk")
self.driver.get("xxx")
self.driver.find_element_by_id("username")
self.driver.find_element_by_id("username").send_keys(username)
self.driver.find_element_by_id("password")
self.driver.find_element_by_id("password").send_keys(password)
self.driver.find_element_by_id("button")
self.driver.find_element_by_id("button").click()
time.sleep(3) #不加等待時間,則page_source獲取的是登錄頁面的源代碼
assert u"封閉學校管理平台" in self.driver.page_source ,"Keyword not in page"
def tearDown(self):
self.driver.quit()
關鍵字驅動:將測試用例的執行步驟存放在文件中,每個步驟單獨封閉成一個函數,以這個函數名作為關鍵字,將函數名及傳參寫入文件中,第個步驟對應一行文件
數據文件:D:\\test\\schoolLogin.txt
文件內容:
visitUrl||["xxx"]
find_ele||["username","admin_cyl"]
find_ele||["password","123456a"]
click_login||["button"]
assert_word||[u"封閉學校管理平台"]
代碼:school_login.py
#encoding=utf-8
import unittest
from selenium import webdriver
import time
class VisitSchool(unittest.TestCase):
def setUp(self):
#啟動IE瀏覽器
self.driver = webdriver.Ie(executable_path="D:\\IEDriverServer")
def visitUrl(self,url):
#由於參數個數不一致,所以使用列表做為參數,再用eval將列表字符串轉化為列表
url = eval(url)
#打開網頁
self.driver.get(url[0])
def find_ele(self,arg):
arg = eval(arg)
#定位輸入框並輸入值
self.driver.find_element_by_id(arg[0]).send_keys(arg[1])
#本來想用兩個函數,一個定位,一個輸入值,但是輸入函數中無法使用定位,所以合並成一個函數
def click_login(self,id):
id = eval(id)
#定位按鈕並點擊
self.driver.find_element_by_id(id[0]).click()
def assert_word(self,keyword):
#等待3秒,以便頁面加載,否則page_source是登錄頁面的
time.sleep(3)
keyword = eval(keyword)
#斷言
assert keyword[0].strip() in self.driver.page_source, "Keyword not in page"
def test_schoolLogin(self):
with open("D:\\test\\schoolLogin.txt") as fp:
for line in fp:
action,data = line.split("||")
action = action.strip()
data = data.decode("gbk").strip()
#拼接執行命令
exec("self."+action+"(u'"+data+"')")
def tearDown(self):
self.driver.quit()
if __name__ == "__main__":
unittest.main()