Skip to content

Commit

Permalink
Adding additional unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Mitali Jha committed Jan 13, 2016
1 parent 99e4818 commit ffdbe28
Show file tree
Hide file tree
Showing 13 changed files with 1,148 additions and 9 deletions.
44 changes: 44 additions & 0 deletions client/src/test/java/org/asynchttpclient/RequestBuilderTest.java
Expand Up @@ -18,14 +18,22 @@
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import static org.asynchttpclient.Dsl.get; import static org.asynchttpclient.Dsl.get;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;


import java.io.IOException; import java.io.IOException;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;


import org.asynchttpclient.cookie.Cookie;
import org.testng.annotations.Test; import org.testng.annotations.Test;


import io.netty.handler.codec.http.HttpMethod;

public class RequestBuilderTest { public class RequestBuilderTest {


private final static String SAFE_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890-_~."; private final static String SAFE_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890-_~.";
Expand Down Expand Up @@ -107,4 +115,40 @@ public void testContentTypeCharsetToBodyEncoding() {
final Request req2 = get("http://localhost").setHeader("Content-Type", "application/json; charset=\"utf-8\"").build(); final Request req2 = get("http://localhost").setHeader("Content-Type", "application/json; charset=\"utf-8\"").build();
assertEquals(req2.getCharset(), UTF_8); assertEquals(req2.getCharset(), UTF_8);
} }

@Test
public void testDefaultMethod() {
RequestBuilder requestBuilder = new RequestBuilder();
String defaultMethodName = HttpMethod.GET.name();
assertEquals(requestBuilder.method, defaultMethodName, "Default HTTP method should be " + defaultMethodName);
}

@Test
public void testSetHeaders() {
RequestBuilder requestBuilder = new RequestBuilder();
assertTrue(requestBuilder.headers.isEmpty(), "Headers should be empty by default.");

Map<String, Collection<String>> headers = new HashMap<>();
headers.put("Content-Type", Collections.singleton("application/json"));
requestBuilder.setHeaders(headers);
assertTrue(requestBuilder.headers.contains("Content-Type"), "headers set by setHeaders have not been set");
assertEquals(requestBuilder.headers.get("Content-Type"), "application/json", "header value incorrect");
}

public void testAddOrReplaceCookies() {
RequestBuilder requestBuilder = new RequestBuilder();
Cookie cookie = new Cookie("name", "value", false, "google.com", "/", 1000, true, true);
requestBuilder.addOrReplaceCookie(cookie);
assertEquals(requestBuilder.cookies.size(), 1, "cookies size should be 1 after adding one cookie");
assertEquals(requestBuilder.cookies.get(0), cookie, "cookie does not match");

Cookie cookie2 = new Cookie("name", "value2", true, "google2.com", "/path", 1001, false, false);
requestBuilder.addOrReplaceCookie(cookie2);
assertEquals(requestBuilder.cookies.size(), 1, "cookies size should remain 1 as we just replaced a cookie with same name");
assertEquals(requestBuilder.cookies.get(0), cookie2, "cookie does not match");

Cookie cookie3 = new Cookie("name", "value", false, "google.com", "/", 1000, true, true);
requestBuilder.addOrReplaceCookie(cookie3);
assertEquals(requestBuilder.cookies.size(), 2, "cookie size must be 2 after adding 1 more cookie i.e. cookie3");
}
} }
Expand Up @@ -37,4 +37,17 @@ public void testSaveLoad() throws Exception {
assertEquals(m.get("http://localhost/test.url"), Long.valueOf(15L)); assertEquals(m.get("http://localhost/test.url"), Long.valueOf(15L));
assertEquals(m.get("http://localhost/test2.url"), Long.valueOf(50L)); assertEquals(m.get("http://localhost/test2.url"), Long.valueOf(50L));
} }

@Test
public void testRemove() {
PropertiesBasedResumableProcessor propertiesProcessor = new PropertiesBasedResumableProcessor();
propertiesProcessor.put("http://localhost/test.url", 15L);
propertiesProcessor.put("http://localhost/test2.url", 50L);
propertiesProcessor.remove("http://localhost/test.url");
propertiesProcessor.save(null);
propertiesProcessor = new PropertiesBasedResumableProcessor();
Map<String, Long> propertiesMap = propertiesProcessor.load();
assertEquals(propertiesMap.size(), 1);
assertEquals(propertiesMap.get("http://localhost/test2.url"), Long.valueOf(50L));
}
} }
Expand Up @@ -14,32 +14,183 @@
*/ */


import static org.asynchttpclient.Dsl.get; import static org.asynchttpclient.Dsl.get;
import static org.mockito.Mockito.*;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.testng.Assert.*; import static org.testng.Assert.*;
import io.netty.handler.codec.http.HttpHeaders;


