How to attach screenshot to Extent Report in java selenium - java

I am trying to attach screenshot for failed testcases from my path to Extent Report but somehow i am not able to attach into it.
I have tried my possible solution but it fails .
I have used extent report version 3
here is mine full code in separate extenreport class :
package com.qa.ExtentReportListener;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.testng.IReporter;
import org.testng.IResultMap;
import org.testng.ISuite;
import org.testng.ISuiteResult;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.xml.XmlSuite;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.ChartLocation;
import com.aventstack.extentreports.reporter.configuration.Theme;
import com.crm.qa.util.TestUtil;
public class ExtentTestNGIReporterListener implements IReporter {
private static final String OUTPUT_FOLDER = "test-output/";
private static final String FILE_NAME = "Extent.html";
private ExtentReports extent;
private ExtentTest test;
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
init();
for (ISuite suite : suites) {
Map<String, ISuiteResult> result = suite.getResults();
for (ISuiteResult r : result.values()) {
ITestContext context = r.getTestContext();
buildTestNodes(context.getFailedTests(), Status.FAIL);
buildTestNodes(context.getSkippedTests(), Status.SKIP);
buildTestNodes(context.getPassedTests(), Status.PASS);
}
}
for (String s : Reporter.getOutput()) {
extent.setTestRunnerOutput(s);
}
extent.flush();
}
private void init() {
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(OUTPUT_FOLDER + FILE_NAME);
htmlReporter.config().setDocumentTitle("ExtentReports - Created by TestNG Listener");
htmlReporter.config().setReportName("ExtentReports - Created by TestNG Listener");
htmlReporter.config().setTestViewChartLocation(ChartLocation.BOTTOM);
htmlReporter.config().setTheme(Theme.STANDARD);
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
extent.setReportUsesManualConfiguration(true);
}
private void buildTestNodes(IResultMap tests, Status status) {
if (tests.size() > 0) {
for (ITestResult result : tests.getAllResults()) {
test = extent.createTest(result.getMethod().getMethodName());
for (String group : result.getMethod().getGroups())
test.assignCategory(group);
if (result.getThrowable() != null) {
test.log(status, result.getThrowable());
}
else {
test.log(status, "Test " + status.toString().toLowerCase() + "ed");
}
test.getModel().setStartTime(getTime(result.getStartMillis()));
test.getModel().setEndTime(getTime(result.getEndMillis()));
}
}
}
public void down(ITestResult result) throws IOException{
if(result.getStatus()==ITestResult.FAILURE){
test.log(Status.FAIL, "TEST CASE FAILED IS "+result.getName()); //to add name in extent report
test.log(Status.FAIL, "TEST CASE FAILED IS "+result.getThrowable()); //to add error/exception in extent report
String screenshotPath = TestUtil.takeScreenshotAtEndOfTest();
test.fail("Test Case failed check screenshot below"+test.addScreenCaptureFromPath(screenshotPath));
//extentTest.log(Status.FAIL, MediaEntityBuilder.createScreenCaptureFromPath(screenshotPath).build()); //to add screenshot in extent report
//extentTest.fail("details").addScreenCaptureFromPath(screenshotPath);
}
else if(result.getStatus()==ITestResult.SKIP){
test.log(Status.SKIP, "Test Case SKIPPED IS " + result.getName());
}
else if(result.getStatus()==ITestResult.SUCCESS){
test.log(Status.PASS, "Test Case PASSED IS " + result.getName());
}
extent.flush();
}
private Date getTime(long millis) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(millis);
return calendar.getTime();
}
}
here is my util class which contain screenshot method:
public static String takeScreenshotAtEndOfTest() throws IOException {
String dateName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
TakesScreenshot ts = (TakesScreenshot)driver;
File source = ts.getScreenshotAs(OutputType.FILE);
String destination = System.getProperty("user.dir") + "/screenshots/" + dateName
+ ".png";
File finalDestination = new File(destination);
FileHandler.copy(source, finalDestination);
return destination;
}

If you want take screen shots for failed test cases with test class name use below code segment.

Extent Report already provide the utility to take the screenshot .Please refer the below link:
https://extentreports.com/docs/versions/3/java/#automatic-screenshot-management
also find the snapshot and code for same:
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter("extent.html");
htmlReporter.config().setAutoCreateRelativePathMedia(true);
test1.fail("details", MediaEntityBuilder.createScreenCaptureFromPath("1.png").build());
test2.fail("details", MediaEntityBuilder.createScreenCaptureFromPath("2.png").build());
how to take Screenshot using extent report

