Cucumber - Undefined Steps Though defined - selenium

I'm creating a Simple Selenium Cucumber project and defined steps using "Lambda Expressions Constructor" way for a feature file but when I ran the CucumberTest class I'm getting failure exception as
There are undefined steps!
My StepDefinition is below one
And Feature file is the below one
CucumberRunner class is below:
So please suggest me is there any different approach for calling Step Definition File if I use Lambda Expressions?

As already mentioned in my comment. The option glue expects a list of package names, not directories. Changing it from
glue = {"src/test/java/my.project.automation.wolfram_alpha" }
to
glue = {"my.project.automation.wolfram_alpha" }
will solve the issue.
Find working snippets below. Assuming following structure
src/test/java/my/project/automation/wolfram_alpha/StepDef.java
src/test/java/my/project/automation/wolfram_alpha/cucumberTest.java
src/test/resources/wolfram.feature
pom.xml
pom.xml (dependencies part)
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<version.cucumber>3.0.2</version.cucumber>
</properties>
<dependencies>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java8</artifactId>
<version>${version.cucumber}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-junit</artifactId>
<version>${version.cucumber}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-testng</artifactId>
<version>${version.cucumber}</version>
<scope>test</scope>
</dependency>
</dependencies>
cucumberTest.java
package my.project.automation.wolfram_alpha;
import cucumber.api.CucumberOptions;
import cucumber.api.testng.AbstractTestNGCucumberTests;
#CucumberOptions(
features = { "src/test/resources/wolfram.feature" },
glue = {"my.project.automation.wolfram_alpha" }
)
public class cucumberTest extends AbstractTestNGCucumberTests {
}
StepDef.java
package my.project.automation.wolfram_alpha;
import cucumber.api.java8.En;
public class StepDef implements En {
public StepDef() {
Given("URL of WolframAlpha" , () -> {
System.out.println("Given URL of WolframAlpha");
});
When("user logged in as {string} with {string}" , (String user, String password) -> {
System.out.printf("When user logged in as {%s} with {%s}%n", user, password);
});
And("login is successful" , () -> {
System.out.println("And login is successful");
});
And("user search for a {string}" , (String topic) -> {
System.out.printf("And user search for a {%s}%n", topic);
});
Then("results are displayed in a creative way" , () -> {
System.out.println("Then results are displayed in a creative way");
});
}
}
wolfram.feature from the question
Running the test with mvn test produces following output.
Running my.project.automation.wolfram_alpha.cucumberTest
Configuring TestNG with: org.apache.maven.surefire.testng.conf.TestNG652Configurator#726f3b58
Given URL of WolframAlpha
When user logged in as {user} with {password}
And login is successful
And user search for a {IDOL}
Then results are displayed in a creative way
1 Scenarios (1 passed)
5 Steps (5 passed)

Related

Spring webflux with jwt + csrf token

