Faking Ajax Request Form for testing - java

In my Playframework 2.4 project I have methods like this:
public static Result resetValue(int client) {
String receivedName= form().bindFromRequest().get("username");
User user = User.findByName(receivedName);
if( user == null ) {
return badRequest("No user logged in");
}
user.setValue(0);
user.saveUsertoDB();
return ok("Value set to zero");
}
I want to write JUnit Tests for those methods and ran into the problem that I don`t know how to recreate the Ajax Requests which would normally call those methods in my application.
I am looking for a way to fake the ajax requests and integrate the needed fields into the request so that I can successfully test those methods.

You can use a FakeRequest to be passed to a route()-call.
#Test
public void testResetValueWithFakeRequest() {
Call call = controllers.routes.Application.resetValue(1);
ImmutableMap<String, String> formData = ImmutableMap.of("username", "Jakob");
RequestBuilder request = fakeRequest(call).bodyForm(formData);
Result result = route(request);
assertEquals(OK, result.status());
}
Please see chapters Testing your application > Unit testing controllers and Writing functional tests > Testing the router in play documentation for details.

Related

Persistent and asynchronous stream for communication between appengine/Spring and front-end

At the moment my website is using Spring that handles the http(s) request to and from the front-end like this:
#RestController
public class ComputeController {
#RequestMapping(value = "/api/compute", method = RequestMethod.POST)
public String compute(#RequestBody CodeToken code, OAuth2Authentication OAuth2) {
Map<String, String> userInfo = UserInformation.getUserInfo(OAuth2);
String sourceCode = code.getSource();
String filename = code.getFilename();
String email = userInfo.get("email");
try {
DataStorage dateStorage = new DataStorage();
Compiler compiler = new Compiler(dateStorage);
return compiler.compile(filename, sourceCode, email);
} catch (Exception e) { // TODO Don't catch all exceptions
return e.getStackTrace().toString();
}
}
}
The problem is that I need my front-end (built in Angular) to be able to receive and send information asynchronous from the http(s) request sent from the front-end. Like an continuous I/O stream from the server mid request while the "compiler.compile(...)" is running.
I presume I need to use sockets for this but I'm looking for suggestion on a good way to implement them.
If I understand your intention correctly, you're trying to display some progress in your client while the code compiles. You have two options:
As you proposed, use WebSockets. Spring supports them well. You can see an example here: https://github.com/AlexeySoshin/SpringWebSockets/tree/master/src/main/java/com/alexeysoshin/chat
Instead of blocking your response,
Do compilation on a separate thread pool.
Assign each compilation UUID when you submit this task.
Return the client this task immediately.
Poll another endpoint with UUID

Logged in user null Auth0/Spark Java

I am trying to get Auth0 integrated into my web app which uses the spark-java framework.
The problem is while the authentication works perfectly, including the callback(I see the new user created on Auth0's website and my website gets redirected), I can't access the logged in user info. I've tried several methods like SessionUtils.getAuth0User(request.raw()) and none of them are working.
For example in the provided tutorial here: https://github.com/auth0-samples/auth0-servlet-sample/tree/master/01-Login
they access the logged in user info like so:
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
final Auth0User user = SessionUtils.getAuth0User(req);
if (user != null) {
req.setAttribute("user", user);
}
req.getRequestDispatcher("/WEB-INF/jsp/home.jsp").forward(req, res);
}
I've tried doing something similar with Spark but since the get works a bit differently in Spark I do this:
port(Integer.valueOf(System.getenv("PORT")));
staticFileLocation("/spark/template/freemarker");
String clientId = System.getenv("AUTH0_CLIENT_ID");
String clientDomain = System.getenv("AUTH0_DOMAIN");
get("/", (request, response) ->
{
Map<String, Object> attributes = new HashMap<>();
Auth0User user = SessionUtils.getAuth0User(request.raw());
if(user != null) {
attributes.put("user", user);
attributes.put("loggedIn" , true);
}
else
attributes.put("loggedIn" , false);
attributes.put("clientId" , clientId);
attributes.put("clientDomain" , clientDomain);
return new ModelAndView(attributes, "index.ftl");
}, new FreeMarkerEngine());
The code is always reporting the user as null even though the user is created and stored in the database and the signin works properly with no runtime or console errors. The other methods I tried I replaced the line where I set the user variable and wrote the following.
Alternate Method 1:
Auth0User user = (Auth0User) request.session().attribute("auth0User");
Here auth0User is the same string literal Auth0 uses in their implementation of SessionUtils as shown in their source code referenced here: https://github.com/auth0/auth0-java-mvc-common/blob/master/src/main/java/com/auth0/SessionUtils.java
Alternate Method 2:
Auth0User user = (Auth0User) request.raw().getUserPrincipal();
In addition this is my javascript code running client side for the authentication:
var lock = new Auth0Lock('${clientId}', '${clientDomain}', {
auth: {
redirectUrl: 'http://localhost:5000/build',
responseType: 'code',
params: {
scope: 'openid user_id name nickname email picture'
}
}
});
$(document).ready(function()
{
$('.signup').click(function()
{
doSignup();
});
});
function doSignup() {
lock.show();
}
I have no idea why user is being evaluated to null every time and I would love some feedback on what I'm doing wrong. Thanks.
In order for you to get a non null user instance from SessionUtils.getAuth0User(req) some piece of code must first call SessionUtils.setAuth0User. This should be done when you receive confirmation that the user authenticated with success.
In the auth0-servlet-sample you were using as reference this is done by configuring an Auth0ServletCallback that will handle requests performed to /callback endpoint. Since the Auth0ServletCallback calls (see code below) the set user for you, in the servlet example you can then get the user with success.
protected void store(final Tokens tokens, final Auth0User user, final HttpServletRequest req)
{
SessionUtils.setTokens(req, tokens);
SessionUtils.setAuth0User(req, user);
}
At the moment the available samples (auth0-servlet-sample, auth0-servlet-sso-sample, auth0-spring-mvc-sample, auth0-spring-security-api-sample and auth0-spring-security-mvc-sample) don't include one for spark-java so I can't refer you to any sample.
In order to solve this you have to include additional logic to process the result of the authentication operation in your spark-java application and in case of success call the SessionUtils.setAuth0User yourself if you then want to use the corresponding SessionUtils.getAuth0User method.
For general guidance on integrating a web application with Auth0 check Integrating a Web App with Auth0.

Junit testing play framework

I need to test controllers that are secured with:
#Security.Authenticated(Secured.class).
Even after i log in i get unauthorized,i read that i need to copy the cookie from the log in response and send it with every request to secured method. tried that without any luck.
any idea how to solve that?
Assuming that you are using Helper.route method for testing, logged in behavior can be accomplished by using FakeRequest.withSession method.
For instance, if you are using email as authentication token in your Secured class;
#Override
public String getUsername(Http.Context ctx) {
return ctx.session().get("email");
}
Your test method would be like this;
#Test
public void testPage() {
FakeRequest testRequest = new FakeRequest(Helpers.GET, "/page")
.withSession("email", "mail#example.com");
Result result = Helpers.route(testRequest);
assertThat(Helpers.status(result)).isEqualTo(Helpers.OK);
}

Jersey Test Framework 2.5 - test POST method

I'm trying to find some manual how to test POST methods using jersey framework, only got examples for GET method.
Here's example:
#POST
#Path("add")
#Consumes(MediaType.APPLICATION_XML)
#Produces(MediaType.APPLICATION_XML)
public Response addUser(JAXBElement<User> user) {
int code = userService.addUser(user.getValue());
if (code == 500) {
return Response.status(500).build();
}
return Response.status(code).entity(user).build();
}
Could you please post some POST method test example?
Thank you in advance.
After research I did it!
Here's my solution, it works just fine.
And it's rather integration test, but we can write unit tests in similar manner.
public class RestTest extends JerseyTest{
#Override
protected Application configure() {
return new Your_Resource_Config(); //Your resource config with registered classes
}
//#Before and/or #After for db preparing etc. - if you want integration tests
#Test
public void addUserTest() {
User user = new User();
user.setEmail("user2#mail.com");
user.setName("Jane Doe");
user.getUserRoles().getRoles().add("supertester");
Entity<User> userEntity = Entity.entity(user, MediaType.APPLICATION_XML_TYPE);
target("users/add").request().post(userEntity); //Here we send POST request
Response response = target("users/find").queryParam("email", "user2#mail.com").request().get(); //Here we send GET request for retrieving results
Assert.assertEquals("user2#mail.com", response.readEntity(User.class).getEmail());
}

Play! framework 1.2.5: How to test if response is secure?

A test case for my contact formular page is to make sure it's always in a secure context respectively using SSL. Basically, all I want to know, is that I have a given request where request.secure = true;
The following response does not contain any information about this and its headers are empty:
#Test
public void shouldShowContactForm() {
Response response = GET("/contact");
// How can I ask the response, if the complete URL is in HTTPS?
}
Even if I explicitly set my own request, I cant see the right way to do this:
#Test
public void shouldShowContactFormInSSLContext() {
Request request = newRequest();
request.secure = true;
Response response = GET(request, "/contact");
// Is it now possible?
}
Is this even the right approach to test this or am I simply missing something important about the request/response?
For this question I think what I've done for my apps in the past is have a #before interceptor on all my controllers that looks like this.
#Before
static void checkSSL(){
if(Play.mode.equals(Play.Mode.PROD)){
if(!request.secure) {
Router.ActionDefinition cashTicketDefinition = Router.reverse(request.controller + "." + request.actionMethod);
cashTicketDefinition.absolute();
String url = cashTicketDefinition.url.replaceFirst( "http:", "https:");
redirect(url, true);
}
}
}

Categories

Resources