java - Unit-testing methods secured with Securesocial annotation -


i'm trying make functional tests webapplication using play 2.1.4 , socialsecure. before using securesocial tests pretty straight forward im having troubles figuering out how can make tests on secured actions.

@test public void createnewnote() {     result result;     // should return bad request if no data given     result = callaction(             controllers.routes.ref.notes.newnote(),             fakerequest().withformurlencodedbody(                     immutablemap.of("title", "", "text",                             "")));     assertthat(status(result)).isequalto(bad_request);      result = callaction(             controllers.routes.ref.notes.newnote(),             fakerequest().withformurlencodedbody(                     immutablemap.of("title", "my note title", "text",                             "my note content")));      // should return redirect status if successful     assertthat(status(result)).isequalto(see_other);     assertthat(redirectlocation(result)).isequalto("/notes");      note newnote = note.find.where().eq("title", "my note title")             .findunique();      // should saved db     assertnotnull(newnote);     assertequals("my note title", newnote.title);     assertequals("my note content", newnote.text); } 

as of right got user in test yml file:

- !!models.user id: 1234567890 username: pingu provider: twitter firstname: pingu lastname: pingusson email: pingu@note.com password: password 

my user pretty straight forward...:

@table(     uniqueconstraints=         @uniqueconstraint(columnnames={"username"})) @entity public class user extends model {      private static final long serialversionuid = 1l;  @id public string id;  public string provider;  public string firstname;  public string lastname;  public string email;  public string password;  @minlength(5) @maxlength(20) public string username;  public static finder<string, user> find = new finder<string, user>(         string.class, user.class);  public static user findbyid(string id) {     return find.where().eq("id", id).findunique(); } public static user findbyemail(string email) {     return find.where().eq("email", email).findunique(); } @override public string tostring() {     return this.id + " - " + this.firstname; } 

}

and userservice:

public class userservice extends baseuserservice {

public userservice(application application) {     super(application); }  @override public void dodeleteexpiredtokens() {     if (logger.isdebugenabled()) {         logger.debug("deleteexpiredtokens...");     }     list<localtoken> list = localtoken.find.where().lt("expireat", new datetime().tostring()).findlist();     for(localtoken localtoken : list) {         localtoken.delete();     } }  @override public void dodeletetoken(string uuid) {     if (logger.isdebugenabled()) {         logger.debug("deletetoken...");         logger.debug(string.format("uuid = %s", uuid));     }     localtoken localtoken = localtoken.find.byid(uuid);     if(localtoken != null) {         localtoken.delete();     } }  @override //public identity dofind(userid userid) { public identity dofind(identityid identityid){     if (logger.isdebugenabled()) {         logger.debug(string.format("finding id = %s", identityid.userid()));      }      user localuser = user.find.byid(identityid.userid());     logger.debug(string.format("localuser = " + localuser));     if(localuser == null) return null;     socialuser socialuser = new socialuser(new identityid(localuser.id, localuser.provider),             localuser.firstname,          localuser.lastname,          string.format("%s %s", localuser.firstname, localuser.lastname),         option.apply(localuser.email),          null,          new authenticationmethod("userpassword"),         null,          null,          some.apply(new passwordinfo("bcrypt", localuser.password, null))     );       if (logger.isdebugenabled()) {         logger.debug(string.format("socialuser = %s", socialuser));     }     return socialuser; }   @override public identity dofindbyemailandprovider(string email, string providerid) {     list<user> list = user.find.where().eq("email", email).eq("provider", providerid).findlist();     if(list.size() != 1){         logger.debug("found null in findbyemailandprovider...");         return null;     }     user localuser = list.get(0);     socialuser socialuser =              new socialuser(new identityid(localuser.email, localuser.provider),                     localuser.firstname,                      localuser.lastname,                      string.format("%s %s", localuser.firstname, localuser.lastname),                     option.apply(localuser.email),                      null,                      new authenticationmethod("userpassword"),                     null,                      null,                      some.apply(new passwordinfo("bcrypt", localuser.password, null))                );       return socialuser; }  @override public token dofindtoken(string token) {     if (logger.isdebugenabled()) {         logger.debug("findtoken...");         logger.debug(string.format("token = %s", token));     }     localtoken localtoken = localtoken.find.byid(token);     if(localtoken == null) return null;     token result = new token();     result.uuid = localtoken.uuid;     result.creationtime = new datetime(localtoken.createdat);     result.email = localtoken.email;     result.expirationtime = new datetime(localtoken.expireat);     result.issignup = localtoken.issignup;     if (logger.isdebugenabled()) {         logger.debug(string.format("foundtoken = %s", result));     }     return result; }  @override public identity dosave(identity user) {     if (logger.isdebugenabled()) {         logger.debug("save...!_!");         logger.debug(string.format("user = %s", user));     }     user localuser = null;     localuser = user.find.byid(user.identityid().userid());     logger.debug("id = " + user.identityid().userid());     logger.debug("provider = " + user.identityid().providerid());     logger.debug("firstname = " + user.firstname());     logger.debug("lastname = " + user.lastname());     logger.debug(user.fullname() + "");     logger.debug("email = " + user.email());     logger.debug(user.email().getclass() + "");      if (localuser == null) {         logger.debug("adding new...");         localuser = new user();         localuser.id = user.identityid().userid();         localuser.provider = user.identityid().providerid();         localuser.firstname = user.firstname();         localuser.lastname = user.lastname();          //temporary solution twitter not have email in oauth answer         if(!(user.email().tostring()).equals("none")){             localuser.email = user.email().get();         }         if(!(user.passwordinfo() + "").equals("none")){             localuser.password = user.passwordinfo().get().password();         }         localuser.save();     } else {         logger.debug("existing one...");         localuser.id = user.identityid().userid();         localuser.provider = user.identityid().providerid();         localuser.firstname = user.firstname();         localuser.lastname = user.lastname();          //temporary solution twitter not have email in oauth answer         if(!(user.email().tostring()).equals("none")){             localuser.email = user.email().get();         }         if(!(user.passwordinfo() + "").equals("none")){             localuser.password = user.passwordinfo().get().password();         }         localuser.update();     }     return user; }  @override public void dosave(token token) {     localtoken localtoken = new localtoken();     localtoken.uuid = token.uuid;     localtoken.email = token.email;     try {         simpledateformat df = new simpledateformat("yyyy-mm-dd hh:mm:ss");         localtoken.createdat = df.parse(token.creationtime.tostring("yyyy-mm-dd hh:mm:ss"));         localtoken.expireat = df.parse(token.expirationtime.tostring("yyyy-mm-dd hh:mm:ss"));     } catch (parseexception e) {         logger.error("userservice.dosave(): ", e);     }     localtoken.issignup = token.issignup;     localtoken.save(); } 

}

as of understanding should in someway set session user logged in using .withsession method on fakerequest , maybe set value on serverside.

tried searching web examples using securesocial , play found no tests @ all.

how can login in user can preform tests?

best regards rawa

thanks david weinbergs comment able solve after trail , error. (:

i started out localuser implementation reply: https://stackoverflow.com/a/18589402/1724097

this how solved it:

to make unit tests created local user in database, using test-data.yml file:

- !!models.localuser     id: 1234567890     username: username     provider: userpass     firstname: firstname     lastname: lastname     email: user@example.com     #hash "password"     password: $2a$10$.ve.rwjfmblrv2hiqhzm5.ciqzyohhjylyrkpmmwxar6vp58u7flw  

then made test utils class create fakecookie.

import models.localuser; import play.logger; import securesocial.core.authenticator; import securesocial.core.identityid; import securesocial.core.socialuser; import securesocial.core.passwordinfo; import scala.some; import securesocial.core.authenticationmethod; import scala.option; import scala.util.right; import scala.util.either; import play.mvc.http.cookie;  public class utils {       public static cookie fakecookie(string user){          localuser localuser = localuser.findbyemail(user);         logger.debug("username: " + localuser.username +" - id: " + localuser.id);          socialuser socialuser = new socialuser(new identityid(localuser.id, localuser.provider),                 localuser.firstname,              localuser.lastname,              string.format("%s %s", localuser.firstname, localuser.lastname),             option.apply(localuser.email),              null,              new authenticationmethod("userpassword"),             null,              null,              some.apply(new passwordinfo("bcrypt", localuser.password, null))         );            either either = authenticator.create(socialuser);         authenticator auth = (authenticator) either.right().get();         play.api.mvc.cookie scalacookie = auth.tocookie();           //debug loggig         logger.debug("cookie data:");         logger.debug("name: " + "value: " + auth.cookiename() + " | class: " + auth.cookiename().getclass() + " | should type: " + "java.lang.string");         logger.debug("value: " + "value: " + scalacookie.value() + " | class: " + scalacookie.value().getclass() + " | should type: " + "java.lang.string");         logger.debug("maxage: " + "value: " + scalacookie.maxage() + " | class: " + scalacookie.maxage().getclass() + " | should type: " + "int");         logger.debug("path: " + "value: " + scalacookie.path() + " | class: " + scalacookie.path().getclass() + " | should type: " + "java.lang.string");         logger.debug("domain: " + "value: " + scalacookie.domain() + " | class: " + auth.cookiedomain().getclass() + " | should type: " + "java.lang.string");         logger.debug("secure: " + "value: " + auth.cookiesecure() + " | class: " + "boolean" + " | should type: " + "boolean");         logger.debug("httponly: " + "value: " + auth.cookiehttponly() + " | class: " + "boolean" + " | should type: " + "boolean");          // securesocial doesnt seem set maxage or domain set them myself.         cookie fakecookie = new cookie(auth.cookiename(), scalacookie.value(), 120, scalacookie.path(), "none", auth.cookiesecure(), auth.cookiehttponly());         return fakecookie;     } } 

and use cookie in fakerequest im logged in:

cookie cookie = utils.fakecookie("user@example.com");  result result = callaction(         controllers.routes.ref.yoursampleclass.yoursecuredfucntion(),         fakerequest().withformurlencodedbody(                 immutablemap.of("value", "some input value")).withcookies(cookie));  // should return redirect status if successful assertthat(status(result)).isequalto(see_other); assertthat(redirectlocation(result)).isequalto("/yourwantedresult"); 

hope helps others!


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -