以前selenium+python自動化測試--登陸 中,幾個帳號和密碼登陸就要寫幾個用例,感受很麻煩~,因此下面介紹一下用數據驅動實現不一樣用例的登陸。html
話很少說,直接貼代碼~~python
文件名稱:test_ddtlogin.pyweb
import ddt import unittest from selenium import webdriver from common.base import Base testdata = [ {'user':'','psw':'','exp':'請輸入手機號碼'}, {'user':'admin','psw':'','exp':'請輸入密碼'}, {'user':'','psw':'666666','exp':'請輸入手機號碼'}, {'user':'admin','psw':'666666','exp':'帳號不存在'} ] @ddt.ddt class Testddt(unittest.TestCase): # 定位手機號 username = ("name", "loginName") # 定位密碼 psw = ("name", "loginPassWord") # 定位登陸按鈕 loginbutton = ("id", "loginBtn") # 定位提示信息 message = ("className", "toast-message") @classmethod def setUpClass(cls): cls.driver = webdriver.Firefox() cls.baseddt = Base(cls.driver) cls.driver.get("不肯透露姓名的url") def setUp(self): self.baseddt.clear(self.username) self.baseddt.clear(self.psw) @classmethod def tearDownClass(cls): cls.driver.quit() # 加載測試數據 @ddt.data(*testdata) def test_01(self,data): username = data['user'] password = data['psw'] exp = data['exp'] #輸入手機號 self.baseddt.send(self.username,username) #輸入密碼 self.baseddt.send(self.psw,password) #點擊登陸按鈕 self.baseddt.click(self.loginbutton) #獲取結果 result = self.baseddt.find(self.message).text print("我是結果:", result) self.assertEqual(result, exp) if __name__ == '__main__': unittest.main()
上面代碼運行屢次後,發現最後一個用例執行失敗了,以爲多是緩存問題,因此仍是改爲下面的代碼:緩存
import ddt import unittest from selenium import webdriver from common.base import Base testdata = [ {'user':'','psw':'','exp':'請輸入手機號碼'}, {'user':'admin','psw':'','exp':'請輸入密碼'}, {'user':'','psw':'666666','exp':'請輸入手機號碼'}, {'user':'admin','psw':'666666','exp':'帳號不存在'} ] @ddt.ddt class Testddt(unittest.TestCase): # 定位手機號 username = ("name", "loginName") # 定位密碼 psw = ("name", "loginPassWord") # 定位登陸按鈕 loginbutton = ("id", "loginBtn") # 定位提示信息 message = ("className", "toast-message") @classmethod def setUpClass(cls): cls.driver = webdriver.Firefox() cls.baseddt = Base(cls.driver) def setUp(self): self.driver.get("不肯透露姓名的url") def tearDown(self): self.driver.delete_all_cookies() @classmethod def tearDownClass(cls): cls.driver.quit() # 加載測試數據 @ddt.data(*testdata) def test_01(self,data): username = data['user'] password = data['psw'] exp = data['exp'] #輸入手機號 self.baseddt.send(self.username,username) #輸入密碼 self.baseddt.send(self.psw,password) #點擊登陸按鈕 self.baseddt.click(self.loginbutton) #獲取結果 result = self.baseddt.find(self.message).text print("我是結果:", result) self.assertEqual(result, exp) if __name__ == '__main__': unittest.main()
運行結果:cookie
純屬我的思路,若有錯誤請在評論區指出,必定當即糾正。很是感謝~ 測試
讀取文件操做請看下回分解😜ui