I need to implement CSRF protection to my backend. I am using the below configurations. But applications allow Post and Get requests without CSRF token.
#Slf4j
#EnableWebFluxSecurity
#EnableReactiveMethodSecurity
public class SecurityConfig {
#Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
.csrf(csrf -> csrf.csrfTokenRepository(CookieServerCsrfTokenRepository.withHttpOnlyFalse()))
.authorizeExchange()
.anyExchange().authenticated()
.and().oauth2ResourceServer().jwt();
return http.build();
}
}
include the actual CSRF token in the HTTP request
#ControllerAdvice
public class SecurityControllerAdvice {
#ModelAttribute
Mono<CsrfToken> csrfToken(ServerWebExchange exchange) {
Mono<CsrfToken> csrfToken = exchange.getAttribute(CsrfToken.class.getName());
return csrfToken.doOnSuccess(token -> {
exchange.getAttributes()
.put(CsrfRequestDataValueProcessor.DEFAULT_CSRF_ATTR_NAME, token);
});
}
}
I tried the API using postman. But this is not working for me.
Spring version
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.3</version>
<relativePath/>
</parent>
Dependencies:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-resource-server</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-jose</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
Final target: My frontend is Vuejs + nuxtjs. Can someone help me to
find the best way for implement this?
By using the oauth2ResourceServer() DSL, you are telling Spring Security that you are not using cookie-based authentication, therefore you do not need CSRF protection.
If you take a look at the OAuth2ResourceServerConfigurer#registerDefaultCsrfOverride you will notice that it doesn't apply the CSRF token validation to requests that contain a Bearer token, by using the BearerTokenRequestMatcher.
private void registerDefaultCsrfOverride(H http) {
CsrfConfigurer<H> csrf = http.getConfigurer(CsrfConfigurer.class);
if (csrf != null) {
csrf.ignoringRequestMatchers(this.requestMatcher);
}
}
CSRF exploits the browser behavior that automatically attaches the Cookies for the request, so I can trick users from my website www.malicioussite.example to click on a button and send a request to www.fakebank.example/transferMoneyToMe.
When you are using the Authorization header to send the JWT, the browser does not know about the access token, and therefore, will not attach the header automatically.
You can dive more deeply into this behavior starting from this answer https://security.stackexchange.com/questions/189326/do-i-need-csrf-protection-in-this-setup-with-a-rest-api-backed-with-oauth2-and-a

Unable to run cucumber scenarios using intellij and ubuntu, implement step definitions but they are already implemented

