Geb click executed before input is completed - grails

I'm running a simple Geb test like so:
class IndexPage extends Page {
//static url = "http://localhost:8080/sampleGrailsApp"
static at = { title == "sampleGrailsApp" }
static content = {
signInButton { $("div", 0, class: "container-fluid").find("button", 0) }
modalFooterSignInButton(wait: true, to: MyPage) { $("footer", 0, class: "modal-footer").find("input", 0, class: "btn-primary") }
modalFooterUsernameInput { $("form").username = it }
modalFooterPasswordInput { $("form").password = it }
signIn { username, password ->
signInButton.click()
waitFor { modalFooterSignInButton.present }
modalFooterUsernameInput username
modalFooterPasswordInput password
modalFooterSignInButton.click()
}
}
}
In my test, the page is called as follows:
def "sigin"() {
given: "User is at index page"
at IndexPage
when: "User signs in"
signIn "username","password"
then: "Goes to MyPage"
at MyPage
}
On some occasions, the modalFooterSignInButton.click() happens before the username has been entered completely therefore failing the test. Has anyone encountered this before? How do I wait for input to complete first before click is activated? I'm using Geb 0.9.2.
Thanks in advance.

Try using isDisplayed() instead of present as present means is present in the code but isDisplayed() means it appears in the UI. Hope the following stuffs would solve your problem!
waitFor { modalFooterSignInButton.isDisplayed()}
Also, use waitFor{} in case of critical situations as I don't know anything about your app.

You could do something like :
waitFor { $(<username-input>).text().contains("username") } // after username is entered.
waitFor { $(<password-input>).text().contains("password") } // after password is entered.
before calling modalFooterSignInButton.click()
Also, is this behavior specific to any browser or it happens in all the browsers?

Related

ERR_TOO_MANY_REDIRECTS in grails

I have a filter that is applicable for all controllers and actions
all(controller:'*', action:'*')
If a certain condition is met, I am trying to redirect the user to another page. But I am getting the above stated error. I inserted some logs to see if the filter is being applied or not and I noticed that the
if(condition){} block was being executed multiple times and hence I believe the error is occurring.
Please let me know how I can overcome this. Thank you.
I have code, I hope this help you
def filters = {
sessionCheck(controller: '*', action: '*') {
before = {
if(!(controllerName=="valueSet" && (actionName=="MATReleases" || actionName=="downloadReleases"))) {
if ("your condition") {
def url =new ApplicationTagLib().createLink(controller:'router',action:'sessionExpired')
render(status: 500, contentType: 'text/html', text: "<script>var sessionExpired ; window.location.href='${url}';</script>")
return false
}else{
}
} else {
println "else part"
}
}
}
}

Email Verification in Laravel 5.1.*

I want to add email verification on my laravel app. Just after submitting the registration form the user will get an email with confirmation link. How can I implement this by using laravel's default auth controller? I have added two fields on my user table (confirmed, confirmation_code). Please someone help me...
As per our comment thread, here's how you can integrate it in to the AuthController. There may be better ways to do this, but it has worked a charm for me.
public function postRegister(Request $request)
{
//Run validator checks....
$confirmation_code = str_random(30);
$newUser = new User;
$newUser->username = $request->username;
$newUser->email = $request->email;
$newUser->password = bcrypt($request->password);
$newUser->confirmation_code = $confirmation_code;
$newUser->save();
$data = array('confirmation_code' => $confirmation_code);
Mail::send('emails.verify', $data, function ($message) use ($newUser){
$message->to($newUser->email, $newUser->username);
$message->subject('Please verify your email address');
});
//Continue on with any other logic
}
It was for when they are in the logged in state. Fortunately I managed to solve this one. I changed my Authenticate middleware like this:
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('auth/login');
}
} elseif (!\Auth::user()->is_activated()) {
\Session::flash('message', 'Please activate your account to proceed.');
return redirect()->guest('/notice/activate');
}
return $next($request);
}

Shiro / Vaadin loses session at page reload

