selenium phantomjs tutorial
この記事では、PhantomJSを使用したSeleniumの自動化について、コード例を使用して説明します。
PhantomJSは、主にGUIレスの自動化に使用されるヘッドレスブラウザーです。
このブラウザで発生するパフォーマンスと実行はより高速であり、通常、手動監視が不要なシナリオや完全に自動化可能なアプリケーションで使用されます。
PhantomJSは、スクリプトを夜間に実行する場合に強くお勧めします。スクリプトの実行は高速であるため、人間による監視は必要ありません。また、スクリプト実行プロセスを手動で追跡するための自動スクリーンショットのオプションも提供します。
学習内容:
どのvrヘッドセットがps4で動作するか
- Webページの自動化におけるPhantomJSの利用
- PhantomJSとSeleniumFor Web Automation(基本)
- PhantomJSとSeleniumFor Web Automation(Advanced)
- 実行後のスクリーンショットとレポート
- PhantomJSをテストブラウザとして使用するための推奨事項
- 推奨読書
Webページの自動化におけるPhantomJSの利用
この記事では、Selenium自動化ツールを使用して、PhantomJSブラウザーで機能の自動化を実行します。
PhantomJSは、実際にはGUIインターフェースを持たないブラウザーをインスタンス化しますが、(Firefox、IEなど)、標準のDOMスクリプト、Ajax呼び出しなどのGUIインターフェースを備えたブラウザーのすべての標準を備えています。
SeleniumでPhantomJSを使用する目的
PhantomJSをSeleniumで使用する目的を理解することは非常に重要です。
Seleniumは、Webアプリケーションのさまざまな機能を自動化するために使用される機能自動化ツールであることは誰もが知っています。
現在、PhantomJSの目的はわずかに異なります。これは、GUIを使用しないブラウザであり、その主な用途は、本格的な回帰テストの自動化ではなく、スモークテスト/検証テストのカテゴリに分類されるテストケースを自動化することです。
SeleniumとPhantomJSを使用して自動化する場合は、テストケースの選択に注意する必要があります。もう1つの重要な部分は、実行を物理的に確認できないため、テストケースの実行ステータスを追跡することです。
PhantomJSとSeleniumFor Web Automation(基本)
GUIインターフェイスを備えた他のブラウザ(Firefox、IE、Chromeなど)と同様に、PhantomJSについても、Seleniumには自動化をサポートするための標準APIがあります。
簡単なコードで同じことを説明しましょう。
import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.phantomjs.PhantomJSDriverService; import org.openqa.selenium.remote.DesiredCapabilities; public class PhantomJSTest { public void phantomJS() throws InterruptedException, IOException { DesiredCapabilities caps = new DesiredCapabilities(); caps.setJavascriptEnabled(true); caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, 'D:\chromedriver\phantomjs-2.1.1-windows\bin\phantomjs.exe'); caps.setCapability('takesScreenshot', true); PhantomJSDriver driver = new PhantomJSDriver(caps); String baseUrl = 'http://www.google.com'; driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.get(baseUrl + '/'); File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile, new File('d:\PhantomJSSample\screenshotAfterLaunchingGoogle.jpeg'),true); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.navigate().to('https://selenium.dev//');//Launch URL File scrFile1 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile1, new File('d:\PhantomJSSample\screenshotAfterLaunchingURL.jpeg'),true); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.findElement(By.linkText('Download')).click();//Click on the Link driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); File scrFile2 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile2, new File('d:\PhantomJSSample\screenshotAfterClickingDownload.jpeg'),true); Thread.sleep(2000); int header_size =driver.findElements(By.xpath('(//div(@id='mainContent')//h3(1))')).size();//Get the total count of h3 headers in the page for(int i=1; i?=header_size; i++) { String suggestion_name_xp = '('+'//div(@id='mainContent')//h3(1)'+')'+'('+i+')'; String header =driver.findElement(By.xpath(suggestion_name_xp)).getText(); System.out.println(header); //Print the name of headers } Thread.sleep(2000); } public static void main(String() args) throws InterruptedException, IOException { PhantomJSTest pj =new PhantomJSTest(); pj.phantomJS(); } }
上記のコードスニペットが起動します Seleniumの公式ウェブサイト PhantomJSブラウザで、ダウンロードタブのクリック操作を実行します。次に、ダウンロードページのメインコンテンツのh3タグ付きヘッダーの数を計算して印刷します。
各操作の実行後、手動追跡用のスクリーンショットを撮ります。
経験豊富なadonetインタビューの質問と回答
次に、同じテスト機能をフレームワーク内に統合し、スクリーンショットとともにログ追跡を行います。また、エクステントレポートの統合とともに自動メール送信を追加して、完全な自動ラップを提供し、後で実行結果を追跡できるようにします。
PhantomJSとSeleniumFor Web Automation(Advanced)
フレームワーク構造の画像
フレームワークは、画像が示すとおりであり、次のもので構成されています。
- すべてのテストスクリプトで再利用できる再利用可能なコンポーネント
- 新しいテストケースごとに新しく作成されるテストコンポーネント。
- (Web要素ロケーター、URLなど)のようなフレームワークの入力であるリソースコンポーネント
ここでは、プロジェクトはテストフレームワークTestNGとともにMaven上に構築されています。また、エクステントレポートを使用しました。しかし、私はMavenプロジェクトやエクステントレポートの詳細には触れておらず、PhantomJSに焦点を合わせ続けています。
各コンポーネントのコードの詳細を以下に示します。このフレームワークは、phantomJSの実装に焦点を当てることを目的としているため、フレームワークはそれに基づいて設計されていますが、自分のビジネス仕様に従ってこのフレームワークを確実に拡張できます。
まず、宣言する必要のある依存関係を確認します POM.xml このプロジェクトを実行するために
'http://maven.apache.org/POM/4.0.0' xmlns:xsi= 'http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation= 'http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd' > 4.0.0 com.phantom.com com.phantomjs.com 0.0.1-SNAPSHOT org.apache.maven.plugins maven-resources-plugin 3.0.2 maven-plugin org.seleniumhq.selenium selenium-java 3.11.0 org.testng testng 6.8 test com.github.detro.ghostdriver phantomjsdriver 1.0.1 javax.mail mail 1.4 com.relevantcodes extentreports 2.40.2
POM.xml
再利用可能なコンポーネント
package ReusableElements; import java.io.File; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.phantomjs.PhantomJSDriverService; import org.openqa.selenium.remote.DesiredCapabilities; import org.testng.annotations.BeforeClass; import com.relevantcodes.extentreports.ExtentReports; import com.relevantcodes.extentreports.ExtentTest; import com.relevantcodes.extentreports.LogStatus; import ScreenShotLoc.ScreenShotLocations; public class InitiateBrowser { public static WebDriver driver = null; public ExtentReports extent; public ExtentTest logger; String workingDir = ScreenShotLocations.extentReportLoc; PropertyReader pr = new PropertyReader(); @BeforeClass public void InitBrowser() { extent = new ExtentReports(workingDir+'\ExtentReports\PhantomJSExectionResults.html', true); logger=extent.startTest('PhantomJS Implementation'); String BrowserName = 'PhantomJS'; if(BrowserName.equalsIgnoreCase('PhantomJS')) { DesiredCapabilities caps = new DesiredCapabilities(); caps.setJavascriptEnabled(true); caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, ScreenShotLocations.PhantomJSdriverLoc); caps.setCapability('takesScreenshot', true); driver = new PhantomJSDriver(caps); List baseUrls = pr.URLReader(); String baseUrl= baseUrls.get(0); String altUrl= baseUrls.get(1); driver.get(baseUrl); logger.log(LogStatus.PASS, 'Browser Initiated'); driver.navigate().to(altUrl); logger.log(LogStatus.PASS, 'Navigated to target browser'); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); } else if(BrowserName.equalsIgnoreCase('Chrome')) { System.setProperty('webdriver.chrome.driver',ScreenShotLocations.ChromedriverLoc); driver = new ChromeDriver(); List baseUrls = pr.URLReader(); String baseUrl= baseUrls.get(0); driver.get(baseUrl); logger.log(LogStatus.PASS, 'Browser Initiated'); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); } } }
InitiateBrowser.java
このコードは、ブラウザの開始に関連付けられています。
ここでは、ブラウザ名がハードコードされています。ただし、外部化することはできます(プロパティ/ Excelシートで)。使用するブラウザを選択できます。ここでは、PhantomJSを使用しました。
package ReusableElements; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; public class PropertyReader { Listvals = new ArrayList(); public List PropReader(){ Properties prop = new Properties(); try { prop.load(PropertyReader.class.getClassLoader().getResourceAsStream('ObjectRepository.properties')); vals.add(prop.getProperty('Download_Tab')); vals.add(prop.getProperty('H3_Headerlist')); } catch (IOException ex) { ex.printStackTrace(); } return vals; } public List URLReader() { Properties prp = new Properties(); try { prp.load(PropertyReader.class.getClassLoader().getResourceAsStream('APPURL.properties')); vals.add(prp.getProperty('APPURL')); vals.add(prp.getProperty('ALTERNATE_APPURL')); }catch (IOException ex) { ex.printStackTrace(); } return vals; } }
PropertyReader.java
このコードは、Web要素ロケーターおよびURLコンテナーとして使用した読み取りプロパティファイルに関連付けられています。
package ReusableElements; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; public class ReuseableMethods extends InitiateBrowser { public void LinktextClick(String loc) { driver.findElement(By.linkText(loc)).click();//Click on the Link } public String GetText(String loc) { String text= driver.findElement(By.xpath(loc)).getText(); return text; } public void takeScreenShot(String loc) throws IOException { File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile, new File(loc),true); } }
ReuseableMethods.java
このコードは、スクリプトで定期的に使用するさまざまなSelenium関数を処理しますが、これらの関数をテストスクリプトから分離して、フレームワークのコード行を減らし、使いやすさを向上させています。
package ReusableElements; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class SendMail { public void SendAutomatedMail() { final String from='XXXX';//change accordingly final String user='XXXX';//change accordingly final String password='XXXX';//change accordingly final String to='XXXX';//change accordingly //Creating the object for the session Properties props = new Properties(); props.put('mail.smtp.auth', 'true'); props.put('mail.smtp.starttls.enable', 'true'); props.put('mail.smtp.host','smtp.gmail.com'); props.put('mail.smtp.port', '587'); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user,password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject('TestExecution completed!! Please find the report'); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText('Hi All'); messageBodyPart.setText('please find the attachment'); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); String filename = 'D:/PhantomJSSample/ExtentReports/PhantomJSExectionResults.html'; DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); Transport.send(message); System.out.println('message sent successfully...'); } catch (MessagingException e) {e.printStackTrace();} } }
SendMail.java
このコードは、テストケースの実行後に自動メールを送信することを扱います。
テストコンポーネント
package com.phantomjs.com; import java.util.ArrayList; import java.util.List; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.testng.annotations.Test; import com.relevantcodes.extentreports.LogStatus; import ReusableElements.InitiateBrowser; import ReusableElements.PropertyReader; import ReusableElements.ReuseableMethods; import ReusableElements.SendMail; import ScreenShotLoc.ScreenShotLocations; public class TestScripts extends InitiateBrowser { @Test public void TestScript() throws IOException, InterruptedException { ReuseableMethods rm =new ReuseableMethods(); PropertyReader prop =new PropertyReader(); SendMail sm = new SendMail(); String download,h3_header; rm.takeScreenShot(ScreenShotLocations.screenshotAfterLaunchingURL); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); List propvals = prop.PropReader(); download= propvals.get(0); h3_header= propvals.get(1); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); try{ rm.LinktextClick(download);//Click on the Link logger.log(LogStatus.PASS, 'Validate if download Tab is clickable'); } catch(NoSuchElementException e) { logger.log(LogStatus.FAIL, 'Error while clicking on download Tab'); } driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); rm.takeScreenShot(ScreenShotLocations.screenshotAfterClickingDownload); Thread.sleep(2000); try{ int header_size =driver.findElements(By.xpath(h3_header)).size();//Get the total count of h3 headers in the page List headersh3 = new ArrayList(); for(int i=1; i?header_size; i++) { String suggestion_name_xp = '('+h3_header+')'+'('+i+')'; String header =rm.GetText(suggestion_name_xp); System.out.println(header); //Print the name of headers headersh3.add(header); //storing h3 main content headers to the list } logger.log(LogStatus.PASS, 'All main content h3 headers list printed on console'); int headers_count = headersh3.size(); if(headers_count==4) { logger.log(LogStatus.PASS, 'Validate if the main content h3 header count is as per business specification'); } Thread.sleep(2000); } catch(NoSuchElementException e) { logger.log(LogStatus.FAIL, 'Error while printing h3 headers list on console'); } extent.endTest(logger); extent.flush(); sm.SendAutomatedMail(); } }
TestScripts.java
これは実際のテストケースです。
- URLを公開しています。
- ダウンロードタブをクリックして、ダウンロードリンクがクリック可能かどうかを確認しています。
- ページのダウンロードタブにあるすべてのh3ヘッダーを読んでいます。
- h3ヘッダーの数を検証しています。
再利用可能なコンポーネント
package ScreenShotLoc; public interface ScreenShotLocations { String screenshotAfterLaunchingURL= 'd:\PhantomJSSample\screenshotAfterLaunchingURL.jpeg'; String screenshotAfterClickingDownload= 'd:\PhantomJSSample\screenshotAfterClickingDownload.jpeg'; String extentReportLoc= 'd:\PhantomJSSample\'; String ChromedriverLoc= 'D:\chromedriver\chromedriver.exe'; String PhantomJSdriverLoc= 'D:\phantomjs-2.1.1-windows\bin\phantomjs.exe'; }
ScreenShotLocations.java
APPURL = https://www.google.com ALTERNATE_APPURL = https://selenium.dev/
APPURL.properties
Download_Tab = Download H3_Headerlist= (//div(@id='mainContent')//h3(1))
ObjectRepository.properties
フレームワークはデータ駆動型になるように設計されているため、これらはこのフレームワークに供給される入力です。
- ScreenShotLoc.javaは、スクリーンショットの場所をドライブに保存し、ドライバーの場所をブラウザーに保存します。
- APPURL.propertiesは、テストに関係するアプリケーションURLを格納します。
- ObjectRepository.propertiesは、Web要素ロケーターを格納します。
実行後のスクリーンショットとレポート
次に、実行後のレポートを表示します。
Windows10で.torrentファイルを開く方法
ポジティブシナリオ: 上のスクリーンショットは、自動テストケースのすべてのテストステップが正常に実行されたときに生成されるレポートです。
ネガティブシナリオ: 上のスクリーンショットは、自動テストケースのすべてのテストステップが正常に実行されなかった場合に生成されるレポートです。
自動メールのスクリーンショット:
PhantomJSをテストブラウザとして使用するための推奨事項
PhantomJSをテストブラウザとして使用する場合の推奨事項を以下に示します。
- 実行は高速で、パフォーマンスも良好です。
- ブラウザはGUIが少ないわけではないため、手動で監視する必要がない場合は、自動化の候補として適しています。
- テストケースがスモークテストを実行するように設計されている場合、または検証ポイントのみが考慮されるテストケースの場合に強くお勧めします。
- 回帰機能テストにはお勧めしません。
推奨読書= >> Seleniumのスクリーンショット
幸せな読書!!
推奨読書
- Cucumber Seleniumチュートリアル:Cucumber Java SeleniumWebDriverの統合
- Selenium自動化プロジェクトのテスト見積もりに影響を与える7つの要因– Seleniumチュートリアル#32
- Appium Studio for Eclipse:EclipseからのエンドツーエンドのAppium / Selenium自動化
- Selenium WebDriverの概要– Seleniumチュートリアル#8
- Seleniumグリッドチュートリアル:クロスブラウザテストのセットアップと例
- ChromeDriver Seleniumチュートリアル:ChromeでのSeleniumWebdriverテスト
- 効率的なSeleniumスクリプティングとトラブルシューティングシナリオ– Seleniumチュートリアル#27
- ログを使用したSeleniumスクリプトのデバッグ(Log4jチュートリアル)– Seleniumチュートリアル#26