Try using this :
logger.log(Status.FAIL, logger.addScreenCaptureFromPath("YOUR PATH"));
UPDATE :
If this doesn't work, just cast the inner logger with markup.
import com.aventstack.extentreports.markuputils.Markup;

package com.helper;
import org.testng.annotations.Test;
import com.aventstack.extentreports.AnalysisStrategy;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.MediaEntityBuilder;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.reporter.ExtentSparkReporter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.codec.binary.Base64;
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.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.opera.OperaDriver;
import org.testng.IResultMap;
import org.testng.ITest;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
public class TestingEdgeDriver {
ExtentReports extent;
ExtentTest test;
WebDriver driver;
ExtentTest Parent;
ExtentTest child1,child;
#BeforeMethod
public void setup(){
DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH-mm-ss");
String destDir = dateFormat.format(new Date());
ExtentSparkReporter esp=new ExtentSparkReporter(System.getProperty("user.dir")+"/ExtentReport/ExtentReports_"+destDir+"/SwarupExtentReport.html");
extent=new ExtentReports();
extent.attachReporter(esp);
extent.setAnalysisStrategy(AnalysisStrategy.SUITE);
}
#Test (testName="Chrome browser Testing")public void chromeBrowser() throws IOException{
/*extent.attachReporter(spark);
extent.createTest("chromeBrowser").log(Status.PASS , "This is logging event for the setup and it is passed");
extent.flush();*/
Parent=extent.createTest("CMO");
child1=Parent.createNode("Test1");
child=child1.createNode("Chrome browser Testing");
System.out.println("The tread value for Chrome browser is "+ Thread.currentThread().getId());
System.setProperty("webdriver.chrome.driver","E:\\chromedriver_win32 (2)\\chromedriver.exe");
driver=new ChromeDriver();
child.log(Status.PASS, "Chrome browser has opened",MediaEntityBuilder.createScreenCaptureFromPath(capture(driver)).build());
driver.get("https://www.icicibank.com");
child.log(Status.PASS,"Expected was its should open the bank website",MediaEntityBuilder.createScreenCaptureFromPath(capture(driver)).build());
child.log(Status.PASS, "Need to open the URL "+" http://www.icicibank.com");
driver.manage().window().maximize();
child.log(Status.PASS, "Test Case is passed",MediaEntityBuilder.createScreenCaptureFromPath(capture(driver)).build());
}
#AfterMethod
public void getResult(ITestResult result){
if(result.getStatus()==ITestResult.SUCCESS){
child.log(Status.PASS, "Test case is passed "+result.getStatus()+" "+result.getTestClass()+" "+result.getName());
child.log(Status.PASS, "Test case is passed "+result.getTestName());
}
if(result.getStatus()==ITestResult.FAILURE){
child.log(Status.FAIL, "Test case is failed at below location "+result.getThrowable());
}
extent.flush();
}
/*#Test public void operaTesting(){
System.out.println("The tread value for Opera browser is "+ Thread.currentThread().getId());
System.setProperty("webdriver.opera.driver","E:\\operadriver_win32\\operadriver_win32\\operadriver.exe");
Reporter.log("opera driver has been set",true);
driver=new OperaDriver();
driver.manage().window().maximize();
driver.get("https://www.irctc.co.in");
}
#Test public void FirefoxTesting(){
System.out.println("The tread value for Firefox browser is "+ Thread.currentThread().getId());
System.setProperty("webdriver.gecko.driver","E:\\gecodriver\\geckodriver-v0.29.0-win32\\geckodriver.exe");
Reporter.log("Gecko Driver has been set",true);
driver=new FirefoxDriver();
driver.manage().window().maximize();
Reporter.log("firefox driver has been initialsed",true);
driver.get("https://www.primevideo.com/");
}
#Test public void InternetExplorerTesting(){
System.out.println("The tread value for IE browser is "+ Thread.currentThread().getId());
System.setProperty("webdriver.ie.driver","E:\\IEDriverServer_Win32_3.4.0\\IEDriverServer.exe");
Reporter.log("IE driver has been set",true);
driver=new InternetExplorerDriver();
driver.manage().window().maximize();
driver.get("https://www.hotstar.com/in");
}*/
public static String captureBase64(WebDriver driver) throws IOException {
String encodedBase64 = null;
FileInputStream fileInputStream = null;
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
File Dest = new File("src/../BStackImages/" + System.currentTimeMillis()
+ ".png");
String errflpath = Dest.getAbsolutePath();
FileUtils.copyFile(scrFile, Dest);
try {
fileInputStream =new FileInputStream(Dest);
byte[] bytes =new byte[(int)Dest.length()];
fileInputStream.read(bytes);
encodedBase64 = new String(Base64.encodeBase64(bytes));
}catch (FileNotFoundException e){
e.printStackTrace();
}
return "data:image/png;base64,"+encodedBase64;
}
public static String capture(WebDriver driver) throws IOException {
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
File Dest = new File("src/../BStackImages/" + System.currentTimeMillis()
+ ".png");
String errflpath = Dest.getAbsolutePath();
FileUtils.copyFile(scrFile, Dest);
return errflpath;
}
}

