1. 程式人生 > >Selenium學習筆記(六)——Selenium Grid

Selenium學習筆記(六)——Selenium Grid

什麼是Selenium Grid

Selenium Grid是Selenium專門用於在不同瀏覽器、作業系統和機器上並行執行的元件。
Selenium Grid使用hub-nodes的結構,你可以在hub上啟動測試,不過測試則會在不同的機器node上執行。
hub and nodes

什麼時候使用Selenium Grid

  • 需要在不同瀏覽器、作業系統和機器上同時執行測試時
  • 節省測試時間

如何配置Selenium Grid

Step1. 下載Selenium Server的jar包到兩臺能夠通訊的機器上。
(Hub)Machine A 192.168.1.102
(Node)Machine B 192.168.1.111。
Step2. 啟動hub端。
執行命令: java -jar selenium-server-standalone-3.4.0.jar -role hub


hub
Step3. 驗證hub狀態。
在hub和node上是否能訪問hub控制中心:http://192.168.1.102:4444/grid/console
Step4. 啟動並註冊Node到Hub。
執行命令: java Dwebdriver.ie.driver=C:/drivers/IEDriverServer.exe -jar selenium-server-standalone-3.4.0.jar -role webdriver - hub http://192.168.1.102:4444/grid/register -port 5566(node的埠可以選擇任意未被佔用埠,而瀏覽器驅動變數必須在這裡提供,不能在程式碼中設定)
Step5. 檢查是否註冊成功。
開啟hub的配置頁面,能看到註冊的nodes時,我們就已經完成了一個簡單的Grid的配置:
這裡寫圖片描述

編寫Grid適用的測試指令碼

編寫Grid適用的測試指令碼需要用到兩個類:
DesiredCapabilites用於設定我們需要自動化的瀏覽器和系統型別;
RemoteWebDriver用於設定測試在哪些node上執行。

DesiredCapabilites

根據在hub的配置頁面中可以看到註冊nodes中支援的瀏覽器,把滑鼠放在想執行的瀏覽器圖示上可以看到設定資訊。根據資訊設定DesiredCapabilities:

DesiredCapabilities capability = DesiredCapabilities.internetExplorer();
capability.setBrowserName("internet explorer"
); capability.setPlatform(Platform.VISTA);

RemoteWebDriver

以node的URL和DesiredCapabilites物件為引數建立RemoteWebDriver物件。

WebDriver driver = new RemoteWebDriver(new URL("http://192.168.1.4:5566/wd/hub"), capability);

部分程式碼

DesiredCapabilities capability = DesiredCapabilities.internetExplorer();
// 避免IE安全設定裡,各個域的安全級別不一致導致的錯誤 
// Caused by: org.openqa.selenium.NoSuchSessionException: Unexpected error launching Internet Explorer. Protected Mode settings are not the same for all zones. Enable Protected Mode must be set to the same value (enabled or disabled) for all zones. (WARNING: The server did not provide any stacktrace information)
capability.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
capability.setBrowserName("internet explorer");
capability.setPlatform(Platform.VISTA);
WebDriver driver = new RemoteWebDriver(new URL("http://192.168.1.111:5566/wd/hub"), capability);
String baseUrl = "http://www.baidu.com/";
driver.get(baseUrl);