I am trying to run a sample feature file with a couple cucumber scenarios, but when i run them i get that i did not implement the step definition, but i actually did, i have a folder called stepDefinitions and inside a java class called StepDefinition, where i wrote the steps
Testing started at 20:14 ...
Undefined scenarios:
/home/adrianjimenez/IdeaProjects/RestAssured/src/test/java/RestAssuredFramework/features/fileValidations.feature:13 # Verify if Place is being Successfully added using AddPlaceAPI
/home/adrianjimenez/IdeaProjects/RestAssured/src/test/java/RestAssuredFramework/features/fileValidations.feature:17 # Verify if Delete Place functionality is working
2 Scenarios (2 undefined)
10 Steps (10 undefined)
0m0.536s
You can implement missing steps with the snippets below:
#Given("Add Place Payload with {string} {string} {string}")
public void add_Place_Payload_with(String string, String string2, String string3) {
// Write code here that turns the phrase above into concrete actions
throw new cucumber.api.PendingException();
}
#When("user calls {string} with {string} http request")
public void user_calls_with_http_request(String string, String string2) {
// Write code here that turns the phrase above into concrete actions
throw new cucumber.api.PendingException();
}
#Then("the API call got success with status code {int}")
public void the_API_call_got_success_with_status_code(Integer int1) {
// Write code here that turns the phrase above into concrete actions
throw new cucumber.api.PendingException();
}
#Then("{string} in response body is {string}")
public void in_response_body_is(String string, String string2) {
// Write code here that turns the phrase above into concrete actions
throw new cucumber.api.PendingException();
}
#Then("verify place_Id created maps to {string} using {string}")
public void verify_place_Id_created_maps_to_using(String string, String string2) {
// Write code here that turns the phrase above into concrete actions
throw new cucumber.api.PendingException();
}
#Given("DeletePlace Payload")
public void deleteplace_Payload() {
// Write code here that turns the phrase above into concrete actions
throw new cucumber.api.PendingException();
}
Process finished with exit code 0
But i actually implemented the steps so i do not understand what is happening, these are the steps i have implemented.
package RestAssuredFramework.stepDefinitions;
import RestAssuredFramework.resources.APIResources;
import RestAssuredFramework.resources.TestDataBuilder;
import RestAssuredFramework.resources.Utils;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import io.restassured.builder.ResponseSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import io.restassured.specification.ResponseSpecification;
import java.io.IOException;
import static io.restassured.RestAssured.given;
import static org.junit.Assert.assertEquals;
public class StepDefinition extends Utils {
RequestSpecification res;
String responseString;
static String place_id;
ResponseSpecification resspec;
Response response;
TestDataBuilder testDataBuilder = new TestDataBuilder();
JsonPath jsonPath;
#Given("Add Place Payload with {string} {string} {string}")
public void add_Place_Payload_with(String name, String language, String address) throws IOException {
// Write code here that turns the phrase above into concrete actions
res=given().spec(requestSpecification())
.body(testDataBuilder.addPlacePayload(name,language,address));
}
#When("user calls {string} with {string} http request")
public void user_calls_with_http_request(String resource, String method) {
// Write code here that turns the phrase above into concrete actions
//constructor will be called with value of resource which you pass
APIResources resourceAPI=APIResources.valueOf(resource);
System.out.println(resourceAPI.getResource());
resspec =new ResponseSpecBuilder().expectStatusCode(200).expectContentType(ContentType.JSON).build();
if(method.equalsIgnoreCase("POST"))
response =res.when().post(resourceAPI.getResource());
else if(method.equalsIgnoreCase("GET"))
response =res.when().get(resourceAPI.getResource());
}
#Then("the API call got success with status code {int}")
public void the_API_call_got_success_with_status_code(Integer int1) {
// Write code here that turns the phrase above into concrete actions
assertEquals(response.getStatusCode(),200);
}
#Then("{string} in response body is {string}")
public void in_response_body_is(String keyValue, String Expectedvalue) {
// Write code here that turns the phrase above into concrete actions
assertEquals(getJsonPath(response,keyValue),Expectedvalue);
}
#Then("verify place_Id created maps to {string} using {string}")
public void verify_place_Id_created_maps_to_using(String expectedName, String resource) throws IOException {
// requestSpec
place_id=getJsonPath(response,"place_id");
res=given().spec(requestSpecification()).queryParam("place_id",place_id);
user_calls_with_http_request(resource,"GET");
String actualName=getJsonPath(response,"name");
assertEquals(actualName,expectedName);
}
//delete scneario
#Given("DeletePlace Payload")
public void deleteplace_Payload() throws IOException {
// Write code here that turns the phrase above into concrete actions
res =given().spec(requestSpecification()).body(testDataBuilder.deletePlacePayload(place_id));
}
}
and this is my feature file
Feature: Validating Place API's
#AddPlace #Regression
Scenario Outline: Verify if Place is being Successfully added using AddPlaceAPI
Given Add Place Payload with "<name>" "<language>" "<address>"
When user calls "AddPlaceAPI" with "POST" http request
Then the API call got success with status code 200
And "status" in response body is "OK"
And "scope" in response body is "APP"
And verify place_Id created maps to "<name>" using "getPlaceAPI"
Examples:
|name | language |address |
|peter | Spanish |Aguascalientes, st|
# |BBhouse | Spanish |Sea cross center |
#DeletePlace #Regression
Scenario: Verify if Delete Place functionality is working
Given DeletePlace Payload
When user calls "deletePlaceAPI" with "POST" http request
Then the API call got success with status code 200
And "status" in response body is "OK"
intellij version
IntelliJ IDEA 2019.3.2 (Community Edition)
Build #IC-193.6015.39, built on January 21, 2020
Runtime version: 11.0.5+10-b520.30 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Linux 5.0.0-37-generic
GC: ParNew, ConcurrentMarkSweep
Memory: 725M
Cores: 4
Registry:
Non-Bundled Plugins: gherkin, cucumber-java
pom.xml
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
<groupId>org.example</groupId>
<artifactId>RestAssured</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
UTF-8
7
io.cucumber
cucumber-java
4.8.0
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-junit -->
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-junit</artifactId>
<version>4.8.0</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>4.1.2</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
-->
com.fasterxml.jackson.core
jackson-databind
2.10.1
this is the test runner class
package RestAssuredFramework.cucumber.Options;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;
#RunWith(Cucumber.class)
#CucumberOptions(
features = "src/test/java/RestAssuredFramework",
glue = {"StepDefinition"}
)
public class TestRunner {
}
I also have the following plugins installed in intellij
Cucumber for java 193.5662.7
Gherkin 193.6015.53
You need to provide correct glue in #CucumberOptions annotation
glue = {"RestAssuredFramework.stepDefinitions"}
glue - is the package name where step definitions stored

