From 09a07eadccc542c576fe366853f24be0f3026022 Mon Sep 17 00:00:00 2001 From: Steve Whelan Date: Thu, 12 Dec 2019 14:31:15 -0500 Subject: [PATCH] Add test for POST request. Refactor status check. --- .../jwplayer/jwplatform/JWPlatformClient.java | 28 ++-- .../jwplatform/TestJWPlatformClient.java | 149 +++++++++++++++++- 2 files changed, 154 insertions(+), 23 deletions(-) diff --git a/src/main/java/com/jwplayer/jwplatform/JWPlatformClient.java b/src/main/java/com/jwplayer/jwplatform/JWPlatformClient.java index 5b846fa..5395e26 100644 --- a/src/main/java/com/jwplayer/jwplatform/JWPlatformClient.java +++ b/src/main/java/com/jwplayer/jwplatform/JWPlatformClient.java @@ -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 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())); @@ -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; } @@ -257,9 +250,10 @@ public JSONObject request(final String path, final Map 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())); diff --git a/src/test/java/com/jwplayer/jwplatform/TestJWPlatformClient.java b/src/test/java/com/jwplayer/jwplatform/TestJWPlatformClient.java index 17e78a7..a750004 100644 --- a/src/test/java/com/jwplayer/jwplatform/TestJWPlatformClient.java +++ b/src/test/java/com/jwplayer/jwplatform/TestJWPlatformClient.java @@ -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"; @@ -32,7 +40,7 @@ public class TestJWPlatformClient { @Test @SuppressWarnings("unchecked") - public void testSpecialCharacterUrlEncoding() throws Exception { + public void testGetRequestWithSpecialCharacterUrlEncoding() throws Exception { final HashMap params = new HashMap() { { @@ -69,8 +77,39 @@ public void testSpecialCharacterUrlEncoding() throws Exception { } } + @Test + @SuppressWarnings("unchecked") + public void testPostRequestWithSpecialCharacterUrlEncoding() throws Exception { + final HashMap params = + new HashMap() { + { + 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); @@ -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); @@ -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 response = PowerMockito.mock(HttpResponse.class); + mockStatic(Unirest.class); + + final String xmlResponse = + "\"\n" + + " \n" + + " \n" + + " ok\n" + + " \""; + 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 queryBlock = new HashMap<>(); + queryBlock.put("key", "abc"); + queryBlock.put("token", "def"); + + final Map 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 videoCreateResponseMap = new HashMap<>(); + videoCreateResponseMap.put("link", linkBlock); + videoCreateResponseMap.put("status", "ok"); + + final JSONObject videoCreateResponse = new JSONObject(videoCreateResponseMap); + + final Map expectedVideoBlock = new HashMap<>(); + expectedVideoBlock.put("size", 1245108); + expectedVideoBlock.put("key", "ghi"); + expectedVideoBlock.put("md5", "b73c2094ad142f452312d3f8712c75f1"); + + final Map expectedResponseBlock = new HashMap<>(); + expectedResponseBlock.put("redirect_link", ""); + expectedResponseBlock.put("video", expectedVideoBlock); + expectedResponseBlock.put("status", "ok"); + final Map 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()); + } }