Skip to content

Commit

Permalink
#1849 add method assertIsStaticFile() and special case allowing to te…
Browse files Browse the repository at this point in the history
…st RenderStatic in functional tests

P.S. it implements my comments for PR playframework#1246
  • Loading branch information
asolntsev committed Jul 31, 2018
1 parent 05ff024 commit 77a2c40
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 74 deletions.
133 changes: 71 additions & 62 deletions framework/src/play/test/FunctionalTest.java
Original file line number Diff line number Diff line change
@@ -1,48 +1,46 @@
package play.test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.nio.channels.Channels;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.regex.Pattern;

import org.apache.commons.lang.ArrayUtils;
import org.junit.Before;

import com.ning.http.client.FluentCaseInsensitiveStringsMap;
import com.ning.http.client.multipart.FilePart;
import com.ning.http.client.multipart.MultipartBody;
import com.ning.http.client.multipart.MultipartUtils;
import com.ning.http.client.multipart.Part;
import com.ning.http.client.multipart.StringPart;

import org.apache.commons.lang.ArrayUtils;
import org.junit.Before;
import play.Invoker;
import play.Invoker.InvocationContext;
import play.classloading.enhancers.ControllersEnhancer.ControllerInstrumentation;
import play.exceptions.JavaExecutionException;
import play.exceptions.UnexpectedException;
import play.libs.F.Action;
import play.mvc.ActionInvoker;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Http.Request;
import play.mvc.Http.Response;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import play.mvc.Router.ActionDefinition;
import play.mvc.Scope.RenderArgs;
import play.mvc.results.RenderStatic;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.nio.channels.Channels;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.regex.Pattern;