import java.io.IOException;
import java.nio.ByteBuffer;

import org.asynchttpclient.AsyncHandler;
import org.asynchttpclient.AsyncHandler.State;
import org.asynchttpclient.netty.NettyResponseHeaders;
import org.asynchttpclient.HttpResponseBodyPart;
import org.asynchttpclient.HttpResponseHeaders;
import org.asynchttpclient.HttpResponseStatus;
import org.asynchttpclient.Request; import org.asynchttpclient.Request;
import org.asynchttpclient.uri.Uri;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockTestCase;
import org.testng.annotations.Test; import org.testng.annotations.Test;


import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpHeaders;

/** /**
* @author Benjamin Hanzelmann * @author Benjamin Hanzelmann
*/ */
public class ResumableAsyncHandlerTest { @PrepareForTest({ HttpResponseStatus.class, State.class })

public class ResumableAsyncHandlerTest extends PowerMockTestCase {
@Test(groups = "standalone") @Test
public void testAdjustRange() { public void testAdjustRange() {
MapResumableProcessor proc = new MapResumableProcessor(); MapResumableProcessor proc = new MapResumableProcessor();


ResumableAsyncHandler h = new ResumableAsyncHandler(proc); ResumableAsyncHandler handler = new ResumableAsyncHandler(proc);
Request request = get("http://test/url").build(); Request request = get("http://test/url").build();
Request newRequest = h.adjustRequestRange(request); Request newRequest = handler.adjustRequestRange(request);
assertEquals(newRequest.getUri(), request.getUri()); assertEquals(newRequest.getUri(), request.getUri());
String rangeHeader = newRequest.getHeaders().get(HttpHeaders.Names.RANGE); String rangeHeader = newRequest.getHeaders().get(HttpHeaders.Names.RANGE);
assertNull(rangeHeader); assertNull(rangeHeader);


proc.put("http://test/url", 5000); proc.put("http://test/url", 5000);
newRequest = h.adjustRequestRange(request); newRequest = handler.adjustRequestRange(request);
assertEquals(newRequest.getUri(), request.getUri()); assertEquals(newRequest.getUri(), request.getUri());
rangeHeader = newRequest.getHeaders().get(HttpHeaders.Names.RANGE); rangeHeader = newRequest.getHeaders().get(HttpHeaders.Names.RANGE);
assertEquals(rangeHeader, "bytes=5000-"); assertEquals(rangeHeader, "bytes=5000-");
} }

@Test
public void testOnStatusReceivedOkStatus() throws Exception {
MapResumableProcessor processor = new MapResumableProcessor();
ResumableAsyncHandler handler = new ResumableAsyncHandler(processor);
HttpResponseStatus responseStatus200 = mock(HttpResponseStatus.class);
when(responseStatus200.getStatusCode()).thenReturn(200);
when(responseStatus200.getUri()).thenReturn(mock(Uri.class));
State state = handler.onStatusReceived(responseStatus200);
assertEquals(state, AsyncHandler.State.CONTINUE, "Status should be CONTINUE for a OK response");
}

@Test
public void testOnStatusReceived206Status() throws Exception {
MapResumableProcessor processor = new MapResumableProcessor();
ResumableAsyncHandler handler = new ResumableAsyncHandler(processor);
HttpResponseStatus responseStatus206 = mock(HttpResponseStatus.class);
when(responseStatus206.getStatusCode()).thenReturn(206);
when(responseStatus206.getUri()).thenReturn(mock(Uri.class));
State state = handler.onStatusReceived(responseStatus206);
assertEquals(state, AsyncHandler.State.CONTINUE, "Status should be CONTINUE for a 'Partial Content' response");
}

@Test
public void testOnStatusReceivedOkStatusWithDecoratedAsyncHandler() throws Exception {
HttpResponseStatus mockResponseStatus = mock(HttpResponseStatus.class);
when(mockResponseStatus.getStatusCode()).thenReturn(200);
when(mockResponseStatus.getUri()).thenReturn(mock(Uri.class));

AsyncHandler decoratedAsyncHandler = mock(AsyncHandler.class);
State mockState = mock(State.class);
when(decoratedAsyncHandler.onStatusReceived(mockResponseStatus)).thenReturn(mockState);

ResumableAsyncHandler handler = new ResumableAsyncHandler(decoratedAsyncHandler);

State state = handler.onStatusReceived(mockResponseStatus);
verify(decoratedAsyncHandler).onStatusReceived(mockResponseStatus);
assertEquals(state, mockState, "State returned should be equal to the one returned from decoratedAsyncHandler");
}

@Test
public void testOnStatusReceived500Status() throws Exception{
MapResumableProcessor processor = new MapResumableProcessor();
ResumableAsyncHandler handler = new ResumableAsyncHandler(processor);
HttpResponseStatus mockResponseStatus = mock(HttpResponseStatus.class);
when(mockResponseStatus.getStatusCode()).thenReturn(500);
when(mockResponseStatus.getUri()).thenReturn(mock(Uri.class));
State state = handler.onStatusReceived(mockResponseStatus);
assertEquals(state, AsyncHandler.State.ABORT, "State should be ABORT for Internal Server Error status");
}

@Test
public void testOnBodyPartReceived() throws Exception {
ResumableAsyncHandler handler = new ResumableAsyncHandler();
HttpResponseBodyPart bodyPart = PowerMockito.mock(HttpResponseBodyPart.class);
when(bodyPart.getBodyPartBytes()).thenReturn(new byte[0]);
ByteBuffer buffer = ByteBuffer.allocate(0);
when(bodyPart.getBodyByteBuffer()).thenReturn(buffer);
State state = handler.onBodyPartReceived(bodyPart);
assertEquals(state, AsyncHandler.State.CONTINUE, "State should be CONTINUE for a successful onBodyPartReceived");
}

@Test
public void testOnBodyPartReceivedWithResumableListenerThrowsException() throws Exception {
ResumableAsyncHandler handler = new ResumableAsyncHandler();

ResumableListener resumableListener = PowerMockito.mock(ResumableListener.class);
doThrow(new IOException()).when(resumableListener).onBytesReceived(anyObject());
handler.setResumableListener(resumableListener);

HttpResponseBodyPart bodyPart = PowerMockito.mock(HttpResponseBodyPart.class);
State state = handler.onBodyPartReceived(bodyPart);
assertEquals(state, AsyncHandler.State.ABORT,
"State should be ABORT if the resumableListener threw an exception in onBodyPartReceived");
}

@Test
public void testOnBodyPartReceivedWithDecoratedAsyncHandler() throws Exception {
HttpResponseBodyPart bodyPart = PowerMockito.mock(HttpResponseBodyPart.class);
when(bodyPart.getBodyPartBytes()).thenReturn(new byte[0]);
ByteBuffer buffer = ByteBuffer.allocate(0);
when(bodyPart.getBodyByteBuffer()).thenReturn(buffer);

AsyncHandler decoratedAsyncHandler = mock(AsyncHandler.class);
State mockState = mock(State.class);
when(decoratedAsyncHandler.onBodyPartReceived(bodyPart)).thenReturn(mockState);

// following is needed to set the url variable
HttpResponseStatus mockResponseStatus = mock(HttpResponseStatus.class);
when(mockResponseStatus.getStatusCode()).thenReturn(200);
Uri mockUri = mock(Uri.class);
when(mockUri.toUrl()).thenReturn("http://non.null");
when(mockResponseStatus.getUri()).thenReturn(mockUri);

ResumableAsyncHandler handler = new ResumableAsyncHandler(decoratedAsyncHandler);
handler.onStatusReceived(mockResponseStatus);

State state = handler.onBodyPartReceived(bodyPart);
assertEquals(state, mockState, "State should be equal to the state returned from decoratedAsyncHandler");

}

@Test
public void testOnHeadersReceived() throws Exception {
ResumableAsyncHandler handler = new ResumableAsyncHandler();
HttpHeaders responseHeaders = new DefaultHttpHeaders();
HttpResponseHeaders headers = new NettyResponseHeaders(responseHeaders);
State status = handler.onHeadersReceived(headers);
assertEquals(status, AsyncHandler.State.CONTINUE, "State should be CONTINUE for a successful onHeadersReceived");
}

@Test
public void testOnHeadersReceivedWithDecoratedAsyncHandler() throws Exception {
HttpHeaders responseHeaders = new DefaultHttpHeaders();
HttpResponseHeaders headers = new NettyResponseHeaders(responseHeaders);

AsyncHandler decoratedAsyncHandler = mock(AsyncHandler.class);
State mockState = mock(State.class);
when(decoratedAsyncHandler.onHeadersReceived(headers)).thenReturn(mockState);

ResumableAsyncHandler handler = new ResumableAsyncHandler(decoratedAsyncHandler);
State status = handler.onHeadersReceived(headers);
assertEquals(status, mockState, "State should be equal to the state returned from decoratedAsyncHandler");
}

@Test
public void testOnHeadersReceivedContentLengthMinus() throws Exception {
ResumableAsyncHandler handler = new ResumableAsyncHandler();
HttpHeaders responseHeaders = new DefaultHttpHeaders();
responseHeaders.add(HttpHeaders.Names.CONTENT_LENGTH, -1);
HttpResponseHeaders headers = new NettyResponseHeaders(responseHeaders);
State status = handler.onHeadersReceived(headers);
assertEquals(status, AsyncHandler.State.ABORT, "State should be ABORT for content length -1");
}
} }
@@ -0,0 +1,37 @@
package org.asynchttpclient.handler.resumable;

