JBehave + TestNG + Selenium Grid - generate jbehave index.html report file for each seperate selenium node when using single jbehave story file - selenium-webdriver

I have a JBehave project in which need to integrate with TestNG and Selenium grid which using this, this and this code in github (sorry since i cant past the entire code so only showing the reference) i have done the JBehave + TestNG + Selenium Grid.
But my problem is when using single Story file to execute in different Selenium node the jbehave report index.html file is shown for any one node only. I want to have separate report for each node in a single or more jbehave report index.html file. I should not run with two story files and all, how can i show separate report for each and every Selenium node in a single jbehave report html file.
I know the jbehave use freemarker for their report generation but i have no clue on how to override this and show report for each selenium nodes. Any idea please share.
Thanks in Advance.

I dont think combining Jbehave and TestNG is a better idea. Jbehave supports the stories and using testng, there would be of no use, like grouping, parameter,etc. There are existing JunitStories class which works fine with Jbehave. If your using it for organizing your test results, you can use customized Allure reporting tool for jbehave (link). You could use Jbehave + Allure + Selenium Grid architecture.

Finally tried a way and found it to be an temporary solution for it now.
Create a String variable that gets the details in Story Runner Class.
RemoteWebDriver driver = (RemoteWebDriver) DriverManager.getDriver();
String hostname = hng.getHostName(driver.getSessionId());
String browserName = driver.getCapabilities().getBrowserName();
String browserVersion = driver.getCapabilities().getVersion();
Then pass that value to the Story Embedded class as shown below.
Embedder storyEmbedder = new StoryEmbedder(driver, browserName + "v" + browserVersion);
In the Story Embedded class assign that String value as shown below
private WebDriver driver;
private static String name;
public StoryEmbedder(WebDriver driver, String hostname) {
this.driver = driver;
this.name = hostname;
}
Then in the Configuration method inside the useStoryReporterBuilder function add the following code.
.withRelativeDirectory(name) //where 'name' is the String variable refer above step.
like the return will be as follows
return new MostUsefulConfiguration()
.useStoryControls(new StoryControls().doDryRun(false).doSkipScenariosAfterFailure(false))
.useStoryLoader(
new LoadFromClasspath(embedderClass))
.useStoryParser(
new RegexStoryParser(
examplesTableFactory))
.useStoryPathResolver(new UnderscoredCamelCaseResolver())
.useStoryReporterBuilder(
new StoryReporterBuilder().withCodeLocation(CodeLocations.codeLocationFromClass(embedderClass))
.withDefaultFormats().withPathResolver(new ResolveToPackagedName())
.withViewResources(viewResources).withReporters(new MyStoryReporter())
.withFormats(Format.CONSOLE, Format.TXT, Format.HTML, Format.XML).withFailureTrace(true)
.withFailureTraceCompression(true).withCrossReference(xref).withRelativeDirectory(name)).useParameterConverters(parameterConverters)
// use '%' instead of '$' to identify parameters
.useStepPatternParser(new RegexPrefixCapturingPatternParser("%"));
Now i can have two folders based on browser and browser version.
If you guys have any better answer please do help by posting it.
Thanks in Advance.

Related

Is there any way we can control the size of the image attached in testNG report?

I have been trying to capture Screenshots for Passed/Failed test in my testNG reports captured in Test-Output folder. I have succeeded in doing so, however I want a bit more improvement in the way things are right now.
The Screenshot is displayed in full size and covers the whole screen, I would like to make it appear smaller in report and then user can click on it to see the image maximized.
I am capturing the Screenshot with the help of Reporter.log(ScreenshotPath) in the static TakeScreenshot method which is a part of finally block in my test case.
public static void TakeScreenshotMethod() throws IOException {
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
File ScreenshotName = new File(UtilityClass.ScreenshotPathCustomerPortal + count +".jpg");
FileUtils.copyFile(scrFile, ScreenshotName);
String filePath = ScreenshotName.toString();
String path = "<img src=\"file://" + filePath + "\" alt=\"\"/>";
Reporter.log(path);
count++;
}
I would like to control the size of the image being displayed in my report.
You can a bit modify the <img> tag by adding a style like normal html with some property (width, height), like this:
String path = "<img src=\"file://" + filePath + "\" alt=\"\" style=\"width: 230px; height :500px;\" />";
If you are asking for this behavior in the default TestNG reports, then the answer is NO its not possible. TestNG reports are agnostic to the content that gets embedded in them. So TestNG doesn't know if an image or if a video for that matter is being embedded in it. So it also doesn't different on how to get them rendered.
If you would like to control these behaviors, you should do one of the following:
Build your own custom reporter that has this behavior by implementing the org.testng.IReporter interface and then wiring in this listener via the <listeners> tag or via #Listeners interface or via a Service Provider Interface mechanism. You can learn about wiring in listeners in general from my blog post here.
You can explore some of the reporting solutions that exist already out there such as allure reports (or) extent reports etc., and see if one of them fits your requirement and use them instead.
TestNG doesn't have any role to play in this.