Use this code in after method
if(result.getStatus()==result.FAILURE || result.getStatus()==result.SKIP) {
String screenshotPath = util.captureScreenshot(driver, result.getName());
result.setAttribute("screenshotPath", screenshotPath); //sets the value the variable/attribute screenshotPath as the path of the sceenshot
}
and add below code in buildtestnodes
if(result.getStatus()==result.FAILURE || result.getStatus()==result.SKIP) {
String screenshotPath=(String)
result.getAttribute("screenshotPath");
test.log(status, test.addScreenCapture(screenshotPath));
}

Use this following example is in Java
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
// Store the screenshot in current project dir.
String screenShot = System.getProperty("user.dir")+"\\Artifacts\\FileName.png";
// Call Webdriver to click the screenshot.
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
// Save the screenshot.
FileUtils.copyFile(scrFile, new File(screenShot));

Related

Unable to call the parameters from one class-method to another class-method

I have tried with the below code having two classes once is Class1-TestData and Method1-excel(),
And another call to access the parameters Class2-AdminLoginAction and Method2-Admin_Login().
Here is the problem with I need to call the string parameters like UID and PWD as I marked in the Screenshot attached. But the script showed some error and was unable to access it. So, How can I solve this problem, Am I going to the right approach or any other way? Please do need full as soon as possible.
Script image for two classes
import java.io.IOException;
import java.util.Date;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.*;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.reporter.ExtentSparkReporter;
public class AdminLoginAction extends TestData{
WebDriver d;
Date currentdate = new Date();
String Screenshotdate = currentdate.toString().replace(" ", "-").replace(":", "-");
ExtentSparkReporter spark = new ExtentSparkReporter("ExtentReport.html");
ExtentReports extent = new ExtentReports();
#Test()
public void Admin_Login() throws InterruptedException, IOException {
TestData excel = new TestData();
extent.attachReporter(spark);
ExtentTest test = extent.createTest("Launch browswer and access the WeClean Login page");
test.log(Status.PASS, "Launch browser success...!!!");
test.pass("Verified launching browser");
System.setProperty("webdriver.chrome.driver", "D:\\backup\\selenium\\chromedriver.exe");
d = new ChromeDriver();
d.manage().window().maximize();
d.get(URL);
Utils.CaptureScreenshot(d, Screenshotdate + "_Login.png");
d.findElement(By.id("loginUser")).sendKeys(UID);
d.findElement(By.id("password")).sendKeys(PWD);
d.findElement(By.id("loginButton")).click();
Thread.sleep(5000);
Utils.CaptureScreenshot(d, Screenshotdate + "_HomePage.png");
test.log(Status.PASS, "Admin Logged in Successful");
test.pass("Verified Admin logged in");
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.Test;
public class TestData{
public void excel() throws IOException {
String filePath = System.getProperty("user.dir")+"\\Inputfiles";
File file = new File(filePath + "\\TestData.xlsx");
FileInputStream inputStream = new FileInputStream(file);
XSSFWorkbook wb=new XSSFWorkbook(inputStream);
XSSFSheet sheet=wb.getSheet("Admin_inputs");
XSSFRow row2=sheet.getRow(1);
XSSFCell cell=row2.getCell(0);
double UID= cell.getNumericCellValue();
XSSFCell cell2 = row2.getCell(1);
String PWD = cell2.getStringCellValue();
}
You can try like this:
public class TestData {
double UID;
String PWD;
public void excel() throws IOException {
String filePath = System.getProperty("user.dir") + "\\Inputfiles";
File file = new File(filePath + "\\TestData.xlsx");
FileInputStream inputStream = new FileInputStream(file);
XSSFWorkbook wb = new XSSFWorkbook(inputStream);
XSSFSheet sheet = wb.getSheet("Admin_inputs");
XSSFRow row2 = sheet.getRow(1);
XSSFCell cell = row2.getCell(0);
UID = cell.getNumericCellValue();
XSSFCell cell2 = row2.getCell(1);
PWD = cell2.getStringCellValue();
}
}
In Admin_Login() method, am just printing UID and PWD, change the code according to your requirement:
public class AdminLoginAction extends TestData {
#Test()
public void Admin_Login() throws InterruptedException, IOException {
// TestData excel = new TestData(); // you don't need to create this object because you are already inheriting `TestData` class.
excel(); // before using UID and PWD you have to call excel() method.
System.out.println(UID);
System.out.println(PWD);
}
}

Selenium test in Java returns the error: Connection reset

I tried some selenium and it worked but stopped in the middle of the crawling process
these are codes:
import java.util.Date;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class Kream {
private static WebDriver driver;
public static final String WEB_DRIVER_ID = "webdriver.chrome.driver"; // 크롬 드라이버
public static final String WEB_DRIVER_PATH = "C://chromedriver.exe";
public static void main(String[] args) throws InterruptedException {
Kream krm = new Kream();
int rank = 0; // 순서 주려고 선언
System.setProperty(WEB_DRIVER_ID, WEB_DRIVER_PATH); // 운영체제 드라이버 설정
ChromeOptions options = new ChromeOptions(); // 옵션 쓰려고 객체화
options.addArguments("headless");
options.setPageLoadStrategy(PageLoadStrategy.NORMAL);
WebDriver driver = new ChromeDriver(options);
try {
String url = "https://kream.co.kr/search?category_id=34&sort=popular&per_page=40";
driver.get(url);
List<WebElement> el = driver.findElements(By.className("search_result_item"));
var stTime = new Date().getTime(); //현재시간
while (new Date().getTime() < stTime + 15000) { //30초 동안 무한스크롤 지속
Thread.sleep(500); //리소스 초과 방지
//executeScript: 해당 페이지에 JavaScript 명령을 보내는 거
((JavascriptExecutor)driver).executeScript("window.scrollTo(0, document.body.scrollHeight)", el);
for (WebElement element:el) {
System.out.println(++rank+". ");
System.out.print(element.findElement(By.tagName("img")).getAttribute("src"));
System.out.print("|"+element.findElement(By.className("brand")).getText());
System.out.print("|"+element.findElement(By.className("name")).getText());
System.out.print("|"+element.findElement(By.className("translated_name")).getText());
System.out.print("|"+element.findElement(By.className("amount")).getText());
System.out.print("|"+element.findElement(By.className("desc")).getText());
System.out.print("|"+element.findElement(By.className("express_mark")).getText());
System.out.println();
}
}
} finally {
driver.close();
driver.quit();
}
}
}
and return the error that says
onError
java.net.SocketException: Connection reset
at java.base/sun.nio.ch.SocketChannelImpl.throwConnectionReset(SocketChannelImpl.java:394)
at java.base/sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:426)
at io.netty.buffer.PooledByteBuf.setBytes(PooledByteBuf.java:258)
at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1132)
at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:357)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:151)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:722)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:658)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:584)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:496)
at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997)
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.base/java.lang.Thread.run(Thread.java:833)
current versions:
chromedriver version:103.0.5060.24
chrome version: 103.0.5060.114
I already tried to match the both versions so mismatching wouldn't be the reason probably.
Thank you for the answer in advance.
I made changes to your script and this was working fine as expected, please check the below!
If still you encountered any issues, kindly share complete logs for issue resolution.
package com.selenium;
import java.util.Date;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class Kream {
private static WebDriver driver;
public static final String WEB_DRIVER_ID = "webdriver.chrome.driver"; // 크롬 드라이버
public static final String WEB_DRIVER_PATH = "C://chromedriver.exe";
public static void main(String[] args) throws InterruptedException {
Kream krm = new Kream();
int rank = 0; // 순서 주려고 선언
System.setProperty(WEB_DRIVER_ID, WEB_DRIVER_PATH); // 운영체제 드라이버 설정
ChromeOptions options = new ChromeOptions(); // 옵션 쓰려고 객체화
options.addArguments("headless");
options.setPageLoadStrategy(PageLoadStrategy.NORMAL);
WebDriver driver = new ChromeDriver();
try {
String url = "https://kream.co.kr/search?category_id=34&sort=popular&per_page=40";
driver.get(url);
List<WebElement> el = driver.findElements(By.className("search_result_item"));
var stTime = new Date().getTime(); //현재시간
while (new Date().getTime() < stTime + 15000) { //30초 동안 무한스크롤 지속
Thread.sleep(500); //리소스 초과 방지
//executeScript: 해당 페이지에 JavaScript 명령을 보내는 거
((JavascriptExecutor) driver)
.executeScript("window.scrollTo(0, document.body.scrollHeight)", el);
for (WebElement element : el) {
System.out.println(++rank + ". ");
System.out.print(element.findElement(By.tagName("img")).getAttribute("src"));
System.out.print("|" + element.findElement(By.className("brand")).getText());
System.out.print("|" + element.findElement(By.className("name")).getText());
System.out.print("|" + element.findElement(By.className("translated_name")).getText());
System.out.print("|" + element.findElement(By.className("amount")).getText());
System.out.print("|" + element.findElement(By.className("desc")).getText());
// System.out.print("|" + element.findElement(By.className("express_mark")).getText());
/*The above tag with class name as express_mark doesn't have any text attribute and hence, this is commented out!*/
System.out.println();
}
}
} finally {
driver.close();
driver.quit();
}
}
}

