Gherkin Nested Steps meaning - cucumber

I am writing Gherkin test cases and Java step definitions in my project. I am new to Gherkin and trying to understand the meaning of nested steps. Can you please help me to understand if the 2nd scenario given involves nested steps?
In my example, I would like to reuse 1st scenario code in 2nd scenario given statement logic. Is there a best way to reuse or rewrite the logic?
Note: Below example is written just to explain my question. It may not be a good Gherkin.
Background:
Given The application is opened
Scenario: Successful Login
Given the user name and password are entered
When login button is clicked
Then user login is successful
Scenario: Add Address Successful
Given user login is successful
And Add Address button is clicked
And user city, country are entered
when Submit button is clicked

Nested steps refer to calling defined steps inside a "main" one. In your example, the first scenario has the login functionality, which will / can be used in all other scenarios that require the user to be logged in.
So, the second scenario will have a Given step which calls the login action / steps of the first scenario. There are multiple ways to do this:
1. If you are defining those steps in the same class, it's just a matter of calling the same methods inside a different step / method.
Like so:
public class TestStepsOne {
// Steps from first scenario
#Given("^the user name and password are entered$")
public void enterUsernamePassword() throws Throwable {
System.out.println("User and password entered");
}
#When("^login button is clicked$")
public void clickLoginButton() throws Throwable {
System.out.println("Clicked login button");
}
#Then("^user login is successful$")
public void isLoggedIn() throws Throwable {
System.out.println("Logged in!");
}
// All together
#Given("the user is logged in")
public void loginSuccessfully() throws Throwable {
enterUsernamePassword();
clickLoginButton();
isLoggedIn();
}
}
Now you can use the Given the user is logged in in any scenario, and it will perform the login action.
2. Using Picocontainer -> details here
First you need to add these dependencies to your pom.xml:
<dependency>
<groupId>org.picocontainer</groupId>
<artifactId>picocontainer</artifactId>
<version>2.15</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-picocontainer</artifactId>
<version>1.2.5</version>
</dependency>
You can separate your step definitions.
Like so:
public class TestStepsOne {
// Same as above, without the nested one
}
and second class:
public class TestStepsTwo {
private final TestStepsOne testStepsOne;
public TestStepsTwo(TestStepsOne testStepsOne) {
this.testStepsOne = testStepsOne;
}
#Given("the user is logged in")
public void loginSuccessfully() throws Throwable {
testStepsOne.enterUsernamePassword();
testStepsOne.clickLoginButton();
testStepsOne.isLoggedIn();
}
}
3. Using cuke4duke -> details here , includes examples
Like so:
public class CallingSteps extends Steps {
public CallingSteps(StepMother stepMother) {
super(stepMother);
}
#When("^I call another step$")
public void iCallAnotherStep() {
Given("the user is logged in"); // This will call a step defined somewhere else.
}
}
Hope this helps

Related

Java - Spring MVC - Redirect to route without button/change url dynamically

Please excuse me for my bad english.
This is my problem using Spring MVC:
Let assume that a user is clicking on a button and arrived to a route called "/randomRoute".
I want him to have the possibility to keep doing his job (for example filling a form). About a certain amount of time (represented by the Thread.sleep in the thread), and whatever he did before, I want him to be redirected to a new route called "/newRandomRoute".
I thought about using Thread.run so that the user can continue his work until the delay is done but I don't know how to implement the redirect to the new route.
Is that possible with Spring? Or is there a way to change the url after the Thread.sleep method?
If you want more precision (I am trying to do something on the "Go to "newRandomRoute" page" comment:
#Controller
#RequestMapping("/home")
public class Chat {
#GetMapping("/randomRoute")
public String displayRandomRoute() {
new Thread() {
#Override
public void run() {
try {
Thread.sleep(5000);
// Go to "/newRandomRoute" newPage
} catch (Exception e) {}
}
}.start();
return "page";
}
#GetMapping("/newRandomRoute")
public String displayNewRandomRoute() {
return "newPage";
}
}
Thanks for your help :)

Java+Cucumber: get the current tag/abverb being executed

I am trying to print the current step being executed in Cucumber. I am using a custom formatter to print the step definition. However, I also want to print the current adverb (Given, When, Then, And...) that is being executed. I might be missing something as well, is it possible in Cucumber? Here is my code:
Formatter:
public class MyCucumberFormatter implements ConcurrentEventListener {
#Override
public void setEventPublisher(EventPublisher publisher) {
publisher.registerHandlerFor(TestStepStarted.class, runStartedHandler);
}
private EventHandler<TestStepStarted> runStartedHandler = new EventHandler<TestStepStarted>() {
#Override
public void receive(TestStepStarted event) {
startReport(event);
}
};
private void startReport(TestStepStarted event) {
if (!(event.testStep instanceof PickleStepTestStep)) {
return;
}
PickleStepTestStep testStep = (PickleStepTestStep) event.testStep;
log("Step: " + testStep.getStepText());
}
}
Example scenario:
Scenario: Test user life cycle: create user, activate and delete
Given A valid admin logs in
When Admin creates new user
And User is activated
Then User should successfully login
Right now, it prints as:
A valid admin logs in
Admin creates new user
User is activated
User should successfully login
I want it to print as:
Given A valid admin logs in
When Admin creates new user
And User is activated
Then User should successfully login
You can't do this in v4.x yet but you can do this in v5.0.0-RC1 by going through pickleStepTestStep.getStep().getKeyWord()

