use of com.github.ambry.rest.MockRestResponseChannel in project ambry by linkedin.
the class FrontendTestUrlSigningServiceFactory method getStatsReportTest.
/**
* Tests the handling of {@link Operations#STATS_REPORT} get requests.
* @throws Exception
*/
@Test
public void getStatsReportTest() throws Exception {
AggregatedAccountStorageStats aggregatedAccountStorageStats = new AggregatedAccountStorageStats(StorageStatsUtilTest.generateRandomAggregatedAccountStorageStats((short) 1, 10, 10, 1000L, 2, 100));
AggregatedPartitionClassStorageStats aggregatedPartitionClassStorageStats = new AggregatedPartitionClassStorageStats(StorageStatsUtilTest.generateRandomAggregatedPartitionClassStorageStats(new String[] { "default", "newClass" }, (short) 1, 10, 10, 1000L, 2, 100));
doAnswer(invocation -> {
String clusterName = invocation.getArgument(0);
if (clusterName.equals(CLUSTER_NAME)) {
return aggregatedAccountStorageStats;
} else {
return null;
}
}).when(accountStatsStore).queryAggregatedAccountStorageStatsByClusterName(anyString());
doAnswer(invocation -> {
String clusterName = invocation.getArgument(0);
if (clusterName.equals(CLUSTER_NAME)) {
return aggregatedPartitionClassStorageStats;
} else {
return null;
}
}).when(accountStatsStore).queryAggregatedPartitionClassStorageStatsByClusterName(anyString());
ObjectMapper mapper = new ObjectMapper();
// construct a request to get account stats
JSONObject headers = new JSONObject();
headers.put(RestUtils.Headers.CLUSTER_NAME, CLUSTER_NAME);
headers.put(RestUtils.Headers.GET_STATS_REPORT_TYPE, StatsReportType.ACCOUNT_REPORT.name());
RestRequest request = createRestRequest(RestMethod.GET, Operations.STATS_REPORT, headers, null);
MockRestResponseChannel restResponseChannel = new MockRestResponseChannel();
doOperation(request, restResponseChannel);
assertEquals("Storage stats mismatch", aggregatedAccountStorageStats.getStorageStats(), mapper.readValue(restResponseChannel.getResponseBody(), AggregatedAccountStorageStats.class).getStorageStats());
// construct a request to get partition class stats
headers = new JSONObject();
headers.put(RestUtils.Headers.CLUSTER_NAME, CLUSTER_NAME);
headers.put(RestUtils.Headers.GET_STATS_REPORT_TYPE, StatsReportType.PARTITION_CLASS_REPORT.name());
request = createRestRequest(RestMethod.GET, Operations.STATS_REPORT, headers, null);
restResponseChannel = new MockRestResponseChannel();
doOperation(request, restResponseChannel);
assertEquals("Storage stats mismatch", aggregatedPartitionClassStorageStats.getStorageStats(), mapper.readValue(restResponseChannel.getResponseBody(), AggregatedPartitionClassStorageStats.class).getStorageStats());
// test clustername not found case to ensure that it goes through the exception path
headers = new JSONObject();
headers.put(RestUtils.Headers.CLUSTER_NAME, "WRONG_CLUSTER");
headers.put(RestUtils.Headers.GET_STATS_REPORT_TYPE, StatsReportType.ACCOUNT_REPORT.name());
request = createRestRequest(RestMethod.GET, Operations.STATS_REPORT, headers, null);
try {
doOperation(request, new MockRestResponseChannel());
fail("Operation should have failed");
} catch (RestServiceException e) {
assertEquals("ErrorCode not as expected", RestServiceErrorCode.NotFound, e.getErrorCode());
}
}
use of com.github.ambry.rest.MockRestResponseChannel in project ambry by linkedin.
the class FrontendTestUrlSigningServiceFactory method updateTtlRejectedTest.
/**
* Tests the case when the TTL update is rejected
* @throws Exception
*/
@Test
public void updateTtlRejectedTest() throws Exception {
FrontendTestRouter testRouter = new FrontendTestRouter();
String exceptionMsg = TestUtils.getRandomString(10);
testRouter.exceptionToReturn = new RouterException(exceptionMsg, RouterErrorCode.BlobUpdateNotAllowed);
testRouter.exceptionOpType = FrontendTestRouter.OpType.UpdateBlobTtl;
frontendRestRequestService = new FrontendRestRequestService(frontendConfig, frontendMetrics, testRouter, clusterMap, idConverterFactory, securityServiceFactory, urlSigningService, idSigningService, null, accountService, accountAndContainerInjector, datacenterName, hostname, clusterName, accountStatsStore, QUOTA_MANAGER);
frontendRestRequestService.setupResponseHandler(responseHandler);
frontendRestRequestService.start();
String blobId = new BlobId(blobIdVersion, BlobId.BlobIdType.NATIVE, (byte) -1, Account.UNKNOWN_ACCOUNT_ID, Container.UNKNOWN_CONTAINER_ID, clusterMap.getAllPartitionIds(null).get(0), false, BlobId.BlobDataType.DATACHUNK).getID();
JSONObject headers = new JSONObject();
setUpdateTtlHeaders(headers, blobId, "updateTtlRejectedTest");
RestRequest restRequest = createRestRequest(RestMethod.PUT, Operations.UPDATE_TTL, headers, null);
MockRestResponseChannel restResponseChannel = verifyOperationFailure(restRequest, RestServiceErrorCode.NotAllowed);
assertEquals("Unexpected response status", ResponseStatus.MethodNotAllowed, restResponseChannel.getStatus());
assertEquals("Unexpected value for the 'allow' header", FrontendRestRequestService.TTL_UPDATE_REJECTED_ALLOW_HEADER_VALUE, restResponseChannel.getHeader(RestUtils.Headers.ALLOW));
}
use of com.github.ambry.rest.MockRestResponseChannel in project ambry by linkedin.
the class FrontendTestUrlSigningServiceFactory method getAccountsTest.
/**
* Tests the handling of {@link Operations#ACCOUNTS} get requests.
* @throws Exception
*/
@Test
public void getAccountsTest() throws Exception {
RestRequest restRequest = createRestRequest(RestMethod.GET, Operations.ACCOUNTS, null, null);
MockRestResponseChannel restResponseChannel = new MockRestResponseChannel();
doOperation(restRequest, restResponseChannel);
Set<Account> expected = new HashSet<>(accountService.getAllAccounts());
Set<Account> actual = new HashSet<>(AccountCollectionSerde.accountsFromInputStreamInJson(new ByteArrayInputStream(restResponseChannel.getResponseBody())));
assertEquals("Unexpected GET /accounts response", expected, actual);
// test an account not found case to ensure that it goes through the exception path
restRequest = createRestRequest(RestMethod.GET, Operations.ACCOUNTS, new JSONObject().put(RestUtils.Headers.TARGET_ACCOUNT_ID, accountService.generateRandomAccount().getId()), null);
try {
doOperation(restRequest, new MockRestResponseChannel());
fail("Operation should have failed");
} catch (RestServiceException e) {
assertEquals("Error code not as expected", RestServiceErrorCode.NotFound, e.getErrorCode());
}
}
use of com.github.ambry.rest.MockRestResponseChannel in project ambry by linkedin.
the class FrontendTestUrlSigningServiceFactory method postBlobAndVerifyWithAccountAndContainer.
/**
* Posts a blob and verifies the injected {@link Account} and {@link Container} into the {@link RestRequest}.
* @param accountName The accountName to send as the header of the request.
* @param containerName The containerName to send as the header of the request.
* @param serviceId The serviceId to send as the header of the request.
* @param isPrivate The isPrivate flag for the blob.
* @param expectedAccount The expected {@link Account} that would be injected into the {@link RestRequest}.
* @param expectedContainer The expected {@link Container} that would be injected into the {@link RestRequest}.
* @param expectedRestErrorCode The expected {@link RestServiceErrorCode} after the put operation.
* @return The blobId string if the put operation is successful, {@link null} otherwise.
* @throws Exception
*/
private String postBlobAndVerifyWithAccountAndContainer(String accountName, String containerName, String serviceId, boolean isPrivate, Account expectedAccount, Container expectedContainer, RestServiceErrorCode expectedRestErrorCode) throws Exception {
ByteBuffer content = ByteBuffer.wrap(TestUtils.getRandomBytes(CONTENT_LENGTH));
List<ByteBuffer> contents = new LinkedList<>();
contents.add(content);
contents.add(null);
String contentType = "application/octet-stream";
String ownerId = "postGetHeadDeleteOwnerID";
JSONObject headers = new JSONObject();
setAmbryHeadersForPut(headers, 7200, isPrivate, serviceId, contentType, ownerId, accountName, containerName, null);
RestRequest restRequest = createRestRequest(RestMethod.POST, "/", headers, contents);
MockRestResponseChannel restResponseChannel = new MockRestResponseChannel();
try {
doOperation(restRequest, restResponseChannel);
if (expectedRestErrorCode != null) {
fail("Should have thrown");
}
} catch (RestServiceException e) {
assertEquals("Wrong RestServiceErrorCode", expectedRestErrorCode, e.getErrorCode());
}
assertEquals("Wrong account object in RestRequest's args", expectedAccount, restRequest.getArgs().get(RestUtils.InternalKeys.TARGET_ACCOUNT_KEY));
assertEquals("Wrong container object in RestRequest's args", expectedContainer, restRequest.getArgs().get(RestUtils.InternalKeys.TARGET_CONTAINER_KEY));
if (expectedRestErrorCode == null) {
// Verify that container metrics were injected iff the account is not in the exclusion list
ContainerMetrics containerMetrics = restRequest.getMetricsTracker().getContainerMetrics();
if (frontendConfig.containerMetricsExcludedAccounts.contains(accountName)) {
assertNull("Expected no container metrics", containerMetrics);
} else {
assertNotNull("Expected container metrics", containerMetrics);
}
}
return expectedRestErrorCode == null ? restResponseChannel.getHeader(RestUtils.Headers.LOCATION) : null;
}
use of com.github.ambry.rest.MockRestResponseChannel in project ambry by linkedin.
the class GetAccountsHandlerTest method getSingleContainerSuccessTest.
/**
* Test success case of getting single container.
* @throws Exception
*/
@Test
public void getSingleContainerSuccessTest() throws Exception {
Account existingAccount = accountService.createAndAddRandomAccount();
Container existingContainer = existingAccount.getAllContainers().iterator().next();
ThrowingBiConsumer<RestRequest, Container> testAction = (request, expectedContainer) -> {
RestResponseChannel restResponseChannel = new MockRestResponseChannel();
ReadableStreamChannel channel = sendRequestGetResponse(request, restResponseChannel);
assertNotNull("There should be a response", channel);
Assert.assertNotNull("Date has not been set", restResponseChannel.getHeader(RestUtils.Headers.DATE));
assertEquals("Content-type is not as expected", RestUtils.JSON_CONTENT_TYPE, restResponseChannel.getHeader(RestUtils.Headers.CONTENT_TYPE));
assertEquals("Content-length is not as expected", channel.getSize(), Integer.parseInt((String) restResponseChannel.getHeader(RestUtils.Headers.CONTENT_LENGTH)));
RetainingAsyncWritableChannel asyncWritableChannel = new RetainingAsyncWritableChannel((int) channel.getSize());
channel.readInto(asyncWritableChannel, null).get();
assertEquals("Container does not match", Collections.singletonList(expectedContainer), AccountCollectionSerde.containersFromInputStreamInJson(asyncWritableChannel.consumeContentAsInputStream(), existingAccount.getId()));
};
testAction.accept(createRestRequest(existingAccount.getName(), null, existingContainer.getName(), Operations.ACCOUNTS_CONTAINERS), existingContainer);
}
Aggregations