Jmeter WebDriverSampler fail with Chromedriver headless

I have some tests with WebDriverSampler in Jmeter that work correctly with chromedriver. It is a selenium script that opens a web page and checks that it contains a series of elements. Everything works right until I've tried with the chromedriver headless option.
In this case I get the exception "Expected condition failed: waiting for presence of element located by: By.xpath: ..." as if that element did not exist yet to be loaded. I do not know what can happen, because if I stop using the headless option, if everything works correctly and find the element that really exists.
This is an example of code used(it works without the headless option):
var wait = new support_ui.WebDriverWait(WDS.browser, 30);
var conditions = org.openqa.selenium.support.ui.ExpectedConditions
WDS.sampleResult.sampleStart();
WDS.sampleResult.getLatency();
WDS.browser.get('http://mi-app/');
try{
wait.until(conditions.presenceOfElementLocated(pkg.By.xpath('/ruta_de elemento_existente')));
WDS.log.info('OK')
}catch(e){
WDS.sampleResult.setSuccessful(false);
WDS.sampleResult.setResponseMessage('Fail');
WDS.log.error(e.message)
}
try{
wait.until(conditions.presenceOfElementLocated(pkg.By.xpath('/ruta_de elemento2_existente')));
WDS.log.info('OK2')
}catch(e){
WDS.sampleResult.setSuccessful(false);
WDS.sampleResult.setResponseMessage('Fail2');
WDS.log.error(e.message)
}
WDS.sampleResult.sampleEnd();
I hope someone can help me with this problem, because I need to use the headless option. Thank you very much for your time.
You can print the page source to jmeter.log file by using the following function:
WDS.log.info(WDS.browser.getPageSource())
Or even save it into a separate file like:
org.apache.commons.io.FileUtils.writeStringToFile(new java.io.File('test.html'), WDS.browser.getPageSource())
Or take screenshot on failure like:
WDS.browser.getScreenshotAs(org.openqa.selenium.OutputType.FILE).renameTo(new java.io.File('test.png'))
Check out The WebDriver Sampler: Your Top 10 Questions Answered article for more information.
Also be aware that if the machine where you run your Selenium tests doesn't have GUI you can still normally launch browsers using i.e. Xvfb on Linux or under Local System account on Windows

How can enroll student, using unique application number for run Multiple browsers like chrome, firefox in selenium webdriver

Scenario: Unique application number(Zee1106) using to enroll students and running testng for Multiple browsers(parallel) like chrome, firefox in selenium webdriver.
In the above scenario, I have run the test suite,first browser(chrome) enrolled successfully and the next browser(firefox) is not enrolled. Because already enrolled alert was coming. In this scenario, How can i enroll students using unique application number for multiple browser in webdriver.
Thanks,
Vairamuthu
There are quite a few ways to achieve this. One easiest way is to have the "Application Numbers" stored as a comma separated values in your test data sheet and use each for the respective browsers. Example:
//Assume applicationNo is stored as a comma separated value in test data. Something like this
String applicationNo="zee1106, zee1107, zee1108"; //please read these data from test data sheet
String[] unquieAppNo=applicationNo.split(",");
//get the browserName
Capabilities caps = ((RemoteWebDriver) driver).getCapabilities();
String browserName = caps.getBrowserName();
//if the browser name is chrome then use one of the application id and so on for each browser.
if(browserName.equalsIgnoreCase("chrome")){
driver.findElement(By.id("<employee app number>")).sendKeys(unquieAppNo[0]);
}else if (browserName.equalsIgnoreCase("firefox")) {
driver.findElement(By.id("<employee app number>")).sendKeys(unquieAppNo[1]);
}else{ //any other browser
driver.findElement(By.id("<employee app number>")).sendKeys(unquieAppNo[2]);
}
It is hard to tell with no code posted at all. Which Language you are working on?Please post the way you instantiate you Webdriver. From your description, I'm guessing that you are using something like this (static):
public static WebDriver driver;
Whilst you need a different WebDriver instance everytime:
public WebDriver driver;