I added Shiro session management (based on Kim's and Leif's webinar) to the Vaadin quick ticket dashboard demo application. When I do a browser reload in the application I get thrown back to the login page with no session. How / where can I prevent this.
I have a standard shiro.ini setup
Login button handler:
signin.addClickListener(new ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
boolean loginOK = false;
Factory<SecurityManager> factory =
new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager((org.apache.shiro.mgt.SecurityManager)
securityManager);
Subject currentUser = SecurityUtils.getSubject();
//collect user principals and credentials in a gui specific manner
//such as username/password html form, X509 certificate, OpenID, etc.
//We'll use the username/password example here since it is the most common.
UsernamePasswordToken token =
new UsernamePasswordToken(username.getValue(), password.getValue());
//this is all you have to do to support 'remember me' (no config - built in!):
token.setRememberMe(true);
//currentUser.login(token);
try {
logger.log(Level.INFO, "trying login");
currentUser.login( token );
logger.log(Level.INFO, "login done");
//if no exception, that's it, we're done!
} catch ( Exception e ) {
logger.log(Level.INFO, "exception");
}
if ( currentUser.hasRole( "schwartz" ) ) {
loginOK = true;
} else {
loginOK = false;
}
if (loginOK) {
signin.removeShortcutListener(enter);
buildMainView();
} else {
if (loginPanel.getComponentCount() > 2) {
// Remove the previous error message
loginPanel.removeComponent(loginPanel.getComponent(2));
}
// Add new error message
Label error = new Label(
"Wrong username or password. <span>Hint: try empty values</span>",
ContentMode.HTML);
error.addStyleName("error");
error.setSizeUndefined();
error.addStyleName("light");
// Add animation
error.addStyleName("v-animate-reveal");
loginPanel.addComponent(error);
username.focus();
}
}
});
Use #preserveonRefresh annotation in UI init class
I recommend using Shiro's web filter. This way, your session will not be lost and you can prohibit unauthorized actions (e.g. Instantiating view objects) easily since Shiro's context is already set up when you display the login or any other view.

Geb 'at null' when asserting page

