HTTPCLIENT-1244: convert unit tests for cache module to use Mockito

Contributed by Joseph Walton <joe at kafsemo dot org>

git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@1661658 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Oleg Kalnichevski 2015-02-23 12:42:47 +00:00
parent d6b8a525b9
commit 95754d776c
14 changed files with 661 additions and 711 deletions

View File

@ -74,6 +74,11 @@
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.easymock</groupId> <groupId>org.easymock</groupId>
<artifactId>easymock</artifactId> <artifactId>easymock</artifactId>

View File

@ -26,7 +26,6 @@
*/ */
package org.apache.http.client.cache; package org.apache.http.client.cache;
import static org.easymock.classextension.EasyMock.createNiceMock;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
@ -34,6 +33,7 @@ import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
@ -65,7 +65,7 @@ public class TestHttpCacheEntry {
nineSecondsAgo = new Date(now.getTime() - 9 * 1000L); nineSecondsAgo = new Date(now.getTime() - 9 * 1000L);
statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1,
HttpStatus.SC_OK, "OK"); HttpStatus.SC_OK, "OK");
mockResource = createNiceMock(Resource.class); mockResource = mock(Resource.class);
} }
private HttpCacheEntry makeEntry(final Header[] headers) { private HttpCacheEntry makeEntry(final Header[] headers) {

View File

@ -26,6 +26,10 @@
*/ */
package org.apache.http.impl.client.cache; package org.apache.http.impl.client.cache;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException; import java.io.IOException;
import org.apache.http.Header; import org.apache.http.Header;
@ -41,7 +45,6 @@ import org.apache.http.client.methods.HttpRequestWrapper;
import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.routing.HttpRoute; import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHeader;
import org.easymock.classextension.EasyMock;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -60,15 +63,15 @@ public class TestAsynchronousValidationRequest {
@Before @Before
public void setUp() { public void setUp() {
mockParent = EasyMock.createNiceMock(AsynchronousValidator.class); mockParent = mock(AsynchronousValidator.class);
mockClient = EasyMock.createNiceMock(CachingExec.class); mockClient = mock(CachingExec.class);
route = new HttpRoute(new HttpHost("foo.example.com", 80)); route = new HttpRoute(new HttpHost("foo.example.com", 80));
request = HttpRequestWrapper.wrap(new HttpGet("/")); request = HttpRequestWrapper.wrap(new HttpGet("/"));
context = HttpClientContext.create(); context = HttpClientContext.create();
mockExecAware = EasyMock.createNiceMock(HttpExecutionAware.class); mockExecAware = mock(HttpExecutionAware.class);
mockCacheEntry = EasyMock.createNiceMock(HttpCacheEntry.class); mockCacheEntry = mock(HttpCacheEntry.class);
mockResponse = EasyMock.createNiceMock(CloseableHttpResponse.class); mockResponse = mock(CloseableHttpResponse.class);
mockStatusLine = EasyMock.createNiceMock(StatusLine.class); mockStatusLine = mock(StatusLine.class);
} }
@Test @Test
@ -79,17 +82,19 @@ public class TestAsynchronousValidationRequest {
mockParent, mockClient, route, request, context, mockExecAware, mockCacheEntry, mockParent, mockClient, route, request, context, mockExecAware, mockCacheEntry,
identifier, 0); identifier, 0);
EasyMock.expect( when(
mockClient.revalidateCacheEntry( mockClient.revalidateCacheEntry(
route, request, context, mockExecAware, mockCacheEntry)).andReturn(mockResponse); route, request, context, mockExecAware, mockCacheEntry)).thenReturn(mockResponse);
EasyMock.expect(mockResponse.getStatusLine()).andReturn(mockStatusLine); when(mockResponse.getStatusLine()).thenReturn(mockStatusLine);
EasyMock.expect(mockStatusLine.getStatusCode()).andReturn(200); when(mockStatusLine.getStatusCode()).thenReturn(200);
mockParent.markComplete(identifier);
mockParent.jobSuccessful(identifier);
replayMocks();
impl.run(); impl.run();
verifyMocks();
verify(mockClient).revalidateCacheEntry(
route, request, context, mockExecAware, mockCacheEntry);
verify(mockResponse).getStatusLine();
verify(mockParent).markComplete(identifier);
verify(mockParent).jobSuccessful(identifier);
} }
@Test @Test
@ -100,17 +105,20 @@ public class TestAsynchronousValidationRequest {
mockParent, mockClient, route, request, context, mockExecAware, mockCacheEntry, mockParent, mockClient, route, request, context, mockExecAware, mockCacheEntry,
identifier, 0); identifier, 0);
EasyMock.expect( when(
mockClient.revalidateCacheEntry( mockClient.revalidateCacheEntry(
route, request, context, mockExecAware, mockCacheEntry)).andReturn(mockResponse); route, request, context, mockExecAware, mockCacheEntry)).thenReturn(mockResponse);
EasyMock.expect(mockResponse.getStatusLine()).andReturn(mockStatusLine); when(mockResponse.getStatusLine()).thenReturn(mockStatusLine);
EasyMock.expect(mockStatusLine.getStatusCode()).andReturn(200); when(mockStatusLine.getStatusCode()).thenReturn(200);
mockParent.markComplete(identifier);
mockParent.jobSuccessful(identifier);
replayMocks();
impl.run(); impl.run();
verifyMocks();
verify(mockClient).revalidateCacheEntry(
route, request, context, mockExecAware, mockCacheEntry);
verify(mockResponse).getStatusLine();
verify(mockStatusLine).getStatusCode();
verify(mockParent).markComplete(identifier);
verify(mockParent).jobSuccessful(identifier);
} }
@Test @Test
@ -122,18 +130,22 @@ public class TestAsynchronousValidationRequest {
mockParent, mockClient, route, request, context, mockExecAware, mockCacheEntry, mockParent, mockClient, route, request, context, mockExecAware, mockCacheEntry,
identifier, 0); identifier, 0);
EasyMock.expect( when(
mockClient.revalidateCacheEntry( mockClient.revalidateCacheEntry(
route, request, context, mockExecAware, mockCacheEntry)).andReturn(mockResponse); route, request, context, mockExecAware, mockCacheEntry)).thenReturn(mockResponse);
EasyMock.expect(mockResponse.getStatusLine()).andReturn(mockStatusLine); when(mockResponse.getStatusLine()).thenReturn(mockStatusLine);
EasyMock.expect(mockStatusLine.getStatusCode()).andReturn(200); when(mockStatusLine.getStatusCode()).thenReturn(200);
EasyMock.expect(mockResponse.getHeaders(HeaderConstants.WARNING)).andReturn(warning); when(mockResponse.getHeaders(HeaderConstants.WARNING)).thenReturn(warning);
mockParent.markComplete(identifier);
mockParent.jobFailed(identifier);
replayMocks();
impl.run(); impl.run();
verifyMocks();
verify(mockClient).revalidateCacheEntry(
route, request, context, mockExecAware, mockCacheEntry);
verify(mockResponse).getStatusLine();
verify(mockStatusLine).getStatusCode();
verify(mockResponse).getHeaders(HeaderConstants.WARNING);
verify(mockParent).markComplete(identifier);
verify(mockParent).jobFailed(identifier);
} }
@Test @Test
@ -144,16 +156,17 @@ public class TestAsynchronousValidationRequest {
mockParent, mockClient, route, request, context, mockExecAware, mockCacheEntry, mockParent, mockClient, route, request, context, mockExecAware, mockCacheEntry,
identifier, 0); identifier, 0);
EasyMock.expect( when(
mockClient.revalidateCacheEntry( mockClient.revalidateCacheEntry(
route, request, context, mockExecAware, mockCacheEntry)).andThrow( route, request, context, mockExecAware, mockCacheEntry)).thenThrow(
new ProtocolException()); new ProtocolException());
mockParent.markComplete(identifier);
mockParent.jobFailed(identifier);
replayMocks();
impl.run(); impl.run();
verifyMocks();
verify(mockClient).revalidateCacheEntry(
route, request, context, mockExecAware, mockCacheEntry);
verify(mockParent).markComplete(identifier);
verify(mockParent).jobFailed(identifier);
} }
@Test @Test
@ -164,16 +177,17 @@ public class TestAsynchronousValidationRequest {
mockParent, mockClient, route, request, context, mockExecAware, mockCacheEntry, mockParent, mockClient, route, request, context, mockExecAware, mockCacheEntry,
identifier, 0); identifier, 0);
EasyMock.expect( when(
mockClient.revalidateCacheEntry( mockClient.revalidateCacheEntry(
route, request, context, mockExecAware, mockCacheEntry)).andThrow( route, request, context, mockExecAware, mockCacheEntry)).thenThrow(
new IOException()); new IOException());
mockParent.markComplete(identifier);
mockParent.jobFailed(identifier);
replayMocks();
impl.run(); impl.run();
verifyMocks();
verify(mockClient).revalidateCacheEntry(
route, request, context, mockExecAware, mockCacheEntry);
verify(mockParent).markComplete(identifier);
verify(mockParent).jobFailed(identifier);
} }
@Test @Test
@ -184,33 +198,16 @@ public class TestAsynchronousValidationRequest {
mockParent, mockClient, route, request, context, mockExecAware, mockCacheEntry, mockParent, mockClient, route, request, context, mockExecAware, mockCacheEntry,
identifier, 0); identifier, 0);
EasyMock.expect( when(
mockClient.revalidateCacheEntry( mockClient.revalidateCacheEntry(
route, request, context, mockExecAware, mockCacheEntry)).andThrow( route, request, context, mockExecAware, mockCacheEntry)).thenThrow(
new RuntimeException()); new RuntimeException());
mockParent.markComplete(identifier);
mockParent.jobFailed(identifier);
replayMocks();
impl.run(); impl.run();
verifyMocks();
}
public void replayMocks() { verify(mockClient).revalidateCacheEntry(
EasyMock.replay(mockClient); route, request, context, mockExecAware, mockCacheEntry);
EasyMock.replay(mockExecAware); verify(mockParent).markComplete(identifier);
EasyMock.replay(mockCacheEntry); verify(mockParent).jobFailed(identifier);
EasyMock.replay(mockResponse);
EasyMock.replay(mockStatusLine);
EasyMock.replay(mockParent);
}
public void verifyMocks() {
EasyMock.verify(mockClient);
EasyMock.verify(mockExecAware);
EasyMock.verify(mockCacheEntry);
EasyMock.verify(mockResponse);
EasyMock.verify(mockStatusLine);
EasyMock.verify(mockParent);
} }
} }

View File

