index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/waiters/WaitersSyncFunctionalTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.waiters; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.core.waiters.WaiterOverrideConfiguration; import software.amazon.awssdk.core.waiters.WaiterResponse; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.services.restjsonwithwaiters.RestJsonWithWaitersClient; import software.amazon.awssdk.services.restjsonwithwaiters.model.AllTypesRequest; import software.amazon.awssdk.services.restjsonwithwaiters.model.AllTypesResponse; import software.amazon.awssdk.services.restjsonwithwaiters.model.EmptyModeledException; import software.amazon.awssdk.services.restjsonwithwaiters.waiters.RestJsonWithWaitersWaiter; import software.amazon.awssdk.utils.builder.SdkBuilder; public class WaitersSyncFunctionalTest { private RestJsonWithWaitersClient client; private RestJsonWithWaitersWaiter waiter; @BeforeEach public void setup() { client = mock(RestJsonWithWaitersClient.class); waiter = RestJsonWithWaitersWaiter.builder() .client(client) .overrideConfiguration(WaiterOverrideConfiguration.builder() .maxAttempts(3) .backoffStrategy(BackoffStrategy.none()) .build()) .build(); } @AfterEach public void cleanup() { client.close(); waiter.close(); } @Test public void allTypeOperation_withSyncWaiter_shouldReturnResponse() { AllTypesResponse response = (AllTypesResponse) AllTypesResponse.builder() .sdkHttpResponse(SdkHttpResponse.builder() .statusCode(200) .build()) .build(); when(client.allTypes(any(AllTypesRequest.class))).thenReturn(response); WaiterResponse<AllTypesResponse> waiterResponse = waiter.waitUntilAllTypesSuccess(AllTypesRequest.builder().build()); assertThat(waiterResponse.attemptsExecuted()).isEqualTo(1); assertThat(waiterResponse.matched().response()).hasValueSatisfying(r -> assertThat(r).isEqualTo(response)); } @Test public void allTypeOperationFailed_withSyncWaiter_shouldThrowException() { when(client.allTypes(any(AllTypesRequest.class))).thenThrow(SdkServiceException.builder().statusCode(200).build()); WaiterResponse<AllTypesResponse> waiterResponse = waiter.waitUntilAllTypesSuccess(AllTypesRequest.builder().build()); assertThat(waiterResponse.attemptsExecuted()).isEqualTo(1); assertThat(waiterResponse.matched().exception()).hasValueSatisfying(r -> assertThat(r).isInstanceOf(SdkServiceException.class)); } @Test public void allTypeOperationRetry_withSyncWaiter_shouldReturnResponseAfterException() { AllTypesResponse response = (AllTypesResponse) AllTypesResponse.builder() .sdkHttpResponse(SdkHttpResponse.builder() .statusCode(200) .build()) .build(); when(client.allTypes(any(AllTypesRequest.class))).thenThrow(SdkServiceException.builder().statusCode(404).build()) .thenReturn(response); WaiterResponse<AllTypesResponse> waiterResponse = waiter.waitUntilAllTypesSuccess(AllTypesRequest.builder().build()); assertThat(waiterResponse.attemptsExecuted()).isEqualTo(2); assertThat(waiterResponse.matched().response()).hasValueSatisfying(r -> assertThat(r).isEqualTo(response)); } @Test public void allTypeOperationRetryMoreThanMaxAttempts_withSyncWaiter_shouldThrowException() { SdkServiceException exception = SdkServiceException.builder().statusCode(404).build(); AllTypesResponse response = (AllTypesResponse) AllTypesResponse.builder() .sdkHttpResponse(SdkHttpResponse.builder() .statusCode(200) .build()) .build(); when(client.allTypes(any(AllTypesRequest.class))).thenThrow(exception) .thenThrow(exception) .thenThrow(exception) .thenReturn(response); assertThatThrownBy(() -> waiter.waitUntilAllTypesSuccess(AllTypesRequest.builder().build())) .isInstanceOf(SdkClientException.class).hasMessageContaining("exceeded the max retry attempts"); } @Test public void requestOverrideConfig_shouldTakePrecedence() { AllTypesResponse response = (AllTypesResponse) AllTypesResponse.builder() .sdkHttpResponse(SdkHttpResponse.builder() .statusCode(200) .build()) .build(); when(client.allTypes(any(AllTypesRequest.class))).thenThrow(SdkServiceException.builder().statusCode(404).build()) .thenReturn(response); assertThatThrownBy(() -> waiter.waitUntilAllTypesSuccess(b -> b.build(), o -> o.maxAttempts(1))) .isInstanceOf(SdkClientException.class).hasMessageContaining("exceeded the max retry attempts"); } @Test public void unexpectedException_shouldNotRetry() { when(client.allTypes(any(AllTypesRequest.class))).thenThrow(new RuntimeException("blah")); assertThatThrownBy(() -> waiter.waitUntilAllTypesSuccess(b -> b.build())) .hasMessageContaining("An exception was thrown and did not match any waiter acceptors") .isInstanceOf(SdkClientException.class); } @Test public void failureException_shouldThrowException() { when(client.allTypes(any(AllTypesRequest.class))).thenThrow(EmptyModeledException.builder() .awsErrorDetails(AwsErrorDetails.builder() .errorCode("EmptyModeledException") .build()) .build()); assertThatThrownBy(() -> waiter.waitUntilAllTypesSuccess(SdkBuilder::build)) .hasMessageContaining("transitioned the waiter to failure state") .isInstanceOf(SdkClientException.class); } @Test public void unexpectedResponse_shouldRetry() { AllTypesResponse response1 = (AllTypesResponse) AllTypesResponse.builder() .sdkHttpResponse(SdkHttpResponse.builder() .statusCode(202) .build()) .build(); AllTypesResponse response2 = (AllTypesResponse) AllTypesResponse.builder() .sdkHttpResponse(SdkHttpResponse.builder() .statusCode(200) .build()) .build(); when(client.allTypes(any(AllTypesRequest.class))).thenReturn(response1, response2); WaiterResponse<AllTypesResponse> waiterResponse = waiter.waitUntilAllTypesSuccess(AllTypesRequest.builder().build()); assertThat(waiterResponse.attemptsExecuted()).isEqualTo(2); assertThat(waiterResponse.matched().response()).hasValueSatisfying(r -> assertThat(r).isEqualTo(response2)); } @Test public void failureResponse_shouldThrowException() { AllTypesResponse response = (AllTypesResponse) AllTypesResponse.builder() .sdkHttpResponse(SdkHttpResponse.builder() .statusCode(500) .build()) .build(); when(client.allTypes(any(AllTypesRequest.class))).thenReturn(response); assertThatThrownBy(() -> waiter.waitUntilAllTypesSuccess(SdkBuilder::build)) .hasMessageContaining("A waiter acceptor was matched and transitioned the waiter to failure state") .isInstanceOf(SdkClientException.class); } @Test public void closeWaiterCreatedWithClient_clientDoesNotClose() { waiter.close(); verify(client, never()).close(); } }
2,900
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/waiters/WaitersAsyncFunctionalTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.waiters; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledExecutorService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.core.waiters.WaiterOverrideConfiguration; import software.amazon.awssdk.core.waiters.WaiterResponse; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.services.restjsonwithwaiters.RestJsonWithWaitersAsyncClient; import software.amazon.awssdk.services.restjsonwithwaiters.model.AllTypesRequest; import software.amazon.awssdk.services.restjsonwithwaiters.model.AllTypesResponse; import software.amazon.awssdk.services.restjsonwithwaiters.model.EmptyModeledException; import software.amazon.awssdk.services.restjsonwithwaiters.waiters.RestJsonWithWaitersAsyncWaiter; import software.amazon.awssdk.utils.CompletableFutureUtils; import software.amazon.awssdk.utils.builder.SdkBuilder; public class WaitersAsyncFunctionalTest { public RestJsonWithWaitersAsyncClient asyncClient; public RestJsonWithWaitersAsyncWaiter asyncWaiter; @BeforeEach public void setup() { asyncClient = mock(RestJsonWithWaitersAsyncClient.class); asyncWaiter = RestJsonWithWaitersAsyncWaiter.builder() .client(asyncClient) .overrideConfiguration(WaiterOverrideConfiguration.builder() .maxAttempts(3) .backoffStrategy(BackoffStrategy.none()) .build()) .build(); } @AfterEach public void cleanup() { asyncClient.close(); asyncWaiter.close(); } @Test public void allTypeOperation_withAsyncWaiter_shouldReturnResponse() throws Exception { AllTypesResponse response = (AllTypesResponse) AllTypesResponse.builder() .sdkHttpResponse(SdkHttpResponse.builder() .statusCode(200) .build()) .build(); CompletableFuture<AllTypesResponse> serviceFuture = new CompletableFuture<>(); when(asyncClient.allTypes(any(AllTypesRequest.class))).thenReturn(serviceFuture); CompletableFuture<WaiterResponse<AllTypesResponse>> responseFuture = asyncWaiter.waitUntilAllTypesSuccess(AllTypesRequest.builder() .integerMember(1) .build()); serviceFuture.complete(response); assertThat(responseFuture.get().attemptsExecuted()).isEqualTo(1); assertThat(responseFuture.get().matched().response()).hasValueSatisfying(r -> assertThat(r).isEqualTo(response)); } @Test public void allTypeOperationFailed_withAsyncWaiter_shouldReturnException() throws Exception { CompletableFuture<AllTypesResponse> serviceFuture = new CompletableFuture<>(); when(asyncClient.allTypes(any(AllTypesRequest.class))).thenReturn(serviceFuture); CompletableFuture<WaiterResponse<AllTypesResponse>> responseFuture = asyncWaiter.waitUntilAllTypesSuccess(AllTypesRequest.builder().build()); serviceFuture.completeExceptionally(SdkServiceException.builder().statusCode(200).build()); assertThat(responseFuture.get().attemptsExecuted()).isEqualTo(1); assertThat(responseFuture.get().matched().exception()).hasValueSatisfying(r -> assertThat(r).isInstanceOf(SdkServiceException.class)); } @Test public void allTypeOperationRetry_withAsyncWaiter_shouldReturnResponseAfterException() throws Exception { AllTypesResponse response2 = (AllTypesResponse) AllTypesResponse.builder() .sdkHttpResponse(SdkHttpResponse.builder() .statusCode(200) .build()) .build(); CompletableFuture<AllTypesResponse> serviceFuture1 = CompletableFutureUtils.failedFuture(SdkServiceException.builder().statusCode(404).build()); CompletableFuture<AllTypesResponse> serviceFuture2 = new CompletableFuture<>(); when(asyncClient.allTypes(any(AllTypesRequest.class))).thenReturn(serviceFuture1, serviceFuture2); CompletableFuture<WaiterResponse<AllTypesResponse>> responseFuture = asyncWaiter.waitUntilAllTypesSuccess(AllTypesRequest.builder().build()); serviceFuture2.complete(response2); assertThat(responseFuture.get().attemptsExecuted()).isEqualTo(2); assertThat(responseFuture.get().matched().response()).hasValueSatisfying(r -> assertThat(r).isEqualTo(response2)); } @Test public void requestOverrideConfig_shouldTakePrecedence() { AllTypesResponse response = (AllTypesResponse) AllTypesResponse.builder() .sdkHttpResponse(SdkHttpResponse.builder() .statusCode(200) .build()) .build(); CompletableFuture<AllTypesResponse> serviceFuture1 = CompletableFutureUtils.failedFuture(SdkServiceException.builder().statusCode(404).build()); CompletableFuture<AllTypesResponse> serviceFuture2 = CompletableFuture.completedFuture(response); when(asyncClient.allTypes(any(AllTypesRequest.class))).thenReturn(serviceFuture1, serviceFuture2); assertThatThrownBy(() -> asyncWaiter.waitUntilAllTypesSuccess(b -> b.build(), o -> o.maxAttempts(1)).join()) .hasMessageContaining("exceeded the max retry attempts").hasCauseInstanceOf(SdkClientException.class); } @Test public void unexpectedException_shouldNotRetry() { CompletableFuture<AllTypesResponse> failedFuture = CompletableFutureUtils.failedFuture(new RuntimeException("")); when(asyncClient.allTypes(any(AllTypesRequest.class))).thenReturn(failedFuture); assertThatThrownBy(() -> asyncWaiter.waitUntilAllTypesSuccess(b -> b.build()).join()) .hasMessageContaining("An exception was thrown and did not match any waiter acceptors") .hasCauseInstanceOf(SdkClientException.class); } @Test public void unexpectedResponse_shouldRetry() { AllTypesResponse response = (AllTypesResponse) AllTypesResponse.builder() .sdkHttpResponse(SdkHttpResponse.builder() .statusCode(200) .build()).build(); CompletableFuture<AllTypesResponse> future1 = CompletableFuture.completedFuture((AllTypesResponse) AllTypesResponse.builder() .sdkHttpResponse(SdkHttpResponse.builder() .statusCode(202) .build()).build()); CompletableFuture<AllTypesResponse> future2 = CompletableFuture.completedFuture(response); when(asyncClient.allTypes(any(AllTypesRequest.class))).thenReturn(future1, future2); WaiterResponse<AllTypesResponse> waiterResponse = asyncWaiter.waitUntilAllTypesSuccess(b -> b.build()).join(); assertThat(waiterResponse.attemptsExecuted()).isEqualTo(2); assertThat(waiterResponse.matched().response()).hasValueSatisfying(r -> assertThat(r).isEqualTo(response)); } @Test public void failureResponse_shouldThrowException() { CompletableFuture<AllTypesResponse> future = CompletableFuture.completedFuture((AllTypesResponse) AllTypesResponse.builder() .sdkHttpResponse(SdkHttpResponse.builder() .statusCode(500) .build()) .build()); when(asyncClient.allTypes(any(AllTypesRequest.class))).thenReturn(future); assertThatThrownBy(() -> asyncWaiter.waitUntilAllTypesSuccess(SdkBuilder::build).join()) .hasMessageContaining("transitioned the waiter to failure state") .hasCauseInstanceOf(SdkClientException.class); } @Test public void failureException_shouldThrowException() { when(asyncClient.allTypes(any(AllTypesRequest.class))).thenReturn(CompletableFutureUtils.failedFuture(EmptyModeledException.builder() .awsErrorDetails(AwsErrorDetails.builder() .errorCode("EmptyModeledException") .build()) .build())); assertThatThrownBy(() -> asyncWaiter.waitUntilAllTypesSuccess(SdkBuilder::build).join()) .hasMessageContaining("transitioned the waiter to failure state") .hasCauseInstanceOf(SdkClientException.class); } @Test void errorShouldNotBeWrapped() { when(asyncClient.allTypes(any(AllTypesRequest.class))).thenReturn(CompletableFutureUtils.failedFuture(new OutOfMemoryError())); assertThatThrownBy(() -> asyncWaiter.waitUntilAllTypesSuccess(SdkBuilder::build).join()) .hasCauseInstanceOf(Error.class); } @Test public void closeWaiterCreatedWithClient_clientDoesNotClose() { asyncWaiter.close(); verify(asyncClient, never()).close(); } @Test public void closeWaiterCreatedWithExecutorService_executorServiceDoesNotClose() { ScheduledExecutorService executorService = mock(ScheduledExecutorService.class); RestJsonWithWaitersAsyncWaiter newWaiter = RestJsonWithWaitersAsyncWaiter.builder() .client(asyncClient) .scheduledExecutorService(executorService) .overrideConfiguration(WaiterOverrideConfiguration.builder() .maxAttempts(3) .backoffStrategy(BackoffStrategy.none()) .build()) .build(); newWaiter.close(); verify(executorService, never()).shutdown(); } }
2,901
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/waiters/WaitersRuntimeResponseStatusAcceptorTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.waiters; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.waiters.WaiterState; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.services.restjsonwithwaiters.waiters.internal.WaitersRuntime.ResponseStatusAcceptor; /** * Verify the accuracy of {@link ResponseStatusAcceptor}. */ public class WaitersRuntimeResponseStatusAcceptorTest { @Test public void usesStatus() { assertThat(new ResponseStatusAcceptor(200, WaiterState.RETRY).waiterState()).isEqualTo(WaiterState.RETRY); assertThat(new ResponseStatusAcceptor(200, WaiterState.FAILURE).waiterState()).isEqualTo(WaiterState.FAILURE); assertThat(new ResponseStatusAcceptor(200, WaiterState.SUCCESS).waiterState()).isEqualTo(WaiterState.SUCCESS); } @Test public void checksStatusOnResponse() { SdkHttpFullResponse http200 = SdkHttpResponse.builder().statusCode(200).build(); SdkHttpFullResponse http500 = SdkHttpResponse.builder().statusCode(500).build(); assertThat(new ResponseStatusAcceptor(200, WaiterState.SUCCESS).matches(new ExampleSdkResponse(http200))).isTrue(); assertThat(new ResponseStatusAcceptor(200, WaiterState.SUCCESS).matches(new ExampleSdkResponse(http500))).isFalse(); assertThat(new ResponseStatusAcceptor(500, WaiterState.SUCCESS).matches(new ExampleSdkResponse(http500))).isTrue(); assertThat(new ResponseStatusAcceptor(500, WaiterState.SUCCESS).matches(new ExampleSdkResponse(http200))).isFalse(); } @Test public void checksStatusOnException() { assertThat(new ResponseStatusAcceptor(200, WaiterState.SUCCESS).matches((Throwable) null)).isFalse(); assertThat(new ResponseStatusAcceptor(200, WaiterState.SUCCESS).matches(new Throwable())).isFalse(); assertThat(new ResponseStatusAcceptor(200, WaiterState.SUCCESS).matches(SdkException.create("", null))).isFalse(); assertThat(new ResponseStatusAcceptor(200, WaiterState.SUCCESS).matches(SdkServiceException.create("", null))).isFalse(); assertThat(new ResponseStatusAcceptor(200, WaiterState.SUCCESS).matches(SdkServiceException.builder() .message("") .statusCode(500) .build())) .isFalse(); assertThat(new ResponseStatusAcceptor(200, WaiterState.SUCCESS).matches(SdkServiceException.builder() .message("") .statusCode(200) .build())) .isTrue(); } private static class ExampleSdkResponse extends SdkResponse { protected ExampleSdkResponse(SdkHttpResponse httpResponse) { super(new Builder() { @Override public Builder sdkHttpResponse(SdkHttpResponse sdkHttpResponse) { throw new UnsupportedOperationException(); } @Override public SdkHttpResponse sdkHttpResponse() { return httpResponse; } @Override public SdkResponse build() { throw new UnsupportedOperationException(); } }); } @Override public Builder toBuilder() { throw new UnsupportedOperationException(); } @Override public List<SdkField<?>> sdkFields() { throw new UnsupportedOperationException(); } } }
2,902
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/waiters/WaitersRuntimeDefaultAcceptorsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.waiters; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.waiters.WaiterState; import software.amazon.awssdk.services.restjsonwithwaiters.waiters.internal.WaitersRuntime; /** * Verify the accuracy of {@link WaitersRuntime#DEFAULT_ACCEPTORS}. */ public class WaitersRuntimeDefaultAcceptorsTest { @Test public void defaultAcceptorsRetryOnUnrecognizedResponse() { assertThat(WaitersRuntime.DEFAULT_ACCEPTORS.stream().filter(acceptor -> acceptor.matches(new Object())).findFirst()) .hasValueSatisfying(v -> assertThat(v.waiterState()).isEqualTo(WaiterState.RETRY)); } }
2,903
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/waiters/WaiterResourceTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.waiters; import java.util.concurrent.ScheduledExecutorService; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.services.restjsonwithwaiters.RestJsonWithWaitersAsyncClient; import software.amazon.awssdk.services.restjsonwithwaiters.RestJsonWithWaitersClient; import software.amazon.awssdk.services.restjsonwithwaiters.waiters.RestJsonWithWaitersAsyncWaiter; import software.amazon.awssdk.services.restjsonwithwaiters.waiters.RestJsonWithWaitersWaiter; @RunWith(MockitoJUnitRunner.class) public class WaiterResourceTest { @Mock private RestJsonWithWaitersClient client; @Mock private RestJsonWithWaitersAsyncClient asyncClient; @Mock private ScheduledExecutorService executorService; @Test public void closeSyncWaiter_customizedClientProvided_shouldNotCloseClient() { RestJsonWithWaitersWaiter waiter = RestJsonWithWaitersWaiter.builder() .client(client) .build(); waiter.close(); Mockito.verify(client, Mockito.never()).close(); } @Test public void closeAsyncWaiter_customizedClientAndExecutorServiceProvided_shouldNotClose() { RestJsonWithWaitersAsyncWaiter waiter = RestJsonWithWaitersAsyncWaiter.builder() .client(asyncClient) .scheduledExecutorService(executorService) .build(); waiter.close(); Mockito.verify(client, Mockito.never()).close(); Mockito.verify(executorService, Mockito.never()).shutdown(); } }
2,904
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/waiters/WaitersRuntimeValueTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.waiters; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.core.traits.LocationTrait; import software.amazon.awssdk.services.restjsonwithwaiters.waiters.internal.WaitersRuntime.Value; import software.amazon.awssdk.utils.Pair; public class WaitersRuntimeValueTest { @Test public void valueReturnsConstructorInput() { assertThat(new Value(null).value()).isEqualTo(null); assertThat(new Value(sdkPojo()).value()).isEqualTo(sdkPojo()); assertThat(new Value(5).value()).isEqualTo(5); assertThat(new Value("").value()).isEqualTo(""); assertThat(new Value(true).value()).isEqualTo(true); assertThat(new Value(emptyList()).value()).isEqualTo(emptyList()); } @Test public void valuesReturnsListForm() { assertThat(new Value(null).values()).isEqualTo(emptyList()); assertThat(new Value(5).values()).isEqualTo(singletonList(5)); assertThat(new Value("").values()).isEqualTo(singletonList("")); assertThat(new Value(true).values()).isEqualTo(singletonList(true)); assertThat(new Value(singletonList("a")).values()).isEqualTo(singletonList("a")); assertThat(new Value(sdkPojo()).values()).isEqualTo(singletonList(sdkPojo())); } @Test public void andBehavesWithBooleans() { assertThat(booleanTrue().and(booleanTrue())).isEqualTo(booleanTrue()); assertThat(booleanFalse().and(booleanTrue())).isEqualTo(booleanFalse()); assertThat(booleanTrue().and(booleanFalse())).isEqualTo(booleanFalse()); assertThat(booleanFalse().and(booleanFalse())).isEqualTo(booleanFalse()); } @Test public void andBehavesWithPojos() { Value truePojo1 = sdkPojoValue(Pair.of("foo", "bar")); Value truePojo2 = sdkPojoValue(Pair.of("foo", "bar")); Value falsePojo1 = sdkPojoValue(); Value falsePojo2 = sdkPojoValue(); assertThat(truePojo1.and(truePojo2)).isSameAs(truePojo2); assertThat(falsePojo1.and(truePojo1)).isSameAs(falsePojo1); assertThat(truePojo1.and(falsePojo1)).isSameAs(falsePojo1); assertThat(falsePojo1.and(falsePojo2)).isSameAs(falsePojo1); } @Test public void andBehavesWithLists() { Value trueList1 = new Value(singletonList("foo")); Value trueList2 = new Value(singletonList("foo")); Value falseList1 = new Value(emptyList()); Value falseList2 = new Value(emptyList()); assertThat(trueList1.and(trueList2)).isSameAs(trueList2); assertThat(falseList1.and(trueList1)).isSameAs(falseList1); assertThat(trueList1.and(falseList1)).isSameAs(falseList1); assertThat(falseList1.and(falseList2)).isSameAs(falseList1); } @Test public void andBehavesWithStrings() { Value trueList1 = new Value("foo"); Value trueList2 = new Value("foo"); Value falseList1 = new Value(""); Value falseList2 = new Value(""); assertThat(trueList1.and(trueList2)).isSameAs(trueList2); assertThat(falseList1.and(trueList1)).isSameAs(falseList1); assertThat(trueList1.and(falseList1)).isSameAs(falseList1); assertThat(falseList1.and(falseList2)).isSameAs(falseList1); } @Test public void orBehavesWithBooleans() { assertThat(booleanTrue().or(booleanTrue())).isEqualTo(booleanTrue()); assertThat(booleanFalse().or(booleanTrue())).isEqualTo(booleanTrue()); assertThat(booleanTrue().or(booleanFalse())).isEqualTo(booleanTrue()); assertThat(booleanFalse().or(booleanFalse())).isEqualTo(new Value(null)); } @Test public void orBehavesWithPojos() { Value truePojo1 = sdkPojoValue(Pair.of("foo", "bar")); Value truePojo2 = sdkPojoValue(Pair.of("foo", "bar")); Value falsePojo1 = sdkPojoValue(); Value falsePojo2 = sdkPojoValue(); assertThat(truePojo1.or(truePojo2)).isSameAs(truePojo1); assertThat(falsePojo1.or(truePojo1)).isSameAs(truePojo1); assertThat(truePojo1.or(falsePojo1)).isSameAs(truePojo1); assertThat(falsePojo1.or(falsePojo2)).isEqualTo(new Value(null)); } @Test public void orBehavesWithLists() { Value trueList1 = new Value(singletonList("foo")); Value trueList2 = new Value(singletonList("foo")); Value falseList1 = new Value(emptyList()); Value falseList2 = new Value(emptyList()); assertThat(trueList1.or(trueList2)).isSameAs(trueList1); assertThat(falseList1.or(trueList1)).isSameAs(trueList1); assertThat(trueList1.or(falseList1)).isSameAs(trueList1); assertThat(falseList1.or(falseList2)).isEqualTo(new Value(null)); } @Test public void orBehavesWithStrings() { Value trueList1 = new Value("foo"); Value trueList2 = new Value("foo"); Value falseList1 = new Value(""); Value falseList2 = new Value(""); assertThat(trueList1.or(trueList2)).isSameAs(trueList1); assertThat(falseList1.or(trueList1)).isSameAs(trueList1); assertThat(trueList1.or(falseList1)).isSameAs(trueList1); assertThat(falseList1.or(falseList2)).isEqualTo(new Value(null)); } @Test public void notBehaves() { assertThat(booleanTrue().not()).isEqualTo(booleanFalse()); assertThat(booleanFalse().not()).isEqualTo(booleanTrue()); assertThat(new Value("").not()).isEqualTo(booleanTrue()); } @Test public void constantBehaves() { assertThat(new Value(null).constant(new Value(5))).isEqualTo(new Value(5)); assertThat(new Value(null).constant(5)).isEqualTo(new Value(5)); } @Test public void wildcardBehavesWithNull() { assertThat(new Value(null).wildcard()).isEqualTo(new Value(null)); } @Test public void wildcardBehavesWithPojos() { assertThat(sdkPojoValue(Pair.of("foo", "bar"), Pair.of("foo2", singletonList("bar")), Pair.of("foo3", sdkPojo(Pair.of("x", "y")))) .wildcard()) .isEqualTo(new Value(asList("bar", singletonList("bar"), sdkPojo(Pair.of("x", "y"))))); } @Test public void flattenBehavesWithNull() { assertThat(new Value(null).flatten()).isEqualTo(new Value(null)); } @Test public void flattenBehavesWithLists() { assertThat(new Value(asList("bar", singletonList("bar"), sdkPojo(Pair.of("x", "y")))) .flatten()) .isEqualTo(new Value(asList("bar", "bar", sdkPojo(Pair.of("x", "y"))))); } @Test public void fieldBehaves() { assertThat(new Value(null).field("foo")).isEqualTo(new Value(null)); assertThat(sdkPojoValue(Pair.of("foo", "bar")).field("foo")).isEqualTo(new Value("bar")); } @Test public void filterBehaves() { assertThat(new Value(null).filter(x -> new Value(true))).isEqualTo(new Value(null)); Value listValue = new Value(asList("foo", "bar")); assertThat(listValue.filter(x -> new Value(Objects.equals(x.value(), "foo")))).isEqualTo(new Value(asList("foo"))); assertThat(listValue.filter(x -> new Value(false))).isEqualTo(new Value(emptyList())); assertThat(listValue.filter(x -> new Value(true))).isEqualTo(listValue); } @Test public void lengthBehaves() { assertThat(new Value(null).length()).isEqualTo(new Value(null)); assertThat(new Value("a").length()).isEqualTo(new Value(1)); assertThat(sdkPojoValue(Pair.of("a", "b")).length()).isEqualTo(new Value(1)); assertThat(new Value(singletonList("a")).length()).isEqualTo(new Value(1)); } @Test public void containsBehaves() { assertThat(new Value(null).length()).isEqualTo(new Value(null)); assertThat(new Value("abcde").contains(new Value("bcd"))).isEqualTo(new Value(true)); assertThat(new Value("abcde").contains(new Value("f"))).isEqualTo(new Value(false)); assertThat(new Value(asList("a", "b")).contains(new Value("a"))).isEqualTo(new Value(true)); assertThat(new Value(asList("a", "b")).contains(new Value("c"))).isEqualTo(new Value(false)); } @Test public void compareIntegerBehaves() { assertThat(new Value(1).compare(">", new Value(2))).isEqualTo(new Value(false)); assertThat(new Value(1).compare(">=", new Value(2))).isEqualTo(new Value(false)); assertThat(new Value(1).compare("<=", new Value(2))).isEqualTo(new Value(true)); assertThat(new Value(1).compare("<", new Value(2))).isEqualTo(new Value(true)); assertThat(new Value(1).compare("==", new Value(2))).isEqualTo(new Value(false)); assertThat(new Value(1).compare("!=", new Value(2))).isEqualTo(new Value(true)); assertThat(new Value(1).compare(">", new Value(1))).isEqualTo(new Value(false)); assertThat(new Value(1).compare(">=", new Value(1))).isEqualTo(new Value(true)); assertThat(new Value(1).compare("<=", new Value(1))).isEqualTo(new Value(true)); assertThat(new Value(1).compare("<", new Value(1))).isEqualTo(new Value(false)); assertThat(new Value(1).compare("==", new Value(1))).isEqualTo(new Value(true)); assertThat(new Value(1).compare("!=", new Value(1))).isEqualTo(new Value(false)); } @Test public void multiSelectListBehaves() { assertThat(new Value(5).multiSelectList(x -> new Value(1), x -> new Value(2))) .isEqualTo(new Value(asList(1, 2))); } private Value booleanTrue() { return new Value(true); } private Value booleanFalse() { return new Value(false); } @SafeVarargs private final Value sdkPojoValue(Pair<String, Object>... entry) { return new Value(sdkPojo(entry)); } @SafeVarargs private final SdkPojo sdkPojo(Pair<String, Object>... entry) { Map<String, Object> result = new HashMap<>(); Stream.of(entry).forEach(e -> result.put(e.left(), e.right())); return new MockSdkPojo(result); } private static class MockSdkPojo implements SdkPojo { private final Map<String, Object> map; private MockSdkPojo(Map<String, Object> map) { this.map = map; } @Override public List<SdkField<?>> sdkFields() { return map.entrySet().stream().map(this::sdkField).collect(Collectors.toList()); } private <T> SdkField<T> sdkField(Map.Entry<String, T> e) { @SuppressWarnings("unchecked") Class<T> valueClass = (Class<T>) e.getValue().getClass(); return SdkField.builder(MarshallingType.newType(valueClass)) .memberName(e.getKey()) .getter(x -> e.getValue()) .traits(LocationTrait.builder().build()) .build(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MockSdkPojo that = (MockSdkPojo) o; return Objects.equals(map, that.map); } @Override public int hashCode() { return Objects.hash(map); } } }
2,905
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/defaultendpointprovider/DefaultEndpointProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.defaultendpointprovider; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.defaultendpointprovider.endpoints.DefaultEndpointProviderEndpointProvider; public class DefaultEndpointProviderTest { private static final DefaultEndpointProviderEndpointProvider DEFAULT_ENDPOINT_PROVIDER = DefaultEndpointProviderEndpointProvider.defaultProvider(); @Test public void unknownRegion_resolvesToAwsPartition() { assertThat(resolveEndpoint("unknown-region", null)) .isEqualTo("https://default-endpoint-provider.unknown-region.amazonaws.com"); } @Test public void awsRegion_resolvesToAwsPartition() { assertThat(resolveEndpoint("us-west-2", null)) .isEqualTo("https://default-endpoint-provider.us-west-2.amazonaws.com"); } @Test public void cnRegion_resolvesToCnPartition() { assertThat(resolveEndpoint("cn-north-1", null)) .isEqualTo("https://default-endpoint-provider.cn-north-1.amazonaws.com.cn"); } @Test public void endpointOverride_resolvesToEndpointOverride() { assertThat(resolveEndpoint("unknown-region", "http://localhost:1234")) .isEqualTo("http://localhost:1234"); assertThat(resolveEndpoint("us-west-2", "http://localhost:1234")) .isEqualTo("http://localhost:1234"); } private String resolveEndpoint(String region, String endpointOverride) { return DEFAULT_ENDPOINT_PROVIDER.resolveEndpoint(e -> e.region(Region.of(region)) .endpoint(endpointOverride)) .join() .url() .toString(); } }
2,906
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/customizeduseragent/InternalUserAgentTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.customizeduseragent; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.containing; import static com.github.tomakehurst.wiremock.client.WireMock.notMatching; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; import software.amazon.awssdk.services.protocolrestjsonwithinternalconfig.ProtocolRestJsonWithInternalConfigAsyncClient; import software.amazon.awssdk.services.protocolrestjsonwithinternalconfig.ProtocolRestJsonWithInternalConfigClient; import software.amazon.awssdk.utils.builder.SdkBuilder; public class InternalUserAgentTest { @Rule public WireMockRule wireMock = new WireMockRule(0); private ProtocolRestJsonWithInternalConfigClient client; private ProtocolRestJsonWithInternalConfigAsyncClient asyncClient; private ProtocolRestJsonClient clientWithoutInternalConfig; private ProtocolRestJsonAsyncClient asyncClientWithoutInternalConfig; @Before public void setupClient() { client = ProtocolRestJsonWithInternalConfigClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .build(); clientWithoutInternalConfig = ProtocolRestJsonClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .build(); asyncClient = ProtocolRestJsonWithInternalConfigAsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .build(); asyncClientWithoutInternalConfig = ProtocolRestJsonAsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .build(); } @Test public void syncWithInternalUserAgent_shouldContainInternalUserAgent() { stubResponse(); client.oneOperation(SdkBuilder::build); verifyUserAgent(); } @Test public void asyncWithInternalUserAgent_shouldContainInternalUserAgent() { stubResponse(); asyncClient.oneOperation(SdkBuilder::build).join(); verifyUserAgent(); } @Test public void syncWithoutInternalUserAgent_shouldNotContainInternalUserAgent() { stubResponse(); clientWithoutInternalConfig.allTypes(SdkBuilder::build); verifyNotContainUserAgent(); } @Test public void asyncWithoutInternalUserAgent_shouldNotContainInternalUserAgent() { stubResponse(); asyncClientWithoutInternalConfig.allTypes(SdkBuilder::build).join(); verifyNotContainUserAgent(); } private void verifyUserAgent() { verify(postRequestedFor(anyUrl()).withHeader("user-agent", containing("md/foobar"))); } private void verifyNotContainUserAgent() { verify(postRequestedFor(anyUrl()).withHeader("user-agent", notMatching(".*md/foobar.*"))); } private void stubResponse() { stubFor(post(anyUrl()) .willReturn(aResponse().withStatus(200) .withBody("{}"))); } }
2,907
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/eventstreams/EventDispatchTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.eventstreams; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import java.util.function.Consumer; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.services.eventstreamrestjson.model.EventOne; import software.amazon.awssdk.services.eventstreamrestjson.model.EventStream; import software.amazon.awssdk.services.eventstreamrestjson.model.EventStreamOperationResponseHandler; import software.amazon.awssdk.services.eventstreamrestjson.model.EventTwo; /** * Tests to ensure that the generated classes that represent each event on an * event stream call the correct visitor methods; i.e. that the double * dispatching works as expected. */ @RunWith(MockitoJUnitRunner.class) public class EventDispatchTest { @Mock private EventStreamOperationResponseHandler.Visitor visitor; @Mock private Consumer<EventStream> onDefaultConsumer; @Mock private Consumer<EventOne> theEventOneConsumer; @Mock private Consumer<EventOne> legacyGeneratedEventConsumer; @Mock private Consumer<EventTwo> eventTwoConsumer; @Mock private Consumer<EventTwo> secondEventTwoConsumer; @Rule public ExpectedException expected = ExpectedException.none(); @Test public void test_acceptTheEventOne_correctVisitorMethodCalled() { EventStream eventStream = EventStream.theEventOneBuilder().build(); eventStream.accept(visitor); verify(visitor).visitTheEventOne(Mockito.eq((EventOne) eventStream)); verifyNoMoreInteractions(visitor); } @Test public void test_acceptTheEventOne_visitorBuiltWithBuilder_correctVisitorMethodCalled() { EventStreamOperationResponseHandler.Visitor visitor = visitorBuiltWithBuilder(); EventStream eventStream = EventStream.theEventOneBuilder().build(); eventStream.accept(visitor); verify(theEventOneConsumer).accept(eq((EventOne) eventStream)); verifyNoMoreConsumerInteractions(); } @Test public void test_acceptLegacyGeneratedEvent_correctVisitorMethodCalled() { EventStream eventStream = EventOne.builder().build(); eventStream.accept(visitor); // Note: notice the visit() method rather than visitLegacyGeneratedEvent() verify(visitor).visit(Mockito.eq((EventOne) eventStream)); verifyNoMoreInteractions(visitor); } @Test public void test_acceptLegacyGeneratedEvent_visitorBuiltWithBuilder_correctVisitorMethodCalled() { EventStreamOperationResponseHandler.Visitor visitor = visitorBuiltWithBuilder(); EventStream eventStream = EventOne.builder().build(); eventStream.accept(visitor); verify(legacyGeneratedEventConsumer).accept(eq((EventOne) eventStream)); verifyNoMoreConsumerInteractions(); } @Test public void test_acceptEventTwo_correctVisitorMethodCalled() { EventStream eventStream = EventStream.eventTwoBuilder().build(); eventStream.accept(visitor); verify(visitor).visitEventTwo(Mockito.eq((EventTwo) eventStream)); verifyNoMoreInteractions(visitor); } @Test public void test_acceptEvenTwo_visitorBuiltWithBuilder_correctVisitorMethodCalled() { EventStreamOperationResponseHandler.Visitor visitor = visitorBuiltWithBuilder(); EventStream eventStream = EventStream.eventTwoBuilder().build(); eventStream.accept(visitor); verify(eventTwoConsumer).accept(eq((EventTwo) eventStream)); verifyNoMoreConsumerInteractions(); } @Test public void test_acceptSecondEventTwo_correctVisitorMethodCalled() { EventStream eventStream = EventStream.secondEventTwoBuilder().build(); eventStream.accept(visitor); verify(visitor).visitSecondEventTwo(Mockito.eq((EventTwo) eventStream)); verifyNoMoreInteractions(visitor); } @Test public void test_acceptSecondEvenTwo_visitorBuiltWithBuilder_correctVisitorMethodCalled() { EventStreamOperationResponseHandler.Visitor visitor = visitorBuiltWithBuilder(); EventStream eventStream = EventStream.secondEventTwoBuilder().build(); eventStream.accept(visitor); verify(secondEventTwoConsumer).accept(eq((EventTwo) eventStream)); verifyNoMoreConsumerInteractions(); } @Test public void test_acceptOnBaseClass_UnCustomizedEvent_throwsException() { expected.expect(UnsupportedOperationException.class); EventTwo eventTwo = EventTwo.builder().build(); eventTwo.accept(visitor); } private EventStreamOperationResponseHandler.Visitor visitorBuiltWithBuilder() { return EventStreamOperationResponseHandler.Visitor.builder() .onDefault(onDefaultConsumer) .onTheEventOne(theEventOneConsumer) .onEventTwo(eventTwoConsumer) .onEventOne(legacyGeneratedEventConsumer) .onSecondEventTwo(secondEventTwoConsumer) .build(); } private void verifyNoMoreConsumerInteractions() { verifyNoMoreInteractions(onDefaultConsumer, theEventOneConsumer, eventTwoConsumer, legacyGeneratedEventConsumer, secondEventTwoConsumer); } }
2,908
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/eventstreams/EventMarshallingTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.eventstreams; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import io.reactivex.Flowable; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.junit.MockitoJUnitRunner; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.async.SdkHttpContentPublisher; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.eventstreamrestjson.EventStreamRestJsonAsyncClient; import software.amazon.awssdk.services.eventstreamrestjson.model.EventStream; import software.amazon.awssdk.services.eventstreamrestjson.model.EventStreamOperationRequest; import software.amazon.awssdk.services.eventstreamrestjson.model.EventStreamOperationResponseHandler; import software.amazon.awssdk.services.eventstreamrestjson.model.InputEventStream; import software.amazon.eventstream.Message; import software.amazon.eventstream.MessageDecoder; @RunWith(MockitoJUnitRunner.class) public class EventMarshallingTest { @Mock public SdkAsyncHttpClient mockHttpClient; private EventStreamRestJsonAsyncClient client; private List<Message> marshalledEvents; private MessageDecoder chunkDecoder; private MessageDecoder eventDecoder; @Before public void setup() { when(mockHttpClient.execute(any(AsyncExecuteRequest.class))).thenAnswer(this::mockExecute); client = EventStreamRestJsonAsyncClient.builder() .region(Region.US_WEST_2) .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .httpClient(mockHttpClient) .build(); marshalledEvents = new ArrayList<>(); chunkDecoder = new MessageDecoder(); eventDecoder = new MessageDecoder(); } @Test public void testMarshalling_setsCorrectEventType() { List<InputEventStream> inputEvents = Stream.of( InputEventStream.inputEventBuilder().build(), InputEventStream.inputEventBBuilder().build(), InputEventStream.inputEventTwoBuilder().build() ).collect(Collectors.toList()); Flowable<InputEventStream> inputStream = Flowable.fromIterable(inputEvents); client.eventStreamOperation(EventStreamOperationRequest.builder().build(), inputStream, EventStreamOperationResponseHandler.builder() .subscriber(() -> new Subscriber<EventStream>() { @Override public void onSubscribe(Subscription subscription) { } @Override public void onNext(EventStream eventStream) { } @Override public void onError(Throwable throwable) { } @Override public void onComplete() { } }) .build()).join(); List<String> expectedTypes = Stream.of( "InputEvent", "InputEventB", "InputEventTwo" ).collect(Collectors.toList());; assertThat(marshalledEvents).hasSize(inputEvents.size()); for (int i = 0; i < marshalledEvents.size(); ++i) { Message marshalledEvent = marshalledEvents.get(i); String expectedType = expectedTypes.get(i); assertThat(marshalledEvent.getHeaders().get(":event-type").getString()) .isEqualTo(expectedType); } } private CompletableFuture<Void> mockExecute(InvocationOnMock invocation) { AsyncExecuteRequest request = invocation.getArgument(0, AsyncExecuteRequest.class); SdkHttpContentPublisher content = request.requestContentPublisher(); List<ByteBuffer> chunks = Flowable.fromPublisher(content).toList().blockingGet(); for (ByteBuffer c : chunks) { chunkDecoder.feed(c); } for (Message m : chunkDecoder.getDecodedMessages()) { eventDecoder.feed(m.getPayload()); } marshalledEvents.addAll(eventDecoder.getDecodedMessages()); request.responseHandler().onHeaders(SdkHttpResponse.builder().statusCode(200).build()); request.responseHandler().onStream(Flowable.empty()); return CompletableFuture.completedFuture(null); } }
2,909
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/mixedauth/ClientBuilderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.mixedauth; import static org.assertj.core.api.Assertions.assertThatNoException; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.regions.Region; public class ClientBuilderTest { @Test public void syncClient_buildWithDefaults_validationsSucceed() { MixedauthClientBuilder builder = MixedauthClient.builder(); builder.region(Region.US_WEST_2).credentialsProvider(AnonymousCredentialsProvider.create()); assertThatNoException().isThrownBy(builder::build); } @Test public void asyncClient_buildWithDefaults_validationsSucceed() { MixedauthAsyncClientBuilder builder = MixedauthAsyncClient.builder(); builder.region(Region.US_WEST_2).credentialsProvider(AnonymousCredentialsProvider.create()); assertThatNoException().isThrownBy(builder::build); } }
2,910
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/protocolquery/MoveQueryParamsToBodyTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.protocolquery; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.reactivex.Flowable; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.ExecutableHttpRequest; import software.amazon.awssdk.http.HttpExecuteRequest; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.async.SdkHttpContentPublisher; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.utils.IoUtils; public class MoveQueryParamsToBodyTest { private static final String CUSTOM_PARAM_NAME = "CustomParamName"; private static final String CUSTOM_PARAM_VALUE = "CustomParamValue"; private static final AwsCredentialsProvider CREDENTIALS = StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")); private SdkHttpClient syncMockHttpClient; private SdkAsyncHttpClient asyncMockHttpClient; private ProtocolQueryClient syncClient; private ProtocolQueryAsyncClient asyncClient; @BeforeEach public void setup() throws IOException { syncMockHttpClient = mock(SdkHttpClient.class); ExecutableHttpRequest mockRequest = mock(ExecutableHttpRequest.class); when(mockRequest.call()).thenThrow(new IOException("IO error!")); when(syncMockHttpClient.prepareRequest(any())).thenReturn(mockRequest); asyncMockHttpClient = mock(SdkAsyncHttpClient.class); } @AfterEach public void teardown() { if (syncClient != null) { syncClient.close(); } syncClient = null; if (asyncClient != null) { asyncClient.close(); } asyncClient = null; } private void verifyParametersMovedToBody_syncClient(ArgumentCaptor<HttpExecuteRequest> requestCaptor) throws IOException { ContentStreamProvider requestContent = requestCaptor.getValue().contentStreamProvider().get(); String contentString = IoUtils.toUtf8String(requestContent.newStream()); assertThat(contentString).contains(CUSTOM_PARAM_NAME + "=" + CUSTOM_PARAM_VALUE); } private void verifyParametersMovedToBody_asyncClient(ArgumentCaptor<AsyncExecuteRequest> requestCaptor) { SdkHttpContentPublisher content = requestCaptor.getValue().requestContentPublisher(); List<ByteBuffer> chunks = Flowable.fromPublisher(content).toList().blockingGet(); String contentString = new String(chunks.get(0).array()); assertThat(contentString).contains(CUSTOM_PARAM_NAME + "=" + CUSTOM_PARAM_VALUE); } @Test public void customInterceptor_syncClient_additionalQueryParamsAdded_paramsAlsoMovedToBody() throws IOException { syncClient = ProtocolQueryClient.builder() .overrideConfiguration(o -> o.addExecutionInterceptor(new AdditionalQueryParamInterceptor())) .region(Region.US_WEST_2) .credentialsProvider(CREDENTIALS) .httpClient(syncMockHttpClient) .build(); ArgumentCaptor<HttpExecuteRequest> requestCaptor = ArgumentCaptor.forClass(HttpExecuteRequest.class); assertThatThrownBy(() -> syncClient.membersInQueryParams(r -> r.stringQueryParam("hello"))) .isInstanceOf(SdkClientException.class) .hasMessageContaining("IO"); verify(syncMockHttpClient, atLeast(1)).prepareRequest(requestCaptor.capture()); verifyParametersMovedToBody_syncClient(requestCaptor); } @Test public void customInterceptor_asyncClient_additionalQueryParamsAdded_paramsAlsoMovedToBody() throws IOException { asyncClient = ProtocolQueryAsyncClient.builder() .overrideConfiguration(o -> o.addExecutionInterceptor(new AdditionalQueryParamInterceptor())) .region(Region.US_WEST_2) .credentialsProvider(CREDENTIALS) .httpClient(asyncMockHttpClient) .build(); ArgumentCaptor<AsyncExecuteRequest> requestCaptor = ArgumentCaptor.forClass(AsyncExecuteRequest.class); asyncClient.membersInQueryParams(r -> r.stringQueryParam("hello")); verify(asyncMockHttpClient, atLeast(1)).execute(requestCaptor.capture()); verifyParametersMovedToBody_asyncClient(requestCaptor); } @Test public void requestOverrideConfiguration_syncClient_additionalQueryParamsAdded_paramsAlsoMovedToBody() throws IOException { syncClient = ProtocolQueryClient.builder() .region(Region.US_WEST_2) .credentialsProvider(CREDENTIALS) .httpClient(syncMockHttpClient) .build(); ArgumentCaptor<HttpExecuteRequest> requestCaptor = ArgumentCaptor.forClass(HttpExecuteRequest.class); assertThatThrownBy(() -> syncClient.membersInQueryParams(r -> r.stringQueryParam("hello") .overrideConfiguration(createOverrideConfigWithQueryParams()))) .isInstanceOf(SdkClientException.class) .hasMessageContaining("IO"); verify(syncMockHttpClient, atLeast(1)).prepareRequest(requestCaptor.capture()); verifyParametersMovedToBody_syncClient(requestCaptor); } @Test public void requestOverrideConfiguration_asyncClient_additionalQueryParamsAdded_paramsAlsoMovedToBody() throws IOException { asyncClient = ProtocolQueryAsyncClient.builder() .region(Region.US_WEST_2) .credentialsProvider(CREDENTIALS) .httpClient(asyncMockHttpClient) .build(); ArgumentCaptor<AsyncExecuteRequest> requestCaptor = ArgumentCaptor.forClass(AsyncExecuteRequest.class); asyncClient.membersInQueryParams(r -> r.stringQueryParam("hello").overrideConfiguration(createOverrideConfigWithQueryParams())); verify(asyncMockHttpClient, atLeast(1)).execute(requestCaptor.capture()); verifyParametersMovedToBody_asyncClient(requestCaptor); } @Test public void syncClient_noQueryParamsAdded_onlyContainsOriginalContent() throws IOException { syncClient = ProtocolQueryClient.builder() .region(Region.US_WEST_2) .credentialsProvider(CREDENTIALS) .httpClient(syncMockHttpClient) .build(); ArgumentCaptor<HttpExecuteRequest> requestCaptor = ArgumentCaptor.forClass(HttpExecuteRequest.class); assertThatThrownBy(() -> syncClient.allTypes(r -> r.stringMember("hello"))) .isInstanceOf(SdkClientException.class) .hasMessageContaining("IO"); verify(syncMockHttpClient, atLeast(1)).prepareRequest(requestCaptor.capture()); ContentStreamProvider requestContent = requestCaptor.getValue().contentStreamProvider().get(); String contentString = IoUtils.toUtf8String(requestContent.newStream()); assertThat(contentString).isEqualTo("Action=QueryService.AllTypes&Version=2016-03-11&StringMember=hello"); } @Test public void asyncClient_noQueryParamsAdded_onlyContainsOriginalContent() throws IOException { asyncClient = ProtocolQueryAsyncClient.builder() .region(Region.US_WEST_2) .credentialsProvider(CREDENTIALS) .httpClient(asyncMockHttpClient) .build(); ArgumentCaptor<AsyncExecuteRequest> requestCaptor = ArgumentCaptor.forClass(AsyncExecuteRequest.class); asyncClient.allTypes(r -> r.stringMember("hello")); verify(asyncMockHttpClient, atLeast(1)).execute(requestCaptor.capture()); SdkHttpContentPublisher content = requestCaptor.getValue().requestContentPublisher(); List<ByteBuffer> chunks = Flowable.fromPublisher(content).toList().blockingGet(); String contentString = new String(chunks.get(0).array()); assertThat(contentString).isEqualTo("Action=QueryService.AllTypes&Version=2016-03-11&StringMember=hello"); } private AwsRequestOverrideConfiguration createOverrideConfigWithQueryParams() { Map<String, List<String>> queryMap = new HashMap<>(); List<String> paramValues = new ArrayList<>(); paramValues.add(CUSTOM_PARAM_VALUE); queryMap.put(CUSTOM_PARAM_NAME, paramValues); return AwsRequestOverrideConfiguration.builder().rawQueryParameters(queryMap).build(); } private static class AdditionalQueryParamInterceptor implements ExecutionInterceptor { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { return context.httpRequest().toBuilder() .putRawQueryParameter(CUSTOM_PARAM_NAME, CUSTOM_PARAM_VALUE) .build(); } } }
2,911
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/protocolquery/AsyncOperationCancelTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.protocolquery; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolquery.model.AllTypesResponse; import software.amazon.awssdk.services.protocolquery.model.StreamingInputOperationResponse; import software.amazon.awssdk.services.protocolquery.model.StreamingOutputOperationResponse; import java.util.concurrent.CompletableFuture; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; /** * Test to ensure that cancelling the future returned for an async operation will cancel the future returned by the async HTTP client. */ @RunWith(MockitoJUnitRunner.class) public class AsyncOperationCancelTest { @Mock private SdkAsyncHttpClient mockHttpClient; private ProtocolQueryAsyncClient client; private CompletableFuture executeFuture; @Before public void setUp() { client = ProtocolQueryAsyncClient.builder() .region(Region.US_EAST_1) .credentialsProvider(StaticCredentialsProvider.create( AwsBasicCredentials.create("foo", "bar"))) .httpClient(mockHttpClient) .build(); executeFuture = new CompletableFuture(); when(mockHttpClient.execute(any())).thenReturn(executeFuture); } @Test public void testNonStreamingOperation() throws InterruptedException { CompletableFuture<AllTypesResponse> responseFuture = client.allTypes(r -> { }); responseFuture.cancel(true); assertThat(executeFuture.isCompletedExceptionally()).isTrue(); assertThat(executeFuture.isCancelled()).isTrue(); } @Test public void testStreamingInputOperation() { CompletableFuture<StreamingInputOperationResponse> responseFuture = client.streamingInputOperation(r -> {}, AsyncRequestBody.empty()); responseFuture.cancel(true); assertThat(executeFuture.isCompletedExceptionally()).isTrue(); assertThat(executeFuture.isCancelled()).isTrue(); } @Test public void testStreamingOutputOperation() { CompletableFuture<ResponseBytes<StreamingOutputOperationResponse>> responseFuture = client.streamingOutputOperation(r -> { }, AsyncResponseTransformer.toBytes()); responseFuture.cancel(true); assertThat(executeFuture.isCompletedExceptionally()).isTrue(); assertThat(executeFuture.isCancelled()).isTrue(); } @Test // TODO: Query code generation does not support event streaming operations public void testEventStreamingOperation() { // CompletableFuture<Void> responseFuture = client.eventStreamOperation(r -> { // }, // subscriber -> {}, // new EventStreamOperationResponseHandler() { // @Override // public void responseReceived(EventStreamOperationResponse response) { // } // // @Override // public void onEventStream(SdkPublisher<EventStream> publisher) { // } // // @Override // public void exceptionOccurred(Throwable throwable) { // } // // @Override // public void complete() { // } // }); // responseFuture.cancel(true); // assertThat(executeFuture.isCompletedExceptionally()).isTrue(); } }
2,912
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/defaultsmode/ClientDefaultsModeTestSuite.java
/* * Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.defaultsmode; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.anyRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.containing; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import com.github.tomakehurst.wiremock.client.WireMock; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.awscore.client.builder.AwsClientBuilder; import software.amazon.awssdk.awscore.defaultsmode.DefaultsMode; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.model.AllTypesResponse; /** * Tests suites to verify {@link DefaultsMode} behavior. We currently just test SDK default configuration such as * {@link RetryMode}; there is no easy way to test HTTP timeout option. * */ public abstract class ClientDefaultsModeTestSuite<ClientT, BuilderT extends AwsClientBuilder<BuilderT, ClientT>> { @Rule public WireMockRule wireMock = new WireMockRule(0); @Test public void legacyDefaultsMode_shouldUseLegacySetting() { stubResponse(); ClientT client = clientBuilder().overrideConfiguration(o -> o.retryPolicy(RetryMode.LEGACY)).build(); callAllTypes(client); WireMock.verify(postRequestedFor(anyUrl()).withHeader("User-Agent", containing("cfg/retry-mode/legacy"))); } @Test public void standardDefaultsMode_shouldApplyStandardDefaults() { stubResponse(); ClientT client = clientBuilder().defaultsMode(DefaultsMode.STANDARD).build(); callAllTypes(client); WireMock.verify(postRequestedFor(anyUrl()).withHeader("User-Agent", containing("cfg/retry-mode/standard"))); } @Test public void retryModeOverridden_shouldTakePrecedence() { stubResponse(); ClientT client = clientBuilder().defaultsMode(DefaultsMode.STANDARD).overrideConfiguration(o -> o.retryPolicy(RetryMode.LEGACY)).build(); callAllTypes(client); WireMock.verify(postRequestedFor(anyUrl()).withHeader("User-Agent", containing("cfg/retry-mode/legacy"))); } private BuilderT clientBuilder() { return newClientBuilder().credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + wireMock.port())); } protected abstract BuilderT newClientBuilder(); protected abstract AllTypesResponse callAllTypes(ClientT client); private void verifyRequestCount(int count) { verify(count, anyRequestedFor(anyUrl())); } private void stubResponse() { stubFor(post(anyUrl()) .willReturn(aResponse())); } }
2,913
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/defaultsmode/AsyncClientDefaultsModeTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.defaultsmode; import java.util.concurrent.CompletionException; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClientBuilder; import software.amazon.awssdk.services.protocolrestjson.model.AllTypesResponse; public class AsyncClientDefaultsModeTest extends ClientDefaultsModeTestSuite<ProtocolRestJsonAsyncClient, ProtocolRestJsonAsyncClientBuilder> { @Override protected ProtocolRestJsonAsyncClientBuilder newClientBuilder() { return ProtocolRestJsonAsyncClient.builder(); } @Override protected AllTypesResponse callAllTypes(ProtocolRestJsonAsyncClient client) { try { return client.allTypes().join(); } catch (CompletionException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } throw e; } } }
2,914
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/defaultsmode/SyncClientDefaultsModeTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.defaultsmode; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClientBuilder; import software.amazon.awssdk.services.protocolrestjson.model.AllTypesResponse; public class SyncClientDefaultsModeTest extends ClientDefaultsModeTestSuite<ProtocolRestJsonClient, ProtocolRestJsonClientBuilder> { @Override protected ProtocolRestJsonClientBuilder newClientBuilder() { return ProtocolRestJsonClient.builder(); } @Override protected AllTypesResponse callAllTypes(ProtocolRestJsonClient client) { return client.allTypes(); } }
2,915
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/protocolrestxml/AsyncOperationCancelTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.protocolrestxml; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestxml.model.AllTypesResponse; import software.amazon.awssdk.services.protocolrestxml.model.EventStream; import software.amazon.awssdk.services.protocolrestxml.model.EventStreamOperationResponse; import software.amazon.awssdk.services.protocolrestxml.model.EventStreamOperationResponseHandler; import software.amazon.awssdk.services.protocolrestxml.model.StreamingInputOperationResponse; import software.amazon.awssdk.services.protocolrestxml.model.StreamingOutputOperationResponse; import java.util.concurrent.CompletableFuture; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; /** * Test to ensure that cancelling the future returned for an async operation will cancel the future returned by the async HTTP client. */ @RunWith(MockitoJUnitRunner.class) public class AsyncOperationCancelTest { @Mock private SdkAsyncHttpClient mockHttpClient; private ProtocolRestXmlAsyncClient client; private CompletableFuture executeFuture; @Before public void setUp() { client = ProtocolRestXmlAsyncClient.builder() .region(Region.US_EAST_1) .credentialsProvider(StaticCredentialsProvider.create( AwsBasicCredentials.create("foo", "bar"))) .httpClient(mockHttpClient) .build(); executeFuture = new CompletableFuture(); when(mockHttpClient.execute(any())).thenReturn(executeFuture); } @Test public void testNonStreamingOperation() { CompletableFuture<AllTypesResponse> responseFuture = client.allTypes(r -> { }); responseFuture.cancel(true); assertThat(executeFuture.isCompletedExceptionally()).isTrue(); assertThat(executeFuture.isCancelled()).isTrue(); } @Test public void testStreamingInputOperation() { CompletableFuture<StreamingInputOperationResponse> responseFuture = client.streamingInputOperation(r -> {}, AsyncRequestBody.empty()); responseFuture.cancel(true); assertThat(executeFuture.isCompletedExceptionally()).isTrue(); assertThat(executeFuture.isCancelled()).isTrue(); } @Test public void testStreamingOutputOperation() { CompletableFuture<ResponseBytes<StreamingOutputOperationResponse>> responseFuture = client.streamingOutputOperation(r -> { }, AsyncResponseTransformer.toBytes()); responseFuture.cancel(true); assertThat(executeFuture.isCompletedExceptionally()).isTrue(); assertThat(executeFuture.isCancelled()).isTrue(); } @Test public void testEventStreamingOperation() { CompletableFuture<Void> responseFuture = client.eventStreamOperation(r -> { }, new EventStreamOperationResponseHandler() { @Override public void responseReceived(EventStreamOperationResponse response) { } @Override public void onEventStream(SdkPublisher<EventStream> publisher) { } @Override public void exceptionOccurred(Throwable throwable) { } @Override public void complete() { } }); responseFuture.cancel(true); assertThat(executeFuture.isCompletedExceptionally()).isTrue(); } }
2,916
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/protocolrestxml/ServiceRequestRequiredValidationMarshallingTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.protocolrestxml; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatNoException; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.lang.reflect.Field; import java.net.URI; import java.util.Collection; import java.util.HashMap; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.protocols.xml.AwsXmlProtocolFactory; import software.amazon.awssdk.services.protocolrestxml.model.NestedQueryParameterOperation; import software.amazon.awssdk.services.protocolrestxml.model.QueryParameterOperationRequest; import software.amazon.awssdk.services.protocolrestxml.transform.QueryParameterOperationRequestMarshaller; class ServiceRequestRequiredValidationMarshallingTest { private static QueryParameterOperationRequestMarshaller marshaller; private static AwsXmlProtocolFactory awsXmlProtocolFactory; @BeforeAll static void setup() { awsXmlProtocolFactory = AwsXmlProtocolFactory .builder() .clientConfiguration(SdkClientConfiguration .builder() .option(SdkClientOption.ENDPOINT, URI.create("http://localhost")) .build()) .build(); marshaller = new QueryParameterOperationRequestMarshaller(awsXmlProtocolFactory); } @Test void marshal_notMissingRequiredMembers_doesNotThrowException() { QueryParameterOperationRequest request = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember("myHeader") .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()) .build(); assertThatNoException().isThrownBy(() -> marshaller.marshall(request)); } @Test void marshal_missingRequiredMemberAtQueryParameterLocation_throwsException() { QueryParameterOperationRequest request = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember("myHeader") .queryParamOne(null) .queryParamTwo("myParamTwo") .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()) .build(); assertThatThrownBy(() -> marshaller.marshall(request)) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Parameter 'QueryParamOne' must not be null"); } @Test void marshal_missingRequiredMemberListAtQueryParameterLocation_defaultsToEmptyCollectionAndDoesNotThrowException() { QueryParameterOperationRequest request = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember("myHeader") .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .requiredListQueryParams((Collection<Integer>) null) .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()) .build(); assertThat(request.requiredListQueryParams()).isEmpty(); assertThatNoException().isThrownBy(() -> marshaller.marshall(request)); } @Test void marshal_forceMissingRequiredMemberListAtQueryParameterLocation_throwsException() { QueryParameterOperationRequest.Builder builder = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember("myHeader") .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()); forceNull(builder, "requiredListQueryParams"); QueryParameterOperationRequest request = builder.build(); assertThat(request.requiredListQueryParams()).isNull(); assertThatThrownBy(() -> marshaller.marshall(request)) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Parameter 'RequiredListQueryParams' must not be null"); } @Test void marshal_missingRequiredMemberOfListAtQueryParameterLocation_doesNotThrowException() { QueryParameterOperationRequest request = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember("myHeader") .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .requiredListQueryParams(1, null, 3) .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()) .build(); assertThatNoException().isThrownBy(() -> marshaller.marshall(request)); } @Test void marshal_missingNonRequiredMemberListAtQueryParameterLocation_defaultsToEmptyCollectionAndDoesNotThrowException() { QueryParameterOperationRequest request = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember("myHeader") .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .optionalListQueryParams((Collection<String>) null) .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()) .build(); assertThat(request.optionalListQueryParams()).isEmpty(); assertThatNoException().isThrownBy(() -> marshaller.marshall(request)); } @Test void marshal_forceMissingNonRequiredMemberListAtQueryParameterLocation_doesNotThrowException() { QueryParameterOperationRequest.Builder builder = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember("myHeader") .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()); forceNull(builder, "optionalListQueryParams"); QueryParameterOperationRequest request = builder.build(); assertThat(request.optionalListQueryParams()).isNull(); assertThatNoException().isThrownBy(() -> marshaller.marshall(request)); } @Test void marshal_missingNonRequiredMemberOfListAtQueryParameterLocation_doesNotThrowException() { QueryParameterOperationRequest request = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember("myHeader") .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .optionalListQueryParams("1", null, "3") .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()) .build(); assertThatNoException().isThrownBy(() -> marshaller.marshall(request)); } @Test void marshal_missingRequiredMemberMapAtQueryParameterLocation_defaultsToEmptyCollectionAndDoesNotThrowException() { QueryParameterOperationRequest request = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember("myHeader") .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .requiredMapQueryParams(null) .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()) .build(); assertThat(request.requiredMapQueryParams()).isEmpty(); assertThatNoException().isThrownBy(() -> marshaller.marshall(request)); } @Test void marshal_forceMissingRequiredMemberMaoAtQueryParameterLocation_throwsException() { QueryParameterOperationRequest.Builder builder = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember("myHeader") .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()); forceNull(builder, "requiredMapQueryParams"); QueryParameterOperationRequest request = builder.build(); assertThat(request.requiredMapQueryParams()).isNull(); assertThatThrownBy(() -> marshaller.marshall(request)) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Parameter 'RequiredMapQueryParams' must not be null"); } @Test void marshal_missingRequiredMemberOfMapAtQueryParameterLocation_doesNotThrowException() { QueryParameterOperationRequest request = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember("myHeader") .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .requiredListQueryParams() .optionalListQueryParams() .requiredMapQueryParams(Stream.of(new String[][] {{"key1", "value1"}, {"key2", null}}) .collect(HashMap::new, (map, array) -> map.put(array[0], array[1]), HashMap::putAll)) .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()) .build(); assertThatThrownBy(() -> marshaller.marshall(request)) .isInstanceOf(SdkClientException.class) .hasCauseInstanceOf(ClassCastException.class); } @Test void marshal_missingRequiredMemberAtUriLocation_throwsException() { QueryParameterOperationRequest request = QueryParameterOperationRequest .builder() .pathParam(null) .stringHeaderMember("myHeader") .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()) .build(); assertThatThrownBy(() -> marshaller.marshall(request)) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Parameter 'PathParam' must not be null"); } @Test void marshal_missingRequiredMemberAtHeaderLocation_throwsException() { QueryParameterOperationRequest request = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember(null) .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()) .build(); assertThatThrownBy(() -> marshaller.marshall(request)) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Parameter 'x-amz-header-string' must not be null"); } @Test void marshal_missingRequiredMemberAtQueryParameterLocationOfNestedShape_throwsException() { QueryParameterOperationRequest request = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember("myHeader") .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne(null) .queryParamTwo("myNestedParamTwo") .build()) .build(); assertThatThrownBy(() -> marshaller.marshall(request)) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Parameter 'QueryParamOne' must not be null"); } private static void forceNull(QueryParameterOperationRequest.Builder builder, String fieldName) { try { Field field = builder.getClass().getDeclaredField(fieldName); boolean originallyAccessible = field.isAccessible(); if (!originallyAccessible) { field.setAccessible(true); } field.set(builder, null); if (!originallyAccessible) { field.setAccessible(false); } } catch (NoSuchFieldException|IllegalAccessException e) { throw new RuntimeException(e); } } }
2,917
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/delegatingclients/DelegatingSyncClientTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.delegatingclients; import static org.assertj.core.api.Assertions.assertThat; import java.net.URI; import java.util.Iterator; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.services.protocolrestjson.DelegatingProtocolRestJsonAsyncClient; import software.amazon.awssdk.services.protocolrestjson.DelegatingProtocolRestJsonClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; import software.amazon.awssdk.services.protocolrestjson.model.AllTypesRequest; import software.amazon.awssdk.services.protocolrestjson.model.PaginatedOperationWithResultKeyRequest; import software.amazon.awssdk.services.protocolrestjson.model.PaginatedOperationWithResultKeyResponse; import software.amazon.awssdk.services.protocolrestjson.model.ProtocolRestJsonRequest; import software.amazon.awssdk.services.protocolrestjson.paginators.PaginatedOperationWithResultKeyIterable; import software.amazon.awssdk.services.protocolrestjson.paginators.PaginatedOperationWithResultKeyPublisher; import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient; import software.amazon.awssdk.utils.StringInputStream; public class DelegatingSyncClientTest { private static final String INTERCEPTED_HEADER = "intercepted-header"; private static final String INTERCEPTED_HEADER_VALUE = "intercepted-value"; private static final String RESPONSE = "response"; MockSyncHttpClient mockSyncHttpClient = new MockSyncHttpClient(); ProtocolRestJsonClient defaultClient = ProtocolRestJsonClient.builder() .httpClient(mockSyncHttpClient) .endpointOverride(URI.create("http://localhost")) .build(); ProtocolRestJsonClient decoratingClient = new DecoratingClient(defaultClient); @BeforeEach public void before() { mockSyncHttpClient.stubNextResponse( HttpExecuteResponse.builder() .response(SdkHttpResponse.builder().statusCode(200).build()) .responseBody(AbortableInputStream.create(new StringInputStream(RESPONSE))) .build()); } @Test public void standardOp_Request_standardFutureResponse_delegatingClient_SuccessfullyIntercepts() { decoratingClient.allTypes(AllTypesRequest.builder().stringMember("test").build()); validateIsDecorated(); } @Test public void standardOp_ConsumerRequest_standardFutureResponse_delegatingClient_SuccessfullyIntercepts() { decoratingClient.allTypes(r -> r.stringMember("test")); validateIsDecorated(); } @Test public void paginatedOp_Request_standardFutureResponse_delegatingClient_SuccessfullyIntercepts() { decoratingClient.paginatedOperationWithResultKey(PaginatedOperationWithResultKeyRequest.builder() .nextToken("token") .build()); validateIsDecorated(); } @Test public void paginatedOp_ConsumerRequest_standardFutureResponse_delegatingClient_SuccessfullyIntercepts() { decoratingClient.paginatedOperationWithResultKey(r -> r.nextToken("token")); validateIsDecorated(); } @Test public void paginatedOp_Request_publisherResponse_delegatingClient_SuccessfullyIntercepts() { PaginatedOperationWithResultKeyIterable iterable = decoratingClient.paginatedOperationWithResultKeyPaginator(PaginatedOperationWithResultKeyRequest.builder() .nextToken("token") .build()); iterable.forEach(PaginatedOperationWithResultKeyResponse::items); validateIsDecorated(); } @Test public void paginatedOp_ConsumerRequest_publisherResponse_delegatingClient_SuccessfullyIntercepts() { PaginatedOperationWithResultKeyIterable iterable = decoratingClient.paginatedOperationWithResultKeyPaginator(r -> r.nextToken("token").build()); iterable.forEach(PaginatedOperationWithResultKeyResponse::items); validateIsDecorated(); } private void validateIsDecorated() { SdkHttpRequest lastRequest = mockSyncHttpClient.getLastRequest(); assertThat(lastRequest.headers().get(INTERCEPTED_HEADER)).isNotNull(); assertThat(lastRequest.headers().get(INTERCEPTED_HEADER).get(0)).isEqualTo(INTERCEPTED_HEADER_VALUE); } private static final class DecoratingClient extends DelegatingProtocolRestJsonClient { DecoratingClient(ProtocolRestJsonClient client) { super(client); } @Override protected <T extends ProtocolRestJsonRequest, ReturnT> ReturnT invokeOperation(T request, Function<T, ReturnT> operation) { return operation.apply(decorateRequest(request)); } @SuppressWarnings("unchecked") private <T extends ProtocolRestJsonRequest> T decorateRequest(T request) { AwsRequestOverrideConfiguration alin = AwsRequestOverrideConfiguration.builder() .putHeader(INTERCEPTED_HEADER, INTERCEPTED_HEADER_VALUE) .build(); return (T) request.toBuilder() .overrideConfiguration(alin) .build(); } } }
2,918
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/delegatingclients/DelegatingAsyncClientTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.delegatingclients; import static org.assertj.core.api.Assertions.assertThat; import java.net.URI; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.services.protocolrestjson.DelegatingProtocolRestJsonAsyncClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; import software.amazon.awssdk.services.protocolrestjson.model.AllTypesRequest; import software.amazon.awssdk.services.protocolrestjson.model.PaginatedOperationWithResultKeyRequest; import software.amazon.awssdk.services.protocolrestjson.model.PaginatedOperationWithResultKeyResponse; import software.amazon.awssdk.services.protocolrestjson.model.ProtocolRestJsonRequest; import software.amazon.awssdk.services.protocolrestjson.paginators.PaginatedOperationWithResultKeyPublisher; import software.amazon.awssdk.testutils.service.http.MockAsyncHttpClient; import software.amazon.awssdk.utils.StringInputStream; public class DelegatingAsyncClientTest { private static final String INTERCEPTED_HEADER = "intercepted-header"; private static final String INTERCEPTED_HEADER_VALUE = "intercepted-value"; private static final String RESPONSE = "response"; MockAsyncHttpClient mockAsyncHttpClient = new MockAsyncHttpClient(); ProtocolRestJsonAsyncClient defaultClient = ProtocolRestJsonAsyncClient.builder() .httpClient(mockAsyncHttpClient) .endpointOverride(URI.create("http://localhost")) .build(); ProtocolRestJsonAsyncClient decoratingClient = new DecoratingClient(defaultClient); @BeforeEach public void before() { mockAsyncHttpClient.stubNextResponse( HttpExecuteResponse.builder() .response(SdkHttpResponse.builder().statusCode(200).build()) .responseBody(AbortableInputStream.create(new StringInputStream(RESPONSE))) .build()); } @Test public void standardOp_Request_standardFutureResponse_delegatingClient_SuccessfullyIntercepts() { decoratingClient.allTypes(AllTypesRequest.builder().stringMember("test").build()).join(); validateIsDecorated(); } @Test public void standardOp_ConsumerRequest_standardFutureResponse_delegatingClient_SuccessfullyIntercepts() { decoratingClient.allTypes(r -> r.stringMember("test")).join(); validateIsDecorated(); } @Test public void paginatedOp_Request_standardFutureResponse_delegatingClient_SuccessfullyIntercepts() { decoratingClient.paginatedOperationWithResultKey( PaginatedOperationWithResultKeyRequest.builder().nextToken("token").build()) .join(); validateIsDecorated(); } @Test public void paginatedOp_ConsumerRequest_standardFutureResponse_delegatingClient_SuccessfullyIntercepts() { decoratingClient.paginatedOperationWithResultKey(r -> r.nextToken("token")).join(); validateIsDecorated(); } @Test public void paginatedOp_Request_publisherResponse_delegatingClient_DoesNotIntercept() throws Exception { PaginatedOperationWithResultKeyPublisher publisher = decoratingClient.paginatedOperationWithResultKeyPaginator(PaginatedOperationWithResultKeyRequest.builder() .nextToken("token") .build()); CompletableFuture<Void> future = publisher.subscribe(PaginatedOperationWithResultKeyResponse::items); future.get(); validateIsDecorated(); } @Test public void paginatedOp_ConsumerRequest_publisherResponse_delegatingClient_DoesNotIntercept() throws Exception { PaginatedOperationWithResultKeyPublisher publisher = decoratingClient.paginatedOperationWithResultKeyPaginator(r -> r.nextToken("token").build()); CompletableFuture<Void> future = publisher.subscribe(PaginatedOperationWithResultKeyResponse::items); future.get(); validateIsDecorated(); } private void validateIsDecorated() { SdkHttpRequest lastRequest = mockAsyncHttpClient.getLastRequest(); assertThat(lastRequest.headers().get(INTERCEPTED_HEADER)).isNotNull(); assertThat(lastRequest.headers().get(INTERCEPTED_HEADER).get(0)).isEqualTo(INTERCEPTED_HEADER_VALUE); } private static final class DecoratingClient extends DelegatingProtocolRestJsonAsyncClient { DecoratingClient(ProtocolRestJsonAsyncClient client) { super(client); } @Override protected <T extends ProtocolRestJsonRequest, ReturnT> CompletableFuture<ReturnT> invokeOperation(T request, Function<T, CompletableFuture<ReturnT>> operation) { return operation.apply(decorateRequest(request)); } @SuppressWarnings("unchecked") private <T extends ProtocolRestJsonRequest> T decorateRequest(T request) { AwsRequestOverrideConfiguration alin = AwsRequestOverrideConfiguration.builder() .putHeader(INTERCEPTED_HEADER, INTERCEPTED_HEADER_VALUE) .build(); return (T) request.toBuilder() .overrideConfiguration(alin) .build(); } } }
2,919
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/serviceclientconfiguration/ServiceClientConfigurationUsingInternalPluginsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.serviceclientconfiguration; import static org.assertj.core.api.Assertions.assertThat; import java.net.URI; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.SdkPlugin; import software.amazon.awssdk.services.protocolrestxmlinternalplugins.ProtocolRestXmlInternalPluginsAsyncClient; import software.amazon.awssdk.services.protocolrestxmlinternalplugins.ProtocolRestXmlInternalPluginsClient; public class ServiceClientConfigurationUsingInternalPluginsTest { private static final SdkPlugin NOOP_PLUGIN = config -> {}; private static final URI ENDPOINT_OVERRIDE_INTERNAL_TEST_PLUGIN_URI = URI.create("http://127.0.0.1"); @Test void syncClientWithExternalPluginEndpointOverride_serviceClientConfiguration_shouldReturnCorrectEndpointOverride() { URI uri = URI.create("https://www.amazon.com/"); ProtocolRestXmlInternalPluginsClient client = ProtocolRestXmlInternalPluginsClient.builder() .addPlugin(config -> config.endpointOverride(uri)) .build(); URI endpointOverride = client.serviceClientConfiguration().endpointOverride().orElse(null); assertThat(endpointOverride).isEqualTo(uri); } @Test void syncClientWithoutExternalPluginEndpointOverride_serviceClientConfiguration_shouldReturnCorrectEndpointOverride() { ProtocolRestXmlInternalPluginsClient client = ProtocolRestXmlInternalPluginsClient.builder() .addPlugin(NOOP_PLUGIN) .build(); URI endpointOverride = client.serviceClientConfiguration().endpointOverride().orElse(null); assertThat(endpointOverride).isEqualTo(ENDPOINT_OVERRIDE_INTERNAL_TEST_PLUGIN_URI); } @Test void syncClientWithoutEndpointOverride_serviceClientConfiguration_shouldReturnCorrectEndpointOverride() { ProtocolRestXmlInternalPluginsClient client = ProtocolRestXmlInternalPluginsClient.builder() .build(); URI endpointOverride = client.serviceClientConfiguration().endpointOverride().orElse(null); assertThat(endpointOverride).isEqualTo(ENDPOINT_OVERRIDE_INTERNAL_TEST_PLUGIN_URI); } @Test void asyncClientWithExternalPluginEndpointOverride_serviceClientConfiguration_shouldReturnCorrectEndpointOverride() { URI uri = URI.create("https://www.amazon.com/"); ProtocolRestXmlInternalPluginsAsyncClient client = ProtocolRestXmlInternalPluginsAsyncClient.builder() .addPlugin(config -> config.endpointOverride(uri)) .build(); URI endpointOverride = client.serviceClientConfiguration().endpointOverride().orElse(null); assertThat(endpointOverride).isEqualTo(uri); } @Test void asyncClientWithoutExternalPluginEndpointOverride_serviceClientConfiguration_shouldReturnCorrectEndpointOverride() { ProtocolRestXmlInternalPluginsAsyncClient client = ProtocolRestXmlInternalPluginsAsyncClient.builder() .addPlugin(NOOP_PLUGIN) .build(); URI endpointOverride = client.serviceClientConfiguration().endpointOverride().orElse(null); assertThat(endpointOverride).isEqualTo(ENDPOINT_OVERRIDE_INTERNAL_TEST_PLUGIN_URI); } @Test void asyncClientWithoutEndpointOverride_serviceClientConfiguration_shouldReturnCorrectEndpointOverride() { ProtocolRestXmlInternalPluginsAsyncClient client = ProtocolRestXmlInternalPluginsAsyncClient.builder() .build(); URI endpointOverride = client.serviceClientConfiguration().endpointOverride().orElse(null); assertThat(endpointOverride).isEqualTo(ENDPOINT_OVERRIDE_INTERNAL_TEST_PLUGIN_URI); } }
2,920
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/serviceclientconfiguration/ServiceClientConfigurationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.serviceclientconfiguration; import static org.assertj.core.api.Assertions.assertThat; import java.net.URI; import java.time.Duration; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.endpoints.EndpointProvider; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlAsyncClient; import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlClient; import software.amazon.awssdk.services.protocolrestxml.endpoints.ProtocolRestXmlEndpointProvider; public class ServiceClientConfigurationTest { @Test public void syncClient_serviceClientConfiguration_shouldReturnCorrectRegion() { ProtocolRestXmlClient client = ProtocolRestXmlClient.builder() .region(Region.ME_SOUTH_1) .build(); Region region = client.serviceClientConfiguration().region(); assertThat(region).isEqualTo(Region.ME_SOUTH_1); } @Test public void syncClientWithEndpointOverride_serviceClientConfiguration_shouldReturnCorrectEndpointOverride() { URI uri = URI.create("https://www.amazon.com/"); ProtocolRestXmlClient client = ProtocolRestXmlClient.builder() .endpointOverride(uri) .build(); URI endpointOverride = client.serviceClientConfiguration().endpointOverride().orElse(null); assertThat(endpointOverride).isEqualTo(uri); } @Test public void syncClientWithoutEndpointOverride_serviceClientConfiguration_shouldReturnEmptyOptional() { ProtocolRestXmlClient client = ProtocolRestXmlClient.builder() .build(); URI endpointOverride = client.serviceClientConfiguration().endpointOverride().orElse(null); assertThat(endpointOverride).isNull(); } @Test public void syncClient_serviceClientConfiguration_shouldReturnCorrectClientOverrideConfigurationFields() { ClientOverrideConfiguration overrideConfiguration = ClientOverrideConfiguration.builder() .apiCallAttemptTimeout(Duration.ofSeconds(30)) .apiCallTimeout(Duration.ofSeconds(90)) .retryPolicy(c -> c.numRetries(4)) .build(); ProtocolRestXmlClient client = ProtocolRestXmlClient.builder() .overrideConfiguration(overrideConfiguration) .build(); ClientOverrideConfiguration overrideConfig = client.serviceClientConfiguration().overrideConfiguration(); assertThat(overrideConfig.apiCallAttemptTimeout().get()).isEqualTo(Duration.ofSeconds(30)); assertThat(overrideConfig.apiCallTimeout().get()).isEqualTo(Duration.ofSeconds(90)); assertThat(overrideConfig.retryPolicy().get().numRetries()).isEqualTo(4); assertThat(overrideConfig.defaultProfileFile()).hasValue(ProfileFile.defaultProfileFile()); assertThat(overrideConfig.metricPublishers()).isEmpty(); } @Test public void syncClient_serviceClientConfiguration_includesAllSettingsInToString() { ClientOverrideConfiguration overrideConfiguration = ClientOverrideConfiguration.builder() .apiCallAttemptTimeout(Duration.ofSeconds(30)) .apiCallTimeout(Duration.ofSeconds(90)) .retryPolicy(c -> c.numRetries(4)) .build(); ProtocolRestXmlClient client = ProtocolRestXmlClient.builder() .overrideConfiguration(overrideConfiguration) .region(Region.US_WEST_2) .build(); assertThat(client.serviceClientConfiguration().overrideConfiguration().apiCallAttemptTimeout().get()).isEqualTo(Duration.ofSeconds(30)); assertThat(client.serviceClientConfiguration().overrideConfiguration().apiCallTimeout().get()).isEqualTo(Duration.ofSeconds(90)); assertThat(client.serviceClientConfiguration().overrideConfiguration().retryPolicy().get().numRetries()).isEqualTo(4); assertThat(client.serviceClientConfiguration().overrideConfiguration().defaultProfileFile()).hasValue(ProfileFile.defaultProfileFile()); assertThat(client.serviceClientConfiguration().overrideConfiguration().metricPublishers()).isEmpty(); } @Test public void syncClient_serviceClientConfiguration_withoutOverrideConfiguration_shouldReturnEmptyFields () { ProtocolRestXmlClient client = ProtocolRestXmlClient.builder() .build(); ClientOverrideConfiguration overrideConfig = client.serviceClientConfiguration().overrideConfiguration(); assertThat(overrideConfig.apiCallAttemptTimeout()).isNotPresent(); assertThat(overrideConfig.apiCallTimeout()).isNotPresent(); assertThat(overrideConfig.retryPolicy().get().numRetries()).isEqualTo(3); assertThat(overrideConfig.defaultProfileFile()).hasValue(ProfileFile.defaultProfileFile()); assertThat(overrideConfig.metricPublishers()).isEmpty(); } @Test public void syncClientWithEndpointProvider_serviceClientConfiguration_shouldReturnCorrectEndpointProvider() { ProtocolRestXmlEndpointProvider clientEndpointProvider = ProtocolRestXmlEndpointProvider.defaultProvider(); ProtocolRestXmlClient client = ProtocolRestXmlClient.builder() .endpointProvider(clientEndpointProvider) .build(); EndpointProvider endpointProvider = client.serviceClientConfiguration().endpointProvider().orElse(null); assertThat(endpointProvider).isEqualTo(clientEndpointProvider); } @Test public void syncClientWithoutEndpointProvider_serviceClientConfiguration_shouldReturnDefaultEndpointProvider() { ProtocolRestXmlClient client = ProtocolRestXmlClient.builder() .build(); EndpointProvider endpointProvider = client.serviceClientConfiguration().endpointProvider().orElse(null); assertThat(endpointProvider instanceof ProtocolRestXmlEndpointProvider).isTrue(); } @Test public void asyncClient_serviceClientConfiguration_shouldReturnCorrectRegion() { ProtocolRestXmlAsyncClient client = ProtocolRestXmlAsyncClient.builder() .region(Region.ME_SOUTH_1) .build(); Region region = client.serviceClientConfiguration().region(); assertThat(region).isEqualTo(Region.ME_SOUTH_1); } @Test public void asyncClientWithEndpointOverride_serviceClientConfiguration_shouldReturnCorrectEndpointOverride() { URI uri = URI.create("https://www.amazon.com/"); ProtocolRestXmlAsyncClient client = ProtocolRestXmlAsyncClient.builder() .endpointOverride(uri) .build(); URI endpointOverride = client.serviceClientConfiguration().endpointOverride().orElse(null); assertThat(endpointOverride).isEqualTo(uri); } @Test public void asyncClientWithoutEndpointOverride_serviceClientConfiguration_shouldReturnEmptyOptional() { ProtocolRestXmlAsyncClient client = ProtocolRestXmlAsyncClient.builder() .build(); URI endpointOverride = client.serviceClientConfiguration().endpointOverride().orElse(null); assertThat(endpointOverride).isNull(); } @Test public void asyncClient_serviceClientConfiguration_shouldReturnCorrectClientOverrideConfigurationFields() { ClientOverrideConfiguration overrideConfiguration = ClientOverrideConfiguration.builder() .apiCallAttemptTimeout(Duration.ofSeconds(30)) .apiCallTimeout(Duration.ofSeconds(90)) .retryPolicy(c -> c.numRetries(4)) .build(); ProtocolRestXmlAsyncClient client = ProtocolRestXmlAsyncClient.builder() .overrideConfiguration(overrideConfiguration) .build(); ClientOverrideConfiguration overrideConfig = client.serviceClientConfiguration().overrideConfiguration(); assertThat(overrideConfig.apiCallAttemptTimeout().get()).isEqualTo(Duration.ofSeconds(30)); assertThat(overrideConfig.apiCallTimeout().get()).isEqualTo(Duration.ofSeconds(90)); assertThat(overrideConfig.retryPolicy().get().numRetries()).isEqualTo(4); assertThat(overrideConfig.defaultProfileFile()).hasValue(ProfileFile.defaultProfileFile()); assertThat(overrideConfig.metricPublishers()).isEmpty(); } @Test public void asyncClient_serviceClientConfiguration_withoutOverrideConfiguration_shouldReturnEmptyFields () { ProtocolRestXmlAsyncClient client = ProtocolRestXmlAsyncClient.builder() .build(); ClientOverrideConfiguration overrideConfig = client.serviceClientConfiguration().overrideConfiguration(); assertThat(overrideConfig.apiCallAttemptTimeout()).isNotPresent(); assertThat(overrideConfig.apiCallTimeout()).isNotPresent(); assertThat(overrideConfig.retryPolicy().get().numRetries()).isEqualTo(3); assertThat(overrideConfig.defaultProfileFile()).hasValue(ProfileFile.defaultProfileFile()); assertThat(overrideConfig.metricPublishers()).isEmpty(); } @Test public void asyncClientWithEndpointProvider_serviceClientConfiguration_shouldReturnCorrectEndpointProvider() { ProtocolRestXmlEndpointProvider clientEndpointProvider = ProtocolRestXmlEndpointProvider.defaultProvider(); ProtocolRestXmlAsyncClient client = ProtocolRestXmlAsyncClient.builder() .endpointProvider(clientEndpointProvider) .build(); EndpointProvider endpointProvider = client.serviceClientConfiguration().endpointProvider().orElse(null); assertThat(endpointProvider).isEqualTo(clientEndpointProvider); } @Test public void asyncClientWithoutEndpointProvider_serviceClientConfiguration_shouldReturnDefault() { ProtocolRestXmlAsyncClient client = ProtocolRestXmlAsyncClient.builder() .build(); EndpointProvider endpointProvider = client.serviceClientConfiguration().endpointProvider().orElse(null); assertThat(endpointProvider instanceof ProtocolRestXmlEndpointProvider).isTrue(); } }
2,921
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/serviceclientconfiguration/ServiceClientConfigurationUsingPluginsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.serviceclientconfiguration; import static org.assertj.core.api.Assertions.assertThat; import java.net.URI; import java.time.Duration; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.SdkPlugin; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.endpoints.EndpointProvider; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlAsyncClient; import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlClient; import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlServiceClientConfiguration; import software.amazon.awssdk.services.protocolrestxml.endpoints.ProtocolRestXmlEndpointProvider; // The same battery of tests as in `ServiceClientConfigurationTest` but using plugins. public class ServiceClientConfigurationUsingPluginsTest { private static final SdkPlugin NOOP_PLUGIN = config -> {}; @Test void syncClient_serviceClientConfiguration_shouldReturnCorrectRegion() { SdkPlugin testPlugin = config -> { if (config instanceof ProtocolRestXmlServiceClientConfiguration.Builder) { ProtocolRestXmlServiceClientConfiguration.Builder builder = (ProtocolRestXmlServiceClientConfiguration.Builder) config; builder.region(Region.ME_SOUTH_1); } }; ProtocolRestXmlClient client = ProtocolRestXmlClient.builder() .addPlugin(testPlugin) .build(); Region region = client.serviceClientConfiguration().region(); assertThat(region).isEqualTo(Region.ME_SOUTH_1); } @Test void syncClientWithEndpointOverride_serviceClientConfiguration_shouldReturnCorrectEndpointOverride() { URI uri = URI.create("https://www.amazon.com/"); ProtocolRestXmlClient client = ProtocolRestXmlClient.builder() .addPlugin(config -> config.endpointOverride(uri)) .build(); URI endpointOverride = client.serviceClientConfiguration().endpointOverride().orElse(null); assertThat(endpointOverride).isEqualTo(uri); } @Test void syncClientWithoutEndpointOverride_serviceClientConfiguration_shouldReturnEmptyOptional() { ProtocolRestXmlClient client = ProtocolRestXmlClient.builder() .addPlugin(NOOP_PLUGIN) .build(); URI endpointOverride = client.serviceClientConfiguration().endpointOverride().orElse(null); assertThat(endpointOverride).isNull(); } @Test void syncClient_serviceClientConfiguration_shouldReturnCorrectClientOverrideConfigurationFields() { ClientOverrideConfiguration overrideConfiguration = ClientOverrideConfiguration.builder() .apiCallAttemptTimeout(Duration.ofSeconds(30)) .apiCallTimeout(Duration.ofSeconds(90)) .retryPolicy(c -> c.numRetries(4)) .build(); ProtocolRestXmlClient client = ProtocolRestXmlClient.builder() .addPlugin(config -> config.overrideConfiguration(overrideConfiguration)) .build(); ClientOverrideConfiguration result = client.serviceClientConfiguration().overrideConfiguration(); assertThat(result.apiCallAttemptTimeout().get()).isEqualTo(Duration.ofSeconds(30)); assertThat(result.apiCallTimeout().get()).isEqualTo(Duration.ofSeconds(90)); assertThat(result.retryPolicy().get().numRetries()).isEqualTo(4); assertThat(result.defaultProfileFile()).hasValue(ProfileFile.defaultProfileFile()); assertThat(result.metricPublishers()).isEmpty(); } @Test void syncClient_serviceClientConfiguration_withoutOverrideConfiguration_shouldReturnEmptyFields() { ProtocolRestXmlClient client = ProtocolRestXmlClient.builder() .addPlugin(NOOP_PLUGIN) .build(); ClientOverrideConfiguration overrideConfiguration = client.serviceClientConfiguration().overrideConfiguration(); assertThat(overrideConfiguration.apiCallAttemptTimeout()).isNotPresent(); assertThat(overrideConfiguration.apiCallTimeout()).isNotPresent(); assertThat(overrideConfiguration.retryPolicy().get().numRetries()).isEqualTo(3); assertThat(overrideConfiguration.defaultProfileFile()).hasValue(ProfileFile.defaultProfileFile()); assertThat(overrideConfiguration.metricPublishers()).isEmpty(); } @Test void syncClientWithEndpointProvider_serviceClientConfiguration_shouldReturnCorrectEndpointProvider() { ProtocolRestXmlEndpointProvider clientEndpointProvider = ProtocolRestXmlEndpointProvider.defaultProvider(); ProtocolRestXmlClient client = ProtocolRestXmlClient.builder() .addPlugin(config -> config.endpointProvider(clientEndpointProvider)) .build(); EndpointProvider endpointProvider = client.serviceClientConfiguration().endpointProvider().orElse(null); assertThat(endpointProvider).isEqualTo(clientEndpointProvider); } @Test void syncClientWithoutEndpointProvider_serviceClientConfiguration_shouldReturnDefaultEndpointProvider() { ProtocolRestXmlClient client = ProtocolRestXmlClient.builder() .build(); EndpointProvider endpointProvider = client.serviceClientConfiguration().endpointProvider().orElse(null); assertThat(endpointProvider instanceof ProtocolRestXmlEndpointProvider).isTrue(); } @Test void asyncClient_serviceClientConfiguration_shouldReturnCorrectRegion() { SdkPlugin testPlugin = config -> { if (config instanceof ProtocolRestXmlServiceClientConfiguration.Builder) { ProtocolRestXmlServiceClientConfiguration.Builder builder = (ProtocolRestXmlServiceClientConfiguration.Builder) config; builder.region(Region.ME_SOUTH_1); } }; ProtocolRestXmlAsyncClient client = ProtocolRestXmlAsyncClient.builder() .addPlugin(testPlugin) .build(); Region region = client.serviceClientConfiguration().region(); assertThat(region).isEqualTo(Region.ME_SOUTH_1); } @Test void asyncClientWithEndpointOverride_serviceClientConfiguration_shouldReturnCorrectEndpointOverride() { URI uri = URI.create("https://www.amazon.com/"); ProtocolRestXmlAsyncClient client = ProtocolRestXmlAsyncClient.builder() .addPlugin(config -> config.endpointOverride(uri)) .build(); URI endpointOverride = client.serviceClientConfiguration().endpointOverride().orElse(null); assertThat(endpointOverride).isEqualTo(uri); } @Test void asyncClientWithoutEndpointOverride_serviceClientConfiguration_shouldReturnEmptyOptional() { ProtocolRestXmlAsyncClient client = ProtocolRestXmlAsyncClient.builder() .addPlugin(NOOP_PLUGIN) .build(); URI endpointOverride = client.serviceClientConfiguration().endpointOverride().orElse(null); assertThat(endpointOverride).isNull(); } @Test void asyncClient_serviceClientConfiguration_shouldReturnCorrectClientOverrideConfigurationFields() { ClientOverrideConfiguration overrideConfiguration = ClientOverrideConfiguration.builder() .apiCallAttemptTimeout(Duration.ofSeconds(30)) .apiCallTimeout(Duration.ofSeconds(90)) .retryPolicy(c -> c.numRetries(4)) .build(); ProtocolRestXmlAsyncClient client = ProtocolRestXmlAsyncClient.builder() .addPlugin(config -> config.overrideConfiguration(overrideConfiguration)) .build(); ClientOverrideConfiguration result = client.serviceClientConfiguration().overrideConfiguration(); assertThat(result.apiCallAttemptTimeout().get()).isEqualTo(Duration.ofSeconds(30)); assertThat(result.apiCallTimeout().get()).isEqualTo(Duration.ofSeconds(90)); assertThat(result.retryPolicy().get().numRetries()).isEqualTo(4); assertThat(result.defaultProfileFile()).hasValue(ProfileFile.defaultProfileFile()); assertThat(result.metricPublishers()).isEmpty(); } @Test void asyncClient_serviceClientConfiguration_withoutOverrideConfiguration_shouldReturnEmptyFieldsAndDefaults() { ProtocolRestXmlAsyncClient client = ProtocolRestXmlAsyncClient.builder() .addPlugin(NOOP_PLUGIN) .build(); ClientOverrideConfiguration result = client.serviceClientConfiguration().overrideConfiguration(); assertThat(result.apiCallAttemptTimeout()).isNotPresent(); assertThat(result.apiCallTimeout()).isNotPresent(); assertThat(result.retryPolicy().get().numRetries()).isEqualTo(3); assertThat(result.defaultProfileFile()).hasValue(ProfileFile.defaultProfileFile()); assertThat(result.metricPublishers()).isEmpty(); } @Test void asyncClientWithEndpointProvider_serviceClientConfiguration_shouldReturnCorrectEndpointProvider() { ProtocolRestXmlEndpointProvider clientEndpointProvider = ProtocolRestXmlEndpointProvider.defaultProvider(); SdkPlugin testPlugin = config -> config.endpointProvider(clientEndpointProvider); ProtocolRestXmlAsyncClient client = ProtocolRestXmlAsyncClient.builder() .addPlugin(testPlugin) .build(); EndpointProvider endpointProvider = client.serviceClientConfiguration().endpointProvider().orElse(null); assertThat(endpointProvider).isEqualTo(clientEndpointProvider); } @Test void asyncClientWithoutEndpointProvider_serviceClientConfiguration_shouldReturnDefault() { ProtocolRestXmlAsyncClient client = ProtocolRestXmlAsyncClient.builder() .addPlugin(NOOP_PLUGIN) .build(); EndpointProvider endpointProvider = client.serviceClientConfiguration().endpointProvider().orElse(null); assertThat(endpointProvider instanceof ProtocolRestXmlEndpointProvider).isTrue(); } }
2,922
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/rules/ValidateUriScheme.java
package software.amazon.awssdk.services.rules; import java.util.List; import java.util.Map; import java.util.stream.Stream; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.EndpointResult; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Identifier; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Literal; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Template; /** * Validate that URIs start with a scheme */ public class ValidateUriScheme extends TraversingVisitor<ValidationError> { boolean checkingEndpoint = false; @Override public Stream<ValidationError> visitEndpoint(EndpointResult endpoint) { checkingEndpoint = true; Stream<ValidationError> errors = endpoint.getUrl().accept(this); checkingEndpoint = false; return errors; } @Override public Stream<ValidationError> visitLiteral(Literal literal) { return literal.accept(new Literal.Visitor<Stream<ValidationError>>() { @Override public Stream<ValidationError> visitBool(boolean b) { return Stream.empty(); } @Override public Stream<ValidationError> visitStr(Template value) { return validateTemplate(value); } @Override public Stream<ValidationError> visitObject(Map<Identifier, Literal> members) { return Stream.empty(); } @Override public Stream<ValidationError> visitTuple(List<Literal> members) { return Stream.empty(); } @Override public Stream<ValidationError> visitInt(int value) { return Stream.empty(); } }); } private Stream<ValidationError> validateTemplate(Template template) { if (checkingEndpoint) { Template.Part head = template.getParts().get(0); if (head instanceof Template.Literal) { String templateStart = ((Template.Literal) head).getValue(); if (!(templateStart.startsWith("http://") || templateStart.startsWith("https://"))) { return Stream.of(new ValidationError( ValidationErrorType.INVALID_URI, "URI should start with `http://` or `https://` but the URI started with " + templateStart) ); } } /* Allow dynamic URIs for now—we should lint that at looks like a scheme at some point */ } return Stream.empty(); } }
2,923
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/rules/TraversingVisitor.java
package software.amazon.awssdk.services.rules; import java.util.List; import java.util.stream.Stream; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Condition; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.EndpointResult; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.EndpointRuleset; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Expr; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Fn; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Rule; public abstract class TraversingVisitor<R> extends DefaultVisitor<Stream<R>> { public Stream<R> visitRuleset(EndpointRuleset ruleset) { return ruleset.getRules() .stream() .flatMap(this::handleRule); } private Stream<R> handleRule(Rule rule) { Stream<R> fromConditions = visitConditions(rule.getConditions()); return Stream.concat(fromConditions, rule.accept(this)); } @Override public Stream<R> visitFn(Fn fn) { return fn.acceptFnVisitor(this); } @Override public Stream<R> getDefault() { return Stream.empty(); } @Override public Stream<R> visitEndpointRule(EndpointResult endpoint) { return visitEndpoint(endpoint); } @Override public Stream<R> visitErrorRule(Expr error) { return error.accept(this); } @Override public Stream<R> visitTreeRule(List<Rule> rules) { return rules.stream().flatMap(subrule -> subrule.accept(this)); } public Stream<R> visitEndpoint(EndpointResult endpoint) { return Stream.concat( endpoint.getUrl() .accept(this), endpoint.getProperties() .entrySet() .stream() .flatMap(map -> map.getValue().accept(this)) ); } public Stream<R> visitConditions(List<Condition> conditions) { return conditions.stream().flatMap(c -> c.getFn().accept(this)); } }
2,924
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/rules/DefaultVisitor.java
package software.amazon.awssdk.services.rules; import java.util.List; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.BooleanEqualsFn; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.EndpointResult; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Expr; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.ExprVisitor; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Fn; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.FnVisitor; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.GetAttr; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.IsSet; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.IsValidHostLabel; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.IsVirtualHostableS3Bucket; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Literal; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Not; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.ParseArn; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.ParseUrl; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.PartitionFn; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Ref; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Rule; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.RuleValueVisitor; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.StringEqualsFn; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Substring; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.UriEncodeFn; public abstract class DefaultVisitor<R> implements RuleValueVisitor<R>, ExprVisitor<R>, FnVisitor<R> { public abstract R getDefault(); @Override public R visitLiteral(Literal literal) { return getDefault(); } @Override public R visitRef(Ref ref) { return getDefault(); } @Override public R visitFn(Fn fn) { return getDefault(); } @Override public R visitPartition(PartitionFn fn) { return getDefault(); } @Override public R visitParseArn(ParseArn fn) { return getDefault(); } @Override public R visitIsValidHostLabel(IsValidHostLabel fn) { return getDefault(); } @Override public R visitBoolEquals(BooleanEqualsFn fn) { return getDefault(); } @Override public R visitStringEquals(StringEqualsFn fn) { return getDefault(); } @Override public R visitIsSet(IsSet fn) { return getDefault(); } @Override public R visitNot(Not not) { return getDefault(); } @Override public R visitGetAttr(GetAttr getAttr) { return getDefault(); } @Override public R visitParseUrl(ParseUrl parseUrl) { return getDefault(); } @Override public R visitSubstring(Substring substring) { return getDefault(); } @Override public R visitTreeRule(List<Rule> rules) { return getDefault(); } @Override public R visitErrorRule(Expr error) { return getDefault(); } @Override public R visitEndpointRule(EndpointResult endpoint) { return getDefault(); } @Override public R visitUriEncode(UriEncodeFn fn) { return getDefault(); } @Override public R visitIsVirtualHostLabelsS3Bucket(IsVirtualHostableS3Bucket fn) { return getDefault(); } }
2,925
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/rules/EndpointTest.java
package software.amazon.awssdk.services.rules; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Optional; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.EndpointRuleset; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Identifier; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Parameter; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.ParameterType; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.RuleEngine; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.RuleError; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Value; import software.amazon.awssdk.utils.Pair; public class EndpointTest { public static final String EXPECT = "expect"; public static final String PARAMS = "params"; public static final String DOCUMENTATION = "documentation"; private final String documentation; public Expectation getExpectation() { return expectation; } private final Expectation expectation; private final Value.Record params; private EndpointTest(Builder builder) { this.documentation = builder.documentation; this.expectation = Optional.ofNullable(builder.expectation).orElseThrow(NoSuchElementException::new); this.params = Optional.ofNullable(builder.params).orElseThrow(NoSuchElementException::new);; } public String getDocumentation() { return documentation; } public List<Pair<Identifier, Value>> getParams() { ArrayList<Pair<Identifier, Value>> out = new ArrayList<>(); params.forEach((name, value) -> { out.add(Pair.of(name, value)); }); return out; } public List<Parameter> getParameters() { ArrayList<Parameter> result = new ArrayList<Parameter>(); params.forEach((name, value) -> { Parameter.Builder pb = Parameter.builder().name(name); if (value instanceof Value.Str) { pb.type(ParameterType.STRING); result.add(pb.build()); } else if (value instanceof Value.Bool) { pb.type(ParameterType.BOOLEAN); result.add(pb.build()); } }); return result; } public void execute(EndpointRuleset ruleset) { Value actual = RuleEngine.defaultEngine().evaluate(ruleset, this.params.getValue()); RuleError.ctx( String.format("while executing test case%s", Optional .ofNullable(documentation) .map(d -> " " + d) .orElse("")), () -> expectation.check(actual) ); } public static EndpointTest fromNode(JsonNode node) { Map<String, JsonNode> objNode = node.asObject(); Builder b = builder(); JsonNode documentationNode = objNode.get(DOCUMENTATION); if (documentationNode != null) { b.documentation(documentationNode.asString()); } b.params(Value.fromNode(objNode.get(PARAMS)).expectRecord()); b.expectation(Expectation.fromNode(objNode.get(EXPECT))); return b.build(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EndpointTest that = (EndpointTest) o; if (documentation != null ? !documentation.equals(that.documentation) : that.documentation != null) return false; if (!expectation.equals(that.expectation)) return false; return params.equals(that.params); } @Override public int hashCode() { int result = documentation != null ? documentation.hashCode() : 0; result = 31 * result + expectation.hashCode(); result = 31 * result + params.hashCode(); return result; } public static Builder builder() { return new Builder(); } public static abstract class Expectation { public static final String ERROR = "error"; public static Expectation fromNode(JsonNode node) { Map<String, JsonNode> objNode = node.asObject(); Expectation result; JsonNode errorNode = objNode.get(ERROR); if (errorNode != null) { result = new Error(errorNode.asString()); } else { result = new Endpoint(Value.endpointFromNode(node)); } return result; } abstract void check(Value value); public static Error error(String message) { return new Error(message); } public static class Error extends Expectation { public String getMessage() { return message; } private final String message; public Error(String message) { this.message = message; } @Override void check(Value value) { RuleError.ctx("While checking endpoint test (expecting an error)", () -> { if (!value.expectString().equals(this.message)) { throw new AssertionError(String.format("Expected error %s but got %s", this.message, value)); } }); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Error error = (Error) o; return message.equals(error.message); } @Override public int hashCode() { return message.hashCode(); } } public static class Endpoint extends Expectation { public Value.Endpoint getEndpoint() { return endpoint; } private final Value.Endpoint endpoint; public Endpoint(Value.Endpoint endpoint) { this.endpoint = endpoint; } @Override void check(Value value) { Value.Endpoint actual = value.expectEndpoint(); if (!actual.equals(this.endpoint)) { throw new AssertionError( String.format("Expected endpoint:\n%s but got:\n%s", this.endpoint.toString(), actual)); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Endpoint endpoint1 = (Endpoint) o; return endpoint != null ? endpoint.equals(endpoint1.endpoint) : endpoint1.endpoint == null; } @Override public int hashCode() { return endpoint != null ? endpoint.hashCode() : 0; } } } public static class Builder { private String documentation; private Expectation expectation; private Value.Record params; public Builder documentation(String documentation) { this.documentation = documentation; return this; } public Builder expectation(Expectation expectation) { this.expectation = expectation; return this; } public Builder params(Value.Record params) { this.params = params; return this; } public EndpointTest build() { return new EndpointTest(this); } } }
2,926
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/rules/RuleEngineTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.rules; import static org.assertj.core.api.Assertions.assertThat; import java.io.InputStream; import java.util.Collections; import org.junit.jupiter.api.Test; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.EndpointRuleset; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Identifier; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.RuleEngine; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Value; import software.amazon.awssdk.utils.MapUtils; public class RuleEngineTest { private EndpointRuleset parse(String resource) { InputStream is = getClass().getClassLoader().getResourceAsStream(resource); JsonNode node = JsonNodeParser.create().parse(is); return EndpointRuleset.fromNode(node); } @Test void testRuleEval() { EndpointRuleset actual = parse("rules/valid-rules/minimal-ruleset.json"); Value result = RuleEngine.defaultEngine().evaluate(actual, MapUtils.of(Identifier.of("Region"), Value.fromStr("us-east-1"))); Value.Endpoint expected = Value.Endpoint.builder() .url("https://us-east-1.amazonaws.com") .property("authSchemes", Value.fromArray(Collections.singletonList( Value.fromRecord(MapUtils.of( Identifier.of("name"), Value.fromStr("v4"), Identifier.of("signingScope"), Value.fromStr("us-east-1"), Identifier.of("signingName"), Value.fromStr("serviceName") )) ))) .build(); assertThat(result.expectEndpoint()).isEqualTo(expected); } }
2,927
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/rules/EndpointTestSuite.java
package software.amazon.awssdk.services.rules; import java.util.ArrayList; import java.util.List; import java.util.Map; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.EndpointRuleset; public class EndpointTestSuite { public static final String SERVICE = "service"; public static final String TEST_CASES = "testCases"; private final List<EndpointTest> testCases; private final String service; public EndpointTestSuite(String service, List<EndpointTest> testCases) { this.service = service; this.testCases = testCases; } private EndpointTestSuite(Builder b) { this(b.service, b.testCases); } public void execute(EndpointRuleset ruleset) { for (EndpointTest test : this.getTestCases()) { test.execute(ruleset); } } public static EndpointTestSuite fromNode(JsonNode node) { Map<String, JsonNode> objNode = node.asObject(); Builder b = builder(); b.service(objNode.get(SERVICE).asString()); objNode.get(TEST_CASES).asArray() .stream().map(EndpointTest::fromNode) .forEach(b::addTestCase); return b.build(); } public String getService() { return service; } public List<EndpointTest> getTestCases() { return testCases; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EndpointTestSuite that = (EndpointTestSuite) o; if (!testCases.equals(that.testCases)) return false; return service.equals(that.service); } @Override public int hashCode() { int result = testCases.hashCode(); result = 31 * result + service.hashCode(); return result; } public static Builder builder() { return new Builder(); } public static class Builder { private String service; private final List<EndpointTest> testCases = new ArrayList<>(); public Builder service(String service) { this.service = service; return this; } public Builder addTestCase(EndpointTest testCase) { this.testCases.add(testCase); return this; } public EndpointTestSuite build() { return new EndpointTestSuite(this); } } }
2,928
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/rules/ValidationError.java
package software.amazon.awssdk.services.rules; import java.util.Objects; public final class ValidationError { private final ValidationErrorType validationErrorType; private final String error; public ValidationError(ValidationErrorType validationErrorType, String error) { this.validationErrorType = validationErrorType; this.error = error; } public ValidationErrorType validationErrorType() { return validationErrorType; } public String error() { return error; } @Override public String toString() { return this.validationErrorType + ", " + this.error; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null || obj.getClass() != this.getClass()) return false; ValidationError that = (ValidationError) obj; return Objects.equals(this.validationErrorType, that.validationErrorType) && Objects.equals(this.error, that.error); } @Override public int hashCode() { return Objects.hash(validationErrorType, error); } }
2,929
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/rules/IntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.rules; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.io.UncheckedIOException; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.EndpointRuleset; import software.amazon.awssdk.services.rules.testutil.TestDiscovery; @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class IntegrationTest { private static final TestDiscovery TEST_DISCOVERY = new TestDiscovery(); @ParameterizedTest @MethodSource("validTestcases") void checkValidRules(ValidationTestCase validationTestCase) { EndpointRuleset ruleset = EndpointRuleset.fromNode(validationTestCase.contents()); List<ValidationError> errors = new ValidateUriScheme().visitRuleset(ruleset) .collect(Collectors.toList()); assertEquals(errors, Collections.emptyList()); } @ParameterizedTest @MethodSource("checkableTestCases") void executeTestSuite(TestDiscovery.RulesTestcase testcase) { testcase.testcase().execute(testcase.ruleset()); } private Stream<ValidationTestCase> validTestcases() { return TEST_DISCOVERY.getValidRules() .stream() .map(name -> new ValidationTestCase(name, TEST_DISCOVERY.validRulesetUrl(name), TEST_DISCOVERY.testCaseUrl(name))); } private Stream<TestDiscovery.RulesTestcase> checkableTestCases() { return TEST_DISCOVERY.testSuites() .flatMap( suite -> suite.testSuites() .stream() .flatMap(ts -> ts.getTestCases() .stream() .map(tc -> new TestDiscovery.RulesTestcase(suite.ruleset(), tc)))); } public static final class ValidationTestCase { private final String name; private final URL ruleSet; private final URL testCase; public ValidationTestCase(String name, URL ruleSet, URL testCase) { this.name = name; this.ruleSet = ruleSet; this.testCase = testCase; } JsonNode contents() { try { return JsonNode.parser().parse(ruleSet.openStream()); } catch (IOException e) { throw new UncheckedIOException(e); } } public URL ruleSet() { return ruleSet; } public URL testCase() { return testCase; } @Override public String toString() { return name; } } }
2,930
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/rules/ValidationErrorType.java
package software.amazon.awssdk.services.rules; public enum ValidationErrorType { INCONSISTENT_PARAMETER_TYPE, UNSUPPORTED_PARAMETER_TYPE, PARAMETER_MISMATCH, PARAMETER_TYPE_MISMATCH, SERVICE_ID_MISMATCH, REQUIRED_PARAMETER_MISSING, PARAMETER_IS_NOT_USED, PARAMETER_IS_NOT_DEFINED, INVALID_URI, }
2,931
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/rules
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/rules/testutil/TestDiscovery.java
package software.amazon.awssdk.services.rules.testutil; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UncheckedIOException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.EndpointRuleset; import software.amazon.awssdk.services.rules.EndpointTest; import software.amazon.awssdk.services.rules.EndpointTestSuite; public class TestDiscovery { private static final String RESOURCE_ROOT = "/rules"; public static final class RulesTestcase { private final EndpointRuleset ruleset; private final EndpointTest testcase; public RulesTestcase(EndpointRuleset ruleset, EndpointTest testcase) { this.ruleset = ruleset; this.testcase = testcase; } @Override public String toString() { return testcase.getDocumentation(); } public EndpointRuleset ruleset() { return ruleset; } public EndpointTest testcase() { return testcase; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null || obj.getClass() != this.getClass()) return false; RulesTestcase that = (RulesTestcase) obj; return Objects.equals(this.ruleset, that.ruleset) && Objects.equals(this.testcase, that.testcase); } @Override public int hashCode() { return Objects.hash(ruleset, testcase); } } public static final class RulesTestSuite { private final EndpointRuleset ruleset; private final List<EndpointTestSuite> testSuites; public RulesTestSuite(EndpointRuleset ruleset, List<EndpointTestSuite> testSuites) { this.ruleset = ruleset; this.testSuites = testSuites; } @Override public String toString() { return ruleset.toString(); } public EndpointRuleset ruleset() { return ruleset; } public List<EndpointTestSuite> testSuites() { return testSuites; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null || obj.getClass() != this.getClass()) return false; RulesTestSuite that = (RulesTestSuite) obj; return Objects.equals(this.ruleset, that.ruleset) && Objects.equals(this.testSuites, that.testSuites); } @Override public int hashCode() { return Objects.hash(ruleset, testSuites); } } public Stream<RulesTestSuite> testSuites() { JsonNode.parser(); List<JsonNode> rulesetNodes = getValidRules() .stream() .map(e -> JsonNode.parser().parse(getResourceStream("valid-rules/" + e))) .collect(Collectors.toList()); List<JsonNode> testSuiteFiles = getManifestEntries("test-cases/manifest.txt") .stream() .map(e -> JsonNode.parser().parse(getResourceStream("test-cases/" + e))) .collect(Collectors.toList()); List<EndpointRuleset> rulesets = rulesetNodes.stream() .map(EndpointRuleset::fromNode) .collect(Collectors.toList()); List<String> rulesetIds = rulesets.stream() .map(EndpointRuleset::getServiceId) .collect(Collectors.toList()); if (rulesetIds.stream() .distinct() .count() != rulesets.size()) { throw new RuntimeException(String.format("Duplicate service ids discovered: %s", rulesets.stream() .map(EndpointRuleset::getServiceId) .sorted() .collect(Collectors.toList()))); } List<EndpointTestSuite> testSuites = testSuiteFiles.stream() .map(EndpointTestSuite::fromNode) .collect(Collectors.toList()); testSuites.stream() .filter(testSuite -> !rulesetIds.contains(testSuite.getService())) .forEach(bad -> { throw new RuntimeException("did not find service for " + bad.getService()); }); return rulesets.stream() .map(ruleset -> { List<EndpointTestSuite> matchingTestSuites = testSuites.stream() .filter(test -> test.getService() .equals(ruleset.getServiceId())) .collect(Collectors.toList()); return new RulesTestSuite(ruleset, matchingTestSuites); }); } private List<String> getManifestEntries(String path) { String absPath = RESOURCE_ROOT + "/" + path; try (BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(absPath)))) { List<String> entries = new ArrayList<>(); while (true) { String e = br.readLine(); if (e == null) { break; } entries.add(e); } return entries; } catch (IOException e) { throw new UncheckedIOException(e); } } private InputStream getResourceStream(String path) { String absPath = RESOURCE_ROOT + "/" + path; return getClass().getResourceAsStream(absPath); } private URL getResource(String path) { String absPath = RESOURCE_ROOT + "/" + path; return getClass().getResource(absPath); } public RulesTestSuite getTestSuite(String name) { return new RulesTestSuite(rulesetFromPath(name), Collections.singletonList(testSuiteFromPath(name))); } public List<String> getValidRules() { return getManifestEntries("valid-rules/manifest.txt"); } public URL validRulesetUrl(String name) { return getResource("valid-rules/" + name); } public URL testCaseUrl(String name) { return getResource("test-cases/" + name); } private EndpointRuleset rulesetFromPath(String name) { return EndpointRuleset.fromNode(JsonNode.parser().parse(Objects.requireNonNull(this.getClass() .getResourceAsStream(String.format("valid-rules/%s", name))))); } private EndpointTestSuite testSuiteFromPath(String name) { return EndpointTestSuite.fromNode(JsonNode.parser().parse(Objects.requireNonNull(this.getClass() .getResourceAsStream(String.format("test-cases/%s", name))))); } }
2,932
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/protocolrestjson/AsyncOperationCancelTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.protocolrestjson; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import io.reactivex.Flowable; import java.util.concurrent.CompletableFuture; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestjson.model.AllTypesResponse; import software.amazon.awssdk.services.protocolrestjson.model.EventStream; import software.amazon.awssdk.services.protocolrestjson.model.EventStreamOperationResponse; import software.amazon.awssdk.services.protocolrestjson.model.EventStreamOperationResponseHandler; import software.amazon.awssdk.services.protocolrestjson.model.InputEventStream; import software.amazon.awssdk.services.protocolrestjson.model.StreamingInputOperationResponse; import software.amazon.awssdk.services.protocolrestjson.model.StreamingOutputOperationResponse; /** * Test to ensure that cancelling the future returned for an async operation will cancel the future returned by the async HTTP client. */ @RunWith(MockitoJUnitRunner.class) public class AsyncOperationCancelTest { @Mock private SdkAsyncHttpClient mockHttpClient; private ProtocolRestJsonAsyncClient client; private CompletableFuture<Void> executeFuture; @Before public void setUp() { client = ProtocolRestJsonAsyncClient.builder() .region(Region.US_EAST_1) .credentialsProvider(StaticCredentialsProvider.create( AwsBasicCredentials.create("foo", "bar"))) .httpClient(mockHttpClient) .build(); executeFuture = new CompletableFuture<>(); when(mockHttpClient.execute(any())).thenReturn(executeFuture); } @Test public void testNonStreamingOperation() { CompletableFuture<AllTypesResponse> responseFuture = client.allTypes(r -> {}); responseFuture.cancel(true); assertThat(executeFuture.isCompletedExceptionally()).isTrue(); assertThat(executeFuture.isCancelled()).isTrue(); } @Test public void testStreamingOperation() { CompletableFuture<StreamingInputOperationResponse> responseFuture = client.streamingInputOperation(r -> {}, AsyncRequestBody.empty()); responseFuture.cancel(true); assertThat(executeFuture.isCompletedExceptionally()).isTrue(); assertThat(executeFuture.isCancelled()).isTrue(); } @Test public void testStreamingOutputOperation() { CompletableFuture<ResponseBytes<StreamingOutputOperationResponse>> responseFuture = client.streamingOutputOperation(r -> { }, AsyncResponseTransformer.toBytes()); responseFuture.cancel(true); assertThat(executeFuture.isCompletedExceptionally()).isTrue(); assertThat(executeFuture.isCancelled()).isTrue(); } @Test public void testEventStreamingOperation() throws InterruptedException { CompletableFuture<Void> responseFuture = client.eventStreamOperation(r -> {}, Flowable.just(InputEventStream.inputEventBuilder().build()), new EventStreamOperationResponseHandler() { @Override public void responseReceived(EventStreamOperationResponse response) { } @Override public void onEventStream(SdkPublisher<EventStream> publisher) { } @Override public void exceptionOccurred(Throwable throwable) { } @Override public void complete() { } }); responseFuture.cancel(true); assertThat(executeFuture.isCompletedExceptionally()).isTrue(); assertThat(executeFuture.isCancelled()).isTrue(); } }
2,933
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/protocolrestjson/ClientBuilderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.protocolrestjson; import static org.assertj.core.api.Assertions.assertThatNoException; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.regions.Region; public class ClientBuilderTest { @Test public void syncClient_buildWithDefaults_validationsSucceed() { ProtocolRestJsonClientBuilder builder = ProtocolRestJsonClient.builder(); builder.region(Region.US_WEST_2).credentialsProvider(AnonymousCredentialsProvider.create()); assertThatNoException().isThrownBy(builder::build); } @Test public void asyncClient_buildWithDefaults_validationsSucceed() { ProtocolRestJsonAsyncClientBuilder builder = ProtocolRestJsonAsyncClient.builder(); builder.region(Region.US_WEST_2).credentialsProvider(AnonymousCredentialsProvider.create()); assertThatNoException().isThrownBy(builder::build); } }
2,934
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/protocolrestjson/BlobUnmarshallingTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.protocolrestjson; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static org.assertj.core.api.Assertions.assertThat; import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; import com.github.tomakehurst.wiremock.junit5.WireMockTest; import java.net.URI; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolquery.ProtocolQueryAsyncClient; import software.amazon.awssdk.services.protocolquery.ProtocolQueryClient; import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlAsyncClient; import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlClient; /** * This verifies that blob types are unmarshalled correctly depending on where they exist. Specifically, we currently unmarshall * SdkBytes fields bound to the payload as empty if the service responds with no data and SdkBytes fields bound to a field as * null if the service does not specify that field. */ @WireMockTest public class BlobUnmarshallingTest { private static List<Arguments> testParameters() { List<Arguments> testCases = new ArrayList<>(); for (ClientType clientType : ClientType.values()) { for (Protocol protocol : Protocol.values()) { for (SdkBytesLocation value : SdkBytesLocation.values()) { for (ContentLength contentLength : ContentLength.values()) { testCases.add(Arguments.arguments(clientType, protocol, value, contentLength)); } } } } return testCases; } private enum ClientType { SYNC, ASYNC } private enum Protocol { JSON, XML, QUERY } private enum SdkBytesLocation { PAYLOAD, FIELD } private enum ContentLength { ZERO, CHUNKED_ZERO } @ParameterizedTest @MethodSource("testParameters") public void missingSdkBytes_unmarshalledCorrectly(ClientType clientType, Protocol protocol, SdkBytesLocation bytesLoc, ContentLength contentLength, WireMockRuntimeInfo wm) { if (contentLength == ContentLength.ZERO) { stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withHeader("Content-Length", "0").withBody(""))); } else if (contentLength == ContentLength.CHUNKED_ZERO) { stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody(""))); } SdkBytes serviceResult = callService(wm, clientType, protocol, bytesLoc); if (bytesLoc == SdkBytesLocation.PAYLOAD) { assertThat(serviceResult).isNotNull().isEqualTo(SdkBytes.fromUtf8String("")); } else if (bytesLoc == SdkBytesLocation.FIELD) { assertThat(serviceResult).isNull(); } } @ParameterizedTest @MethodSource("testParameters") public void presentSdkBytes_unmarshalledCorrectly(ClientType clientType, Protocol protocol, SdkBytesLocation bytesLoc, ContentLength contentLength, WireMockRuntimeInfo wm) { String responsePayload = presentSdkBytesResponse(protocol, bytesLoc); if (contentLength == ContentLength.ZERO) { stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200) .withHeader("Content-Length", Integer.toString(responsePayload.length())) .withBody(responsePayload))); } else if (contentLength == ContentLength.CHUNKED_ZERO) { stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody(responsePayload))); } assertThat(callService(wm, clientType, protocol, bytesLoc)).isEqualTo(SdkBytes.fromUtf8String("X")); } private String presentSdkBytesResponse(Protocol protocol, SdkBytesLocation bytesLoc) { switch (bytesLoc) { case PAYLOAD: return "X"; case FIELD: switch (protocol) { case JSON: return "{\"BlobArg\": \"WA==\"}"; case XML: return "<AllTypes><BlobArg>WA==</BlobArg></AllTypes>"; case QUERY: return "<AllTypesResponse><AllTypes><BlobArg>WA==</BlobArg></AllTypes></AllTypesResponse>"; default: throw new UnsupportedOperationException(); } default: throw new UnsupportedOperationException(); } } private SdkBytes callService(WireMockRuntimeInfo wm, ClientType clientType, Protocol protocol, SdkBytesLocation bytesLoc) { switch (clientType) { case SYNC: return syncCallService(wm, protocol, bytesLoc); case ASYNC: return asyncCallService(wm, protocol, bytesLoc); default: throw new UnsupportedOperationException(); } } private SdkBytes syncCallService(WireMockRuntimeInfo wm, Protocol protocol, SdkBytesLocation bytesLoc) { switch (protocol) { case JSON: return syncJsonCallService(wm, bytesLoc); case XML: return syncXmlCallService(wm, bytesLoc); case QUERY: return syncQueryCallService(wm, bytesLoc); default: throw new UnsupportedOperationException(); } } private SdkBytes asyncCallService(WireMockRuntimeInfo wm, Protocol protocol, SdkBytesLocation bytesLoc) { switch (protocol) { case JSON: return asyncJsonCallService(wm, bytesLoc); case XML: return asyncXmlCallService(wm, bytesLoc); case QUERY: return asyncQueryCallService(wm, bytesLoc); default: throw new UnsupportedOperationException(); } } private SdkBytes asyncQueryCallService(WireMockRuntimeInfo wm, SdkBytesLocation bytesLoc) { ProtocolQueryAsyncClient client = ProtocolQueryAsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create(wm.getHttpBaseUrl())) .build(); switch (bytesLoc) { case PAYLOAD: return client.operationWithExplicitPayloadBlob(r -> {}).join().payloadMember(); case FIELD: return client.allTypes(r -> {}).join().blobArg(); default: throw new UnsupportedOperationException(); } } private SdkBytes asyncXmlCallService(WireMockRuntimeInfo wm, SdkBytesLocation bytesLoc) { ProtocolRestXmlAsyncClient client = ProtocolRestXmlAsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create(wm.getHttpBaseUrl())) .build(); switch (bytesLoc) { case PAYLOAD: return client.operationWithExplicitPayloadBlob(r -> {}).join().payloadMember(); case FIELD: return client.allTypes(r -> {}).join().blobArg(); default: throw new UnsupportedOperationException(); } } private SdkBytes asyncJsonCallService(WireMockRuntimeInfo wm, SdkBytesLocation bytesLoc) { ProtocolRestJsonAsyncClient client = ProtocolRestJsonAsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create(wm.getHttpBaseUrl())) .build(); switch (bytesLoc) { case PAYLOAD: return client.operationWithExplicitPayloadBlob(r -> {}).join().payloadMember(); case FIELD: return client.allTypes(r -> {}).join().blobArg(); default: throw new UnsupportedOperationException(); } } private SdkBytes syncQueryCallService(WireMockRuntimeInfo wm, SdkBytesLocation bytesLoc) { ProtocolQueryClient client = ProtocolQueryClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create(wm.getHttpBaseUrl())) .build(); switch (bytesLoc) { case PAYLOAD: return client.operationWithExplicitPayloadBlob(r -> {}).payloadMember(); case FIELD: return client.allTypes(r -> {}).blobArg(); default: throw new UnsupportedOperationException(); } } private SdkBytes syncXmlCallService(WireMockRuntimeInfo wm, SdkBytesLocation bytesLoc) { ProtocolRestXmlClient client = ProtocolRestXmlClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create(wm.getHttpBaseUrl())) .build(); switch (bytesLoc) { case PAYLOAD: return client.operationWithExplicitPayloadBlob(r -> {}).payloadMember(); case FIELD: return client.allTypes(r -> {}).blobArg(); default: throw new UnsupportedOperationException(); } } private SdkBytes syncJsonCallService(WireMockRuntimeInfo wm, SdkBytesLocation bytesLoc) { ProtocolRestJsonClient client = ProtocolRestJsonClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create(wm.getHttpBaseUrl())) .build(); switch (bytesLoc) { case PAYLOAD: return client.operationWithExplicitPayloadBlob(r -> {}).payloadMember(); case FIELD: return client.allTypes(r -> {}).blobArg(); default: throw new UnsupportedOperationException(); } } }
2,935
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/protocolrestjson/HashCodeEqualsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.protocolrestjson; import static org.assertj.core.api.Assertions.assertThat; import java.time.Duration; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.awscore.AwsResponseMetadata; import software.amazon.awssdk.awscore.DefaultAwsResponseMetadata; import software.amazon.awssdk.core.ApiName; import software.amazon.awssdk.services.protocolrestjson.model.AllTypesRequest; import software.amazon.awssdk.services.protocolrestjson.model.AllTypesResponse; import software.amazon.awssdk.services.protocolrestjson.model.ProtocolRestJsonResponseMetadata; public class HashCodeEqualsTest { private static AllTypesRequest.Builder requestBuilder; private static AllTypesResponse.Builder responseBuilder; @BeforeAll public static void setUp() { requestBuilder = AllTypesRequest.builder() .stringMember("foo") .integerMember(123) .booleanMember(true) .floatMember(123.0f) .doubleMember(123.9) .longMember(123L) .simpleList("so simple") .overrideConfiguration(b -> b.apiCallTimeout(Duration.ofMinutes(1)) .putHeader("test", "test") .apiCallAttemptTimeout(Duration.ofMillis(200)) .addApiName(ApiName.builder() .name("test") .version("version") .build()) .credentialsProvider(() -> AwsBasicCredentials.create("tests", "safda")) ); Map<String, String> metadata = new HashMap<>(); AwsResponseMetadata responseMetadata = ProtocolRestJsonResponseMetadata.create(DefaultAwsResponseMetadata.create(metadata)); responseBuilder = AllTypesResponse.builder() .stringMember("foo") .integerMember(123) .booleanMember(true) .floatMember(123.0f) .doubleMember(123.9) .longMember(123L) .simpleList("so simple"); } @Test public void request_sameFields_shouldEqual() { AllTypesRequest request = requestBuilder.build(); AllTypesRequest anotherRequest = requestBuilder.build(); assertThat(request).isEqualTo(anotherRequest); assertThat(request.hashCode()).isEqualTo(anotherRequest.hashCode()); } @Test public void request_differentOverrideConfiguration_shouldNotEqual_sdkFieldsShouldEqual() { AllTypesRequest anotherRequest = requestBuilder.build(); AllTypesRequest request = requestBuilder.overrideConfiguration(b -> b.credentialsProvider( () -> AwsBasicCredentials.create("TEST", "test") )).build(); assertThat(request).isNotEqualTo(anotherRequest); assertThat(request.equalsBySdkFields(anotherRequest)).isTrue(); assertThat(request.hashCode()).isNotEqualTo(anotherRequest.hashCode()); } @Test public void response_sameFields_shouldEqual() { AllTypesResponse response = responseBuilder.build(); AllTypesResponse anotherResponse = responseBuilder.build(); assertThat(response).isEqualTo(anotherResponse); assertThat(response.hashCode()).isEqualTo(anotherResponse.hashCode()); } @Test public void response_differentResponseMetadata_shouldNotEqual_sdkFieldsShouldEqual() { AllTypesResponse anotherResponse = responseBuilder.build(); Map<String, String> metadata = new HashMap<>(); metadata.put("foo", "bar"); AwsResponseMetadata responseMetadata = ProtocolRestJsonResponseMetadata.create(DefaultAwsResponseMetadata.create(metadata)); AllTypesResponse response = (AllTypesResponse) responseBuilder.responseMetadata(responseMetadata).build(); assertThat(response.equalsBySdkFields(anotherResponse)).isTrue(); assertThat(response).isNotEqualTo(anotherResponse); assertThat(response.hashCode()).isNotEqualTo(anotherResponse.hashCode()); } }
2,936
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/protocolrestjson/ServiceRequestRequiredValidationMarshallingTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.protocolrestjson; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatNoException; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.lang.reflect.Field; import java.net.URI; import java.util.Collection; import java.util.HashMap; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.protocols.json.AwsJsonProtocolFactory; import software.amazon.awssdk.services.protocolrestjson.model.NestedQueryParameterOperation; import software.amazon.awssdk.services.protocolrestjson.model.QueryParameterOperationRequest; import software.amazon.awssdk.services.protocolrestjson.transform.QueryParameterOperationRequestMarshaller; class ServiceRequestRequiredValidationMarshallingTest { private static QueryParameterOperationRequestMarshaller marshaller; private static AwsJsonProtocolFactory awsJsonProtocolFactory; @BeforeAll static void setup() { awsJsonProtocolFactory = AwsJsonProtocolFactory .builder() .clientConfiguration(SdkClientConfiguration .builder() .option(SdkClientOption.ENDPOINT, URI.create("http://localhost")) .build()) .build(); marshaller = new QueryParameterOperationRequestMarshaller(awsJsonProtocolFactory); } @Test void marshal_notMissingRequiredMembers_doesNotThrowException() { QueryParameterOperationRequest request = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember("myHeader") .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()) .build(); assertThatNoException().isThrownBy(() -> marshaller.marshall(request)); } @Test void marshal_missingRequiredMemberAtQueryParameterLocation_throwsException() { QueryParameterOperationRequest request = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember("myHeader") .queryParamOne(null) .queryParamTwo("myParamTwo") .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()) .build(); assertThatThrownBy(() -> marshaller.marshall(request)) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Parameter 'QueryParamOne' must not be null"); } @Test void marshal_missingRequiredMemberListAtQueryParameterLocation_defaultsToEmptyCollectionAndDoesNotThrowException() { QueryParameterOperationRequest request = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember("myHeader") .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .requiredListQueryParams((Collection<Integer>) null) .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()) .build(); assertThat(request.requiredListQueryParams()).isEmpty(); assertThatNoException().isThrownBy(() -> marshaller.marshall(request)); } @Test void marshal_forceMissingRequiredMemberListAtQueryParameterLocation_throwsException() { QueryParameterOperationRequest.Builder builder = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember("myHeader") .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()); forceNull(builder, "requiredListQueryParams"); QueryParameterOperationRequest request = builder.build(); assertThat(request.requiredListQueryParams()).isNull(); assertThatThrownBy(() -> marshaller.marshall(request)) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Parameter 'RequiredListQueryParams' must not be null"); } @Test void marshal_missingRequiredMemberOfListAtQueryParameterLocation_doesNotThrowException() { QueryParameterOperationRequest request = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember("myHeader") .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .requiredListQueryParams(1, null, 3) .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()) .build(); assertThatNoException().isThrownBy(() -> marshaller.marshall(request)); } @Test void marshal_missingNonRequiredMemberListAtQueryParameterLocation_defaultsToEmptyCollectionAndDoesNotThrowException() { QueryParameterOperationRequest request = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember("myHeader") .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .optionalListQueryParams((Collection<String>) null) .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()) .build(); assertThat(request.optionalListQueryParams()).isEmpty(); assertThatNoException().isThrownBy(() -> marshaller.marshall(request)); } @Test void marshal_forceMissingNonRequiredMemberListAtQueryParameterLocation_doesNotThrowException() { QueryParameterOperationRequest.Builder builder = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember("myHeader") .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()); forceNull(builder, "optionalListQueryParams"); QueryParameterOperationRequest request = builder.build(); assertThat(request.optionalListQueryParams()).isNull(); assertThatNoException().isThrownBy(() -> marshaller.marshall(request)); } @Test void marshal_missingNonRequiredMemberOfListAtQueryParameterLocation_doesNotThrowException() { QueryParameterOperationRequest request = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember("myHeader") .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .optionalListQueryParams("1", null, "3") .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()) .build(); assertThatNoException().isThrownBy(() -> marshaller.marshall(request)); } @Test void marshal_missingRequiredMemberMapAtQueryParameterLocation_defaultsToEmptyCollectionAndDoesNotThrowException() { QueryParameterOperationRequest request = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember("myHeader") .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .requiredMapQueryParams(null) .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()) .build(); assertThat(request.requiredMapQueryParams()).isEmpty(); assertThatNoException().isThrownBy(() -> marshaller.marshall(request)); } @Test void marshal_forceMissingRequiredMemberMaoAtQueryParameterLocation_throwsException() { QueryParameterOperationRequest.Builder builder = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember("myHeader") .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()); forceNull(builder, "requiredMapQueryParams"); QueryParameterOperationRequest request = builder.build(); assertThat(request.requiredMapQueryParams()).isNull(); assertThatThrownBy(() -> marshaller.marshall(request)) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Parameter 'RequiredMapQueryParams' must not be null"); } @Test void marshal_missingRequiredMemberOfMapAtQueryParameterLocation_doesNotThrowException() { QueryParameterOperationRequest request = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember("myHeader") .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .requiredListQueryParams() .optionalListQueryParams() .requiredMapQueryParams(Stream.of(new String[][] {{"key1", "value1"}, {"key2", null}}) .collect(HashMap::new, (map, array) -> map.put(array[0], array[1]), HashMap::putAll)) .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()) .build(); assertThatNoException().isThrownBy(() -> marshaller.marshall(request)); } @Test void marshal_missingRequiredMemberAtUriLocation_throwsException() { QueryParameterOperationRequest request = QueryParameterOperationRequest .builder() .pathParam(null) .stringHeaderMember("myHeader") .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()) .build(); assertThatThrownBy(() -> marshaller.marshall(request)) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Parameter 'PathParam' must not be null"); } @Test void marshal_missingRequiredMemberAtHeaderLocation_throwsException() { QueryParameterOperationRequest request = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember(null) .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne("myNestedParamOne") .queryParamTwo("myNestedParamTwo") .build()) .build(); assertThatThrownBy(() -> marshaller.marshall(request)) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Parameter 'x-amz-header-string' must not be null"); } @Test void marshal_missingRequiredMemberAtQueryParameterLocationOfNestedShape_throwsException() { QueryParameterOperationRequest request = QueryParameterOperationRequest .builder() .pathParam("myPathParam") .stringHeaderMember("myHeader") .queryParamOne("myParamOne") .queryParamTwo("myParamTwo") .nestedQueryParameterOperation(NestedQueryParameterOperation .builder() .queryParamOne(null) .queryParamTwo("myNestedParamTwo") .build()) .build(); assertThatThrownBy(() -> marshaller.marshall(request)) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Parameter 'QueryParamOne' must not be null"); } private static void forceNull(QueryParameterOperationRequest.Builder builder, String fieldName) { try { Field field = builder.getClass().getDeclaredField(fieldName); boolean originallyAccessible = field.isAccessible(); if (!originallyAccessible) { field.setAccessible(true); } field.set(builder, null); if (!originallyAccessible) { field.setAccessible(false); } } catch (NoSuchFieldException|IllegalAccessException e) { throw new RuntimeException(e); } } }
2,937
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/protocolrestjson/StringPayloadUnmarshallingTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.protocolrestjson; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static org.assertj.core.api.Assertions.assertThat; import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; import com.github.tomakehurst.wiremock.junit5.WireMockTest; import java.net.URI; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlAsyncClient; import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlClient; @WireMockTest public class StringPayloadUnmarshallingTest { private static final String TEST_PAYLOAD = "X"; private static List<Arguments> testParameters() { List<Arguments> testCases = new ArrayList<>(); for (ClientType clientType : ClientType.values()) { for (Protocol protocol : Protocol.values()) { for (StringLocation value : StringLocation.values()) { for (ContentLength contentLength : ContentLength.values()) { testCases.add(Arguments.arguments(clientType, protocol, value, contentLength)); } } } } return testCases; } private enum ClientType { SYNC, ASYNC } private enum Protocol { JSON, XML } private enum StringLocation { PAYLOAD, FIELD } private enum ContentLength { ZERO, NOT_PRESENT } @ParameterizedTest @MethodSource("testParameters") public void missingStringPayload_unmarshalledCorrectly(ClientType clientType, Protocol protocol, StringLocation stringLoc, ContentLength contentLength, WireMockRuntimeInfo wm) { if (contentLength == ContentLength.ZERO) { stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withHeader("Content-Length", "0").withBody(""))); } else if (contentLength == ContentLength.NOT_PRESENT) { stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody(""))); } String serviceResult = callService(wm, clientType, protocol, stringLoc); if (stringLoc == StringLocation.PAYLOAD) { assertThat(serviceResult).isNotNull().isEqualTo(""); } else if (stringLoc == StringLocation.FIELD) { assertThat(serviceResult).isNull(); } } @ParameterizedTest @MethodSource("testParameters") public void presentStringPayload_unmarshalledCorrectly(ClientType clientType, Protocol protocol, StringLocation stringLoc, ContentLength contentLength, WireMockRuntimeInfo wm) { String responsePayload = presentStringResponse(protocol, stringLoc); if (contentLength == ContentLength.ZERO) { stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200) .withHeader("Content-Length", Integer.toString(responsePayload.length())) .withBody(responsePayload))); } else if (contentLength == ContentLength.NOT_PRESENT) { stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200).withBody(responsePayload))); } assertThat(callService(wm, clientType, protocol, stringLoc)).isEqualTo(TEST_PAYLOAD); } private String presentStringResponse(Protocol protocol, StringLocation stringLoc) { switch (stringLoc) { case PAYLOAD: return TEST_PAYLOAD; case FIELD: switch (protocol) { case JSON: return "{\"StringMember\": \"X\"}"; case XML: return "<AllTypes><StringMember>X</StringMember></AllTypes>"; default: throw new UnsupportedOperationException(); } default: throw new UnsupportedOperationException(); } } private String callService(WireMockRuntimeInfo wm, ClientType clientType, Protocol protocol, StringLocation stringLoc) { switch (clientType) { case SYNC: return syncCallService(wm, protocol, stringLoc); case ASYNC: return asyncCallService(wm, protocol, stringLoc); default: throw new UnsupportedOperationException(); } } private String syncCallService(WireMockRuntimeInfo wm, Protocol protocol, StringLocation stringLoc) { switch (protocol) { case JSON: return syncJsonCallService(wm, stringLoc); case XML: return syncXmlCallService(wm, stringLoc); default: throw new UnsupportedOperationException(); } } private String asyncCallService(WireMockRuntimeInfo wm, Protocol protocol, StringLocation stringLoc) { switch (protocol) { case JSON: return asyncJsonCallService(wm, stringLoc); case XML: return asyncXmlCallService(wm, stringLoc); default: throw new UnsupportedOperationException(); } } private String syncJsonCallService(WireMockRuntimeInfo wm, StringLocation stringLoc) { ProtocolRestJsonClient client = ProtocolRestJsonClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create(wm.getHttpBaseUrl())) .build(); switch (stringLoc) { case PAYLOAD: return client.operationWithExplicitPayloadString(r -> {}).payloadMember(); case FIELD: return client.allTypes(r -> {}).stringMember(); default: throw new UnsupportedOperationException(); } } private String asyncJsonCallService(WireMockRuntimeInfo wm, StringLocation stringLoc) { ProtocolRestJsonAsyncClient client = ProtocolRestJsonAsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create(wm.getHttpBaseUrl())) .build(); switch (stringLoc) { case PAYLOAD: return client.operationWithExplicitPayloadString(r -> {}).join().payloadMember(); case FIELD: return client.allTypes(r -> {}).join().stringMember(); default: throw new UnsupportedOperationException(); } } private String syncXmlCallService(WireMockRuntimeInfo wm, StringLocation stringLoc) { ProtocolRestXmlClient client = ProtocolRestXmlClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create(wm.getHttpBaseUrl())) .build(); switch (stringLoc) { case PAYLOAD: return client.operationWithExplicitPayloadString(r -> {}).payloadMember(); case FIELD: return client.allTypes(r -> {}).stringMember(); default: throw new UnsupportedOperationException(); } } private String asyncXmlCallService(WireMockRuntimeInfo wm, StringLocation stringLoc) { ProtocolRestXmlAsyncClient client = ProtocolRestXmlAsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create(wm.getHttpBaseUrl())) .build(); switch (stringLoc) { case PAYLOAD: return client.operationWithExplicitPayloadString(r -> {}).join().payloadMember(); case FIELD: return client.allTypes(r -> {}).join().stringMember(); default: throw new UnsupportedOperationException(); } } }
2,938
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/protocolrestjson
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/protocolrestjson/model/GetValueForFieldTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.protocolrestjson.model; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import org.junit.jupiter.api.Test; /** * Tests for the generated {@code getValueForField} methods on model objects. */ public class GetValueForFieldTest { @Test public void nullMemberShouldReturnEmptyOptional() { AllTypesRequest request = AllTypesRequest.builder().build(); assertThat(request.getValueForField("StringMember", String.class).isPresent(), is(equalTo(false))); } @Test public void setMemberShouldReturnNonEmptyOptional() { AllTypesRequest request = AllTypesRequest.builder() .stringMember("hello, world") .build(); assertThat(request.getValueForField("StringMember", String.class).get(), is(equalTo("hello, world"))); } }
2,939
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/protocolrestjson
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/protocolrestjson/model/MapCopierTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.protocolrestjson.model; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.util.DefaultSdkAutoConstructMap; import software.amazon.awssdk.core.util.SdkAutoConstructMap; /** * Tests for generated map member copiers. */ public class MapCopierTest { @Test public void nullParamsAreCopiedAsAutoConstructedMap() { assertThat(MapOfStringToStringCopier.copy(null)).isInstanceOf(SdkAutoConstructMap.class); } @Test public void preservesAutoConstructedMapInput() { assertThat(MapOfStringToStringCopier.copy(DefaultSdkAutoConstructMap.getInstance())).isInstanceOf(SdkAutoConstructMap.class); } @Test public void explicitlyEmptyMapsAreNotCopiedAsAutoConstructed() { assertThat(MapOfStringToStringCopier.copy(new HashMap<>())).isNotInstanceOf(SdkAutoConstructMap.class); } @Test public void nullValuesInMapsAreCopied() { Map<String, String> map = new HashMap<>(); map.put("test", null); assertThat(MapOfStringToStringCopier.copy(map)).isEqualTo(map); } @Test public void modificationsInOriginalMapDoNotReflectInCopiedMap() { Map<String, String> map = new HashMap<>(); Map<String, String> copiedMap = MapOfStringToStringCopier.copy(map); map.put("test", null); assertThat(copiedMap).isEmpty(); } @Test public void copiedMapIsImmutable() { assertThatThrownBy(() -> MapOfStringToStringCopier.copy(new HashMap<>()).put("test", "a")).isInstanceOf(UnsupportedOperationException.class); } @Test public void unknownEnumKeyNotAddedToCopiedMap() { Map<String, String> mapOfEnumToEnum = new HashMap<>(); mapOfEnumToEnum.put("foo", "bar"); Map<EnumType, EnumType> copy = MapOfEnumToEnumCopier.copyStringToEnum(mapOfEnumToEnum); assertThat(copy).isEmpty(); } @Test public void knownEnumKeyAddedToCopiedMap() { Map<String, String> mapOfEnumToEnum = new HashMap<>(); mapOfEnumToEnum.put(EnumType.ENUM_VALUE1.toString(), "bar"); Map<EnumType, EnumType> copy = MapOfEnumToEnumCopier.copyStringToEnum(mapOfEnumToEnum); assertThat(copy).hasSize(1); } }
2,940
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/protocolrestjson
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/protocolrestjson/model/ModelBuilderMapMemberTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.protocolrestjson.model; import static org.assertj.core.api.Assertions.assertThat; import java.util.HashMap; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.util.SdkAutoConstructMap; /** * Test for verifying map member behavior for model builders. */ public class ModelBuilderMapMemberTest { @Test public void defaultConstructedModelsHaveInitialValue() { AllTypesRequest request = AllTypesRequest.builder().build(); assertThat(request.mapOfStringToString()).isInstanceOf(SdkAutoConstructMap.class); } @Test public void nullSetterCreatesSdkAutoConstructedMap() { AllTypesRequest request = AllTypesRequest.builder() .mapOfStringToString(null) .build(); assertThat(request.mapOfStringToString()).isInstanceOf(SdkAutoConstructMap.class); } @Test public void modelToBuilderRoundTripPreservesAutoConstructedMaps() { AllTypesRequest request = AllTypesRequest.builder().build(); AllTypesRequest roundTrip = request.toBuilder().build(); assertThat(roundTrip.mapOfStringToString()).isInstanceOf(SdkAutoConstructMap.class); } @Test public void modelToBuilderRoundTripPreservesExplicitEmptyMaps() { AllTypesRequest request = AllTypesRequest.builder() .mapOfStringToString(new HashMap<>()) .build(); AllTypesRequest roundTrip = request.toBuilder().build(); assertThat(roundTrip.mapOfStringToString()).isNotInstanceOf(SdkAutoConstructMap.class); } }
2,941
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/protocolrestjson
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/protocolrestjson/model/ListCopierTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.protocolrestjson.model; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.util.DefaultSdkAutoConstructList; import software.amazon.awssdk.core.util.SdkAutoConstructList; /** * Tests for generated list member copiers. */ public class ListCopierTest { @Test public void nullParamsAreCopiedAsAutoConstructedList() { assertThat(ListOfStringsCopier.copy(null)).isInstanceOf(SdkAutoConstructList.class); } @Test public void preservesAutoConstructedListInput() { assertThat(ListOfStringsCopier.copy(DefaultSdkAutoConstructList.getInstance())).isInstanceOf(SdkAutoConstructList.class); } @Test public void explicitlyEmptyListsAreNotCopiedAsAutoConstructed() { assertThat(ListOfStringsCopier.copy(new ArrayList<>())).isNotInstanceOf(SdkAutoConstructList.class); } }
2,942
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/protocolrestjson
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/protocolrestjson/model/ModelBuilderListMemberTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.protocolrestjson.model; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.Collection; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.util.SdkAutoConstructList; /** * Test for verifying list member behavior for model builders. */ public class ModelBuilderListMemberTest { @Test public void defaultConstructedModelsHaveInitialValue() { AllTypesRequest request = AllTypesRequest.builder().build(); assertThat(request.listOfEnumsAsStrings()).isInstanceOf(SdkAutoConstructList.class); } @Test public void nullSetterCreatesSdkAutoConstructedList() { AllTypesRequest request = AllTypesRequest.builder() .listOfEnumsWithStrings((Collection<String>) null) .build(); assertThat(request.listOfEnumsAsStrings()).isInstanceOf(SdkAutoConstructList.class); } @Test public void modelToBuilderRoundTripPreservesAutoConstructedLists() { AllTypesRequest request = AllTypesRequest.builder().build(); AllTypesRequest roundTrip = request.toBuilder().build(); assertThat(roundTrip.listOfEnumsAsStrings()).isInstanceOf(SdkAutoConstructList.class); } @Test public void modelToBuilderRoundTripPreservesExplicitEmptyLists() { AllTypesRequest request = AllTypesRequest.builder() .listOfEnums(new ArrayList<>()) .build(); AllTypesRequest roundTrip = request.toBuilder().build(); assertThat(roundTrip.listOfEnumsAsStrings()).isNotInstanceOf(SdkAutoConstructList.class); } }
2,943
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/documenttype/DocumentTypeTest.java
package software.amazon.awssdk.services.documenttype; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.awscore.client.builder.AwsClientBuilder; import software.amazon.awssdk.awscore.client.builder.AwsSyncClientBuilder; import software.amazon.awssdk.core.SdkNumber; import software.amazon.awssdk.core.document.Document; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.ExecutableHttpRequest; import software.amazon.awssdk.http.HttpExecuteRequest; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.documenttypejson.DocumentTypeJsonClient; import software.amazon.awssdk.services.documenttypejson.model.AcceptHeader; import software.amazon.awssdk.services.documenttypejson.model.AllTypesResponse; import software.amazon.awssdk.services.documenttypejson.model.AllTypesWithPayloadResponse; import software.amazon.awssdk.services.documenttypejson.model.ExplicitRecursivePayloadResponse; import software.amazon.awssdk.services.documenttypejson.model.ImplicitNestedDocumentPayloadResponse; import software.amazon.awssdk.services.documenttypejson.model.ImplicitOnlyDocumentPayloadResponse; import software.amazon.awssdk.services.documenttypejson.model.ImplicitRecursivePayloadResponse; import software.amazon.awssdk.services.documenttypejson.model.NestedDocumentPayload; import software.amazon.awssdk.services.documenttypejson.model.RecursiveStructType; import software.amazon.awssdk.services.documenttypejson.model.StringPayload; import software.amazon.awssdk.services.documenttypejson.model.WithExplicitDocumentPayloadResponse; import software.amazon.awssdk.utils.StringInputStream; import software.amazon.awssdk.utils.builder.SdkBuilder; public class DocumentTypeTest { public static final Document STRING_DOCUMENT = Document.fromString("docsString"); @Rule public WireMockRule wireMock = new WireMockRule(0); private DocumentTypeJsonClient jsonClient; private SdkHttpClient httpClient; @Before public void setup() throws IOException { httpClient = Mockito.mock(SdkHttpClient.class); jsonClient = initializeSync(DocumentTypeJsonClient.builder()).build(); } private void setUpStub(String contentBody) { InputStream content = new StringInputStream(contentBody); SdkHttpFullResponse successfulHttpResponse = SdkHttpResponse.builder() .statusCode(200) .putHeader("accept", AcceptHeader.IMAGE_JPEG.toString()) .putHeader("Content-Length", String.valueOf(contentBody.length())) .build(); ExecutableHttpRequest request = Mockito.mock(ExecutableHttpRequest.class); try { Mockito.when(request.call()).thenReturn(HttpExecuteResponse.builder() .responseBody(AbortableInputStream.create(content)) .response(successfulHttpResponse) .build()); } catch (IOException e) { e.printStackTrace(); } Mockito.when(httpClient.prepareRequest(any())).thenReturn(request); } @Test public void implicitPayloadEmptyRequestMarshallingAndUnMarshalling() { setUpStub("{}"); AllTypesResponse allTypesResponse = jsonClient.allTypes(SdkBuilder::build); String syncRequest = getSyncRequestBody(); assertThat(syncRequest).isEqualTo("{}"); assertThat(allTypesResponse.myDocument()).isNull(); } @Test public void implicitPayloadNonEmptyRequestMarshallingAndUnMarshalling() { setUpStub("{\"StringMember\":\"stringMember\",\"IntegerMember\":3,\"MyDocument\":\"stringDocument\"}"); AllTypesResponse allTypesResponse = jsonClient.allTypes( c -> c.stringMember("stringMember").integerMember(3)); String syncRequest = getSyncRequestBody(); assertThat(syncRequest).isEqualTo("{\"StringMember\":\"stringMember\",\"IntegerMember\":3}"); assertThat(allTypesResponse.stringMember()).isEqualTo("stringMember"); assertThat(allTypesResponse.integerMember()).isEqualTo(3); assertThat(allTypesResponse.myDocument()).isEqualTo(Document.fromString("stringDocument")); } @Test public void explicitPayloadEmptyRequestMarshallingAndUnMarshalling() { setUpStub("{}"); AllTypesWithPayloadResponse allTypesWithPayloadResponse = jsonClient.allTypesWithPayload(c -> c.stringPayload(StringPayload.builder().build())); String syncRequest = getSyncRequestBody(); assertThat(syncRequest).isEqualTo("{}"); assertThat(allTypesWithPayloadResponse.accept()).isEqualTo(AcceptHeader.IMAGE_JPEG); assertThat(allTypesWithPayloadResponse.stringPayload().stringMember()).isNull(); } @Test public void explicitPayloadRequestMarshallingAndUnMarshalling() { String jsonFormat = "{\"StringMember\":\"payloadMember\"}"; setUpStub(jsonFormat); AllTypesWithPayloadResponse payloadMember = jsonClient.allTypesWithPayload( c -> c.stringPayload(StringPayload.builder().stringMember("payloadMember").build()).build()); String syncRequest = getSyncRequestBody(); assertThat(syncRequest).isEqualTo(jsonFormat); assertThat(payloadMember.accept()).isEqualTo(AcceptHeader.IMAGE_JPEG); assertThat(payloadMember.stringPayload().stringMember()).isEqualTo("payloadMember"); } @Test public void implicitNestedPayloadWithSimpleDocument() { String jsonFormat = "{\"NestedDocumentPayload\":{\"StringMember\":\"stringMember\"," + "\"MyDocument\":\"stringDoc\"}}"; setUpStub(jsonFormat); ImplicitNestedDocumentPayloadResponse implicitNestedDocumentPayload = jsonClient.implicitNestedDocumentPayload( c -> c.nestedDocumentPayload( NestedDocumentPayload.builder() .myDocument(Document.fromString("stringDoc")) .stringMember("stringMember") .build()).build()); String syncRequest = getSyncRequestBody(); assertThat(syncRequest).isEqualTo(jsonFormat); assertThat(implicitNestedDocumentPayload.nestedDocumentPayload().myDocument()).isEqualTo(Document.fromString("stringDoc" )); assertThat(implicitNestedDocumentPayload.nestedDocumentPayload().stringMember()).isEqualTo("stringMember"); assertThat(implicitNestedDocumentPayload.accept()).isEqualTo(AcceptHeader.IMAGE_JPEG); } @Test public void implicitNestedPayloadWithDocumentMap() { String jsonFormat = "{\"" + "NestedDocumentPayload\":" + "{\"StringMember\":\"stringMember\"," + "\"MyDocument\":" + "{\"number\":2,\"stringValue\":\"string\"}}" + "}"; setUpStub(jsonFormat); Document document = Document.mapBuilder() .putNumber("number", SdkNumber.fromString("2")) .putString("stringValue", "string").build(); ImplicitNestedDocumentPayloadResponse response = jsonClient.implicitNestedDocumentPayload( c -> c.nestedDocumentPayload( NestedDocumentPayload.builder() .myDocument(document) .stringMember("stringMember").build()) .build()); String syncRequest = getSyncRequestBody(); assertThat(syncRequest).isEqualTo(jsonFormat); assertThat(response.nestedDocumentPayload().stringMember()).isEqualTo("stringMember"); assertThat(response.nestedDocumentPayload().myDocument()).isEqualTo(document); assertThat(response.accept()).isEqualTo(AcceptHeader.IMAGE_JPEG); } @Test public void explicitDocumentOnlyStringPayload() { String jsonFormat = "{\"MyDocument\":\"docsString\"}"; setUpStub(jsonFormat); WithExplicitDocumentPayloadResponse response = jsonClient.withExplicitDocumentPayload(c -> c.myDocument(STRING_DOCUMENT).accept(AcceptHeader.IMAGE_JPEG)); String syncRequest = getSyncRequestBody(); assertThat(syncRequest).isEqualTo(jsonFormat); SdkHttpRequest sdkHttpRequest = getSyncRequest(); assertThat(sdkHttpRequest.firstMatchingHeader("accept").get()).contains(AcceptHeader.IMAGE_JPEG.toString()); assertThat(response.myDocument()).isEqualTo(STRING_DOCUMENT); assertThat(response.myDocument().isString()).isTrue(); } @Test public void explicitDocumentOnlyListPayload() { String jsonFormat = "{\"MyDocument\":[{\"key\":\"value\"},null,\"string\",3,false]}"; setUpStub(jsonFormat); Document document = Document.listBuilder() .addDocument(Document.mapBuilder().putString("key", "value").build()) .addNull().addString("string").addNumber(3).addBoolean(false).build(); WithExplicitDocumentPayloadResponse response = jsonClient.withExplicitDocumentPayload(c -> c.myDocument(document).accept(AcceptHeader.IMAGE_JPEG)); String syncRequest = getSyncRequestBody(); assertThat(syncRequest).isEqualTo(jsonFormat); SdkHttpRequest sdkHttpRequest = getSyncRequest(); assertThat(sdkHttpRequest.firstMatchingHeader("accept").get()).contains(AcceptHeader.IMAGE_JPEG.toString()); assertThat(response.myDocument()).isEqualTo(document); assertThat(response.myDocument().isList()).isTrue(); } @Test public void explicitDocumentOnlyNullDocumentPayload() { String jsonFormat = "{\"MyDocument\":null}"; setUpStub(jsonFormat); WithExplicitDocumentPayloadResponse response = jsonClient.withExplicitDocumentPayload(c -> c.myDocument(Document.fromNull()).accept(AcceptHeader.IMAGE_JPEG)); String syncRequest = getSyncRequestBody(); assertThat(syncRequest).isEqualTo(jsonFormat); SdkHttpRequest sdkHttpRequest = getSyncRequest(); assertThat(sdkHttpRequest.firstMatchingHeader("accept").get()).contains(AcceptHeader.IMAGE_JPEG.toString()); assertThat(response.myDocument()).isNotNull(); assertThat(response.myDocument().isNull()).isTrue(); } @Test public void explicitDocumentOnlyNullPayload() { String jsonFormat = "null"; setUpStub(jsonFormat); WithExplicitDocumentPayloadResponse response = jsonClient.withExplicitDocumentPayload(c -> c.myDocument(null).accept(AcceptHeader.IMAGE_JPEG)); String syncRequest = getSyncRequestBody(); assertThat(syncRequest).isEqualTo("{}"); SdkHttpRequest sdkHttpRequest = getSyncRequest(); assertThat(sdkHttpRequest.firstMatchingHeader("accept").get()).contains(AcceptHeader.IMAGE_JPEG.toString()); assertThat(response.myDocument()).isNull(); } @Test public void explicitDocumentOnlyEmptyPayload() { String jsonFormat = ""; setUpStub(jsonFormat); WithExplicitDocumentPayloadResponse response = jsonClient.withExplicitDocumentPayload(c -> c.myDocument(null).accept(AcceptHeader.IMAGE_JPEG)); String syncRequest = getSyncRequestBody(); assertThat(syncRequest).isEqualTo("{}"); SdkHttpRequest sdkHttpRequest = getSyncRequest(); assertThat(sdkHttpRequest.firstMatchingHeader("accept").get()).contains(AcceptHeader.IMAGE_JPEG.toString()); assertThat(response.myDocument()).isNull(); } @Test public void explicitDocumentOnlyPayloadWithMemberNameAsKeyNames() { String jsonFormat = "{\"MyDocument\":{\"MyDocument\":\"docsString\"}}"; setUpStub(jsonFormat); Document document = Document.mapBuilder() .putDocument("MyDocument", STRING_DOCUMENT).build(); WithExplicitDocumentPayloadResponse response = jsonClient.withExplicitDocumentPayload(c -> c.myDocument(document).accept(AcceptHeader.IMAGE_JPEG)); String syncRequest = getSyncRequestBody(); assertThat(syncRequest).isEqualTo("{\"MyDocument\":{\"MyDocument\":\"docsString\"}}"); SdkHttpRequest sdkHttpRequest = getSyncRequest(); assertThat(sdkHttpRequest.firstMatchingHeader("accept").get()).contains(AcceptHeader.IMAGE_JPEG.toString()); assertThat(response.myDocument()).isEqualTo(document); assertThat(response.myDocument().isMap()).isTrue(); } @Test public void explicitPayloadWithRecursiveMember() { String jsonFormat = "{\"NoRecurse\":\"noRecursive1\",\"MyDocument\":\"level1\"," + "\"RecursiveStruct\":{\"NoRecurse\":\"noRecursive2\",\"MyDocument\":\"leve2\"}}"; setUpStub(jsonFormat); ExplicitRecursivePayloadResponse response = jsonClient.explicitRecursivePayload(c -> c.recursiveStructType( RecursiveStructType.builder() .myDocument(Document.fromString("level1")) .noRecurse("noRecursive1") .recursiveStruct(RecursiveStructType.builder().myDocument(Document.fromString("leve2")).noRecurse( "noRecursive2").build()) .build()) .registryName("registryName").accept(AcceptHeader.IMAGE_JPEG)); String syncRequest = getSyncRequestBody(); assertThat(syncRequest).isEqualTo(jsonFormat); SdkHttpRequest sdkHttpRequest = getSyncRequest(); assertThat(sdkHttpRequest.firstMatchingHeader("accept").get()).contains(AcceptHeader.IMAGE_JPEG.toString()); assertThat(response.registryName()).isNull(); assertThat(response.accept()).isEqualTo(AcceptHeader.IMAGE_JPEG); assertThat(response.recursiveStructType().noRecurse()).isEqualTo("noRecursive1"); assertThat(response.recursiveStructType().myDocument()).isEqualTo(Document.fromString("level1")); assertThat(response.recursiveStructType().recursiveStruct()) .isEqualTo(RecursiveStructType.builder().noRecurse("noRecursive2").myDocument(Document.fromString("leve2")).build()); } @Test public void explicitPayloadWithRecursiveMemberDocumentMap() { String jsonFormat = "{" + "\"NoRecurse\":\"noRecursive1\"," + "\"MyDocument\":" + "{\"docsL1\":\"docsStringL1\"}," + "\"RecursiveStruct\":" + "{\"NoRecurse\":\"noRecursive2\"," + "\"MyDocument\":" + "{\"docsL2\":\"docsStringL2\"}" + "}" + "}"; setUpStub(jsonFormat); Document documentOuter = Document.mapBuilder().putDocument("docsL1", Document.fromString("docsStringL1")).build(); Document documentInner = Document.mapBuilder().putDocument("docsL2", Document.fromString("docsStringL2")).build(); ExplicitRecursivePayloadResponse response = jsonClient.explicitRecursivePayload( c -> c.recursiveStructType( RecursiveStructType.builder() .myDocument(documentOuter) .noRecurse("noRecursive1") .recursiveStruct( RecursiveStructType.builder() .myDocument(documentInner) .noRecurse("noRecursive2") .build()) .build()) .registryName("registryName") .accept(AcceptHeader.IMAGE_JPEG) ); String syncRequest = getSyncRequestBody(); assertThat(syncRequest).isEqualTo(jsonFormat); SdkHttpRequest sdkHttpRequest = getSyncRequest(); assertThat(sdkHttpRequest.firstMatchingHeader("accept").get()).contains(AcceptHeader.IMAGE_JPEG.toString()); assertThat(response.registryName()).isNull(); assertThat(response.accept()).isEqualTo(AcceptHeader.IMAGE_JPEG); assertThat(response.recursiveStructType().noRecurse()).isEqualTo("noRecursive1"); assertThat(response.recursiveStructType().myDocument()).isEqualTo(documentOuter); assertThat(response.recursiveStructType().recursiveStruct()) .isEqualTo(RecursiveStructType.builder().noRecurse("noRecursive2").myDocument(documentInner).build()); } @Test public void implicitPayloadWithRecursiveMemberDocumentMap() { String jsonFormat = "{\"MyDocument\":[1,null,\"end\"],\"MapOfStringToString\":{\"key1\":\"value1\"," + "\"key2\":\"value2\"},\"RecursiveStructType\":{\"NoRecurse\":\"noRecursive1\"," + "\"MyDocument\":{\"docsL1\":\"docsStringL1\"}," + "\"RecursiveStruct\":{\"NoRecurse\":\"noRecursive2\"," + "\"MyDocument\":{\"docsL2\":\"docsStringL2\"}}}}"; setUpStub(jsonFormat); Document documentOuter = Document.mapBuilder().putDocument("docsL1", Document.fromString("docsStringL1")).build(); Document documentInner = Document.mapBuilder().putDocument("docsL2", Document.fromString("docsStringL2")).build(); Document listDocument = Document.listBuilder().addNumber(1).addNull().addString("end").build(); Map<String, String> stringStringMap = new HashMap<>(); stringStringMap.put("key1", "value1"); stringStringMap.put("key2", "value2"); ImplicitRecursivePayloadResponse response = jsonClient.implicitRecursivePayload( c -> c.recursiveStructType( RecursiveStructType.builder() .myDocument(documentOuter) .noRecurse("noRecursive1") .recursiveStruct( RecursiveStructType.builder() .myDocument(documentInner) .noRecurse("noRecursive2") .build()) .build()) .registryName("registryName") .myDocument(listDocument) .mapOfStringToString(stringStringMap) .accept(AcceptHeader.IMAGE_JPEG) ); String syncRequest = getSyncRequestBody(); assertThat(syncRequest).isEqualTo(jsonFormat); SdkHttpRequest sdkHttpRequest = getSyncRequest(); assertThat(sdkHttpRequest.firstMatchingHeader("accept").get()).contains(AcceptHeader.IMAGE_JPEG.toString()); assertThat(response.registryName()).isNull(); assertThat(response.accept()).isEqualTo(AcceptHeader.IMAGE_JPEG); assertThat(response.recursiveStructType().noRecurse()).isEqualTo("noRecursive1"); assertThat(response.recursiveStructType().myDocument()).isEqualTo(documentOuter); assertThat(response.recursiveStructType().recursiveStruct()) .isEqualTo(RecursiveStructType.builder().noRecurse("noRecursive2").myDocument(documentInner).build()); assertThat(response.myDocument()).isEqualTo(listDocument); } @Test public void implicitDocumentOnlyPayloadWithStringMember() { String jsonFormat = "{\"MyDocument\":\"stringDocument\"}"; setUpStub(jsonFormat); Document document = Document.fromString("stringDocument"); ImplicitOnlyDocumentPayloadResponse response = jsonClient.implicitOnlyDocumentPayload(c -> c.myDocument(document)); String syncRequest = getSyncRequestBody(); assertThat(syncRequest).isEqualTo("{\"MyDocument\":\"stringDocument\"}"); SdkHttpRequest sdkHttpRequest = getSyncRequest(); assertThat(response.myDocument()).isEqualTo(document); } @Test public void implicitDocumentOnlyPayloadWithNullDocumentMember() { String jsonFormat = "{\"MyDocument\":null}"; setUpStub(jsonFormat); Document document = Document.fromNull(); ImplicitOnlyDocumentPayloadResponse response = jsonClient.implicitOnlyDocumentPayload(c -> c.myDocument(document)); String syncRequest = getSyncRequestBody(); assertThat(syncRequest).isEqualTo(jsonFormat); SdkHttpRequest sdkHttpRequest = getSyncRequest(); assertThat(response.myDocument()).isNotNull(); assertThat(response.myDocument()).isEqualTo(document); } @Test public void implicitDocumentOnlyPayloadWithNull() { String jsonFormat = "{}"; setUpStub(jsonFormat); ImplicitOnlyDocumentPayloadResponse response = jsonClient.implicitOnlyDocumentPayload(c -> c.myDocument(null)); String syncRequest = getSyncRequestBody(); assertThat(syncRequest).isEqualTo("{}"); SdkHttpRequest sdkHttpRequest = getSyncRequest(); assertThat(response.myDocument()).isNull(); } @Test public void implicitDocumentOnlyPayloadWithMapKeyAsMemberNames() { String jsonFormat = "{\"MyDocument\":{\"MyDocument\":\"stringDocument\"}}"; setUpStub(jsonFormat); Document document = Document.mapBuilder() .putDocument("MyDocument", Document.fromString("stringDocument")) .build(); ImplicitOnlyDocumentPayloadResponse response = jsonClient.implicitOnlyDocumentPayload(c -> c.myDocument(document)); String syncRequest = getSyncRequestBody(); assertThat(syncRequest).isEqualTo(jsonFormat); assertThat(response.myDocument()).isEqualTo(document); } private <T extends AwsSyncClientBuilder<T, ?> & AwsClientBuilder<T, ?>> T initializeSync(T syncClientBuilder) { return initialize(syncClientBuilder.httpClient(httpClient)); } private <T extends AwsClientBuilder<T, ?>> T initialize(T clientBuilder) { return clientBuilder.credentialsProvider(AnonymousCredentialsProvider.create()) .region(Region.US_WEST_2); } private SdkHttpRequest getSyncRequest() { ArgumentCaptor<HttpExecuteRequest> captor = ArgumentCaptor.forClass(HttpExecuteRequest.class); Mockito.verify(httpClient).prepareRequest(captor.capture()); return captor.getValue().httpRequest(); } private String getSyncRequestBody() { ArgumentCaptor<HttpExecuteRequest> captor = ArgumentCaptor.forClass(HttpExecuteRequest.class); Mockito.verify(httpClient).prepareRequest(captor.capture()); InputStream inputStream = captor.getValue().contentStreamProvider().get().newStream(); return new BufferedReader( new InputStreamReader(inputStream, StandardCharsets.UTF_8)) .lines() .collect(Collectors.joining("\n")); } }
2,944
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/tostring/SensitiveDataRedactedTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.tostring; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import software.amazon.awssdk.services.tostring.model.InputShape; public class SensitiveDataRedactedTest { @Test public void stringIncluded() { assertThat(InputShape.builder().string("Value").build().toString()) .contains("Value"); } @Test public void sensitiveStringRedacted() { assertThat(InputShape.builder().sensitiveString("Value").build().toString()) .doesNotContain("Value"); } @Test public void recursiveRedactionWorks() { assertThat(InputShape.builder() .recursiveShape(InputShape.builder().sensitiveString("Value").build()) .build() .toString()) .doesNotContain("Value"); } @Test public void stringMarkedSensitiveRedacted() { assertThat(InputShape.builder().stringMemberMarkedSensitive("Value").build().toString()) .doesNotContain("Value"); } @Test public void sensitiveListOfStringRedacted() { assertThat(InputShape.builder().listOfSensitiveString("Value").build().toString()) .doesNotContain("Value"); } @Test public void sensitiveListOfListOfStringRedacted() { assertThat(InputShape.builder().listOfListOfSensitiveString(singletonList(singletonList("Value"))).build().toString()) .doesNotContain("Value"); } @Test public void sensitiveMapOfSensitiveStringToStringRedacted() { assertThat(InputShape.builder().mapOfSensitiveStringToString(singletonMap("Value", "Value")).build().toString()) .doesNotContain("Value"); } @Test public void sensitiveMapOfStringToSensitiveStringRedacted() { assertThat(InputShape.builder().mapOfStringToSensitiveString(singletonMap("Value", "Value")).build().toString()) .doesNotContain("Value"); } @Test public void sensitiveMapOfStringToListOfListOfSensitiveStringRedacted() { Map<String, List<List<String>>> value = singletonMap("Value", singletonList(singletonList("Value"))); assertThat(InputShape.builder().mapOfStringToListOfListOfSensitiveString(value).toString()) .doesNotContain("Value"); } }
2,945
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/awsquerycompatible/AwsQueryCompatibleErrorTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.awsquerycompatible; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.querycompatiblejson.QueryCompatibleJsonAsyncClient; import software.amazon.awssdk.services.querycompatiblejson.QueryCompatibleJsonClient; import software.amazon.awssdk.services.querycompatiblejson.model.QueryCompatibleJsonException; import software.amazon.awssdk.utils.builder.SdkBuilder; public class AwsQueryCompatibleErrorTest { @Rule public WireMockRule wireMock = new WireMockRule(0); private QueryCompatibleJsonClient client; private QueryCompatibleJsonAsyncClient asyncClient; private static final String SERVICE_NAME = "QueryCompatibleJson"; private static final String QUERY_HEADER_VALUE = "CustomException;Sender"; private static final String INVALID_QUERY_HEADER_VALUE = "CustomException Sender"; private static final String EMPTY_QUERY_HEADER_VALUE = ";Sender"; private static final String SERVICE_EXCEPTION = "ServiceModeledException"; private static final String CUSTOM_EXCEPTION = "CustomException"; private static final String X_AMZN_QUERY_ERROR = "x-amzn-query-error"; @Before public void setupClient() { client = QueryCompatibleJsonClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .build(); asyncClient = QueryCompatibleJsonAsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .build(); } @Test public void verifyClientException_shouldRetrievedFromHeader() { stubResponseWithQueryHeaderAndBody(QUERY_HEADER_VALUE); assertThatThrownBy(() -> client.allType(SdkBuilder::build)) .satisfies(e -> verifyErrorResponse((AwsServiceException) e, CUSTOM_EXCEPTION)) .isInstanceOf(QueryCompatibleJsonException.class); } @Test public void verifyClientException_invalidHeader_shouldRetrievedFromContent() { stubResponseWithQueryHeaderAndBody(INVALID_QUERY_HEADER_VALUE); assertThatThrownBy(() -> client.allType(SdkBuilder::build)) .satisfies(e -> verifyErrorResponse((AwsServiceException) e, SERVICE_EXCEPTION)); } @Test public void verifyClientException_emptyHeader_shouldRetrievedFromContent() { stubResponseWithQueryHeaderAndBody(EMPTY_QUERY_HEADER_VALUE); assertThatThrownBy(() -> client.allType(SdkBuilder::build)) .satisfies(e -> verifyErrorResponse((AwsServiceException) e, SERVICE_EXCEPTION)); } @Test public void verifyAsyncClientException_invalidHeader_shouldRetrievedFromContent() { stubResponseWithQueryHeaderAndBody(INVALID_QUERY_HEADER_VALUE); assertThatThrownBy(() -> asyncClient.allType(r -> { }).join()).hasRootCauseInstanceOf(AwsServiceException.class) .hasMessageContaining(SERVICE_EXCEPTION); } @Test public void verifyAsyncClientException_emptyHeader_shouldRetrievedFromContent() { stubResponseWithQueryHeaderAndBody(EMPTY_QUERY_HEADER_VALUE); assertThatThrownBy(() -> asyncClient.allType(r -> { }).join()).hasRootCauseInstanceOf(AwsServiceException.class) .hasMessageContaining(SERVICE_EXCEPTION); } private void stubResponseWithQueryHeaderAndBody(String queryHeaderValue) { stubFor(post(anyUrl()) .willReturn(aResponse() .withStatus(403) .withHeader(X_AMZN_QUERY_ERROR, queryHeaderValue) .withBody(String.format("{\"__type\": \"%s\"}", SERVICE_EXCEPTION)))); } private void verifyErrorResponse(AwsServiceException e, String expectedErrorCode) { AwsErrorDetails awsErrorDetails = e.awsErrorDetails(); assertThat(e.statusCode()).isEqualTo(403); assertThat(awsErrorDetails.errorCode()).isEqualTo(expectedErrorCode); assertThat(awsErrorDetails.serviceName()).isEqualTo(SERVICE_NAME); assertThat(awsErrorDetails.sdkHttpResponse()).isNotNull(); } }
2,946
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/testutil/MockIdentityProviderUtil.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.testutil; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; import java.util.concurrent.CompletableFuture; import org.mockito.MockSettings; import org.mockito.internal.creation.MockSettingsImpl; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.ResolveIdentityRequest; public class MockIdentityProviderUtil { public static IdentityProvider<AwsCredentialsIdentity> mockIdentityProvider() { IdentityProvider<AwsCredentialsIdentity> mockIdentityProvider = mock(IdentityProvider.class, withSettings().lenient()); setup(mockIdentityProvider); return mockIdentityProvider; } public static void setup(IdentityProvider<AwsCredentialsIdentity> mockIdentityProvider) { when(mockIdentityProvider.resolveIdentity(any(ResolveIdentityRequest.class))).thenAnswer(invocation -> { try { Thread.sleep(100); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new RuntimeException(ie); } return CompletableFuture.completedFuture(AwsBasicCredentials.create("foo", "bar")); }); when(mockIdentityProvider.resolveIdentity()).thenAnswer(invocation -> { try { Thread.sleep(100); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new RuntimeException(ie); } return CompletableFuture.completedFuture(AwsBasicCredentials.create("foo", "bar")); }); when(mockIdentityProvider.identityType()).thenReturn(AwsCredentialsIdentity.class); } }
2,947
0
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/main/java/software/amazon/awssdk/plugins/EndpointOverrideInternalTestPlugin.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.plugins; import java.net.URI; import software.amazon.awssdk.core.SdkPlugin; import software.amazon.awssdk.core.SdkServiceClientConfiguration; public class EndpointOverrideInternalTestPlugin implements SdkPlugin { @Override public void configureClient(SdkServiceClientConfiguration.Builder config) { URI uri = URI.create("http://127.0.0.1"); config.endpointOverride(uri); } }
2,948
0
Create_ds/aws-sdk-java-v2/test/service-test-utils/src/main/java/software/amazon/awssdk/testutils
Create_ds/aws-sdk-java-v2/test/service-test-utils/src/main/java/software/amazon/awssdk/testutils/service/AwsIntegrationTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.testutils.service; import java.io.IOException; import java.io.InputStream; import reactor.blockhound.BlockHound; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProviderChain; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.utils.IoUtils; public abstract class AwsIntegrationTestBase { static { BlockHound.install(); } /** Default Properties Credentials file path. */ private static final String TEST_CREDENTIALS_PROFILE_NAME = "aws-test-account"; public static final AwsCredentialsProviderChain CREDENTIALS_PROVIDER_CHAIN = AwsCredentialsProviderChain.of(ProfileCredentialsProvider.builder() .profileName(TEST_CREDENTIALS_PROFILE_NAME) .build(), DefaultCredentialsProvider.create()); /** * Shared AWS credentials, loaded from a properties file. */ private static final AwsCredentials CREDENTIALS = CREDENTIALS_PROVIDER_CHAIN.resolveCredentials(); /** * @return AWSCredentials to use during tests. Setup by base fixture * @deprecated by {@link #getCredentialsProvider()} */ @Deprecated protected static AwsCredentials getCredentials() { return CREDENTIALS; } /** * @return {@link IdentityProvider<AwsCredentialsIdentity>} to use during tests. Setup by base fixture */ protected static IdentityProvider<AwsCredentialsIdentity> getCredentialsProvider() { return StaticCredentialsProvider.create(CREDENTIALS); } /** * Reads a system resource fully into a String * * @param location * Relative or absolute location of system resource. * @return String contents of resource file * @throws RuntimeException * if any error occurs */ protected String getResourceAsString(Class<?> clazz, String location) { try (InputStream resourceStream = clazz.getResourceAsStream(location)) { String resourceAsString = IoUtils.toUtf8String(resourceStream); resourceStream.close(); return resourceAsString; } catch (IOException e) { throw new RuntimeException(e); } } }
2,949
0
Create_ds/aws-sdk-java-v2/test/service-test-utils/src/main/java/software/amazon/awssdk/testutils
Create_ds/aws-sdk-java-v2/test/service-test-utils/src/main/java/software/amazon/awssdk/testutils/service/AwsTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.testutils.service; import static org.junit.Assert.assertThat; import static software.amazon.awssdk.utils.StringUtils.isBlank; import java.io.IOException; import java.io.InputStream; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import reactor.blockhound.BlockHound; import software.amazon.awssdk.auth.credentials.AwsCredentialsProviderChain; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.utils.IoUtils; public abstract class AwsTestBase { static { BlockHound.install(); } /** Default Properties Credentials file path. */ private static final String TEST_CREDENTIALS_PROFILE_NAME = "aws-test-account"; public static final AwsCredentialsProviderChain CREDENTIALS_PROVIDER_CHAIN = AwsCredentialsProviderChain.of(ProfileCredentialsProvider.builder() .profileName(TEST_CREDENTIALS_PROFILE_NAME) .build(), DefaultCredentialsProvider.create()); /** * @deprecated Extend from {@link AwsIntegrationTestBase} to access credentials */ @Deprecated public static void setUpCredentials() { // Ignored } /** * Reads a system resource fully into a String * * @param location * Relative or absolute location of system resource. * @return String contents of resource file * @throws RuntimeException * if any error occurs */ protected static String getResourceAsString(Class<?> clazz, String location) { try (InputStream resourceStream = clazz.getResourceAsStream(location)) { return IoUtils.toUtf8String(resourceStream); } catch (IOException e) { throw new RuntimeException(e); } } /** * @deprecated Use {@link #isValidSdkServiceException} in a hamcrest matcher */ @Deprecated protected void assertValidException(SdkServiceException e) { assertThat(e, isValidSdkServiceException()); } public static Matcher<SdkServiceException> isValidSdkServiceException() { return new TypeSafeMatcher<SdkServiceException>() { private StringBuilder sb = new StringBuilder(); @Override protected boolean matchesSafely(SdkServiceException item) { isNotBlank(item.requestId(), "requestId"); isNotBlank(item.getMessage(), "message"); return sb.length() == 0; } @Override public void describeTo(Description description) { description.appendText(sb.toString()); } private void isNotBlank(String value, String fieldName) { if (isBlank(value)) { if (sb.length() > 0) { sb.append(", "); } sb.append(fieldName).append(" should not be null or blank"); } } }; } }
2,950
0
Create_ds/aws-sdk-java-v2/test/service-test-utils/src/main/java/software/amazon/awssdk/testutils
Create_ds/aws-sdk-java-v2/test/service-test-utils/src/main/java/software/amazon/awssdk/testutils/service/BlockHoundAllowlist.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.testutils.service; import reactor.blockhound.BlockHound; import reactor.blockhound.integration.BlockHoundIntegration; /** * Implements {@link BlockHoundIntegration} to explicitly allow SDK calls that are known to be blocking. Some calls (with an * associated tracking issue) may wrongly block, but we allow-list them so that existing integration tests will continue to pass * and so that we preserve visibility on future regression detection. * <p> * https://github.com/reactor/BlockHound/blob/master/docs/custom_integrations.md */ public class BlockHoundAllowlist implements BlockHoundIntegration { @Override public void applyTo(BlockHound.Builder builder) { // https://github.com/aws/aws-sdk-java-v2/issues/2145 builder.allowBlockingCallsInside( "software.amazon.awssdk.http.nio.netty.internal.BetterSimpleChannelPool", "close" ); // https://github.com/aws/aws-sdk-java-v2/issues/2360 builder.allowBlockingCallsInside( "software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider", "getToken" ); } }
2,951
0
Create_ds/aws-sdk-java-v2/test/service-test-utils/src/main/java/software/amazon/awssdk/testutils
Create_ds/aws-sdk-java-v2/test/service-test-utils/src/main/java/software/amazon/awssdk/testutils/service/S3BucketUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.testutils.service; import static software.amazon.awssdk.utils.JavaSystemSetting.USER_NAME; import static software.amazon.awssdk.utils.StringUtils.lowerCase; import java.util.Random; import software.amazon.awssdk.utils.Logger; public final class S3BucketUtils { private static final Logger logger = Logger.loggerFor(S3BucketUtils.class); private static final Random RANDOM = new Random(); private static final int MAX_BUCKET_NAME_LENGTH = 63; private S3BucketUtils() { } /** * Creates a temporary bucket name using the class name of the calling class as a prefix. * * @return an s3 bucket name */ public static String temporaryBucketName() { String callingClass = Thread.currentThread().getStackTrace()[2].getClassName(); return temporaryBucketName(shortenClassName(callingClass.substring(callingClass.lastIndexOf('.')))); } /** * Creates a temporary bucket name using the class name of the object passed as a prefix. * * @param clz an object who's class will be used as the prefix * @return an s3 bucket name */ public static String temporaryBucketName(Object clz) { return temporaryBucketName(clz.getClass()); } /** * Creates a temporary bucket name using the class name as a prefix. * * @param clz class to use as the prefix * @return an s3 bucket name */ public static String temporaryBucketName(Class<?> clz) { return temporaryBucketName(shortenClassName(clz.getSimpleName())); } /** * Creates a temporary bucket name using the prefix passed. * * @param prefix prefix to use for the bucket name * @return an s3 bucket name */ public static String temporaryBucketName(String prefix) { String shortenedUserName = shortenIfNeeded(USER_NAME.getStringValue().orElse("unknown"), 7); String bucketName = lowerCase(prefix) + "-" + lowerCase(shortenedUserName) + "-" + RANDOM.nextInt(10000); if (bucketName.length() > 63) { logger.error(() -> "S3 buckets can only be 63 chars in length, try a shorter prefix"); throw new RuntimeException("S3 buckets can only be 63 chars in length, try a shorter prefix"); } return bucketName; } private static String shortenClassName(String clzName) { return clzName.length() <= 45 ? clzName : clzName.substring(0, 45); } private static String shortenIfNeeded(String str, int length) { return str.length() <= length ? str : str.substring(0, length); } }
2,952
0
Create_ds/aws-sdk-java-v2/test/service-test-utils/src/main/java/software/amazon/awssdk/testutils/service
Create_ds/aws-sdk-java-v2/test/service-test-utils/src/main/java/software/amazon/awssdk/testutils/service/http/MockSyncHttpClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.testutils.service.http; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import software.amazon.awssdk.http.ExecutableHttpRequest; import software.amazon.awssdk.http.HttpExecuteRequest; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.utils.Pair; /** * Mockable implementation of {@link SdkHttpClient}. */ public final class MockSyncHttpClient implements SdkHttpClient, MockHttpClient { private static final Duration DEFAULT_DURATION = Duration.ofMillis(50); private final List<SdkHttpRequest> capturedRequests = new ArrayList<>(); private final List<Pair<HttpExecuteResponse, Duration>> responses = new LinkedList<>(); private final AtomicInteger responseIndex = new AtomicInteger(0); private boolean isClosed; @Override public ExecutableHttpRequest prepareRequest(HttpExecuteRequest request) { capturedRequests.add(request.httpRequest()); return new ExecutableHttpRequest() { @Override public HttpExecuteResponse call() { Pair<HttpExecuteResponse, Duration> responseDurationPair = responses.get(responseIndex.getAndIncrement() % responses.size()); HttpExecuteResponse response = responseDurationPair.left(); Duration duration = responseDurationPair.right(); try { Thread.sleep(duration.toMillis()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } if (response == null) { throw new IllegalStateException("No responses remain."); } return response; } @Override public void abort() { } }; } @Override public void close() { isClosed = true; } @Override public void reset() { this.capturedRequests.clear(); this.responses.clear(); this.responseIndex.set(0); } @Override public void stubNextResponse(HttpExecuteResponse nextResponse) { this.responses.clear(); this.responses.add(Pair.of(nextResponse, DEFAULT_DURATION)); this.responseIndex.set(0); } @Override public void stubNextResponse(HttpExecuteResponse nextResponse, Duration delay) { this.responses.add(Pair.of(nextResponse, delay)); this.responseIndex.set(0); } @Override public void stubResponses(Pair<HttpExecuteResponse, Duration>... responses) { this.responses.clear(); this.responses.addAll(Arrays.asList(responses)); this.responseIndex.set(0); } @Override public void stubResponses(HttpExecuteResponse... responses) { this.responses.clear(); this.responses.addAll(Arrays.stream(responses).map(r -> Pair.of(r, DEFAULT_DURATION)).collect(Collectors.toList())); this.responseIndex.set(0); } @Override public List<SdkHttpRequest> getRequests() { return Collections.unmodifiableList(capturedRequests); } @Override public SdkHttpRequest getLastRequest() { if (capturedRequests.isEmpty()) { throw new IllegalStateException("No requests were captured by the mock"); } return capturedRequests.get(capturedRequests.size() - 1); } public boolean isClosed() { return isClosed; } }
2,953
0
Create_ds/aws-sdk-java-v2/test/service-test-utils/src/main/java/software/amazon/awssdk/testutils/service
Create_ds/aws-sdk-java-v2/test/service-test-utils/src/main/java/software/amazon/awssdk/testutils/service/http/MockAsyncHttpClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.testutils.service.http; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.nio.ByteBuffer; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.async.SdkHttpContentPublisher; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.Pair; /** * Mock implementation of {@link SdkAsyncHttpClient}. */ public final class MockAsyncHttpClient implements SdkAsyncHttpClient, MockHttpClient { private static final Duration DEFAULT_DURATION = Duration.ofMillis(50); private final List<SdkHttpRequest> capturedRequests = new ArrayList<>(); private final List<Pair<HttpExecuteResponse, Duration>> responses = new LinkedList<>(); private final AtomicInteger responseIndex = new AtomicInteger(0); private final ExecutorService executor; private Integer asyncRequestBodyLength; private byte[] streamingPayload; public MockAsyncHttpClient() { this.executor = Executors.newFixedThreadPool(3); } @Override public CompletableFuture<Void> execute(AsyncExecuteRequest request) { capturedRequests.add(request.request()); int index = responseIndex.getAndIncrement() % responses.size(); HttpExecuteResponse nextResponse = responses.get(index).left(); byte[] content = nextResponse.responseBody().map(p -> invokeSafely(() -> IoUtils.toByteArray(p))) .orElseGet(() -> new byte[0]); request.responseHandler().onHeaders(nextResponse.httpResponse()); CompletableFuture.runAsync(() -> request.responseHandler().onStream(new ResponsePublisher(content, index)), executor); if (asyncRequestBodyLength != null && asyncRequestBodyLength > 0) { captureStreamingPayload(request.requestContentPublisher()); } return CompletableFuture.completedFuture(null); } @Override public void close() { executor.shutdown(); } @Override public void reset() { this.capturedRequests.clear(); this.responses.clear(); this.responseIndex.set(0); } @Override public List<SdkHttpRequest> getRequests() { return Collections.unmodifiableList(capturedRequests); } @Override public SdkHttpRequest getLastRequest() { if (capturedRequests.isEmpty()) { throw new IllegalStateException("No requests were captured by the mock"); } return capturedRequests.get(capturedRequests.size() - 1); } @Override public void stubNextResponse(HttpExecuteResponse nextResponse) { this.responses.clear(); this.responses.add(Pair.of(nextResponse, DEFAULT_DURATION)); this.responseIndex.set(0); } @Override public void stubNextResponse(HttpExecuteResponse nextResponse, Duration delay) { this.responses.clear(); this.responses.add(Pair.of(nextResponse, delay)); this.responseIndex.set(0); } @Override public void stubResponses(Pair<HttpExecuteResponse, Duration>... responses) { this.responses.clear(); this.responses.addAll(Arrays.asList(responses)); this.responseIndex.set(0); } @Override public void stubResponses(HttpExecuteResponse... responses) { this.responses.clear(); this.responses.addAll(Arrays.stream(responses).map(r -> Pair.of(r, DEFAULT_DURATION)).collect(Collectors.toList())); this.responseIndex.set(0); } /** * Enable capturing the streaming payload by setting the length of the AsyncRequestBody. */ public void setAsyncRequestBodyLength(int asyncRequestBodyLength) { this.asyncRequestBodyLength = asyncRequestBodyLength; } private void captureStreamingPayload(SdkHttpContentPublisher publisher) { ByteBuffer byteBuffer = ByteBuffer.allocate(asyncRequestBodyLength); Subscriber<ByteBuffer> subscriber = new CapturingSubscriber(byteBuffer); publisher.subscribe(subscriber); streamingPayload = byteBuffer.array(); } /** * Returns the streaming payload byte array, if the asyncRequestBodyLength was set correctly. Otherwise, returns empty * Optional. */ public Optional<byte[]> getStreamingPayload() { return streamingPayload != null ? Optional.of(streamingPayload.clone()) : Optional.empty(); } private final class ResponsePublisher implements SdkHttpContentPublisher { private final byte[] content; private final int index; private ResponsePublisher(byte[] content, int index) { this.content = content; this.index = index; } @Override public Optional<Long> contentLength() { return Optional.of((long) content.length); } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { s.onSubscribe(new Subscription() { private boolean running = true; @Override public void request(long n) { if (n <= 0) { running = false; s.onError(new IllegalArgumentException("Demand must be positive")); } else if (running) { running = false; s.onNext(ByteBuffer.wrap(content)); try { Thread.sleep(responses.get(index).right().toMillis()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } s.onComplete(); } } @Override public void cancel() { running = false; } }); } } private static class CapturingSubscriber implements Subscriber<ByteBuffer> { private ByteBuffer byteBuffer; private CountDownLatch done = new CountDownLatch(1); CapturingSubscriber(ByteBuffer byteBuffer) { this.byteBuffer = byteBuffer; } @Override public void onSubscribe(Subscription subscription) { subscription.request(Long.MAX_VALUE); } @Override public void onNext(ByteBuffer buffer) { byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); byteBuffer.put(bytes); } @Override public void onError(Throwable t) { done.countDown(); } @Override public void onComplete() { done.countDown(); } } }
2,954
0
Create_ds/aws-sdk-java-v2/test/service-test-utils/src/main/java/software/amazon/awssdk/testutils/service
Create_ds/aws-sdk-java-v2/test/service-test-utils/src/main/java/software/amazon/awssdk/testutils/service/http/MockHttpClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.testutils.service.http; import java.time.Duration; import java.util.List; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.utils.Pair; public interface MockHttpClient { /** * Resets this mock by clearing any captured requests and wiping any stubbed responses. */ void reset(); /** * Sets up the next HTTP response that will be returned by the mock. Removes responses previously added to the mock. */ void stubNextResponse(HttpExecuteResponse nextResponse); default void stubNextResponse200() { stubNextResponse(HttpExecuteResponse.builder() .response(SdkHttpResponse.builder() .statusCode(200) .putHeader("Content-Length", "0") .build()) .build()); } /** * Sets up the next HTTP response that will be returned by the mock with a delay. Removes responses previously added to the * mock. */ void stubNextResponse(HttpExecuteResponse nextResponse, Duration delay); void stubResponses(Pair<HttpExecuteResponse, Duration>... responses); /** * Sets the next set of HTTP responses that will be returned by the mock. Removes responses previously added to the mock. */ void stubResponses(HttpExecuteResponse... responses); /** * Get the last request called on the mock. */ SdkHttpRequest getLastRequest(); /** * Get all requests called on the mock. */ List<SdkHttpRequest> getRequests(); }
2,955
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/ProtocolTestSuiteLoader.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.protocol.model.TestCase; import software.amazon.awssdk.protocol.model.TestSuite; /** * Loads the test specification from it's JSON representation. Assumes the JSON files are in the * AwsDrSharedSdk package under /test/protocols. */ public final class ProtocolTestSuiteLoader { private static final String RESOURCE_PREFIX = "/software/amazon/awssdk/protocol/suites/"; private static final ObjectMapper MAPPER = new ObjectMapper() .enable(JsonParser.Feature.ALLOW_COMMENTS) .enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); public List<TestCase> load(String suitePath) throws IOException { return loadTestSuite(suitePath).getTestCases().stream() .flatMap(this::loadTestCases) .collect(Collectors.toList()); } private TestSuite loadTestSuite(String suitePath) throws IOException { return MAPPER.readValue(getClass().getResource(RESOURCE_PREFIX + suitePath), TestSuite.class); } private Stream<? extends TestCase> loadTestCases(String testCase) { try { List<TestCase> testCases = MAPPER .readValue(getClass().getResource(RESOURCE_PREFIX + testCase), new ListTypeReference()); return testCases.stream(); } catch (IOException e) { throw new RuntimeException(e); } } private static class ListTypeReference extends TypeReference<List<TestCase>> { } }
2,956
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/reflect/ClientReflector.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.reflect; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URI; import java.util.stream.Stream; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.awscore.client.builder.AwsClientBuilder; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.Metadata; import software.amazon.awssdk.core.sync.ResponseTransformer; import software.amazon.awssdk.protocol.model.TestCase; import software.amazon.awssdk.protocol.wiremock.WireMockUtils; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.utils.SdkAutoCloseable; /** * Reflection utils to create the client class and invoke operation methods. */ public class ClientReflector implements SdkAutoCloseable { private final IntermediateModel model; private final Metadata metadata; private final Object client; private final Class<?> interfaceClass; public ClientReflector(IntermediateModel model) { this.model = model; this.metadata = model.getMetadata(); this.interfaceClass = getInterfaceClass(); this.client = createClient(); } private Class<?> getInterfaceClass() { try { return Class.forName(getClientFqcn(metadata.getSyncInterface())); } catch (Exception e) { throw new RuntimeException(e); } } /** * Call the operation method on the client with the given request. * * @param params Params to call the operation with. Usually just the request POJO but might be additional params * for streaming operations. * @return Unmarshalled result */ public Object invokeMethod(TestCase testCase, Object... params) throws Exception { String operationName = testCase.getWhen().getOperationName(); Method operationMethod = getOperationMethod(operationName, params); return operationMethod.invoke(client, params); } /** * Call the operation (with a streaming output) method on the client with the given request. * * @param requestObject POJO request object. * @param responseHandler Response handler for an operation with a streaming output. * @return Unmarshalled result */ public Object invokeStreamingMethod(TestCase testCase, Object requestObject, ResponseTransformer<?, ?> responseHandler) throws Exception { String operationName = testCase.getWhen().getOperationName(); Method operationMethod = getOperationMethod(operationName, requestObject.getClass(), ResponseTransformer.class); return operationMethod.invoke(client, requestObject, responseHandler); } @Override public void close() { if (client instanceof SdkAutoCloseable) { ((SdkAutoCloseable) client).close(); } } /** * Create the sync client to use in the tests. */ private Object createClient() { try { // Reflectively create a builder, configure it, and then create the client. Object untypedBuilder = interfaceClass.getMethod("builder").invoke(null); AwsClientBuilder<?, ?> builder = (AwsClientBuilder<?, ?>) untypedBuilder; return builder.credentialsProvider(getMockCredentials()) .region(Region.US_EAST_1) .endpointOverride(URI.create(getEndpoint())) .build(); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } private String getEndpoint() { return "http://localhost:" + WireMockUtils.port(); } /** * @return Dummy credentials to create client with. */ private StaticCredentialsProvider getMockCredentials() { return StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")); } /** * @param simpleClassName Class name to fully qualify. * @return Fully qualified name of class in the client's base package. */ private String getClientFqcn(String simpleClassName) { return String.format("%s.%s", metadata.getFullClientPackageName(), simpleClassName); } /** * Gets the method for the given operation and parameters. Assumes the classes of the params matches * the classes of the declared method parameters (i.e. no inheritance). * * @return Method object to invoke operation. */ private Method getOperationMethod(String operationName, Object... params) throws Exception { Class[] classes = Stream.of(params).map(Object::getClass).toArray(Class[]::new); return getOperationMethod(operationName, classes); } /** * @return Method object to invoke operation. */ private Method getOperationMethod(String operationName, Class<?>... classes) throws Exception { return interfaceClass.getMethod(getOperationMethodName(operationName), classes); } /** * @return Name of the client method for the given operation. */ private String getOperationMethodName(String operationName) { return model.getOperations().get(operationName).getMethodName(); } }
2,957
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/reflect/ShapeModelReflector.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.reflect; import static software.amazon.awssdk.utils.Validate.paramNotNull; import com.fasterxml.jackson.databind.JsonNode; import java.lang.reflect.Method; import java.math.BigDecimal; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Spliterator; import java.util.Spliterators; import java.util.stream.StreamSupport; import software.amazon.awssdk.codegen.internal.Utils; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.MemberModel; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.protocol.reflect.document.JsonNodeToDocumentConvertor; import software.amazon.awssdk.utils.StringUtils; /** * Transforms a JSON representation (using C2J member names) of a modeled POJO into that POJO. */ public class ShapeModelReflector { private final IntermediateModel model; private final String shapeName; private final JsonNode input; public ShapeModelReflector(IntermediateModel model, String shapeName, JsonNode input) { this.model = paramNotNull(model, "model"); this.shapeName = paramNotNull(shapeName, "shapeName"); this.input = input; } public Object createShapeObject() { try { return createStructure(model.getShapes().get(shapeName), input); } catch (Exception e) { throw new TestCaseReflectionException(e); } } /** * Get the value for the streaming member in the {@link JsonNode}. */ public String getStreamingMemberValue() { return StreamSupport.stream(Spliterators.spliteratorUnknownSize(input.fields(), Spliterator.ORDERED), false) .filter(f -> model.getShapes().get(shapeName) .getMemberByC2jName(f.getKey()) .getHttp().getIsStreaming()) .map(f -> f.getValue().asText()) .findFirst() .orElseThrow(() -> new IllegalStateException("Streaming member not found in " + shapeName)); } private Object createStructure(ShapeModel structureShape, JsonNode input) throws Exception { String fqcn = getFullyQualifiedModelClassName(structureShape.getShapeName()); Class<?> shapeClass = Class.forName(fqcn); Method builderMethod = null; try { builderMethod = shapeClass.getDeclaredMethod("builder"); } catch (NoSuchMethodException ignored) { // Ignored } if (builderMethod != null) { builderMethod.setAccessible(true); Object builderInstance = builderMethod.invoke(null); if (input != null) { initializeFields(structureShape, input, builderInstance); } Method buildMethod = builderInstance.getClass().getDeclaredMethod("build"); buildMethod.setAccessible(true); return buildMethod.invoke(builderInstance); } else { Object shapeObject = Class.forName(fqcn).newInstance(); if (input != null) { initializeFields(structureShape, input, shapeObject); } return shapeObject; } } private void initializeFields(ShapeModel structureShape, JsonNode input, Object shapeObject) throws Exception { Iterator<String> fieldNames = input.fieldNames(); while (fieldNames.hasNext()) { String memberName = fieldNames.next(); MemberModel memberModel = structureShape.getMemberByC2jName(memberName); if (memberModel == null) { throw new IllegalArgumentException("Member " + memberName + " was not found in the " + structureShape.getC2jName() + " shape."); } Object toSet = getMemberValue(input.get(memberName), memberModel); if (toSet != null) { Method setter = getMemberSetter(shapeObject.getClass(), memberModel); setter.setAccessible(true); setter.invoke(shapeObject, toSet); } } } private String getFullyQualifiedModelClassName(String modelClassName) { return String.format("%s.%s", model.getMetadata().getFullModelPackageName(), modelClassName); } /** * Find the corresponding setter method for the member. Assumes only simple types are * supported. * * @param currentMember Member to get setter for. * @return Setter Method object. */ private Method getMemberSetter(Class<?> containingClass, MemberModel currentMember) throws Exception { return containingClass.getMethod(getMethodName(currentMember), Class.forName(getFullyQualifiedType(currentMember))); } private String getMethodName(MemberModel memberModel) { String methodName = StringUtils.uncapitalize(memberModel.getName()); if (Utils.isListWithEnumShape(memberModel) || Utils.isMapWithEnumShape(memberModel)) { methodName += "WithStrings"; } return methodName; } private String getFullyQualifiedType(MemberModel memberModel) { if (memberModel.isSimple()) { switch (memberModel.getVariable().getSimpleType()) { case "Instant": case "SdkBytes": case "InputStream": case "Document": return memberModel.getSetterModel().getVariableSetterType(); case "BigDecimal": return "java.math.BigDecimal"; default: return "java.lang." + memberModel.getSetterModel().getVariableSetterType(); } } else if (memberModel.isList()) { return "java.util.Collection"; } else if (memberModel.isMap()) { return "java.util.Map"; } else { return getFullyQualifiedModelClassName( memberModel.getSetterModel().getVariableSetterType()); } } /** * Get the value of the member as specified in the test description. Only supports simple types * at the moment. * * @param currentNode JsonNode containing value of member. */ private Object getMemberValue(JsonNode currentNode, MemberModel memberModel) { String simpleType = memberModel.getVariable().getSimpleType(); if (simpleType.equals("Document")) { return new JsonNodeToDocumentConvertor().visit(currentNode); } // Streaming members are not in the POJO, for Document type null Json Nodes are represented as NullDocument if (currentNode.isNull()) { return null; } if (memberModel.isSimple()) { return getSimpleMemberValue(currentNode, memberModel); } else if (memberModel.isList()) { return getListMemberValue(currentNode, memberModel); } else if (memberModel.isMap()) { return getMapMemberValue(currentNode, memberModel); } else { ShapeModel structureShape = model.getShapes() .get(memberModel.getVariable().getVariableType()); try { return createStructure(structureShape, currentNode); } catch (Exception e) { throw new TestCaseReflectionException(e); } } } private Object getMapMemberValue(JsonNode currentNode, MemberModel memberModel) { Map<String, Object> map = new HashMap<>(); currentNode.fields() .forEachRemaining(e -> map.put(e.getKey(), getMemberValue(e.getValue(), memberModel.getMapModel().getValueModel()))); return map; } private Object getListMemberValue(JsonNode currentNode, MemberModel memberModel) { ArrayList<Object> list = new ArrayList<>(); currentNode.elements() .forEachRemaining(e -> list.add(getMemberValue(e, memberModel.getListModel().getListMemberModel()))); return list; } private Object getSimpleMemberValue(JsonNode currentNode, MemberModel memberModel) { if (memberModel.getHttp().getIsStreaming()) { return null; } switch (memberModel.getVariable().getSimpleType()) { case "Long": return currentNode.asLong(); case "Short": return (short) currentNode.asInt(); case "Integer": return currentNode.asInt(); case "String": return currentNode.asText(); case "Boolean": return currentNode.asBoolean(); case "Double": return currentNode.asDouble(); case "Instant": return Instant.ofEpochMilli(currentNode.asLong()); case "SdkBytes": return SdkBytes.fromUtf8String(currentNode.asText()); case "Float": return (float) currentNode.asDouble(); case "Character": return asCharacter(currentNode); case "BigDecimal": return new BigDecimal(currentNode.asText()); default: throw new IllegalArgumentException( "Unsupported fieldType " + memberModel.getVariable().getSimpleType()); } } private Character asCharacter(JsonNode currentNode) { String text = currentNode.asText(); if (text != null && text.length() > 1) { throw new IllegalArgumentException("Invalid character " + currentNode.asText()); } else if (text != null && text.length() == 1) { return currentNode.asText().charAt(0); } else { return null; } } }
2,958
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/reflect/TestCaseReflectionException.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.reflect; public class TestCaseReflectionException extends RuntimeException { public TestCaseReflectionException(Throwable t) { super(t); } }
2,959
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/reflect
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/reflect/document/JsonNodeToDocumentConvertor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.reflect.document; import com.fasterxml.jackson.databind.JsonNode; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import software.amazon.awssdk.core.SdkNumber; import software.amazon.awssdk.core.document.Document; public class JsonNodeToDocumentConvertor { public Document visit(JsonNode jsonNode) { if (jsonNode.isObject()) { return visitMap(jsonNode); } else if (jsonNode.isArray()) { return visitList(jsonNode); } else if (jsonNode.isBoolean()) { return Document.fromBoolean(jsonNode.asBoolean()); } else if (jsonNode.isNumber()) { return visitNumber(jsonNode); } else if (jsonNode.isTextual()) { return visitString(jsonNode); } else if (jsonNode.isNull()) { return visitNull(); } else { throw new IllegalArgumentException("Unknown Type"); } } private Document visitMap(JsonNode jsonContent) { Map<String, Document> documentMap = new LinkedHashMap<>(); jsonContent.fieldNames().forEachRemaining(s -> documentMap.put(s, visit(jsonContent.get(s)))); return Document.fromMap(documentMap); } private Document visitList(JsonNode jsonContent) { List<Document> documentList = new ArrayList<>(); jsonContent.elements().forEachRemaining(s -> documentList.add(visit(s))); return Document.fromList(documentList); } private Document visitNull() { return Document.fromNull(); } private Document visitNumber(JsonNode jsonNode) { return Document.fromNumber(SdkNumber.fromString(jsonNode.numberValue().toString())); } private Document visitString(JsonNode jsonNode) { return Document.fromString(jsonNode.asText()); } }
2,960
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts/marshalling/UriAssertion.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.asserts.marshalling; import static org.junit.Assert.assertEquals; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import java.net.URI; /** * Asserts on the URI of a marshalled request. */ public class UriAssertion extends MarshallingAssertion { private final String expectedUri; public UriAssertion(String uri) { this.expectedUri = uri; } @Override protected void doAssert(LoggedRequest actual) throws Exception { assertEquals(removeTrailingSlash(expectedUri), removeTrailingSlash(getActualPath(actual))); } private String getActualPath(LoggedRequest actual) { return URI.create(actual.getUrl()).getPath(); } private String removeTrailingSlash(String str) { return (str.endsWith("/")) ? str.substring(0, str.lastIndexOf('/')) : str; } }
2,961
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts/marshalling/XmlBodyAssertion.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.asserts.marshalling; import com.github.tomakehurst.wiremock.verification.LoggedRequest; /** * Asserts on the body (expected to be XML) of the marshalled request. */ public class XmlBodyAssertion extends MarshallingAssertion { private final String xmlEquals; public XmlBodyAssertion(String xmlEquals) { this.xmlEquals = xmlEquals; } @Override protected void doAssert(LoggedRequest actual) throws Exception { XmlAsserts.assertXmlEquals(xmlEquals, actual.getBodyAsString()); } }
2,962
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts/marshalling/HeadersAssertion.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.asserts.marshalling; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.github.tomakehurst.wiremock.http.HttpHeaders; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import java.util.List; import java.util.Map; /** * Asserts on the headers in the marshalled request */ public class HeadersAssertion extends MarshallingAssertion { private Map<String, List<String>> contains; private List<String> doesNotContain; public void setContains(Map<String, List<String>> contains) { this.contains = contains; } public void setDoesNotContain(List<String> doesNotContain) { this.doesNotContain = doesNotContain; } @Override protected void doAssert(LoggedRequest actual) throws Exception { if (contains != null) { assertHeadersContains(actual.getHeaders()); } if (doesNotContain != null) { assertDoesNotContainHeaders(actual.getHeaders()); } } private void assertHeadersContains(HttpHeaders actual) { contains.forEach((expectedKey, expectedValues) -> { assertTrue(String.format("Header '%s' was expected to be present. Actual headers: %s", expectedKey, actual), actual.getHeader(expectedKey).isPresent()); List<String> actualValues = actual.getHeader(expectedKey).values(); assertEquals(expectedValues, actualValues); }); } private void assertDoesNotContainHeaders(HttpHeaders actual) { doesNotContain.forEach(headerName -> { assertFalse(String.format("Header '%s' was expected to be absent", headerName), actual.getHeader(headerName).isPresent()); }); } }
2,963
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts/marshalling/XmlAsserts.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.asserts.marshalling; import static org.junit.Assert.fail; import java.io.StringWriter; import java.io.Writer; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.custommonkey.xmlunit.Diff; import org.custommonkey.xmlunit.examples.RecursiveElementNameAndTextQualifier; import org.w3c.dom.Document; import software.amazon.awssdk.utils.StringInputStream; public final class XmlAsserts { private static final DocumentBuilder DOCUMENT_BUILDER = getDocumentBuilder(); private XmlAsserts() { } private static DocumentBuilder getDocumentBuilder() { DocumentBuilderFactory dbf = newSecureDocumentBuilderFactory(); try { return dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } } public static void assertXmlEquals(String expectedXml, String actualXml) { try { doAssertXmlEquals(expectedXml, actualXml); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } private static void doAssertXmlEquals(String expectedXml, String actualXml) throws Exception { Diff diff = new Diff(expectedXml, actualXml); diff.overrideElementQualifier(new RecursiveElementNameAndTextQualifier()); if (!diff.similar()) { fail("\nExpected the following XML\n" + formatXml(expectedXml) + "\nbut actual XML was\n\n" + formatXml(actualXml)); } } private static String formatXml(String xmlDocumentString) throws Exception { return formatXml(DOCUMENT_BUILDER.parse(new StringInputStream(xmlDocumentString))); } private static String formatXml(Document xmlDocument) throws Exception { Transformer transformer = newSecureTransformerFactory().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(xmlDocument); transformer.transform(source, result); try (Writer writer = result.getWriter()) { return writer.toString(); } } private static DocumentBuilderFactory newSecureDocumentBuilderFactory() { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setXIncludeAware(false); docFactory.setExpandEntityReferences(false); trySetFeature(docFactory, XMLConstants.FEATURE_SECURE_PROCESSING, true); trySetFeature(docFactory, "http://apache.org/xml/features/disallow-doctype-decl", true); trySetFeature(docFactory, "http://xml.org/sax/features/external-general-entities", false); trySetFeature(docFactory, "http://xml.org/sax/features/external-parameter-entities", false); trySetAttribute(docFactory, "http://javax.xml.XMLConstants/property/accessExternalDTD", ""); trySetAttribute(docFactory, "http://javax.xml.XMLConstants/property/accessExternalSchema", ""); return docFactory; } private static TransformerFactory newSecureTransformerFactory() { TransformerFactory transformerFactory = TransformerFactory.newInstance(); trySetAttribute(transformerFactory, XMLConstants.ACCESS_EXTERNAL_DTD, ""); trySetAttribute(transformerFactory, XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); return transformerFactory; } private static void trySetFeature(DocumentBuilderFactory factory, String feature, boolean value) { try { factory.setFeature(feature, value); } catch (Exception e) { throw new RuntimeException(e); } } private static void trySetAttribute(DocumentBuilderFactory factory, String feature, String value) { try { factory.setAttribute(feature, value); } catch (Exception e) { throw new RuntimeException(e); } } private static void trySetAttribute(TransformerFactory factory, String feature, Object value) { try { factory.setAttribute(feature, value); } catch (Exception e) { throw new RuntimeException(e); } } }
2,964
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts/marshalling/MarshallingAssertion.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.asserts.marshalling; import com.github.tomakehurst.wiremock.verification.LoggedRequest; /** * Assertion on the marshalled request. */ public abstract class MarshallingAssertion { /** * Asserts on the marshalled request. * * @param actual Marshalled request * @throws AssertionError If any assertions fail */ public final void assertMatches(LoggedRequest actual) throws AssertionError { // Wrap checked exceptions to play nicer with lambda's try { doAssert(actual); } catch (Error | RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } } /** * Hook to allow subclasses to perform their own assertion logic. Allows subclasses to throw * checked exceptions without propogating it back to the caller. */ protected abstract void doAssert(LoggedRequest actual) throws Exception; }
2,965
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts/marshalling/HttpMethodAssertion.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.asserts.marshalling; import static org.junit.Assert.assertEquals; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.utils.Validate; public class HttpMethodAssertion extends MarshallingAssertion { private final SdkHttpMethod expectedMethodName; public HttpMethodAssertion(SdkHttpMethod method) { this.expectedMethodName = Validate.paramNotNull(method, "method"); } @Override protected void doAssert(LoggedRequest actual) { assertEquals(expectedMethodName.name(), actual.getMethod().value()); } }
2,966
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts/marshalling/SerializedAs.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.asserts.marshalling; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.protocol.model.SdkHttpMethodDeserializer; /** * Main composite for marshalling assertions. Contains sub assertions for each component of an HTTP * request. */ public class SerializedAs extends CompositeMarshallingAssertion { public void setBody(RequestBodyAssertion body) { addAssertion(body); } public void setHeaders(HeadersAssertion headers) { addAssertion(headers); } public void setUri(String uri) { addAssertion(new UriAssertion(uri)); } @JsonDeserialize(using = SdkHttpMethodDeserializer.class) public void setMethod(SdkHttpMethod method) { addAssertion(new HttpMethodAssertion(method)); } public void setParams(QueryParamsAssertion params) { addAssertion(params); } }
2,967
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts/marshalling/QueryParamsAssertion.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.asserts.marshalling; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.hamcrest.collection.IsMapContaining.hasKey; import static org.junit.Assert.assertThat; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; import software.amazon.awssdk.utils.StringUtils; /** * Asserts on the query parameters of the marshalled request. */ public class QueryParamsAssertion extends MarshallingAssertion { private Map<String, List<String>> contains; private Map<String, List<String>> containsOnly; private List<String> doesNotContain; public void setContains(Map<String, List<String>> contains) { this.contains = contains; } public void setContainsOnly(Map<String, List<String>> containsOnly) { this.containsOnly = containsOnly; } public void setDoesNotContain(List<String> doesNotContain) { this.doesNotContain = doesNotContain; } @Override protected void doAssert(LoggedRequest actual) throws Exception { try { Map<String, List<String>> actualParams = parseQueryParams(actual); doAssert(actualParams); } catch (AssertionError error) { // We may send the query params in the body if there is no other content. Try // decoding body as params and rerun the assertions. Map<String, List<String>> actualParams = parseQueryParamsFromBody( actual.getBodyAsString()); doAssert(actualParams); } } private void doAssert(Map<String, List<String>> actualParams) { if (contains != null) { assertContains(actualParams); } if (doesNotContain != null) { assertDoesNotContain(actualParams); } if (containsOnly != null) { assertContainsOnly(actualParams); } } private Map<String, List<String>> parseQueryParamsFromBody(String body) { return toQueryParamMap(URLEncodedUtils.parse(body, StandardCharsets.UTF_8)); } private Map<String, List<String>> parseQueryParams(LoggedRequest actual) { return toQueryParamMap(parseNameValuePairsFromQuery(actual)); } /** * Group the list of {@link NameValuePair} by parameter name. */ private Map<String, List<String>> toQueryParamMap(List<NameValuePair> queryParams) { return queryParams.stream().collect(Collectors.groupingBy(NameValuePair::getName, Collectors .mapping(NameValuePair::getValue, Collectors.toList()))); } private List<NameValuePair> parseNameValuePairsFromQuery(LoggedRequest actual) { String queryParams = URI.create(actual.getUrl()).getQuery(); if (StringUtils.isEmpty(queryParams)) { return Collections.emptyList(); } return URLEncodedUtils.parse(queryParams, StandardCharsets.UTF_8); } private void assertContains(Map<String, List<String>> actualParams) { contains.entrySet().forEach(e -> assertThat(actualParams.get(e.getKey()), containsInAnyOrder(e.getValue().toArray()))); } private void assertDoesNotContain(Map<String, List<String>> actualParams) { doesNotContain.forEach(key -> assertThat(actualParams, not(hasKey(key)))); } private void assertContainsOnly(Map<String, List<String>> actualParams) { assertThat(actualParams.keySet(), equalTo(containsOnly.keySet())); containsOnly.entrySet().forEach(e -> assertThat( actualParams.get(e.getKey()), containsInAnyOrder(e.getValue().toArray()) )); } }
2,968
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts/marshalling/RequestBodyAssertion.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.asserts.marshalling; /** * Asserts on the request body of the marshalled request. Contains sub assertions for payloads that * are known to be JSON or XML which require more sophisticated comparison. */ public class RequestBodyAssertion extends CompositeMarshallingAssertion { public void setJsonEquals(String jsonEquals) { addAssertion(new JsonBodyAssertion(jsonEquals)); } public void setXmlEquals(String xmlEquals) { addAssertion(new XmlBodyAssertion(xmlEquals)); } public void setEquals(String equals) { addAssertion(new RawBodyAssertion(equals)); } }
2,969
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts/marshalling/CompositeMarshallingAssertion.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.asserts.marshalling; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import java.util.ArrayList; import java.util.List; /** * Composite for MarshallingAssertion objects. */ public class CompositeMarshallingAssertion extends MarshallingAssertion { private final List<MarshallingAssertion> assertions = new ArrayList<>(); @Override protected void doAssert(LoggedRequest actual) throws Exception { for (MarshallingAssertion assertion : assertions) { assertion.assertMatches(actual); } } protected void addAssertion(MarshallingAssertion assertion) { assertions.add(assertion); } }
2,970
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts/marshalling/RawBodyAssertion.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.asserts.marshalling; import static org.junit.Assert.assertEquals; import com.github.tomakehurst.wiremock.verification.LoggedRequest; public class RawBodyAssertion extends MarshallingAssertion { private String expectedContent; public RawBodyAssertion(String rawBodyContents) { this.expectedContent = rawBodyContents; } @Override protected void doAssert(LoggedRequest actual) throws Exception { assertEquals(expectedContent, actual.getBodyAsString()); } }
2,971
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts/marshalling/JsonBodyAssertion.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.asserts.marshalling; import static org.junit.Assert.assertEquals; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.tomakehurst.wiremock.verification.LoggedRequest; /** * Asserts on the body (expected to be JSON) of the marshalled request. */ public class JsonBodyAssertion extends MarshallingAssertion { private static final ObjectMapper MAPPER = new ObjectMapper(); private final String jsonEquals; public JsonBodyAssertion(String jsonEquals) { this.jsonEquals = jsonEquals; } @Override protected void doAssert(LoggedRequest actual) throws Exception { JsonNode expected = MAPPER.readTree(jsonEquals); JsonNode actualJson = MAPPER.readTree(actual.getBodyAsString()); assertEquals(expected, actualJson); } }
2,972
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts/unmarshalling/UnmarshallingAssertion.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.asserts.unmarshalling; /** * Assertion on the unmarshalled result. */ public abstract class UnmarshallingAssertion { /** * @param context Context containing additional metadata about the test case * @param actual Unmarshalled result object * @throws AssertionError If any assertions fail */ public final void assertMatches(UnmarshallingTestContext context, Object actual) { // Catches the exception to play nicer with lambda's try { doAssert(context, actual); } catch (Exception e) { throw new RuntimeException(e); } } /** * Hook to allow subclasses to perform their own assertion logic. Allows subclasses to throw * checked exceptions without propogating it back to the caller. */ protected abstract void doAssert(UnmarshallingTestContext context, Object actual) throws Exception; }
2,973
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts/unmarshalling/UnmarshallingTestContext.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.asserts.unmarshalling; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.core.sync.ResponseTransformer; /** * Unmarshalling assertions require some context about the service and operation being exercised. */ public class UnmarshallingTestContext { private IntermediateModel model; private String operationName; private String streamedResponse; public UnmarshallingTestContext withModel(IntermediateModel model) { this.model = model; return this; } public IntermediateModel getModel() { return model; } public UnmarshallingTestContext withOperationName(String operationName) { this.operationName = operationName; return this; } public String getOperationName() { return operationName; } /** * Streamed response will only be present for operations that have a streaming member in the output. We * capture the actual contents if via a custom {@link ResponseTransformer}. */ public UnmarshallingTestContext withStreamedResponse(String streamedResponse) { this.streamedResponse = streamedResponse; return this; } public String getStreamedResponse() { return streamedResponse; } }
2,974
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/asserts/unmarshalling/UnmarshalledResultAssertion.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.asserts.unmarshalling; import static junit.framework.Assert.fail; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import com.fasterxml.jackson.databind.JsonNode; import java.io.InputStream; import java.lang.reflect.Field; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.io.IOUtils; import org.unitils.reflectionassert.ReflectionComparator; import org.unitils.reflectionassert.ReflectionComparatorFactory; import org.unitils.reflectionassert.comparator.Comparator; import org.unitils.reflectionassert.difference.Difference; import org.unitils.reflectionassert.report.impl.DefaultDifferenceReport; import software.amazon.awssdk.protocol.reflect.ShapeModelReflector; /** * Asserts on the unmarshalled result of a given operation. */ public class UnmarshalledResultAssertion extends UnmarshallingAssertion { private final JsonNode expectedResult; public UnmarshalledResultAssertion(JsonNode expectedResult) { this.expectedResult = expectedResult; } @Override protected void doAssert(UnmarshallingTestContext context, Object actual) throws Exception { ShapeModelReflector shapeModelReflector = createShapeReflector(context); Object expectedResult = shapeModelReflector.createShapeObject(); for (Field field : expectedResult.getClass().getDeclaredFields()) { assertFieldEquals(field, actual, expectedResult); } // Streaming response is captured by the response handler so we have to handle it separately if (context.getStreamedResponse() != null) { assertEquals(shapeModelReflector.getStreamingMemberValue(), context.getStreamedResponse()); } } /** * We can't use assertReflectionEquals on the result object directly. InputStreams require some * special handling so we compare field by field and use a special assertion for streaming * types. */ private void assertFieldEquals(Field field, Object actual, Object expectedResult) throws Exception { field.setAccessible(true); if (field.getType().isAssignableFrom(InputStream.class)) { assertTrue(IOUtils.contentEquals((InputStream) field.get(expectedResult), (InputStream) field.get(actual))); } else { Difference difference = CustomComparatorFactory.getComparator() .getDifference(field.get(expectedResult), field.get(actual)); if (difference != null) { fail(new DefaultDifferenceReport().createReport(difference)); } } } private ShapeModelReflector createShapeReflector(UnmarshallingTestContext context) { return new ShapeModelReflector(context.getModel(), getOutputClassName(context), this.expectedResult); } /** * @return Class name of the output model. */ private String getOutputClassName(UnmarshallingTestContext context) { return context.getModel().getOperations().get(context.getOperationName()).getReturnType() .getReturnType(); } private static class CustomComparatorFactory extends ReflectionComparatorFactory { private static ReflectionComparator getComparator() { List<Comparator> comparators = new ArrayList<>(); comparators.add(new InstantComparator()); comparators.addAll(ReflectionComparatorFactory.getComparatorChain(Collections.emptySet())); return new ReflectionComparator(comparators); } } private static class InstantComparator implements Comparator { @Override public boolean canCompare(Object left, Object right) { return left instanceof Instant || right instanceof Instant; } @Override public Difference compare(Object left, Object right, boolean onlyFirstDifference, ReflectionComparator reflectionComparator) { if (right == null) { return new Difference("Right value null.", left, null); } if (!left.equals(right)) { return new Difference("Different values.", left, right); } return null; } } }
2,975
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/model/When.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.model; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; public class When { @JsonDeserialize(using = WhenActionDeserialzer.class) private WhenAction action; @JsonProperty(value = "operation") private String operationName; public WhenAction getAction() { return action; } public void setAction(WhenAction action) { this.action = action; } public String getOperationName() { return operationName; } public void setOperationName(String operationName) { this.operationName = operationName; } }
2,976
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/model/WhenActionDeserialzer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.model; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import java.io.IOException; class WhenActionDeserialzer extends JsonDeserializer<WhenAction> { @Override public WhenAction deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { return WhenAction.fromValue(p.getText()); } }
2,977
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/model/WhenAction.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.model; public enum WhenAction { MARSHALL("marshall"), UNMARSHALL("unmarshall"); private final String action; WhenAction(String action) { this.action = action; } public static WhenAction fromValue(String action) { switch (action) { case "marshall": return MARSHALL; case "unmarshall": return UNMARSHALL; default: throw new IllegalArgumentException("Unsupported test action " + action); } } }
2,978
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/model/SdkHttpMethodDeserializer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.model; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import java.io.IOException; import software.amazon.awssdk.http.SdkHttpMethod; public class SdkHttpMethodDeserializer extends JsonDeserializer<SdkHttpMethod> { @Override public SdkHttpMethod deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { return SdkHttpMethod.fromValue(p.getText()); } }
2,979
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/model/Then.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; import software.amazon.awssdk.protocol.asserts.marshalling.MarshallingAssertion; import software.amazon.awssdk.protocol.asserts.marshalling.SerializedAs; import software.amazon.awssdk.protocol.asserts.unmarshalling.UnmarshalledResultAssertion; import software.amazon.awssdk.protocol.asserts.unmarshalling.UnmarshallingAssertion; public class Then { private final MarshallingAssertion serializedAs; private final UnmarshallingAssertion deserializedAs; @JsonCreator public Then(@JsonProperty("serializedAs") SerializedAs serializedAs, @JsonProperty("deserializedAs") JsonNode deserializedAs) { this.serializedAs = serializedAs; this.deserializedAs = new UnmarshalledResultAssertion(deserializedAs); } /** * @return The assertion object to use for marshalling tests */ public MarshallingAssertion getMarshallingAssertion() { return serializedAs; } /** * @return The assertion object to use for unmarshalling tests */ public UnmarshallingAssertion getUnmarshallingAssertion() { return deserializedAs; } }
2,980
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/model/GivenResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.model; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import java.util.Map; public class GivenResponse { @JsonProperty(value = "status_code") private Integer statusCode; private Map<String, List<String>> headers; private String body; public Integer getStatusCode() { return statusCode; } public void setStatusCode(Integer statusCode) { this.statusCode = statusCode; } public Map<String, List<String>> getHeaders() { return headers; } public void setHeaders(Map<String, List<String>> headers) { this.headers = headers; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } }
2,981
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/model/Given.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.model; import com.fasterxml.jackson.databind.JsonNode; public class Given { private JsonNode input; private GivenResponse response; public JsonNode getInput() { return input; } public void setInput(JsonNode input) { this.input = input; } public GivenResponse getResponse() { return response; } public void setResponse(GivenResponse response) { this.response = response; } }
2,982
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/model/TestCase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.model; public class TestCase { private String description; // Given is optional private Given given = new Given(); private When when; private Then then; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Given getGiven() { return given; } public void setGiven(Given given) { this.given = given; } public When getWhen() { return when; } public void setWhen(When when) { this.when = when; } public Then getThen() { return then; } public void setThen(Then then) { this.then = then; } @Override public String toString() { return description; } }
2,983
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/model/TestSuite.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; public class TestSuite { private final List<String> testCases; @JsonCreator public TestSuite(@JsonProperty("testCases") List<String> testCases) { this.testCases = testCases; } public List<String> getTestCases() { return testCases; } }
2,984
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/runners/ProtocolTestRunner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.runners; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.protocol.model.TestCase; import software.amazon.awssdk.protocol.reflect.ClientReflector; import software.amazon.awssdk.protocol.wiremock.WireMockUtils; /** * Runs a list of test cases (either marshalling or unmarshalling). */ public final class ProtocolTestRunner { private static final Logger log = LoggerFactory.getLogger(ProtocolTestRunner.class); private static final ObjectMapper MAPPER = new ObjectMapper() .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .enable(JsonParser.Feature.ALLOW_COMMENTS); private final ClientReflector clientReflector; private final MarshallingTestRunner marshallingTestRunner; private final UnmarshallingTestRunner unmarshallingTestRunner; public ProtocolTestRunner(String intermediateModelLocation) { WireMockUtils.startWireMockServer(); IntermediateModel model = loadModel(intermediateModelLocation); this.clientReflector = new ClientReflector(model); this.marshallingTestRunner = new MarshallingTestRunner(model, clientReflector); this.unmarshallingTestRunner = new UnmarshallingTestRunner(model, clientReflector); } private IntermediateModel loadModel(String intermedidateModelLocation) { try { return MAPPER.readValue(getClass().getResource(intermedidateModelLocation), IntermediateModel.class); } catch (IOException e) { throw new RuntimeException(e); } } public void runTests(List<TestCase> tests) throws Exception { for (TestCase testCase : tests) { runTest(testCase); } clientReflector.close(); } public void runTest(TestCase testCase) throws Exception { log.info("Running test: {}", testCase.getDescription()); switch (testCase.getWhen().getAction()) { case MARSHALL: marshallingTestRunner.runTest(testCase); break; case UNMARSHALL: unmarshallingTestRunner.runTest(testCase); break; default: throw new IllegalArgumentException( "Unsupported action " + testCase.getWhen().getAction()); } } }
2,985
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/runners/MarshallingTestRunner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.runners; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static org.junit.Assert.assertEquals; import com.fasterxml.jackson.databind.JsonNode; import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; import com.github.tomakehurst.wiremock.client.WireMock; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import java.util.List; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.protocol.model.TestCase; import software.amazon.awssdk.protocol.reflect.ClientReflector; import software.amazon.awssdk.protocol.reflect.ShapeModelReflector; import software.amazon.awssdk.protocol.wiremock.WireMockUtils; /** * Test runner for test cases exercising the client marshallers. */ class MarshallingTestRunner { private final IntermediateModel model; private final ClientReflector clientReflector; MarshallingTestRunner(IntermediateModel model, ClientReflector clientReflector) { this.model = model; this.clientReflector = clientReflector; } /** * @return LoggedRequest that wire mock captured. */ private static LoggedRequest getLoggedRequest() { List<LoggedRequest> requests = WireMockUtils.findAllLoggedRequests(); assertEquals(1, requests.size()); return requests.get(0); } void runTest(TestCase testCase) throws Exception { resetWireMock(); ShapeModelReflector shapeModelReflector = createShapeModelReflector(testCase); if (!model.getShapes().get(testCase.getWhen().getOperationName() + "Request").isHasStreamingMember()) { clientReflector.invokeMethod(testCase, shapeModelReflector.createShapeObject()); } else { clientReflector.invokeMethod(testCase, shapeModelReflector.createShapeObject(), RequestBody.fromString(shapeModelReflector.getStreamingMemberValue())); } LoggedRequest actualRequest = getLoggedRequest(); testCase.getThen().getMarshallingAssertion().assertMatches(actualRequest); } /** * Reset wire mock and re-configure stubbing. */ private void resetWireMock() { WireMock.reset(); // Stub to return 200 for all requests ResponseDefinitionBuilder responseDefBuilder = aResponse().withStatus(200); // XML Unmarshallers expect at least one level in the XML document. if (model.getMetadata().isXmlProtocol()) { responseDefBuilder.withBody("<foo></foo>"); } stubFor(any(urlMatching(".*")).willReturn(responseDefBuilder)); } private ShapeModelReflector createShapeModelReflector(TestCase testCase) { String operationName = testCase.getWhen().getOperationName(); String requestClassName = getOperationRequestClassName(operationName); JsonNode input = testCase.getGiven().getInput(); return new ShapeModelReflector(model, requestClassName, input); } /** * @return Name of the request class that corresponds to the given operation. */ private String getOperationRequestClassName(String operationName) { return operationName + "Request"; } }
2,986
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/runners/UnmarshallingTestRunner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.runners; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import com.fasterxml.jackson.databind.JsonNode; import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; import com.github.tomakehurst.wiremock.client.WireMock; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.Metadata; import software.amazon.awssdk.core.sync.ResponseTransformer; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.protocol.asserts.unmarshalling.UnmarshallingTestContext; import software.amazon.awssdk.protocol.model.GivenResponse; import software.amazon.awssdk.protocol.model.TestCase; import software.amazon.awssdk.protocol.reflect.ClientReflector; import software.amazon.awssdk.protocol.reflect.ShapeModelReflector; import software.amazon.awssdk.utils.IoUtils; /** * Test runner for test cases exercising the client unmarshallers. */ class UnmarshallingTestRunner { private final IntermediateModel model; private final Metadata metadata; private final ClientReflector clientReflector; UnmarshallingTestRunner(IntermediateModel model, ClientReflector clientReflector) { this.model = model; this.metadata = model.getMetadata(); this.clientReflector = clientReflector; } void runTest(TestCase testCase) throws Exception { resetWireMock(testCase.getGiven().getResponse()); String operationName = testCase.getWhen().getOperationName(); ShapeModelReflector shapeModelReflector = createShapeModelReflector(testCase); if (!hasStreamingMember(operationName)) { Object actualResult = clientReflector.invokeMethod(testCase, shapeModelReflector.createShapeObject()); testCase.getThen().getUnmarshallingAssertion().assertMatches(createContext(operationName), actualResult); } else { CapturingResponseTransformer responseHandler = new CapturingResponseTransformer(); Object actualResult = clientReflector .invokeStreamingMethod(testCase, shapeModelReflector.createShapeObject(), responseHandler); testCase.getThen().getUnmarshallingAssertion() .assertMatches(createContext(operationName, responseHandler.captured), actualResult); } } /** * {@link ResponseTransformer} that simply captures all the content as a String so we * can compare it with the expected in * {@link software.amazon.awssdk.protocol.asserts.unmarshalling.UnmarshalledResultAssertion}. */ private static class CapturingResponseTransformer implements ResponseTransformer<Object, Void> { private String captured; @Override public Void transform(Object response, AbortableInputStream inputStream) throws Exception { this.captured = IoUtils.toUtf8String(inputStream); return null; } } private boolean hasStreamingMember(String operationName) { return model.getShapes().get(operationName + "Response").isHasStreamingMember(); } /** * Reset wire mock and re-configure stubbing. */ private void resetWireMock(GivenResponse givenResponse) { WireMock.reset(); // Stub to return given response in test definition. stubFor(any(urlMatching(".*")).willReturn(toResponseBuilder(givenResponse))); } private ResponseDefinitionBuilder toResponseBuilder(GivenResponse givenResponse) { ResponseDefinitionBuilder responseBuilder = aResponse().withStatus(200); if (givenResponse.getHeaders() != null) { givenResponse.getHeaders().forEach((key, values) -> { responseBuilder.withHeader(key, values.toArray(new String[0])); }); } if (givenResponse.getStatusCode() != null) { responseBuilder.withStatus(givenResponse.getStatusCode()); } if (givenResponse.getBody() != null) { responseBuilder.withBody(givenResponse.getBody()); } else if (metadata.isXmlProtocol()) { // XML Unmarshallers expect at least one level in the XML document. If no body is explicitly // set by the test add a fake one here. responseBuilder.withBody("<foo></foo>"); } return responseBuilder; } private ShapeModelReflector createShapeModelReflector(TestCase testCase) { String operationName = testCase.getWhen().getOperationName(); String requestClassName = getOperationRequestClassName(operationName); JsonNode input = testCase.getGiven().getInput(); return new ShapeModelReflector(model, requestClassName, input); } private UnmarshallingTestContext createContext(String operationName) { return createContext(operationName, null); } private UnmarshallingTestContext createContext(String operationName, String streamedResponse) { return new UnmarshallingTestContext() .withModel(model) .withOperationName(operationName) .withStreamedResponse(streamedResponse); } /** * @return Name of the request class that corresponds to the given operation. */ private String getOperationRequestClassName(String operationName) { return model.getOperations().get(operationName).getInput().getVariableType(); } }
2,987
0
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol
Create_ds/aws-sdk-java-v2/test/protocol-tests-core/src/main/java/software/amazon/awssdk/protocol/wiremock/WireMockUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.protocol.wiremock; import static com.github.tomakehurst.wiremock.client.WireMock.anyRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.client.WireMock; import com.github.tomakehurst.wiremock.http.RequestMethod; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.matching.RequestPatternBuilder; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import java.util.List; /** * Utils to start the WireMock server and retrieve the chosen port. */ public final class WireMockUtils { // Use 0 to dynamically assign an available port. private static final WireMockServer WIRE_MOCK = new WireMockServer(wireMockConfig().port(0)); private WireMockUtils() { } public static void startWireMockServer() { WIRE_MOCK.start(); WireMock.configureFor(WIRE_MOCK.port()); } /** * @return The port that was chosen by the WireMock server. */ public static int port() { return WIRE_MOCK.port(); } /** * @return All LoggedRequests that wire mock captured. */ public static List<LoggedRequest> findAllLoggedRequests() { List<LoggedRequest> requests = findAll( new RequestPatternBuilder(RequestMethod.ANY, urlMatching(".*"))); return requests; } public static void verifyRequestCount(int expectedCount, WireMockRule wireMock) { wireMock.verify(expectedCount, anyRequestedFor(anyUrl())); } }
2,988
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/TransferManagerBenchmarkConfig.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.s3benchmarks; import java.time.Duration; import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm; import software.amazon.awssdk.utils.ToString; public final class TransferManagerBenchmarkConfig { private final String filePath; private final String bucket; private final String key; private final Double targetThroughput; private final Long partSizeInMb; private final ChecksumAlgorithm checksumAlgorithm; private final Integer iteration; private final Long contentLengthInMb; private final Duration timeout; private final Long memoryUsageInMb; private final Long connectionAcquisitionTimeoutInSec; private final Boolean forceCrtHttpClient; private final Integer maxConcurrency; private final Long readBufferSizeInMb; private final BenchmarkRunner.TransferManagerOperation operation; private String prefix; private TransferManagerBenchmarkConfig(Builder builder) { this.filePath = builder.filePath; this.bucket = builder.bucket; this.key = builder.key; this.targetThroughput = builder.targetThroughput; this.partSizeInMb = builder.partSizeInMb; this.checksumAlgorithm = builder.checksumAlgorithm; this.iteration = builder.iteration; this.readBufferSizeInMb = builder.readBufferSizeInMb; this.operation = builder.operation; this.prefix = builder.prefix; this.contentLengthInMb = builder.contentLengthInMb; this.timeout = builder.timeout; this.memoryUsageInMb = builder.memoryUsage; this.connectionAcquisitionTimeoutInSec = builder.connectionAcquisitionTimeoutInSec; this.forceCrtHttpClient = builder.forceCrtHttpClient; this.maxConcurrency = builder.maxConcurrency; } public String filePath() { return filePath; } public String bucket() { return bucket; } public String key() { return key; } public Double targetThroughput() { return targetThroughput; } public Long partSizeInMb() { return partSizeInMb; } public ChecksumAlgorithm checksumAlgorithm() { return checksumAlgorithm; } public Integer iteration() { return iteration; } public Long readBufferSizeInMb() { return readBufferSizeInMb; } public BenchmarkRunner.TransferManagerOperation operation() { return operation; } public String prefix() { return prefix; } public Long contentLengthInMb() { return contentLengthInMb; } public Duration timeout() { return this.timeout; } public Long memoryUsageInMb() { return this.memoryUsageInMb; } public Long connectionAcquisitionTimeoutInSec() { return this.connectionAcquisitionTimeoutInSec; } public boolean forceCrtHttpClient() { return this.forceCrtHttpClient; } public Integer maxConcurrency() { return this.maxConcurrency; } public static Builder builder() { return new Builder(); } @Override public String toString() { return ToString.builder("TransferManagerBenchmarkConfig") .add("filePath", filePath) .add("bucket", bucket) .add("key", key) .add("targetThroughput", targetThroughput) .add("partSizeInMb", partSizeInMb) .add("checksumAlgorithm", checksumAlgorithm) .add("iteration", iteration) .add("contentLengthInMb", contentLengthInMb) .add("timeout", timeout) .add("memoryUsageInMb", memoryUsageInMb) .add("connectionAcquisitionTimeoutInSec", connectionAcquisitionTimeoutInSec) .add("forceCrtHttpClient", forceCrtHttpClient) .add("maxConcurrency", maxConcurrency) .add("readBufferSizeInMb", readBufferSizeInMb) .add("operation", operation) .add("prefix", prefix) .build(); } static final class Builder { private Long readBufferSizeInMb; private ChecksumAlgorithm checksumAlgorithm; private String filePath; private String bucket; private String key; private Double targetThroughput; private Long partSizeInMb; private Long contentLengthInMb; private Long memoryUsage; private Long connectionAcquisitionTimeoutInSec; private Boolean forceCrtHttpClient; private Integer maxConcurrency; private Integer iteration; private BenchmarkRunner.TransferManagerOperation operation; private String prefix; private Duration timeout; public Builder filePath(String filePath) { this.filePath = filePath; return this; } public Builder bucket(String bucket) { this.bucket = bucket; return this; } public Builder key(String key) { this.key = key; return this; } public Builder targetThroughput(Double targetThroughput) { this.targetThroughput = targetThroughput; return this; } public Builder partSizeInMb(Long partSizeInMb) { this.partSizeInMb = partSizeInMb; return this; } public Builder checksumAlgorithm(ChecksumAlgorithm checksumAlgorithm) { this.checksumAlgorithm = checksumAlgorithm; return this; } public Builder iteration(Integer iteration) { this.iteration = iteration; return this; } public Builder operation(BenchmarkRunner.TransferManagerOperation operation) { this.operation = operation; return this; } public Builder readBufferSizeInMb(Long readBufferSizeInMb) { this.readBufferSizeInMb = readBufferSizeInMb; return this; } public Builder prefix(String prefix) { this.prefix = prefix; return this; } public Builder contentLengthInMb(Long contentLengthInMb) { this.contentLengthInMb = contentLengthInMb; return this; } public Builder timeout(Duration timeout) { this.timeout = timeout; return this; } public Builder memoryUsageInMb(Long memoryUsage) { this.memoryUsage = memoryUsage; return this; } public Builder connectionAcquisitionTimeoutInSec(Long connectionAcquisitionTimeoutInSec) { this.connectionAcquisitionTimeoutInSec = connectionAcquisitionTimeoutInSec; return this; } public Builder forceCrtHttpClient(Boolean forceCrtHttpClient) { this.forceCrtHttpClient = forceCrtHttpClient; return this; } public Builder maxConcurrency(Integer maxConcurrency) { this.maxConcurrency = maxConcurrency; return this; } public TransferManagerBenchmarkConfig build() { return new TransferManagerBenchmarkConfig(this); } } }
2,989
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/TransferManagerUploadDirectoryBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.printOutResult; import java.io.File; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import software.amazon.awssdk.transfer.s3.model.CompletedDirectoryUpload; import software.amazon.awssdk.transfer.s3.model.DirectoryUpload; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; public class TransferManagerUploadDirectoryBenchmark extends BaseTransferManagerBenchmark { private static final Logger logger = Logger.loggerFor("TransferManagerUploadDirectoryBenchmark"); private final TransferManagerBenchmarkConfig config; public TransferManagerUploadDirectoryBenchmark(TransferManagerBenchmarkConfig config) { super(config); Validate.notNull(config.filePath(), "File path must not be null"); this.config = config; } @Override protected void doRunBenchmark() { try { uploadDirectory(iteration, true); } catch (Exception exception) { logger.error(() -> "Request failed: ", exception); } } private void uploadDirectory(int count, boolean printoutResult) throws Exception { List<Double> metrics = new ArrayList<>(); logger.info(() -> "Starting to upload directory"); for (int i = 0; i < count; i++) { uploadOnce(metrics); } if (printoutResult) { printOutResult(metrics, "TM v2 Upload Directory"); } } private void uploadOnce(List<Double> latencies) throws Exception { Path uploadPath = new File(this.path).toPath(); long start = System.currentTimeMillis(); DirectoryUpload upload = transferManager.uploadDirectory(b -> b.bucket(bucket) .s3Prefix(config.prefix()) .source(uploadPath)); CompletedDirectoryUpload completedDirectoryUpload = upload.completionFuture().get(timeout.getSeconds(), TimeUnit.SECONDS); if (completedDirectoryUpload.failedTransfers().isEmpty()) { long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); } else { logger.error(() -> "Some transfers failed: " + completedDirectoryUpload.failedTransfers()); } } }
2,990
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/JavaS3ClientUploadBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.s3benchmarks; import static software.amazon.awssdk.transfer.s3.SizeConstant.MB; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm; import software.amazon.awssdk.services.s3.model.PutObjectResponse; import software.amazon.awssdk.utils.async.SimplePublisher; public class JavaS3ClientUploadBenchmark extends BaseJavaS3ClientBenchmark { private final String filePath; private final Long contentLengthInMb; private final Long partSizeInMb; private final ChecksumAlgorithm checksumAlgorithm; public JavaS3ClientUploadBenchmark(TransferManagerBenchmarkConfig config) { super(config); this.filePath = config.filePath(); this.contentLengthInMb = config.contentLengthInMb(); this.partSizeInMb = config.partSizeInMb(); this.checksumAlgorithm = config.checksumAlgorithm(); } @Override protected void sendOneRequest(List<Double> latencies) throws Exception { if (filePath == null) { double latency = uploadFromMemory(); latencies.add(latency); return; } Double latency = runWithTime( s3AsyncClient.putObject(req -> req.key(key).bucket(bucket).checksumAlgorithm(checksumAlgorithm), Paths.get(filePath))::join).latency(); latencies.add(latency); } private double uploadFromMemory() throws Exception { if (contentLengthInMb == null) { throw new UnsupportedOperationException("Java upload benchmark - contentLengthInMb required for upload from memory"); } long partSizeInBytes = partSizeInMb * MB; // upload using known content length SimplePublisher<ByteBuffer> publisher = new SimplePublisher<>(); byte[] bytes = new byte[(int) partSizeInBytes]; Thread uploadThread = Executors.defaultThreadFactory().newThread(() -> { long remaining = contentLengthInMb * MB; while (remaining > 0) { publisher.send(ByteBuffer.wrap(bytes)); remaining -= partSizeInBytes; } publisher.complete(); }); CompletableFuture<PutObjectResponse> responseFuture = s3AsyncClient.putObject(r -> r.bucket(bucket) .key(key) .contentLength(contentLengthInMb * MB) .checksumAlgorithm(checksumAlgorithm), AsyncRequestBody.fromPublisher(publisher)); uploadThread.start(); long start = System.currentTimeMillis(); responseFuture.get(timeout.getSeconds(), TimeUnit.SECONDS); long end = System.currentTimeMillis(); return (end - start) / 1000.0; } @Override protected long contentLength() throws Exception { return filePath != null ? Files.size(Paths.get(filePath)) : contentLengthInMb * MB; } }
2,991
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/BenchmarkUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.s3benchmarks; import static software.amazon.awssdk.transfer.s3.SizeConstant.GB; import java.time.Duration; import java.util.Collection; import java.util.List; import software.amazon.awssdk.utils.Logger; public final class BenchmarkUtils { static final int PRE_WARMUP_ITERATIONS = 10; static final int PRE_WARMUP_RUNS = 20; static final int BENCHMARK_ITERATIONS = 10; static final Duration DEFAULT_TIMEOUT = Duration.ofMinutes(10); static final String WARMUP_KEY = "warmupobject"; static final String COPY_SUFFIX = "_copy"; private static final Logger logger = Logger.loggerFor("TransferManagerBenchmark"); private BenchmarkUtils() { } public static void printOutResult(List<Double> metrics, String name, long contentLengthInByte) { logger.info(() -> String.format("=============== %s Result ================", name)); logger.info(() -> String.valueOf(metrics)); double averageLatency = metrics.stream() .mapToDouble(a -> a) .average() .orElse(0.0); double lowestLatency = metrics.stream() .mapToDouble(a -> a) .min().orElse(0.0); double contentLengthInGigabit = (contentLengthInByte / (double) GB) * 8.0; logger.info(() -> "Average latency (s): " + averageLatency); logger.info(() -> "Latency variance (s): " + variance(metrics, averageLatency)); logger.info(() -> "Object size (Gigabit): " + contentLengthInGigabit); logger.info(() -> "Average throughput (Gbps): " + contentLengthInGigabit / averageLatency); logger.info(() -> "Highest average throughput (Gbps): " + contentLengthInGigabit / lowestLatency); logger.info(() -> "=========================================================="); } public static void printOutResult(List<Double> metrics, String name) { logger.info(() -> String.format("=============== %s Result ================", name)); logger.info(() -> String.valueOf(metrics)); double averageLatency = metrics.stream() .mapToDouble(a -> a) .average() .orElse(0.0); double lowestLatency = metrics.stream() .mapToDouble(a -> a) .min() .orElse(0.0); logger.info(() -> "Average latency (s): " + averageLatency); logger.info(() -> "Lowest latency (s): " + lowestLatency); logger.info(() -> "Latency variance (s): " + variance(metrics, averageLatency)); logger.info(() -> "=========================================================="); } /** * calculates the variance (std deviation squared) of the sample * @param sample the values to calculate the variance for * @param mean the known mean of the sample * @return the variance value */ private static double variance(Collection<Double> sample, double mean) { double numerator = 0; for (double value : sample) { double diff = value - mean; numerator += (diff * diff); } return numerator / sample.size(); } }
2,992
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/V1TransferManagerUploadBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.printOutResult; import java.io.File; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; public class V1TransferManagerUploadBenchmark extends V1BaseTransferManagerBenchmark { private static final Logger logger = Logger.loggerFor("V1TransferManagerUploadBenchmark"); private final File sourceFile; V1TransferManagerUploadBenchmark(TransferManagerBenchmarkConfig config) { super(config); Validate.notNull(config.key(), "Key must not be null"); Validate.notNull(config.filePath(), "File path must not be null"); sourceFile = new File(path); } @Override protected void doRunBenchmark() { uploadFile(); } private void uploadFile() { List<Double> metrics = new ArrayList<>(); logger.info(() -> "Starting to upload"); for (int i = 0; i < iteration; i++) { uploadOnce(metrics); } long contentLength = sourceFile.length(); printOutResult(metrics, "TM v1 Upload File", contentLength); } private void uploadOnce(List<Double> latencies) { long start = System.currentTimeMillis(); try { transferManager.upload(bucket, key, sourceFile).waitForCompletion(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.warn(() -> "Thread interrupted when waiting for completion", e); } long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); } }
2,993
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/TransferManagerUploadBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.printOutResult; import static software.amazon.awssdk.transfer.s3.SizeConstant.MB; import java.io.File; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.transfer.s3.model.Upload; import software.amazon.awssdk.transfer.s3.model.UploadRequest; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.async.SimplePublisher; public class TransferManagerUploadBenchmark extends BaseTransferManagerBenchmark { private static final Logger logger = Logger.loggerFor("TransferManagerUploadBenchmark"); private final TransferManagerBenchmarkConfig config; public TransferManagerUploadBenchmark(TransferManagerBenchmarkConfig config) { super(config); Validate.notNull(config.key(), "Key must not be null"); Validate.mutuallyExclusive("Only one of --file or --contentLengthInMB option must be specified, but both were.", config.filePath(), config.contentLengthInMb()); if (config.filePath() == null && config.contentLengthInMb() == null) { throw new IllegalArgumentException("Either --file or --contentLengthInMB must be specified, but none were."); } this.config = config; } @Override protected void doRunBenchmark() { try { doUpload(iteration, true); } catch (Exception exception) { logger.error(() -> "Request failed: ", exception); } } @Override protected void additionalWarmup() { try { doUpload(3, false); } catch (Exception exception) { logger.error(() -> "Warmup failed: ", exception); } } private void doUpload(int count, boolean printOutResult) throws Exception { List<Double> metrics = new ArrayList<>(); for (int i = 0; i < count; i++) { if (config.contentLengthInMb() == null) { logger.info(() -> "Starting to upload from file"); uploadOnceFromFile(metrics); } else { logger.info(() -> "Starting to upload from memory"); uploadOnceFromMemory(metrics); } } if (printOutResult) { if (config.contentLengthInMb() == null) { printOutResult(metrics, "Upload from File", Files.size(Paths.get(path))); } else { printOutResult(metrics, "Upload from Memory", config.contentLengthInMb() * MB); } } } private void uploadOnceFromFile(List<Double> latencies) { File sourceFile = new File(path); long start = System.currentTimeMillis(); transferManager.uploadFile(b -> b.putObjectRequest(r -> r.bucket(bucket) .key(key) .checksumAlgorithm(config.checksumAlgorithm())) .source(sourceFile.toPath())) .completionFuture().join(); long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); } private void uploadOnceFromMemory(List<Double> latencies) throws Exception { SimplePublisher<ByteBuffer> publisher = new SimplePublisher<>(); long partSizeInBytes = config.partSizeInMb() * MB; byte[] bytes = new byte[(int) partSizeInBytes]; UploadRequest uploadRequest = UploadRequest .builder() .putObjectRequest(r -> r.bucket(bucket) .key(key) .contentLength(config.contentLengthInMb() * MB) .checksumAlgorithm(config.checksumAlgorithm())) .requestBody(AsyncRequestBody.fromPublisher(publisher)) .build(); Thread uploadThread = Executors.defaultThreadFactory().newThread(() -> { long remaining = config.contentLengthInMb() * MB; while (remaining > 0) { publisher.send(ByteBuffer.wrap(bytes)); remaining -= partSizeInBytes; } publisher.complete(); }); Upload upload = transferManager.upload(uploadRequest); uploadThread.start(); long start = System.currentTimeMillis(); upload.completionFuture().get(timeout.getSeconds(), TimeUnit.SECONDS); long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); } }
2,994
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/V1TransferManagerDownloadBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.printOutResult; import static software.amazon.awssdk.utils.FunctionalUtils.runAndLogError; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; public class V1TransferManagerDownloadBenchmark extends V1BaseTransferManagerBenchmark { private static final Logger logger = Logger.loggerFor("V1TransferManagerDownloadBenchmark"); V1TransferManagerDownloadBenchmark(TransferManagerBenchmarkConfig config) { super(config); Validate.notNull(config.key(), "Key must not be null"); Validate.notNull(config.filePath(), "File path must not be null"); } @Override protected void doRunBenchmark() { downloadToFile(); } private void downloadToFile() { List<Double> metrics = new ArrayList<>(); logger.info(() -> "Starting to download to file"); for (int i = 0; i < iteration; i++) { downloadOnceToFile(metrics); } long contentLength = s3Client.getObjectMetadata(bucket, key).getContentLength(); printOutResult(metrics, "V1 Download to File", contentLength); } private void downloadOnceToFile(List<Double> latencies) { Path downloadPath = new File(this.path).toPath(); long start = System.currentTimeMillis(); try { transferManager.download(bucket, key, new File(this.path)).waitForCompletion(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.warn(() -> "Thread interrupted when waiting for completion", e); } long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); runAndLogError(logger.logger(), "Deleting file failed", () -> Files.delete(downloadPath)); } }
2,995
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/CrtS3ClientDownloadBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.s3benchmarks; import java.net.URI; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import software.amazon.awssdk.crt.http.HttpHeader; import software.amazon.awssdk.crt.http.HttpRequest; import software.amazon.awssdk.crt.s3.S3MetaRequest; import software.amazon.awssdk.crt.s3.S3MetaRequestOptions; import software.amazon.awssdk.crt.s3.S3MetaRequestResponseHandler; public class CrtS3ClientDownloadBenchmark extends BaseCrtClientBenchmark { public CrtS3ClientDownloadBenchmark(TransferManagerBenchmarkConfig config) { super(config); } @Override protected void sendOneRequest(List<Double> latencies) throws Exception { CompletableFuture<Void> resultFuture = new CompletableFuture<>(); S3MetaRequestResponseHandler responseHandler = new TestS3MetaRequestResponseHandler(resultFuture); String endpoint = bucket + ".s3." + region + ".amazonaws.com"; HttpHeader[] headers = {new HttpHeader("Host", endpoint)}; HttpRequest httpRequest = new HttpRequest("GET", "/" + key, headers, null); S3MetaRequestOptions metaRequestOptions = new S3MetaRequestOptions() .withEndpoint(URI.create("https://" + endpoint)) .withMetaRequestType(S3MetaRequestOptions.MetaRequestType.GET_OBJECT).withHttpRequest(httpRequest) .withResponseHandler(responseHandler); long start = System.currentTimeMillis(); try (S3MetaRequest metaRequest = crtS3Client.makeMetaRequest(metaRequestOptions)) { resultFuture.get(10, TimeUnit.MINUTES); } long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); } }
2,996
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/V1TransferManagerUploadDirectoryBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.printOutResult; import java.io.File; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; public class V1TransferManagerUploadDirectoryBenchmark extends V1BaseTransferManagerBenchmark { private static final Logger logger = Logger.loggerFor("V1TransferManagerUploadDirectoryBenchmark"); private final TransferManagerBenchmarkConfig config; private final File sourceFile; V1TransferManagerUploadDirectoryBenchmark(TransferManagerBenchmarkConfig config) { super(config); Validate.notNull(config.filePath(), "File path must not be null"); sourceFile = new File(path); this.config = config; } @Override protected void doRunBenchmark() { upload(); } private void upload() { List<Double> metrics = new ArrayList<>(); logger.info(() -> "Starting to upload directory"); for (int i = 0; i < iteration; i++) { uploadOnce(metrics); } printOutResult(metrics, "TM v1 Upload Directory"); } private void uploadOnce(List<Double> latencies) { long start = System.currentTimeMillis(); try { transferManager.uploadDirectory(bucket, config.prefix(), sourceFile, true).waitForCompletion(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.warn(() -> "Thread interrupted when waiting for completion", e); } long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); } }
2,997
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/JavaS3ClientCopyBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.COPY_SUFFIX; import java.util.List; import software.amazon.awssdk.utils.Logger; public class JavaS3ClientCopyBenchmark extends BaseJavaS3ClientBenchmark { private static final Logger log = Logger.loggerFor(JavaS3ClientCopyBenchmark.class); public JavaS3ClientCopyBenchmark(TransferManagerBenchmarkConfig config) { super(config); } @Override protected void sendOneRequest(List<Double> latencies) throws Exception { log.info(() -> "Starting copy"); Double latency = runWithTime(s3AsyncClient.copyObject( req -> req.sourceKey(key).sourceBucket(bucket) .destinationBucket(bucket).destinationKey(key + COPY_SUFFIX) )::join).latency(); latencies.add(latency); } @Override protected long contentLength() throws Exception { return s3Client.headObject(b -> b.bucket(bucket).key(key)).contentLength(); } }
2,998
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/BaseCrtClientBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.BENCHMARK_ITERATIONS; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.printOutResult; import static software.amazon.awssdk.transfer.s3.SizeConstant.MB; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.s3.S3Client; import software.amazon.awssdk.crt.s3.S3ClientOptions; import software.amazon.awssdk.crt.s3.S3FinishedResponseContext; import software.amazon.awssdk.crt.s3.S3MetaRequestResponseHandler; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.providers.AwsRegionProvider; import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain; import software.amazon.awssdk.services.s3.internal.crt.S3NativeClientConfiguration; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; public abstract class BaseCrtClientBenchmark implements TransferManagerBenchmark { private static final Logger logger = Logger.loggerFor(BaseCrtClientBenchmark.class); protected final String bucket; protected final String key; protected final int iteration; protected final S3NativeClientConfiguration s3NativeClientConfiguration; protected final S3Client crtS3Client; protected final software.amazon.awssdk.services.s3.S3Client s3Sync; protected final Region region; protected final long contentLength; protected BaseCrtClientBenchmark(TransferManagerBenchmarkConfig config) { logger.info(() -> "Benchmark config: " + config); Validate.isNull(config.filePath(), "File path is not supported in CrtS3ClientBenchmark"); Long partSizeInBytes = config.partSizeInMb() == null ? null : config.partSizeInMb() * MB; this.s3NativeClientConfiguration = S3NativeClientConfiguration.builder() .partSizeInBytes(partSizeInBytes) .targetThroughputInGbps(config.targetThroughput() == null ? Double.valueOf(100.0) : config.targetThroughput()) .checksumValidationEnabled(true) .build(); this.bucket = config.bucket(); this.key = config.key(); this.iteration = config.iteration() == null ? BENCHMARK_ITERATIONS : config.iteration(); S3ClientOptions s3ClientOptions = new S3ClientOptions().withRegion(s3NativeClientConfiguration.signingRegion()) .withEndpoint(s3NativeClientConfiguration.endpointOverride() == null ? null : s3NativeClientConfiguration.endpointOverride().toString()) .withCredentialsProvider(s3NativeClientConfiguration.credentialsProvider()) .withClientBootstrap(s3NativeClientConfiguration.clientBootstrap()) .withPartSize(s3NativeClientConfiguration.partSizeBytes()) .withComputeContentMd5(false) .withThroughputTargetGbps(s3NativeClientConfiguration.targetThroughputInGbps()); Long readBufferSizeInMb = config.readBufferSizeInMb() == null ? null : config.readBufferSizeInMb() * MB; if (readBufferSizeInMb != null) { s3ClientOptions.withInitialReadWindowSize(readBufferSizeInMb); s3ClientOptions.withReadBackpressureEnabled(true); } this.crtS3Client = new S3Client(s3ClientOptions); s3Sync = software.amazon.awssdk.services.s3.S3Client.builder().build(); this.contentLength = s3Sync.headObject(b -> b.bucket(bucket).key(key)).contentLength(); AwsRegionProvider instanceProfileRegionProvider = new DefaultAwsRegionProviderChain(); region = instanceProfileRegionProvider.getRegion(); } protected abstract void sendOneRequest(List<Double> latencies) throws Exception; @Override public void run() { try { warmUp(); doRunBenchmark(); } catch (Exception e) { logger.error(() -> "Exception occurred", e); } finally { cleanup(); } } private void cleanup() { s3Sync.close(); s3NativeClientConfiguration.close(); crtS3Client.close(); } private void warmUp() throws Exception { logger.info(() -> "Starting to warm up"); for (int i = 0; i < 3; i++) { sendOneRequest(new ArrayList<>()); Thread.sleep(500); } logger.info(() -> "Ending warm up"); } private void doRunBenchmark() throws Exception { List<Double> metrics = new ArrayList<>(); for (int i = 0; i < iteration; i++) { sendOneRequest(metrics); } printOutResult(metrics, "Download to File", contentLength); } protected static final class TestS3MetaRequestResponseHandler implements S3MetaRequestResponseHandler { private final CompletableFuture<Void> resultFuture; TestS3MetaRequestResponseHandler(CompletableFuture<Void> resultFuture) { this.resultFuture = resultFuture; } @Override public int onResponseBody(ByteBuffer bodyBytesIn, long objectRangeStart, long objectRangeEnd) { return bodyBytesIn.remaining(); } @Override public void onFinished(S3FinishedResponseContext context) { if (context.getErrorCode() != 0) { String errorMessage = String.format("Request failed. %s Response status: %s ", CRT.awsErrorString(context.getErrorCode()), context.getResponseStatus()); resultFuture.completeExceptionally( SdkClientException.create(errorMessage)); return; } resultFuture.complete(null); } } }
2,999