Showing posts with label Functional Test. Show all posts
Showing posts with label Functional Test. Show all posts

Thursday, 27 November 2014

How to test file upload action in Play Framework 2 in Java?

In this post, we will see how we can test an action that expects a file upload (e.g. a profile picture or an image) in Play Framework 2 for Java. First, lets create an action that accepts a file upload as below:

 public static F.Promise uploadProfileImage() {
    final Http.MultipartFormData body = request().body().asMultipartFormData();
    final Http.MultipartFormData.FilePart picture = body.getFile("picture");
    User user = // get the user from db
    
    final File imgFile = picture.getFile();
    final String imgPathToSave = "images/" + "some unique name";
    //save on disk
    final boolean success = new File("images").mkdirs();
    final byte[] bytes = IOUtils.toByteArray(new FileInputStream(imgFile));
    FileUtils.writeByteArrayToFile(new File(imgPathToSave),bytes);
    user.profileImageUrl = imgPathToSave;
    user.save();
       
}


AS you can see, the body of the request is a MultipartFormData. This makes a bit tricky to write functional tests in Play Framework 2 for Java actually. But, let's see the solution.

@Test
public void uploadProfileImageOK() throws Exception { 
   MultipartFormData.FilePart part = new MultipartFormData.FilePart<>("picture","test-image.jpg",Scala.Option("image/jpeg"),new File("test-image.jpg"));

   MultipartFormData formData = new MultipartFormData(Scala.>emptyMap(),Scala.toSeq(Arrays.asList(part)),Scala.emptySeq(),Scala. emptySeq());

   AnyContent anyContent = new AnyContentAsMultipartFormData(formData);

   Result uploadImageResult = callAction(controllers.routes.ref.UserController.uploadProfileImage(), fakeRequest().withHeader("Csrf-Token", "nocheck").withCookies(fakeCookie).withAnyContent(anyContent,"multipart/form-data", "POST"));

   assertEquals(OK, status(uploadImageResult));

   
}

To see more about functional testing in Play Framework 2 using Java see: How to test an action secure by SecureSocial in Play Framework 2 in Java

How to test an action secure by SecureSocial in Play Framework 2 in Java?

SecureSocial is an authentication module for Play Framework 2 applications supporting OAuth, OAuth2, OpenID, Username/Password and custom authentication schemes. Suppose you have an action and you have secured it with @SecureSocial.SecuredAction annotation:

public class Application extends Controller {
    @SecureSocial.SecuredAction
    public static Result index() {
        Identity user = (Identity) ctx().args.get(SecureSocial.USER_KEY);
        return ok(index.render(user));
    }
}

At the time of writing this blog post, SecureSocial only uses cookies for authentication. If you want to write a functional test for this action without taking care of a fake cookie you will get an unauthorized message. To do this we need to some provisioning before our test. Best is to use the @Befor. Below is the steps:
  1. Lets assume that you save your user authentication data in the User model. Here we create a fake user before
  2. 
    @Before
    public void setUp() throws Exception {
       User user = new User();
       User user = new User();
       user.firstName = "jack";
       user.lastName = "sparrow";
       user.email = "jack.sparrow@caribbean.com";
       user.providerId = "userpasswordid";
       user.password = "$2a$10$ywqls6dRsN4wLr.xNydi2uDVFNkOlmi9WSAfRy.RXdN5sgKKnKhau";
       user.authMethod = "userPassword";
       user.save();
    }
    
    
    Please note that the password that you see above is a hash produced with "Bcrypt" encryption and the value depends on how you have implemented this. See Secure Social Password Plugin for more info.
  3. Now create a class named FunctionalTestHelpers and add the following method:
  4. 
    public static Http.Cookie getFakeCookie(String email){
            User user = User.findByEmail(email);
    
            SocialUser socialUser = new SocialUser(new IdentityId(user.email,user.providerId),
                    user.firstName,
                    user.lastName,
                    String.format("%s %s", user.firstName, user.lastName),
                    Option.apply(user.email),
                    null,
                    new AuthenticationMethod("userPassword"),
                    null,
                    null,
                    Some.apply(new PasswordInfo("bcrypt", user.password, null))
            );
    
            Either either = Authenticator.create(socialUser);
            Authenticator auth = (Authenticator) either.right().get();
            Cookie scalaCookie = auth.toCookie();
    
            return new Http.Cookie(scalaCookie.name(),
                                   scalaCookie.value(),
                                   null,
                                   scalaCookie.path(),
                                   null,
                                   scalaCookie.secure(),
                                   scalaCookie.httpOnly());
    
        }
    
    
  5. Now you can use the code below in your tests to get a fake cookie. The code above basically mimics what SecureSocial does for creating a cookie.
  6.  
    Http.Cookie fakeCookie = FunctionalTestHelpers.getFakeCookie("jack.sparrow@caribbean.com"); 
    
  7. Now lets see it in action:
  8. 
    final Result deleteResult = callAction(controllers.routes.ref.TaskController.removeTask(taskId),fakeRequest().withCookies(fakeCookie).withHeader("Csrf-Token", "nocheck"));
    assertThat(status(deleteResult)).isEqualTo(OK);
    
    

Wednesday, 26 November 2014

How to test actions annotated with @RequireCSRFCheck in Play Framework 2?

Let say you have an action as below that you want to protect against CSRF attacks, so you add the @RequireCSRFCheck annotation:

@RequireCSRFCheck
public Result saveUser() {
    // Handle body (process a form)
    return ok();
}

Now suppose you want to write some functional tests for this action. All you need to do is to add fake "nocheck" to your header in "callAction" as below:

final Result result = callAction(controllers.routes.ref.UserController.saveUser(),fakeRequest().withHeader("Csrf-Token", "nocheck"));
assertThat(status(result)).isEqualTo(OK);

For more information about CSRF checks in Play Framework 2 see: JavaCsrf