@ -26,6 +26,13 @@
*/ */
package org.apache.http.impl.client.cache; package org.apache.http.impl.client.cache;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException; import java.io.IOException;
import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -41,11 +48,10 @@ import org.apache.http.client.methods.HttpRequestWrapper;
import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.routing.HttpRoute; import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHeader;
import org.easymock.Capture;
import org.easymock.classextension.EasyMock;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.ArgumentCaptor;
@SuppressWarnings({"boxing","static-access"}) // test code @SuppressWarnings({"boxing","static-access"}) // test code
public class TestAsynchronousValidator { public class TestAsynchronousValidator {
@ -63,26 +69,26 @@ public class TestAsynchronousValidator {
@Before @Before
public void setUp() { public void setUp() {
mockClient = EasyMock.createNiceMock(CachingExec.class); mockClient = mock(CachingExec.class);
route = new HttpRoute(new HttpHost("foo.example.com", 80)); route = new HttpRoute(new HttpHost("foo.example.com", 80));
request = HttpRequestWrapper.wrap(new HttpGet("/")); request = HttpRequestWrapper.wrap(new HttpGet("/"));
context = HttpClientContext.create(); context = HttpClientContext.create();
context.setTargetHost(new HttpHost("foo.example.com")); context.setTargetHost(new HttpHost("foo.example.com"));
mockExecAware = EasyMock.createNiceMock(HttpExecutionAware.class); mockExecAware = mock(HttpExecutionAware.class);
mockCacheEntry = EasyMock.createNiceMock(HttpCacheEntry.class); mockCacheEntry = mock(HttpCacheEntry.class);
mockSchedulingStrategy = EasyMock.createNiceMock(SchedulingStrategy.class); mockSchedulingStrategy = mock(SchedulingStrategy.class);
} }
@Test @Test
public void testRevalidateCacheEntrySchedulesExecutionAndPopulatesIdentifier() { public void testRevalidateCacheEntrySchedulesExecutionAndPopulatesIdentifier() {
impl = new AsynchronousValidator(mockSchedulingStrategy); impl = new AsynchronousValidator(mockSchedulingStrategy);
EasyMock.expect(mockCacheEntry.hasVariants()).andReturn(false); when(mockCacheEntry.hasVariants()).thenReturn(false);
mockSchedulingStrategy.schedule(EasyMock.isA(AsynchronousValidationRequest.class));
replayMocks();
impl.revalidateCacheEntry(mockClient, route, request, context, mockExecAware, mockCacheEntry); impl.revalidateCacheEntry(mockClient, route, request, context, mockExecAware, mockCacheEntry);
verifyMocks();
verify(mockCacheEntry).hasVariants();
verify(mockSchedulingStrategy).schedule(isA(AsynchronousValidationRequest.class));
Assert.assertEquals(1, impl.getScheduledIdentifiers().size()); Assert.assertEquals(1, impl.getScheduledIdentifiers().size());
} }
@ -91,13 +97,13 @@ public class TestAsynchronousValidator {
public void testMarkCompleteRemovesIdentifier() { public void testMarkCompleteRemovesIdentifier() {
impl = new AsynchronousValidator(mockSchedulingStrategy); impl = new AsynchronousValidator(mockSchedulingStrategy);
EasyMock.expect(mockCacheEntry.hasVariants()).andReturn(false); when(mockCacheEntry.hasVariants()).thenReturn(false);
final Capture<AsynchronousValidationRequest> cap = new Capture<AsynchronousValidationRequest>();
mockSchedulingStrategy.schedule(EasyMock.capture(cap));
replayMocks();
impl.revalidateCacheEntry(mockClient, route, request, context, mockExecAware, mockCacheEntry); impl.revalidateCacheEntry(mockClient, route, request, context, mockExecAware, mockCacheEntry);
verifyMocks();
final ArgumentCaptor<AsynchronousValidationRequest> cap = ArgumentCaptor.forClass(AsynchronousValidationRequest.class);
verify(mockCacheEntry).hasVariants();
verify(mockSchedulingStrategy).schedule(cap.capture());
Assert.assertEquals(1, impl.getScheduledIdentifiers().size()); Assert.assertEquals(1, impl.getScheduledIdentifiers().size());
@ -110,30 +116,28 @@ public class TestAsynchronousValidator {
public void testRevalidateCacheEntryDoesNotPopulateIdentifierOnRejectedExecutionException() { public void testRevalidateCacheEntryDoesNotPopulateIdentifierOnRejectedExecutionException() {
impl = new AsynchronousValidator(mockSchedulingStrategy); impl = new AsynchronousValidator(mockSchedulingStrategy);
EasyMock.expect(mockCacheEntry.hasVariants()).andReturn(false); when(mockCacheEntry.hasVariants()).thenReturn(false);
mockSchedulingStrategy.schedule(EasyMock.isA(AsynchronousValidationRequest.class)); doThrow(new RejectedExecutionException()).when(mockSchedulingStrategy).schedule(isA(AsynchronousValidationRequest.class));
EasyMock.expectLastCall().andThrow(new RejectedExecutionException());
replayMocks();
impl.revalidateCacheEntry(mockClient, route, request, context, mockExecAware, mockCacheEntry); impl.revalidateCacheEntry(mockClient, route, request, context, mockExecAware, mockCacheEntry);
verifyMocks();
verify(mockCacheEntry).hasVariants();
Assert.assertEquals(0, impl.getScheduledIdentifiers().size()); Assert.assertEquals(0, impl.getScheduledIdentifiers().size());
verify(mockSchedulingStrategy).schedule(isA(AsynchronousValidationRequest.class));
} }
@Test @Test
public void testRevalidateCacheEntryProperlyCollapsesRequest() { public void testRevalidateCacheEntryProperlyCollapsesRequest() {
impl = new AsynchronousValidator(mockSchedulingStrategy); impl = new AsynchronousValidator(mockSchedulingStrategy);
EasyMock.expect(mockCacheEntry.hasVariants()).andReturn(false); when(mockCacheEntry.hasVariants()).thenReturn(false);
mockSchedulingStrategy.schedule(EasyMock.isA(AsynchronousValidationRequest.class));
EasyMock.expect(mockCacheEntry.hasVariants()).andReturn(false);
replayMocks();
impl.revalidateCacheEntry(mockClient, route, request, context, mockExecAware, mockCacheEntry); impl.revalidateCacheEntry(mockClient, route, request, context, mockExecAware, mockCacheEntry);
impl.revalidateCacheEntry(mockClient, route, request, context, mockExecAware, mockCacheEntry); impl.revalidateCacheEntry(mockClient, route, request, context, mockExecAware, mockCacheEntry);
verifyMocks();
verify(mockCacheEntry, times(2)).hasVariants();
verify(mockSchedulingStrategy).schedule(isA(AsynchronousValidationRequest.class));
Assert.assertEquals(1, impl.getScheduledIdentifiers().size()); Assert.assertEquals(1, impl.getScheduledIdentifiers().size());
} }
@ -152,18 +156,18 @@ public class TestAsynchronousValidator {
new BasicHeader(HeaderConstants.VARY, "Accept-Encoding") new BasicHeader(HeaderConstants.VARY, "Accept-Encoding")
}; };
EasyMock.expect(mockCacheEntry.hasVariants()).andReturn(true).times(2); when(mockCacheEntry.hasVariants()).thenReturn(true);
EasyMock.expect(mockCacheEntry.getHeaders(HeaderConstants.VARY)).andReturn(variantHeaders).times(2); when(mockCacheEntry.getHeaders(HeaderConstants.VARY)).thenReturn(variantHeaders);
mockSchedulingStrategy.schedule(EasyMock.isA(AsynchronousValidationRequest.class)); mockSchedulingStrategy.schedule(isA(AsynchronousValidationRequest.class));
EasyMock.expectLastCall().times(2);
replayMocks();
impl.revalidateCacheEntry(mockClient, route, HttpRequestWrapper.wrap(req1), context, mockExecAware, mockCacheEntry); impl.revalidateCacheEntry(mockClient, route, HttpRequestWrapper.wrap(req1), context, mockExecAware, mockCacheEntry);
impl.revalidateCacheEntry(mockClient, route, HttpRequestWrapper.wrap(req2), context, mockExecAware, mockCacheEntry); impl.revalidateCacheEntry(mockClient, route, HttpRequestWrapper.wrap(req2), context, mockExecAware, mockCacheEntry);
verifyMocks();
verify(mockCacheEntry, times(2)).hasVariants();
verify(mockCacheEntry, times(2)).getHeaders(HeaderConstants.VARY);
verify(mockSchedulingStrategy, times(2)).schedule(isA(AsynchronousValidationRequest.class));
Assert.assertEquals(2, impl.getScheduledIdentifiers().size()); Assert.assertEquals(2, impl.getScheduledIdentifiers().size());
} }
@Test @Test
@ -175,11 +179,10 @@ public class TestAsynchronousValidator {
final ImmediateSchedulingStrategy schedulingStrategy = new ImmediateSchedulingStrategy(config); final ImmediateSchedulingStrategy schedulingStrategy = new ImmediateSchedulingStrategy(config);
impl = new AsynchronousValidator(schedulingStrategy); impl = new AsynchronousValidator(schedulingStrategy);
EasyMock.expect(mockCacheEntry.hasVariants()).andReturn(false); when(mockCacheEntry.hasVariants()).thenReturn(false);
EasyMock.expect(mockClient.revalidateCacheEntry( when(mockClient.revalidateCacheEntry(
route, request, context, mockExecAware, mockCacheEntry)).andReturn(null); route, request, context, mockExecAware, mockCacheEntry)).thenReturn(null);
replayMocks();
impl.revalidateCacheEntry(mockClient, route, request, context, mockExecAware, mockCacheEntry); impl.revalidateCacheEntry(mockClient, route, request, context, mockExecAware, mockCacheEntry);
try { try {
@ -189,7 +192,8 @@ public class TestAsynchronousValidator {
} catch (final InterruptedException ie) { } catch (final InterruptedException ie) {
} finally { } finally {
verifyMocks(); verify(mockCacheEntry).hasVariants();
verify(mockClient).revalidateCacheEntry(route, request, context, mockExecAware, mockCacheEntry);
Assert.assertEquals(0, impl.getScheduledIdentifiers().size()); Assert.assertEquals(0, impl.getScheduledIdentifiers().size());
} }
@ -199,24 +203,8 @@ public class TestAsynchronousValidator {
public void testSchedulingStrategyShutdownOnClose() throws IOException { public void testSchedulingStrategyShutdownOnClose() throws IOException {
impl = new AsynchronousValidator(mockSchedulingStrategy); impl = new AsynchronousValidator(mockSchedulingStrategy);
mockSchedulingStrategy.close();
replayMocks();
impl.close(); impl.close();
verifyMocks();
}
public void replayMocks() { verify(mockSchedulingStrategy).close();
EasyMock.replay(mockSchedulingStrategy);
EasyMock.replay(mockClient);
EasyMock.replay(mockExecAware);
EasyMock.replay(mockCacheEntry);
}
public void verifyMocks() {
EasyMock.verify(mockSchedulingStrategy);
EasyMock.verify(mockClient);
EasyMock.verify(mockExecAware);
EasyMock.verify(mockCacheEntry);
} }
} }

View File

@ -26,10 +26,10 @@
*/ */
package org.apache.http.impl.client.cache; package org.apache.http.impl.client.cache;
import static org.easymock.EasyMock.expect; import static org.mockito.Mockito.mock;
import static org.easymock.classextension.EasyMock.createNiceMock; import static org.mockito.Mockito.verify;
import static org.easymock.classextension.EasyMock.replay; import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.easymock.classextension.EasyMock.verify; import static org.mockito.Mockito.when;
import java.io.IOException; import java.io.IOException;
import java.util.Date; import java.util.Date;
@ -51,9 +51,6 @@ import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHttpEntityEnclosingRequest; import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.message.BasicHttpRequest; import org.apache.http.message.BasicHttpRequest;
import org.apache.http.message.BasicHttpResponse; import org.apache.http.message.BasicHttpResponse;
import org.easymock.EasyMock;
import org.easymock.IAnswer;
import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -78,25 +75,15 @@ public class TestCacheInvalidator {
tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); tenSecondsAgo = new Date(now.getTime() - 10 * 1000L);
host = new HttpHost("foo.example.com"); host = new HttpHost("foo.example.com");
mockStorage = createNiceMock(HttpCacheStorage.class); mockStorage = mock(HttpCacheStorage.class);
cacheKeyGenerator = new CacheKeyGenerator(); cacheKeyGenerator = new CacheKeyGenerator();
mockEntry = createNiceMock(HttpCacheEntry.class); mockEntry = mock(HttpCacheEntry.class);
request = HttpTestUtils.makeDefaultRequest(); request = HttpTestUtils.makeDefaultRequest();
response = HttpTestUtils.make200Response(); response = HttpTestUtils.make200Response();
impl = new CacheInvalidator(cacheKeyGenerator, mockStorage); impl = new CacheInvalidator(cacheKeyGenerator, mockStorage);
} }
private void replayMocks() {
replay(mockStorage);
replay(mockEntry);
}
private void verifyMocks() {
verify(mockStorage);
verify(mockEntry);
}
// Tests // Tests
@Test @Test
public void testInvalidatesRequestsThatArentGETorHEAD() throws Exception { public void testInvalidatesRequestsThatArentGETorHEAD() throws Exception {
@ -106,12 +93,12 @@ public class TestCacheInvalidator {
cacheEntryHasVariantMap(variantMap); cacheEntryHasVariantMap(variantMap);
cacheReturnsEntryForUri(theUri); cacheReturnsEntryForUri(theUri);
entryIsRemoved(theUri);
replayMocks();
impl.flushInvalidatedCacheEntries(host, request); impl.flushInvalidatedCacheEntries(host, request);
verifyMocks(); verify(mockEntry).getVariantMap();
verify(mockStorage).getEntry(theUri);
verify(mockStorage).removeEntry(theUri);
} }
@Test @Test
@ -127,14 +114,13 @@ public class TestCacheInvalidator {
cacheEntryHasVariantMap(new HashMap<String,String>()); cacheEntryHasVariantMap(new HashMap<String,String>());
cacheReturnsEntryForUri(theUri); cacheReturnsEntryForUri(theUri);
entryIsRemoved(theUri);
entryIsRemoved("http://foo.example.com:80/content");
replayMocks();
impl.flushInvalidatedCacheEntries(host, putRequest); impl.flushInvalidatedCacheEntries(host, putRequest);
verifyMocks(); verify(mockEntry).getVariantMap();
verify(mockStorage).getEntry(theUri);
verify(mockStorage).removeEntry(theUri);
verify(mockStorage).removeEntry("http://foo.example.com:80/content");
} }
@Test @Test
@ -150,14 +136,13 @@ public class TestCacheInvalidator {
cacheEntryHasVariantMap(new HashMap<String,String>()); cacheEntryHasVariantMap(new HashMap<String,String>());
cacheReturnsEntryForUri(theUri); cacheReturnsEntryForUri(theUri);
entryIsRemoved(theUri);
entryIsRemoved(cacheKeyGenerator.canonicalizeUri(contentLocation));
replayMocks();
impl.flushInvalidatedCacheEntries(host, putRequest); impl.flushInvalidatedCacheEntries(host, putRequest);
verifyMocks(); verify(mockEntry).getVariantMap();
verify(mockStorage).getEntry(theUri);
verify(mockStorage).removeEntry(theUri);
verify(mockStorage).removeEntry(cacheKeyGenerator.canonicalizeUri(contentLocation));
} }
@Test @Test
@ -173,14 +158,13 @@ public class TestCacheInvalidator {
cacheEntryHasVariantMap(new HashMap<String,String>()); cacheEntryHasVariantMap(new HashMap<String,String>());
cacheReturnsEntryForUri(theUri); cacheReturnsEntryForUri(theUri);
entryIsRemoved(theUri);
entryIsRemoved("http://foo.example.com:80/content");
replayMocks();
impl.flushInvalidatedCacheEntries(host, putRequest); impl.flushInvalidatedCacheEntries(host, putRequest);
verifyMocks(); verify(mockEntry).getVariantMap();
verify(mockStorage).getEntry(theUri);
verify(mockStorage).removeEntry(theUri);
verify(mockStorage).removeEntry("http://foo.example.com:80/content");
} }
@Test @Test
@ -196,29 +180,30 @@ public class TestCacheInvalidator {
cacheEntryHasVariantMap(new HashMap<String,String>()); cacheEntryHasVariantMap(new HashMap<String,String>());
cacheReturnsEntryForUri(theUri); cacheReturnsEntryForUri(theUri);
entryIsRemoved(theUri);
replayMocks();
impl.flushInvalidatedCacheEntries(host, putRequest); impl.flushInvalidatedCacheEntries(host, putRequest);
verifyMocks(); verify(mockEntry).getVariantMap();
verify(mockStorage).getEntry(theUri);
verify(mockStorage).removeEntry(theUri);
} }
@Test @Test
public void testDoesNotInvalidateGETRequest() throws Exception { public void testDoesNotInvalidateGETRequest() throws Exception {
request = new BasicHttpRequest("GET","/",HTTP_1_1); request = new BasicHttpRequest("GET","/",HTTP_1_1);
replayMocks();
impl.flushInvalidatedCacheEntries(host, request); impl.flushInvalidatedCacheEntries(host, request);
verifyMocks();
verify(mockStorage).getEntry("http://foo.example.com:80/");
verifyNoMoreInteractions(mockStorage);
} }
@Test @Test
public void testDoesNotInvalidateHEADRequest() throws Exception { public void testDoesNotInvalidateHEADRequest() throws Exception {
request = new BasicHttpRequest("HEAD","/",HTTP_1_1); request = new BasicHttpRequest("HEAD","/",HTTP_1_1);
replayMocks();
impl.flushInvalidatedCacheEntries(host, request); impl.flushInvalidatedCacheEntries(host, request);
verifyMocks();
verify(mockStorage).getEntry("http://foo.example.com:80/");
verifyNoMoreInteractions(mockStorage);
} }
@Test @Test
@ -230,11 +215,13 @@ public class TestCacheInvalidator {
cacheEntryisForMethod("HEAD"); cacheEntryisForMethod("HEAD");
cacheEntryHasVariantMap(new HashMap<String, String>()); cacheEntryHasVariantMap(new HashMap<String, String>());
cacheReturnsEntryForUri(theURI); cacheReturnsEntryForUri(theURI);
entryIsRemoved(theURI);
replayMocks();
impl.flushInvalidatedCacheEntries(host, request); impl.flushInvalidatedCacheEntries(host, request);
verifyMocks();
verify(mockEntry).getRequestMethod();
verify(mockEntry).getVariantMap();
verify(mockStorage).getEntry(theURI);
verify(mockStorage).removeEntry(theURI);
} }
@Test @Test
@ -249,12 +236,14 @@ public class TestCacheInvalidator {
cacheEntryisForMethod("HEAD"); cacheEntryisForMethod("HEAD");
cacheEntryHasVariantMap(variants); cacheEntryHasVariantMap(variants);
cacheReturnsEntryForUri(theURI); cacheReturnsEntryForUri(theURI);
entryIsRemoved(theURI);
entryIsRemoved(theVariantURI);
replayMocks();
impl.flushInvalidatedCacheEntries(host, request); impl.flushInvalidatedCacheEntries(host, request);
verifyMocks();
verify(mockEntry).getRequestMethod();
verify(mockEntry).getVariantMap();
verify(mockStorage).getEntry(theURI);
verify(mockStorage).removeEntry(theURI);
verify(mockStorage).removeEntry(theVariantURI);
} }
@Test @Test
@ -264,9 +253,10 @@ public class TestCacheInvalidator {
cacheReturnsEntryForUri(theURI); cacheReturnsEntryForUri(theURI);
replayMocks();
impl.flushInvalidatedCacheEntries(host, request); impl.flushInvalidatedCacheEntries(host, request);
verifyMocks();
verify(mockStorage).getEntry(theURI);
verifyNoMoreInteractions(mockStorage);
} }
@Test @Test
@ -277,9 +267,10 @@ public class TestCacheInvalidator {
cacheReturnsEntryForUri(theURI); cacheReturnsEntryForUri(theURI);
replayMocks();
impl.flushInvalidatedCacheEntries(host, request); impl.flushInvalidatedCacheEntries(host, request);
verifyMocks();
verify(mockStorage).getEntry(theURI);
verifyNoMoreInteractions(mockStorage);
} }
@Test @Test
@ -291,27 +282,33 @@ public class TestCacheInvalidator {
cacheEntryisForMethod("GET"); cacheEntryisForMethod("GET");
cacheReturnsEntryForUri(theURI); cacheReturnsEntryForUri(theURI);
replayMocks();
impl.flushInvalidatedCacheEntries(host, request); impl.flushInvalidatedCacheEntries(host, request);
verifyMocks();
verify(mockEntry).getRequestMethod();
verify(mockStorage).getEntry(theURI);
verifyNoMoreInteractions(mockStorage);
} }
@Test @Test
public void testDoesNotInvalidateRequestsWithClientCacheControlHeaders() throws Exception { public void testDoesNotInvalidateRequestsWithClientCacheControlHeaders() throws Exception {
request = new BasicHttpRequest("GET","/",HTTP_1_1); request = new BasicHttpRequest("GET","/",HTTP_1_1);
request.setHeader("Cache-Control","no-cache"); request.setHeader("Cache-Control","no-cache");
replayMocks();
impl.flushInvalidatedCacheEntries(host, request); impl.flushInvalidatedCacheEntries(host, request);
verifyMocks();
verify(mockStorage).getEntry("http://foo.example.com:80/");
verifyNoMoreInteractions(mockStorage);
} }
@Test @Test
public void testDoesNotInvalidateRequestsWithClientPragmaHeaders() throws Exception { public void testDoesNotInvalidateRequestsWithClientPragmaHeaders() throws Exception {
request = new BasicHttpRequest("GET","/",HTTP_1_1); request = new BasicHttpRequest("GET","/",HTTP_1_1);
request.setHeader("Pragma","no-cache"); request.setHeader("Pragma","no-cache");
replayMocks();
impl.flushInvalidatedCacheEntries(host, request); impl.flushInvalidatedCacheEntries(host, request);
verifyMocks();
verify(mockStorage).getEntry("http://foo.example.com:80/");
verifyNoMoreInteractions(mockStorage);
} }
@Test @Test
@ -324,12 +321,12 @@ public class TestCacheInvalidator {
cacheReturnsEntryForUri(theUri); cacheReturnsEntryForUri(theUri);
cacheEntryHasVariantMap(mapOfURIs); cacheEntryHasVariantMap(mapOfURIs);
entryIsRemoved(variantUri);
entryIsRemoved(theUri);
replayMocks();
impl.flushInvalidatedCacheEntries(host, request); impl.flushInvalidatedCacheEntries(host, request);
verifyMocks();
verify(mockStorage).getEntry(theUri);
verify(mockEntry).getVariantMap();
verify(mockStorage).removeEntry(variantUri);
verify(mockStorage).removeEntry(theUri);
} }
@Test @Test
@ -339,17 +336,18 @@ public class TestCacheInvalidator {
cacheReturnsExceptionForUri(theURI); cacheReturnsExceptionForUri(theURI);
replayMocks();
impl.flushInvalidatedCacheEntries(host, request); impl.flushInvalidatedCacheEntries(host, request);
verifyMocks();
verify(mockStorage).getEntry(theURI);
verifyNoMoreInteractions(mockStorage);
} }
@Test @Test
public void doesNotFlushForResponsesWithoutContentLocation() public void doesNotFlushForResponsesWithoutContentLocation()
throws Exception { throws Exception {
replayMocks();
impl.flushInvalidatedCacheEntries(host, request, response); impl.flushInvalidatedCacheEntries(host, request, response);
verifyMocks();
verifyNoMoreInteractions(mockStorage);
} }
@Test @Test
@ -365,12 +363,12 @@ public class TestCacheInvalidator {
new BasicHeader("ETag", "\"old-etag\"") new BasicHeader("ETag", "\"old-etag\"")
}); });
expect(mockStorage.getEntry(theURI)).andReturn(entry).anyTimes(); when(mockStorage.getEntry(theURI)).thenReturn(entry);
mockStorage.removeEntry(theURI);
replayMocks();
impl.flushInvalidatedCacheEntries(host, request, response); impl.flushInvalidatedCacheEntries(host, request, response);
verifyMocks();
verify(mockStorage).getEntry(theURI);
verify(mockStorage).removeEntry(theURI);
} }
@Test @Test
@ -387,12 +385,12 @@ public class TestCacheInvalidator {
new BasicHeader("ETag", "\"old-etag\"") new BasicHeader("ETag", "\"old-etag\"")
}); });
expect(mockStorage.getEntry(theURI)).andReturn(entry).anyTimes(); when(mockStorage.getEntry(theURI)).thenReturn(entry);
mockStorage.removeEntry(theURI);
replayMocks();
impl.flushInvalidatedCacheEntries(host, request, response); impl.flushInvalidatedCacheEntries(host, request, response);
verifyMocks();
verify(mockStorage).getEntry(theURI);
verify(mockStorage).removeEntry(theURI);
} }
@Test @Test
@ -404,24 +402,9 @@ public class TestCacheInvalidator {
final String theURI = "http://foo.example.com:80/bar"; final String theURI = "http://foo.example.com:80/bar";
response.setHeader("Content-Location", theURI); response.setHeader("Content-Location", theURI);
final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(new Header[] {
new BasicHeader("Date", DateUtils.formatDate(tenSecondsAgo)),
new BasicHeader("ETag", "\"old-etag\"")
});
expect(mockStorage.getEntry(theURI)).andReturn(entry).anyTimes();
mockStorage.removeEntry(theURI);
EasyMock.expectLastCall().andAnswer(new IAnswer<Void>() {
@Override
public Void answer() {
Assert.fail();
return null;
}
}).anyTimes();
replayMocks();
impl.flushInvalidatedCacheEntries(host, request, response); impl.flushInvalidatedCacheEntries(host, request, response);
verifyMocks();
verifyNoMoreInteractions(mockStorage);
} }
@Test @Test
@ -437,12 +420,12 @@ public class TestCacheInvalidator {
new BasicHeader("ETag", "\"old-etag\"") new BasicHeader("ETag", "\"old-etag\"")
}); });
expect(mockStorage.getEntry(cacheKey)).andReturn(entry).anyTimes(); when(mockStorage.getEntry(cacheKey)).thenReturn(entry);
mockStorage.removeEntry(cacheKey);
replayMocks();
impl.flushInvalidatedCacheEntries(host, request, response); impl.flushInvalidatedCacheEntries(host, request, response);
verifyMocks();
verify(mockStorage).getEntry(cacheKey);
verify(mockStorage).removeEntry(cacheKey);
} }
@Test @Test
@ -458,12 +441,12 @@ public class TestCacheInvalidator {
new BasicHeader("ETag", "\"old-etag\"") new BasicHeader("ETag", "\"old-etag\"")
}); });
expect(mockStorage.getEntry(cacheKey)).andReturn(entry).anyTimes(); when(mockStorage.getEntry(cacheKey)).thenReturn(entry);
mockStorage.removeEntry(cacheKey);
replayMocks();
impl.flushInvalidatedCacheEntries(host, request, response); impl.flushInvalidatedCacheEntries(host, request, response);
verifyMocks();
verify(mockStorage).getEntry(cacheKey);
verify(mockStorage).removeEntry(cacheKey);
} }
@Test @Test
@ -479,19 +462,12 @@ public class TestCacheInvalidator {
new BasicHeader("ETag", "\"old-etag\"") new BasicHeader("ETag", "\"old-etag\"")
}); });
expect(mockStorage.getEntry(cacheKey)).andReturn(entry).anyTimes(); when(mockStorage.getEntry(cacheKey)).thenReturn(entry);
mockStorage.removeEntry(cacheKey);
EasyMock.expectLastCall().andAnswer(new IAnswer<Void>() {
@Override
public Void answer() {
Assert.fail();
return null;
}
}).anyTimes();
replayMocks();
impl.flushInvalidatedCacheEntries(host, request, response); impl.flushInvalidatedCacheEntries(host, request, response);
verifyMocks();
verify(mockStorage).getEntry(cacheKey);
verifyNoMoreInteractions(mockStorage);
} }
@ -509,19 +485,11 @@ public class TestCacheInvalidator {
new BasicHeader("ETag", "\"same-etag\"") new BasicHeader("ETag", "\"same-etag\"")
}); });
expect(mockStorage.getEntry(theURI)).andReturn(entry).anyTimes(); when(mockStorage.getEntry(theURI)).thenReturn(entry);
mockStorage.removeEntry(theURI);
EasyMock.expectLastCall().andAnswer(new IAnswer<Void>() {
@Override
public Void answer() {
Assert.fail();
return null;
}
}).anyTimes();
replayMocks();
impl.flushInvalidatedCacheEntries(host, request, response); impl.flushInvalidatedCacheEntries(host, request, response);
verifyMocks();
verify(mockStorage).getEntry(theURI);
verifyNoMoreInteractions(mockStorage);
} }
@Test @Test
@ -537,19 +505,12 @@ public class TestCacheInvalidator {
new BasicHeader("ETag", "\"old-etag\"") new BasicHeader("ETag", "\"old-etag\"")
}); });
expect(mockStorage.getEntry(theURI)).andReturn(entry).anyTimes(); when(mockStorage.getEntry(theURI)).thenReturn(entry);
mockStorage.removeEntry(theURI);
EasyMock.expectLastCall().andAnswer(new IAnswer<Void>() {
@Override
public Void answer() {
Assert.fail();
return null;
}
}).anyTimes();
replayMocks();
impl.flushInvalidatedCacheEntries(host, request, response); impl.flushInvalidatedCacheEntries(host, request, response);
verifyMocks();
verify(mockStorage).getEntry(theURI);
verifyNoMoreInteractions(mockStorage);
} }
@Test @Test
@ -560,19 +521,12 @@ public class TestCacheInvalidator {
final String theURI = "http://foo.example.com:80/bar"; final String theURI = "http://foo.example.com:80/bar";
response.setHeader("Content-Location", theURI); response.setHeader("Content-Location", theURI);
expect(mockStorage.getEntry(theURI)).andReturn(null).anyTimes(); when(mockStorage.getEntry(theURI)).thenReturn(null);
mockStorage.removeEntry(theURI);
EasyMock.expectLastCall().andAnswer(new IAnswer<Void>() {
@Override
public Void answer() {
Assert.fail();
return null;
}
}).anyTimes();
replayMocks();
impl.flushInvalidatedCacheEntries(host, request, response); impl.flushInvalidatedCacheEntries(host, request, response);
verifyMocks();
verify(mockStorage).getEntry(theURI);
verifyNoMoreInteractions(mockStorage);
} }
@Test @Test
@ -588,19 +542,12 @@ public class TestCacheInvalidator {
new BasicHeader("ETag", "\"old-etag\"") new BasicHeader("ETag", "\"old-etag\"")
}); });
expect(mockStorage.getEntry(theURI)).andReturn(entry).anyTimes(); when(mockStorage.getEntry(theURI)).thenReturn(entry);
mockStorage.removeEntry(theURI);
EasyMock.expectLastCall().andAnswer(new IAnswer<Void>() {
@Override
public Void answer() {
Assert.fail();
return null;
}
}).anyTimes();
replayMocks();
impl.flushInvalidatedCacheEntries(host, request, response); impl.flushInvalidatedCacheEntries(host, request, response);
verifyMocks();
verify(mockStorage).getEntry(theURI);
verifyNoMoreInteractions(mockStorage);
} }
@Test @Test
@ -615,11 +562,12 @@ public class TestCacheInvalidator {
new BasicHeader("Date", DateUtils.formatDate(tenSecondsAgo)), new BasicHeader("Date", DateUtils.formatDate(tenSecondsAgo)),
}); });
expect(mockStorage.getEntry(theURI)).andReturn(entry).anyTimes(); when(mockStorage.getEntry(theURI)).thenReturn(entry);
replayMocks();
impl.flushInvalidatedCacheEntries(host, request, response); impl.flushInvalidatedCacheEntries(host, request, response);
verifyMocks();
verify(mockStorage).getEntry(theURI);
verifyNoMoreInteractions(mockStorage);
} }
@Test @Test
@ -635,12 +583,13 @@ public class TestCacheInvalidator {
new BasicHeader("Date", DateUtils.formatDate(tenSecondsAgo)), new BasicHeader("Date", DateUtils.formatDate(tenSecondsAgo)),
}); });
expect(mockStorage.getEntry(theURI)).andReturn(entry).anyTimes(); when(mockStorage.getEntry(theURI)).thenReturn(entry);
mockStorage.removeEntry(theURI);
replayMocks();
impl.flushInvalidatedCacheEntries(host, request, response); impl.flushInvalidatedCacheEntries(host, request, response);
verifyMocks();
verify(mockStorage).getEntry(theURI);
verify(mockStorage).removeEntry(theURI);
verifyNoMoreInteractions(mockStorage);
} }
@Test @Test
@ -655,12 +604,13 @@ public class TestCacheInvalidator {
new BasicHeader("ETag", "\"old-etag\"") new BasicHeader("ETag", "\"old-etag\"")
}); });
expect(mockStorage.getEntry(theURI)).andReturn(entry).anyTimes(); when(mockStorage.getEntry(theURI)).thenReturn(entry);
mockStorage.removeEntry(theURI);
replayMocks();
impl.flushInvalidatedCacheEntries(host, request, response); impl.flushInvalidatedCacheEntries(host, request, response);
verifyMocks();
verify(mockStorage).getEntry(theURI);
verify(mockStorage).removeEntry(theURI);
verifyNoMoreInteractions(mockStorage);
} }
@Test @Test
@ -676,12 +626,13 @@ public class TestCacheInvalidator {
new BasicHeader("Date", DateUtils.formatDate(tenSecondsAgo)) new BasicHeader("Date", DateUtils.formatDate(tenSecondsAgo))
}); });
expect(mockStorage.getEntry(theURI)).andReturn(entry).anyTimes(); when(mockStorage.getEntry(theURI)).thenReturn(entry);
mockStorage.removeEntry(theURI);
replayMocks();
impl.flushInvalidatedCacheEntries(host, request, response); impl.flushInvalidatedCacheEntries(host, request, response);
verifyMocks();
verify(mockStorage).getEntry(theURI);
verify(mockStorage).removeEntry(theURI);
verifyNoMoreInteractions(mockStorage);
} }
@Test @Test
@ -697,35 +648,31 @@ public class TestCacheInvalidator {
new BasicHeader("Date", "foo") new BasicHeader("Date", "foo")
}); });
expect(mockStorage.getEntry(theURI)).andReturn(entry).anyTimes(); when(mockStorage.getEntry(theURI)).thenReturn(entry);
mockStorage.removeEntry(theURI);
replayMocks();
impl.flushInvalidatedCacheEntries(host, request, response); impl.flushInvalidatedCacheEntries(host, request, response);
verifyMocks();
verify(mockStorage).getEntry(theURI);
verify(mockStorage).removeEntry(theURI);
verifyNoMoreInteractions(mockStorage);
} }
// Expectations // Expectations
private void cacheEntryHasVariantMap(final Map<String,String> variantMap) { private void cacheEntryHasVariantMap(final Map<String,String> variantMap) {
expect(mockEntry.getVariantMap()).andReturn(variantMap); when(mockEntry.getVariantMap()).thenReturn(variantMap);
} }
private void cacheReturnsEntryForUri(final String theUri) throws IOException { private void cacheReturnsEntryForUri(final String theUri) throws IOException {
expect(mockStorage.getEntry(theUri)).andReturn(mockEntry); when(mockStorage.getEntry(theUri)).thenReturn(mockEntry);
} }
private void cacheReturnsExceptionForUri(final String theUri) throws IOException { private void cacheReturnsExceptionForUri(final String theUri) throws IOException {
expect(mockStorage.getEntry(theUri)).andThrow( when(mockStorage.getEntry(theUri)).thenThrow(
new IOException("TOTAL FAIL")); new IOException("TOTAL FAIL"));
} }
private void entryIsRemoved(final String theUri) throws IOException {
mockStorage.removeEntry(theUri);
}
private void cacheEntryisForMethod(final String httpMethod) { private void cacheEntryisForMethod(final String httpMethod) {
expect(mockEntry.getRequestMethod()).andReturn(httpMethod); when(mockEntry.getRequestMethod()).thenReturn(httpMethod);
} }
} }