/**
* Application tests support
Expand Down Expand Up @@ -82,7 +80,7 @@ public static Response GET(Object url, boolean followRedirect) {
Http.Header redirectedTo = response.headers.get("Location");
String location = redirectedTo.value();
if (location.contains("http")) {
java.net.URL redirectedUrl = null;
java.net.URL redirectedUrl;
try {
redirectedUrl = new java.net.URL(redirectedTo.value());
} catch (MalformedURLException e) {
Expand All @@ -106,7 +104,7 @@ public static Response GET(Object url, boolean followRedirect) {
* @return the response
*/
public static Response GET(Request request, Object url) {
String path = "";
String path;
String queryString = "";
String turl = url.toString();
if (turl.contains("?")) {
Expand Down Expand Up @@ -160,7 +158,7 @@ public static Response POST(Object url, String contenttype, InputStream body) {
* @return the response
*/
public static Response POST(Request request, Object url, String contenttype, InputStream body) {
String path = "";
String path;
String queryString = "";
String turl = url.toString();
if (turl.contains("?")) {
Expand Down Expand Up @@ -196,7 +194,7 @@ public static Response POST(Object url, Map<String, String> parameters, Map<Stri
}

public static Response POST(Object url, Map<String, String> parameters) {
return POST(newRequest(), url, parameters, new HashMap<String, File>());
return POST(newRequest(), url, parameters, new HashMap<>());
}

public static Response POST(Request request, Object url, Map<String, String> parameters, Map<String, File> files) {
Expand All @@ -215,11 +213,11 @@ public static Response POST(Request request, Object url, Map<String, String> par
}
}

MultipartBody requestEntity = null;
MultipartBody requestEntity;
/*
* ^1 MultipartBody::read is not working (if parts.isEmpty() == true) byte[] array = null;
**/
_ByteArrayOutputStream baos = null;
_ByteArrayOutputStream baos;
try {
requestEntity = MultipartUtils.newMultipartBody(parts, new FluentCaseInsensitiveStringsMap());
request.headers.putAll(ArrayUtils
Expand All @@ -237,7 +235,7 @@ public static Response POST(Request request, Object url, Map<String, String> par
}
// InputStream body = new ByteArrayInputStream(array != null ? array :
// new byte[0]); // ^1
InputStream body = new ByteArrayInputStream(baos != null ? baos.getByteArray() : new byte[0]);
InputStream body = new ByteArrayInputStream(baos.getByteArray());
return POST(request, url, MULTIPART_FORM_DATA, body);
}

Expand All @@ -259,7 +257,7 @@ public static Response PUT(Object url, String contenttype, String body) {
* @return the response
*/
public static Response PUT(Request request, Object url, String contenttype, String body) {
String path = "";
String path;
String queryString = "";
String turl = url.toString();
if (turl.contains("?")) {
Expand Down Expand Up @@ -293,7 +291,7 @@ public static Response DELETE(String url) {
* @return the response
*/
public static Response DELETE(Request request, Object url) {
String path = "";
String path;
String queryString = "";
String turl = url.toString();
if (turl.contains("?")) {
Expand All @@ -317,7 +315,7 @@ public static void makeRequest(final Request request, final Response response) {
final Future<?> invocationResult = TestEngine.functionalTestsExecutor.submit(new Invoker.Invocation() {

@Override
public void execute() throws Exception {
public void execute() {
renderArgs.clear();
ActionInvoker.invoke(request, response);

Expand Down Expand Up @@ -372,7 +370,14 @@ public InvocationContext getInvocationContext() {
invocationResult.get();
}
catch (ExecutionException e) {
throw unwrapOriginalException(e);
RuntimeException originalException = unwrapOriginalException(e);
if (originalException instanceof RenderStatic) {
response.status = 200;
response.direct = ((RenderStatic) originalException).file;
}
else {
throw originalException;
}
}
catch (Exception e) {
throw new RuntimeException(e);
Expand All @@ -399,15 +404,16 @@ public InvocationContext getInvocationContext() {
}
}

/**
* Check if the original exceptions fits the usual patterns.
* If yes, return the very original runtime exception.
*/
private static RuntimeException unwrapOriginalException(final ExecutionException e) {
// Check if the original exceptions fits the usual patterns. If yes, throw the very
// original runtime exception
final Throwable executionCause = e.getCause();
if (executionCause != null
&& (executionCause instanceof JavaExecutionException || executionCause instanceof UnexpectedException)) {
final Throwable originalCause = executionCause.getCause();
if (originalCause != null && originalCause instanceof RuntimeException) {
throw (RuntimeException) originalCause;
Throwable executionCause = e.getCause();
if (executionCause instanceof JavaExecutionException || executionCause instanceof UnexpectedException) {
Throwable originalCause = executionCause.getCause();
if (originalCause instanceof RuntimeException) {
return (RuntimeException) originalCause;
}
}
// As a last fallback, just wrap everything up
Expand Down Expand Up @@ -441,23 +447,20 @@ public static Response newResponse() {
// Register an onWriteChunk action so that Response.writeChunk() won't throw
// an unhandled exception if the controller action calls it.
response.onWriteChunk(
new Action<Object>() {
@Override
public void invoke(Object chunk) {
// Mimic the behavior of PlayHandler$LazyChunkedInput.writeChunk()
if (chunk != null) {
try {
byte[] bytes;
if (chunk instanceof byte[]) {
bytes = (byte[]) chunk;
} else {
bytes = chunk.toString().getBytes(response.encoding);
}
response.out.write(bytes);
} catch (Exception exception) {
// Something is wrong with the chunk.
throw new RuntimeException(exception);
chunk -> {
// Mimic the behavior of PlayHandler$LazyChunkedInput.writeChunk()
if (chunk != null) {
try {
byte[] bytes;
if (chunk instanceof byte[]) {
bytes = (byte[]) chunk;
} else {
bytes = chunk.toString().getBytes(response.encoding);
}
response.out.write(bytes);
} catch (Exception exception) {
// Something is wrong with the chunk.
throw new RuntimeException(exception);
}
}
});
Expand All @@ -466,8 +469,7 @@ public void invoke(Object chunk) {
}

public static Request newRequest() {
Request request = Request.createRequest(null, "GET", "/", "", null, null, null, null, false, 80, "localhost", false, null, null);
return request;
return Request.createRequest(null, "GET", "/", "", null, null, null, null, false, 80, "localhost", false, null, null);
}

// Assertions
Expand Down Expand Up @@ -503,6 +505,13 @@ public static void assertStatus(int status, Response response) {
assertEquals("Response status ", (Object) status, response.status);
}

public static void assertIsStaticFile(Response response, String filePath) {
assertIsOk(response);

String file = (String) response.direct;
assertEquals(filePath, file);
}

/**
* Exact equality assertion on response body
*
Expand Down
26 changes: 14 additions & 12 deletions samples-and-tests/just-test-cases/test/FunctionalTestTest.java
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
import org.junit.*;

import play.test.*;
import play.libs.WS;
import play.mvc.Http.*;
import play.mvc.results.*;
import models.*;
import models.User;
import org.junit.Test;
import play.mvc.Http.Cookie;
import play.mvc.Http.Request;
import play.mvc.Http.Response;
import play.mvc.results.NotFound;
import play.test.Fixtures;
import play.test.FunctionalTest;
import play.test.UnitTest;

import java.util.HashMap;

public class FunctionalTestTest extends FunctionalTest {

@org.junit.Before
public void setUp() throws Exception {
public void setUp() {
Fixtures.deleteDatabase();
Fixtures.loadModels("users.yml");
}
Expand Down Expand Up @@ -115,17 +117,17 @@ public void usingRedirection() {

@Test
public void canGetRenderArgs() {
Response response = GET("/users/edit");
Response response = GET("/users/edit");
assertIsOk(response);
assertNotNull(renderArgs("u"));
User u = (User) renderArgs("u");
assertEquals("Guillaume", u.name);
}

@Test(expected = RenderStatic.class)
@Test
public void testGettingStaticFile() {
Response response = GET("/public/session.test?req=1");
assertIsOk(response);
Response response = GET("/public/session.test?req=1");
assertIsStaticFile(response, "public/session.test");
}

/**
Expand Down

0 comments on commit 77a2c40

Please sign in to comment.