shiro web step by step example not work,stormpath is moved

Shiro web example
I follow this, but in step 2, the stormpath is moved to another site okta, so I don't know what shall I do.
There is an exception:
java.lang.IllegalStateException: Unable to load credentials from any provider in the chain.
So I wrote a reamls by myself.
public class CustomSecurityRealm extends JdbcRealm{
#Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
char[] psw = upToken.getPassword();
String username = upToken.getUsername();
return new SimpleAuthenticationInfo(username, psw, getName());
}
#Override
public void setDataSource(DataSource dataSource) {
// TODO Auto-generated method stub
DruidDataSource ds=new DruidDataSource();
ds.setUrl("jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf8&autoReconnect=true&rewriteBatchedStatements=TRUE");
ds.setUsername("root");
ds.setPassword("root");
dataSource=ds;
}
}
And in shiro.ini I change securityManager.realm = $stormpathRealm to securityManager.realm = realm.CustomSecurityRealm
But exception is the same. Or sometimes no error when I delete it from tomcat and add again, but home page is not found --404.
I hate this, I just want to see how to use shiro in web project,why it is so hard?
I have no jndi, so I didn't copy from this example, I just want to make things simple. How can I run the web sample?
Take a look at the examples in https://github.com/apache/shiro/tree/master/samples
We will get that tutorial updated too.

Acumatica: Sign Out User After Process Completion

I am trying to sign out a user once a process is completed, I tried using the PXAccess or the PXAccessInfo classes in order to do so but did not manage to find a correct way in logging out a user. Are there any other means in signing out a user which I might have glossed over?
I adapted the standard SignOut code so it can be run from a graph extension instead of a Aspx.cs web page. It is equivalent to this SignOut menu item:
In this example I put the code in SOOrderEntry Initialize override so it signs out the current user as soon as you navigate to the SalesOrderEntry graph. You can put it in an Action event handler but I haven't tested it in a PXLongOperation context which runs in a separate thread context:
public class SOOrderEntry_Extension:PXGraphExtension<SOOrderEntry>
{
public override void Initialize()
{
System.Web.UI.Page page = System.Web.HttpContext.Current.Handler as System.Web.UI.Page;
if (page != null)
{
PX.Data.PXLogin.LogoutUser(PX.Data.PXAccess.GetUserName(), page.Session.SessionID);
PX.Common.PXContext.Session.SetString("UserLogin", string.Empty);
string absoluteLoginUrl = PX.Export.Authentication.AuthenticationManagerModule.Instance.SignOut();
page.Session.Abandon();
PX.Data.Auth.ExternalAuthHelper.SignOut(System.Web.HttpContext.Current, absoluteLoginUrl);
PX.Export.Authentication.FormsAuthenticationModule.
RedirectToLoginPage(PX.Data.Auth.ExternalAuthHelper.SILENT_LOGIN + "=None", true);
}
}
}

How to extend OrchardCMS to show/hide navigation and content from intranet vs internet users

I have certain pages that I want accessible only to users that are accessing the site from within a given IP range. For all other users, these pages should be inaccessible, and their respective links not visible in the menu/navigation.
I'm new to OrchardCMS, can someone provide some general guidance and point me in the right direction?
There two aspects to answer your question.
1. To check access to orchard content items and menu item relative to it:
To achieve this, you can implement new IAuthorizationServiceEventHandler to replace the default roles based authorization service, the best sample for you is ContentMenuItemAuthorizationEventHandler which you can find under Orchard.ContentPicker module, I included a sample code to explain the usage of this handler:
public class CustomAuthorizationEventHandler :
IAuthorizationServiceEventHandler{
public ContentMenuItemAuthorizationEventHandler() {
}
public void Checking(CheckAccessContext context) { }
public void Adjust(CheckAccessContext context) {
//Here you can put your business to grant user or not
context.Granted = true; //Roles service will look to this value to grant access to the user
context.Adjusted = true;
}
public void Complete(CheckAccessContext context) {}
}
2. To check access to some actions.
To achieve this, you can implement new IAuthorizationFilter to check access to some actions in your system:
public class CustomAuthorizationFilter : FilterProvider, IAuthorizationFilter {
public void OnAuthorization(AuthorizationContext filterContext) {
if (!Granted) {
filterContext.Result = new HttpUnauthorizedResult();
}
}
}
The solutions mentioned by #mdameer are ok, but you will run into difficulties when using containers, lists, projections and stuff.
I had a similar task but with date time ranges. See my question and answer to the task to get an idea how to tackle this via a custom part:
How to skip displaying a content item in Orchard CMS?

Resources