Skip to content

Commit

Permalink
Add test for POST request. Refactor status check.
Browse files Browse the repository at this point in the history
  • Loading branch information
swhelan091 committed Dec 12, 2019
1 parent b6655ce commit 09a07ea
Show file tree
Hide file tree
Showing 2 changed files with 154 additions and 23 deletions.
28 changes: 11 additions & 17 deletions src/main/java/com/jwplayer/jwplatform/JWPlatformClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -102,16 +102,16 @@ private String encodeStringForJWPlatformAPI(final String stringToEncode)
* appropriate JWPlatformException exception based on the
* error message.
*
* @param response - a {@code HttpResponse} object with the API response
* @param statusCode - the response status code
* @param response - a {@code JSONObject} object with the API response block
* @throws JWPlatformException - API returned an exception
*/
private void checkForNon200Response(final HttpResponse<JsonNode> response) throws JWPlatformException {
if (response.getStatus() != 200) {
private void checkForNon200Response(final int statusCode, final JSONObject response)
throws JWPlatformException {
if (statusCode != 200) {
try {
final String errorType = response.getBody().getObject().get("code").toString();
final String message = response.getBody().getObject().toString(2);
MediaAPIExceptionFactory.throwJWPlatformException(
StringUtils.stripEnd(errorType, "Error"), message);
StringUtils.stripEnd(response.getString("code"), "Error"), response.toString());
} catch (final JSONException e) {
throw new JWPlatformUnknownException(
String.format("Unknown JSONException thrown: %s", e.toString()));
Expand Down Expand Up @@ -172,20 +172,13 @@ private JSONObject uploadVideo(final String uploadPath, final String localFilePa

final Reader reader = new InputStreamReader(r.getBody());
response = XML.toJSONObject(CharStreams.toString(reader));

checkForNon200Response(r.getStatus(), response.getJSONObject("response"));
} catch (final UnirestException | IOException e) {
throw new JWPlatformUnknownException(
String.format("Non-JSON response from server: %s", e.toString()));
}

final JSONObject responseBlock = response.getJSONObject("response");
final String status = responseBlock.getString("status");
if (status.toUpperCase().equals("ERROR")) {
final String errorType = responseBlock.getString("code");
final String message = responseBlock.getString("message");
MediaAPIExceptionFactory.throwJWPlatformException(
StringUtils.stripEnd(errorType, "Error"), message);
}

return response;
}

Expand Down Expand Up @@ -257,9 +250,10 @@ public JSONObject request(final String path, final Map<String, String> params,
default:
throw new JWPlatformException(String.format("%s is not a supported request type.", requestType));
}
checkForNon200Response(response);
final JSONObject responseBlock = response.getBody().getObject();
checkForNon200Response(response.getStatus(), responseBlock);

return response.getBody().getObject();
return responseBlock;
} catch (final UnirestException e) {
throw new JWPlatformUnknownException(
String.format("Non-JSON response from server: %s", e.toString()));
Expand Down
149 changes: 143 additions & 6 deletions src/test/java/com/jwplayer/jwplatform/TestJWPlatformClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,36 @@

import static junit.framework.TestCase.fail;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.anyMap;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.contains;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mockStatic;

import com.jwplayer.jwplatform.exception.JWPlatformException;
import com.jwplayer.jwplatform.exception.JWPlatformUnknownException;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.mashape.unirest.request.GetRequest;
import com.mashape.unirest.request.HttpRequestWithBody;
import com.mashape.unirest.request.body.MultipartBody;
import com.mashape.unirest.request.body.RequestBodyEntity;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.internal.verification.VerificationModeFactory;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Unirest.class, HttpResponse.class})
@PrepareForTest({Unirest.class, HttpResponse.class, HttpRequestWithBody.class, MultipartBody.class})
public class TestJWPlatformClient {

private final String apiKey = "fakeApiKey";
Expand All @@ -32,7 +40,7 @@ public class TestJWPlatformClient {

@Test
@SuppressWarnings("unchecked")
public void testSpecialCharacterUrlEncoding() throws Exception {
public void testGetRequestWithSpecialCharacterUrlEncoding() throws Exception {
final HashMap<String, String> params =
new HashMap<String, String>() {
{
Expand Down Expand Up @@ -69,8 +77,39 @@ public void testSpecialCharacterUrlEncoding() throws Exception {
}
}

@Test
@SuppressWarnings("unchecked")
public void testPostRequestWithSpecialCharacterUrlEncoding() throws Exception {
final HashMap<String, String> params =
new HashMap<String, String>() {
{
put("url", "media.com +!~");
}
};
final JSONObject expectedResponse = new JSONObject();
expectedResponse.put("status", 200);

final HttpResponse httpResponse = PowerMockito.mock(HttpResponse.class);
final JsonNode jsonNode = PowerMockito.mock(JsonNode.class);
when(httpResponse.getBody()).thenReturn(jsonNode);
when(jsonNode.getObject()).thenReturn(expectedResponse);
when(httpResponse.getStatus()).thenReturn(200);
mockStatic(Unirest.class);

final HttpRequestWithBody requestWithBody = PowerMockito.mock(HttpRequestWithBody.class);
final RequestBodyEntity requestBodyEntity = PowerMockito.mock(RequestBodyEntity.class);
when(Unirest.post(anyString())).thenReturn(requestWithBody);
when(requestWithBody.body(any(JSONObject.class))).thenReturn(requestBodyEntity);
when(requestBodyEntity.asJson()).thenReturn(httpResponse);

final JWPlatformClient mediaAPIClient = JWPlatformClient.create(apiKey, apiSecret);
final JSONObject actualResponse = mediaAPIClient.request(path, params, true, "POST");

assertEquals(expectedResponse.getInt("status"), actualResponse.getInt("status"));
}

@Test(expected = JWPlatformUnknownException.class)
public void testRequestNon200ResponseUnknownException() throws Exception {
public void testGetRequestNon200ResponseUnknownException() throws Exception {
final JSONObject expectedResponse = new JSONObject();
final JWPlatformClient mediaAPIClient = JWPlatformClient.create(apiKey, apiSecret);
final HttpResponse httpResponse = PowerMockito.mock(HttpResponse.class);
Expand All @@ -89,7 +128,7 @@ public void testRequestNon200ResponseUnknownException() throws Exception {
}

@Test(expected = JWPlatformUnknownException.class)
public void testRequestUnirestException() throws Exception {
public void testGetRequestUnirestException() throws Exception {
final JWPlatformClient mediaAPIClient = JWPlatformClient.create(apiKey, apiSecret);
final GetRequest getRequest = PowerMockito.mock(GetRequest.class);
mockStatic(Unirest.class);
Expand All @@ -100,4 +139,102 @@ public void testRequestUnirestException() throws Exception {

mediaAPIClient.request(path);
}

@Test(expected = JWPlatformUnknownException.class)
public void testPostRequestNon200ResponseUnknownException() throws Exception {
final JSONObject expectedResponse = new JSONObject();
final JWPlatformClient mediaAPIClient = JWPlatformClient.create(apiKey, apiSecret);
final HttpResponse httpResponse = PowerMockito.mock(HttpResponse.class);
final JsonNode jsonNode = PowerMockito.mock(JsonNode.class);
final HttpRequestWithBody requestWithBody = PowerMockito.mock(HttpRequestWithBody.class);
mockStatic(Unirest.class);

when(Unirest.post(anyString())).thenReturn(requestWithBody);
when(requestWithBody.asJson()).thenReturn(httpResponse);
when(jsonNode.getObject()).thenReturn(expectedResponse);
when(httpResponse.getStatus()).thenReturn(418);
when(httpResponse.getBody()).thenReturn(jsonNode);
when(jsonNode.getObject()).thenReturn(expectedResponse);

mediaAPIClient.request(path, "POST");
}

@Test(expected = JWPlatformUnknownException.class)
public void testPostRequestUnirestException() throws Exception {
final JWPlatformClient mediaAPIClient = JWPlatformClient.create(apiKey, apiSecret);
final HttpRequestWithBody requestWithBody = PowerMockito.mock(HttpRequestWithBody.class);
mockStatic(Unirest.class);

when(Unirest.post(anyString())).thenReturn(requestWithBody);
when(requestWithBody.asJson()).thenThrow(new UnirestException("some exception"));

mediaAPIClient.request(path, "post");
}

@Test(expected = JWPlatformException.class)
public void testExceptionForUnsupportRequestType() throws Exception {
final JWPlatformClient mediaAPIClient = JWPlatformClient.create(apiKey, apiSecret);
mediaAPIClient.request(path, "PUT");
}

@Test
public void testSuccessfulUpload() throws Exception {
final JWPlatformClient mediaAPIClient = JWPlatformClient.create(apiKey, apiSecret);
final HttpRequestWithBody requestWithBody = PowerMockito.mock(HttpRequestWithBody.class);
final MultipartBody multipartBody = PowerMockito.mock(MultipartBody.class);
final HttpResponse<InputStream> response = PowerMockito.mock(HttpResponse.class);
mockStatic(Unirest.class);

final String xmlResponse =
"\"<response>\n"
+ " <redirect_link></redirect_link>\n"
+ " <video>\n"
+ " \t<size>1245108</size>\n"
+ " \t<key>ghi</key>\n"
+ " \t<md5>b73c2094ad142f452312d3f8712c75f1</md5>\n"
+ " </video>\n"
+ " <status>ok</status>\n"
+ " </response>\"";
final InputStream streamResponse = new ByteArrayInputStream(xmlResponse.getBytes());

when(multipartBody.asBinary()).thenReturn(response);
when(response.getBody()).thenReturn(streamResponse);
when(response.getStatus()).thenReturn(200);
when(requestWithBody.field(eq("file"), any(File.class))).thenReturn(multipartBody);
when(Unirest.post(anyString())).thenReturn(requestWithBody);

final Map<String, String> queryBlock = new HashMap<>();
queryBlock.put("key", "abc");
queryBlock.put("token", "def");

final Map<String, Object> linkBlock = new HashMap<>();
linkBlock.put("path", "/v1/videos/upload");
linkBlock.put("protocol", "http");
linkBlock.put("address", "upload-portal.jwplatform.com");
linkBlock.put("query", queryBlock);

final Map<String, Object> videoCreateResponseMap = new HashMap<>();
videoCreateResponseMap.put("link", linkBlock);
videoCreateResponseMap.put("status", "ok");

final JSONObject videoCreateResponse = new JSONObject(videoCreateResponseMap);

final Map<String, Object> expectedVideoBlock = new HashMap<>();
expectedVideoBlock.put("size", 1245108);
expectedVideoBlock.put("key", "ghi");
expectedVideoBlock.put("md5", "b73c2094ad142f452312d3f8712c75f1");

final Map<String, Object> expectedResponseBlock = new HashMap<>();
expectedResponseBlock.put("redirect_link", "");
expectedResponseBlock.put("video", expectedVideoBlock);
expectedResponseBlock.put("status", "ok");
final Map<String, Object> expectedResponseMap = new HashMap<>();
expectedResponseMap.put("response", expectedResponseBlock);

final JSONObject expectedResponse = new JSONObject(expectedResponseMap);

final JSONObject actualResponse = mediaAPIClient.upload(videoCreateResponse, "/some/path");
PowerMockito.verifyStatic(VerificationModeFactory.times(1));
assertEquals(expectedResponse.toString(), actualResponse.toString());
}
}

0 comments on commit 09a07ea

Please sign in to comment.