Apache Beam : is it possible to comsume messages of RabbitMQ with exchange and routing key

I defined a pipeline in Apache Beam to consume messages of a given queue in RabbitMQ message broker.
I defined an exchange and routing key in RabbitMQ.
I used AmqpIO.read() in Beam (version 2.9.0) but I did not found any API to set the echange and the routing key.
(Following this doc : https://beam.apache.org/releases/javadoc/2.4.0/org/apache/beam/sdk/io/amqp/AmqpIO.html)
Is there any possibility to do that ? Even with any other plugin.
Regards,
Ali
There is a new (experimental) IO connector for RabbitMQ shipped with the latest v2.9.0 Apache Beam release. The AMQP connector will not work for RabbitMQ.
If you are using Maven add the following dependency in your POM
<!-- Beam MongoDB I/O -->
<dependency>
<groupId>org.apache.beam</groupId>
<artifactId>beam-sdks-java-io-mongodb</artifactId>
<version>2.9.0</version>
</dependency>
and you can use it in a pipeline like
public class RabbitMQPipeline {
final static Logger log = LoggerFactory.getLogger(RabbitMQPipeline.class);
/**
* Mongo Pipeline options.
*/
public interface RabbitMQPipelineOptions extends PipelineOptions {
#Description("Path of the file to read from")
#Default.String("amqp://localhost")
#Required
String getUri();
void setUri(String uri);
}
/**
* #param args
*/
public static void main(String[] args) {
RabbitMQPipelineOptions options = PipelineOptionsFactory.fromArgs(args).withValidation()
.as(RabbitMQPipelineOptions.class);
Pipeline pipeline = Pipeline.create(options);
PCollection<RabbitMqMessage> messages = pipeline
.apply(RabbitMqIO2.read().withUri(options.getUri()).withQueue("test"));
messages.apply(ParDo.of(new DoFn<RabbitMqMessage, String>() {
#ProcessElement
public void process(#Element RabbitMqMessage msg) {
System.out.println(msg.toString());
}
}));
pipeline.run().waitUntilFinish();
}
}
The RabbitMqIO Javadoc has examples of how to use the reader and writer.
A word of caution
There is a known bug that has been fixed but scheduled for release in v2.11.0 that blocks the connector from working even in the simplest scenarios. The fix is really simple (see JIRA issue) but you will need to rebuild a new version of the class. In case you want to give it a try make sure you add the following Maven dependency
<dependency>
<groupId>com.google.auto.value</groupId>
<artifactId>auto-value</artifactId>
<version>1.5.2</version>
<scope>provided</scope>
</dependency>
and add the following configuration in Maven Compiler plugin
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<annotationProcessors>
<annotationProcessor>com.google.auto.value.processor.AutoValueProcessor</annotationProcessor>
</annotationProcessors>
</configuration>
</plugin>
If you are using Eclipse make sure you install the m2-apt Maven plugin. Good luck!

Unsatisfied dependencies with Weld during integration testing

I am able to deploy a RESTEasy application working well with Weld (meaning my CDI works) but I am having some trouble with my integration tests. I get this error:
org.jboss.weld.exceptions.DeploymentException:
WELD-001408: Unsatisfied dependencies for type SomeService with qualifiers #Default
while testing:
#RunWith(WeldJUnit4Runner.class)
public class SomeServiceIT {
#Inject
private SomeService service;
#Test
public void test() {
System.out.println(service);
}
}
The last message in my logs is
DEBUG::WELD-000100: Weld initialized. Validating beans
Content of src/test/resources/META-INF/beans.xml:
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.1" bean-discovery-mode="all">
</beans>
By the way I tried the cdi-unit library and it works, but I need to use my own WeldJUnit4Runner which is currently:
public class WeldJUnit4Runner extends BlockJUnit4ClassRunner {
private final Weld weld;
private final WeldContainer container;
public WeldJUnit4Runner(Class<?> klass) throws InitializationError {
super(klass);
this.weld = new Weld();
this.container = weld.initialize();
}
#Override
protected Object createTest() throws Exception {
return container.instance().select(getTestClass().getJavaClass()).get();
}
}
I use weld-se 2.4.1.Final for testing.
Thanks.
EDIT:
So it seems like Weld only looks into src/test/java (when I copy SomeService over to src/test/java it woks). This is silly, I am not going to duplicate all my classes to test them... How to tell Weld to retrieve classes from src/main/java?
So I was able to make it work by creating src/main/resources/META-INF/beans.xml in addition to the existing src/main/webapp/WEB-INF/beans.xml and src/test/resources/META-INF/beans.xml meaning now I have 3 times the exact same file in the same project which I find silly but I guess this is how it is in the Weld world...
Thanks all for your time.
EDIT:
Actually I am able to deploy the application with only src/main/resources/META-INF/beans.xml (I removed src/main/webapp/WEB-INF/beans.xml)
Sorry, I have no solution, but only a small clue: if you want to do some customizations of the BlockJUnit4ClassRunner - why don't you try to extend the org.jglue.cdiunit.CdiRunner or org.apache.deltaspike.testcontrol.api.junit.CdiTestRunner? Or at least take a look at their source code.
Ps. I always find Weld's class-path scanning brittle & error prone. And try to avoid it as much as possible.
It should work so I post here what I did.
Firstly, I use :
Eclipse Luna
JDK 7
The tree of my project is the following one :
Here are my pom dependencies :
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se-core</artifactId>
<version>2.4.1.Final</version>
<scope>test</scope>
</dependency>
The SomeService interface :
package org.jvi.cdirunner;
public interface SomeService {
void test();
}
The SomeServiceImpl implementation :
package org.jvi.cdirunner;
public class SomeServiceImpl implements SomeService {
#Override
public void test() {
// TODO Auto-generated method stub
}
}
And the test to run :
package org.jvi.cdirunner.test;
import javax.inject.Inject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.jvi.cdirunner.SomeService;
#RunWith(WeldJUnit4Runner.class)
public class SomeServiceIT {
#Inject
private SomeService service;
#Test
public void test() {
System.out.println(service);
}
}
And everything works fine if I run the test under Eclipse. I can't figure out why it doesn't work on your side.

Infinispan 6.0 CDI and default configuration

I'm having problems defining configuration for a CDI application (glassfish 4).
I have:
#CacheResult(cacheName = "example")
public String getSomething(String something){
logger.debug("getSomething "+something);
return "this is "+something;
}
This works as expected, the second time is called is not executed because it's cached
However, I want to specify a configuration for my caches. I have tried writing a infinispan.xml file (in src/main/resources), but it's ignored. I have also tried with both:
#Produces
#Default
public Configuration defaultEmbeddedCacheConfiguration() {
return new ConfigurationBuilder().expiration().lifespan(3000l)
.eviction()
.strategy(EvictionStrategy.LRU)
.maxEntries(2)
.build();
}
#Produces
#ApplicationScoped
public EmbeddedCacheManager defaultEmbeddedCacheManager() {
return new DefaultCacheManager(defaultEmbeddedCacheConfiguration());
}
But these methods are never called.
I have also tried with #ConfigureCache
My dependencies are:
<dependency>
<groupId>org.infinispan</groupId>
<artifactId>infinispan-cdi</artifactId>
<version>6.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.infinispan</groupId>
<artifactId>infinispan-jcache</artifactId>
<version>6.0.2.Final</version>
</dependency>
Any ideas?
Thx