Selenium網站自動化測試:如何處理瀏覽器的安全性設定

Selenium網站自動化測試:如何處理瀏覽器的安全性設定

這篇文章主要說明當瀏覽器的安全設定

導致網頁原件無法如預期執行時,應該如何處理?

以jQuery 的執行為例子,當該來源的JS無法被信任時,

瀏覽器預設安全設定會自動停止所有的JavaScript執行。

因此,自動化測試也就無法對網頁原件操作。

Selenium提供瀏覽器環境設定的方法,可以在啟動瀏覽器的時候設定相關安全設定,讓自動化測試程式可以繼續進行。

最後,舉一個完整的 Java 程式範例說明如何實作。

測試情境

我們利用這個網站測試

https://dl.dropboxusercontent.com/u/2611448/site/sortable.html

number pannel

這個網站提供數字的 Drag and Drop. 可以將每個數字用滑鼠任意拖拉就可以交換位置

如果用預設瀏覽器瀏覽這個網站的時候,會因為安全性設定的問題,無法做拖拉

以FireFox 為例,需要將安全性設定允許執行,設定如下圖。

但是,如果我們是用Selenium自動化測試程式執行時,要如預先設定這樣的安全性設定呢?

FireFox security Settings

測試腳本

我們預期的測試腳本如下:

1. 用FireFox 瀏覽網站 https://dl.dropboxusercontent.com/u/2611448/site/sortable.html

2. 設定安全性設定,讓網站內容可以順利執行

3. 將數字2 與 3的位置用 Drag and Drop 相互對調

程式說明

這個例子中,我們主要需要調整兩個FireFox 的安全性設定

  • security.mixed_content.block_active_content
  • security.mixed_content.block_display_content

利用Selenium 提供的 FirefoxProfile物件設定安全性屬性,範例如下:

FirefoxProfile profile = new FirefoxProfile();
profile.setPreference(“security.mixed_content.block_active_content”,false);
profile.setPreference(“security.mixed_content.block_display_content”,true);

另外,Drag and Drop 的部分可以利用滑鼠的 clickAndHold還有 release這兩個滑鼠動作來達成

使用方式先在網頁原件source的地方執行 ClickAndHold,接著再到網頁目的地原件執行 release

builder.clickAndHold(Source).release(Destination).perform();

 

Java範例程式

[pastacode lang=”java” message=”Selenium FireFox Security Settings” highlight=”” provider=”manual”]

package mySelenium;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.interactions.Actions;

public class DragDropNum {
	public static void main(String args[]) {
		
		FirefoxProfile profile = new FirefoxProfile();
		// set the profile to disable the security protection.
		// otherwise, it won't be able to drag and drop
		profile.setPreference("security.mixed_content.block_active_content",false);
		profile.setPreference("security.mixed_content.block_display_content",true);
						
		WebDriver driver = new FirefoxDriver(profile);
		driver.get("https://dl.dropboxusercontent.com/u/2611448/site/sortable.html");

		//	Drag three to two
		WebElement three = driver.findElement(By.name("three"));
		WebElement two = driver.findElement(By.name("two"));
				
		Actions builder = new Actions(driver);
		// Move tile3 to the position of tile2
		builder.clickAndHold(three).release(two).perform();
	}
}

[/pastacode]

Leave a Reply

Your email address will not be published. Required fields are marked *