use of org.easymock.Capture in project rest.li by linkedin.
the class TestArgumentBuilder method testBuildArgsHappyPath.
@Test
public void testBuildArgsHappyPath() {
//test integer association key integer
String param1Key = "param1";
Parameter<Integer> param1 = new Parameter<Integer>(param1Key, Integer.class, DataTemplateUtil.getSchema(Integer.class), false, null, Parameter.ParamType.ASSOC_KEY_PARAM, false, AnnotationSet.EMPTY);
Integer param1Value = 123;
//test regular string argument
String param2Key = "param2";
Parameter<String> param2 = new Parameter<String>(param2Key, String.class, DataTemplateUtil.getSchema(String.class), true, null, Parameter.ParamType.QUERY, true, AnnotationSet.EMPTY);
String param2Value = "param2Value";
//test data template argument array with more than element
String param3Key = "param3";
Parameter<StringArray> param3 = new Parameter<StringArray>(param3Key, StringArray.class, DataTemplateUtil.getSchema(StringArray.class), true, null, Parameter.ParamType.QUERY, true, AnnotationSet.EMPTY);
DataList param3Value = new DataList(Arrays.asList("param3a", "param3b"));
StringArray param3Final = new StringArray(param3Value);
//test data template argument array with only one element
String param4Key = "param4";
Parameter<StringArray> param4 = new Parameter<StringArray>(param4Key, StringArray.class, DataTemplateUtil.getSchema(StringArray.class), true, null, Parameter.ParamType.QUERY, true, AnnotationSet.EMPTY);
String param4Value = "param4Value";
StringArray param4Final = new StringArray(new DataList(Collections.singletonList(param4Value)));
// test record template
String param5Key = "param5";
Parameter<TestRecord> param5 = new Parameter<TestRecord>(param5Key, TestRecord.class, DataTemplateUtil.getSchema(TestRecord.class), true, null, Parameter.ParamType.QUERY, true, AnnotationSet.EMPTY);
DataMap param5Value = new DataMap();
param5Value.put("doubleField", "5.5");
param5Value.put("floatField", "5");
param5Value.put("intField", "5");
param5Value.put("longField", "5");
TestRecord param5Final = new TestRecord();
param5Final.setDoubleField(5.5);
param5Final.setFloatField(5F);
param5Final.setIntField(5);
param5Final.setLongField(5);
// test record template array
String param6Key = "param6";
Parameter<TestRecordArray> param6 = new Parameter<TestRecordArray>(param6Key, TestRecordArray.class, DataTemplateUtil.getSchema(TestRecordArray.class), true, null, Parameter.ParamType.QUERY, true, AnnotationSet.EMPTY);
DataList param6Value = new DataList();
DataMap testRecordDataMap1 = new DataMap();
testRecordDataMap1.put("doubleField", "6.6");
testRecordDataMap1.put("floatField", "6");
testRecordDataMap1.put("intField", "6");
testRecordDataMap1.put("longField", "6");
DataMap testRecordDataMap2 = new DataMap();
testRecordDataMap2.put("doubleField", "66.6");
testRecordDataMap2.put("floatField", "66");
testRecordDataMap2.put("intField", "66");
testRecordDataMap2.put("longField", "66");
param6Value.add(testRecordDataMap1);
param6Value.add(testRecordDataMap2);
TestRecordArray param6Final = new TestRecordArray();
TestRecord testRecord1 = new TestRecord();
testRecord1.setDoubleField(6.6);
testRecord1.setFloatField(6);
testRecord1.setIntField(6);
testRecord1.setLongField(6);
TestRecord testRecord2 = new TestRecord();
testRecord2.setDoubleField(66.6);
testRecord2.setFloatField(66);
testRecord2.setIntField(66);
testRecord2.setLongField(66);
param6Final.add(testRecord1);
param6Final.add(testRecord2);
List<Parameter<?>> parameters = new ArrayList<Parameter<?>>();
parameters.add(param1);
parameters.add(param2);
parameters.add(param3);
parameters.add(param4);
parameters.add(param5);
parameters.add(param6);
Object[] positionalArguments = new Object[0];
Capture<String> param1Capture = new Capture<String>();
Capture<String> param2Capture = new Capture<String>();
Capture<String> param3Capture = new Capture<String>();
Capture<String> param4Capture = new Capture<String>();
Capture<String> param5Capture = new Capture<String>();
Capture<String> param6Capture = new Capture<String>();
ServerResourceContext mockResourceContext = EasyMock.createMock(ServerResourceContext.class);
EasyMock.expect(mockResourceContext.getRequestAttachmentReader()).andReturn(null);
MutablePathKeys mockPathKeys = EasyMock.createMock(MutablePathKeys.class);
ResourceMethodDescriptor mockResourceMethodDescriptor = getMockResourceMethod(parameters);
//easy mock for processing param1
EasyMock.expect(mockPathKeys.get(EasyMock.capture(param1Capture))).andReturn(param1Value);
EasyMock.expect(mockResourceContext.getPathKeys()).andReturn(mockPathKeys);
//easy mock for processing param2
EasyMock.expect(mockResourceContext.getParameter(EasyMock.capture(param2Capture))).andReturn(param2Value);
//easy mock for processing param3
EasyMock.expect(mockResourceContext.getStructuredParameter(EasyMock.capture(param3Capture))).andReturn(param3Value);
//easy mock for processing param4
EasyMock.expect(mockResourceContext.getStructuredParameter(EasyMock.capture(param4Capture))).andReturn(param4Value);
//easy mock for processing param5
EasyMock.expect(mockResourceContext.getStructuredParameter(EasyMock.capture(param5Capture))).andReturn(param5Value);
//easy mock for processing param6
EasyMock.expect(mockResourceContext.getStructuredParameter(EasyMock.capture(param6Capture))).andReturn(param6Value);
EasyMock.replay(mockResourceContext, mockPathKeys);
Object[] results = ArgumentBuilder.buildArgs(positionalArguments, mockResourceMethodDescriptor, mockResourceContext, null);
EasyMock.verify(mockPathKeys, mockResourceContext, mockResourceMethodDescriptor);
Assert.assertEquals(param1Capture.getValue(), param1Key);
Assert.assertEquals(param2Capture.getValue(), param2Key);
Assert.assertEquals(param3Capture.getValue(), param3Key);
Assert.assertEquals(param4Capture.getValue(), param4Key);
Assert.assertEquals(param5Capture.getValue(), param5Key);
Assert.assertEquals(param6Capture.getValue(), param6Key);
Assert.assertEquals(results[0], param1Value);
Assert.assertEquals(results[1], param2Value);
Assert.assertEquals(results[2], param3Final);
Assert.assertEquals(results[3], param4Final);
Assert.assertEquals(results[4], param5Final);
Assert.assertEquals(results[5], param6Final);
}
use of org.easymock.Capture in project rest.li by linkedin.
the class TestRestLiMethodInvocation method testExecutionReport.
@Test
public void testExecutionReport() throws RestLiSyntaxException, URISyntaxException {
Map<String, ResourceModel> resourceModelMap = buildResourceModels(StatusCollectionResource.class, AsyncStatusCollectionResource.class, PromiseStatusCollectionResource.class, TaskStatusCollectionResource.class);
ResourceModel statusResourceModel = resourceModelMap.get("/statuses");
ResourceModel asyncStatusResourceModel = resourceModelMap.get("/asyncstatuses");
ResourceModel promiseStatusResourceModel = resourceModelMap.get("/promisestatuses");
ResourceModel taskStatusResourceModel = resourceModelMap.get("/taskstatuses");
ResourceMethodDescriptor methodDescriptor;
StatusCollectionResource statusResource;
AsyncStatusCollectionResource asyncStatusResource;
PromiseStatusCollectionResource promiseStatusResource;
TaskStatusCollectionResource taskStatusResource;
// #1: Sync Method Execution
methodDescriptor = statusResourceModel.findMethod(ResourceMethod.GET);
statusResource = getMockResource(StatusCollectionResource.class);
EasyMock.expect(statusResource.get(eq(1L))).andReturn(null).once();
checkInvocation(statusResource, methodDescriptor, "GET", version, "/statuses/1", null, buildPathKeys("statusID", 1L), new RequestExecutionCallback<RestResponse>() {
//A 404 is considered an error by rest.li
@Override
public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
Assert.assertNull(executionReport.getParseqTrace(), "There should be no parseq trace!");
}
@Override
public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
Assert.fail("Request failed unexpectedly.");
}
}, true, false);
// #2: Callback based Async Method Execution
Capture<RequestExecutionReport> requestExecutionReportCapture = new Capture<RequestExecutionReport>();
RestLiCallback<?> callback = getCallback(requestExecutionReportCapture);
methodDescriptor = asyncStatusResourceModel.findMethod(ResourceMethod.GET);
asyncStatusResource = getMockResource(AsyncStatusCollectionResource.class);
asyncStatusResource.get(eq(1L), EasyMock.<Callback<Status>>anyObject());
EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
@SuppressWarnings("unchecked") Callback<Status> callback = (Callback<Status>) EasyMock.getCurrentArguments()[1];
callback.onSuccess(null);
return null;
}
});
EasyMock.replay(asyncStatusResource);
checkAsyncInvocation(asyncStatusResource, callback, methodDescriptor, "GET", version, "/asyncstatuses/1", null, buildPathKeys("statusID", 1L), true);
Assert.assertNull(requestExecutionReportCapture.getValue().getParseqTrace());
// #3: Promise based Async Method Execution
methodDescriptor = promiseStatusResourceModel.findMethod(ResourceMethod.GET);
promiseStatusResource = getMockResource(PromiseStatusCollectionResource.class);
EasyMock.expect(promiseStatusResource.get(eq(1L))).andReturn(Promises.<Status>value(null)).once();
checkInvocation(promiseStatusResource, methodDescriptor, "GET", version, "/promisestatuses/1", null, buildPathKeys("statusID", 1L), new RequestExecutionCallback<RestResponse>() {
//A 404 is considered an error by rest.li
@Override
public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
Assert.assertNotNull(executionReport.getParseqTrace(), "There should be a valid parseq trace!");
}
@Override
public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
Assert.fail("Request failed unexpectedly.");
}
}, true, false);
// #4: Task based Async Method Execution
methodDescriptor = taskStatusResourceModel.findMethod(ResourceMethod.GET);
taskStatusResource = getMockResource(TaskStatusCollectionResource.class);
EasyMock.expect(taskStatusResource.get(eq(1L))).andReturn(Task.callable("myTask", new Callable<Status>() {
@Override
public Status call() throws Exception {
return new Status();
}
})).once();
checkInvocation(taskStatusResource, methodDescriptor, "GET", version, "/taskstatuses/1", null, buildPathKeys("statusID", 1L), new RequestExecutionCallback<RestResponse>() {
@Override
public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
Assert.fail("Request failed unexpectedly.");
}
@Override
public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
Assert.assertNotNull(executionReport.getParseqTrace());
}
}, true, false);
}
use of org.easymock.Capture in project commons by twitter.
the class LowResClockTest method testLowResClock.
@Test
public void testLowResClock() {
final WaitingFakeClock clock = new WaitingFakeClock();
final long start = clock.nowMillis();
ScheduledExecutorService mockExecutor = createMock(ScheduledExecutorService.class);
final Capture<Runnable> runnable = new Capture<Runnable>();
final Capture<Long> period = new Capture<Long>();
mockExecutor.scheduleAtFixedRate(capture(runnable), anyLong(), captureLong(period), eq(TimeUnit.MILLISECONDS));
expectLastCall().andAnswer(new IAnswer<ScheduledFuture<?>>() {
public ScheduledFuture<?> answer() {
final Thread ticker = new Thread() {
@Override
public void run() {
Tick tick = new Tick(clock, start, period.getValue(), runnable.getValue());
try {
while (true) {
clock.doOnAdvance(tick);
}
} catch (InterruptedException e) {
/* terminate */
}
}
};
ticker.setDaemon(true);
ticker.start();
final ScheduledFuture<?> future = createMock(ScheduledFuture.class);
final AtomicBoolean stopped = new AtomicBoolean(false);
expect(future.isCancelled()).andAnswer(new IAnswer<Boolean>() {
@Override
public Boolean answer() throws Throwable {
return stopped.get();
}
}).anyTimes();
expect(future.cancel(anyBoolean())).andAnswer(new IAnswer<Boolean>() {
@Override
public Boolean answer() throws Throwable {
ticker.interrupt();
stopped.set(true);
return true;
}
});
replay(future);
return future;
}
});
replay(mockExecutor);
LowResClock lowRes = new LowResClock(Amount.of(1L, Time.SECONDS), mockExecutor, clock);
long t = lowRes.nowMillis();
clock.advance(Amount.of(100L, Time.MILLISECONDS));
assertEquals(t, lowRes.nowMillis());
clock.advance(Amount.of(900L, Time.MILLISECONDS));
assertEquals(t + 1000, lowRes.nowMillis());
clock.advance(Amount.of(100L, Time.MILLISECONDS));
assertEquals(t + 1000, lowRes.nowMillis());
lowRes.close();
try {
lowRes.nowMillis();
fail("Closed clock should throw exception!");
} catch (IllegalStateException e) {
/* expected */
}
}
use of org.easymock.Capture in project commons by twitter.
the class ThriftTest method testAsyncRetrySelection.
@Test
public void testAsyncRetrySelection() throws Exception {
// verify subclasses pass the retry filter
class HopelesslyLost extends NotFoundException {
}
Capture<AsyncMethodCallback<Integer>> callbackCapture1 = new Capture<AsyncMethodCallback<Integer>>();
expectAsyncServiceCall(true).calculateMass(eq("jake"), capture(callbackCapture1));
requestTracker.requestResult((InetSocketAddress) anyObject(), eq(RequestTracker.RequestResult.FAILED), anyLong());
Capture<AsyncMethodCallback<Integer>> callbackCapture2 = new Capture<AsyncMethodCallback<Integer>>();
expectAsyncServiceRetry(true).calculateMass(eq("jake"), capture(callbackCapture2));
requestTracker.requestResult((InetSocketAddress) anyObject(), eq(RequestTracker.RequestResult.FAILED), anyLong());
// Verifies that our callback was called.
TTransportException nonRetryableException = new TTransportException();
callback.onError(nonRetryableException);
Thrift<TestServiceAsync> thrift = createAsyncThrift(expectUnusedExecutorService());
control.replay();
TestServiceAsync testService = thrift.builder().withRetries(2).retryOn(NotFoundException.class).withConnectTimeout(ASYNC_CONNECT_TIMEOUT).create();
testService.calculateMass("jake", callback);
callbackCapture1.getValue().onError(new HopelesslyLost());
callbackCapture2.getValue().onError(nonRetryableException);
assertRequestsTotal(thrift, 1);
assertErrorsTotal(thrift, 1);
assertReconnectsTotal(thrift, 1);
assertTimeoutsTotal(thrift, 0);
control.verify();
}
use of org.easymock.Capture in project commons by twitter.
the class ThriftTest method testDoCallThriftException.
@Test
public void testDoCallThriftException() throws Exception {
Capture<TTransport> transportCapture = new Capture<TTransport>();
TestService testService = expectThriftError(transportCapture);
TTransportException tException = new TTransportException();
expect(testService.calculateMass("jake")).andThrow(tException);
requestTracker.requestResult((InetSocketAddress) anyObject(), eq(RequestTracker.RequestResult.FAILED), anyLong());
Thrift<TestService> thrift = createThrift(expectUnusedExecutorService());
control.replay();
try {
thrift.builder().blocking().create().calculateMass("jake");
fail("Expected thrift exception to bubble unmodified");
} catch (TException e) {
assertSame(tException, e);
}
assertRequestsTotal(thrift, 1);
assertErrorsTotal(thrift, 1);
assertReconnectsTotal(thrift, 1);
assertTimeoutsTotal(thrift, 0);
assertTrue(transportCapture.hasCaptured());
assertFalse("Expected the transport to be forcibly closed when a thrift error is encountered", transportCapture.getValue().isOpen());
control.verify();
}
Aggregations