How to use REST API mark tests as fail?

I use this https://www.browserstack.com/docs/automate/selenium/view-test-results/mark-tests-as-pass-fail as reference.
But I not able to let the REST API shows 'fail'. May I know what is my problem? I also attached the text logs, it shows 'Run JavaScript......'
, is it correct?
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.JavascriptExecutor;
public class test1 {
public WebDriver driver = null;
public static final String USERNAME = "";
public static final String AUTOMATE_KEY = "";
public static final String URL = "https://" + USERNAME + ":" + AUTOMATE_KEY + "#hub-cloud.browserstack.com/wd/hub";
#BeforeClass
public void setup() throws MalformedURLException {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("os", "Windows");
caps.setCapability("os_version", "10");
caps.setCapability("browser", "Chrome");
caps.setCapability("browser_version", "80");
caps.setCapability("name", "Test1");
driver = new RemoteWebDriver(new URL(URL), caps);
}
#Test (priority = 1)
public void test_1() {
driver.get("https://youtube.com");
String actualUrl = "https://www.youtube.com/";
String expectedUrl = "https://www.youtube.com/";
Assert.assertEquals(actualUrl, expectedUrl);
JavascriptExecutor jse = (JavascriptExecutor)driver;
if (actualUrl.equals(expectedUrl)) {
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \"passed\", \"reason\": \"Url matched!\"}}");
}
else {
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"failed\", \"reason\": \"Url not matched\"}}");
}
}
#Test (priority = 2)
public void test_2() {
driver.get("https://google.com");
String actualUrl = "https://www.google.com/";
String expectedUrl = "https://www.youtube1.com/";
Assert.assertEquals(actualUrl, expectedUrl);
JavascriptExecutor jse = (JavascriptExecutor)driver;
if (actualUrl.equals(expectedUrl)) {
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \"passed\", \"reason\": \"Url matched!\"}}");
}
else {
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"failed\", \"reason\": \"Url not matched\"}}");
}
}
#AfterClass
public void tearDown() {
driver.quit();
}
}
I tested with youtube and google url.
Assert.assertEquals(actualUrl, expectedUrl);
is not a soft assert , it will stop the command execution so the test won't reach the api line.
remove that from your tests or use soft assert .
SoftAssert softAssert = new SoftAssert();
softAssert.assertEquals(actualUrl, expectedUrl)