View File

@ -26,6 +26,10 @@
*/ */
package org.apache.http.impl.client.cache; package org.apache.http.impl.client.cache;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.apache.http.Header; import org.apache.http.Header;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.HttpRequest; import org.apache.http.HttpRequest;
@ -34,7 +38,6 @@ import org.apache.http.client.cache.HttpCacheEntry;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHttpRequest; import org.apache.http.message.BasicHttpRequest;
import org.easymock.classextension.EasyMock;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -54,21 +57,11 @@ public class TestCacheKeyGenerator {
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
defaultHost = new HttpHost("foo.example.com"); defaultHost = new HttpHost("foo.example.com");
mockEntry = EasyMock.createNiceMock(HttpCacheEntry.class); mockEntry = mock(HttpCacheEntry.class);
mockRequest = EasyMock.createNiceMock(HttpRequest.class); mockRequest = mock(HttpRequest.class);
extractor = new CacheKeyGenerator(); extractor = new CacheKeyGenerator();
} }
private void replayMocks() {
EasyMock.replay(mockEntry);
EasyMock.replay(mockRequest);
}
private void verifyMocks() {
EasyMock.verify(mockEntry);
EasyMock.verify(mockRequest);
}
@Test @Test
public void testExtractsUriFromAbsoluteUriInRequest() { public void testExtractsUriFromAbsoluteUriInRequest() {
final HttpHost host = new HttpHost("bar.example.com"); final HttpHost host = new HttpHost("bar.example.com");
@ -124,7 +117,7 @@ public class TestCacheKeyGenerator {
@Test @Test
public void testGetVariantURIWithNoVaryHeaderReturnsNormalURI() { public void testGetVariantURIWithNoVaryHeaderReturnsNormalURI() {
final String theURI = "theURI"; final String theURI = "theURI";
org.easymock.EasyMock.expect(mockEntry.hasVariants()).andReturn(false); when(mockEntry.hasVariants()).thenReturn(false);
extractor = new CacheKeyGenerator() { extractor = new CacheKeyGenerator() {
@Override @Override
public String getURI(final HttpHost h, final HttpRequest req) { public String getURI(final HttpHost h, final HttpRequest req) {
@ -134,9 +127,8 @@ public class TestCacheKeyGenerator {
} }
}; };
replayMocks();
final String result = extractor.getVariantURI(defaultHost, mockRequest, mockEntry); final String result = extractor.getVariantURI(defaultHost, mockRequest, mockEntry);
verifyMocks(); verify(mockEntry).hasVariants();
Assert.assertSame(theURI, result); Assert.assertSame(theURI, result);
} }
@ -154,15 +146,16 @@ public class TestCacheKeyGenerator {
return theURI; return theURI;
} }
}; };
EasyMock.expect(mockEntry.hasVariants()).andReturn(true).anyTimes(); when(mockEntry.hasVariants()).thenReturn(true);
EasyMock.expect(mockEntry.getHeaders("Vary")).andReturn(varyHeaders); when(mockEntry.getHeaders("Vary")).thenReturn(varyHeaders);
EasyMock.expect(mockRequest.getHeaders("Accept-Encoding")).andReturn( when(mockRequest.getHeaders("Accept-Encoding")).thenReturn(
encHeaders); encHeaders);
replayMocks();
final String result = extractor.getVariantURI(defaultHost, mockRequest, mockEntry); final String result = extractor.getVariantURI(defaultHost, mockRequest, mockEntry);
verifyMocks(); verify(mockEntry).hasVariants();
verify(mockEntry).getHeaders("Vary");
verify(mockRequest).getHeaders("Accept-Encoding");
Assert.assertEquals("{Accept-Encoding=gzip}" + theURI, result); Assert.assertEquals("{Accept-Encoding=gzip}" + theURI, result);
} }
@ -179,15 +172,16 @@ public class TestCacheKeyGenerator {
return theURI; return theURI;
} }
}; };
EasyMock.expect(mockEntry.hasVariants()).andReturn(true).anyTimes(); when(mockEntry.hasVariants()).thenReturn(true);
EasyMock.expect(mockEntry.getHeaders("Vary")).andReturn(varyHeaders); when(mockEntry.getHeaders("Vary")).thenReturn(varyHeaders);
EasyMock.expect(mockRequest.getHeaders("Accept-Encoding")) when(mockRequest.getHeaders("Accept-Encoding"))
.andReturn(noHeaders); .thenReturn(noHeaders);
replayMocks();
final String result = extractor.getVariantURI(defaultHost, mockRequest, mockEntry); final String result = extractor.getVariantURI(defaultHost, mockRequest, mockEntry);
verifyMocks(); verify(mockEntry).hasVariants();
verify(mockEntry).getHeaders("Vary");
verify(mockRequest).getHeaders("Accept-Encoding");
Assert.assertEquals("{Accept-Encoding=}" + theURI, result); Assert.assertEquals("{Accept-Encoding=}" + theURI, result);
} }
@ -205,16 +199,18 @@ public class TestCacheKeyGenerator {
return theURI; return theURI;
} }
}; };
EasyMock.expect(mockEntry.hasVariants()).andReturn(true).anyTimes(); when(mockEntry.hasVariants()).thenReturn(true);
EasyMock.expect(mockEntry.getHeaders("Vary")).andReturn(varyHeaders); when(mockEntry.getHeaders("Vary")).thenReturn(varyHeaders);
EasyMock.expect(mockRequest.getHeaders("Accept-Encoding")).andReturn( when(mockRequest.getHeaders("Accept-Encoding")).thenReturn(
encHeaders); encHeaders);
EasyMock.expect(mockRequest.getHeaders("User-Agent")).andReturn(uaHeaders); when(mockRequest.getHeaders("User-Agent")).thenReturn(uaHeaders);
replayMocks();
final String result = extractor.getVariantURI(defaultHost, mockRequest, mockEntry); final String result = extractor.getVariantURI(defaultHost, mockRequest, mockEntry);
verifyMocks(); verify(mockEntry).hasVariants();
verify(mockEntry).getHeaders("Vary");
verify(mockRequest).getHeaders("Accept-Encoding");
verify(mockRequest).getHeaders("User-Agent");
Assert.assertEquals("{Accept-Encoding=gzip&User-Agent=browser}" + theURI, result); Assert.assertEquals("{Accept-Encoding=gzip&User-Agent=browser}" + theURI, result);
} }
@ -233,15 +229,17 @@ public class TestCacheKeyGenerator {
return theURI; return theURI;
} }
}; };
EasyMock.expect(mockEntry.hasVariants()).andReturn(true).anyTimes(); when(mockEntry.hasVariants()).thenReturn(true);
EasyMock.expect(mockEntry.getHeaders("Vary")).andReturn(varyHeaders); when(mockEntry.getHeaders("Vary")).thenReturn(varyHeaders);
EasyMock.expect(mockRequest.getHeaders("Accept-Encoding")).andReturn(encHeaders); when(mockRequest.getHeaders("Accept-Encoding")).thenReturn(encHeaders);
EasyMock.expect(mockRequest.getHeaders("User-Agent")).andReturn(uaHeaders); when(mockRequest.getHeaders("User-Agent")).thenReturn(uaHeaders);
replayMocks();
final String result = extractor.getVariantURI(defaultHost, mockRequest, mockEntry); final String result = extractor.getVariantURI(defaultHost, mockRequest, mockEntry);
verifyMocks(); verify(mockEntry).hasVariants();
verify(mockEntry).getHeaders("Vary");
verify(mockRequest).getHeaders("Accept-Encoding");
verify(mockRequest).getHeaders("User-Agent");
Assert.assertEquals("{Accept-Encoding=gzip&User-Agent=browser}" + theURI, result); Assert.assertEquals("{Accept-Encoding=gzip&User-Agent=browser}" + theURI, result);
} }
@ -260,15 +258,17 @@ public class TestCacheKeyGenerator {
return theURI; return theURI;
} }
}; };
EasyMock.expect(mockEntry.hasVariants()).andReturn(true).anyTimes(); when(mockEntry.hasVariants()).thenReturn(true);
EasyMock.expect(mockEntry.getHeaders("Vary")).andReturn(varyHeaders); when(mockEntry.getHeaders("Vary")).thenReturn(varyHeaders);
EasyMock.expect(mockRequest.getHeaders("Accept-Encoding")).andReturn(encHeaders); when(mockRequest.getHeaders("Accept-Encoding")).thenReturn(encHeaders);
EasyMock.expect(mockRequest.getHeaders("User-Agent")).andReturn(uaHeaders); when(mockRequest.getHeaders("User-Agent")).thenReturn(uaHeaders);
replayMocks();
final String result = extractor.getVariantURI(defaultHost, mockRequest, mockEntry); final String result = extractor.getVariantURI(defaultHost, mockRequest, mockEntry);
verifyMocks(); verify(mockEntry).hasVariants();
verify(mockEntry).getHeaders("Vary");
verify(mockRequest).getHeaders("Accept-Encoding");
verify(mockRequest).getHeaders("User-Agent");
Assert Assert
.assertEquals("{Accept-Encoding=gzip%2C+deflate&User-Agent=browser}" + theURI, .assertEquals("{Accept-Encoding=gzip%2C+deflate&User-Agent=browser}" + theURI,
result); result);

View File

@ -26,6 +26,12 @@
*/ */
package org.apache.http.impl.client.cache; package org.apache.http.impl.client.cache;
import static org.mockito.Matchers.isA;
import static org.mockito.Matchers.same;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
@ -33,9 +39,7 @@ import org.apache.http.Header;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.client.cache.HttpCacheEntry; import org.apache.http.client.cache.HttpCacheEntry;
import org.apache.http.client.methods.HttpRequestWrapper; import org.apache.http.client.methods.HttpRequestWrapper;
import org.apache.http.client.utils.DateUtils;
import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHeader;
import org.easymock.classextension.EasyMock;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -47,27 +51,15 @@ public class TestCachedHttpResponseGenerator {
private HttpRequestWrapper request; private HttpRequestWrapper request;
private CacheValidityPolicy mockValidityPolicy; private CacheValidityPolicy mockValidityPolicy;
private CachedHttpResponseGenerator impl; private CachedHttpResponseGenerator impl;
private Date now;
@Before @Before
public void setUp() { public void setUp() {
now = new Date();
final Date eightSecondsAgo = new Date(now.getTime() - 8 * 1000L);
final Date tenSecondsFromNow = new Date(now.getTime() + 10 * 1000L);
final Header[] hdrs = { new BasicHeader("Date", DateUtils.formatDate(eightSecondsAgo)),
new BasicHeader("Expires", DateUtils.formatDate(tenSecondsFromNow)),
new BasicHeader("Content-Length", "150") };
entry = HttpTestUtils.makeCacheEntry(new HashMap<String, String>()); entry = HttpTestUtils.makeCacheEntry(new HashMap<String, String>());
request = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest()); request = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest());
mockValidityPolicy = EasyMock.createNiceMock(CacheValidityPolicy.class); mockValidityPolicy = mock(CacheValidityPolicy.class);
impl = new CachedHttpResponseGenerator(mockValidityPolicy); impl = new CachedHttpResponseGenerator(mockValidityPolicy);
} }
public void replayMocks() {
EasyMock.replay(mockValidityPolicy);
}
@Test @Test
public void testResponseHasContentLength() { public void testResponseHasContentLength() {
final byte[] buf = new byte[] { 1, 2, 3, 4, 5 }; final byte[] buf = new byte[] { 1, 2, 3, 4, 5 };
@ -117,10 +109,11 @@ public class TestCachedHttpResponseGenerator {
@Test @Test
public void testAgeHeaderIsPopulatedWithCurrentAgeOfCacheEntryIfNonZero() { public void testAgeHeaderIsPopulatedWithCurrentAgeOfCacheEntryIfNonZero() {
currentAge(10L); currentAge(10L);
replayMocks();
final HttpResponse response = impl.generateResponse(request, entry); final HttpResponse response = impl.generateResponse(request, entry);
verify(mockValidityPolicy).getCurrentAgeSecs(same(entry), isA(Date.class));
final Header ageHdr = response.getFirstHeader("Age"); final Header ageHdr = response.getFirstHeader("Age");
Assert.assertNotNull(ageHdr); Assert.assertNotNull(ageHdr);
Assert.assertEquals(10L, Long.parseLong(ageHdr.getValue())); Assert.assertEquals(10L, Long.parseLong(ageHdr.getValue()));
@ -129,10 +122,11 @@ public class TestCachedHttpResponseGenerator {
@Test @Test
public void testAgeHeaderIsNotPopulatedIfCurrentAgeOfCacheEntryIsZero() { public void testAgeHeaderIsNotPopulatedIfCurrentAgeOfCacheEntryIsZero() {
currentAge(0L); currentAge(0L);
replayMocks();
final HttpResponse response = impl.generateResponse(request, entry); final HttpResponse response = impl.generateResponse(request, entry);
verify(mockValidityPolicy).getCurrentAgeSecs(same(entry), isA(Date.class));
final Header ageHdr = response.getFirstHeader("Age"); final Header ageHdr = response.getFirstHeader("Age");
Assert.assertNull(ageHdr); Assert.assertNull(ageHdr);
} }
@ -140,19 +134,20 @@ public class TestCachedHttpResponseGenerator {
@Test @Test
public void testAgeHeaderIsPopulatedWithMaxAgeIfCurrentAgeTooBig() { public void testAgeHeaderIsPopulatedWithMaxAgeIfCurrentAgeTooBig() {
currentAge(CacheValidityPolicy.MAX_AGE + 1L); currentAge(CacheValidityPolicy.MAX_AGE + 1L);
replayMocks();
final HttpResponse response = impl.generateResponse(request, entry); final HttpResponse response = impl.generateResponse(request, entry);
verify(mockValidityPolicy).getCurrentAgeSecs(same(entry), isA(Date.class));
final Header ageHdr = response.getFirstHeader("Age"); final Header ageHdr = response.getFirstHeader("Age");
Assert.assertNotNull(ageHdr); Assert.assertNotNull(ageHdr);
Assert.assertEquals(CacheValidityPolicy.MAX_AGE, Long.parseLong(ageHdr.getValue())); Assert.assertEquals(CacheValidityPolicy.MAX_AGE, Long.parseLong(ageHdr.getValue()));
} }
private void currentAge(final long sec) { private void currentAge(final long sec) {
EasyMock.expect( when(
mockValidityPolicy.getCurrentAgeSecs(EasyMock.same(entry), mockValidityPolicy.getCurrentAgeSecs(same(entry),
EasyMock.isA(Date.class))).andReturn(sec); isA(Date.class))).thenReturn(sec);
} }
@Test @Test

View File

@ -36,7 +36,6 @@ import org.apache.http.client.cache.HttpCacheEntry;
import org.apache.http.client.utils.DateUtils; import org.apache.http.client.utils.DateUtils;
import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHttpRequest; import org.apache.http.message.BasicHttpRequest;
import org.easymock.classextension.EasyMock;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -51,7 +50,6 @@ public class TestCachedResponseSuitabilityChecker {
private HttpHost host; private HttpHost host;
private HttpRequest request; private HttpRequest request;
private HttpCacheEntry entry; private HttpCacheEntry entry;
private CacheValidityPolicy mockValidityPolicy;
private CachedResponseSuitabilityChecker impl; private CachedResponseSuitabilityChecker impl;
@Before @Before
@ -63,7 +61,6 @@ public class TestCachedResponseSuitabilityChecker {
host = new HttpHost("foo.example.com"); host = new HttpHost("foo.example.com");
request = new BasicHttpRequest("GET", "/foo", HttpVersion.HTTP_1_1); request = new BasicHttpRequest("GET", "/foo", HttpVersion.HTTP_1_1);
mockValidityPolicy = EasyMock.createNiceMock(CacheValidityPolicy.class);
entry = HttpTestUtils.makeCacheEntry(); entry = HttpTestUtils.makeCacheEntry();
impl = new CachedResponseSuitabilityChecker(CacheConfig.DEFAULT); impl = new CachedResponseSuitabilityChecker(CacheConfig.DEFAULT);
@ -73,14 +70,6 @@ public class TestCachedResponseSuitabilityChecker {
return HttpTestUtils.makeCacheEntry(elevenSecondsAgo, nineSecondsAgo, headers); return HttpTestUtils.makeCacheEntry(elevenSecondsAgo, nineSecondsAgo, headers);
} }
public void replayMocks() {
EasyMock.replay(mockValidityPolicy);
}
public void verifyMocks() {
EasyMock.verify(mockValidityPolicy);
}
@Test @Test
public void testNotSuitableIfContentLengthHeaderIsWrong() { public void testNotSuitableIfContentLengthHeaderIsWrong() {
final Header[] headers = { final Header[] headers = {

View File

@ -26,11 +26,14 @@
*/ */
package org.apache.http.impl.client.cache; package org.apache.http.impl.client.cache;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import org.apache.http.client.cache.Resource; import org.apache.http.client.cache.Resource;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.easymock.EasyMock;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
@ -38,11 +41,9 @@ public class TestCombinedEntity {
@Test @Test
public void testCombinedEntityBasics() throws Exception { public void testCombinedEntityBasics() throws Exception {
final Resource resource = EasyMock.createNiceMock(Resource.class); final Resource resource = mock(Resource.class);
EasyMock.expect(resource.getInputStream()).andReturn( when(resource.getInputStream()).thenReturn(
new ByteArrayInputStream(new byte[] { 1, 2, 3, 4, 5 })); new ByteArrayInputStream(new byte[] { 1, 2, 3, 4, 5 }));
resource.dispose();
EasyMock.replay(resource);
final ByteArrayInputStream instream = new ByteArrayInputStream(new byte[] { 6, 7, 8, 9, 10 }); final ByteArrayInputStream instream = new ByteArrayInputStream(new byte[] { 6, 7, 8, 9, 10 });
final CombinedEntity entity = new CombinedEntity(resource, instream); final CombinedEntity entity = new CombinedEntity(resource, instream);
@ -53,7 +54,8 @@ public class TestCombinedEntity {
final byte[] result = EntityUtils.toByteArray(entity); final byte[] result = EntityUtils.toByteArray(entity);
Assert.assertArrayEquals(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, result); Assert.assertArrayEquals(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, result);
EasyMock.verify(resource); verify(resource).getInputStream();
verify(resource).dispose();
} }
} }

View File

@ -26,13 +26,16 @@
*/ */
package org.apache.http.impl.client.cache; package org.apache.http.impl.client.cache;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.client.methods.HttpRequestWrapper; import org.apache.http.client.methods.HttpRequestWrapper;
import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.routing.HttpRoute; import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.execchain.ClientExecChain; import org.apache.http.impl.execchain.ClientExecChain;
import org.apache.http.message.BasicHttpRequest; import org.apache.http.message.BasicHttpRequest;
import org.easymock.EasyMock;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -46,7 +49,7 @@ public class TestExponentialBackingOffSchedulingStrategy {
@Before @Before
public void setUp() { public void setUp() {
mockExecutor = EasyMock.createMock(ScheduledExecutorService.class); mockExecutor = mock(ScheduledExecutorService.class);
impl = new ExponentialBackOffSchedulingStrategy( impl = new ExponentialBackOffSchedulingStrategy(
mockExecutor, mockExecutor,
@ -62,9 +65,9 @@ public class TestExponentialBackingOffSchedulingStrategy {
expectRequestScheduledWithoutDelay(request); expectRequestScheduledWithoutDelay(request);
replayMocks();
impl.schedule(request); impl.schedule(request);
verifyMocks();
verify(mockExecutor).schedule(request, 0, TimeUnit.MILLISECONDS);
} }
@Test @Test
@ -73,9 +76,9 @@ public class TestExponentialBackingOffSchedulingStrategy {
expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(6)); expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(6));
replayMocks();
impl.schedule(request); impl.schedule(request);
verifyMocks();
verify(mockExecutor).schedule(request, 6000, TimeUnit.MILLISECONDS);
} }
@Test @Test
@ -84,9 +87,9 @@ public class TestExponentialBackingOffSchedulingStrategy {
expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(60)); expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(60));
replayMocks();
impl.schedule(request); impl.schedule(request);
verifyMocks();
verify(mockExecutor).schedule(request, 60000, TimeUnit.MILLISECONDS);
} }
@Test @Test
@ -95,9 +98,9 @@ public class TestExponentialBackingOffSchedulingStrategy {
expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(600)); expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(600));
replayMocks();
impl.schedule(request); impl.schedule(request);
verifyMocks();
verify(mockExecutor).schedule(request, 600000, TimeUnit.MILLISECONDS);
} }
@Test @Test
@ -106,9 +109,9 @@ public class TestExponentialBackingOffSchedulingStrategy {
expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(6000)); expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(6000));
replayMocks();
impl.schedule(request); impl.schedule(request);
verifyMocks();
verify(mockExecutor).schedule(request, 6000000, TimeUnit.MILLISECONDS);
} }
@Test @Test
@ -117,9 +120,9 @@ public class TestExponentialBackingOffSchedulingStrategy {
expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(60000)); expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(60000));
replayMocks();
impl.schedule(request); impl.schedule(request);
verifyMocks();
verify(mockExecutor).schedule(request, 60000000, TimeUnit.MILLISECONDS);
} }
@Test @Test
@ -128,9 +131,9 @@ public class TestExponentialBackingOffSchedulingStrategy {
expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(86400)); expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(86400));
replayMocks();
impl.schedule(request); impl.schedule(request);
verifyMocks();
verify(mockExecutor).schedule(request, 86400000, TimeUnit.MILLISECONDS);
} }
@Test @Test
@ -139,9 +142,9 @@ public class TestExponentialBackingOffSchedulingStrategy {
expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(86400)); expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(86400));
replayMocks();
impl.schedule(request); impl.schedule(request);
verifyMocks();
verify(mockExecutor).schedule(request, 86400000, TimeUnit.MILLISECONDS);
} }
private void expectRequestScheduledWithoutDelay(final AsynchronousValidationRequest request) { private void expectRequestScheduledWithoutDelay(final AsynchronousValidationRequest request) {
@ -149,19 +152,11 @@ public class TestExponentialBackingOffSchedulingStrategy {
} }
private void expectRequestScheduledWithDelay(final AsynchronousValidationRequest request, final long delayInMillis) { private void expectRequestScheduledWithDelay(final AsynchronousValidationRequest request, final long delayInMillis) {
EasyMock.expect(mockExecutor.schedule(request, delayInMillis, TimeUnit.MILLISECONDS)).andReturn(null); when(mockExecutor.schedule(request, delayInMillis, TimeUnit.MILLISECONDS)).thenReturn(null);
}
private void replayMocks() {
EasyMock.replay(mockExecutor);
}
private void verifyMocks() {
EasyMock.verify(mockExecutor);
} }
private AsynchronousValidationRequest createAsynchronousValidationRequest(final int errorCount) { private AsynchronousValidationRequest createAsynchronousValidationRequest(final int errorCount) {
final ClientExecChain clientExecChain = EasyMock.createNiceMock(ClientExecChain.class); final ClientExecChain clientExecChain = mock(ClientExecChain.class);
final CachingExec cachingHttpClient = new CachingExec(clientExecChain); final CachingExec cachingHttpClient = new CachingExec(clientExecChain);
final AsynchronousValidator mockValidator = new AsynchronousValidator(impl); final AsynchronousValidator mockValidator = new AsynchronousValidator(impl);
final HttpRoute httpRoute = new HttpRoute(new HttpHost("foo.example.com", 80)); final HttpRoute httpRoute = new HttpRoute(new HttpHost("foo.example.com", 80));

View File

@ -26,6 +26,13 @@
*/ */
package org.apache.http.impl.client.cache; package org.apache.http.impl.client.cache;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.File; import java.io.File;
import java.util.Date; import java.util.Date;
@ -42,11 +49,11 @@ import org.apache.http.client.utils.DateUtils;
import org.apache.http.conn.routing.HttpRoute; import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.execchain.ClientExecChain; import org.apache.http.impl.execchain.ClientExecChain;
import org.apache.http.message.BasicHttpResponse; import org.apache.http.message.BasicHttpResponse;
import org.easymock.EasyMock;
import org.junit.After; import org.junit.After;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.Matchers;
public class TestHttpCacheJiraNumber1147 { public class TestHttpCacheJiraNumber1147 {
@ -87,7 +94,7 @@ public class TestHttpCacheJiraNumber1147 {
final ResourceFactory resourceFactory = new FileResourceFactory(cacheDir); final ResourceFactory resourceFactory = new FileResourceFactory(cacheDir);
final HttpCacheStorage httpCacheStorage = new ManagedHttpCacheStorage(cacheConfig); final HttpCacheStorage httpCacheStorage = new ManagedHttpCacheStorage(cacheConfig);
final ClientExecChain backend = EasyMock.createNiceMock(ClientExecChain.class); final ClientExecChain backend = mock(ClientExecChain.class);
final HttpRequestWrapper get = HttpRequestWrapper.wrap(new HttpGet("http://somehost/")); final HttpRequestWrapper get = HttpRequestWrapper.wrap(new HttpGet("http://somehost/"));
final HttpClientContext context = HttpClientContext.create(); final HttpClientContext context = HttpClientContext.create();
final HttpHost target = new HttpHost("somehost", 80); final HttpHost target = new HttpHost("somehost", 80);
@ -105,12 +112,11 @@ public class TestHttpCacheJiraNumber1147 {
response.setHeader("Cache-Control", "public, max-age=3600"); response.setHeader("Cache-Control", "public, max-age=3600");
response.setHeader("Last-Modified", DateUtils.formatDate(tenSecondsAgo)); response.setHeader("Last-Modified", DateUtils.formatDate(tenSecondsAgo));
EasyMock.expect(backend.execute( when(backend.execute(
EasyMock.eq(route), eq(route),
EasyMock.isA(HttpRequestWrapper.class), isA(HttpRequestWrapper.class),
EasyMock.isA(HttpClientContext.class), isA(HttpClientContext.class),
EasyMock.<HttpExecutionAware>isNull())).andReturn(Proxies.enhanceResponse(response)); (HttpExecutionAware) Matchers.isNull())).thenReturn(Proxies.enhanceResponse(response));
EasyMock.replay(backend);
final BasicHttpCache cache = new BasicHttpCache(resourceFactory, httpCacheStorage, cacheConfig); final BasicHttpCache cache = new BasicHttpCache(resourceFactory, httpCacheStorage, cacheConfig);
final ClientExecChain t = createCachingExecChain(backend, cache, cacheConfig); final ClientExecChain t = createCachingExecChain(backend, cache, cacheConfig);
@ -119,23 +125,30 @@ public class TestHttpCacheJiraNumber1147 {
Assert.assertEquals(200, response1.getStatusLine().getStatusCode()); Assert.assertEquals(200, response1.getStatusLine().getStatusCode());
IOUtils.consume(response1.getEntity()); IOUtils.consume(response1.getEntity());
EasyMock.verify(backend); verify(backend).execute(
eq(route),
isA(HttpRequestWrapper.class),
isA(HttpClientContext.class),
(HttpExecutionAware) Matchers.isNull());
removeCache(); removeCache();
EasyMock.reset(backend); reset(backend);
EasyMock.expect(backend.execute( when(backend.execute(
EasyMock.eq(route), eq(route),
EasyMock.isA(HttpRequestWrapper.class), isA(HttpRequestWrapper.class),
EasyMock.isA(HttpClientContext.class), isA(HttpClientContext.class),
EasyMock.<HttpExecutionAware>isNull())).andReturn(Proxies.enhanceResponse(response)); (HttpExecutionAware) Matchers.isNull())).thenReturn(Proxies.enhanceResponse(response));
EasyMock.replay(backend);
final HttpResponse response2 = t.execute(route, get, context, null); final HttpResponse response2 = t.execute(route, get, context, null);
Assert.assertEquals(200, response2.getStatusLine().getStatusCode()); Assert.assertEquals(200, response2.getStatusLine().getStatusCode());
IOUtils.consume(response2.getEntity()); IOUtils.consume(response2.getEntity());
EasyMock.verify(backend); verify(backend).execute(
eq(route),
isA(HttpRequestWrapper.class),
isA(HttpClientContext.class),
(HttpExecutionAware) Matchers.isNull());
} }
protected ClientExecChain createCachingExecChain(final ClientExecChain backend, protected ClientExecChain createCachingExecChain(final ClientExecChain backend,

View File

@ -26,7 +26,8 @@
*/ */
package org.apache.http.impl.client.cache; package org.apache.http.impl.client.cache;
import org.easymock.classextension.EasyMock; import static org.mockito.Mockito.mock;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -40,8 +41,8 @@ public class TestImmediateSchedulingStrategy {
@Before @Before
public void setUp() { public void setUp() {
mockExecutor = EasyMock.createMock(ExecutorService.class); mockExecutor = mock(ExecutorService.class);
mockRevalidationRequest = EasyMock.createNiceMock(AsynchronousValidationRequest.class); mockRevalidationRequest = mock(AsynchronousValidationRequest.class);
schedulingStrategy = new ImmediateSchedulingStrategy(mockExecutor); schedulingStrategy = new ImmediateSchedulingStrategy(mockExecutor);
} }
@ -49,10 +50,6 @@ public class TestImmediateSchedulingStrategy {
public void testRequestScheduledImmediately() { public void testRequestScheduledImmediately() {
mockExecutor.execute(mockRevalidationRequest); mockExecutor.execute(mockRevalidationRequest);
EasyMock.replay(mockExecutor);
EasyMock.replay(mockRevalidationRequest);
schedulingStrategy.schedule(mockRevalidationRequest); schedulingStrategy.schedule(mockRevalidationRequest);
EasyMock.verify(mockExecutor);
EasyMock.verify(mockRevalidationRequest);
} }
} }

View File

@ -26,6 +26,13 @@
*/ */
package org.apache.http.impl.client.cache.ehcache; package org.apache.http.impl.client.cache.ehcache;
import static org.mockito.Matchers.isA;
import static org.mockito.Matchers.same;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
@ -40,7 +47,6 @@ import org.apache.http.client.cache.HttpCacheUpdateCallback;
import org.apache.http.client.cache.HttpCacheUpdateException; import org.apache.http.client.cache.HttpCacheUpdateException;
import org.apache.http.impl.client.cache.CacheConfig; import org.apache.http.impl.client.cache.CacheConfig;
import org.apache.http.impl.client.cache.HttpTestUtils; import org.apache.http.impl.client.cache.HttpTestUtils;
import org.easymock.EasyMock;
import org.junit.Test; import org.junit.Test;
@SuppressWarnings("boxing") // test code @SuppressWarnings("boxing") // test code
@ -52,22 +58,12 @@ public class TestEhcacheHttpCacheStorage extends TestCase {
@Override @Override
public void setUp() { public void setUp() {
mockCache = EasyMock.createNiceMock(Ehcache.class); mockCache = mock(Ehcache.class);
final CacheConfig config = CacheConfig.custom().setMaxUpdateRetries(1).build(); final CacheConfig config = CacheConfig.custom().setMaxUpdateRetries(1).build();
mockSerializer = EasyMock.createNiceMock(HttpCacheEntrySerializer.class); mockSerializer = mock(HttpCacheEntrySerializer.class);
impl = new EhcacheHttpCacheStorage(mockCache, config, mockSerializer); impl = new EhcacheHttpCacheStorage(mockCache, config, mockSerializer);
} }
private void replayMocks(){
EasyMock.replay(mockCache);
EasyMock.replay(mockSerializer);
}
private void verifyMocks(){
EasyMock.verify(mockCache);
EasyMock.verify(mockSerializer);
}
@Test @Test
public void testCachePut() throws IOException { public void testCachePut() throws IOException {
final String key = "foo"; final String key = "foo";
@ -75,23 +71,21 @@ public class TestEhcacheHttpCacheStorage extends TestCase {
final Element e = new Element(key, new byte[]{}); final Element e = new Element(key, new byte[]{});
mockSerializer.writeTo(EasyMock.same(value), EasyMock.isA(OutputStream.class));
mockCache.put(e);
replayMocks();
impl.putEntry(key, value); impl.putEntry(key, value);
verifyMocks();
verify(mockSerializer).writeTo(same(value), isA(OutputStream.class));
verify(mockCache).put(e);;
} }
@Test @Test
public void testCacheGetNullEntry() throws IOException { public void testCacheGetNullEntry() throws IOException {
final String key = "foo"; final String key = "foo";
EasyMock.expect(mockCache.get(key)).andReturn(null); when(mockCache.get(key)).thenReturn(null);
replayMocks();
final HttpCacheEntry resultingEntry = impl.getEntry(key); final HttpCacheEntry resultingEntry = impl.getEntry(key);
verifyMocks();
verify(mockCache).get(key);
assertNull(resultingEntry); assertNull(resultingEntry);
} }
@ -103,14 +97,15 @@ public class TestEhcacheHttpCacheStorage extends TestCase {
final Element element = new Element(key, new byte[]{}); final Element element = new Element(key, new byte[]{});
EasyMock.expect(mockCache.get(key)) when(mockCache.get(key))
.andReturn(element); .thenReturn(element);
EasyMock.expect(mockSerializer.readFrom(EasyMock.isA(InputStream.class))) when(mockSerializer.readFrom(isA(InputStream.class)))
.andReturn(cachedValue); .thenReturn(cachedValue);
replayMocks();
final HttpCacheEntry resultingEntry = impl.getEntry(key); final HttpCacheEntry resultingEntry = impl.getEntry(key);
verifyMocks();
verify(mockCache).get(key);
verify(mockSerializer).readFrom(isA(InputStream.class));
assertSame(cachedValue, resultingEntry); assertSame(cachedValue, resultingEntry);
} }
@ -119,11 +114,10 @@ public class TestEhcacheHttpCacheStorage extends TestCase {
public void testCacheRemove() { public void testCacheRemove() {
final String key = "foo"; final String key = "foo";
EasyMock.expect(mockCache.remove(key)).andReturn(true); when(mockCache.remove(key)).thenReturn(true);
replayMocks();
impl.removeEntry(key); impl.removeEntry(key);
verifyMocks(); verify(mockCache).remove(key);
} }
@Test @Test
@ -142,15 +136,16 @@ public class TestEhcacheHttpCacheStorage extends TestCase {
}; };
// get empty old entry // get empty old entry
EasyMock.expect(mockCache.get(key)).andReturn(null); when(mockCache.get(key)).thenReturn(null);
// put new entry // put new entry
mockSerializer.writeTo(EasyMock.same(updatedValue), EasyMock.isA(OutputStream.class)); mockSerializer.writeTo(same(updatedValue), isA(OutputStream.class));
mockCache.put(element);
replayMocks();
impl.updateEntry(key, callback); impl.updateEntry(key, callback);
verifyMocks();
verify(mockCache).get(key);
verify(mockSerializer).writeTo(same(updatedValue), isA(OutputStream.class));
verify(mockCache).put(element);
} }
@Test @Test
@ -170,16 +165,19 @@ public class TestEhcacheHttpCacheStorage extends TestCase {
}; };
// get existing old entry // get existing old entry
EasyMock.expect(mockCache.get(key)).andReturn(existingElement); when(mockCache.get(key)).thenReturn(existingElement);
EasyMock.expect(mockSerializer.readFrom(EasyMock.isA(InputStream.class))).andReturn(existingValue); when(mockSerializer.readFrom(isA(InputStream.class))).thenReturn(existingValue);
// update // update
mockSerializer.writeTo(EasyMock.same(updatedValue), EasyMock.isA(OutputStream.class)); mockSerializer.writeTo(same(updatedValue), isA(OutputStream.class));
EasyMock.expect(mockCache.replace(EasyMock.same(existingElement), EasyMock.isA(Element.class))).andReturn(true); when(mockCache.replace(same(existingElement), isA(Element.class))).thenReturn(true);
replayMocks();
impl.updateEntry(key, callback); impl.updateEntry(key, callback);
verifyMocks();
verify(mockCache).get(key);
verify(mockSerializer).readFrom(isA(InputStream.class));
verify(mockSerializer).writeTo(same(updatedValue), isA(OutputStream.class));
verify(mockCache).replace(same(existingElement), isA(Element.class));
} }
@Test @Test
@ -199,20 +197,18 @@ public class TestEhcacheHttpCacheStorage extends TestCase {
}; };
// get existing old entry, will happen twice // get existing old entry, will happen twice
EasyMock.expect(mockCache.get(key)).andReturn(existingElement).times(2); when(mockCache.get(key)).thenReturn(existingElement);
EasyMock.expect(mockSerializer.readFrom(EasyMock.isA(InputStream.class))).andReturn(existingValue).times(2); when(mockSerializer.readFrom(isA(InputStream.class))).thenReturn(existingValue);
// update but fail // Fail first and then succeed
mockSerializer.writeTo(EasyMock.same(updatedValue), EasyMock.isA(OutputStream.class)); when(mockCache.replace(same(existingElement), isA(Element.class))).thenReturn(false).thenReturn(true);
EasyMock.expectLastCall().times(2);
EasyMock.expect(mockCache.replace(EasyMock.same(existingElement), EasyMock.isA(Element.class))).andReturn(false);
// update again and succeed
EasyMock.expect(mockCache.replace(EasyMock.same(existingElement), EasyMock.isA(Element.class))).andReturn(true);
replayMocks();
impl.updateEntry(key, callback); impl.updateEntry(key, callback);
verifyMocks();
verify(mockCache, times(2)).get(key);
verify(mockSerializer, times(2)).readFrom(isA(InputStream.class));
verify(mockSerializer, times(2)).writeTo(same(updatedValue), isA(OutputStream.class));
verify(mockCache, times(2)).replace(same(existingElement), isA(Element.class));
} }
@Test @Test
@ -232,19 +228,20 @@ public class TestEhcacheHttpCacheStorage extends TestCase {
}; };
// get existing old entry // get existing old entry
EasyMock.expect(mockCache.get(key)).andReturn(existingElement).times(2); when(mockCache.get(key)).thenReturn(existingElement);
EasyMock.expect(mockSerializer.readFrom(EasyMock.isA(InputStream.class))).andReturn(existingValue).times(2); when(mockSerializer.readFrom(isA(InputStream.class))).thenReturn(existingValue);
// update but fail // update but fail
mockSerializer.writeTo(EasyMock.same(updatedValue), EasyMock.isA(OutputStream.class)); when(mockCache.replace(same(existingElement), isA(Element.class))).thenReturn(false);
EasyMock.expectLastCall().times(2);
EasyMock.expect(mockCache.replace(EasyMock.same(existingElement), EasyMock.isA(Element.class))).andReturn(false).times(2);
replayMocks();
try{ try{
impl.updateEntry(key, callback); impl.updateEntry(key, callback);
fail("Expected HttpCacheUpdateException"); fail("Expected HttpCacheUpdateException");
} catch (final HttpCacheUpdateException e) { } } catch (final HttpCacheUpdateException e) { }
verifyMocks();
verify(mockCache, times(2)).get(key);
verify(mockSerializer, times(2)).readFrom(isA(InputStream.class));
verify(mockSerializer, times(2)).writeTo(same(updatedValue), isA(OutputStream.class));
verify(mockCache, times(2)).replace(same(existingElement), isA(Element.class));
} }
} }

