Parsing Cucumber Feature Files into JSON or NDJSON using Java with Cucumber 7.6.0 or Gherkin-Java 24.0.0 - automation

Background of the Question:
Earlier Issue:
I have already asked this question in the past with attached thread below but the use case was different in that case. I just needed a way to print the JSON into stdout using (NodeJS) cucumber-js. I used Native Cucumber parsing using cucumber CLI commands as per (https://github.com/cucumber/cucumber-js/blob/main/docs/formatters.md).
How to convert cucumber gherkin feature files into JSON or AST format?
Current Issue:
I want to Parse Gherkin Feature Files to JSON using Java. These JSON files would be later interpreted and rendered into a front end dashboard where we could filter feature files based on tags, scenarios and text match for features.
I came through React cucumber (https://github.com/cucumber/react-components) Library but this is more of a JS Based solution and I need to process the Parsed Feature file JSON before passing to the view layer.
Can someone please provide the code snippet for parsing Gherkin Feature file to JSON in Java. I went through below threads but all are using deprecated code.
Cucumber feature file - parsing to an object
How to parse Cucumber feature file in java or groovy?
and a few more.
Please provide an example code snippet if possible. Thanks in Advance :)

You can use io.cucumber.junit.Cucumber for reference. Briefly in your case you would do the following:
public class Main {
public static void main(String[] args){
RuntimeOptions runtimeOptions = new CucumberPropertiesParser()
.parse(CucumberProperties.fromSystemProperties())
.addDefaultFeaturePathIfAbsent()
.build();
SynchronizedEventBus bus = synchronize(new TimeServiceEventBus(Clock.systemUTC(), UUID::randomUUID));
FeatureParser parser = new FeatureParser(bus::generateId);
Supplier<ClassLoader> classLoader = ClassLoaders::getDefaultClassLoader;
FeaturePathFeatureSupplier featureSupplier = new FeaturePathFeatureSupplier(classLoader, runtimeOptions,
parser);
List<Feature> features = featureSupplier.get();
ObjectMapper objectMapper = new ObjectMapper();
System.out.println(objectMapper.writeWithDefaultPrettyPrinter().writeValueAsString(features));
}
}

Related

Karate Framework- is there a way to use my own application.properties file or replace individual properties with my own values during execution? [duplicate]

We are trying to co exist with another java project which uses Webdriver etc. As part of this we would like to re use the same .properties file that is being used by other project for our configuration etc. Could some one guide us on reading from .properties file in Karate DSL.
There is nothing built in to Karate - but the solution for you is clear, write a simple Java utility to read a properties file - or since it is so simple, you should be able to do this even in JS, in the karate-config.js itself.
And also refer this: https://github.com/intuit/karate#calling-java
I haven't tested the below code, but you get the idea:
* def stream = read('classpath:myfile.properties')
* def props = new java.util.Properties()
* eval props.load(stream)

Grails compile .gsp to .html from gradle/command line

Is there any way that I can compile a gsp view into an html given a provided model from a groovy script without having to run all the Grails application?
The use case is that due to client demands we have to use Javascript/jQuery to create the front-end of the application. We've already had the architecture definition, but we're having issues creating integration front-end tests since our front-end composes of .gsp, javascript and css, all componentized.
For instance: Button may have a .gsp a .js and a .css associated to it.
Ideal solution to create front-end component integration tests: Have the .gsp compiled into html before the tests run so we can run the assertions in the *.test.js files. Since we don't need database, services or other instances to compile the .gsp, no need for the application to be running, avoiding the time to boot up the app.
Thanks in advance!
Next code should help you.
File gspFile = new File(BuildSettings.BASE_DIR, "grails-app/view/path/to/view/${viewName}.gsp")
This code will find gsp, you can find it by absoluteUrl
if(gspFile.exists()) {
def model = model((Class)scaffoldValue)
def viewGenerator = new GStringTemplateEngine()
Template t = viewGenerator.createTemplate(gspFile)
def contents = new FastStringWriter()
t.make(model.asMap()).writeTo(groovy.lang.Writer)
}
Writer you should find by yourself, think that it can be a stream to the file.
Didn't test it, but it should work :)

I want to run each .feature file as single TestNG test using Karate?

I want to run each .feature file as single TestNG test using Karate, how can I do it?
We are using karate to automate REST API's. We have custom listener which will record status of each TestNG test and other information to postgress DB.
One more way running by tags:
#CucumberOptions(tags = { "#getVersion" })
public class GetVersionTest extends KarateRunner {
}
Feature File:
#getVersion
Feature: Testing Rest API with Karate and Java
Scenario:
Given url 'https://......'
When method get
Then status 200
And match response contains '{version= x.xx.x}'
Did you try using the Karate TestNG support ? The documentation has details on how to use: https://github.com/intuit/karate#running-with-testng
As the developer of Karate I actually strongly recommend that teams don't use TestNG. My suggestion is that you use the new 'hooks' feature to call your custom Java code from Karate directly and you won't depend on TestNG or even JUnit.
If you still need a custom way of running, the TestNG support is actually a single class: KarateRunner.java. I really don't know if it runs each feature as a TestNG test or not since I am not a TestNG expert. But you should be able to create your own version of this Java code that does what you want and maybe contribute it back to the project.

Logging Messages from Java Class back to the Karate Report

We have a scenario where we have to post a json request and then validate few actions in the UI. So we have a karate feature file which hits a request and after that we are invoking a java class from within the feature file. The java class would run the Selenium Webdriver test of us. In the java methods we have few Assertions/Info Messages which we would like to log back to the Karate Reports.
Is there a way in Karate with which we can write these messages from my Java Class to the Karate Test Reports?
If you use the Karate parallel runner it is designed to collect anything logged to package com.intuit.karate, which will then appear in the cucumber-html-report.
So you can try using the same slf4j Logger - and it might work.
A better way might be to just return a Map back to Karate from your Java code, with all the information you need to log. Then all you need to do is use the print keyword. I would recommend this approach actually, it should be less complicated and it does not assume that you are using the Cucumber HTML reporting. You could even do Karate asserts with the match keyword on the JSON that you get, refer to this example: dogs.feature.
We did try logging back to “com.intuit.karate” as shown below and its logging to the ‘overview-features.html’ report
Logger in Java class :
private static final Logger logger = LoggerFactory.getLogger("com.intuit.karate");
However we made an observation that if an exception is thrown from the java class the exception would appear first and then followed by all the information that is logged, both looks to exist as a different piece in the report.
For e.g
This is sample method with logger in the java class which i am invoking from the feature file
public void myTestMethod() {
logger.info("Starting Test");
logger.info("Setting path of chrome driver");
System.setProperty("webdriver.chrome.driver", "chromedriver.exe"); //driver doesnt exist in this path
logger.info("invoking chrome"); // we would expect the exception to be thrown after this line
driver = new ChromeDriver();
logger.info("perform search in google");
driver.get("http://www.google.com");
driver.findElement(By.id("lst-ib")).sendKeys("Selenium");
driver.findElement(By.id("lst-ib")).submit();
driver.quit();
}
But in the reports the exception appears first and then all the information that is logged from the java class. Both looks like two different pieces in the report, please see the report here https://www.screencast.com/t/bBhAIj7WKj
In the above case would it be possible to have the exception thrown after the line where we log” invoking Chrome” i think this would make it easier to identify the test failures from the reports. Please let us know if this would be possible
It worked for me by passing the karate object from the javascript file to the java code. With this I was able to call the karate.log function from the Java code. This way I could see the messages on the report.

How to integrate Galen reports in Jenkins

I've started to use Galen framework to test the layout of my website pages and I also have my other test, written in Selenium, integrated into Jenkins.
I'm using Java+JUnit+Maven and I would like to know if anyone has managed to integrate the Galen reporting into Jenkins and how.
Because for the moment I am using something like:
assertThat(layoutReport.errors(), is(0));
which tells me if there were errors in the tests but not where.
Thanks!
P.S. If someone with reputation could make the tag galen-framework so that we can group these type of questions, it would be great :D
In your case you could use Galen for generating HTML reports as it normally does when you run tests with it. Though you will have to manage the creation of GalenTestInfo objects.
Here is how the HTML report generation works. Imagine you have somewhere obtainAllTests method defined which returns a list of all executed tests.
List<GalenTestInfo> tests = obtainAllTests();
new HtmlReportBuilder().build(tests, "target/galen-html-reports");
Somewhere in your code you could create a GalenTestInfo and add it to some collection:
GalenTestInfo testInfo = GalenTestInfo.fromString("Here goes the name of your test");
Once you have done the layout checking and obtained LayoutReport object you could add this report to the report of the test. Here is how you can do it:
LayoutReport layoutReport = Galen.checkLayout(driver,
specPath, includedTags, null,
new Properties(), null);
testInfo.getReport().layout(layoutReport, "A title for your layout check");
You can find more insights in this project https://github.com/galenframework/galen-sample-java-tests. It has a basic setup for Galen tests in Java + TestNG + Maven. The reports in it are collected in a singleton GalenReportsContainer. There is also a reporter implemented in GalenReportingListener which takes all those tests from GalenReportsContainer and generates HTML reports.
You can see a full example for Java (TestNG and JUnit) and JavaScript here:
https://github.com/hypery2k/galen_samples.
I use the HTML Plugin together with Jenkins, see example here