Allure steps descriptions cut in the report

I am using Allure framework to generate reports for our tests. I annotated methods of my tests with #Step annotation from alllure, e.g.:
#Step("Openining page: {0}")
public void beforeNavigateTo(String url, WebDriver driver) {
However, in the report Allure steps are cut in the middle, e.g.:
[16:51:42.647] Openining page: https://x.yyy.com/simplesaml/saml2/idp/SSOService.php?spentityid=https://neta...
I would like to see full step description so I can reproduce it.
How can I do it?
You can use allure.max.title.length system property to change maximum step title length.

How does JBehave work with Java?

I have a task for work that I can't seem to complete because I don't fully get the toolset at hand. I am supposed to use JBehave along with Selenium Web Driver to be able to add a certain book to a wishlist on an amazon account. I have a given story and I supposed to use the previously mentioned tools to be used for "learning purposes". I understand that JBehave is a framework for BDD. So, I have some sort of story that I want to test. However, what confuses me is the configuration and "step definition" part which I don't really get. My problem is I don't really understand how to get all those parts working together. Where does Selenium WebDriver fit in the equation? Note that I have used Selenium with Java and that was a breeze.
I want to give you an example of a story in gherkin format and I would appreciate any insights on this subject matter, maybe a clarification on how all the pieces fit together.
Given user <username> with password <password> has a valid amazon.com account
And has a wish list
And wants to purchase book <title> at a later date
When a request to place the book in the wish list is made
Then the book is placed in the wish list
And the book <title> appears in the wish list when <username> logs in at a later date.
Now that you have your Story you need your Steps. The steps are the Java code that will be executed by the story. Each line in your story gets mapped to a Java Step. See the documentation on Candidate Steps.
Here is a really simple stab at what your story and steps might look like. But it should at least give you an idea of how the stories and steps tie together.
Story
Given user username with password passcode is on product page url
When the user clicks add to wish list
Then the wish list page is displayed
And the product title appears on the wish list
Steps
public class WishlistSteps {
WebDriver driver = null;
#BeforeScenario
public void scenarioSetup() {
driver = new FirefoxDriver;
}
#Given("user $username with password $passcode is on product page $url")
public void loadProduct(String username, String passcode, String url) {
doUserLogin(driver, username, passcode); // defined elsewhere
driver.get(url);
}
#When("the user clicks add to wishlist")
public void addToWishlist() {
driver.findElement(By.class("addToWishlist")).click();
}
#Then("the wish list page is displayed")
public void isWishlistPage() {
assertTrue("Wishlist page", driver.getCurrentUrl().matches(".*/gp/registry/wishlist.*"));
}
#Then("the product $title appears on the wish list")
public void checkProduct(String title) {
// check product entries
// assert if product not found
}
#AfterScenario
public void afterScenario() {
driver.quit();
}
}
Next you will need a runner which actually finds and runs the stories. See the documentation on Running Stories. Below is a very simple runner that would run as a JUnit test.
Runner
public class JBehaveRunner extends JUnitStories {
public JBehaveRunner() {
super();
}
#Override
public injectableStepsFactory stepsFactory() {
return new InstanceStepsFactory( configuration(),
new WishlistSteps() );
}
#Override
protected List<String> storyPaths() {
return Arrays.asList("stories/Wishlist.story");
}
}
This runner would then be executed as a JUnit test. You can configure your IDE to run it, or use Maven or Gradle (depending on your setup).
mvn test
I have found that the pages below provide a great overview of the whole setup. And the examples from the JBhave repository are useful as well.
Automated Acceptance-Testing using JBehave
JBehave Configuration Tutorial
JBehave Examples

Resources