輸入項 | 允許輸入 | 可為空 | 格式規(guī)范 | 合法性 | 依賴項 |
---|---|---|---|---|---|
原管理員密碼 | 是 | 否 | 字符串 | 長度限制:5-63; 字符集:英文字符集; | 需要與管理員密碼相同 |
新管理員密碼 | 是 | 否 | 字符串 | 長度限制:5-63; 字符集:英文字符集; | |
確認(rèn)管理員密碼 | 是 | 否 | 字符串 | 需要與新管理員密碼相同 |
根據(jù)防呆規(guī)則可以列出:1.可能出現(xiàn)的錯誤 2.出現(xiàn)錯誤時頁面應(yīng)有的提示語
#可能出現(xiàn)的錯誤 errcode = ['oldPwdErr', 'lenErr', 'charErr', 'matchErr', 'pwdSameErr',\ 'oldPwdBlankErr', 'newPwdBlankErr'] #出現(xiàn)錯誤時頁面應(yīng)有的提示語 errTips = { 'oldPwdErr' :'原密碼錯誤', 'lenErr' : '新密碼長度應(yīng)為5~63位', 'charErr' : "新密碼包含非法字符", 'matchErr' : '兩次密碼輸入不一致', 'pwdSameErr' : '新密碼與原密碼相同,請重新輸入', 'oldPwdBlankErr' : '請輸入原密碼', 'newPwdBlankErr' : '請輸入新密碼' }
需要輸入的數(shù)據(jù)為要檢查的data和登陸密碼
def checkData(data, loginPwd):#檢查順序跟頁面順序相同 pwd = loginPwd #'oldPwdBlankErr' if data['pwdOld'] == "": return errcode[5] #newPwdBlankErr if data['pwdNew'] == "": return errcode[6] #charErr strTmp = data['pwdNew'] for x in xrange(0,len(data['pwdNew'])): if ord(strTmp[x]) 33 or ord(strTmp[x]) > 127:#ASCII表示范圍:32-127 return errcode[2] #lenErr if len(data['pwdNew']) > 63 or len(data['pwdNew']) 5: return errcode[1] #oldPwdErr if pwd != loginData.login_data['login_pwd']: return errcode[0] #pwdSameErr if data['pwdNew'] == pwd: return errcode[4] #no error return None
def checkResponse(error): if error == None: return webText = getText('//*[@id="PwdTip"]') if webText == False:#沒有提示 print('###Error: no tips on web!') else: webText = webText.decode('UTF-8') waitandClick('//*[@id="ModifyPwd"]/i') time.sleep(1) return webText
data = [ {"pwdNew" : "12345678","pwdOld" : '8dadla'},#"oldPwdErr" {"pwdNew" : "admi","pwdOld" : 'admin'},#lenErr {'pwdNew' : '1 2 3','pwdOld' : 'admin'},#charErr {'pwdNew' : 'admin','pwdOld' : 'admin'},#pwdSameErr {'pwdNew' : "",'pwdOld' : ""},#oldPwdBlank {'pwdNew' : "",'pwdOld' : "admin"}#newPwdBlank ]
單元測試中,不同的部分應(yīng)該是數(shù)據(jù),所以可以定義一個通用的操作。
其中self.assertEqual(checkResponse(error), errTips[error])是判定測試是否通過的條件:頁面提示語是否正確。
def commonAction(self, arg): error = checkData(arg) changeUserPwd.main(arg) self.assertEqual(checkResponse(error), errTips[error])
測試類中主要包括了測試用例6個,和對應(yīng)的以“test”開頭的測試函數(shù)。
這里繼承了python的unittest。
關(guān)于unittest的語法請參考://www.jb51.net/article/65856.htm
class TestCase(unittest.TestCase): data = [ {"pwdNew" : "12345678","pwdOld" : '8dadla'},#"oldPwdErr" {"pwdNew" : "admi","pwdOld" : '*'},#lenErr {'pwdNew' : '1 2 3','pwdOld' : '*'},#charErr {'pwdNew' : 'admin','pwdOld' : '*'},#pwdSameErr {'pwdNew' : "",'pwdOld' : ""},#oldPwdBlank {'pwdNew' : "",'pwdOld' : "*"}#newPwdBlank ] def commonAction(self, arg): error = checkData(arg) changeUserPwd.main(arg) self.assertEqual(checkResponse(error), errTips[error]) def test_oldPwdErr(self): self.commonAction(self.data[0]) def test_lenErr(self): self.commonAction(self.data[1]) def test_charErr(self): self.commonAction(self.data[2]) def test_pwdSameErr(self): self.commonAction(self.data[3]) def test_oldPwdBlank(self): self.commonAction(self.data[4]) def test_newPwdBlank(self): self.commonAction(self.data[5])
這里利用了HTMLTestRunner來生成測試報告。
HTMLTestRunner語法請參看:https://testerhome.com/topics/7576
生成的測試報告將會存放在reports/test_report文件夾下,按照時間命名。測試報告的title叫做“修改管理員密碼試報告”
unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='test_report',report_title='修改管理員密碼試報告'))
def closeDriver(): time.sleep(3) driver.quit() os.system('killall chromedriver') os.system('killall geckodriver')
到這里,我們可以完成修改用戶名密碼模塊的單元測試了,為了增加代碼的健壯性,下面介紹異常處理。
點擊按鈕的時候可能出現(xiàn)的異常情況是:可能頁面元素還沒有加載出來的時候,點擊的動作就發(fā)生了。這樣就會引發(fā)找不到元素異常。
解決的方法是通過顯示等待,每10ms檢查一次頁面元素是否加載完成,完成后就點擊,否則就等到超時時間之后結(jié)束動作。
def waitandClick(xpath): try: WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, xpath))) except TimeoutException as e: print('Error:waitandClick, TimeoutException, xpath = %s\n' % xpath) else: driver.find_element_by_xpath(xpath).click()
在填寫表單時,除了頁面元素還沒有加載完成的異常外,還可能原有表單中有文本,而我們的輸入則是以追加模式填寫的。這就會導(dǎo)致填寫的文本不準(zhǔn)確。
def waitandSendkeys(xpath, keys): try: WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath))) except TimeoutException as e: print('Error:waitandSendkeys, TimeoutException, xpath = %s\n' % xpath) else: driver.find_element_by_xpath(xpath).clear() driver.find_element_by_xpath(xpath).send_keys(keys)
在元素加載中可能出現(xiàn): 1. 在超時時間內(nèi)元素沒有加載完成 2. 查詢的元素根本不存在
針對這兩種情況進(jìn)行異常處理:
def waitforDisplay(xpath): try: WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath))) except TimeoutException as e: print('Error:waitforDisplay, TimeoutException, xpath = %s\n' % xpath) else: try: process = driver.find_element_by_xpath(xpath) WebDriverWait(driver, 10).until(lambda driver: process.is_displayed()) except NoSuchElementException as e: print('Error:waitforDisplay, NoSuchElementException, xpath = %s\n' % xpath)
# -*- coding: UTF-8 -*- #!/usr/bin/env python from selenium import webdriver import time, os from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import TimeoutException import unittest import HtmlTestRunner import sys reload(sys) sys.setdefaultencoding('utf-8') # 1. 打開瀏覽器,訪問p.to driver = webdriver.Chrome() def openDriver(): driver.get("http://p.to") driver.maximize_window() # 2. 登陸 class loginClass(object): """docstring for login""" def __init__(self, arg): self.login_pwd = arg def login(self): waitandSendkeys('//*[@id="Pwd"]', self.login_pwd) waitandClick('//*[@id="Save"]') def login(data): openDriver() test1 = loginClass(data) test1.login() # 3.修改管理員密碼 class changePwdClass(object): """docstring for changePwdClass""" def __init__(self, arg): self.pwdNew = arg.get('pwdNew', '') self.pwdOld = arg.get('pwdOld', '') def changeUserPwd(self): waitandClick('//*[@id="Con"]/div[1]/ul[2]/li[1]') waitandClick('//*[@id="Con"]/div[1]/ul[2]/li[1]/ul/li[3]') waitforDisplay('//*[@id="_Widget"]') waitandSendkeys('//*[@id="PwdOld"]', self.pwdOld) waitandSendkeys('//*[@id="PwdNew"]', self.pwdNew) waitandSendkeys('//*[@id="PwdCfm"]', self.pwdNew) waitandClick('//*[@id="SavePwd"]') def changeUserPwd_main(data): changePwdObj = changePwdClass(data) changePwdObj.changeUserPwd() # 4. 單元測試數(shù)據(jù) errcode = ['oldPwdErr', 'lenErr', 'charErr', 'matchErr', 'pwdSameErr',\ 'oldPwdBlankErr', 'newPwdBlankErr'] errTips = { 'oldPwdErr' :'原密碼錯誤', 'lenErr' : '新密碼長度應(yīng)為5~63位', 'charErr' : "新密碼包含非法字符", 'matchErr' : '兩次密碼輸入不一致', 'pwdSameErr' : '新密碼與原密碼相同,請重新輸入', 'oldPwdBlankErr' : '請輸入原密碼', 'newPwdBlankErr' : '請輸入新密碼' } # 5. 檢查輸入的數(shù)據(jù)合法性 def checkData(data):#檢查順序跟頁面順序相同 #pwd = loginPwd pwd='admin' #'oldPwdBlankErr' if data['pwdOld'] == "": return errcode[5] #newPwdBlankErr if data['pwdNew'] == "": return errcode[6] #charErr strTmp = data['pwdNew'] for x in xrange(0,len(data['pwdNew'])): if ord(strTmp[x]) 33 or ord(strTmp[x]) > 127:#ASCII表示范圍:32-127 return errcode[2] #lenErr if len(data['pwdNew']) > 63 or len(data['pwdNew']) 5: return errcode[1] #oldPwdErr if pwd != data['pwdOld']: return errcode[0] #pwdSameErr if data['pwdNew'] == data['pwdOld']: return errcode[4] #no error return None # 6. 獲取輸入錯誤數(shù)據(jù)之后的頁面提示語 def checkResponse(error): if error == None: return # webText = driver.find_element_by_xpath('//*[@id="PwdTip"]').text webText = getText('//*[@id="PwdTip"]') if webText == False:#沒有提示 print('###Error: no tips on web!') else: webText = webText.decode('UTF-8') waitandClick('//*[@id="ModifyPwd"]/i') return webText # 8.單元測試類 class TestCase(unittest.TestCase): # 7. 編寫測試用例 data = [ {"pwdNew" : "12345678","pwdOld" : '8dadla'},#"oldPwdErr" {"pwdNew" : "admi","pwdOld" : 'admin'},#lenErr {'pwdNew' : '1 2 3','pwdOld' : 'admin'},#charErr {'pwdNew' : 'admin','pwdOld' : 'admin'},#pwdSameErr {'pwdNew' : "",'pwdOld' : ""},#oldPwdBlank {'pwdNew' : "",'pwdOld' : "admin"}#newPwdBlank ] def commonAction(self, arg): error = checkData(arg) changeUserPwd_main(arg) self.assertEqual(checkResponse(error), errTips[error]) time.sleep(1) def test_oldPwdErr(self): self.commonAction(self.data[0]) def test_lenErr(self): self.commonAction(self.data[1]) def test_charErr(self): self.commonAction(self.data[2]) def test_pwdSameErr(self): self.commonAction(self.data[3]) def test_oldPwdBlank(self): self.commonAction(self.data[4]) def test_newPwdBlank(self): self.commonAction(self.data[5]) # 10. 關(guān)閉瀏覽器 def closeDriver(): time.sleep(3) driver.quit() os.system('killall chromedriver') os.system('killall geckodriver') # 11. 異常處理 ## 11.1 點擊函數(shù) def waitandClick(xpath): try: WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, xpath))) except TimeoutException as e: print('Error:waitandClick, TimeoutException, xpath = %s\n' % xpath) else: driver.find_element_by_xpath(xpath).click() ## 11.2 填寫表單 def waitandSendkeys(xpath, keys): try: WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath))) except TimeoutException as e: print('Error:waitandSendkeys, TimeoutException, xpath = %s\n' % xpath) else: driver.find_element_by_xpath(xpath).clear() driver.find_element_by_xpath(xpath).send_keys(keys) ## 11.3 元素加載 def waitforDisplay(xpath): try: WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath))) except TimeoutException as e: print('Error:waitforDisplay, TimeoutException, xpath = %s\n' % xpath) else: try: process = driver.find_element_by_xpath(xpath) WebDriverWait(driver, 10).until(lambda driver: process.is_displayed()) except NoSuchElementException as e: print('Error:waitforDisplay, NoSuchElementException, xpath = %s\n' % xpath) def elementIsDisplayed(xpath): try: driver.find_element_by_xpath(xpath) except NoSuchElementException as e: return False def getText(xpath): time.sleep(1) return driver.find_element_by_xpath(xpath).text if __name__ == '__main__': openDriver() login('admin') #data = {'pwdNew'='admin', 'pwdOld'='12345678'} #changeUserPwd_main(data) #9. 進(jìn)行單元測試并生成測試報告 unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='test_report',report_title='修改管理員密碼試報告')) closeDriver()
完整demo請參看:https://github.com/niununu/k2p_web_test
到此這篇關(guān)于python實現(xiàn)自動化腳本編寫的文章就介紹到這了,更多相關(guān)python 自動化腳本 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
標(biāo)簽:洛陽 岳陽 吉林 清遠(yuǎn) 安慶 長春 泉州 怒江
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《python實現(xiàn)自動化腳本編寫》,本文關(guān)鍵詞 python,實現(xiàn),自動化,腳本,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。