index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __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/metrics/SyncClientMetricPublisherResolutionTest.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.metrics;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Arrays;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
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.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClientBuilder;
import software.amazon.awssdk.services.testutil.MockIdentityProviderUtil;
@RunWith(MockitoJUnitRunner.class)
public class SyncClientMetricPublisherResolutionTest {
@Mock
private SdkHttpClient mockHttpClient;
private ProtocolRestJsonClient client;
@After
public void teardown() {
if (client != null) {
client.close();
}
client = null;
}
@Test
public void testApiCall_noPublishersSet_noException() throws IOException {
client = clientWithPublishers();
client.allTypes();
}
@Test
public void testApiCall_publishersSetOnClient_clientPublishersInvoked() throws IOException {
MetricPublisher publisher1 = mock(MetricPublisher.class);
MetricPublisher publisher2 = mock(MetricPublisher.class);
client = clientWithPublishers(publisher1, publisher2);
try {
client.allTypes();
} catch (Throwable t) {
// ignored, call fails because our mock HTTP client isn't set up
} finally {
verify(publisher1).publish(any(MetricCollection.class));
verify(publisher2).publish(any(MetricCollection.class));
}
}
@Test
public void testApiCall_publishersSetOnRequest_requestPublishersInvoked() throws IOException {
MetricPublisher publisher1 = mock(MetricPublisher.class);
MetricPublisher publisher2 = mock(MetricPublisher.class);
client = clientWithPublishers();
try {
client.allTypes(r -> r.overrideConfiguration(o ->
o.addMetricPublisher(publisher1).addMetricPublisher(publisher2)));
} catch (Throwable t) {
// ignored, call fails because our mock HTTP client isn't set up
} finally {
verify(publisher1).publish(any(MetricCollection.class));
verify(publisher2).publish(any(MetricCollection.class));
}
}
@Test
public void testApiCall_publishersSetOnClientAndRequest_requestPublishersInvoked() throws IOException {
MetricPublisher clientPublisher1 = mock(MetricPublisher.class);
MetricPublisher clientPublisher2 = mock(MetricPublisher.class);
MetricPublisher requestPublisher1 = mock(MetricPublisher.class);
MetricPublisher requestPublisher2 = mock(MetricPublisher.class);
client = clientWithPublishers(clientPublisher1, clientPublisher2);
try {
client.allTypes(r -> r.overrideConfiguration(o ->
o.addMetricPublisher(requestPublisher1).addMetricPublisher(requestPublisher2)));
} catch (Throwable t) {
// ignored, call fails because our mock HTTP client isn't set up
} finally {
verify(requestPublisher1).publish(any(MetricCollection.class));
verify(requestPublisher2).publish(any(MetricCollection.class));
verifyNoMoreInteractions(clientPublisher1);
verifyNoMoreInteractions(clientPublisher2);
}
}
private ProtocolRestJsonClient clientWithPublishers(MetricPublisher... metricPublishers) throws IOException {
ProtocolRestJsonClientBuilder builder = ProtocolRestJsonClient.builder()
.httpClient(mockHttpClient)
.region(Region.US_WEST_2)
.credentialsProvider(MockIdentityProviderUtil.mockIdentityProvider());
AbortableInputStream content = AbortableInputStream.create(new ByteArrayInputStream("{}".getBytes()));
SdkHttpFullResponse httpResponse = SdkHttpFullResponse.builder()
.statusCode(200)
.content(content)
.build();
HttpExecuteResponse mockResponse = mockExecuteResponse(httpResponse);
ExecutableHttpRequest mockExecuteRequest = mock(ExecutableHttpRequest.class);
when(mockExecuteRequest.call()).thenAnswer(invocation -> {
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
return mockResponse;
});
when(mockHttpClient.prepareRequest(any(HttpExecuteRequest.class)))
.thenReturn(mockExecuteRequest);
if (metricPublishers != null) {
builder.overrideConfiguration(o -> o.metricPublishers(Arrays.asList(metricPublishers)));
}
return builder.build();
}
private static HttpExecuteResponse mockExecuteResponse(SdkHttpFullResponse httpResponse) {
HttpExecuteResponse mockResponse = mock(HttpExecuteResponse.class);
when(mockResponse.httpResponse()).thenReturn(httpResponse);
when(mockResponse.responseBody()).thenReturn(httpResponse.content());
return mockResponse;
}
}
| 2,600 |
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/metrics/CoreMetricsTest.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.metrics;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URI;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.core.internal.metrics.SdkErrorType;
import software.amazon.awssdk.core.metrics.CoreMetric;
import software.amazon.awssdk.endpoints.Endpoint;
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.HttpMetric;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.services.protocolrestjson.endpoints.ProtocolRestJsonEndpointParams;
import software.amazon.awssdk.services.protocolrestjson.endpoints.ProtocolRestJsonEndpointProvider;
import software.amazon.awssdk.services.protocolrestjson.model.EmptyModeledException;
import software.amazon.awssdk.services.protocolrestjson.model.SimpleStruct;
import software.amazon.awssdk.services.protocolrestjson.paginators.PaginatedOperationWithResultKeyIterable;
import software.amazon.awssdk.services.testutil.MockIdentityProviderUtil;
@RunWith(MockitoJUnitRunner.class)
public class CoreMetricsTest {
private static final String SERVICE_ID = "AmazonProtocolRestJson";
private static final String REQUEST_ID = "req-id";
private static final String EXTENDED_REQUEST_ID = "extended-id";
private static final int MAX_RETRIES = 2;
private static ProtocolRestJsonClient client;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Mock
private SdkHttpClient mockHttpClient;
@Mock
private MetricPublisher mockPublisher;
@Mock
private ProtocolRestJsonEndpointProvider mockEndpointProvider;
@Before
public void setup() throws IOException {
client = ProtocolRestJsonClient.builder()
.httpClient(mockHttpClient)
.region(Region.US_WEST_2)
.credentialsProvider(MockIdentityProviderUtil.mockIdentityProvider())
.overrideConfiguration(c -> c.addMetricPublisher(mockPublisher).retryPolicy(b -> b.numRetries(MAX_RETRIES)))
.endpointProvider(mockEndpointProvider)
.build();
AbortableInputStream content = contentStream("{}");
SdkHttpFullResponse httpResponse = SdkHttpFullResponse.builder()
.statusCode(200)
.putHeader("x-amz-request-id", REQUEST_ID)
.putHeader("x-amz-id-2", EXTENDED_REQUEST_ID)
.content(content)
.build();
HttpExecuteResponse mockResponse = mockExecuteResponse(httpResponse);
ExecutableHttpRequest mockExecuteRequest = mock(ExecutableHttpRequest.class);
when(mockExecuteRequest.call()).thenAnswer(invocation -> {
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
return mockResponse;
});
when(mockHttpClient.prepareRequest(any(HttpExecuteRequest.class)))
.thenReturn(mockExecuteRequest);
when(mockEndpointProvider.resolveEndpoint(any(ProtocolRestJsonEndpointParams.class))).thenReturn(
CompletableFuture.completedFuture(Endpoint.builder()
.url(URI.create("https://protocolrestjson.amazonaws.com"))
.build()));
}
@After
public void teardown() {
if (client != null) {
client.close();
}
client = null;
}
@Test
public void testApiCall_noConfiguredPublisher_succeeds() {
ProtocolRestJsonClient noPublisher = ProtocolRestJsonClient.builder()
.region(Region.US_WEST_2)
.credentialsProvider(MockIdentityProviderUtil.mockIdentityProvider())
.httpClient(mockHttpClient)
.build();
noPublisher.allTypes();
}
@Test
public void testApiCall_publisherOverriddenOnRequest_requestPublisherTakesPrecedence() {
MetricPublisher requestMetricPublisher = mock(MetricPublisher.class);
client.allTypes(r -> r.overrideConfiguration(o -> o.addMetricPublisher(requestMetricPublisher)));
verify(requestMetricPublisher).publish(any(MetricCollection.class));
verifyNoMoreInteractions(mockPublisher);
}
@Test
public void testPaginatingApiCall_publisherOverriddenOnRequest_requestPublisherTakesPrecedence() {
MetricPublisher requestMetricPublisher = mock(MetricPublisher.class);
PaginatedOperationWithResultKeyIterable iterable =
client.paginatedOperationWithResultKeyPaginator(
r -> r.overrideConfiguration(o -> o.addMetricPublisher(requestMetricPublisher)));
List<SimpleStruct> resultingItems = iterable.items().stream().collect(Collectors.toList());
verify(requestMetricPublisher).publish(any(MetricCollection.class));
verifyNoMoreInteractions(mockPublisher);
}
@Test
public void testApiCall_operationSuccessful_addsMetrics() {
client.allTypes();
ArgumentCaptor<MetricCollection> collectionCaptor = ArgumentCaptor.forClass(MetricCollection.class);
verify(mockPublisher).publish(collectionCaptor.capture());
MetricCollection capturedCollection = collectionCaptor.getValue();
assertThat(capturedCollection.name()).isEqualTo("ApiCall");
assertThat(capturedCollection.metricValues(CoreMetric.SERVICE_ID))
.containsExactly(SERVICE_ID);
assertThat(capturedCollection.metricValues(CoreMetric.OPERATION_NAME))
.containsExactly("AllTypes");
assertThat(capturedCollection.metricValues(CoreMetric.API_CALL_SUCCESSFUL)).containsExactly(true);
assertThat(capturedCollection.metricValues(CoreMetric.API_CALL_DURATION).get(0))
.isGreaterThan(Duration.ZERO);
assertThat(capturedCollection.metricValues(CoreMetric.CREDENTIALS_FETCH_DURATION).get(0))
.isGreaterThanOrEqualTo(Duration.ZERO);
assertThat(capturedCollection.metricValues(CoreMetric.MARSHALLING_DURATION).get(0))
.isGreaterThanOrEqualTo(Duration.ZERO);
assertThat(capturedCollection.metricValues(CoreMetric.RETRY_COUNT)).containsExactly(0);
assertThat(capturedCollection.metricValues(CoreMetric.SERVICE_ENDPOINT).get(0)).isEqualTo(URI.create(
"https://protocolrestjson.amazonaws.com"));
assertThat(capturedCollection.children()).hasSize(1);
MetricCollection attemptCollection = capturedCollection.children().get(0);
assertThat(attemptCollection.name()).isEqualTo("ApiCallAttempt");
assertThat(attemptCollection.metricValues(CoreMetric.BACKOFF_DELAY_DURATION))
.containsExactly(Duration.ZERO);
assertThat(attemptCollection.metricValues(HttpMetric.HTTP_STATUS_CODE))
.containsExactly(200);
assertThat(attemptCollection.metricValues(CoreMetric.SIGNING_DURATION).get(0))
.isGreaterThanOrEqualTo(Duration.ZERO);
assertThat(attemptCollection.metricValues(CoreMetric.AWS_REQUEST_ID))
.containsExactly(REQUEST_ID);
assertThat(attemptCollection.metricValues(CoreMetric.AWS_EXTENDED_REQUEST_ID))
.containsExactly(EXTENDED_REQUEST_ID);
assertThat(attemptCollection.metricValues(CoreMetric.SERVICE_CALL_DURATION).get(0))
.isGreaterThanOrEqualTo(Duration.ofMillis(100));
assertThat(attemptCollection.metricValues(CoreMetric.UNMARSHALLING_DURATION).get(0))
.isGreaterThanOrEqualTo(Duration.ZERO);
}
@Test
public void testApiCall_serviceReturnsError_errorInfoIncludedInMetrics() throws IOException {
AbortableInputStream content = contentStream("{}");
SdkHttpFullResponse httpResponse = SdkHttpFullResponse.builder()
.statusCode(500)
.putHeader("x-amz-request-id", REQUEST_ID)
.putHeader("x-amz-id-2", EXTENDED_REQUEST_ID)
.putHeader("X-Amzn-Errortype", "EmptyModeledException")
.content(content)
.build();
HttpExecuteResponse response = mockExecuteResponse(httpResponse);
ExecutableHttpRequest mockExecuteRequest = mock(ExecutableHttpRequest.class);
when(mockExecuteRequest.call()).thenReturn(response);
when(mockHttpClient.prepareRequest(any(HttpExecuteRequest.class)))
.thenReturn(mockExecuteRequest);
thrown.expect(EmptyModeledException.class);
try {
client.allTypes();
} finally {
ArgumentCaptor<MetricCollection> collectionCaptor = ArgumentCaptor.forClass(MetricCollection.class);
verify(mockPublisher).publish(collectionCaptor.capture());
MetricCollection capturedCollection = collectionCaptor.getValue();
assertThat(capturedCollection.children()).hasSize(MAX_RETRIES + 1);
assertThat(capturedCollection.metricValues(CoreMetric.RETRY_COUNT)).containsExactly(MAX_RETRIES);
assertThat(capturedCollection.metricValues(CoreMetric.API_CALL_SUCCESSFUL)).containsExactly(false);
for (MetricCollection requestMetrics : capturedCollection.children()) {
// A service exception is still a successful HTTP execution so
// we should still have HTTP metrics as well.
assertThat(requestMetrics.metricValues(HttpMetric.HTTP_STATUS_CODE))
.containsExactly(500);
assertThat(requestMetrics.metricValues(CoreMetric.AWS_REQUEST_ID))
.containsExactly(REQUEST_ID);
assertThat(requestMetrics.metricValues(CoreMetric.AWS_EXTENDED_REQUEST_ID))
.containsExactly(EXTENDED_REQUEST_ID);
assertThat(requestMetrics.metricValues(CoreMetric.SERVICE_CALL_DURATION)).hasOnlyOneElementSatisfying(d -> {
assertThat(d).isGreaterThanOrEqualTo(Duration.ZERO);
});
assertThat(requestMetrics.metricValues(CoreMetric.UNMARSHALLING_DURATION)).hasOnlyOneElementSatisfying(d -> {
assertThat(d).isGreaterThanOrEqualTo(Duration.ZERO);
});
assertThat(requestMetrics.metricValues(CoreMetric.ERROR_TYPE)).containsExactly(SdkErrorType.SERVER_ERROR.toString());
}
}
}
@Test
public void testApiCall_httpClientThrowsNetworkError_errorTypeIncludedInMetrics() throws IOException {
ExecutableHttpRequest mockExecuteRequest = mock(ExecutableHttpRequest.class);
when(mockExecuteRequest.call()).thenThrow(new IOException("I/O error"));
when(mockHttpClient.prepareRequest(any(HttpExecuteRequest.class)))
.thenReturn(mockExecuteRequest);
thrown.expect(SdkException.class);
try {
client.allTypes();
} finally {
ArgumentCaptor<MetricCollection> collectionCaptor = ArgumentCaptor.forClass(MetricCollection.class);
verify(mockPublisher).publish(collectionCaptor.capture());
MetricCollection capturedCollection = collectionCaptor.getValue();
assertThat(capturedCollection.children()).isNotEmpty();
for (MetricCollection requestMetrics : capturedCollection.children()) {
assertThat(requestMetrics.metricValues(CoreMetric.ERROR_TYPE)).containsExactly(SdkErrorType.IO.toString());
}
}
}
@Test
public void testApiCall_endpointProviderAddsPathQueryFragment_notReportedInServiceEndpointMetric() {
when(mockEndpointProvider.resolveEndpoint(any(ProtocolRestJsonEndpointParams.class)))
.thenReturn(CompletableFuture.completedFuture(Endpoint.builder()
.url(URI.create("https://protocolrestjson.amazonaws.com:8080/foo?bar#baz"))
.build()));
client.allTypes();
ArgumentCaptor<MetricCollection> collectionCaptor = ArgumentCaptor.forClass(MetricCollection.class);
verify(mockPublisher).publish(collectionCaptor.capture());
MetricCollection capturedCollection = collectionCaptor.getValue();
URI expectedServiceEndpoint = URI.create("https://protocolrestjson.amazonaws.com:8080");
assertThat(capturedCollection.metricValues(CoreMetric.SERVICE_ENDPOINT)).containsExactly(expectedServiceEndpoint);
}
private static HttpExecuteResponse mockExecuteResponse(SdkHttpFullResponse httpResponse) {
HttpExecuteResponse mockResponse = mock(HttpExecuteResponse.class);
when(mockResponse.httpResponse()).thenReturn(httpResponse);
when(mockResponse.responseBody()).thenReturn(httpResponse.content());
return mockResponse;
}
private static AbortableInputStream contentStream(String content) {
ByteArrayInputStream baos = new ByteArrayInputStream(content.getBytes());
return AbortableInputStream.create(baos);
}
}
| 2,601 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/metrics | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/metrics/async/AsyncEventStreamingCoreMetricsTest.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.metrics.async;
import static org.mockito.Mockito.when;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.net.URI;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
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.core.async.EmptyPublisher;
import software.amazon.awssdk.core.signer.NoOpSigner;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient;
import software.amazon.awssdk.services.protocolrestjson.model.EventStreamOperationRequest;
import software.amazon.awssdk.services.protocolrestjson.model.EventStreamOperationResponseHandler;
import software.amazon.awssdk.services.testutil.MockIdentityProviderUtil;
/**
* Core metrics test for async streaming API
*/
@RunWith(MockitoJUnitRunner.class)
public class AsyncEventStreamingCoreMetricsTest extends BaseAsyncCoreMetricsTest {
@Rule
public WireMockRule wireMock = new WireMockRule(0);
@Mock
private MetricPublisher mockPublisher;
private ProtocolRestJsonAsyncClient client;
@Before
public void setup() {
client = ProtocolRestJsonAsyncClient.builder()
.region(Region.US_WEST_2)
.credentialsProvider(MockIdentityProviderUtil.mockIdentityProvider())
.endpointOverride(URI.create("http://localhost:" + wireMock.port()))
.overrideConfiguration(c -> c.addMetricPublisher(mockPublisher)
.retryPolicy(b -> b.numRetries(MAX_RETRIES)))
.build();
}
@After
public void teardown() {
wireMock.resetAll();
if (client != null) {
client.close();
}
client = null;
}
@Override
String operationName() {
return "EventStreamOperation";
}
@Override
Supplier<CompletableFuture<?>> callable() {
return () -> client.eventStreamOperation(EventStreamOperationRequest.builder().overrideConfiguration(b -> b.signer(new NoOpSigner())).build(),
new EmptyPublisher<>(),
EventStreamOperationResponseHandler.builder()
.subscriber(b -> {})
.build());
}
@Override
MetricPublisher publisher() {
return mockPublisher;
}
}
| 2,602 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/metrics | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/metrics/async/AsyncCoreMetricsTest.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.metrics.async;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
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.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient;
import software.amazon.awssdk.services.protocolrestjson.model.PaginatedOperationWithResultKeyResponse;
import software.amazon.awssdk.services.protocolrestjson.paginators.PaginatedOperationWithResultKeyPublisher;
import software.amazon.awssdk.services.testutil.MockIdentityProviderUtil;
/**
* Core metrics test for async non-streaming API
*/
@RunWith(MockitoJUnitRunner.class)
public class AsyncCoreMetricsTest extends BaseAsyncCoreMetricsTest {
@Mock
private MetricPublisher mockPublisher;
@Rule
public WireMockRule wireMock = new WireMockRule(0);
private ProtocolRestJsonAsyncClient client;
@Before
public void setup() throws IOException {
client = ProtocolRestJsonAsyncClient.builder()
.region(Region.US_WEST_2)
.credentialsProvider(MockIdentityProviderUtil.mockIdentityProvider())
.endpointOverride(URI.create("http://localhost:" + wireMock.port()))
.overrideConfiguration(c -> c.addMetricPublisher(mockPublisher).retryPolicy(b -> b.numRetries(MAX_RETRIES)))
.build();
}
@After
public void teardown() {
wireMock.resetAll();
if (client != null) {
client.close();
}
client = null;
}
@Override
String operationName() {
return "AllTypes";
}
@Override
Supplier<CompletableFuture<?>> callable() {
return () -> client.allTypes();
}
@Override
MetricPublisher publisher() {
return mockPublisher;
}
@Test
public void apiCall_noConfiguredPublisher_succeeds() {
stubSuccessfulResponse();
ProtocolRestJsonAsyncClient noPublisher = ProtocolRestJsonAsyncClient.builder()
.region(Region.US_WEST_2)
.credentialsProvider(MockIdentityProviderUtil.mockIdentityProvider())
.endpointOverride(URI.create("http://localhost:" + wireMock.port()))
.build();
noPublisher.allTypes().join();
}
@Test
public void apiCall_publisherOverriddenOnRequest_requestPublisherTakesPrecedence() {
stubSuccessfulResponse();
MetricPublisher requestMetricPublisher = mock(MetricPublisher.class);
client.allTypes(r -> r.overrideConfiguration(o -> o.addMetricPublisher(requestMetricPublisher))).join();
verify(requestMetricPublisher).publish(any(MetricCollection.class));
verifyNoMoreInteractions(mockPublisher);
}
@Test
public void testPaginatingApiCall_publisherOverriddenOnRequest_requestPublisherTakesPrecedence() throws Exception {
stubSuccessfulResponse();
MetricPublisher requestMetricPublisher = mock(MetricPublisher.class);
PaginatedOperationWithResultKeyPublisher paginatedPublisher =
client.paginatedOperationWithResultKeyPaginator(
r -> r.overrideConfiguration(o -> o.addMetricPublisher(requestMetricPublisher)));
CompletableFuture<Void> future = paginatedPublisher.subscribe(PaginatedOperationWithResultKeyResponse::items);
future.get();
verify(requestMetricPublisher).publish(any(MetricCollection.class));
verifyNoMoreInteractions(mockPublisher);
}
}
| 2,603 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/metrics | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/metrics/async/AsyncClientMetricPublisherResolutionTest.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.metrics.async;
import static org.hamcrest.Matchers.instanceOf;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import org.junit.After;
import org.junit.Before;
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.junit.MockitoJUnitRunner;
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.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClientBuilder;
import software.amazon.awssdk.services.protocolrestjson.model.ProtocolRestJsonException;
import software.amazon.awssdk.services.testutil.MockIdentityProviderUtil;
@RunWith(MockitoJUnitRunner.class)
public class AsyncClientMetricPublisherResolutionTest {
@Rule
public WireMockRule wireMock = new WireMockRule(0);
@Rule
public ExpectedException thrown = ExpectedException.none();
private ProtocolRestJsonAsyncClient client;
@After
public void teardown() {
wireMock.resetAll();
if (client != null) {
client.close();
}
client = null;
}
@Test
public void testApiCall_noPublishersSet_noNpe() {
client = clientWithPublishers();
// This is thrown because all the requests to our wiremock are
// nonsense, it's just important that we don't get NPE because we
// don't have publishers set
thrown.expectCause(instanceOf(ProtocolRestJsonException.class));
client.allTypes().join();
}
@Test
public void testApiCall_publishersSetOnClient_clientPublishersInvoked() throws IOException {
MetricPublisher publisher1 = mock(MetricPublisher.class);
MetricPublisher publisher2 = mock(MetricPublisher.class);
client = clientWithPublishers(publisher1, publisher2);
try {
client.allTypes().join();
} catch (Throwable t) {
// ignored, call fails because our mock HTTP client isn't set up
} finally {
verify(publisher1).publish(any(MetricCollection.class));
verify(publisher2).publish(any(MetricCollection.class));
}
}
@Test
public void testApiCall_publishersSetOnRequest_requestPublishersInvoked() throws IOException {
MetricPublisher publisher1 = mock(MetricPublisher.class);
MetricPublisher publisher2 = mock(MetricPublisher.class);
client = clientWithPublishers();
try {
client.allTypes(r -> r.overrideConfiguration(o ->
o.addMetricPublisher(publisher1).addMetricPublisher(publisher2)))
.join();
} catch (Throwable t) {
// ignored, call fails because our mock HTTP client isn't set up
} finally {
verify(publisher1).publish(any(MetricCollection.class));
verify(publisher2).publish(any(MetricCollection.class));
}
}
@Test
public void testApiCall_publishersSetOnClientAndRequest_requestPublishersInvoked() throws IOException {
MetricPublisher clientPublisher1 = mock(MetricPublisher.class);
MetricPublisher clientPublisher2 = mock(MetricPublisher.class);
MetricPublisher requestPublisher1 = mock(MetricPublisher.class);
MetricPublisher requestPublisher2 = mock(MetricPublisher.class);
client = clientWithPublishers(clientPublisher1, clientPublisher2);
try {
client.allTypes(r -> r.overrideConfiguration(o ->
o.addMetricPublisher(requestPublisher1).addMetricPublisher(requestPublisher2)))
.join();
} catch (Throwable t) {
// ignored, call fails because our mock HTTP client isn't set up
} finally {
verify(requestPublisher1).publish(any(MetricCollection.class));
verify(requestPublisher2).publish(any(MetricCollection.class));
verifyNoMoreInteractions(clientPublisher1);
verifyNoMoreInteractions(clientPublisher2);
}
}
private ProtocolRestJsonAsyncClient clientWithPublishers(MetricPublisher... metricPublishers) {
ProtocolRestJsonAsyncClientBuilder builder = ProtocolRestJsonAsyncClient.builder()
.region(Region.US_WEST_2)
.credentialsProvider(MockIdentityProviderUtil.mockIdentityProvider())
.endpointOverride(URI.create("http://localhost:" + wireMock.port()));
if (metricPublishers != null) {
builder.overrideConfiguration(o -> o.metricPublishers(Arrays.asList(metricPublishers)));
}
return builder.build();
}
}
| 2,604 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/metrics | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/metrics/async/AsyncStreamingCoreMetricsTest.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.metrics.async;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient;
import software.amazon.awssdk.services.protocolrestjson.model.StreamingInputOperationRequest;
import software.amazon.awssdk.services.testutil.MockIdentityProviderUtil;
/**
* Core metrics test for async streaming API
*/
@RunWith(MockitoJUnitRunner.class)
public class AsyncStreamingCoreMetricsTest extends BaseAsyncCoreMetricsTest {
@Mock
private MetricPublisher mockPublisher;
@Rule
public WireMockRule wireMock = new WireMockRule(0);
private ProtocolRestJsonAsyncClient client;
@Before
public void setup() throws IOException {
client = ProtocolRestJsonAsyncClient.builder()
.region(Region.US_WEST_2)
.credentialsProvider(MockIdentityProviderUtil.mockIdentityProvider())
.endpointOverride(URI.create("http://localhost:" + wireMock.port()))
.overrideConfiguration(c -> c.addMetricPublisher(mockPublisher).retryPolicy(b -> b.numRetries(MAX_RETRIES)))
.build();
}
@After
public void teardown() {
wireMock.resetAll();
if (client != null) {
client.close();
}
client = null;
}
@Override
String operationName() {
return "StreamingInputOperation";
}
@Override
Supplier<CompletableFuture<?>> callable() {
return () -> client.streamingInputOperation(StreamingInputOperationRequest.builder().build(),
AsyncRequestBody.fromBytes("helloworld".getBytes()));
}
@Override
MetricPublisher publisher() {
return mockPublisher;
}
}
| 2,605 |
0 | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/metrics | Create_ds/aws-sdk-java-v2/test/codegen-generated-classes-test/src/test/java/software/amazon/awssdk/services/metrics/async/BaseAsyncCoreMetricsTest.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.metrics.async;
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 static org.mockito.Mockito.verify;
import com.github.tomakehurst.wiremock.http.Fault;
import com.github.tomakehurst.wiremock.stubbing.Scenario;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.metrics.CoreMetric;
import software.amazon.awssdk.core.internal.metrics.SdkErrorType;
import software.amazon.awssdk.http.HttpMetric;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.services.protocolrestjson.model.EmptyModeledException;
@RunWith(MockitoJUnitRunner.class)
public abstract class BaseAsyncCoreMetricsTest {
private static final String SERVICE_ID = "AmazonProtocolRestJson";
private static final String REQUEST_ID = "req-id";
private static final String EXTENDED_REQUEST_ID = "extended-id";
static final int MAX_RETRIES = 2;
public static final Duration FIXED_DELAY = Duration.ofMillis(500);
@Test
public void apiCall_operationSuccessful_addsMetrics() {
stubSuccessfulResponse();
callable().get().join();
addDelayIfNeeded();
ArgumentCaptor<MetricCollection> collectionCaptor = ArgumentCaptor.forClass(MetricCollection.class);
verify(publisher()).publish(collectionCaptor.capture());
MetricCollection capturedCollection = collectionCaptor.getValue();
verifySuccessfulApiCallCollection(capturedCollection);
assertThat(capturedCollection.children()).hasSize(1);
MetricCollection attemptCollection = capturedCollection.children().get(0);
assertThat(attemptCollection.name()).isEqualTo("ApiCallAttempt");
verifySuccessfulApiCallAttemptCollection(attemptCollection);
assertThat(attemptCollection.metricValues(CoreMetric.SERVICE_CALL_DURATION).get(0))
.isGreaterThanOrEqualTo(FIXED_DELAY);
}
@Test
public void apiCall_allRetryAttemptsFailedOf500() {
stubErrorResponse();
assertThatThrownBy(() -> callable().get().join()).hasCauseInstanceOf(EmptyModeledException.class);
addDelayIfNeeded();
ArgumentCaptor<MetricCollection> collectionCaptor = ArgumentCaptor.forClass(MetricCollection.class);
verify(publisher()).publish(collectionCaptor.capture());
MetricCollection capturedCollection = collectionCaptor.getValue();
verifyFailedApiCallCollection(capturedCollection);
assertThat(capturedCollection.children()).hasSize(MAX_RETRIES + 1);
capturedCollection.children().forEach(this::verifyFailedApiCallAttemptCollection);
}
@Test
public void apiCall_allRetryAttemptsFailedOfNetworkError() {
stubNetworkError();
assertThatThrownBy(() -> callable().get().join()).hasCauseInstanceOf(SdkClientException.class);
addDelayIfNeeded();
ArgumentCaptor<MetricCollection> collectionCaptor = ArgumentCaptor.forClass(MetricCollection.class);
verify(publisher()).publish(collectionCaptor.capture());
MetricCollection capturedCollection = collectionCaptor.getValue();
verifyFailedApiCallCollection(capturedCollection);
assertThat(capturedCollection.children()).hasSize(MAX_RETRIES + 1);
capturedCollection.children().forEach(requestMetrics -> {
assertThat(requestMetrics.metricValues(HttpMetric.HTTP_STATUS_CODE))
.isEmpty();
assertThat(requestMetrics.metricValues(CoreMetric.AWS_REQUEST_ID))
.isEmpty();
assertThat(requestMetrics.metricValues(CoreMetric.AWS_EXTENDED_REQUEST_ID))
.isEmpty();
assertThat(requestMetrics.metricValues(CoreMetric.SERVICE_CALL_DURATION).get(0))
.isGreaterThanOrEqualTo(FIXED_DELAY);
assertThat(requestMetrics.metricValues(CoreMetric.ERROR_TYPE)).containsExactly(SdkErrorType.IO.toString());
});
}
@Test
public void apiCall_firstAttemptFailedRetrySucceeded() {
stubSuccessfulRetry();
callable().get().join();
addDelayIfNeeded();
ArgumentCaptor<MetricCollection> collectionCaptor = ArgumentCaptor.forClass(MetricCollection.class);
verify(publisher()).publish(collectionCaptor.capture());
MetricCollection capturedCollection = collectionCaptor.getValue();
verifyApiCallCollection(capturedCollection);
assertThat(capturedCollection.metricValues(CoreMetric.RETRY_COUNT)).containsExactly(1);
assertThat(capturedCollection.metricValues(CoreMetric.API_CALL_SUCCESSFUL)).containsExactly(true);
assertThat(capturedCollection.children()).hasSize(2);
MetricCollection failedAttempt = capturedCollection.children().get(0);
verifyFailedApiCallAttemptCollection(failedAttempt);
MetricCollection successfulAttempt = capturedCollection.children().get(1);
verifySuccessfulApiCallAttemptCollection(successfulAttempt);
}
/**
* Adds delay after calling CompletableFuture.join to wait for publisher to get metrics.
*/
void addDelayIfNeeded() {
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
abstract String operationName();
abstract Supplier<CompletableFuture<?>> callable();
abstract MetricPublisher publisher();
private void verifyFailedApiCallAttemptCollection(MetricCollection requestMetrics) {
assertThat(requestMetrics.metricValues(HttpMetric.HTTP_STATUS_CODE))
.containsExactly(500);
assertThat(requestMetrics.metricValues(CoreMetric.AWS_REQUEST_ID))
.containsExactly(REQUEST_ID);
assertThat(requestMetrics.metricValues(CoreMetric.AWS_EXTENDED_REQUEST_ID))
.containsExactly(EXTENDED_REQUEST_ID);
assertThat(requestMetrics.metricValues(CoreMetric.BACKOFF_DELAY_DURATION).get(0))
.isGreaterThanOrEqualTo(Duration.ZERO);
assertThat(requestMetrics.metricValues(CoreMetric.SERVICE_CALL_DURATION).get(0))
.isGreaterThanOrEqualTo(Duration.ZERO);
assertThat(requestMetrics.metricValues(CoreMetric.ERROR_TYPE)).containsExactly(SdkErrorType.SERVER_ERROR.toString());
}
private void verifySuccessfulApiCallAttemptCollection(MetricCollection attemptCollection) {
assertThat(attemptCollection.metricValues(HttpMetric.HTTP_STATUS_CODE))
.containsExactly(200);
assertThat(attemptCollection.metricValues(CoreMetric.AWS_REQUEST_ID))
.containsExactly(REQUEST_ID);
assertThat(attemptCollection.metricValues(CoreMetric.AWS_EXTENDED_REQUEST_ID))
.containsExactly(EXTENDED_REQUEST_ID);
assertThat(attemptCollection.metricValues(CoreMetric.BACKOFF_DELAY_DURATION).get(0))
.isGreaterThanOrEqualTo(Duration.ZERO);
assertThat(attemptCollection.metricValues(CoreMetric.SIGNING_DURATION).get(0))
.isGreaterThanOrEqualTo(Duration.ZERO);
}
private void verifyFailedApiCallCollection(MetricCollection capturedCollection) {
verifyApiCallCollection(capturedCollection);
assertThat(capturedCollection.metricValues(CoreMetric.RETRY_COUNT)).containsExactly(MAX_RETRIES);
assertThat(capturedCollection.metricValues(CoreMetric.API_CALL_SUCCESSFUL)).containsExactly(false);
}
private void verifySuccessfulApiCallCollection(MetricCollection capturedCollection) {
verifyApiCallCollection(capturedCollection);
assertThat(capturedCollection.metricValues(CoreMetric.RETRY_COUNT)).containsExactly(0);
assertThat(capturedCollection.metricValues(CoreMetric.API_CALL_SUCCESSFUL)).containsExactly(true);
}
private void verifyApiCallCollection(MetricCollection capturedCollection) {
assertThat(capturedCollection.name()).isEqualTo("ApiCall");
assertThat(capturedCollection.metricValues(CoreMetric.SERVICE_ID))
.containsExactly(SERVICE_ID);
assertThat(capturedCollection.metricValues(CoreMetric.OPERATION_NAME))
.containsExactly(operationName());
assertThat(capturedCollection.metricValues(CoreMetric.CREDENTIALS_FETCH_DURATION).get(0))
.isGreaterThanOrEqualTo(Duration.ZERO);
assertThat(capturedCollection.metricValues(CoreMetric.MARSHALLING_DURATION).get(0))
.isGreaterThanOrEqualTo(Duration.ZERO);
assertThat(capturedCollection.metricValues(CoreMetric.API_CALL_DURATION).get(0))
.isGreaterThan(FIXED_DELAY);
assertThat(capturedCollection.metricValues(CoreMetric.SERVICE_ENDPOINT).get(0)).toString()
.startsWith("http://localhost");
}
void stubSuccessfulResponse() {
stubFor(post(anyUrl())
.willReturn(aResponse().withStatus(200)
.withHeader("x-amz-request-id", REQUEST_ID)
.withFixedDelay((int) FIXED_DELAY.toMillis())
.withHeader("x-amz-id-2", EXTENDED_REQUEST_ID)
.withBody("{}")));
}
void stubErrorResponse() {
stubFor(post(anyUrl())
.willReturn(aResponse().withStatus(500)
.withHeader("x-amz-request-id", REQUEST_ID)
.withHeader("x-amz-id-2", EXTENDED_REQUEST_ID)
.withFixedDelay((int) FIXED_DELAY.toMillis())
.withHeader("X-Amzn-Errortype", "EmptyModeledException")
.withBody("{}")));
}
void stubNetworkError() {
stubFor(post(anyUrl())
.willReturn(aResponse().withFault(Fault.CONNECTION_RESET_BY_PEER)
.withFixedDelay((int) FIXED_DELAY.toMillis())
));
}
void stubSuccessfulRetry() {
stubFor(post(anyUrl())
.inScenario("retry at 500")
.whenScenarioStateIs(Scenario.STARTED)
.willSetStateTo("first attempt")
.willReturn(aResponse()
.withHeader("x-amz-request-id", REQUEST_ID)
.withHeader("x-amz-id-2", EXTENDED_REQUEST_ID)
.withFixedDelay((int) FIXED_DELAY.toMillis())
.withHeader("X-Amzn-Errortype", "EmptyModeledException")
.withStatus(500)));
stubFor(post(anyUrl())
.inScenario("retry at 500")
.whenScenarioStateIs("first attempt")
.willSetStateTo("second attempt")
.willReturn(aResponse()
.withStatus(200)
.withHeader("x-amz-request-id", REQUEST_ID)
.withHeader("x-amz-id-2", EXTENDED_REQUEST_ID)
.withFixedDelay((int) FIXED_DELAY.toMillis())
.withBody("{}")));
}
}
| 2,606 |
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/customsdkshape/CustomSdkShapeTest.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.customsdkshape;
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.anyRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl;
import static com.github.tomakehurst.wiremock.client.WireMock.notMatching;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo;
import com.github.tomakehurst.wiremock.junit5.WireMockTest;
import java.net.URI;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlClient;
@WireMockTest
public class CustomSdkShapeTest {
private ProtocolRestXmlClient xmlClient;
@Mock
private SdkHttpClient mockHttpClient;
@BeforeEach
public void setUp(WireMockRuntimeInfo wmRuntimeInfo) {
xmlClient = ProtocolRestXmlClient.builder()
.region(Region.US_WEST_2)
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid",
"skid")))
.httpClient(mockHttpClient)
.endpointOverride(URI.create("http://localhost:" + wmRuntimeInfo.getHttpPort()))
.build();
}
@Test
public void requestPayloadDoesNotContainInjectedCustomShape() {
stubFor(any(urlMatching(".*"))
.willReturn(aResponse().withStatus(200).withBody("<xml></xml>")));
xmlClient.allTypes(c -> c.sdkPartType("DEFAULT").build());
xmlClient.allTypes(c -> c.sdkPartType("LAST").build());
verify(anyRequestedFor(anyUrl()).withRequestBody(notMatching("^.*SdkPartType.*$")));
}
}
| 2,607 |
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/retry/AsyncRetryFailureTest.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.retry;
import java.net.URI;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.retry.RetryMode;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient;
import software.amazon.awssdk.testutils.service.http.MockAsyncHttpClient;
public class AsyncRetryFailureTest extends RetryFailureTestSuite<MockAsyncHttpClient> {
private final ProtocolRestJsonAsyncClient client;
public AsyncRetryFailureTest() {
super(new MockAsyncHttpClient());
client = ProtocolRestJsonAsyncClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")))
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost"))
.httpClient(mockHttpClient)
.build();
}
@Override
protected void callAllTypesOperation() {
client.allTypes().join();
}
}
| 2,608 |
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/retry/SyncClientRetryModeTest.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.retry;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClientBuilder;
import software.amazon.awssdk.services.protocolrestjson.model.AllTypesResponse;
public class SyncClientRetryModeTest extends ClientRetryModeTestSuite<ProtocolRestJsonClient, ProtocolRestJsonClientBuilder> {
@Override
protected ProtocolRestJsonClientBuilder newClientBuilder() {
return ProtocolRestJsonClient.builder();
}
@Override
protected AllTypesResponse callAllTypes(ProtocolRestJsonClient client) {
return client.allTypes();
}
}
| 2,609 |
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/retry/RetryFailureTestSuite.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.retry;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import java.util.concurrent.CompletionException;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.testutils.service.http.MockHttpClient;
/**
* A set of tests that verify the behavior of the SDK when retries are exhausted.
*/
public abstract class RetryFailureTestSuite<T extends MockHttpClient> {
protected final T mockHttpClient;
protected RetryFailureTestSuite(T mockHttpClient) {
this.mockHttpClient = mockHttpClient;
}
@BeforeEach
public void setupClient() {
mockHttpClient.reset();
}
protected abstract void callAllTypesOperation();
@Test
public void clientSideErrorsIncludeSuppressedExceptions() {
mockHttpClient.stubResponses(retryableFailure(),
retryableFailure(),
nonRetryableFailure());
try {
callAllTypesOperation();
} catch (Throwable e) {
if (e instanceof CompletionException) {
e = e.getCause();
}
e.printStackTrace();
assertThat(e.getSuppressed()).hasSize(2)
.allSatisfy(t -> assertThat(t.getMessage()).contains("500"));
}
}
private HttpExecuteResponse retryableFailure() {
return HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder()
.statusCode(500)
.putHeader("content-length", "0")
.build())
.build();
}
private HttpExecuteResponse nonRetryableFailure() {
return HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder()
.statusCode(400)
.putHeader("content-length", "0")
.build())
.build();
}
}
| 2,610 |
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/retry/AsyncClientRetryModeTest.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.retry;
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 AsyncClientRetryModeTest
extends ClientRetryModeTestSuite<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,611 |
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/retry/AsyncRetryHeaderTest.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.retry;
import java.net.URI;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.retry.RetryMode;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.testutils.service.http.MockAsyncHttpClient;
import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient;
public class AsyncRetryHeaderTest extends RetryHeaderTestSuite<MockAsyncHttpClient> {
private final ProtocolRestJsonAsyncClient client;
public AsyncRetryHeaderTest() {
super(new MockAsyncHttpClient());
client = ProtocolRestJsonAsyncClient.builder()
.overrideConfiguration(c -> c.retryPolicy(RetryMode.STANDARD))
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")))
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost"))
.httpClient(mockHttpClient)
.build();
}
@Override
protected void callAllTypesOperation() {
client.allTypes().join();
}
}
| 2,612 |
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/retry/SyncRetryFailureTest.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.retry;
import java.net.URI;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.retry.RetryMode;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient;
public class SyncRetryFailureTest extends RetryFailureTestSuite<MockSyncHttpClient> {
private final ProtocolRestJsonClient client;
public SyncRetryFailureTest() {
super(new MockSyncHttpClient());
client = ProtocolRestJsonClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid",
"skid")))
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost"))
.httpClient(mockHttpClient)
.build();
}
@Override
protected void callAllTypesOperation() {
client.allTypes();
}
}
| 2,613 |
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/retry/SyncRetryHeaderTest.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.retry;
import java.net.URI;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.retry.RetryMode;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient;
public class SyncRetryHeaderTest extends RetryHeaderTestSuite<MockSyncHttpClient> {
private final ProtocolRestJsonClient client;
public SyncRetryHeaderTest() {
super(new MockSyncHttpClient());
client = ProtocolRestJsonClient.builder()
.overrideConfiguration(c -> c.retryPolicy(RetryMode.STANDARD))
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid",
"skid")))
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost"))
.httpClient(mockHttpClient)
.build();
}
@Override
protected void callAllTypesOperation() {
client.allTypes();
}
}
| 2,614 |
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/retry/RetryHeaderTestSuite.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.retry;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.testutils.service.http.MockHttpClient;
/**
* A set of tests that verify the behavior of retry-related headers (amz-sdk-invocation-id and amz-sdk-request).
*/
public abstract class RetryHeaderTestSuite<T extends MockHttpClient> {
protected final T mockHttpClient;
protected RetryHeaderTestSuite(T mockHttpClient) {
this.mockHttpClient = mockHttpClient;
}
@BeforeEach
public void setupClient() {
mockHttpClient.reset();
}
protected abstract void callAllTypesOperation();
@Test
public void invocationIdSharedBetweenRetries() {
mockHttpClient.stubResponses(retryableFailure(), retryableFailure(), success());
callAllTypesOperation();
List<SdkHttpRequest> requests = mockHttpClient.getRequests();
assertThat(requests).hasSize(3);
String firstInvocationId = invocationId(requests.get(0));
assertThat(invocationId(requests.get(1))).isEqualTo(firstInvocationId);
assertThat(invocationId(requests.get(2))).isEqualTo(firstInvocationId);
}
@Test
public void invocationIdDifferentBetweenApiCalls() {
mockHttpClient.stubResponses(success());
callAllTypesOperation();
callAllTypesOperation();
List<SdkHttpRequest> requests = mockHttpClient.getRequests();
assertThat(requests).hasSize(2);
String firstInvocationId = invocationId(requests.get(0));
assertThat(invocationId(requests.get(1))).isNotEqualTo(firstInvocationId);
}
@Test
public void retryAttemptAndMaxAreCorrect() {
mockHttpClient.stubResponses(retryableFailure(), success());
callAllTypesOperation();
List<SdkHttpRequest> requests = mockHttpClient.getRequests();
assertThat(requests).hasSize(2);
assertThat(retryComponent(requests.get(0), "attempt")).isEqualTo("1");
assertThat(retryComponent(requests.get(1), "attempt")).isEqualTo("2");
assertThat(retryComponent(requests.get(0), "max")).isEqualTo("3");
assertThat(retryComponent(requests.get(1), "max")).isEqualTo("3");
}
private String invocationId(SdkHttpRequest request) {
return request.firstMatchingHeader("amz-sdk-invocation-id")
.orElseThrow(() -> new AssertionError("Expected aws-sdk-invocation-id in " + request));
}
private String retryComponent(SdkHttpRequest request, String componentName) {
return retryComponent(request.firstMatchingHeader("amz-sdk-request")
.orElseThrow(() -> new AssertionError("Expected amz-sdk-request in " + request)),
componentName);
}
private String retryComponent(String amzSdkRequestHeader, String componentName) {
return Stream.of(amzSdkRequestHeader.split(";"))
.map(h -> h.split("="))
.filter(h -> h[0].trim().equals(componentName))
.map(h -> h[1].trim())
.findAny()
.orElseThrow(() -> new AssertionError("Expected " + componentName + " in " + amzSdkRequestHeader));
}
private HttpExecuteResponse retryableFailure() {
return HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder()
.statusCode(500)
.putHeader("content-length", "0")
.build())
.build();
}
private HttpExecuteResponse success() {
return HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder()
.statusCode(200)
.putHeader("content-length", "0")
.build())
.build();
}
}
| 2,615 |
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/retry/ClientRetryModeTestSuite.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.retry;
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.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
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 java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
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.core.exception.SdkException;
import software.amazon.awssdk.core.retry.RetryMode;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.model.AllTypesResponse;
import software.amazon.awssdk.utils.StringInputStream;
public abstract class ClientRetryModeTestSuite<ClientT, BuilderT extends AwsClientBuilder<BuilderT, ClientT>> {
@Rule
public WireMockRule wireMock = new WireMockRule(0);
@Test
public void legacyRetryModeIsFourAttempts() {
stubThrottlingResponse();
ClientT client = clientBuilder().overrideConfiguration(o -> o.retryPolicy(RetryMode.LEGACY)).build();
assertThatThrownBy(() -> callAllTypes(client)).isInstanceOf(SdkException.class);
verifyRequestCount(4);
}
@Test
public void standardRetryModeIsThreeAttempts() {
stubThrottlingResponse();
ClientT client = clientBuilder().overrideConfiguration(o -> o.retryPolicy(RetryMode.STANDARD)).build();
assertThatThrownBy(() -> callAllTypes(client)).isInstanceOf(SdkException.class);
verifyRequestCount(3);
}
@Test
public void retryModeCanBeSetByProfileFile() {
ProfileFile profileFile = ProfileFile.builder()
.content(new StringInputStream("[profile foo]\n" +
"retry_mode = standard"))
.type(ProfileFile.Type.CONFIGURATION)
.build();
stubThrottlingResponse();
ClientT client = clientBuilder().overrideConfiguration(o -> o.defaultProfileFile(profileFile)
.defaultProfileName("foo")).build();
assertThatThrownBy(() -> callAllTypes(client)).isInstanceOf(SdkException.class);
verifyRequestCount(3);
}
@Test
public void legacyRetryModeExcludesThrottlingExceptions() throws InterruptedException {
stubThrottlingResponse();
ExecutorService executor = Executors.newFixedThreadPool(51);
ClientT client = clientBuilder().overrideConfiguration(o -> o.retryPolicy(RetryMode.LEGACY)).build();
for (int i = 0; i < 51; ++i) {
executor.execute(() -> assertThatThrownBy(() -> callAllTypes(client)).isInstanceOf(SdkException.class));
}
executor.shutdown();
assertThat(executor.awaitTermination(30, TimeUnit.SECONDS)).isTrue();
// 51 requests * 4 attempts = 204 requests
verifyRequestCount(204);
}
@Test
public void standardRetryModeIncludesThrottlingExceptions() throws InterruptedException {
stubThrottlingResponse();
ExecutorService executor = Executors.newFixedThreadPool(51);
ClientT client = clientBuilder().overrideConfiguration(o -> o.retryPolicy(RetryMode.STANDARD)).build();
for (int i = 0; i < 51; ++i) {
executor.execute(() -> assertThatThrownBy(() -> callAllTypes(client)).isInstanceOf(SdkException.class));
}
executor.shutdown();
assertThat(executor.awaitTermination(30, TimeUnit.SECONDS)).isTrue();
// Would receive 153 without throttling (51 requests * 3 attempts = 153 requests)
verifyRequestCount(151);
}
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 stubThrottlingResponse() {
stubFor(post(anyUrl())
.willReturn(aResponse().withStatus(429)));
}
}
| 2,616 |
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/bearerauth/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.bearerauth;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.mockito.Mockito.mock;
import java.lang.reflect.Method;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider;
import software.amazon.awssdk.auth.token.credentials.aws.DefaultAwsTokenProvider;
import software.amazon.awssdk.auth.token.signer.aws.BearerTokenSigner;
import software.amazon.awssdk.awscore.client.config.AwsClientOption;
import software.amazon.awssdk.core.client.builder.SdkDefaultClientBuilder;
import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.signer.Signer;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.identity.spi.TokenIdentity;
import software.amazon.awssdk.regions.Region;
public class ClientBuilderTest {
@Test
public void syncClient_includesDefaultProvider_includesDefaultSigner() {
DefaultBearerauthClientBuilder builder = new DefaultBearerauthClientBuilder();
SdkClientConfiguration config = getSyncConfig(builder);
assertThat(config.option(AwsClientOption.TOKEN_IDENTITY_PROVIDER))
.isInstanceOf(DefaultAwsTokenProvider.class);
assertThat(config.option(SdkAdvancedClientOption.TOKEN_SIGNER))
.isInstanceOf(BearerTokenSigner.class);
}
@Test
public void syncClient_customTokenProviderSet_presentInFinalConfig() {
DefaultBearerauthClientBuilder builder = new DefaultBearerauthClientBuilder();
SdkTokenProvider mockProvider = mock(SdkTokenProvider.class);
builder.tokenProvider(mockProvider);
SdkClientConfiguration config = getSyncConfig(builder);
assertThat(config.option(AwsClientOption.TOKEN_IDENTITY_PROVIDER))
.isSameAs(mockProvider);
}
@Test
public void syncClient_customTokenIdentityProviderSet_presentInFinalConfig() {
DefaultBearerauthClientBuilder builder = new DefaultBearerauthClientBuilder();
IdentityProvider<TokenIdentity> mockProvider = mock(IdentityProvider.class);
builder.tokenProvider(mockProvider);
SdkClientConfiguration config = getSyncConfig(builder);
assertThat(config.option(AwsClientOption.TOKEN_IDENTITY_PROVIDER))
.isSameAs(mockProvider);
}
@Test
public void syncClient_customSignerSet_presentInFinalConfig() {
DefaultBearerauthClientBuilder builder = new DefaultBearerauthClientBuilder();
Signer mockSigner = mock(Signer.class);
builder.overrideConfiguration(o -> o.putAdvancedOption(SdkAdvancedClientOption.TOKEN_SIGNER, mockSigner));
SdkClientConfiguration config = getSyncConfig(builder);
assertThat(config.option(SdkAdvancedClientOption.TOKEN_SIGNER))
.isSameAs(mockSigner);
}
@Test
public void asyncClient_includesDefaultProvider_includesDefaultSigner() {
DefaultBearerauthAsyncClientBuilder builder = new DefaultBearerauthAsyncClientBuilder();
SdkClientConfiguration config = getAsyncConfig(builder);
assertThat(config.option(AwsClientOption.TOKEN_IDENTITY_PROVIDER))
.isInstanceOf(DefaultAwsTokenProvider.class);
assertThat(config.option(SdkAdvancedClientOption.TOKEN_SIGNER))
.isInstanceOf(BearerTokenSigner.class);
}
@Test
public void asyncClient_customTokenProviderSet_presentInFinalConfig() {
DefaultBearerauthAsyncClientBuilder builder = new DefaultBearerauthAsyncClientBuilder();
SdkTokenProvider mockProvider = mock(SdkTokenProvider.class);
builder.tokenProvider(mockProvider);
SdkClientConfiguration config = getAsyncConfig(builder);
assertThat(config.option(AwsClientOption.TOKEN_IDENTITY_PROVIDER))
.isSameAs(mockProvider);
}
@Test
public void asyncClient_customTokenIdentityProviderSet_presentInFinalConfig() {
DefaultBearerauthAsyncClientBuilder builder = new DefaultBearerauthAsyncClientBuilder();
IdentityProvider<TokenIdentity> mockProvider = mock(IdentityProvider.class);
builder.tokenProvider(mockProvider);
SdkClientConfiguration config = getAsyncConfig(builder);
assertThat(config.option(AwsClientOption.TOKEN_IDENTITY_PROVIDER))
.isSameAs(mockProvider);
}
@Test
public void asyncClient_customSignerSet_presentInFinalConfig() {
DefaultBearerauthAsyncClientBuilder builder = new DefaultBearerauthAsyncClientBuilder();
Signer mockSigner = mock(Signer.class);
builder.overrideConfiguration(o -> o.putAdvancedOption(SdkAdvancedClientOption.TOKEN_SIGNER, mockSigner));
SdkClientConfiguration config = getAsyncConfig(builder);
assertThat(config.option(SdkAdvancedClientOption.TOKEN_SIGNER))
.isSameAs(mockSigner);
}
@Test
public void syncClient_buildWithDefaults_validationsSucceed() {
DefaultBearerauthClientBuilder builder = new DefaultBearerauthClientBuilder();
builder.region(Region.US_WEST_2).credentialsProvider(AnonymousCredentialsProvider.create());
assertThatNoException().isThrownBy(builder::build);
}
@Test
public void asyncClient_buildWithDefaults_validationsSucceed() {
DefaultBearerauthAsyncClientBuilder builder = new DefaultBearerauthAsyncClientBuilder();
builder.region(Region.US_WEST_2).credentialsProvider(AnonymousCredentialsProvider.create());
assertThatNoException().isThrownBy(builder::build);
}
// syncClientConfiguration() is a protected method, and the concrete builder classes are final
private static SdkClientConfiguration getSyncConfig(DefaultBearerauthClientBuilder builder) {
try {
Method syncClientConfiguration = SdkDefaultClientBuilder.class.getDeclaredMethod("syncClientConfiguration");
syncClientConfiguration.setAccessible(true);
return (SdkClientConfiguration) syncClientConfiguration.invoke(builder);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// syncClientConfiguration() is a protected method, and the concrete builder classes are final
private static SdkClientConfiguration getAsyncConfig(DefaultBearerauthAsyncClientBuilder builder) {
try {
Method syncClientConfiguration = SdkDefaultClientBuilder.class.getDeclaredMethod("asyncClientConfiguration");
syncClientConfiguration.setAccessible(true);
return (SdkClientConfiguration) syncClientConfiguration.invoke(builder);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 2,617 |
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/endpointproviders/EndpointInterceptorTests.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.endpointproviders;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.concurrent.CompletableFuture;
import org.junit.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption;
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.core.interceptor.SdkInternalExecutionAttribute;
import software.amazon.awssdk.endpoints.Endpoint;
import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme;
import software.amazon.awssdk.http.auth.spi.signer.AsyncSignRequest;
import software.amazon.awssdk.http.auth.spi.signer.AsyncSignedRequest;
import software.amazon.awssdk.http.auth.spi.signer.BaseSignRequest;
import software.amazon.awssdk.http.auth.spi.signer.HttpSigner;
import software.amazon.awssdk.http.auth.spi.signer.SignRequest;
import software.amazon.awssdk.http.auth.spi.signer.SignedRequest;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.identity.spi.IdentityProviders;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersAsyncClient;
import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersAsyncClientBuilder;
import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersClient;
import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersClientBuilder;
import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.RestJsonEndpointProvidersEndpointProvider;
import software.amazon.awssdk.utils.CompletableFutureUtils;
public class EndpointInterceptorTests {
@Test
public void sync_hostPrefixInjectDisabled_hostPrefixNotAdded() {
CapturingInterceptor interceptor = new CapturingInterceptor();
RestJsonEndpointProvidersClient client = syncClientBuilder()
.overrideConfiguration(o -> o.addExecutionInterceptor(interceptor)
.putAdvancedOption(SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION, true))
.build();
assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {}))
.hasMessageContaining("stop");
Endpoint endpoint = interceptor.executionAttributes().getAttribute(SdkInternalExecutionAttribute.RESOLVED_ENDPOINT);
assertThat(endpoint.url().getHost()).isEqualTo("restjson.us-west-2.amazonaws.com");
}
@Test
public void async_hostPrefixInjectDisabled_hostPrefixNotAdded() {
CapturingInterceptor interceptor = new CapturingInterceptor();
RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder()
.overrideConfiguration(o -> o.addExecutionInterceptor(interceptor)
.putAdvancedOption(SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION, true))
.build();
assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {}).join())
.hasMessageContaining("stop");
Endpoint endpoint = interceptor.executionAttributes().getAttribute(SdkInternalExecutionAttribute.RESOLVED_ENDPOINT);
assertThat(endpoint.url().getHost()).isEqualTo("restjson.us-west-2.amazonaws.com");
}
@Test
public void sync_clientContextParamsSetOnBuilder_includedInExecutionAttributes() {
CapturingInterceptor interceptor = new CapturingInterceptor();
RestJsonEndpointProvidersClient client = syncClientBuilder()
.overrideConfiguration(o -> o.addExecutionInterceptor(interceptor))
.build();
assertThatThrownBy(() -> client.operationWithNoInputOrOutput(r -> {
})).hasMessageContaining("stop");
Endpoint endpoint = interceptor.executionAttributes().getAttribute(SdkInternalExecutionAttribute.RESOLVED_ENDPOINT);
assertThat(endpoint).isNotNull();
}
@Test
public void async_clientContextParamsSetOnBuilder_includedInExecutionAttributes() {
CapturingInterceptor interceptor = new CapturingInterceptor();
RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder()
.overrideConfiguration(o -> o.addExecutionInterceptor(interceptor))
.build();
assertThatThrownBy(() -> client.operationWithNoInputOrOutput(r -> {
}).join()).hasMessageContaining("stop");
Endpoint endpoint = interceptor.executionAttributes().getAttribute(SdkInternalExecutionAttribute.RESOLVED_ENDPOINT);
assertThat(endpoint).isNotNull();
}
@Test
public void sync_endpointProviderReturnsHeaders_includedInHttpRequest() {
RestJsonEndpointProvidersEndpointProvider defaultProvider = RestJsonEndpointProvidersEndpointProvider.defaultProvider();
CapturingInterceptor interceptor = new CapturingInterceptor();
RestJsonEndpointProvidersClient client = syncClientBuilder()
.overrideConfiguration(o -> o.addExecutionInterceptor(interceptor))
.endpointProvider(r -> defaultProvider.resolveEndpoint(r)
.thenApply(e -> e.toBuilder()
.putHeader("TestHeader", "TestValue")
.build()))
.build();
assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {}))
.hasMessageContaining("stop");
assertThat(interceptor.context.httpRequest().matchingHeaders("TestHeader")).containsExactly("TestValue");
}
@Test
public void async_endpointProviderReturnsHeaders_includedInHttpRequest() {
RestJsonEndpointProvidersEndpointProvider defaultProvider = RestJsonEndpointProvidersEndpointProvider.defaultProvider();
CapturingInterceptor interceptor = new CapturingInterceptor();
RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder()
.overrideConfiguration(o -> o.addExecutionInterceptor(interceptor))
.endpointProvider(r -> defaultProvider.resolveEndpoint(r)
.thenApply(e -> e.toBuilder()
.putHeader("TestHeader", "TestValue")
.build()))
.build();
assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {}).join())
.hasMessageContaining("stop");
assertThat(interceptor.context.httpRequest().matchingHeaders("TestHeader")).containsExactly("TestValue");
}
@Test
public void sync_endpointProviderReturnsHeaders_appendedToExistingRequest() {
RestJsonEndpointProvidersEndpointProvider defaultProvider = RestJsonEndpointProvidersEndpointProvider.defaultProvider();
CapturingInterceptor interceptor = new CapturingInterceptor();
RestJsonEndpointProvidersClient client = syncClientBuilder()
.overrideConfiguration(o -> o.addExecutionInterceptor(interceptor))
.endpointProvider(r -> defaultProvider.resolveEndpoint(r)
.thenApply(e -> e.toBuilder()
.putHeader("TestHeader", "TestValue")
.build()))
.build();
assertThatThrownBy(() -> client.operationWithHostPrefix(r -> r.overrideConfiguration(c -> c.putHeader("TestHeader",
"TestValue0"))))
.hasMessageContaining("stop");
assertThat(interceptor.context.httpRequest().matchingHeaders("TestHeader")).containsExactly("TestValue", "TestValue0");
}
@Test
public void async_endpointProviderReturnsHeaders_appendedToExistingRequest() {
RestJsonEndpointProvidersEndpointProvider defaultProvider = RestJsonEndpointProvidersEndpointProvider.defaultProvider();
CapturingInterceptor interceptor = new CapturingInterceptor();
RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder()
.overrideConfiguration(o -> o.addExecutionInterceptor(interceptor))
.endpointProvider(r -> defaultProvider.resolveEndpoint(r)
.thenApply(e -> e.toBuilder()
.putHeader("TestHeader", "TestValue")
.build()))
.build();
assertThatThrownBy(() -> client.operationWithHostPrefix(r -> r.overrideConfiguration(c -> c.putHeader("TestHeader",
"TestValue0")))
.join())
.hasMessageContaining("stop");
assertThat(interceptor.context.httpRequest().matchingHeaders("TestHeader")).containsExactly("TestValue", "TestValue0");
}
// TODO(sra-identity-auth): Enable for useSraAuth=true
/*
@Test
public void sync_endpointProviderReturnsSignerProperties_overridesV4AuthSchemeResolverProperties() {
RestJsonEndpointProvidersEndpointProvider defaultEndpointProvider =
RestJsonEndpointProvidersEndpointProvider.defaultProvider();
CapturingSigner signer = new CapturingSigner();
List<EndpointAuthScheme> endpointAuthSchemes = new ArrayList<>();
endpointAuthSchemes.add(SigV4AuthScheme.builder()
.signingRegion("region-from-ep")
.signingName("name-from-ep")
.disableDoubleEncoding(true)
.build());
RestJsonEndpointProvidersClient client = syncClientBuilder()
.endpointProvider(r -> defaultEndpointProvider.resolveEndpoint(r)
.thenApply(e -> e.toBuilder()
.putAttribute(AwsEndpointAttribute.AUTH_SCHEMES, endpointAuthSchemes)
.build()))
.putAuthScheme(authScheme("aws.auth#sigv4", signer))
.build();
assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {}))
.hasMessageContaining("stop");
assertThat(signer.request.property(AwsV4HttpSigner.REGION_NAME)).isEqualTo("region-from-ep");
assertThat(signer.request.property(AwsV4HttpSigner.SERVICE_SIGNING_NAME)).isEqualTo("name-from-ep");
assertThat(signer.request.property(AwsV4HttpSigner.DOUBLE_URL_ENCODE)).isEqualTo(false);
}
@Test
public void async_endpointProviderReturnsSignerProperties_overridesV4AuthSchemeResolverProperties() {
RestJsonEndpointProvidersEndpointProvider defaultEndpointProvider =
RestJsonEndpointProvidersEndpointProvider.defaultProvider();
CapturingSigner signer = new CapturingSigner();
List<EndpointAuthScheme> endpointAuthSchemes = new ArrayList<>();
endpointAuthSchemes.add(SigV4AuthScheme.builder()
.signingRegion("region-from-ep")
.signingName("name-from-ep")
.disableDoubleEncoding(true)
.build());
RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder()
.endpointProvider(r -> defaultEndpointProvider.resolveEndpoint(r)
.thenApply(e -> e.toBuilder()
.putAttribute(AwsEndpointAttribute.AUTH_SCHEMES, endpointAuthSchemes)
.build()))
.putAuthScheme(authScheme("aws.auth#sigv4", signer))
.build();
assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {}).join())
.hasMessageContaining("stop");
assertThat(signer.request.property(AwsV4HttpSigner.REGION_NAME)).isEqualTo("region-from-ep");
assertThat(signer.request.property(AwsV4HttpSigner.SERVICE_SIGNING_NAME)).isEqualTo("name-from-ep");
assertThat(signer.request.property(AwsV4HttpSigner.DOUBLE_URL_ENCODE)).isEqualTo(false);
}
@Test
public void sync_endpointProviderReturnsSignerProperties_overridesV4AAuthSchemeResolverProperties() {
RestJsonEndpointProvidersEndpointProvider defaultEndpointProvider =
RestJsonEndpointProvidersEndpointProvider.defaultProvider();
CapturingSigner signer = new CapturingSigner();
List<EndpointAuthScheme> endpointAuthSchemes = new ArrayList<>();
endpointAuthSchemes.add(SigV4aAuthScheme.builder()
.addSigningRegion("region-1-from-ep")
.signingName("name-from-ep")
.disableDoubleEncoding(true)
.build());
RestJsonEndpointProvidersClient client = syncClientBuilder()
.endpointProvider(r -> defaultEndpointProvider.resolveEndpoint(r)
.thenApply(e -> e.toBuilder()
.putAttribute(AwsEndpointAttribute.AUTH_SCHEMES, endpointAuthSchemes)
.build()))
.putAuthScheme(authScheme("aws.auth#sigv4a", signer))
.authSchemeProvider(p -> singletonList(AuthSchemeOption.builder()
.schemeId("aws.auth#sigv4a")
.putSignerProperty(
AwsV4aHttpSigner.REGION_SET, RegionSet.create("us-east-1"))
.putSignerProperty(AwsV4aHttpSigner.SERVICE_SIGNING_NAME, "Y")
.putSignerProperty(AwsV4aHttpSigner.DOUBLE_URL_ENCODE, true)
.build()))
.build();
assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {}))
.hasMessageContaining("stop");
assertThat(signer.request.property(AwsV4aHttpSigner.REGION_SET)).isEqualTo(RegionSet.create("region-1-from-ep"));
assertThat(signer.request.property(AwsV4aHttpSigner.SERVICE_SIGNING_NAME)).isEqualTo("name-from-ep");
assertThat(signer.request.property(AwsV4aHttpSigner.DOUBLE_URL_ENCODE)).isEqualTo(false);
}
@Test
public void async_endpointProviderReturnsSignerProperties_overridesV4AAuthSchemeResolverProperties() {
RestJsonEndpointProvidersEndpointProvider defaultEndpointProvider =
RestJsonEndpointProvidersEndpointProvider.defaultProvider();
CapturingSigner signer = new CapturingSigner();
List<EndpointAuthScheme> endpointAuthSchemes = new ArrayList<>();
endpointAuthSchemes.add(SigV4aAuthScheme.builder()
.addSigningRegion("region-1-from-ep")
.signingName("name-from-ep")
.disableDoubleEncoding(true)
.build());
RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder()
.endpointProvider(r -> defaultEndpointProvider.resolveEndpoint(r)
.thenApply(e -> e.toBuilder()
.putAttribute(AwsEndpointAttribute.AUTH_SCHEMES, endpointAuthSchemes)
.build()))
.putAuthScheme(authScheme("aws.auth#sigv4a", signer))
.authSchemeProvider(p -> singletonList(AuthSchemeOption.builder()
.schemeId("aws.auth#sigv4a")
.putSignerProperty(AwsV4aHttpSigner.REGION_SET,
RegionSet.create("us-east-1"))
.putSignerProperty(AwsV4aHttpSigner.SERVICE_SIGNING_NAME, "Y")
.putSignerProperty(AwsV4aHttpSigner.DOUBLE_URL_ENCODE, true)
.build()))
.build();
assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {}).join())
.hasMessageContaining("stop");
assertThat(signer.request.property(AwsV4aHttpSigner.REGION_SET)).isEqualTo(RegionSet.create("region-1-from-ep"));
assertThat(signer.request.property(AwsV4aHttpSigner.SERVICE_SIGNING_NAME)).isEqualTo("name-from-ep");
assertThat(signer.request.property(AwsV4aHttpSigner.DOUBLE_URL_ENCODE)).isEqualTo(false);
}
@Test
public void sync_endpointProviderDoesNotReturnV4SignerProperties_executionAttributesFromAuthSchemeOption() {
RestJsonEndpointProvidersEndpointProvider defaultEndpointProvider =
RestJsonEndpointProvidersEndpointProvider.defaultProvider();
CapturingInterceptor interceptor = new CapturingInterceptor();
RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder()
.overrideConfiguration(c -> c.addExecutionInterceptor(interceptor))
.authSchemeProvider(p -> singletonList(AuthSchemeOption.builder()
.schemeId("aws.auth#sigv4")
.putSignerProperty(AwsV4HttpSigner.REGION_NAME, "X")
.putSignerProperty(AwsV4HttpSigner.SERVICE_SIGNING_NAME, "Y")
.putSignerProperty(AwsV4HttpSigner.DOUBLE_URL_ENCODE, true)
.build()))
.endpointProvider(r -> defaultEndpointProvider.resolveEndpoint(r)
.thenApply(e -> e.toBuilder()
.putAttribute(AwsEndpointAttribute.AUTH_SCHEMES, emptyList())
.build()))
.build();
assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {}).join())
.hasMessageContaining("stop");
assertThat(interceptor.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION)).isEqualTo(Region.of("X"));
assertThat(interceptor.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME)).isEqualTo("Y");
assertThat(interceptor.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE)).isEqualTo(true);
}
@Test
public void sync_endpointProviderReturnsV4SignerProperties_executionAttributesFromEndpointProvider() {
RestJsonEndpointProvidersEndpointProvider defaultEndpointProvider =
RestJsonEndpointProvidersEndpointProvider.defaultProvider();
CapturingInterceptor interceptor = new CapturingInterceptor();
List<EndpointAuthScheme> endpointAuthSchemes = new ArrayList<>();
endpointAuthSchemes.add(SigV4AuthScheme.builder()
.signingRegion("region-from-ep")
.signingName("name-from-ep")
.disableDoubleEncoding(false)
.build());
RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder()
.overrideConfiguration(c -> c.addExecutionInterceptor(interceptor))
.endpointProvider(r -> defaultEndpointProvider.resolveEndpoint(r)
.thenApply(e -> e.toBuilder()
.putAttribute(AwsEndpointAttribute.AUTH_SCHEMES, endpointAuthSchemes)
.build()))
.authSchemeProvider(p -> singletonList(AuthSchemeOption.builder()
.schemeId("aws.auth#sigv4")
.putSignerProperty(AwsV4HttpSigner.REGION_NAME, "X")
.putSignerProperty(AwsV4HttpSigner.SERVICE_SIGNING_NAME, "Y")
.putSignerProperty(AwsV4HttpSigner.DOUBLE_URL_ENCODE, false)
.build()))
.build();
assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {}).join())
.hasMessageContaining("stop");
assertThat(interceptor.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION)).isEqualTo(Region.of("region-from-ep"));
assertThat(interceptor.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME)).isEqualTo("name-from-ep");
assertThat(interceptor.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE)).isEqualTo(true);
}
@Test
public void sync_endpointProviderDoesNotReturnV4aSignerProperties_executionAttributesFromAuthSchemeOption() {
RestJsonEndpointProvidersEndpointProvider defaultEndpointProvider =
RestJsonEndpointProvidersEndpointProvider.defaultProvider();
CapturingInterceptor interceptor = new CapturingInterceptor();
RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder()
.overrideConfiguration(c -> c.addExecutionInterceptor(interceptor))
.authSchemeProvider(p -> singletonList(AuthSchemeOption.builder()
.schemeId("aws.auth#sigv4a")
.putSignerProperty(AwsV4aHttpSigner.REGION_SET,
RegionSet.create("region-from-ap"))
.putSignerProperty(AwsV4aHttpSigner.SERVICE_SIGNING_NAME, "Y")
.putSignerProperty(AwsV4aHttpSigner.DOUBLE_URL_ENCODE, true)
.build()))
.endpointProvider(r -> defaultEndpointProvider.resolveEndpoint(r)
.thenApply(e -> e.toBuilder()
.putAttribute(AwsEndpointAttribute.AUTH_SCHEMES, emptyList())
.build()))
.putAuthScheme(authScheme("aws.auth#sigv4a", AwsV4HttpSigner.create()))
.build();
assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {}).join())
.hasMessageContaining("stop");
assertThat(interceptor.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION_SCOPE)).isEqualTo(RegionScope.create("region-from-ap"));
assertThat(interceptor.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME)).isEqualTo("Y");
assertThat(interceptor.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE)).isEqualTo(true);
}
@Test
public void sync_endpointProviderReturnsV4aSignerProperties_executionAttributesFromEndpointProvider() {
RestJsonEndpointProvidersEndpointProvider defaultEndpointProvider =
RestJsonEndpointProvidersEndpointProvider.defaultProvider();
CapturingInterceptor interceptor = new CapturingInterceptor();
List<EndpointAuthScheme> endpointAuthSchemes = new ArrayList<>();
endpointAuthSchemes.add(SigV4aAuthScheme.builder()
.addSigningRegion("region-from-ep")
.signingName("name-from-ep")
.disableDoubleEncoding(false)
.build());
RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder()
.overrideConfiguration(c -> c.addExecutionInterceptor(interceptor))
.endpointProvider(r -> defaultEndpointProvider.resolveEndpoint(r)
.thenApply(e -> e.toBuilder()
.putAttribute(AwsEndpointAttribute.AUTH_SCHEMES, endpointAuthSchemes)
.build()))
.authSchemeProvider(p -> singletonList(AuthSchemeOption.builder()
.schemeId("aws.auth#sigv4a")
.putSignerProperty(AwsV4aHttpSigner.REGION_SET,
RegionSet.create("us-east-1"))
.putSignerProperty(AwsV4aHttpSigner.SERVICE_SIGNING_NAME, "Y")
.putSignerProperty(AwsV4aHttpSigner.DOUBLE_URL_ENCODE, false)
.build()))
.putAuthScheme(authScheme("aws.auth#sigv4a", AwsV4HttpSigner.create()))
.build();
assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {}).join())
.hasMessageContaining("stop");
assertThat(interceptor.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION_SCOPE)).isEqualTo(RegionScope.create("region-from-ep"));
assertThat(interceptor.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME)).isEqualTo("name-from-ep");
assertThat(interceptor.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE)).isEqualTo(true);
}
*/
private static AuthScheme<?> authScheme(String schemeId, HttpSigner<AwsCredentialsIdentity> signer) {
return new AuthScheme<AwsCredentialsIdentity>() {
@Override
public String schemeId() {
return schemeId;
}
@Override
public IdentityProvider<AwsCredentialsIdentity> identityProvider(IdentityProviders providers) {
return providers.identityProvider(AwsCredentialsIdentity.class);
}
@Override
public HttpSigner<AwsCredentialsIdentity> signer() {
return signer;
}
};
}
public static class CapturingSigner implements HttpSigner<AwsCredentialsIdentity> {
private BaseSignRequest<?, ?> request;
@Override
public SignedRequest sign(SignRequest<? extends AwsCredentialsIdentity> request) {
this.request = request;
throw new CaptureCompletedException("stop");
}
@Override
public CompletableFuture<AsyncSignedRequest> signAsync(AsyncSignRequest<? extends AwsCredentialsIdentity> request) {
this.request = request;
return CompletableFutureUtils.failedFuture(new CaptureCompletedException("stop"));
}
}
public static class CapturingInterceptor implements ExecutionInterceptor {
private Context.BeforeTransmission context;
private ExecutionAttributes executionAttributes;
@Override
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) {
this.context = context;
this.executionAttributes = executionAttributes;
throw new CaptureCompletedException("stop");
}
public ExecutionAttributes executionAttributes() {
return executionAttributes;
}
}
public static class CaptureCompletedException extends RuntimeException {
CaptureCompletedException(String message) {
super(message);
}
}
private RestJsonEndpointProvidersClientBuilder syncClientBuilder() {
return RestJsonEndpointProvidersClient.builder()
.region(Region.US_WEST_2)
.credentialsProvider(
StaticCredentialsProvider.create(
AwsBasicCredentials.create("akid", "skid")));
}
private RestJsonEndpointProvidersAsyncClientBuilder asyncClientBuilder() {
return RestJsonEndpointProvidersAsyncClient.builder()
.region(Region.US_WEST_2)
.credentialsProvider(
StaticCredentialsProvider.create(
AwsBasicCredentials.create("akid", "skid")));
}
}
| 2,618 |
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/endpointproviders/AuthSchemeUtilsTest.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.endpointproviders;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.Collections;
import org.junit.Test;
import software.amazon.awssdk.awscore.endpoints.authscheme.EndpointAuthScheme;
import software.amazon.awssdk.awscore.endpoints.authscheme.SigV4AuthScheme;
import software.amazon.awssdk.awscore.endpoints.authscheme.SigV4aAuthScheme;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.AuthSchemeUtils;
public class AuthSchemeUtilsTest {
@Test
public void chooseAuthScheme_noSchemesInList_throws() {
assertThatThrownBy(() -> AuthSchemeUtils.chooseAuthScheme(Collections.emptyList()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("Endpoint did not contain any known auth schemes");
}
@Test
public void chooseAuthScheme_noKnownSchemes_throws() {
EndpointAuthScheme sigv1 = mock(EndpointAuthScheme.class);
when(sigv1.name()).thenReturn("sigv1");
EndpointAuthScheme sigv5 = mock(EndpointAuthScheme.class);
when(sigv5.name()).thenReturn("sigv5");
assertThatThrownBy(() -> AuthSchemeUtils.chooseAuthScheme(Arrays.asList(sigv1, sigv5)))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("Endpoint did not contain any known auth schemes");
}
@Test
public void chooseAuthScheme_multipleSchemesKnown_choosesFirst() {
EndpointAuthScheme sigv4 = SigV4AuthScheme.builder().build();
EndpointAuthScheme sigv4a = SigV4aAuthScheme.builder().build();
assertThat(AuthSchemeUtils.chooseAuthScheme(Arrays.asList(sigv4, sigv4a))).isEqualTo(sigv4);
}
}
| 2,619 |
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/endpointproviders/EndpointProviderTest.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.endpointproviders;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.RestJsonEndpointProvidersEndpointProvider;
public class EndpointProviderTest {
@Test
public void resolveEndpoint_requiredParamNotPresent_throws() {
assertThatThrownBy(() -> RestJsonEndpointProvidersEndpointProvider.defaultProvider()
.resolveEndpoint(r -> {}))
.hasMessageContaining("must not be null");
}
@Test
public void resolveEndpoint_optionalParamNotPresent_doesNotThrow() {
assertThatNoException().isThrownBy(() ->
RestJsonEndpointProvidersEndpointProvider.defaultProvider()
.resolveEndpoint(r -> r.useFips(null)
.region(Region.of("us-mars-1"))));
}
}
| 2,620 |
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/endpointproviders/DefaultPartitionDataProviderTest.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.endpointproviders;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.DefaultPartitionDataProvider;
import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Partition;
import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Partitions;
public class DefaultPartitionDataProviderTest {
private DefaultPartitionDataProvider provider;
@BeforeEach
public void setup() {
provider = new DefaultPartitionDataProvider();
}
@Test
public void loadPartitions_returnsData() {
Partitions partitions = provider.loadPartitions();
assertThat(partitions.partitions()).isNotEmpty();
}
@Test
public void loadPartitions_partitionsContainsValidData() {
Partition awsPartition = provider.loadPartitions()
.partitions()
.stream().filter(e -> e.id().equals("aws"))
.findFirst()
.orElseThrow(
() -> new RuntimeException("could not find aws partition"));
assertThat(awsPartition.regions()).containsKey("us-west-2");
}
}
| 2,621 |
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/endpointproviders/ParametersTest.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.endpointproviders;
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.verify;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.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.regions.Region;
import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersClient;
import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.RestJsonEndpointProvidersEndpointParams;
import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.RestJsonEndpointProvidersEndpointProvider;
public class ParametersTest {
private static final AwsCredentialsProvider CREDENTIALS = StaticCredentialsProvider.create(
AwsBasicCredentials.create("akid", "skid"));
private static final Region REGION = Region.of("us-east-9000");
private RestJsonEndpointProvidersEndpointProvider mockEndpointProvider;
@Before
public void setup() {
mockEndpointProvider = mock(RestJsonEndpointProvidersEndpointProvider.class);
when(mockEndpointProvider.resolveEndpoint(any(RestJsonEndpointProvidersEndpointParams.class)))
.thenThrow(new RuntimeException("boom"));
}
@Test
public void parametersObject_defaultStringParam_isPresent() {
RestJsonEndpointProvidersEndpointParams params = RestJsonEndpointProvidersEndpointParams.builder().build();
assertThat(params.regionWithDefault()).isEqualTo(Region.of("us-east-1"));
}
@Test
public void parametersObject_defaultBooleanParam_isPresent() {
RestJsonEndpointProvidersEndpointParams params = RestJsonEndpointProvidersEndpointParams.builder().build();
assertThat(params.useFips()).isEqualTo(false);
}
@Test
public void parametersObject_defaultStringParam_customValue_isPresent() {
RestJsonEndpointProvidersEndpointParams params = RestJsonEndpointProvidersEndpointParams.builder()
.regionWithDefault(Region.of(
"us-east-1000"))
.build();
assertThat(params.regionWithDefault()).isEqualTo(Region.of("us-east-1000"));
}
@Test
public void parametersObject_defaultBooleanParam_customValue_isPresent() {
RestJsonEndpointProvidersEndpointParams params = RestJsonEndpointProvidersEndpointParams.builder()
.useFips(true)
.build();
assertThat(params.useFips()).isEqualTo(true);
}
@Test
public void parametersObject_defaultStringParam_setToNull_usesDefaultValue() {
RestJsonEndpointProvidersEndpointParams params = RestJsonEndpointProvidersEndpointParams.builder()
.regionWithDefault(null)
.build();
assertThat(params.regionWithDefault()).isEqualTo(Region.of("us-east-1"));
}
@Test
public void parametersObject_defaultBooleanParam_setToNull_usesDefaultValue() {
RestJsonEndpointProvidersEndpointParams params = RestJsonEndpointProvidersEndpointParams.builder()
.useFips(null)
.build();
assertThat(params.useFips()).isEqualTo(false);
}
@Test
public void regionBuiltIn_resolvedCorrectly() {
RestJsonEndpointProvidersClient client = RestJsonEndpointProvidersClient.builder()
.region(REGION)
.credentialsProvider(CREDENTIALS)
.endpointProvider(mockEndpointProvider)
.build();
assertThatThrownBy(() -> client.operationWithNoInputOrOutput(r -> {
}));
ArgumentCaptor<RestJsonEndpointProvidersEndpointParams> paramsCaptor =
ArgumentCaptor.forClass(RestJsonEndpointProvidersEndpointParams.class);
verify(mockEndpointProvider).resolveEndpoint(paramsCaptor.capture());
RestJsonEndpointProvidersEndpointParams params = paramsCaptor.getValue();
assertThat(params.region()).isEqualTo(REGION);
}
@Test
public void dualStackBuiltIn_resolvedCorrectly() {
RestJsonEndpointProvidersClient client = RestJsonEndpointProvidersClient.builder()
.region(REGION)
.dualstackEnabled(true)
.credentialsProvider(CREDENTIALS)
.endpointProvider(mockEndpointProvider)
.build();
assertThatThrownBy(() -> client.operationWithNoInputOrOutput(r -> {
}));
ArgumentCaptor<RestJsonEndpointProvidersEndpointParams> paramsCaptor =
ArgumentCaptor.forClass(RestJsonEndpointProvidersEndpointParams.class);
verify(mockEndpointProvider).resolveEndpoint(paramsCaptor.capture());
RestJsonEndpointProvidersEndpointParams params = paramsCaptor.getValue();
assertThat(params.useDualStack()).isEqualTo(true);
}
@Test
public void fipsBuiltIn_resolvedCorrectly() {
RestJsonEndpointProvidersClient client = RestJsonEndpointProvidersClient.builder()
.region(REGION)
.fipsEnabled(true)
.credentialsProvider(CREDENTIALS)
.endpointProvider(mockEndpointProvider)
.build();
assertThatThrownBy(() -> client.operationWithNoInputOrOutput(r -> {
}));
ArgumentCaptor<RestJsonEndpointProvidersEndpointParams> paramsCaptor =
ArgumentCaptor.forClass(RestJsonEndpointProvidersEndpointParams.class);
verify(mockEndpointProvider).resolveEndpoint(paramsCaptor.capture());
RestJsonEndpointProvidersEndpointParams params = paramsCaptor.getValue();
assertThat(params.useFips()).isEqualTo(true);
}
@Test
public void staticContextParams_OperationWithStaticContextParamA_resolvedCorrectly() {
RestJsonEndpointProvidersClient client = RestJsonEndpointProvidersClient.builder()
.region(REGION)
.credentialsProvider(CREDENTIALS)
.endpointProvider(mockEndpointProvider)
.build();
assertThatThrownBy(() -> client.operationWithStaticContextParamA(r -> {
}));
ArgumentCaptor<RestJsonEndpointProvidersEndpointParams> paramsCaptor =
ArgumentCaptor.forClass(RestJsonEndpointProvidersEndpointParams.class);
verify(mockEndpointProvider).resolveEndpoint(paramsCaptor.capture());
RestJsonEndpointProvidersEndpointParams params = paramsCaptor.getValue();
assertThat(params.staticStringParam()).isEqualTo("operation A");
}
@Test
public void staticContextParams_OperationWithStaticContextParamB_resolvedCorrectly() {
RestJsonEndpointProvidersClient client = RestJsonEndpointProvidersClient.builder()
.region(REGION)
.credentialsProvider(CREDENTIALS)
.endpointProvider(mockEndpointProvider)
.build();
assertThatThrownBy(() -> client.operationWithStaticContextParamB(r -> {
}));
ArgumentCaptor<RestJsonEndpointProvidersEndpointParams> paramsCaptor =
ArgumentCaptor.forClass(RestJsonEndpointProvidersEndpointParams.class);
verify(mockEndpointProvider).resolveEndpoint(paramsCaptor.capture());
RestJsonEndpointProvidersEndpointParams params = paramsCaptor.getValue();
assertThat(params.staticStringParam()).isEqualTo("operation B");
}
@Test
public void contextParams_OperationWithContextParam_resolvedCorrectly() {
RestJsonEndpointProvidersClient client = RestJsonEndpointProvidersClient.builder()
.region(REGION)
.credentialsProvider(CREDENTIALS)
.endpointProvider(mockEndpointProvider)
.build();
assertThatThrownBy(() -> client.operationWithContextParam(r -> r.stringMember("foobar")));
ArgumentCaptor<RestJsonEndpointProvidersEndpointParams> paramsCaptor =
ArgumentCaptor.forClass(RestJsonEndpointProvidersEndpointParams.class);
verify(mockEndpointProvider).resolveEndpoint(paramsCaptor.capture());
RestJsonEndpointProvidersEndpointParams params = paramsCaptor.getValue();
assertThat(params.operationContextParam()).isEqualTo("foobar");
}
@Test
public void clientContextParams_setOnBuilder_resolvedCorrectly() {
RestJsonEndpointProvidersClient client = RestJsonEndpointProvidersClient.builder()
.region(REGION)
.credentialsProvider(CREDENTIALS)
.endpointProvider(mockEndpointProvider)
.stringClientContextParam("foobar")
.booleanClientContextParam(true)
.build();
assertThatThrownBy(() -> client.operationWithNoInputOrOutput(r -> {
}));
ArgumentCaptor<RestJsonEndpointProvidersEndpointParams> paramsCaptor =
ArgumentCaptor.forClass(RestJsonEndpointProvidersEndpointParams.class);
verify(mockEndpointProvider).resolveEndpoint(paramsCaptor.capture());
RestJsonEndpointProvidersEndpointParams params = paramsCaptor.getValue();
assertThat(params.stringClientContextParam()).isEqualTo("foobar");
assertThat(params.booleanClientContextParam()).isTrue();
}
}
| 2,622 |
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/endpointproviders/AwsEndpointProviderUtilsTest.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.endpointproviders;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import software.amazon.awssdk.awscore.AwsExecutionAttribute;
import software.amazon.awssdk.awscore.endpoints.AwsEndpointAttribute;
import software.amazon.awssdk.awscore.endpoints.authscheme.EndpointAuthScheme;
import software.amazon.awssdk.awscore.endpoints.authscheme.SigV4AuthScheme;
import software.amazon.awssdk.awscore.endpoints.authscheme.SigV4aAuthScheme;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute;
import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute;
import software.amazon.awssdk.endpoints.Endpoint;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.AwsEndpointProviderUtils;
import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Identifier;
import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.internal.Value;
import software.amazon.awssdk.utils.MapUtils;
public class AwsEndpointProviderUtilsTest {
@Test
public void endpointOverridden_attrIsFalse_returnsFalse() {
ExecutionAttributes attrs = new ExecutionAttributes();
attrs.putAttribute(SdkExecutionAttribute.ENDPOINT_OVERRIDDEN, false);
assertThat(AwsEndpointProviderUtils.endpointIsOverridden(attrs)).isFalse();
}
@Test
public void endpointOverridden_attrIsAbsent_returnsFalse() {
ExecutionAttributes attrs = new ExecutionAttributes();
assertThat(AwsEndpointProviderUtils.endpointIsOverridden(attrs)).isFalse();
}
@Test
public void endpointOverridden_attrIsTrue_returnsTrue() {
ExecutionAttributes attrs = new ExecutionAttributes();
attrs.putAttribute(SdkExecutionAttribute.ENDPOINT_OVERRIDDEN, true);
assertThat(AwsEndpointProviderUtils.endpointIsOverridden(attrs)).isTrue();
}
@Test
public void endpointIsDiscovered_attrIsFalse_returnsFalse() {
ExecutionAttributes attrs = new ExecutionAttributes();
attrs.putAttribute(SdkInternalExecutionAttribute.IS_DISCOVERED_ENDPOINT, false);
assertThat(AwsEndpointProviderUtils.endpointIsDiscovered(attrs)).isFalse();
}
@Test
public void endpointIsDiscovered_attrIsAbsent_returnsFalse() {
ExecutionAttributes attrs = new ExecutionAttributes();
assertThat(AwsEndpointProviderUtils.endpointIsDiscovered(attrs)).isFalse();
}
@Test
public void endpointIsDiscovered_attrIsTrue_returnsTrue() {
ExecutionAttributes attrs = new ExecutionAttributes();
attrs.putAttribute(SdkInternalExecutionAttribute.IS_DISCOVERED_ENDPOINT, true);
assertThat(AwsEndpointProviderUtils.endpointIsDiscovered(attrs)).isTrue();
}
@Test
public void disableHostPrefixInjection_attrIsFalse_returnsFalse() {
ExecutionAttributes attrs = new ExecutionAttributes();
attrs.putAttribute(SdkInternalExecutionAttribute.DISABLE_HOST_PREFIX_INJECTION, false);
assertThat(AwsEndpointProviderUtils.disableHostPrefixInjection(attrs)).isFalse();
}
@Test
public void disableHostPrefixInjection_attrIsAbsent_returnsFalse() {
ExecutionAttributes attrs = new ExecutionAttributes();
assertThat(AwsEndpointProviderUtils.disableHostPrefixInjection(attrs)).isFalse();
}
@Test
public void disableHostPrefixInjection_attrIsTrue_returnsTrue() {
ExecutionAttributes attrs = new ExecutionAttributes();
attrs.putAttribute(SdkInternalExecutionAttribute.DISABLE_HOST_PREFIX_INJECTION, true);
assertThat(AwsEndpointProviderUtils.disableHostPrefixInjection(attrs)).isTrue();
}
@Test
public void valueAsEndpoint_isNone_throws() {
assertThatThrownBy(() -> AwsEndpointProviderUtils.valueAsEndpointOrThrow(Value.none()))
.isInstanceOf(SdkClientException.class);
}
@Test
public void valueAsEndpoint_isString_throwsAsMsg() {
assertThatThrownBy(() -> AwsEndpointProviderUtils.valueAsEndpointOrThrow(Value.fromStr("oops!")))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("oops!");
}
@Test
public void valueAsEndpoint_isEndpoint_returnsEndpoint() {
Value.Endpoint endpointVal = Value.Endpoint.builder()
.url("https://myservice.aws")
.build();
Endpoint expected = Endpoint.builder()
.url(URI.create("https://myservice.aws"))
.build();
assertThat(expected.url()).isEqualTo(AwsEndpointProviderUtils.valueAsEndpointOrThrow(endpointVal).url());
}
@Test
public void valueAsEndpoint_endpointHasAuthSchemes_includesAuthSchemes() {
List<Value> authSchemes = Arrays.asList(
Value.fromRecord(MapUtils.of(Identifier.of("name"), Value.fromStr("sigv4"),
Identifier.of("signingRegion"), Value.fromStr("us-west-2"),
Identifier.of("signingName"), Value.fromStr("myservice"),
Identifier.of("disableDoubleEncoding"), Value.fromBool(false))),
Value.fromRecord(MapUtils.of(Identifier.of("name"), Value.fromStr("sigv4a"),
Identifier.of("signingRegionSet"),
Value.fromArray(Collections.singletonList(Value.fromStr("*"))),
Identifier.of("signingName"), Value.fromStr("myservice"),
Identifier.of("disableDoubleEncoding"), Value.fromBool(false))),
// Unknown scheme name, should ignore
Value.fromRecord(MapUtils.of(Identifier.of("name"), Value.fromStr("sigv5")))
);
Value.Endpoint endpointVal = Value.Endpoint.builder()
.url("https://myservice.aws")
.property("authSchemes", Value.fromArray(authSchemes))
.build();
EndpointAuthScheme sigv4 = SigV4AuthScheme.builder()
.signingName("myservice")
.signingRegion("us-west-2")
.disableDoubleEncoding(false)
.build();
EndpointAuthScheme sigv4a = SigV4aAuthScheme.builder()
.signingName("myservice")
.addSigningRegion("*")
.disableDoubleEncoding(false)
.build();
assertThat(AwsEndpointProviderUtils.valueAsEndpointOrThrow(endpointVal).attribute(AwsEndpointAttribute.AUTH_SCHEMES))
.containsExactly(sigv4, sigv4a);
}
@Test
public void valueAsEndpoint_endpointHasUnknownProperty_ignores() {
Value.Endpoint endpointVal = Value.Endpoint.builder()
.url("https://myservice.aws")
.property("foo", Value.fromStr("baz"))
.build();
assertThat(AwsEndpointProviderUtils.valueAsEndpointOrThrow(endpointVal).attribute(AwsEndpointAttribute.AUTH_SCHEMES)).isNull();
}
@Test
public void valueAsEndpoint_endpointHasHeaders_includesHeaders() {
Value.Endpoint endpointVal = Value.Endpoint.builder()
.url("https://myservice.aws")
.addHeader("foo1", "bar1")
.addHeader("foo1", "bar2")
.addHeader("foo2", "baz")
.build();
Map<String, List<String>> expectedHeaders = MapUtils.of("foo1", Arrays.asList("bar1", "bar2"),
"foo2", Arrays.asList("baz"));
assertThat(AwsEndpointProviderUtils.valueAsEndpointOrThrow(endpointVal).headers()).isEqualTo(expectedHeaders);
}
@Test
public void regionBuiltIn_returnsAttrValue() {
ExecutionAttributes attrs = new ExecutionAttributes();
attrs.putAttribute(AwsExecutionAttribute.AWS_REGION, Region.US_EAST_1);
assertThat(AwsEndpointProviderUtils.regionBuiltIn(attrs)).isEqualTo(Region.US_EAST_1);
}
@Test
public void dualStackEnabledBuiltIn_returnsAttrValue() {
ExecutionAttributes attrs = new ExecutionAttributes();
attrs.putAttribute(AwsExecutionAttribute.DUALSTACK_ENDPOINT_ENABLED, true);
assertThat(AwsEndpointProviderUtils.dualStackEnabledBuiltIn(attrs)).isEqualTo(true);
}
@Test
public void fipsEnabledBuiltIn_returnsAttrValue() {
ExecutionAttributes attrs = new ExecutionAttributes();
attrs.putAttribute(AwsExecutionAttribute.FIPS_ENDPOINT_ENABLED, true);
assertThat(AwsEndpointProviderUtils.fipsEnabledBuiltIn(attrs)).isEqualTo(true);
}
@Test
public void endpointBuiltIn_doesNotIncludeQueryParams() {
URI endpoint = URI.create("https://example.com/path?foo=bar");
ExecutionAttributes attrs = new ExecutionAttributes();
attrs.putAttribute(SdkExecutionAttribute.ENDPOINT_OVERRIDDEN, true);
attrs.putAttribute(SdkExecutionAttribute.CLIENT_ENDPOINT, endpoint);
assertThat(AwsEndpointProviderUtils.endpointBuiltIn(attrs).toString()).isEqualTo("https://example.com/path");
}
@Test
public void useGlobalEndpointBuiltIn_returnsAttrValue() {
ExecutionAttributes attrs = new ExecutionAttributes();
attrs.putAttribute(AwsExecutionAttribute.USE_GLOBAL_ENDPOINT, true);
assertThat(AwsEndpointProviderUtils.useGlobalEndpointBuiltIn(attrs)).isEqualTo(true);
}
@Test
public void setUri_combinesPathsCorrectly() {
URI clientEndpoint = URI.create("https://override.example.com/a");
URI requestUri = URI.create("https://override.example.com/a/c");
URI resolvedUri = URI.create("https://override.example.com/a/b");
SdkHttpRequest request = SdkHttpRequest.builder()
.uri(requestUri)
.method(SdkHttpMethod.GET)
.build();
assertThat(AwsEndpointProviderUtils.setUri(request, clientEndpoint, resolvedUri).getUri().toString())
.isEqualTo("https://override.example.com/a/b/c");
}
@Test
public void setUri_doubleSlash_combinesPathsCorrectly() {
URI clientEndpoint = URI.create("https://override.example.com/a");
URI requestUri = URI.create("https://override.example.com/a//c");
URI resolvedUri = URI.create("https://override.example.com/a/b");
SdkHttpRequest request = SdkHttpRequest.builder()
.uri(requestUri)
.method(SdkHttpMethod.GET)
.build();
assertThat(AwsEndpointProviderUtils.setUri(request, clientEndpoint, resolvedUri).getUri().toString())
.isEqualTo("https://override.example.com/a/b//c");
}
@Test
public void setUri_withTrailingSlashNoPath_combinesPathsCorrectly() {
URI clientEndpoint = URI.create("https://override.example.com/");
URI requestUri = URI.create("https://override.example.com//a");
URI resolvedUri = URI.create("https://override.example.com/");
SdkHttpRequest request = SdkHttpRequest.builder()
.uri(requestUri)
.method(SdkHttpMethod.GET)
.build();
assertThat(AwsEndpointProviderUtils.setUri(request, clientEndpoint, resolvedUri).getUri().toString())
.isEqualTo("https://override.example.com//a");
}
@Test
public void addHostPrefix_prefixIsNull_returnsUnModified() {
URI url = URI.create("https://foo.aws");
Endpoint e = Endpoint.builder()
.url(url)
.build();
assertThat(AwsEndpointProviderUtils.addHostPrefix(e, null).url()).isEqualTo(url);
}
@Test
public void addHostPrefix_prefixIsEmpty_returnsUnModified() {
URI url = URI.create("https://foo.aws");
Endpoint e = Endpoint.builder()
.url(url)
.build();
assertThat(AwsEndpointProviderUtils.addHostPrefix(e, "").url()).isEqualTo(url);
}
@Test
public void addHostPrefix_prefixPresent_returnsPrefixPrepended() {
URI url = URI.create("https://foo.aws");
Endpoint e = Endpoint.builder()
.url(url)
.build();
URI expected = URI.create("https://api.foo.aws");
assertThat(AwsEndpointProviderUtils.addHostPrefix(e, "api.").url()).isEqualTo(expected);
}
@Test
public void addHostPrefix_prefixPresent_preservesPortPathAndQuery() {
URI url = URI.create("https://foo.aws:1234/a/b/c?queryParam1=val1");
Endpoint e = Endpoint.builder()
.url(url)
.build();
URI expected = URI.create("https://api.foo.aws:1234/a/b/c?queryParam1=val1");
assertThat(AwsEndpointProviderUtils.addHostPrefix(e, "api.").url()).isEqualTo(expected);
}
@Test
public void addHostPrefix_prefixInvalid_throws() {
URI url = URI.create("https://foo.aws");
Endpoint e = Endpoint.builder()
.url(url)
.build();
assertThatThrownBy(() -> AwsEndpointProviderUtils.addHostPrefix(e, "foo#bar.*baz"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("component must match the pattern");
}
}
| 2,623 |
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/endpointproviders/ClientBuilderTests.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.endpointproviders;
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.verify;
import static org.mockito.Mockito.when;
import java.net.URI;
import java.util.concurrent.CompletableFuture;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute;
import software.amazon.awssdk.endpoints.Endpoint;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersAsyncClient;
import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersAsyncClientBuilder;
import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersClient;
import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersClientBuilder;
import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.RestJsonEndpointProvidersClientContextParams;
import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.RestJsonEndpointProvidersEndpointParams;
import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.RestJsonEndpointProvidersEndpointProvider;
import software.amazon.awssdk.utils.AttributeMap;
import software.amazon.awssdk.utils.CompletableFutureUtils;
public class ClientBuilderTests {
@Test
public void syncBuilder_setCustomProvider_interceptorUsesProvider() {
RestJsonEndpointProvidersEndpointProvider mockProvider = mock(RestJsonEndpointProvidersEndpointProvider.class);
SdkHttpClient mockClient = mock(SdkHttpClient.class);
when(mockClient.clientName()).thenReturn("MockHttpClient");
when(mockClient.prepareRequest(any())).thenThrow(new RuntimeException("boom"));
when(mockProvider.resolveEndpoint(any(RestJsonEndpointProvidersEndpointParams.class)))
.thenReturn(CompletableFuture.completedFuture(Endpoint.builder()
.url(URI.create("https://my-service.com"))
.build()));
RestJsonEndpointProvidersClient client =
RestJsonEndpointProvidersClient.builder()
.endpointProvider(mockProvider)
.httpClient(mockClient)
.region(Region.US_WEST_2)
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create("akid", "skid")))
.build();
assertThatThrownBy(() -> client.operationWithNoInputOrOutput(r -> {
})).hasMessageContaining("boom");
verify(mockProvider).resolveEndpoint(any(RestJsonEndpointProvidersEndpointParams.class));
ArgumentCaptor<HttpExecuteRequest> httpRequestCaptor = ArgumentCaptor.forClass(HttpExecuteRequest.class);
verify(mockClient).prepareRequest(httpRequestCaptor.capture());
URI requestUri = httpRequestCaptor.getValue().httpRequest().getUri();
assertThat(requestUri.getScheme()).isEqualTo("https");
assertThat(requestUri.getHost()).isEqualTo("my-service.com");
}
@Test
public void asyncBuilder_setCustomProvider_interceptorUsesProvider() {
RestJsonEndpointProvidersEndpointProvider mockProvider = mock(RestJsonEndpointProvidersEndpointProvider.class);
SdkAsyncHttpClient mockClient = mock(SdkAsyncHttpClient.class);
when(mockClient.clientName()).thenReturn("MockHttpClient");
when(mockClient.execute(any())).thenAnswer(i -> {
AsyncExecuteRequest r = i.getArgument(0, AsyncExecuteRequest.class);
r.responseHandler().onError(new RuntimeException("boom"));
return CompletableFutureUtils.failedFuture(new RuntimeException());
});
when(mockProvider.resolveEndpoint(any(RestJsonEndpointProvidersEndpointParams.class)))
.thenReturn(CompletableFuture.completedFuture(Endpoint.builder()
.url(URI.create("https://my-service.com"))
.build()));
RestJsonEndpointProvidersAsyncClient client =
RestJsonEndpointProvidersAsyncClient.builder()
.endpointProvider(mockProvider)
.httpClient(mockClient)
.region(Region.US_WEST_2)
.credentialsProvider(
StaticCredentialsProvider.create(
AwsBasicCredentials.create("akid", "skid")))
.build();
assertThatThrownBy(() -> client.operationWithNoInputOrOutput(r -> {
}).join())
.hasRootCauseMessage("boom");
verify(mockProvider).resolveEndpoint(any(RestJsonEndpointProvidersEndpointParams.class));
ArgumentCaptor<AsyncExecuteRequest> httpRequestCaptor = ArgumentCaptor.forClass(AsyncExecuteRequest.class);
verify(mockClient).execute(httpRequestCaptor.capture());
URI requestUri = httpRequestCaptor.getValue().request().getUri();
assertThat(requestUri.getScheme()).isEqualTo("https");
assertThat(requestUri.getHost()).isEqualTo("my-service.com");
}
@Test
public void sync_clientContextParamsSetOnBuilder_includedInExecutionAttributes() {
ExecutionInterceptor mockInterceptor = mock(ExecutionInterceptor.class);
when(mockInterceptor.modifyRequest(any(), any())).thenThrow(new RuntimeException("oops"));
RestJsonEndpointProvidersClient client = syncClientBuilder()
.overrideConfiguration(o -> o.addExecutionInterceptor(mockInterceptor))
.booleanClientContextParam(true)
.stringClientContextParam("hello")
.build();
assertThatThrownBy(() -> client.operationWithNoInputOrOutput(r -> {
})).hasMessageContaining("oops");
ArgumentCaptor<ExecutionAttributes> attributesCaptor = ArgumentCaptor.forClass(ExecutionAttributes.class);
verify(mockInterceptor).modifyRequest(any(), attributesCaptor.capture());
ExecutionAttributes executionAttrs = attributesCaptor.getValue();
AttributeMap clientContextParams = executionAttrs.getAttribute(SdkInternalExecutionAttribute.CLIENT_CONTEXT_PARAMS);
assertThat(clientContextParams.get(RestJsonEndpointProvidersClientContextParams.BOOLEAN_CLIENT_CONTEXT_PARAM))
.isEqualTo(true);
assertThat(clientContextParams.get(RestJsonEndpointProvidersClientContextParams.STRING_CLIENT_CONTEXT_PARAM))
.isEqualTo("hello");
}
@Test
public void async_clientContextParamsSetOnBuilder_includedInExecutionAttributes() {
ExecutionInterceptor mockInterceptor = mock(ExecutionInterceptor.class);
when(mockInterceptor.modifyRequest(any(), any())).thenThrow(new RuntimeException("oops"));
RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder()
.overrideConfiguration(o -> o.addExecutionInterceptor(mockInterceptor))
.booleanClientContextParam(true)
.stringClientContextParam("hello")
.build();
assertThatThrownBy(() -> client.operationWithNoInputOrOutput(r -> {
}).join()).hasMessageContaining("oops");
ArgumentCaptor<ExecutionAttributes> attributesCaptor = ArgumentCaptor.forClass(ExecutionAttributes.class);
verify(mockInterceptor).modifyRequest(any(), attributesCaptor.capture());
ExecutionAttributes executionAttrs = attributesCaptor.getValue();
AttributeMap clientContextParams = executionAttrs.getAttribute(SdkInternalExecutionAttribute.CLIENT_CONTEXT_PARAMS);
assertThat(clientContextParams.get(RestJsonEndpointProvidersClientContextParams.BOOLEAN_CLIENT_CONTEXT_PARAM))
.isEqualTo(true);
assertThat(clientContextParams.get(RestJsonEndpointProvidersClientContextParams.STRING_CLIENT_CONTEXT_PARAM))
.isEqualTo("hello");
}
private RestJsonEndpointProvidersClientBuilder syncClientBuilder() {
return RestJsonEndpointProvidersClient.builder()
.region(Region.US_WEST_2)
.credentialsProvider(
StaticCredentialsProvider.create(
AwsBasicCredentials.create("akid", "skid")));
}
private RestJsonEndpointProvidersAsyncClientBuilder asyncClientBuilder() {
return RestJsonEndpointProvidersAsyncClient.builder()
.region(Region.US_WEST_2)
.credentialsProvider(
StaticCredentialsProvider.create(
AwsBasicCredentials.create("akid", "skid")));
}
}
| 2,624 |
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/endpointproviders/RequestOverrideEndpointProviderTests.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.endpointproviders;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.net.URI;
import java.util.concurrent.CompletableFuture;
import org.junit.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption;
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.core.interceptor.SdkInternalExecutionAttribute;
import software.amazon.awssdk.endpoints.Endpoint;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersAsyncClient;
import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersAsyncClientBuilder;
import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersClient;
import software.amazon.awssdk.services.restjsonendpointproviders.RestJsonEndpointProvidersClientBuilder;
import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.RestJsonEndpointProvidersEndpointParams;
import software.amazon.awssdk.services.restjsonendpointproviders.endpoints.RestJsonEndpointProvidersEndpointProvider;
public class RequestOverrideEndpointProviderTests {
@Test
public void sync_endpointOverridden_equals_requestOverride() {
CapturingInterceptor interceptor = new CapturingInterceptor();
RestJsonEndpointProvidersClient client = syncClientBuilder()
.overrideConfiguration(o -> o.addExecutionInterceptor(interceptor)
.putAdvancedOption(SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION, true))
.build();
assertThatThrownBy(() -> client.operationWithHostPrefix(
r -> r.overrideConfiguration(o -> o.endpointProvider(new CustomEndpointProvider(Region.AWS_GLOBAL))))
)
.hasMessageContaining("stop");
Endpoint endpoint = interceptor.executionAttributes().getAttribute(SdkInternalExecutionAttribute.RESOLVED_ENDPOINT);
assertThat(endpoint.url().getHost()).isEqualTo("restjson.aws-global.amazonaws.com");
}
@Test
public void sync_endpointOverridden_equals_ClientsWhenNoRequestOverride() {
CapturingInterceptor interceptor = new CapturingInterceptor();
RestJsonEndpointProvidersClient client = syncClientBuilder().endpointProvider(new CustomEndpointProvider(Region.EU_WEST_2))
.overrideConfiguration(o -> o.addExecutionInterceptor(interceptor)
.putAdvancedOption(SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION, true))
.build();
assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {})).hasMessageContaining("stop");
Endpoint endpoint = interceptor.executionAttributes().getAttribute(SdkInternalExecutionAttribute.RESOLVED_ENDPOINT);
assertThat(endpoint.url().getHost()).isEqualTo("restjson.eu-west-2.amazonaws.com");
}
@Test
public void async_endpointOverridden_equals_requestOverride() {
CapturingInterceptor interceptor = new CapturingInterceptor();
RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder()
.overrideConfiguration(o -> o.addExecutionInterceptor(interceptor)
.putAdvancedOption(SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION, true))
.build();
assertThatThrownBy(() -> client.operationWithHostPrefix(
r -> r.overrideConfiguration(o -> o.endpointProvider(new CustomEndpointProvider(Region.AWS_GLOBAL)))
).join())
.hasMessageContaining("stop");
Endpoint endpoint = interceptor.executionAttributes().getAttribute(SdkInternalExecutionAttribute.RESOLVED_ENDPOINT);
assertThat(endpoint.url().getHost()).isEqualTo("restjson.aws-global.amazonaws.com");
}
@Test
public void async_endpointOverridden_equals_ClientsWhenNoRequestOverride() {
CapturingInterceptor interceptor = new CapturingInterceptor();
RestJsonEndpointProvidersAsyncClient client = asyncClientBuilder().endpointProvider(new CustomEndpointProvider(Region.EU_WEST_2))
.overrideConfiguration(o -> o.addExecutionInterceptor(interceptor)
.putAdvancedOption(SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION, true))
.build();
assertThatThrownBy(() -> client.operationWithHostPrefix(r -> {}).join())
.hasMessageContaining("stop");
Endpoint endpoint = interceptor.executionAttributes().getAttribute(SdkInternalExecutionAttribute.RESOLVED_ENDPOINT);
assertThat(endpoint.url().getHost()).isEqualTo("restjson.eu-west-2.amazonaws.com");
}
public static class CapturingInterceptor implements ExecutionInterceptor {
private ExecutionAttributes executionAttributes;
@Override
public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) {
this.executionAttributes = executionAttributes;
throw new CaptureCompletedException("stop");
}
public ExecutionAttributes executionAttributes() {
return executionAttributes;
}
public class CaptureCompletedException extends RuntimeException {
CaptureCompletedException(String message) {
super(message);
}
}
}
private RestJsonEndpointProvidersClientBuilder syncClientBuilder() {
return RestJsonEndpointProvidersClient.builder()
.region(Region.US_WEST_2)
.credentialsProvider(
StaticCredentialsProvider.create(
AwsBasicCredentials.create("akid", "skid")));
}
private RestJsonEndpointProvidersAsyncClientBuilder asyncClientBuilder() {
return RestJsonEndpointProvidersAsyncClient.builder()
.region(Region.US_WEST_2)
.credentialsProvider(
StaticCredentialsProvider.create(
AwsBasicCredentials.create("akid", "skid")));
}
class CustomEndpointProvider implements RestJsonEndpointProvidersEndpointProvider{
final RestJsonEndpointProvidersEndpointProvider endpointProvider;
final Region overridingRegion;
CustomEndpointProvider (Region region){
this.endpointProvider = RestJsonEndpointProvidersEndpointProvider.defaultProvider();
this.overridingRegion = region;
}
@Override
public CompletableFuture<Endpoint> resolveEndpoint(RestJsonEndpointProvidersEndpointParams endpointParams) {
return endpointProvider.resolveEndpoint(endpointParams.toBuilder().region(overridingRegion).build());
}
}
}
| 2,625 |
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/customresponsemetadata/CustomResponseMetadataTest.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.customresponsemetadata;
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.junit.WireMockRule;
import java.net.URI;
import java.util.concurrent.CompletableFuture;
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.core.ResponseBytes;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.sync.ResponseTransformer;
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.protocolrestjson.model.AllTypesResponse;
import software.amazon.awssdk.services.protocolrestjson.model.ProtocolRestJsonResponse;
import software.amazon.awssdk.services.protocolrestjson.model.StreamingOutputOperationResponse;
import software.amazon.awssdk.utils.builder.SdkBuilder;
public class CustomResponseMetadataTest {
@Rule
public WireMockRule wireMock = new WireMockRule(0);
private ProtocolRestJsonClient client;
private ProtocolRestJsonAsyncClient asyncClient;
@Before
public void setupClient() {
client = ProtocolRestJsonClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")))
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + wireMock.port()))
.build();
asyncClient = 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 syncNonStreaming_shouldContainResponseMetadata() {
stubResponseWithHeaders();
AllTypesResponse allTypesResponse = client.allTypes(SdkBuilder::build);
verifyResponseMetadata(allTypesResponse);
}
@Test
public void syncStreaming_shouldContainResponseMetadata() {
stubResponseWithHeaders();
ResponseBytes<StreamingOutputOperationResponse> streamingOutputOperationResponseResponseBytes =
client.streamingOutputOperation(SdkBuilder::build, ResponseTransformer.toBytes());
verifyResponseMetadata(streamingOutputOperationResponseResponseBytes.response());
}
@Test
public void asyncNonStreaming_shouldContainResponseMetadata() {
stubResponseWithHeaders();
AllTypesResponse allTypesResponse = asyncClient.allTypes(SdkBuilder::build).join();
verifyResponseMetadata(allTypesResponse);
}
@Test
public void asyncStreaming_shouldContainResponseMetadata() {
stubResponseWithHeaders();
CompletableFuture<ResponseBytes<StreamingOutputOperationResponse>> response =
asyncClient.streamingOutputOperation(SdkBuilder::build, AsyncResponseTransformer.toBytes());
verifyResponseMetadata(response.join().response());
}
@Test
public void headerNotAvailable_responseMetadataShouldBeUnknown() {
stubResponseWithoutHeaders();
AllTypesResponse allTypesResponse = client.allTypes(SdkBuilder::build);
verifyUnknownResponseMetadata(allTypesResponse);
}
private void verifyResponseMetadata(ProtocolRestJsonResponse allTypesResponse) {
assertThat(allTypesResponse.responseMetadata()).isNotNull();
assertThat(allTypesResponse.responseMetadata().barId()).isEqualTo("bar");
assertThat(allTypesResponse.responseMetadata().fooId()).isEqualTo("foo");
assertThat(allTypesResponse.responseMetadata().requestId()).isEqualTo("foobar");
}
private void verifyUnknownResponseMetadata(ProtocolRestJsonResponse allTypesResponse) {
assertThat(allTypesResponse.responseMetadata()).isNotNull();
assertThat(allTypesResponse.responseMetadata().barId()).isEqualTo("UNKNOWN");
assertThat(allTypesResponse.responseMetadata().fooId()).isEqualTo("UNKNOWN");
assertThat(allTypesResponse.responseMetadata().requestId()).isEqualTo("UNKNOWN");
}
private void stubResponseWithHeaders() {
stubFor(post(anyUrl())
.willReturn(aResponse().withStatus(200)
.withHeader("x-foo-id", "foo")
.withHeader("x-bar-id", "bar")
.withHeader("x-foobar-id", "foobar")
.withBody("{}")));
}
private void stubResponseWithoutHeaders() {
stubFor(post(anyUrl())
.willReturn(aResponse().withStatus(200)
.withBody("{}")));
}
}
| 2,626 |
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,627 |
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,628 |
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,629 |
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,630 |
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,631 |
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,632 |
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,633 |
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,634 |
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,635 |
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,636 |
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,637 |
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,638 |
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,639 |
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,640 |
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,641 |
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,642 |
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,643 |
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,644 |
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,645 |
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,646 |
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,647 |
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,648 |
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,649 |
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,650 |
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,651 |
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,652 |
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,653 |
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,654 |
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,655 |
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,656 |
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,657 |
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,658 |
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,659 |
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,660 |
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,661 |
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,662 |
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,663 |
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,664 |
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,665 |
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,666 |
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,667 |
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,668 |
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,669 |
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,670 |
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,671 |
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,672 |
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,673 |
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,674 |
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,675 |
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,676 |
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,677 |
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,678 |
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,679 |
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,680 |
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,681 |
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,682 |
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,683 |
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,684 |
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,685 |
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,686 |
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,687 |
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,688 |
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,689 |
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,690 |
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,691 |
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,692 |
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,693 |
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,694 |
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,695 |
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,696 |
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,697 |
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,698 |
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,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.