import static org.mockito.Mockito.*;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;

import org.powermock.api.mockito.PowerMockito;
import org.testng.annotations.Test;

public class ResumableRandomAccessFileListenerTest {

@Test
public void testOnBytesReceivedBufferHasArray() throws IOException {
RandomAccessFile file = PowerMockito.mock(RandomAccessFile.class);
ResumableRandomAccessFileListener listener = new ResumableRandomAccessFileListener(file);
byte[] array = new byte[] { 1, 2, 23, 33 };
ByteBuffer buf = ByteBuffer.wrap(array);
listener.onBytesReceived(buf);
verify(file).write(array, 0, 4);
}

@Test
public void testOnBytesReceivedBufferHasNoArray() throws IOException {
RandomAccessFile file = PowerMockito.mock(RandomAccessFile.class);
ResumableRandomAccessFileListener listener = new ResumableRandomAccessFileListener(file);

byte[] byteArray = new byte[] { 1, 2, 23, 33 };
ByteBuffer buf = ByteBuffer.allocateDirect(4);
buf.put(byteArray);
buf.flip();
listener.onBytesReceived(buf);
verify(file).write(byteArray);
}

}
@@ -0,0 +1,73 @@
package org.asynchttpclient.netty;

import static org.testng.Assert.*;

import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;

