Search in sources :

Example 16 with MockRestResponseChannel

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());
    }
}
Also used : RestServiceException(com.github.ambry.rest.RestServiceException) MockRestRequest(com.github.ambry.rest.MockRestRequest) RestRequest(com.github.ambry.rest.RestRequest) JSONObject(org.json.JSONObject) AggregatedAccountStorageStats(com.github.ambry.server.storagestats.AggregatedAccountStorageStats) AggregatedPartitionClassStorageStats(com.github.ambry.server.storagestats.AggregatedPartitionClassStorageStats) MockRestResponseChannel(com.github.ambry.rest.MockRestResponseChannel) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test) RestUtilsTest(com.github.ambry.rest.RestUtilsTest) StorageStatsUtilTest(com.github.ambry.server.StorageStatsUtilTest)

Example 17 with MockRestResponseChannel

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));
}
Also used : RouterException(com.github.ambry.router.RouterException) MockRestRequest(com.github.ambry.rest.MockRestRequest) RestRequest(com.github.ambry.rest.RestRequest) JSONObject(org.json.JSONObject) MockRestResponseChannel(com.github.ambry.rest.MockRestResponseChannel) BlobId(com.github.ambry.commons.BlobId) Test(org.junit.Test) RestUtilsTest(com.github.ambry.rest.RestUtilsTest) StorageStatsUtilTest(com.github.ambry.server.StorageStatsUtilTest)

Example 18 with MockRestResponseChannel

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());
    }
}
Also used : RestServiceException(com.github.ambry.rest.RestServiceException) Account(com.github.ambry.account.Account) MockRestRequest(com.github.ambry.rest.MockRestRequest) RestRequest(com.github.ambry.rest.RestRequest) JSONObject(org.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) MockRestResponseChannel(com.github.ambry.rest.MockRestResponseChannel) HashSet(java.util.HashSet) Test(org.junit.Test) RestUtilsTest(com.github.ambry.rest.RestUtilsTest) StorageStatsUtilTest(com.github.ambry.server.StorageStatsUtilTest)

Example 19 with MockRestResponseChannel

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;
}
Also used : RestServiceException(com.github.ambry.rest.RestServiceException) MockRestRequest(com.github.ambry.rest.MockRestRequest) RestRequest(com.github.ambry.rest.RestRequest) JSONObject(org.json.JSONObject) MockRestResponseChannel(com.github.ambry.rest.MockRestResponseChannel) ByteBuffer(java.nio.ByteBuffer) LinkedList(java.util.LinkedList)

Example 20 with MockRestResponseChannel

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);
}
Also used : MockRestRequest(com.github.ambry.rest.MockRestRequest) FutureResult(com.github.ambry.router.FutureResult) ThrowingConsumer(com.github.ambry.utils.ThrowingConsumer) AccountCollectionSerde(com.github.ambry.account.AccountCollectionSerde) RequestPath(com.github.ambry.rest.RequestPath) HashSet(java.util.HashSet) JSONObject(org.json.JSONObject) TestUtils(com.github.ambry.utils.TestUtils) RetainingAsyncWritableChannel(com.github.ambry.commons.RetainingAsyncWritableChannel) Container(com.github.ambry.account.Container) ReadableStreamChannel(com.github.ambry.router.ReadableStreamChannel) MetricRegistry(com.codahale.metrics.MetricRegistry) RestMethod(com.github.ambry.rest.RestMethod) Collection(java.util.Collection) RestResponseChannel(com.github.ambry.rest.RestResponseChannel) RestServiceErrorCode(com.github.ambry.rest.RestServiceErrorCode) Test(org.junit.Test) ThrowingBiConsumer(com.github.ambry.utils.ThrowingBiConsumer) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) RestServiceException(com.github.ambry.rest.RestServiceException) MockRestResponseChannel(com.github.ambry.rest.MockRestResponseChannel) Account(com.github.ambry.account.Account) RestUtils(com.github.ambry.rest.RestUtils) Assert(org.junit.Assert) RestRequest(com.github.ambry.rest.RestRequest) Collections(java.util.Collections) InMemAccountService(com.github.ambry.account.InMemAccountService) Account(com.github.ambry.account.Account) Container(com.github.ambry.account.Container) MockRestRequest(com.github.ambry.rest.MockRestRequest) RestRequest(com.github.ambry.rest.RestRequest) ReadableStreamChannel(com.github.ambry.router.ReadableStreamChannel) RetainingAsyncWritableChannel(com.github.ambry.commons.RetainingAsyncWritableChannel) RestResponseChannel(com.github.ambry.rest.RestResponseChannel) MockRestResponseChannel(com.github.ambry.rest.MockRestResponseChannel) MockRestResponseChannel(com.github.ambry.rest.MockRestResponseChannel) Test(org.junit.Test)

Aggregations

MockRestResponseChannel (com.github.ambry.rest.MockRestResponseChannel)72 RestRequest (com.github.ambry.rest.RestRequest)57 MockRestRequest (com.github.ambry.rest.MockRestRequest)51 JSONObject (org.json.JSONObject)39 RestServiceException (com.github.ambry.rest.RestServiceException)36 Test (org.junit.Test)34 RestResponseChannel (com.github.ambry.rest.RestResponseChannel)27 RestMethod (com.github.ambry.rest.RestMethod)19 Account (com.github.ambry.account.Account)18 FutureResult (com.github.ambry.router.FutureResult)17 ReadableStreamChannel (com.github.ambry.router.ReadableStreamChannel)17 ExecutionException (java.util.concurrent.ExecutionException)17 StorageStatsUtilTest (com.github.ambry.server.StorageStatsUtilTest)16 RestUtils (com.github.ambry.rest.RestUtils)15 ByteBuffer (java.nio.ByteBuffer)15 MetricRegistry (com.codahale.metrics.MetricRegistry)14 RestServiceErrorCode (com.github.ambry.rest.RestServiceErrorCode)14 RestUtilsTest (com.github.ambry.rest.RestUtilsTest)14 TestUtils (com.github.ambry.utils.TestUtils)14 TimeUnit (java.util.concurrent.TimeUnit)14