selenium phantomjs tutorial
In questo articolo, l'automazione del selenio con PhantomJS viene spiegata con esempi di codice:
PhantomJS è un browser headless che viene utilizzato principalmente per l'automazione senza GUI.
Le prestazioni e l'esecuzione che avvengono su questo browser sono più veloci ed è generalmente utilizzato negli scenari in cui non è richiesto il monitoraggio manuale e su quelle applicazioni che sono completamente automatizzabili.
PhantomJS è altamente raccomandato in caso di esecuzione di script durante la notte, dove il monitoraggio umano non è richiesto in quanto l'esecuzione è veloce veloce. Fornisce inoltre opzioni per uno screenshot automatico per il monitoraggio manuale del processo di esecuzione dello script.
Cosa imparerai:
- Utilizzo di PhantomJS nell'automazione della pagina Web
- PhantomJS e selenio per l'automazione Web (di base)
- PhantomJS e selenio per l'automazione web (avanzato)
- Screenshot e report post-esecuzione
- Raccomandazione per utilizzare PhantomJS come browser di prova
- Lettura consigliata
Utilizzo di PhantomJS nell'automazione della pagina Web
In questo articolo, utilizzeremo lo strumento di automazione Selenium per eseguire l'automazione funzionale sul browser PhantomJS.
PhantomJS crea effettivamente un'istanza di un browser che non dispone di un'interfaccia GUI, ma ha tutto lo standard di un browser con un'interfaccia GUI come (Firefox, IE, ecc.), Script DOM standard, chiamate Ajax, ecc.
Obiettivo dell'utilizzo di PhantomJS con selenio
È molto importante capire l'obiettivo dell'utilizzo di PhantomJS con selenio.
Sappiamo tutti che Selenium è uno strumento di automazione funzionale che viene utilizzato per automatizzare varie funzionalità delle applicazioni web.
Ora l'obiettivo di PhantomJS è leggermente diverso in quanto è un browser senza GUI e il suo utilizzo principale è automatizzare i casi di test con rientri nella categoria dei test del fumo / test di convalida e non dell'automazione del test regressivo a tutti gli effetti.
Se automatizziamo utilizzando Selenium e PhantomJS, dobbiamo stare attenti nella scelta dei casi di test. Un'altra parte importante è il monitoraggio dello stato di esecuzione dei casi di test poiché non possiamo vedere fisicamente l'esecuzione.
PhantomJS e selenio per l'automazione Web (di base)
Proprio come qualsiasi altro browser con interfaccia GUI (Firefox, IE, Chrome, ecc.), Anche per PhantomJS Selenium ha un'API standard per supportare l'automazione.
Illustriamo lo stesso con un semplice codice:
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(); } }
Lo snippet di codice sopra viene avviato Sito ufficiale del selenio sul browser PhantomJS ed esegue l'operazione di clic sulla scheda di download. Quindi calcola il numero di intestazioni con tag h3 del contenuto principale nella pagina di download e lo stampa.
aziende che ti pagano per provare i loro prodotti
Dopo l'esecuzione di ogni operazione, acquisisce uno screenshot per il tracciamento manuale.
miglior editor python per mac os x
Ora integreremo la stessa funzionalità di test all'interno di un framework con tracciamento dei log insieme allo screenshot. Aggiungiamo anche il mailing automatico insieme all'integrazione del rapporto di estensione per fornire un quadro completo di automazione, in modo da poter monitorare il risultato dell'esecuzione in seguito.
PhantomJS e selenio per l'automazione web (avanzato)
Immagine della struttura del quadro
La struttura è come suggerisce l'immagine ed è composta da:
- I componenti riutilizzabili che possono essere riutilizzati da ogni script di test
- Il componente di test che verrà creato nuovo con ogni nuovo caso di test.
- I componenti delle risorse che sono gli input del framework come (localizzatori di elementi Web, URL, ecc.)
Qui il progetto è costruito su Maven insieme al framework di test TestNG. Inoltre, abbiamo utilizzato Extent Report. Ma non sto entrando nei dettagli di un progetto Maven o di un report sull'estensione, ma mi limito a concentrarmi su PhantomJS.
Di seguito sono riportati i dettagli del codice per ciascuno dei componenti. Questo framework ha lo scopo di concentrarsi sull'implementazione di phantomJS, quindi il framework è progettato sulla base di questo, ma si può sicuramente estendere questo framework secondo le proprie specifiche aziendali.
Per prima cosa, vedremo in quali dipendenze dobbiamo dichiarare POM.xml per eseguire questo progetto
'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
Componenti riutilizzabili
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
Questa parte di codice è associata all'avvio del browser.
Qui il nome del browser è hardcoded. Ma può essere esternalizzato (in proprietà / foglio Excel). Si può scegliere quale browser utilizzare e qui abbiamo utilizzato 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
Questo pezzo di codice è associato al file delle proprietà di lettura che abbiamo usato come localizzatore di elementi web e contenitore di 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
Questo pezzo di codice si occupa di varie funzioni Selenium che usiamo regolarmente nei nostri script, ma abbiamo separato queste funzioni dagli script di test per ridurre le righe di codice nel framework e aumentarne l'usabilità.
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
Questa parte di codice si occupa dell'invio di una mail automatica dopo l'esecuzione del test case.
Componenti di prova
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
Questo è il vero caso di test in cui:
- Stiamo lanciando l'URL.
- Stiamo facendo clic sulla scheda di download e verificando che il collegamento per il download sia selezionabile o meno.
- Stiamo leggendo tutte le intestazioni h3 nella scheda download della pagina.
- Stiamo convalidando il conteggio delle intestazioni h3.
Componenti riutilizzabili
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
Questi sono gli input forniti a questo framework poiché il framework è progettato per essere basato sui dati.
- ScreenShotLoc.java memorizza la posizione dello screenshot nell'unità e la posizione del driver del browser.
- APPURL.properties memorizza l'URL dell'applicazione coinvolta nel test.
- ObjectRepository.properties memorizza i localizzatori di elementi web.
Screenshot e report post-esecuzione
Ora vedremo il report di post-esecuzione:
Scenario positivo: Lo screenshot sopra è il report generato quando tutti i passaggi di test dei casi di test automatizzati vengono eseguiti correttamente.
come aprire i file .jar
Scenario negativo: Lo screenshot sopra è il report generato quando tutti i passaggi di test dei casi di test automatizzati non vengono eseguiti correttamente.
Screenshot automatico della posta:
Raccomandazione per utilizzare PhantomJS come browser di prova
Di seguito sono riportati alcuni consigli su quando utilizzare PhantomJS come browser di prova.
- L'esecuzione è veloce con buone prestazioni.
- Un buon candidato per l'automazione se il monitoraggio manuale non è richiesto in quanto il browser non è privo di GUI.
- Altamente raccomandato quando i casi di test sono progettati per eseguire test del fumo o casi di test in cui vengono presi in considerazione solo i punti di convalida.
- Non consigliato per test funzionali regressivi.
Lettura suggerita = >> Screenshot in selenio
Buona lettura!!
Lettura consigliata
- Esercitazione sul selenio di cetriolo: integrazione con WebDriver di selenio Java di cetriolo
- 7 fattori che influenzano la stima del test del progetto Selenium Automation - Selenium Tutorial # 32
- Appium Studio for Eclipse: automazione end-to-end Appium / Selenium di Eclipse
- Introduzione a Selenium WebDriver - Selenium Tutorial # 8
- Selenium Grid Tutorial: configurazione ed esempio di test cross browser
- Tutorial ChromeDriver Selenium: test Webdriver Selenium su Chrome
- Scenari efficienti di scripting selenio e risoluzione dei problemi - Tutorial selenio n. 27
- Debug degli script di selenio con i registri (tutorial di Log4j) - Esercitazione di selenio # 26