How to capture JavaScript errors with Selenium WebDriver using Java

I was wondering if there is a way to capture JavaScript errors on a page while running automated Selenium tests.
There is logs Beta version in WebDriver
driver.manage().logs().get(LogType.BROWSER);
Will give you the console content.
Then you can filter it using Level
LogEntries entries = driver.manage().logs().get(LogType.BROWSER);
entries.filter(Level.SEVERE);
And there is one that worked for me. Here it is.
public boolean isThereJSErrorOnThePage() {
Set<String> errorStrings = new HashSet<>();
errorStrings.add("SyntaxError");
errorStrings.add("EvalError");
errorStrings.add("ReferenceError");
errorStrings.add("RangeError");
errorStrings.add("TypeError");
errorStrings.add("URIError");
LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
for (LogEntry logEntry : logEntries) {
for (String errorString : errorStrings) {
if (logEntry.getMessage().contains(errorString)) {
LOGGER.error("Java Script error has been detected:");
LOGGER.error(new Date(logEntry.getTimestamp()) + " " + logEntry.getLevel() + " " + logEntry.getMessage());
return true;
}
}
}
return false;
}
If it does not work out of a box, try to add capabilities:
DesiredCapabilities desiredCapabilities = DesiredCapabilities.chrome();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.BROWSER, Level.ALL);
desiredCapabilities.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
driver = new ChromeDriver(desiredCapabilities);
you can try https://github.com/AutomatedOwl/chromedriver-js-errors-collector
it captures all the js errors and attaches them to allure report.
Try the below code for capturing the javascript error of webPage and let me know if it has helped you
import java.util.List;
import java.util.concurrent.TimeUnit;
import net.jsourcerer.webdriver.jserrorcollector.JavaScriptError;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class jsError {
WebDriver driver;
#BeforeTest
public void setup() throws Exception {
FirefoxProfile profile = new FirefoxProfile();
JavaScriptError.addExtension(profile);
driver = new FirefoxDriver(profile);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.com/2015/01/table-with-checkbox.html");
}
#Test
public void printPageErrors() throws Exception {
//Capture all errors and store them In array.
List<JavaScriptError> Errors = JavaScriptError.readErrors(driver);
System.out.println("Total No Of JavaScript Errors : " + Errors.size());
//Print Javascript Errors one by one from array.
for (int i = 0; i < Errors.size(); i++) {
System.out.println("Error Message : "
+ Errors.get(i).getErrorMessage());
System.out.println("Error Line No : "
+ Errors.get(i).getLineNumber());
System.out.println(Errors.get(i).getSourceName());
System.out.println();
}
}
}
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
import java.util.Date;
import java.util.logging.Level;
public class LoginTest {
private WebDriver driver;
#BeforeMethod
public void setPreConditions() {
WebDriverManager.chromedriver().setup();
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
LoggingPreferences loggingPreferences = new LoggingPreferences();
loggingPreferences.enable(LogType.BROWSER, Level.ALL);
capabilities.setCapability(CapabilityType.LOGGING_PREFS, loggingPreferences);
driver = new ChromeDriver(capabilities);
driver.manage().window().maximize();
driver.get("your_web_application_url");
// Put a wait condition if needed.
}
#Test
public void checkJavaScriptErrors() {
checkJavaScriptErrorsAreNotAvailable(Level.SEVERE);
}
#AfterMethod
public void quit() {
driver.quit();
}
private void printJavaScriptErrors() {
LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
for (LogEntry entry : logEntries) {
System.out.println(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());
}
}
private void checkJavaScriptErrorsAreNotAvailable(Level level) {
LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
SoftAssert softAssert = new SoftAssert();
for (LogEntry entry : logEntries) {
if (entry.getLevel().equals(level)) {
softAssert.fail(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());
}
}
softAssert.assertAll();
}
}
If you only need to print the JavaScript errors, you can use the method printJavaScriptErrors()
If you need to fail the test when there are JavaScript errors, you can use checkJavaScriptErrorsAreNotAvailable(Level level).
Since the SoftAssert is used, it will show all the relevant level errors when the test is failed.

