selenium phantomjs tutorial
이 기사에서는 PhantomJS를 사용한 Selenium Automation이 코드 예제로 설명됩니다.
PhantomJS는 주로 GUI가 적은 자동화에 사용되는 헤드리스 브라우저입니다.
이 브라우저에서 발생하는 성능 및 실행은 더 빠르며 일반적으로 수동 모니터링이 필요하지 않은 시나리오와 완전히 자동화 가능한 애플리케이션에서 사용됩니다.
PhantomJS는 실행이 빠르기 때문에 사람의 모니터링이 필요하지 않은 야간 스크립트 실행의 경우 적극 권장됩니다. 또한 스크립트 실행 프로세스의 수동 추적을위한 자동 스크린 샷 옵션을 제공합니다.
학습 내용 :
- 웹 페이지 자동화에서 PhantomJS 활용
- 웹 자동화를위한 PhantomJS 및 Selenium (기본)
- 웹 자동화를위한 PhantomJS 및 Selenium (고급)
- 사후 실행 스크린 샷 및 보고서
- PhantomJS를 테스트 브라우저로 사용하기위한 권장 사항
- 추천 도서
웹 페이지 자동화에서 PhantomJS 활용
이 기사에서는 Selenium 자동화 도구를 사용하여 PhantomJS 브라우저에서 기능 자동화를 수행 할 것입니다.
PhantomJS는 실제로 GUI 인터페이스가없는 브라우저를 인스턴스화하지만 (Firefox, IE 등), 표준 DOM 스크립팅, Ajax 호출 등과 같은 GUI 인터페이스가있는 브라우저의 모든 표준을 가지고 있습니다.
PhantomJS를 셀레늄과 함께 사용하는 목적
Selenium과 함께 PhantomJS를 사용하는 목적을 이해하는 것은 매우 중요합니다.
우리 모두는 Selenium이 웹 애플리케이션의 다양한 기능을 자동화하는 데 사용되는 기능 자동화 도구라는 것을 알고 있습니다.
이제 PhantomJS의 목적은 GUI가 덜 브라우저이고 주요 용도는 본격적인 회귀 테스트 자동화가 아닌 연기 테스트 / 검증 테스트 범주에 속하는 테스트 사례를 자동화하는 것이므로 약간 다릅니다.
Selenium 및 PhantomJS를 사용하여 자동화하는 경우 테스트 케이스를 신중하게 선택해야합니다. 또 다른 중요한 부분은 실행을 물리적으로 볼 수 없기 때문에 테스트 케이스의 실행 상태를 추적하는 것입니다.
웹 자동화를위한 PhantomJS 및 Selenium (기본)
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(); } }
위의 코드 조각이 시작됩니다. 셀레늄 공식 웹 사이트 PhantomJS 브라우저에서 다운로드 탭에서 클릭 작업을 수행합니다. 그런 다음 다운로드 페이지에있는 주요 콘텐츠의 h3 태그 헤더 수를 계산하여 인쇄합니다.
각 작업을 실행 한 후 수동 추적을 위해 스크린 샷을 찍습니다.
이제 우리는 스크린 샷과 함께 로그 추적을 사용하여 프레임 워크 내에서 동일한 테스트 기능을 통합 할 것입니다. 또한 나중에 실행 결과를 추적 할 수 있도록 범위 보고서 통합과 함께 자동 메일 링을 추가하여 완전한 자동화 랩을 제공합니다.
웹 자동화를위한 PhantomJS 및 Selenium (고급)
프레임 워크 구조 이미지
프레임 워크는 이미지에서 알 수 있듯이 다음과 같이 구성됩니다.
- 모든 테스트 스크립트에서 재사용 할 수있는 재사용 가능한 구성 요소
- 각각의 새로운 테스트 케이스와 함께 새로 생성 될 테스트 구성 요소입니다.
- (웹 요소 로케이터, URL 등)과 같은 프레임 워크의 입력 인 리소스 구성 요소
여기서 프로젝트는 테스트 프레임 워크 TestNG와 함께 Maven에 빌드됩니다. 또한 Extent Report를 사용했습니다. 그러나 나는 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
이 코드는 브라우저 시작과 관련이 있습니다.
여기서 브라우저 이름은 하드 코딩됩니다. 그러나 외부화 될 수 있습니다 (속성 / 엑셀 시트에서). 사용할 브라우저를 선택할 수 있으며 여기에서는 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
이 코드는 웹 요소 로케이터 및 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는 웹 요소 로케이터를 저장합니다.
사후 실행 스크린 샷 및 보고서
이제 사후 실행 보고서를 살펴 보겠습니다.
긍정적 인 시나리오 : 위 스크린 샷은 자동화 된 테스트 케이스의 모든 테스트 단계가 성공적으로 실행되었을 때 생성 된 보고서입니다.
부정적인 시나리오 : 위 스크린 샷은 자동화 된 테스트 케이스의 모든 테스트 단계가 성공적으로 실행되지 않았을 때 생성 된 보고서입니다.
자동 메일 스크린 샷 :
PhantomJS를 테스트 브라우저로 사용하기위한 권장 사항
다음은 PhantomJS를 테스트 브라우저로 사용하는 경우에 대한 몇 가지 권장 사항입니다.
- 좋은 성능으로 실행이 빠릅니다.
- 브라우저가 GUI보다 적지 않기 때문에 수동 모니터링이 필요하지 않은 경우 자동화를위한 좋은 후보입니다.
- 테스트 케이스가 연기 테스트를 수행하도록 설계된 경우 또는 검증 포인트 만 고려되는 테스트 케이스를 사용할 때 적극 권장됩니다.
- 회귀 적 기능 테스트에는 권장되지 않습니다.
추천 읽기 = >> 셀레늄의 스크린 샷
행복한 독서 !!
추천 도서
- Cucumber Selenium 튜토리얼 : Cucumber Java Selenium WebDriver 통합
- Selenium 자동화 프로젝트의 테스트 추정에 영향을 미치는 7 가지 요인 – Selenium Tutorial # 32
- Eclipse 용 Appium Studio : Eclipse에서 엔드-투-엔드 Appium / Selenium 자동화
- Selenium WebDriver 소개 – Selenium Tutorial # 8
- Selenium Grid Tutorial : 크로스 브라우저 테스트 설정 및 예
- ChromeDriver Selenium 자습서 : Chrome에서 Selenium Webdriver 테스트
- 효율적인 Selenium 스크립팅 및 문제 해결 시나리오 – Selenium 자습서 # 27
- 로그로 Selenium 스크립트 디버깅 (Log4j 튜토리얼) – Selenium 튜토리얼 # 26