I'm trying to write a simple Geb/Spock test using Grails but I am receiving the following test failure.
| Failure: login works correctly(...UserAuthAcceptanceSpec)
| Condition not satisfied:
at HomePage
|
null
I can follow the test through with a debugger using a browser and can see that the application works as expected and the correct heading is being shown. However, the test is failing when I try to invoke the at checker. Can anyone tell me why the final assertion in the test might be failing and why the 'at' checker appears to be null?
Here is my code: (Geb v0.9.0, Grails 2.2.2)
Spock Specification:
class UserAuthAcceptanceSpec extends GebReportingSpec {
def "login works correctly"() {
given: "the correct credentials"
def theCorrectUsername = "admin"
def theCorrectPassword = "password"
when: "logging in"
to LoginPage
username = theCorrectUsername
password = theCorrectPassword
submitButton.click() //([HomePage, LoginPage])
then: "the welcome page is shown"
heading =~ /(?i)Welcome.*/ // <- same as 'at' checker in HomePage
and: "the 'at' checker works"
at HomePage // <- fails
}
LoginPage:
class LoginPage extends Page {
final String path = "/login/auth"
static content = {
heading(required: false, wait:true) { $("h1").text() }
username { $("input", name:"j_username") }
password { $("input", name:"j_password") }
submitButton { $("input", id:"submit") }
}
static at = {
title =~ /Login.*/
}
}
HomePage:
class HomePage extends Page {
final String path = "/"
static content = {
heading(required: false, wait:true) { $("h1").text() }
}
static at = {
heading =~ /(?i)Welcome.*/
}
}
The at checker should use ==~ rather than =~.
Geb's implicit assertions mean the statements:
heading1 =~ /(?i)Welcome.*/
heading2 ==~ /(?i)Welcome.*/
effectively become:
assert (heading1 =~ /(?i)Welcome.*/) == true // [1]
assert (heading2 ==~ /(?i)Welcome.*/) == true // [2]
[2] will evaluate to a boolean and pass/fail as expected, whereas [1] evaluates to a java.util.regex.Matcher causing the failure.
See the Groovy Regex FAQ for an explanation of the difference between the two syntaxes.

Definition of page component template '$' of 'ApplicationSummaryPage' is invalid, params must be either a Closure, or Map and Closure

Below is my Geb Page, Spec and Error. I am not sure where and what the issue is. When I remove the below from the ApplicationSummaryPage then I doesn't get this error.
ds(wait: true)
{ module DatasourceInformationRow, $("table.ic-table-creditReportProduct table tr", it) }
class ApplicationSummaryPage extends Page
{
static url = "application-summary/application-summary.jsf"
static at =
{ assert title == "Application Summary" }
static content =
{
menu
{ module MenuModule }
userPanel
{module UserPanelModule }
ds(wait: true)
{ module DatasourceInformationRow, $("table.ic-table-creditReportProduct table tr", it) }
applicationSummaryForm
{ $("#applicationSummary_form") }
workItemDiv
{$("div", id: "consumerWorkItems:workItemPanel")}
workItemsSection
{workItemDiv.find (".ui-panel-title").text()}
resubmitLink
{$("a",id: "loginForm")}
overrideDecisionLink
{$("a",id: "loginForm")}
addNoteLink
{$("a",id: "loginForm")}
}
}
Spec
class SearchSpec extends BaseUiSpec
{
def setup()
{
login("manager")
}
def "cccc"()
{
when: "I search"
to SearchPage
at SearchPage
applicationid.value "10002000000010000"
searchButton.click()
at SearchPage
waitFor
{ searchResultsData }
println "------------"+ searchResults(0).ApplicationId.text()
searchResults(0).ApplicationId.click(ApplicationSummaryPage)
Thread.sleep 5000
at ApplicationSummaryPage
println "-----???"+ ds
}
}
Error
geb.waiting.WaitTimeoutException: condition did not pass in 15.0 seconds (failed with exception)
at geb.waiting.Wait.waitFor(Wait.groovy:126)
at geb.content.PageContentTemplate.create(PageContentTemplate.groovy:117)
at geb.content.PageContentTemplate.get(PageContentTemplate.groovy:98)
at geb.content.NavigableSupport.getContent(NavigableSupport.groovy:43)
at geb.content.NavigableSupport.propertyMissing(NavigableSupport.groovy:127)
at geb.Browser.propertyMissing(Browser.groovy:175)
at geb.spock.GebSpec.propertyMissing(GebSpec.groovy:55)
at test.SearchSpec.cccc(SearchSpec.groovy:33)
Caused by: geb.error.InvalidPageContent: Definition of page component template '$' of 'ApplicationSummaryPage' is invalid, params must be either a Closure, or Map and Closure (args were: [class java.lang.String, null])
at geb.content.PageContentTemplateBuilder.throwBadInvocationError(PageContentTemplateBuilder.groovy:69)
at geb.content.PageContentTemplateBuilder.methodMissing(PageContentTemplateBuilder.groovy:51)
at groovy.lang.GroovyObjectSupport.invokeMethod(GroovyObjectSupport.java:44)
at com.equifax.ic.testing.framework.ui.pages.applicationmanagement.ApplicationSummaryPage._clinit__closure2_closure5(ApplicationSummaryPage.groovy:24)
at com.equifax.ic.testing.framework.ui.pages.applicationmanagement.ApplicationSummaryPage._clinit__closure2_closure5(ApplicationSummaryPage.groovy)
at geb.content.PageContentTemplate.invokeFactory(PageContentTemplate.groovy:134)
at geb.content.PageContentTemplate.create_closure1(PageContentTemplate.groovy:103)
at geb.content.PageContentTemplate.create_closure1(PageContentTemplate.groovy)
at geb.waiting.Wait.waitFor(Wait.groovy:115)
... 7 more
The problem was that i wan't passing the index for ds. The corrected version is below
println "-----???"+ ds(0)
Got the response on Geb mailing list. Posting here for others.

Resources