import static org.mockito.Mockito.*;

import org.asynchttpclient.AsyncHandler;
import org.testng.annotations.Test;

public class NettyResponseFutureTest {

@Test
public void testCancel() {
AsyncHandler asyncHandler = mock(AsyncHandler.class);
NettyResponseFuture nettyResponseFuture = new NettyResponseFuture<>(null, asyncHandler, null, 3, null, null);
boolean result = nettyResponseFuture.cancel(false);
verify(asyncHandler).onThrowable(anyObject());
assertTrue(result, "Cancel should return true if the Future was cancelled successfully");
assertTrue(nettyResponseFuture.isCancelled(), "isCancelled should return true for a cancelled Future");
}

@Test
public void testCancelOnAlreadyCancelled() {
AsyncHandler asyncHandler = mock(AsyncHandler.class);
NettyResponseFuture nettyResponseFuture = new NettyResponseFuture<>(null, asyncHandler, null, 3, null, null);
nettyResponseFuture.cancel(false);
boolean result = nettyResponseFuture.cancel(false);
assertFalse(result, "cancel should return false for an already cancelled Future");
assertTrue(nettyResponseFuture.isCancelled(), "isCancelled should return true for a cancelled Future");
}

@Test(expectedExceptions = CancellationException.class)
public void testGetContentThrowsCancellationExceptionIfCancelled() throws InterruptedException, ExecutionException {
AsyncHandler asyncHandler = mock(AsyncHandler.class);
NettyResponseFuture nettyResponseFuture = new NettyResponseFuture<>(null, asyncHandler, null, 3, null, null);
nettyResponseFuture.cancel(false);
nettyResponseFuture.get();
fail("A CancellationException must have occurred by now as 'cancel' was called before 'get'");
}

@Test
public void testGet() throws Exception {
AsyncHandler asyncHandler = mock(AsyncHandler.class);
Object value = new Object();
when(asyncHandler.onCompleted()).thenReturn(value);
NettyResponseFuture nettyResponseFuture = new NettyResponseFuture<>(null, asyncHandler, null, 3, null, null);
nettyResponseFuture.done();
Object result = nettyResponseFuture.get();
assertEquals(result, value, "The Future should return the value given by asyncHandler#onCompleted");
}

@Test(expectedExceptions = ExecutionException.class)
public void testGetThrowsExceptionThrownByAsyncHandler() throws Exception {
AsyncHandler asyncHandler = mock(AsyncHandler.class);
when(asyncHandler.onCompleted()).thenThrow(new RuntimeException());
NettyResponseFuture nettyResponseFuture = new NettyResponseFuture<>(null, asyncHandler, null, 3, null, null);
nettyResponseFuture.done();
nettyResponseFuture.get();
fail("An ExecutionException must have occurred by now as asyncHandler threw an exception in 'onCompleted'");
}

@Test(expectedExceptions = ExecutionException.class)
public void testGetThrowsExceptionOnAbort() throws InterruptedException, ExecutionException {
AsyncHandler asyncHandler = mock(AsyncHandler.class);
NettyResponseFuture nettyResponseFuture = new NettyResponseFuture<>(null, asyncHandler, null, 3, null, null);
nettyResponseFuture.abort(new RuntimeException());
nettyResponseFuture.get();
fail("An ExecutionException must have occurred by now as 'abort' was called before 'get'");
}
}

0 comments on commit ffdbe28

Please sign in to comment.