How do I add a screenshot to an Allure report? - junit5

I have a Selenide+Java project which uses allure reporting. I am using the TestExecutionListener to handle browser setup, but I am having some extreme difficulty figuring out how to add screenshots to the report on a test failure.
I'm using
<dependency>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-junit5</artifactId>
<version>2.13.0</version>
<scope>test</scope>
</dependency>
And in my Listener code:
public class BrowserListener implements TestExecutionListener {
Browser browser;
#Override
public void executionStarted(TestIdentifier testIdentifier) {
if(testIdentifier.isTest()) {
browser = new Browser();
browser.openBrowser();
}
}
#Override
public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) {
//code here to log failed execution - ideally would like to put screenshot on failure
browser.close();
}
}
How do I add a screenshot to an Allure report using Selenide/Junit 5?

I managed to get this working by adding the following:
import com.codeborne.selenide.Configuration;
import com.codeborne.selenide.Selenide;
import com.codeborne.selenide.WebDriverRunner;
import org.apache.commons.io.FileUtils;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.openqa.selenium.NoSuchSessionException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import java.io.File;
import java.io.IOException;
import static com.codeborne.selenide.Selenide.open;
import static com.codeborne.selenide.WebDriverRunner.getSelenideDriver;
import static io.qameta.allure.Allure.addAttachment;
#Override
public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) {
if (testExecutionResult.getStatus().equals(TestExecutionResult.Status.FAILED)) {
try {
File screenshotAs = ((TakesScreenshot) getSelenideDriver().getWebDriver()).getScreenshotAs(OutputType.FILE);
addAttachment("Screenshot", FileUtils.openInputStream(screenshotAs));
} catch (IOException | NoSuchSessionException e) {
// NO OP
} finally {
WebDriverRunner.getSelenideDriver().getWebDriver().quit();
}
}
}

Related

I am getting io.cucumber.java.InvalidMethodSignatureException in Cucumber Java

My Feature file -
Feature: Open google page
#Sanity
Scenario: Open google search
Given User open google search
Then enter text "hi" in search bar
And close the browser
###########################################################################
Page Object class -
package pageObjects;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class GoogleObjects {
public WebDriver ldriver;
public GoogleObjects(WebDriver rdriver) {
ldriver = rdriver;
PageFactory.initElements(rdriver, this);
}
#FindBy(name = "q")
#CacheLookup
WebElement search;
public void Search(String searchTxt) {
search.sendKeys(searchTxt);
search.sendKeys(Keys.DOWN, Keys.ENTER);
}
public void btnClick() {
ldriver.close();
}
}
############################################################################
StepDifinition class -
package stepDefinitions;
import org.openqa.selenium.WebDriver;
import io.cucumber.java.en.*;
import pageObjects.GoogleObjects;
public class GoogleSearch {
public WebDriver driver;
#Given("^User open google search$")
public void user_open_google_search() throws Throwable {
driver.get("https://www.google.com");
}
#Then("^enter text \"([^\"]*)\" in search bar$")
public void enter_text_something_in_search_bar(String TxT) throws Throwable {
GoogleObjects gb = new GoogleObjects(driver);
gb.Search(TxT);
}
#And("^close the browser$")
public void close_the_browser() throws Throwable {
GoogleObjects gb = new GoogleObjects(driver);
gb.close();
}
}
##########################################################################
Test Runner class -
package runner;
import org.junit.runner.RunWith;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
#RunWith(Cucumber.class)
#CucumberOptions(
features = {".//Features/google.feature"},
glue = {"stepDefinitions"},
monochrome=true,
tags = "#Sanity",
plugin = {"pretty","html:target/reports.html" ,
"json:target/reports.json"}
)
public class testRunner {
}
######################################################################
hooks class -
package stepDefinitions;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import io.cucumber.java.After;
import io.cucumber.java.Before;
public class hooks {
WebDriver driver;
#Before
public WebDriver setUp() throws IOException {
System.setProperty("webdriver.chrome.driver","*:\\****\\***\\Drivers\\chromedriver.exe");
driver = new ChromeDriver();
return driver;
}
#After
public void tearDown() {
driver.quit();
}
}
###########################################################
I created a Maven project with cucumber framework and wrote a feature file, step
definitions, test runner and hooks file.
When I run my test runner I am getting "io.cucumber.java.InvalidMethodSignatureException", when I import io.cucumber.java.before/after but my test is running when I import from junit, but #before and #after doesn't work in cucumber if we import from juint. I not understanding why I am getting InvalidMethodSignatureException.
I tried providing order=0 for #Before annotation. It doesn't work
Above is the code, please help me.
You get this issue because methods annotated with io.cucumber.java.Before have to be void.
In your example it returns WebDriver. This is why you get InvalidMethodSignatureException.

