基於Selenium和unittest單元測試框架的一個測試框架SeleniumBase。
1、SeleniumBase支持 pip安裝
> pip install seleniumbase
它依賴的庫比較多,包括pytest、nose這些第三方單元測試框架,是爲更方便的運行測試用例,因爲這兩個測試框架是支持unittest測試用例的執行的
2、SeleniumBase還生成了“seleniumbase”命令,主要是爲了方便我們安裝瀏覽器驅動。
> seleniumbase install chromedriver
> seleniumbase install geckodriver
> seleniumbase install edgedriver
> seleniumbase install iedriver
> seleniumbase install operadriver
3、在項目的examples/目錄下面提供了豐富的例子。
from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_basic(self):
self.open("https://xkcd.com/353/")
self.assert_element('img[alt="Python"]')
self.click('a[rel="license"]')
self.assert_text("free to copy", "div center")
self.open("https://xkcd.com/1481/")
title = self.get_attribute("#comic img", "title")
self.assert_true("86,400 seconds per day" in title)
self.click("link=Blag")
self.assert_text("The blag of the webcomic", "h2")
self.update_text("input#s", "Robots!\n")
self.assert_text("Hooray robots!", "#content")
self.open("https://xkcd.com/1319/")
self.assert_exact_text("Automation", "#ctitle")
4、接下來是腳本的執行,你可以使用pytest或nose,因爲SeleniumBase已經幫你裝好了:
> pytest my_first_test.py --browser=chrome
> nosetests my_first_test.py --browser=firefox
它還提供的有“—demo_mode”模式,使腳本執行的過程變得很慢,而且還會讓操作的元素高亮顯示,方便你查看和定位問題。
> pytest my_first_test.py --demo_mode
在調試Selenium腳本的時候,我們希望錯誤時可以暫停腳本,那麼可以加“--pdb -s”參數。
> pytest my_first_test.py --pdb -s
當腳本報錯時是這樣的:
上面的代碼將使瀏覽器窗口保持打開狀態,以防出現故障。你可以繼續輸入命令:
“c”:繼續
“s”:步驟
“n”下一步
你還可以利用pytest 的 pytest-thml插件生成測試報告。
> pytest test_suite.py --html=report.html
當用例運行失敗時自動截圖!