View File

@ -26,6 +26,13 @@
*/ */
package org.apache.http.impl.client.cache.memcached; package org.apache.http.impl.client.cache.memcached;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import java.io.IOException; import java.io.IOException;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
@ -40,7 +47,6 @@ import org.apache.http.client.cache.HttpCacheUpdateCallback;
import org.apache.http.client.cache.HttpCacheUpdateException; import org.apache.http.client.cache.HttpCacheUpdateException;
import org.apache.http.impl.client.cache.CacheConfig; import org.apache.http.impl.client.cache.CacheConfig;
import org.apache.http.impl.client.cache.HttpTestUtils; import org.apache.http.impl.client.cache.HttpTestUtils;
import org.easymock.EasyMock;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -57,38 +63,18 @@ public class TestMemcachedHttpCacheStorage extends TestCase {
@Override @Override
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
mockMemcachedClient = EasyMock.createNiceMock(MemcachedClientIF.class); mockMemcachedClient = mock(MemcachedClientIF.class);
mockKeyHashingScheme = EasyMock.createNiceMock(KeyHashingScheme.class); mockKeyHashingScheme = mock(KeyHashingScheme.class);
mockMemcachedCacheEntryFactory = EasyMock.createNiceMock(MemcachedCacheEntryFactory.class); mockMemcachedCacheEntryFactory = mock(MemcachedCacheEntryFactory.class);
mockMemcachedCacheEntry = EasyMock.createNiceMock(MemcachedCacheEntry.class); mockMemcachedCacheEntry = mock(MemcachedCacheEntry.class);
mockMemcachedCacheEntry2 = EasyMock.createNiceMock(MemcachedCacheEntry.class); mockMemcachedCacheEntry2 = mock(MemcachedCacheEntry.class);
mockMemcachedCacheEntry3 = EasyMock.createNiceMock(MemcachedCacheEntry.class); mockMemcachedCacheEntry3 = mock(MemcachedCacheEntry.class);
mockMemcachedCacheEntry4 = EasyMock.createNiceMock(MemcachedCacheEntry.class); mockMemcachedCacheEntry4 = mock(MemcachedCacheEntry.class);
final CacheConfig config = CacheConfig.custom().setMaxUpdateRetries(1).build(); final CacheConfig config = CacheConfig.custom().setMaxUpdateRetries(1).build();
impl = new MemcachedHttpCacheStorage(mockMemcachedClient, config, impl = new MemcachedHttpCacheStorage(mockMemcachedClient, config,
mockMemcachedCacheEntryFactory, mockKeyHashingScheme); mockMemcachedCacheEntryFactory, mockKeyHashingScheme);
} }
private void replayMocks() {
EasyMock.replay(mockMemcachedClient);
EasyMock.replay(mockKeyHashingScheme);
EasyMock.replay(mockMemcachedCacheEntry);
EasyMock.replay(mockMemcachedCacheEntry2);
EasyMock.replay(mockMemcachedCacheEntry3);
EasyMock.replay(mockMemcachedCacheEntry4);
EasyMock.replay(mockMemcachedCacheEntryFactory);
}
private void verifyMocks() {
EasyMock.verify(mockMemcachedClient);
EasyMock.verify(mockKeyHashingScheme);
EasyMock.verify(mockMemcachedCacheEntry);
EasyMock.verify(mockMemcachedCacheEntry2);
EasyMock.verify(mockMemcachedCacheEntry3);
EasyMock.verify(mockMemcachedCacheEntry4);
EasyMock.verify(mockMemcachedCacheEntryFactory);
}
@Test @Test
public void testSuccessfulCachePut() throws IOException { public void testSuccessfulCachePut() throws IOException {
final String url = "foo"; final String url = "foo";
@ -96,18 +82,20 @@ public class TestMemcachedHttpCacheStorage extends TestCase {
final HttpCacheEntry value = HttpTestUtils.makeCacheEntry(); final HttpCacheEntry value = HttpTestUtils.makeCacheEntry();
final byte[] serialized = HttpTestUtils.getRandomBytes(128); final byte[] serialized = HttpTestUtils.getRandomBytes(128);
EasyMock.expect(mockMemcachedCacheEntryFactory.getMemcachedCacheEntry(url, value)) when(mockMemcachedCacheEntryFactory.getMemcachedCacheEntry(url, value))
.andReturn(mockMemcachedCacheEntry); .thenReturn(mockMemcachedCacheEntry);
EasyMock.expect(mockMemcachedCacheEntry.toByteArray()) when(mockMemcachedCacheEntry.toByteArray())
.andReturn(serialized); .thenReturn(serialized);
EasyMock.expect(mockKeyHashingScheme.hash(url)) when(mockKeyHashingScheme.hash(url))
.andReturn(key); .thenReturn(key);
EasyMock.expect(mockMemcachedClient.set(key, 0, serialized)) when(mockMemcachedClient.set(key, 0, serialized))
.andReturn(null); .thenReturn(null);
replayMocks();
impl.putEntry(url, value); impl.putEntry(url, value);
verifyMocks(); verify(mockMemcachedCacheEntryFactory).getMemcachedCacheEntry(url, value);
verify(mockMemcachedCacheEntry).toByteArray();
verify(mockKeyHashingScheme).hash(url);
verify(mockMemcachedClient).set(key, 0, serialized);
} }
@Test @Test
@ -116,16 +104,18 @@ public class TestMemcachedHttpCacheStorage extends TestCase {
final HttpCacheEntry value = HttpTestUtils.makeCacheEntry(); final HttpCacheEntry value = HttpTestUtils.makeCacheEntry();
final byte[] serialized = HttpTestUtils.getRandomBytes(128); final byte[] serialized = HttpTestUtils.getRandomBytes(128);
EasyMock.expect(mockMemcachedCacheEntryFactory.getMemcachedCacheEntry(url, value)) when(mockMemcachedCacheEntryFactory.getMemcachedCacheEntry(url, value))
.andReturn(mockMemcachedCacheEntry).times(0,1); .thenReturn(mockMemcachedCacheEntry);
EasyMock.expect(mockMemcachedCacheEntry.toByteArray()) when(mockMemcachedCacheEntry.toByteArray())
.andReturn(serialized).times(0,1); .thenReturn(serialized);
EasyMock.expect(mockKeyHashingScheme.hash(url)) when(mockKeyHashingScheme.hash(url))
.andThrow(new MemcachedKeyHashingException(new Exception())); .thenThrow(new MemcachedKeyHashingException(new Exception()));
replayMocks();
impl.putEntry(url, value); impl.putEntry(url, value);
verifyMocks();
verify(mockMemcachedCacheEntryFactory).getMemcachedCacheEntry(url, value);
verify(mockMemcachedCacheEntry).toByteArray();
verify(mockKeyHashingScheme).hash(url);
} }
public void testThrowsIOExceptionWhenMemcachedPutTimesOut() { public void testThrowsIOExceptionWhenMemcachedPutTimesOut() {
@ -134,22 +124,25 @@ public class TestMemcachedHttpCacheStorage extends TestCase {
final HttpCacheEntry value = HttpTestUtils.makeCacheEntry(); final HttpCacheEntry value = HttpTestUtils.makeCacheEntry();
final byte[] serialized = HttpTestUtils.getRandomBytes(128); final byte[] serialized = HttpTestUtils.getRandomBytes(128);
EasyMock.expect(mockMemcachedCacheEntryFactory.getMemcachedCacheEntry(url, value)) when(mockMemcachedCacheEntryFactory.getMemcachedCacheEntry(url, value))
.andReturn(mockMemcachedCacheEntry); .thenReturn(mockMemcachedCacheEntry);
EasyMock.expect(mockMemcachedCacheEntry.toByteArray()) when(mockMemcachedCacheEntry.toByteArray())
.andReturn(serialized); .thenReturn(serialized);
EasyMock.expect(mockKeyHashingScheme.hash(url)) when(mockKeyHashingScheme.hash(url))
.andReturn(key); .thenReturn(key);
EasyMock.expect(mockMemcachedClient.set(key, 0, serialized)) when(mockMemcachedClient.set(key, 0, serialized))
.andThrow(new OperationTimeoutException("timed out")); .thenThrow(new OperationTimeoutException("timed out"));
replayMocks();
try { try {
impl.putEntry(url, value); impl.putEntry(url, value);
fail("should have thrown exception"); fail("should have thrown exception");
} catch (final IOException expected) { } catch (final IOException expected) {
} }
verifyMocks();
verify(mockMemcachedCacheEntryFactory).getMemcachedCacheEntry(url, value);
verify(mockMemcachedCacheEntry).toByteArray();
verify(mockKeyHashingScheme).hash(url);
verify(mockMemcachedClient).set(key, 0, serialized);
} }
@Test @Test
@ -158,21 +151,20 @@ public class TestMemcachedHttpCacheStorage extends TestCase {
final String key = "key"; final String key = "key";
final HttpCacheEntry value = HttpTestUtils.makeCacheEntry(); final HttpCacheEntry value = HttpTestUtils.makeCacheEntry();
EasyMock.expect(mockMemcachedCacheEntryFactory.getMemcachedCacheEntry(url, value)) when(mockMemcachedCacheEntryFactory.getMemcachedCacheEntry(url, value))
.andReturn(mockMemcachedCacheEntry); .thenReturn(mockMemcachedCacheEntry);
EasyMock.expect(mockMemcachedCacheEntry.toByteArray()) when(mockMemcachedCacheEntry.toByteArray())
.andThrow(new MemcachedSerializationException(new Exception())); .thenThrow(new MemcachedSerializationException(new Exception()));
EasyMock.expect(mockKeyHashingScheme.hash(url))
.andReturn(key).times(0,1);
replayMocks();
try { try {
impl.putEntry(url, value); impl.putEntry(url, value);
fail("should have thrown exception"); fail("should have thrown exception");
} catch (final IOException expected) { } catch (final IOException expected) {
} }
verifyMocks();
verify(mockMemcachedCacheEntryFactory).getMemcachedCacheEntry(url, value);
verify(mockMemcachedCacheEntry).toByteArray();
} }
@Test @Test
@ -183,17 +175,22 @@ public class TestMemcachedHttpCacheStorage extends TestCase {
final byte[] serialized = HttpTestUtils.getRandomBytes(128); final byte[] serialized = HttpTestUtils.getRandomBytes(128);
final HttpCacheEntry cacheEntry = HttpTestUtils.makeCacheEntry(); final HttpCacheEntry cacheEntry = HttpTestUtils.makeCacheEntry();
EasyMock.expect(mockKeyHashingScheme.hash(url)).andReturn(key); when(mockKeyHashingScheme.hash(url)).thenReturn(key);
EasyMock.expect(mockMemcachedClient.get(key)).andReturn(serialized); when(mockMemcachedClient.get(key)).thenReturn(serialized);
EasyMock.expect(mockMemcachedCacheEntryFactory.getUnsetCacheEntry()) when(mockMemcachedCacheEntryFactory.getUnsetCacheEntry())
.andReturn(mockMemcachedCacheEntry); .thenReturn(mockMemcachedCacheEntry);
mockMemcachedCacheEntry.set(serialized); when(mockMemcachedCacheEntry.getStorageKey()).thenReturn(url);
EasyMock.expect(mockMemcachedCacheEntry.getStorageKey()).andReturn(url); when(mockMemcachedCacheEntry.getHttpCacheEntry()).thenReturn(cacheEntry);
EasyMock.expect(mockMemcachedCacheEntry.getHttpCacheEntry()).andReturn(cacheEntry);
replayMocks();
final HttpCacheEntry resultingEntry = impl.getEntry(url); final HttpCacheEntry resultingEntry = impl.getEntry(url);
verifyMocks();
verify(mockKeyHashingScheme).hash(url);
verify(mockMemcachedClient).get(key);
verify(mockMemcachedCacheEntryFactory).getUnsetCacheEntry();
verify(mockMemcachedCacheEntry).set(serialized);
verify(mockMemcachedCacheEntry).getStorageKey();
verify(mockMemcachedCacheEntry).getHttpCacheEntry();
assertSame(cacheEntry, resultingEntry); assertSame(cacheEntry, resultingEntry);
} }
@ -203,12 +200,14 @@ public class TestMemcachedHttpCacheStorage extends TestCase {
final String url = "foo"; final String url = "foo";
final String key = "key"; final String key = "key";
EasyMock.expect(mockKeyHashingScheme.hash(url)).andReturn(key); when(mockKeyHashingScheme.hash(url)).thenReturn(key);
EasyMock.expect(mockMemcachedClient.get(key)).andReturn(new Object()); when(mockMemcachedClient.get(key)).thenReturn(new Object());
replayMocks();
final HttpCacheEntry resultingEntry = impl.getEntry(url); final HttpCacheEntry resultingEntry = impl.getEntry(url);
verifyMocks();
verify(mockKeyHashingScheme).hash(url);
verify(mockMemcachedClient).get(key);
assertNull(resultingEntry); assertNull(resultingEntry);
} }
@ -218,12 +217,14 @@ public class TestMemcachedHttpCacheStorage extends TestCase {
final String url = "foo"; final String url = "foo";
final String key = "key"; final String key = "key";
EasyMock.expect(mockKeyHashingScheme.hash(url)).andReturn(key); when(mockKeyHashingScheme.hash(url)).thenReturn(key);
EasyMock.expect(mockMemcachedClient.get(key)).andReturn(null); when(mockMemcachedClient.get(key)).thenReturn(null);
replayMocks();
final HttpCacheEntry resultingEntry = impl.getEntry(url); final HttpCacheEntry resultingEntry = impl.getEntry(url);
verifyMocks();
verify(mockKeyHashingScheme).hash(url);
verify(mockMemcachedClient).get(key);
assertNull(resultingEntry); assertNull(resultingEntry);
} }
@ -234,16 +235,18 @@ public class TestMemcachedHttpCacheStorage extends TestCase {
final String key = "key"; final String key = "key";
final byte[] serialized = HttpTestUtils.getRandomBytes(128); final byte[] serialized = HttpTestUtils.getRandomBytes(128);
EasyMock.expect(mockKeyHashingScheme.hash(url)).andReturn(key); when(mockKeyHashingScheme.hash(url)).thenReturn(key);
EasyMock.expect(mockMemcachedClient.get(key)).andReturn(serialized); when(mockMemcachedClient.get(key)).thenReturn(serialized);
EasyMock.expect(mockMemcachedCacheEntryFactory.getUnsetCacheEntry()) when(mockMemcachedCacheEntryFactory.getUnsetCacheEntry())
.andReturn(mockMemcachedCacheEntry); .thenReturn(mockMemcachedCacheEntry);
mockMemcachedCacheEntry.set(serialized); doThrow(new MemcachedSerializationException(new Exception())).when(mockMemcachedCacheEntry).set(serialized);
EasyMock.expectLastCall().andThrow(new MemcachedSerializationException(new Exception()));
replayMocks();
assertNull(impl.getEntry(url)); assertNull(impl.getEntry(url));
verifyMocks();
verify(mockKeyHashingScheme).hash(url);
verify(mockMemcachedClient).get(key);
verify(mockMemcachedCacheEntryFactory).getUnsetCacheEntry();
verify(mockMemcachedCacheEntry).set(serialized);
} }
@Test @Test
@ -251,65 +254,66 @@ public class TestMemcachedHttpCacheStorage extends TestCase {
IOException { IOException {
final String url = "foo"; final String url = "foo";
EasyMock.expect(mockKeyHashingScheme.hash(url)).andThrow(new MemcachedKeyHashingException(new Exception())); when(mockKeyHashingScheme.hash(url)).thenThrow(new MemcachedKeyHashingException(new Exception()));
replayMocks();
assertNull(impl.getEntry(url)); assertNull(impl.getEntry(url));
verifyMocks(); verify(mockKeyHashingScheme).hash(url);
} }
@Test @Test
public void testThrowsIOExceptionIfMemcachedTimesOutOnGet() { public void testThrowsIOExceptionIfMemcachedTimesOutOnGet() {
final String url = "foo"; final String url = "foo";
final String key = "key"; final String key = "key";
EasyMock.expect(mockKeyHashingScheme.hash(url)).andReturn(key); when(mockKeyHashingScheme.hash(url)).thenReturn(key);
EasyMock.expect(mockMemcachedClient.get(key)) when(mockMemcachedClient.get(key))
.andThrow(new OperationTimeoutException("")); .thenThrow(new OperationTimeoutException(""));
replayMocks();
try { try {
impl.getEntry(url); impl.getEntry(url);
fail("should have thrown exception"); fail("should have thrown exception");
} catch (final IOException expected) { } catch (final IOException expected) {
} }
verifyMocks(); verify(mockKeyHashingScheme).hash(url);
verify(mockMemcachedClient).get(key);
} }
@Test @Test
public void testCacheRemove() throws IOException { public void testCacheRemove() throws IOException {
final String url = "foo"; final String url = "foo";
final String key = "key"; final String key = "key";
EasyMock.expect(mockKeyHashingScheme.hash(url)).andReturn(key); when(mockKeyHashingScheme.hash(url)).thenReturn(key);
EasyMock.expect(mockMemcachedClient.delete(key)).andReturn(null); when(mockMemcachedClient.delete(key)).thenReturn(null);
replayMocks();
impl.removeEntry(url); impl.removeEntry(url);
verifyMocks();
verify(mockKeyHashingScheme).hash(url);
verify(mockMemcachedClient).delete(key);
} }
@Test @Test
public void testCacheRemoveHandlesKeyHashingFailure() throws IOException { public void testCacheRemoveHandlesKeyHashingFailure() throws IOException {
final String url = "foo"; final String url = "foo";
EasyMock.expect(mockKeyHashingScheme.hash(url)).andReturn(null); when(mockKeyHashingScheme.hash(url)).thenReturn(null);
replayMocks();
impl.removeEntry(url); impl.removeEntry(url);
verifyMocks(); verify(mockKeyHashingScheme).hash(url);
} }
@Test @Test
public void testCacheRemoveThrowsIOExceptionOnMemcachedTimeout() { public void testCacheRemoveThrowsIOExceptionOnMemcachedTimeout() {
final String url = "foo"; final String url = "foo";
final String key = "key"; final String key = "key";
EasyMock.expect(mockKeyHashingScheme.hash(url)).andReturn(key); when(mockKeyHashingScheme.hash(url)).thenReturn(key);
EasyMock.expect(mockMemcachedClient.delete(key)) when(mockMemcachedClient.delete(key))
.andThrow(new OperationTimeoutException("")); .thenThrow(new OperationTimeoutException(""));
replayMocks();
try { try {
impl.removeEntry(url); impl.removeEntry(url);
fail("should have thrown exception"); fail("should have thrown exception");
} catch (final IOException expected) { } catch (final IOException expected) {
} }
verifyMocks();
verify(mockKeyHashingScheme).hash(url);
verify(mockMemcachedClient).delete(key);
} }
@Test @Test
@ -329,18 +333,22 @@ public class TestMemcachedHttpCacheStorage extends TestCase {
}; };
// get empty old entry // get empty old entry
EasyMock.expect(mockKeyHashingScheme.hash(url)).andReturn(key).anyTimes(); when(mockKeyHashingScheme.hash(url)).thenReturn(key);
EasyMock.expect(mockMemcachedClient.gets(key)).andReturn(null); when(mockMemcachedClient.gets(key)).thenReturn(null);
EasyMock.expect(mockMemcachedCacheEntryFactory.getMemcachedCacheEntry(url, updatedValue)) when(mockMemcachedCacheEntryFactory.getMemcachedCacheEntry(url, updatedValue))
.andReturn(mockMemcachedCacheEntry); .thenReturn(mockMemcachedCacheEntry);
EasyMock.expect(mockMemcachedCacheEntry.toByteArray()).andReturn(serialized); when(mockMemcachedCacheEntry.toByteArray()).thenReturn(serialized);
EasyMock.expect( when(
mockMemcachedClient.set(EasyMock.eq(key), EasyMock.eq(0), mockMemcachedClient.set(key, 0,
EasyMock.aryEq(serialized))).andReturn(null); serialized)).thenReturn(null);
replayMocks();
impl.updateEntry(url, callback); impl.updateEntry(url, callback);
verifyMocks();
verify(mockKeyHashingScheme, times(2)).hash(url);
verify(mockMemcachedClient).gets(key);
verify(mockMemcachedCacheEntryFactory).getMemcachedCacheEntry(url, updatedValue);
verify(mockMemcachedCacheEntry).toByteArray();
verify(mockMemcachedClient).set(key, 0, serialized);
} }
@Test @Test
@ -362,23 +370,28 @@ public class TestMemcachedHttpCacheStorage extends TestCase {
}; };
// get empty old entry // get empty old entry
EasyMock.expect(mockKeyHashingScheme.hash(url)).andReturn(key).anyTimes(); when(mockKeyHashingScheme.hash(url)).thenReturn(key);
EasyMock.expect(mockMemcachedClient.gets(key)).andReturn(casValue); when(mockMemcachedClient.gets(key)).thenReturn(casValue);
EasyMock.expect(mockMemcachedCacheEntryFactory.getUnsetCacheEntry()) when(mockMemcachedCacheEntryFactory.getUnsetCacheEntry())
.andReturn(mockMemcachedCacheEntry); .thenReturn(mockMemcachedCacheEntry);
mockMemcachedCacheEntry.set(oldBytes); when(mockMemcachedCacheEntry.getStorageKey()).thenReturn("not" + url);
EasyMock.expect(mockMemcachedCacheEntry.getStorageKey()).andReturn("not" + url).anyTimes();
EasyMock.expect(mockMemcachedCacheEntryFactory.getMemcachedCacheEntry(url, updatedValue)) when(mockMemcachedCacheEntryFactory.getMemcachedCacheEntry(url, updatedValue))
.andReturn(mockMemcachedCacheEntry2); .thenReturn(mockMemcachedCacheEntry2);
EasyMock.expect(mockMemcachedCacheEntry2.toByteArray()).andReturn(newBytes); when(mockMemcachedCacheEntry2.toByteArray()).thenReturn(newBytes);
EasyMock.expect( when(
mockMemcachedClient.set(EasyMock.eq(key), EasyMock.eq(0), mockMemcachedClient.set(key, 0,
EasyMock.aryEq(newBytes))).andReturn(null); newBytes)).thenReturn(null);
replayMocks();
impl.updateEntry(url, callback); impl.updateEntry(url, callback);
verifyMocks();
verify(mockKeyHashingScheme, times(2)).hash(url);
verify(mockMemcachedClient).gets(key);
verify(mockMemcachedCacheEntryFactory).getUnsetCacheEntry();
verify(mockMemcachedCacheEntry).getStorageKey();
verify(mockMemcachedCacheEntryFactory).getMemcachedCacheEntry(url, updatedValue);
verify(mockMemcachedCacheEntry2).toByteArray();
verify(mockMemcachedClient).set(key, 0, newBytes);
} }
@Test @Test
@ -402,25 +415,31 @@ public class TestMemcachedHttpCacheStorage extends TestCase {
}; };
// get empty old entry // get empty old entry
EasyMock.expect(mockKeyHashingScheme.hash(url)).andReturn(key).anyTimes(); when(mockKeyHashingScheme.hash(url)).thenReturn(key);
EasyMock.expect(mockMemcachedClient.gets(key)).andReturn(casValue); when(mockMemcachedClient.gets(key)).thenReturn(casValue);
EasyMock.expect(mockMemcachedCacheEntryFactory.getUnsetCacheEntry()) when(mockMemcachedCacheEntryFactory.getUnsetCacheEntry())
.andReturn(mockMemcachedCacheEntry); .thenReturn(mockMemcachedCacheEntry);
mockMemcachedCacheEntry.set(oldBytes); when(mockMemcachedCacheEntry.getStorageKey()).thenReturn(url);
EasyMock.expect(mockMemcachedCacheEntry.getStorageKey()).andReturn(url); when(mockMemcachedCacheEntry.getHttpCacheEntry()).thenReturn(existingValue);
EasyMock.expect(mockMemcachedCacheEntry.getHttpCacheEntry()).andReturn(existingValue);
EasyMock.expect(mockMemcachedCacheEntryFactory.getMemcachedCacheEntry(url, updatedValue)) when(mockMemcachedCacheEntryFactory.getMemcachedCacheEntry(url, updatedValue))
.andReturn(mockMemcachedCacheEntry2); .thenReturn(mockMemcachedCacheEntry2);
EasyMock.expect(mockMemcachedCacheEntry2.toByteArray()).andReturn(newBytes); when(mockMemcachedCacheEntry2.toByteArray()).thenReturn(newBytes);
EasyMock.expect( when(
mockMemcachedClient.cas(EasyMock.eq(key), EasyMock.eq(casValue.getCas()), mockMemcachedClient.cas(key, casValue.getCas(),
EasyMock.aryEq(newBytes))).andReturn(CASResponse.OK); newBytes)).thenReturn(CASResponse.OK);
replayMocks();
impl.updateEntry(url, callback); impl.updateEntry(url, callback);
verifyMocks();
verify(mockKeyHashingScheme).hash(url);
verify(mockMemcachedClient).gets(key);
verify(mockMemcachedCacheEntryFactory).getUnsetCacheEntry();
verify(mockMemcachedCacheEntry).getStorageKey();
verify(mockMemcachedCacheEntry).getHttpCacheEntry();
verify(mockMemcachedCacheEntryFactory).getMemcachedCacheEntry(url, updatedValue);
verify(mockMemcachedCacheEntry2).toByteArray();
verify(mockMemcachedClient).cas(key, casValue.getCas(), newBytes);
} }
@Test @Test
@ -446,29 +465,35 @@ public class TestMemcachedHttpCacheStorage extends TestCase {
}; };
// get empty old entry // get empty old entry
EasyMock.expect(mockKeyHashingScheme.hash(url)).andReturn(key).anyTimes(); when(mockKeyHashingScheme.hash(url)).thenReturn(key);
EasyMock.expect(mockMemcachedClient.gets(key)).andReturn(casValue); when(mockMemcachedClient.gets(key)).thenReturn(casValue);
EasyMock.expect(mockMemcachedCacheEntryFactory.getUnsetCacheEntry()) when(mockMemcachedCacheEntryFactory.getUnsetCacheEntry())
.andReturn(mockMemcachedCacheEntry); .thenReturn(mockMemcachedCacheEntry);
mockMemcachedCacheEntry.set(oldBytes); when(mockMemcachedCacheEntry.getStorageKey()).thenReturn(url);
EasyMock.expect(mockMemcachedCacheEntry.getStorageKey()).andReturn(url); when(mockMemcachedCacheEntry.getHttpCacheEntry()).thenReturn(existingValue);
EasyMock.expect(mockMemcachedCacheEntry.getHttpCacheEntry()).andReturn(existingValue);
EasyMock.expect(mockMemcachedCacheEntryFactory.getMemcachedCacheEntry(url, updatedValue)) when(mockMemcachedCacheEntryFactory.getMemcachedCacheEntry(url, updatedValue))
.andReturn(mockMemcachedCacheEntry2); .thenReturn(mockMemcachedCacheEntry2);
EasyMock.expect(mockMemcachedCacheEntry2.toByteArray()).andReturn(newBytes); when(mockMemcachedCacheEntry2.toByteArray()).thenReturn(newBytes);
EasyMock.expect( when(
mockMemcachedClient.cas(EasyMock.eq(key), EasyMock.eq(casValue.getCas()), mockMemcachedClient.cas(key, casValue.getCas(),
EasyMock.aryEq(newBytes))).andReturn(CASResponse.EXISTS); newBytes)).thenReturn(CASResponse.EXISTS);
replayMocks();
try { try {
impl.updateEntry(url, callback); impl.updateEntry(url, callback);
fail("should have thrown exception"); fail("should have thrown exception");
} catch (final HttpCacheUpdateException expected) { } catch (final HttpCacheUpdateException expected) {
} }
verifyMocks();
verify(mockKeyHashingScheme).hash(url);
verify(mockMemcachedClient).gets(key);
verify(mockMemcachedCacheEntryFactory).getUnsetCacheEntry();
verify(mockMemcachedCacheEntry).getStorageKey();
verify(mockMemcachedCacheEntry).getHttpCacheEntry();
verify(mockMemcachedCacheEntryFactory).getMemcachedCacheEntry(url, updatedValue);
verify(mockMemcachedCacheEntry2).toByteArray();
verify(mockMemcachedClient).cas(key, casValue.getCas(), newBytes);
} }
@ -481,11 +506,8 @@ public class TestMemcachedHttpCacheStorage extends TestCase {
final HttpCacheEntry existingValue2 = HttpTestUtils.makeCacheEntry(); final HttpCacheEntry existingValue2 = HttpTestUtils.makeCacheEntry();
final HttpCacheEntry updatedValue = HttpTestUtils.makeCacheEntry(); final HttpCacheEntry updatedValue = HttpTestUtils.makeCacheEntry();
final HttpCacheEntry updatedValue2 = HttpTestUtils.makeCacheEntry(); final HttpCacheEntry updatedValue2 = HttpTestUtils.makeCacheEntry();
final byte[] oldBytes = HttpTestUtils.getRandomBytes(128);
final byte[] oldBytes2 = HttpTestUtils.getRandomBytes(128); final byte[] oldBytes2 = HttpTestUtils.getRandomBytes(128);
final CASValue<Object> casValue = new CASValue<Object>(1, oldBytes);
final CASValue<Object> casValue2 = new CASValue<Object>(2, oldBytes2); final CASValue<Object> casValue2 = new CASValue<Object>(2, oldBytes2);
final byte[] newBytes = HttpTestUtils.getRandomBytes(128);
final byte[] newBytes2 = HttpTestUtils.getRandomBytes(128); final byte[] newBytes2 = HttpTestUtils.getRandomBytes(128);
final HttpCacheUpdateCallback callback = new HttpCacheUpdateCallback() { final HttpCacheUpdateCallback callback = new HttpCacheUpdateCallback() {
@ -499,41 +521,43 @@ public class TestMemcachedHttpCacheStorage extends TestCase {
} }
}; };
EasyMock.expect(mockKeyHashingScheme.hash(url)).andReturn(key).anyTimes(); when(mockKeyHashingScheme.hash(url)).thenReturn(key);
EasyMock.expect(mockMemcachedClient.gets(key)).andReturn(casValue);
EasyMock.expect(mockMemcachedCacheEntryFactory.getUnsetCacheEntry())
.andReturn(mockMemcachedCacheEntry);
mockMemcachedCacheEntry.set(oldBytes);
EasyMock.expect(mockMemcachedCacheEntry.getStorageKey()).andReturn(url);
EasyMock.expect(mockMemcachedCacheEntry.getHttpCacheEntry()).andReturn(existingValue);
EasyMock.expect(mockMemcachedCacheEntryFactory.getMemcachedCacheEntry(url, updatedValue))
.andReturn(mockMemcachedCacheEntry2);
EasyMock.expect(mockMemcachedCacheEntry2.toByteArray()).andReturn(newBytes);
EasyMock.expect(
mockMemcachedClient.cas(EasyMock.eq(key), EasyMock.eq(casValue.getCas()),
EasyMock.aryEq(newBytes))).andReturn(CASResponse.EXISTS);
// take two // take two
EasyMock.expect(mockMemcachedClient.gets(key)).andReturn(casValue2); when(mockMemcachedClient.gets(key)).thenReturn(casValue2);
EasyMock.expect(mockMemcachedCacheEntryFactory.getUnsetCacheEntry()) when(mockMemcachedCacheEntryFactory.getUnsetCacheEntry())
.andReturn(mockMemcachedCacheEntry3); .thenReturn(mockMemcachedCacheEntry3);
mockMemcachedCacheEntry3.set(oldBytes2); when(mockMemcachedCacheEntry3.getStorageKey()).thenReturn(url);
EasyMock.expect(mockMemcachedCacheEntry3.getStorageKey()).andReturn(url); when(mockMemcachedCacheEntry3.getHttpCacheEntry()).thenReturn(existingValue2);
EasyMock.expect(mockMemcachedCacheEntry3.getHttpCacheEntry()).andReturn(existingValue2);
EasyMock.expect(mockMemcachedCacheEntryFactory.getMemcachedCacheEntry(url, updatedValue2)) when(mockMemcachedCacheEntryFactory.getMemcachedCacheEntry(url, updatedValue2))
.andReturn(mockMemcachedCacheEntry4); .thenReturn(mockMemcachedCacheEntry4);
EasyMock.expect(mockMemcachedCacheEntry4.toByteArray()).andReturn(newBytes2); when(mockMemcachedCacheEntry4.toByteArray()).thenReturn(newBytes2);
EasyMock.expect( when(
mockMemcachedClient.cas(EasyMock.eq(key), EasyMock.eq(casValue2.getCas()), mockMemcachedClient.cas(key, casValue2.getCas(),
EasyMock.aryEq(newBytes2))).andReturn(CASResponse.OK); newBytes2)).thenReturn(CASResponse.OK);
replayMocks();
impl.updateEntry(url, callback); impl.updateEntry(url, callback);
verifyMocks();
verify(mockKeyHashingScheme).hash(url);
verify(mockMemcachedClient).gets(key);
verify(mockMemcachedCacheEntryFactory).getUnsetCacheEntry();
verify(mockMemcachedCacheEntry3).set(oldBytes2);
verify(mockMemcachedCacheEntry3).getStorageKey();
verify(mockMemcachedCacheEntry3).getHttpCacheEntry();
verify(mockMemcachedCacheEntryFactory).getMemcachedCacheEntry(url, updatedValue2);
verify(mockMemcachedCacheEntry4).toByteArray();
verify(mockMemcachedClient).cas(key, casValue2.getCas(), newBytes2);
verifyNoMoreInteractions(mockMemcachedClient);
verifyNoMoreInteractions(mockKeyHashingScheme);
verifyNoMoreInteractions(mockMemcachedCacheEntry);
verifyNoMoreInteractions(mockMemcachedCacheEntry2);
verifyNoMoreInteractions(mockMemcachedCacheEntry3);
verifyNoMoreInteractions(mockMemcachedCacheEntry4);
verifyNoMoreInteractions(mockMemcachedCacheEntryFactory);
} }
@ -552,17 +576,18 @@ public class TestMemcachedHttpCacheStorage extends TestCase {
}; };
// get empty old entry // get empty old entry
EasyMock.expect(mockKeyHashingScheme.hash(url)).andReturn(key).anyTimes(); when(mockKeyHashingScheme.hash(url)).thenReturn(key);
EasyMock.expect(mockMemcachedClient.gets(key)) when(mockMemcachedClient.gets(key))
.andThrow(new OperationTimeoutException("")); .thenThrow(new OperationTimeoutException(""));
replayMocks();
try { try {
impl.updateEntry(url, callback); impl.updateEntry(url, callback);
fail("should have thrown exception"); fail("should have thrown exception");
} catch (final IOException expected) { } catch (final IOException expected) {
} }
verifyMocks();
verify(mockKeyHashingScheme).hash(url);
verify(mockMemcachedClient).gets(key);
} }
@ -570,15 +595,15 @@ public class TestMemcachedHttpCacheStorage extends TestCase {
public void testThrowsExceptionOnUpdateIfCannotHashStorageKey() throws Exception { public void testThrowsExceptionOnUpdateIfCannotHashStorageKey() throws Exception {
final String url = "foo"; final String url = "foo";
EasyMock.expect(mockKeyHashingScheme.hash(url)) when(mockKeyHashingScheme.hash(url))
.andThrow(new MemcachedKeyHashingException(new Exception())); .thenThrow(new MemcachedKeyHashingException(new Exception()));
replayMocks();
try { try {
impl.updateEntry(url, null); impl.updateEntry(url, null);
fail("should have thrown exception"); fail("should have thrown exception");
} catch (final HttpCacheUpdateException expected) { } catch (final HttpCacheUpdateException expected) {
} }
verifyMocks();
verify(mockKeyHashingScheme).hash(url);
} }
} }