How to use REST API mark tests as fail? - java

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)

Related

How do I click on this autoComplete countryName?

This is the link I wanted to automate. But I am not being able to click on countryName. I wanted to enter "na" in the searchField and then click on "Nepal" using the list attribute i.e list.get(i).click() but I have not been able to. Please help
package autoComplete;
import java.time.Duration;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
public class AutoCompleteCountry {
WebDriver driver;
String url = "https://practice-cybertekschool.herokuapp.com/autocomplete";
By countryField = By.id("myCountry");
By countryList = By.xpath("//input[#type='hidden']");
#BeforeTest
public void getUrl() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));
driver.get(url);
}
#Test
public void autoCompleteTest() throws InterruptedException {
driver.findElement(countryField).sendKeys("N");
List<WebElement> listOfCountry = driver.findElements(countryList);
// driver.findElement(nepalClick).click();
for (int i = 0; i < listOfCountry.size(); i++) {
// System.out.println(list);
String searchText = listOfCountry.get(i).getAttribute("value");
System.out.println(searchText);
if (searchText.equals("Nepal")) {
listOfCountry.get(i).click();
}
}
}
#AfterTest
public void tearDown() throws InterruptedException {
Thread.sleep(5000);
driver.quit();
}
}
This is the error screenshot:
Error Screenshot
You needn't iterate through the whole list if you just want to click the "Nepal" option. Does the following help at all?
driver.findElement(By.CSS_SELECTOR, 'input[value="Nepal"]').click()
you can use Webdriver wait with a customExpected Condition like this below
Instead of using implicit wait use WebDriverwait for Fluentwait
private static ExpectedCondition<Boolean> waitForDropdownElement(By by, String value) {
return ( driver -> {
List<WebElement> listOfCountry = driver.findElements(by);
for (int i = 0; i < listOfCountry.size(); i++) {
String searchText = listOfCountry.get(i).getText();
if (searchText.equals(value)) {
listOfCountry.get(i).click();
return true;
}
}
return false;
});
}
Also modified below locator like this, as you will get element not clickable exception on using that
By countryList = By.xpath("//div[#id='myCountryautocomplete-list']//div");
Full code below which is working for me
import io.github.bonigarcia.wdm.WebDriverManager;
import java.time.Duration;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class AutoCompleteCountry {
WebDriver driver;
String url = "https://practice-cybertekschool.herokuapp.com/autocomplete";
By countryField = By.id("myCountry");
By countryList = By.xpath("//div[#id='myCountryautocomplete-list']//div");
#BeforeTest
public void getUrl() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));
driver.get(url);
}
#Test
public void autoCompleteTest() throws InterruptedException {
driver.findElement(countryField).sendKeys("N");
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(60));
wait.until(waitForDropdownElement(countryList, "Nepal"));
}
#AfterTest
public void tearDown() throws InterruptedException {
Thread.sleep(5000);
driver.quit();
}
private static ExpectedCondition<Boolean> waitForDropdownElement(By by, String value) {
return (driver -> {
List<WebElement> listOfCountry = driver.findElements(by);
for (int i = 0; i < listOfCountry.size(); i++) {
String searchText = listOfCountry.get(i).getText();
if (searchText.equals(value)) {
listOfCountry.get(i).click();
return true;
}
}
return false;
});
}
}

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();
}
}
}

xpath and id is not working of a particular page of mobile app

I am trying to automate a mobile app.I am using appium java.While automating,xpath and id of a particular screen is not working.All the screens are working fine but it stucks on a particular page in which none of the id and xpath are working.Deals section are not working.
No error are shown.
here is the code
package tests;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
public class BaseClass {
AppiumDriver<MobileElement> driver ;
#BeforeTest
public void setup() {
try {
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability("deviceName", "SM MO15G");
cap.setCapability("udid", "R9ZNA0374XT");
cap.setCapability("platformName", "Android");
cap.setCapability("platformVersion", "11.0");
//cap.setCapability("ignoreHiddenApiPolicyError", "true");
cap.setCapability("appPackage", "com.tringapps.everest.marketplace");
cap.setCapability("appActivity", "com.everest.MainActivity");
//cap.setCapability("appWaitForLaunch", "false");
cap.setCapability("automationName" ,"uiautomator2");
cap.setCapability("skipuUnlock", "false");
URL url = new URL("http://127.0.0.1:4723/wd/hub");
driver = new AppiumDriver<MobileElement>(url,cap);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
Thread.sleep(3000);
MobileElement skip = driver.findElement(By.xpath("//android.view.ViewGroup[#content-desc=\"next_button_onboarding\"]"));
skip.click();
Thread.sleep(3000);
MobileElement skipcaliber = driver.findElement(By.xpath("//android.view.ViewGroup[#content-desc=\"skip_button_onboarding\"]"));
skipcaliber.click();
Thread.sleep(10000);
MobileElement deals = driver.findElement(By.xpath("//android.widget.TextView[#content-desc=\"home-dealOfTheDay-seeMore\"]"));
deals.click();
}
catch(Exception exp) {
System.out.println("cause is :" +exp.getCause());
System.out.println("Message is :" + exp.getMessage());
exp.printStackTrace();
}
}
#Test
public void sampleTest() {
System.out.println("I am inside the sample test");
}
#AfterTest
public void teardown() {
}
}

How to attach screenshot to Extent Report in java selenium

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));

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.

Categories

Resources