How to call a method in every test which is in the base class and has a data provider in selenium

I have been trying to integrate browser stack with my selenium scripts. As part of which i have added desired capabilities in my 'getBrowser' method with data provider in the Base class. As i want to run my scripts in multiple browsers. The browsers list is in "getData" method in Base class.
How can i call the getBrowser method in my testcases and have the getData(browsers list) defined in only the base class. This what i have done and its not right. i have added my base class and the test script.
Base.getBrowser(Platform platform, String browserName, String browserVersion); this line is were i am stuck.
Any help would be appreciated. Thanks
package com.gale.precision.FundVisualizer.core;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.DataProvider;
import org.openqa.selenium.Platform;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class Base {
//public static WebDriver driver = null;
public static WebDriver driver;
public static String DriverPath = System.getProperty("user.dir") + "//" + "Drivers";
public static String DirectoryPath = System.getProperty("user.dir");
public static Properties prop = new Properties();
public static InputStream input = null;
public static final String USERNAME = "antonyprabhu1";
public static final String AUTOMATE_KEY = "xHRMpqxgD8sn3e3sr75s";
public static final String URL = "https://" + USERNAME + ":" + AUTOMATE_KEY + "#hub-cloud.browserstack.com/wd/hub";
#DataProvider(name = "EnvironmentDetails")
public static void getBrowser(Platform platform, String browserName, String browserVersion) throws MalformedURLException
{
DesiredCapabilities capability = new DesiredCapabilities();
capability.setPlatform(platform);
capability.setBrowserName(browserName);
capability.setVersion(browserVersion);
capability.setCapability("browserstack.debug", "true");
driver = new RemoteWebDriver(new URL(URL), capability);
try {
input = new FileInputStream(DirectoryPath + "//" + "config" + "//" + "app.properties");
prop.load(input);
} catch (IOException e) {
e.printStackTrace();
}
}
#DataProvider(name = "EnvironmentDetails", parallel = true)
public Object[][] getData() {
Object[][] testData = new Object[][] {
{
Platform.MAC, "chrome", "62.0"
}, {
Platform.WIN8,
"chrome",
"62.0"
}, {
Platform.WINDOWS,
"firefox",
"57"
}
};
return testData;
}
public static void closeBrowser() {
driver.quit();
}
}
package comparison;
import java.net.MalformedURLException;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Platform;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.gale.precision.FundVisualizer.core.Base;
import com.gale.precision.FundVisualizer.core.ExtentReport;
import com.gale.precision.FundVisualizer.pageObject.Comparison;
import com.gale.precision.FundVisualizer.pageObject.InvestmentsSearch;
#SuppressWarnings("unused")
public class AddedInvestmentDisplay extends ExtentReport {
/*============================================================================================================================
Test case : Verify that already selected Investments for comparison does not show up
======================================================================================*/
#Test(testName = "Comparison: Verify an already selected Investment for comparison does not show up in search")
public void verifyAddedInvestmentDisplay() throws InterruptedException, MalformedURLException {
//test = extent.createTest(Thread.currentThread().getStackTrace()[1].getMethodName());
Base.getBrowser(Platform platform, String browserName, String browserVersion);
InvestmentsSearch.login(Base.driver);
InvestmentsSearch.InvestmentsLink(Base.driver).click();
JavascriptExecutor jse = (JavascriptExecutor) Base.driver;
jse.executeScript("window.scrollBy(0,750)", "");
InvestmentsSearch.ViewResults(Base.driver).click();
for (int i = 0; i <= 2; i++)
{
try {
Comparison.firstCheckBox(Base.driver).click();
break;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
//Base.clickingStaleElements(Comparison.firstCheckBox(Base.driver));
//Comparison.firstCheckBox(Base.driver).click();
for (int i = 0; i <= 2; i++)
{
try {
Comparison.analyzeOrCompare(Base.driver).click();
break;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
Comparison.addInvestmentField(Base.driver).sendKeys("MFC027");
Comparison.firstSearchResult(Base.driver).click();
Comparison.addInvestmentField(Base.driver).sendKeys("MFC027");
Assert.assertEquals(Comparison.emptySearchResult(Base.driver).isDisplayed(), true);
}
#DataProvider(name = "EnvironmentDetails", parallel = true)
public Object[][] getData() {
Object[][] testData = new Object[][] {
{
Platform.MAC, "chrome", "62.0"
}, {
Platform.WIN8,
"chrome",
"62.0"
}, {
Platform.WINDOWS,
"firefox",
"57"
}
};
return testData;
}
#AfterClass
public void tearDown()
{
Base.closeBrowser();
}
}
I could resolve this issue by passing the parameters in the #test method
#Test(testName="Comparison: Verify adding an index in the comparison", dataProvider = "EnvironmentDetails",dataProviderClass = BrowsersDataProvider.class)
public void verifyAddingIndex(Platform platform, String browserName, String browserVersion) throws InterruptedException, MalformedURLException {
//test = extent.createTest(Thread.currentThread().getStackTrace()[1].getMethodName());
Base.getBrowser(platform,browserName,browserVersion);
InvestmentsSearch.login(Base.driver);
like

Categories

Resources