getWindowHandle() throws error message "Nullpointerexception"

this is a simple selenium function that is trying to get a windowhandle.
right at that statement it throws" Nullpointerexception"
import static org.junit.Assert.*;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class WindowHandles {
WebDriver achromeDriver;
String abaseUrl;
public void setUp() throws Exception {
abaseUrl = "http://letskodeit.teachable.com/pages/practice";
System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\ChromeDirver\\chromedriver.exe");
achromeDriver = new ChromeDriver();
achromeDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
achromeDriver.manage().window().maximize();;
System.out.println("setup completed");
}
#Test
public void test() {
try{
String aparentwindowHandle = achromeDriver.getWindowHandle();
System.out.println("the parent window handle is "+ aparentwindowHandle);
WebElement aopenwindowelementbutton = achromeDriver.findElement(By.id("openwindow"));
aopenwindowelementbutton.click();
String achildwindowhandle = achromeDriver.getWindowHandle();
System.out.println("the child window handle is: " + achildwindowhandle);
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
A bit more details about your usecase and your observation would have helped us to debug the issue in a better way. However, it seems as you are using the junit framework and in-absence of any of the annotations the setUp() method is never executed.
As the test() method is annotated with #Test the program reaches there with achromeDriver as Null
Solution
A quick solution would be to add #Before annotation to setUp() method as follows:
#Before
public void setUp() throws Exception {
abaseUrl = "http://letskodeit.teachable.com/pages/practice";
System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\ChromeDirver\\chromedriver.exe");
achromeDriver = new ChromeDriver();
achromeDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
achromeDriver.manage().window().maximize();;
System.out.println("setup completed");
}

How to extract only text from a document(it may be a pdf,word or any other) using apache tika?

I am trying to extract only text from a pdf or word file that can contain images and other things as well using apache tika .How can I get only text from them?
What are the dependencies that i need in tika?
This the java code i have written:
package secondp;
import java.io.File;
import org.apache.tika.Tika;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.pdf.PDFParser;
import org.apache.tika.sax.BodyContentHandler;
import org.apache.tika.Tika;
import org.xml.sax.SAXException;
public class trial {
public static void main(final String[] args) {
try {
System.out.println(trial.convert("test.pdf"));
} catch (final Exception e) {
e.printStackTrace();
}
}
public static String convert(final String fileName) throws IOException, SAXException, TikaException {
try(final FileInputStream inputstream = new FileInputStream(new File(fileName))) {
final BodyContentHandler handler = new BodyContentHandler();
new PDFParser().parse(inputstream, handler, new Metadata(), new ParseContext());
return handler.toString().trim();
}
}
}

JUnit Parallel Testing

I'm trying to run a piece of code that I found online to run JUnit test in parallel but the only thing I've modified is the URL to hit my local host. Problem is I'm constantly getting the following error and even though I've setup selenium grid many times and know how to set paths etc. I don't know how to fix this one.
org.openqa.selenium.WebDriverException: The path to the driver executable must be set by the webdriver.ie.driver system property; for more information, see http://code.google.com/p/selenium/wiki/InternetExplorerDriver.
here's the code
package AutomationFrameWork;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.runners.Parameterized;
import org.junit.runners.model.RunnerScheduler;
public class Parallelized extends Parameterized {
private static class ThreadPoolScheduler implements RunnerScheduler {
private ExecutorService executor;
public ThreadPoolScheduler() {
String threads = System.getProperty("junit.parallel.threads", "16");
int numThreads = Integer.parseInt(threads);
executor = Executors.newFixedThreadPool(numThreads);
}
#Override
public void finished() {
executor.shutdown();
try {
executor.awaitTermination(10, TimeUnit.MINUTES);
} catch (InterruptedException exc) {
throw new RuntimeException(exc);
}
}
#Override
public void schedule(Runnable childStatement) {
executor.submit(childStatement);
}
}
public Parallelized(Class<?> klass) throws Throwable {
super(klass);
setScheduler(new ThreadPoolScheduler());
}
}
package AutomationFrameWork;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.LinkedList;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Platform;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
#RunWith(Parallelized.class)
public class JUnitParallel {
private String platform;
private String browserName;
private String browserVersion;
private WebDriver driver;
#Parameterized.Parameters
public static LinkedList<String[]> getEnvironments() throws Exception {
LinkedList<String[]> env = new LinkedList<String[]>();
env.add(new String[]{Platform.WINDOWS.toString(), "chrome", "27"});
env.add(new String[]{Platform.WINDOWS.toString(),"firefox","20"});
env.add(new String[]{Platform.WINDOWS.toString(),"ie","11"});
env.add(new String[]{Platform.WINDOWS.toString(),"safari","5.1.7"});
//add more browsers here
return env;
}
public JUnitParallel(String platform, String browserName, String browserVersion) {
this.platform = platform;
this.browserName = browserName;
this.browserVersion = browserVersion;
}
#Before
public void setUp() throws Exception {
DesiredCapabilities capability = new DesiredCapabilities();
capability.setCapability("platform", platform);
capability.setCapability("browser", browserName);
capability.setCapability("browserVersion", browserVersion);
capability.setCapability("build", "JUnit-Parallel");
capability.setCapability("InternetExplorerDriverServer.IE_ENSURE_CLEAN_SESSION",true);
System.setProperty("webdriver.ie.driver",
"C:\\Users\\path to driver\\IEDriverServer.exe");
driver = new RemoteWebDriver(
new URL("http://localhost:7777".concat("/wd/hub")),
capability
);
}
#Test
public void testSimple() throws Exception {
driver.get("http://www.google.com");
String title = driver.getTitle();
System.out.println("Page title is: " + title);
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("BrowserStack");
element.submit();
driver = new Augmenter().augment(driver);
File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(srcFile, new File("Screenshot.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
#After
public void tearDown() throws Exception {
driver.quit();
}
}

Selenium javax.imageio.IIOException: Can't read input file

I am facing this error for my Selenium script...
I am trying to generate the pdf evidence of the testing i am doing and while running my script i am getting this error
My Code:
package test;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.googlecode.seleniumjavaevidence.report.GenerateEvidenceReport;
import com.googlecode.seleniumjavaevidence.selenium.SeleniumEvidence;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.*;
public class NewTest {
WebDriver driver = new FirefoxDriver();
List<SeleniumEvidence> evidence ;
String exception ;
#BeforeTest
public void setUp() throws Exception {
driver.get("https://www.google.co.in");
}
#Test
public void testLogin() throws Exception {
try {
// driver.findElement(By.id("lst-ib"));
evidence.add(new SeleniumEvidence("get evidence from here",((TakesScreenshot) driver).getScreenshotAs(OutputType.BASE64)));
} catch (Exception e) {
evidence.add(new SeleniumEvidence("Unexpected error", ((TakesScreenshot) driver).getScreenshotAs(OutputType.BASE64)));
exception = e.fillInStackTrace().getMessage();
} finally {
GenerateEvidenceReport.generatePDFEvidence(evidence, "null", null, null, exception);
}
}
}
https://code.google.com/p/selenium-java-evidence/wiki/HowToUse?wl=pt-BR
Seems to suggest:
A imageio.IOException will always appears if you don't put the images
in the correct path on your code. It's not a problem from
selenium-java-evidence... Revise your code and put all images in the
correct path.